Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/34458-unwalled-seed-person-refs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/metadata-protocol': patch
'@objectstack/runtime': patch
---

Clause-②: no
Metadata-protocol: none

fix(runtime): on an un-walled first boot, a seed person reference naming the first admin resolves to that admin

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.

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.
134 changes: 134 additions & 0 deletions packages/metadata-protocol/src/seed-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,14 @@ export class SeedLoaderService implements ISeedLoaderService {
* several parameters away from where the load opens it. Reset per `load`.
*/
private landedKeyLedger?: LandedKeyLedger;
/**
* [#34458] The person references the last {@link load} left NULL because no
* `sys_user` row answered yet, each on a row it landed on. Reset per `load`;
* read and shrunk by {@link resolveHeldPersonReferences}.
*/
private heldPersonReferences: HeldPersonReference[] = [];
/** [#34458] The retry in flight: a second one waits for it, so two never interleave. */
private heldPersonRetry: Promise<unknown> = Promise.resolve();

constructor(engine: IDataEngine, metadata: IMetadataService, logger: Logger, options: SeedLoaderServiceOptions = {}) {
this.engine = engine;
Expand Down Expand Up @@ -1006,6 +1014,7 @@ export class SeedLoaderService implements ISeedLoaderService {
*/
async load(request: SeedLoaderRequestParsed): Promise<SeedLoaderResultParsed> {
this.loadProgress = undefined;
this.heldPersonReferences = [];
try {
return await runWithAdvisoryAggregation(
() => this.loadDatasets(request),
Expand All @@ -1016,6 +1025,94 @@ export class SeedLoaderService implements ISeedLoaderService {
}
}

/** [#34458] How many person references {@link resolveHeldPersonReferences} still holds. */
heldPersonReferenceCount(): number {
return this.heldPersonReferences.length;
}

/**
* [#34458] Retry the person references the last {@link load} left NULL
* because no `sys_user` row answered yet — the seed that runs before the
* first admin exists names that admin, and pass 2 is otherwise its last word.
*
* Each reference is resolved by the rule pass 2 used ({@link
* resolveReferenceItem}, the same organization), and a reference that now
* resolves is written onto the row the load landed on, and only while that
* column is still NULL: the write is a compare-and-set by the row's id, so a
* row the seed did not write is never reached (ADR-0138 D1), and a value
* someone set since is kept. A reference that resolves is released whatever
* the write matched; one that still misses stays held for the next call.
* Calls run one after another, never interleaved.
*/
resolveHeldPersonReferences(): Promise<{ resolved: number; held: number }> {
const run = this.heldPersonRetry.then(() => this.retryHeldPersonReferences());
this.heldPersonRetry = run.catch(() => undefined);
return run;
}

/** The body of {@link resolveHeldPersonReferences}, one call at a time. */
private async retryHeldPersonReferences(): Promise<{ resolved: number; held: number }> {
const pending = this.heldPersonReferences;
if (pending.length === 0) return { resolved: 0, held: 0 };
const stillHeld: HeldPersonReference[] = [];
let resolved = 0;
for (const held of pending) {
const items = Array.isArray(held.attemptedValue) ? held.attemptedValue : [held.attemptedValue];
const values: unknown[] = [];
let missed = false;
for (const item of items) {
if (isMissing(item)) continue;
const outcome = await this.resolveReferenceItem(held, item, new Map(), { organizationId: held.organizationId });
if (outcome.status === 'resolved' || outcome.status === 'kept') {
values.push(outcome.value);
continue;
}
// [#31021] Gone on purpose: no link to write for this element.
if (outcome.status === 'withdrawn') continue;
missed = true;
break;
}
if (missed) {
stillHeld.push(held);
continue;
}
if (values.length === 0) continue;
try {
const written = await this.engine.update(
held.objectName,
{ [held.field]: held.multiple ? values : values[0] },
{
...this.writeOptionsFor(held.rowOrganization),
where: { id: held.recordId, [held.field]: null },
multi: true,
} as any,
);
if (typeof written === 'number' && written > 0) resolved += 1;
} catch (err) {
stillHeld.push(held);
const causeSentence = seedFailureCause(err);
this.logger.error(
`[SeedLoader] Held person reference back-fill FAILED — ${held.objectName}.${held.field} stays NULL on ` +
`row '${held.recordId}' although ${held.targetObject}.${held.targetField} = ` +
`'${this.formatAttempted(held.attemptedValue)}' now resolves. The row itself looks healthy while the ` +
'person the seed named is missing from it. The write is tried again at the next person insert of ' +
`this process; fix the error below, or set ${held.field} on that row by hand. ` +
`${seedCauseLabel(err, causeSentence)}: ${causeSentence}.`,
err instanceof Error ? err : undefined,
{ object: held.objectName, field: held.field, recordId: held.recordId },
);
}
}
this.heldPersonReferences = stillHeld;
if (resolved > 0) {
this.logger.info(
`[SeedLoader] ${resolved} seed person reference(s) left NULL before their person existed now resolve, ` +
`on rows the seed landed on; ${stillHeld.length} still wait for their person`,
);
}
return { resolved, held: stillHeld.length };
}

/**
* Record on `err` what this load wrote before it threw (see
* {@link SeedLoadPartialWrites}) and hand back the error to rethrow — the
Expand Down Expand Up @@ -3455,6 +3552,24 @@ export class SeedLoaderService implements ISeedLoaderService {
: missingProbe?.nonMemberOf
? `; the ${deferred.targetObject} row that answers to it is not a member of organization ${missingProbe.nonMemberOf}`
: ''));
// [#34458] A person can appear after the seed — the first admin signs
// up after the boot seed ran — so a missed person is held for
// `resolveHeldPersonReferences`, on the row this load landed on.
const heldRowId = deferred.internalId
?? insertedRecords.get(deferred.objectName)?.get(deferred.recordExternalId);
if (stillUnresolved && deferred.targetObject === SystemObjectName.USER && heldRowId) {
this.heldPersonReferences.push({
objectName: deferred.objectName,
recordId: heldRowId,
field: deferred.field,
targetObject: deferred.targetObject,
targetField: deferred.targetField,
attemptedValue: deferred.attemptedValue,
multiple: deferred.multiple === true,
rowOrganization: deferred.rowOrganization,
organizationId,
});
}
}
}
}
Expand Down Expand Up @@ -5118,3 +5233,22 @@ interface DeferredUpdate {
*/
rowOrganization?: unknown;
}

/**
* [#34458] A person reference pass 2 left NULL because no `sys_user` row
* answered to it yet, on a row this load landed on: the deferral it came
* from, plus the id of that row and the organization the load probed in.
* {@link SeedLoaderService.resolveHeldPersonReferences} retries it once a
* person exists.
*/
interface HeldPersonReference {
readonly objectName: string;
readonly recordId: string;
readonly field: string;
readonly targetObject: string;
readonly targetField: string;
readonly attemptedValue: unknown;
readonly multiple: boolean;
readonly rowOrganization?: unknown;
readonly organizationId?: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
* so `owner_id` read right; a `Field.user()` or `Field.lookup('sys_user')`
* column naming the owner stayed NULL.
*
* The control boots the same app un-walled. There the boot seed loads before
* the dev admin exists, so its person columns have nobody to resolve to, and
* only the first-admin handoff writes `owner_id` afterwards. That outcome is
* measured on main and pinned here as it stands: the fix waits only for the
* walled bootstrap's own `default` organization, so the un-walled boot must
* read exactly as before.
* The second leg boots the same app un-walled. There the boot seed loads
* before the dev admin exists, so its person columns have nobody to resolve to
* when the seed runs, and the first-admin handoff writes `owner_id` and no
* other column. The seed loader therefore holds each person reference its last
* pass left NULL, on the row it landed on, and the runtime's AppPlugin retries
* them once a `sys_user` row is inserted, writing each one that now resolves
* while its column is still NULL. So the un-walled boot resolves the owner too,
* through its own moment rather than the walled replay's.
*
* ## What is real
*
Expand Down Expand Up @@ -184,7 +186,7 @@ describe('the walled Default Organization’s seed resolves the platform owner i
});
});

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

it('the wall is down, the seed landed once before the admin existed, and only the handoff owns the row', async () => {
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 () => {
const tenancy: any = await booted.stack.kernel.getServiceAsync('tenancy');
expect(tenancy.isolationActive).toBe(false);
expect(booted.adminId).not.toBe('');
const rows = await ownerTasks(booted.ql, {});
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ assignee: null, reviewer: null, owner_id: booted.adminId });
expect(rows[0]).toMatchObject({
assignee: booted.adminId,
reviewer: booted.adminId,
owner_id: booted.adminId,
});
});
});

