Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/34504-skills-before-hook-unit-of-work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/skills': patch
---

docs(skills): the hooks skill teaches when a `before*` hook's `ctx.api` writes roll back with a refused save

Clause-②: no
Metadata-protocol: none

objectstack-data's `references/data-hooks.md`, "Before vs After Hooks" table: the `before*` Transaction cell no longer says only "Within transaction". It now says the hook runs in one transaction with the outer write, so a refusal anywhere in that write (a validation, a later hook, a driver constraint) rolls back the hook's `ctx.api` writes too, with no per-hook opt-out. It names the four exits: a caller's open transaction decides; a hooked object off the default datasource, or a default driver with no transactions (Turso's remote transport), opens none, so those writes stay stored after a refusal; a hook registered in code with `registerHook` opens none. It also says MongoDB needs a replica set, which was read in the driver's code and not measured. Best Practices gains one DON'T: a `before*` hook does not write business records to another datasource through `ctx.api`. Its transaction refuses that write with `CrossDatasourceTransactionWriteError`, and only an append-only ledger (`lifecycle.class` `audit` / `telemetry` / `event`) is written outside it. `evals/hooks-security-seeds-datasources.json` gains two cases, one for each rule. Four restatements in data-hooks.md were removed to pay for the new text.
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,26 @@
"must_contain": ["caller", "roll"],
"must_not_contain": []
}
},
{
"id": 25,
"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?",
"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).",
"files": [],
"assertions": {
"must_contain": ["roll", "default datasource", "registerHook"],
"must_not_contain": []
}
},
{
"id": 26,
"prompt": "`order` is on the default datasource; `shipment`, a business object, is on our `warehouse` datasource. Write a `beforeInsert` hook on `order` that inserts the matching `shipment` row through `ctx.api`.",
"expected_output": "Redirects: a `before*` hook does not write a business record to another datasource through `ctx.api`. The hook's writes run in one transaction with the save, on the default datasource, and the `shipment` insert is refused there with `CrossDatasourceTransactionWriteError`. Keep the objects a `before*` hook writes on the default datasource: move `shipment` there. Only an append-only ledger on another datasource (`lifecycle.class` `audit` / `telemetry` / `event`) is written outside the transaction, and `shipment` is not one.",
"files": [],
"assertions": {
"must_contain": ["CrossDatasourceTransactionWriteError", "default datasource"],
"must_not_contain": []
}
}
]
}
31 changes: 13 additions & 18 deletions skills/objectstack-data/references/data-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
- [Best Practices](#best-practices) · [Error Handling](#error-handling) · [References](#references)

Reference companion to `objectstack-data/SKILL.md`, and the catalog's anchor for
data hooks. Covers the lifecycle events, the sandboxed `body` (and the deprecated
inline `handler`), the `HookContext` API, registration, and the canonical patterns
(delete guards, audit trails, cross-object writes, read masking).
data hooks.
`check:skill-examples` skips the unmarked blocks: fragments, shapes, and pattern 4's bare `any`.


Expand Down Expand Up @@ -61,7 +59,7 @@ ObjectStack provides lifecycle events organized by operation type:
| **Purpose** | Validation, enrichment, transformation | Side effects, notifications, logging |
| **Can modify** | `ctx.input` (mutable) | `ctx.result` (mutable) |
| **Can abort** | Yes (throw error → rollback) | A sync after-hook's throw still rolls back the transaction (see error handling) |
| **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 |
| **Transaction** | One transaction with the outer write: a refusal anywhere in it (a validation, a later hook, a driver constraint) rolls back the hook's `ctx.api` writes; no per-hook opt-out. Exits: a caller's open transaction decides; a hooked object off the default datasource, or a default driver with no transactions (Turso's remote transport), opens none, so those writes stay stored after a refusal; a hook registered in code (`registerHook`) opens none. MongoDB needs a replica set (read in code, not measured) | **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 |
| **Error handling** | Aborts by default (`onError: 'abort'`) | **Also aborts by default** — `onError` defaults to `'abort'` unconditionally; set `onError: 'log'` on side-effect hooks |

---
Expand Down Expand Up @@ -184,14 +182,9 @@ in neither). So:
object) — the engine refuses the batch whole, before any write, when two rows'
key sets differ (`MULTI_UPDATE_HOOK_KEY_DIVERGENCE`, status 400; ADR-0058
Amendment II.3).
- **`after*` hooks fire PER ROW, so a bulk write needs no special
condition.** A predicate (`multi: true`) update/delete dispatches its `after*`
hooks **once per matched row**, each on a single-record-shaped context —
`previous` is that row's pre-image, `record` is that row's real state (not the
bare payload), and `input.id` (`handler`; a `body`: `ctx.previous.id`) names the row. A transition condition therefore
**is** available on `afterUpdate` / `afterDelete`: write it once and it means
the same thing whether the write carried an id or a predicate, with no
bulk-aware branch of its own.
- **`after*` hooks dispatch once per matched row too** (`record` is that row's
real state, not the bare payload), so a transition condition on `afterUpdate` /
`afterDelete` means the same whether the write carried an id or a predicate.
- **Guard optional values with `!= null`, never with `has(...)`.** A declared
field holding `null` is *present*, so `has(record.spent)` is uniformly true and
`has(record.spent) && record.spent > record.budget` still faults on
Expand Down Expand Up @@ -671,7 +664,7 @@ A `body` cannot do this: it writes back only `ctx.input`, and its `ctx.result` i
> set or position), prefer declarative **field-level metadata** (secret/masked
> fields) — it applies on every read path automatically. Use an `afterFind` hook
> only for masking that depends on runtime logic the field metadata can't
> express. A single `afterFind` subscription covers both `find` and `findOne`.
> express.

```typescript
const maskSensitiveData = defineHook({
Expand Down Expand Up @@ -752,9 +745,7 @@ with no start or end is neither checked nor counted.
## Registration Methods

**1. Declarative — `defineStack({ hooks })`, the default.** `AppPlugin` auto-binds
these at startup: no `register*Hook` boilerplate, and the declarative fields
(`condition`, `async`, `retryPolicy`, `timeoutMs`, `onError`, `priority`) are honoured
**only** on this path. A string-named `handler` (deprecated) resolves through the stack's
these at startup: no `register*Hook` boilerplate. A string-named `handler` (deprecated) resolves through the stack's
`functions` map.

```typescript
Expand Down Expand Up @@ -791,8 +782,12 @@ the layout both real hook modules in the repo use.
cross-object operations; refuse a business rule by a
[declared code](#declared-refusals-refusals); test hooks in isolation.

❌ **DON'T** — do expensive work in `before*` (it blocks the transaction); let a
hook re-trigger itself; use `object: '*'` unless you mean every object; throw in
❌ **DON'T** — do expensive work in `before*` (it blocks the transaction); write
business records to another datasource from a `before*` hook through `ctx.api`
(its transaction refuses that write with `CrossDatasourceTransactionWriteError`;
only an append-only ledger, `lifecycle.class` `audit` / `telemetry` / `event`, is
written outside it and survives its rollback); let a hook re-trigger itself;
use `object: '*'` unless you mean every object; throw in
`after*` unless the failure must abort the operation; 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,
Expand Down
Loading