Skip to content

Commit 47a3b95

Browse files
fix(metadata-protocol)!: an organization's seed load resolves people through its membership, reports a refused reference probe, and writes as that organization (#33222)
domain:server#7 · os-tesla · session_01L9qibzSAkofrHDU1U8yFeA <!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoSLDKWQ8v7cxY9uDGijfncD)_ Fixes #33207 Fixes #33206 Clause-②: yes (narrowing) — narrowed: under a walled tenancy posture (`isolated` or `group`), every read and by-id write a seed write performs or triggers (a hook's `ctx.api` read, the engine's own reads on that row, the loader's update of an existing row and its pass-2 back-fill) is scoped to the organization the row is written as, where it reached every organization's rows. Widened: on a load for one organization, a person reference resolves to a member of that organization, `sys_organization` to the load's own, an object no organization walls (no `organization_id` column and no tenant field) across organizations, and a hook on a seeded row sees the organization the row is written as. Nothing that resolved before stops resolving; no load that succeeded is refused. Metadata-protocol: none **Contract review at CONTRACT_REVIEW_TIER (narrowing):** round 1 FAIL on `3c36f9c6e` (one must-fix, two should-fix, three nits). The fixes are on this head; the same reviewer owes the delta review before the seat lands it. ## 维护者速读 - 改了什么:按组织回放种子数据时,人员引用改为只在该组织成员中解析(非成员绝不借用);被数据库拒绝的引用查询如实报出;种子写入带上行所属组织,hook 能看到 `organizationId`。 - 为什么改:下游应用在 18.4.0 上发现,演示数据里的负责人全部落空、依赖组织的 system hook 什么也算不出,样例数据无法作为标准种子交付。 - 风险与回滚:BREAKING——walled 模式下种子写入触发的 hook 和引擎读取只能看到该行所属组织的数据(此前能看到所有组织);只改 `seed-loader.ts`,回滚即还原该文件。 - 先看:`packages/metadata-protocol/src/seed-loader.ts` 的 `resolveFromDatabase` / `probeScopeOf` / `probeOrganizationMember`,以及 `loadDatasets` 里 `seedOptions` 的赋值。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/seed-org-scoped-references.integration.test.ts`,预期 17 个用例全绿。 - 需要你做的:无,增量合约复审通过后由席位落地。 ## What changes **#33207: references on an organization's own load.** `resolveFromDatabase` AND-scoped every probe with `organization_id`, `sys_user` included. `sys_user` has no such column, so the SQL driver refused the probe (`INVALID_FILTER`), the bare `catch` read it as "no match", and the reference was reported as "no such sys_user row exists". Measured on `main` 6e1ab9b with the real AppPlugin replayer, ObjectQL and SqlDriver: the single-tenant boot resolved `rep: 'Zhang Wei'` to `usr_zhang`; both per-organization replays left it `null`, the member's organization included. Each target is now judged once per load (`probeScopeOf`) from the definition the stamp already reads: 1. carries an `organization_id` column (declared or injected), or cannot be described: filtered to the load's organization, as before; 2. `sys_user`: candidates by the field, read in id order page by page (50 a page) until one holds a `sys_member` row in the load's organization (`probeOrganizationMember`). A same-named person outside it is never used, and "not a member" is said only after every candidate was asked; 3. `sys_organization`: the load's own organization only; 4. no organization column, author-owned (no `managedBy`) and resolving no tenant field at all (`resolveTenantFieldName`, the reading the wall scopes by): global, unscoped. An object walled by another tenant column (`tenancy.tenantField`) and platform-managed tables without the column keep the old probe, and its refusal is now reported. A load with no organization probes unscoped, exactly as before. **The narrowed catch.** A refused probe records its code and the chain moves on. The load is never refused for it. One `warn` per target, field and code per load; the pass-2 error keeps its first sentence and appends the refusal's code (or, for a person outside the organization, that the person is not a member) instead of claiming no row exists. **#33206: the organization in the write context.** `ExecutionContext` has no `organizationId` key: a hook's `session.organizationId` and its `ctx.api` scope are built from `tenantId` (measured: the card's `{ ...SEED_WRITE_EXECUTION_CONTEXT, organizationId }` reaches no hook). The loader now builds its options bag per load: `{ context: { ...SEED_WRITE_EXECUTION_CONTEXT, tenantId } }`, with `tenantId` the organization the load stamps its rows with (`config.organizationId ?? fallbackOrgId`, the seat's ruling on the shape note). A row that supplies its own, different `organization_id` is written as that organization (`writeOptionsFor`): its insert or update, and its pass-2 back-fill, so a walled by-id write finds the row; a batch holds rows of one write organization. `SEED_WRITE_EXECUTION_CONTEXT` is unchanged. A load with no organization, pinned or derived, uses the frozen `SEED_OPTIONS` bag itself. The landed-key ledger insert uses the per-load bag. A pass-2 back-fill whose update answers `null` (the data-engine contract's "matched no row") is reported as a failed back-fill, never counted as resolved. ObjectQL itself already refuses a by-id update it cannot find with a not-found error, which the back-fill reports. `skipTriggers` does not stop hooks: it reaches only the record-change trigger's flow dispatch, and `triggerHooks` skips metadata hooks only on `skipAutomations`. So the card's premise stands: app hooks run on seed writes. ## Tests New `packages/runtime/src/seed-org-scoped-references.integration.test.ts` (real AppPlugin, its walled `seed-replayer` and its `single` inline seed, SeedLoaderService, ObjectQL, SqlDriver over better-sqlite3), 17 cases: - a member of the load organization is resolved (`rep` and `owner_id`); - a same-named person who is not a member is NOT resolved (two people named Wang Fang, one per organization, the other organization's created first; Zhang Wei, a member of North only, is not given to South); - a member among sixty same-named people (more than one page) is found, and "not a member" is said only after all were asked; - a refused probe is reported with its code, once per target, field and code; - a global catalog resolves; an object walled by `tenantField: 'workspace_id'` is not taken for global (another organization's row is not borrowed); the organization table answers only for the load organization; - CONTROL: a tenant-carrying target is still filtered (South's `Globex` is not borrowed by North); - CONTROL: a load with no organization probes unscoped, with no membership asked; - a hook sees the load organization on a replay, a reseed, the `single` boot (sole organization) and a direct pinned load (the install path); - a row that supplies its own organization is written as it, its pass-2 back-fill included (walled posture); - a pass-2 back-fill the write organization cannot see is reported, not counted as resolved; - CONTROL: a load with no organization writes with the seed posture unchanged (`session` equals `{ isSystem, skipTriggers }`); - the declared narrowing: under `isolated` and under `group`, a hook's `ctx.api` read on a seeded row sees only the load organization. And one case in `packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts`: an engine `update` answering `null` on the back-fill is reported at `error` with "matched no row" and is not counted as resolved. <details><summary>Ablations (every negative pin, plus the two positive halves): mutate, rebuild, marker proved in dist/, run, restore</summary> Each leg through `scripts/ablation-replace.mjs` (anchor must hit, restore proved by blob hash), `OS_SKIP_DTS=1 pnpm --filter @objectstack/metadata-protocol build`, `scripts/ablation-dist-preflight.mjs` (marker present in 2 built files), then the file above. | leg | mutation | red | |---|---|---| | A | first candidate taken, membership ignored | non-member NOT resolved | | B | organization filter dropped for tenant targets | CONTROL tenant target; refused probe | | C | refusal swallowed (old bare catch) | refused probe reported | | D | own-organization filter dropped | organization table answers only for the load organization | | E | write context without the organization | replay/reseed hook, `single` hook, install hook, declared narrowing | | F | `sys_user` probed with the organization filter (main) | member resolved; non-member | | G (r1) | one page of candidates only | member among sixty same-named people | | H (r1) | `global` without the tenant-field reading | `workspace_id` object not borrowed | | I (r1) | every row written as the load organization | own-organization row and its back-fill | | J (r1) | back-fill written as the load organization | own-organization row and its back-fill | | E (r1, again) | write context without the organization | the four hook pins, narrowing under `isolated` and `group` | | K (r1) | `null` answer not checked | the unit pin: matched no row | Every leg: `ok restored: blob == HEAD` and `git diff HEAD` empty (r0 legs at blob 337629a, r1 legs at de0e52a / c3371fe). Restore leg r1: rebuilt, markers G H I J E `--absent` from dist/, file 17/17 green, tree clean. </details> <details><summary>Suites and gates</summary> - `pnpm --filter @objectstack/metadata-protocol exec vitest run`: r1 Test Files 339 passed, 9 skipped; Tests 22844 passed, 43 skipped. No existing seed-loader pin needed a change. - `pnpm --filter @objectstack/metadata-protocol typecheck`, `pnpm --filter @objectstack/runtime typecheck` (with `check:test-typecheck`): exit 0, after a declaration build of the runtime closure. - `pnpm lint`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands`: 94 lines, each run with stdin closed. 90 exit 0 on first run; `check:query-options-erasure` (two new untyped probe bags, now typed `EngineQueryOptions`) and `check:test-source-alias` (the pins reach AppPlugin's lazy `@objectstack/metadata` import; now warmed at module top) fixed and exit 0; `check:skill-examples` and `check-plugin-teardown-shape --self-test` refused for a missing prerequisite (spec declarations, a commit outside the shallow clone), both exit 0 once met. `check:dual-build-cjs-loads`: NOT MEASURED, reason: it needs every package's dist/ (a full `pnpm build`); CI's Lint & Repo Gates runs it. - Full dogfood on head `3c36f9c6e` (after merging `origin/main` once), command as CI: build the closure, then `pnpm --filter @objectstack/dogfood test` under the lock (no shard, no path): `VERDICT command-exit 1`, Test Files 1 failed | 463 passed | 3 skipped (467), Tests 6 failed | 3921 passed | 42 skipped (3969). The one red file, `test/rest-route-generation-tombstones.test.ts`, failed every case on `TS7016: Could not find a declaration file for module '@objectstack/spec/api'`: my post-merge rebuild used `OS_SKIP_DTS=1`, so `packages/spec/dist` held no declarations for its tsc fixture. After `pnpm --filter @objectstack/spec build` with declarations, that file: Test Files 1 passed, Tests 10 passed. Nothing in the diff reaches it. - After the merge: the four seed files in `packages/runtime` (this file, `seed-replay-per-organization-identity`, `seed-loader-null-organization-holder-real-driver`, `app-plugin.seed-landed`): Test Files 4 passed, Tests 29 passed. </details> ## Acceptance notes - AppPlugin's no-metadata fallback (a basic insert per record when the metadata service is absent) writes with `SEED_WRITE_OPTIONS`, stamps nothing and has no organization; untouched. - A person resolves through membership only; `sys_member` declares no validity columns today, so "member" is "holds a row in the organization". - Platform-managed tables with no organization column (identity, auth and engine tables other than `sys_user` and `sys_organization`) keep the filtered probe on an organization's load; it is refused and now said once. No scope rule is invented for them. - The `single` boot, a publish and a hot reload probe references unscoped, as before; only their write context gains the sole organization. ## Verification Round 1 (review fixes): two commits on top of `3c36f9c6e`, pushed head `752448bfb`. Round 0 head: `3c36f9c6e` (merge of `origin/main` at `6e1ab9b2`..its tip, three commits, none on the seed loader or the replayer; no open PR touches `seed-loader.ts`). Measured before the change on `main` 6e1ab9b; shape note `server-seat-7/r2026-11-13/out/33207-33206-proposed-shape.md`, accepted by the seat (claim amendments 6871524022 on #33207 and 6871533047 on #33206). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibzSAkofrHDU1U8yFeA --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibzSAkofrHDU1U8yFeA)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fd7b378 commit 47a3b95

