Skip to content

Commit b070e1c

Browse files
fix(core): an import lookup naming a detail resolves within the row's own master (#33613)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DFWmDYdUPFhME7Z7Ky3ySCZ)_ Fixes #33523 Area-lease pilot #33059, area A3. Clause-②: yes (narrowing) — widening: a row whose master identifies one of several same-named details now resolves it, where it was refused `reference_ambiguous`; `@objectstack/core` gains the export `referenceScopeSources`, the types `ReferenceMaster` / `ReferenceScopeSource`, and optional parameters on `RefResolver`, `coerceFieldValue`, `coerceRow`, `CoerceContext` and `ExportFieldMeta`. Narrowing: a row that names a master and a detail only another master carries is refused `reference_not_found`, where that detail was linked across masters; and a caller who cannot read the target's master field (or a `dependsOn` `param` field) is refused `reference_not_found` for a scoped lookup cell that the unscoped lookup resolved, because the scope puts that field into the caller's own filter and a filter on a field the caller cannot read is refused. Metadata-protocol: none Skills-docs: `content/docs/data-modeling/import-mappings.mdx` gains "A lookup cell is resolved within the row's own master"; `skills/objectstack-data/rules/relationships.md` names the scoping under `master_detail`. ## 维护者速读 - What changed: a data import resolving a lookup cell now searches only within the master record the same row sets, when the target is that master's detail (`master_detail`) or the field declares `dependsOn`. - Why: with two contracts each carrying an "Advance 30%" billing step, an invoice import row failed with `reference_ambiguous` although its own contract picks one; the record form's picker already narrows by contract (measured by HotCRM's invoice import template). - Risk and rollback: two answers narrow. A row naming contract B and a step that only contract A has used to link A's step; it now fails `reference_not_found`. A caller who cannot read the step's contract field now gets `reference_not_found` for a step the row scopes by contract, even when its name is unique. Remedy for both: correct the master cell, or leave the master column out and set it in a second update. Rollback is a revert of this PR; no data migration. - Look first: `referenceScopeSources` and the two-pass `coerceRow` in `packages/core/src/utils/import-coerce.ts`; the `where` merge and cache key in `packages/core/src/utils/import-runner.ts`; the new `import-runner-reference-master-scope.test.ts`. - Two-minute check: `pnpm --filter @objectstack/core exec vitest run src/utils/import-runner-reference-master-scope.test.ts`; expect 10 passed. - What you need to do: this PR touches `skills/**` (Tier H), so it lands by the maintainer's approval and merge. ## What changes - **Scope sources** (`referenceScopeSources`, `packages/core/src/utils/import-coerce.ts`). For a reference column of the row, the scope is built from (1) the field's own `dependsOn` (string form: same name on both sides; `{ field, param }`: target field `param`) when the row fills the sibling, and (2) each `master_detail` field the lookup TARGET declares, when exactly one other single-value reference column of the row points at that master object and is filled. Two such columns (bill-to / ship-to) do not say which is the master, so neither scopes. - **Ordering** (`coerceRow`). Unscoped columns coerce first in row order; a scoped column coerces after its source columns, with their coerced ids as its scope. A failed or non-scalar source scopes nothing. When no pending column is ready (a cycle, or a column whose source waits behind one), every pending column resolves unscoped, as on `main`. Errors are still reported in the row's column order. An optional `sourceRow` lets the match-key pass (`rowsSharingKey`) read the scope from the whole row, so a key column naming a detail groups by the same id the row's own pass resolves, for one level of master: a source column outside the key columns is coerced unscoped, so in a chain (account → contract → milestone) the two passes can differ. - **Resolver** (`import-runner.ts`). The scope is merged into every candidate's `where` (`{ [candidate]: display, ...scope }`), so a tie and a miss are judged inside it; the cache key carries the scope; a candidate the scope already fixes is skipped. The read is the same `findData` with the same caller `context` as before, so RLS is unchanged and a record the caller cannot read never matches. FLS is not unchanged: the scope puts the target's master field (or a `dependsOn` `param`) into the caller's own `where`, plugin-security's predicate guard refuses a caller `where` on a field the caller cannot read, and the resolver reads that throw as no match. So a caller who cannot read that field gets `reference_not_found` for a scoped cell that resolved on `main`. It fails closed and discloses nothing; it is declared in the `Clause-②` narrowing, the changeset and the docs (option (b) of review#2's S1), and the unscoped retry (option (a)) is not implemented. The target's masters are read off the same served-target declaration the resolver already reads (`servesReferenceTarget`, now also `masters` via `referenceTargetOf`), so a target the caller cannot serve answers no masters. - **Field meta** (`import-field-meta.ts`). `ExportFieldMeta.dependsOn` carries the normalised `{ field, param }` pairs; present only when declared. - **Remedy for a narrowed row** (in the changeset and the docs). A pasted id is scoped too, so a row that means another master's detail has no way through in one import: correct the master cell, or, when the cross-master link is intended, leave the master column out of the import and set it in a second update. For the field-permission case, grant the caller read access to that field, or leave the master column out the same way. - **Docs.** `content/docs/data-modeling/import-mappings.mdx` (new subsection under cell coercion, with the field-permission case and the remedy) and the data skill's relationships rule (5 lines under `master_detail`). The docs and changeset say the `dependsOn` scope is the filter the record form's picker applies, and that the `master_detail` inference has no picker counterpart, so for a lookup without `dependsOn` the import is stricter than the form. - Not touched: `packages/spec/**`, the REST import door (`packages/rest/src/import*.ts` feeds `runImport` unchanged; the premise's "likely code" there was measured and the fix lives entirely in core), no stored-data migration. ## Why Measured premise on `origin/main` 4bba8b8: `runImport`'s resolver queried `where: { [field]: display }` over the whole target for every candidate and returned `ambiguous` on two hits; nothing read the row's other columns. The record picker scopes by `dependsOn` / the master, so the two doors disagreed. ## Tests New `packages/core/src/utils/import-runner-reference-master-scope.test.ts` (10 cases, fake protocol answering equality over every `where` key): - acceptance 1: two contracts each with "Advance 30%"; rows naming A and B link `m1` and `m2`; column order does not matter. - acceptance 2: a row with no (or a blank) master cell is `reference_ambiguous`; a unique name still resolves object-wide. - acceptance 3: a name absent under the row's master, a name unique object-wide but under another master, and a pasted id of another master's detail are all `reference_not_found`. - every read carries the caller's context; two master columns stay unscoped; a field's own `dependsOn` scopes a plain lookup; a master cell that fails scopes nothing. - the match-key pass: two keys under different masters are two keys; a key naming another master's detail answers `reference_not_found` on that row alone (unscoped it would fail both rows as a duplicate key). Ablations (one-shot, restored, `scripts/ablation-replace.mjs`; tests import `src` directly, no dist involved): - `where: { [f]: display, ...(scope ?? {}) }` → `where: { [f]: display }`: 7 failed | 3 passed (the 3 that stay green are the unscoped cases). Restored: blob == HEAD `f33b0cb042ea`, `git diff HEAD` empty. - `coerceRow(cells, metaMap, coerceCtx, rows[i])` → without `rows[i]`: 1 failed | 9 passed (the match-key case). Restored likewise. ## Acceptance notes - `dependsOn` is honoured as the picker reads it (`param` names the target field). A `dependsOn` entry naming a column the row leaves blank scopes nothing. - Review#2 nit N3 is carried, not fixed here: the scoped and unscoped cache keys share one string space (`obj::display` against `obj::display::[...]`), so a display value that itself ends in a serialized scope could collide within one import and one caller. - The HotCRM import template text (`packages/rest/src/import-template.ts` `howToFill`) still says a name matching more than one record is refused; it is not wrong for a row without its master and was left as is. ## Verification Readings at head `81e7c21e` (this round's commit edits the changeset, `import-mappings.mdx` and two docblocks in `import-coerce.ts` / `import-runner.ts`; no code line changes since `dad002e6ec`). Every build and test below ran under `scripts/pm/os-verify-lock.sh`, and each reading is quoted from that run with its `VERDICT command-exit` line. <details><summary>CI reds on earlier heads, and their fixes</summary> - `7b9cc0b17a`: `TypeScript Type Check` red (TS2339 on `where.contract` in the new test, `check:test-typecheck`). Fixed by `9467884463`, which types the scoped `where` read. - `9467884463`: `Test Core` shards 4/8 and 5/8 red on two `test:repo` pins, both fixed by `dad002e6ec`: - core `src/security/second-object-read-exposure.pin.test.ts`: `import-runner.ts` now calls `referenceTargetOf` (in `mastersOf`) and was not classified. It is now a `CALLERS` row, classified as `executes`: `mastersOf` runs inside `servesReferenceTarget`, after the target's exposure is asked. - rest `src/rest-server-canonical-query-ast.test.ts`: it pinned the old literal `where: { [f]: display }`; it now pins `where: { [f]: display, ...(scope ?? {}) }`. - The earlier local runs used each package's `test` script (vitest project `local`), which does not include `test:repo` (project `repo`). That is why the core and rest greens reported in round 1 missed both pins. This round ran `test:repo` for core and rest as well (below). </details> <details><summary>Core and rest: test, test:repo, typecheck</summary> - `pnpm --filter @objectstack/core typecheck`: `VERDICT command-exit 0`. - `pnpm --filter @objectstack/core test`: Test Files 147 passed (147), Tests 3390 passed (3390); `VERDICT command-exit 0`. - `pnpm --filter @objectstack/core run test:repo`: Test Files 8 passed (8), Tests 103 passed (103); `VERDICT command-exit 0`. - `pnpm --filter @objectstack/rest run test:repo`: Test Files 5 passed (5), Tests 300 passed, 23 skipped (323); `VERDICT command-exit 0`. </details> <details><summary>Direct dependents that call the changed code (run locally at 81e7c21)</summary> The closure `--filter '@objectstack/core' --filter '@objectstack/objectql^...' --filter '@objectstack/plugin-auth^...' --filter '@objectstack/service-automation^...' --filter '@objectstack/runtime^...' --filter '@objectstack/rest^...'` was built first (`VERDICT command-exit 0`). Each run is the package's `test` script, not `test:repo`. - `@objectstack/objectql` (`runImport` against the real engine): Test Files 595 passed (595), Tests 13028 passed (13028); `VERDICT command-exit 0`. - `@objectstack/plugin-auth` (`admin-import-users` runs `runImport`): Test Files 274 passed (274), Tests 5303 passed, 10 skipped (5313); `VERDICT command-exit 0`. - `@objectstack/service-automation` (connector pull through `runImport`): Test Files 281 passed (281), Tests 3916 passed (3916); `VERDICT command-exit 0`. - `@objectstack/runtime`: Test Files 602 passed (602), Tests 10781 passed, 19 skipped (10800); `VERDICT command-exit 0`. - `@objectstack/rest` (the import door): Test Files 411 passed (411), Tests 8393 passed, 332 skipped (8725); `VERDICT command-exit 0`. `@objectstack/core` has 62 direct dependents. The five above are the ones whose source reaches `runImport`, `coerceRow`, `coerceFieldValue`, `buildFieldMetaMap` or `ExportFieldMeta` (`git grep` over `packages/`). CI's `Test Core` shards cover 61 of the 62; `@objectstack/dogfood` runs in the merge queue's `Dogfood Regression Gate`. </details> <details><summary>Derived gate families (`dispatch-gates.mjs`, 104 families, tree 81e7c21)</summary> - `node scripts/pm/dispatch-gates.mjs --ran` with every exit code recorded: 104 derived, 101 run, 3 NOT MEASURED, 0 UNRUN. - Exit 0: 101, including `check-changeset-no-major`, `check-adr-0087-registration` (`[clause-②-narrowing] not-required (no-migration-prescription)`), `check-empty-changeset`, `check:changeset-gate-self-tests`, `check:doc-authoring`, `check:doc-anchors`, `check:docs-*`, `check:skill-links`, `check:nul-bytes`, `check:issue-citations` and `check:type-check-debt`. - NOT MEASURED locally, prerequisite not met (exit 3), all run by CI: `check-plugin-teardown-shape --self-test` (needs an unshallow clone), `@objectstack/spec` `check:skill-examples`, and `check:dual-build-cjs-loads` (needs a full `pnpm build`). </details> <details><summary>Published skills readings</summary> - Unchanged this round. `skills/objectstack-data/rules/relationships.md`: 399 → 393 lines; 4127 (ceiling) → 4098 tokens. - All published `SKILL.md`: 4597 → 4597 lines (none edited). - Whole `skills/` tree: 20679 → 20673 lines. </details> CI at `81e7c21e`: 68 check runs, 58 success and 10 skipped, none failed. The successes include `Test Core`, `TypeScript Type Check`, `Type Check · workspace`, `Build Core`, `Build Docs`, `Lint & Repo Gates`, `Lint · ESLint` and `Check Changeset`. The skipped runs include the dogfood shards, which do not run on a pull request. Dogfood: the full battery was not completed locally (the round-1 run printed 1689 passing lines and then stalled, with no summary, so no count is claimed). It runs in the merge queue's required `Dogfood Regression Gate` before this lands. The three dogfood files that drive the import on a real engine were run at `81e7c21e` after building the dogfood closure (`pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2 test/import-lands-readable-rows.dogfood.test.ts test/import-reference-exposure.dogfood.test.ts test/import-user-field-target.dogfood.test.ts`): Test Files 3 passed (3), Tests 17 passed (17); `VERDICT command-exit 0`. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (eslint on the changed files: exit 0; the repo-wide run is CI's). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [ ] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cwotoQMyrtSr5EqqAF <!-- signed: domain:server#5 · os-elon-musk · session_016WV4d1QwJJ5KGZTThP4fnq --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a557fa3 commit b070e1c

