Skip to content

Commit 35c6331

Browse files
fix(seed): a deferred-key seed row a person deleted stays deleted (#35361)
Fixes #34856 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:种子行在落地时若其 externalId 中的引用尚为空(如被指派的人还没注册),现在会以其按"作者原写键"派生的落地 id 记入落地键账本;此后无论引用仍空还是已解析,删除都能被识别。 - 为什么改:之前这类行在账本里没有任何记录,用户删掉后下一次种子加载会把它重新插回来,删除不生效。 - 风险与回滚:仅影响 `landedKeys` 开启的 upsert/ignore 数据集里、键含延迟引用的行;键完整的行、从未落地的行、重新播种行为不变。回滚即 revert 本 PR。 - 先看:`packages/metadata-protocol/src/seed-loader.ts`(`deferredLandedKey`、`isWithdrawnRow`、撤回分支里丢弃本行 pass-2 延迟),`packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts` 末尾的 #34856 describe。 - 两分钟验证:`pnpm --filter @objectstack/metadata-protocol exec vitest run src/seed-loader-deferred-key-reference.test.ts`,预期 17 个用例全绿(其中 8 个是 #34856 新增)。 - 需要你做的:无,席位落地。 ## What changes A seed row whose `externalId` includes a reference that is still empty on the load that lands it (the #34800 shape: a person not signed up yet) keyed `''` in the landed-key ledger, and the ledger records only non-empty keys, so a person's delete of that row was undone by the next load. - `seed-loader.ts`: such a row is now recorded under `deferredLandedKey`, an `id` key over `seedDeferredKeyRowId` of the AUTHORED key (the id the row lands with, #34800 / PR #34854). It is read off the record before any reference resolves, so the next load computes the same key whether the reference is still empty or has resolved since. - The honour check (`isWithdrawnRow`) consults that key after the existing natural-key and found-by-id checks, both when the record keys `''` and when it keys complete but that complete key was never recorded. - A row withdrawn this way also drops the key-reference deferrals it pushed on the way, so pass 2 does not report a drop for a row that was never meant to land (caught by the `success` assertion before this line existed). Why the derived id and not "the key it will carry": the resolved key is unknown while the reference stays empty, which is exactly the state the first delete happens in. The derived id is the one identity computable in both states. Its `id` spelling cannot collide with a reference-keyed dataset's natural-key entries, because field names travel with the values in a ledger key. ## Tests A new top-level `describe` in `packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts`, the #34800 harness (real `SeedLoaderService`, that file's already-pinned engine double, a fresh loader per load). It goes in that file rather than a new one so the pinned double is reused instead of copied into the engine-double ledger: - `ignore` and `upsert`: deleted while the person is still missing, not inserted again (success, skipped 1, inserted 0). - `ignore` and `upsert`: deleted, then the person signs up, still not inserted again. - The ledger entry equals `[["id", ROW_ID]]` for the row's landed id. - CONTROL: a complete-key row deleted stays deleted, as before. - CONTROL: a deferred-key row the seed never landed here still lands, beside the deleted one. - A kept deferred-key row found again and filled once the person signs up is the existing pin `with the landed-key record kept, the row is found too…` in the same file, still green. - CONTROL: a deliberate re-seed brings the deleted row back. ## Acceptance notes - Real-engine pin (ObjectQL + SqlDriver) not added: `@objectstack/metadata-protocol` has no objectql/driver dependency, and the real-driver sibling lives in `packages/runtime`, outside this card's file fence. Loader-level pins with the copied engine double cover the behaviour. - Edge, not changed: when a dataset authors `organization_id` as a natural-key reference rather than taking the stamped tenant organization, `seedDeferredKeyRowId` is computed over the pre-resolution value at the honour check and the post-resolution value at landing (pre-existing in #34800's `rowLandedWithEmptyKeyReference`). `deferredLandedKey` is computed once, before resolution, so the ledger stays self-consistent across loads either way. ## Verification All readings on head `ca2df4fd`. <details><summary>Red on main, then green</summary> - Before the fix (pins run against the unchanged loader at 81c0947): `Tests 7 failed | 2 passed (9)`. The four delete cases failed with `expected [ { name: 'Onboard', … } ] to have a length of +0 but got 1`, which reproduces the card. - `pnpm --filter @objectstack/metadata-protocol typecheck` exit 0; full package `vitest run`: `Test Files 359 passed | 9 skipped (368)`, `Tests 23227 passed | 45 skipped (23272)` (run on 3bd8c56; ca2df4f only moves the pins into the harness file). - On ca2df4f: `seed-loader-deferred-key-reference.test.ts` + `seed-loader-landed-ids.test.ts`: `Tests 44 passed (44)`; typecheck exit 0. </details> <details><summary>Ablations (each restored, `git diff HEAD` empty and HEAD blob hash matched after)</summary> - Delete the ledger-record line (`else if (deferredKeyFields.size > 0 …) landedKeyByRecordIndex.set(i, deferredLandedKey)`): 6 failed. - Replace the honour branch with `return false`: 5 failed (on ca2df4f, against the folded pins: `Tests 5 failed | 12 passed (17)`). - Delete `deferredUpdates.length = deferredUpdatesBeforeRow`: 2 failed (the `success` assertion on the still-missing cases). - Mutations landed through `scripts/ablation-replace.mjs` (anchor 1 to 0, blob moved); no build involved, as the pins import `./seed-loader.js` from source. </details> <details><summary>Gates</summary> - `dispatch-gates.mjs --commands` derived 67 families for this diff; all 67 run on ca2df4f, all exit 0. `--ran` reconciliation: 67 derived, 67 run, 0 NOT-MEASURED, 0 UNRUN. - `check-plugin-teardown-shape.mjs --self-test` first exited 3 on a shallow clone (its pinned fixture commit was missing); after fetching that one commit it passed, 48 cases. - `check:engine-double-contract`: `OK — 1359 pinned`. - `overlap-check.mjs --branch=HEAD`: `VERDICT clean exit 0`, 0 PR heads share a file. - `check-nul-bytes.mjs`: OK. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8b550f8 commit 35c6331

3 files changed

Lines changed: 160 additions & 2 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(seed): a seed row that landed while a reference in its key was still empty stays deleted once a person deletes it
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A seed dataset whose `externalId` includes a reference can land a row before that reference resolves, for example a task assigned to a person who has not signed up yet. With the record of landed seed rows kept (`landedKeys: 'honour'`), such a row was recorded under no key, because its key had an empty part when it landed. A person who deleted the row got it back on the next seed load.
11+
12+
The row is now recorded under the id it lands with, which is derived from the key as the seed authored it. The next load finds that record whether the reference is still empty or has resolved since, so the deleted row is not inserted again. A row the seed never landed in the organization still lands, and a deliberate re-seed still brings deleted rows back.

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,3 +256,120 @@ describe('seed: a key reference empty on the first load holds one row across loa
256256
expect(store.dkr_tag.every((r) => /^gen-/.test(r.id))).toBe(true);
257257
});
258258
});
259+
260+
/**
261+
* [#34856] A row that landed while a reference in its key was still empty, and
262+
* that a person then deleted, stays deleted — as a row whose key was complete
263+
* at landing does. The record of landed rows (`landedKeys: 'honour'`) recorded
264+
* nothing for a key with an empty component, so such a row was never recorded
265+
* and the next load inserted it again (measured before the fix with exactly
266+
* these loads: back on the next load, whether the person was still missing or
267+
* had signed up since). It is now recorded under the id it lands with, derived
268+
* from its key as AUTHORED: the one identity a load can compute both while the
269+
* reference is still empty and after it resolves. A person's delete removes the
270+
* row from the store directly, as the app's own delete would.
271+
*/
272+
273+
/** One load by a fresh loader, keeping the landed-key record in `landedKeys` mode. */
274+
async function loadWith(engine: IDataEngine, seeds: any[], landedKeys: 'honour' | 'reseed' = 'honour') {
275+
return new SeedLoaderService(engine, createMetadata(), createLogger() as never, { landedKeys })
276+
.load({ seeds, config: CONFIG });
277+
}
278+
279+
/** A person deletes the seeded task named `name` in the app. */
280+
function deleteTask(store: Record<string, any[]>, name: string): void {
281+
const before = store.dkr_task.length;
282+
store.dkr_task = store.dkr_task.filter((r) => r.name !== name);
283+
expect(store.dkr_task.length).toBe(before - 1);
284+
}
285+
286+
describe('seed: a row whose key reference was empty at landing stays deleted (#34856)', () => {
287+
for (const mode of ['ignore', 'upsert'] as const) {
288+
it(`${mode}: deleted while the person is still missing, it is not inserted again`, async () => {
289+
const { engine, store } = createEngine();
290+
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];
291+
292+
await loadWith(engine, seeds);
293+
expect(store.dkr_task).toHaveLength(1);
294+
deleteTask(store, 'Onboard');
295+
const second = await loadWith(engine, seeds);
296+
await loadWith(engine, seeds);
297+
298+
expect(store.dkr_task).toHaveLength(0);
299+
expect(second.success).toBe(true);
300+
expect(second.summary.totalSkipped).toBe(1);
301+
expect(second.summary.totalInserted).toBe(0);
302+
});
303+
304+
it(`${mode}: deleted, then the person signs up, it is still not inserted again`, async () => {
305+
const { engine, store } = createEngine();
306+
const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])];
307+
308+
await loadWith(engine, seeds);
309+
deleteTask(store, 'Onboard');
310+
signUp(store, 'Alice');
311+
const second = await loadWith(engine, seeds);
312+
await loadWith(engine, seeds);
313+
314+
expect(store.dkr_task).toHaveLength(0);
315+
expect(second.summary.totalSkipped).toBe(1);
316+
expect(second.summary.totalInserted).toBe(0);
317+
});
318+
}
319+
320+
it('the row is recorded under the id it landed with, derived from its key as authored', async () => {
321+
const { engine, store } = createEngine();
322+
await loadWith(engine, [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])]);
323+
324+
expect(store.dkr_task).toHaveLength(1);
325+
expect(store.dkr_task[0].id).toMatch(/^seed_/);
326+
expect(store.sys_seed_landed_key).toEqual([
327+
expect.objectContaining({ object_name: 'dkr_task', seed_key: JSON.stringify([['id', store.dkr_task[0].id]]) }),
328+
]);
329+
});
330+
331+
it('CONTROL: a row whose key was complete at landing, deleted, stays deleted as before', async () => {
332+
const { engine, store } = createEngine();
333+
signUp(store, 'Alice');
334+
const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])];
335+
336+
await loadWith(engine, seeds);
337+
expect(store.dkr_task[0].id).toMatch(/^gen-/);
338+
deleteTask(store, 'Onboard');
339+
const second = await loadWith(engine, seeds);
340+
341+
expect(store.dkr_task).toHaveLength(0);
342+
expect(second.summary.totalSkipped).toBe(1);
343+
});
344+
345+
it('CONTROL: a deferred-key row never landed here still lands, beside one a person deleted', async () => {
346+
const { engine, store } = createEngine();
347+
await loadWith(engine, [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])]);
348+
deleteTask(store, 'Onboard');
349+
350+
// An upgrade adds a second record to the seed, its key reference empty too.
351+
const upgraded = [taskSeed('ignore', [
352+
{ name: 'Onboard', assignee: 'Alice' },
353+
{ name: 'Review', assignee: 'Alice' },
354+
])];
355+
const second = await loadWith(engine, upgraded);
356+
await loadWith(engine, upgraded);
357+
358+
expect(store.dkr_task.map((r) => r.name)).toEqual(['Review']);
359+
expect(second.summary.totalInserted).toBe(1);
360+
expect(second.summary.totalSkipped).toBe(1);
361+
});
362+
363+
it('CONTROL: a deliberate re-seed brings the deleted deferred-key row back', async () => {
364+
const { engine, store } = createEngine();
365+
const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])];
366+
367+
await loadWith(engine, seeds);
368+
deleteTask(store, 'Onboard');
369+
await loadWith(engine, seeds, 'reseed');
370+
371+
expect(store.dkr_task).toHaveLength(1);
372+
expect(store.dkr_task[0].name).toBe('Onboard');
373+
expect(store.dkr_task[0].assignee ?? null).toBeNull();
374+
});
375+
});

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

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2297,6 +2297,23 @@ export class SeedLoaderService implements ISeedLoaderService {
22972297
const authoredKeyValues = authoredKey === ''
22982298
? undefined
22992299
: new Map([...referenceKeyFields].map((field) => [field, record[field]] as const));
2300+
/**
2301+
* [#34856] The key the record of landed rows keeps this row under when a
2302+
* reference in its key is empty on the load that lands it: the id the
2303+
* row lands with ({@link seedDeferredKeyRowId} over the AUTHORED key),
2304+
* spelled as an `id` key. The key as stored cannot serve — it has an
2305+
* empty component then, and once the reference resolves it names an id
2306+
* the landing load never knew — so a person's delete of such a row was
2307+
* recorded under nothing and undone by the next load. This one is the
2308+
* same while the reference stays empty and after it resolves. Read off
2309+
* the record before any reference resolves; `''` exactly when
2310+
* `authoredKey` is.
2311+
*/
2312+
const deferredLandedKey = authoredKey === ''
2313+
? ''
2314+
: seedLandedKey(
2315+
{ id: seedDeferredKeyRowId(objectName, String(record[organizationColumn] ?? ''), authoredKey) }, 'id',
2316+
);
23002317
/** [#34800] Key fields whose reference this record defers to pass 2. */
23012318
const deferredKeyFields = new Set<string>();
23022319

@@ -2461,14 +2478,20 @@ export class SeedLoaderService implements ISeedLoaderService {
24612478
const isWithdrawnRow = (): boolean => {
24622479
if (!recordedKeys || !this.landedKeyLedger?.honour) return false;
24632480
const key = this.externalIdKey(record, externalId);
2464-
if (key === '' || existingRecords?.has(key)) return false;
2481+
if (key !== '' && existingRecords?.has(key)) return false;
24652482
// [#34800] Found by id: the row is there, under a key column still empty.
24662483
if (rowLandedWithEmptyKeyReference() !== undefined) return false;
2467-
return recordedKeys.has(landedKeyOf(record, i));
2484+
if (key !== '' && recordedKeys.has(landedKeyOf(record, i))) return true;
2485+
// [#34856] Landed while a reference in its key was empty: recorded
2486+
// under the id it landed with, whether the reference is still empty
2487+
// (the record keys `''`) or resolves now.
2488+
return deferredLandedKey !== '' && recordedKeys.has(deferredLandedKey);
24682489
};
24692490
let withdrawnRow = false;
24702491
let withdrawnAsked = recordedKeys === undefined;
24712492
const referencesResolvedBeforeRow = referencesResolved;
2493+
const referencesDeferredBeforeRow = referencesDeferred; // [#34856]
2494+
const deferredUpdatesBeforeRow = deferredUpdates.length; // [#34856]
24722495
for (const ref of recordRefs) {
24732496
// [#31021] Asked once, the moment the key is final: before the first
24742497
// reference that is not part of it.
@@ -2749,6 +2772,10 @@ export class SeedLoaderService implements ISeedLoaderService {
27492772
// Nothing of this row is written, and the references its key resolved
27502773
// on the way are not booked as this load's.
27512774
referencesResolved = referencesResolvedBeforeRow;
2775+
// [#34856] Nor the key references it deferred: pass 2 has no row to
2776+
// write them onto, and would report each as a reference it dropped.
2777+
referencesDeferred = referencesDeferredBeforeRow;
2778+
deferredUpdates.length = deferredUpdatesBeforeRow;
27522779
skipped++;
27532780
const ledger = this.landedKeyLedger!;
27542781
ledger.withdrawnRows.set(objectName, (ledger.withdrawnRows.get(objectName) ?? 0) + 1);
@@ -2908,6 +2935,8 @@ export class SeedLoaderService implements ISeedLoaderService {
29082935
if (recordedKeys) {
29092936
const landedKey = landedKeyOf(record, i);
29102937
if (landedKey !== '') landedKeyByRecordIndex.set(i, landedKey);
2938+
// [#34856] A key reference still empty: under the id it lands with.
2939+
else if (deferredKeyFields.size > 0 && deferredLandedKey !== '') landedKeyByRecordIndex.set(i, deferredLandedKey);
29112940
}
29122941

29132942
// Insert/upsert the record

0 commit comments

Comments
 (0)