Skip to content

Commit c594fd0

Browse files
committed
fix(objectql)!: the unlanded-write refusal leads with the outer write, declares 500 INTERNAL_ERROR, and never claims a failed rollback
- A conversion that meets an earlier one re-leads it (cascade walk and hook seam), so a nested cascade's caller reads its own object; `cause` stays the original ERR_SUMMARY_RECOMPUTE at every depth. - The converted error declares `status: 500` and `code: INTERNAL_ERROR`, so doors read it structurally. Data door body byte-identical; the action door now answers 500 INTERNAL_ERROR (was 400), same sentence. - ObjectQL.transaction no longer says "rolled back" when its rollback threw: rollbackFailedRefusal says nothing is known about what is stored. Forced test edits: the #29381 objectql pin's code assertions (undefined -> INTERNAL_ERROR), the action pin's 400 -> 500, and the data door pin tightened to the whole body. Claude-Session: https://claude.ai/code/session_01ADHkmPCSqt8uDw17RmX9hu Co-authored-by: Claude <noreply@anthropic.com>
1 parent 61f49fa commit c594fd0

7 files changed

Lines changed: 318 additions & 27 deletions

‎packages/objectql/src/engine-cascade-summary-rollback.test.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,8 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren
144144
const { engine, driver } = await makeEngine(true);
145145
const err: any = await engine.delete('acct', { where: { id: 'a1' } }).then(() => null, (e: unknown) => e);
146146
expect(err).toBeInstanceOf(Error);
147-
expect(err.code).toBeUndefined();
147+
expect(err.code).toBe('INTERNAL_ERROR');
148+
expect(err.status).toBe(500);
148149
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
149150
expect(err.written).toBeUndefined();
150151
expect(driver.rolledBack).toHaveLength(1);
@@ -156,7 +157,8 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren
156157
const { engine, driver } = await makeEngine(false);
157158
const err: any = await engine.delete('acct', { where: { id: 'a1' } }).then(() => null, (e: unknown) => e);
158159
expect(err).toBeInstanceOf(Error);
159-
expect(err.code).toBeUndefined();
160+
expect(err.code).toBe('INTERNAL_ERROR');
161+
expect(err.status).toBe(500);
160162
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
161163
expect(ids(driver.rowsOf('acct'))).toEqual(['a1']);
162164
// The dependent the walk reached first is gone: nothing can roll it back.
@@ -167,7 +169,8 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren
167169
const { engine, driver } = await makeEngine(false);
168170
const err: any = await engine.delete('acct', { where: { name: 'A' }, multi: true }).then(() => null, (e: unknown) => e);
169171
expect(err).toBeInstanceOf(Error);
170-
expect(err.code).toBeUndefined();
172+
expect(err.code).toBe('INTERNAL_ERROR');
173+
expect(err.status).toBe(500);
171174
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
172175
expect(ids(driver.rowsOf('acct'))).toEqual(['a1']);
173176
});
@@ -178,7 +181,8 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren
178181
.transaction(async (trx: any) => engine.delete('line', { where: { id: 'l1' }, context: trx }))
179182
.then(() => null, (e: unknown) => e);
180183
expect(err).toBeInstanceOf(Error);
181-
expect(err.code).toBeUndefined();
184+
expect(err.code).toBe('INTERNAL_ERROR');
185+
expect(err.status).toBe(500);
182186
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
183187
expect(driver.rolledBack).toHaveLength(1);
184188
expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2']);
@@ -191,7 +195,8 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren
191195
.transaction(async (trx: any) => trx.object('line').deleteById('l1'))
192196
.then(() => null, (e: unknown) => e);
193197
expect(err).toBeInstanceOf(Error);
194-
expect(err.code).toBeUndefined();
198+
expect(err.code).toBe('INTERNAL_ERROR');
199+
expect(err.status).toBe(500);
195200
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
196201
expect(driver.rolledBack).toHaveLength(1);
197202
expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2']);