/**
* ADR-0138 D1 on the un-walled handoff. The person the seed names here signs
* up after the boot (and after the dev admin), so the held reference waits
* past the admin's insert and resolves on that person's own insert. Only the
* seed's own rows are reached, and only while their column is still NULL: a
* row the seed did not write keeps the NULL its writer left, and a seeded row
* someone assigned meanwhile keeps that assignment.
*/
describe('un-walled: a held seed person reference fills only the seed’s own rows, and only while still NULL', () => {
const env = legEnv([
['OS_TENANCY_POSTURE', undefined],
['OS_AUTH_MEMBERSHIP_POLICY', undefined],
]);
const LATE_NAME = 'Late Person';
const LATE_EMAIL = 'late.person@example.com';
const LATE_APP = {
...APP,
manifest: { ...APP.manifest, id: 'com.example.seedowner.late' },
data: [
{
object: TASK,
mode: 'upsert',
externalId: 'name',
records: [
{ name: 'Late task', assignee: LATE_NAME },
{ name: 'Late task, assigned meanwhile', assignee: LATE_NAME },
],
},
],
};
let stack: VerifyStack;
let ql: any;
let adminId: string;
let lateId: string;
let beforeSignUp: Array<Record<string, unknown>>;

const taskNamed = async (name: string) => (await ql.find(TASK, { where: { name }, ...SYS }))[0];

beforeAll(async () => {
env.apply();
stack = await bootStack(LATE_APP as never, { extraPlugins: [new OrganizationsPlugin()] });
await stack.signIn();
ql = await stack.kernel.getServiceAsync<any>('objectql');
adminId = String((await ql.findOne('sys_user', { where: { email: ADMIN_EMAIL }, ...SYS }))?.id ?? '');
// A row the seed did not write, with no person: a guest's or a form's.
await ql.insert(TASK, { name: 'Guest task' }, SYS);
// A seeded row someone assigned by hand before the named person arrived.
const meanwhile = await taskNamed('Late task, assigned meanwhile');
await ql.update(TASK, { id: meanwhile.id, assignee: adminId }, SYS);
beforeSignUp = await ql.find(TASK, { where: {}, ...SYS });
await stack.signUp(LATE_EMAIL, undefined, LATE_NAME);
lateId = String((await ql.findOne('sys_user', { where: { email: LATE_EMAIL }, ...SYS }))?.id ?? '');
}, 120_000);

afterAll(async () => {
await stack?.stop();
env.restore();
});

it('PREMISE: before the named person signs up, the seeded reference is NULL and the admin’s insert did not fill it', () => {
expect(adminId).not.toBe('');
expect(lateId).not.toBe('');
const byName = Object.fromEntries(beforeSignUp.map((row) => [row.name, row.assignee]));
expect(byName).toEqual({
'Late task': null,
'Late task, assigned meanwhile': adminId,
'Guest task': null,
});
});

it('the seed’s NULL reference resolves to the person once they exist; the guest row and the hand assignment stand', async () => {
expect((await taskNamed('Late task')).assignee).toBe(lateId);
expect((await taskNamed('Late task, assigned meanwhile')).assignee).toBe(adminId);
expect((await taskNamed('Guest task')).assignee).toBeNull();
});
});
58 changes: 58 additions & 0 deletions packages/runtime/src/app-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,13 @@ export class AppPlugin implements Plugin {
readonly securityMetadataRegistrar: AppPluginSecurityMetadataRegistrar;
/** [#31382] The host's per-kernel scheduled-work policy for this app's jobs; absent ⇒ the deployment switch. */
private readonly scheduledWorkPolicy: ScheduledWorkPolicySource | undefined;
/**
* [#34458] The inline boot seed's loader while it holds person references
* its pass 2 left NULL because no `sys_user` row answered yet — the first
* admin of a single-tenant install signs up after the boot seed ran. Read
* by {@link registerSeedPersonReferenceHandoff}; released once it holds none.
*/
private heldSeedPersonReferences?: SeedLoaderService;

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

this.registerHotReloadSeeder(ctx, ql);
this.registerSeedTenancyHandoff(ctx, ql);
this.registerSeedPersonReferenceHandoff(ctx, ql);
}

