Skip to content

Commit 8d827da

Browse files
docs(skills): an async after-hook on a write event starts after the commit and is dropped on rollback; an async afterFind starts at dispatch (#34529)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBVs9DfPrhduu8nqVJV7D9qh)_ Fixes #34191 Clause-②: no Metadata-protocol: none Skills-docs: updated here ## 维护者速读 - 改了什么:`objectstack-data` 技能的 hooks 参考里,「Before vs After」表的 Transaction 行按事件写准:写事件(`afterInsert` / `afterUpdate` / `afterDelete`)的 `async: true` 钩子在最外层事务提交后才启动,事务回滚(含提交失败)就不运行;`afterFind` 的在读取派发时启动;不在事务里的立即启动。Best Practices 加一条 DON'T:不要用 `async: true` 钩子去响应被拒绝或回滚的写入;改用同步钩子(它的 `ctx.api` 写入会随该写入一起回滚),或在发起写入的调用方记录。评测夹具加两例(一正一反)。 - 为什么改:原文对所有 async after 钩子都写「后台、提交后」,对 `afterFind` 不准,也没说回滚时钩子被丢弃;AI 作者会照着写一个「写入失败时触发」的 async 钩子,而它永远不会触发。 - 风险与回滚:只动已发布技能的文字、评测夹具和 changeset,不动运行时与契约;新增文字靠删同文件三处重复付账,token 上限行不动(9996 / 10011)。回滚即 revert 本 PR。 - 先看:① `skills/objectstack-data/references/data-hooks.md` 的 Transaction 行(与 `packages/spec/src/data/hook.zod.ts` 的 `async` TSDoc 是否一致);② 同文件 Best Practices 的 DON'T 句;③ 三处删除(「Update by id」段、`body` 与 `handler` 表上方的引句、`findOne` 说明的末句)是否确为重复。 - 两分钟验证:`node scripts/check-skills-token-ratchet.mjs`,预期看到 `skills/objectstack-data/references/data-hooks.md is 9996 tokens (ceiling 10011; headroom 15)` 且以 ✓ 收尾。 - 需要你做的:`skills/**` 属受管面,席位合同复审 PASS 后请批准本 PR 一次;若低风险技能臂读作 Tier S 则无,席位落地。 ## What changes `skills/objectstack-data/references/data-hooks.md`, the **Transaction** row of Before vs After Hooks, `after*` column. Before: > **Within the transaction** (unless `async: true` — then in the background, after commit) After: > **Within the transaction**. `async: true` on `afterInsert` / `afterUpdate` / `afterDelete`: starts once the outermost transaction commits, never if it rolls back (a failed commit included); on `afterFind`: starts as the read is dispatched; outside a transaction: starts at once Same file, Best Practices, the DON'T paragraph gains one clause: > react to a refused or rolled-back write from an `async: true` hook, which never runs then — use a sync hook (its `ctx.api` writes roll back with the write) or record it in the caller, where the write is made Both homes are the governing text's ("use a blocking hook, or record the refusal where the write is made"); the hook is called "sync", the word this file already uses for a hook that is not `async` (the Can abort row). The file pays for the new text by dropping three restatements, so it shrinks (895 → 890 lines, 10003 → 9996 priced tokens) and its ceiling row does not move: - Dropped: the paragraph "**Update by id.** `update` reads the primary key out of `data`, so the single-record form is `update({ id, ...fieldsToChange })` — e.g. `update({ id: pos, status: 'filled' })`." Still carried by the `update(data, opts?)` row of the method table a few lines above it in the same section ("**`update({ id, ...fields })`** — put the id **inside** `data`"), and shown in the copy-paste example (`await ctx.api.object('position').update({ id: rec.position_id, status: 'filled' });`). - Dropped: the sentence "A hook carries its logic as a **`body`** — the form a metadata-only runtime executes — or as the deprecated inline **`handler`**." Still carried by the table directly under the heading it sat beneath (Shape row: "`body: { language, source, capabilities }` (pure metadata)"; Status row: "**Preferred for new code**" against "**Deprecated**"), and by the schema example's comment "The logic: a sandboxed body (the inline `handler` is deprecated)". - Dropped: the sentence "It is `findOne`'s implicit "just one of them" that turns a missing predicate into a confidently wrong record." Still carried by the paragraph that opens the same note ("an absent or empty predicate does not come back as `null` — it comes back as the object's **first row**: a real, plausible-looking record with nothing to do with what you asked for, which your `if (!row)` cannot catch"). `skills/objectstack-data/evals/hooks-security-seeds-datasources.json`: two appended cases in the file's standard shape. - id 23 (positive): a background `afterInsert` on `order` that adds a `fulfilment_job` row, with orders arriving in atomic batches that can roll back, plus the question whether an `afterFind` hook with the same flag waits for the commit. The answer is an `async: true` `afterInsert` with `api.write`; it starts once the outermost transaction commits and never runs on rollback, and the `afterFind` hook starts as the read is dispatched. - id 24 (DON'T-shaped): "Write a background hook that adds a `payment_failure` row whenever an insert on `payment` is refused or rolled back." The answer redirects: an `async` hook never sees that insert; the failure is recorded in the caller, where the write is made, and a sync hook cannot leave the row because its `ctx.api` writes roll back with the write. `must_contain` requires the caller-side home (`caller`); `must_not_contain` is empty, since a correct answer names the flag the way the skill does. `.changeset/34191-skills-async-hook-commit.md`: `@objectstack/skills` patch. Line budget. The order gave +12 net lines across `skills/**`. The seat ruled (answer A in the card thread) that the +12 reads on priced teaching text and that eval fixtures are reported separately, since they are outside the ratchet's priced population (ruling record 6513306068). Readings: teaching text −5 lines (+7 / −12), eval fixture +20 lines (two cases of 10 lines each, the shape every case in the file has), net +15 across `skills/**`. Authoring tier: `dispatch-gates --tier` answers MANDATORY CONTRACT_REVIEW_TIER for `skills/**` (clause ①, no one-line exit). This card thread is served at that tier (`Served-tier: CONTRACT_REVIEW_TIER`, read from the session record), so the diff was authored in the thread itself. ## Tests No package source changes, so there is no package test to run. The two eval cases are fixtures (measured, not ratcheted) and are self-consistent: every `must_contain` string appears in its case's `expected_output`, no `must_not_contain` string does, and the 24 ids in the file are distinct (checked by script on `919c3dfb`). `check:skill-examples` type-checks the marked code blocks of the edited file: "347 prose examples type-check across 3 surface(s)", exit 0. <details><summary>Size readings, before (merge base <code>9e6fee19</code>) and after (<code>919c3dfb</code>)</summary> | Reading | before | after | |:--|:--|:--| | `references/data-hooks.md` lines / bytes | 895 / 40011 | 890 / 39984 | | same file, priced tokens / ceiling | 10003 / 10011 | 9996 / 10011 | | `evals/hooks-security-seeds-datasources.json` lines / bytes / tokens (not ratcheted) | 225 / 20311 / 5078 | 245 / 22460 / 5615 | | all `skills/*/SKILL.md`, lines summed | 4594 | 4594 | | ratcheted (authored) bundle tokens / ceiling sum | 188607 / 194737 | 188600 / 194737 | | eval fixtures tokens | 48698 | 49235 | | bundle total tokens (whole shipped tree) | 249100 | 249630 | No `SKILL.md` is touched. The after column is the token ratchet's own print on `919c3dfb`; the before column is that print less this diff's measured deltas (−7 priced, +537 eval). </details> ## Acceptance notes The engine behaviour was confirmed from code on `9e6fee19` before any text was written. It agrees with the card and with the governing text (the `async` TSDoc in `packages/spec/src/data/hook.zod.ts` and `content/docs/automation/hooks.mdx`, section "`async: true` after hooks run after the commit"). <details><summary>(a) A write event's async after-hook waits for the outermost commit, and is dropped on rollback or a failed commit</summary> `packages/objectql/src/unit-detach.ts`, `UNIT_SETTLED_EVENTS` and `waitsForUnitCommit` (lines 104-109): ```ts const UNIT_SETTLED_EVENTS: ReadonlySet<string> = new Set(['afterInsert', 'afterUpdate', 'afterDelete']); /** Does an `async` run dispatched for `event` wait for its unit's commit? */ export function waitsForUnitCommit(event: unknown): boolean { return typeof event === 'string' && UNIT_SETTLED_EVENTS.has(event); } ``` `packages/objectql/src/hook-wrappers.ts`, the fire-and-forget branch of the declarative wrapper (line 540) hands that answer to the detached run, and line 542 reads the dropped case: ```ts void runDetachedHook(engineApi, () => runWithErrorPolicy(dispatching ? detached : atDispatch), waitsForUnitCommit(ctx.event)) .then((ran) => { if (ran !== UNIT_ROLLED_BACK) { recordOutcome(); return; } logger.debug('[hook] async handler not run: the unit of work it was fired in rolled back', { ``` `unit-detach.ts`, `runOutsideOpenUnitsOnCommit` (lines 196-216) queues the run on the open unit, started on commit and answered `UNIT_ROLLED_BACK` without running on drop: ```ts queue.pending!.push({ commit: start, drop: () => resolve(UNIT_ROLLED_BACK) }); ``` `packages/objectql/src/engine-transactions-section.ts`, `TransactionsSectionFacet.transaction`: the driver commit is inside the `try`, so a failed commit lands in the `catch`, which drops the queue before rolling back (line 117); the queue is started only after the commit returned (line 137): ```ts } catch (err) { settleUnitCommitQueue(commitQueue, false); ... settleUnitCommitQueue(commitQueue, true); ``` Outermost: a nested `transaction()` finds `ambient?.transaction` (line 72), joins it with `owned: false` and opens no queue of its own, so only the outer unit's outcome settles the run. `ScopedContext`'s transaction (`engine-scoped-context.ts` lines 260 and 268) and the `beginTransaction` trio (`settleTrioCommitQueue`, lines 348 and 354) settle the same way. Pins: `packages/objectql/src/engine-scoped-transaction-late-write.test.ts`, the describe "an async after-hook fired inside a unit runs on its commit, never on its rollback" (line 460), among them "engine.transaction() rolls back: the hook never starts and writes nothing" and "nested: an inner ctx.api.transaction(fn) that returns is no commit, and the outer rollback drops the hook". </details> <details><summary>(b) An async afterFind starts at dispatch; outside a unit every async after-hook starts at once</summary> `afterFind` is not in `UNIT_SETTLED_EVENTS`, so `waitsForUnitCommit('afterFind')` is `false` and `runDetachedHook` runs the body at once, outside the open units (`unit-detach.ts`, `runDetachedHook` and `runOutsideOpenUnits`). The module doc says why: "It does not undo a read: the rows `afterFind` saw were already returned to the caller, so an `async` `afterFind` run starts at dispatch, outside the units". Outside a unit: `runOutsideOpenUnitsOnCommit` line 203, `if (!queue) return runOutsideOpenUnits(txStore, threaded, body);`. Pins in the same test file: "afterFind inside engine.transaction() that commits: a read's async hook starts at dispatch, in the unit's lifetime, not after the commit" (line 619), "afterFind inside engine.transaction() that rolls back: the read's async hook still runs, outside the unit" (line 634), "CONTROL outside any unit: the hook starts at dispatch, before the write returns, unchanged" (line 664). </details> Notes, none filed: - Vocabulary. The governing text says "unit of work"; this file says "transaction" throughout (the row's own name included), so the new text keeps "transaction". - The DON'T names both homes the governing text offers and says a sync hook's `ctx.api` writes roll back with the write (contract review 6933584271, S1 and N1). Eval 24 requires the caller-side home and forbids nothing (S2). - "Outside a transaction" does not spell out that a lone save is inside one when the object has an aborting blocking `after*` hook or one with a `condition` (the review's N2); either reading starts the hook after the row is stored, so the row is left as it is. - The token ceiling row for `data-hooks.md` is left at 10011 (headroom now 15). Lowering it is an edit to `scripts/check-skills-token-ratchet.mjs`, outside this card's file surface. ## Verification <details><summary>Derived gates on <code>919c3dfb</code>: 47 derived, 46 run and exit 0, 1 NOT MEASURED locally</summary> `node scripts/pm/dispatch-gates.mjs --commands` listed the same 47 commands as on the first head (3 paths vs merge base `9e6fee19e`). Each ran serially with its exit code recorded before any pipe as `CMD :: exit N`, then reconciled: ``` Run reconciliation — 47 derived, 46 run, 1 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 47 derived famil(ies) accounted for — 46 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3). ``` NOT MEASURED: `pnpm check:dual-build-cjs-loads`, exit 3 "PREREQUISITE NOT MET" (it reads a full build, and this diff changes no package source). CI's Lint lanes run it on this PR. `check:dts-closure`, `check:lean-entry-closure` and `check:sourcemap-no-sources-content` exit 0 here against the 44 packages this worktree has built (the lint and client closures, built under the verify lock), not a full build; CI's run is the full one. Also run, each exit 0: `pnpm --filter @objectstack/spec run check:skill-examples` ("347 prose examples type-check across 3 surface(s)"), `pnpm --filter @objectstack/spec run check:skill-docs`. Token ratchet: "57 authored bundle file(s) within their ceilings; 10 generator-owned file(s) and 29 eval fixture(s) measured, not ratcheted"; `skills/objectstack-data/references/data-hooks.md is 9996 tokens (ceiling 10011; headroom 15)`. First head `6dbeb77d`: 47 derived, 43 exit 0, 4 NOT MEASURED (no build yet). </details> <details><summary>Governed-surface reading</summary> `node scripts/pm/check-governed-merges.mjs --branch HEAD` on the first head `6dbeb77d`: "2 of 3 path(s) hit the register" (`skills/**` ×2; the changeset is not on the register), landing tier H on a path list alone; the low-risk skills arm reads NOT MEASURED until `--pr` can read the pull request. Size on `919c3dfb`: 49 changed lines (+37 / −12), under the 3000 human-merge threshold. This PR stays a draft; the seat reviews and lands. </details> Base: the branch is cut from `9e6fee19`. `origin/main` was at `ec6b5fd3` when this PR opened; the commits in between touch no file of this diff (`skills/objectstack-data/**`, the ratchet script), and `git merge-tree` reports a clean merge, so `main` was not merged in. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgAt23MH7HTGSbYsVo <!-- signed: domain:skills#3 · os-support-ai · session_01WGufzgtCwPzNYSczvxDEpw --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5a50524 commit 8d827da

3 files changed

Lines changed: 37 additions & 12 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/skills': patch
3+
---
4+
5+
docs(skills): an `async` after-hook on a write event starts after the commit and is dropped on rollback; an `async` `afterFind` starts at dispatch
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`skills/objectstack-data/references/data-hooks.md`, the **Transaction** row of Before vs After Hooks: an `async: true` hook on `afterInsert` / `afterUpdate` / `afterDelete` starts once the outermost transaction commits and never runs if it rolls back, a failed commit included; on `afterFind` it starts as the read is dispatched; outside a transaction it starts at once. The row used to say "in the background, after commit" for every event and did not say the hook is dropped on rollback. Best Practices gains one DON'T: do not react to a refused or rolled-back write from an `async: true` hook, which never runs then; use a sync hook, whose `ctx.api` writes roll back with the write, or record it in the caller, where the write is made. Two eval cases exercise it: a background `afterInsert` that must not announce an order that did not survive, and a request for a background hook that records a failed insert. The file pays by dropping three restatements (the "Update by id" paragraph, which repeated its row of the `ctx.api.object` method table; the sentence above the `body` vs `handler` table, which repeated the table; and the closing sentence of the `findOne` note, which repeated its opening paragraph), so its token ceiling does not move. No schema or runtime change.

‎skills/objectstack-data/evals/hooks-security-seeds-datasources.json‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,26 @@
220220
"must_contain": ["renamedFrom: ['sales_rep']", "value: 'crm_sales_rep'"],
221221
"must_not_contain": []
222222
}
223+
},
224+
{
225+
"id": 23,
226+
"prompt": "When an `order` is created, add a `fulfilment_job` row for the warehouse without slowing the save. Orders also arrive in atomic batches that can roll back, and a job must never exist for an order that did not survive. Our `afterFind` read-log hook carries the same flag: does it wait for the commit too?",
227+
"expected_output": "An `afterInsert` hook on `order` with `async: true` and a sandboxed `body: { language: 'js', source, capabilities: ['api.write'] }` that inserts the `fulfilment_job` through `ctx.api`; nothing awaits it, so the save is not slowed. Inside a transaction (the atomic batch) it starts once the outermost transaction commits and never runs if that rolls back, a failed commit included, so no job is written for an order that did not survive; outside a transaction it starts at once. The `afterFind` hook does not wait: a rollback does not undo a read, so with the flag it starts as the read is dispatched, whatever the transaction does next.",
228+
"files": [],
229+
"assertions": {
230+
"must_contain": ["afterInsert", "async: true", "api.write", "commit", "afterFind"],
231+
"must_not_contain": ["handler:", "HookContext"]
232+
}
233+
},
234+
{
235+
"id": 24,
236+
"prompt": "Write a background hook that adds a `payment_failure` row whenever an insert on `payment` is refused or rolled back. It must not slow the save.",
237+
"expected_output": "Redirects: a background (`async: true`) hook on `afterInsert` cannot do this. Inside a transaction it starts only once the outermost transaction commits and never runs when that rolls back (a failed commit included), so it never sees a refused or rolled-back insert. Record the failure in the caller, where the write is made: the caller receives the error and inserts the `payment_failure` row outside the rolled-back transaction. A sync hook is no home for this row either: its own `ctx.api` writes roll back with the write. The `async` flag stays for work that follows a committed insert.",
238+
"files": [],
239+
"assertions": {
240+
"must_contain": ["caller", "roll"],
241+
"must_not_contain": []
242+
}
223243
}
224244
]
225245
}

