From 0bf59ffa23271f9f4a65f5e6276cd9bf2f357acc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:36:17 +0000 Subject: [PATCH 1/6] fix(metadata-protocol): a seed resolves a lookup an object extension adds like an authored one The seed loader now reads each object as the engine serves it (object extensions folded in) and the metadata service's copy only when the engine has no schema, so an extension lookup joins the dependency graph and its natural key resolves to the target's id. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- .changeset/35254-seed-extension-lookup.md | 21 ++ ...seed-loader-engine-schema-fallback.test.ts | 18 +- ...seed-loader-extension-lookup-35254.test.ts | 251 ++++++++++++++++++ .../src/seed-loader-summary-stale.test.ts | 13 +- packages/metadata-protocol/src/seed-loader.ts | 76 +++--- 5 files changed, 331 insertions(+), 48 deletions(-) create mode 100644 .changeset/35254-seed-extension-lookup.md create mode 100644 packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts diff --git a/.changeset/35254-seed-extension-lookup.md b/.changeset/35254-seed-extension-lookup.md new file mode 100644 index 00000000000..be2f8fbb59d --- /dev/null +++ b/.changeset/35254-seed-extension-lookup.md @@ -0,0 +1,21 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a seed resolves a lookup that another package adds through `objectExtensions` to the target's id + +Clause-②: no +Metadata-protocol: none + +A package can add a lookup to another package's object through `objectExtensions`. A seed that set that lookup by the target's natural key (`externalId`) used to store the raw key in the foreign-key column on a boot that loads a compiled artifact (`os dev`, `os serve`, the cloud runtime). The record then linked to nothing, and the console showed "Restricted record". The same seed resolved correctly under the in-process test harness. + +The cause was the seed loader's object read. It took the metadata service's copy of the object, which on an artifact boot is the object as its own package wrote it, without the fields an extension adds. Now the loader reads the object as the engine serves it, with its extensions included. It falls back to the metadata service's copy only when the engine has no schema for the object. So a lookup an extension adds is treated exactly like one the owner wrote, in every mode (`upsert`, `ignore`, `update`): + +- it adds a dependency, so the target dataset loads first; +- its natural key is resolved to the target's id; +- it waits for the second pass when the target loads later in the same load; +- an unknown key is refused with the same error. + +The same read now drives the loader's other per-field decisions for such a field: the required-on-insert check, the tenant column, the replay compare and the undeclared-column warning. + +Rows an earlier load stored with the raw key are not rewritten. Run the seed again (in `update` or `upsert` mode) to store the target's id in place of the key. diff --git a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts index 6aa2d2247f6..9cedd0a6f01 100644 --- a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts +++ b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts @@ -207,7 +207,7 @@ describe('seed reference graph — engine schema fallback (marketplace objects)' expect(result.summary.totalReferencesResolved).toBeGreaterThanOrEqual(4); }); - it('prefers the metadata service definition when it exists (the engine is probed only for roll-ups)', async () => { + it('falls back to the metadata service definition when the engine has no schema for the object', async () => { const { engine, store } = createFaithfulEngine({}); const metadata = createEmptyMetadata(); (metadata.getObject as any).mockImplementation(async (name: string) => ENGINE_SCHEMAS[name]); @@ -222,16 +222,16 @@ describe('seed reference graph — engine schema fallback (marketplace objects)' expect(store.crm_contact.find((r) => r.email === 'john.smith@acme.example.com')!.crm_account).toBe(acmeId); // The engine here registers no schema at all (`createFaithfulEngine({})`), // so the references above resolved from the metadata service's definition. - // The engine is still asked once per seeded object, for the roll-up strip - // alone (#35655): the metadata copy carries no object extension, so the - // strip also reads the engine's merged schema. (The other engine question - // is the ADR-0131 D9 registration read for `sys_organization`, which this + // [#35254] The engine is asked FIRST for every seeded object: its schema + // is the object as served, object extensions folded in, and the metadata + // copy is read only when it has none. (The other engine question is the + // ADR-0131 D9 registration read for `sys_organization`, which this // metadata double does not know: does the composition register an // organization object at all? It answers from the same resolver.) - const probed = (engine as any).getSchema.mock.calls.map((c: unknown[]) => c[0]); - expect(probed.filter((name: string) => name !== 'sys_organization').sort()).toEqual( - ['crm_account', 'crm_contact', 'crm_opportunity'], - ); + const probed = new Set((engine as any).getSchema.mock.calls.map((c: unknown[]) => c[0] as string)); + probed.delete('sys_organization'); + expect([...probed].sort()).toEqual(['crm_account', 'crm_contact', 'crm_opportunity']); + for (const name of probed) expect(metadata.getObject).toHaveBeenCalledWith(name); }); it('survives an engine without getSchema (contract-minimal engines keep the old behavior)', async () => { diff --git a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts new file mode 100644 index 00000000000..55cc39e4a7f --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts @@ -0,0 +1,251 @@ +// 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'; + +/** + * [#35254] A lookup that one package adds to another package's object through + * `objectExtensions` (ADR-0130 D5) resolves in a seed exactly like a lookup + * the owner authored: it joins the dependency graph, its natural key becomes + * the target's id, it is deferred to pass 2 when the target loads later, and + * an unknown key is refused the same way. + * + * The shape this file reproduces is the boot that ingests a compiled artifact + * (`os dev`, `os serve`, the cloud runtime). There the metadata service holds + * each object AS ITS PACKAGE AUTHORED IT, and the extension's fields exist only + * in the engine registry's fold. The loader used to prefer the metadata copy + * whenever it had `fields`, so the extension lookup was no reference at all: + * no `ext_order → ext_quote` edge, and the quote's name written verbatim into + * the foreign-key column. Measured on unfixed `origin/main` a5a5312ff4 with + * this harness: `quote_ref = 'Q-ACME'`, `insertOrder` with `ext_order` first. + * + * The metadata double serves the authored `ext_order` (no `quote_ref`); the + * engine double's `getSchema` serves the folded one (with it), as the ObjectQL + * registry does after `registerApp` applies the extension. Every case keeps a + * CONTROL beside it: the same seed through `account_ref`, a lookup the owner + * authored on the same object. + */ + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** The faithful engine of seed-loader-engine-schema-fallback.test.ts (where-filtering find, the + * producer's dispatch predicates on findOne / update / delete), plus a store a case can pre-fill. */ +function createFaithfulEngine(schemas: Record) { + const store: Record = {}; + let idCounter = 0; + + const engine = { + find: vi.fn(async (objectName: string, query?: any) => { + let records = store[objectName] || []; + if (query?.where) { + records = records.filter((r) => + Object.entries(query.where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), + ); + } + if (typeof query?.limit === 'number') { + records = records.slice(0, query.limit); + } + return records; + }), + 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) => { + if (!store[objectName]) store[objectName] = []; + if (Array.isArray(data)) { + const records = data.map((d) => ({ id: `gen-${++idCounter}`, ...d })); + store[objectName].push(...records); + return records; + } + const record = { id: `gen-${++idCounter}`, ...data }; + store[objectName].push(record); + return record; + }), + update: vi.fn(async (objectName: string, data: any) => { + assertEngineUpdateDispatch(data, undefined); + const records = store[objectName] || []; + const idx = records.findIndex((r) => r.id === data.id); + if (idx >= 0) { + records[idx] = { ...records[idx], ...data }; + return records[idx]; + } + return data; + }), + 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 () => []), + getSchema: vi.fn((objectName: string) => schemas[objectName]), + } as unknown as IDataEngine & { getSchema: ReturnType }; + + return { engine, store }; +} + +/** The owner package's objects, as it authored them — what the metadata service holds on an artifact boot. */ +function authoredObjects(quoteBacklink: boolean): Record { + return { + ext_account: { name: 'ext_account', fields: { name: { type: 'text', required: true } } }, + ext_order: { + name: 'ext_order', + fields: { + name: { type: 'text', required: true }, + account_ref: { type: 'lookup', reference: 'ext_account' }, + }, + }, + ext_quote: { + name: 'ext_quote', + fields: { + name: { type: 'text', required: true }, + ...(quoteBacklink ? { order_ref: { type: 'lookup', reference: 'ext_order' } } : {}), + }, + }, + }; +} + +/** The same objects as the engine's registry serves them: `ext_order` with the extension's lookup folded in. */ +function servedObjects(quoteBacklink: boolean): Record { + const authored = authoredObjects(quoteBacklink); + return { + ...authored, + ext_order: { + ...authored.ext_order, + fields: { ...authored.ext_order.fields, quote_ref: { type: 'lookup', reference: 'ext_quote' } }, + }, + }; +} + +function createMetadata(objects: Record): 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: 'upsert', + batchSize: 1000, + transaction: false, +} as any; + +const ENV = ['prod', 'dev', 'test']; + +function loaderFor(quoteBacklink = false) { + const { engine, store } = createFaithfulEngine(servedObjects(quoteBacklink)); + const logger = createLogger(); + const loader = new SeedLoaderService(engine, createMetadata(authoredObjects(quoteBacklink)), logger); + return { loader, store, logger, engine }; +} + +/** The order dataset first, then the targets — the order a later package's seeds arrive in. */ +function seeds(mode: string, order: Record) { + return [ + { object: 'ext_order', externalId: 'name', mode, env: ENV, records: [{ name: 'O-1', ...order }] }, + { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME' }] }, + { object: 'ext_account', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Acme' }] }, + ] as any[]; +} + +describe('[#35254] a seed resolves a lookup an object extension adds like an authored one', () => { + for (const mode of ['upsert', 'ignore'] as const) { + it(`${mode} (inserting): the extension lookup stores the quote's id, and the graph loads the quote first`, async () => { + const { loader, store } = loaderFor(); + const result = await loader.load({ seeds: seeds(mode, { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); + + expect(result.success).toBe(true); + expect(result.summary.totalErrored).toBe(0); + const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; + const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; + expect(store.ext_order).toHaveLength(1); + expect(store.ext_order[0].quote_ref).toBe(quoteId); + // CONTROL: the authored lookup on the same row. + expect(store.ext_order[0].account_ref).toBe(accountId); + + const order = result.dependencyGraph.insertOrder; + expect(order.indexOf('ext_quote')).toBeLessThan(order.indexOf('ext_order')); + expect(order.indexOf('ext_account')).toBeLessThan(order.indexOf('ext_order')); + const node = result.dependencyGraph.nodes.find((n) => n.object === 'ext_order')!; + expect([...node.dependsOn].sort()).toEqual(['ext_account', 'ext_quote']); + expect(node.references.map((r) => `${r.field}->${r.targetObject}`).sort()).toEqual([ + 'account_ref->ext_account', + 'quote_ref->ext_quote', + ]); + }); + } + + it('update: the existing order gets the quote\'s id and no second order is inserted', async () => { + const { loader, store } = loaderFor(); + store.ext_order = [{ id: 'ord-existing', name: 'O-1' }]; + + const result = await loader.load({ seeds: seeds('update', { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); + + expect(result.success).toBe(true); + expect(result.summary.totalErrored).toBe(0); + const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; + const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; + expect(store.ext_order).toEqual([ + expect.objectContaining({ id: 'ord-existing', name: 'O-1', quote_ref: quoteId, account_ref: accountId }), + ]); + }); + + it('a target that loads after the order (a cycle) is deferred to pass 2 and resolved, as an authored lookup is', async () => { + // `ext_quote.order_ref` points back at the order, so the graph has a cycle + // only once the extension lookup is read: one side loads first and its + // reference waits for pass 2. + const { loader, store } = loaderFor(true); + const result = await loader.load({ + seeds: [ + { object: 'ext_order', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'O-1', quote_ref: 'Q-ACME' }] }, + { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME', order_ref: 'O-1' }] }, + ] as any[], + config: CONFIG, + }); + + expect(result.summary.totalErrored).toBe(0); + const order = store.ext_order.find((r) => r.name === 'O-1')!; + const quote = store.ext_quote.find((r) => r.name === 'Q-ACME')!; + expect(order.quote_ref).toBe(quote.id); + expect(quote.order_ref).toBe(order.id); + expect(result.summary.totalReferencesDeferred).toBeGreaterThanOrEqual(1); + }); + + it('an unknown natural key is refused exactly as the authored lookup refuses it, and no raw key is stored', async () => { + const run = async (field: 'quote_ref' | 'account_ref') => { + const { loader, store } = loaderFor(); + const result = await loader.load({ seeds: seeds('upsert', { [field]: 'Ghost' }), config: CONFIG }); + return { result, store }; + }; + const extension = await run('quote_ref'); + const authored = await run('account_ref'); + + for (const { result, store } of [extension, authored]) { + expect(result.success).toBe(false); + expect(result.summary.totalErrored).toBe(1); + expect((store.ext_order ?? []).some((r) => r.quote_ref === 'Ghost' || r.account_ref === 'Ghost')).toBe(false); + } + const shape = (r: typeof extension.result, field: string, target: string) => + r.errors.map((e: any) => ({ + message: String(e.message).split(field).join('FIELD').split(target).join('TARGET'), + recordIndex: e.recordIndex, + attemptedValue: e.attemptedValue, + })); + expect(shape(extension.result, 'quote_ref', 'ext_quote')).toEqual(shape(authored.result, 'account_ref', 'ext_account')); + expect(extension.result.errors.map((e: any) => e.message).join('\n')).toContain('ext_order.quote_ref'); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index 9a6ce12598d..e83efc3c03d 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -455,13 +455,12 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { /** * [#35655] A roll-up an object EXTENSION contributes is never seeded either. - * The loader resolves a definition from the metadata service first and uses - * that copy whenever it has `fields`; the metadata service stores the object - * as registered, with no extension merged in, so its copy can lack a roll-up - * the engine's merged schema declares and computes. The strip therefore reads - * both the resolved definition and the engine's own schema. These pins hand - * the loader a metadata copy WITHOUT the extension's roll-up and an engine - * schema WITH it. + * The metadata service can store the object as registered, with no extension + * merged in, so its copy can lack a roll-up the engine's merged schema + * declares and computes. The strip reads the resolved definition, which is + * the engine's merged schema whenever the engine has one ([#35254] + * `resolveObjectDefinition`). These pins hand the loader a metadata copy + * WITHOUT the extension's roll-up and an engine schema WITH it. */ describe('a roll-up an object extension contributes is never seeded either (#35655)', () => { const METADATA_COPY = { diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 7ace59dffee..fdbca4a7794 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -629,9 +629,11 @@ function seedRowTenantColumn(definition: unknown): string | null { * its definition declares, plus `owner_id` when the system-column pass injects * it and the object does not declare it. * - * The definition the loader resolves is the metadata service's, which is what - * the author wrote. An object that relies on the platform's owner has no - * `owner_id` there: objectql adds it at registration, from the same + * The definition the loader resolves is the engine's registered schema, which + * already carries the injected column, and otherwise the metadata service's + * copy ([#35254] `resolveObjectDefinition`), which is what the author wrote. + * An object that relies on the platform's owner has no `owner_id` in that + * copy: objectql adds it at registration, from the same * `resolveInjectedSystemColumns` plan read here, as {@link OWNER_FIELD_DEF} (a * `sys_user` lookup). Read from the declared fields alone, a seed value naming * a person in that column was written as the name itself, while a declared @@ -1658,26 +1660,40 @@ export class SeedLoaderService implements ISeedLoaderService { } /** - * Object definition for reference-graph construction: the metadata service - * first, then the engine's own schema registry. + * The object definition every per-field decision of a load reads: the + * reference graph, natural-key resolution, required-on-insert, the tenant + * column, the roll-up strip, the replay comparands. It is the object AS THE + * ENGINE SERVES IT — the engine's own schema registry, object extensions + * folded in — and the metadata service's copy only when the engine has no + * schema for the name. * - * The engine fallback matters for marketplace-installed packages: their - * objects are registered through the `manifest` service straight into the - * ObjectQL registry AFTER `bridgeObjectsToMetadataService` ran at boot, so - * the metadata service has never heard of them. Resolving only via metadata - * left the reference graph empty for those objects — every lookup / - * master_detail seed value was written verbatim (the raw externalId string, - * e.g. `crm_contact.crm_account = 'Acme Corporation'`) instead of the target - * record's id. Dangling references break parent joins, and under + * [#35254] The engine comes FIRST because it is the one store that holds the + * object a write lands on. A boot that ingests a compiled artifact (`os dev`, + * `os serve`, the cloud runtime) gives the metadata service each object as + * its package authored it, and the fields another package adds through + * `objectExtensions` (ADR-0130 D5) live only in the registry's fold. Read + * from that copy, a lookup an extension adds was no reference at all: no + * dependency edge, no natural-key resolution, and the raw key written into + * the foreign-key column — while the in-process boot, whose metadata service + * is bridged from the folded registry, resolved the same seed. The loader + * does not merge extensions itself: the registry's fold is the one source. + * + * The metadata service stays the fallback for an engine that exposes no + * schema registry (the `IDataEngine` contract does not require one) or does + * not know the name. The fallback the other way round predates this order: + * marketplace-installed packages register straight into the ObjectQL + * registry AFTER `bridgeObjectsToMetadataService` ran at boot, so the + * metadata service never hears of them, and resolving through it alone left + * their reference graph empty — every lookup / master_detail seed value + * written verbatim (e.g. `crm_contact.crm_account = 'Acme Corporation'`). + * Dangling references break parent joins, and under * `sharingModel: controlled_by_parent` RLS that makes the whole object * invisible to everyone, admins included. */ private async resolveObjectDefinition(objectName: string): Promise { - const fromMetadata = (await this.metadata.getObject(objectName)) as any; - if (fromMetadata?.fields) return fromMetadata; - const engineSchema = this.engineSchemaOf(objectName) as any; - if (engineSchema?.fields) return engineSchema; - return fromMetadata; + const served = this.engineSchemaOf(objectName) as any; + if (served?.fields) return served; + return (await this.metadata.getObject(objectName)) as any; } /** @@ -2137,14 +2153,11 @@ export class SeedLoaderService implements ISeedLoaderService { // [#35655] The roll-up columns a seed never writes (`summaryFieldNames`), // the values this dataset's records supplied for them, and which of them // did — reported once, after the record loop. Read from the resolved - // definition AND the engine's merged schema: the metadata service's copy - // wins `resolveObjectDefinition` whenever it has `fields`, and it can lack - // a roll-up an object extension contributed, which the engine still - // computes — so a seed must not write it either. - const summaryFields = [...new Set([ - ...summaryFieldNames(objectDefinition), - ...summaryFieldNames(this.engineSchemaOf(objectName)), - ])]; + // definition, which is the engine's merged schema whenever the engine has + // one ([#35254] `resolveObjectDefinition`), so a roll-up an object + // extension contributes, which the engine computes, is never written by a + // seed either. + const summaryFields = summaryFieldNames(objectDefinition); let summaryValuesDropped = 0; const summaryFieldsDropped = new Set(); // How a replay compares each field (`isNoOpReplay`): [#24562] a temporal @@ -3717,17 +3730,16 @@ export class SeedLoaderService implements ISeedLoaderService { * The one question {@link resolveFromDatabase} must be able to answer before * it may add the `name` leg to its probe chain. Answered from the SAME * definition resolver the reference graph is built from - * ({@link resolveObjectDefinition} — the metadata service first, then the - * engine's own schema registry), so the loader cannot form one opinion about + * ({@link resolveObjectDefinition} — the engine's own schema registry first, + * then the metadata service), so the loader cannot form one opinion about * an object's columns here and a different one two methods up. That resolver * is already imported and already called at boot, so this asks the registry * a question it is standing right next to; no new dependency, no new seam. * * **`true` on an unknown**, deliberately. Three populations reach here: an - * object the metadata service knows (authoritative), one only the engine's - * registry knows (marketplace-installed packages — the reason - * `resolveObjectDefinition` has its fallback at all), and one NEITHER can - * describe. For the third the honest answer is "unknown", and an unknown is + * object the engine's registry knows (the served object), one only the + * metadata service knows (an engine with no schema registry), and one + * NEITHER can describe. For the third the honest answer is "unknown", and an unknown is * not a denial: keeping the leg preserves today's behaviour exactly, and the * probe against a genuinely absent object fails on its first leg regardless. * Answering `false` there would be this file making up a column list. From fb269ca492fc5d33bd0b535eddbb486599a3008f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:52:03 +0000 Subject: [PATCH 2/6] test(metadata-protocol): pin extension-lookup cycle parity; add artifact-boot dogfood repro Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- ...seed-loader-extension-lookup-35254.test.ts | 56 +++++--- ...eed-extension-lookup-35254.dogfood.test.ts | 129 ++++++++++++++++++ 2 files changed, 165 insertions(+), 20 deletions(-) create mode 100644 packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts diff --git a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts index 55cc39e4a7f..e102ce60fff 100644 --- a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts +++ b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts @@ -182,10 +182,9 @@ describe('[#35254] a seed resolves a lookup an object extension adds like an aut expect(order.indexOf('ext_account')).toBeLessThan(order.indexOf('ext_order')); const node = result.dependencyGraph.nodes.find((n) => n.object === 'ext_order')!; expect([...node.dependsOn].sort()).toEqual(['ext_account', 'ext_quote']); - expect(node.references.map((r) => `${r.field}->${r.targetObject}`).sort()).toEqual([ - 'account_ref->ext_account', - 'quote_ref->ext_quote', - ]); + // (The injected `owner_id` → `sys_user` reference rides along on both; it is not this pin's subject.) + expect(node.references.filter((r) => r.targetObject.startsWith('ext_')).map((r) => `${r.field}->${r.targetObject}`).sort()) + .toEqual(['account_ref->ext_account', 'quote_ref->ext_quote']); }); } @@ -206,23 +205,40 @@ describe('[#35254] a seed resolves a lookup an object extension adds like an aut it('a target that loads after the order (a cycle) is deferred to pass 2 and resolved, as an authored lookup is', async () => { // `ext_quote.order_ref` points back at the order, so the graph has a cycle - // only once the extension lookup is read: one side loads first and its - // reference waits for pass 2. - const { loader, store } = loaderFor(true); - const result = await loader.load({ - seeds: [ - { object: 'ext_order', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'O-1', quote_ref: 'Q-ACME' }] }, - { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME', order_ref: 'O-1' }] }, - ] as any[], - config: CONFIG, - }); + // only once the extension lookup is read: one side loads first, its + // reference waits for pass 2, and pass 2 writes it back. CONTROL: the same + // cycle with `quote_ref` authored on the order itself. + const run = async (authoredQuoteRef: boolean) => { + const { engine, store } = createFaithfulEngine(servedObjects(true)); + const authored = authoredObjects(true); + if (authoredQuoteRef) authored.ext_order = servedObjects(true).ext_order; + const loader = new SeedLoaderService(engine, createMetadata(authored), createLogger()); + const result = await loader.load({ + seeds: [ + { object: 'ext_order', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'O-1', quote_ref: 'Q-ACME' }] }, + { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME', order_ref: 'O-1' }] }, + ] as any[], + config: CONFIG, + }); + const order = store.ext_order.find((r) => r.name === 'O-1')!; + const quote = store.ext_quote.find((r) => r.name === 'Q-ACME')!; + const backfills = (engine.update as any).mock.calls.map(([object, data]: [string, any]) => + [object, Object.keys(data).filter((k) => k !== 'id').sort()]); + return { result, order, quote, backfills }; + }; + const extension = await run(false); + const control = await run(true); - expect(result.summary.totalErrored).toBe(0); - const order = store.ext_order.find((r) => r.name === 'O-1')!; - const quote = store.ext_quote.find((r) => r.name === 'Q-ACME')!; - expect(order.quote_ref).toBe(quote.id); - expect(quote.order_ref).toBe(order.id); - expect(result.summary.totalReferencesDeferred).toBeGreaterThanOrEqual(1); + for (const { result, order, quote } of [extension, control]) { + expect(result.summary.totalErrored).toBe(0); + expect(result.dependencyGraph.circularDependencies.length).toBeGreaterThan(0); + expect(order.quote_ref).toBe(quote.id); + expect(quote.order_ref).toBe(order.id); + } + // One side was written in pass 2, and the extension lookup took the same path the authored one does. + expect(extension.backfills.length).toBeGreaterThan(0); + expect(extension.backfills).toEqual(control.backfills); + expect(extension.result.dependencyGraph.insertOrder).toEqual(control.result.dependencyGraph.insertOrder); }); it('an unknown natural key is refused exactly as the authored lookup refuses it, and no raw key is stored', async () => { diff --git a/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts b/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts new file mode 100644 index 00000000000..c08bd94fcac --- /dev/null +++ b/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts @@ -0,0 +1,129 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#35254] A seed that sets a lookup another package adds through +// `objectExtensions` (ADR-0130 D5) stores the target's id, on the boot that +// loads a COMPILED ARTIFACT — the door `os dev`, `os serve` and the cloud +// runtime load through. +// +// On that boot the metadata service holds each object as its own package +// authored it; the extension's fields exist only in the ObjectQL registry's +// fold. The seed loader used to read the metadata copy, so the extension lookup +// was no reference: no dependency edge, and the target's natural key written +// verbatim into the foreign-key column. The in-process boot (no artifact) bridges +// the metadata service from the folded registry and resolved the same seed, +// which is why `@objectstack/verify` alone never saw it. +// +// Two packages, composed the way a deployment receives them: +// - `qa_ext_app` (app) owns `qa_ext_order` and seeds order `O-1`, with its own +// authored lookup `account_ref` set by name (the CONTROL); +// - `qa_ext_mod` (module) owns `qa_ext_quote`, adds `quote_ref` +// (→ `qa_ext_quote`) to `qa_ext_order`, seeds the quote, then +// - `update` mode: sets `O-1.quote_ref` by the quote's name; +// - `upsert` mode: inserts order `O-2` with `quote_ref` by the quote's name. + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { MetadataPlugin } from '@objectstack/metadata'; +import { composeStacks, defineStack } from '@objectstack/spec'; +import { writeBuildShapedArtifact } from './build-shaped-artifact.js'; + +const QUOTE = 'Acme Annual Renewal Quote'; +const ACCOUNT = 'Acme Corporation'; + +const appPackage = defineStack({ + manifest: { id: 'com.qa.ext35254.app', namespace: 'qa_ext', name: 'qa_ext_app', version: '1.0.0', type: 'app' }, + objects: [ + { + name: 'qa_ext_account', label: 'Account', sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name', required: true } }, + }, + { + name: 'qa_ext_order', label: 'Order', sharingModel: 'public_read_write', + fields: { + name: { type: 'text', label: 'Name', required: true }, + account_ref: { type: 'lookup', label: 'Account', reference: 'qa_ext_account' }, + }, + }, + ], + data: [ + { object: 'qa_ext_account', externalId: 'name', mode: 'upsert', records: [{ name: ACCOUNT }] }, + { object: 'qa_ext_order', externalId: 'name', mode: 'upsert', records: [{ name: 'O-1', account_ref: ACCOUNT }] }, + ], +} as never); + +const modulePackage = defineStack({ + manifest: { id: 'com.qa.ext35254.mod', namespace: 'qa_ext', name: 'qa_ext_mod', version: '1.0.0', type: 'module' }, + objects: [ + { + name: 'qa_ext_quote', label: 'Quote', sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name', required: true } }, + }, + ], + objectExtensions: [ + { extend: 'qa_ext_order', fields: { quote_ref: { type: 'lookup', label: 'Source Quote', reference: 'qa_ext_quote' } } }, + ], + data: [ + // The order datasets come BEFORE the quote's: only the dependency edge puts the quote first. + { object: 'qa_ext_order', externalId: 'name', mode: 'update', records: [{ name: 'O-1', quote_ref: QUOTE }] }, + { object: 'qa_ext_order', externalId: 'name', mode: 'upsert', records: [{ name: 'O-2', quote_ref: QUOTE, account_ref: ACCOUNT }] }, + { object: 'qa_ext_quote', externalId: 'name', mode: 'upsert', records: [{ name: QUOTE }] }, + ], +} as never); + +describe('[#35254] an artifact boot resolves a seed lookup an object extension adds', () => { + const artifact = composeStacks([appPackage, modulePackage], { manifest: 'preserve' }) as any; + let stack: VerifyStack; + let admin: string; + let dir: string; + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), 'dogfood-seed-ext-lookup-')); + const artifactPath = join(dir, 'objectstack.json'); + writeBuildShapedArtifact(artifact as unknown as Record, artifactPath); + stack = await bootStack(artifact, { + extraPlugins: [ + new MetadataPlugin({ + rootDir: dir, watch: false, artifactWatch: false, registerSystemObjects: false, + artifactSource: { mode: 'local-file', path: artifactPath }, + }), + ], + }); + admin = await stack.signIn(); + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + const rows = async (object: string): Promise => { + const res = await stack.apiAs(admin, 'GET', `/data/${object}`); + const text = await res.text(); + expect(res.status, text.slice(0, 300)).toBe(200); + const body = JSON.parse(text); + return (body?.records ?? body?.data?.records ?? body?.data ?? body?.items ?? []) as any[]; + }; + + it('PREMISE: the metadata service holds the order without the extension field, the engine serves it with it', async () => { + const metadata: any = await stack.kernel.getServiceAsync('metadata'); + const authored = await metadata.getObject('qa_ext_order'); + expect(Object.keys(authored?.fields ?? {})).not.toContain('quote_ref'); + const ql: any = await stack.kernel.getServiceAsync('objectql'); + expect(Object.keys(ql.getSchema('qa_ext_order')?.fields ?? {})).toContain('quote_ref'); + }); + + it('update and upsert both store the quote\'s id, never its name; the authored lookup beside it resolves too', async () => { + const [quote] = await rows('qa_ext_quote'); + const [account] = await rows('qa_ext_account'); + expect(quote?.id).toBeTruthy(); + const orders = await rows('qa_ext_order'); + const byName = Object.fromEntries(orders.map((o) => [o.name, o])); + expect(orders.map((o) => o.name).sort()).toEqual(['O-1', 'O-2']); + expect([byName['O-1'].quote_ref, byName['O-2'].quote_ref]).toEqual([quote.id, quote.id]); + // CONTROL: the owner's own lookup on the same rows. + expect([byName['O-1'].account_ref, byName['O-2'].account_ref]).toEqual([account.id, account.id]); + }); +}); From 5872b068c5311d602f90d583f506e3317e6c9142 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:53:17 +0000 Subject: [PATCH 3/6] test(dogfood): the artifact-boot repro builds the module with artifactObjects Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- .../dogfood/test/seed-extension-lookup-35254.dogfood.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts b/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts index c08bd94fcac..672a957987c 100644 --- a/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts +++ b/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts @@ -16,7 +16,8 @@ // Two packages, composed the way a deployment receives them: // - `qa_ext_app` (app) owns `qa_ext_order` and seeds order `O-1`, with its own // authored lookup `account_ref` set by name (the CONTROL); -// - `qa_ext_mod` (module) owns `qa_ext_quote`, adds `quote_ref` +// - `qa_ext_mod` (module, built with the app's objects as `artifactObjects`) +// owns `qa_ext_quote`, adds `quote_ref` // (→ `qa_ext_quote`) to `qa_ext_order`, seeds the quote, then // - `update` mode: sets `O-1.quote_ref` by the quote's name; // - `upsert` mode: inserts order `O-2` with `quote_ref` by the quote's name. @@ -71,7 +72,7 @@ const modulePackage = defineStack({ { object: 'qa_ext_order', externalId: 'name', mode: 'upsert', records: [{ name: 'O-2', quote_ref: QUOTE, account_ref: ACCOUNT }] }, { object: 'qa_ext_quote', externalId: 'name', mode: 'upsert', records: [{ name: QUOTE }] }, ], -} as never); +} as never, { artifactObjects: ['qa_ext_account', 'qa_ext_order'] } as never); describe('[#35254] an artifact boot resolves a seed lookup an object extension adds', () => { const artifact = composeStacks([appPackage, modulePackage], { manifest: 'preserve' }) as any; From 8fad3815b41301d7dece436bd30dc4b7eaea2992 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:08:09 +0000 Subject: [PATCH 4/6] test(dogfood): drop the harness-boot repro, which stays green on the unfixed resolver Measured: bootStack with the artifact MetadataPlugin resolves the extension lookup on both legs of the ablation, so it cannot pin this defect; the real os dev boot does reproduce it (recorded in the PR). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- ...eed-extension-lookup-35254.dogfood.test.ts | 130 ------------------ 1 file changed, 130 deletions(-) delete mode 100644 packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts diff --git a/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts b/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts deleted file mode 100644 index 672a957987c..00000000000 --- a/packages/qa/dogfood/test/seed-extension-lookup-35254.dogfood.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// [#35254] A seed that sets a lookup another package adds through -// `objectExtensions` (ADR-0130 D5) stores the target's id, on the boot that -// loads a COMPILED ARTIFACT — the door `os dev`, `os serve` and the cloud -// runtime load through. -// -// On that boot the metadata service holds each object as its own package -// authored it; the extension's fields exist only in the ObjectQL registry's -// fold. The seed loader used to read the metadata copy, so the extension lookup -// was no reference: no dependency edge, and the target's natural key written -// verbatim into the foreign-key column. The in-process boot (no artifact) bridges -// the metadata service from the folded registry and resolved the same seed, -// which is why `@objectstack/verify` alone never saw it. -// -// Two packages, composed the way a deployment receives them: -// - `qa_ext_app` (app) owns `qa_ext_order` and seeds order `O-1`, with its own -// authored lookup `account_ref` set by name (the CONTROL); -// - `qa_ext_mod` (module, built with the app's objects as `artifactObjects`) -// owns `qa_ext_quote`, adds `quote_ref` -// (→ `qa_ext_quote`) to `qa_ext_order`, seeds the quote, then -// - `update` mode: sets `O-1.quote_ref` by the quote's name; -// - `upsert` mode: inserts order `O-2` with `quote_ref` by the quote's name. - -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { bootStack, type VerifyStack } from '@objectstack/verify'; -import { MetadataPlugin } from '@objectstack/metadata'; -import { composeStacks, defineStack } from '@objectstack/spec'; -import { writeBuildShapedArtifact } from './build-shaped-artifact.js'; - -const QUOTE = 'Acme Annual Renewal Quote'; -const ACCOUNT = 'Acme Corporation'; - -const appPackage = defineStack({ - manifest: { id: 'com.qa.ext35254.app', namespace: 'qa_ext', name: 'qa_ext_app', version: '1.0.0', type: 'app' }, - objects: [ - { - name: 'qa_ext_account', label: 'Account', sharingModel: 'public_read_write', - fields: { name: { type: 'text', label: 'Name', required: true } }, - }, - { - name: 'qa_ext_order', label: 'Order', sharingModel: 'public_read_write', - fields: { - name: { type: 'text', label: 'Name', required: true }, - account_ref: { type: 'lookup', label: 'Account', reference: 'qa_ext_account' }, - }, - }, - ], - data: [ - { object: 'qa_ext_account', externalId: 'name', mode: 'upsert', records: [{ name: ACCOUNT }] }, - { object: 'qa_ext_order', externalId: 'name', mode: 'upsert', records: [{ name: 'O-1', account_ref: ACCOUNT }] }, - ], -} as never); - -const modulePackage = defineStack({ - manifest: { id: 'com.qa.ext35254.mod', namespace: 'qa_ext', name: 'qa_ext_mod', version: '1.0.0', type: 'module' }, - objects: [ - { - name: 'qa_ext_quote', label: 'Quote', sharingModel: 'public_read_write', - fields: { name: { type: 'text', label: 'Name', required: true } }, - }, - ], - objectExtensions: [ - { extend: 'qa_ext_order', fields: { quote_ref: { type: 'lookup', label: 'Source Quote', reference: 'qa_ext_quote' } } }, - ], - data: [ - // The order datasets come BEFORE the quote's: only the dependency edge puts the quote first. - { object: 'qa_ext_order', externalId: 'name', mode: 'update', records: [{ name: 'O-1', quote_ref: QUOTE }] }, - { object: 'qa_ext_order', externalId: 'name', mode: 'upsert', records: [{ name: 'O-2', quote_ref: QUOTE, account_ref: ACCOUNT }] }, - { object: 'qa_ext_quote', externalId: 'name', mode: 'upsert', records: [{ name: QUOTE }] }, - ], -} as never, { artifactObjects: ['qa_ext_account', 'qa_ext_order'] } as never); - -describe('[#35254] an artifact boot resolves a seed lookup an object extension adds', () => { - const artifact = composeStacks([appPackage, modulePackage], { manifest: 'preserve' }) as any; - let stack: VerifyStack; - let admin: string; - let dir: string; - - beforeAll(async () => { - dir = mkdtempSync(join(tmpdir(), 'dogfood-seed-ext-lookup-')); - const artifactPath = join(dir, 'objectstack.json'); - writeBuildShapedArtifact(artifact as unknown as Record, artifactPath); - stack = await bootStack(artifact, { - extraPlugins: [ - new MetadataPlugin({ - rootDir: dir, watch: false, artifactWatch: false, registerSystemObjects: false, - artifactSource: { mode: 'local-file', path: artifactPath }, - }), - ], - }); - admin = await stack.signIn(); - }, 300_000); - - afterAll(async () => { - await stack?.stop?.(); - if (dir) rmSync(dir, { recursive: true, force: true }); - }); - - const rows = async (object: string): Promise => { - const res = await stack.apiAs(admin, 'GET', `/data/${object}`); - const text = await res.text(); - expect(res.status, text.slice(0, 300)).toBe(200); - const body = JSON.parse(text); - return (body?.records ?? body?.data?.records ?? body?.data ?? body?.items ?? []) as any[]; - }; - - it('PREMISE: the metadata service holds the order without the extension field, the engine serves it with it', async () => { - const metadata: any = await stack.kernel.getServiceAsync('metadata'); - const authored = await metadata.getObject('qa_ext_order'); - expect(Object.keys(authored?.fields ?? {})).not.toContain('quote_ref'); - const ql: any = await stack.kernel.getServiceAsync('objectql'); - expect(Object.keys(ql.getSchema('qa_ext_order')?.fields ?? {})).toContain('quote_ref'); - }); - - it('update and upsert both store the quote\'s id, never its name; the authored lookup beside it resolves too', async () => { - const [quote] = await rows('qa_ext_quote'); - const [account] = await rows('qa_ext_account'); - expect(quote?.id).toBeTruthy(); - const orders = await rows('qa_ext_order'); - const byName = Object.fromEntries(orders.map((o) => [o.name, o])); - expect(orders.map((o) => o.name).sort()).toEqual(['O-1', 'O-2']); - expect([byName['O-1'].quote_ref, byName['O-2'].quote_ref]).toEqual([quote.id, quote.id]); - // CONTROL: the owner's own lookup on the same rows. - expect([byName['O-1'].account_ref, byName['O-2'].account_ref]).toEqual([account.id, account.id]); - }); -}); From e3d33403a2b6acb6480c2e390845e766ab94f38a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:08:25 +0000 Subject: [PATCH 5/6] test(metadata-protocol): state the measured unfixed readings in the pin's header Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- .../src/seed-loader-extension-lookup-35254.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts index e102ce60fff..5fae5d0c5f5 100644 --- a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts +++ b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts @@ -18,8 +18,10 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin * in the engine registry's fold. The loader used to prefer the metadata copy * whenever it had `fields`, so the extension lookup was no reference at all: * no `ext_order → ext_quote` edge, and the quote's name written verbatim into - * the foreign-key column. Measured on unfixed `origin/main` a5a5312ff4 with - * this harness: `quote_ref = 'Q-ACME'`, `insertOrder` with `ext_order` first. + * the foreign-key column. Measured with the resolver of `origin/main` + * a5a5312ff4 put back: this harness stores `quote_ref = 'Q-ACME'`, and a real + * `os dev` boot of a two-package artifact of this shape stores the quote's + * name in both an `update` and an `upsert` row. * * The metadata double serves the authored `ext_order` (no `quote_ref`); the * engine double's `getSchema` serves the folded one (with it), as the ObjectQL From dd697760d1b01c723810cac1ba33a0d7d476d71b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:39:38 +0000 Subject: [PATCH 6/6] test(metadata-protocol): fold the extension-lookup pins into the engine-schema-fallback file, on its pinned engine double Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- ...seed-loader-engine-schema-fallback.test.ts | 194 +++++++++++++ ...seed-loader-extension-lookup-35254.test.ts | 269 ------------------ 2 files changed, 194 insertions(+), 269 deletions(-) delete mode 100644 packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts diff --git a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts index 9cedd0a6f01..a8695a928eb 100644 --- a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts +++ b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts @@ -250,3 +250,197 @@ describe('seed reference graph — engine schema fallback (marketplace objects)' expect(store.crm_contact.every((r) => r.crm_account === 'Acme Corporation')).toBe(true); }); }); + +/** + * [#35254] A lookup that one package adds to another package's object through + * `objectExtensions` (ADR-0130 D5) resolves in a seed exactly like a lookup + * the owner authored: it joins the dependency graph, its natural key becomes + * the target's id, it is deferred to pass 2 when the target loads later, and + * an unknown key is refused the same way. + * + * The shape these pins reproduce is the boot that ingests a compiled artifact + * (`os dev`, `os serve`, the cloud runtime). There the metadata service holds + * each object AS ITS PACKAGE AUTHORED IT, and the extension's fields exist only + * in the engine registry's fold. The loader used to prefer the metadata copy + * whenever it had `fields`, so the extension lookup was no reference at all: + * no `ext_order → ext_quote` edge, and the quote's name written verbatim into + * the foreign-key column. Measured with the resolver of `origin/main` + * a5a5312ff4 put back: this harness stores `quote_ref = 'Q-ACME'`, and a real + * `os dev` boot of a two-package artifact of this shape stores the quote's + * name in both an `update` and an `upsert` row. + * + * The metadata double serves the authored `ext_order` (no `quote_ref`); the + * engine double's `getSchema` serves the folded one (with it), as the ObjectQL + * registry does after `registerApp` applies the extension. Every case keeps a + * CONTROL beside it: the same seed through `account_ref`, a lookup the owner + * authored on the same object. The engine double is this file's own + * (`createFaithfulEngine`), already pinned to the engine's dispatch contract. + */ + +/** The owner package's objects, as it authored them — what the metadata service holds on an artifact boot. */ +function authoredObjects(quoteBacklink: boolean): Record { + return { + ext_account: { name: 'ext_account', fields: { name: { type: 'text', required: true } } }, + ext_order: { + name: 'ext_order', + fields: { + name: { type: 'text', required: true }, + account_ref: { type: 'lookup', reference: 'ext_account' }, + }, + }, + ext_quote: { + name: 'ext_quote', + fields: { + name: { type: 'text', required: true }, + ...(quoteBacklink ? { order_ref: { type: 'lookup', reference: 'ext_order' } } : {}), + }, + }, + }; +} + +/** The same objects as the engine's registry serves them: `ext_order` with the extension's lookup folded in. */ +function servedObjects(quoteBacklink: boolean): Record { + const authored = authoredObjects(quoteBacklink); + return { + ...authored, + ext_order: { + ...authored.ext_order, + fields: { ...authored.ext_order.fields, quote_ref: { type: 'lookup', reference: 'ext_quote' } }, + }, + }; +} + +function createMetadataServing(objects: Record): 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 EXT_ENV = ['prod', 'dev', 'test']; + +function loaderFor(quoteBacklink = false) { + const { engine, store } = createFaithfulEngine(servedObjects(quoteBacklink)); + const logger = createLogger(); + const loader = new SeedLoaderService(engine, createMetadataServing(authoredObjects(quoteBacklink)), logger); + return { loader, store, logger, engine }; +} + +/** The order dataset first, then the targets — the order a later package's seeds arrive in. */ +function seeds(mode: string, order: Record) { + return [ + { object: 'ext_order', externalId: 'name', mode, env: EXT_ENV, records: [{ name: 'O-1', ...order }] }, + { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: EXT_ENV, records: [{ name: 'Q-ACME' }] }, + { object: 'ext_account', externalId: 'name', mode: 'upsert', env: EXT_ENV, records: [{ name: 'Acme' }] }, + ] as any[]; +} + +describe('[#35254] a seed resolves a lookup an object extension adds like an authored one', () => { + for (const mode of ['upsert', 'ignore'] as const) { + it(`${mode} (inserting): the extension lookup stores the quote's id, and the graph loads the quote first`, async () => { + const { loader, store } = loaderFor(); + const result = await loader.load({ seeds: seeds(mode, { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); + + expect(result.success).toBe(true); + expect(result.summary.totalErrored).toBe(0); + const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; + const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; + expect(store.ext_order).toHaveLength(1); + expect(store.ext_order[0].quote_ref).toBe(quoteId); + // CONTROL: the authored lookup on the same row. + expect(store.ext_order[0].account_ref).toBe(accountId); + + const order = result.dependencyGraph.insertOrder; + expect(order.indexOf('ext_quote')).toBeLessThan(order.indexOf('ext_order')); + expect(order.indexOf('ext_account')).toBeLessThan(order.indexOf('ext_order')); + const node = result.dependencyGraph.nodes.find((n) => n.object === 'ext_order')!; + expect([...node.dependsOn].sort()).toEqual(['ext_account', 'ext_quote']); + // (The injected `owner_id` → `sys_user` reference rides along on both; it is not this pin's subject.) + expect(node.references.filter((r) => r.targetObject.startsWith('ext_')).map((r) => `${r.field}->${r.targetObject}`).sort()) + .toEqual(['account_ref->ext_account', 'quote_ref->ext_quote']); + }); + } + + it('update: the existing order gets the quote\'s id and no second order is inserted', async () => { + const { loader, store } = loaderFor(); + store.ext_order = [{ id: 'ord-existing', name: 'O-1' }]; + + const result = await loader.load({ seeds: seeds('update', { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); + + expect(result.success).toBe(true); + expect(result.summary.totalErrored).toBe(0); + const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; + const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; + expect(store.ext_order).toEqual([ + expect.objectContaining({ id: 'ord-existing', name: 'O-1', quote_ref: quoteId, account_ref: accountId }), + ]); + }); + + it('a target that loads after the order (a cycle) is deferred to pass 2 and resolved, as an authored lookup is', async () => { + // `ext_quote.order_ref` points back at the order, so the graph has a cycle + // only once the extension lookup is read: one side loads first, its + // reference waits for pass 2, and pass 2 writes it back. CONTROL: the same + // cycle with `quote_ref` authored on the order itself. + const run = async (authoredQuoteRef: boolean) => { + const { engine, store } = createFaithfulEngine(servedObjects(true)); + const authored = authoredObjects(true); + if (authoredQuoteRef) authored.ext_order = servedObjects(true).ext_order; + const loader = new SeedLoaderService(engine, createMetadataServing(authored), createLogger()); + const result = await loader.load({ + seeds: [ + { object: 'ext_order', externalId: 'name', mode: 'upsert', env: EXT_ENV, records: [{ name: 'O-1', quote_ref: 'Q-ACME' }] }, + { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: EXT_ENV, records: [{ name: 'Q-ACME', order_ref: 'O-1' }] }, + ] as any[], + config: CONFIG, + }); + const order = store.ext_order.find((r) => r.name === 'O-1')!; + const quote = store.ext_quote.find((r) => r.name === 'Q-ACME')!; + const backfills = (engine.update as any).mock.calls.map(([object, data]: [string, any]) => + [object, Object.keys(data).filter((k) => k !== 'id').sort()]); + return { result, order, quote, backfills }; + }; + const extension = await run(false); + const control = await run(true); + + for (const { result, order, quote } of [extension, control]) { + expect(result.summary.totalErrored).toBe(0); + expect(result.dependencyGraph.circularDependencies.length).toBeGreaterThan(0); + expect(order.quote_ref).toBe(quote.id); + expect(quote.order_ref).toBe(order.id); + } + // One side was written in pass 2, and the extension lookup took the same path the authored one does. + expect(extension.backfills.length).toBeGreaterThan(0); + expect(extension.backfills).toEqual(control.backfills); + expect(extension.result.dependencyGraph.insertOrder).toEqual(control.result.dependencyGraph.insertOrder); + }); + + it('an unknown natural key is refused exactly as the authored lookup refuses it, and no raw key is stored', async () => { + const run = async (field: 'quote_ref' | 'account_ref') => { + const { loader, store } = loaderFor(); + const result = await loader.load({ seeds: seeds('upsert', { [field]: 'Ghost' }), config: CONFIG }); + return { result, store }; + }; + const extension = await run('quote_ref'); + const authored = await run('account_ref'); + + for (const { result, store } of [extension, authored]) { + expect(result.success).toBe(false); + expect(result.summary.totalErrored).toBe(1); + expect((store.ext_order ?? []).some((r) => r.quote_ref === 'Ghost' || r.account_ref === 'Ghost')).toBe(false); + } + const shape = (r: typeof extension.result, field: string, target: string) => + r.errors.map((e: any) => ({ + message: String(e.message).split(field).join('FIELD').split(target).join('TARGET'), + recordIndex: e.recordIndex, + attemptedValue: e.attemptedValue, + })); + expect(shape(extension.result, 'quote_ref', 'ext_quote')).toEqual(shape(authored.result, 'account_ref', 'ext_account')); + expect(extension.result.errors.map((e: any) => e.message).join('\n')).toContain('ext_order.quote_ref'); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts b/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts deleted file mode 100644 index 5fae5d0c5f5..00000000000 --- a/packages/metadata-protocol/src/seed-loader-extension-lookup-35254.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -// 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'; - -/** - * [#35254] A lookup that one package adds to another package's object through - * `objectExtensions` (ADR-0130 D5) resolves in a seed exactly like a lookup - * the owner authored: it joins the dependency graph, its natural key becomes - * the target's id, it is deferred to pass 2 when the target loads later, and - * an unknown key is refused the same way. - * - * The shape this file reproduces is the boot that ingests a compiled artifact - * (`os dev`, `os serve`, the cloud runtime). There the metadata service holds - * each object AS ITS PACKAGE AUTHORED IT, and the extension's fields exist only - * in the engine registry's fold. The loader used to prefer the metadata copy - * whenever it had `fields`, so the extension lookup was no reference at all: - * no `ext_order → ext_quote` edge, and the quote's name written verbatim into - * the foreign-key column. Measured with the resolver of `origin/main` - * a5a5312ff4 put back: this harness stores `quote_ref = 'Q-ACME'`, and a real - * `os dev` boot of a two-package artifact of this shape stores the quote's - * name in both an `update` and an `upsert` row. - * - * The metadata double serves the authored `ext_order` (no `quote_ref`); the - * engine double's `getSchema` serves the folded one (with it), as the ObjectQL - * registry does after `registerApp` applies the extension. Every case keeps a - * CONTROL beside it: the same seed through `account_ref`, a lookup the owner - * authored on the same object. - */ - -function createLogger() { - return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; -} - -/** The faithful engine of seed-loader-engine-schema-fallback.test.ts (where-filtering find, the - * producer's dispatch predicates on findOne / update / delete), plus a store a case can pre-fill. */ -function createFaithfulEngine(schemas: Record) { - const store: Record = {}; - let idCounter = 0; - - const engine = { - find: vi.fn(async (objectName: string, query?: any) => { - let records = store[objectName] || []; - if (query?.where) { - records = records.filter((r) => - Object.entries(query.where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), - ); - } - if (typeof query?.limit === 'number') { - records = records.slice(0, query.limit); - } - return records; - }), - 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) => { - if (!store[objectName]) store[objectName] = []; - if (Array.isArray(data)) { - const records = data.map((d) => ({ id: `gen-${++idCounter}`, ...d })); - store[objectName].push(...records); - return records; - } - const record = { id: `gen-${++idCounter}`, ...data }; - store[objectName].push(record); - return record; - }), - update: vi.fn(async (objectName: string, data: any) => { - assertEngineUpdateDispatch(data, undefined); - const records = store[objectName] || []; - const idx = records.findIndex((r) => r.id === data.id); - if (idx >= 0) { - records[idx] = { ...records[idx], ...data }; - return records[idx]; - } - return data; - }), - 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 () => []), - getSchema: vi.fn((objectName: string) => schemas[objectName]), - } as unknown as IDataEngine & { getSchema: ReturnType }; - - return { engine, store }; -} - -/** The owner package's objects, as it authored them — what the metadata service holds on an artifact boot. */ -function authoredObjects(quoteBacklink: boolean): Record { - return { - ext_account: { name: 'ext_account', fields: { name: { type: 'text', required: true } } }, - ext_order: { - name: 'ext_order', - fields: { - name: { type: 'text', required: true }, - account_ref: { type: 'lookup', reference: 'ext_account' }, - }, - }, - ext_quote: { - name: 'ext_quote', - fields: { - name: { type: 'text', required: true }, - ...(quoteBacklink ? { order_ref: { type: 'lookup', reference: 'ext_order' } } : {}), - }, - }, - }; -} - -/** The same objects as the engine's registry serves them: `ext_order` with the extension's lookup folded in. */ -function servedObjects(quoteBacklink: boolean): Record { - const authored = authoredObjects(quoteBacklink); - return { - ...authored, - ext_order: { - ...authored.ext_order, - fields: { ...authored.ext_order.fields, quote_ref: { type: 'lookup', reference: 'ext_quote' } }, - }, - }; -} - -function createMetadata(objects: Record): 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: 'upsert', - batchSize: 1000, - transaction: false, -} as any; - -const ENV = ['prod', 'dev', 'test']; - -function loaderFor(quoteBacklink = false) { - const { engine, store } = createFaithfulEngine(servedObjects(quoteBacklink)); - const logger = createLogger(); - const loader = new SeedLoaderService(engine, createMetadata(authoredObjects(quoteBacklink)), logger); - return { loader, store, logger, engine }; -} - -/** The order dataset first, then the targets — the order a later package's seeds arrive in. */ -function seeds(mode: string, order: Record) { - return [ - { object: 'ext_order', externalId: 'name', mode, env: ENV, records: [{ name: 'O-1', ...order }] }, - { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME' }] }, - { object: 'ext_account', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Acme' }] }, - ] as any[]; -} - -describe('[#35254] a seed resolves a lookup an object extension adds like an authored one', () => { - for (const mode of ['upsert', 'ignore'] as const) { - it(`${mode} (inserting): the extension lookup stores the quote's id, and the graph loads the quote first`, async () => { - const { loader, store } = loaderFor(); - const result = await loader.load({ seeds: seeds(mode, { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); - - expect(result.success).toBe(true); - expect(result.summary.totalErrored).toBe(0); - const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; - const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; - expect(store.ext_order).toHaveLength(1); - expect(store.ext_order[0].quote_ref).toBe(quoteId); - // CONTROL: the authored lookup on the same row. - expect(store.ext_order[0].account_ref).toBe(accountId); - - const order = result.dependencyGraph.insertOrder; - expect(order.indexOf('ext_quote')).toBeLessThan(order.indexOf('ext_order')); - expect(order.indexOf('ext_account')).toBeLessThan(order.indexOf('ext_order')); - const node = result.dependencyGraph.nodes.find((n) => n.object === 'ext_order')!; - expect([...node.dependsOn].sort()).toEqual(['ext_account', 'ext_quote']); - // (The injected `owner_id` → `sys_user` reference rides along on both; it is not this pin's subject.) - expect(node.references.filter((r) => r.targetObject.startsWith('ext_')).map((r) => `${r.field}->${r.targetObject}`).sort()) - .toEqual(['account_ref->ext_account', 'quote_ref->ext_quote']); - }); - } - - it('update: the existing order gets the quote\'s id and no second order is inserted', async () => { - const { loader, store } = loaderFor(); - store.ext_order = [{ id: 'ord-existing', name: 'O-1' }]; - - const result = await loader.load({ seeds: seeds('update', { quote_ref: 'Q-ACME', account_ref: 'Acme' }), config: CONFIG }); - - expect(result.success).toBe(true); - expect(result.summary.totalErrored).toBe(0); - const quoteId = store.ext_quote.find((r) => r.name === 'Q-ACME')!.id; - const accountId = store.ext_account.find((r) => r.name === 'Acme')!.id; - expect(store.ext_order).toEqual([ - expect.objectContaining({ id: 'ord-existing', name: 'O-1', quote_ref: quoteId, account_ref: accountId }), - ]); - }); - - it('a target that loads after the order (a cycle) is deferred to pass 2 and resolved, as an authored lookup is', async () => { - // `ext_quote.order_ref` points back at the order, so the graph has a cycle - // only once the extension lookup is read: one side loads first, its - // reference waits for pass 2, and pass 2 writes it back. CONTROL: the same - // cycle with `quote_ref` authored on the order itself. - const run = async (authoredQuoteRef: boolean) => { - const { engine, store } = createFaithfulEngine(servedObjects(true)); - const authored = authoredObjects(true); - if (authoredQuoteRef) authored.ext_order = servedObjects(true).ext_order; - const loader = new SeedLoaderService(engine, createMetadata(authored), createLogger()); - const result = await loader.load({ - seeds: [ - { object: 'ext_order', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'O-1', quote_ref: 'Q-ACME' }] }, - { object: 'ext_quote', externalId: 'name', mode: 'upsert', env: ENV, records: [{ name: 'Q-ACME', order_ref: 'O-1' }] }, - ] as any[], - config: CONFIG, - }); - const order = store.ext_order.find((r) => r.name === 'O-1')!; - const quote = store.ext_quote.find((r) => r.name === 'Q-ACME')!; - const backfills = (engine.update as any).mock.calls.map(([object, data]: [string, any]) => - [object, Object.keys(data).filter((k) => k !== 'id').sort()]); - return { result, order, quote, backfills }; - }; - const extension = await run(false); - const control = await run(true); - - for (const { result, order, quote } of [extension, control]) { - expect(result.summary.totalErrored).toBe(0); - expect(result.dependencyGraph.circularDependencies.length).toBeGreaterThan(0); - expect(order.quote_ref).toBe(quote.id); - expect(quote.order_ref).toBe(order.id); - } - // One side was written in pass 2, and the extension lookup took the same path the authored one does. - expect(extension.backfills.length).toBeGreaterThan(0); - expect(extension.backfills).toEqual(control.backfills); - expect(extension.result.dependencyGraph.insertOrder).toEqual(control.result.dependencyGraph.insertOrder); - }); - - it('an unknown natural key is refused exactly as the authored lookup refuses it, and no raw key is stored', async () => { - const run = async (field: 'quote_ref' | 'account_ref') => { - const { loader, store } = loaderFor(); - const result = await loader.load({ seeds: seeds('upsert', { [field]: 'Ghost' }), config: CONFIG }); - return { result, store }; - }; - const extension = await run('quote_ref'); - const authored = await run('account_ref'); - - for (const { result, store } of [extension, authored]) { - expect(result.success).toBe(false); - expect(result.summary.totalErrored).toBe(1); - expect((store.ext_order ?? []).some((r) => r.quote_ref === 'Ghost' || r.account_ref === 'Ghost')).toBe(false); - } - const shape = (r: typeof extension.result, field: string, target: string) => - r.errors.map((e: any) => ({ - message: String(e.message).split(field).join('FIELD').split(target).join('TARGET'), - recordIndex: e.recordIndex, - attemptedValue: e.attemptedValue, - })); - expect(shape(extension.result, 'quote_ref', 'ext_quote')).toEqual(shape(authored.result, 'account_ref', 'ext_account')); - expect(extension.result.errors.map((e: any) => e.message).join('\n')).toContain('ext_order.quote_ref'); - }); -});