Skip to content

Commit 85f2ac5

Browse files
fix(metadata-protocol): a seed owner_id naming a person resolves on objects that rely on the injected owner column (#34023)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbKnsd8ZLsq9hBbRRm5JvJb2)_ Fixes #33791 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:种子数据加载时,业务对象若依赖平台自动注入的 `owner_id`(自己没声明),种子里写的人名现在会像 `Field.user()` 一样解析成该用户的 id;该人不是本组织成员时留空并报「not a member」错误。 - 为什么改:之前这类对象(多数业务对象,如 HotCRM 的 invoice、payment)会把人名原样存成文本,不报错也不记日志;记录归属于一个不存在的用户,首位管理员接管也认领不到它。 - 风险与回滚:只改种子引用图的构建,声明了 `owner_id` 的对象和不注入 owner 的对象不受影响;已存的文本值不会被本改动改写。回滚即撤回本 PR。 - 先看:`packages/metadata-protocol/src/seed-loader.ts`(`seedReferenceGraphFields` 与 `buildDependencyGraph` 中的一行调用)、`packages/runtime/src/seed-org-scoped-references.integration.test.ts`(桩改为返回作者原始定义 + 新的 #33791 用例组)。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/seed-org-scoped-references.integration.test.ts`,预期 31 个用例全部通过,其中 #33791 组 5 个。 - 需要你做的:无,席位落地。 ## What changes The seed loader builds its reference graph from the definition the metadata service serves, which is the one the author wrote. An object that relies on the platform's `owner_id` does not declare it: objectql's system-field pass adds it at registration. `buildDependencyGraph` read the declared fields only, so a seed `owner_id: 'PERSON NAME'` on such an object was stored as the name itself, while a declared `Field.user()` / `Field.lookup('sys_user')` on the same row resolved. - `seed-loader.ts`: a new `seedReferenceGraphFields(definition)` returns the declared fields plus `owner_id` as `OWNER_FIELD_DEF` (the `sys_user` lookup the registry injects) when `resolveInjectedSystemColumns(definition).owner` is true and the object does not declare `owner_id`. `buildDependencyGraph` iterates that map. A declared `owner_id` wins whatever its type; objects with no injected owner (`ownership: 'org' | 'none' | 'business_unit'`, `managedBy`, a `sys_*` name, `systemFields: false`) are unchanged. The injected owner then takes the same resolution path as a declared person lookup: unscoped on a load with no organization, membership-scoped on an organization's own load, NULL plus the "not a member of organization" error for a non-member. - `seed-org-scoped-references.integration.test.ts`: the metadata stub now serves the as-authored definition (it served `engine.registry.getObject(...)`, the enriched one, which hid this defect). The existing #33207 case that seeds `owner_id: 'Zhang Wei'` on `crm_deal` turned red on `origin/main` once the stub was corrected, and is green with the fix. A new top-level describe pins single boot, walled replay (member, same-name per organization, non-member NULL + error on both `owner_id` and `rep`), the pinned install load, and the no-organization control. - `seed-loader-injected-owner-reference.test.ts` (new): graph-level pins on authored definitions: the injected row, its equality with a declared `sys_user` lookup named `owner_id`, a declared `owner_id` winning, a declared non-reference `owner_id`, the six no-owner boundary objects, and `sys_user` ordering with no cycle. - `seed-loader-reference-carrier.test.ts`, `seed-loader-implicit-reference-target.test.ts`: their fixtures (`book`, `crm_task`) are user-owned objects, so the graph now also carries an `owner_id` row for them. Their assertions judge the declared carrier field, so they now read the declared field's rows only (fixture triage: the fixtures are unchanged; the new row is correct for them). - Changeset: `@objectstack/metadata-protocol` patch. ## Tests All readings below are on head `03ff3585` (after merging `origin/main` at `b8ac0e24`) unless named otherwise. - `@objectstack/metadata-protocol` `pnpm test`: Test Files 343 passed, 9 skipped (352); Tests 22913 passed, 43 skipped. `typecheck`: exit 0. - `@objectstack/runtime` `typecheck`: exit 0. Seed files of the runtime suite (13 files, including `seed-loader.test.ts` and `seed-org-scoped-references.integration.test.ts`): Tests 141 passed. - Full `@objectstack/runtime` `pnpm test` at `655dd0d1` (before the merge): 604 of 605 files passed; the one failure was `seed-loader.test.ts` "should ignore references to objects not in the graph", whose fixture `contact` is user-owned and now also carries the `owner_id` row. Its assertion was updated to name both rows (`account_id` to `account`, `owner_id` to `sys_user`) in `0a56c258`, and the file is green at the final head. - Consumers of `SeedLoaderService` outside these packages, at `655dd0d1`: objectql seed and publish files (13 files, 227 tests), `@objectstack/cloud-connection` `marketplace-install-local*` (56 files, 688 tests), `@objectstack/cli` `seed-record-values-load-parity` (1 test): all passed. ## Acceptance notes - Ruling (card TO) implemented as written: the reference graph treats the injected owner column like a declared `sys_user` lookup; the pin serves the as-authored definition; a non-member resolves to NULL with the "not a member" error, as `rep` does. - The first-admin handoff (`claimSeedOwnership`) claims rows whose `owner_id` is NULL; a non-member's row is now NULL, so it is claimable. Not re-pinned here (outside this file surface); read from `packages/runtime/src/app-plugin.ts`. - `content/docs/data-modeling/seed-data.mdx` already promises this (the target table row for `sys_user`, "people: `owner_id`, people lookups"); its text agrees with the fix, so it is not edited. - Only `owner_id` is added. The audit `*_by` columns and `owning_business_unit_id` are also injected lookups but are readonly and server-stamped; they are not part of this card's ruling and are left as they were. - The card's "related observation" (on a walled boot the organization-create replay runs before the founder's `sys_member` row is written) is out of scope and untouched. - Declaration self-check: `Clause-②: no` and `Metadata-protocol: none` hold. No schema key, accepted value or metadata type moves; a seed that loaded still loads. A non-member name now lands as NULL with a reported error instead of as text, which is the behaviour the 18.5.0 changeset and docs already promised for person references. ## Verification <details><summary>Red first on origin/main (the card's hypothesis H1)</summary> The new pins and the corrected stub, run against the unchanged `origin/main` loader (`64807a9c`) after a closure build: - `seed-loader-injected-owner-reference.test.ts`: 3 failed, 8 passed. `expected [] to deeply equal [ { field: 'owner_id', ... } ]`; `dependsOn` `['crm_account']` instead of `['crm_account', 'sys_user']`. - `seed-org-scoped-references.integration.test.ts`: 5 failed, 26 passed. Single boot: `"owner_id": "Zhang Wei"` stored where `rep` is `"usr_zhang"`. Walled replay: `"owner_id": "Wang Fang"` and `"Zhang Wei"` stored as text. The existing #33207 case that seeds `owner_id` also went red once the stub served the authored definition. With the fix (`seed-loader.ts` built into `dist/`): 11 of 11 and 31 of 31. </details> <details><summary>Ablation (each leg rebuilt; runtime reads metadata-protocol from dist/)</summary> Mutation through `scripts/ablation-replace.mjs`: the guard `if (!resolveInjectedSystemColumns(definition).owner) return fields;` replaced by `if (definition.fields) return fields;` (anchor 1 to 0, blob `811047510bd6` to `ccd9579da705`), then `pnpm --filter @objectstack/metadata-protocol build` and `ablation-dist-preflight.mjs @objectstack/metadata-protocol 'resolveInjectedSystemColumns(definition).owner' --absent`: marker absent from all 24 built files. Result: the graph pins 3 failed of 11 and the runtime pins 5 failed of 31, the same cases as on `origin/main`. Restore: blob back to `811047510bd6` = HEAD, `git diff HEAD` empty, `git status --porcelain` empty; rebuilt, and the preflight in default mode reads the marker present in 1 built file. A first attempt that replaced the call site was refused by the dts build (`TS6133` unused function), so nothing ran on it. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran`: 66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN; every recorded exit code is 0. `check:query-options-erasure` hit a 300 s local timeout under a shared box once and passed on rerun; `check:type-check-debt` ran under the verify lock (re-measure OK, 0 errors above the record). - PR-body gates with this body as the event: `check-changeset-no-major` exit 0, `check-closing-keyword-parity` exit 0, `check-adr-0087-registration` exit 0, `check-empty-changeset` exit 0. - `dispatch-gates --tier`: no path-derived mandate; 254 changed lines. - `git merge-tree --write-tree` against `origin/main`: clean. No open PR touches `seed-loader.ts` or the runtime harness file (59 open PRs read through REST). - Full dogfood battery: not owed (no `!` in the title, no `(narrowing)` arm). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fb3d1ff commit 85f2ac5

7 files changed

Lines changed: 242 additions & 12 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): a seed `owner_id` naming a person resolves on an object that relies on the injected owner column
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.
13+
14+
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.

