Skip to content

Commit 109a903

Browse files
fix(objectql): an async after-hook fired inside a unit of work runs once the unit commits, and not at all when it rolls back (#34043)
domain:server#5 · zhuangjianguo · session_01QsR2jTEivi2wogPpeo3xd5 <!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ Fixes #33760 Clause-②: no Metadata-protocol: semantic Skills-docs: follow-up #34191 ## 维护者速读 - **改了什么**:在事务单元内触发的 `async: true` 写入类 after 钩子(afterInsert/afterUpdate/afterDelete),改为在最外层单元提交之后才启动;单元回滚时根本不运行。读取类 `afterFind` 与单元外的行为不变。 - **为什么改**:以前 async 钩子在单元尚未提交时就启动:Postgres 等多连接数据库上它读不到触发它的那条写入;单元回滚后钩子照样跑完,写下引用不存在记录的数据(Postgres 16 与 SQLite 实测)。 - **风险与回滚**:依赖“回滚后 async 钩子仍运行”的应用会失去这次运行(例如记录失败尝试),应改用阻断型钩子;回滚即回退本 PR,无数据迁移。 - **先看**:`packages/objectql/src/unit-detach.ts`(提交队列与延后启动);`engine-transactions-section.ts` 与 `engine-scoped-context.ts` 的提交/回滚后结算;`hook-wrappers.ts` 的 fire-and-forget 分支。 - **两分钟验证**:`pnpm --filter @objectstack/objectql exec vitest run --project local src/engine-scoped-transaction-late-write.test.ts`,预期 31/31 全绿。 - **需要你做的**:无,席位落地。 ## What changes An `async: true` after-hook fired inside a unit of work started at dispatch, while the unit was still open. On a database with more than one connection its `ctx.api` reads ran before the triggering write was committed, and when the unit rolled back the hook had already run. The PR #33703 review record (comment 6892346943) named this; PR #33703's changeset told users the hook "is not deferred until the triggering write commits", "is not cancelled if that unit rolls back", and "should be a blocking hook instead" when it must see the write. That behaviour now changes, and this PR's changeset says so. **Mechanism** (`packages/objectql/src/unit-detach.ts`): a `UnitCommitQueue` per unit the engine owns. - `ObjectQL.transaction()` and `ScopedContext.transaction()` open a queue, hand it to `runOpenedUnit` (it rides the `txStore` entry and the `openedUnits` map, and outlives the close), and settle it after the commit (start every run) or on the rollback path (drop every run). - `ScopedContext#[DETACHED_HOOK_RUN]` now goes through `runOutsideOpenUnitsOnCommit`: when the dispatch is inside an unsettled unit (ambient entry first, else the handle the api carries), the detached run is queued, bound to the dispatch's async context with `AsyncResource.bind`, and answers `UNIT_ROLLED_BACK` without running on a rollback. With no unsettled unit, it starts at once, as before. - A nested `transaction()` joins the outer unit (ADR-0067 D2) and opens no queue, so only the outermost commit starts the run. - The `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio (the sandbox runner's `ctx.api.transaction(fn)`) keeps a per-handle queue in a module `WeakMap`, settled by its own commit and rollback. - The unit a run waits for is read off the ENGINE-BUILT api, which `wrapDeclarativeHook` holds before a `runAs` install replaces `ctx.api` (review 6898709123, finding 1). A derived api need not know the unit: the unscoped api a `runAs: 'user'` hook gets on a trigger with no user (`UnscopedHookApi`) has no engine and no detach, so asking it started the run at dispatch, inside the unit, and after a rollback too. - `wrapDeclarativeHook`'s fire-and-forget leg hands a deferred run a copy of the hook context taken at dispatch (the flat input and the api the handler is owed survive the wrapper's synchronous restores); a run that starts at once still gets the context by reference. A dropped run logs one `debug` line and records no execution metric. - Only a WRITE event's run waits (`waitsForUnitCommit`: `afterInsert` / `afterUpdate` / `afterDelete`), per contract review 6899793526 M1. A rollback does not undo a read, so an `async` `afterFind` run starts at dispatch, outside the units, exactly as under #33651; `[DETACHED_HOOK_RUN]` takes the choice as a second argument. - The door's own unit, cascades and atomic batches all go through `ObjectQL.transaction()`, so they are covered without editing the S2 files (`engine-cascade-planning.ts`, `engine-delete-and-aggregate.ts`, `engine-top-level.ts`, `engine-middleware-and-context.ts`). **Spec prose** (`packages/spec/src/data/hook.zod.ts`): the `HookEvent` docblock's opening now says an `async: true` hook runs only once the unit commits (so "has already run" does not apply to it), the "roll back with everything else" bullet says blocking hooks only, the "Effects OUTSIDE the engine" bullet names that burden as a blocking hook's, and the `async` key's TSDoc states the commit/rollback semantics and the `afterFind` exception. No `.describe()` or schema shape changes. **Guide** (`content/docs/automation/hooks.mdx`, review 6899793526 S1): "After hooks run inside the unit of work", its bullets and its callout now speak of blocking hooks, and a new subsection "`async: true` after hooks run after the commit" states the commit, rollback, outside-unit and `afterFind` cases; the DON'T bullet is qualified the same way. **Declaration** (area S3 decision, card comment 6897999027): `Clause-②: no` follows the PR #33703 contract-review ruling on the same mechanism (6892346943): nothing waits for an async hook, so no answer to the triggering request moves, and nothing in the diff is a published accept set or export. `Metadata-protocol: semantic`: what an author's `async: true` does changes, so `@objectstack/objectql` takes a `minor` changeset; `@objectstack/spec` takes `patch` for the shipped TSDoc in `src/**/*.zod.ts` and `dist`. ADR-0088 line 32 describes hooks as "synchronous, data-layer, in-transaction". That remains true of blocking hooks; an `async: true` hook is now explicitly post-commit. The ADR is not edited. `skills/objectstack-data/references/data-hooks.md:64` already says "in the background, after commit"; with this change that clause matches the shipped behaviour. This PR does not touch `skills/**`. ## DELIBERATE CORRECTION — `.changeset/33651-async-hook-outside-door-unit.md` `Check Changeset` is red on purpose (route 0: this PR changes a pending release note it did not add) and stays red; no `skip-changeset`. Review 6899793526 N4: that unreleased note and this PR's note would both reach the same release notes and say opposite things. Changed under it, so the timing rule is stated once: - Removed the first bullet ("An async after-hook runs in the background but is not deferred until the triggering write commits. … it is not cancelled if that unit rolls back. … An async hook that must see the triggering write should be a blocking hook instead."). It is false from this PR on. - Removed the sentence "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)." and added: "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." - Third bullet now ends at "Before, they rolled back only when they happened to run before that unit settled." (dropped: "An async hook that must undo its effect when the triggering write fails should be a blocking hook instead."). This PR's own note (`.changeset/33760-async-hook-on-commit.md`) now opens its list with "This is the one statement of when an async after-hook runs inside a unit of work", adds the `afterFind` and one-pass-start bullets, and states the N1 (a) and (b) deviations. ## Tests - New describe in `packages/objectql/src/engine-scoped-transaction-late-write.test.ts` (#33760): commit and rollback on `engine.transaction()`, `ctx.api.transaction(fn)`, the trio, nested (inner return + outer rollback drops; outer commit starts once), blocking + async on the same event in the door's unit (commit, and abort-rollback), and a CONTROL outside any unit. - Moved #33703 pin: in the describe "an async after-hook beside a blocking one writes outside the door's unit", the blocking leg used to wait until the async hook's write reached the driver inside the unit, which fixed the order of the original failure. That write cannot reach the driver before the commit any more, so the leg now records whether the async hook had started, and the pins read `false`. What they still pin is #33651's: the write is stored, outside the unit. - Review round (6898709123 finding 1): two pins for an `async: true`, `runAs: 'user'` after-hook fired by a system-context write (no user) inside `engine.transaction()`: on commit it starts after the commit (and its `ctx.api` is the `UnscopedHookApi`, so the pin reaches the shape the finding names); on rollback it never starts. - Review round 2 (6899793526 M1, N3): `afterFind` inside `engine.transaction()` that commits (the run starts while the unit is open, before the commit, and its note write is enrolled in no unit) and that rolls back (the run still starts, nothing is dropped, its write enrolled in no unit), the outside-unit `afterFind` CONTROL, and a deferred `afterInsert` run that throws after the commit (`transaction()` resolves, the fire-and-forget error line is logged after the commit). The unit file now holds 31 cases. - Dogfood twin: the `afterFind` commit / rollback / CONTROL set on SQLite through knex, where the rollback case reads the hook's own note row standing after the unit rolled back. - Real-driver twin: a new top-level describe in `packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts` (booted stack, SQLite via knex), on the same harness file per ruling record 6583487846. ## Acceptance notes - Ride-along, comment only: `packages/qa/dogfood/test/hook-after-abort-rollback.dogfood.test.ts`'s header said an async hook "is started inside the unit and writes after it commits"; corrected to the shipped timing (the area added it to the file surface). - `HookContext.transaction` and `ScopedContext#transactionHandle` inside a deferred run still expose the committed handle (the #33703 review nit); unchanged here. - A trio handle whose `commitTransaction` throws, with no rollback after it, leaves its queue to the `WeakMap`: the waiting runs are dropped silently, as the unit's writes are. - N1 (a) and (b) (records 6898698040 finding 4 and 6899793526 N1), stated as deviations in the changeset: (a) a write from work the callback did not await, made after the callback returned and before a commit that then fails, is stored while its async hook is dropped with the unit; (b) a write to an append-only system-ledger object routed to another datasource runs outside the unit and survives its rollback, while its async hook is held by the unit and dropped. - N2 (records 6898698040 finding 5 and 6899793526 N2, left as is): a deferred run's execution metric is measured from dispatch, so it includes the wait for the commit. - N3 (6899793526): the throw-after-commit pin is added (Tests). Not added: an async hook fired from an atomic batch or an atomic cascade, and `transaction()` on a driver without transactions; each holds by construction (they open their unit through `ObjectQL.transaction()`, or open none). - N5 (6899793526): every run a unit held starts in one synchronous pass at commit; a bulk write with a per-row async hook holds one context copy per row until then, bounded by the per-row hook budget. Now a sentence in `unit-detach.ts` and in the changeset. - Skills follow-up owed: `data-hooks.md` says async hooks run "in the background, after commit", and does not teach that one is dropped when its unit rolls back; the seat files that card. ## Verification Final head `7c8f07ee92`, after review#2's delta PASS 6903738456. CI at that head ran 68 check-runs: 57 success, 10 skipped, and 1 red, which is Check Changeset, the designed DELIBERATE CORRECTION red (see that section). Test Core 1–8/8 and Lint · scoped · query-options erasure are success. At `c122a90f45`, under the lock: objectql late-write + hook-run-as 66/66 (the late-write file holds 31 cases), and the dogfood twin 21/21. `7c8f07ee92` drops two `as any` casts in pins only. The M1 ablation is NOT MEASURED (lock queue); the A4 ablation reds exactly the two user-pin pins. Earlier readings: measured at `a3d85bbecf` (before the `origin/main` merge) unless a line names `709b3aeea1`, the final head (merge of `origin/main` b4ce310 plus the declaration and ride-along commits). Logs in the folds. <details><summary>Step 1 premise readings (before the fix, origin/main 63e47fe)</summary> Event order per path, `ObjectQL` + `SqlDriver`, async `afterInsert` probe (start, re-read its row, insert a note): ```text pg | ctx.api.transaction commit | hook-start:sc > callback-returns > hook-read:sc:saw=0 > COMMIT > hook-wrote:sc | notes=1 pg | engine.transaction rollback | hook-start:er > callback-throws > ROLLBACK > caller-saw-rollback > hook-read:er:saw=0 > hook-wrote:er | notes=1 pg | nested inner commit + outer rollback | hook-start:nr > inner-returns > outer-throws > ROLLBACK > caller-saw-rollback > hook-read:nr:saw=0 > hook-wrote:nr | notes=1 pg | door unit rollback (gate veto) | hook-start:veto > gate:veto > ROLLBACK > door-refused > hook-read:veto:saw=0 > hook-wrote:veto | notes=1 sqlite | engine.transaction commit | hook-start:ec > callback-returns > COMMIT > hook-read:ec:saw=1 > hook-wrote:ec | notes=1 sqlite | door unit rollback (gate veto) | hook-start:veto > gate:veto > ROLLBACK > door-refused > hook-read:veto:saw=0 > hook-wrote:veto | notes=1 ``` Dogfood twin against the origin/main build: `Tests 6 failed | 6 passed (12)`, each red the hook having started inside the unit or run after the rollback (`expected [ true, 1 ] to deeply equal [ false, +0 ]`). </details> <details><summary>After the fix</summary> ```text pg | engine.transaction commit | callback-returns > COMMIT > hook-start:ec > hook-read:ec:saw=1 > hook-wrote:ec | notes=1 pg | ctx.api.transaction commit | callback-returns > COMMIT > hook-start:sc > hook-read:sc:saw=1 > hook-wrote:sc | notes=1 pg | engine.transaction rollback | callback-throws > ROLLBACK > caller-saw-rollback | notes=0 pg | nested inner commit + outer rollback | inner-returns > outer-throws > ROLLBACK > caller-saw-rollback | notes=0 pg | door unit rollback (gate veto) | gate:veto > ROLLBACK > door-refused | notes=0 pg | CONTROL no unit | hook-start:pl > insert-returns > hook-read:pl:saw=1 > hook-wrote:pl | notes=1 ``` - objectql unit pins: 25/25. Full `pnpm --filter @objectstack/objectql test`: 596 files, 13179 tests passed. `typecheck` exit 0. - Dogfood twin on the rebuilt objectql: 12/12. - runtime `src/sandbox/` (the trio's consumer): 41 files, 431 tests passed. - spec `test`: 842 files, 26956 passed, 1 todo; `typecheck` exit 0; `check:generated` all 14 up to date. - Derived gates (`dispatch-gates --commands`): 92 run locally, all exit 0; `check:type-check-debt` exit 0 under the lock; `check:dual-build-cjs-loads` left to CI. - At `709b3aeea1`, after the merge and a rebuilt dogfood closure: objectql `engine-scoped-transaction-late-write.test.ts` + `hook-run-as.test.ts` 60/60; dogfood `scoped-transaction-late-write` + `hook-after-abort-rollback` 18/18; objectql `tsc --noEmit` exit 0. PR-body gates on this body: `check-changeset-no-major` (LEVEL AXIS: clause-② `no`, metadata-protocol `semantic`, graded `minor`), `check-adr-0087-registration`, `check-closing-keyword-parity`, `check:partof-closing-keyword`, all exit 0. </details> <details><summary>Ablations (each restored, `git diff HEAD` empty, blob equal to HEAD)</summary> - A1, start at dispatch (`if (queue || !queue)` in `runOutsideOpenUnitsOnCommit`): 11 failed / 14 passed, including every rollback, nested, door and trio pin and the moved #33703 blocking-leg pin. - A2, a rollback starts the runs (`run.commit()` for both outcomes in `settleUnitCommitQueue`): exactly the 5 rollback pins red. - A3, no trio queue (`openTrioCommitQueue(trx)` removed): exactly the 2 trio pins red. - Dogfood twin: the origin/main build is the ablation leg (6 red, above). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 35cc663 commit 109a903

12 files changed

Lines changed: 889 additions & 61 deletions

‎.changeset/33651-async-hook-outside-door-unit.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,12 @@ An object with an `async: true` `afterUpdate` hook worked until a second, blocki
1111

1212
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.
1313

14-
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.
14+
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.
1515

1616
What changes for a hook author:
1717

18-
- 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.
1918
- An async hook's writes are stored whatever blocking hooks share its event.
20-
- 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.
19+
- 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.
2120
- 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.
2221

2322
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.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/objectql': minor
3+
'@objectstack/spec': patch
4+
---
5+
6+
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
7+
8+
Clause-②: no
9+
Metadata-protocol: semantic
10+
11+
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.
12+
13+
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:
14+
15+
- 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.
16+
- 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.
17+
- 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.
18+
- 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.
19+
- 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.
20+
- 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.
21+
22+
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.
23+
24+
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.
25+
26+
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.

‎content/docs/automation/hooks.mdx‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,10 @@ An `after*` hook does **not** mean "the write happened". It means **the write
304304
has been requested and will happen unless this unit of work is undone**.
305305
`afterInsert`, `afterUpdate` and `afterDelete` are dispatched *before* the
306306
enclosing transaction commits, so a later refusal in the same unit can roll the
307-
row back after your handler has already run.
307+
row back after your handler has already run. That is true of a **blocking**
308+
hook, the default. An `async: true` hook is dispatched there too, but does not
309+
run there: see [`async: true` after hooks run after the
310+
commit](#async-true-after-hooks-run-after-the-commit).
308311

309312
Four ordinary operations put a write inside such a unit:
310313

@@ -315,7 +318,7 @@ Four ordinary operations put a write inside such a unit:
315318
| `batchData` / `deleteManyData` with `atomic: true` | Every member's `after*` — the batch aborts and rolls back on the first failure |
316319
| Any write you wrapped yourself in `ctx.api.transaction(...)` or `engine.transaction(...)` | Everything in the callback |
317320

318-
What this means when you write a handler:
321+
What this means when you write a blocking handler:
319322

320323
- **Effects that go back through the engine are safe.** Writes made with
321324
`ctx.api.object('x')` join the same transaction and roll back with
@@ -332,12 +335,36 @@ Before hooks carry no such caveat: they run before the write is issued, and
332335
throwing from one refuses the operation outright.
333336

334337
<Callout type="info">
335-
This is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)),
336-
not an implementation detail awaiting a fix. Deferring `after*` to commit time
337-
would move a handler's own `ctx.api` writes *outside* the transaction the write
338-
ran in, which is a worse guarantee than the one documented here.
338+
For a blocking hook this is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)),
339+
not an implementation detail awaiting a fix. Deferring a blocking `after*` to
340+
commit time would move its own `ctx.api` writes *outside* the transaction the
341+
write ran in, which is a worse guarantee than the one documented here. An
342+
`async: true` hook has no such writes to keep: nothing awaits it, so its writes
343+
never joined the unit, and it is the one that waits for the commit (below).
339344
</Callout>
340345

