Skip to content

Commit 7b3b830

Browse files
committed
fix(objectql)!: a nested write's stale-roll-up refusal never answers for a delete or transaction that did not land
A cascade dependent's ERR_SUMMARY_RECOMPUTE stopped the parent delete's walk (and, under the atomic plan, rolled the dependent back), yet reached the caller unchanged, so every surface that answers that refusal as the write's success reported a delete that never happened. The cascade walk and both owned transaction() rollbacks now convert it into a code-less refusal carrying the original as cause. Claude-Session: https://claude.ai/code/session_01ADHkmQQoWsHzMSsiaM89mr Co-authored-by: Claude <noreply@anthropic.com>
1 parent a19759a commit 7b3b830

4 files changed

Lines changed: 433 additions & 8 deletions

File tree

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A cascade dependent's stale-roll-up refusal never answers for a delete that
5+
* did not land.
6+
*
7+
* `SummaryRecomputeError` (`ERR_SUMMARY_RECOMPUTE`) means "this write is
8+
* stored, only a parent's roll-up recompute failed", and every answering
9+
* surface (the data doors, the action / sandbox / flow writers) turns it into
10+
* the write's own success. A by-id delete walks its `master_detail`
11+
* dependents first, each through the public `delete()`. When one dependent's
12+
* delete raises that refusal (its roll-up into ANOTHER parent cannot be
13+
* recomputed), the walk stops before the parent's own row is removed, so the
14+
* parent delete did not land — under the `'atomic'` plan the transaction then
15+
* rolls the dependent back too. The refusal used to leave the parent's
16+
* `delete()` unchanged, and the caller was told the delete succeeded.
17+
*
18+
* Pinned here: the parent delete refuses with an error that is NOT the
19+
* stale-roll-up refusal, on the atomic plan (nothing stored changes) and on a
20+
* runtime that cannot roll back (the parent is still stored); a refusal that
21+
* escapes a caller's own `transaction()` that rolls back is converted the same
22+
* way. Controls: a delete of the dependent itself — its own write landed, only
23+
* its recompute failed — still answers `ERR_SUMMARY_RECOMPUTE` carrying its
24+
* result, and so does a caller's transaction that catches it and commits.
25+
*
26+
* The driver rolls back for real (a snapshot per transaction), and refuses
27+
* every write to `bucket` while `refuseBucket` is set: that is the roll-up
28+
* recompute's parent update, refused without a transient message, so no retry
29+
* runs.
30+
*/
31+
32+
import { describe, it, expect } from 'vitest';
33+
import { ObjectQL } from './engine.js';
34+
35+
type Row = Record<string, unknown>;
36+
37+
function matches(row: Row, where: any): boolean {
38+
if (!where || typeof where !== 'object') return true;
39+
return Object.entries(where).every(([k, v]) => {
40+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
41+
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
42+
if (k.startsWith('$')) return true;
43+
if (v && typeof v === 'object' && !Array.isArray(v)) {
44+
const ops = v as Record<string, unknown>;
45+
if ('$in' in ops) return (ops.$in as unknown[]).map(String).includes(String(row[k]));
46+
if ('$eq' in ops) return String(row[k]) === String(ops.$eq);
47+
if ('$ne' in ops) return String(row[k]) !== String(ops.$ne);
48+
return true;
49+
}
50+
return row[k] === v || (row[k] != null && v != null && String(row[k]) === String(v));
51+
});
52+
}
53+
54+
function makeDriver(transactional: boolean) {
55+
let stores = new Map<string, Map<string, Row>>();
56+
const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!);
57+
const begun: unknown[] = [];
58+
const rolledBack: unknown[] = [];
59+
const snapshots = new Map<unknown, typeof stores>();
60+
const state = { refuseBucket: false };
61+
let n = 0;
62+
const driver: any = {
63+
name: 'primary', version: '0.0.0', supports: {}, begun, rolledBack, state,
64+
rowsOf: (o: string) => Array.from(storeFor(o).values()),
65+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
66+
async syncSchema() {},
67+
async find(o: string, ast: any) {
68+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
69+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
70+
},
71+
async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; },
72+
async create(o: string, data: Row) {
73+
const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` };
74+
storeFor(o).set(String(row.id), row);
75+
return row;
76+
},
77+
async update(o: string, id: string, data: Row) {
78+
if (state.refuseBucket && o === 'bucket') throw new Error('bucket store refused the write');
79+
const row = { ...storeFor(o).get(String(id)), ...data, id };
80+
storeFor(o).set(String(id), row);
81+
return row;
82+
},
83+
async delete(o: string, id: string) { return storeFor(o).delete(String(id)); },
84+
async count(o: string, ast: any) { return (await this.find(o, ast)).length; },
85+
async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); },
86+
async bulkUpdate() { return []; }, async bulkDelete() {},
87+
};
88+
if (transactional) {
89+
driver.beginTransaction = async () => {
90+
const handle = { trx: begun.length + 1 };
91+
snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))])));
92+
begun.push(handle);
93+
return handle;
94+
};
95+
driver.commit = async (h: unknown) => { snapshots.delete(h); };
96+
driver.rollback = async (h: unknown) => { stores = snapshots.get(h) ?? stores; rolledBack.push(h); };
97+
}
98+
return driver;
99+
}
100+
101+
async function makeEngine(transactional: boolean) {
102+
const log = () => {};
103+
const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any);
104+
const driver = makeDriver(transactional);
105+
engine.registerDriver(driver, true);
106+
await engine.init();
107+
const text = (name: string) => ({ name, type: 'text' });
108+
engine.registry.registerObject({ name: 'acct', label: 'acct', fields: { id: { ...text('id'), primaryKey: true }, name: text('name') } } as any, '__test__');
109+
engine.registry.registerObject({
110+
name: 'bucket', label: 'bucket',
111+
fields: {
112+
id: { ...text('id'), primaryKey: true }, name: text('name'),
113+
line_count: { name: 'line_count', type: 'summary', summaryOperations: { object: 'line', function: 'count' } },
114+
},
115+
} as any, '__test__');
116+
engine.registry.registerObject({
117+
name: 'line', label: 'line',
118+
fields: {
119+
id: { ...text('id'), primaryKey: true }, name: text('name'),
120+
acct: { name: 'acct', type: 'master_detail', reference: 'acct', deleteBehavior: 'cascade' },
121+
bucket: { name: 'bucket', type: 'lookup', reference: 'bucket' },
122+
},
123+
} as any, '__test__');
124+
await engine.insert('acct', { id: 'a1', name: 'A' });
125+
await engine.insert('bucket', { id: 'b1', name: 'B' });
126+
await engine.insert('line', { id: 'l1', name: 'L1', acct: 'a1', bucket: 'b1' });
127+
await engine.insert('line', { id: 'l2', name: 'L2', acct: 'a1', bucket: 'b1' });
128+
driver.begun.length = 0;
129+
driver.rolledBack.length = 0;
130+
driver.state.refuseBucket = true;
131+
return { engine, driver };
132+
}
133+
134+
const ids = (rows: Row[]) => rows.map((r) => r.id).sort();
135+
136+
describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a parent delete that did not land', () => {
137+
it('atomic plan: the parent delete refuses with another error, and nothing stored changes', async () => {
138+
const { engine, driver } = await makeEngine(true);
139+
const err: any = await engine.delete('acct', { where: { id: 'a1' } } as any).then(() => null, (e: unknown) => e);
140+
expect(err).toBeInstanceOf(Error);
141+
expect(err.code).toBeUndefined();
142+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
143+
expect(err.written).toBeUndefined();
144+
expect(driver.rolledBack).toHaveLength(1);
145+
expect(ids(driver.rowsOf('acct'))).toEqual(['a1']);
146+
expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2']);
147+
});
148+
149+
it('a runtime that cannot roll back: the parent is still stored, and the caller is refused', async () => {
150+
const { engine, driver } = await makeEngine(false);
151+
const err: any = await engine.delete('acct', { where: { id: 'a1' } } as any).then(() => null, (e: unknown) => e);
152+
expect(err).toBeInstanceOf(Error);
153+
expect(err.code).toBeUndefined();
154+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
155+
expect(ids(driver.rowsOf('acct'))).toEqual(['a1']);
156+
// The dependent the walk reached first is gone: nothing can roll it back.
157+
expect(ids(driver.rowsOf('line'))).toEqual(['l2']);
158+
});
159+
160+
it('a caller\'s own transaction that the refusal rolls back: refused with another error, nothing stored', async () => {
161+
const { engine, driver } = await makeEngine(true);
162+
const err: any = await engine
163+
.transaction(async (trx: any) => engine.delete('line', { where: { id: 'l1' }, context: trx } as any))
164+
.then(() => null, (e: unknown) => e);
165+
expect(err).toBeInstanceOf(Error);
166+
expect(err.code).toBeUndefined();
167+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
168+
expect(driver.rolledBack).toHaveLength(1);
169+
expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2']);
170+
});
171+
172+
it('the same through a scoped context\'s transaction (ctx.api)', async () => {
173+
const { engine, driver } = await makeEngine(true);
174+
const scoped = (engine as any).createContext({ isSystem: true });
175+
const err: any = await scoped
176+
.transaction(async (trx: any) => trx.object('line').deleteById('l1'))
177+
.then(() => null, (e: unknown) => e);
178+
expect(err).toBeInstanceOf(Error);
179+
expect(err.code).toBeUndefined();
180+
expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE');
181+
expect(driver.rolledBack).toHaveLength(1);
182+
expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2']);
183+
});
184+
185+
it('CONTROL the dependent\'s own delete landed: ERR_SUMMARY_RECOMPUTE, carrying its result', async () => {
186+
const { engine, driver } = await makeEngine(true);
187+
const err: any = await engine.delete('line', { where: { id: 'l1' } } as any).then(() => null, (e: unknown) => e);
188+
expect(err?.code).toBe('ERR_SUMMARY_RECOMPUTE');
189+
expect(err.written).toBe(true);
190+
expect(ids(driver.rowsOf('line'))).toEqual(['l2']);
191+
});
192+
193+
it('CONTROL a caller\'s transaction that catches the refusal commits, and the refusal stays true', async () => {
194+
const { engine, driver } = await makeEngine(true);
195+
let caught: any;
196+
await engine.transaction(async (trx: any) => {
197+
await engine.delete('line', { where: { id: 'l1' }, context: trx } as any).catch((e: unknown) => { caught = e; });
198+
});
199+
expect(caught?.code).toBe('ERR_SUMMARY_RECOMPUTE');
200+
expect(driver.rolledBack).toHaveLength(0);
201+
expect(ids(driver.rowsOf('line'))).toEqual(['l2']);
202+
});
203+
});

‎packages/objectql/src/engine.ts‎

Lines changed: 18 additions & 8 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, type SummaryRecomputeFailure } from './summary-errors.js';
204+
import { SummaryRecomputeError, cascadeStoppedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
205205
import { TransactionUnsupportedError } from './transaction-errors.js';
206206
import {
207207
aggregateSummaryValue,
@@ -20917,8 +20917,13 @@ export class ObjectQL implements IObjectQLEngine {
2091720917
// wrapping its cascade. `buildDriverOptions` only fills keys that
2091820918
// are still `undefined`, so re-running it adds the handle and
2091920919
// changes nothing else.
20920+
//
20921+
// A dependent's stale-roll-up refusal stops the walk before this
20922+
// row is removed, so it is not this delete's answer:
20923+
// `cascadeStoppedRefusal` says what it is instead.
2092020924
const runByIdDelete = async (writeContext?: ExecutionContext) => {
20921-
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext);
20925+
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext)
20926+
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
2092220927
return await driver.delete(
2092320928
object,
2092420929
hookContext.input.id as string,
@@ -21010,8 +21015,11 @@ export class ObjectQL implements IObjectQLEngine {
2101021015
const matchedIds = matched.map((row) => row?.id).filter((v): v is string | number => v != null);
2101121016
if (summaryKeyColumns.length > 0) summaryPriorRows = withoutDeletedSelfParents(object, matched, matchedIds, this.getSummaryDescriptors(object));
2101221017
deletedSecrets = deletedSecretSlots(deleteSchema, matched);
21013-
// [#27004] One walk, rooted at the whole matched set.
21014-
await this.cascadeDeleteRelations(object, matchedIds, writeContext);
21018+
// [#27004] One walk, rooted at the whole matched set. A
21019+
// dependent's stale-roll-up refusal is not this delete's
21020+
// answer, as in the by-id branch.
21021+
await this.cascadeDeleteRelations(object, matchedIds, writeContext)
21022+
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
2101521023
// The id set rides an `$in`; batched so one statement never
2101621024
// outgrows a driver's bind-parameter limit.
2101721025
const batchSize = ObjectQL.REFERENCE_PROBE_BATCH;
@@ -21864,8 +21872,9 @@ export class ObjectQL implements IObjectQLEngine {
2186421872
// [#21274] A boundary outside the middleware seam: a commit failure, or
2186521873
// a callback that reached the driver through the transaction handle.
2186621874
// An error that already crossed an engine boundary inside the callback
21867-
// comes back as the same reference.
21868-
throw redactPropagatedDriverFault(err);
21875+
// comes back as the same reference. A stale-roll-up refusal ("stored")
21876+
// is no longer true once this rollback has run: `rolledBackRefusal`.
21877+
throw redactPropagatedDriverFault(rolledBackRefusal(err));
2186921878
}
2187021879
}
2187121880

@@ -22855,8 +22864,9 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
2285522864
} catch (error) {
2285622865
if (driver.rollback) await driver.rollback(trx);
2285722866
else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);
22858-
// [#21274] The engine surface's twin (`ObjectQL.transaction`).
22859-
throw redactPropagatedDriverFault(error);
22867+
// [#21274] The engine surface's twin (`ObjectQL.transaction`), the
22868+
// stale-roll-up conversion included.
22869+
throw redactPropagatedDriverFault(rolledBackRefusal(error));
2286022870
}
2286122871
}
2286222872

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,60 @@ export class SummaryRecomputeError extends Error {
7272
this.name = 'SummaryRecomputeError';
7373
}
7474
}
75+
76+
/**
77+
* The refusal a unit answers when a write NESTED in it raised
78+
* {@link SummaryRecomputeError} and the unit itself then did not land.
79+
*
80+
* That refusal says "this write is stored, only a roll-up recompute failed",
81+
* 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
84+
* being true:
85+
*
86+
* - a delete's cascade walk deletes (or clears) each dependent through the
87+
* public write path, before the parent's own row is removed. A dependent's
88+
* refusal stops the walk, so the parent's row is never removed — and under
89+
* the `'atomic'` plan the transaction then rolls the dependent back too;
90+
* - a `transaction()` whose callback lets the refusal escape rolls back every
91+
* write in it, the refusing one included.
92+
*
93+
* Either way the caller's own write did not land, so it is told so: an error
94+
* with no `code` (an internal failure, which is what an unrecomputable roll-up
95+
* is), the original refusal kept as `cause` for the operator. Every other error
96+
* passes through unchanged, and so does the refusal anywhere it is still true:
97+
* the dependent's own delete, a write outside any unit, a transaction that
98+
* catches it and commits, a joined transaction whose owner decides.
99+
*
100+
* Matched by `code`, as every reader of the refusal matches it.
101+
*/
102+
function unlandedWriteRefusal(e: unknown, lead: string): unknown {
103+
if (!(e instanceof Error) || (e as { code?: unknown }).code !== SUMMARY_RECOMPUTE_CODE) return e;
104+
const failures = (e as { failures?: unknown }).failures;
105+
const named = Array.isArray(failures)
106+
? [...new Set((failures as SummaryRecomputeFailure[]).map((f) => `${f?.parentObject}.${f?.field}`))]
107+
: [];
108+
const summaries = named.length > 0 ? `the roll-up summary ${named.join(', ')}` : 'a parent roll-up summary';
109+
const refusal = new Error(
110+
`${lead} A write inside it was stored, then ${summaries} could not be recomputed after it, and that ` +
111+
"refusal stopped it. Fix the summary field's `summaryOperations` (the engine's warning names why the " +
112+
'recompute was refused), then retry.',
113+
);
114+
(refusal as Error & { cause?: unknown }).cause = e;
115+
return refusal;
116+
}
117+
118+
/** {@link unlandedWriteRefusal} for a delete whose cascade walk the refusal stopped. */
119+
export function cascadeStoppedRefusal(e: unknown, object: string): unknown {
120+
return unlandedWriteRefusal(
121+
e,
122+
`The delete of '${object}' did not complete: its cascade stopped before the record was removed. ` +
123+
'Under a transaction that rolls back nothing was written; otherwise the dependents written before ' +
124+
'that point stay written.',
125+
);
126+
}
127+
128+
/** {@link unlandedWriteRefusal} for a transaction the refusal rolled back. */
129+
export function rolledBackRefusal(e: unknown): unknown {
130+
return unlandedWriteRefusal(e, 'The transaction rolled back, so nothing written inside it was stored.');
131+
}

0 commit comments

Comments
 (0)