5 files changed

Lines changed: 837 additions & 39 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol)!: a seed load for one organization resolves people through membership in that organization, says when a reference lookup was refused, and gives hooks on seeded rows the organization the rows are stamped with
6+
7+
Clause-②: yes (narrowing) — narrowed: under a walled tenancy posture (`isolated` or `group`), every read and by-id write a seed write performs or triggers (a hook's `ctx.api` read, the engine's own reads on that row such as reference checks and roll-ups, and the loader's own update of an existing row and its pass-2 back-fill) is scoped to the organization the row is written as, where it reached every organization's rows. Widened: on a load for one organization (the per-organization replay, a reseed, an install into an organization), a reference to a person (`owner_id`, a `sys_user` lookup) resolves to a person who is a member of that organization, where it never resolved; a reference to `sys_organization` resolves to the load's own organization; a reference to an object no organization walls (no `organization_id` column and no tenant field at all, e.g. `tenancy: { enabled: false }`) resolves across organizations; and a hook on a seeded row now sees the organization the row is stamped with as `ctx.session.organizationId`, on those loads and on every load that stamps the install's sole organization (the boot under `single`, a publish, a hot reload). Nothing that resolved before stops resolving, and no load that succeeded is refused.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) no key of any schema is added, removed, renamed or re-shaped and no stored row changes shape: what moves is which rows a hook reads through its own api while a seed load for one organization writes, so there is nothing for a migration to rewrite and no tombstone -->
11+
12+
**BREAKING** for an app hook that reads through `ctx.api` on a seeded row under a walled tenancy posture and relied on seeing other organizations' rows. A seed load for organization A now writes as organization A: the hook, and every engine read the write triggers, reads what it reads when a person of organization A creates the row through the API. A row that supplies its own `organization_id` is written as that organization instead. The fix: a hook that genuinely needs rows of every organization says so with `ctx.api.sudo()` and filters them itself, as it must on the API path already.
13+
14+
What changes, by load:
15+
16+
- **A reference to a person on an organization's own load.** `sys_user` carries no organization (identity lives above it), so the loader's reference lookup no longer filters it by `organization_id`, which the database refused. It reads the people the natural key names, in id order and page by page, and keeps the first one holding a `sys_member` row in the load's organization. A person who exists but is not a member is never used: the reference stays empty, and only once every person the key names has been asked about does its error say the person is not a member of that organization.
17+
- **Every other reference target** is judged from its registered schema: one with an `organization_id` column is looked up inside the load's organization, as before; `sys_organization` answers only for the load's own organization; an author's object that resolves no tenant field at all has no organization filter. An object walled by another tenant column (`tenancy.tenantField`) and a platform-managed table with no organization column keep the old lookup, and its refusal is now reported.
18+
- **A refused lookup** (an unknown column, an unregistered object, a driver fault) is no longer read as "no match". The load logs it once per target, field and code, keeps going, and the reference's error names the refusal's code instead of saying no such row exists. The load's outcome is unchanged: the reference was unresolved before and stays unresolved.
19+
- **The write context.** Every seed write of a load carries `tenantId` set to the organization the row is written as: the one it supplies itself, else the one the load stamps it with (the one the caller pinned, or the install's sole organization). The shared `SEED_WRITE_EXECUTION_CONTEXT` is unchanged. A load with no organization, pinned or derived, writes with exactly the context it used before.
20+
- **A pass-2 back-fill that lands on no row** (a data engine answering `null` for the by-id update) is reported as a failed back-fill, never counted as resolved.
21+
- **A load with no organization** (the single-tenant boot, a publish, a hot reload) resolves references across the whole database, as before.

‎content/docs/data-modeling/seed-data.mdx‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,26 @@ const contactsSeed = defineSeed(Contact, {
461461
export const SeedData = [accountsSeed, contactsSeed];
462462
```
463463

464+
### References on an organization's own load
465+
466+
A load that seeds one organization (the per-organization replay, a reseed, a
467+
package install into an organization) resolves a natural key **inside that
468+
organization**, by what the target object carries:
469+
470+
| Target | Resolves to |
471+
|:---|:---|
472+
| An object with an `organization_id` column (every business object) | a row of the load's organization only; another organization's row with the same key is never used |
473+
| `sys_user` (people: `owner_id`, people lookups) | a person who is a **member** of the load's organization (a `sys_member` row there); a same-named person outside it is never used |
474+
| `sys_organization` | the load's own organization only |
475+
| An object no organization walls: no `organization_id` column and no tenant field (for example `tenancy: { enabled: false }`) | any row: global rows belong to every organization |
476+
| An object walled by another tenant column (`tenancy.tenantField`) with no `organization_id` column | nothing on such a load: the lookup is refused and reported, never answered from another organization |
477+
478+
A load with no organization (the single-tenant boot) resolves across the whole
479+
database, as it always has. When the database refuses a lookup outright (for
480+
example a column the target does not have), the load logs the refusal once,
481+
with its code, and the reference's error says the lookup was refused instead
482+
of claiming the row does not exist.
483+
464484
### Multi-Value Lookups (`multiple: true`)
465485

466486
A lookup declared `multiple: true` stores an **array** of related record ids, so its
@@ -628,6 +648,12 @@ same way. A row someone already owns is never touched.
628648
passes `config.identity`).
629649
- `os.org.id` resolves to the current organization; during a per-tenant replay
630650
it is that tenant's id, falling back to the load's `organizationId`.
651+
- Hooks run on seeded rows (seeds skip only flow automation), and a hook sees
652+
the organization the row is stamped with as `ctx.session.organizationId`,
653+
the same as for a row written through the API (a row that supplies its own
654+
`organization_id` is written as that organization). Under a walled tenancy
655+
posture its `ctx.api` reads, and every engine read the write triggers, are
656+
scoped to that organization. A load with no organization gives hooks none.
631657

632658
### Failure is loud, not silent
633659

‎packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,39 @@ describe('seed deferred back-fill failure is reported, not swallowed (framework#
193193
expect(result.errors.some((e: { field: string }) => e.field === 'head_id')).toBe(true);
194194
});
195195

196+
/**
197+
* #33206 — the data-engine contract lets `update` answer `null` for a by-id
198+
* update that matched no row (the row is gone, or the organization the write
199+
* carries cannot see it). The link was not written, so the back-fill is a
200+
* failure like a thrown one, never counted as resolved.
201+
*/
202+
it('a pass-2 reference update that matched no row (null) is reported, not counted as resolved (#33206)', async () => {
203+
const { engine, store } = createFaithfulEngine();
204+
const metadata = createMetadata();
205+
206+
const realUpdate = (engine.update as any).getMockImplementation();
207+
(engine.update as any).mockImplementation(async (obj: string, data: any, opts: any) => {
208+
if (obj === 'audit_department') return null;
209+
return realUpdate(obj, data, opts);
210+
});
211+
212+
const logger = createLogger();
213+
const result = await new SeedLoaderService(engine, metadata, logger).load({
214+
seeds: SEEDS,
215+
config: CONFIG,
216+
});
217+
218+
expect(store.audit_department.find((r) => r.name === 'Engineering')!.head_id == null).toBe(true);
219+
expect(result.success).toBe(false);
220+
expect(result.errors.some((e: { field: string }) => e.field === 'head_id')).toBe(true);
221+
const line = logger.error.mock.calls
222+
.map((c: unknown[]) => String(c[0]))
223+
.find((m: string) => m.includes('audit_department.head_id'));
224+
expect(line).toContain('matched no row');
225+
const dept = result.results.find((r: { object: string }) => r.object === 'audit_department');
226+
expect(dept?.referencesResolved ?? 0).toBe(0);
227+
});
228+
196229
/**
197230
* #4729 — the LOG LEVEL has to agree with the count.
198231
*

0 commit comments

Comments
 (0)