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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .changeset/33651-async-hook-outside-door-unit.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/objectql': patch
---
Expand All @@ -11,13 +11,12 @@

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.
26 changes: 26 additions & 0 deletions .changeset/33760-async-hook-on-commit.md
Original file line number Diff line number Diff line change
@@ -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.
46 changes: 37 additions & 9 deletions content/docs/automation/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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
Expand All @@ -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.

<Callout type="info">
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).
</Callout>

### `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
Expand Down Expand Up @@ -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

Expand Down
32 changes: 24 additions & 8 deletions packages/objectql/src/engine-scoped-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -168,10 +168,14 @@ export class ScopedContextFacet {
}

/** The body of `ScopedContext#[DETACHED_HOOK_RUN]`; the method's docblock there is its contract. */
static detachedHookRun<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, 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<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK> {
// 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. */
Expand Down Expand Up @@ -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 = <R>(fn: () => Promise<R>): Promise<R> =>
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;
}

/**
Expand Down Expand Up @@ -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 };
}
Expand All @@ -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<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
if (this.releaseJoinedHandle(handle)) return;
settleTrioCommitQueue(handle, false);
const driver = this.txDriver();
if (!driver) return;
if (driver.rollback) await driver.rollback(handle);
Expand Down
Loading
Loading