/**
* [#34458] Resolve the inline boot seed's person references the moment a
* person exists to resolve them to.
*
* An un-walled boot seed loads before the first admin's `sys_user` row
* exists, so a `Field.user()` / `Field.lookup('sys_user')` value naming
* that admin lands NULL and pass 2 reports it unresolved. The first-admin
* handoff (`claimSeedOwnership`, plugin-security) writes `owner_id` and no
* other column, and a later boot's replay of a create-only dataset leaves
* an existing row as it is, so nothing else ever filled those columns.
*
* After every `sys_user` insert while the loader holds such references,
* the loader retries them by its own resolution rule and writes each one
* that now resolves onto the row the seed landed on, only while that column
* is still NULL (`SeedLoaderService#resolveHeldPersonReferences`): a row
* the seed did not write is never touched (ADR-0138 D1), and a value set
* since is kept. The walled boot writes no inline seed (its per-organization
* replay waits for the owner's membership instead), so this never holds
* anything there.
*/
private registerSeedPersonReferenceHandoff(ctx: PluginContext, ql: any): void {
if (!ql || typeof ql.registerMiddleware !== 'function') return;
ql.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
await next();
const loader = this.heldSeedPersonReferences;
if (!loader) return;
const isUserCreate =
opCtx?.object === 'sys_user' &&
(opCtx?.operation === 'create' || opCtx?.operation === 'insert');
if (!isUserCreate) return;
try {
const { held } = await loader.resolveHeldPersonReferences();
if (held === 0 && this.heldSeedPersonReferences === loader) this.heldSeedPersonReferences = undefined;
} catch (e: any) {
// Best-effort, like the tenancy handoff beside it: the person
// was just created and that must stand. The references stay
// held and the next `sys_user` insert retries them; a failed
// write was already logged at `error` by the loader.
ctx.logger.warn('[AppPlugin] seed person-reference handoff failed; the next user insert retries it', {
error: e?.message ?? String(e),
});
}
});
}

/**
Expand Down
Loading