Skip to content

Commit de395b4

Browse files
fix(metadata-protocol)!: a seed record that leaves a key field blank is refused at load (#35459)
Fixes #34857 Also delivers (folded, closed by the area at close-out): #35336, #35376 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #35480 — skills/objectstack-data/references/seeds.md (:48 the externalId row, :68 the composite key, :93 externalId selection: none says a record must carry every key field or is refused at load) ## 维护者速读 - 用户能看到什么变化:种子数据里某条记录缺了用来识别它的键值(比如没填名称),以前每次启动、安装或升级都会悄悄多插一行;现在这一条不再写入,加载结果写明是哪个对象的第几条、缺哪个字段、怎么改,其余数据照常加载。另外「同一对象有两个兜底语种集」的报错不再提已经不存在的「进程内升级」原因。 - 为什么做:安装、升级与启动可靠性(种子数据生命周期);修的是作者自写种子每次加载重复插行且无提示的问题。 - 出错会怎样:故意留空键值的作者,这条记录在新环境里不再出现(以前是每次多一行);已经重复的行不会被清理;撤回本次合并即可恢复旧行为。 - 要你做什么:无。 ## 席位核对 ### What changes Ruling B1 (record 7000515976), extended to single-field keys (record 7000600379). - `packages/metadata-protocol/src/seed-loader.ts`: in `loadDataset`'s record loop, for the keyed modes (`ignore`, `upsert`, `update`), a record that leaves a field of its `externalId` blank (`undefined`, `null` or `''`; any component of a composite key, or the single field, `name` by default) is refused: `errored++`, one `ReferenceResolutionError` (`field` = the blank field(s), `targetField: '(externalId)'`, `recordIndex`), one `logger.error` per dataset (none on a dry run), `continue`. The check sits where the authored key is read: after `resolveSeedRecord` (expressions) and the organization stamp, BEFORE any reference resolves, so a deferred reference (#34800 / #34856) still holds its authored value and is never caught. The blank rule is the one `seedLandedKey` / `externalIdKey` already key `''` by, now one helper `isBlankSeedKeyValue`; whitespace is a value (A3, unchanged). - A2 choice: the per-record refusal REPLACES the #28952 dataset-level `warn`. That warn said "every record is written as a new row, on every load", which is false once nothing is written, and a dataset-level line on top of per-record errors would report the same records twice. The per-record message carries the #28952 prescription too (key the dataset on fields every record carries, a list, or `'id'`). The boot log says it once per dataset. - `findDuplicateFallbackSets` (#35376, PR #35374 merged 2026-11-19T08:44Z before this PR opened): refusal text and docblock name only the cause that still arises, two packages marking one object. - Docs `content/docs/data-modeling/seed-data.mdx`: Import Modes states the rule; the composite-key section says every listed field is carried; the `TestUser` example (records with no `name`) gains `externalId: 'email'` (A4); the fallback bullet drops the stale in-process-upgrade cause (#35376). - ADR-0087 ledger entry `packages/spec/src/migrations/entries/semantic/18.seed-key-blank-record-refused.ts` (data only, no export, no Zod change; authorized by the PM for this narrowing), marked `registered seed-key-blank-record-refused` in the changeset. ### Tests New pins (shared-harness rule, top-level describes in existing harness files): - `seed-loader-empty-key-warn.test.ts`: composite key with one component `''` / `null` / omitted (three loads: 2, 2, 2 rows; error names object, index 1, field `sku`, fix), single-field `sku`, default `name` through a parsed request (`SeedLoaderRequestSchema.parse`, no `externalId`: the message reads "keyed on externalId 'name' (also the key a dataset gets when it names none) and leaves 'name' blank"), CONTROL an authored `name`+`sku` key gets no such hint, an expression evaluating empty (`os.user.id`) refused, `update` reports instead of skipping silently, dry run reports and logs nothing, CONTROL fully keyed dataset converges and says nothing, CONTROL whitespace-only value is a value. The #28952 describe flips: every record refused, one error each, one line per dataset, no `warn`. - `seed-loader-deferred-key-reference.test.ts`: CONTROL `ignore` and `upsert`, a deferred key reference is not refused, three loads one row; CONTROL a key reference authored `''` beside it is refused. The #34856 delete describe in the same file stays green. Fixture triage (what each pinned is kept): - `seed-loader-deferred-dropped.test.ts` (reverse pin): its keyless device was a blank `region` in a keyed dataset, now refused. Remade, not deleted: the department dataset names no `mode` and the load config no `defaultMode` (a request built without the parse's defaults, the one load that still writes a row keyed `''`), so pass-2 write-back by captured id stays pinned on a written keyless row. Added: the KEYED blank-component record is refused before it writes or defers anything. - `seed-loader-pointer-pair.test.ts`: `insertSeed` keyed on `id` with no ids now gives each record its id; the KEYLESS heal case moves to the same mode-less device. - `seed-loader-composite-key-diagnostic.test.ts`: the ruling's pair `('a','b')` / `('a\0b','')` — the second is now refused, still never matched to the first. - `protocol.seed-external-id-refusal.test.ts`: the `externalId: 'id'` control's record carries an id. - `packages/objectql/src/engine-seed-required-deferral.test.ts`: datasets with no `externalId` (default `name`) and no `name` get `externalId: 'process_name'` / `'action'`; the KEYLESS heal case uses the mode-less device. - `packages/runtime/src/seed-loader.test.ts`: "should handle records with no matching externalId field" pinned the insert; flipped to the refusal. - `seed-loader-locale-scope.test.ts`: #35376's pin follows the new text. ### Acceptance notes - A1 (measured on 35c6331 with a copy of the base loader, three loads each): single `code` 2, 3, 4 rows, 0 warn, 0 error; default `name` 2, 3, 4; composite `''` 2, 3, 4; composite `null` (`ignore`) 2, 3, 4. With the fix: 1, 1, 1 and one error per load. - Stock: the dogfood battery boots every example app; zero blank-key refusals in its log. - Departs from PR #29066's seat route ("the boot loader never refuses"), by the maintainer's ruling. A boot still does not fail (`haltOnError: false`). - The mode-less load (no `mode`, no `defaultMode`) is left unkeyed on purpose; nothing in this PR changes it. - Not changed: rows earlier loads duplicated stay. - `seed-loader-locale-scope.test.ts` "an upgrade that changed the marked set (versions 1 and 2 on one list)" still feeds both versions straight to the loader; its comment describes the pre-#35374 replay list. Left as is: the loader still refuses that input from a direct caller. ### Verification All readings on head `755c75a5` (the fold commit `64abfecd`, one merge of `origin/main` `a9b36eff`, the #35376 commit) unless named. <details><summary>Tests and typecheck</summary> - `pnpm --filter @objectstack/metadata-protocol test`: `Test Files 358 passed | 9 skipped (367)`, `Tests 23238 passed | 45 skipped (23283)`. - `pnpm --filter @objectstack/metadata-protocol --filter @objectstack/runtime --filter @objectstack/objectql typecheck`: exit 0. - Re-keyed consumer files: runtime `src/seed-loader.test.ts src/seed-datasets.test.ts src/app-plugin.seed-locale-producer.test.ts` `Tests 93 passed (93)`; objectql `src/engine-seed-required-deferral.test.ts` `Tests 7 passed (7)`. - Consumer sweep on `64abfecd`'s tree (dist rebuilt): every test file outside this package that names the seed loader or authors seed records, run in runtime (36 files), objectql (26), cloud-connection (26), rest (10), metadata (4), plugins/organizations (5), cli unit tier (3): all green after the two re-keyed files above; integration-tier cli files declared to CI. - Dogfood battery (narrowing arm), `pnpm --filter @objectstack/dogfood test` after the `@objectstack/dogfood^...` build, on `755c75a5`: `Test Files 482 passed | 3 skipped (485)`, `Tests 4092 passed | 68 skipped (4160)`, lock verdict `command-exit 0`; zero blank-key refusals in the boot logs. </details> <details><summary>Ablation (restored, blob equals HEAD, `git diff HEAD` empty)</summary> - `scripts/ablation-replace.mjs` on `seed-loader.ts`: `const blankKeyFields = [...keyFields].filter(...)` replaced by `const blankKeyFields: string[] = [];` (anchor 1 to 0, blob `b10e9f2e` to `23591f6e`). `seed-loader-empty-key-warn.test.ts` + `seed-loader-deferred-key-reference.test.ts`: `Tests 11 failed | 22 passed (33)`; the 11 are every refusal pin, the 22 include every CONTROL. Restored: blob `b10e9f2e` equals HEAD. No build involved: the pins import `./seed-loader.js` from source. </details> <details><summary>Gates</summary> - `dispatch-gates.mjs --commands` derives 117 families (the diff touches `packages/spec`). Run locally on `755c75a5`, all exit 0: `check-adr-0087-registration` (with `--self-test`; reads `registered seed-key-blank-record-refused (new here)`), `check-changeset-no-major`, `check-empty-changeset`, `check:nul-bytes`, `check:doc-authoring`, `check:durability-log-level`, `check:issue-citations`, `check:doc-anchors`, `check:docs-single-h1`, `check:doc-frontmatter`, `check:startup-registry-verdict`, `check:engine-double-contract`, `docs-audit/check-affected-docs`, `check:cross-package-test-inputs`, `check:test-source-alias`, spec `check:upgrade-guide`, spec `check:spec-changes`, `check:type-check-coverage`, `check:type-check-debt`, `check:dts-closure`. The other derived families are declared to CI (`--ran`: 21 run, the rest UNRUN locally). - `overlap-check.mjs --branch=HEAD`: `VERDICT clean exit 0` (shares one test file with open PR #35388, merges cleanly). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CaysxGzF62ACvZ1x9x --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 97f3420 commit de395b4

14 files changed

Lines changed: 504 additions & 138 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/metadata-protocol': minor
3+
---
4+
5+
fix(metadata-protocol)!: a seed record that leaves a key field blank is refused at load instead of being inserted again on every load
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: narrowed
9+
Skills-docs: follow-up #35480 — skills/objectstack-data/references/seeds.md (:48 the externalId row, :68 the composite key, :93 `externalId` selection: none says a record must carry every key field or is refused at load)
10+
11+
<!-- adr-0087: registered seed-key-blank-record-refused -->
12+
13+
**BREAKING** for a seed record whose `externalId` value is blank. A seed is replayed on every single-tenant boot, every package install or upgrade and every publish, and each replay matches records to the rows earlier loads wrote by the dataset's `externalId`. A record that left a key field blank (no value, `null` or `''`): any component of a composite key such as `['team', 'project']`, or the one field of a single-field key (`name` when the dataset names none), matched no row and was written again by every `ignore` or `upsert` load, with nothing said. Measured over three loads of one such record beside a keyed one: 2, then 3, then 4 rows. An `update` load skipped it, also in silence.
14+
15+
- FROM: the record was written as a new row on every load (`ignore`, `upsert`) or skipped (`update`); when every record of a dataset keyed empty, the load logged one dataset-level `warn` and still wrote each record again.
16+
- TO: in the keyed modes (`ignore`, `upsert`, `update`) the load refuses the record before anything of it is written: the load result carries one error for it naming the object, the record index, the blank field(s) and the fix, the boot log says it once per dataset at `error`, and every other record and dataset loads. A dry run (`validate`) reports the same error. A dataset whose every record keys empty is the same refusal for each record; the dataset-level `warn` is gone, since it would report the same records twice.
17+
- The fix for an author: give the record a value for the blank key field, or key the dataset on fields every record carries: a field the object declares, a list of fields when no single field names a row, or `'id'` when the records carry their own ids.
18+
19+
**Not moved.** The check reads the key as authored, after the record's expressions resolve and before any reference resolves. A reference the load defers or cannot resolve yet (a person who has not signed up) is authored, so it is not blank and its row lands and holds one row across loads, as before. A whitespace-only value is a value, as before. Rows earlier loads duplicated are data and stay; remove the extra copies yourself if they matter. A request built without the parse's defaults (no `mode` on the dataset, no `defaultMode` on the config) is not keyed and is unchanged.
20+
21+
**Also: the duplicate-fallback refusal names the cause that still arises.** When the datasets being seeded mark more than one set of one object `fallback: true`, the refusal and the seed-data page no longer name "an upgrade within this process" as a cause: an upgrade now replaces a package's datasets on the replay list, so the cause left is two packages marking the same object. Wording only; what is refused is unchanged.

‎content/docs/data-modeling/seed-data.mdx‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,14 @@ customer has since edited.
7676
| `update` | Update only, skip if not found | Migration patches on existing rows |
7777

7878
Every mode matches on `externalId`, so a replay finds the row an earlier load wrote.
79+
Every record carries a value for each `externalId` field (`name` when the dataset
80+
names none). A record that leaves one blank (no value, `null` or `''`) could match no
81+
row and would be inserted again on every replay, so the load refuses it: nothing of
82+
it is written, the load reports an error naming the object, the record and the blank
83+
field, and the dataset's other records load. The check reads the key as written in the
84+
seed, after the record's expressions resolve, so an expression that comes out empty is
85+
refused, while a reference the load cannot resolve yet (a person who has not signed
86+
up) is not blank.
7987
The unkeyed modes `insert` and `replace` are retired: see
8088
[Moving off `insert` and `replace`](#moving-off-insert-and-replace).
8189

@@ -311,6 +319,7 @@ defineSeed(Account, {
311319

312320
// Automated test fixtures — CI/CD only
313321
defineSeed(TestUser, {
322+
externalId: 'email', // the records carry no `name`, the default key
314323
env: ['test'],
315324
records: [
316325
{ email: 'ci-admin@example.com', role: 'admin' },
@@ -413,11 +422,9 @@ The rules:
413422
and the load's error (also logged at warn) names the object. Every marked set
414423
still loads for the locales it lists, exactly as an unmarked set would, and
415424
every other object still seeds. Identical copies of one set — the same
416-
package's datasets merged twice — count once. Two versions of one package
417-
whose marked set changed are two sets: an upgrade keeps the earlier
418-
version's datasets on the per-organization replay list until the process
419-
restarts, so until then an organization on an unlisted locale gets no
420-
fallback for that object.
425+
package's datasets merged twice — count once. An upgrade replaces the
426+
package's datasets on the per-organization replay list, so two versions of
427+
one package are never two sets; two packages marking the same object are.
421428

422429
The loader logs, at info, each fallback set it loaded and the locale it filled
423430
in for. Datasets without the marker load exactly as before.
@@ -608,7 +615,9 @@ A join (junction) table linking two objects many-to-many has **no single-field
608615
natural key** — the *pair* of foreign keys is what makes a row unique. Pass a
609616
**list** of field names as the `externalId` so the seed runner can match existing
610617
rows on the composite key and stay idempotent across replays. The foreign keys are
611-
compared by their *resolved* record ids, which are stable between boots.
618+
compared by their *resolved* record ids, which are stable between boots. Every record
619+
carries every listed field: a record with one of them blank is refused at load, like
620+
any record with a blank key (see [Import Modes](#import-modes)).
612621

613622
```typescript
614623
// A team can staff many projects; a project can have many teams.

‎packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,9 @@ const seed = (target: string, externalId: string | string[] | undefined, mode =
192192
object: target,
193193
mode,
194194
...(externalId !== undefined ? { externalId } : {}),
195-
records: [{ name: 'G1', sku: 'g', organization_id: 'org_seedkey' }],
195+
// A dataset keyed on `id` carries the id on its record: a keyed load refuses
196+
// a record that leaves a key field blank (#34857).
197+
records: [{ name: 'G1', sku: 'g', organization_id: 'org_seedkey', ...(externalId === 'id' ? { id: 'seedkey_g1' } : {}) }],
196198
});
197199

198200
/** Plant a seed draft as a draft stored before the rule sits at rest. */

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9077,9 +9077,9 @@ export class ObjectStackProtocolImplementation implements
90779077
* Answered as the schema gate answers, with the envelope of
90789078
* {@link unknownDatasourceSaveRefusal}: `422 INVALID_METADATA`, one finding
90799079
* per missing member at `externalId` (`externalId.N` for a composite
9080-
* member), naming the field and the object. The boot loader
9081-
* never refuses; it warns once for a keyed dataset whose every record
9082-
* keys empty ({@link SeedLoaderService}).
9080+
* member), naming the field and the object. The boot loader refuses
9081+
* each keyed record that leaves a key field blank, one error per
9082+
* record, and loads the rest ({@link SeedLoaderService}).
90839083
*/
90849084
private seedExternalIdSaveRefusal(
90859085
singularType: string,

‎packages/metadata-protocol/src/seed-loader-composite-key-diagnostic.test.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ describe('[#16488] negative control: the U+0000 joiner still separates map keys'
345345
expect(nulCount('a')).toBe(0);
346346
});
347347

348-
it("the ruling's own pair — ('a','b') and ('a\\0b','') — still do not collide", async () => {
348+
it("the ruling's own pair — ('a','b') and ('a\\0b','') — still do not collide: the blank-component record is refused, never matched", async () => {
349349
const objects = { demo_pair: { name: 'demo_pair', fields: { a: { type: 'text' }, b: { type: 'text' } } } };
350350
const seeds = [{
351351
object: 'demo_pair',
@@ -362,10 +362,14 @@ describe('[#16488] negative control: the U+0000 joiner still separates map keys'
362362
const result = await new SeedLoaderService(engine, createMetadata(objects), createLogger() as never)
363363
.load({ seeds, config: CONFIG } as never);
364364

365-
expect(result.success).toBe(true);
366-
// Two rows, not one: the second never matched the first.
367-
expect(store.demo_pair).toHaveLength(2);
368-
expect(store.demo_pair.map((r: any) => r.a).sort()).toEqual([`a${NUL}b`, 'a'].sort());
365+
// [#34857] The second record leaves `b` blank, so a keyed load refuses it
366+
// before it is written; it is reported by index, never matched to (or
367+
// swallowed by) the first row, which lands on its own.
368+
expect(result.success).toBe(false);
369+
expect(store.demo_pair).toHaveLength(1);
370+
expect(store.demo_pair[0].a).toBe('a');
371+
expect(result.errors).toHaveLength(1);
372+
expect(result.errors[0]).toMatchObject({ sourceObject: 'demo_pair', field: 'b', recordIndex: 1 });
369373
});
370374

371375
it('a pair that WOULD collide under a visible `+` joiner still dedupes as two rows on replay', async () => {

‎packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts‎

Lines changed: 49 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -129,12 +129,21 @@ const CONFIG = {
129129
transaction: false,
130130
} as any;
131131

132-
/** Composite-keyed department seed; `region` decides whether its key registers. */
133-
const compositeSeeds = (region: string) => [
132+
/**
133+
* Composite-keyed department seed; `region` decides whether its key registers.
134+
*
135+
* A KEYED load refuses a record that leaves a key component blank, before
136+
* anything of it is written (#34857), so the keyless device — a WRITTEN row
137+
* whose natural key is `''` — is a department dataset that names no mode, read
138+
* by a load whose config names no default either ({@link KEYLESS_CONFIG}): a
139+
* request built without the parse's defaults, the one load that still writes
140+
* such a row. The worker dataset stays keyed (`ignore`).
141+
*/
142+
const compositeSeeds = (region: string, mode: 'ignore' | null = 'ignore') => [
134143
{
135144
object: 'drop_department',
136145
externalId: ['name', 'region'],
137-
mode: 'ignore',
146+
...(mode === null ? {} : { mode }),
138147
env: ['prod', 'dev', 'test'],
139148
records: [{ name: 'Engineering', region, head_id: 'Alice' }],
140149
},
@@ -147,6 +156,12 @@ const compositeSeeds = (region: string) => [
147156
},
148157
] as any[];
149158

159+
/** The keyless device's seeds: `region` blank, the department dataset mode-less. */
160+
const keylessSeeds = () => compositeSeeds('', null);
161+
162+
/** A load config with no default mode, so a dataset naming none is not keyed. */
163+
const KEYLESS_CONFIG = { ...CONFIG, defaultMode: undefined } as any;
164+
150165
const deferredDropLines = (logger: ReturnType<typeof createLogger>) =>
151166
logger.error.mock.calls.filter((c: unknown[]) => String(c[0]).includes('Deferred reference DROPPED'));
152167

@@ -171,8 +186,8 @@ describe('pass 2 heals a row whose natural key evaluated empty (#5127 → #11674
171186
const logger = createLogger();
172187

173188
const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
174-
seeds: compositeSeeds(''),
175-
config: CONFIG,
189+
seeds: keylessSeeds(),
190+
config: KEYLESS_CONFIG,
176191
});
177192

178193
// The row is there AND carries its association.
@@ -200,18 +215,35 @@ describe('pass 2 heals a row whose natural key evaluated empty (#5127 → #11674
200215
const logger = createLogger();
201216

202217
await new SeedLoaderService(engine, createMetadata(), logger).load({
218+
seeds: keylessSeeds(),
219+
config: KEYLESS_CONFIG,
220+
});
221+
222+
expect(logger.error).not.toHaveBeenCalled();
223+
expect(logger.warn).not.toHaveBeenCalled();
224+
});
225+
226+
/**
227+
* [#34857] Why the device above is mode-less: the same department record
228+
* in a KEYED dataset is refused at load for its blank `region`, before
229+
* anything of it is written or deferred — no row, so no back-fill to heal
230+
* and no pass-2 drop to report.
231+
*/
232+
it('a KEYED dataset refuses the blank-component record before it writes or defers anything', async () => {
233+
const { engine, store } = createFaithfulEngine();
234+
const logger = createLogger();
235+
236+
const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
203237
seeds: compositeSeeds(''),
204238
config: CONFIG,
205239
});
206240

207-
expect(logger.error).not.toHaveBeenCalled();
208-
// [#34613] The dataset is keyed now (the unkeyed `insert` it ran in is
209-
// retired), so the one `warn` is #28952's notice that every record keys
210-
// empty — a fact about the declaration. Nothing at warn is about the
211-
// deferral the load healed.
212-
const warned = logger.warn.mock.calls.map((c: unknown[]) => String(c[0]));
213-
expect(warned).toHaveLength(1);
214-
expect(warned[0]).toMatch(/keys every record on externalId 'name\+region', and no record carries a value for it/);
241+
expect(store.drop_department ?? []).toHaveLength(0);
242+
const deptResult = result.results.find((r: { object: string }) => r.object === 'drop_department')!;
243+
expect(deptResult).toMatchObject({ inserted: 0, errored: 1, referencesDeferred: 0 });
244+
expect(deptResult.errors).toHaveLength(1);
245+
expect(deptResult.errors[0]).toMatchObject({ field: 'region', recordIndex: 0 });
246+
expect(deferredDropLines(logger)).toHaveLength(0);
215247
});
216248

217249
/**
@@ -226,8 +258,8 @@ describe('pass 2 heals a row whose natural key evaluated empty (#5127 → #11674
226258
const { engine } = createFaithfulEngine();
227259

228260
const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).load({
229-
seeds: compositeSeeds(''),
230-
config: CONFIG,
261+
seeds: keylessSeeds(),
262+
config: KEYLESS_CONFIG,
231263
});
232264

233265
const deptResult = result.results.find((r: { object: string }) => r.object === 'drop_department')!;
@@ -400,8 +432,8 @@ describe('pass 2 finds no id because a KEYLESS record failed in pass 1 (#11674)'
400432
const { engine, store, logger } = loadWithFailingKeylessDepartment();
401433

402434
const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
403-
seeds: compositeSeeds(''), // region '' → externalIdKey '' → no natural key
404-
config: CONFIG,
435+
seeds: keylessSeeds(), // region '' → externalIdKey '' → no natural key
436+
config: KEYLESS_CONFIG,
405437
});
406438

407439
// The row really is absent — nothing to back-fill onto.

‎packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,3 +373,41 @@ describe('seed: a row whose key reference was empty at landing stays deleted (#3
373373
expect(store.dkr_task[0].assignee ?? null).toBeNull();
374374
});
375375
});
376+
377+
describe('seed: a key reference that resolves empty is not a blank key (#34857)', () => {
378+
/**
379+
* The blank-key refusal reads the key as AUTHORED, before any reference
380+
* resolves. A deferred key reference is authored (`'Alice'`) and empty only
381+
* after resolution, so it is never refused: the row lands, holds one row
382+
* across loads, and the #34856 delete record above keeps working.
383+
*/
384+
const blankKeyRefusals = (result: any): any[] =>
385+
result.errors.filter((e: any) => e.message.includes('was NOT loaded: it is keyed on externalId'));
386+
387+
for (const mode of ['ignore', 'upsert'] as const) {
388+
it(`CONTROL ${mode}: the deferred-key row lands and is not refused, three loads one row`, async () => {
389+
const { engine, store } = createEngine();
390+
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];
391+
392+
for (let boot = 0; boot < 3; boot++) {
393+
const result = await load(engine, seeds);
394+
expect(blankKeyRefusals(result)).toEqual([]);
395+
expect(store.dkr_task).toHaveLength(1);
396+
}
397+
expect(store.dkr_task[0].assignee ?? null).toBeNull();
398+
});
399+
}
400+
401+
it('CONTROL: beside it, a record of the same dataset whose key reference is authored blank is refused', async () => {
402+
const { engine, store } = createEngine();
403+
const result = await load(engine, [taskSeed('ignore', [
404+
{ name: 'Onboard', assignee: 'Alice' },
405+
{ name: 'Review', assignee: '' },
406+
])]);
407+
408+
const refused = blankKeyRefusals(result);
409+
expect(refused).toHaveLength(1);
410+
expect(refused[0]).toMatchObject({ sourceObject: 'dkr_task', field: 'assignee', recordIndex: 1 });
411+
expect(store.dkr_task.map((r) => r.name)).toEqual(['Onboard']);
412+
});
413+
});

0 commit comments

Comments
 (0)