Skip to content

Commit 81eae2b

Browse files
fix(core): a scoped import lookup miss names the scoping column when the value exists outside the scope (#36735)
Fixes #36159 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:导入数据时,如果某个查找列的值只存在于另一个上级记录下(例如合同属于另一个客户),被拒的那一行提示现在会写明是按哪一列、哪个值限定的,例如「合同:未找到匹配“CTR-0006”的记录(客户 = "Acme")」;真的不存在的值,提示不变。 - 为什么做:替用 CSV 批量导入订单、合同的用户解决;以前这种行只提示“找不到记录”,导入的人去搜却能搜到,误以为系统出错。 - 出错会怎样:只改提示文字,拒绝与否和错误代码都不变;最坏是提示多一段或少一段说明,可以直接撤回本次合并。 - 无。 ## What changes `packages/core/src/utils/import-coerce.ts`. A lookup cell scoped by the row (the field's `dependsOn` column, or the master the target's `master_detail` field points at) used to answer every miss with `import_reference_not_found`: `Contract: no record matches "CTR-0006"`, also when CTR-0006 exists under another account. After a scoped miss, `referenceNotFound` asks the same `resolveRef` once more without the scope. When that finds a record (one or several), the scope is why nothing matched, and the message adds the scoping columns and the cells the row gave them: ``` Contract: no record matches "CTR-0006" (Account = "UI Probe X Co") ``` A value that matches nothing at all keeps the plain sentence. Single-value and multi-value cells use the same path. Per the seat's routing in the claim (`Ruling-ref:`): the reason stays `reference_not_found`, the code stays `import_reference_not_found`, no new enum value, no new catalog key. The extra part is built in core from the column label, the cell and punctuation only. It reads the same under every locale the catalog sentence is rendered in, and nothing in `packages/spec` changes. The exported signatures do not change. `coerceFieldValue(raw, meta, ctx, scope)` now calls an internal `coerceCell`, which also takes the scoping columns (`ScopedBy`, not exported). Only `coerceRow` knows those columns and passes them. An outside caller of `coerceFieldValue` with a scope gets the plain sentence, as before. Mechanism assumptions, measured: - The probe runs as the importer. `runImport`'s resolver sends every lookup through `p.findData(findArgsBase(...))`, which carries the import's own `context`. The probe is the same resolver with no scope, so it finds only records the importer can already read by the same value, and the message says nothing about the record it found. A runner test pins this: rows hidden from the caller produce the plain sentence, and every read runs with the caller's context. - `packages/spec/src/system/validation-message.ts` holds `import_reference_not_found` (line 164). That template is unchanged. The sentence is composed in core, so this needed no `needs_decision`. ## Tests The pins go into the existing harness `import-runner-reference-master-scope.test.ts`, as a new top-level `describe`, so they use that file's engine-like `findData` fake. This follows AGENTS.md (ruling record 6583487846: a new pin for a component that already has a shared harness file goes into that file). The dispatch had preferred a new file named for the card. - dependsOn-scoped cell naming another parent's record: `reference_not_found`, message `task: no record matches "Design review" (Project = "Gemini")`. - master-scoped cell naming another master's detail, by name and by pasted id: same shape, naming `Contract`. - a value that matches no record anywhere: the plain `no record matches` sentence, for both scope routes. - multi-value cell: the out-of-scope token gets the qualified sentence, and a truly missing token gets the plain one. - the probe runs as the caller: a record the caller's reads cannot see stays unnamed, the unscoped probe read did happen, and every read ran with the caller's context. <details><summary>Package runs</summary> Targeted: `pnpm --filter @objectstack/core exec vitest run --maxWorkers=2 src/utils/import-runner-reference-master-scope.test.ts src/utils/import-coerce.test.ts` under `os-verify-lock.sh`: ``` Test Files 2 passed (2) Tests 191 passed (191) os-verify-lock: VERDICT command-exit 0 ``` Full package: `pnpm --filter @objectstack/core typecheck && pnpm --filter @objectstack/core test` (typecheck includes `check:test-typecheck` over `tsconfig.test.json`, which compiles the test files): ``` check:test-typecheck: OK Test Files 156 passed (156) Tests 3712 passed (3712) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>One ablation: the probe's verdict ignored</summary> The test imports `./import-runner` from source (no `dist` in the path), so no rebuild was needed. Run with `node scripts/ablation-replace.mjs` after the fix was committed. Anchor `if (unscoped.id === undefined && !unscoped.ambiguous) return refusal;` replaced by `return refusal;`. Anchor count went 1 to 0, blob 55535a7 to c33835840466. ``` × a dependsOn-scoped cell naming another parent's record ... × a master-scoped cell naming another master's detail, by name or by id ... × a multi-value cell: the token outside the scope is refused with the same sentence Test Files 1 failed (1) Tests 3 failed | 12 passed (15) ablation-replace: ok restored: blob == HEAD (55535a7) and `git diff HEAD` is empty ``` This is the expected direction. The plain-sentence pin and the caller-context pin stay green, because the ablation makes every miss read plain. </details> <details><summary>Gates at d1d8b71: 65 derived, 61 exit 0, 4 NOT MEASURED, 0 red</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 65 families from the merge base 3aa008d. Each one was run in turn, with its exit code recorded before any pipe. `--ran` verdict: "65 derived famil(ies) accounted for — 61 run, 4 NOT-MEASURED (4 DERIVED from a recorded exit 3)". NOT MEASURED here, all four exit 3 PREREQUISITE NOT MET; CI's `Lint & Repo Gates` runs them on a full build: - `check:dual-build-cjs-loads`: needs every package's `dist` (`pnpm build`). Only core's closure was built. - `check:lean-entry-closure`: needs `packages/objectql/dist`, and objectql's own closure was not built. - `node scripts/check-plugin-teardown-shape.mjs --self-test`: needs an unshallowed clone for its pinned fixture commit. - `check:type-check-debt`: its closure build queued on the shared verify lock behind a sibling's dogfood run (exit 99, queue-timeout). `node scripts/pm/overlap-check.mjs --branch=HEAD`: VERDICT clean exit 0 (origin/main merges cleanly, 0 open PR heads share a file). </details> ## Acceptance notes - The added part is locale-neutral by design (label, cell, `=`, quotes). A fully translated sentence, like the card's example `"CTR-0006" belongs to another Account`, would need a new catalog key in `packages/spec`, which is published surface. That is outside this dispatch and outside the seat's routing. - The probe adds one lookup per scoped miss. A scoped hit costs nothing extra. An unscoped verdict that is a hit is cached by the resolver, as before. - A caller who cannot read the scoping field on the target (the narrowing that came with the scope) also gets the qualified sentence when the unscoped lookup finds the record. That is true: the row's scope is why the cell did not resolve. ## Verification Two minutes: in the worktree, run `pnpm --filter @objectstack/core exec vitest run --maxWorkers=2 src/utils/import-runner-reference-master-scope.test.ts`. Expect 15 passed, including the five `[#36159]` cases. Read first, by risk: 1. `packages/core/src/utils/import-coerce.ts`, `referenceNotFound`: the probe and the message. 2. `packages/core/src/utils/import-coerce.ts`, `coerceRow`'s scope loop: where `ScopedBy` is built from the source column's label and raw cell. 3. `packages/core/src/utils/import-runner-reference-master-scope.test.ts`, the new `describe`. --- _Generated by [Claude Code](https://claude.ai/code/session_011y7As6FyXmJyGyHNKXUkV7)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent cb2d6aa commit 81eae2b

3 files changed

Lines changed: 168 additions & 10 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/core': patch
3+
---
4+
5+
fix(core): an import lookup cell refused by the row's own scope names the scoping column
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
An import lookup cell is resolved within the record the same row names for it: the lookup's `dependsOn` column, or the master a detail target belongs to. When the value matched a record only under another parent, the refusal read `Contract: no record matches "CTR-0006"`, and an importer who searched for CTR-0006 found it.
11+
12+
After a scoped lookup matches nothing, the import now asks the same lookup once more without the scope, as the same importing user. When that finds the value, the refusal names the scoping column and what the row wrote there: `Contract: no record matches "CTR-0006" (Account = "Acme")`. A value that matches no record at all keeps `Contract: no record matches "CTR-0006"`. Single-value and multi-value lookup cells read the same.
13+
14+
The reason stays `reference_not_found` and the code stays `import_reference_not_found`. The added part is built from the column label, the cell and punctuation, so it reads the same in every locale. The second lookup runs as the importing user, so it finds only records that user can already read, and the message says nothing about the record it found.

‎packages/core/src/utils/import-coerce.ts‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,48 @@ function resolveScoped(
144144
return scope ? resolveRef(referenceObject, display, meta, scope) : resolveRef(referenceObject, display, meta);
145145
}
146146

147+
/**
148+
* [#36159] A row column a lookup cell was scoped by: the column's label and its
149+
* cell as the importer typed it. Carried beside the scope (whose keys are the
150+
* TARGET's fields and whose values are coerced ids) so a refusal can name what
151+
* the importer wrote.
152+
*/
153+
interface ScopedBy {
154+
label: string;
155+
value: string;
156+
}
157+
158+
/**
159+
* [#36159] The refusal for a reference cell that matched nothing. A scoped
160+
* miss is asked once more WITHOUT the scope, through the same resolver: when
161+
* the value matches a record there (one or several), the row's own scope is
162+
* why nothing matched, and the sentence names the scoping columns and the
163+
* values the row gave them, e.g. `Contract: no record matches "CTR-0006"
164+
* (Account = "Acme")`. A value that matches nothing at all keeps the plain
165+
* sentence. The reason stays `reference_not_found`.
166+
*
167+
* The probe is the caller's own read: the resolver runs every lookup as the
168+
* importing principal, so it can find only a record that principal can already
169+
* read by the same value, and the sentence says nothing of that record. The
170+
* qualifier is composed from labels, cells and punctuation only, so it reads
171+
* the same under every locale the catalog sentence is rendered in.
172+
*/
173+
async function referenceNotFound(
174+
meta: ExportFieldMeta,
175+
field: string,
176+
value: string,
177+
ctx: CoerceContext,
178+
scope: Readonly<Record<string, unknown>> | undefined,
179+
scopedBy: readonly ScopedBy[] | undefined,
180+
): Promise<{ error: FieldCoerceError }> {
181+
const refusal = coerceError(meta, field, 'reference_not_found', 'import_reference_not_found', value, ctx);
182+
if (!scope || !scopedBy || scopedBy.length === 0 || !ctx.resolveRef || !meta.reference) return refusal;
183+
const unscoped = normalizeRefMatch(await ctx.resolveRef(meta.reference, value, meta));
184+
if (unscoped.id === undefined && !unscoped.ambiguous) return refusal;
185+
const qualifier = scopedBy.map((s) => `${s.label} = "${s.value}"`).join(', ');
186+
return { error: { ...refusal.error, message: `${refusal.error.message} (${qualifier})` } };
187+
}
188+
147189
/** Normalise a resolver result (legacy string or structured) to a RefMatch. */
148190
function normalizeRefMatch(result: string | undefined | RefMatch): RefMatch {
149191
if (result == null) return {};
@@ -760,6 +802,20 @@ export async function coerceFieldValue(
760802
meta: ExportFieldMeta | undefined,
761803
ctx: CoerceContext,
762804
scope?: Readonly<Record<string, unknown>>,
805+
): Promise<{ value?: unknown; keptOptionValues?: string[] } | { error: FieldCoerceError }> {
806+
return coerceCell(raw, meta, ctx, scope);
807+
}
808+
809+
/**
810+
* {@link coerceFieldValue}, plus the row columns its scope came from
811+
* ({@link ScopedBy}), which only {@link coerceRow} knows.
812+
*/
813+
async function coerceCell(
814+
raw: unknown,
815+
meta: ExportFieldMeta | undefined,
816+
ctx: CoerceContext,
817+
scope?: Readonly<Record<string, unknown>>,
818+
scopedBy?: readonly ScopedBy[],
763819
): Promise<{ value?: unknown; keptOptionValues?: string[] } | { error: FieldCoerceError }> {
764820
const trim = ctx.trimWhitespace !== false;
765821
const field = meta?.name ?? '';
@@ -850,9 +906,7 @@ export async function coerceFieldValue(
850906
if (m.ambiguous) {
851907
return coerceError(meta, field, 'reference_ambiguous', 'import_reference_ambiguous', token, ctx);
852908
}
853-
if (m.id === undefined) {
854-
return coerceError(meta, field, 'reference_not_found', 'import_reference_not_found', token, ctx);
855-
}
909+
if (m.id === undefined) return referenceNotFound(meta, field, token, ctx, scope, scopedBy);
856910
out.push(m.id);
857911
}
858912
return { value: out };
@@ -866,9 +920,7 @@ export async function coerceFieldValue(
866920
if (match.ambiguous) {
867921
return coerceError(meta, field, 'reference_ambiguous', 'import_reference_ambiguous', display, ctx);
868922
}
869-
if (match.id === undefined) {
870-
return coerceError(meta, field, 'reference_not_found', 'import_reference_not_found', display, ctx);
871-
}
923+
if (match.id === undefined) return referenceNotFound(meta, field, display, ctx, scope, scopedBy);
872924
return { value: match.id };
873925
}
874926

@@ -1026,13 +1078,20 @@ export async function coerceRow(
10261078
const ready = pending.filter((k) => scoped.get(k)!.every((s) => settled(s.field)));
10271079
for (const key of ready.length > 0 ? ready : pending) {
10281080
let scope: Record<string, unknown> | undefined;
1081+
const scopedBy: ScopedBy[] = [];
10291082
if (ready.length > 0) {
10301083
for (const s of scoped.get(key)!) {
10311084
const v = await sourceValue(s.field);
1032-
if (v !== undefined) (scope ??= {})[s.param] = v;
1085+
if (v === undefined) continue;
1086+
(scope ??= {})[s.param] = v;
1087+
// [#36159] What the importer wrote in the scoping column, by its label.
1088+
scopedBy.push({
1089+
label: metaMap.get(s.field)?.label?.trim() || s.field,
1090+
value: String(sourceRow[s.field]).trim(),
1091+
});
10331092
}
10341093
}
1035-
outcomes.set(key, await coerceFieldValue(rawRow[key], metaMap.get(key), ctx, scope));
1094+
outcomes.set(key, await coerceCell(rawRow[key], metaMap.get(key), ctx, scope, scopedBy));
10361095
}
10371096
pending = pending.filter((k) => !outcomes.has(k));
10381097
}

‎packages/core/src/utils/import-runner-reference-master-scope.test.ts‎

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,17 +59,22 @@ const ROWS: Record<string, Row[]> = {
5959
xm_task: [
6060
{ id: 't1', name: 'Kickoff', project: 'p1' },
6161
{ id: 't2', name: 'Kickoff', project: 'p2' },
62+
{ id: 't3', name: 'Design review', project: 'p1' },
6263
],
6364
};
6465

6566
/** The importing object: an invoice that sets a contract, a milestone and a task. */
6667
const metaMap = buildFieldMetaMap({
6768
fields: {
6869
name: TEXT,
69-
contract: { type: 'lookup', reference: 'xm_contract' },
70+
contract: { type: 'lookup', reference: 'xm_contract', label: 'Contract' },
7071
milestone: { type: 'lookup', reference: 'xm_milestone' },
71-
project: { type: 'lookup', reference: 'xm_project' },
72+
project: { type: 'lookup', reference: 'xm_project', label: 'Project' },
7273
task: { type: 'lookup', reference: 'xm_task', dependsOn: [{ field: 'project', param: 'project' }] },
74+
// A multi-value lookup scoped the same way, for the multi-value refusal.
75+
tasks: {
76+
type: 'lookup', reference: 'xm_task', multiple: true, dependsOn: [{ field: 'project', param: 'project' }],
77+
},
7378
// A second column pointing at the master, used only by the two-column case.
7479
other_contract: { type: 'lookup', reference: 'xm_contract' },
7580
},
@@ -225,3 +230,83 @@ describe('[#33523] the match-key pass scopes a key column by the row\'s master t
225230
expect(createData.mock.calls.map(([a]) => a.data.milestone)).toEqual(['m3']);
226231
});
227232
});
233+
234+
describe('[#36159] a scoped miss whose value exists outside the row\'s scope names the scoping column', () => {
235+
const refusal = (r: { ok: boolean; code?: string; field?: string; error?: string }) =>
236+
({ ok: r.ok, code: r.code, field: r.field, error: r.error });
237+
238+
it('a dependsOn-scoped cell naming another parent\'s record: reference_not_found naming Project and its cell', async () => {
239+
const { p, createData } = protocol();
240+
// "Design review" exists, under Apollo only.
241+
const summary = await run(p, [{ name: 'INV-1', project: 'Gemini', task: 'Design review' }]);
242+
expect(summary.results.map(refusal)).toEqual([{
243+
ok: false, code: 'reference_not_found', field: 'task',
244+
error: 'task: no record matches "Design review" (Project = "Gemini")',
245+
}]);
246+
expect(createData).not.toHaveBeenCalled();
247+
});
248+
249+
it('a master-scoped cell naming another master\'s detail, by name or by id: the same sentence naming Contract', async () => {
250+
const { p } = protocol();
251+
const summary = await run(p, [
252+
{ name: 'INV-1', contract: 'Contract B', milestone: 'Final 70%' },
253+
{ name: 'INV-2', contract: 'Contract B', milestone: 'm1' },
254+
]);
255+
expect(summary.results.map(refusal)).toEqual([
256+
{
257+
ok: false, code: 'reference_not_found', field: 'milestone',
258+
error: 'milestone: no record matches "Final 70%" (Contract = "Contract B")',
259+
},
260+
{
261+
ok: false, code: 'reference_not_found', field: 'milestone',
262+
error: 'milestone: no record matches "m1" (Contract = "Contract B")',
263+
},
264+
]);
265+
});
266+
267+
it('a value that matches no record at all keeps the plain no-record-matches sentence', async () => {
268+
const { p } = protocol();
269+
const summary = await run(p, [
270+
{ name: 'INV-1', project: 'Gemini', task: 'Retrospective' },
271+
{ name: 'INV-2', contract: 'Contract B', milestone: 'Holdback 5%' },
272+
]);
273+
expect(summary.results.map(refusal)).toEqual([
274+
{ ok: false, code: 'reference_not_found', field: 'task', error: 'task: no record matches "Retrospective"' },
275+
{ ok: false, code: 'reference_not_found', field: 'milestone', error: 'milestone: no record matches "Holdback 5%"' },
276+
]);
277+
});
278+
279+
it('a multi-value cell: the token outside the scope is refused with the same sentence', async () => {
280+
const { p } = protocol();
281+
const summary = await run(p, [
282+
{ name: 'INV-1', project: 'Gemini', tasks: 'Kickoff; Design review' },
283+
{ name: 'INV-2', project: 'Gemini', tasks: 'Kickoff; Retrospective' },
284+
]);
285+
expect(summary.results.map(refusal)).toEqual([
286+
{
287+
ok: false, code: 'reference_not_found', field: 'tasks',
288+
error: 'tasks: no record matches "Design review" (Project = "Gemini")',
289+
},
290+
{ ok: false, code: 'reference_not_found', field: 'tasks', error: 'tasks: no record matches "Retrospective"' },
291+
]);
292+
});
293+
294+
it('the unscoped probe is the importing caller\'s own read, and a record that caller cannot read stays unnamed', async () => {
295+
const { p, findData } = protocol();
296+
// The caller's reads see no Apollo task: the fake hides xm_task rows of p1
297+
// from this caller, as row-level security would.
298+
findData.mockImplementation(async (args: FindArgs) =>
299+
(ROWS[args.object] ?? [])
300+
.filter((r) => !(args.object === 'xm_task' && r.project === 'p1'))
301+
.filter((r) => matches(r, args.query!.where as Record<string, unknown>)));
302+
const summary = await run(p, [{ name: 'INV-1', project: 'Gemini', task: 'Design review' }]);
303+
expect(summary.results.map(refusal)).toEqual([
304+
{ ok: false, code: 'reference_not_found', field: 'task', error: 'task: no record matches "Design review"' },
305+
]);
306+
const taskReads = findData.mock.calls.map(([a]) => a).filter((a) => a.object === 'xm_task');
307+
// Both the scoped lookup and the unscoped probe ran, and every read ran as the caller.
308+
expect(taskReads.some((a) => (a.query!.where as Row).project === 'p2')).toBe(true);
309+
expect(taskReads.some((a) => !('project' in (a.query!.where as Row)))).toBe(true);
310+
for (const a of findData.mock.calls.map(([call]) => call)) expect(a.context).toBe(CALLER);
311+
});
312+
});

0 commit comments

Comments
 (0)