9 files changed

Lines changed: 565 additions & 27 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/core': patch
3+
'@objectstack/skills': patch
4+
---
5+
6+
fix(core): a data import resolves a lookup cell naming a detail record within the master the same row names (#33523)
7+
8+
Clause-②: yes (narrowing) — widening: a row whose master identifies one of several same-named details now resolves it, where it was refused `reference_ambiguous`; `@objectstack/core` exports `referenceScopeSources` and the types `ReferenceMaster` and `ReferenceScopeSource`, `RefResolver` and `coerceFieldValue` take an optional scope, `coerceRow` an optional source row, `CoerceContext` an optional `referenceMasters`, and `ExportFieldMeta` an optional `dependsOn`. Narrowing: a row that names a master and a detail only another master carries is refused `reference_not_found`, where the detail was linked across masters; and a caller who cannot read the target's master field (or a `dependsOn` `param` field) is refused `reference_not_found` for a scoped lookup cell that the unscoped lookup resolved, because the scope puts that field into the caller's own filter and a filter on a field the caller cannot read is refused.
9+
Metadata-protocol: none
10+
Skills-docs: `content/docs/data-modeling/import-mappings.mdx` gains "A lookup cell is resolved within the row's own master"; `skills/objectstack-data/rules/relationships.md` names the scoping under `master_detail`.
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) No key of any authorable schema is added, removed, renamed or re-shaped. `master_detail` and `dependsOn` are read as declared; the change is in how the import runtime resolves a cell, and no stored row is rewritten. -->
13+
14+
**What changes.** A detail's name is often unique only inside its master: two contracts can each carry an "Advance 30%" billing milestone. The import resolved a lookup cell across every record of the target, so a row naming contract B and "Advance 30%" failed with `reference_ambiguous`. A lookup cell is now resolved within the row's own master when either:
15+
16+
- the lookup's target declares a `master_detail` field, and exactly one other single-value reference column of the row points at that master object and is filled in; or
17+
- the lookup field declares `dependsOn`, and the row fills in the sibling field it names (the string form compares the target field of the same name; `{ field, param }` compares `param`). This is the filter the record form's picker applies; the `master_detail` inference above has no counterpart in the picker, so for a lookup without `dependsOn` the import is stricter than the form.
18+
19+
Inside that scope a tie is `reference_ambiguous`, and a name that only another master carries is `reference_not_found`; it never resolves to another master's record. The same holds for the match-key pass of an update or upsert import, so a key column naming a detail is grouped by the value the row's own pass resolves, for one level of master: a master column outside the key columns is resolved unscoped in that pass, so in a chain such as account → contract → milestone the two passes can differ.
20+
21+
**What stays.** A row that leaves the master blank is resolved across the whole target as before, `reference_ambiguous` on a tie. Two columns of the row pointing at the master object (a bill-to and a ship-to account) do not say which one is the master, so neither scopes; `dependsOn` says it. A master cell that fails its own lookup scopes nothing. Every lookup still reads as the importing caller: the scope only adds conditions to the same read, so a record the caller cannot read never matches.
22+
23+
**Field permissions.** Because the scope is part of the caller's own filter, a caller who cannot read the target's master field, or the field a `dependsOn` entry names as `param`, has every scoped candidate refused, and the cell answers `reference_not_found` even for a detail the caller can read and whose name is unique. The same row resolved before this change. It fails closed and discloses nothing.
24+
25+
**Remedy for a narrowed row.** A pasted id is scoped too, so a row that means another master's detail has no way through in one import. Correct the master cell; or, when the cross-master link is intended, leave the master column out of the import and set it in a second update. For the field-permission case, grant the importing caller read access to that field, or leave the master column (or the `dependsOn` sibling) out in the same way.
26+
27+
**Docs.** `content/docs/data-modeling/import-mappings.mdx` describes the scoping under cell coercion; the data skill's relationships rule names it under `master_detail`.

