diff --git a/.changeset/33651-async-hook-outside-door-unit.md b/.changeset/33651-async-hook-outside-door-unit.md index b671364542f..7b20c2a551c 100644 --- a/.changeset/33651-async-hook-outside-door-unit.md +++ b/.changeset/33651-async-hook-outside-door-unit.md @@ -11,13 +11,12 @@ An object with an `async: true` `afterUpdate` hook worked until a second, blocki The blocking hook (default `onError: 'abort'`) makes the write door open a unit of work, so that hook's abort can roll the write back. The async hook is dispatched inside that unit and starts at once, while the unit is still open, so its first writes joined it. Nothing waits for an async hook, so the unit committed under those writes. The same happened inside a unit a caller opened (`engine.transaction()`, `ctx.api.transaction(fn)`) whenever the async hook wrote before that unit settled. -An async after-hook now runs outside every unit of work open when it is dispatched. From the first write on, its writes are enrolled in no unit and run on their own connection, as they would with no unit open. What they see is not the same as with no unit open: there, the triggering write is already committed; here, it may not be yet (see the first bullet below). A unit the hook opens itself (`ctx.api.transaction(fn)`) is its own. This makes the existing changelog sentence about work a unit starts and does not await ("It now runs on its own connection, as it would outside any unit") true from the moment that work starts, not only after the unit has settled. +An async after-hook now runs outside every unit of work open when it is dispatched. From the first write on, its writes are enrolled in no unit and run on their own connection, as they would with no unit open. A unit the hook opens itself (`ctx.api.transaction(fn)`) is its own. When the hook starts, and whether it runs at all when that unit rolls back, is stated in one place, the entry for the follow-up fix: an async after-hook fired inside a unit of work runs once that unit commits, and not at all when it rolls back. This makes the existing changelog sentence about work a unit starts and does not await ("It now runs on its own connection, as it would outside any unit") true from the moment that work starts, not only after the unit has settled. What changes for a hook author: -- An async after-hook runs in the background but is not deferred until the triggering write commits. It can start before that write's unit commits, so it may see the state from before that write, and it is not cancelled if that unit rolls back. On a database with more than one connection (Postgres, MySQL, Mongo), its `ctx.api` reads and writes run on their own connection and do not see the triggering write until its unit commits: an async `afterUpdate` that re-reads its record can read the old values, and an async `afterInsert` that updates the new row or inserts a child that references it can find no row. Before this change, those early statements joined the unit, saw the write, and failed or rolled back with it. An async hook that must see the triggering write should be a blocking hook instead. - An async hook's writes are stored whatever blocking hooks share its event. -- An async hook's writes no longer roll back with the write that triggered it. Before, they rolled back only when they happened to run before that unit settled. An async hook that must undo its effect when the triggering write fails should be a blocking hook instead. +- An async hook's writes no longer roll back with the write that triggered it. Before, they rolled back only when they happened to run before that unit settled. - On a database with a single connection (SQLite), an async hook's write waits until the triggering write's unit releases the connection. Nothing waits for the async hook, so the triggering write is not delayed. Blocking hooks are unchanged: their `ctx.api` writes join the unit and roll back with it. An async hook with no unit open is unchanged too. diff --git a/.changeset/33760-async-hook-on-commit.md b/.changeset/33760-async-hook-on-commit.md new file mode 100644 index 00000000000..c6c5622cb48 --- /dev/null +++ b/.changeset/33760-async-hook-on-commit.md @@ -0,0 +1,26 @@ +--- +'@objectstack/objectql': minor +'@objectstack/spec': patch +--- + +fix(objectql): an `async: true` after-hook fired inside a unit of work runs once that unit commits, and not at all when it rolls back + +Clause-②: no +Metadata-protocol: semantic + +An `async: true` after-hook fired inside a unit of work started at once, while the unit was still open. Two things followed. On a database with more than one connection (Postgres, MySQL, Mongo), its `ctx.api` reads and writes ran on their own connection before the triggering write was committed, so an async `afterUpdate` that re-read its record could read the old values, and an async `afterInsert` that updated the new row or inserted a child referencing it could find no row. And when the unit rolled back, the hook had already run: its writes landed, referencing a row that was never stored. Measured on Postgres 16 and on SQLite through knex, for a caller's `engine.transaction()`, a `ctx.api.transaction(fn)`, a nested unit, and the unit the write door opens for a blocking `after*` hook beside the async one. + +This is the one statement of when an async after-hook runs inside a unit of work. The previous fix (#33703) moved its writes outside the unit; its entry in these notes leaves the timing to this one. Now: + +- An async after-hook fired inside a unit of work starts after the outermost unit commits. Its `ctx.api` reads see the committed write, on every database. A nested `transaction()` joins the outer unit, so its return is no commit: the outer unit's outcome decides. +- When that unit rolls back, the async hook does not run at all. It writes nothing and calls nothing, so an external effect it makes (a webhook, an email) is never announced for a write that was undone. +- The units this covers are every one the engine opens: a caller's `engine.transaction()`, `ctx.api.transaction(fn)` (in a sandboxed hook body too), an atomic batch or cascade, and the unit the write door opens for a blocking `after*` hook that can abort. A blocking hook beside the async one on the same event still runs inside that unit, before the commit. +- Outside any unit an async hook starts at once, after the write, as before. Its writes still run outside every unit, on their own connection, and nothing waits for it. +- This is for the write events (`afterInsert`, `afterUpdate`, `afterDelete`). A rollback does not undo a read, so an async `afterFind` hook starts when the read is dispatched, outside the unit, as before, whatever the unit does next. +- All the async hooks a unit held start together, in the order they were dispatched, once it commits. A bulk write with a per-row async hook holds one per row until then. + +An async hook whose job was to react to a write that failed (to record a refused attempt, say) no longer runs for it. Use a blocking hook, or react to the caller's error, for that. + +Known deviations, both narrow: a write that is stored while its unit is later undone still loses its async hook with that unit, in two cases. (a) A write from work the transaction callback started and did not await, made after the callback returned and before a commit that then fails. (b) A write to an append-only system-ledger object routed to another datasource, which `transaction()` runs outside the unit and which survives its rollback: its async hook is held by the unit and dropped with it. + +The `async` key's documentation in `@objectstack/spec` (`HookSchema.async`, and the `HookEvent` note on `ctx.api` writes rolling back with the unit, which now names blocking hooks only) says the same. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index c93cf1d14f2..ff6b1f87355 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -293,7 +293,10 @@ An `after*` hook does **not** mean "the write happened". It means **the write has been requested and will happen unless this unit of work is undone**. `afterInsert`, `afterUpdate` and `afterDelete` are dispatched *before* the enclosing transaction commits, so a later refusal in the same unit can roll the -row back after your handler has already run. +row back after your handler has already run. That is true of a **blocking** +hook, the default. An `async: true` hook is dispatched there too, but does not +run there: see [`async: true` after hooks run after the +commit](#async-true-after-hooks-run-after-the-commit). Four ordinary operations put a write inside such a unit: @@ -304,7 +307,7 @@ Four ordinary operations put a write inside such a unit: | `batchData` / `deleteManyData` with `atomic: true` | Every member's `after*` — the batch aborts and rolls back on the first failure | | Any write you wrapped yourself in `ctx.api.transaction(...)` or `engine.transaction(...)` | Everything in the callback | -What this means when you write a handler: +What this means when you write a blocking handler: - **Effects that go back through the engine are safe.** Writes made with `ctx.api.object('x')` join the same transaction and roll back with @@ -321,12 +324,36 @@ Before hooks carry no such caveat: they run before the write is issued, and throwing from one refuses the operation outright. -This is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)), -not an implementation detail awaiting a fix. Deferring `after*` to commit time -would move a handler's own `ctx.api` writes *outside* the transaction the write -ran in, which is a worse guarantee than the one documented here. +For a blocking hook this is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)), +not an implementation detail awaiting a fix. Deferring a blocking `after*` to +commit time would move its own `ctx.api` writes *outside* the transaction the +write ran in, which is a worse guarantee than the one documented here. An +`async: true` hook has no such writes to keep: nothing awaits it, so its writes +never joined the unit, and it is the one that waits for the commit (below). +### `async: true` after hooks run after the commit + +An `async: true` hook on `afterInsert`, `afterUpdate` or `afterDelete` is not +awaited: the write returns without waiting for it, and the hook can neither +abort the write nor have its writes rolled back with it. Inside a unit of work +(any row of the table above) it therefore waits for that unit's outcome: + +- **The unit commits:** the hook starts once the **outermost** unit has + committed, so its `ctx.api` reads see the triggering write. A nested + `transaction()` joins the outer unit, so its return is no commit. +- **The unit rolls back:** the hook **never runs**. It does not announce a + write that did not survive, so an `async` hook is the one to give an effect + outside the engine. To react to a write that was refused, use a blocking + hook, or record the refusal where the write is made. +- **Outside any unit**, or on a driver with no transactions: the hook starts + at once, as the write is dispatched. + +Either way its own `ctx.api` writes run outside the triggering unit, on their +own; a `ctx.api.transaction(...)` it opens is its own unit. An `async` +`afterFind` hook does not wait: a rollback does not undo a read, so it starts +when the read is dispatched, outside any unit, whatever the unit does next. + ## Refusing in the user's language — `refusals` A hook that says "no" to a write throws. A sentence written into the throw @@ -513,9 +540,10 @@ ctx = { - Trigger unbounded cascades of writes - Perform heavy/long-running work inline in a hook - Mutate `ctx.result` in before hooks (it is only populated for after hooks) -- Treat an `after*` hook as proof the write committed — it fires inside the - unit of work, so an un-retractable external effect there can outlive a - rollback (see [above](#after-hooks-run-inside-the-unit-of-work)) +- Treat a blocking `after*` hook as proof the write committed — it fires inside + the unit of work, so an un-retractable external effect there can outlive a + rollback (see [above](#after-hooks-run-inside-the-unit-of-work)); an + `async: true` one runs only after the commit ## Related business logic diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 60df2cbd04c..879222275c4 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -46,7 +46,7 @@ import { rolledBackRefusal } from './summary-errors.js'; import { TransactionUnsupportedError } from './transaction-errors.js'; import { redactPropagatedDriverFault } from '@objectstack/types'; import { UnscopedHookApi } from './hook-run-as.js'; -import { runOutsideOpenUnits } from './unit-detach.js'; +import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js'; import { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js'; import type { HookRunAs, HookRunAsRef } from './hook-run-as.js'; import { scopedContextHost } from './engine-scoped-hosts.js'; @@ -168,10 +168,14 @@ export class ScopedContextFacet { } /** The body of `ScopedContext#[DETACHED_HOOK_RUN]`; the method's docblock there is its contract. */ - static detachedHookRun(this: Pick, body: () => T): T { - // The engine's ambient store, reached the `as any` way `transaction` below reaches it. - const txStore = (this.engine as any)?.txStore; - return runOutsideOpenUnits(txStore, this.executionContext?.transaction, body); + static detachedHookRun(this: Pick, body: () => Promise, waitForCommit: boolean): Promise { + // The engine's ambient store and its published units, reached the `as any` + // way `transaction` below reaches them. + const engine = this.engine as any; + const threaded = this.executionContext?.transaction; + return waitForCommit + ? runOutsideOpenUnitsOnCommit(engine?.txStore, engine?.openedUnits, threaded, body) + : runOutsideOpenUnits(engine?.txStore, threaded, body); } /** The body of `ScopedContext#transaction`; the method's docblock there is its contract. */ @@ -239,23 +243,30 @@ export class ScopedContextFacet { // when the callback settles, so work the callback started and did not await // (an `async: true` hook) no longer keeps the finished handle, neither the // ambient one nor the `trxCtx` one threaded above. + // [#33760] With the engine's `ObjectQL.transaction` twin, the queue the + // `async` after-hooks dispatched in this unit wait on for its outcome. + const commitQueue = newUnitCommitQueue(); const runIn = (fn: () => Promise): Promise => - typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn) : fn(); + typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn, commitQueue) : fn(); + let result: any; try { // Reached only with no ambient transaction to join, so this call really // did open one and the callback owns the outcome (#5696 / #6168). - const result = await runIn(() => callback(trxCtx, { owned: true })); + result = await runIn(() => callback(trxCtx, { owned: true })); if (driver.commit) await driver.commit(trx); else if (driver.commitTransaction) await driver.commitTransaction(trx); - return result; } catch (error) { + settleUnitCommitQueue(commitQueue, false); if (driver.rollback) await driver.rollback(trx); else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx); // [#21274] The engine surface's twin (`ObjectQL.transaction`), the // stale-roll-up conversion included. throw redactPropagatedDriverFault(rolledBackRefusal(error)); } + // Committed: start the waiting runs, outside the `try`, never awaited. + settleUnitCommitQueue(commitQueue, true); + return result; } /** @@ -320,6 +331,9 @@ export class ScopedContextFacet { const driver = this.txDriver(); if (!driver) return null; const trx = await driver.beginTransaction(); + // [#33760] The `async` after-hooks dispatched in this unit wait for the + // trio's own commit, or are dropped by its rollback (`unit-detach.ts`). + openTrioCommitQueue(trx); const ctx = this.derive({ ...this.executionContext, transaction: trx }); return { ctx, handle: trx, owned: true }; } @@ -331,11 +345,13 @@ export class ScopedContextFacet { if (!driver) return; if (driver.commit) await driver.commit(handle); else if (driver.commitTransaction) await driver.commitTransaction(handle); + settleTrioCommitQueue(handle, true); } /** The body of `ScopedContext#rollbackTransaction`; the method's docblock there is its contract. */ static async rollbackTransaction(this: Pick, handle: unknown): Promise { if (this.releaseJoinedHandle(handle)) return; + settleTrioCommitQueue(handle, false); const driver = this.txDriver(); if (!driver) return; if (driver.rollback) await driver.rollback(handle); diff --git a/packages/objectql/src/engine-scoped-transaction-late-write.test.ts b/packages/objectql/src/engine-scoped-transaction-late-write.test.ts index 0600499de2c..d6c6b6206b5 100644 --- a/packages/objectql/src/engine-scoped-transaction-late-write.test.ts +++ b/packages/objectql/src/engine-scoped-transaction-late-write.test.ts @@ -204,16 +204,20 @@ describe('#22855 — un-awaited work does not keep a finished unit\'s handle', ( * ambiently. The unit then committed under them and the writes failed with * "Transaction query already complete". * - * The blocking leg waits until the async hook's write has reached the driver, - * as a blocking hook doing real work lets it, and that statement runs behind - * the unit's commit: the order the real failure took is fixed, not raced. + * [#33760] The async hook no longer starts inside that unit at all: it waits + * for the unit's commit (the commit-dispatch describe at the end of this + * file). The blocking leg used to wait here until the async hook's write had + * reached the driver, which fixed the order the real failure took; that write + * cannot reach the driver before the commit now, so the leg records whether + * the async hook had started instead, and the pins below read `false`. What + * they still pin is #33651's: the async hook's write is stored, outside the + * unit, on its own connection. */ async function makeUpdateEngine(legs: { blocking?: boolean; secondAsync?: boolean; asyncLeg?: boolean; ownUnit?: boolean } = {}) { const log = () => {}; const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any); const driver = makeDriver(); - let reached!: () => void; - const noteReached = new Promise((r) => { reached = r; }); + let reached = () => {}; let landed!: () => void; const commitLanded = new Promise((r) => { landed = r; }); const commit = driver.commit; @@ -236,11 +240,13 @@ async function makeUpdateEngine(legs: { blocking?: boolean; secondAsync?: boolea engine.registry.registerObject(obj('rec') as any, '__test__'); engine.registry.registerObject(obj('note') as any, '__test__'); const outcomes: string[] = []; + let asyncStarted = false; let report!: (outcome: string) => void; const drafted = new Promise((r) => { report = r; }); const draftNote = { name: 'draft_note', object: 'rec', events: ['afterUpdate'], async: true, runAs: 'system', onError: 'log', handler: async (ctx: any) => { + asyncStarted = true; openAtDispatch = new Set(driver.begun); try { if (legs.ownUnit) { @@ -258,8 +264,7 @@ async function makeUpdateEngine(legs: { blocking?: boolean; secondAsync?: boolea name: 'blocking_leg', object: 'rec', events: ['afterUpdate'], priority: 400, handler: async (ctx: any) => { await ctx.api.object('note').insert({ name: 'blocking' }); - await Promise.race([noteReached, new Promise((r) => setTimeout(r, 200))]); - outcomes.push('blocking ran'); + outcomes.push(asyncStarted ? 'blocking ran after the async hook started' : 'blocking ran'); }, } as unknown as Hook; const secondAsync = { ...blockingLeg, name: 'second_async', async: true, onError: 'log' } as unknown as Hook; @@ -339,3 +344,330 @@ describe('an async after-hook beside a blocking one writes outside the door\'s u expect(noteUnenrolled(driver)).toEqual([false]); }); }); + +/** + * #33760 — an `async: true` after-hook fired inside a unit of work starts once + * the OUTERMOST unit commits, and never when it rolls back (`unit-detach.ts`, + * `runOutsideOpenUnitsOnCommit`). Before, it started at dispatch, inside the + * unit: on a multi-connection database its `ctx.api` reads ran before the + * triggering write was visible, and a rollback did not stop it. + * + * Every unit the engine owns is one: a caller's `engine.transaction()`, a + * hook's or handler's `ctx.api.transaction(fn)`, and the write door's own unit + * for a blocking `after*` hook that can abort (#22782). The order is read off + * one event log the driver's commit and rollback write to, and a dropped run + * is read off the engine's own `debug` line for it, so "never ran" is an + * event, not a timeout. + */ +async function makeCommitEngine() { + const events: string[] = []; + let dropped!: (hook: string) => void; + const drops: string[] = []; + const quiet = () => {}; + // A deferred run's failure reaches the wrapper's error line (fire-and-forget). + let errored!: (hook: string) => void; + const erroredRun = new Promise((r) => { errored = r; }); + const logger = { + debug: (msg: string, meta?: any) => { if (/rolled back/.test(msg)) { drops.push(meta?.hook); dropped?.(meta?.hook); } }, + info: quiet, warn: quiet, + error: (msg: string, _err?: unknown, meta?: any) => { + if (/fire-and-forget/.test(msg)) { events.push(`error logged:${meta?.hook}`); errored(meta?.hook); } + }, + }; + const engine = new ObjectQL({ logger } as any); + const driver = makeDriver(); + const commit = driver.commit; + driver.commit = async (h: object) => { await commit(h); events.push('commit'); }; + const rollback = driver.rollback; + driver.rollback = async (h: object) => { await rollback(h); events.push('rollback'); }; + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(obj('rec') as any, '__test__'); + engine.registry.registerObject(obj('note') as any, '__test__'); + const ran: Record> = {}; + const settle: Record void> = {}; + const runOf = (name: string) => (ran[name] ??= new Promise((r) => { settle[name] = r; })); + const asyncNote = { + name: 'async_note', object: 'rec', events: ['afterInsert'], async: true, onError: 'log', + handler: async (ctx: any) => { + const name = String(ctx.input.name); + events.push(`async started:${name}`); + runOf(name); + // What the hook sees of its triggering row, and a write that references it. + const seen = (await ctx.api.object('rec').find({})).filter((r: any) => r.name === name).length; + await ctx.api.object('note').insert({ name: `note:${name}` }); + settle[name]!(seen); + }, + } as unknown as Hook; + // The door's unit: a blocking `afterInsert` that can abort (default `onError`), + // after the async one (priority 400 > 100), which vetoes a `veto` name. + const gate = { + name: 'gate', object: 'rec', events: ['afterInsert'], priority: 400, + handler: (ctx: any) => { + events.push(`gate:${ctx.input.name}`); + if (String(ctx.input.name).startsWith('veto')) throw new Error('refused by the gate'); + }, + } as unknown as Hook; + // [#33760 review] A `'user'` pin on a trigger that carries no user: the + // handler's `ctx.api` is the unscoped api (`UnscopedHookApi`), which has no + // engine and no detach of its own. It records the api it got, and touches no + // data (that api refuses every data door). + const apiKinds: string[] = []; + const userPin = { + name: 'user_pin', object: 'rec', events: ['afterInsert'], async: true, runAs: 'user', onError: 'log', + handler: (ctx: any) => { + const name = String(ctx.input.name); + events.push(`user-pin started:${name}`); + apiKinds.push(ctx.api?.constructor?.name); + runOf(name); + settle[name]!(0); + }, + } as unknown as Hook; + // [#33760 review#2] A read's `async` hook: a rollback does not undo the read, + // so its run is not the unit's to hold or drop. It writes a note of its own. + const readNote = { + name: 'read_note', object: 'rec', events: ['afterFind'], async: true, onError: 'log', + handler: async (ctx: any) => { + events.push('read-hook started'); + runOf('read'); + await ctx.api.object('note').insert({ name: 'note:read' }); + settle.read!(0); + }, + } as unknown as Hook; + // A deferred run that throws once it starts, after the commit. The default + // `onError` ('abort'), so the throw reaches the fire-and-forget catch. + const thrower = { + name: 'thrower', object: 'rec', events: ['afterInsert'], async: true, + handler: async () => { events.push('thrower started'); throw new Error('the deferred run fails'); }, + } as unknown as Hook; + const bind = (withGate: boolean, opts: { userPin?: boolean; read?: boolean; thrower?: boolean } = {}) => bindHooksToEngine( + engine, + opts.read ? [readNote] : opts.thrower ? [thrower] : opts.userPin ? [userPin] : withGate ? [asyncNote, gate] : [asyncNote], + { packageId: 'app:t', logger: logger as any }, + ); + const api = new ScopedContext({ isSystem: true } as any, engine as any); + const droppedRun = () => new Promise((r) => { dropped = r; }); + const notes = () => driver.rowsOf('note').map((r: any) => r.name); + return { engine, driver, api, events, drops, bind, runOf, droppedRun, notes, apiKinds, erroredRun }; +} + +/** Did the read's hook start while the unit is still open? Bounded, so a run held for the commit reads as `not started`. */ +const startedInUnit = (started: Promise) => Promise.race([ + started.then(() => 'started in the unit'), + new Promise((r) => setTimeout(() => r('not started in the unit'), 200)), +]); + +describe('#33760 — an async after-hook fired inside a unit runs on its commit, never on its rollback', () => { + it('engine.transaction() commits: the hook starts after the commit, sees its row, and writes outside the unit', async () => { + const { engine, driver, events, bind, runOf, notes } = await makeCommitEngine(); + bind(false); + await engine.transaction(async (trx: any) => { + await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } }); + events.push('callback returns'); + }); + expect(await runOf('r1')).toBe(1); + expect(events).toEqual(['callback returns', 'commit', 'async started:r1']); + expect(notes()).toEqual(['note:r1']); + expect(unenrolled(driver)).toEqual([['rec', false], ['note', true]]); + }); + + it('engine.transaction() rolls back: the hook never starts and writes nothing', async () => { + const { engine, driver, events, drops, bind, droppedRun, notes } = await makeCommitEngine(); + bind(false); + const drop = droppedRun(); + await expect(engine.transaction(async (trx: any) => { + await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } }); + throw new Error('the caller rolls back'); + })).rejects.toThrow('the caller rolls back'); + expect(await drop).toBe('async_note'); + expect(events).toEqual(['rollback']); + expect(drops).toEqual(['async_note']); + expect([driver.rowsOf('rec'), notes()]).toEqual([[], []]); + }); + + it('ctx.api.transaction(fn) commits: the hook starts after the commit and sees its row', async () => { + const { api, events, bind, runOf, notes } = await makeCommitEngine(); + bind(false); + await api.transaction(async (tx) => { await tx.object('rec').insert({ name: 'r1' }); events.push('callback returns'); }); + expect(await runOf('r1')).toBe(1); + expect(events).toEqual(['callback returns', 'commit', 'async started:r1']); + expect(notes()).toEqual(['note:r1']); + }); + + it('ctx.api.transaction(fn) rolls back: the hook never starts and writes nothing', async () => { + const { api, events, bind, droppedRun, notes } = await makeCommitEngine(); + bind(false); + const drop = droppedRun(); + await expect(api.transaction(async (tx) => { + await tx.object('rec').insert({ name: 'r1' }); + throw new Error('the caller rolls back'); + })).rejects.toThrow('the caller rolls back'); + expect(await drop).toBe('async_note'); + expect(events).toEqual(['rollback']); + expect(notes()).toEqual([]); + }); + + it('nested: an inner ctx.api.transaction(fn) that returns is no commit, and the outer rollback drops the hook', async () => { + const { engine, api, events, bind, droppedRun, notes } = await makeCommitEngine(); + bind(false); + const drop = droppedRun(); + await expect(engine.transaction(async () => { + await api.transaction(async (tx, info) => { + expect(info.owned).toBe(false); + await tx.object('rec').insert({ name: 'r1' }); + }); + events.push('inner returned'); + throw new Error('the outer caller rolls back'); + })).rejects.toThrow('the outer caller rolls back'); + expect(await drop).toBe('async_note'); + expect(events).toEqual(['inner returned', 'rollback']); + expect(notes()).toEqual([]); + }); + + it('nested: the outer commit starts the hook once, after it', async () => { + const { engine, api, events, bind, runOf } = await makeCommitEngine(); + bind(false); + await engine.transaction(async () => { + await api.transaction(async (tx) => { await tx.object('rec').insert({ name: 'r1' }); }); + events.push('inner returned'); + }); + expect(await runOf('r1')).toBe(1); + expect(events).toEqual(['inner returned', 'commit', 'async started:r1']); + }); + + it('blocking + async on the same event, the door\'s own unit commits: the blocking hook runs in the unit, the async one after the commit', async () => { + const { driver, api, events, bind, runOf, notes } = await makeCommitEngine(); + bind(true); + await api.object('rec').insert({ name: 'r1' }); + expect(await runOf('r1')).toBe(1); + expect(driver.begun).toHaveLength(1); + expect(events).toEqual(['gate:r1', 'commit', 'async started:r1']); + expect(notes()).toEqual(['note:r1']); + }); + + it('blocking + async on the same event, the blocking hook aborts: the door\'s unit rolls back and the async hook never starts', async () => { + const { driver, api, events, bind, droppedRun, notes } = await makeCommitEngine(); + bind(true); + const drop = droppedRun(); + await expect(api.object('rec').insert({ name: 'veto' })).rejects.toThrow('refused by the gate'); + expect(await drop).toBe('async_note'); + expect(events).toEqual(['gate:veto', 'rollback']); + expect([driver.rowsOf('rec'), notes()]).toEqual([[], []]); + }); + + it('the beginTransaction trio (the sandbox runner\'s ctx.api.transaction): the hook waits for its commitTransaction', async () => { + const { api, events, bind, runOf } = await makeCommitEngine(); + bind(false); + const unit = (await api.beginTransaction())!; + expect(unit.owned).toBe(true); + await unit.ctx.object('rec').insert({ name: 'r1' }); + events.push('body done'); + await api.commitTransaction(unit.handle); + expect(await runOf('r1')).toBe(1); + expect(events).toEqual(['body done', 'commit', 'async started:r1']); + }); + + it('the beginTransaction trio rolls back: the hook never starts', async () => { + const { api, events, bind, droppedRun, notes } = await makeCommitEngine(); + bind(false); + const drop = droppedRun(); + const unit = (await api.beginTransaction())!; + await unit.ctx.object('rec').insert({ name: 'r1' }); + await api.rollbackTransaction(unit.handle); + expect(await drop).toBe('async_note'); + expect(events).toEqual(['rollback']); + expect(notes()).toEqual([]); + }); + + it('runAs \'user\' on a user-less system write in engine.transaction(): the unscoped api still waits for the commit', async () => { + const { engine, events, bind, runOf, apiKinds } = await makeCommitEngine(); + bind(false, { userPin: true }); + await engine.transaction(async (trx: any) => { + await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } }); + events.push('callback returns'); + }); + await runOf('r1'); + expect(events).toEqual(['callback returns', 'commit', 'user-pin started:r1']); + expect(apiKinds).toEqual(['UnscopedHookApi']); + }); + + it('runAs \'user\' on a user-less system write in engine.transaction() that rolls back: the hook never starts', async () => { + const { engine, events, drops, bind, droppedRun } = await makeCommitEngine(); + bind(false, { userPin: true }); + const drop = droppedRun(); + await expect(engine.transaction(async (trx: any) => { + await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } }); + throw new Error('the caller rolls back'); + })).rejects.toThrow('the caller rolls back'); + expect(await drop).toBe('user_pin'); + expect(events).toEqual(['rollback']); + expect(drops).toEqual(['user_pin']); + }); + + it('a deferred run that throws after the commit: transaction() still resolves and the failure is logged', async () => { + const { engine, events, bind, erroredRun } = await makeCommitEngine(); + bind(false, { thrower: true }); + await expect(engine.transaction(async (trx: any) => { + await engine.insert('rec', { name: 'r1' }, { context: { ...trx, isSystem: true } }); + events.push('callback returns'); + return 'resolved'; + })).resolves.toBe('resolved'); + expect(await erroredRun).toBe('thrower'); + expect(events).toEqual(['callback returns', 'commit', 'thrower started', 'error logged:thrower']); + }); + + it('afterFind inside engine.transaction() that commits: a read\'s async hook starts at dispatch, in the unit\'s lifetime, not after the commit', async () => { + const { engine, driver, events, bind, runOf, notes } = await makeCommitEngine(); + await engine.insert('rec', { name: 'r0' }, { context: { isSystem: true } }); + bind(false, { read: true }); + await engine.transaction(async (trx: any) => { + await engine.find('rec', {}, { context: { ...trx, isSystem: true } }); + events.push(await startedInUnit(runOf('read'))); + }); + await runOf('read'); + expect(events).toEqual(['read-hook started', 'started in the unit', 'commit']); + expect(notes()).toEqual(['note:read']); + // Outside the unit, as under #33651: its write enrolled in nothing. + expect(unenrolled(driver).filter(([o]) => o === 'note')).toEqual([['note', true]]); + }); + + it('afterFind inside engine.transaction() that rolls back: the read\'s async hook still runs, outside the unit', async () => { + const { engine, driver, events, drops, bind, runOf } = await makeCommitEngine(); + await engine.insert('rec', { name: 'r0' }, { context: { isSystem: true } }); + bind(false, { read: true }); + await expect(engine.transaction(async (trx: any) => { + await engine.find('rec', {}, { context: { ...trx, isSystem: true } }); + events.push(await startedInUnit(runOf('read'))); + throw new Error('the caller rolls back'); + })).rejects.toThrow('the caller rolls back'); + await runOf('read'); + expect(events).toEqual(['read-hook started', 'started in the unit', 'rollback']); + expect(drops).toEqual([]); + // Its write enrolled in nothing. (This double's rollback restores a whole + // store snapshot, so the row itself is not read here; the dogfood twin + // reads it standing on SQLite.) + expect(unenrolled(driver).filter(([o]) => o === 'note')).toEqual([['note', true]]); + }); + + it('CONTROL afterFind outside any unit: the read\'s async hook starts at dispatch, unchanged', async () => { + const { driver, api, events, bind, runOf, notes } = await makeCommitEngine(); + await api.object('rec').insert({ name: 'r0' }); + bind(false, { read: true }); + await api.object('rec').find({}); + events.push('find returns'); + await runOf('read'); + expect(events).toEqual(['read-hook started', 'find returns']); + expect(driver.begun).toHaveLength(0); + expect(notes()).toEqual(['note:read']); + }); + + it('CONTROL outside any unit: the hook starts at dispatch, before the write returns, unchanged', async () => { + const { driver, api, events, bind, runOf } = await makeCommitEngine(); + bind(false); + await api.object('rec').insert({ name: 'r1' }); + events.push('insert returns'); + expect(await runOf('r1')).toBe(1); + expect(events).toEqual(['async started:r1', 'insert returns']); + expect(driver.begun).toHaveLength(0); + }); +}); diff --git a/packages/objectql/src/engine-transactions-section.ts b/packages/objectql/src/engine-transactions-section.ts index eed7dd98b00..58cb7b9b9f7 100644 --- a/packages/objectql/src/engine-transactions-section.ts +++ b/packages/objectql/src/engine-transactions-section.ts @@ -34,7 +34,7 @@ import { redactPropagatedDriverFault } from '@objectstack/types'; import type { EngineTransactionInfo, EngineTransactionOptions, IDataDriver } from '@objectstack/core'; import { rollbackFailedRefusal, rolledBackRefusal } from './summary-errors.js'; import { TransactionUnsupportedError } from './transaction-errors.js'; -import { isDetachedUnitHandle } from './unit-detach.js'; +import { isDetachedUnitHandle, newUnitCommitQueue, settleUnitCommitQueue, type UnitCommitQueue } from './unit-detach.js'; import type { TransactionScope } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; @@ -103,15 +103,18 @@ export class TransactionsSectionFacet { } const trx = await drv.beginTransaction(); const trxCtx = { ...(baseContext ?? {}), transaction: trx }; + // [#33760] The `async` after-hooks dispatched in this unit wait here for its outcome. + const commitQueue = newUnitCommitQueue(); + let result: T; try { // Run the callback inside the ambient transaction store so internal // queries during writes reuse this transaction's connection (ADR-0034), // CLOSED once the callback settles, before the commit (#22782, #22855). - const result = await this.runOpenedUnit(trx, driver!, () => callback(trxCtx, { owned: true })); + result = await this.runOpenedUnit(trx, driver!, () => callback(trxCtx, { owned: true }), commitQueue); if (drv.commit) await drv.commit(trx); else if (drv.commitTransaction) await drv.commitTransaction(trx); - return result; } catch (err) { + settleUnitCommitQueue(commitQueue, false); let rollbackFailed = false; try { if (drv.rollback) await drv.rollback(trx); @@ -129,6 +132,10 @@ export class TransactionsSectionFacet { // `rollbackFailedRefusal`. throw redactPropagatedDriverFault(rollbackFailed ? rollbackFailedRefusal(err) : rolledBackRefusal(err)); } + // Outside the `try`: the unit has committed, and nothing a waiting run + // does may reach the rollback path. Each run is started, never awaited. + settleUnitCommitQueue(commitQueue, true); + return result; } /** @@ -155,10 +162,17 @@ export class TransactionsSectionFacet { * * A primitive handle cannot key {@link openedUnits}, so it keeps only the * ambient half. + * + * [#33760] `commitQueue`, when the caller passes one, rides the entry and + * OUTLIVES the close: an `async: true` hook dispatched in the unit waits on + * it (`runOutsideOpenUnitsOnCommit`, `unit-detach.ts`) until the caller — + * the one that commits or rolls back — settles it. The close above does + * not touch it, so work dispatched between the callback's settling and the + * commit still waits for the commit. */ - static runOpenedUnit(this: Pick, trx: unknown, owner: IDataDriver, body: () => Promise): Promise { - const entry: { transaction: unknown; scope?: TransactionScope } = - { transaction: trx, scope: this.newTransactionScope(owner) }; + static runOpenedUnit(this: Pick, trx: unknown, owner: IDataDriver, body: () => Promise, commitQueue?: UnitCommitQueue): Promise { + const entry: { transaction: unknown; scope?: TransactionScope; commitQueue?: UnitCommitQueue } = + { transaction: trx, scope: this.newTransactionScope(owner), ...(commitQueue ? { commitQueue } : {}) }; if (trx !== null && (typeof trx === 'object' || typeof trx === 'function')) this.openedUnits.set(trx, entry); return this.txStore.run(entry, body).finally(() => { entry.transaction = undefined; entry.scope = undefined; }); } diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 7bbfc0ea205..a91fc41a7a2 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -244,7 +244,7 @@ import { stripReadonlyFields, staticReadonlyInsertSubject } from './validation/r // and points at `ctx.previous` — the module owns the measurement and the // reason the explanation cannot be composed any further downstream. import { UnscopedHookApi, SEED_USER_GRANTS, APP_AUTHORED_HOOK_API, type HookRunAs, type HookRunAsRef, type RunAsDerivableApi } from './hook-run-as.js'; -import { DETACHED_HOOK_RUN } from './unit-detach.js'; +import { DETACHED_HOOK_RUN, type UNIT_ROLLED_BACK, type UnitCommitQueue } from './unit-detach.js'; // [#6457] The master-detail header a `parent`-scoped predicate reads is made // total over the MASTER's declared fields before it leaves this engine — the // same helper every other server seam materialises with (#1871/#4649/#4953). @@ -417,6 +417,12 @@ export class ObjectQL implements IObjectQLEngine { * caller populated, so every reader must treat it as optional. */ scope?: TransactionScope; + /** + * [#33760] The `async: true` after-hook runs waiting for this unit's + * commit, when its owner opened one (`unit-detach.ts`). Absent where the + * entry's unit has no owner here to settle it, as `scope` is. + */ + commitQueue?: UnitCommitQueue; }>(); /** @@ -427,7 +433,7 @@ export class ObjectQL implements IObjectQLEngine { * here ({@link isClosedUnitHandle}). Weak, so a finished unit's handle stays * collectable. */ - private readonly openedUnits = new WeakMap(); + private readonly openedUnits = new WeakMap(); /** * [#22305] The {@link CascadeDeleteSet} of the by-id cascade delete in @@ -5371,9 +5377,9 @@ export class ObjectQL implements IObjectQLEngine { return (TransactionsSectionFacet.transaction).call(transactionsSectionHost.of(this), callback, baseContext, opts); } - private runOpenedUnit(trx: unknown, owner: IDataDriver, body: () => Promise): Promise { + private runOpenedUnit(trx: unknown, owner: IDataDriver, body: () => Promise, commitQueue?: UnitCommitQueue): Promise { // [#29986 codemod] The body moved to `engine-transactions-section.ts`, its docblock with it (see `TransactionsSectionHost`). - return (TransactionsSectionFacet.runOpenedUnit).call(transactionsSectionHost.of(this), trx, owner, body); + return (TransactionsSectionFacet.runOpenedUnit).call(transactionsSectionHost.of(this), trx, owner, body, commitQueue); } private isClosedUnitHandle(handle: unknown): boolean { @@ -6538,13 +6544,17 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi { * and the one this api carries treated as closed for the run * (`runOutsideOpenUnits`, `unit-detach.ts`). Called by `wrapDeclarativeHook` * when such a hook detaches, so its writes never enrol in a unit that - * commits under them. + * commits under them. [#33760] With `waitForCommit` (a write event's run, + * `waitsForUnitCommit`), started once the unit it was dispatched in + * commits, and answering `UNIT_ROLLED_BACK` without running when that unit + * rolls back (`runOutsideOpenUnitsOnCommit`); at once outside any unit, and + * at once for any other event (`afterFind`). * * Keyed on {@link DETACHED_HOOK_RUN}, a symbol the package entry does not * export, so it is no nameable member of this class's published face. */ - [DETACHED_HOOK_RUN](body: () => T): T { - return (ScopedContextFacet.detachedHookRun).call(scopedContextHost.of(this), body); + [DETACHED_HOOK_RUN](body: () => Promise, waitForCommit: boolean): Promise { + return (ScopedContextFacet.detachedHookRun).call(scopedContextHost.of(this), body, waitForCommit); } /** diff --git a/packages/objectql/src/hook-wrappers.ts b/packages/objectql/src/hook-wrappers.ts index 7f2d8ac3c97..1fe0e341418 100644 --- a/packages/objectql/src/hook-wrappers.ts +++ b/packages/objectql/src/hook-wrappers.ts @@ -24,7 +24,7 @@ import { materializeDeclaredFields } from './declared-fields.js'; import { describeCelFault, type CelFault } from './cel-fault.js'; import { nullPreviousReadDetail, ruleScope, type PreviousBinding } from './validation/rule-validator.js'; import { hookRunAs, deriveHookApi, deriveAppAuthoredHookApi, seedHookUserGrants, seedHookUnreadMembership, type HookRunAs } from './hook-run-as.js'; -import { runDetachedHook } from './unit-detach.js'; +import { runDetachedHook, UNIT_ROLLED_BACK, waitsForUnitCommit } from './unit-detach.js'; /** * The logger the hook layer writes its diagnostics to — the `Logger` CONTRACT @@ -267,7 +267,8 @@ export function declaredHookCondition(meta: Pick): (Expressio * * 1. condition → skip when the formula evaluates FALSE; abort the operation * when it cannot be evaluated at all (#4775) - * 2. async → fire-and-forget (after* events only) + * 2. async → fire-and-forget (after* events only), on the commit of + * the unit it fires in, never on its rollback (#33760) * 3. retry → repeat on throw with backoff * 4. timeout → abort if handler runs too long * 5. onError → swallow when set to 'log' @@ -474,6 +475,13 @@ export function wrapDeclarativeHook( } const restore = installFlatInput(ctx); + // [#33760] The engine-built api, held before a `runAs` install replaces it: + // the unit an `async` run waits for is the one the TRIGGERING write is in, + // and only this api knows it. A derived api need not — the unscoped one a + // `'user'` pin gets on a user-less trigger (`UnscopedHookApi`) carries no + // engine and no detach at all, so asking it would start the run at once, + // inside the unit, and after a rollback too. + const engineApi = ctx.api; // [#14010] `runAs` is applied to `ctx.api` ONLY, and only for the handler // call — the same install/restore shape as the flat input above, so the // engine's own context object is never touched (the condition gate above @@ -515,12 +523,29 @@ export function wrapDeclarativeHook( // as before this key existed — unless the hook is app-authored, whose // derived api (#25653) the same restore would take away. const detached = restoreApi === noRestore ? ctx : { ...ctx }; + // [#33760] A run that waits for its unit's commit starts after both + // restores below, so it gets a copy taken now, which keeps the flat + // input and the api the handler is owed. One that starts now (outside + // any unit) still gets `detached`, by reference as before. + const atDispatch = detached === ctx ? { ...ctx } : detached; + let dispatching = true; // [#33651] And it runs outside every unit of work open at dispatch — // the door's own unit for a blocking `after*` beside it (#22782), or a // caller's: nothing awaits it, so a unit it joined would commit under - // its writes ("Transaction query already complete"). `unit-detach.ts`. - void runDetachedHook(detached.api, () => runWithErrorPolicy(detached)) - .then(() => recordOutcome()) + // its writes ("Transaction query already complete"). [#33760] Once + // that unit commits, and not at all when it rolls back — the unit read + // off `engineApi`, whatever api the handler itself runs on. Only for a + // write event: a rollback does not undo a read, so an `afterFind` run + // starts now. `unit-detach.ts`. + void runDetachedHook(engineApi, () => runWithErrorPolicy(dispatching ? detached : atDispatch), waitsForUnitCommit(ctx.event)) + .then((ran) => { + if (ran !== UNIT_ROLLED_BACK) { recordOutcome(); return; } + logger.debug('[hook] async handler not run: the unit of work it was fired in rolled back', { + hook: meta.name, + object: ctx.object, + event: ctx.event, + }); + }) .catch((err) => { recordOutcome(err); // Contract arg order (#5637) — see the `onError=log` site above. @@ -529,6 +554,7 @@ export function wrapDeclarativeHook( error: (err as any)?.message, }); }); + dispatching = false; return; } diff --git a/packages/objectql/src/unit-detach.ts b/packages/objectql/src/unit-detach.ts index 7415f1c6f79..92e2c11dbf5 100644 --- a/packages/objectql/src/unit-detach.ts +++ b/packages/objectql/src/unit-detach.ts @@ -37,9 +37,37 @@ * handle and is its own. On a single-connection pool such a write waits for * the dispatching unit to release the connection, which nothing awaits, so it * cannot deadlock the dispatching write. + * + * [#33760] And the detached run waits for the unit to SETTLE: it starts once + * the outermost unit open at dispatch commits, and never when that unit rolls + * back. Started at dispatch, the hook ran while the triggering write was not + * committed yet: on a database with more than one connection its `ctx.api` + * reads did not see that write, and a rollback did not stop it (measured on + * Postgres and on SQLite through knex). The unit's owner — `ObjectQL`'s + * `transaction()` or `ScopedContext`'s, through the one `runOpenedUnit` both + * run their callback in — gives the unit a {@link UnitCommitQueue} and settles + * it after its commit or rollback ({@link settleUnitCommitQueue}). A nested + * `transaction()` joins the outer unit (ADR-0067 D2) and opens no queue, so + * its return is no commit: the outer unit's outcome decides. The + * `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio — the + * sandbox runner's `ctx.api.transaction(fn)` — opens one per handle it owns + * ({@link openTrioCommitQueue}). Outside any unit, or where no unit opened + * (a driver without transactions), the run starts at dispatch, as before. + * + * Only a WRITE event's run waits ({@link waitsForUnitCommit}). A rollback + * undoes the write that fired `afterInsert` / `afterUpdate` / `afterDelete`, + * so a run that announces it must not outlive it. It does not undo a read: + * the rows `afterFind` saw were already returned to the caller, so an `async` + * `afterFind` run starts at dispatch, outside the units, as under #33651, + * whatever the unit it was read in does next. + * + * Every run a unit queued starts in one synchronous pass once it commits, in + * dispatch order: a bulk write with a per-row `async` hook holds one context + * copy per row until then, bounded by the per-row hook budget + * (`resolveBulkPerRowHookBudget`), and then starts every handler at once. */ -import { AsyncLocalStorage } from 'node:async_hooks'; +import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; /** The unit handles the current run was detached from, accumulated across nested detached runs. */ const detachedHandles = new AsyncLocalStorage>(); @@ -68,9 +96,129 @@ export function runOutsideOpenUnits( return typeof txStore?.exit === 'function' ? txStore.exit(run) : run(); } +/** + * The events whose `async` run waits for the commit of the unit it was + * dispatched in, and is dropped when that unit rolls back: the `after*` + * events of a write. Any other event (`afterFind`) starts at dispatch. + */ +const UNIT_SETTLED_EVENTS: ReadonlySet = new Set(['afterInsert', 'afterUpdate', 'afterDelete']); + +/** Does an `async` run dispatched for `event` wait for its unit's commit? */ +export function waitsForUnitCommit(event: unknown): boolean { + return typeof event === 'string' && UNIT_SETTLED_EVENTS.has(event); +} + +/** What a detached run answers when the unit it waited for rolled back: the body never ran. */ +export const UNIT_ROLLED_BACK: unique symbol = Symbol('objectstack.objectql.unitRolledBack'); + +/** + * [#33760] The runs waiting for one unit to commit. `pending` is the list + * while the unit is open, and `undefined` once {@link settleUnitCommitQueue} + * has settled it, so a run asked for after that starts at once. + */ +export interface UnitCommitQueue { + pending: Array<{ commit(): void; drop(): void }> | undefined; +} + +/** A queue for a unit about to open: its owner settles it after the commit or rollback. */ +export function newUnitCommitQueue(): UnitCommitQueue { + return { pending: [] }; +} + +/** + * Settle `queue` once its unit's outcome is known: start every waiting run + * when the unit `committed`, drop every one when it rolled back. Emptied + * first, so a run that dispatches another starts that one at once. + */ +export function settleUnitCommitQueue(queue: UnitCommitQueue | undefined, committed: boolean): void { + const pending = queue?.pending; + if (!queue || !pending) return; + queue.pending = undefined; + for (const run of pending) { + // Each run is fire-and-forget and handles its own outcome; one that + // throws synchronously must not cost the next its start. + try { if (committed) run.commit(); else run.drop(); } catch { /* the run's own outcome */ } + } +} + +/** + * The queues of the units the `beginTransaction` trio opened, by handle. The + * trio never publishes its unit (no closure spans begin to commit), so its + * queue cannot ride a store entry; its own `commitTransaction` / + * `rollbackTransaction` settle it ({@link settleTrioCommitQueue}). Weak, so a + * handle nobody commits or rolls back takes its waiting runs with it, exactly + * as it takes its uncommitted writes. + */ +const trioQueues = new WeakMap(); + +/** The trio opened a unit on `handle`: runs dispatched in it wait for its commit. */ +export function openTrioCommitQueue(handle: unknown): void { + if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) trioQueues.set(handle, newUnitCommitQueue()); +} + +/** The trio committed (`committed`) or rolled back the unit on `handle`. */ +export function settleTrioCommitQueue(handle: unknown, committed: boolean): void { + if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return; + const queue = trioQueues.get(handle); + trioQueues.delete(handle); + settleUnitCommitQueue(queue, committed); +} + +/** A unit entry as the engine's ambient store and its `openedUnits` map hold it. */ +interface QueuedUnitEntry { transaction?: unknown; commitQueue?: UnitCommitQueue } + +/** + * The queue of the unit a run dispatched now is inside, while that unit has + * not settled: the ambient entry's, else the one of the unit whose handle the + * api carries (published, or the trio's). A handle the current run was detached from is no unit to wait + * for: the run is already past that unit's commit. + */ +function unsettledUnitQueue( + txStore: Pick, 'getStore'> | undefined, + openedUnits: Pick, 'get'> | undefined, + threaded: unknown, +): UnitCommitQueue | undefined { + const ambient = txStore?.getStore(); + if (ambient?.commitQueue?.pending) return ambient.commitQueue; + if (threaded === null || (typeof threaded !== 'object' && typeof threaded !== 'function')) return undefined; + if (isDetachedUnitHandle(threaded)) return undefined; + const queue = openedUnits?.get(threaded)?.commitQueue ?? trioQueues.get(threaded); + return queue?.pending ? queue : undefined; +} + +/** + * [#33760] Run `body` outside every unit open now ({@link runOutsideOpenUnits}), + * once the unit it was dispatched in commits: queued on that unit's + * {@link UnitCommitQueue}, in the async context of the dispatch, and answering + * {@link UNIT_ROLLED_BACK} without running when the unit rolls back. With no + * unsettled unit to wait for, `body` starts now. + */ +export function runOutsideOpenUnitsOnCommit( + txStore: Pick, 'getStore' | 'exit'> | undefined, + openedUnits: Pick, 'get'> | undefined, + threaded: unknown, + body: () => Promise, +): Promise { + const queue = unsettledUnitQueue(txStore, openedUnits, threaded); + if (!queue) return runOutsideOpenUnits(txStore, threaded, body); + return new Promise((resolve, reject) => { + // Bound to the dispatch's async context, so the run sees the stores it + // was dispatched under (identity, cascade), not the committing owner's. + const start = AsyncResource.bind(() => { + try { + runOutsideOpenUnits(txStore, threaded, body).then(resolve, reject); + } catch (err) { + reject(err); + } + }); + queue.pending!.push({ commit: start, drop: () => resolve(UNIT_ROLLED_BACK) }); + }); +} + /** * The key of `ScopedContext#[DETACHED_HOOK_RUN]`, which runs a body outside - * the units open for that api ({@link runOutsideOpenUnits}). A symbol, and ⛔ + * the units open for that api, at once or once the unit it was dispatched in + * commits ({@link runOutsideOpenUnitsOnCommit}). A symbol, and ⛔ * not re-exported from the package entry, for the reason `SEED_USER_GRANTS` * gives (`hook-run-as.ts`): it is no nameable member of the class's published * face. @@ -78,16 +226,18 @@ export function runOutsideOpenUnits( export const DETACHED_HOOK_RUN: unique symbol = Symbol('objectstack.objectql.detachedHookRun'); interface DetachableHookApi { - [DETACHED_HOOK_RUN](body: () => T): T; + [DETACHED_HOOK_RUN](body: () => Promise, waitForCommit: boolean): Promise; } /** * Run an `async` hook's `body` detached from the units open for `api`, the - * hook's `ctx.api`. An api that cannot detach (a hook context assembled by - * hand) runs `body` as is. + * hook's `ctx.api`. With `waitForCommit` ({@link waitsForUnitCommit}), once the + * unit it was dispatched in commits, answering {@link UNIT_ROLLED_BACK} when + * that unit rolls back instead; without it, at once. An api that cannot + * detach (a hook context assembled by hand) runs `body` as is. */ -export function runDetachedHook(api: unknown, body: () => T): T { +export function runDetachedHook(api: unknown, body: () => Promise, waitForCommit: boolean): Promise { const detachable = api as Partial | undefined; if (!detachable || typeof detachable[DETACHED_HOOK_RUN] !== 'function') return body(); - return detachable[DETACHED_HOOK_RUN](body); + return detachable[DETACHED_HOOK_RUN](body, waitForCommit); } diff --git a/packages/qa/dogfood/test/hook-after-abort-rollback.dogfood.test.ts b/packages/qa/dogfood/test/hook-after-abort-rollback.dogfood.test.ts index 22991429189..1939ca150f7 100644 --- a/packages/qa/dogfood/test/hook-after-abort-rollback.dogfood.test.ts +++ b/packages/qa/dogfood/test/hook-after-abort-rollback.dogfood.test.ts @@ -15,9 +15,11 @@ // hook answers REST's sanitised `500 INTERNAL_ERROR` (its terminal branch) on // both sides of the fix; what this file pins is what is STORED. // -// One more case the unit made necessary: an `async: true` hook is started -// inside the unit and writes after it commits. It used to inherit the finished -// handle and lose its write ("Transaction query already complete", measured). +// One more case the unit made necessary: an `async: true` hook fired inside +// the unit. It used to start inside the unit, inherit the finished handle and +// lose its write ("Transaction query already complete", measured). Since +// #33760 it starts only after the unit commits, and not at all on a rollback; +// the positive control below still reads its late note. import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; diff --git a/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts b/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts index 666d4586e4e..f8c8843102d 100644 --- a/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts +++ b/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts @@ -29,6 +29,30 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; const TRIGGER = 'stl_trigger'; const REC = 'stl_rec'; const NOTE = 'stl_note'; +/** The commit-dispatch describe's objects: `UNIT` is written inside units, `DOOR` opens the door's own. */ +const UNIT = 'stl_unit'; +const DOOR = 'stl_door'; +/** Read inside units: its `async` `afterFind` hook is not the unit's to hold or drop (#33760 review#2). */ +const READ = 'stl_read'; + +/** Names whose `async` hook has STARTED (set synchronously, at the first line of its body). */ +const started = new Set(); +/** Names whose `async` hook has FINISHED, with the count of its own row its read saw. */ +const finished = new Map(); +/** Per `DOOR` name: had the `async` hook started when the blocking hook after it ran? */ +const startedAtGate = new Map(); +/** + * The card's `async` hook: mark the start, re-read the triggering row through + * `ctx.api` (what a multi-connection database shows it depends on whether the + * unit has committed), and write a note that references it. + */ +const commitProbe = (object: string) => async (ctx: any) => { + const name = String(ctx.input.data.name); + started.add(name); + const seen = (await ctx.api.object(object).find({ where: { name } })).length; + await ctx.api.object(NOTE).insert({ name: 'after-commit', rec_name: name }); + finished.set(name, seen); +}; const named = (name: string) => ObjectSchema.create({ name, label: name, sharingModel: 'public_read_write', @@ -41,7 +65,7 @@ const stlStack = defineStack({ name: 'Scoped transaction late-write fixture', description: 'A handler that writes inside ctx.api.transaction, and an async hook that writes after the unit commits.', }, - objects: [named(TRIGGER), named(REC), named(NOTE)], + objects: [named(TRIGGER), named(REC), named(NOTE), named(UNIT), named(DOOR), named(READ)], hooks: [ // The handler of the card's measurement. A `before*` hook, so the write // door opens no unit of its own (#22782) and `ctx.api.transaction` really @@ -52,6 +76,19 @@ const stlStack = defineStack({ if (name.startsWith('explicit')) { // The card's probe: the write goes through the unit's own context. await ctx.api.transaction(async (tx: any) => { await tx.object(REC).insert({ name }); }); + } else if (name.startsWith('unit')) { + // The commit-dispatch describe: a unit this hook opens and owns + // (`unit-commit`), or one it rolls back (`unit-rollback`) and + // swallows, so the trigger row itself is stored either way. Inside + // a caller's unit the same call joins it (`unit-nested`). + try { + await ctx.api.transaction(async (tx: any) => { + await tx.object(UNIT).insert({ name }); + if (name.startsWith('unit-rollback')) throw new Error('rolled back by the probe'); + }); + } catch (e) { + if (!name.startsWith('unit-rollback')) throw e; + } } else if (name.startsWith('ambient')) { // Same unit, but the write goes through the OUTER api: only the // ambient store enrols it. @@ -66,6 +103,26 @@ const stlStack = defineStack({ await new Promise((r) => setTimeout(r, 40)); await ctx.api.object(NOTE).insert({ name: 'late', rec_name: ctx.input.data.name }); } }, + { name: 'stl_unit_async', object: UNIT, events: ['afterInsert'], async: true, onError: 'log', handler: commitProbe(UNIT) }, + // The door's own unit (#22782): a blocking `afterInsert` that can abort + // makes the write door open one. It runs after the `async` hook is + // dispatched (priority 400 > 100), records whether that hook had already + // started, and vetoes a `veto-` name, which rolls the door's unit back. + // A read's `async` hook: per row read, mark the start and write a note. + { name: 'stl_read_async', object: READ, events: ['afterFind'], async: true, onError: 'log', + handler: async (ctx: any) => { + const names = (Array.isArray(ctx.result) ? ctx.result : []).map((r: any) => String(r.name)); + for (const name of names) started.add(name); + for (const name of names) await ctx.api.object(NOTE).insert({ name: 'after-read', rec_name: name }); + for (const name of names) finished.set(name, 1); + } }, + { name: 'stl_door_async', object: DOOR, events: ['afterInsert'], async: true, onError: 'log', handler: commitProbe(DOOR) }, + { name: 'stl_door_gate', object: DOOR, events: ['afterInsert'], priority: 400, + handler: (ctx: any) => { + const name = String(ctx.input.data.name); + startedAtGate.set(name, started.has(name)); + if (name.startsWith('veto')) throw new Error('refused by the gate'); + } }, ], } as never); @@ -113,3 +170,150 @@ describe('un-awaited work does not keep a finished unit\'s handle (#22855)', () expect([await stored(REC, name), await lateNotes(name)]).toEqual([1, 1]); }); }); + +// #33760 — an `async: true` after-hook fired inside a unit of work runs once the +// OUTERMOST unit commits, and not at all when it rolls back. Before, it started +// at dispatch, while the unit was still open: on a multi-connection database its +// `ctx.api` reads could not see the triggering row yet, and a rollback did not +// stop it. On this single-connection SQLite pool its statements queued behind +// the unit; the start, and the run after a rollback, were the same. +// +// The three units the card names: the write door's own (a blocking `afterInsert` +// beside the async one), a caller's `engine.transaction()`, and a hook's +// `ctx.api.transaction(fn)`. A rollback is judged after a SENTINEL: the same +// object written outside any unit, whose hook runs at once — when its note is +// in, a hook queued earlier on the same connection would have run too. +describe('an async after-hook fired inside a unit runs on its commit, not on its rollback (#33760)', () => { + let stack: VerifyStack; + let ql: any; + const uniq = (prefix: string) => `${prefix}-${Math.random().toString(36).slice(2, 8)}`; + const notesOf = async (name: string) => (await stack.rows(NOTE, { rec_name: name, name: 'after-commit' })).length; + /** Wait (up to 2 s) for `name`'s async hook to finish; answer [notes, rows its read saw]. */ + const ran = async (name: string) => { + for (let i = 0; i < 40 && !finished.has(name); i++) await new Promise((r) => setTimeout(r, 50)); + return [await notesOf(name), finished.get(name)]; + }; + /** Write a sentinel outside any unit and wait for its hook; then `name`'s hook would have run. */ + const settled = async (name: string) => { + const sentinel = uniq('sentinel'); + await ql.insert(UNIT, { name: sentinel }, { context: { isSystem: true } }); + expect(await ran(sentinel)).toEqual([1, 1]); + return [started.has(name), await notesOf(name)]; + }; + const sys = (trx: any) => ({ context: { ...trx, isSystem: true } }); + + beforeAll(async () => { + stack = await bootStack(stlStack); + ql = await stack.kernel.getServiceAsync('objectql'); + }, 120_000); + afterAll(async () => { await stack?.stop(); }); + + it('engine.transaction() that commits: the hook has not started when the callback returns, then runs and sees its row', async () => { + const name = uniq('engine-commit'); + let startedInUnit: boolean | undefined; + await ql.transaction(async (trx: any) => { + await ql.insert(UNIT, { name }, sys(trx)); + startedInUnit = started.has(name); + }); + expect(startedInUnit).toBe(false); + expect(await ran(name)).toEqual([1, 1]); + }); + + it('engine.transaction() that rolls back: the hook never runs', async () => { + const name = uniq('engine-rollback'); + await expect(ql.transaction(async (trx: any) => { + await ql.insert(UNIT, { name }, sys(trx)); + throw new Error('rolled back by the probe'); + })).rejects.toThrow('rolled back by the probe'); + expect(await settled(name)).toEqual([false, 0]); + }); + + it('ctx.api.transaction(fn) that commits: the hook runs after it and sees its row', async () => { + const name = uniq('unit-commit'); + await stack.hooks.run(TRIGGER, 'insert', { name }, { system: true }); + expect(await ran(name)).toEqual([1, 1]); + }); + + it('ctx.api.transaction(fn) that rolls back: the hook never runs', async () => { + const name = uniq('unit-rollback'); + await stack.hooks.run(TRIGGER, 'insert', { name }, { system: true }); + expect(await stack.rows(UNIT, { name })).toHaveLength(0); + expect(await settled(name)).toEqual([false, 0]); + }); + + it('nested: ctx.api.transaction(fn) joins a caller\'s engine.transaction(); its return is no commit, and the outer rollback drops the hook', async () => { + const name = uniq('unit-nested'); + let startedAfterInner: boolean | undefined; + await expect(ql.transaction(async (trx: any) => { + await ql.insert(TRIGGER, { name }, sys(trx)); + startedAfterInner = started.has(name); + throw new Error('rolled back by the probe'); + })).rejects.toThrow('rolled back by the probe'); + expect(startedAfterInner).toBe(false); + expect(await settled(name)).toEqual([false, 0]); + }); + + it('the door\'s own unit (blocking + async afterInsert on one event) commits: the blocking hook runs first, the async one after the commit', async () => { + const name = uniq('door'); + await stack.hooks.run(DOOR, 'insert', { name }, { system: true }); + expect(startedAtGate.get(name)).toBe(false); + expect(await ran(name)).toEqual([1, 1]); + }); + + it('the door\'s own unit rolls back on the blocking hook\'s abort: the async hook never runs', async () => { + const name = uniq('veto'); + await expect(stack.hooks.run(DOOR, 'insert', { name }, { system: true })).rejects.toThrow('refused by the gate'); + expect(await stack.rows(DOOR, { name })).toHaveLength(0); + expect(startedAtGate.get(name)).toBe(false); + expect(await settled(name)).toEqual([false, 0]); + }); + + const readNotesOf = async (name: string) => (await stack.rows(NOTE, { rec_name: name, name: 'after-read' })).length; + /** Inside the unit: has `name`'s read hook started within 500 ms? A run held for the commit has not. */ + const startedWhileOpen = async (name: string) => { + for (let i = 0; i < 10 && !started.has(name); i++) await new Promise((r) => setTimeout(r, 50)); + return started.has(name); + }; + const readRan = async (name: string) => { + for (let i = 0; i < 40 && !finished.has(name); i++) await new Promise((r) => setTimeout(r, 50)); + return readNotesOf(name); + }; + + it('afterFind inside engine.transaction() that commits: the read\'s async hook starts in the unit\'s lifetime, not after the commit', async () => { + const name = uniq('read-commit'); + await ql.insert(READ, { name }, { context: { isSystem: true } }); + let startedInUnit: boolean | undefined; + await ql.transaction(async (trx: any) => { + await ql.find(READ, { where: { name } }, sys(trx)); + startedInUnit = await startedWhileOpen(name); + }); + expect(startedInUnit).toBe(true); + expect(await readRan(name)).toBe(1); + }); + + it('afterFind inside engine.transaction() that rolls back: the read\'s async hook still runs, and its own write stands', async () => { + const name = uniq('read-rollback'); + await ql.insert(READ, { name }, { context: { isSystem: true } }); + let startedInUnit: boolean | undefined; + await expect(ql.transaction(async (trx: any) => { + await ql.find(READ, { where: { name } }, sys(trx)); + startedInUnit = await startedWhileOpen(name); + throw new Error('rolled back by the probe'); + })).rejects.toThrow('rolled back by the probe'); + expect(startedInUnit).toBe(true); + expect(await readRan(name)).toBe(1); + }); + + it('CONTROL afterFind outside any unit: the read\'s async hook runs, unchanged', async () => { + const name = uniq('read-plain'); + await ql.insert(READ, { name }, { context: { isSystem: true } }); + await ql.find(READ, { where: { name } }, { context: { isSystem: true } }); + expect(await readRan(name)).toBe(1); + }); + + it('CONTROL outside any unit: the hook runs and sees its row, unchanged', async () => { + const name = uniq('plain'); + await ql.insert(UNIT, { name }, { context: { isSystem: true } }); + expect(await ran(name)).toEqual([1, 1]); + }); +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index e6354b5e7a8..5217cc260fb 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -493,7 +493,11 @@ export type HookRefusal = z.input; * write happened". They are dispatched before the enclosing transaction (if * there is one) commits, so a later refusal can roll the row back after the * hook has already run. Ruled on #7477 (2026-08-11) as the declared semantics, - * not an implementation detail to be re-timed later. + * not an implementation detail to be re-timed later. A blocking hook RUNS at + * that dispatch; an `async: true` hook is dispatched there too but runs only + * once the unit commits, and never when it rolls back (#33760, see `async` + * below) — so for an async hook, what this section says about a hook that + * "has already run" does not apply. * * Four ordinary ways a write ends up inside such a unit: * - the write door itself, when the object has a blocking (not `async`) @@ -510,15 +514,20 @@ export type HookRefusal = z.input; * around the write itself. * * What that means for a handler: - * - **Effects through the same engine are safe.** `ctx.api` / `ctx.ql` writes - * join the same transaction and roll back with everything else — which is - * exactly what makes an in-engine audit hook correct. + * - **Effects through the same engine are safe — in a blocking hook.** A + * blocking (not `async`) hook's `ctx.api` / `ctx.ql` writes join the same + * transaction and roll back with everything else — which is exactly what + * makes an in-engine audit hook correct. An `async: true` hook is the + * exception: it runs after the unit commits and not at all if it rolls + * back (see `async` below), so its writes are never part of the unit. * - **Effects OUTSIDE the engine are the hook's own responsibility to make * rollback-tolerant** — webhooks, notifications, external index updates, * file deletion, email. On a rollback the row survives and the * announcement has already gone out. Make such an effect idempotent and * reconcilable, or enqueue it for a worker that re-reads the row before - * acting rather than trusting the event alone. + * acting rather than trusting the event alone. This is a blocking hook's + * burden: an `async: true` hook runs only after the commit, so it never + * announces a write that was rolled back. * * The `before*` events carry no such caveat: they run before the write is * issued, and throwing from one refuses the operation. @@ -719,6 +728,18 @@ export const HookSchema = lazySchema(() => strictObject( * If true, the hook runs in the background and does not block the transaction. * Only applicable for 'after*' events. * Default: false (Blocking) + * + * Fired inside a unit of work (see {@link HookEvent}), an async hook starts + * once the outermost unit commits, and is dropped without running when that + * unit rolls back; its `ctx.api` reads then see the committed write, and its + * writes run outside the unit, on their own connection. Outside any unit it + * starts at once, after the write. Nothing waits for it, and its errors + * never reach the caller. + * + * That waiting is for a WRITE event's hook (`afterInsert` / `afterUpdate` / + * `afterDelete`). A rollback does not undo a read, so an async `afterFind` + * hook starts when the read is dispatched, outside the unit, whatever the + * unit it was read in does next. */ async: z.boolean().default(false).describe('Run specifically as fire-and-forget'),