diff --git a/.changeset/34800-seed-deferred-key-reference.md b/.changeset/34800-seed-deferred-key-reference.md new file mode 100644 index 00000000000..69f6fa79291 --- /dev/null +++ b/.changeset/34800-seed-deferred-key-reference.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +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 + +Clause-②: no +Metadata-protocol: none + +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. + +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. + +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. diff --git a/packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts new file mode 100644 index 00000000000..c80ba71f35d --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts @@ -0,0 +1,258 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { SeedLoaderService } from './seed-loader.js'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; + +/** + * [#34800] A dataset whose `externalId` includes a reference the first load + * must leave empty — the person it names has not signed up yet — holds ONE row + * across loads. + * + * The row lands with that key column NULL (the reference is deferred to pass 2 + * and misses there too). Matching existing rows by natural key cannot find it + * again: while the reference stays unresolvable the record keys empty, and + * once it resolves the record carries an id the stored row does not. Measured + * before the fix, three loads over one store: 1 → 2 → 3 rows, and 1 → 2 → 2 + * when the person appears between loads (the copy that finally carried the + * person sat beside the first one, still NULL). The loader now lands such a + * row with an id derived from the key as authored, and a replay whose natural + * key misses finds the row by that id — and fills the reference onto it once + * it resolves. + * + * Each load runs a fresh loader over the same store, as a restart does: the + * held person references a loader keeps in memory do not survive it. + * + * The engine double filters `where` by equality (an absent column matches + * `null`), keeps an id the write supplies and refuses a second row under one + * id, as a primary key does, and answers the compare-and-set update form. + */ + +const ORG = 'org_dkr34800test'; + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +function rowMatches(row: Record, where: Record = {}): boolean { + return Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`fake driver: unsupported combinator ${k}`); + if (v !== null && typeof v === 'object') throw new Error(`fake driver: unsupported operator on ${k}`); + return (row[k] ?? null) === (v ?? null); + }); +} + +function createEngine(): { engine: IDataEngine; store: Record } { + const store: Record = {}; + let idCounter = 0; + const engine = { + find: vi.fn(async (objectName: string, query?: any) => { + let rows = (store[objectName] ?? []).filter((r) => rowMatches(r, query?.where)); + if (typeof query?.limit === 'number') rows = rows.slice(0, query.limit); + return rows.map((r) => ({ ...r })); + }), + findOne: vi.fn(async (objectName: string, query?: any) => { + assertEngineFindOnePredicate(objectName, query); + const rows = await (engine.find as any)(objectName, { ...query, limit: 1 }); + return rows[0] ?? null; + }), + insert: vi.fn(async (objectName: string, data: any) => { + const rows = (store[objectName] ??= []); + const land = (d: any) => { + const id = d.id ?? `gen-${++idCounter}`; + if (rows.some((r) => r.id === id)) throw new Error(`fake driver: duplicate primary key '${id}'`); + const row = { ...d, id }; + rows.push(row); + return { ...row }; + }; + return Array.isArray(data) ? data.map(land) : land(data); + }), + update: vi.fn(async (objectName: string, data: any, options?: any) => { + assertEngineUpdateDispatch(data, options); + const rows = store[objectName] ?? []; + if (options?.where) { + let n = 0; + for (const row of rows) { + if (!rowMatches(row, options.where)) continue; + Object.assign(row, data); + n += 1; + } + return n; + } + const row = rows.find((r) => r.id === data.id); + if (!row) return null; + Object.assign(row, data); + return { ...row }; + }), + delete: vi.fn(async (_objectName: string, options?: any) => { + assertEngineDeleteDispatch(options); + return { deleted: 1 }; + }), + count: vi.fn(async (objectName: string) => (store[objectName] ?? []).length), + aggregate: vi.fn(async () => []), + } as unknown as IDataEngine; + return { engine, store }; +} + +const OBJECTS: Record = { + dkr_person: { name: 'dkr_person', fields: { name: { type: 'text' } } }, + dkr_task: { + name: 'dkr_task', + fields: { + name: { type: 'text' }, + assignee: { type: 'lookup', reference: 'dkr_person' }, + notes: { type: 'text' }, + }, + }, + dkr_tag: { name: 'dkr_tag', fields: { name: { type: 'text' }, kind: { type: 'text' }, notes: { type: 'text' } } }, + sys_seed_landed_key: { + name: 'sys_seed_landed_key', + fields: { object_name: { type: 'text' }, seed_key: { type: 'textarea' } }, + }, +}; + +function createMetadata(): IMetadataService { + return { + getObject: vi.fn(async (name: string) => OBJECTS[name]), + listObjects: vi.fn(async () => Object.values(OBJECTS)), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => OBJECTS[name]), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; +} + +const CONFIG = { + dryRun: false, + haltOnError: false, + multiPass: true, + defaultMode: 'ignore', + batchSize: 1000, + transaction: false, + organizationId: ORG, +} as any; + +function taskSeed(mode: 'ignore' | 'upsert', records: Array>) { + return { object: 'dkr_task', externalId: ['name', 'assignee'], mode, env: ['prod', 'dev', 'test'], records }; +} + +/** One load by a fresh loader — a restart. */ +async function load(engine: IDataEngine, seeds: any[], landedKeys?: 'honour') { + return new SeedLoaderService(engine, createMetadata(), createLogger() as never, landedKeys ? { landedKeys } : {}) + .load({ seeds, config: CONFIG }); +} + +function signUp(store: Record, name: string): string { + const id = `person-${name.toLowerCase()}`; + (store.dkr_person ??= []).push({ id, name, organization_id: ORG }); + return id; +} + +describe('seed: a key reference empty on the first load holds one row across loads (#34800)', () => { + for (const mode of ['ignore', 'upsert'] as const) { + it(`${mode}: three loads while the person never appears leave one row`, async () => { + const { engine, store } = createEngine(); + const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])]; + + const counts: number[] = []; + for (let boot = 0; boot < 3; boot++) { + await load(engine, seeds); + counts.push(store.dkr_task.length); + } + + expect(counts).toEqual([1, 1, 1]); + expect(store.dkr_task[0].assignee ?? null).toBeNull(); + }); + + it(`${mode}: the person appearing between loads fills the reference onto the row first landed`, async () => { + const { engine, store } = createEngine(); + const seeds = [taskSeed(mode, [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }])]; + + await load(engine, seeds); + const firstLanded = store.dkr_task[0].id; + const alice = signUp(store, 'Alice'); + const second = await load(engine, seeds); + await load(engine, seeds); + + expect(second.success).toBe(true); + expect(store.dkr_task).toHaveLength(1); + expect(store.dkr_task[0]).toMatchObject({ id: firstLanded, name: 'Onboard', assignee: alice }); + }); + } + + it('with the landed-key record kept, the row is found too and is not reported as removed', async () => { + const { engine, store } = createEngine(); + const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])]; + + await load(engine, seeds, 'honour'); + const alice = signUp(store, 'Alice'); + const second = await load(engine, seeds, 'honour'); + await load(engine, seeds, 'honour'); + + expect(second.summary.totalSkipped).toBe(1); + expect(store.dkr_task).toHaveLength(1); + expect(store.dkr_task[0].assignee).toBe(alice); + }); + + it('two records that differ only in the reference stay two rows, each filled with its own person', async () => { + const { engine, store } = createEngine(); + const seeds = [taskSeed('ignore', [ + { name: 'Onboard', assignee: 'Alice' }, + { name: 'Onboard', assignee: 'Bob' }, + ])]; + + await load(engine, seeds); + await load(engine, seeds); + expect(store.dkr_task).toHaveLength(2); + const [alice, bob] = [signUp(store, 'Alice'), signUp(store, 'Bob')]; + await load(engine, seeds); + await load(engine, seeds); + + expect(store.dkr_task).toHaveLength(2); + expect(store.dkr_task.map((r) => r.assignee).sort()).toEqual([alice, bob].sort()); + }); + + it('a row a person created with the reference empty is never taken for the seed row', async () => { + const { engine, store } = createEngine(); + store.dkr_task = [{ id: 'customer-row', name: 'Onboard', assignee: null, notes: 'mine', organization_id: ORG }]; + const seeds = [taskSeed('upsert', [{ name: 'Onboard', assignee: 'Alice', notes: 'seeded' }])]; + + await load(engine, seeds); + const alice = signUp(store, 'Alice'); + await load(engine, seeds); + + expect(store.dkr_task).toHaveLength(2); + expect(store.dkr_task.find((r) => r.id === 'customer-row')).toEqual( + { id: 'customer-row', name: 'Onboard', assignee: null, notes: 'mine', organization_id: ORG }, + ); + expect(store.dkr_task.find((r) => r.id !== 'customer-row')).toMatchObject({ assignee: alice, notes: 'seeded' }); + }); + + it('CONTROL: a composite key whose reference resolves on the first load is matched as before, engine-minted id', async () => { + const { engine, store } = createEngine(); + const alice = signUp(store, 'Alice'); + const seeds = [taskSeed('ignore', [{ name: 'Onboard', assignee: 'Alice' }])]; + + for (let boot = 0; boot < 3; boot++) await load(engine, seeds); + + expect(store.dkr_task).toHaveLength(1); + expect(store.dkr_task[0]).toMatchObject({ assignee: alice }); + expect(store.dkr_task[0].id).toMatch(/^gen-/); + }); + + it('CONTROL: a composite key over plain fields is matched as before, engine-minted id', async () => { + const { engine, store } = createEngine(); + const seeds = [{ + object: 'dkr_tag', externalId: ['name', 'kind'], mode: 'upsert', env: ['prod', 'dev', 'test'], + records: [{ name: 'Urgent', kind: 'priority' }, { name: 'Urgent', kind: 'label' }], + }]; + + for (let boot = 0; boot < 3; boot++) await load(engine, seeds); + + expect(store.dkr_tag).toHaveLength(2); + expect(store.dkr_tag.every((r) => /^gen-/.test(r.id))).toBe(true); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 95729c29a45..195e71f0f09 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -48,6 +48,7 @@ import { validationFailureDetails } from '@objectstack/types'; // `SysMetadataRepository` (#4867) and `cascadeDeleteRelations` (#8895) ask, so // a driver quirk is taught to the platform once instead of per seam. import { isMissingTableError } from '@objectstack/metadata/errors'; +import { createHash } from 'node:crypto'; // [#25779] `seedFile(path)` values: stored, kept across replays, and owned by // the row that holds them; an id-shaped file value that names no file refused. import { SeedDatasetFiles, type SeedFileClaims } from './seed-files.js'; @@ -424,6 +425,32 @@ function seedLandedKey(record: Record, externalId: string | str return JSON.stringify(pairs); } +/** + * [#34800] The id a seed row lands with when a reference in its `externalId` + * is still empty on the load that inserts it — a person not signed up yet, + * deferred to pass 2 and held past it. + * + * Such a row is stored with that key column NULL, so the natural key the load + * matches existing rows by can never find it again: while the reference stays + * unresolvable the record keys empty, and once it resolves the record carries + * an id the stored row does not. Each load then inserted another copy. The + * row's identity has to come from what does not move between loads: the key + * as AUTHORED (`authoredKey`, {@link seedLandedKey} over the record before + * its references resolve — the natural key the author wrote, never the id it + * resolves to), in the object and organization the row belongs to. + * + * DERIVED, never minted, for {@link perOrganizationSeedRowId}'s reason: a + * replay finds its row again by recomputing the id. A digest rather than the + * key itself, because the key is any text the author wrote and an id is not. + * A row a person created never carries one, so a lookup by this id can only + * find the seed's own row, and two records whose keys differ only in that + * reference derive two ids. + */ +function seedDeferredKeyRowId(objectName: string, rowOrganization: string, authoredKey: string): string { + const digest = createHash('sha256').update(JSON.stringify([objectName, rowOrganization, authoredKey])).digest('hex'); + return `seed_${digest.slice(0, 32)}`; +} + /** * [#31021] What a load does with the record of landed seed rows — see * {@link SeedLoaderServiceOptions.landedKeys}. Set once per load. @@ -1611,8 +1638,19 @@ export class SeedLoaderService implements ISeedLoaderService { // that share the same natural key — e.g. `name: 'Acme Corp'`). let existingRecords: Map | undefined; const keyedMode = mode === 'upsert' || mode === 'update' || mode === 'ignore'; + // [#34800] The externalId fields that are references. A row can land with + // one of them still empty, and a replay finds that row by its id (see + // `seedDeferredKeyRowId`), so the same read also indexes every row by id. + const referenceKeyFields: ReadonlySet = new Set( + (refMap.get(objectName) ?? []) + .map((ref) => ref.field) + .filter((field) => (Array.isArray(externalId) ? externalId : [externalId]).includes(field)), + ); + const existingRowsById = referenceKeyFields.size > 0 ? new Map() : undefined; + /** [#34800] Ids of rows a record of this dataset found by id (or will insert with), so no two claim one. */ + const claimedKeyRowIds = new Set(); if (keyedMode && !config.dryRun) { - existingRecords = await this.loadExistingRecords(objectName, externalId, config.organizationId); + existingRecords = await this.loadExistingRecords(objectName, externalId, config.organizationId, existingRowsById); } // [#28952] A keyed dataset whose every record keys EMPTY — its // `externalId` names a field no record carries, most often a field the @@ -2103,6 +2141,17 @@ export class SeedLoaderService implements ISeedLoaderService { authoredIdByRecordIndex.set(i, authoredId); } + // [#34800] The key as AUTHORED, before any of its references resolves: + // the identity of a row that lands while one of them is still empty. + // `''` when the dataset keys on no reference or the record leaves a key + // field blank as written; such a record matches by natural key alone. + const authoredKey = existingRowsById ? seedLandedKey(record, externalId) : ''; + const authoredKeyValues = authoredKey === '' + ? undefined + : new Map([...referenceKeyFields].map((field) => [field, record[field]] as const)); + /** [#34800] Key fields whose reference this record defers to pass 2. */ + const deferredKeyFields = new Set(); + // Resolve references let unresolvedRefError = false; @@ -2169,6 +2218,54 @@ export class SeedLoaderService implements ISeedLoaderService { }); } + /** + * [#34800] The row this record landed on while a reference in its key + * was still empty, found by id when its natural key cannot find it: + * the row's own key column is NULL, so the key misses whether the + * reference is still deferred (the record keys `''`) or resolves now + * (the record carries an id the row does not). An exact natural-key + * match always wins. The id is the record's own `id` when it carries + * one, else {@link seedDeferredKeyRowId}; a row found by it is taken + * only when its other key columns still equal the record's and each + * reference column it holds is empty or the very value the record + * resolved, and only by one record of the load. A row a person created + * carries neither id, so it is never taken. + * + * Asked once the key is final — after the key's references resolved — + * and answered once per record. + */ + let deferredKeyRow: { row: any } | null | undefined; + const rowLandedWithEmptyKeyReference = (): any | undefined => { + if (deferredKeyRow !== undefined) return deferredKeyRow?.row; + deferredKeyRow = null; + if (!existingRowsById || authoredKey === '') return undefined; + const key = this.externalIdKey(record, externalId); + if (key !== '' && existingRecords?.has(key)) return undefined; + const ownId = record['id']; + const rowId = typeof ownId === 'string' && ownId !== '' + ? ownId + : seedDeferredKeyRowId(objectName, String(record[organizationColumn] ?? ''), authoredKey); + const row = existingRowsById.get(rowId); + if (row === undefined || claimedKeyRowIds.has(rowId)) return undefined; + for (const field of keyFields) { + if (deferredKeyFields.has(field)) continue; + if (referenceKeyFields.has(field) && isMissing(row[field])) continue; + if (String(row[field] ?? '') !== String(record[field] ?? '')) return undefined; + } + claimedKeyRowIds.add(rowId); + deferredKeyRow = { row }; + return row; + }; + /** + * [#34800] The existing rows this record's write decision reads: the + * dataset's, or — when the record landed on a row its natural key + * cannot find — that one row, under the key the record has. + */ + const existingRowsFor = (): Map | undefined => { + const row = rowLandedWithEmptyKeyReference(); + return row === undefined ? existingRecords : new Map([[this.externalIdKey(record, externalId), row]]); + }; + /** * [#25761] Is this row one the load MATCHED — an existing row this * dataset writes over? The create-only policy is the only thing that @@ -2179,7 +2276,7 @@ export class SeedLoaderService implements ISeedLoaderService { * nothing, so every row they see is one they create. */ const matchesExistingRow = (): boolean => - existingRecords?.has(this.externalIdKey(record, externalId)) === true; + existingRowsFor()?.has(this.externalIdKey(record, externalId)) === true; const allRecordRefs: Array< Pick & { multiple?: boolean } @@ -2217,6 +2314,8 @@ export class SeedLoaderService implements ISeedLoaderService { if (!recordedKeys || !this.landedKeyLedger?.honour) return false; const key = this.externalIdKey(record, externalId); if (key === '' || existingRecords?.has(key)) return false; + // [#34800] Found by id: the row is there, under a key column still empty. + if (rowLandedWithEmptyKeyReference() !== undefined) return false; return recordedKeys.has(landedKeyOf(record, i)); }; let withdrawnRow = false; @@ -2404,6 +2503,7 @@ export class SeedLoaderService implements ISeedLoaderService { // array): a partially-written array is a corrupt association, and // pass 2 re-resolves every element from the same authored keys. delete record[ref.field]; + if (keyFields.has(ref.field)) deferredKeyFields.add(ref.field); // [#34800] deferredUpdates.push({ objectName, recordExternalId: this.externalIdKey(record, externalId), @@ -2524,12 +2624,54 @@ export class SeedLoaderService implements ISeedLoaderService { for (const column of createOnlyColumns) delete record[column]; } + // [#34800] A row that lands while a reference in its key is still empty + // takes the id derived from its authored key, so the next load finds it + // by that id (`rowLandedWithEmptyKeyReference`) instead of inserting + // another. Only for the modes that insert a keyed row they do not find, + // only when the record names no id of its own, and never an id a row of + // this organization or another record of this load already has. + if (!config.dryRun && (mode === 'upsert' || mode === 'ignore') && deferredKeyFields.size > 0 + && authoredKey !== '' && record['id'] === undefined && rowLandedWithEmptyKeyReference() === undefined) { + const rowId = seedDeferredKeyRowId(objectName, String(record[organizationColumn] ?? ''), authoredKey); + if (!existingRowsById!.has(rowId) && !claimedKeyRowIds.has(rowId)) { + claimedKeyRowIds.add(rowId); + record['id'] = rowId; + } + } + // [#34800] `ignore` writes nothing over a row it found, so a key + // reference that was empty when the row landed and resolves now is + // back-filled by pass 2 onto that row, that column only — the way a held + // person reference is written later onto the row the seed landed on. + const landedKeyRow = mode === 'ignore' && config.multiPass && !config.dryRun + ? rowLandedWithEmptyKeyReference() + : undefined; + if (landedKeyRow !== undefined) { + for (const ref of allRecordRefs) { + if (!referenceKeyFields.has(ref.field) || deferredKeyFields.has(ref.field) || ref.multiple) continue; + if (!isMissing(landedKeyRow[ref.field]) || isMissing(record[ref.field])) continue; + deferredUpdates.push({ + objectName, + recordExternalId: this.externalIdKey(record, externalId), + externalIdLabel: this.externalIdLabel(externalId), + field: ref.field, + targetObject: ref.targetObject, + targetField: ref.targetField, + attemptedValue: authoredKeyValues!.get(ref.field), + multiple: false, + recordIndex: i, + }); + // Booked as pass 2's, which counts it resolved once it is written. + if (record[ref.field] !== authoredKeyValues!.get(ref.field)) referencesResolved--; + referencesDeferred++; + } + } + // [#25779] Seed files, once the row's references and organization are // final: each `seedFile(path)` becomes the id of a file stored for (or // kept by) this row, and a file value that cannot be honoured refuses // the row before anything of it is written. if (datasetFiles) { - const matched = existingRecords?.get(this.externalIdKey(record, externalId)); + const matched = existingRowsFor()?.get(this.externalIdKey(record, externalId)); const organizationOfRow = typeof record[organizationColumn] === 'string' && record[organizationColumn] !== '' ? (record[organizationColumn] as string) @@ -2590,7 +2732,7 @@ export class SeedLoaderService implements ISeedLoaderService { // verbatim — this line only moves WHEN the author learns, from after the // engine's rejection to before the write that provokes it. if (!config.dryRun && requiredDeferrals.length > 0) { - if (this.decideWriteAction(record, mode, externalId, existingRecords, comparands).action === 'insert') { + if (this.decideWriteAction(record, mode, externalId, existingRowsFor(), comparands).action === 'insert') { for (const deferral of requiredDeferrals) { if (earlySignalledFields.has(deferral.field)) continue; earlySignalledFields.add(deferral.field); @@ -2629,7 +2771,7 @@ export class SeedLoaderService implements ISeedLoaderService { // against an earlier one via `insertedRecords` — see `hasSelfRef`. try { const result = await this.writeRecord( - objectName, record, mode, externalId, existingRecords, comparands, record[organizationColumn], + objectName, record, mode, externalId, existingRowsFor(), comparands, record[organizationColumn], ); if (result.action === 'inserted') written.inserted++; @@ -2653,7 +2795,7 @@ export class SeedLoaderService implements ISeedLoaderService { // already exist (rejected update), so keep its natural-key // mapping alive for downstream reference resolution. const externalIdValue = this.externalIdKey(record, externalId); - const existingId = this.extractId(existingRecords?.get(externalIdValue)); + const existingId = this.extractId(existingRowsFor()?.get(externalIdValue)); if (existingId) noteLanded(i, existingId); // [commit 9a884c6e4] if (externalIdValue && existingId) { insertedRecords.get(objectName)!.set(externalIdValue, existingId); @@ -2672,7 +2814,7 @@ export class SeedLoaderService implements ISeedLoaderService { ); } } else { - const decision = this.decideWriteAction(record, mode, externalId, existingRecords, comparands); + const decision = this.decideWriteAction(record, mode, externalId, existingRowsFor(), comparands); const externalIdValue = this.externalIdKey(record, externalId); if (decision.action === 'skip') { @@ -4740,6 +4882,8 @@ export class SeedLoaderService implements ISeedLoaderService { objectName: string, externalId: string | string[], organizationId?: string, + /** [#34800] When given, filled with every row read, by id — keyed or not. */ + byId?: Map, ): Promise> { const map = new Map(); try { @@ -4770,6 +4914,8 @@ export class SeedLoaderService implements ISeedLoaderService { if (key) { map.set(key, record); } + const id = byId ? this.extractId(record) : undefined; + if (id) byId!.set(id, record); } } catch (error) { // [#8896] Discriminate by error TYPE. This map is not a convenience — diff --git a/packages/runtime/src/seed-deferred-key-reference-real-driver.integration.test.ts b/packages/runtime/src/seed-deferred-key-reference-real-driver.integration.test.ts new file mode 100644 index 00000000000..edd0c26d3d5 --- /dev/null +++ b/packages/runtime/src/seed-deferred-key-reference-real-driver.integration.test.ts @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34800] A seed dataset whose composite `externalId` includes a reference the + * first load must leave empty — the person it names has not signed up yet — + * holds ONE row across boots, and the reference lands on that row once the + * person exists. + * + * ## Why a real engine and a real driver over one file + * + * The defect is about what the database STORES: the row lands with the key's + * reference column NULL, and every later boot compared its key against that + * stored row. So this file runs the real `SeedLoaderService` behind a real + * `ObjectQL`, over a real `SqlDriver` on one better-sqlite3 FILE, and each boot + * is a new engine, driver and loader over it — a restart, which is also what + * drops the person references a loader holds in memory. Measured on main + * before the fix with exactly these boots: 1 → 2 → 3 rows while the person + * never appears, 1 → 2 → 2 when the person appears after the first boot, on + * both paths below. The loader-level cases, controls included, live in + * `packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts`. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL } from '@objectstack/objectql'; +import { SeedLoaderService } from '@objectstack/metadata-protocol'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysSeedLandedKey } from '@objectstack/platform-objects'; +import { SeedLoaderRequestSchema, type EngineQueryOptions } from '@objectstack/spec/data'; + +const ORG = 'org_dkr34800realdrv'; + +const PERSON = { name: 'dkr_person', label: 'Person', fields: { name: { type: 'text' } } }; +const TASK = { + name: 'dkr_task', + label: 'Task', + fields: { + name: { type: 'text' }, + assignee: { type: 'lookup', reference: 'dkr_person' }, + notes: { type: 'text' }, + }, +}; + +const cleanups: Array<() => unknown> = []; +afterEach(async () => { + while (cleanups.length) { + try { await cleanups.pop()!(); } catch { /* already closed */ } + } +}); + +function metadataFor(objects: any[]) { + const byName = new Map(objects.map((o) => [o.name, o])); + return { + getObject: vi.fn(async (name: string) => byName.get(name)), + listObjects: vi.fn(async () => objects), + getObjects: vi.fn(async () => objects), + get: vi.fn(async (_t: string, n: string) => byName.get(n)), + list: vi.fn(async () => []), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + register: vi.fn(async () => {}), + unregister: vi.fn(async () => {}), + } as any; +} + +const SYSTEM: EngineQueryOptions = { context: { isSystem: true } }; + +/** + * Three boots over one database file. Before boot `signUpBefore` (when given) + * the person the seed names is created, as a sign-up between restarts would. + */ +async function bootThreeTimes(opts: { mode: 'ignore' | 'upsert'; ledger: boolean; signUpBefore?: number }) { + const dir = mkdtempSync(join(tmpdir(), 'os-34800-')); + cleanups.push(() => rmSync(dir, { recursive: true, force: true })); + const objects: any[] = opts.ledger ? [PERSON, TASK, SysSeedLandedKey] : [PERSON, TASK]; + const seeds = [{ + object: 'dkr_task', + mode: opts.mode, + externalId: ['name', 'assignee'], + records: [{ name: 'Onboard', assignee: 'Alice', notes: 'first week' }], + }]; + const counts: number[] = []; + let rows: any[] = []; + for (let boot = 1; boot <= 3; boot++) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of objects) engine.registry.registerObject(o, 'com.objectstack.test.34800'); + await driver.initObjects(objects.map((o) => engine.registry.getObject(o.name) ?? o) as any); + try { + if (boot === opts.signUpBefore) { + await engine.insert('dkr_person', { name: 'Alice', organization_id: ORG }, SYSTEM as any); + } + const loader = new SeedLoaderService( + engine as never, + metadataFor(objects), + { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as never, + opts.ledger ? { landedKeys: 'honour' } : {}, + ); + await loader.load(SeedLoaderRequestSchema.parse({ seeds, config: { multiPass: true, organizationId: ORG } }) as never); + rows = (await engine.find('dkr_task', SYSTEM)) as any[]; + counts.push(rows.length); + if (boot === 3) { + const people = (await engine.find('dkr_person', SYSTEM)) as any[]; + return { counts, rows, aliceId: people[0]?.id as string | undefined }; + } + } finally { + await engine.destroy(); + await driver.disconnect(); + } + } + throw new Error('unreachable'); +} + +describe('seed: a composite key over a reference empty on the first boot (sqlite-file, #34800)', () => { + it('per-organization replay with the landed-key record: the person never appears, one row across three boots', async () => { + const { counts, rows } = await bootThreeTimes({ mode: 'ignore', ledger: true }); + + expect(counts).toEqual([1, 1, 1]); + expect(rows[0]).toMatchObject({ name: 'Onboard', assignee: null, organization_id: ORG }); + }); + + it('no landed-key record, upsert: the person appears after the first boot, the reference lands on the row first landed', async () => { + const { counts, rows, aliceId } = await bootThreeTimes({ mode: 'upsert', ledger: false, signUpBefore: 2 }); + + expect(counts).toEqual([1, 1, 1]); + expect(aliceId).toBeTruthy(); + expect(rows[0]).toMatchObject({ name: 'Onboard', assignee: aliceId }); + }); +}); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index cd593c9c3ea..5c74f4854e6 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2446,6 +2446,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-deferred-key-reference.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts", "verb": "delete",