From e8cef187a69f79ab114b5b671685440f400ae7db Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:13:41 +0000 Subject: [PATCH 1/3] fix(plugin-security): the seed ownership hand-over yields to the event loop between 50-row batches On a synchronous driver every await of the claim's one predicate write resolved as a microtask, so a 1,500-row seed's hand-over held the event loop for 2.6 s and a sign-in waited for all of it. The NULL arm now writes its seeded ids 50 at a time with a setImmediate between writes, and the by-row path yields every 50 rows. The organizations twin gets the same. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mvv8ZvVXKGoTSX3eE --- .../src/claim-org-seed-ownership.ts | 119 +++++++-- .../claim-seed-ownership-yield.pin.test.ts | 249 ++++++++++++++++++ .../src/claim-seed-ownership.test.ts | 40 +-- .../src/claim-seed-ownership.ts | 129 ++++++++- 4 files changed, 493 insertions(+), 44 deletions(-) create mode 100644 packages/plugins/plugin-security/src/claim-seed-ownership-yield.pin.test.ts diff --git a/packages/plugins/organizations/src/claim-org-seed-ownership.ts b/packages/plugins/organizations/src/claim-org-seed-ownership.ts index a5185bdb6a5..d53e636770a 100644 --- a/packages/plugins/organizations/src/claim-org-seed-ownership.ts +++ b/packages/plugins/organizations/src/claim-org-seed-ownership.ts @@ -108,6 +108,22 @@ * the chunked predicate write. A row whose own write is refused stays * owner-less and is reported; the object's other rows are still claimed. The * twin made the same change. + * + * ## [#26825] …written a bounded batch at a time, yielding between batches + * + * On a synchronous driver (better-sqlite3, the wasm fallback) every `await` of + * a claim write resolves as a microtask, so one chunk's write ran its whole + * per-row fan-out (code hooks, an audit row per row) as one unbroken chain, and + * no request was read until it ended; the write is one engine transaction, and + * SQLite's pool holds one connection, so no yield can land inside it. Its + * single-tenant twin was measured stalling the event loop 2.7 s on a 1 500-row + * seed. So a chunk is written {@link CLAIM_HANDOVER_ROWS} ids at a time, with + * one macrotask yielded after every write ({@link yieldToEventLoop}), and the + * by-row path yields after every {@link CLAIM_HANDOVER_ROWS} rows. Which rows + * are claimed is unchanged, and so is a chunk every batch of which is refused + * (one warning, the chunk owner-less). The unit of failure is now the batch: + * when only some batches are refused, the others stay claimed and one warning + * names the rows left owner-less. The twin made the same change. */ import { analyzeRelationshipTraversals } from '@objectstack/formula'; @@ -162,6 +178,31 @@ const CLAIM_WRITE_CTX = { isSystem: true, skipAutomations: true }; */ const CLAIM_CHUNK_IDS = Math.floor(MAX_BULK_PER_ROW_HOOK_ROWS / 2); +/** + * [#26825] Seeded rows one claim write re-owns, and rows the by-row path + * writes between two yields: the bound on how long a request waits behind the + * claim on a synchronous driver. The twin's value (about 1.8 ms of per-row hook + * work per row was measured there, so a batch is about 90 ms). + */ +const CLAIM_HANDOVER_ROWS = 50; + +/** + * [#26825] Yield one macrotask so the host's event loop can read pending I/O + * between two claim writes. + * + * A module-private copy, by ruling (#26825): the same four lines live in the + * single-tenant twin `claimSeedOwnership` (`@objectstack/plugin-security`), + * in `@objectstack/metadata-protocol` (`seed-files.ts`) and in + * `@objectstack/core` (`import-runner.ts`). None is exported, and exporting one + * would widen a published surface for a `setImmediate` promise. + */ +function yieldToEventLoop(): Promise { + return new Promise((resolve) => { + if (typeof setImmediate === 'function') setImmediate(resolve); + else setTimeout(resolve, 0); + }); +} + /** * The affected-row count a predicate write resolved, or `undefined` when the * result is not one. @@ -177,13 +218,18 @@ function affectedRowCount(value: unknown): number | undefined { } /** - * Re-own the rows one chunk's predicate matches, in one write. Returns the - * affected-row count it resolved. + * Re-own the rows one chunk's predicate matches. Returns the sum of the + * affected-row counts its writes resolved. * - * Never throws. Best-effort per chunk, as the per-id loop was per row: a chunk - * that cannot be claimed must not cost a later chunk or a later object its - * claim. An unreadable count is warned as unknown and counts nothing, because - * this function never adds a number it cannot attest. + * [#26825] Written {@link CLAIM_HANDOVER_ROWS} ids at a time, one write each, + * with one macrotask yielded after every write. + * + * Never throws. Best-effort per batch, as the per-id loop was per row: a batch + * that cannot be claimed must not cost a later batch, chunk or object its + * claim. When every batch is refused the warning is the one a refused chunk + * always gave; when only some are, one warning names the rows left owner-less + * and the first refusal. An unreadable count is warned as unknown, once, and + * counts nothing, because this function never adds a number it cannot attest. */ async function claimChunk( reown: (where: Record) => Promise, @@ -192,34 +238,56 @@ async function claimChunk( where: Record, logger: ClaimOwnershipOptions['logger'], ): Promise { - const ids = (where.id as { $in: readonly string[] }).$in.length; + const chunk = (where.id as { $in: readonly string[] }).$in; + const ids = chunk.length; const at = { object: objectName, organizationId, ids }; - try { - const count = affectedRowCount(await reown(where)); - if (count === undefined) { - logger?.warn?.( - `[org-scoping] claimOrgSeedOwnership could not read an affected-row count for ${objectName} ` + - `in org ${organizationId}: the seeded rows were re-owned but this run cannot say how many`, - at, - ); - return 0; + let claimed = 0; + let countUnknown = false; + const refused: string[] = []; + let firstError: string | undefined; + for (let from = 0; from < ids; from += CLAIM_HANDOVER_ROWS) { + const batch = chunk.slice(from, from + CLAIM_HANDOVER_ROWS); + try { + const count = affectedRowCount(await reown({ ...where, id: { $in: batch } })); + if (count === undefined) countUnknown = true; + else claimed += count; + } catch (e) { + if (refused.length === 0) firstError = (e as Error).message; + refused.push(...batch); + } finally { + await yieldToEventLoop(); } - return count; - } catch (e) { + } + if (refused.length === ids) { logger?.warn?.( `[org-scoping] claimOrgSeedOwnership failed for ${objectName} in org ${organizationId}: ` + `the ${ids} seeded row(s) of this write stay owner-less`, - { ...at, error: (e as Error).message }, + { ...at, error: firstError }, + ); + } else if (refused.length > 0) { + logger?.warn?.( + `[org-scoping] claimOrgSeedOwnership failed for ${objectName} in org ${organizationId}: ` + + `${refused.length} of the ${ids} seeded row(s) of this chunk stay owner-less`, + { ...at, refused: refused.length, refusedIds: refused.slice(0, 20), error: firstError }, ); - return 0; } + if (countUnknown) { + logger?.warn?.( + `[org-scoping] claimOrgSeedOwnership could not read an affected-row count for ${objectName} ` + + `in org ${organizationId}: the seeded rows were re-owned but this run cannot say how many`, + at, + ); + } + return claimed; } /** * [#25668] Re-own one chunk's seeded rows one write each: the chunk's scope and * owner-less terms plus the row's id. Returns the sum of the affected-row * counts. Never throws: a refused row stays owner-less and the chunk's - * refusals are reported once, with the first refusal's message. + * refusals are reported once, with the first refusal's message. [#26825] + * Yields one macrotask after every {@link CLAIM_HANDOVER_ROWS} rows and after + * the last. */ async function claimChunkByRow( reown: (where: Record) => Promise, @@ -233,7 +301,8 @@ async function claimChunkByRow( let countUnknown = false; const refused: string[] = []; let firstError: string | undefined; - for (const id of ids) { + for (let i = 0; i < ids.length; i += 1) { + const id = ids[i]!; try { const count = affectedRowCount(await reown({ ...where, id })); if (count === undefined) countUnknown = true; @@ -242,6 +311,8 @@ async function claimChunkByRow( refused.push(id); firstError ??= (e as Error).message; } + // [#26825] A request waits behind one batch of rows, never the chunk. + if ((i + 1) % CLAIM_HANDOVER_ROWS === 0 || i === ids.length - 1) await yieldToEventLoop(); } const at = { object: objectName, organizationId, ids: ids.length }; if (refused.length > 0) { @@ -320,7 +391,9 @@ function storedExpressionReadsOwner(schema: ServiceObject): boolean { * and re-owns the org's unowned seeded rows as `isSystem` with * `skipAutomations`, in one predicate write per chunk of * {@link CLAIM_CHUNK_IDS} seeded ids — [#25668] one write per row instead on an - * object whose stored expressions read `owner_id`. Returns a per-object summary whose + * object whose stored expressions read `owner_id`; [#26825] either path writes + * {@link CLAIM_HANDOVER_ROWS} rows at most between two yields to the event + * loop. Returns a per-object summary whose * `count` is the sum of every write's affected-row count. */ export async function claimOrgSeedOwnership( diff --git a/packages/plugins/plugin-security/src/claim-seed-ownership-yield.pin.test.ts b/packages/plugins/plugin-security/src/claim-seed-ownership-yield.pin.test.ts new file mode 100644 index 00000000000..133b2a88c24 --- /dev/null +++ b/packages/plugins/plugin-security/src/claim-seed-ownership-yield.pin.test.ts @@ -0,0 +1,249 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#26825] The seed ownership hand-over yields to the event loop between + * bounded batches — measured on a REAL `ObjectQL` over a real `SqlDriver` + * (better-sqlite3 `:memory:`), the synchronous driver the stall was measured on. + * + * On better-sqlite3 every `await` of a claim write resolves as a microtask, so + * one predicate write ran its whole per-row fan-out (code hooks, an audit row + * per row) as one unbroken chain: measured on `os serve --dev` with a 1 500-row + * seed, the NULL arm's one write took 2.6 s and a sign-in issued meanwhile + * waited for all of it. These pins hold the cure and the four conditions it was + * accepted on: + * + * 1. **the yield** — at most one batch of rows is re-owned between two + * macrotask turns, and a read issued while the hand-over runs completes + * before the hand-over ends; + * 2. **the result** — every seeded row is owned by the admin and every claimed + * row wrote exactly one audit row, the outcome one unbatched write gave; + * 3. **a batch refused** — the other batches stay claimed, one warning names + * the rows left unowned and the first refusal, and the next run claims them; + * 4. **every batch refused** — nothing is claimed and the one warning is the + * one a refused chunk always gave. + * + * The audit row is written by a code-registered `afterUpdate` hook, the shape + * of plugin-audit's writer: an engine insert inside the claim's write. The + * booted-app half (the real audit plugin) is the dogfood + * `seed-ownership-claim-dispatch.dogfood.test.ts`. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; + +import { claimSeedOwnership } from './claim-seed-ownership.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; + +const SYS = { context: { isSystem: true } } as const; +const ADMIN = 'usr_admin_human'; +const OBJECT = 'probe_deal'; +const AUDIT = 'probe_audit'; +const READ_OBJECT = 'probe_person'; +/** The claim's hand-over batch (`CLAIM_HANDOVER_ROWS`, module-private). */ +const HANDOVER_ROWS = 50; +/** Seeded rows: six batches, and one partial batch at the end. */ +const N = 6 * HANDOVER_ROWS + 20; + +const OBJECTS: any[] = [ + { + name: OBJECT, + label: 'Probe Deal', + fields: { + id: { type: 'text', label: 'Id', primary: true }, + name: { type: 'text', label: 'Name' }, + owner_id: { type: 'text', label: 'Owner' }, + }, + }, + { + name: AUDIT, + label: 'Probe Audit', + fields: { + record_id: { type: 'text', label: 'Record' }, + owner_id: { type: 'text', label: 'New owner' }, + }, + }, + { + name: READ_OBJECT, + label: 'Probe Person', + fields: { email: { type: 'text', label: 'Email' } }, + }, +]; + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +/** The seed's report of the rows it landed on: every probe deal. */ +const seededAre = (ids: string[]) => (object: string): readonly string[] => (object === OBJECT ? ids : []); + +/** + * A booted engine with `N` unowned seeded deals, one person to read, and a + * code-registered `afterUpdate` hook writing one audit row per updated deal. + * `refuse` names the deals a code-registered `beforeUpdate` hook refuses. + */ +async function boot() { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.claim-yield-26825', + name: 'Claim yield', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: OBJECTS, + } as any); + await engine.syncSchemas(); + // The organization-less rows below exist only on a store built before 18.x. + await relaxTenantColumns(engine, [OBJECT, AUDIT, READ_OBJECT]); + engines.push(engine); + + const ids = Array.from({ length: N }, (_, i) => `d${String(i).padStart(4, '0')}`); + const driver = (engine as any).getDriverForObject(OBJECT); + await driver.bulkCreate(OBJECT, ids.map((id) => ({ id, name: `Deal ${id}`, owner_id: null }))); + await (engine as any).getDriverForObject(READ_OBJECT).bulkCreate(READ_OBJECT, [{ id: 'p1', email: 'a@example.com' }]); + + const refuse = new Set(); + let claimedRows = 0; + engine.registerHook('beforeUpdate', async (ctx: any) => { + const id = String(ctx?.input?.id ?? ''); + if (refuse.has(id) || refuse.has('*')) throw new Error(`probe refused ${id}`); + }, { object: OBJECT, packageId: 'probe.refuse' }); + engine.registerHook('afterUpdate', async (ctx: any) => { + claimedRows += 1; + await (engine as any).insert(AUDIT, { record_id: String(ctx?.input?.id ?? ''), owner_id: ADMIN }, SYS); + }, { object: OBJECT, packageId: 'probe.audit' }); + + return { engine, ids, refuse, claimed: () => claimedRows }; +} + +async function ownersOf(engine: ObjectQL): Promise> { + const rows = await (engine as any).find(OBJECT, { fields: ['id', 'owner_id'] }, SYS); + return new Map(rows.map((r: any) => [r.id, r.owner_id ?? null])); +} + +async function auditRows(engine: ObjectQL): Promise { + const rows = await (engine as any).find(AUDIT, { fields: ['record_id'] }, SYS); + return rows.map((r: any) => String(r.record_id)).sort(); +} + +const nextTurn = () => new Promise((resolve) => setImmediate(resolve)); + +describe('[#26825] the seed ownership hand-over yields between bounded batches (real engine, better-sqlite3)', () => { + it('re-owns at most one batch of rows between two macrotask turns', async () => { + const { engine, ids, claimed } = await boot(); + let done = false; + let maxPerTurn = 0; + let turns = 0; + const sampler = (async () => { + let seen = claimed(); + while (!done) { + await nextTurn(); + turns += 1; + maxPerTurn = Math.max(maxPerTurn, claimed() - seen); + seen = claimed(); + } + })(); + + const result = await claimSeedOwnership(engine, ADMIN, { seededRecordIds: seededAre(ids) }); + done = true; + await sampler; + + expect(result).toEqual([{ object: OBJECT, count: N }]); + expect(turns, 'no macrotask turn ran while the hand-over ran').toBeGreaterThan(N / HANDOVER_ROWS); + expect(maxPerTurn).toBeLessThanOrEqual(HANDOVER_ROWS); + }, 60_000); + + it('serves a read issued during the hand-over before the hand-over ends', async () => { + const { engine, ids, claimed } = await boot(); + const order: string[] = []; + let claimedAtRead: number | undefined; + const claim = claimSeedOwnership(engine, ADMIN, { seededRecordIds: seededAre(ids) }) + .then(() => { order.push('hand-over'); }); + // Issued from a macrotask, as a request arrives: the stand-in for the + // sign-in's user lookup, on another object of the same engine and driver. + const read = nextTurn() + .then(() => (engine as any).find(READ_OBJECT, { where: { email: 'a@example.com' } }, SYS)) + .then((rows: any[]) => { + expect(rows).toHaveLength(1); + claimedAtRead = claimed(); + order.push('read'); + }); + await Promise.all([claim, read]); + + expect(order).toEqual(['read', 'hand-over']); + expect(claimedAtRead).toBeLessThan(N); + }, 60_000); + + it('hands every seeded row to the admin with one audit row per claimed row', async () => { + const { engine, ids } = await boot(); + + const result = await claimSeedOwnership(engine, ADMIN, { seededRecordIds: seededAre(ids) }); + + expect(result).toEqual([{ object: OBJECT, count: N }]); + const owners = await ownersOf(engine); + expect([...owners.keys()].sort()).toEqual(ids); + for (const owner of owners.values()) expect(owner).toBe(ADMIN); + expect(await auditRows(engine)).toEqual(ids); + }, 60_000); + + it('a refused batch leaves only its rows unowned, says which, and the next run claims them', async () => { + const { engine, ids, refuse } = await boot(); + // One row of the third batch: the engine refuses that batch's write whole. + const refusedBatch = ids.slice(2 * HANDOVER_ROWS, 3 * HANDOVER_ROWS); + refuse.add(refusedBatch[7]!); + const warn = vi.fn(); + + const first = await claimSeedOwnership(engine, ADMIN, { + seededRecordIds: seededAre(ids), + logger: { info: vi.fn(), warn }, + }); + + expect(first).toEqual([{ object: OBJECT, count: N - HANDOVER_ROWS }]); + const owners = await ownersOf(engine); + for (const id of ids) expect(owners.get(id)).toBe(refusedBatch.includes(id) ? null : ADMIN); + expect(await auditRows(engine)).toEqual(ids.filter((id) => !refusedBatch.includes(id))); + expect(warn).toHaveBeenCalledTimes(1); + const [message, meta] = warn.mock.calls[0]!; + expect(message).toContain(`claimSeedOwnership failed for ${OBJECT}; ${HANDOVER_ROWS} of ${N} seeded row(s) stay unowned`); + expect(meta).toMatchObject({ object: OBJECT, refused: HANDOVER_ROWS, ids: refusedBatch.slice(0, 20) }); + expect(meta.error).toContain(`probe refused ${refusedBatch[7]}`); + + refuse.clear(); + const second = await claimSeedOwnership(engine, ADMIN, { seededRecordIds: seededAre(ids) }); + + expect(second).toEqual([{ object: OBJECT, count: HANDOVER_ROWS }]); + for (const owner of (await ownersOf(engine)).values()) expect(owner).toBe(ADMIN); + expect(await auditRows(engine)).toEqual(ids); + }, 60_000); + + it('every batch refused: nothing claimed, and the one warning a refused chunk always gave', async () => { + const { engine, ids, refuse } = await boot(); + refuse.add('*'); + const warn = vi.fn(); + + const result = await claimSeedOwnership(engine, ADMIN, { + seededRecordIds: seededAre(ids), + logger: { info: vi.fn(), warn }, + }); + + expect(result).toEqual([]); + for (const owner of (await ownersOf(engine)).values()) expect(owner).toBeNull(); + expect(await auditRows(engine)).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + const [message, meta] = warn.mock.calls[0]!; + expect(message).toBe( + `[security] claimSeedOwnership failed for ${OBJECT}; those rows stay unowned until the claim next runs — ` + + 'the next seed settle (`app:seeded`, on this boot or a later one) or the next platform-admin promotion', + ); + expect(meta).toMatchObject({ object: OBJECT, where: { owner_id: null, id: { $in: `${N} id(s)` } } }); + expect(meta.error).toContain('probe refused'); + }, 60_000); +}); diff --git a/packages/plugins/plugin-security/src/claim-seed-ownership.test.ts b/packages/plugins/plugin-security/src/claim-seed-ownership.test.ts index 1822e523e59..cb3aadaaffa 100644 --- a/packages/plugins/plugin-security/src/claim-seed-ownership.test.ts +++ b/packages/plugins/plugin-security/src/claim-seed-ownership.test.ts @@ -10,6 +10,8 @@ import { const SYSTEM = 'usr_system'; const ADMIN = 'usr_admin_human'; +/** [#26825] Seeded ids one NULL-arm write carries: the claim's hand-over batch. */ +const HANDOVER_ROWS = 50; /** One recorded call to `ql.update` — the shape, not just the payload. */ interface RecordedWrite { @@ -275,10 +277,12 @@ describe('claimSeedOwnership', () => { // ── [#14530] the predicate-write shape ──────────────────────────────────── - it('issues ONE predicate write per unowned shape — never one write per row', async () => { + it('issues ONE predicate write per unowned shape and hand-over batch — never one write per row', async () => { // The whole point of the card: N rows used to cost N single-id writes, so // the batch existed only in this caller's loop and nothing downstream could - // see it. The write COUNT is the pin, and it must not scale with N. + // see it. The write COUNT is the pin: [#26825] the NULL arm writes one batch + // of HANDOVER_ROWS seeded ids per write, so it scales with N / HANDOVER_ROWS, + // and the seed-identity arm is still one write. const schemas = [{ name: 'crm_lead', fields: [{ name: 'owner_id' }] }]; const rows = Array.from({ length: 500 }, (_, i) => ({ id: `l${i}`, @@ -290,17 +294,16 @@ describe('claimSeedOwnership', () => { const result = await claimSeedOwnership(ql, ADMIN, { seededRecordIds: seededIds({ crm_lead: seeded }) }); expect(result).toEqual([{ object: 'crm_lead', count: 500 }]); - expect(writes).toHaveLength(2); + expect(writes).toHaveLength(250 / HANDOVER_ROWS + 1); expect(writes.every((w) => w.multi)).toBe(true); // The set fits in one write per predicate, so the paged fallback never // engages and this pass issues NO read at all — the predicate write IS the // scan. expect(ql.find).not.toHaveBeenCalled(); // [#23354] The NULL arm carries the seed's ids; the seed identity arm does not. - expect(writes.map((w) => w.where)).toEqual([ - { owner_id: null, id: { $in: seeded } }, - { owner_id: SYSTEM }, - ]); + const batches = Array.from({ length: 250 / HANDOVER_ROWS }, (_, b) => + ({ owner_id: null, id: { $in: seeded.slice(b * HANDOVER_ROWS, (b + 1) * HANDOVER_ROWS) } })); + expect(writes.map((w) => w.where)).toEqual([...batches, { owner_id: SYSTEM }]); // Every write carries the payload only — no `id` in `data`, which is what // routes the engine down `updateMany` instead of the single-id door. expect(writes.every((w) => Object.keys(w.data).join() === 'owner_id')).toBe(true); @@ -491,9 +494,12 @@ describe('claimSeedOwnership', () => { // path never does — and it converged back onto whole-set writes rather than // paging to the end. expect(reads.length).toBeGreaterThan(0); - // Still batched, not per row: a handful of writes, none of them over the - // ceiling that refused the unpaged attempt. - expect(writes.length).toBeLessThan(10); + // Still batched, not per row: the seed-identity arm took a handful of + // writes, none of them over the ceiling that refused the unpaged attempt. + // [#26825] The NULL arm's 6 000 seeded ids are hand-over batches. + const nullArm = writes.filter((w) => (w.where as any).owner_id === null); + expect(nullArm).toHaveLength(6_000 / HANDOVER_ROWS); + expect(writes.length - nullArm.length).toBeLessThan(10); expect(writes.every((w) => w.matched.length <= MAX_BULK_PER_ROW_HOOK_ROWS)).toBe(true); // A page is big enough that plugin-sharing's 1000-row recompute cap still // sees these writes as batches rather than recomputing them row by row. @@ -716,10 +722,11 @@ describe('claimSeedOwnership — the NULL arm re-owns only the rows the seed rep expect(info.mock.calls[0]![1].seededRows).toBe(1); }); - it('chunks the seeded ids, so no IN list is longer than half the per-row hook ceiling and none is refused', async () => { + it('writes the seeded ids in hand-over batches, far under half the per-row hook ceiling, and none is refused', async () => { // The chunk keeps the list inside a driver's bound-parameter limit and // under the ceiling, so the engine never refuses a NULL-arm write whole - // and the arm issues no read. + // and the arm issues no read. [#26825] Each chunk is written in batches of + // HANDOVER_ROWS ids, the bound on how long a request waits behind it. const schemas = [{ name: 'crm_case', fields: [{ name: 'owner_id' }] }]; const rows = Array.from({ length: 12_000 }, (_, i) => ({ id: `c${i}`, owner_id: null as string | null })); const { ql, writes, reads } = makeQL(schemas, { crm_case: rows }); @@ -728,11 +735,10 @@ describe('claimSeedOwnership — the NULL arm re-owns only the rows the seed rep expect(result).toEqual([{ object: 'crm_case', count: 12_000 }]); const nullArm = writes.filter((w) => (w.where as any).owner_id === null); - expect(nullArm.map((w) => (w.where as any).id.$in.length)).toEqual([ - MAX_BULK_PER_ROW_HOOK_ROWS / 2, - MAX_BULK_PER_ROW_HOOK_ROWS / 2, - 12_000 - MAX_BULK_PER_ROW_HOOK_ROWS, - ]); + expect(nullArm.map((w) => (w.where as any).id.$in.length)).toEqual( + Array.from({ length: 12_000 / HANDOVER_ROWS }, () => HANDOVER_ROWS), + ); + expect(HANDOVER_ROWS).toBeLessThan(MAX_BULK_PER_ROW_HOOK_ROWS / 2); expect(reads).toEqual([]); }); }); diff --git a/packages/plugins/plugin-security/src/claim-seed-ownership.ts b/packages/plugins/plugin-security/src/claim-seed-ownership.ts index f18af1a534c..7eb5e7776f1 100644 --- a/packages/plugins/plugin-security/src/claim-seed-ownership.ts +++ b/packages/plugins/plugin-security/src/claim-seed-ownership.ts @@ -202,6 +202,32 @@ * write cannot store the result. A row whose own write is refused stays * unowned and is reported with the per-predicate warning, and the object's * other rows are still claimed. + * + * ## [#26825] …handed over a bounded batch at a time, yielding between batches + * + * On a synchronous driver (better-sqlite3, the wasm fallback) every `await` of + * a claim write resolves as a microtask, so ONE predicate write ran its whole + * per-row fan-out (the hooks above, an audit row per row, a file field's + * reference hooks) as one unbroken chain, and no request was read off a socket + * until it ended. Measured on `os serve --dev` over file-backed sqlite, a + * 1 500-row seed whose rows each carry a seed file: the NULL arm's one write + * took 2 641 ms, the event loop stalled 2.7 s, and a sign-in issued meanwhile + * answered in 2–2.9 s. The write is also one engine transaction, and SQLite's + * pool holds one connection, so no yield can land INSIDE it: the cure is a + * smaller write. The NULL arm's chunk is therefore written + * {@link CLAIM_HANDOVER_ROWS} ids at a time, and the claim yields one macrotask + * after every write ({@link yieldToEventLoop}); the by-row path yields after + * every {@link CLAIM_HANDOVER_ROWS} rows. A request now waits behind one + * batch, never behind a seed. + * + * Which rows are claimed, by whom, and with which audit rows is unchanged; so + * is a chunk every batch of which is refused (one warning, the chunk unowned). + * The unit of failure is the batch: when only some batches of a chunk are + * refused, the others stay claimed and one warning names the rows left + * unowned, which the next run claims, where one refused write used to leave + * the whole chunk unowned. The `owner_id = usr_system` arm is still one + * predicate write (no seed writes that owner in the shapes measured); it + * yields after it. */ import { analyzeRelationshipTraversals } from '@objectstack/formula'; @@ -279,6 +305,36 @@ const CLAIM_WRITE_CTX = { isSystem: true, skipAutomations: true }; */ const CLAIM_PAGE_ROWS = Math.floor(MAX_BULK_PER_ROW_HOOK_ROWS / 2); +/** + * [#26825] Seeded rows one hand-over write re-owns, and rows the by-row path + * writes between two yields: the bound on how long a request waits behind the + * claim on a synchronous driver. + * + * Measured, not derived: a claimed row cost about 1.8 ms of per-row hook work + * on `os serve --dev` over sqlite with a file field (2 641 ms for 1 500 rows), + * so a batch is about 90 ms. Far below {@link CLAIM_PAGE_ROWS}, so a batch is + * never refused for the per-row hook ceiling. + */ +const CLAIM_HANDOVER_ROWS = 50; + +/** + * [#26825] Yield one macrotask so the host's event loop can read pending I/O + * between two hand-over writes. + * + * A module-private copy, by ruling (#26825): the same four lines live in + * `@objectstack/metadata-protocol` (`seed-files.ts`, the seed loader's file + * work) and `@objectstack/core` (`import-runner.ts`, the import row loop), + * and in this plugin's multi-organization twin `claimOrgSeedOwnership` + * (`@objectstack/organizations`). None is exported, and exporting one would + * widen a published surface for a `setImmediate` promise. + */ +function yieldToEventLoop(): Promise { + return new Promise((resolve) => { + if (typeof setImmediate === 'function') setImmediate(resolve); + else setTimeout(resolve, 0); + }); +} + /** * Fallback pages one predicate may take before this function gives up on it. * @@ -537,11 +593,70 @@ async function claimPredicate( return total; } +/** + * [#26825] {@link claimPredicate} over one unowned predicate, a batch of + * {@link CLAIM_HANDOVER_ROWS} seeded ids at a time, with one macrotask yielded + * after every write. The `owner_id = usr_system` predicate names no ids and is + * written as before, then yields. + * + * Returns the sum of the batches' counts. A batch whose write is refused + * leaves its rows unowned and the next batch is still written. If every batch + * is refused, the first refusal is rethrown, so the caller reports the + * predicate exactly as it did when the chunk was one write; if only some are, + * one warning names the rows left unowned and the first refusal. + */ +async function claimPredicateInBatches( + io: ObjectWriter, + objectName: string, + where: Record, + logger: ClaimOwnershipOptions['logger'], +): Promise { + const named = (where.id as { $in?: unknown } | undefined)?.$in; + if (!Array.isArray(named)) { + try { + return await claimPredicate(io, objectName, where, logger); + } finally { + await yieldToEventLoop(); + } + } + let claimed = 0; + const refused: string[] = []; + let firstError: unknown; + for (let at = 0; at < named.length; at += CLAIM_HANDOVER_ROWS) { + const batch = named.slice(at, at + CLAIM_HANDOVER_ROWS).map(String); + try { + claimed += await claimPredicate(io, objectName, { ...where, id: { $in: batch } }, logger); + } catch (e) { + if (refused.length === 0) firstError = e; + refused.push(...batch); + } finally { + await yieldToEventLoop(); + } + } + if (refused.length === 0) return claimed; + if (refused.length === named.length) throw firstError; + logger?.warn?.( + `[security] claimSeedOwnership failed for ${objectName}; ${refused.length} of ${named.length} seeded row(s) ` + + 'stay unowned until the claim next runs — the next seed settle (`app:seeded`, on this boot or a later one) ' + + 'or the next platform-admin promotion', + { + object: objectName, + where: whereForLog(where), + refused: refused.length, + ids: refused.slice(0, 20), + error: (firstError as Error)?.message, + }, + ); + return claimed; +} + /** * [#25668] Re-own the given rows of one unowned predicate one write each: the * predicate's own terms plus the row's id, a compare-and-set the engine * evaluates over that one row. Never throws for a row: a refused row stays * unowned and is reported once for the batch, with the first refusal's message. + * [#26825] Yields one macrotask after every {@link CLAIM_HANDOVER_ROWS} rows and + * after the last. */ async function claimRows( io: ObjectWriter, @@ -554,7 +669,8 @@ async function claimRows( let countUnknown = false; const refused: string[] = []; let firstError: string | undefined; - for (const id of ids) { + for (let i = 0; i < ids.length; i += 1) { + const id = ids[i]!; try { const count = affectedRowCount(await io.reown({ ...where, id })); if (count === undefined) countUnknown = true; @@ -563,6 +679,8 @@ async function claimRows( refused.push(id); firstError ??= (e as Error).message; } + // [#26825] A request waits behind one batch of rows, never the object. + if ((i + 1) % CLAIM_HANDOVER_ROWS === 0 || i === ids.length - 1) await yieldToEventLoop(); } if (refused.length > 0) { logger?.warn?.( @@ -747,8 +865,10 @@ function reportClaimPass( * {@link unownedPredicates} entry — the seeded ids' chunks under the NULL arm, * then the seed identity — paging that write only when the engine refuses it * for its per-row hook budget, and [#25668] one write per row instead on an - * object whose stored expressions read `owner_id`. Returns a per-object summary - * whose `count` is the sum of every write's affected-row count. + * object whose stored expressions read `owner_id`. [#26825] Either path writes + * {@link CLAIM_HANDOVER_ROWS} rows at most between two yields to the event loop. + * Returns a per-object summary whose `count` is the sum of every write's + * affected-row count. */ export async function claimSeedOwnership( ql: any, @@ -809,7 +929,8 @@ export async function claimSeedOwnership( seededRows += seededIds.length; // [#25668] One predicate write cannot store a per-row value of a stored // field the claim's `owner_id` moves; such an object is claimed by row. - const claim = storedExpressionReadsOwner(schema) ? claimPredicateByRow : claimPredicate; + // [#26825] Either way the claim yields between bounded batches of rows. + const claim = storedExpressionReadsOwner(schema) ? claimPredicateByRow : claimPredicateInBatches; let updated = 0; for (const where of unownedPredicates(seededIds)) { From b07bb3545f10a41db2565aed6210d39e90e305d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:17:11 +0000 Subject: [PATCH 2/3] test(organizations): pin the organization seed claim's hand-over batches and yield Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mvv8ZvVXKGoTSX3eE --- ...claim-org-seed-ownership-yield.pin.test.ts | 234 ++++++++++++++++++ .../src/claim-org-seed-ownership.test.ts | 36 +-- 2 files changed, 255 insertions(+), 15 deletions(-) create mode 100644 packages/plugins/organizations/src/claim-org-seed-ownership-yield.pin.test.ts diff --git a/packages/plugins/organizations/src/claim-org-seed-ownership-yield.pin.test.ts b/packages/plugins/organizations/src/claim-org-seed-ownership-yield.pin.test.ts new file mode 100644 index 00000000000..7c6a0c77ab6 --- /dev/null +++ b/packages/plugins/organizations/src/claim-org-seed-ownership-yield.pin.test.ts @@ -0,0 +1,234 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#26825] The organization seed ownership claim yields to the event loop + * between bounded batches — measured on a REAL `ObjectQL` over a real + * `SqliteWasmDriver`, a synchronous driver: every `await` of a claim write + * resolves as a microtask there, so one chunk's write used to run its whole + * per-row fan-out (code hooks, an audit row per row) as one unbroken chain. + * Its single-tenant twin was measured stalling the event loop 2.7 s on a + * 1 500-row seed (`claim-seed-ownership-yield.pin.test.ts`, plugin-security). + * + * 1. **the yield** — at most one batch of rows is re-owned between two + * macrotask turns, and a read issued meanwhile completes before the claim; + * 2. **the result** — every seeded row of the organization is owned by its + * owner, with one audit row per claimed row, and no other row is touched; + * 3. **a batch refused** — the other batches stay claimed, one warning names + * the rows left owner-less and the first refusal, and the next run claims + * them; + * 4. **every batch refused** — nothing is claimed, and the one warning is the + * one a refused chunk always gave. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; + +import { claimOrgSeedOwnership } from './claim-org-seed-ownership.js'; + +const SYS = { context: { isSystem: true } } as const; +const ORG = 'org_alpha'; +const OTHER_ORG = 'org_north'; +const OWNER = 'usr_org_owner'; +const OBJECT = 'probe_deal'; +const AUDIT = 'probe_audit'; +/** The claim's hand-over batch (`CLAIM_HANDOVER_ROWS`, module-private). */ +const HANDOVER_ROWS = 50; +/** Seeded rows: six batches, and one partial batch at the end. */ +const N = 6 * HANDOVER_ROWS + 20; + +const OBJECTS = [ + { + name: OBJECT, + label: 'Probe Deal', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + owner_id: { name: 'owner_id', type: 'text' }, + organization_id: { name: 'organization_id', type: 'text' }, + }, + }, + { + name: AUDIT, + label: 'Probe Audit', + fields: { + record_id: { name: 'record_id', type: 'text' }, + organization_id: { name: 'organization_id', type: 'text' }, + }, + }, +]; + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +/** The organization's seed replay reported landing on these rows. */ +const seededAre = (ids: string[]) => (object: string): readonly string[] => (object === OBJECT ? ids : []); + +/** + * A booted engine with `N` owner-less seeded deals in `ORG`, one owner-less + * deal in another organization, and a code-registered `afterUpdate` hook + * writing one audit row per updated deal. `refuse` names the deals a + * code-registered `beforeUpdate` hook refuses (`*` refuses every one). + */ +async function boot() { + const engine = new ObjectQL(); + engine.registerDriver(new SqliteWasmDriver({ filename: ':memory:' } as never) as never, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.org-claim-yield-26825', + name: 'Organization claim yield', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: OBJECTS, + } as never); + await engine.syncSchemas(); + engines.push(engine); + + const ids = Array.from({ length: N }, (_, i) => `d${String(i).padStart(4, '0')}`); + const driver = (engine as any).getDriverForObject(OBJECT); + await driver.bulkCreate(OBJECT, [ + ...ids.map((id) => ({ id, name: `Deal ${id}`, owner_id: null, organization_id: ORG })), + { id: 'foreign', name: 'Foreign', owner_id: null, organization_id: OTHER_ORG }, + ]); + + const refuse = new Set(); + let claimedRows = 0; + engine.registerHook('beforeUpdate', async (ctx: any) => { + const id = String(ctx?.input?.id ?? ''); + if (refuse.has(id) || refuse.has('*')) throw new Error(`probe refused ${id}`); + }, { object: OBJECT, packageId: 'probe.refuse' }); + engine.registerHook('afterUpdate', async (ctx: any) => { + claimedRows += 1; + await (engine as any).insert(AUDIT, { record_id: String(ctx?.input?.id ?? ''), organization_id: ORG }, SYS); + }, { object: OBJECT, packageId: 'probe.audit' }); + + return { engine, ids, refuse, claimed: () => claimedRows }; +} + +async function ownersOf(engine: ObjectQL): Promise> { + const rows = await (engine as any).find(OBJECT, { fields: ['id', 'owner_id'] }, SYS); + return new Map(rows.map((r: any) => [r.id, r.owner_id ?? null])); +} + +async function auditRows(engine: ObjectQL): Promise { + const rows = await (engine as any).find(AUDIT, { fields: ['record_id'] }, SYS); + return rows.map((r: any) => String(r.record_id)).sort(); +} + +const nextTurn = () => new Promise((resolve) => setImmediate(resolve)); + +describe('[#26825] the organization seed ownership claim yields between bounded batches (real engine, sqlite-wasm)', () => { + it('re-owns at most one batch of rows between two macrotask turns', async () => { + const { engine, ids, claimed } = await boot(); + let done = false; + let maxPerTurn = 0; + let turns = 0; + const sampler = (async () => { + let seen = claimed(); + while (!done) { + await nextTurn(); + turns += 1; + maxPerTurn = Math.max(maxPerTurn, claimed() - seen); + seen = claimed(); + } + })(); + + const result = await claimOrgSeedOwnership(engine as never, ORG, OWNER, { seededRecordIds: seededAre(ids) }); + done = true; + await sampler; + + expect(result).toEqual([{ object: OBJECT, count: N }]); + expect(turns, 'no macrotask turn ran while the claim ran').toBeGreaterThan(N / HANDOVER_ROWS); + expect(maxPerTurn).toBeLessThanOrEqual(HANDOVER_ROWS); + }, 60_000); + + it('serves a read issued during the claim before the claim ends', async () => { + const { engine, ids, claimed } = await boot(); + const order: string[] = []; + let claimedAtRead: number | undefined; + const claim = claimOrgSeedOwnership(engine as never, ORG, OWNER, { seededRecordIds: seededAre(ids) }) + .then(() => { order.push('claim'); }); + const read = nextTurn() + .then(() => (engine as any).find(OBJECT, { where: { id: 'foreign' } }, SYS)) + .then((rows: any[]) => { + expect(rows).toHaveLength(1); + claimedAtRead = claimed(); + order.push('read'); + }); + await Promise.all([claim, read]); + + expect(order).toEqual(['read', 'claim']); + expect(claimedAtRead).toBeLessThan(N); + }, 60_000); + + it('hands every seeded row to the owner with one audit row per claimed row, and no other row', async () => { + const { engine, ids } = await boot(); + + const result = await claimOrgSeedOwnership(engine as never, ORG, OWNER, { seededRecordIds: seededAre(ids) }); + + expect(result).toEqual([{ object: OBJECT, count: N }]); + const owners = await ownersOf(engine); + for (const id of ids) expect(owners.get(id)).toBe(OWNER); + expect(owners.get('foreign')).toBeNull(); + expect(await auditRows(engine)).toEqual(ids); + }, 60_000); + + it('a refused batch leaves only its rows owner-less, says which, and the next run claims them', async () => { + const { engine, ids, refuse } = await boot(); + const refusedBatch = ids.slice(2 * HANDOVER_ROWS, 3 * HANDOVER_ROWS); + refuse.add(refusedBatch[7]!); + const warn = vi.fn(); + + const first = await claimOrgSeedOwnership(engine as never, ORG, OWNER, { + seededRecordIds: seededAre(ids), + logger: { info: vi.fn(), warn }, + }); + + expect(first).toEqual([{ object: OBJECT, count: N - HANDOVER_ROWS }]); + const owners = await ownersOf(engine); + for (const id of ids) expect(owners.get(id)).toBe(refusedBatch.includes(id) ? null : OWNER); + expect(await auditRows(engine)).toEqual(ids.filter((id) => !refusedBatch.includes(id))); + expect(warn).toHaveBeenCalledTimes(1); + const [message, meta] = warn.mock.calls[0]!; + expect(message).toBe( + `[org-scoping] claimOrgSeedOwnership failed for ${OBJECT} in org ${ORG}: ` + + `${HANDOVER_ROWS} of the ${N} seeded row(s) of this chunk stay owner-less`, + ); + expect(meta).toMatchObject({ object: OBJECT, organizationId: ORG, ids: N, refused: HANDOVER_ROWS, refusedIds: refusedBatch.slice(0, 20) }); + expect(meta.error).toContain(`probe refused ${refusedBatch[7]}`); + + refuse.clear(); + const second = await claimOrgSeedOwnership(engine as never, ORG, OWNER, { seededRecordIds: seededAre(ids) }); + + expect(second).toEqual([{ object: OBJECT, count: HANDOVER_ROWS }]); + for (const id of ids) expect((await ownersOf(engine)).get(id)).toBe(OWNER); + expect(await auditRows(engine)).toEqual(ids); + }, 60_000); + + it('every batch refused: nothing claimed, and the one warning a refused chunk always gave', async () => { + const { engine, ids, refuse } = await boot(); + refuse.add('*'); + const warn = vi.fn(); + + const result = await claimOrgSeedOwnership(engine as never, ORG, OWNER, { + seededRecordIds: seededAre(ids), + logger: { info: vi.fn(), warn }, + }); + + expect(result).toEqual([]); + for (const owner of (await ownersOf(engine)).values()) expect(owner).toBeNull(); + expect(await auditRows(engine)).toEqual([]); + expect(warn).toHaveBeenCalledTimes(1); + const [message, meta] = warn.mock.calls[0]!; + expect(message).toBe( + `[org-scoping] claimOrgSeedOwnership failed for ${OBJECT} in org ${ORG}: ` + + `the ${N} seeded row(s) of this write stay owner-less`, + ); + expect(meta).toEqual({ object: OBJECT, organizationId: ORG, ids: N, error: expect.stringContaining('probe refused') }); + }, 60_000); +}); diff --git a/packages/plugins/organizations/src/claim-org-seed-ownership.test.ts b/packages/plugins/organizations/src/claim-org-seed-ownership.test.ts index 2c517b999fe..bddcfe08525 100644 --- a/packages/plugins/organizations/src/claim-org-seed-ownership.test.ts +++ b/packages/plugins/organizations/src/claim-org-seed-ownership.test.ts @@ -120,6 +120,8 @@ function seededIds(byObject: Record): (object: string) => read } const CHUNK = Math.floor(MAX_BULK_PER_ROW_HOOK_ROWS / 2); +/** [#26825] Seeded ids one claim write carries: the claim's hand-over batch. */ +const HANDOVER_ROWS = 50; describe('claimOrgSeedOwnership', () => { it('returns [] when registry is unavailable', async () => { @@ -291,26 +293,27 @@ describe('claimOrgSeedOwnership', () => { expect(rows.find((r) => r.id === 'owned')!.owner_id).toBe(SOMEONE); expect(rows.find((r) => r.id === 'foreign')!.owner_id).toBeNull(); - // Three chunks, each under the ceiling; every write keeps the claim's - // predicate and names its chunk; nothing was read. - expect(writes.map((w) => w.matched.length)).toEqual([CHUNK, CHUNK, N - 2 * CHUNK]); + // Three chunks, each under the ceiling, [#26825] each written in hand-over + // batches; every write keeps the claim's predicate and names its batch; + // nothing was read. + expect(writes.map((w) => w.matched.length)).toEqual(Array.from({ length: N / HANDOVER_ROWS }, () => HANDOVER_ROWS)); for (const w of writes) { expect(Object.keys(w.where).sort()).toEqual(['id', 'organization_id', 'owner_id']); expect(w.where).toMatchObject({ organization_id: ORG, owner_id: null }); - expect(w.where.id.$in.length).toBeLessThanOrEqual(CHUNK); + expect(w.where.id.$in.length).toBeLessThanOrEqual(HANDOVER_ROWS); expect(w.context).toEqual({ isSystem: true, skipAutomations: true }); } expect(ql.find).not.toHaveBeenCalled(); }); - it('an unreadable count is warned as unknown, counts nothing, and the next chunk still lands', async () => { + it('an unreadable count is warned as unknown, counts nothing, and the next write still lands', async () => { const schemas = [{ name: 'crm_lead', fields: BOTH_COLUMNS }]; const seeded = Array.from({ length: CHUNK + 1 }, (_, i) => `l${String(i).padStart(5, '0')}`); const rows = seeded.map((id) => ({ id, organization_id: ORG, owner_id: null as string | null })); const logger = makeLogger(); let call = 0; const { ql } = makeQL(schemas, { crm_lead: rows }, { - // The first chunk's driver answers a record rather than a count. + // The first write's driver answers a record rather than a count. writeAnswer: (_object, where) => { call += 1; if (call === 1) return { id: 'not-a-count' }; @@ -323,8 +326,11 @@ describe('claimOrgSeedOwnership', () => { expect( await claimOrgSeedOwnership(ql, ORG, OWNER, { logger, seededRecordIds: seededIds({ crm_lead: seeded }) }), - ).toEqual([{ object: 'crm_lead', count: 1 }]); - expect(ql.update).toHaveBeenCalledTimes(2); + ).toEqual([{ object: 'crm_lead', count: CHUNK + 1 - HANDOVER_ROWS }]); + // [#26825] One write per hand-over batch: the first chunk's, then the + // second chunk's one id. + expect(ql.update).toHaveBeenCalledTimes(CHUNK / HANDOVER_ROWS + 1); + expect(logger.warn).toHaveBeenCalledTimes(1); expect(logger.warn).toHaveBeenCalledWith( expect.stringContaining('could not read an affected-row count'), expect.objectContaining({ object: 'crm_lead', organizationId: ORG, ids: CHUNK }), @@ -340,13 +346,12 @@ describe('claimOrgSeedOwnership', () => { const leads = seeded.map((id) => ({ id, organization_id: ORG, owner_id: null as string | null })); const deals = [{ id: 'd1', organization_id: ORG, owner_id: null }]; const logger = makeLogger(); - let leadWrites = 0; + const secondChunk = new Set(seeded.slice(CHUNK, 2 * CHUNK)); const { ql } = makeQL(schemas, { crm_lead: leads, crm_deal: deals }, { - // The second crm_lead chunk is refused outright by a code hook. - failWrite: (object) => { + // Every write of the second crm_lead chunk is refused outright by a code hook. + failWrite: (object, where) => { if (object !== 'crm_lead') return undefined; - leadWrites += 1; - return leadWrites === 2 ? new Error('a code hook refused the write') : undefined; + return secondChunk.has(where.id.$in[0]) ? new Error('a code hook refused the write') : undefined; }, }); @@ -361,9 +366,10 @@ describe('claimOrgSeedOwnership', () => { ]); expect(leads.filter((r) => r.owner_id === OWNER)).toHaveLength(CHUNK + 1); expect(deals[0].owner_id).toBe(OWNER); + expect(logger.warn).toHaveBeenCalledTimes(1); expect(logger.warn).toHaveBeenCalledWith( - expect.stringContaining('failed for crm_lead'), - expect.objectContaining({ object: 'crm_lead', ids: CHUNK, error: 'a code hook refused the write' }), + expect.stringContaining(`failed for crm_lead in org ${ORG}: the ${CHUNK} seeded row(s) of this write stay owner-less`), + { object: 'crm_lead', organizationId: ORG, ids: CHUNK, error: 'a code hook refused the write' }, ); }); }); From d51a116db45324fff2380ac68c0c2fb6e31e8c1a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 20:20:08 +0000 Subject: [PATCH 3/3] chore(changeset): seed ownership hand-over yields between batches Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5mvv8ZvVXKGoTSX3eE --- .changeset/26825-seed-claim-yield.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .changeset/26825-seed-claim-yield.md diff --git a/.changeset/26825-seed-claim-yield.md b/.changeset/26825-seed-claim-yield.md new file mode 100644 index 00000000000..9d2878c4ad5 --- /dev/null +++ b/.changeset/26825-seed-claim-yield.md @@ -0,0 +1,11 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/organizations': patch +--- + +fix(plugin-security): the seed ownership hand-over no longer holds the event loop for seconds, so a sign-in during it is answered + +Clause-②: no +Metadata-protocol: none + +The seed ownership hand-over that runs when a seed settles (`app:seeded`, plugin-security's `claimSeedOwnership`) and its multi-organization twin (`claimOrgSeedOwnership` in `@objectstack/organizations`) no longer re-own a large seed in one unbroken run. On a synchronous driver (better-sqlite3, the wasm fallback) every step of a claim write resolves as a microtask, so one write over a 1,500-row seed ran its per-row hooks and audit rows for 2.6 s and a sign-in issued meanwhile waited for all of it. The claim now writes the seeded rows 50 at a time and yields the event loop after every write (the by-row path after every 50 rows); a sign-in during it answers in hundreds of milliseconds. The same rows go to the same owner with the same audit rows. If only some batches of a chunk are refused, the other batches stay claimed and one warning names the rows left unowned, which the next run claims; a chunk every batch of which is refused is reported and left unowned as before.