‎skills/objectstack-data/references/data-hooks.md‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ ObjectStack provides lifecycle events organized by operation type:
6161
| **Purpose** | Validation, enrichment, transformation | Side effects, notifications, logging |
6262
| **Can modify** | `ctx.input` (mutable) | `ctx.result` (mutable) |
6363
| **Can abort** | Yes (throw error → rollback) | A sync after-hook's throw still rolls back the transaction (see error handling) |
64-
| **Transaction** | Within transaction | **Within the transaction** (unless `async: true` — then in the background, after commit) |
64+
| **Transaction** | Within transaction | **Within the transaction**. `async: true` on `afterInsert` / `afterUpdate` / `afterDelete`: starts once the outermost transaction commits, never if it rolls back (a failed commit included); on `afterFind`: starts as the read is dispatched; outside a transaction: starts at once |
6565
| **Error handling** | Aborts by default (`onError: 'abort'`) | **Also aborts by default** — `onError` defaults to `'abort'` unconditionally; set `onError: 'log'` on side-effect hooks |
6666

6767
---
@@ -214,9 +214,6 @@ CEL has no overload for does **not** degrade to "the hook did not fire" — it
214214

215215
## Sandboxed Hook Bodies (`body`) — What the Sandbox `ctx` Can Call
216216

