From 2c5dcc5322a164397ab318320a8f66b7311b3b0e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 19:56:07 +0000 Subject: [PATCH 1/7] fix(objectql): a refused write rolls back the ctx.api write its before* hook made A metadata-bound before* hook now opens the write door's unit on a transactional default driver, so a refusal later in the same write (a declared validation, a later before* hook) rolls the hook's side write back. A caller's open unit still decides; drivers without transactions keep the side write. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kgF3mo9f7LXuv5hac --- .../src/engine-after-hook-abort-unit.test.ts | 91 ++++++++++++++++++- .../src/engine-delete-and-aggregate.ts | 3 +- .../src/engine-hooks-and-functions.ts | 23 ++++- packages/objectql/src/engine-insert.ts | 3 +- packages/objectql/src/engine-update.ts | 3 +- 5 files changed, 115 insertions(+), 8 deletions(-) diff --git a/packages/objectql/src/engine-after-hook-abort-unit.test.ts b/packages/objectql/src/engine-after-hook-abort-unit.test.ts index d5207acebcc..4d31a56aec9 100644 --- a/packages/objectql/src/engine-after-hook-abort-unit.test.ts +++ b/packages/objectql/src/engine-after-hook-abort-unit.test.ts @@ -7,8 +7,9 @@ * Before this, a plain write opened no unit of work, so a throwing * `afterInsert` refused the caller while the row, and the `ctx.api` write an * earlier hook made, stayed stored. The write door now opens a unit for exactly - * that case (`inAfterAbortUnit`); every other write opens none, which the - * `begun` ledger below measures. + * that case (`inAfterAbortUnit`), and since #34412 for a metadata-bound + * `before*` hook too (the last describe); every other write opens none, which + * the `begun` ledger below measures. * * The driver rolls back for real (a snapshot per transaction): a stub whose * `rollback()` is a no-op cannot tell "wrapped" from "not wrapped". @@ -120,11 +121,11 @@ describe('#22782 — an aborting after* hook rolls its write back', () => { expect(driver.begun).toHaveLength(0); }); - it('CONTROL a throwing before* hook — refused, nothing stored, no unit opened', async () => { + it('a throwing before* hook — refused, nothing stored; the unit its chain opens rolls back (#34412)', async () => { const { engine, driver } = await makeEngine([hook('veto', ['beforeInsert'], boom)]); await expect(engine.insert('case', { name: 'c1' })).rejects.toThrow('refused by the hook'); expect(driver.rowsOf('case')).toEqual([]); - expect(driver.begun).toHaveLength(0); + expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 1]); }); it('CONTROL inside a caller-opened transaction() — it joins (one unit), and the caller decides', async () => { @@ -237,3 +238,85 @@ describe('#22856 — an after* hook carrying a condition rolls its write back wh expect(driver.begun).toHaveLength(0); }); }); + +/** + * #34412 — a `before*` hook that writes through `ctx.api` makes a write of its + * own before the outer row is stored. A refusal later in the same write (a + * declared validation, a later `before*` hook) used to leave that side write + * stored, because a single write opened no unit unless an aborting `after*` + * hook existed. A metadata-bound `before*` hook now opens the door's unit too, + * so the refusal rolls the side write back with the write. + */ +describe('#34412 — a refused write rolls back the ctx.api write its before* hook made', () => { + /** `case` with a declared validation that refuses `hours > 24` — the card's `crm_time_entry` rule. */ + async function makeHoursEngine(hooks: Hook[], opts: { transactional?: boolean } = {}) { + const made = await makeEngine([], opts); + made.engine.registry.registerObject({ + ...obj('case', { hours: { name: 'hours', type: 'number' } }), + validations: [{ name: 'max_hours', type: 'script', condition: 'record.hours > 24', message: 'hours must be 24 or less', severity: 'error' }], + } as any, '__test__'); + bindHooksToEngine(made.engine, hooks, { packageId: 'app:t', logger: { debug() {}, info() {}, warn() {}, error() {} } as any }); + return made; + } + /** The card's hook: it creates a row on another object through `ctx.api`. */ + const sideWriter = (events: string[]) => + hook('side_writer', events, (ctx) => ctx.api.object('note').insert({ name: `from-${ctx.event}` }), { priority: 10 }); + const refusal = (p: Promise) => p.then(() => null, (e) => e); + + it('beforeInsert writes a note, the declared validation refuses the row: the note is absent', async () => { + const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]); + expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(driver.rowsOf('case')).toEqual([]); + expect(driver.rowsOf('note')).toEqual([]); + expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 1]); + }); + + it('beforeUpdate writes a note, the declared validation refuses the patch: the note is absent, the row unchanged', async () => { + const { engine, driver } = await makeHoursEngine([sideWriter(['beforeUpdate'])]); + const row = await engine.insert('case', { name: 'c1', hours: 3 }); + expect(await refusal(engine.update('case', { hours: 30 }, { where: { id: row.id } } as any))).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(driver.rowsOf('case')).toMatchObject([{ id: row.id, hours: 3 }]); + expect(driver.rowsOf('note')).toEqual([]); + }); + + it('beforeDelete writes a note, a later beforeDelete hook refuses: the note is absent, the row kept', async () => { + const { engine, driver } = await makeHoursEngine([sideWriter(['beforeDelete']), hook('veto', ['beforeDelete'], boom, { priority: 20 })]); + const row = await engine.insert('case', { name: 'c1', hours: 3 }); + expect(await refusal(engine.delete('case', { where: { id: row.id } } as any))).toMatchObject({ message: expect.stringContaining('refused by the hook') }); + expect(driver.rowsOf('case')).toMatchObject([{ id: row.id }]); + expect(driver.rowsOf('note')).toEqual([]); + }); + + it('CONTROL the write succeeds: the row and the note are both stored, the unit commits', async () => { + const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]); + await engine.insert('case', { name: 'c1', hours: 3 }); + expect(driver.rowsOf('case')).toMatchObject([{ name: 'c1', hours: 3 }]); + expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]); + expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 0]); + }); + + it('CONTROL inside a caller-opened transaction() — it joins (one unit), and the caller decides', async () => { + const { engine, driver } = await makeHoursEngine([sideWriter(['beforeInsert'])]); + await engine.transaction(async (trx: any) => { + expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }, { context: trx }))).toMatchObject({ code: 'VALIDATION_FAILED' }); + }); + expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 0]); + expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]); + }); + + it('CONTROL a driver with no transactions keeps the side write, as hookStoppedRefusal says, and warns nothing', async () => { + const { engine, driver, warns } = await makeHoursEngine([sideWriter(['beforeInsert'])], { transactional: false }); + expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(driver.rowsOf('case')).toEqual([]); + expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-beforeInsert' }]); + expect(warns.filter((w) => w.includes('transaction'))).toEqual([]); + }); + + it('CONTROL a code-registered beforeInsert opens no unit — the #22782 line', async () => { + const { engine, driver } = await makeHoursEngine([]); + engine.registerHook('beforeInsert', async (ctx: any) => { await ctx.api.object('note').insert({ name: 'from-code' }); }, { object: 'case' }); + expect(await refusal(engine.insert('case', { name: 'c1', hours: 30 }))).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(driver.begun).toHaveLength(0); + expect(driver.rowsOf('note')).toMatchObject([{ name: 'from-code' }]); + }); +}); diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 7c7aad63c3f..cd8b6e92fcc 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -147,7 +147,8 @@ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); - // [#22782] An aborting `afterDelete` rolls this write back — see `opensAfterAbortUnit`. + // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's + // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. if (this.opensAfterAbortUnit('afterDelete', object, options?.context)) { return this.inAfterAbortUnit(() => this.delete(object, options)); } diff --git a/packages/objectql/src/engine-hooks-and-functions.ts b/packages/objectql/src/engine-hooks-and-functions.ts index a42dfea02b7..6671f8495a2 100644 --- a/packages/objectql/src/engine-hooks-and-functions.ts +++ b/packages/objectql/src/engine-hooks-and-functions.ts @@ -91,6 +91,13 @@ export interface HooksAndFunctionsHost { readonly txStore: ObjectQL['txStore']; } +/** [#34412] The `before*` event of the same verb as an `after*` one — see `opensAfterAbortUnit`. */ +const BEFORE_EVENT_OF = { + afterInsert: 'beforeInsert', + afterUpdate: 'beforeUpdate', + afterDelete: 'beforeDelete', +} as const; + /** The bodies of the "Class head: units, hooks, functions, body runners, hook dispatch" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ /** @@ -514,6 +521,18 @@ export class HooksAndFunctionsFacet { * after the commit, never through the rollback. Only the write's OWN refusal * arrives here: one a hook's `ctx.api` write raised was already converted * where it left the handler (#29422, `hookStoppedRefusal`), so it rolls back. + * + * [#34412] Yes too when a metadata-bound `before*` hook on the same verb + * matches `object`: such a hook may write through `ctx.api` before the row is + * stored, and a refusal later in the same write (a declared validation, a + * later `before*` hook, a driver constraint) must roll that side write back + * with it, as `HookSchema.onError` `abort` says. Every `before*` hook is + * blocking (`async` is ignored there), so neither `async` nor `onError` + * narrows it. Whether the hook really writes cannot be known before it runs, + * so the answer is "it can". The same three exits apply: an open unit, an + * object off the default driver, a driver with no transactions; on the last + * two the side write stays written, as `hookStoppedRefusal` says. + * Code-registered hooks (no `meta`) open no unit, the #22782 line. */ static opensAfterAbortUnit(this: Pick, event: 'afterInsert' | 'afterUpdate' | 'afterDelete', object: string, context: ExecutionContext | undefined): boolean { const threaded = context?.transaction; @@ -522,7 +541,9 @@ export class HooksAndFunctionsFacet { const aborting = (this.hooks.get(event) ?? []).some((entry) => entry.meta && hookMatchesObject(entry, object) && ((!entry.meta.async && (entry.meta.onError ?? 'abort') === 'abort') || declaredHookCondition(entry.meta) !== undefined)); - if (!aborting) return false; + const sideWriting = (this.hooks.get(BEFORE_EVENT_OF[event]) ?? []).some((entry) => + entry.meta && hookMatchesObject(entry, object)); + if (!aborting && !sideWriting) return false; const defaultDriver = this.defaultDriver ? this.drivers.get(this.defaultDriver) : undefined; try { return this.getDriver(object) === defaultDriver && driverSupportsTransactions(defaultDriver); diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 566b36a8bca..196fb1e4d2d 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -311,7 +311,8 @@ export class InsertFacet { /** The body of `ObjectQL#insert`; the method's docblock there is its contract. */ static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { object = this.resolveObjectName(object); - // [#22782] An aborting `afterInsert` rolls this write back — see `opensAfterAbortUnit`. + // [#22782, #34412] An aborting `afterInsert`, or a refusal after a `beforeInsert` hook's + // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. if (this.opensAfterAbortUnit('afterInsert', object, options?.context)) { return this.inAfterAbortUnit(() => this.insert(object, data, options)); } diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 59f9c42bf33..8c492b96bff 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -148,7 +148,8 @@ export class UpdateFacet { /** The body of `ObjectQL#update`; the method's docblock there is its contract. */ static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { object = this.resolveObjectName(object); - // [#22782] An aborting `afterUpdate` rolls this write back — see `opensAfterAbortUnit`. + // [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's + // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. if (this.opensAfterAbortUnit('afterUpdate', object, options?.context)) { return this.inAfterAbortUnit(() => this.update(object, data, options)); } From b9c614f4776dd7d41258e79d4a439241a00e7fff Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 19:57:33 +0000 Subject: [PATCH 2/7] test(rest): a refused REST create rolls back its beforeInsert hook's ctx.api write Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5kgF3mo9f7LXuv5hac --- ...hook-condition-unevaluable-refusal.test.ts | 56 +++++++++++++++++-- 1 file changed, 51 insertions(+), 5 deletions(-) diff --git a/packages/rest/src/rest-hook-condition-unevaluable-refusal.test.ts b/packages/rest/src/rest-hook-condition-unevaluable-refusal.test.ts index ed86d3732a7..cd26c93e218 100644 --- a/packages/rest/src/rest-hook-condition-unevaluable-refusal.test.ts +++ b/packages/rest/src/rest-hook-condition-unevaluable-refusal.test.ts @@ -102,7 +102,7 @@ function makeRes() { return res; } -async function boot(hooks: any[]) { +async function boot(hooks: any[], objects: any[] = [INQUIRY]) { const engine = new ObjectQL(); liveEngines.push(engine); engine.registerDriver(new SqlDriver({ @@ -111,7 +111,7 @@ async function boot(hooks: any[]) { useNullAsDefault: true, }), true); await engine.init(); - engine.registry.registerObject(INQUIRY as any, PACKAGE_ID); + for (const object of objects) engine.registry.registerObject(object, PACKAGE_ID); await engine.syncSchemas(); const bound = bindHooksToEngine(engine, hooks as any, { packageId: PACKAGE_ID }); expect(bound.registered).toBe(hooks.length); @@ -128,10 +128,10 @@ async function boot(hooks: any[]) { return found; }; const unhandled = vi.spyOn(console, 'error').mockImplementation(() => {}); - const drive = async (path: string, body: unknown) => { + const drive = async (path: string, body: unknown, object = 'inquiry') => { const res = makeRes(); await route(path).handler({ - method: 'POST', path: `/api/v1/data/inquiry${path}`, params: { object: 'inquiry' }, + method: 'POST', path: `/api/v1/data/${object}${path}`, params: { object }, headers: { 'content-type': 'application/json' }, query: {}, body, }, res); return { status: res.statusCode as number, body: res.body as Record }; @@ -139,7 +139,8 @@ async function boot(hooks: any[]) { return { create: (body: unknown) => drive('', body), createMany: (body: unknown) => drive('/createMany', body), - rows: async () => ((await engine.find('inquiry', {})) as unknown[]).length, + createOn: (object: string, body: unknown) => drive('', body, object), + rows: async (object = 'inquiry') => ((await engine.find(object, {})) as unknown[]).length, /** Every `[REST] Unhandled error` line this boot printed. */ unhandledLines: () => unhandled.mock.calls.filter((c) => c[0] === '[REST] Unhandled error:'), }; @@ -213,3 +214,48 @@ describe('[#24662] an unevaluable hook condition is a coded refusal on the REST expect((lines[0][1] as { reason?: unknown }).reason).toBe('uncompilable'); }); }); + +/** + * [#34412] The REST data door over a transactional driver (sqlite): a + * `beforeInsert` hook creates a row on another object through `ctx.api`, then + * the object's declared validation refuses the outer row. The refusal used to + * leave the hook's row stored, because a single write opened no unit unless an + * aborting `after*` hook existed; the hook now opens the door's unit, so the + * refusal rolls it back. The control: an accepted create keeps both rows. + */ +describe('[#34412] a refused REST create rolls back the ctx.api write its beforeInsert hook made', () => { + const TIMED = { + name: 'timed', label: 'Timed', systemFields: false, + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true, label: 'ID' }, + name: { name: 'name', type: 'text' as const, label: 'Name' }, + hours: { name: 'hours', type: 'number' as const, label: 'Hours' }, + }, + validations: [{ name: 'max_hours', type: 'script', condition: 'record.hours > 24', message: 'Hours must be 24 or less.', severity: 'error' }], + }; + const MASTER = { ...INQUIRY, name: 'timed_master', label: 'Timed master' }; + const MASTER_WRITER = { + name: 'qa_master_writer', object: 'timed', events: ['beforeInsert'], + handler: async (ctx: any) => { await ctx.api.object('timed_master').insert({ id: `m-${ctx.input.data.id}`, name: 'draft' }); }, + }; + + it('the declared validation refuses the row: 400 VALIDATION_FAILED, and the hook\'s row is absent', async () => { + const stack = await boot([MASTER_WRITER], [TIMED, MASTER]); + + const res = await stack.createOn('timed', { id: 't1', name: 'line', hours: 30 }); + + expect({ status: res.status, code: res.body.code }).toEqual({ status: 400, code: 'VALIDATION_FAILED' }); + expect(await stack.rows('timed')).toBe(0); + expect(await stack.rows('timed_master')).toBe(0); + }); + + it('CONTROL: an accepted create stores the row and the hook\'s row', async () => { + const stack = await boot([MASTER_WRITER], [TIMED, MASTER]); + + const res = await stack.createOn('timed', { id: 't2', name: 'line', hours: 3 }); + + expect(res.status).toBeLessThan(300); + expect(await stack.rows('timed')).toBe(1); + expect(await stack.rows('timed_master')).toBe(1); + }); +}); From fd513773bd8cabbff839206809bf1c64910b79ab Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:11:07 +0000 Subject: [PATCH 3/7] docs(objectql): a before* hook declared in metadata opens the write's unit; changeset The hooks page and the data-flow table gain the before* row beside the after* one: the write, its before* hooks and their ctx.api writes share one unit, with the same exits. The changeset names what narrows: a before* write meant to survive a refusal rolls back, a write to another datasource is refused, MongoDB needs a replica set. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5m1wi6BQceRHYYxHFy --- .../34412-before-hook-side-write-unit.md | 22 +++++++++++++++++++ content/docs/api/data-flow.mdx | 2 +- content/docs/automation/hooks.mdx | 14 ++++++++++-- 3 files changed, 35 insertions(+), 3 deletions(-) create mode 100644 .changeset/34412-before-hook-side-write-unit.md diff --git a/.changeset/34412-before-hook-side-write-unit.md b/.changeset/34412-before-hook-side-write-unit.md new file mode 100644 index 00000000000..ae64275189d --- /dev/null +++ b/.changeset/34412-before-hook-side-write-unit.md @@ -0,0 +1,22 @@ +--- +'@objectstack/objectql': minor +--- + +fix(objectql)!: a write refused after its `before*` hook wrote through `ctx.api` no longer keeps that hook's write + +Clause-②: no (narrowing) +Metadata-protocol: semantic + + + +**BREAKING** stored-outcome narrowing, shipped as `minor` under the launch-window convention for breaking changes. + +- **FROM:** `insert` / `update` / `delete` (REST `createData` / `updateData` / `deleteData`, `ctx.api`, the engine door, single and predicate writes) on an object whose `before*` hook for that verb is bound from metadata, and that has no `after*` hook able to abort. The write door opened no unit of work. A `before*` hook that wrote another record through `ctx.api` committed that write at once, so when the write was refused later in the same call (a declared validation, a later `before*` hook, a driver constraint), the caller was refused and the hook's record stayed stored. Example: a `beforeInsert` hook on a time entry creates the week's timesheet, the entry is refused by `hours > 24`, and an empty timesheet remains. +- **TO:** a `beforeInsert`, `beforeUpdate` or `beforeDelete` hook bound from metadata opens the write door's unit for writes of its verb, whatever its `onError`. A refusal anywhere in that write rolls back the row and every `ctx.api` write the hook chain made. The caller is refused exactly as before. Hook count and order are unchanged. +- **A `before*` write meant to survive a refusal now rolls back.** There is no per-hook opt-out: `onError: 'log'` decides only whether the hook's own throw refuses the write, not whether its writes survive a refusal elsewhere. The one exception is an append-only ledger on another datasource (an object whose `lifecycle.class` is `audit`, `telemetry` or `event`), which is written outside the unit and survives the rollback, as in any unit. **Fix, if you relied on it:** record the attempt from an `after*` hook with `async: true` (it runs only after a commit), or record it where the write is made. +- **Inside the new unit, the rules of any unit apply,** so writes that were accepted are now refused on objects carrying such a hook: + - A `before*` hook whose body writes a business row to an object on another datasource has that write refused with `CrossDatasourceTransactionWriteError`, and the outer write is refused with it. **Fix:** keep the objects the hook writes on the default datasource. + - A MongoDB default store needs a replica set for this unit, as it does for `transaction()` and for the `after*` unit already (read in the driver's code: it always opens a session transaction; not measured on a standalone server). **Fix:** run MongoDB as a replica set. + - A `ctx.api.transaction(...)` a `before*` hook opens joins the door's unit instead of committing on its own, and an `async: true` `after*` hook on the same write starts after the unit commits. +- **Unchanged:** a write already inside a unit (a caller's `transaction()`, an atomic batch or cascade) joins it, and that unit's owner still decides. No unit is opened for a hook registered in code with `registerHook` (the platform's own audit stamps among them), a write with `skipAutomations`, an object whose datasource is not the default one, or a default driver with no transactions (ADR-0119 D1, such as a libSQL remote transport). On those a `before*` hook's writes stay stored after a refusal, as the refusal's message says. +- **Cost:** one transaction per write on objects that carry such a hook. On SQLite the write lock is held through the whole `before*` chain, including awaited work inside the hooks. Objects without such a hook pay one map lookup. diff --git a/content/docs/api/data-flow.mdx b/content/docs/api/data-flow.mdx index a20b0fe2582..fd82f495319 100644 --- a/content/docs/api/data-flow.mdx +++ b/content/docs/api/data-flow.mdx @@ -310,7 +310,7 @@ The lifecycle events are defined by the `HookEvent` enum (8 events). Reads fire | Hook | Phase | Can Modify? | Can Abort? | |:---|:---|:---|:---| -| `beforeInsert/Update/Delete` | Pre-persist | ✅ Yes (mutate `input`) | ✅ Yes (throw with `onError: 'abort'`) | +| `beforeInsert/Update/Delete` | Pre-persist, inside the write's unit of work when the hook is declared in metadata | ✅ Yes (mutate `input`) | ✅ Yes (throw with `onError: 'abort'`): the write is refused, and every `ctx.api` write the `before*` hooks made rolls back with it, as it does on any later refusal in the same write. On an object outside the default datasource, or on a driver with no transactions, those writes stay stored — see [After hooks run inside the unit of work](/docs/automation/hooks#after-hooks-run-inside-the-unit-of-work) | | `afterInsert/Update/Delete` | Post-persist, before the unit of work commits | ✅ Yes (mutate `result`) | ✅ Yes (a blocking hook that throws with `onError: 'abort'`, the default): the write is refused and rolled back. On an object outside the default datasource, or on a driver with no transactions, the caller is refused but the row stays stored — see [After hooks run inside the unit of work](/docs/automation/hooks#after-hooks-run-inside-the-unit-of-work) | diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 83663739bd5..de7d963bd37 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -309,11 +309,12 @@ hook, the default. An `async: true` hook is dispatched there too, but does not run there: see [`async: true` after hooks run after the commit](#async-true-after-hooks-run-after-the-commit). -Four ordinary operations put a write inside such a unit: +Five ordinary operations put a write inside such a unit: | Operation | What is inside the transaction | | :--- | :--- | | Any write to an object with an `after*` hook that can abort it: a blocking one whose `onError` is `abort` (the default), or one carrying a `condition`, whatever its `onError` and `async` (a condition that cannot be evaluated aborts the write) | The write and every `after*` hook it dispatches, so that hook's abort rolls the row back. Not opened on an object outside the default datasource, or on a driver with no transactions: there the row stays stored after an abort | +| Any write to an object with a `before*` hook on the same verb (`beforeInsert` for an insert, `beforeUpdate` for an update, `beforeDelete` for a delete), declared in metadata, whatever its `onError` | The write, its `before*` hooks and every `ctx.api` write they make, so a refusal later in the same write (a declared validation, a later `before*` hook, a driver constraint) rolls those writes back with it. Not opened on an object outside the default datasource, or on a driver with no transactions: there a `before*` hook's writes stay stored after a refusal. A hook registered in code with `registerHook` opens no unit | | A by-id `delete()` that cascades to dependent records | Each **cascaded child's** `afterDelete`. The parent's own `afterDelete` runs after that unit closes, unless the row above opened one around the whole delete | | `batchData` / `deleteManyData` with `atomic: true` | Every member's `after*` — the batch aborts and rolls back on the first failure | | Any write you wrapped yourself in `ctx.api.transaction(...)` or `engine.transaction(...)` | Everything in the callback | @@ -332,7 +333,16 @@ What this means when you write a blocking handler: event on its own. Before hooks carry no such caveat: they run before the write is issued, and -throwing from one refuses the operation outright. +throwing from one refuses the operation outright. A `before*` hook's own +`ctx.api` writes are inside the unit its row of the table above opens, so they +follow the same rules: a refusal anywhere in the write rolls them back, with no +per-hook opt-out, and a write to an object on another datasource is refused +with `CrossDatasourceTransactionWriteError`. The one exception is an +append-only ledger on another datasource (an object whose `lifecycle.class` is +`audit`, `telemetry` or `event`): it is written outside the unit and survives +the rollback. Keep the objects a `before*` hook +writes on the default datasource; on MongoDB, run it as a replica set, which +any unit needs. For a blocking hook this is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)), From abe9374566442c6d2bfebdccaed10b828331999f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:26:16 +0000 Subject: [PATCH 4/7] test(objectql): the stale-roll-up beforeInsert pin reads the unit its hook now opens The case pinned the old path: no unit for a before* hook, so the hook's own write stayed. A metadata-bound before* hook now opens the door's unit, so the refusal rolls the hook's row back. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5m1wi6BQceRHYYxHFy --- .../src/engine-hook-stale-summary-refusal.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/objectql/src/engine-hook-stale-summary-refusal.test.ts b/packages/objectql/src/engine-hook-stale-summary-refusal.test.ts index c4cd1e37c67..bce3f0a9ab2 100644 --- a/packages/objectql/src/engine-hook-stale-summary-refusal.test.ts +++ b/packages/objectql/src/engine-hook-stale-summary-refusal.test.ts @@ -23,7 +23,8 @@ * leading with the outer write, and its unit rolls both rows back; * - a code-registered hook (no unit opens): the same refusal, whose text says * what stays written, and both rows are stored; - * - a `before*` hook: the same refusal, and the outer row was never written. + * - a `before*` hook declared in metadata: the same refusal, the outer row was + * never written, and the unit its chain opens rolls the hook's row back. * * Controls: a hook declared `onError: 'log'` does not fail the outer write; the * outer write's OWN refusal still answers `ERR_SUMMARY_RECOMPUTE` carrying its @@ -183,13 +184,14 @@ describe('a hook\'s own ctx.api write that raises ERR_SUMMARY_RECOMPUTE never an expect(names(driver.rowsOf('line'))).toEqual(['from-afterInsert']); }); - it('beforeInsert: the same refusal, and the outer row was never written', async () => { + it('beforeInsert (unit open): the same refusal, the outer row never written, the hook\'s row rolled back', async () => { const { engine, driver } = await makeEngine([hook(['beforeInsert'], writeLine)]); const err = await refusal(engine.insert('case', { name: 'c-1' })); expectHookStopped(err, 'The insert of "case" did not complete: its beforeInsert hook "line_writer" stopped.'); + // A metadata-bound before* hook opens the door's unit (#34412), so the hook's own write rolls back with it. + expect([driver.begun.length, driver.rolledBack.length]).toEqual([1, 1]); expect(names(driver.rowsOf('case'))).toEqual(['existing']); - // No unit opens for a before* hook, so the hook's own write stays, as the text says. - expect(names(driver.rowsOf('line'))).toEqual(['from-beforeInsert']); + expect(driver.rowsOf('line')).toHaveLength(0); }); it('CONTROL onError: \'log\': the hook\'s refusal is logged, and the outer insert answers its own row', async () => { From 320f1f8646ec1e38ea4d4c43da47273ca895eb40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:17:51 +0000 Subject: [PATCH 5/7] test(dogfood): the late-write fixture's writer hook opens no door unit of its own The fixture needs a hook whose ctx.api.transaction opens and owns its unit. It used a beforeInsert hook because the write door opened no unit for one; a before* hook declared in metadata now opens the door's unit, and the hook's transaction only joined it, so a swallowed inner rollback kept its row. A blocking afterInsert with onError 'log' and no condition opens none. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5m1wi6BQceRHYYxHFy --- .../scoped-transaction-late-write.dogfood.test.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts b/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts index f8c8843102d..9fdbb60e654 100644 --- a/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts +++ b/packages/qa/dogfood/test/scoped-transaction-late-write.dogfood.test.ts @@ -67,10 +67,13 @@ const stlStack = defineStack({ }, objects: [named(TRIGGER), named(REC), named(NOTE), named(UNIT), named(DOOR), named(READ)], hooks: [ - // The handler of the card's measurement. A `before*` hook, so the write - // door opens no unit of its own (#22782) and `ctx.api.transaction` really - // opens — and owns — one. The name's prefix picks the shape. - { name: 'stl_writer', object: TRIGGER, events: ['beforeInsert'], + // The handler of the card's measurement. A blocking `afterInsert` with + // `onError: 'log'` and no `condition`, so the write door opens no unit of + // its own (#22782, #22856) and `ctx.api.transaction` really opens — and + // owns — one. Not a `before*` hook: a `before*` hook declared in metadata + // opens the door's unit (#34412), and `ctx.api.transaction` would only + // join it. The name's prefix picks the shape. + { name: 'stl_writer', object: TRIGGER, events: ['afterInsert'], onError: 'log', handler: async (ctx: any) => { const name = String(ctx.input.data.name); if (name.startsWith('explicit')) { From d4062a6ba179318b9d3c5b08516de9b40bdcc12d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:42:25 +0000 Subject: [PATCH 6/7] test(runtime): the before-hook body's ctx.api.transaction joins the door's unit in the title one-hop pin The H2 case pinned that a before-hook body's transaction was the only unit, so every read on it was the title's hop. A before* hook bound from metadata now opens the write door's unit and the body's transaction joins it, so the door's own reads ride the same handle. The pin now asserts one unit for the whole write, every read on it, and exactly the title's two hop reads added over the same body that never asks. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5m1wi6BQceRHYYxHFy --- ...hook-ctx-title-one-hop.integration.test.ts | 45 +++++++++++++------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/packages/runtime/src/sandbox/hook-ctx-title-one-hop.integration.test.ts b/packages/runtime/src/sandbox/hook-ctx-title-one-hop.integration.test.ts index 9427cb9d466..a836fffc8dc 100644 --- a/packages/runtime/src/sandbox/hook-ctx-title-one-hop.integration.test.ts +++ b/packages/runtime/src/sandbox/hook-ctx-title-one-hop.integration.test.ts @@ -20,8 +20,9 @@ // book, an `afterUpdate` names the row's state after the write; // - the hop costs one batched read per reference field the title reads // through, and a title over the row's own columns still costs none; -// - the hop rides the transaction a body opened (`ctx.api.transaction`), on -// the one SQLite connection, instead of asking the pool for a second; +// - the hop rides the transaction a body is in (`ctx.api.transaction`, which +// joins the write door's unit), on the one SQLite connection, instead of +// asking the pool for a second; // - the hop is read as the CALLER: a related record the caller's read does not // return leaves the title absent, as the read of the junction row shows it — // never a partial string, never the hidden name; @@ -254,26 +255,42 @@ describe('#24197 ctx.title() serves a title formula\'s one hop (real engine, rea expect(withTitle).toBe(reads.length); }, 30000); - it('H2 — inside a transaction the BODY opened, the hop rides it on the one SQLite connection', async () => { - // A before-hook with no after-hook bound: the write opens no unit of work - // of its own, so `ctx.api.transaction` OPENS one, and SQLite's single - // pooled connection is held by it until it commits. A hop read on any - // other channel would wait for a second connection that never comes. - const e = await boot([hook( - 'lib_loan', ['beforeUpdate'], - `await ctx.api.transaction(async () => { ctx.input.note = String(await ctx.title()); });`, - ['api.transaction'], - )]); + it('H2 — a before-hook body\'s ctx.api.transaction JOINS the door\'s unit, and the hop reads on it, on the one SQLite connection', async () => { + // A before-hook bound from metadata opens the write door's unit (#34412), so + // `ctx.api.transaction` in its body joins that unit instead of opening a + // second one. SQLite's single pooled connection is held by the unit until + // it commits: a hop read on any other channel would wait for a second + // connection that never comes. + const txBody = (inner: string) => hook( + 'lib_loan', ['beforeUpdate'], `await ctx.api.transaction(async () => { ${inner} });`, ['api.transaction'], + ); + const e = await boot([txBody('ctx.input.note = String(await ctx.title());')]); await e.insert('lib_loan', { id: 'l1', book: 'b1', reader: 'r1' }, { context: SYS }); reads.length = 0; begins.length = 0; const updated: any = await e.update('lib_loan', { id: 'l1', note: 'x' }, { context: LIMITED }); expect(updated.note).toBe('Dune · Ann'); + // ONE transaction for the whole write: the door's, which the body joined. + expect(begins).toHaveLength(1); + // Every read of the write ran on it — the title's hops among them. + expect(reads.length).toBeGreaterThan(0); + for (const r of reads) expect(r.trx).toBe(begins[0]); + const onUnit = (o: string) => reads.filter((r) => r.trx === begins[0] && r.object === o).length; + const withTitle = { book: onUnit('lib_book'), reader: onUnit('lib_reader'), all: reads.length }; + + // The same write whose body opens the same transaction and never asks. + const e2 = await boot([txBody("ctx.input.note = 'x';")]); + await e2.insert('lib_loan', { id: 'l1', book: 'b1', reader: 'r1' }, { context: SYS }); + reads.length = 0; + begins.length = 0; + await e2.update('lib_loan', { id: 'l1', note: 'x' }, { context: LIMITED }); expect(begins).toHaveLength(1); + const baseline = { book: onUnit('lib_book'), reader: onUnit('lib_reader'), all: reads.length }; + // The title's two hop reads — one of each related object — and nothing - // else ran on the body's transaction. - expect(reads.filter((r) => r.trx === begins[0]).map((r) => r.object).sort()).toEqual(['lib_book', 'lib_reader']); + // else is what the body added to the unit. + expect([withTitle.book - baseline.book, withTitle.reader - baseline.reader, withTitle.all - baseline.all]).toEqual([1, 1, 2]); }, 30000); it('H2 — in an after-hook the body JOINS the write\'s own unit of work, and the hop reads on it', async () => { From ea2241644c5ad2cfed2a7bb295e7c2476424159d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:51:58 +0000 Subject: [PATCH 7/7] docs(objectql): name the PostgreSQL no-savepoint consequence of the before* unit Inside the unit a before* hook's ctx.api statement that fails at the database aborts the whole PostgreSQL transaction (25P02), so catching the error, onError: 'log' or a retryPolicy no longer lets the outer write land. The changeset and the hooks page say so; the live measurement is carried on the follow-up card. Claude-Session: https://claude.ai/code/session_01ADHkmSLi1reMd27fT62jJ3 Co-authored-by: Claude --- .changeset/34412-before-hook-side-write-unit.md | 1 + content/docs/automation/hooks.mdx | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/.changeset/34412-before-hook-side-write-unit.md b/.changeset/34412-before-hook-side-write-unit.md index ae64275189d..55e7772ffca 100644 --- a/.changeset/34412-before-hook-side-write-unit.md +++ b/.changeset/34412-before-hook-side-write-unit.md @@ -18,5 +18,6 @@ Metadata-protocol: semantic - A `before*` hook whose body writes a business row to an object on another datasource has that write refused with `CrossDatasourceTransactionWriteError`, and the outer write is refused with it. **Fix:** keep the objects the hook writes on the default datasource. - A MongoDB default store needs a replica set for this unit, as it does for `transaction()` and for the `after*` unit already (read in the driver's code: it always opens a session transaction; not measured on a standalone server). **Fix:** run MongoDB as a replica set. - A `ctx.api.transaction(...)` a `before*` hook opens joins the door's unit instead of committing on its own, and an `async: true` `after*` hook on the same write starts after the unit commits. + - On PostgreSQL a statement that fails at the database aborts the whole unit (`25P02`, "current transaction is aborted"), and the unit takes no savepoint around a hook's `ctx.api` write. So a `before*` hook whose `ctx.api` statement fails there (a constraint, a type error) now refuses the outer write even when the hook body catches the error, `onError: 'log'` swallows it, or its `retryPolicy` re-runs it; that write was stored before. Read in the driver's code, not measured on PostgreSQL; the measurement is carried on #34563. **Fix:** check the condition before the hook writes, or make that write from an `after*` hook with `async: true`. - **Unchanged:** a write already inside a unit (a caller's `transaction()`, an atomic batch or cascade) joins it, and that unit's owner still decides. No unit is opened for a hook registered in code with `registerHook` (the platform's own audit stamps among them), a write with `skipAutomations`, an object whose datasource is not the default one, or a default driver with no transactions (ADR-0119 D1, such as a libSQL remote transport). On those a `before*` hook's writes stay stored after a refusal, as the refusal's message says. - **Cost:** one transaction per write on objects that carry such a hook. On SQLite the write lock is held through the whole `before*` chain, including awaited work inside the hooks. Objects without such a hook pay one map lookup. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index de7d963bd37..cc1afb5cac9 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -344,6 +344,15 @@ the rollback. Keep the objects a `before*` hook writes on the default datasource; on MongoDB, run it as a replica set, which any unit needs. +On PostgreSQL a statement that fails at the database aborts the whole unit +(`25P02`, "current transaction is aborted"), and the unit takes no savepoint +around a hook's `ctx.api` write. A `before*` hook whose `ctx.api` statement +fails there therefore refuses the write it belongs to, even when the hook body +catches the error, `onError: 'log'` swallows it, or its `retryPolicy` re-runs +it. Check the condition before writing, or make that write from an `after*` +hook with `async: true` (not yet measured on PostgreSQL; tracked in +[#34563](https://github.com/objectstack-ai/objectstack/issues/34563)). + For a blocking hook this is a deliberate, ruled semantics ([#7477](https://github.com/objectstack-ai/objectstack/issues/7477)), not an implementation detail awaiting a fix. Deferring a blocking `after*` to