‎content/docs/data-modeling/import-mappings.mdx‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,47 @@ own field metadata:
326326
- **lookup / master\_detail / user** — the display text resolves to a record **id**.
327327
This is what a `lookup` transform is relying on when it copies its cell through.
328328

329+
### A lookup cell is resolved within the row's own master
330+
331+
The display text is matched against the target's id, its title field and its other
332+
identifying fields, as the caller who runs the import: a record that caller cannot read
333+
never matches. A name that matches no record fails the row with `reference_not_found`;
334+
a name that matches more than one fails it with `reference_ambiguous`, and nothing is
335+
linked.
336+
337+
A detail record's name is often unique only inside its master: two contracts can each
338+
carry an "Advance 30%" billing milestone. When the same row also names the master, the
339+
cell is resolved **within that master's records**:
340+
341+
- the lookup's target has a `master_detail` field, and exactly one other single-value
342+
reference column of the row points at that master object and is filled in; or
343+
- the lookup field declares `dependsOn`, and the row fills in the sibling field it
344+
names. The string form compares the target field of the same name; `{ field, param }`
345+
compares the target field `param`. This is the filter the record form's picker applies.
346+
347+
The `master_detail` rule has no counterpart in the picker, which narrows by `dependsOn`
348+
and `lookupFilters`, never by an inferred master: for a lookup without `dependsOn`, the
349+
import is stricter than the form.
350+
351+
Inside that scope a tie is `reference_ambiguous` and a name that only another master
352+
carries is `reference_not_found`; it never resolves to another master's record. A row
353+
that leaves the master blank is resolved across the whole target as before. When two
354+
columns of the row point at the master object (a bill-to and a ship-to account), neither
355+
is taken as the master; declare `dependsOn` on the lookup to say which one is. A master
356+
cell that fails its own lookup scopes nothing, and the row already fails on that cell.
357+
358+
The scope is part of the importing caller's own filter. A caller who cannot read the
359+
target's master field, or the target field a `dependsOn` entry names as `param`, has the
360+
scoped lookup refused, and the cell fails with `reference_not_found`, even for a detail
361+
that caller can read and whose name is unique. Without the master (or the `dependsOn`
362+
sibling) in the row, the same cell resolves.
363+
364+
A pasted id is scoped too, so a row that means another master's detail cannot be linked
365+
in one import. Correct the master cell; or, when the cross-master link is intended, leave
366+
the master column out of the import and set it in a second update. For the
367+
field-permission case, grant the caller read access to that field, or leave the master
368+
column out in the same way.
369+
329370
A field the object does not know is left untouched. A cell that cannot be coerced fails
330371
its own row with the offending column named.
331372

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,19 @@ const CALLERS: Record<string, Classification> = {
158158
wiring: { file: 'packages/core/src/utils/import-runner.ts', call: 'servesReferenceTarget(p, referenceObject' },
159159
pin: 'packages/core/src/utils/import-runner-reference-exposure.test.ts',
160160
},
161+
// [#33523] `mastersOf` reads which master each `master_detail` field of a served lookup target points at,
162+
// so a detail cell is resolved within the row's own master. It runs only inside `servesReferenceTarget`,
163+
// after the target's exposure is asked; the master's own record is read by the master column's
164+
// `resolveRef`, which asks that object's exposure through the same decision.
165+
'packages/core/src/utils/import-runner.ts': {
166+
kind: 'executes',
167+
read: "the import door's master-scoped reference resolution (a detail cell is matched within the master the same row sets)",
168+
decidedIn: 'packages/core/src/utils/import-field-meta.ts',
169+
also:
170+
'`mastersOf` reads which object a served target\'s `master_detail` field names, inside `servesReferenceTarget` '
171+
+ "after the target's exposure is asked; it reads no record. The master's record is read by the master column's "
172+
+ 'own `resolveRef`, which asks that object through the same decision.',
173+
},
161174
'packages/objectql/src/relation-filter-lowering.ts': {
162175
kind: 'decided',
163176
read: "the data door's nested-relation filter condition (`ObjectQL.lowerRelationConditions` reads the related object to lower it), refused rather than withheld",

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

Lines changed: 159 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,52 @@ export interface RefMatch {
9898
* hit, or `{ ambiguous: true }` when several records share the value. Legacy
9999
* resolvers that return `string | undefined` keep working. Implementations are
100100
* expected to cache — the same name shows up on many rows.
101+
*
102+
* `scope`, when given, is a set of equalities on the TARGET's fields that every
103+
* candidate must also satisfy: the row's own master (see
104+
* {@link ReferenceScopeSource}). A match, a tie and a miss are all judged
105+
* inside it, so a cache keyed by the display value alone must key by the scope
106+
* too.
101107
*/
102108
export type RefResolver = (
103109
referenceObject: string,
104110
displayValue: string,
105111
meta: ExportFieldMeta,
112+
scope?: Readonly<Record<string, unknown>>,
106113
) => Promise<string | undefined | RefMatch>;
107114

115+
/**
116+
* A `master_detail` field of a lookup's TARGET: the target field (`field`) and
117+
* the master object it points at (`reference`).
118+
*/
119+
export interface ReferenceMaster {
120+
field: string;
121+
reference: string;
122+
}
123+
124+
/**
125+
* One equality a reference cell's lookup is scoped by: the target field
126+
* (`param`) must equal the value the same row's `field` column coerced to.
127+
*/
128+
export interface ReferenceScopeSource {
129+
field: string;
130+
param: string;
131+
}
132+
133+
/**
134+
* Ask the resolver, passing a scope only when there is one, so an unscoped
135+
* lookup calls a resolver exactly as it always has.
136+
*/
137+
function resolveScoped(
138+
resolveRef: RefResolver,
139+
referenceObject: string,
140+
display: string,
141+
meta: ExportFieldMeta,
142+
scope: Readonly<Record<string, unknown>> | undefined,
143+
): Promise<string | undefined | RefMatch> {
144+
return scope ? resolveRef(referenceObject, display, meta, scope) : resolveRef(referenceObject, display, meta);
145+
}
146+
108147
/** Normalise a resolver result (legacy string or structured) to a RefMatch. */
109148
function normalizeRefMatch(result: string | undefined | RefMatch): RefMatch {
110149
if (result == null) return {};
@@ -128,6 +167,13 @@ export interface CoerceContext {
128167
createMissingOptions?: boolean;
129168
/** Async reference resolver (name/email/id → record id). Optional. */
130169
resolveRef?: RefResolver;
170+
/**
171+
* The `master_detail` fields a lookup target declares. With it, a reference
172+
* cell whose target is the detail of a master the SAME row also sets is
173+
* resolved within that master's records ({@link referenceScopeSources}).
174+
* Absent → only a field's own `dependsOn` scopes a lookup.
175+
*/
176+
referenceMasters?: (referenceObject: string) => Promise<readonly ReferenceMaster[]>;
131177
/**
132178
* Locale of the importing principal (`ExecutionContext.locale`). Cell-coercion
133179
* failures land in the same row report as the engine's validation errors, so
@@ -711,6 +757,7 @@ export async function coerceFieldValue(
711757
raw: unknown,
712758
meta: ExportFieldMeta | undefined,
713759
ctx: CoerceContext,
760+
scope?: Readonly<Record<string, unknown>>,
714761
): Promise<{ value?: unknown; keptOptionValues?: string[] } | { error: FieldCoerceError }> {
715762
const trim = ctx.trimWhitespace !== false;
716763
const field = meta?.name ?? '';
@@ -797,7 +844,7 @@ export async function coerceFieldValue(
797844
if (!ctx.resolveRef || !meta.reference) return { value: tokens };
798845
const out: unknown[] = [];
799846
for (const token of tokens) {
800-
const m = normalizeRefMatch(await ctx.resolveRef(meta.reference, token, meta));
847+
const m = normalizeRefMatch(await resolveScoped(ctx.resolveRef, meta.reference, token, meta, scope));
801848
if (m.ambiguous) {
802849
return coerceError(meta, field, 'reference_ambiguous', 'import_reference_ambiguous', token, ctx);
803850
}
@@ -813,7 +860,7 @@ export async function coerceFieldValue(
813860
// no target object, store the raw value and let referential integrity be
814861
// enforced downstream.
815862
if (!ctx.resolveRef || !meta?.reference) return { value: display };
816-
const match = normalizeRefMatch(await ctx.resolveRef(meta.reference, display, meta));
863+
const match = normalizeRefMatch(await resolveScoped(ctx.resolveRef, meta.reference, display, meta, scope));
817864
if (match.ambiguous) {
818865
return coerceError(meta, field, 'reference_ambiguous', 'import_reference_ambiguous', display, ctx);
819866
}
@@ -860,16 +907,89 @@ export async function coerceFieldValue(
860907
// re-asserted through that route in `import-dryrun-parity.test.ts` — retiring
861908
// the mirror must not silently retire its coverage.
862909

910+
/**
911+
* [#33523] The equalities a reference column's lookup is scoped by on this
912+
* row, or none. A detail's name is unique only inside its master, so a cell
913+
* naming one is resolved within the master the same row sets, and a tie or a
914+
* miss is judged there too:
915+
*
916+
* 1. The field's own `dependsOn`: each sibling the row sets scopes the target
917+
* field it names (`param`), the filter the record picker applies.
918+
* 2. A `master_detail` field the TARGET declares
919+
* ({@link CoerceContext.referenceMasters}), when exactly one other
920+
* single-value reference column of the row points at that master and the
921+
* row sets it. Two such columns (a bill-to and a ship-to account) do not say
922+
* which one is the master, so neither scopes; `dependsOn` says it. The
923+
* picker has no counterpart for this inference.
924+
*
925+
* A row that sets no such column has no scope, and its cell is resolved across
926+
* the whole target as before. Nothing here widens a lookup: a scope only adds
927+
* conditions to the caller's own read.
928+
*/
929+
export async function referenceScopeSources(
930+
key: string,
931+
meta: ExportFieldMeta | undefined,
932+
row: Record<string, unknown>,
933+
metaMap: ReadonlyMap<string, ExportFieldMeta>,
934+
ctx: CoerceContext,
935+
): Promise<ReferenceScopeSource[]> {
936+
if (!ctx.resolveRef || !meta?.reference || !meta.type || !REFERENCE_TYPES.has(meta.type)) return [];
937+
const sets = (f: string): boolean =>
938+
f !== key && Object.prototype.hasOwnProperty.call(row, f) && !isBlank(row[f], ctx.nullValues);
939+
const out: ReferenceScopeSource[] = [];
940+
const params = new Set<string>();
941+
for (const d of meta.dependsOn ?? []) {
942+
if (!sets(d.field) || params.has(d.param)) continue;
943+
out.push({ field: d.field, param: d.param });
944+
params.add(d.param);
945+
}
946+
if (ctx.referenceMasters) {
947+
for (const master of await ctx.referenceMasters(meta.reference)) {
948+
if (params.has(master.field)) continue;
949+
const columns: string[] = [];
950+
for (const [column, m] of metaMap) {
951+
if (m.reference !== master.reference || !m.type || !REFERENCE_TYPES.has(m.type)) continue;
952+
if (isMultiValueField(m) || !sets(column)) continue;
953+
columns.push(column);
954+
}
955+
if (columns.length !== 1) continue;
956+
out.push({ field: columns[0], param: master.field });
957+
params.add(master.field);
958+
}
959+
}
960+
return out;
961+
}
962+
963+
type CoerceOutcome = Awaited<ReturnType<typeof coerceFieldValue>>;
964+
965+
/** A scope value is the one scalar a source column coerced to, else none. */
966+
function scopeValueOf(res: CoerceOutcome): unknown {
967+
if ('error' in res) return undefined;
968+
const v = res.value;
969+
return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' ? v : undefined;
970+
}
971+
863972
/**
864973
* Coerce a whole raw row into a storage-ready record. Unknown columns (no
865974
* matching field metadata) pass through untouched so ad-hoc / schemaless
866975
* objects still import. Collects every field error rather than stopping at the
867976
* first, so a UI can show all problems in a row at once.
977+
*
978+
* [#33523] A reference column scoped by other columns of the row
979+
* ({@link referenceScopeSources}) is coerced after them, with their coerced
980+
* values as its scope. A source column that fails or coerces to no single
981+
* value scopes nothing. When no pending column is ready (a cycle, or a column
982+
* whose source waits behind one), every pending column resolves unscoped.
983+
* `sourceRow` is the whole row the scope is read from when `rawRow` holds only
984+
* some of its columns (the match-key pass); a source column outside `rawRow` is
985+
* coerced unscoped, for its value only, never written or reported, so a chain
986+
* of masters is scoped one level deep there.
868987
*/
869988
export async function coerceRow(
870989
rawRow: Record<string, unknown>,
871990
metaMap: Map<string, ExportFieldMeta>,
872991
ctx: CoerceContext,
992+
sourceRow: Record<string, unknown> = rawRow,
873993
): Promise<{
874994
data: Record<string, unknown>;
875995
errors: FieldCoerceError[];
@@ -881,12 +1001,46 @@ export async function coerceRow(
8811001
*/
8821002
keptOptionValues: Record<string, string[]>;
8831003
}> {
1004+
const outcomes = new Map<string, CoerceOutcome>();
1005+
const scoped = new Map<string, ReferenceScopeSource[]>();
1006+
for (const key of Object.keys(rawRow)) {
1007+
const sources = await referenceScopeSources(key, metaMap.get(key), sourceRow, metaMap, ctx);
1008+
if (sources.length > 0) scoped.set(key, sources);
1009+
}
1010+
for (const [key, raw] of Object.entries(rawRow)) {
1011+
if (!scoped.has(key)) outcomes.set(key, await coerceFieldValue(raw, metaMap.get(key), ctx));
1012+
}
1013+
if (scoped.size > 0) {
1014+
const outside = new Map<string, CoerceOutcome>();
1015+
const sourceValue = async (f: string): Promise<unknown> => {
1016+
let res = outcomes.get(f) ?? outside.get(f);
1017+
if (!res) outside.set(f, res = await coerceFieldValue(sourceRow[f], metaMap.get(f), ctx));
1018+
return scopeValueOf(res);
1019+
};
1020+
const settled = (f: string): boolean =>
1021+
!scoped.has(f) || outcomes.has(f);
1022+
let pending = [...scoped.keys()];
1023+
while (pending.length > 0) {
1024+
const ready = pending.filter((k) => scoped.get(k)!.every((s) => settled(s.field)));
1025+
for (const key of ready.length > 0 ? ready : pending) {
1026+
let scope: Record<string, unknown> | undefined;
1027+
if (ready.length > 0) {
1028+
for (const s of scoped.get(key)!) {
1029+
const v = await sourceValue(s.field);
1030+
if (v !== undefined) (scope ??= {})[s.param] = v;
1031+
}
1032+
}
1033+
outcomes.set(key, await coerceFieldValue(rawRow[key], metaMap.get(key), ctx, scope));
1034+
}
1035+
pending = pending.filter((k) => !outcomes.has(k));
1036+
}
1037+
}
1038+
8841039
const data: Record<string, unknown> = {};
8851040
const errors: FieldCoerceError[] = [];
8861041
const keptOptionValues: Record<string, string[]> = {};
887-
for (const [key, raw] of Object.entries(rawRow)) {
888-
const meta = metaMap.get(key);
889-
const res = await coerceFieldValue(raw, meta ? meta : undefined, ctx);
1042+
for (const key of Object.keys(rawRow)) {
1043+
const res = outcomes.get(key)!;
8901044
if ('error' in res) {
8911045
// Attribute the error to the column even when metadata was missing.
8921046
errors.push({ ...res.error, field: res.error.field || key });

0 commit comments

Comments
 (0)