Repository navigation
Commit 8d827da
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
- .changeset
- skills/objectstack-data
- evals
- references
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
220 | 220 | | |
221 | 221 | | |
222 | 222 | | |
| 223 | + | |
| 224 | + | |
| 225 | + | |
| 226 | + | |
| 227 | + | |
| 228 | + | |
| 229 | + | |
| 230 | + | |
| 231 | + | |
| 232 | + | |
| 233 | + | |
| 234 | + | |
| 235 | + | |
| 236 | + | |
| 237 | + | |
| 238 | + | |
| 239 | + | |
| 240 | + | |
| 241 | + | |
| 242 | + | |
223 | 243 | | |
224 | 244 | | |
225 | 245 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
61 | 61 | | |
62 | 62 | | |
63 | 63 | | |
64 | | - | |
| 64 | + | |
65 | 65 | | |
66 | 66 | | |
67 | 67 | | |
| |||
214 | 214 | | |
215 | 215 | | |
216 | 216 | | |
217 | | - | |
218 | | - | |
219 | | - | |
220 | 217 | | |
221 | 218 | | |
222 | 219 | | |
| |||
321 | 318 | | |
322 | 319 | | |
323 | 320 | | |
324 | | - | |
325 | | - | |
326 | | - | |
327 | | - | |
328 | | - | |
329 | | - | |
| 321 | + | |
330 | 322 | | |
331 | 323 | | |
332 | 324 | | |
| |||
821 | 813 | | |
822 | 814 | | |
823 | 815 | | |
824 | | - | |
825 | | - | |
| 816 | + | |
| 817 | + | |
| 818 | + | |
| 819 | + | |
| 820 | + | |
826 | 821 | | |
827 | 822 | | |
828 | 823 | | |
| |||
0 commit comments