Skip to content

Commit d0348cf

Browse files
fix(runtime): an un-walled boot seed's person references resolve to the first admin once that admin exists (#34516)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi96QpUuH77yeiDEFd5Vi6Pg1)_ Fixes #34458 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:单租户(未开组织隔离墙)首次启动时,种子数据里指向首个管理员的人员字段(负责人、审核人等)在管理员账号创建后会被自动补上,不再永久留空。 - 为什么改:种子先于首个管理员落库,人员引用解析不到就写成空;此前只有 owner_id 会被交接,示例记录的负责人、审核人一直显示为"未分配",后续启动也不会修复。 - 风险与回滚:只回填种子自己写入、且该列仍为空的行;访客写的行和期间被人手动改过的值都不动。回滚即 revert 本 PR,已回填的值保留,不影响其它数据。 - 先看:packages/runtime/src/app-plugin.ts 的 registerSeedPersonReferenceHandoff(sys_user 插入后触发);packages/metadata-protocol/src/seed-loader.ts 的 resolveHeldPersonReferences(按行 id 加列为空条件写入);packages/plugins/organizations/src/default-organization-seed-owner.wall.test.ts。 - 两分钟验证:pnpm --filter @objectstack/organizations exec vitest run src/default-organization-seed-owner.wall.test.ts,预期 5 个用例全绿,未开墙用例里 assignee、reviewer、owner_id 都等于管理员 id。 - 需要你做的:无,席位落地。 ## What changes On an un-walled (single-tenant) first boot the inline boot seed loads before the first admin's `sys_user` row exists, so a `Field.user()` / `Field.lookup('sys_user')` value naming that admin landed NULL. The first-admin handoff (`claimSeedOwnership`) writes `owner_id` only, and a later boot's replay of a create-only dataset leaves an existing row as it is, so `assignee` / `reviewer` style columns stayed NULL for good. - `packages/metadata-protocol/src/seed-loader.ts`: pass 2 now holds each person reference it left NULL (target `sys_user`, row id known) as a `HeldPersonReference`. New `SeedLoaderService#resolveHeldPersonReferences()` retries them with the loader's own `resolveReferenceItem` (same organization), and writes a resolved value with a compare-and-set update by row id and `FIELD = null`. So a row the seed did not write is never reached (ADR-0138 D1), and a value set since is kept. Retries are serialized. A reference that still misses stays held. `heldPersonReferenceCount()` reports how many are held. The held list resets per `load`. - `packages/runtime/src/app-plugin.ts`: after the inline boot seed, `AppPlugin` keeps the loader while it holds references. A new ObjectQL middleware (`registerSeedPersonReferenceHandoff`) runs the retry after every `sys_user` create/insert and releases the loader once it holds none. Failure is best-effort and logged at `warn`, like the tenancy handoff beside it. The user insert always stands. - The walled boot is unchanged: it writes no inline seed, and its per-organization replay already waits for the owner's membership (#34457). - No change under `packages/spec/src/**`; no contract change. The new loader methods are on the concrete `SeedLoaderService` class and are not part of `ISeedLoaderService`. - Changeset `.changeset/34458-unwalled-seed-person-refs.md`: `patch` on `@objectstack/metadata-protocol` and `@objectstack/runtime`. ## Tests `packages/plugins/organizations/src/default-organization-seed-owner.wall.test.ts`. This is the forced test change the card names: - The CONTROL describe is flipped as the card's Done-when requires. It was titled `control: the same seed on an un-walled boot reads as it did before the fix` and asserted `assignee: null, reviewer: null, owner_id: adminId`. It is now titled `the same seed on an un-walled boot resolves the first admin once that admin exists` and asserts `assignee`, `reviewer` and `owner_id` all equal the admin id. - New describe `un-walled: a held seed person reference fills only the seed's own rows, and only while still NULL`. Its PREMISE leg shows the reference is NULL before the named person signs up, and that the admin's insert did not fill it. Its main leg covers three rows. The seed's row resolves to the late person once they exist. A seeded row assigned by hand in the meantime keeps that assignment. A guest-written row with a NULL person stays NULL (the ADR-0138 D1 negative leg). Ablation (one-shot, not kept). The handoff's loader read in `app-plugin.ts` was replaced with an always-undefined read through `scripts/ablation-replace.mjs`. The marker was proved in `packages/runtime/dist` with `ablation-dist-preflight.mjs` (exit 0) after a rebuild. The organizations suite then went red on exactly the two new/flipped legs: `Tests 2 failed | 3 passed (5)`. Restore leg: blob hash equal to HEAD, rebuild, preflight `--absent` exit 0, then `Tests 5 passed (5)`. <details><summary>Suite readings (locked runs, on e2ab3fd; the later merge of origin/main 6c7d730 touches none of these packages)</summary> - `pnpm --filter @objectstack/metadata-protocol test`: exit 0, `Test Files 346 passed | 9 skipped (355)`, `Tests 22968 passed | 45 skipped (23013)` - `pnpm --filter @objectstack/organizations test`: exit 0, `Test Files 20 passed (20)`, `Tests 264 passed (264)` - `pnpm --filter @objectstack/runtime test`: exit 0, `Test Files 609 passed (609)`, `Tests 11271 passed | 19 skipped (11290)` - `pnpm --filter @objectstack/metadata-protocol --filter @objectstack/runtime --filter @objectstack/organizations typecheck`: VERDICT command-exit 0, all three `Done` - Focused re-run after the last code commit (build metadata-protocol + runtime, wall test, three seed-loader suites): VERDICT command-exit 0; wall test `Tests 5 passed (5)`; seed-loader suites `Tests 58 passed (58)` </details> <details><summary>Ablation readings</summary> - Mutation leg: anchor hit (injected marker count 1, original line count 0), `pnpm --filter @objectstack/runtime build` exit 0, `ablation-dist-preflight.mjs @objectstack/runtime '__ABLATION_34458__'` exit 0. Wall test: `× the wall is down, the seed landed once before the admin existed, and every person reference naming the admin resolves to the admin`, `× the seed's NULL reference resolves to the person once they exist; the guest row and the hand assignment stand`, `Tests 2 failed | 3 passed (5)`. - Restore leg: restored blob equals the HEAD blob, rebuild exit 0, preflight `--absent`: marker absent from all 12 built files, then `Test Files 1 passed (1)`, `Tests 5 passed (5)`. </details> ## Acceptance notes - The held references live in process memory. If the process restarts between the boot seed and the first admin's sign-up, the references are not retried. This PR covers the case the card names and the tests drive, where the first admin's `sys_user` row is inserted by the same process that ran the boot seed. A restart before sign-up was not measured. A durable retry would need the seed-settlement contract to carry the held references, which is a spec change this card does not take. Filed: #34542. - The retry runs after every `sys_user` insert only while the loader still holds references; once none are held, the middleware returns at its first check. - The pass-2 `UNRESOLVED` error text still says "No further seed pass retries this". That remains literally true, since the held retry is not a seed pass, and its SCOPE clause already says a later boot step can still write the column. Dropped: the sentence is still literally true, because the held retry is a write after the seed, not a seed pass. - `packages/metadata-protocol/src/seed-loader.ts` overlaps open PR #34429: `git merge-tree --write-tree HEAD refs/pull/34429/head` at 2a00228 exits 0 (tree 0e6916848), with no conflict. ## Verification Gate sweep: `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 72 families for this diff. Each was run with stdin closed and its exit code captured before any pipe. Reconciliation with `--ran` reports `72 derived, 72 run, 0 NOT-MEASURED, 0 UNRUN`. Two families first answered exit 3 (PREREQUISITE NOT MET) and were re-run once the prerequisite was met. `check-plugin-teardown-shape --self-test` needed its pinned fixture commit fetched, then exited 0 with 48 cases. `check:dual-build-cjs-loads` needed every package built, then exited 0 with 124 entry points across 72 packages. <details><summary>Head and gate provenance</summary> - Lines 1 to 67 of the sweep ran on e2ab3fd. The run was interrupted by a container restart and resumed. The last 5 families and the two re-runs ran on 0916d33, which is e2ab3fd plus a merge of origin/main 6c7d730. That merge touches none of the 4 files of this diff, and the re-derivation on 0916d33 lists the same 72 commands. - `check:type-check-debt`: exit 0, 0 ledger entries re-measured, 0 raw tsc errors. - CI has not been awaited; its check-runs are the record for the families CI runs. </details> <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRXuRn93HphKp7kXEz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1a30a17 commit d0348cf

