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..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 @@ -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 () => { @@ -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-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.