Skip to content

Commit bbe3ced

Browse files
docs(hooks): state what a hook body's ctx.api.transaction joins and where it stops; skills: the measured MongoDB and PostgreSQL rule (#38155)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuHK25Zwk1bxA8Zwyv3FSnHC)_ Fixes #35324 Fixes #37992 Clause-②: no Metadata-protocol: none ## 维护者速读 - 是什么:写钩子和动作脚本的开发者(以及照技能写代码的 AI)在文档和数据技能里能读到「脚本里的事务能做到哪、到哪为止」:同一段脚本里事务不能再套事务;脚本自己开的事务里触发的钩子会并进同一个事务;写到别的数据源会被拒(审计、遥测这类只追加的日志表除外);PostgreSQL 和 MongoDB 副本集上一条语句失败整个事务作废;不支持事务的数据库上什么也不回滚且没有提示。MongoDB 那句「未实测」换成了实测结论。运行时行为不变。 - 为什么:属于「AI 照技能写出能跑的元数据」。这些边界以前只能在报错时撞上,其中 MongoDB 单机与 PostgreSQL 的规则上一张卡已实测。 - 出错会怎样:只是文档、技能文字和两条测试,写错了是教错,可直接撤回;技能文件已在字数上限,新增靠删掉同文件里重复的代码注释来付。 - 要你做的:技能目录属于需你批准合并的路径,请审后批准合并。 ## What changes **Premise corrected** (card comment 7234049171): on `main` 0e36120 a test already pinned the nested refusal (asserting only the throw), and a body's own unit IS joined: `publishTrioHandleFor` (`packages/objectql/src/engine-middleware-and-context.ts`) publishes the trio's handle per operation. Measured on the real engine, real QuickJS and a rollback-honest driver: a hook fired by a write inside a trio-opened transaction, `beforeInsert` or `afterInsert`, with or without its own `ctx.api.transaction`, ran on the one handle with one `begin`, and commit kept both rows while rollback kept neither (8 of 8). So the docs and the skill teach the join, not a second unit. - `packages/runtime/src/sandbox/quickjs-runner.test.ts`: "rejects a nested transaction" now asserts a `SandboxError`, exactly one `begin`, the outer unit rolled back, no commit, and nothing after the nested call run. - `packages/runtime/src/sandbox/transaction-ambient-join.integration.test.ts`: two cases on the hook-body face (the engine face is `engine-ambient-transaction.test.ts`): inside a transaction opened through `ScopedContext`'s trio, as an action body's `ctx.api.transaction` opens it, the hook body's `ctx.api.transaction` joins it (one begin, both writes on its handle, one commit), and its rollback undoes the hook's write. - `content/docs/automation/hooks.mdx`: new subsection "What `ctx.api.transaction` joins, and where it stops": joins any open unit, including one a body opened, and hooks of writes inside it join it; one level per body (nested refused); default datasource only, ledger carve-out; a failed statement aborts the unit on PostgreSQL and a MongoDB replica set even when caught; no unit and no warning on a driver with no transactions. The async after-hook bullet's "A nested `transaction()` joins" is bounded and links there. - `skills/objectstack-data/references/data-hooks.md`: the `before*` Transaction cell replaces "MongoDB needs a replica set (read in code, not measured)" with the measured rule (standalone refuses every write of such a transaction, `501 NOT_IMPLEMENTED`, a single-node replica set is enough; on PostgreSQL and a MongoDB replica set a failed `ctx.api` statement refuses the outer write even when caught, logged or retried, `25P02` / `251`; SQLite lets it through). The `api.transaction` row carries the same bounds as the page. The Best Practices ledger sentence points at that row instead of repeating it. - `skills/objectstack-data/evals/hooks-security-seeds-datasources.json`: the "not measured" case now expects the measured rule; the cross-datasource case names the ledger carve-out. - `.changeset/35324-hook-transaction-bounds.md`: `@objectstack/skills` patch (the package ships `skills/**`). The runtime change is tests only and ships nothing. **Skills readings** (lines / bytes, base 0e36120 → head): | | before | after | |:--|--:|--:| | `data-hooks.md` | 872 / 40480 | 856 / 40477 | | `hooks-security-seeds-datasources.json` (eval, unpriced) | 391 / 39028 | 391 / 39521 | | all `skills/**/SKILL.md`, lines | 4952 | 4952 | | whole `skills/` tree, bytes | 1224261 | 1224751 | `data-hooks.md` stays at 10120 tokens, its ceiling (headroom 0). The +878 bytes added are paid by 881 bytes cut in the same file: restating code comments (`// Required: Target object(s)` → `// Required` and five like it; "Database transaction handle", "Cross-object CRUD API", "Record ID being updated / deleted", "Only fields being changed", "Mask sensitive fields", two `candidate` example comments), section labels ("Insert / Update / Delete / Query operations:", "Mutable data", "Execution context", "Engine access", "Available in `after*` hooks:"), and five clauses each stated elsewhere in the file ("`await` is allowed", "In an `after*` hook the body is for side effects", "isolated QuickJS VM", ", not a global admin bypass", "(surfaces as a hook error)", the inline-`handler`-deprecated note, and the ledger definition now in the `api.transaction` row). No fact leaves the file. The `skills/**` edits were written by an isolated sub-agent at the contract-review tier; `node scripts/pm/verify-review-tier.mjs` on its transcript: `PASS — 22 assistant turn(s), every one served at CONTRACT_REVIEW_TIER`. ## Tests <details><summary>runs (head 592009f)</summary> - `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/sandbox/transaction-ambient-join.integration.test.ts`: 8 passed. - `… src/sandbox/quickjs-runner.test.ts -t "nested transaction"`: 1 passed. - Ablation of the new join pins: with `publishTrioHandleFor` short-circuited to `return chain()` in the built `@objectstack/objectql` dist, both new cases fail (2 failed, 6 passed); dist restored from its saved copy. - Gates derived by `node scripts/pm/dispatch-gates.mjs --commands` (81): run locally, all exit 0: `check:doc-anchors`, `check:doc-authoring`, `check:skill-links`, `check:issue-citations`, `check:nul-bytes`, `check-skills-token-ratchet.mjs`, `check:docs-single-h1`, `check:doc-frontmatter`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:skill-identifier-liveness`, `check:corpus-claim-drift`, `check:docs-transcript-drift`, `docs-audit/check-affected-docs.mjs`, `check-issue-citations.mjs`, `check:engine-double-contract`, `check:pm-skill-id-lint`, `check:skill-compatibility`, `check:skill-frame-sync`; and (`@objectstack/spec`) `check:skill-docs`, `check:skill-refs`. The rest, `pnpm typecheck` for `@objectstack/runtime` and the full `Test Core` run: NOT MEASURED locally (dependencies built with `OS_SKIP_DTS=1`), left to CI. </details> ## Acceptance notes - `data-hooks.md` has a code comment "in your plugin's onEnable()" (Plugin Integration section) while the kernel contract has no `onEnable`; untouched here, noted for the skills lane. - The PostgreSQL rule inside an action body's own (owned) transaction is stated from the measured rule for a unit ("a statement that fails at the database aborts the whole unit"); the measurement itself was taken on a `before*` hook's unit. ## Verification Read first: the `api.transaction` row of `data-hooks.md`; the new subsection of `hooks.mdx`; the two new cases at the end of `transaction-ambient-join.integration.test.ts`. Two-minute check: `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/sandbox/transaction-ambient-join.integration.test.ts` shows 8 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgTxpM3qHFCaQuC7eyA <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgTxpM3qHFCaQuC7eyA --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d753fd9 commit bbe3ced

