Skip to content

Commit 61f49fa

Browse files
committed
fix(objectql)!: a hook's own write's stale-roll-up refusal never answers for the write the hook is bound to
A hook that writes through ctx.api and lets that write's ERR_SUMMARY_RECOMPUTE escape no longer hands the refusal (and the hook write's `written`) to the outer write's caller. The one seam a handler's error leaves through (triggerHooks, and the unscoped multi-write dispatch) converts it with hookStoppedRefusal: a code-less error that leads with the outer write, the refusal kept as `cause`. An aborting after* hook's unit now rolls both rows back; with no unit the text says what stays written. Every other hook error, and a hook declared onError 'log', is unchanged. Claude-Session: https://claude.ai/code/session_01ADHkmPCSqt8uDw17RmX9hu Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8ca9dd7 commit 61f49fa

3 files changed

Lines changed: 271 additions & 7 deletions

File tree

Lines changed: 220 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,220 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A hook's own `ctx.api` write that raises the stale-roll-up refusal never
5+
* answers for the write the hook is bound to.
6+
*
7+
* `SummaryRecomputeError` (`ERR_SUMMARY_RECOMPUTE`) means "this write is
8+
* stored, only a parent's roll-up recompute failed". It carries the write's
9+
* result as `written`, and every answering surface turns it into that write's
10+
* own success. A hook that writes through `ctx.api` makes a write of its own.
11+
* When that write raised the refusal and the handler let it escape, the refusal
12+
* reached the OUTER write's caller unchanged. So the caller read the hook's
13+
* record as the result of its own write: measured through the REST data door
14+
* before this file, `POST /data/case` answered `201` with the id and record of
15+
* the row the hook wrote. Under an `after*` hook's unit (`inAfterAbortUnit`) the
16+
* unit then committed, because the refusal says "written".
17+
*
18+
* Pinned here, at the one seam a handler's error leaves through
19+
* (`triggerHooks`):
20+
* - an aborting `afterInsert` / `afterUpdate` / `afterDelete` hook: the outer
21+
* write refuses with an error that is NOT the stale-roll-up refusal (no
22+
* `code`, no `written`, the refusal kept as `cause`), leading with the outer
23+
* write, and its unit rolls both rows back;
24+
* - a code-registered hook (no unit opens): the same refusal, whose text says
25+
* what stays written, and both rows are stored;
26+
* - a `before*` hook: the same refusal, and the outer row was never written.
27+
*
28+
* Controls: a hook declared `onError: 'log'` does not fail the outer write; the
29+
* outer write's OWN refusal still answers `ERR_SUMMARY_RECOMPUTE` carrying its
30+
* own result (and its unit still commits); any other error a hook throws passes
31+
* through unchanged.
32+
*
33+
* The driver rolls back for real (a snapshot per transaction), and refuses
34+
* every write to `bucket` while `refuseBucket` is set: that is the roll-up
35+
* recompute's parent update, refused without a transient message, so no retry
36+
* runs.
37+
*/
38+
39+
import { describe, it, expect } from 'vitest';
40+
import type { Hook } from '@objectstack/spec/data';
41+
import { ObjectQL } from './engine.js';
42+
import { bindHooksToEngine } from './hook-binder.js';
43+
44+
type Row = Record<string, unknown>;
45+
46+
function makeDriver() {
47+
let stores = new Map<string, Map<string, Row>>();
48+
const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!);
49+
const matches = (row: Row, where: any) =>
50+
!where || Object.entries(where).every(([k, v]) => k.startsWith('$') || row[k] === v);
51+
const begun: unknown[] = [];
52+
const committed: unknown[] = [];
53+
const rolledBack: unknown[] = [];
54+
const snapshots = new Map<unknown, typeof stores>();
55+
const state = { refuseBucket: false };
56+
let n = 0;
57+
const driver: any = {
58+
name: 'primary', version: '0.0.0', supports: {}, begun, committed, rolledBack, state,
59+
rowsOf: (o: string) => Array.from(storeFor(o).values()),
60+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
61+
async syncSchema() {},
62+
async find(o: string, ast: any) {
63+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
64+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
65+
},
66+
async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; },
67+
async create(o: string, data: Row) {
68+
const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` };
69+
storeFor(o).set(String(row.id), row);
70+
return row;
71+
},
72+
async update(o: string, id: string, data: Row) {
73+
if (state.refuseBucket && o === 'bucket') throw new Error('bucket store refused the write');
74+
const row = { ...storeFor(o).get(String(id)), ...data, id };
75+
storeFor(o).set(String(id), row);
76+
return row;
77+
},
78+
async delete(o: string, id: string) { return storeFor(o).delete(String(id)); },
79+
async count(o: string, ast: any) { return (await this.find(o, ast)).length; },
80+
async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); },
81+
async bulkUpdate() { return []; }, async bulkDelete() {},
82+
async beginTransaction() {
83+
const handle = { trx: begun.length + 1 };
84+
snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))])));
85+
begun.push(handle);
86+
return handle;
87+
},
88+
async commit(h: unknown) { snapshots.delete(h); committed.push(h); },
89+
async rollback(h: unknown) { stores = snapshots.get(h) ?? stores; rolledBack.push(h); },
90+
};
91+
return driver;
92+
}
93+
94+
const text = (name: string) => ({ name, type: 'text' });
95+
/** The hook's own write: a `line`, whose roll-up into `bucket` the driver refuses. */
96+
const writeLine = (ctx: any) => ctx.api.object('line').insert({ name: `from-${ctx.event}`, bucket: 'b1' });
97+
const hook = (events: string[], handler: (ctx: any) => unknown, extra: Partial<Hook> = {}) =>
98+
({ name: 'line_writer', object: 'case', events, handler, ...extra }) as unknown as Hook;
99+
100+
async function makeEngine(hooks: Hook[]) {
101+
const log = () => {};
102+
const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any);
103+
(engine as any).summaryRetryOptions = { sleep: async () => {}, backoffBaseMs: 0 };
104+
const driver = makeDriver();
105+
engine.registerDriver(driver, true);
106+
await engine.init();
107+
engine.registry.registerObject({ name: 'case', label: 'case', fields: { id: { ...text('id'), primaryKey: true }, name: text('name') } } as any, '__test__');
108+
engine.registry.registerObject({
109+
name: 'bucket', label: 'bucket',
110+
fields: {
111+
id: { ...text('id'), primaryKey: true }, name: text('name'),
112+
line_count: { name: 'line_count', type: 'summary', summaryOperations: { object: 'line', function: 'count' } },
113+
},
114+
} as any, '__test__');
115+
engine.registry.registerObject({
116+
name: 'line', label: 'line',
117+
fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), bucket: { name: 'bucket', type: 'master_detail', reference: 'bucket' } },
118+
} as any, '__test__');
119+
await engine.insert('bucket', { id: 'b1', name: 'B' });
120+
await engine.insert('case', { id: 'c0', name: 'existing' });
121+
bindHooksToEngine(engine, hooks, { packageId: 'app:t' });
122+
driver.begun.length = 0;
123+
driver.committed.length = 0;
124+
driver.rolledBack.length = 0;
125+
driver.state.refuseBucket = true;
126+
return { engine, driver };
127+
}
128+
129+
const refusal = (p: Promise<unknown>): Promise<any> => p.then(() => null, (e: unknown) => e);
130+
const names = (rows: Row[]) => rows.map((r) => r.name).sort();
131+
132+
/** The converted refusal: an internal error naming the OUTER write, the hook write's refusal kept as `cause`. */
133+
function expectHookStopped(err: any, lead: string) {
134+
expect(err).toBeInstanceOf(Error);
135+
expect(err.code).toBeUndefined();
136+
expect(err.written).toBeUndefined();
137+
expect(err.failures).toBeUndefined();
138+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
139+
expect(err.cause?.written?.name).toMatch(/^from-/);
140+
expect(err.message.startsWith(lead), err.message).toBe(true);
141+
expect(err.message).toContain('bucket.line_count');
142+
}
143+
144+
describe('a hook\'s own ctx.api write that raises ERR_SUMMARY_RECOMPUTE never answers for the write it is bound to', () => {
145+
it('afterInsert (aborting, unit open): the insert refuses naming itself, and the unit rolls both rows back', async () => {
146+
const { engine, driver } = await makeEngine([hook(['afterInsert'], writeLine)]);
147+
const err = await refusal(engine.insert('case', { name: 'c-1' }));
148+
expectHookStopped(err, 'The insert of "case" did not complete: its afterInsert hook "line_writer" stopped.');
149+
expect(driver.begun).toHaveLength(1);
150+
expect(driver.committed).toHaveLength(0);
151+
expect(driver.rolledBack).toHaveLength(1);
152+
expect(names(driver.rowsOf('case'))).toEqual(['existing']);
153+
expect(driver.rowsOf('line')).toHaveLength(0);
154+
});
155+
156+
it('afterUpdate and afterDelete (aborting, unit open): refused naming the outer write, the stored row unchanged', async () => {
157+
const upd = await makeEngine([hook(['afterUpdate'], writeLine)]);
158+
const updErr = await refusal(upd.engine.update('case', { id: 'c0', name: 'renamed' }));
159+
expectHookStopped(updErr, 'The update of "case" did not complete: its afterUpdate hook "line_writer" stopped.');
160+
expect(upd.driver.rolledBack).toHaveLength(1);
161+
expect(names(upd.driver.rowsOf('case'))).toEqual(['existing']);
162+
expect(upd.driver.rowsOf('line')).toHaveLength(0);
163+
164+
const del = await makeEngine([hook(['afterDelete'], writeLine)]);
165+
const delErr = await refusal(del.engine.delete('case', { where: { id: 'c0' } }));
166+
expectHookStopped(delErr, 'The delete of "case" did not complete: its afterDelete hook "line_writer" stopped.');
167+
expect(del.driver.rolledBack).toHaveLength(1);
168+
expect(names(del.driver.rowsOf('case'))).toEqual(['existing']);
169+
expect(del.driver.rowsOf('line')).toHaveLength(0);
170+
});
171+
172+
it('a code-registered afterInsert (no unit opens): the same refusal, saying what stays written, and both rows stored', async () => {
173+
const { engine, driver } = await makeEngine([]);
174+
engine.registerHook('afterInsert', writeLine, { object: 'case', hookName: 'code_line_writer' });
175+
const err = await refusal(engine.insert('case', { name: 'c-1' }));
176+
expectHookStopped(err, 'The insert of "case" did not complete: its afterInsert hook "code_line_writer" stopped.');
177+
expect(err.message).toContain(
178+
'Under a transaction that rolls back nothing was written; otherwise what was written before that point stays written.',
179+
);
180+
expect(driver.begun).toHaveLength(0);
181+
expect(names(driver.rowsOf('case'))).toEqual(['c-1', 'existing']);
182+
expect(names(driver.rowsOf('line'))).toEqual(['from-afterInsert']);
183+
});
184+
185+
it('beforeInsert: the same refusal, and the outer row was never written', async () => {
186+
const { engine, driver } = await makeEngine([hook(['beforeInsert'], writeLine)]);
187+
const err = await refusal(engine.insert('case', { name: 'c-1' }));
188+
expectHookStopped(err, 'The insert of "case" did not complete: its beforeInsert hook "line_writer" stopped.');
189+
expect(names(driver.rowsOf('case'))).toEqual(['existing']);
190+
// No unit opens for a before* hook, so the hook's own write stays, as the text says.
191+
expect(names(driver.rowsOf('line'))).toEqual(['from-beforeInsert']);
192+
});
193+
194+
it('CONTROL onError: \'log\': the hook\'s refusal is logged, and the outer insert answers its own row', async () => {
195+
const { engine, driver } = await makeEngine([hook(['afterInsert'], writeLine, { onError: 'log' })]);
196+
const row: any = await engine.insert('case', { name: 'c-1' });
197+
expect(row?.name).toBe('c-1');
198+
expect(names(driver.rowsOf('case'))).toEqual(['c-1', 'existing']);
199+
expect(names(driver.rowsOf('line'))).toEqual(['from-afterInsert']);
200+
});
201+
202+
it('CONTROL the outer write\'s OWN refusal still answers ERR_SUMMARY_RECOMPUTE with its own result, and its unit commits', async () => {
203+
const { engine, driver } = await makeEngine([
204+
{ name: 'observe', object: 'line', events: ['afterInsert'], handler: () => {} } as unknown as Hook,
205+
]);
206+
const err = await refusal(engine.insert('line', { name: 'direct', bucket: 'b1' }));
207+
expect(err?.code).toBe('ERR_SUMMARY_RECOMPUTE');
208+
expect(err.written?.name).toBe('direct');
209+
expect(driver.begun).toHaveLength(1);
210+
expect(driver.committed).toHaveLength(1);
211+
expect(driver.rolledBack).toHaveLength(0);
212+
expect(names(driver.rowsOf('line'))).toEqual(['direct']);
213+
});
214+
215+
it('CONTROL any other error a hook throws passes through unchanged', async () => {
216+
const boom = new Error('refused by the hook');
217+
const { engine } = await makeEngine([hook(['afterInsert'], () => { throw boom; })]);
218+
expect(await refusal(engine.insert('case', { name: 'c-1' }))).toBe(boom);
219+
});
220+
});

‎packages/objectql/src/engine.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ import {
201201
} from '@objectstack/core';
202202
import { WriteEpoch, isWriteEpochOperation } from './write-epoch.js';
203203
import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js';
204-
import { SummaryRecomputeError, cascadeStoppedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
204+
import { SummaryRecomputeError, cascadeStoppedRefusal, hookStoppedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
205205
import { TransactionUnsupportedError } from './transaction-errors.js';
206206
import {
207207
aggregateSummaryValue,
@@ -6008,7 +6008,13 @@ export class ObjectQL implements IObjectQLEngine {
60086008
this.logger.debug('Skipping metadata-bound hook (skipAutomations)', { event, hook: entry.hookName });
60096009
continue;
60106010
}
6011-
await entry.handler(context);
6011+
// [#29422] A stale-roll-up refusal a hook's own `ctx.api` write raised
6012+
// describes THAT write, not this one: `hookStoppedRefusal`.
6013+
try {
6014+
await entry.handler(context);
6015+
} catch (e) {
6016+
throw hookStoppedRefusal(e, event, context.object, entry.hookName);
6017+
}
60126018
}
60136019
}
60146020

@@ -6056,7 +6062,9 @@ export class ObjectQL implements IObjectQLEngine {
60566062
* (`transaction()` covers that one alone and would refuse the write), or when
60576063
* that driver has no transactions (ADR-0119 D1; asking would only warn).
60586064
* `SummaryRecomputeError` means "the records WERE written": it is rethrown
6059-
* after the commit, never through the rollback.
6065+
* after the commit, never through the rollback. Only the write's OWN refusal
6066+
* arrives here: one a hook's `ctx.api` write raised was already converted
6067+
* where it left the handler (#29422, `hookStoppedRefusal`), so it rolls back.
60606068
*/
60616069
private opensAfterAbortUnit(event: 'afterInsert' | 'afterUpdate' | 'afterDelete', object: string, context: ExecutionContext | undefined): boolean {
60626070
const threaded = context?.transaction;
@@ -6322,7 +6330,12 @@ export class ObjectQL implements IObjectQLEngine {
63226330
} as unknown as HookContext;
63236331
for (const entry of flagged) {
63246332
if (skipAutomations && entry.meta) continue;
6325-
await entry.handler(wholeOpCtx);
6333+
// [#29422] As in `triggerHooks`.
6334+
try {
6335+
await entry.handler(wholeOpCtx);
6336+
} catch (e) {
6337+
throw hookStoppedRefusal(e, event, object, entry.hookName);
6338+
}
63266339
}
63276340
// `input` is identity-shared with the batch context, so the observation
63286341
// covers everything the handlers touched.

‎packages/objectql/src/summary-errors.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,16 +79,19 @@ export class SummaryRecomputeError extends Error {
7979
*
8080
* That refusal says "this write is stored, only a roll-up recompute failed",
8181
* and every answering surface turns it into the write's own success. It is
82-
* true for the write that raised it, and only while that write stands. Two
83-
* engine units carry a nested write's refusal past the point where it stops
82+
* true for the write that raised it, and only while that write stands. Three
83+
* engine seams carry a nested write's refusal past the point where it stops
8484
* being true:
8585
*
8686
* - a delete's cascade walk deletes (or clears) each dependent through the
8787
* public write path, before the parent's own row is removed. A dependent's
8888
* refusal stops the walk, so the parent's row is never removed — and under
8989
* the `'atomic'` plan the transaction then rolls the dependent back too;
9090
* - a `transaction()` whose callback lets the refusal escape rolls back every
91-
* write in it, the refusing one included.
91+
* write in it, the refusing one included;
92+
* - a hook that writes through `ctx.api` and lets that write's refusal escape
93+
* stops the write it is hooked to, whose caller would otherwise read the
94+
* hook's write as its own.
9295
*
9396
* Either way the caller's own write did not land, so it is told so: an error
9497
* with no `code` (an internal failure, which is what an unrecomputable roll-up
@@ -127,6 +130,34 @@ export function cascadeStoppedRefusal(e: unknown, object: string): unknown {
127130
);
128131
}
129132

133+
/**
134+
* {@link unlandedWriteRefusal} for a write whose hook a nested write's refusal
135+
* stopped.
136+
*
137+
* A hook that writes through `ctx.api` makes a write of its own. When that
138+
* write raises {@link SummaryRecomputeError}, the refusal leaves the handler
139+
* carrying the HOOK's write as `written`. Let through, it reached the outer
140+
* write's caller as that caller's own refusal, so a door answered the hook's
141+
* record as the result of the write it was asked for. The outer write did not
142+
* complete either: the rest of its chain, its own roll-ups and its events never
143+
* ran. An `after*` hook's unit (`inAfterAbortUnit`) now rolls back both rows,
144+
* as `HookSchema.onError` `abort` says.
145+
*
146+
* Only the refusal is converted; every other error a hook throws passes
147+
* through unchanged. And only one a handler let escape: a hook whose `onError`
148+
* is `log` swallows it before it gets here.
149+
*/
150+
export function hookStoppedRefusal(e: unknown, event: string, object: string | undefined, hook: string | undefined): unknown {
151+
const verb = event.replace(/^(before|after)/, '').toLowerCase() || event;
152+
return unlandedWriteRefusal(
153+
e,
154+
// Double quotes, as in `cascadeStoppedRefusal`.
155+
`The ${verb} of "${object ?? '?'}" did not complete: its ${event} hook${hook ? ` "${hook}"` : ''} stopped. ` +
156+
'Under a transaction that rolls back nothing was written; otherwise what was written before that point ' +
157+
'stays written.',
158+
);
159+
}
160+
130161
/** {@link unlandedWriteRefusal} for a transaction the refusal rolled back. */
131162
export function rolledBackRefusal(e: unknown): unknown {
132163
return unlandedWriteRefusal(e, 'The transaction rolled back, so nothing written inside it was stored.');

0 commit comments

Comments
 (0)