Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/35254-seed-extension-lookup.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand All @@ -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<string>((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 () => {
Expand All @@ -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<string, any> {
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<string, any> {
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<string, any>): 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<string, unknown>) {
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');
});
});
13 changes: 6 additions & 7 deletions packages/metadata-protocol/src/seed-loader-summary-stale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Loading
Loading