6 files changed

Lines changed: 141 additions & 57 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/skills': patch
3+
---
4+
5+
docs(skills): `objectstack-data` states the bounds of a hook transaction, and the measured MongoDB and PostgreSQL rule
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`skills/objectstack-data/references/data-hooks.md`, the `api.transaction` row: `ctx.api.transaction` goes one level per body (a nested call is refused, "nested ctx.api.transaction is not supported"); inside an open unit it joins it, including a unit an action body opened with its own `ctx.api.transaction`, and the hooks of a write made inside that unit run in it and join it too; a write to another datasource is refused except an append-only ledger (`lifecycle.class` `audit` / `telemetry` / `event`), written outside the unit; on PostgreSQL and a MongoDB replica set a failed statement aborts the whole unit even when caught; a driver with no transactions runs the callback with none and no warning.
11+
12+
The `before*` Transaction cell drops "MongoDB needs a replica set (read in code, not measured)" for the measured rule: a standalone MongoDB refuses every write of such a transaction (`501 NOT_IMPLEMENTED`) and a single-node replica set is enough; on PostgreSQL and a MongoDB replica set a failed `ctx.api` statement refuses the outer write even when caught, logged or retried (`25P02` / `251`), while SQLite lets it through. Two eval cases in `skills/objectstack-data/evals/hooks-security-seeds-datasources.json` expect the same.
13+
14+
Nothing an author can write changes. The page stays at its token ceiling (10120): the added sentences are paid by cutting restating code comments and labels in the same file.

