Repository navigation
Commit 109a903
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
File tree
- .changeset
- content/docs/automation
- packages
- objectql/src
- qa/dogfood/test
- spec/src/data
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
11 | 11 | | |
12 | 12 | | |
13 | 13 | | |
14 | | - | |
| 14 | + | |
15 | 15 | | |
16 | 16 | | |
17 | 17 | | |
18 | | - | |
19 | 18 | | |
20 | | - | |
| 19 | + | |
21 | 20 | | |
22 | 21 | | |
23 | 22 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
304 | 304 | | |
305 | 305 | | |
306 | 306 | | |
307 | | - | |
| 307 | + | |
| 308 | + | |
| 309 | + | |
| 310 | + | |
308 | 311 | | |
309 | 312 | | |
310 | 313 | | |
| |||
315 | 318 | | |
316 | 319 | | |
317 | 320 | | |
318 | | - | |
| 321 | + | |
319 | 322 | | |
320 | 323 | | |
321 | 324 | | |
| |||
332 | 335 | | |
333 | 336 | | |
334 | 337 | | |
335 | | - | |
336 | | - | |
337 | | - | |
338 | | - | |
| 338 | + | |
| 339 | + | |
| 340 | + | |
| 341 | + | |
| 342 | + | |
| 343 | + | |
339 | 344 | | |
340 | 345 | | |
| 346 | + | |
| 347 | + | |
| 348 | + | |
| 349 | + | |
| 350 | + | |
| 351 | + | |
| 352 | + | |
| 353 | + | |
| 354 | + | |
| 355 | + | |
| 356 | + | |
| 357 | + | |
| 358 | + | |
| 359 | + | |
| 360 | + | |
| 361 | + | |
| 362 | + | |
| 363 | + | |
| 364 | + | |
| 365 | + | |
| 366 | + | |
| 367 | + | |
341 | 368 | | |
342 | 369 | | |
343 | 370 | | |
| |||
524 | 551 | | |
525 | 552 | | |
526 | 553 | | |
527 | | - | |
528 | | - | |
529 | | - | |
| 554 | + | |
| 555 | + | |
| 556 | + | |
| 557 | + | |
530 | 558 | | |
531 | 559 | | |
532 | 560 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
46 | 46 | | |
47 | 47 | | |
48 | 48 | | |
49 | | - | |
| 49 | + | |
50 | 50 | | |
51 | 51 | | |
52 | 52 | | |
| |||
168 | 168 | | |
169 | 169 | | |
170 | 170 | | |
171 | | - | |
172 | | - | |
173 | | - | |
174 | | - | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
175 | 179 | | |
176 | 180 | | |
177 | 181 | | |
| |||
239 | 243 | | |
240 | 244 | | |
241 | 245 | | |
| 246 | + | |
| 247 | + | |
| 248 | + | |
242 | 249 | | |
243 | | - | |
| 250 | + | |
244 | 251 | | |
| 252 | + | |
245 | 253 | | |
246 | 254 | | |
247 | 255 | | |
248 | | - | |
| 256 | + | |
249 | 257 | | |
250 | 258 | | |
251 | | - | |
252 | 259 | | |
| 260 | + | |
253 | 261 | | |
254 | 262 | | |
255 | 263 | | |
256 | 264 | | |
257 | 265 | | |
258 | 266 | | |
| 267 | + | |
| 268 | + | |
| 269 | + | |
259 | 270 | | |
260 | 271 | | |
261 | 272 | | |
| |||
320 | 331 | | |
321 | 332 | | |
322 | 333 | | |
| 334 | + | |
| 335 | + | |
| 336 | + | |
323 | 337 | | |
324 | 338 | | |
325 | 339 | | |
| |||
331 | 345 | | |
332 | 346 | | |
333 | 347 | | |
| 348 | + | |
334 | 349 | | |
335 | 350 | | |
336 | 351 | | |
337 | 352 | | |
338 | 353 | | |
| 354 | + | |
339 | 355 | | |
340 | 356 | | |
341 | 357 | | |
| |||
0 commit comments