Skip to content
Merged
14 changes: 14 additions & 0 deletions .changeset/33791-seed-injected-owner-reference.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,14 @@ const taskWith = (owner: Record<string, unknown>) => ({
const graphOver = (schemas: Record<string, unknown>, 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<string, unknown>, 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 () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown>, 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<string, unknown>) =>
(await graphOver({ [definition.name as string]: definition }, [definition.name as string])).nodes[0].references;

const invoice = (extra: Record<string, unknown> = {}) => ({
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'));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ const bookWith = (carrier: Record<string, unknown>) => ({
},
});

/**
* [#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 = <T extends { field: string }>(node: { references: T[] } | undefined) =>
node?.references.filter((r) => r.field !== 'owner_id');

const graphOver = (schemas: Record<string, unknown>) =>
new SeedLoaderService(engineWith(schemas), emptyMetadata(), createLogger()).buildDependencyGraph(['author', 'book']);

Expand All @@ -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'));
});

Expand Down Expand Up @@ -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 () => {
Expand All @@ -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([]);
});
});
35 changes: 33 additions & 2 deletions packages/metadata-protocol/src/seed-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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<string, unknown> }): Record<string, unknown> {
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;
Expand Down Expand Up @@ -1290,7 +1320,8 @@ export class SeedLoaderService implements ISeedLoaderService {
const references: ReferenceResolutionParsed[] = [];

if (objDef && objDef.fields) {
const fields = objDef.fields as Record<string, any>;
// [#33791] The declared fields plus the injected `owner_id`.
const fields = seedReferenceGraphFields(objDef) as Record<string, any>;
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
Expand Down
10 changes: 7 additions & 3 deletions packages/runtime/src/seed-loader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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<string, unknown> };
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' } });
});
});
Loading