‎content/docs/automation/hooks.mdx‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,34 @@ write ran in, which is a worse guarantee than the one documented here. An
377377
never joined the unit, and it is the one that waits for the commit (below).
378378
</Callout>
379379

380+
### What `ctx.api.transaction` joins, and where it stops
381+
382+
A body's `ctx.api.transaction(fn)` opens a unit only when none is open. Inside
383+
one (a row of the table above, a caller's `engine.transaction()`, or a unit an
384+
action body opened with its own `ctx.api.transaction`) it **joins** it: its
385+
return is no commit and its throw no rollback, and the outer unit commits or
386+
rolls back all of it. A write made inside a body's transaction runs its hooks
387+
in that unit too, so their `ctx.api` writes, and a `ctx.api.transaction` they
388+
open, join it and roll back with it. Its bounds:
389+
390+
- **One level per body.** A `ctx.api.transaction` called inside another one in
391+
the same body is refused at the inner call ("nested ctx.api.transaction is
392+
not supported") before anything of it runs. The refusal is thrown inside the
393+
outer callback; uncaught, it rolls the outer unit back. Put the inner work in
394+
the outer callback instead.
395+
- **The default datasource only.** A write in it to an object on another
396+
datasource is refused before it runs
397+
(`400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`), except an append-only ledger
398+
(`lifecycle.class` `audit`, `telemetry` or `event`), which is written outside
399+
the unit and survives its rollback.
400+
- **A failed statement aborts the unit.** On PostgreSQL and a MongoDB replica
401+
set, as above, a statement that fails inside the callback aborts the whole
402+
unit even when the callback catches it: every later statement in it is
403+
refused, and nothing the unit wrote is stored.
404+
- **No transactions, no unit.** On a driver with no transactions (Turso's
405+
remote transport), the callback runs anyway, with no transaction and no
406+
warning: each write is stored as it is made, and a throw undoes none of them.
407+
380408
### `async: true` after hooks run after the commit
381409

382410
An `async: true` hook on `afterInsert`, `afterUpdate` or `afterDelete` is not
@@ -385,8 +413,9 @@ abort the write nor have its writes rolled back with it. Inside a unit of work
385413
(any row of the table above) it therefore waits for that unit's outcome:
386414

387415
- **The unit commits:** the hook starts once the **outermost** unit has
388-
committed, so its `ctx.api` reads see the triggering write. A nested
389-
`transaction()` joins the outer unit, so its return is no commit.
416+
committed, so its `ctx.api` reads see the triggering write. A
417+
`transaction()` opened inside the unit joins it, so its return is no commit
418+
([above](#what-ctxapitransaction-joins-and-where-it-stops)).
390419
- **The unit rolls back:** the hook **never runs**. It does not announce a
391420
write that did not survive, so an `async` hook is the one to give an effect
392421
outside the engine. To react to a write that was refused, use a blocking

‎packages/runtime/src/sandbox/quickjs-runner.test.ts‎

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,24 +1101,38 @@ describe('QuickJSScriptRunner — ctx.api.transaction', () => {
11011101
expect(events.some((e) => e.op === 'commit')).toBe(false);
11021102
}, 30000);
11031103

1104-
it('rejects a nested transaction', async () => {
1105-
const { api } = makeTxApi();
1106-
await expect(
1107-
runner.runScript(
1108-
{
1109-
language: 'js',
1110-
source: `
1104+
// One level per body: a `ctx.api.transaction` inside another in the same
1105+
// body is refused at the inner begin, before any driver call, and the refusal
1106+
// travels out through the outer callback, which rolls its own unit back. The
1107+
// hook docs and the data skill state this bound beside "joins".
1108+
it('refuses a nested transaction at the inner begin: one begin, the outer unit rolled back, nothing after it runs', async () => {
1109+
const { api, events } = makeTxApi();
1110+
const err = await runner.runScript(
1111+
{
1112+
language: 'js',
1113+
source: `
1114+
await ctx.api.transaction(async () => {
1115+
await ctx.api.object('a').insert({ x: 1 });
11111116
await ctx.api.transaction(async () => {
1112-
await ctx.api.transaction(async () => {});
1117+
await ctx.api.object('a').insert({ never: 1 });
11131118
});
1114-
`,
1115-
capabilities: ['api.write', 'api.transaction'],
1116-
timeoutMs: 30000,
1117-
},
1118-
ctx({ api }),
1119-
actionOpts,
1120-
),
1121-
).rejects.toThrow(/nested/i);
1119+
await ctx.api.object('a').insert({ never: 2 });
1120+
});
1121+
`,
1122+
capabilities: ['api.write', 'api.transaction'],
1123+
timeoutMs: 30000,
1124+
},
1125+
ctx({ api }),
1126+
actionOpts,
1127+
).then(() => null, (e) => e as SandboxError);
1128+
1129+
expect(err).toBeInstanceOf(SandboxError);
1130+
expect(err?.message).toMatch(/nested/i);
1131+
expect(events).toEqual([
1132+
{ op: 'begin', tx: 1 },
1133+
{ op: 'insert', name: 'a', tx: 1 },
1134+
{ op: 'rollback', tx: 1 },
1135+
]);
11221136
}, 30000);
11231137

11241138
it('requires the api.transaction capability', async () => {

‎packages/runtime/src/sandbox/transaction-ambient-join.integration.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,4 +284,47 @@ describe('#6406 sandbox ctx.api.transaction joins the host transaction (real eng
284284

285285
expect(checkouts).toHaveLength(1);
286286
}, 30000);
287+
288+
/**
289+
* The unit a body opened itself with `ctx.api.transaction` — an action
290+
* body's — is a host transaction too. That face is `ScopedContext`'s discrete
291+
* trio, which no closure spans from begin to commit; every operation made
292+
* through the trio's context publishes its handle for that operation's
293+
* duration (ADR-0034 D1), so the hook a write in it fires runs inside it and
294+
* the hook body's own `ctx.api.transaction` JOINS it (ADR-0067 D2). Driven
295+
* here as the sandbox's `__txBegin` / `__txCommit` / `__txRollback` leaves
296+
* drive it, on the engine's own scoped context. The engine face is pinned in
297+
* `engine-ambient-transaction.test.ts`; this is the hook body's.
298+
*/
299+
const openedByABody = async (end: 'commit' | 'rollback') => {
300+
const scoped: any = (engine as any).createContext({ isSystem: true });
301+
const begun = await scoped.beginTransaction();
302+
expect(begun.owned).toBe(true);
303+
await begun.ctx.object('thing').insert({ name: 'outer' });
304+
if (end === 'commit') await scoped.commitTransaction(begun.handle);
305+
else await scoped.rollbackTransaction(begun.handle);
306+
};
307+
308+
it("inside a transaction a body opened, the hook body's ctx.api.transaction joins it: one begin, both rows commit with it", async () => {
309+
await wire(TX_BODY);
310+
311+
await openedByABody('commit');
312+
313+
expect(seen.begins).toHaveLength(1);
314+
expect(seen.creates).toHaveLength(2);
315+
expect(seen.creates.map((c) => c.transaction)).toEqual([seen.begins[0], seen.begins[0]]);
316+
expect(seen.commits).toEqual([seen.begins[0]]);
317+
expect(committedNames('thing')).toEqual(['inner', 'outer']);
318+
}, 30000);
319+
320+
it("inside a transaction a body opened, its rollback undoes the hook body's joined write too", async () => {
321+
await wire(TX_BODY);
322+
323+
await openedByABody('rollback');
324+
325+
expect(seen.begins).toHaveLength(1);
326+
expect(seen.commits).toHaveLength(0);
327+
expect(seen.rollbacks).toEqual([seen.begins[0]]);
328+
expect(committedNames('thing')).toEqual([]);
329+
}, 30000);
287330
});

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@
234234
{
235235
"id": 28,
236236
"prompt": "A blocking `afterUpdate` hook body on `invoice` (default `onError: 'abort'`) runs `ctx.api.transaction`: it inserts a `payment`, then throws when the balance would go negative. The body catches that throw so the save still succeeds. Is the `payment` row rolled back? Is it committed when the callback returns? We also want it to insert a `bank_transfer`, a business object on our `finance` datasource, in the same callback.",
237-
"expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is on the default datasource only: the `bank_transfer` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE`, and a plain `ctx.api` write to it inside the save's unit is refused the same way. Keep the objects it writes on the default datasource, or make that write outside the unit (an `async: true` hook).",
237+
"expected_output": "Inside the save's unit (a blocking `afterUpdate` that can abort runs in it) `ctx.api.transaction` joins that unit: its throw is no rollback and its return is no commit. The caught throw keeps the `payment` row, and the outer unit commits it with the save, or rolls back all of it. To undo the payment, check the balance before inserting, or let the throw out of the body so the save is refused and everything rolls back. A body transaction is on the default datasource only: the `bank_transfer` insert is refused before it runs, `400 ERR_CROSS_DATASOURCE_TRANSACTION_WRITE` (only an append-only ledger, `lifecycle.class` `audit` / `telemetry` / `event`, is written outside the unit, and `bank_transfer` is not one), and a plain `ctx.api` write to it inside the save's unit is refused the same way. Keep the objects it writes on the default datasource, or make that write outside the unit (an `async: true` hook).",
238238
"files": [],
239239
"assertions": {
240240
"must_contain": ["join", "ERR_CROSS_DATASOURCE_TRANSACTION_WRITE"],
@@ -314,7 +314,7 @@
314314
{
315315
"id": 25,
316316
"prompt": "A `beforeInsert` hook on `time_entry`, declared in the stack's `hooks`, creates the week's `timesheet` row through `ctx.api` when there is none. A validation rule then refuses the entry (`hours > 24`). Is an empty timesheet left behind? Would `onError: 'log'` on the hook keep it? In which setups does it stay?",
317-
"expected_output": "No: the save and the hook's `ctx.api` insert run in one transaction, so the refusal rolls the `timesheet` row back with the entry. `onError: 'log'` does not keep it: there is no per-hook opt-out. It stays stored only where no transaction is opened: `time_entry`, the hooked object, is off the default datasource, or the default driver has no transactions (Turso's remote transport). A hook registered in code with `registerHook` opens no transaction either, and inside a transaction the caller opened, the caller decides. MongoDB needs a replica set for this transaction (read in code, not measured).",
317+
"expected_output": "No: the save and the hook's `ctx.api` insert run in one transaction, so the refusal rolls the `timesheet` row back with the entry. `onError: 'log'` does not keep it: there is no per-hook opt-out. It stays stored only where no transaction is opened: `time_entry`, the hooked object, is off the default datasource, or the default driver has no transactions (Turso's remote transport). A hook registered in code with `registerHook` opens no transaction either, and inside a transaction the caller opened, the caller decides. A standalone MongoDB server refuses every write such a transaction carries (`NOT_IMPLEMENTED`, 501); a single-node replica set is enough. On PostgreSQL and a MongoDB replica set, a `ctx.api` statement of the hook that fails at the database refuses the save even when the body catches it, `onError: 'log'` swallows it or `retryPolicy` re-runs it (`25P02` on PostgreSQL, code `251` on MongoDB); SQLite lets a caught failure through.",
318318
"files": [],
319319
"assertions": {
320320
"must_contain": ["roll", "default datasource", "registerHook"],

0 commit comments

Comments
 (0)