‎packages/metadata-protocol/src/seed-loader-implicit-reference-target.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,14 @@ const taskWith = (owner: Record<string, unknown>) => ({
5858
const graphOver = (schemas: Record<string, unknown>, names: string[] = ['crm_account', 'crm_task']) =>
5959
new SeedLoaderService(engineWith(schemas), emptyMetadata(), createLogger()).buildDependencyGraph(names);
6060

61+
/**
62+
* The references `crm_task` derives from its DECLARED fields. [#33791] It is a
63+
* user-owned object, so the graph also carries a row for the `owner_id` the
64+
* platform injects on it; these cases judge the declared `owner` field only.
65+
*/
6166
const referencesOf = async (schemas: Record<string, unknown>, names?: string[]) =>
62-
(await graphOver(schemas, names)).nodes.find((n) => n.object === 'crm_task')?.references ?? [];
67+
((await graphOver(schemas, names)).nodes.find((n) => n.object === 'crm_task')?.references ?? [])
68+
.filter((r) => r.field !== 'owner_id');
6369

6470
describe('[#19289] seed dependency graph — a `user` field takes its target from the TYPE', () => {
6571
it('a `{ type: "user" }` field with NO `reference` still produces a reference row targeting `sys_user`', async () => {
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#33791] `buildDependencyGraph` reads the injected `owner_id` as the person
5+
* lookup it is, on the AUTHORED definition the metadata service serves.
6+
*
7+
* The metadata service answers an object as its author wrote it. An object
8+
* that relies on the platform's `owner_id` declares no such field: the column
9+
* is added at registration by objectql's system-field pass, which reads
10+
* `resolveInjectedSystemColumns`. A graph built from the declared fields alone
11+
* therefore had no reference for `owner_id`, and a seed naming a person there
12+
* (`owner_id: 'Zhang Wei'`) was written as that text, while a declared
13+
* `Field.user()` on the same row resolved the same name to the user's id.
14+
*
15+
* ⛔ The assertions are on the `references` row, the thing resolution maps over;
16+
* the defect never threw.
17+
*/
18+
19+
import { describe, it, expect, vi } from 'vitest';
20+
import { SeedLoaderService } from './seed-loader.js';
21+
import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts';
22+
23+
function createLogger() {
24+
return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
25+
}
26+
27+
/**
28+
* The metadata service serves the authored definitions; the engine has no
29+
* schema registry, so nothing enriched can stand in for them.
30+
*/
31+
const graphOver = (authored: Record<string, unknown>, names: string[]) => {
32+
const metadata = { getObject: vi.fn(async (name: string) => authored[name]) } as unknown as IMetadataService;
33+
const engine = {} as unknown as IDataEngine;
34+
return new SeedLoaderService(engine, metadata, createLogger()).buildDependencyGraph(names);
35+
};
36+
37+
const referencesOf = async (definition: Record<string, unknown>) =>
38+
(await graphOver({ [definition.name as string]: definition }, [definition.name as string])).nodes[0].references;
39+
40+
const invoice = (extra: Record<string, unknown> = {}) => ({
41+
name: 'crm_invoice',
42+
fields: { name: { type: 'text' }, amount: { type: 'number' } },
43+
...extra,
44+
});
45+
46+
describe('[#33791] the injected owner column is a person reference in the seed graph', () => {
47+
it('an object that declares no owner_id still gets an owner_id reference to sys_user, shaped like a declared lookup', async () => {
48+
const references = await referencesOf(invoice());
49+
expect(references).toEqual([
50+
{ field: 'owner_id', targetObject: 'sys_user', targetField: 'name', fieldType: 'lookup', multiple: undefined },
51+
]);
52+
});
53+
54+
it('it takes the same row a declared sys_user lookup named owner_id takes', async () => {
55+
const injected = await referencesOf(invoice());
56+
const declared = await referencesOf(invoice({
57+
fields: { name: { type: 'text' }, amount: { type: 'number' }, owner_id: { type: 'lookup', reference: 'sys_user' } },
58+
}));
59+
expect(injected).toEqual(declared);
60+
});
61+
62+
it('a declared owner_id wins: one reference, the author’s own type', async () => {
63+
const references = await referencesOf(invoice({
64+
fields: { name: { type: 'text' }, owner_id: { type: 'user' } },
65+
}));
66+
expect(references).toEqual([
67+
{ field: 'owner_id', targetObject: 'sys_user', targetField: 'name', fieldType: 'user', multiple: undefined },
68+
]);
69+
});
70+
71+
it('a declared owner_id that is not a reference stays the author’s plain column', async () => {
72+
expect(await referencesOf(invoice({ fields: { name: { type: 'text' }, owner_id: { type: 'text' } } }))).toEqual([]);
73+
});
74+
75+
// ── The boundary: every object the system-field pass gives no owner_id.
76+
it.each([
77+
['ownership: org', invoice({ ownership: 'org' })],
78+
['ownership: none', invoice({ ownership: 'none' })],
79+
['ownership: business_unit', invoice({ ownership: 'business_unit' })],
80+
['systemFields: false', invoice({ systemFields: false })],
81+
['managedBy', invoice({ managedBy: 'engine-owned' })],
82+
['a sys_ object', { name: 'sys_ledger', fields: { name: { type: 'text' } } }],
83+
])('%s: no owner column is injected, so no owner reference appears', async (_label, definition) => {
84+
expect(await referencesOf(definition)).toEqual([]);
85+
});
86+
87+
it('orders sys_user before the object when both are seeded, with no cycle', async () => {
88+
const graph = await graphOver(
89+
{
90+
sys_user: { name: 'sys_user', managedBy: 'better-auth', fields: { name: { type: 'text' }, email: { type: 'text' } } },
91+
crm_account: { name: 'crm_account', fields: { name: { type: 'text' } } },
92+
crm_invoice: invoice({ fields: { name: { type: 'text' }, account: { type: 'lookup', reference: 'crm_account' } } }),
93+
},
94+
['crm_invoice', 'crm_account', 'sys_user'],
95+
);
96+
expect(graph.nodes.find((n) => n.object === 'crm_invoice')?.dependsOn).toEqual(['crm_account', 'sys_user']);
97+
expect(graph.nodes.find((n) => n.object === 'sys_user')?.dependsOn).toEqual([]);
98+
expect(graph.circularDependencies).toEqual([]);
99+
const at = (name: string) => graph.insertOrder.indexOf(name);
100+
expect(at('sys_user')).toBeLessThan(at('crm_invoice'));
101+
expect(at('crm_account')).toBeLessThan(at('crm_invoice'));
102+
});
103+
});

‎packages/metadata-protocol/src/seed-loader-reference-carrier.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ const bookWith = (carrier: Record<string, unknown>) => ({
5858
},
5959
});
6060

61+
/**
62+
* [#33791] The references `book` derives from its DECLARED fields. `book` is a
63+
* user-owned object, so the graph also carries a row for the `owner_id` the
64+
* platform injects on it; these cases judge the declared carrier, not that row.
65+
*/
66+
const declaredReferencesOf = <T extends { field: string }>(node: { references: T[] } | undefined) =>
67+
node?.references.filter((r) => r.field !== 'owner_id');
68+
6169
const graphOver = (schemas: Record<string, unknown>) =>
6270
new SeedLoaderService(engineWith(schemas), emptyMetadata(), createLogger()).buildDependencyGraph(['author', 'book']);
6371

@@ -68,7 +76,7 @@ describe('[#18550] seed dependency graph — an unreadable `reference` carrier i
6876
const graph = await graphOver({ author, book: bookWith({ reference: 'author' }) });
6977
const book = graph.nodes.find((n) => n.object === 'book');
7078
expect(book?.dependsOn).toEqual(['author']);
71-
expect(book?.references.map((r) => r.targetObject)).toEqual(['author']);
79+
expect(declaredReferencesOf(book)?.map((r) => r.targetObject)).toEqual(['author']);
7280
expect(graph.insertOrder.indexOf('author')).toBeLessThan(graph.insertOrder.indexOf('book'));
7381
});
7482

@@ -103,7 +111,7 @@ describe('[#18550] seed dependency graph — an unreadable `reference` carrier i
103111
const graph = await graphOver({ author, book: bookWith(carrier) });
104112
const book = graph.nodes.find((n) => n.object === 'book');
105113
expect(book?.dependsOn).toEqual([]);
106-
expect(book?.references).toEqual([]);
114+
expect(declaredReferencesOf(book)).toEqual([]);
107115
});
108116

109117
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
119127
},
120128
};
121129
const graph = await graphOver({ author, book: strayCarrier });
122-
expect(graph.nodes.find((n) => n.object === 'book')?.references).toEqual([]);
130+
expect(declaredReferencesOf(graph.nodes.find((n) => n.object === 'book'))).toEqual([]);
123131
});
124132
});

