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