217-
A hook carries its logic as a **`body`** — the form a metadata-only runtime
218-
executes — or as the deprecated inline **`handler`**.
219-
220217
### `body` (sandboxed) vs `handler` (inline) — pick one
221218

222219
| | **`body`** — sandboxed script | **`handler`** — inline function (deprecated) |
@@ -321,12 +318,7 @@ await ctx.api.object('candidate').find({ limit: 1 }); // any row will
321318
```
322319

323320
An unpredicated `find` / `count` is fine — returning or counting every row is an
324-
honest answer. It is `findOne`'s implicit "just one of them" that turns a missing
325-
predicate into a confidently wrong record.
326-
327-
**Update by id.** `update` reads the primary key out of `data`, so the
328-
single-record form is `update({ id, ...fieldsToChange })` — e.g.
329-
`update({ id: pos, status: 'filled' })`.
321+
honest answer.
330322

331323
### Capabilities — the complete list
332324

@@ -821,8 +813,11 @@ cross-object operations; refuse a business rule by a
821813

822814
❌ **DON'T** — do expensive work in `before*` (it blocks the transaction); let a
823815
hook re-trigger itself; use `object: '*'` unless you mean every object; throw in
824-
`after*` unless the failure must abort the operation; assume `ctx.session` exists
825-
— system operations carry no user.
816+
`after*` unless the failure must abort the operation; react to a refused or
817+
rolled-back write from an `async: true` hook, which never runs then — use a sync
818+
hook (its `ctx.api` writes roll back with the write) or record it in the caller,
819+
where the write is made; assume `ctx.session` exists — system operations carry
820+
no user.
826821

827822

828823
---

0 commit comments

Comments
 (0)