Skip to content

Commit 842b468

Browse files
fix(metadata-protocol): a seed key reference empty on the first load holds one row across loads (#34854)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBQ3DFv6XZAspQRYGQoEWhr8)_ Fixes #34800 Clause-②: no Metadata-protocol: none repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH ## 维护者速读 - 改了什么:种子数据集的复合 `externalId` 里含一个首次加载时只能留空的引用(如尚未注册的人员)时,这行以「按作者写下的键派生的 id」落库;之后每次加载按这个 id 找回同一行,引用一旦可解析就补写到这一行上。 - 为什么改:之前每次启动/每次组织重放都再插一行(实测 1 → 2 → 3;人员在两次启动之间注册则 1 → 2 → 2,旧行永远留空)。#34613 退役 insert/replace 后,默认模式 + 复合键正是推荐写法。 - 风险与回滚:只影响「键里有引用、且该引用在插入时被延后」的行;引用首次即可解析的复合键、纯字段复合键照旧(引擎生成 id)。已经产生重复行的安装不会自动清理,下次加载最多再落一行,之后稳定。回滚 = revert 本 PR。 - 先看:`packages/metadata-protocol/src/seed-loader.ts` 里 `rowLandedWithEmptyKeyReference`(按 id 认领的守卫条件)、派生 id 赋值块与 `ignore` 模式的 pass-2 补写块;`seedDeferredKeyRowId`。 - 两分钟验证:`pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/seed-loader-deferred-key-reference.test.ts`,预期 9 个用例全绿(三次加载始终 1 行、人员出现后引用补到首行、两条仅引用不同的记录保持 2 行、客户手建的空引用行不被占用)。 - 需要你做的:无,席位落地。 ## What changes `packages/metadata-protocol/src/seed-loader.ts`: - A row that lands while a reference in its key is deferred (pass 1 could not resolve it, so the column is left out of the insert) now lands with an id derived from the key as authored: `seedDeferredKeyRowId(object, row organization, authoredKey)`, where `authoredKey` is `seedLandedKey` over the record before its references resolve — the person's natural key, never the id it resolves to. Only for `upsert` / `ignore`, only when the record names no `id` of its own, and never an id a row of this organization or another record of the load already holds. - When a record's natural key finds no row, `rowLandedWithEmptyKeyReference` looks the row up by that id (or by the record's own `id`), from the same pre-load read, now also indexed by id (`loadExistingRecords`' optional `byId`). It takes the row only when its other key columns equal the record's and each reference column it holds is empty or the very value the record resolved, and only for one record of the load. An exact natural-key match always wins. The write decision, the create-only check, seed files and the #31021 withdrawal question all read the found row through one view (`existingRowsFor`). - Once the reference resolves it lands on the row first landed: `upsert` updates the row as it does any matched row; `ignore` writes nothing over a row it found, so the one column is back-filled by pass 2 (the held person reference path writes the same way onto the row the seed landed on). Route (the claim's): the replay finds the row as first landed. Why an id and not the #31021 ledger: the ledger stores keys, never which row a key landed on, so it can say "this key landed here" but cannot find the row; and it exists only where a composition registers `sys_seed_landed_key` and the load has an organization. The id is carried by the row itself, so both paths are covered by one mechanism, and a row a person created (random id) can never be taken. Authoring-time refusal of such a key was not taken (it narrows the accept set; the claim excludes it). ## Tests - New `packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts` (9 cases, a fresh loader per load as a restart does): `ignore` and `upsert` × {person never appears: 3 loads → 1 row; person appears between loads: 1 row, reference on the row first landed}; the landed-key record kept (`landedKeys: 'honour'`): 1 row, skipped not withdrawn; two records differing only in the reference stay two rows, each filled with its own person; a customer row with the reference empty is never taken. CONTROLs: a composite key whose reference resolves on the first load, and a composite key over plain fields, match as before with engine-minted ids. - New `packages/runtime/src/seed-deferred-key-reference-real-driver.integration.test.ts` (2 cases): real `SeedLoaderService` + real `ObjectQL` + real `SqlDriver` on one better-sqlite3 file, three boots (new engine/driver/loader each): per-organization replay with the landed-key record, person never appears → `[1, 1, 1]`; no landed-key record, `upsert`, person appears before boot 2 → `[1, 1, 1]` and the reference lands. - `scripts/engine-double-contract.pinned.json`: the three pinned doubles of the new test file, written by `node scripts/check-engine-double-contract.mjs --write` as the gate prescribes (add-only, "0 lost"). ## Acceptance notes - Already-duplicated installs keep their copies (the old rows carry engine-minted ids, which are indistinguishable from a customer's row); the next load lands at most one more row, which every later load finds. Stated in the changeset. - `SeedDatasetFiles.open` still receives the natural-key map only; a row found by id is passed to `prepareRow` through `existingRowsFor`, which is the call that reads it. - A row that landed by its derived id and was filled later, whose person is then removed: the record defers again and still finds the row by id. NOT covered, unchanged from main: a row that landed with its reference resolved (engine-minted id) whose person is later removed keys empty on the next load, and a new row lands. - The held person reference path (`resolveHeldPersonReferences`) is not edited: the deferral's internal id is the found row's id, so a held reference is written onto that row. ## Verification Measured on `origin/main` c513d62 before code, with the same harness as the runtime test (scratch file, deleted): every composition duplicated. <details><summary>Reproduction on main (three boots over one sqlite file)</summary> ``` MEASURE mode=default ledger=true sole=false signUpAfter=null rows=1 -> 2 -> 3 MEASURE mode=default ledger=true sole=true signUpAfter=null rows=1 -> 2 -> 3 MEASURE mode=default ledger=true sole=false signUpAfter=1 rows=1 -> 2 -> 2 MEASURE mode=default ledger=false sole=false signUpAfter=null rows=1 -> 2 -> 3 MEASURE mode=default ledger=false sole=false signUpAfter=1 rows=1 -> 2 -> 2 MEASURE mode=upsert ledger=true sole=false signUpAfter=null rows=1 -> 2 -> 3 MEASURE mode=upsert ledger=false sole=false signUpAfter=1 rows=1 -> 2 -> 2 (the 1 -> 2 -> 2 rows: the second copy carried the person, the first stayed NULL) ``` Same harness on this branch: every line `rows=1 -> 1 -> 1`, reference filled where the person signed up. </details> <details><summary>Ablation (unit file; it imports ./seed-loader.js from src, so no dist leg)</summary> Fix committed first; mutation via `scripts/ablation-replace.mjs`, restore by `git checkout HEAD --`, proven by blob == HEAD and `git diff HEAD` empty. 1. Find-by-id removed (`const row = existingRowsById.get(rowId);` → `const row = undefined as any;`, blob 195e71f → 50685164): 7 failed / 2 passed — every duplicate and fill case red; the two CONTROLs green. 2. Guard replaced by the naive fallback (take any stored row whose reference column is empty): 1 failed / 8 passed — the customer-row case red, as it must be. A first attempt at this mutation reassigned a `const` and threw TypeError in every case; that run was discarded as a non-mutation and redone. </details> <details><summary>Local readings at head 58dc0df (CI runs the full farm)</summary> - `pnpm --filter @objectstack/metadata-protocol typecheck` + full `vitest run` (after merging origin/main dfbc316 and rebuilding the closure): VERDICT command-exit 0 · Test Files 349 passed / 9 skipped (358) · Tests 23100 passed / 45 skipped. - `pnpm --filter @objectstack/runtime typecheck` (tsc + check:test-typecheck OK) and the new runtime file: Test Files 1 passed · Tests 2 passed. - Derived gate families (`dispatch-gates.mjs --commands`, 75 for this diff): `--ran` verdict "75 derived famil(ies) accounted for — 73 run, 2 NOT-MEASURED". NOT MEASURED: `check:dual-build-cjs-loads` (PREREQUISITE NOT MET: reads every package's dist; only the touched closures are built here) and `check-plugin-teardown-shape.mjs --self-test` (shallow clone cannot reach its pinned fixture commit; checker-health only). `check:engine-double-contract` was red until the ledger rows above, exit 0 after. - `overlap-check.mjs`: VERDICT clean — merges cleanly with origin/main and with #34791 (shares seed-loader.ts) and #34784 (shares the ledger). - Package `test:repo` projects and the rest of the farm: declared to CI. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgNCAXyGfBQFZBwixH <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzgNCAXyGfBQFZBwixH --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 73609d0 commit 842b468

5 files changed

Lines changed: 573 additions & 7 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a seed dataset whose `externalId` includes a reference the first load must leave empty now holds one row across loads, and the reference lands on that row once it resolves
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A dataset keyed on a composite `externalId` such as `['name', 'assignee']`, whose reference names a person who has not signed up yet, lands its row with that column empty. Every later load (each boot, each per-organization replay) inserted another copy: while the person stayed missing the record keyed empty, and once the person existed the record carried an id the stored row did not. Three loads left three rows.
11+
12+
Such a row now lands with an id derived from the key as the author wrote it (the person's natural key, never the id it resolves to), in its object and organization. A load whose natural key finds no row looks the row up by that id, and takes it only when its other key columns still match and its reference column is empty or already holds the resolved value. A row a person created never carries such an id, so it is never taken, and two records whose keys differ only in that reference stay two rows. Once the reference resolves it is written onto the row first landed: by the update under `mode: 'upsert'`, and under the default `mode: 'ignore'` by the pass-2 back-fill of that one column. Keys that resolve on the first load, and keys over plain fields, match exactly as before, with engine-minted ids.
13+
14+
An install that already holds such copies keeps them (remove the extras by hand); the next load lands at most one more row, the one the following loads find.
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect, vi } from 'vitest';
4+
import { SeedLoaderService } from './seed-loader.js';
5+
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
6+
import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core';
7+
8+
/**
9+
* [#34800] A dataset whose `externalId` includes a reference the first load
10+
* must leave empty — the person it names has not signed up yet — holds ONE row
11+
* across loads.
12+
*
13+
* The row lands with that key column NULL (the reference is deferred to pass 2
14+
* and misses there too). Matching existing rows by natural key cannot find it
15+
* again: while the reference stays unresolvable the record keys empty, and
16+
* once it resolves the record carries an id the stored row does not. Measured
17+
* before the fix, three loads over one store: 1 → 2 → 3 rows, and 1 → 2 → 2
18+
* when the person appears between loads (the copy that finally carried the
19+
* person sat beside the first one, still NULL). The loader now lands such a
20+
* row with an id derived from the key as authored, and a replay whose natural
21+
* key misses finds the row by that id — and fills the reference onto it once
22+
* it resolves.
23+
*
24+
* Each load runs a fresh loader over the same store, as a restart does: the
25+
* held person references a loader keeps in memory do not survive it.
26+
*
27+
* The engine double filters `where` by equality (an absent column matches
28+
* `null`), keeps an id the write supplies and refuses a second row under one
29+
* id, as a primary key does, and answers the compare-and-set update form.
30+
*/
31+
32+
const ORG = 'org_dkr34800test';
33+
34+
function createLogger() {
35+
return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
36+
}
37+
38+
function rowMatches(row: Record<string, unknown>, where: Record<string, unknown> = {}): boolean {
39+
return Object.entries(where).every(([k, v]) => {
40+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported combinator ${k}`);
41+
if (v !== null && typeof v === 'object') throw new Error(`fake driver: unsupported operator on ${k}`);
42+
return (row[k] ?? null) === (v ?? null);
43+
});
44+
}
45+
46+
function createEngine(): { engine: IDataEngine; store: Record<string, any[]> } {
47+
const store: Record<string, any[]> = {};
48+
let idCounter = 0;
49+
const engine = {
50+
find: vi.fn(async (objectName: string, query?: any) => {
51+
let rows = (store[objectName] ?? []).filter((r) => rowMatches(r, query?.where));
52+
if (typeof query?.limit === 'number') rows = rows.slice(0, query.limit);
53+
return rows.map((r) => ({ ...r }));
54+
}),
55+
findOne: vi.fn(async (objectName: string, query?: any) => {
56+
assertEngineFindOnePredicate(objectName, query);
57+
const rows = await (engine.find as any)(objectName, { ...query, limit: 1 });
58+
return rows[0] ?? null;
59+
}),
60+
insert: vi.fn(async (objectName: string, data: any) => {
61+
const rows = (store[objectName] ??= []);
62+
const land = (d: any) => {
63+
const id = d.id ?? `gen-${++idCounter}`;
64+
if (rows.some((r) => r.id === id)) throw new Error(`fake driver: duplicate primary key '${id}'`);
65+
const row = { ...d, id };
66+
rows.push(row);
67+
return { ...row };
68+
};
69+
return Array.isArray(data) ? data.map(land) : land(data);
70+
}),
71+
update: vi.fn(async (objectName: string, data: any, options?: any) => {
72+
assertEngineUpdateDispatch(data, options);
73+
const rows = store[objectName] ?? [];
74+
if (options?.where) {
75+
let n = 0;
76+
for (const row of rows) {
77+
if (!rowMatches(row, options.where)) continue;
78+
Object.assign(row, data);
79+
n += 1;
80+
}
81+
return n;
82+
}
83+
const row = rows.find((r) => r.id === data.id);
84+
if (!row) return null;
85+
Object.assign(row, data);
86+
return { ...row };
87+
}),
88+
delete: vi.fn(async (_objectName: string, options?: any) => {
89+
assertEngineDeleteDispatch(options);
90+
return { deleted: 1 };
91+
}),
92+
count: vi.fn(async (objectName: string) => (store[objectName] ?? []).length),
93+
aggregate: vi.fn(async () => []),
94+
} as unknown as IDataEngine;
95+
return { engine, store };
96+
}
97+
98+
const OBJECTS: Record<string, any> = {
99+
dkr_person: { name: 'dkr_person', fields: { name: { type: 'text' } } },
100+
dkr_task: {
101+
name: 'dkr_task',
102+
fields: {
103+
name: { type: 'text' },
104+
assignee: { type: 'lookup', reference: 'dkr_person' },
105+
notes: { type: 'text' },
106+
},
107+
},
108+
dkr_tag: { name: 'dkr_tag', fields: { name: { type: 'text' }, kind: { type: 'text' }, notes: { type: 'text' } } },
109+
sys_seed_landed_key: {
110+
name: 'sys_seed_landed_key',
111+
fields: { object_name: { type: 'text' }, seed_key: { type: 'textarea' } },
112+
},
113+
};
114+
115+
function createMetadata(): IMetadataService {
116+
return {
117+
getObject: vi.fn(async (name: string) => OBJECTS[name]),
118+
listObjects: vi.fn(async () => Object.values(OBJECTS)),
119+
register: vi.fn(async () => {}),
120+
get: vi.fn(async (_t: string, name: string) => OBJECTS[name]),
121+
list: vi.fn(async () => []),
122+
unregister: vi.fn(async () => {}),
123+
exists: vi.fn(async () => false),
124+
listNames: vi.fn(async () => []),
125+
} as unknown as IMetadataService;
126+
}
127+
128+
const CONFIG = {
129+
dryRun: false,
130+
haltOnError: false,
131+
multiPass: true,
132+
defaultMode: 'ignore',
133+
batchSize: 1000,
134+
transaction: false,
135+
organizationId: ORG,
136+
} as any;
137+
138+
function taskSeed(mode: 'ignore' | 'upsert', records: Array<Record<string, unknown>>) {
139+
return { object: 'dkr_task', externalId: ['name', 'assignee'], mode, env: ['prod', 'dev', 'test'], records };
140+
}
141+
142+
/** One load by a fresh loader — a restart. */
143+
async function load(engine: IDataEngine, seeds: any[], landedKeys?: 'honour') {
144+
return new SeedLoaderService(engine, createMetadata(), createLogger() as never, landedKeys ? { landedKeys } : {})
145+
.load({ seeds, config: CONFIG });
146+
}
147+
148+
function signUp(store: Record<string, any[]>, name: string): string {
149+
const id = `person-${name.toLowerCase()}`;
150+
(store.dkr_person ??= []).push({ id, name, organization_id: ORG });
151+
return id;
152+
}
153+
154+
describe('seed: a key reference empty on the first load holds one row across loads (#34800)', () => {
155+
for (const mode of ['ignore', 'upsert'] as const) {
156+
it(`${mode}: three loads while the person never appears leave one row`, async () => {
157+
const { engine, store } = createEngine();
158+
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];
159+
160+
const counts: number[] = [];
161+
for (let boot = 0; boot < 3; boot++) {
162+
await load(engine, seeds);
163+
counts.push(store.dkr_task.length);
164+
}
165+
166+
expect(counts).toEqual([1, 1, 1]);
167+
expect(store.dkr_task[0].assignee ?? null).toBeNull();
168+
});
169+
170+
it(`${mode}: the person appearing between loads fills the reference onto the row first landed`, async () => {
171+
const { engine, store } = createEngine();
172+
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];
173+
174+
await load(engine, seeds);
175+
const firstLanded = store.dkr_task[0].id;
176+
const alice = signUp(store, 'Alice');
177+
const second = await load(engine, seeds);
178+
await load(engine, seeds);
179+
180+
expect(second.success).toBe(true);
181+
expect(store.dkr_task).toHaveLength(1);
182+
expect(store.dkr_task[0]).toMatchObject({ id: firstLanded, name: 'Onboard', assignee: alice });
183+
});
184+
}
185+
186+
it('with the landed-key record kept, the row is found too and is not reported as removed', async () => {
187+
const { engine, store } = createEngine();
188+
const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])];
189+
190+
await load(engine, seeds, 'honour');
191+
const alice = signUp(store, 'Alice');
192+
const second = await load(engine, seeds, 'honour');
193+
await load(engine, seeds, 'honour');
194+
195+
expect(second.summary.totalSkipped).toBe(1);
196+
expect(store.dkr_task).toHaveLength(1);
197+
expect(store.dkr_task[0].assignee).toBe(alice);
198+
});
199+
200+
it('two records that differ only in the reference stay two rows, each filled with its own person', async () => {
201+
const { engine, store } = createEngine();
202+
const seeds = [taskSeed('ignore', [
203+
{ name: 'Onboard', assignee: 'Alice' },
204+
{ name: 'Onboard', assignee: 'Bob' },
205+
])];
206+
207+
await load(engine, seeds);
208+
await load(engine, seeds);
209+
expect(store.dkr_task).toHaveLength(2);
210+
const [alice, bob] = [signUp(store, 'Alice'), signUp(store, 'Bob')];
211+
await load(engine, seeds);
212+
await load(engine, seeds);
213+
214+
expect(store.dkr_task).toHaveLength(2);
215+
expect(store.dkr_task.map((r) => r.assignee).sort()).toEqual([alice, bob].sort());
216+
});
217+
218+
it('a row a person created with the reference empty is never taken for the seed row', async () => {
219+
const { engine, store } = createEngine();
220+
store.dkr_task = [{ id: 'customer-row', name: 'Onboard', assignee: null, notes: 'mine', organization_id: ORG }];
221+
const seeds = [taskSeed('upsert', [{ name: 'Onboard', assignee: 'Alice', notes: 'seeded' }])];
222+
223+
await load(engine, seeds);
224+
const alice = signUp(store, 'Alice');
225+
await load(engine, seeds);
226+
227+
expect(store.dkr_task).toHaveLength(2);
228+
expect(store.dkr_task.find((r) => r.id === 'customer-row')).toEqual(
229+
{ id: 'customer-row', name: 'Onboard', assignee: null, notes: 'mine', organization_id: ORG },
230+
);
231+
expect(store.dkr_task.find((r) => r.id !== 'customer-row')).toMatchObject({ assignee: alice, notes: 'seeded' });
232+
});
233+
234+
it('CONTROL: a composite key whose reference resolves on the first load is matched as before, engine-minted id', async () => {
235+
const { engine, store } = createEngine();
236+
const alice = signUp(store, 'Alice');
237+
const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])];
238+
239+
for (let boot = 0; boot < 3; boot++) await load(engine, seeds);
240+
241+
expect(store.dkr_task).toHaveLength(1);
242+
expect(store.dkr_task[0]).toMatchObject({ assignee: alice });
243+
expect(store.dkr_task[0].id).toMatch(/^gen-/);
244+
});
245+
246+
it('CONTROL: a composite key over plain fields is matched as before, engine-minted id', async () => {
247+
const { engine, store } = createEngine();
248+
const seeds = [{
249+
object: 'dkr_tag', externalId: ['name', 'kind'], mode: 'upsert', env: ['prod', 'dev', 'test'],
250+
records: [{ name: 'Urgent', kind: 'priority' }, { name: 'Urgent', kind: 'label' }],
251+
}];
252+
253+
for (let boot = 0; boot < 3; boot++) await load(engine, seeds);
254+
255+
expect(store.dkr_tag).toHaveLength(2);
256+
expect(store.dkr_tag.every((r) => /^gen-/.test(r.id))).toBe(true);
257+
});
258+
});

0 commit comments

Comments
 (0)