‎packages/metadata-protocol/src/seed-loader.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import {
2020
isTenancyDisabled,
2121
referenceTargetOf,
2222
resolveInjectedSystemColumns,
23+
// [#33791] The injected `owner_id`'s own definition, the one the registry adds.
24+
OWNER_FIELD_DEF,
2325
// [#24624] The ONE declaration of which field types the engine masks on read
2426
// (and which `managedBy` buckets exempt them), and the mask itself (ADR-0100).
2527
isMaskedOnReadFieldType,
@@ -29,7 +31,7 @@ import {
2931
RAW_FILE_VALUES_CONTEXT_KEY,
3032
} from '@objectstack/spec/data';
3133
import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel';
32-
import { SystemObjectName } from '@objectstack/spec/system';
34+
import { SystemFieldName, SystemObjectName } from '@objectstack/spec/system';
3335
import { resolveSeedRecord } from '@objectstack/formula';
3436
import {
3537
bulkWrite, withTransientRetry, defaultIsTransientError, type BulkWriteRowResult, runWithAdvisoryAggregation, type AdvisoryGroup,
@@ -509,6 +511,34 @@ function seedRowTenantColumn(definition: unknown): string | null {
509511
return resolveInjectedSystemColumns(definition).tenant ? DEFAULT_TENANT_FIELD : null;
510512
}
511513

514+
/**
515+
* [#33791] The fields the seed reference graph reads for one object: the ones
516+
* its definition declares, plus `owner_id` when the system-column pass injects
517+
* it and the object does not declare it.
518+
*
519+
* The definition the loader resolves is the metadata service's, which is what
520+
* the author wrote. An object that relies on the platform's owner has no
521+
* `owner_id` there: objectql adds it at registration, from the same
522+
* `resolveInjectedSystemColumns` plan read here, as {@link OWNER_FIELD_DEF} (a
523+
* `sys_user` lookup). Read from the declared fields alone, a seed value naming
524+
* a person in that column was written as the name itself, while a declared
525+
* person field on the same row resolved. With it, the injected owner is a
526+
* reference exactly as a declared `sys_user` lookup named `owner_id` is: the
527+
* same resolution, the same organization-scoped membership probe, and NULL with
528+
* the same "not a member" error for a person outside the load's organization.
529+
*
530+
* A declared `owner_id` is the author's and wins, whatever its type (the
531+
* registry lets it win too). An object the pass gives no owner (`ownership:
532+
* 'org' | 'none' | 'business_unit'`, `managedBy`, a `sys_*` name,
533+
* `systemFields: false`) gets nothing added.
534+
*/
535+
function seedReferenceGraphFields(definition: { fields: Record<string, unknown> }): Record<string, unknown> {
536+
const fields = definition.fields;
537+
if (Object.prototype.hasOwnProperty.call(fields, SystemFieldName.OWNER_ID)) return fields;
538+
if (!resolveInjectedSystemColumns(definition).owner) return fields;
539+
return { ...fields, [SystemFieldName.OWNER_ID]: OWNER_FIELD_DEF };
540+
}
541+
512542
/** [ADR-0131 D9] Does a seed row of this object need an organization? See {@link seedRowTenantColumn}. */
513543
function seedRowNeedsOrganization(definition: unknown): boolean {
514544
return seedRowTenantColumn(definition) !== null;
@@ -1290,7 +1320,8 @@ export class SeedLoaderService implements ISeedLoaderService {
12901320
const references: ReferenceResolutionParsed[] = [];
12911321

12921322
if (objDef && objDef.fields) {
1293-
const fields = objDef.fields as Record<string, any>;
1323+
// [#33791] The declared fields plus the injected `owner_id`.
1324+
const fields = seedReferenceGraphFields(objDef) as Record<string, any>;
12941325
for (const [fieldName, fieldDef] of Object.entries(fields)) {
12951326
if (fieldDef.type === 'lookup' || fieldDef.type === 'master_detail' || fieldDef.type === 'user') {
12961327
// [#18550] The read goes through the ONE arbiter, which also

‎packages/runtime/src/seed-loader.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,9 +265,13 @@ describe('SeedLoaderService', () => {
265265

266266
// dependsOn should be empty (account not in graph)
267267
expect(graph.nodes[0].dependsOn).toEqual([]);
268-
// But references should still be tracked (for DB resolution)
269-
expect(graph.nodes[0].references).toHaveLength(1);
270-
expect(graph.nodes[0].references[0].targetObject).toBe('account');
268+
// But references should still be tracked (for DB resolution): the
269+
// declared lookup, and [#33791] the `owner_id` the platform injects on a
270+
// user-owned object (`sys_user` is not in the graph either).
271+
expect(graph.nodes[0].references.map((r) => [r.field, r.targetObject])).toEqual([
272+
['account_id', 'account'],
273+
['owner_id', 'sys_user'],
274+
]);
271275
expect(graph.insertOrder).toEqual(['contact']);
272276
});
273277

‎packages/runtime/src/seed-org-scoped-references.integration.test.ts‎

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,15 @@ async function boot(options: BootOptions) {
174174
seen.push({ name: hctx.input?.data?.name, session: hctx.session, rowOrganization: hctx.result?.organization_id });
175175
}, { object: 'crm_deal' });
176176

177+
// The metadata service serves what the author wrote: an object that relies
178+
// on the injected `owner_id` / `organization_id` does not carry them here.
179+
// Only the engine's registry holds the enriched definition (`definitions`
180+
// above), so serving that from the stub would hide every defect of a loader
181+
// that reads the authored definition and forgets an injected column.
177182
const metadata = {
178-
getObject: vi.fn(async (name: string) => definitions.find((d: any) => d.name === name)),
179-
listObjects: vi.fn(async () => definitions),
180-
getObjects: vi.fn(async () => definitions),
183+
getObject: vi.fn(async (name: string) => objects.find((d: any) => d.name === name)),
184+
listObjects: vi.fn(async () => objects),
185+
getObjects: vi.fn(async () => objects),
181186
get: vi.fn(async () => undefined),
182187
list: vi.fn(async () => []),
183188
exists: vi.fn(async () => false),
@@ -642,3 +647,62 @@ describe('a dataset OF a global object (tenancy disabled) replays per organizati
642647
expect((await rowsOf(engine, 'crm_country')).filter((r) => r.name === 'Peru')).toHaveLength(1);
643648
});
644649
});
650+
651+
describe('#33791 the injected owner column resolves like a declared person lookup', () => {
652+
/** `owner_id` and the declared `rep` of each deal, by deal name. */
653+
const peopleOf = (rows: Row[]) =>
654+
Object.fromEntries(rows.map((r) => [r.name, { owner_id: r.owner_id ?? null, rep: r.rep ?? null }]));
655+
656+
it('the harness serves the authored deal, which has no owner_id; the registry injects one', async () => {
657+
const { engine, metadata } = await boot({ posture: 'single', data: [] });
658+
const authored = (await metadata.getObject('crm_deal')) as { fields: Record<string, unknown> };
659+
expect(Object.keys(authored.fields)).not.toContain('owner_id');
660+
expect(Object.keys(engine.registry.getObject('crm_deal')?.fields ?? {})).toContain('owner_id');
661+
});
662+
663+
it('a single boot resolves a member named in owner_id to that member, as it resolves the declared rep', async () => {
664+
const { dealsOf } = await boot({ posture: 'single', data: [deals([{ name: 'Deal 1', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])] });
665+
expect(peopleOf(await dealsOf())).toEqual({ 'Deal 1': { owner_id: 'usr_zhang', rep: 'usr_zhang' } });
666+
});
667+
668+
it('a walled replay resolves a member per organization; a non-member is NULL with the same error rep gets', async () => {
669+
const { replayer, dealsOf } = await boot({
670+
posture: 'isolated',
671+
data: [deals([{ name: 'Deal 1', owner_id: 'Wang Fang', rep: 'Wang Fang' }, { name: 'Deal 2', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])],
672+
});
673+
674+
const north = await replayer!(ORG_NORTH);
675+
const south = await replayer!(ORG_SOUTH);
676+
677+
expect(north.errors).toEqual([]);
678+
expect(peopleOf(await dealsOf(ORG_NORTH))).toEqual({
679+
'Deal 1': { owner_id: 'usr_wang_north', rep: 'usr_wang_north' },
680+
'Deal 2': { owner_id: 'usr_zhang', rep: 'usr_zhang' },
681+
});
682+
// Zhang Wei is not a member of South: neither column borrows him, and the
683+
// owner is NULL (a first-admin handoff can claim it), never his name as text.
684+
expect(peopleOf(await dealsOf(ORG_SOUTH))).toEqual({
685+
'Deal 1': { owner_id: 'usr_wang_south', rep: 'usr_wang_south' },
686+
'Deal 2': { owner_id: null, rep: null },
687+
});
688+
const errors = south.errors as Array<{ message: string; field?: string }>;
689+
expect(errors.map((e) => e.field).sort()).toEqual(['owner_id', 'rep']);
690+
for (const e of errors) expect(e.message).toContain(`not a member of organization ${ORG_SOUTH}`);
691+
});
692+
693+
it('a direct load pinned to an organization (the install path) resolves owner_id through that organization', async () => {
694+
const { engine, metadata, logger, dealsOf } = await boot({ posture: 'isolated', data: [] });
695+
const loader = new SeedLoaderService(engine as any, metadata as any, logger as any);
696+
const result = await loader.load({
697+
seeds: [deals([{ name: 'Installed', owner_id: 'Wang Fang' }])],
698+
config: { multiPass: true, organizationId: ORG_SOUTH },
699+
} as any);
700+
expect(result.errors).toEqual([]);
701+
expect((await dealsOf(ORG_SOUTH))[0].owner_id).toBe('usr_wang_south');
702+
});
703+
704+
it('CONTROL — a load with no organization resolves owner_id unscoped, as it resolves rep', async () => {
705+
const { dealsOf } = await boot({ posture: 'single', organizations: false, data: [deals([{ name: 'Deal 1', owner_id: 'Zhang Wei', rep: 'Zhang Wei' }])] });
706+
expect(peopleOf(await dealsOf())).toEqual({ 'Deal 1': { owner_id: 'usr_zhang', rep: 'usr_zhang' } });
707+
});
708+
});

0 commit comments

Comments
 (0)