From 1f7b14b2f0a9eb5b6cf819fdb20e1e3bc499d073 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:57:50 +0000 Subject: [PATCH 1/5] test(runtime): serve the authored definition from the seed reference harness's metadata stub Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...-org-scoped-references.integration.test.ts | 70 ++++++++++++++++++- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/seed-org-scoped-references.integration.test.ts b/packages/runtime/src/seed-org-scoped-references.integration.test.ts index 0bafe3defb6..f675c5abfe6 100644 --- a/packages/runtime/src/seed-org-scoped-references.integration.test.ts +++ b/packages/runtime/src/seed-org-scoped-references.integration.test.ts @@ -174,10 +174,15 @@ async function boot(options: BootOptions) { seen.push({ name: hctx.input?.data?.name, session: hctx.session, rowOrganization: hctx.result?.organization_id }); }, { object: 'crm_deal' }); + // The metadata service serves what the author wrote: an object that relies + // on the injected `owner_id` / `organization_id` does not carry them here. + // Only the engine's registry holds the enriched definition (`definitions` + // above), so serving that from the stub would hide every defect of a loader + // that reads the authored definition and forgets an injected column. const metadata = { - getObject: vi.fn(async (name: string) => definitions.find((d: any) => d.name === name)), - listObjects: vi.fn(async () => definitions), - getObjects: vi.fn(async () => definitions), + getObject: vi.fn(async (name: string) => objects.find((d: any) => d.name === name)), + listObjects: vi.fn(async () => objects), + getObjects: vi.fn(async () => objects), get: vi.fn(async () => undefined), list: vi.fn(async () => []), exists: vi.fn(async () => false), @@ -642,3 +647,62 @@ describe('a dataset OF a global object (tenancy disabled) replays per organizati expect((await rowsOf(engine, 'crm_country')).filter((r) => r.name === 'Peru')).toHaveLength(1); }); }); + +describe('#33791 the injected owner column resolves like a declared person lookup', () => { + /** `owner_id` and the declared `rep` of each deal, by deal name. */ + const peopleOf = (rows: Row[]) => + Object.fromEntries(rows.map((r) => [r.name, { owner_id: r.owner_id ?? null, rep: r.rep ?? null }])); + + it('the harness serves the authored deal, which has no owner_id; the registry injects one', async () => { + const { engine, metadata } = await boot({ posture: 'single', data: [] }); + const authored = (await metadata.getObject('crm_deal')) as { fields: Record }; + expect(Object.keys(authored.fields)).not.toContain('owner_id'); + expect(Object.keys(engine.registry.getObject('crm_deal')?.fields ?? {})).toContain('owner_id'); + }); + + it('a single boot resolves a member named in owner_id to that member, as it resolves the declared rep', async () => { + const { dealsOf } = await boot({ posture: 'single', data: [deals([{ name: 'Deal 1', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])] }); + expect(peopleOf(await dealsOf())).toEqual({ 'Deal 1': { owner_id: 'usr_zhang', rep: 'usr_zhang' } }); + }); + + it('a walled replay resolves a member per organization; a non-member is NULL with the same error rep gets', async () => { + const { replayer, dealsOf } = await boot({ + posture: 'isolated', + data: [deals([{ name: 'Deal 1', owner_id: 'Wang Fang', rep: 'Wang Fang' }, { name: 'Deal 2', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])], + }); + + const north = await replayer!(ORG_NORTH); + const south = await replayer!(ORG_SOUTH); + + expect(north.errors).toEqual([]); + expect(peopleOf(await dealsOf(ORG_NORTH))).toEqual({ + 'Deal 1': { owner_id: 'usr_wang_north', rep: 'usr_wang_north' }, + 'Deal 2': { owner_id: 'usr_zhang', rep: 'usr_zhang' }, + }); + // Zhang Wei is not a member of South: neither column borrows him, and the + // owner is NULL (a first-admin handoff can claim it), never his name as text. + expect(peopleOf(await dealsOf(ORG_SOUTH))).toEqual({ + 'Deal 1': { owner_id: 'usr_wang_south', rep: 'usr_wang_south' }, + 'Deal 2': { owner_id: null, rep: null }, + }); + const errors = south.errors as Array<{ message: string; field?: string }>; + expect(errors.map((e) => e.field).sort()).toEqual(['owner_id', 'rep']); + for (const e of errors) expect(e.message).toContain(`not a member of organization ${ORG_SOUTH}`); + }); + + it('a direct load pinned to an organization (the install path) resolves owner_id through that organization', async () => { + const { engine, metadata, logger, dealsOf } = await boot({ posture: 'isolated', data: [] }); + const loader = new SeedLoaderService(engine as any, metadata as any, logger as any); + const result = await loader.load({ + seeds: [deals([{ name: 'Installed', owner_id: 'Wang Fang' }])], + config: { multiPass: true, organizationId: ORG_SOUTH }, + } as any); + expect(result.errors).toEqual([]); + expect((await dealsOf(ORG_SOUTH))[0].owner_id).toBe('usr_wang_south'); + }); + + it('CONTROL — a load with no organization resolves owner_id unscoped, as it resolves rep', async () => { + const { dealsOf } = await boot({ posture: 'single', organizations: false, data: [deals([{ name: 'Deal 1', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])] }); + expect(peopleOf(await dealsOf())).toEqual({ 'Deal 1': { owner_id: 'usr_zhang', rep: 'usr_zhang' } }); + }); +}); From 39fdad3d49f722156a525b229afdff3f88e9d5e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:09:54 +0000 Subject: [PATCH 2/5] fix(metadata-protocol): seed reference graph reads the injected owner_id as a sys_user lookup Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...ed-loader-injected-owner-reference.test.ts | 103 ++++++++++++++++++ packages/metadata-protocol/src/seed-loader.ts | 35 +++++- 2 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 packages/metadata-protocol/src/seed-loader-injected-owner-reference.test.ts diff --git a/packages/metadata-protocol/src/seed-loader-injected-owner-reference.test.ts b/packages/metadata-protocol/src/seed-loader-injected-owner-reference.test.ts new file mode 100644 index 00000000000..75f3f9ddaf4 --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-injected-owner-reference.test.ts @@ -0,0 +1,103 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33791] `buildDependencyGraph` reads the injected `owner_id` as the person + * lookup it is, on the AUTHORED definition the metadata service serves. + * + * The metadata service answers an object as its author wrote it. An object + * that relies on the platform's `owner_id` declares no such field: the column + * is added at registration by objectql's system-field pass, which reads + * `resolveInjectedSystemColumns`. A graph built from the declared fields alone + * therefore had no reference for `owner_id`, and a seed naming a person there + * (`owner_id: 'Zhang Wei'`) was written as that text, while a declared + * `Field.user()` on the same row resolved the same name to the user's id. + * + * ⛔ The assertions are on the `references` row, the thing resolution maps over; + * the defect never threw. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { SeedLoaderService } from './seed-loader.js'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** + * The metadata service serves the authored definitions; the engine has no + * schema registry, so nothing enriched can stand in for them. + */ +const graphOver = (authored: Record, names: string[]) => { + const metadata = { getObject: vi.fn(async (name: string) => authored[name]) } as unknown as IMetadataService; + const engine = {} as unknown as IDataEngine; + return new SeedLoaderService(engine, metadata, createLogger()).buildDependencyGraph(names); +}; + +const referencesOf = async (definition: Record) => + (await graphOver({ [definition.name as string]: definition }, [definition.name as string])).nodes[0].references; + +const invoice = (extra: Record = {}) => ({ + name: 'crm_invoice', + fields: { name: { type: 'text' }, amount: { type: 'number' } }, + ...extra, +}); + +describe('[#33791] the injected owner column is a person reference in the seed graph', () => { + it('an object that declares no owner_id still gets an owner_id reference to sys_user, shaped like a declared lookup', async () => { + const references = await referencesOf(invoice()); + expect(references).toEqual([ + { field: 'owner_id', targetObject: 'sys_user', targetField: 'name', fieldType: 'lookup', multiple: undefined }, + ]); + }); + + it('it takes the same row a declared sys_user lookup named owner_id takes', async () => { + const injected = await referencesOf(invoice()); + const declared = await referencesOf(invoice({ + fields: { name: { type: 'text' }, amount: { type: 'number' }, owner_id: { type: 'lookup', reference: 'sys_user' } }, + })); + expect(injected).toEqual(declared); + }); + + it('a declared owner_id wins: one reference, the author’s own type', async () => { + const references = await referencesOf(invoice({ + fields: { name: { type: 'text' }, owner_id: { type: 'user' } }, + })); + expect(references).toEqual([ + { field: 'owner_id', targetObject: 'sys_user', targetField: 'name', fieldType: 'user', multiple: undefined }, + ]); + }); + + it('a declared owner_id that is not a reference stays the author’s plain column', async () => { + expect(await referencesOf(invoice({ fields: { name: { type: 'text' }, owner_id: { type: 'text' } } }))).toEqual([]); + }); + + // ── The boundary: every object the system-field pass gives no owner_id. + it.each([ + ['ownership: org', invoice({ ownership: 'org' })], + ['ownership: none', invoice({ ownership: 'none' })], + ['ownership: business_unit', invoice({ ownership: 'business_unit' })], + ['systemFields: false', invoice({ systemFields: false })], + ['managedBy', invoice({ managedBy: 'engine-owned' })], + ['a sys_ object', { name: 'sys_ledger', fields: { name: { type: 'text' } } }], + ])('%s: no owner column is injected, so no owner reference appears', async (_label, definition) => { + expect(await referencesOf(definition)).toEqual([]); + }); + + it('orders sys_user before the object when both are seeded, with no cycle', async () => { + const graph = await graphOver( + { + sys_user: { name: 'sys_user', managedBy: 'better-auth', fields: { name: { type: 'text' }, email: { type: 'text' } } }, + crm_account: { name: 'crm_account', fields: { name: { type: 'text' } } }, + crm_invoice: invoice({ fields: { name: { type: 'text' }, account: { type: 'lookup', reference: 'crm_account' } } }), + }, + ['crm_invoice', 'crm_account', 'sys_user'], + ); + expect(graph.nodes.find((n) => n.object === 'crm_invoice')?.dependsOn).toEqual(['crm_account', 'sys_user']); + expect(graph.nodes.find((n) => n.object === 'sys_user')?.dependsOn).toEqual([]); + expect(graph.circularDependencies).toEqual([]); + const at = (name: string) => graph.insertOrder.indexOf(name); + expect(at('sys_user')).toBeLessThan(at('crm_invoice')); + expect(at('crm_account')).toBeLessThan(at('crm_invoice')); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 08d570ab67f..811047510bd 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -20,6 +20,8 @@ import { isTenancyDisabled, referenceTargetOf, resolveInjectedSystemColumns, + // [#33791] The injected `owner_id`'s own definition, the one the registry adds. + OWNER_FIELD_DEF, // [#24624] The ONE declaration of which field types the engine masks on read // (and which `managedBy` buckets exempt them), and the mask itself (ADR-0100). isMaskedOnReadFieldType, @@ -29,7 +31,7 @@ import { RAW_FILE_VALUES_CONTEXT_KEY, } from '@objectstack/spec/data'; import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel'; -import { SystemObjectName } from '@objectstack/spec/system'; +import { SystemFieldName, SystemObjectName } from '@objectstack/spec/system'; import { resolveSeedRecord } from '@objectstack/formula'; import { bulkWrite, withTransientRetry, defaultIsTransientError, type BulkWriteRowResult, runWithAdvisoryAggregation, type AdvisoryGroup, @@ -509,6 +511,34 @@ function seedRowTenantColumn(definition: unknown): string | null { return resolveInjectedSystemColumns(definition).tenant ? DEFAULT_TENANT_FIELD : null; } +/** + * [#33791] The fields the seed reference graph reads for one object: the ones + * 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 + * `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 + * person field on the same row resolved. With it, the injected owner is a + * reference exactly as a declared `sys_user` lookup named `owner_id` is: the + * same resolution, the same organization-scoped membership probe, and NULL with + * the same "not a member" error for a person outside the load's organization. + * + * A declared `owner_id` is the author's and wins, whatever its type (the + * registry lets it win too). An object the pass gives no owner (`ownership: + * 'org' | 'none' | 'business_unit'`, `managedBy`, a `sys_*` name, + * `systemFields: false`) gets nothing added. + */ +function seedReferenceGraphFields(definition: { fields: Record }): Record { + const fields = definition.fields; + if (Object.prototype.hasOwnProperty.call(fields, SystemFieldName.OWNER_ID)) return fields; + if (!resolveInjectedSystemColumns(definition).owner) return fields; + return { ...fields, [SystemFieldName.OWNER_ID]: OWNER_FIELD_DEF }; +} + /** [ADR-0131 D9] Does a seed row of this object need an organization? See {@link seedRowTenantColumn}. */ function seedRowNeedsOrganization(definition: unknown): boolean { return seedRowTenantColumn(definition) !== null; @@ -1290,7 +1320,8 @@ export class SeedLoaderService implements ISeedLoaderService { const references: ReferenceResolutionParsed[] = []; if (objDef && objDef.fields) { - const fields = objDef.fields as Record; + // [#33791] The declared fields plus the injected `owner_id`. + const fields = seedReferenceGraphFields(objDef) as Record; for (const [fieldName, fieldDef] of Object.entries(fields)) { if (fieldDef.type === 'lookup' || fieldDef.type === 'master_detail' || fieldDef.type === 'user') { // [#18550] The read goes through the ONE arbiter, which also From 76f8f8b1e12b65607ba7809bf34ad74aac5c42f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:27:04 +0000 Subject: [PATCH 3/5] chore(changeset): seed owner_id resolution on the injected owner column Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .changeset/33791-seed-injected-owner-reference.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/33791-seed-injected-owner-reference.md diff --git a/.changeset/33791-seed-injected-owner-reference.md b/.changeset/33791-seed-injected-owner-reference.md new file mode 100644 index 00000000000..6c0d6f0bfce --- /dev/null +++ b/.changeset/33791-seed-injected-owner-reference.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): a seed `owner_id` naming a person resolves on an object that relies on the injected owner column + +Clause-②: no +Metadata-protocol: none + +The seed loader builds its reference graph from the object definition the metadata service serves, which is the one the author wrote. An object that does not declare `owner_id` gets the column from the platform at registration, so the graph had no reference for it. A seed value naming a person there (`owner_id: 'Zhang Wei'`) was stored as that text, with no error and no log line, while a declared person field on the same row (`Field.user()`, `Field.lookup('sys_user')`) resolved the same name to the user's id. This happened on every load: the single-organization boot, the per-organization replay, the organization-create replay and a package install into an organization. + +The graph now reads the injected `owner_id` as the `sys_user` lookup the platform registers. The value resolves like any person reference: across the database on a load with no organization, and through the organization's membership on an organization's own load. A person who is not a member of that organization is not resolved. The column is left NULL, and the load reports the same "not a member of organization" error a declared person field gets. The first-admin handoff can then claim the NULL owner. Before, a row with the name stored as text stayed owned by a user id that does not exist, and the handoff never claimed it because the value was not NULL. + +A declared `owner_id` is unchanged: the author's field is read as before, whatever its type. An object that gets no injected owner (`ownership: 'org'`, `'none'` or `'business_unit'`, `managedBy`, a `sys_*` name, `systemFields: false`) gets no owner reference added. This change itself rewrites no stored row: a row that already holds a name in `owner_id` keeps it until a later seed write or an edit sets its owner. From 655dd0d1ddb94964ef9a529d80e6eb935d887a91 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:51:46 +0000 Subject: [PATCH 4/5] test(metadata-protocol): scope the carrier and implicit-target graph pins to the declared field Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../seed-loader-implicit-reference-target.test.ts | 8 +++++++- .../src/seed-loader-reference-carrier.test.ts | 14 +++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/seed-loader-implicit-reference-target.test.ts b/packages/metadata-protocol/src/seed-loader-implicit-reference-target.test.ts index bbb3cfc7ce1..ec45111569a 100644 --- a/packages/metadata-protocol/src/seed-loader-implicit-reference-target.test.ts +++ b/packages/metadata-protocol/src/seed-loader-implicit-reference-target.test.ts @@ -58,8 +58,14 @@ const taskWith = (owner: Record) => ({ const graphOver = (schemas: Record, names: string[] = ['crm_account', 'crm_task']) => new SeedLoaderService(engineWith(schemas), emptyMetadata(), createLogger()).buildDependencyGraph(names); +/** + * The references `crm_task` derives from its DECLARED fields. [#33791] It is a + * user-owned object, so the graph also carries a row for the `owner_id` the + * platform injects on it; these cases judge the declared `owner` field only. + */ const referencesOf = async (schemas: Record, names?: string[]) => - (await graphOver(schemas, names)).nodes.find((n) => n.object === 'crm_task')?.references ?? []; + ((await graphOver(schemas, names)).nodes.find((n) => n.object === 'crm_task')?.references ?? []) + .filter((r) => r.field !== 'owner_id'); describe('[#19289] seed dependency graph — a `user` field takes its target from the TYPE', () => { it('a `{ type: "user" }` field with NO `reference` still produces a reference row targeting `sys_user`', async () => { diff --git a/packages/metadata-protocol/src/seed-loader-reference-carrier.test.ts b/packages/metadata-protocol/src/seed-loader-reference-carrier.test.ts index 4cc9e8bd6ff..18f0592292a 100644 --- a/packages/metadata-protocol/src/seed-loader-reference-carrier.test.ts +++ b/packages/metadata-protocol/src/seed-loader-reference-carrier.test.ts @@ -58,6 +58,14 @@ const bookWith = (carrier: Record) => ({ }, }); +/** + * [#33791] The references `book` derives from its DECLARED fields. `book` is a + * user-owned object, so the graph also carries a row for the `owner_id` the + * platform injects on it; these cases judge the declared carrier, not that row. + */ +const declaredReferencesOf = (node: { references: T[] } | undefined) => + node?.references.filter((r) => r.field !== 'owner_id'); + const graphOver = (schemas: Record) => new SeedLoaderService(engineWith(schemas), emptyMetadata(), createLogger()).buildDependencyGraph(['author', 'book']); @@ -68,7 +76,7 @@ describe('[#18550] seed dependency graph — an unreadable `reference` carrier i const graph = await graphOver({ author, book: bookWith({ reference: 'author' }) }); const book = graph.nodes.find((n) => n.object === 'book'); expect(book?.dependsOn).toEqual(['author']); - expect(book?.references.map((r) => r.targetObject)).toEqual(['author']); + expect(declaredReferencesOf(book)?.map((r) => r.targetObject)).toEqual(['author']); expect(graph.insertOrder.indexOf('author')).toBeLessThan(graph.insertOrder.indexOf('book')); }); @@ -103,7 +111,7 @@ describe('[#18550] seed dependency graph — an unreadable `reference` carrier i const graph = await graphOver({ author, book: bookWith(carrier) }); const book = graph.nodes.find((n) => n.object === 'book'); expect(book?.dependsOn).toEqual([]); - expect(book?.references).toEqual([]); + expect(declaredReferencesOf(book)).toEqual([]); }); it('the type gate stays FIRST: a `text` field carrying a stray `reference` is not read, so not refused', async () => { @@ -119,6 +127,6 @@ describe('[#18550] seed dependency graph — an unreadable `reference` carrier i }, }; const graph = await graphOver({ author, book: strayCarrier }); - expect(graph.nodes.find((n) => n.object === 'book')?.references).toEqual([]); + expect(declaredReferencesOf(graph.nodes.find((n) => n.object === 'book'))).toEqual([]); }); }); From 0a56c2584c01eeda438345e441b2ab587fba3e65 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:32:42 +0000 Subject: [PATCH 5/5] test(runtime): the graph tracks the injected owner reference beside a declared lookup Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- packages/runtime/src/seed-loader.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/seed-loader.test.ts b/packages/runtime/src/seed-loader.test.ts index 2d3c840669d..c0f3ecf1a84 100644 --- a/packages/runtime/src/seed-loader.test.ts +++ b/packages/runtime/src/seed-loader.test.ts @@ -265,9 +265,13 @@ describe('SeedLoaderService', () => { // dependsOn should be empty (account not in graph) expect(graph.nodes[0].dependsOn).toEqual([]); - // But references should still be tracked (for DB resolution) - expect(graph.nodes[0].references).toHaveLength(1); - expect(graph.nodes[0].references[0].targetObject).toBe('account'); + // But references should still be tracked (for DB resolution): the + // declared lookup, and [#33791] the `owner_id` the platform injects on a + // user-owned object (`sys_user` is not in the graph either). + expect(graph.nodes[0].references.map((r) => [r.field, r.targetObject])).toEqual([ + ['account_id', 'account'], + ['owner_id', 'sys_user'], + ]); expect(graph.insertOrder).toEqual(['contact']); });