|
| 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 | +}); |
0 commit comments