Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/34857-seed-blank-key-record-refused.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/metadata-protocol': minor
---

fix(metadata-protocol)!: a seed record that leaves a key field blank is refused at load instead of being inserted again on every load

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)

<!-- adr-0087: registered seed-key-blank-record-refused -->

**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.

- 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.
- 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.
- 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.

**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.

**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.
21 changes: 15 additions & 6 deletions content/docs/data-modeling/seed-data.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,14 @@ customer has since edited.
| `update` | Update only, skip if not found | Migration patches on existing rows |

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

Expand Down Expand Up @@ -311,6 +319,7 @@ defineSeed(Account, {

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

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

```typescript
// A team can staff many projects; a project can have many teams.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,9 @@ const seed = (target: string, externalId: string | string[] | undefined, mode =
object: target,
mode,
...(externalId !== undefined ? { externalId } : {}),
records: [{ name: 'G1', sku: 'g', organization_id: 'org_seedkey' }],
// A dataset keyed on `id` carries the id on its record: a keyed load refuses
// a record that leaves a key field blank (#34857).
records: [{ name: 'G1', sku: 'g', organization_id: 'org_seedkey', ...(externalId === 'id' ? { id: 'seedkey_g1' } : {}) }],
});

/** Plant a seed draft as a draft stored before the rule sits at rest. */
Expand Down
6 changes: 3 additions & 3 deletions packages/metadata-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9077,9 +9077,9 @@ export class ObjectStackProtocolImplementation implements
* Answered as the schema gate answers, with the envelope of
* {@link unknownDatasourceSaveRefusal}: `422 INVALID_METADATA`, one finding
* per missing member at `externalId` (`externalId.N` for a composite
* member), naming the field and the object. The boot loader
* never refuses; it warns once for a keyed dataset whose every record
* keys empty ({@link SeedLoaderService}).
* member), naming the field and the object. The boot loader refuses
* each keyed record that leaves a key field blank, one error per
* record, and loads the rest ({@link SeedLoaderService}).
*/
private seedExternalIdSaveRefusal(
singularType: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ describe('[#16488] negative control: the U+0000 joiner still separates map keys'
expect(nulCount('a')).toBe(0);
});

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

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

it('a pair that WOULD collide under a visible `+` joiner still dedupes as two rows on replay', async () => {
Expand Down
66 changes: 49 additions & 17 deletions packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,21 @@ const CONFIG = {
transaction: false,
} as any;

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

/** The keyless device's seeds: `region` blank, the department dataset mode-less. */
const keylessSeeds = () => compositeSeeds('', null);

/** A load config with no default mode, so a dataset naming none is not keyed. */
const KEYLESS_CONFIG = { ...CONFIG, defaultMode: undefined } as any;

const deferredDropLines = (logger: ReturnType<typeof createLogger>) =>
logger.error.mock.calls.filter((c: unknown[]) => String(c[0]).includes('Deferred reference DROPPED'));

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

const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
seeds: compositeSeeds(''),
config: CONFIG,
seeds: keylessSeeds(),
config: KEYLESS_CONFIG,
});

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

await new SeedLoaderService(engine, createMetadata(), logger).load({
seeds: keylessSeeds(),
config: KEYLESS_CONFIG,
});

expect(logger.error).not.toHaveBeenCalled();
expect(logger.warn).not.toHaveBeenCalled();
});

/**
* [#34857] Why the device above is mode-less: the same department record
* in a KEYED dataset is refused at load for its blank `region`, before
* anything of it is written or deferred — no row, so no back-fill to heal
* and no pass-2 drop to report.
*/
it('a KEYED dataset refuses the blank-component record before it writes or defers anything', async () => {
const { engine, store } = createFaithfulEngine();
const logger = createLogger();

const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
seeds: compositeSeeds(''),
config: CONFIG,
});

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

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

const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).load({
seeds: compositeSeeds(''),
config: CONFIG,
seeds: keylessSeeds(),
config: KEYLESS_CONFIG,
});

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

const result = await new SeedLoaderService(engine, createMetadata(), logger).load({
seeds: compositeSeeds(''), // region '' → externalIdKey '' → no natural key
config: CONFIG,
seeds: keylessSeeds(), // region '' → externalIdKey '' → no natural key
config: KEYLESS_CONFIG,
});

// The row really is absent — nothing to back-fill onto.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,41 @@ describe('seed: a row whose key reference was empty at landing stays deleted (#3
expect(store.dkr_task[0].assignee ?? null).toBeNull();
});
});

describe('seed: a key reference that resolves empty is not a blank key (#34857)', () => {
/**
* The blank-key refusal reads the key as AUTHORED, before any reference
* resolves. A deferred key reference is authored (`'Alice'`) and empty only
* after resolution, so it is never refused: the row lands, holds one row
* across loads, and the #34856 delete record above keeps working.
*/
const blankKeyRefusals = (result: any): any[] =>
result.errors.filter((e: any) => e.message.includes('was NOT loaded: it is keyed on externalId'));

for (const mode of ['ignore', 'upsert'] as const) {
it(`CONTROL ${mode}: the deferred-key row lands and is not refused, three loads one row`, async () => {
const { engine, store } = createEngine();
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];

for (let boot = 0; boot < 3; boot++) {
const result = await load(engine, seeds);
expect(blankKeyRefusals(result)).toEqual([]);
expect(store.dkr_task).toHaveLength(1);
}
expect(store.dkr_task[0].assignee ?? null).toBeNull();
});
}

it('CONTROL: beside it, a record of the same dataset whose key reference is authored blank is refused', async () => {
const { engine, store } = createEngine();
const result = await load(engine, [taskSeed('ignore', [
{ name: 'Onboard', assignee: 'Alice' },
{ name: 'Review', assignee: '' },
])]);

const refused = blankKeyRefusals(result);
expect(refused).toHaveLength(1);
expect(refused[0]).toMatchObject({ sourceObject: 'dkr_task', field: 'assignee', recordIndex: 1 });
expect(store.dkr_task.map((r) => r.name)).toEqual(['Onboard']);
});
});
Loading
Loading