346+
### `async: true` after hooks run after the commit
347+
348+
An `async: true` hook on `afterInsert`, `afterUpdate` or `afterDelete` is not
349+
awaited: the write returns without waiting for it, and the hook can neither
350+
abort the write nor have its writes rolled back with it. Inside a unit of work
351+
(any row of the table above) it therefore waits for that unit's outcome:
352+
353+
- **The unit commits:** the hook starts once the **outermost** unit has
354+
committed, so its `ctx.api` reads see the triggering write. A nested
355+
`transaction()` joins the outer unit, so its return is no commit.
356+
- **The unit rolls back:** the hook **never runs**. It does not announce a
357+
write that did not survive, so an `async` hook is the one to give an effect
358+
outside the engine. To react to a write that was refused, use a blocking
359+
hook, or record the refusal where the write is made.
360+
- **Outside any unit**, or on a driver with no transactions: the hook starts
361+
at once, as the write is dispatched.
362+
363+
Either way its own `ctx.api` writes run outside the triggering unit, on their
364+
own; a `ctx.api.transaction(...)` it opens is its own unit. An `async`
365+
`afterFind` hook does not wait: a rollback does not undo a read, so it starts
366+
when the read is dispatched, outside any unit, whatever the unit does next.
367+
341368
## Refusing in the user's language — `refusals`
342369