4 files changed

Lines changed: 297 additions & 9 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
Clause-②: no
7+
Metadata-protocol: none
8+
9+
fix(runtime): on an un-walled first boot, a seed person reference naming the first admin resolves to that admin
10+
11+
A single-tenant install loads its boot seed before the first admin's `sys_user` row exists. A `Field.user()` or `Field.lookup('sys_user')` value naming that admin therefore landed NULL, and the first-admin handoff wrote `owner_id` and no other column. Sample records assigned to the owner showed as unassigned, apart from the record owner. A later boot did not repair them either: a dataset in the default create-only mode leaves an existing row as it is.
12+
13+
The seed loader now holds each person reference its second pass left NULL, together with the row it landed on (`SeedLoaderService#resolveHeldPersonReferences`, `heldPersonReferenceCount`). `AppPlugin` retries the boot seed's held references after every `sys_user` insert. It resolves each one by the loader's own rule and writes it to that row only while the column is still NULL. A row the seed did not write keeps its value (ADR-0138 D1). A seeded row that someone assigned in the meantime keeps that assignment. A reference that still names nobody stays held until the next user insert of the process. The walled boot is unchanged: it writes no inline seed, and its per-organization replay already waits for the owner's membership.

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

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -971,6 +971,14 @@ export class SeedLoaderService implements ISeedLoaderService {
971971
* several parameters away from where the load opens it. Reset per `load`.
972972
*/
973973
private landedKeyLedger?: LandedKeyLedger;
974+
/**
975+
* [#34458] The person references the last {@link load} left NULL because no
976+
* `sys_user` row answered yet, each on a row it landed on. Reset per `load`;
977+
* read and shrunk by {@link resolveHeldPersonReferences}.
978+
*/
979+
private heldPersonReferences: HeldPersonReference[] = [];
980+
/** [#34458] The retry in flight: a second one waits for it, so two never interleave. */
981+
private heldPersonRetry: Promise<unknown> = Promise.resolve();
974982

975983
constructor(engine: IDataEngine, metadata: IMetadataService, logger: Logger, options: SeedLoaderServiceOptions = {}) {
976984
this.engine = engine;
@@ -1006,6 +1014,7 @@ export class SeedLoaderService implements ISeedLoaderService {
10061014
*/
10071015
async load(request: SeedLoaderRequestParsed): Promise<SeedLoaderResultParsed> {
10081016
this.loadProgress = undefined;
1017+
this.heldPersonReferences = [];
10091018
try {
10101019
return await runWithAdvisoryAggregation(
10111020
() => this.loadDatasets(request),
@@ -1016,6 +1025,94 @@ export class SeedLoaderService implements ISeedLoaderService {
10161025
}
10171026
}
10181027

1028+
/** [#34458] How many person references {@link resolveHeldPersonReferences} still holds. */
1029+
heldPersonReferenceCount(): number {
1030+
return this.heldPersonReferences.length;
1031+
}
1032+
1033+
/**
1034+
* [#34458] Retry the person references the last {@link load} left NULL
1035+
* because no `sys_user` row answered yet — the seed that runs before the
1036+
* first admin exists names that admin, and pass 2 is otherwise its last word.
1037+
*
1038+
* Each reference is resolved by the rule pass 2 used ({@link
1039+
* resolveReferenceItem}, the same organization), and a reference that now
1040+
* resolves is written onto the row the load landed on, and only while that
1041+
* column is still NULL: the write is a compare-and-set by the row's id, so a
1042+
* row the seed did not write is never reached (ADR-0138 D1), and a value
1043+
* someone set since is kept. A reference that resolves is released whatever
1044+
* the write matched; one that still misses stays held for the next call.
1045+
* Calls run one after another, never interleaved.
1046+
*/
1047+
resolveHeldPersonReferences(): Promise<{ resolved: number; held: number }> {
1048+
const run = this.heldPersonRetry.then(() => this.retryHeldPersonReferences());
1049+
this.heldPersonRetry = run.catch(() => undefined);
1050+
return run;
1051+
}
1052+
1053+
/** The body of {@link resolveHeldPersonReferences}, one call at a time. */
1054+
private async retryHeldPersonReferences(): Promise<{ resolved: number; held: number }> {
1055+
const pending = this.heldPersonReferences;
1056+
if (pending.length === 0) return { resolved: 0, held: 0 };
1057+
const stillHeld: HeldPersonReference[] = [];
1058+
let resolved = 0;
1059+
for (const held of pending) {
1060+
const items = Array.isArray(held.attemptedValue) ? held.attemptedValue : [held.attemptedValue];
1061+
const values: unknown[] = [];
1062+
let missed = false;
1063+
for (const item of items) {
1064+
if (isMissing(item)) continue;
1065+
const outcome = await this.resolveReferenceItem(held, item, new Map(), { organizationId: held.organizationId });
1066+
if (outcome.status === 'resolved' || outcome.status === 'kept') {
1067+
values.push(outcome.value);
1068+
continue;
1069+
}
1070+
// [#31021] Gone on purpose: no link to write for this element.
1071+
if (outcome.status === 'withdrawn') continue;
1072+
missed = true;
1073+
break;
1074+
}
1075+
if (missed) {
1076+
stillHeld.push(held);
1077+
continue;
1078+
}
1079+
if (values.length === 0) continue;
1080+
try {
1081+
const written = await this.engine.update(
1082+
held.objectName,
1083+
{ [held.field]: held.multiple ? values : values[0] },
1084+
{
1085+
...this.writeOptionsFor(held.rowOrganization),
1086+
where: { id: held.recordId, [held.field]: null },
1087+
multi: true,
1088+
} as any,
1089+
);
1090+
if (typeof written === 'number' && written > 0) resolved += 1;
1091+
} catch (err) {
1092+
stillHeld.push(held);
1093+
const causeSentence = seedFailureCause(err);
1094+
this.logger.error(
1095+
`[SeedLoader] Held person reference back-fill FAILED — ${held.objectName}.${held.field} stays NULL on ` +
1096+
`row '${held.recordId}' although ${held.targetObject}.${held.targetField} = ` +
1097+
`'${this.formatAttempted(held.attemptedValue)}' now resolves. The row itself looks healthy while the ` +
1098+
'person the seed named is missing from it. The write is tried again at the next person insert of ' +
1099+
`this process; fix the error below, or set ${held.field} on that row by hand. ` +
1100+
`${seedCauseLabel(err, causeSentence)}: ${causeSentence}.`,
1101+
err instanceof Error ? err : undefined,
1102+
{ object: held.objectName, field: held.field, recordId: held.recordId },
1103+
);
1104+
}
1105+
}
1106+
this.heldPersonReferences = stillHeld;
1107+
if (resolved > 0) {
1108+
this.logger.info(
1109+
`[SeedLoader] ${resolved} seed person reference(s) left NULL before their person existed now resolve, ` +
1110+
`on rows the seed landed on; ${stillHeld.length} still wait for their person`,
1111+
);
1112+
}
1113+
return { resolved, held: stillHeld.length };
1114+
}
1115+
10191116
/**
10201117
* Record on `err` what this load wrote before it threw (see
10211118
* {@link SeedLoadPartialWrites}) and hand back the error to rethrow — the
@@ -3455,6 +3552,24 @@ export class SeedLoaderService implements ISeedLoaderService {
34553552
: missingProbe?.nonMemberOf
34563553
? `; the ${deferred.targetObject} row that answers to it is not a member of organization ${missingProbe.nonMemberOf}`
34573554
: ''));
3555+
// [#34458] A person can appear after the seed — the first admin signs
3556+
// up after the boot seed ran — so a missed person is held for
3557+
// `resolveHeldPersonReferences`, on the row this load landed on.
3558+
const heldRowId = deferred.internalId
3559+
?? insertedRecords.get(deferred.objectName)?.get(deferred.recordExternalId);
3560+
if (stillUnresolved && deferred.targetObject === SystemObjectName.USER && heldRowId) {
3561+
this.heldPersonReferences.push({
3562+
objectName: deferred.objectName,
3563+
recordId: heldRowId,
3564+
field: deferred.field,
3565+
targetObject: deferred.targetObject,
3566+
targetField: deferred.targetField,
3567+
attemptedValue: deferred.attemptedValue,
3568+
multiple: deferred.multiple === true,
3569+
rowOrganization: deferred.rowOrganization,
3570+
organizationId,
3571+
});
3572+
}
34583573
}
34593574
}
34603575
}
@@ -5118,3 +5233,22 @@ interface DeferredUpdate {
51185233
*/
51195234
rowOrganization?: unknown;
51205235
}
5236+
5237+
/**
5238+
* [#34458] A person reference pass 2 left NULL because no `sys_user` row
5239+
* answered to it yet, on a row this load landed on: the deferral it came
5240+
* from, plus the id of that row and the organization the load probed in.
5241+
* {@link SeedLoaderService.resolveHeldPersonReferences} retries it once a
5242+
* person exists.
5243+
*/
5244+
interface HeldPersonReference {
5245+
readonly objectName: string;
5246+
readonly recordId: string;
5247+
readonly field: string;
5248+
readonly targetObject: string;
5249+
readonly targetField: string;
5250+
readonly attemptedValue: unknown;
5251+
readonly multiple: boolean;
5252+
readonly rowOrganization?: unknown;
5253+
readonly organizationId?: string;
5254+
}

‎packages/plugins/organizations/src/default-organization-seed-owner.wall.test.ts‎

Lines changed: 92 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
* so `owner_id` read right; a `Field.user()` or `Field.lookup('sys_user')`
1616
* column naming the owner stayed NULL.
1717
*
18-
* The control boots the same app un-walled. There the boot seed loads before
19-
* the dev admin exists, so its person columns have nobody to resolve to, and
20-
* only the first-admin handoff writes `owner_id` afterwards. That outcome is
21-
* measured on main and pinned here as it stands: the fix waits only for the
22-
* walled bootstrap's own `default` organization, so the un-walled boot must
23-
* read exactly as before.
18+
* The second leg boots the same app un-walled. There the boot seed loads
19+
* before the dev admin exists, so its person columns have nobody to resolve to
20+
* when the seed runs, and the first-admin handoff writes `owner_id` and no
21+
* other column. The seed loader therefore holds each person reference its last
22+
* pass left NULL, on the row it landed on, and the runtime's AppPlugin retries
23+
* them once a `sys_user` row is inserted, writing each one that now resolves
24+
* while its column is still NULL. So the un-walled boot resolves the owner too,
25+
* through its own moment rather than the walled replay's.
2426
*
2527
* ## What is real
2628
*
@@ -184,7 +186,7 @@ describe('the walled Default Organization’s seed resolves the platform owner i
184186
});
185187
});
186188

187-
describe('control: the same seed on an un-walled boot reads as it did before the fix', () => {
189+
describe('the same seed on an un-walled boot resolves the first admin once that admin exists', () => {
188190
const env = legEnv([
189191
['OS_TENANCY_POSTURE', undefined],
190192
['OS_AUTH_MEMBERSHIP_POLICY', undefined],
@@ -201,12 +203,93 @@ describe('control: the same seed on an un-walled boot reads as it did before the
201203
env.restore();
202204
});
203205

204-
it('the wall is down, the seed landed once before the admin existed, and only the handoff owns the row', async () => {
206+
it('the wall is down, the seed landed once before the admin existed, and every person reference naming the admin resolves to the admin', async () => {
205207
const tenancy: any = await booted.stack.kernel.getServiceAsync('tenancy');
206208
expect(tenancy.isolationActive).toBe(false);
207209
expect(booted.adminId).not.toBe('');
208210
const rows = await ownerTasks(booted.ql, {});
209211
expect(rows).toHaveLength(1);
210-
expect(rows[0]).toMatchObject({ assignee: null, reviewer: null, owner_id: booted.adminId });
212+
expect(rows[0]).toMatchObject({
213+
assignee: booted.adminId,
214+
reviewer: booted.adminId,
215+
owner_id: booted.adminId,
216+
});
217+
});
218+
});
219+
220+
/**
221+
* ADR-0138 D1 on the un-walled handoff. The person the seed names here signs
222+
* up after the boot (and after the dev admin), so the held reference waits
223+
* past the admin's insert and resolves on that person's own insert. Only the
224+
* seed's own rows are reached, and only while their column is still NULL: a
225+
* row the seed did not write keeps the NULL its writer left, and a seeded row
226+
* someone assigned meanwhile keeps that assignment.
227+
*/
228+
describe('un-walled: a held seed person reference fills only the seed’s own rows, and only while still NULL', () => {
229+
const env = legEnv([
230+
['OS_TENANCY_POSTURE', undefined],
231+
['OS_AUTH_MEMBERSHIP_POLICY', undefined],
232+
]);
233+
const LATE_NAME = 'Late Person';
234+
const LATE_EMAIL = 'late.person@example.com';
235+
const LATE_APP = {
236+
...APP,
237+
manifest: { ...APP.manifest, id: 'com.example.seedowner.late' },
238+
data: [
239+
{
240+
object: TASK,
241+
mode: 'upsert',
242+
externalId: 'name',
243+
records: [
244+
{ name: 'Late task', assignee: LATE_NAME },
245+
{ name: 'Late task, assigned meanwhile', assignee: LATE_NAME },
246+
],
247+
},
248+
],
249+
};
250+
let stack: VerifyStack;
251+
let ql: any;
252+
let adminId: string;
253+
let lateId: string;
254+
let beforeSignUp: Array<Record<string, unknown>>;
255+
256+
const taskNamed = async (name: string) => (await ql.find(TASK, { where: { name }, ...SYS }))[0];
257+
258+
beforeAll(async () => {
259+
env.apply();
260+
stack = await bootStack(LATE_APP as never, { extraPlugins: [new OrganizationsPlugin()] });
261+
await stack.signIn();
262+
ql = await stack.kernel.getServiceAsync<any>('objectql');
263+
adminId = String((await ql.findOne('sys_user', { where: { email: ADMIN_EMAIL }, ...SYS }))?.id ?? '');
264+
// A row the seed did not write, with no person: a guest's or a form's.
265+
await ql.insert(TASK, { name: 'Guest task' }, SYS);
266+
// A seeded row someone assigned by hand before the named person arrived.
267+
const meanwhile = await taskNamed('Late task, assigned meanwhile');
268+
await ql.update(TASK, { id: meanwhile.id, assignee: adminId }, SYS);
269+
beforeSignUp = await ql.find(TASK, { where: {}, ...SYS });
270+
await stack.signUp(LATE_EMAIL, undefined, LATE_NAME);
271+
lateId = String((await ql.findOne('sys_user', { where: { email: LATE_EMAIL }, ...SYS }))?.id ?? '');
272+
}, 120_000);
273+
274+
afterAll(async () => {
275+
await stack?.stop();
276+
env.restore();
277+
});
278+
279+
it('PREMISE: before the named person signs up, the seeded reference is NULL and the admin’s insert did not fill it', () => {
280+
expect(adminId).not.toBe('');
281+
expect(lateId).not.toBe('');
282+
const byName = Object.fromEntries(beforeSignUp.map((row) => [row.name, row.assignee]));
283+
expect(byName).toEqual({
284+
'Late task': null,
285+
'Late task, assigned meanwhile': adminId,
286+
'Guest task': null,
287+
});
288+
});
289+
290+
it('the seed’s NULL reference resolves to the person once they exist; the guest row and the hand assignment stand', async () => {
291+
expect((await taskNamed('Late task')).assignee).toBe(lateId);
292+
expect((await taskNamed('Late task, assigned meanwhile')).assignee).toBe(adminId);
293+
expect((await taskNamed('Guest task')).assignee).toBeNull();
211294
});
212295
});

‎packages/runtime/src/app-plugin.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,13 @@ export class AppPlugin implements Plugin {
315315
readonly securityMetadataRegistrar: AppPluginSecurityMetadataRegistrar;
316316
/** [#31382] The host's per-kernel scheduled-work policy for this app's jobs; absent ⇒ the deployment switch. */
317317
private readonly scheduledWorkPolicy: ScheduledWorkPolicySource | undefined;
318+
/**
319+
* [#34458] The inline boot seed's loader while it holds person references
320+
* its pass 2 left NULL because no `sys_user` row answered yet — the first
321+
* admin of a single-tenant install signs up after the boot seed ran. Read
322+
* by {@link registerSeedPersonReferenceHandoff}; released once it holds none.
323+
*/
324+
private heldSeedPersonReferences?: SeedLoaderService;
318325

319326
/**
320327
* `this.bundle` with every package-owned collection resolved across BOTH
@@ -2173,6 +2180,11 @@ export class AppPlugin implements Plugin {
21732180
},
21742181
});
21752182
const result = await seedLoader.load(request);
2183+
// [#34458] A person the seed names who does not exist yet
2184+
// (the first admin) left a NULL; the handoff below
2185+
// resolves it once a `sys_user` row is inserted.
2186+
this.heldSeedPersonReferences =
2187+
seedLoader.heldPersonReferenceCount() > 0 ? seedLoader : undefined;
21762188
// [#23354] Publish the rows this seed landed on BEFORE the
21772189
// source settles, so the seed-ownership claim that runs on
21782190
// `app:seeded` reads them: it hands over these rows and no
@@ -2368,6 +2380,52 @@ export class AppPlugin implements Plugin {
23682380

23692381
this.registerHotReloadSeeder(ctx, ql);
23702382
this.registerSeedTenancyHandoff(ctx, ql);
2383+
this.registerSeedPersonReferenceHandoff(ctx, ql);
2384+
}
2385+
2386+
/**
2387+
* [#34458] Resolve the inline boot seed's person references the moment a
2388+
* person exists to resolve them to.
2389+
*
2390+
* An un-walled boot seed loads before the first admin's `sys_user` row
2391+
* exists, so a `Field.user()` / `Field.lookup('sys_user')` value naming
2392+
* that admin lands NULL and pass 2 reports it unresolved. The first-admin
2393+
* handoff (`claimSeedOwnership`, plugin-security) writes `owner_id` and no
2394+
* other column, and a later boot's replay of a create-only dataset leaves
2395+
* an existing row as it is, so nothing else ever filled those columns.
2396+
*
2397+
* After every `sys_user` insert while the loader holds such references,
2398+
* the loader retries them by its own resolution rule and writes each one
2399+
* that now resolves onto the row the seed landed on, only while that column
2400+
* is still NULL (`SeedLoaderService#resolveHeldPersonReferences`): a row
2401+
* the seed did not write is never touched (ADR-0138 D1), and a value set
2402+
* since is kept. The walled boot writes no inline seed (its per-organization
2403+
* replay waits for the owner's membership instead), so this never holds
2404+
* anything there.
2405+
*/
2406+
private registerSeedPersonReferenceHandoff(ctx: PluginContext, ql: any): void {
2407+
if (!ql || typeof ql.registerMiddleware !== 'function') return;
2408+
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
2409+
await next();
2410+
const loader = this.heldSeedPersonReferences;
2411+
if (!loader) return;
2412+
const isUserCreate =
2413+
opCtx?.object === 'sys_user' &&
2414+
(opCtx?.operation === 'create' || opCtx?.operation === 'insert');
2415+
if (!isUserCreate) return;
2416+
try {
2417+
const { held } = await loader.resolveHeldPersonReferences();
2418+
if (held === 0 && this.heldSeedPersonReferences === loader) this.heldSeedPersonReferences = undefined;
2419+
} catch (e: any) {
2420+
// Best-effort, like the tenancy handoff beside it: the person
2421+
// was just created and that must stand. The references stay
2422+
// held and the next `sys_user` insert retries them; a failed
2423+
// write was already logged at `error` by the loader.
2424+
ctx.logger.warn('[AppPlugin] seed person-reference handoff failed; the next user insert retries it', {
2425+
error: e?.message ?? String(e),
2426+
});
2427+
}
2428+
});
23712429
}
23722430

23732431
/**

0 commit comments

Comments
 (0)