‎packages/objectql/src/engine-hook-stale-summary-refusal.test.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
* Pinned here, at the one seam a handler's error leaves through
1919
* (`triggerHooks`):
2020
* - 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;
21+
* write refuses with an error that is NOT the stale-roll-up refusal (a
22+
* declared `500 INTERNAL_ERROR`, no `written`, the refusal kept as `cause`),
23+
* leading with the outer write, and its unit rolls both rows back;
2424
* - a code-registered hook (no unit opens): the same refusal, whose text says
2525
* what stays written, and both rows are stored;
2626
* - a `before*` hook: the same refusal, and the outer row was never written.
@@ -132,7 +132,8 @@ const names = (rows: Row[]) => rows.map((r) => r.name).sort();
132132
/** The converted refusal: an internal error naming the OUTER write, the hook write's refusal kept as `cause`. */
133133
function expectHookStopped(err: any, lead: string) {
134134
expect(err).toBeInstanceOf(Error);
135-
expect(err.code).toBeUndefined();
135+
expect(err.code).toBe('INTERNAL_ERROR');
136+
expect(err.status).toBe(500);
136137
expect(err.written).toBeUndefined();
137138
expect(err.failures).toBeUndefined();
138139
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The refusal a write answers when a nested write's stale-roll-up refusal
5+
* stopped it (`summary-errors.ts`, #29291) leads with the write its caller
6+
* asked for, and never claims a rollback that failed.
7+
*
8+
* 1. A nested cascade: deleting an account walks its lines, each line's
9+
* delete walks its subs, and a sub's delete refuses on recompute (its
10+
* roll-up into `bucket` cannot be recomputed). The line's walk converts
11+
* first, naming the line; the account's walk then received a code-less
12+
* error and passed it through, so the account's caller read
13+
* `The delete of "line" did not complete`. Now each outer walk re-leads
14+
* it, at every depth, and `cause` stays the sub's own refusal.
15+
* 2. `ObjectQL.transaction` swallows a failing rollback so the original error
16+
* surfaces. It still converted that error to "The transaction rolled back,
17+
* so nothing written inside it was stored". Now, when the rollback threw,
18+
* the lead says that nothing is known about what is stored.
19+
*
20+
* Controls: a delete of the sub itself still answers `ERR_SUMMARY_RECOMPUTE`
21+
* with its own result; a transaction whose rollback succeeds still says it
22+
* rolled back.
23+
*
24+
* The driver rolls back for real (a snapshot per transaction), refuses every
25+
* write to `bucket` while `refuseBucket` is set (the roll-up recompute's parent
26+
* update, refused without a transient message, so no retry runs), and makes
27+
* `rollback()` throw while `failRollback` is set.
28+
*/
29+
30+
import { describe, it, expect } from 'vitest';
31+
import { ObjectQL } from './engine.js';
32+
import { SummaryRecomputeError, cascadeStoppedRefusal, hookStoppedRefusal } from './summary-errors.js';
33+
34+
type Row = Record<string, unknown>;
35+
36+
function matches(row: Row, where: any): boolean {
37+
if (!where || typeof where !== 'object') return true;
38+
return Object.entries(where).every(([k, v]) => {
39+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
40+
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
41+
if (k.startsWith('$')) return true;
42+
if (v && typeof v === 'object' && !Array.isArray(v)) {
43+
const ops = v as Record<string, unknown>;
44+
if ('$in' in ops) return (ops.$in as unknown[]).map(String).includes(String(row[k]));
45+
if ('$eq' in ops) return String(row[k]) === String(ops.$eq);
46+
if ('$ne' in ops) return String(row[k]) !== String(ops.$ne);
47+
return true;
48+
}
49+
return row[k] === v || (row[k] != null && v != null && String(row[k]) === String(v));
50+
});
51+
}
52+
53+
function makeDriver() {
54+
let stores = new Map<string, Map<string, Row>>();
55+
const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!);
56+
const rolledBack: unknown[] = [];
57+
const snapshots = new Map<unknown, typeof stores>();
58+
const state = { refuseBucket: false, failRollback: false };
59+
let n = 0;
60+
const driver: any = {
61+
name: 'primary', version: '0.0.0', supports: {}, rolledBack, state,
62+
rowsOf: (o: string) => Array.from(storeFor(o).values()),
63+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
64+
async syncSchema() {},
65+
async find(o: string, ast: any) {
66+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
67+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
68+
},
69+
async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; },
70+
async create(o: string, data: Row) {
71+
const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` };
72+
storeFor(o).set(String(row.id), row);
73+
return row;
74+
},
75+
async update(o: string, id: string, data: Row) {
76+
if (state.refuseBucket && o === 'bucket') throw new Error('bucket store refused the write');
77+
const row = { ...storeFor(o).get(String(id)), ...data, id };
78+
storeFor(o).set(String(id), row);
79+
return row;
80+
},
81+
async delete(o: string, id: string) { return storeFor(o).delete(String(id)); },
82+
async deleteMany(o: string, ast: any) {
83+
const doomed = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
84+
for (const r of doomed) storeFor(o).delete(String(r.id));
85+
return doomed.length;
86+
},
87+
async count(o: string, ast: any) { return (await this.find(o, ast)).length; },
88+
async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); },
89+
async bulkUpdate() { return []; }, async bulkDelete() {},
90+
async beginTransaction() {
91+
const handle = { trx: snapshots.size + 1 };
92+
snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))])));
93+
return handle;
94+
},
95+
async commit(h: unknown) { snapshots.delete(h); },
96+
async rollback(h: unknown) {
97+
if (state.failRollback) throw new Error('connection lost during rollback');
98+
stores = snapshots.get(h) ?? stores;
99+
rolledBack.push(h);
100+
},
101+
};
102+
return driver;
103+
}
104+
105+
async function makeEngine() {
106+
const log = () => {};
107+
const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any);
108+
(engine as any).summaryRetryOptions = { sleep: async () => {}, backoffBaseMs: 0 };
109+
const driver = makeDriver();
110+
engine.registerDriver(driver, true);
111+
await engine.init();
112+
const text = (name: string) => ({ name, type: 'text' });
113+
const id = { ...text('id'), primaryKey: true };
114+
engine.registry.registerObject({ name: 'acct', label: 'acct', fields: { id, name: text('name') } } as any, '__test__');
115+
engine.registry.registerObject({
116+
name: 'bucket', label: 'bucket',
117+
fields: { id, name: text('name'), sub_count: { name: 'sub_count', type: 'summary', summaryOperations: { object: 'sub', function: 'count' } } },
118+
} as any, '__test__');
119+
engine.registry.registerObject({
120+
name: 'line', label: 'line',
121+
fields: { id, name: text('name'), acct: { name: 'acct', type: 'master_detail', reference: 'acct', deleteBehavior: 'cascade' } },
122+
} as any, '__test__');
123+
engine.registry.registerObject({
124+
name: 'sub', label: 'sub',
125+
fields: {
126+
id, name: text('name'),
127+
line: { name: 'line', type: 'master_detail', reference: 'line', deleteBehavior: 'cascade' },
128+
bucket: { name: 'bucket', type: 'lookup', reference: 'bucket' },
129+
},
130+
} as any, '__test__');
131+
await engine.insert('acct', { id: 'a1', name: 'A' });
132+
await engine.insert('bucket', { id: 'b1', name: 'B' });
133+
await engine.insert('line', { id: 'l1', name: 'L1', acct: 'a1' });
134+
await engine.insert('sub', { id: 's1', name: 'S1', line: 'l1', bucket: 'b1' });
135+
driver.rolledBack.length = 0;
136+
driver.state.refuseBucket = true;
137+
return { engine, driver };
138+
}
139+
140+
const refusal = (p: Promise<unknown>): Promise<any> => p.then(() => null, (e: unknown) => e);
141+
const ids = (rows: Row[]) => rows.map((r) => r.id).sort();
142+
143+
describe('the unlanded-write refusal leads with the write its caller asked for', () => {
144+
it('a three-level cascade: the account\'s caller reads the account, and `cause` is the sub\'s own refusal', async () => {
145+
const { engine, driver } = await makeEngine();
146+
const err = await refusal(engine.delete('acct', { where: { id: 'a1' } }));
147+
expect(err).toBeInstanceOf(Error);
148+
expect(err.code).toBe('INTERNAL_ERROR');
149+
expect(err.status).toBe(500);
150+
expect(err.message.startsWith('The delete of "acct" did not complete: its cascade stopped'), err.message).toBe(true);
151+
expect(err.message).not.toContain('"line"');
152+
expect(err.message).toContain('bucket.sub_count');
153+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
154+
expect(err.cause?.failures?.[0]?.childObject).toBe('sub');
155+
expect(ids(driver.rowsOf('acct'))).toEqual(['a1']);
156+
expect(ids(driver.rowsOf('line'))).toEqual(['l1']);
157+
expect(ids(driver.rowsOf('sub'))).toEqual(['s1']);
158+
});
159+
160+
it('the middle level\'s own caller still reads the line', async () => {
161+
const { engine } = await makeEngine();
162+
const err = await refusal(engine.delete('line', { where: { id: 'l1' } }));
163+
expect(err.message.startsWith('The delete of "line" did not complete'), err.message).toBe(true);
164+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
165+
});
166+
167+
it('every outer conversion re-leads, whatever the depth, and keeps the original refusal as cause', () => {
168+
const original = new SummaryRecomputeError([{ childObject: 'sub', parentObject: 'bucket', parentId: 'b1', field: 'sub_count', error: null }], true);
169+
const inner = cascadeStoppedRefusal(original, 'line') as any;
170+
const outer = cascadeStoppedRefusal(inner, 'acct') as any;
171+
const hooked = hookStoppedRefusal(outer, 'afterInsert', 'case', 'cleanup') as any;
172+
expect(outer.message.startsWith('The delete of "acct" did not complete'), outer.message).toBe(true);
173+
expect(hooked.message.startsWith('The insert of "case" did not complete: its afterInsert hook "cleanup" stopped.'), hooked.message).toBe(true);
174+
for (const e of [inner, outer, hooked]) {
175+
expect(e.cause).toBe(original);
176+
expect(e.code).toBe('INTERNAL_ERROR');
177+
expect(e.status).toBe(500);
178+
expect(e.message).toContain('bucket.sub_count');
179+
}
180+
});
181+
182+
it('CONTROL a code-less error that is no conversion passes every conversion unchanged', () => {
183+
const other = new Error('something else');
184+
expect(cascadeStoppedRefusal(other, 'acct')).toBe(other);
185+
expect(hookStoppedRefusal(other, 'afterInsert', 'case', undefined)).toBe(other);
186+
});
187+
188+
it('CONTROL the sub\'s own delete landed: ERR_SUMMARY_RECOMPUTE, carrying its result', async () => {
189+
const { engine, driver } = await makeEngine();
190+
const err = await refusal(engine.delete('sub', { where: { id: 's1' } }));
191+
expect(err?.code).toBe('ERR_SUMMARY_RECOMPUTE');
192+
expect(err.written).toBe(true);
193+
expect(driver.rowsOf('sub')).toHaveLength(0);
194+
});
195+
});
196+
197+
describe('ObjectQL.transaction never claims "rolled back" when its rollback threw', () => {
198+
const escapeRefusal = (engine: ObjectQL) =>
199+
refusal(engine.transaction(async (trx: any) => engine.delete('sub', { where: { id: 's1' }, context: trx })));
200+
201+
it('the rollback throws: refused with a lead that says nothing is known, the refusal as cause', async () => {
202+
const { engine, driver } = await makeEngine();
203+
driver.state.failRollback = true;
204+
const err = await escapeRefusal(engine);
205+
expect(err).toBeInstanceOf(Error);
206+
expect(err.code).toBe('INTERNAL_ERROR');
207+
expect(err.status).toBe(500);
208+
expect(err.written).toBeUndefined();
209+
expect(err.message.startsWith(
210+
'The transaction did not complete, and its rollback failed too, so what was written inside it may or may not be stored.',
211+
), err.message).toBe(true);
212+
expect(err.message).not.toContain('rolled back');
213+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
214+
expect(driver.rolledBack).toHaveLength(0);
215+
});
216+
217+
it('CONTROL the rollback succeeds: "The transaction rolled back", and nothing is stored', async () => {
218+
const { engine, driver } = await makeEngine();
219+
const err = await escapeRefusal(engine);
220+
expect(err.message.startsWith('The transaction rolled back, so nothing written inside it was stored.'), err.message).toBe(true);
221+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
222+
expect(driver.rolledBack).toHaveLength(1);
223+
expect(ids(driver.rowsOf('sub'))).toEqual(['s1']);
224+
});
225+
});

‎packages/objectql/src/engine.ts‎

Lines changed: 6 additions & 2 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, hookStoppedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
204+
import { SummaryRecomputeError, cascadeStoppedRefusal, hookStoppedRefusal, rollbackFailedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
205205
import { TransactionUnsupportedError } from './transaction-errors.js';
206206
import {
207207
aggregateSummaryValue,
@@ -21927,18 +21927,22 @@ export class ObjectQL implements IObjectQLEngine {
2192721927
else if (drv.commitTransaction) await drv.commitTransaction(trx);
2192821928
return result;
2192921929
} catch (err) {
21930+
let rollbackFailed = false;
2193021931
try {
2193121932
if (drv.rollback) await drv.rollback(trx);
2193221933
else if (drv.rollbackTransaction) await drv.rollbackTransaction(trx);
2193321934
} catch {
2193421935
// swallow rollback failures so the original error surfaces
21936+
rollbackFailed = true;
2193521937
}
2193621938
// [#21274] A boundary outside the middleware seam: a commit failure, or
2193721939
// a callback that reached the driver through the transaction handle.
2193821940
// An error that already crossed an engine boundary inside the callback
2193921941
// comes back as the same reference. A stale-roll-up refusal ("stored")
2194021942
// is no longer true once this rollback has run: `rolledBackRefusal`.
21941-
throw redactPropagatedDriverFault(rolledBackRefusal(err));
21943+
// [#29421] Nor is "rolled back" once the rollback threw:
21944+
// `rollbackFailedRefusal`.
21945+
throw redactPropagatedDriverFault(rollbackFailed ? rollbackFailedRefusal(err) : rolledBackRefusal(err));
2194221946
}
2194321947
}
2194421948

0 commit comments

Comments
 (0)