343370
A hook that says "no" to a write throws. A sentence written into the throw
@@ -524,9 +551,10 @@ ctx = {
524551
- Trigger unbounded cascades of writes
525552
- Perform heavy/long-running work inline in a hook
526553
- Mutate `ctx.result` in before hooks (it is only populated for after hooks)
527-
- Treat an `after*` hook as proof the write committed — it fires inside the
528-
unit of work, so an un-retractable external effect there can outlive a
529-
rollback (see [above](#after-hooks-run-inside-the-unit-of-work))
554+
- Treat a blocking `after*` hook as proof the write committed — it fires inside
555+
the unit of work, so an un-retractable external effect there can outlive a
556+
rollback (see [above](#after-hooks-run-inside-the-unit-of-work)); an
557+
`async: true` one runs only after the commit
530558

531559
## Related business logic
532560

‎packages/objectql/src/engine-scoped-context.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import { rolledBackRefusal } from './summary-errors.js';
4646
import { TransactionUnsupportedError } from './transaction-errors.js';
4747
import { redactPropagatedDriverFault } from '@objectstack/types';
4848
import { UnscopedHookApi } from './hook-run-as.js';
49-
import { runOutsideOpenUnits } from './unit-detach.js';
49+
import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js';
5050
import { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js';
5151
import type { HookRunAs, HookRunAsRef } from './hook-run-as.js';
5252
import { scopedContextHost } from './engine-scoped-hosts.js';
@@ -168,10 +168,14 @@ export class ScopedContextFacet {
168168
}
169169

170170
/** The body of `ScopedContext#[DETACHED_HOOK_RUN]`; the method's docblock there is its contract. */
171-
static detachedHookRun<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, body: () => T): T {
172-
// The engine's ambient store, reached the `as any` way `transaction` below reaches it.
173-
const txStore = (this.engine as any)?.txStore;
174-
return runOutsideOpenUnits(txStore, this.executionContext?.transaction, body);
171+
static detachedHookRun<T>(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, body: () => Promise<T>, waitForCommit: boolean): Promise<T | typeof UNIT_ROLLED_BACK> {
172+
// The engine's ambient store and its published units, reached the `as any`
173+
// way `transaction` below reaches them.
174+
const engine = this.engine as any;
175+
const threaded = this.executionContext?.transaction;
176+
return waitForCommit
177+
? runOutsideOpenUnitsOnCommit(engine?.txStore, engine?.openedUnits, threaded, body)
178+
: runOutsideOpenUnits(engine?.txStore, threaded, body);
175179
}
176180

177181
/** The body of `ScopedContext#transaction`; the method's docblock there is its contract. */
@@ -239,23 +243,30 @@ export class ScopedContextFacet {
239243
// when the callback settles, so work the callback started and did not await
240244
// (an `async: true` hook) no longer keeps the finished handle, neither the
241245
// ambient one nor the `trxCtx` one threaded above.
246+
// [#33760] With the engine's `ObjectQL.transaction` twin, the queue the
247+
// `async` after-hooks dispatched in this unit wait on for its outcome.
248+
const commitQueue = newUnitCommitQueue();
242249
const runIn = <R>(fn: () => Promise<R>): Promise<R> =>
243-
typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn) : fn();
250+
typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn, commitQueue) : fn();
244251

252+
let result: any;
245253
try {
246254
// Reached only with no ambient transaction to join, so this call really
247255
// did open one and the callback owns the outcome (#5696 / #6168).
248-
const result = await runIn(() => callback(trxCtx, { owned: true }));
256+
result = await runIn(() => callback(trxCtx, { owned: true }));
249257
if (driver.commit) await driver.commit(trx);
250258
else if (driver.commitTransaction) await driver.commitTransaction(trx);
251-
return result;
252259
} catch (error) {
260+
settleUnitCommitQueue(commitQueue, false);
253261
if (driver.rollback) await driver.rollback(trx);
254262
else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);
255263
// [#21274] The engine surface's twin (`ObjectQL.transaction`), the
256264
// stale-roll-up conversion included.
257265
throw redactPropagatedDriverFault(rolledBackRefusal(error));
258266
}
267+
// Committed: start the waiting runs, outside the `try`, never awaited.
268+
settleUnitCommitQueue(commitQueue, true);
269+
return result;
259270
}
260271

261272
/**
@@ -320,6 +331,9 @@ export class ScopedContextFacet {
320331
const driver = this.txDriver();
321332
if (!driver) return null;
322333
const trx = await driver.beginTransaction();
334+
// [#33760] The `async` after-hooks dispatched in this unit wait for the
335+
// trio's own commit, or are dropped by its rollback (`unit-detach.ts`).
336+
openTrioCommitQueue(trx);
323337
const ctx = this.derive({ ...this.executionContext, transaction: trx });
324338
return { ctx, handle: trx, owned: true };
325339
}
@@ -331,11 +345,13 @@ export class ScopedContextFacet {
331345
if (!driver) return;
332346
if (driver.commit) await driver.commit(handle);
333347
else if (driver.commitTransaction) await driver.commitTransaction(handle);
348+
settleTrioCommitQueue(handle, true);
334349
}
335350

336351
/** The body of `ScopedContext#rollbackTransaction`; the method's docblock there is its contract. */
337352
static async rollbackTransaction(this: Pick<ScopedContextHost, 'releaseJoinedHandle' | 'txDriver'>, handle: unknown): Promise<void> {
338353
if (this.releaseJoinedHandle(handle)) return;
354+
settleTrioCommitQueue(handle, false);
339355
const driver = this.txDriver();
340356
if (!driver) return;
341357
if (driver.rollback) await driver.rollback(handle);

0 commit comments

Comments
 (0)