diff --git a/.changeset/33699-cascade-delete-batch.md b/.changeset/33699-cascade-delete-batch.md new file mode 100644 index 00000000000..76cb7e965ff --- /dev/null +++ b/.changeset/33699-cascade-delete-batch.md @@ -0,0 +1,26 @@ +--- +'@objectstack/objectql': patch +'@objectstack/spec': patch +--- + +perf(objectql)!: a cascade delete removes a relation's children as one predicate delete per chunk + +Clause-②: no (narrowing) — the published hook dispatch shape for cascaded children changes (`dispatch.mode` 'record' → 'per-row', `options.multi`, before-hooks run before the set delete); BREAKING banner + ADR-0087 disposition in the changeset; one CONTRACT_REVIEW_TIER review owed before the queue +Metadata-protocol: none + + + +**BREAKING** for a delete-side hook that runs on a cascaded child and reads `ctx.dispatch.mode`, `ctx.input.options`, or the rows of the child's siblings. + +Deleting a record now deletes the children each `cascade` relation reaches as ONE predicate delete per chunk of 500, `DELETE … WHERE id IN (…)`, through the predicate-delete arm a `multi: true` delete already takes. Before this, every child was its own by-id delete. Measured on the SQL-performance bench (one opportunity with 10 line items, the stock plugins loaded): 155 statements before, 58 after, on SQLite and on PostgreSQL alike (one of the 58 is the read of each chunk's ids through the caller's read door). + +What a hook on a cascaded child sees: + +- FROM `ctx.dispatch.mode: 'record'` and `ctx.input.options` `{ where: { id } }` TO `ctx.dispatch.mode: 'per-row'`, with `ctx.dispatch.index` its position in the chunk and `ctx.input.options` carrying `where: { id: { $in: [...] } }` and `multi: true`. `ctx.input.id` and `ctx.previous` still name the child's own row, and `ctx.referentialCascadeDelete` is still `true` on every per-row context, in both phases, grandchildren included. +- FROM `ctx.result` in a cascaded child's `afterDelete` being the driver's by-id answer TO `ctx.result` absent, as on every per-row delete context. Read `ctx.previous` for the deleted row. +- FROM `ctx.dispatch.scope` one scratch object per cascaded child TO one object shared by every child of the chunk, in both phases (the scratch of one caller write, which the chunk now is). +- FROM one context object for a cascaded child's `beforeDelete` and `afterDelete` TO a fresh context per row per phase, so a value a `beforeDelete` handler leaves on `ctx` no longer reaches that child's `afterDelete`. Keep cross-phase state in `ctx.dispatch.scope`, keyed by `ctx.input.id`. +- The one behaviour that flips: the chunk runs every child's `beforeDelete`, then the one set delete, then every child's `afterDelete`. Before, each child ran before → delete → after in turn. So a `beforeDelete` hook that counts a child's remaining siblings now sees them ALL present, where it used to see one fewer at each step. Judge the whole batch instead: on `ctx.input.options.multi === true` read the target set from `ctx.input.options.where` (the shipped last-administrator guard does exactly this, and reaches the same verdict as before), or use `ctx.referentialCascadeDelete === true` to tell the cascade from a hand delete. +- A chunk the caller's scope narrows falls back to today's by-id deletes for that chunk, so the caller still meets the same refusal and the whole cascade rolls back: a child the caller may not delete, which a predicate delete would skip, and a child the caller may not read, which the by-id delete refuses through its re-read of the row (the cascade asks the caller's read door for each chunk's ids before batching it). Such a chunk keeps today's shape, `'record'` with no `multi`, so one cascade can show both shapes. A driver with no `deleteMany`, a floored external driver, and a cascade into the organization object (deleted by id or not at all) keep the by-id path too, and so does a child the walk finds that the cascade's collected set never held (a row a hook of the same cascade wrote after the set was collected): it is deleted as the root of its own cascade, with its own recycle-bin entry, as before. + +Unchanged: one `data.record.deleted` realtime event per child (never the bulk `data.records.deleted`); a refusal from any child's hook, or a permission refusal, rolls the whole cascade back; the recycle bin keeps one entry per root; the bulk per-row hook ceiling is never reached (a chunk is 500, the ceiling 10,000). On a runtime that cannot roll back, a refusal raised after a chunk's set delete (a failed roll-up recompute) now finds the whole chunk deleted, where the per-child walk had deleted only the children before the refusal. diff --git a/packages/objectql/src/engine-cascade-delete-batch.test.ts b/packages/objectql/src/engine-cascade-delete-batch.test.ts new file mode 100644 index 00000000000..4405ca2f5ec --- /dev/null +++ b/packages/objectql/src/engine-cascade-delete-batch.test.ts @@ -0,0 +1,491 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A cascade deletes a relation's children as a BATCH (ruling 6893661036, + * option F1): one predicate delete per chunk of children, so the chunk runs + * every child's `beforeDelete`, then ONE set delete, then the `afterDelete`s. + * + * Pinned here, on a real {@link ObjectQL} engine over a driver that rolls back + * for real (a snapshot per transaction) and logs every write it is handed: + * + * - the order (before x N, one `deleteMany` over `id IN (...)`, after x N) + * and the per-row context shape: `dispatch.mode` `'per-row'` with its own + * `index`, `input.options.multi`, `input.id` and `previous` the child's + * own row, and the declared `referentialCascadeDelete` marker on EVERY + * per-row context, both phases, grandchildren included; + * - chunks of 500 (REFERENCE_PROBE_BATCH); + * - realtime keeps one `data.record.deleted` per child (ruling 6893104201 + * point 1), never the bulk event; + * - a refusal anywhere in the batch rolls the whole cascade back (point 2); + * - a chunk whose caller-scoped read misses a child it asked for falls back + * to today's by-id deletes: today's shape (`'record'`, no `multi`), today's + * refusal envelope and rollback, and no batch hook ran first. One cascade + * can show both shapes; + * - so does a chunk the caller's READ door does not return whole: the read + * scope a by-id child delete enforces through its re-read (plugin-security + * step 2.7) is not on a nested predicate delete's write scope; + * - a driver with no `deleteMany` keeps the by-id path, and so does a cascade + * into the organization object, which is deleted by id or not at all. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts'; +import { ObjectQL } from './engine.js'; + +type Row = Record; + +function matches(row: Row, where: any): boolean { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); + if (k.startsWith('$')) return true; + if (v && typeof v === 'object' && !Array.isArray(v)) { + const ops = v as Record; + if ('$in' in ops) return (ops.$in as unknown[]).map(String).includes(String(row[k])); + if ('$nin' in ops) return !(ops.$nin as unknown[]).map(String).includes(String(row[k])); + if ('$eq' in ops) return String(row[k]) === String(ops.$eq); + return true; + } + return row[k] === v || (row[k] != null && v != null && String(row[k]) === String(v)); + }); +} + +function makeDriver(opts: { deleteMany?: boolean } = {}) { + let stores = new Map>(); + const storeFor = (o: string) => stores.get(o) ?? (stores.set(o, new Map()), stores.get(o)!); + const snapshots = new Map(); + const writes: string[] = []; + const rolledBack: unknown[] = []; + let n = 0; + const driver: any = { + name: 'primary', version: '0.0.0', supports: {}, writes, rolledBack, + rowsOf: (o: string) => Array.from(storeFor(o).values()), + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async syncSchema() {}, + async find(o: string, ast: any) { + const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(o: string, ast: any) { return (await this.find(o, ast))[0] ?? null; }, + async create(o: string, data: Row) { + const row = { ...data, id: (data.id as string) ?? `${o}_${++n}` }; + storeFor(o).set(String(row.id), row); + return row; + }, + async update(o: string, id: string, data: Row) { + const row = { ...storeFor(o).get(String(id)), ...data, id }; + storeFor(o).set(String(id), row); + return row; + }, + async delete(o: string, id: string) { + writes.push(`delete ${o} ${id}`); + return storeFor(o).delete(String(id)); + }, + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, + async bulkCreate(o: string, rows: Row[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { + const handle = { trx: snapshots.size + 1 }; + snapshots.set(handle, new Map(Array.from(stores, ([o, s]) => [o, new Map(Array.from(s, ([k, v]) => [k, { ...v }]))]))); + return handle; + }, + async commit(h: unknown) { snapshots.delete(h); }, + async rollback(h: unknown) { stores = snapshots.get(h) ?? stores; rolledBack.push(h); }, + }; + if (opts.deleteMany !== false) { + driver.deleteMany = async (o: string, ast: any) => { + const doomed = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); + writes.push(`deleteMany ${o} ${doomed.map((r) => r.id).join(',')}`); + for (const r of doomed) storeFor(o).delete(String(r.id)); + return doomed.length; + }; + } + return driver; +} + +const text = (name: string) => ({ name, type: 'text' }); + +async function makeEngine(opts: { deleteMany?: boolean; lines?: number } = {}) { + const log = () => {}; + const engine = new ObjectQL({ logger: { debug: log, info: log, warn: log, error: log } } as any); + const driver = makeDriver(opts); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject({ name: 'acct', label: 'acct', fields: { id: { ...text('id'), primaryKey: true }, name: text('name') } } as any, '__test__'); + engine.registry.registerObject({ + name: 'line', label: 'line', + fields: { + id: { ...text('id'), primaryKey: true }, name: text('name'), + acct: { name: 'acct', type: 'master_detail', reference: 'acct' }, + }, + } as any, '__test__'); + engine.registry.registerObject({ + name: 'line_note', label: 'line_note', + fields: { + id: { ...text('id'), primaryKey: true }, body: text('body'), + line: { name: 'line', type: 'master_detail', reference: 'line' }, + }, + } as any, '__test__'); + engine.registry.registerObject({ + name: 'memo', label: 'memo', + fields: { + id: { ...text('id'), primaryKey: true }, body: text('body'), + acct: { name: 'acct', type: 'master_detail', reference: 'acct' }, + }, + } as any, '__test__'); + await engine.insert('acct', { id: 'a1', name: 'A' }); + const count = opts.lines ?? 3; + for (let i = 1; i <= count; i++) await engine.insert('line', { id: `l${i}`, name: `L${i}`, acct: 'a1' }); + driver.writes.length = 0; + return { engine, driver }; +} + +type Seen = { + object: string; event: string; id: unknown; mode: unknown; index: unknown; multi: unknown; + marker: unknown; previousId: unknown; +}; +function listen(engine: ObjectQL, seen: Seen[], object: string, events = ['beforeDelete', 'afterDelete']) { + for (const event of events) { + engine.on(event, object, (ctx: any) => { + seen.push({ + object: ctx.object, event: ctx.event, id: ctx.input?.id, + mode: ctx.dispatch?.mode, index: ctx.dispatch?.index, + multi: ctx.input?.options?.multi, + marker: ctx.referentialCascadeDelete, + previousId: ctx.previous?.id, + }); + }); + } +} + +const ids = (rows: Row[]) => rows.map((r) => r.id).sort(); +const CALLER = { userId: 'u1', isSystem: true }; + +describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', () => { + it('runs every child\'s beforeDelete, then ONE set delete, then the afterDeletes, on the per-row shape, all marked', async () => { + const { engine, driver } = await makeEngine(); + const seen: Seen[] = []; + listen(engine, seen, 'line'); + const order: string[] = []; + engine.on('beforeDelete', 'line', (ctx: any) => { order.push(`before ${ctx.input.id} writes=${driver.writes.length}`); }); + engine.on('afterDelete', 'line', (ctx: any) => { order.push(`after ${ctx.input.id} writes=${driver.writes.length}`); }); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + + // Every before ran with nothing written; ONE set delete; then every after. + expect(order).toEqual([ + 'before l1 writes=0', 'before l2 writes=0', 'before l3 writes=0', + 'after l1 writes=1', 'after l2 writes=1', 'after l3 writes=1', + ]); + expect(driver.writes).toEqual(['deleteMany line l1,l2,l3', 'delete acct a1']); + + expect(seen.map((s) => `${s.event} ${String(s.id)}`)).toEqual([ + 'beforeDelete l1', 'beforeDelete l2', 'beforeDelete l3', + 'afterDelete l1', 'afterDelete l2', 'afterDelete l3', + ]); + for (const s of seen) { + expect(s.mode, 'a cascaded child is one of N dispatches of one write').toBe('per-row'); + expect(s.multi, 'and its options say so').toBe(true); + expect(s.marker, 'the declared cascade marker on every per-row context').toBe(true); + expect(s.previousId, 'previous is the child\'s own row').toBe(s.id); + } + expect(seen.filter((s) => s.event === 'beforeDelete').map((s) => s.index)).toEqual([0, 1, 2]); + expect(seen.filter((s) => s.event === 'afterDelete').map((s) => s.index)).toEqual([0, 1, 2]); + expect(ids(driver.rowsOf('line'))).toEqual([]); + expect(ids(driver.rowsOf('acct'))).toEqual([]); + }); + + it('dispatch.scope is one object for every child of the chunk, both phases; each phase is a fresh context', async () => { + const probe = async (deleteMany: boolean) => { + const { engine } = await makeEngine({ deleteMany }); + const scopes: Array<{ event: string; id: string; scope: unknown; stashed: unknown; keyed: unknown }> = []; + engine.on('beforeDelete', 'line', (ctx: any) => { + ctx.stashedOnCtx = ctx.input.id; + ctx.dispatch.scope[`seen:${String(ctx.input.id)}`] = 'before'; + scopes.push({ event: 'before', id: String(ctx.input.id), scope: ctx.dispatch.scope, stashed: undefined, keyed: undefined }); + }); + engine.on('afterDelete', 'line', (ctx: any) => { + scopes.push({ + event: 'after', id: String(ctx.input.id), scope: ctx.dispatch.scope, + stashed: ctx.stashedOnCtx, keyed: ctx.dispatch.scope[`seen:${String(ctx.input.id)}`], + }); + }); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + return scopes; + }; + + // Batched: ONE scope object across the chunk's six dispatches; a value + // left on ctx in beforeDelete does not reach that child's afterDelete, + // and the remedy (keep it in dispatch.scope keyed by input.id) does. + const batched = await probe(true); + expect(batched).toHaveLength(6); + expect(new Set(batched.map((s) => s.scope)).size).toBe(1); + for (const s of batched.filter((x) => x.event === 'after')) { + expect(s.stashed, `${s.id}: a ctx stash does not cross phases on a per-row dispatch`).toBeUndefined(); + expect(s.keyed, `${s.id}: dispatch.scope keyed by input.id does`).toBe('before'); + } + + // Control, today's by-id shape: one scope per child, the same context in + // both phases, so the ctx stash arrives. + const byId = await probe(false); + expect(new Set(byId.map((s) => s.scope)).size).toBe(3); + for (const s of byId.filter((x) => x.event === 'after')) { + expect(s.stashed).toBe(s.id); + expect(s.scope).toBe(byId.find((x) => x.event === 'before' && x.id === s.id)!.scope); + } + }); + + it('a before-delete hook counting remaining siblings now sees them all present', async () => { + const { engine } = await makeEngine(); + const remaining: number[] = []; + engine.on('beforeDelete', 'line', async () => { + remaining.push((await engine.find('line', { where: { acct: 'a1' } })).length); + }); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + // The per-child walk saw 3, 2, 1: the one real behaviour flip the ruling names. + expect(remaining).toEqual([3, 3, 3]); + }); + + it('grandchildren are batched too, inside the child batch\'s own walk, and marked', async () => { + const { engine, driver } = await makeEngine(); + await engine.insert('line_note', { id: 'n1', body: 'x', line: 'l1' }); + await engine.insert('line_note', { id: 'n2', body: 'y', line: 'l2' }); + driver.writes.length = 0; + const seen: Seen[] = []; + listen(engine, seen, 'line_note'); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + + expect(driver.writes).toEqual(['deleteMany line_note n1,n2', 'deleteMany line l1,l2,l3', 'delete acct a1']); + expect(seen.map((s) => `${s.event} ${String(s.id)} ${String(s.mode)} ${String(s.marker)}`)).toEqual([ + 'beforeDelete n1 per-row true', 'beforeDelete n2 per-row true', + 'afterDelete n1 per-row true', 'afterDelete n2 per-row true', + ]); + }); + + it('chunks of 500: 501 children are two set deletes', async () => { + const { engine, driver } = await makeEngine({ lines: 501 }); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + const sets = driver.writes.filter((w: string) => w.startsWith('deleteMany line')); + expect(sets.map((w: string) => w.split(' ')[2].split(',').length)).toEqual([500, 1]); + expect(driver.rowsOf('line')).toEqual([]); + }); + + it('realtime keeps one data.record.deleted per child, never the bulk event', async () => { + const { engine } = await makeEngine(); + const published: RealtimeEventPayload[] = []; + const realtime: IRealtimeService = { + publish: vi.fn(async (event: RealtimeEventPayload) => { published.push(event); }), + subscribe: vi.fn(async () => 'sub-1'), + unsubscribe: vi.fn(async () => undefined), + } as any; + engine.setRealtimeService(realtime); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + + const lines = published.filter((e) => e.object === 'line'); + expect(lines.map((e) => e.type)).toEqual(['data.record.deleted', 'data.record.deleted', 'data.record.deleted']); + expect(lines.map((e) => (e.payload as any).recordId)).toEqual(['l1', 'l2', 'l3']); + expect(published.some((e) => e.type === 'data.records.deleted')).toBe(false); + }); + + it('a refusal in the batch\'s before phase rolls the whole cascade back, the caller meets it unchanged', async () => { + const { engine, driver } = await makeEngine(); + engine.on('beforeDelete', 'line', (ctx: any) => { + if (ctx.input.id === 'l2') throw Object.assign(new Error('l2 is frozen'), { code: 'PERMISSION_DENIED', status: 403 }); + }); + const err: any = await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }).then(() => null, (e: unknown) => e); + expect(err?.code).toBe('PERMISSION_DENIED'); + expect(err?.status).toBe(403); + expect(driver.writes).toEqual([]); + expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2', 'l3']); + expect(ids(driver.rowsOf('acct'))).toEqual(['a1']); + }); + + it('a refusal in the batch\'s after phase rolls the set delete back too', async () => { + const { engine, driver } = await makeEngine(); + engine.on('afterDelete', 'line', (ctx: any) => { + if (ctx.input.id === 'l3') throw Object.assign(new Error('l3 refused after'), { code: 'PERMISSION_DENIED', status: 403 }); + }); + const err: any = await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }).then(() => null, (e: unknown) => e); + expect(err?.code).toBe('PERMISSION_DENIED'); + expect(err?.status).toBe(403); + expect(driver.rolledBack.length).toBeGreaterThan(0); + expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2', 'l3']); + expect(ids(driver.rowsOf('acct'))).toEqual(['a1']); + }); +}); + +/** + * A scope that NARROWS a predicate delete and REFUSES the by-id delete of the + * same row, the shape the sharing middleware gives an out-of-scope row. + */ +function narrowAndRefuse(engine: ObjectQL, object: string, hidden: string) { + const byIdAttempts: unknown[] = []; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.operation === 'delete' && opCtx.object === object) { + const id = opCtx.options?.where?.id; + if (id === hidden) { + byIdAttempts.push(id); + throw Object.assign(new Error(`no delete access to ${object}/${hidden}`), { code: 'PERMISSION_DENIED', status: 403 }); + } + if (opCtx.ast && (id === undefined || typeof id === 'object')) { + opCtx.ast = { ...opCtx.ast, where: { $and: [opCtx.ast.where ?? {}, { id: { $nin: [hidden] } }] } }; + } + } + await next(); + }); + return byIdAttempts; +} + +describe('[F1] a chunk the caller\'s scope narrows falls back to today\'s by-id deletes', () => { + it('today\'s refusal envelope, nothing deleted, and no batch hook ran before the by-id walk', async () => { + const { engine, driver } = await makeEngine(); + const seen: Seen[] = []; + listen(engine, seen, 'line'); + const byIdAttempts = narrowAndRefuse(engine, 'line', 'l2'); + + const err: any = await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }).then(() => null, (e: unknown) => e); + + expect(err?.code).toBe('PERMISSION_DENIED'); + expect(err?.status).toBe(403); + expect(byIdAttempts).toEqual(['l2']); + // Only by-id dispatches ran: the batch was handed back before its hooks. + expect(seen.map((s) => `${s.event} ${String(s.id)} ${String(s.mode)}`)).toEqual([ + 'beforeDelete l1 record', 'afterDelete l1 record', + ]); + expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2', 'l3']); + expect(ids(driver.rowsOf('acct'))).toEqual(['a1']); + }); + + it('a fallback that is allowed keeps today\'s shape, and one cascade shows both shapes', async () => { + const { engine, driver } = await makeEngine(); + await engine.insert('memo', { id: 'm1', body: 'a', acct: 'a1' }); + await engine.insert('memo', { id: 'm2', body: 'b', acct: 'a1' }); + driver.writes.length = 0; + // Narrowed for the predicate, ALLOWED by id: the memos fall back. + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.operation === 'delete' && opCtx.object === 'memo' && opCtx.ast) { + opCtx.ast = { ...opCtx.ast, where: { $and: [opCtx.ast.where ?? {}, { id: { $nin: ['m2'] } }] } }; + } + await next(); + }); + const seen: Seen[] = []; + listen(engine, seen, 'line', ['beforeDelete']); + listen(engine, seen, 'memo', ['beforeDelete']); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + + const shapes = seen.map((s) => `${s.object} ${String(s.id)} ${String(s.mode)} multi=${String(s.multi)} marker=${String(s.marker)}`); + expect(shapes.filter((s) => s.startsWith('line'))).toEqual([ + 'line l1 per-row multi=true marker=true', 'line l2 per-row multi=true marker=true', 'line l3 per-row multi=true marker=true', + ]); + expect(shapes.filter((s) => s.startsWith('memo'))).toEqual([ + 'memo m1 record multi=undefined marker=true', 'memo m2 record multi=undefined marker=true', + ]); + expect(driver.writes.filter((w: string) => w.includes('memo'))).toEqual(['delete memo m1', 'delete memo m2']); + expect(driver.rowsOf('memo')).toEqual([]); + }); + + it('a driver with no deleteMany keeps the by-id path', async () => { + const { engine, driver } = await makeEngine({ deleteMany: false }); + const seen: Seen[] = []; + listen(engine, seen, 'line', ['beforeDelete']); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + expect(seen.map((s) => s.mode)).toEqual(['record', 'record', 'record']); + expect(driver.writes).toEqual(['delete line l1', 'delete line l2', 'delete line l3', 'delete acct a1']); + }); +}); + +/** + * A scope that hides a row from the caller's READ door and refuses the by-id + * delete of it, the shape plugin-security's step 2.7 gives a child a + * select-class policy hides (its re-read through the read door comes back + * empty). The write scope of a nested predicate delete does not carry the read + * scope, so the walk asks the read door before it batches. + */ +function hideFromReadsAndRefuse(engine: ObjectQL, object: string, hidden: string, refuseById: boolean) { + const byIdAttempts: unknown[] = []; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object === object && !opCtx.context?.isSystem) { + if (opCtx.operation === 'find' && opCtx.ast) { + opCtx.ast = { ...opCtx.ast, where: { $and: [opCtx.ast.where ?? {}, { id: { $nin: [hidden] } }] } }; + } + if (opCtx.operation === 'delete' && opCtx.options?.where?.id === hidden) { + byIdAttempts.push(hidden); + if (refuseById) { + throw Object.assign(new Error(`no access to ${object}/${hidden}`), { code: 'PERMISSION_DENIED', status: 403 }); + } + } + } + await next(); + }); + return byIdAttempts; +} + +const MEMBER = { userId: 'u1' }; + +describe('[F1] a chunk the caller\'s READ door narrows falls back to today\'s by-id deletes', () => { + it('a child the read door hides and the by-id delete refuses: today\'s 403, nothing deleted, no batch hook ran', async () => { + const { engine, driver } = await makeEngine(); + const seen: Seen[] = []; + listen(engine, seen, 'line'); + const byIdAttempts = hideFromReadsAndRefuse(engine, 'line', 'l2', true); + + const err: any = await engine.delete('acct', { where: { id: 'a1' }, context: { ...MEMBER } }).then(() => null, (e: unknown) => e); + + expect(err?.code).toBe('PERMISSION_DENIED'); + expect(err?.status).toBe(403); + expect(byIdAttempts).toEqual(['l2']); + expect(seen.map((s) => `${s.event} ${String(s.id)} ${String(s.mode)}`)).toEqual([ + 'beforeDelete l1 record', 'afterDelete l1 record', + ]); + expect(driver.writes.some((w: string) => w.startsWith('deleteMany'))).toBe(false); + expect(ids(driver.rowsOf('line'))).toEqual(['l1', 'l2', 'l3']); + expect(ids(driver.rowsOf('acct'))).toEqual(['a1']); + }); + + it('a child the read door hides and the by-id delete allows: deleted by id, today\'s shape', async () => { + const { engine, driver } = await makeEngine(); + const seen: Seen[] = []; + listen(engine, seen, 'line', ['beforeDelete']); + hideFromReadsAndRefuse(engine, 'line', 'l2', false); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...MEMBER } }); + + expect(seen.map((s) => `${String(s.id)} ${String(s.mode)}`)).toEqual(['l1 record', 'l2 record', 'l3 record']); + expect(driver.writes).toEqual(['delete line l1', 'delete line l2', 'delete line l3', 'delete acct a1']); + }); + + it('every child the read door returns: batched (control)', async () => { + const { engine, driver } = await makeEngine(); + hideFromReadsAndRefuse(engine, 'line', 'l_nowhere', true); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...MEMBER } }); + expect(driver.writes).toEqual(['deleteMany line l1,l2,l3', 'delete acct a1']); + }); +}); + +describe('[F1] a cascade into the organization object keeps today\'s by-id deletes', () => { + it('an organization cascaded from its parent is deleted by id, not refused as a predicate delete', async () => { + const { engine, driver } = await makeEngine(); + engine.registry.registerObject({ + name: 'sys_organization', label: 'Organization', + fields: { + id: { ...text('id'), primaryKey: true }, name: text('name'), + holder: { name: 'holder', type: 'lookup', reference: 'acct', deleteBehavior: 'cascade' }, + }, + } as any, '__test__'); + await driver.create('sys_organization', { id: 'o1', name: 'O1', holder: 'a1' }); + driver.writes.length = 0; + const seen: Seen[] = []; + listen(engine, seen, 'sys_organization', ['beforeDelete']); + + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); + + expect(seen.map((s) => `${String(s.id)} ${String(s.mode)} marker=${String(s.marker)}`)).toEqual(['o1 record marker=true']); + expect(driver.writes).toContain('delete sys_organization o1'); + expect(driver.writes.some((w: string) => w.startsWith('deleteMany sys_organization'))).toBe(false); + expect(driver.rowsOf('sys_organization')).toEqual([]); + }); +}); diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 9c00176f6f6..daa43fc8aaf 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -47,11 +47,14 @@ import type { ServiceObject } from '@objectstack/spec/data'; import { SystemFieldName } from '@objectstack/spec/system'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { isMissingTableError } from '@objectstack/metadata/errors'; +import { declaredHttpStatus } from '@objectstack/types'; import { ORGANIZATION_OBJECT, resolveTenantFieldName } from './tenancy/system-write-organization.js'; import { isFederatedUnprovisionedInjectedColumn } from './federated-object.js'; import { - cascadeMemberKey, cascadeSetAdd, cascadeSetHas, declaredMultiValued, deleteWalkTargetOf, statesDeleteSemantics, + CascadeBatchNarrowed, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, declaredMultiValued, deleteWalkTargetOf, + statesDeleteSemantics, } from './engine-top-level.js'; +import { isExternalDriverFloor } from './external-driver-floor.js'; import type { CascadeDeleteSet } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { ObjectQL as ObjectQLClass } from './engine.js'; @@ -856,7 +859,7 @@ export class CascadePlanningFacet { * a `restrict` and a `set_null` consider only rows OUTSIDE it, and a row the * walk has already entered is not cascaded into again. */ - static async walkReferencingRelations(this: Pick, object: string, ids: ReadonlyArray, context: ExecutionContext | undefined, objects: ServiceObject[], cascadeSet: CascadeDeleteSet): Promise { + static async walkReferencingRelations(this: Pick, object: string, ids: ReadonlyArray, context: ExecutionContext | undefined, objects: ServiceObject[], cascadeSet: CascadeDeleteSet): Promise { // Entered before the first nested `delete()` can come back here: every // record of the set, so one member's cascade never deletes another. for (const id of ids) cascadeSetAdd(cascadeSet.entered, object, id); @@ -994,6 +997,11 @@ export class CascadePlanningFacet { const clearedKey = cascadeMemberKey(childName, fieldName); let cleared = cascadeSet.cleared.get(clearedKey); if (!cleared) { cleared = new Set(); cascadeSet.cleared.set(clearedKey, cleared); } + // [ruling 6893661036, F1] The `cascade` dependents of this relation, + // across every record of the set, in the walk's order: deleted after + // the loop, a chunk at a time ({@link deleteCascadedChildren}). + const cascaded: Array = []; + const cascadedSeen = new Set(); for (const id of ids) { let behavior: string = relationBehavior; let dependents = referencing.get(String(id)) ?? []; @@ -1092,23 +1100,11 @@ export class CascadePlanningFacet { // Either way this cascade removes it once, and re-entering would // loop forever on the first and answer 404 on the second. if (cascadeSetHas(cascadeSet.entered, childName, depId)) continue; - // Recurse via the public delete so the child's own cascade, - // hooks and events fire. - // - // [#23221] Inside a token naming exactly this child, which that - // delete claims and projects onto the DECLARED - // `HookContext.referentialCascadeDelete` (see - // claimReferentialCascadeDelete): on the real request path the - // caller's context reaches the child unchanged, so without it a - // freeze guard cannot tell this delete from a hand delete of the - // same row. The context is passed as before, by reference and - // unmarked — see `cascadeIssuedDeletes` for why the marker is not - // a context key. A grandchild is issued by the child's own walk, - // inside a token of its own. - await this.cascadeIssuedDeletes.run( - { object: childName, id: String(depId), claimed: false }, - () => this.delete(childName, { where: { id: depId }, context } as any), - ); + // [ruling 6893661036, F1] Collected, not deleted here: the + // relation's dependents go after this loop, a chunk at a time. + if (cascadedSeen.has(String(depId))) continue; + cascadedSeen.add(String(depId)); + cascaded.push(depId); } else { // [#3023] Clear the FK as an engine-internal referential-integrity // write, tagged so plugin-security's ownership-anchor guard (#3004) @@ -1182,6 +1178,7 @@ export class CascadePlanningFacet { // [#27004] Every row outside the set has had `id` cleared from it. cleared.add(String(id)); } + if (cascaded.length > 0) await deleteCascadedChildren(this, childName, cascaded, context, cascadeSet); } } } @@ -1405,3 +1402,121 @@ export class CascadePlanningFacet { return counts; } } + +/** + * [ruling 6893661036, option F1] Delete the `cascade` dependents of one + * relation: one predicate delete per {@link REFERENCE_PROBE_BATCH} children, + * `where: { id: { $in: chunk } }` with `multi: true`, through the public + * `delete()`. So the chunk runs every child's `beforeDelete`, then ONE set + * delete, then the `afterDelete`s, each context on the per-row shape a + * predicate delete has always had (ADR-0058 Addendum II): `dispatch.mode` + * `'per-row'`, `input.options.multi` set, `previous` the child's own row. + * Before this, every child was its own by-id delete (`dispatch.mode` + * `'record'`), its hooks interleaved with its siblings' deletes. + * + * Inside a token naming exactly the chunk's ids, which that delete claims + * and projects onto the DECLARED `HookContext.referentialCascadeDelete` + * (see claimReferentialCascadeDelete), so every per-row context carries the + * marker, as every by-id child delete did [#23221]. The context is passed + * by reference and unmarked; a grandchild is issued by the chunk's own walk + * (the predicate arm's `cascadeDeleteRelations`, joining this set), inside a + * token of its own. + * + * A chunk keeps today's by-id deletes, one per child, inside a by-id token + * each, when: + * - the child's driver has no `deleteMany` (or is a floored external + * driver, which refuses a predicate write): the in-process path it has; + * - the child object is the organization object, which is deleted by id or + * not at all (`organizationPredicateDeleteRefusal`): its by-id delete is + * where the per-organization clean-up runs; + * - the caller's READ door does not return every child of the chunk + * ({@link readDoorReturnsChunk}): a by-id delete re-reads its row through + * the read door (plugin-security step 2.7), so a child the caller cannot + * read refuses there, where a nested predicate delete, scoped by the + * write-class policies alone, would delete it; + * - the batch's caller-scoped WRITE read misses a child it was asked for + * (`CascadeBatchNarrowed`, thrown before any hook or write): a by-id + * delete of that child refuses where a predicate one would skip it. + * And a dependent the collect phase never held (not in `cascadeSet.members`) + * always goes by id, whatever its chunk does: it is the root of its own + * cascade, with its own recycle-bin entry, as before. + * In each case the by-id path gives today's answer, and a refusal rolls the + * whole cascade back (ruling 6893104201 point 2). So one cascade can show + * both shapes. + */ +async function deleteCascadedChildren(host: Pick, childName: string, dependents: ReadonlyArray, context: ExecutionContext | undefined, cascadeSet: CascadeDeleteSet): Promise { + const driver = host.getDriver(childName) as { deleteMany?: unknown }; + const batchable = typeof driver?.deleteMany === 'function' && !isExternalDriverFloor(driver as any) && + childName !== ORGANIZATION_OBJECT; + const batchSize = ObjectQL.REFERENCE_PROBE_BATCH; + for (let i = 0; i < dependents.length; i += batchSize) { + // [#22305] An earlier chunk's own cascade may have entered a member. + const chunk = dependents.slice(i, i + batchSize).filter((depId) => !cascadeSetHas(cascadeSet.entered, childName, depId)); + if (chunk.length === 0) continue; + // Only the set's collected MEMBERS are batched. A dependent the probe + // found that the collect phase never held (a row a hook of this cascade + // wrote after the set was collected) is deleted by id below, as the root + // of its own cascade, so it keeps its own recycle-bin entry: a predicate + // delete opens none, and the root's entry snapshotted only the members. + const members = chunk.filter((depId) => cascadeSetHas(cascadeSet.members, childName, depId)); + if (batchable && members.length > 0 && await readDoorReturnsChunk(host, childName, members, context)) { + try { + await host.cascadeIssuedDeletes.run( + { object: childName, ids: new Set(members.map((depId) => String(depId))), claimed: false }, + () => host.delete(childName, { where: { id: { $in: members } }, multi: true, context } as any), + ); + // The predicate arm walks a child's own relations only when one + // points at it; entered either way, so a second path to the same row + // never deletes it again. + for (const depId of members) cascadeSetAdd(cascadeSet.entered, childName, depId); + } catch (e) { + if (!(e instanceof CascadeBatchNarrowed)) throw e; + } + } + for (const depId of chunk) { + if (cascadeSetHas(cascadeSet.entered, childName, depId)) continue; + // Recurse via the public delete so the child's own cascade, hooks and + // events fire, inside a token naming exactly this child [#23221]. + await host.cascadeIssuedDeletes.run( + { object: childName, id: String(depId), claimed: false }, + () => host.delete(childName, { where: { id: depId }, context } as any), + ); + } + } +} + +/** + * [ruling 6893104201 point 2] Does the caller's READ door return every child + * of the chunk? Asked through the public `find()` under the walk's context, + * so select-class row-level security, the sharing read filter and every data + * middleware's read visibility compose onto it, as they compose onto the + * by-id child delete's own re-read of its row (plugin-security step 2.7). A + * cascade batch is a nested write, and the security plugin composes the read + * scope onto an addressed predicate write only, so without this question a + * child the caller cannot read, admitted by a delete-class policy, would be + * deleted where the by-id delete refuses it. + * + * `false` hands the chunk to the by-id path, which gives today's answer in + * every case: it refuses a hidden child, and deletes one no write-class row + * filter binds. A read the door REFUSES (a declared 4xx) is answered `false` + * for the same reason: the by-id path asks its own question and answers it. + * A store fault propagates as raised: an outage is not a hidden row. + */ +async function readDoorReturnsChunk(host: Pick, childName: string, chunk: ReadonlyArray, context: ExecutionContext | undefined): Promise { + let rows: unknown; + try { + rows = await host.find(childName, { where: { id: { $in: [...chunk] } }, fields: ['id'], context }); + } catch (e) { + const status = declaredHttpStatus(e); + if (status === undefined || status >= 500) throw e; + // Not a hidden answer: the refusal routes the chunk to the by-id path, + // which asks the read door again per child and answers the caller. + host.logger.debug( + `[cascade] the read door refused the caller on '${childName}'; deleting this chunk of the cascade by id`, + { object: childName, status, error: (e as Error)?.message ?? String(e) }, + ); + return false; + } + const found = new Set((Array.isArray(rows) ? rows : []).map((row: any) => String(row?.id))); + return chunk.every((depId) => found.has(String(depId))); +} diff --git a/packages/objectql/src/engine-cascade-summary-rollback.test.ts b/packages/objectql/src/engine-cascade-summary-rollback.test.ts index 5de001abb3d..53beb9ba63f 100644 --- a/packages/objectql/src/engine-cascade-summary-rollback.test.ts +++ b/packages/objectql/src/engine-cascade-summary-rollback.test.ts @@ -161,8 +161,12 @@ describe('a cascade dependent\'s ERR_SUMMARY_RECOMPUTE never answers for a paren expect(err.status).toBe(500); expect(err.cause?.code).toBe('ERR_SUMMARY_RECOMPUTE'); expect(ids(driver.rowsOf('acct'))).toEqual(['a1']); - // The dependent the walk reached first is gone: nothing can roll it back. - expect(ids(driver.rowsOf('line'))).toEqual(['l2']); + // The dependents the walk deleted are gone: nothing can roll them back. + // [ruling 6893661036, F1] The walk deletes a relation's dependents as ONE + // batch (one set delete, then the per-row after phase and the roll-up + // recompute), so the refusal arrives after the whole batch is removed, + // where the per-child walk stopped after the first child. + expect(ids(driver.rowsOf('line'))).toEqual([]); }); it('a predicate delete (multi) on a runtime that cannot roll back: refused the same way, the parent still stored', async () => { diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 2acaaae8813..6ea0f870fa0 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -75,7 +75,7 @@ import type { EngineDeleteDispatchInput } from './engine-delete-dispatch.js'; import { ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_DELETE_OPTION_KEYS, ENGINE_WHERE_SLOTS, declaredDatetimeLowering, describeNonFilterWhere, foldEngineOptionAliases, isWhereFilterObject, lowerWhereFilterArray, mergeReadContext, - organizationPredicateDeleteRefusal, rejectUnknownEngineOptions, resolveThenLowerWhere, whereResolvedTokenJudge, + CascadeBatchNarrowed, cascadeBatchIdsOf, organizationPredicateDeleteRefusal, rejectUnknownEngineOptions, resolveThenLowerWhere, whereResolvedTokenJudge, writeFailureLogMeta, } from './engine-top-level.js'; import type { EngineReadOptions, OperationContext } from './engine-top-level.js'; @@ -192,7 +192,9 @@ export class DeleteAndAggregateFacet { const permanent = readPermanentDelete(object, options, dispatch.kind); // [#23221] Is this the child delete a cascade issued? Decided here, once, // before any middleware or hook runs, so the claim is this call's alone. - const referentialCascadeDelete = this.claimReferentialCascadeDelete(object, id); + // [ruling 6893661036, F1] A predicate delete hands its `where` instead: a + // cascade batch is claimed by the exact id set it names. + const referentialCascadeDelete = this.claimReferentialCascadeDelete(object, id ?? options?.where); const opCtx: OperationContext = { object, @@ -532,7 +534,11 @@ export class DeleteAndAggregateFacet { // bulk delete with none pays for no read. const perRowBeforeHooks = this.hasHooksFor('beforeDelete', object); const perRowAfterHooks = this.hasHooksFor('afterDelete', object); - if (perRowBeforeHooks || perRowAfterHooks) { + // [ruling 6893661036, F1] A cascade batch (the walk's one predicate + // delete per chunk of children, claimed above) always reads its doomed + // rows: they are its scope check and its per-row realtime events. + const cascadeBatch = referentialCascadeDelete === true; + if (perRowBeforeHooks || perRowAfterHooks || cascadeBatch) { const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); // [#21613] Each doomed row is its per-row `previous`: declared set. const doomed = rowsWithDeclaredColumnsOnly( @@ -540,11 +546,29 @@ export class DeleteAndAggregateFacet { declaredDeleteColumns, ); predicateMatchedRows = doomed; + // [ruling 6893104201 point (2)] The read ran through the AST the + // middleware chain composed for this delete, so it is the caller's + // WRITE scope (the delete-class row filters). The READ scope is not + // on it: the security plugin composes that onto an addressed + // predicate write only, never a nested one, so the walk asked the + // read door for the chunk before issuing it (`readDoorReturnsChunk`). + // A child the walk asked for and this read did not return is one a + // by-id delete would REFUSE (403) where this predicate would skip it: + // before any hook and any write, hand the chunk back to the walk, + // which deletes it by id, so the refusal and the rollback are today's. + if (cascadeBatch) { + const found = new Set(doomed.map((row) => String(row?.id))); + if (!(cascadeBatchIdsOf(options?.where) ?? []).every((v) => found.has(v))) { + throw new CascadeBatchNarrowed(object); + } + } // [D6] One ceiling, both phases, BEFORE the first per-row dispatch // and before the driver call. - this.assertBulkPerRowHookBudget( - object, perRowBeforeHooks ? 'beforeDelete' : 'afterDelete', doomed.length, - ); + if (perRowBeforeHooks || perRowAfterHooks) { + this.assertBulkPerRowHookBudget( + object, perRowBeforeHooks ? 'beforeDelete' : 'afterDelete', doomed.length, + ); + } if (perRowAfterHooks) bulkPerRowRows = doomed; // [D1] Zero matched rows is zero dispatches. if (perRowBeforeHooks && doomed.length > 0) { @@ -815,7 +839,18 @@ export class DeleteAndAggregateFacet { // or the aggregate `data.records.deleted` when the delete was by // predicate (#4639). if (this.realtimeService) { - if (isPredicateWrite) { + if (isPredicateWrite && referentialCascadeDelete && predicateMatchedRows) { + // [ruling 6893104201 point (1)] A cascade batch keeps today's + // events: one `data.record.deleted` per child, each scoped by its + // own pre-image, read before the statement removed it. + for (const row of predicateMatchedRows) { + await this.publishDataEvent('deleted', object, { + recordId: row.id, + organizationRow: row, + context: opCtx.context, + }); + } + } else if (isPredicateWrite) { await this.publishBulkDataEvent('deleted', object, { matched: result, context: opCtx.context, diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index 9659a4b9886..9f13bff9a1c 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -43,6 +43,7 @@ import { bridgeAuthzInvalidation } from './authz-invalidation-bridge.js'; import { isMissingTableError } from '@objectstack/metadata/errors'; import { ORGANIZATION_OBJECT, SystemWriteOrganizationRequiredError, carriesOrganization, resolveSystemWriteOrganization, resolveTenantFieldName, type SystemWriteOrganizationDecision } from './tenancy/system-write-organization.js'; import { isFederatedObject } from './federated-object.js'; +import { cascadeBatchIdsOf } from './engine-top-level.js'; import type { EngineMiddleware, OperationContext } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; @@ -210,7 +211,17 @@ export class MiddlewareAndContextFacet { static claimReferentialCascadeDelete(this: Pick, object: string, id: unknown): true | undefined { const issued = this.cascadeIssuedDeletes.getStore(); if (!issued || issued.claimed || id == null) return undefined; - if (issued.object !== object || issued.id !== String(id)) return undefined; + if (issued.object !== object) return undefined; + if (issued.ids) { + // [ruling 6893661036, F1 · surface amendment 6893212568] A cascade batch: + // `delete()` hands its predicate here in place of an id, and the token + // matches only the predicate naming EXACTLY its id set, so every per-row + // context of that one delete carries the marker and no other delete does. + const named = cascadeBatchIdsOf(id); + if (!named || named.length !== issued.ids.size || !named.every((v) => issued.ids!.has(v))) return undefined; + } else if (typeof id === 'object' || issued.id !== String(id)) { + return undefined; + } issued.claimed = true; return true; } diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index cce21abf515..705972c2fe2 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4589,14 +4589,18 @@ export function cascadeSetAdd(index: Map>, object: string, i /** * [#23221] The one child delete a cascade walk is issuing, for that delete to * recognise itself by — see {@link ObjectQL.cascadeIssuedDeletes}. The walk - * opens one per `cascade` dependent, around its own `delete()` call, and the - * `delete()` whose object and id match claims it. + * opens one around its own `delete()` call, and the `delete()` whose object + * and target match claims it: a by-id delete by `id`, and a batch of children + * (ruling 6893661036, option F1) by `ids`, the exact set its `where.id.$in` + * names. Exactly one of the two is set. */ interface CascadeIssuedDelete { /** The child object the walk is deleting from, as the registry names it. */ readonly object: string; - /** The child row's id, as a string (the walk's `String(depId)`). */ - readonly id: string; + /** The child row's id, as a string (the walk's `String(depId)`): a by-id child delete. */ + readonly id?: string; + /** The chunk's ids, as strings: a cascade batch, one predicate delete over `where.id.$in`. */ + readonly ids?: ReadonlySet; /** * Set by the `delete()` that recognised itself. One token, one dispatch: a * later delete of the same row inside that call (a hook's own) finds it @@ -4605,6 +4609,39 @@ interface CascadeIssuedDelete { claimed: boolean; } +/** + * [ruling 6893661036, F1] A cascade batch's caller-scoped read did not return + * every child the walk asked it to delete: a row the caller may not delete is + * NARROWED out of a predicate delete, where the by-id delete of the same row + * REFUSES it. Thrown by `delete()` before any hook dispatches and before any + * write, and caught by the walk alone, which then deletes that chunk the by-id + * way, so the caller meets today's refusal and the whole cascade rolls back. + * Never reaches a caller: it is engine-internal and carries no code. + */ +class CascadeBatchNarrowed extends Error { + constructor(object: string) { + super(`cascade batch on '${object}' was narrowed by the caller's scope; deleting that chunk by id`); + this.name = 'CascadeBatchNarrowed'; + } +} + +/** + * [ruling 6893661036, F1] The id set a cascade batch names: `where` is exactly + * `{ id: { $in: [...] } }`, the shape the walk issues, and nothing else. + * `undefined` for any other predicate. + */ +function cascadeBatchIdsOf(where: unknown): string[] | undefined { + if (where === null || typeof where !== 'object' || Array.isArray(where)) return undefined; + const keys = Object.keys(where); + if (keys.length !== 1 || keys[0] !== 'id') return undefined; + const idSpec = (where as { id?: unknown }).id; + if (idSpec === null || typeof idSpec !== 'object' || Array.isArray(idSpec)) return undefined; + const opKeys = Object.keys(idSpec); + if (opKeys.length !== 1 || opKeys[0] !== '$in') return undefined; + const list = (idSpec as { $in?: unknown }).$in; + return Array.isArray(list) ? list.map((v) => String(v)) : undefined; +} + /** * [ADR-0010 §3.7] Stamp a manifest item with its owning package's * `(packageId, packageVersion)` before the registry stores it: the call the @@ -5171,8 +5208,8 @@ const WRITE_PRECONDITION_OPTION: unique symbol = Symbol('objectql.writePrecondit // [#29986 codemod] Declared above without `export`, and read by `engine.ts` or a section module. export { - AUTONUMBER_COLLISION_ATTEMPTS, AUTONUMBER_SEED_PAGE_SIZE, AutonumberReaders, CascadeIssuedDelete, - DISPATCHABLE_HOOK_EVENTS, ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_DELETE_OPTION_KEYS, ENGINE_FIND_OPTION_KEYS, + AUTONUMBER_COLLISION_ATTEMPTS, AUTONUMBER_SEED_PAGE_SIZE, AutonumberReaders, CascadeBatchNarrowed, + CascadeIssuedDelete, DISPATCHABLE_HOOK_EVENTS, cascadeBatchIdsOf, ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_DELETE_OPTION_KEYS, ENGINE_FIND_OPTION_KEYS, ENGINE_QUERY_SLOTS, ENGINE_UPDATE_OPTION_KEYS, ENGINE_WIRE_ONLY_SLOTS, FormulaFaultSink, FormulaRelated, IssuedAutonumber, METADATA_ARRAY_KEYS, ReadableIdsSecurityResolution, StoredExpressionServing, TransactionScope, WIRE_ONLY_CANONICAL_SHAPES, WRITE_PRECONDITION_OPTION, applyFormulaPlan, applyStoredExpressionsToPatch, diff --git a/packages/objectql/src/recycle-bin/capture.test.ts b/packages/objectql/src/recycle-bin/capture.test.ts index 9daee326085..3028d815a8f 100644 --- a/packages/objectql/src/recycle-bin/capture.test.ts +++ b/packages/objectql/src/recycle-bin/capture.test.ts @@ -534,6 +534,35 @@ describe("an organization's delete takes its entries with it (ruling Q4)", () => }); }); +/** + * A `cascade` dependent the walk's probe finds but the collect phase never + * held (a row a hook of this same cascade wrote after the set was collected) + * is no member of the root's entry. It is deleted by id, as the root of its + * own cascade, so it keeps an entry of its own; a cascade batch (one predicate + * delete per chunk, which opens no entry) takes only the collected members. + */ +describe('a cascade dependent written after the set was collected keeps its own entry', () => { + it('is deleted by id with an entry of its own, while the collected members stay rows of the root entry', async () => { + const { engine, driver } = await makeEngine(); + seedAccountTree(driver); + // The contacts are batched; their before phase runs ahead of their own + // walk, which probes the notes: n9 lands between the collect and that probe. + engine.on('beforeDelete', 'contact', (ctx: any) => { + if (ctx.input?.id === 'c1') driver.seed('note', { id: 'n9', body: 'late', contact: 'c1' }); + }); + + await engine.delete('account', { where: { id: 'acc1' }, ...USER } as any); + + expect(driver.rowsOf('note')).toHaveLength(0); + const entries = entriesOf(driver); + expect(entries.map((e) => `${String(e.object_name)}/${String(e.record_id)}`).sort()).toEqual(['account/acc1', 'note/n9']); + const root = entries.find((e) => e.object_name === 'account')!; + expect((root.snapshot as any).rows.map((r: any) => `${r.object}/${r.id}`)).toEqual([ + 'account/acc1', 'contact/c1', 'contact/c2', 'note/n1', + ]); + }); +}); + describe('cascadeMembersInOrder', () => { it('lists the root first, then breadth-first along the cascading edges, then any member no edge reached', () => { const set: CascadeDeleteSet = { diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.test.ts b/packages/plugins/plugin-auth/src/last-admin-guard.test.ts index 751142a9838..5d15e05f734 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.test.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.test.ts @@ -2207,3 +2207,101 @@ describe('[#6084] reverse verification: one unguarded write takes the admins AND expect(await bannedFlag(engine, 'usr_platform')).toBeTruthy(); }); }); + +// --------------------------------------------------------------------------- +// [ruling 6893661036, F1] A cascade deletes a relation's children as ONE +// predicate delete per chunk: every child's `beforeDelete` runs before any +// child row is gone, on the per-row shape (`dispatch.mode: 'per-row'`, +// `options.multi`). The membership half reads `options.multi` and judges the +// whole chunk together, so it reaches the verdict the per-child walk reached. +// Each case runs twice on the same fixture: the batch, and the walk's by-id +// path (the driver's `deleteMany` hidden, which is the walk's own fallback). +// --------------------------------------------------------------------------- + +const grp = { + name: 'test_grp', + label: 'Group', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', type: 'text' as const }, + }, +}; +const sysMemberInGroup = { + ...sysMember, + fields: { + ...sysMember.fields, + grp: { name: 'grp', type: 'master_detail' as const, reference: 'test_grp' }, + }, +}; + +describe('[F1] the membership standing half reaches the same verdict on a batched cascade', () => { + async function bootGrouped(shape: 'batch' | 'by-id'): Promise<{ engine: ObjectQL; modes: unknown[] }> { + const engine = new ObjectQL(); + engines.push(engine); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + // The control leg: no `deleteMany`, so the walk deletes each child by id. + if (shape === 'by-id') (driver as unknown as { deleteMany?: unknown }).deleteMany = undefined; + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [sysUser, sysMemberInGroup, grp, sysOrganization, sysPermissionSet, sysUserPermissionSet, sysAccount, sysMetadataActivation]) { + engine.registry.registerObject(o as never); + } + await engine.syncSchemas(); + await engine.insert('sys_organization', { id: DEFAULT_ORG, name: 'Default Organization', slug: 'default' }, SYSTEM); + const names = new Set(); + catalogs.set(engine, names); + const catalog = () => ({ permissions: [...names].map((name) => ({ name })) }); + bindTestSecurityCatalog(engine, catalog); + registerLastAdminGuard(engine as unknown as LastAdminGuardEngine, { packageId: 'test.last-admin-guard' }); + const modes: unknown[] = []; + engine.registerHook('beforeDelete', (ctx: any) => { modes.push(ctx.dispatch?.mode); }, { + object: 'sys_member', priority: 1, packageId: 'test.shape-probe', + }); + await seedAdminPermissionSet(engine); + return { engine, modes }; + } + + async function join(engine: ObjectQL, userId: string, group: string): Promise { + await engine.insert('test_grp', { id: group, name: group }, SYSTEM).catch(() => undefined); + await engine.update('sys_member', { id: `mem_${userId}`, grp: group }, SYSTEM); + } + + for (const shape of ['batch', 'by-id'] as const) { + it(`[${shape}] a group whose cascade removes BOTH administrative memberships is refused, and nothing is deleted`, async () => { + const { engine, modes } = await bootGrouped(shape); + await seedUser(engine, 'usr_owner', { role: 'owner' }); + await seedUser(engine, 'usr_admin', { role: 'admin' }); + await join(engine, 'usr_owner', 'g1'); + await join(engine, 'usr_admin', 'g1'); + + await expect(engine.delete('test_grp', { where: { id: 'g1' }, ...SYSTEM })).rejects.toMatchObject({ + code: 'PERMISSION_DENIED', + status: 403, + object: 'sys_member', + }); + expect(await rowExists(engine, 'sys_member', 'mem_usr_owner')).toBe(true); + expect(await rowExists(engine, 'sys_member', 'mem_usr_admin')).toBe(true); + expect(await rowExists(engine, 'test_grp', 'g1')).toBe(true); + // The shape this leg really ran: the batch is refused at its first + // per-row dispatch, judging the whole chunk before any delete; the by-id + // walk deletes the first membership and is refused at the second. + expect(modes).toEqual(shape === 'batch' ? ['per-row'] : ['record', 'record']); + }); + + it(`[${shape}] a group whose cascade spares another administrator is allowed`, async () => { + const { engine, modes } = await bootGrouped(shape); + await seedUser(engine, 'usr_owner', { role: 'owner' }); + await seedUser(engine, 'usr_member', { role: 'member' }); + await seedUser(engine, 'usr_admin', { role: 'admin' }); + await join(engine, 'usr_owner', 'g1'); + await join(engine, 'usr_member', 'g1'); + await join(engine, 'usr_admin', 'g2'); + + await expect(engine.delete('test_grp', { where: { id: 'g1' }, ...SYSTEM })).resolves.toBeDefined(); + expect(await rowExists(engine, 'sys_member', 'mem_usr_owner')).toBe(false); + expect(await rowExists(engine, 'sys_member', 'mem_usr_member')).toBe(false); + expect(await rowExists(engine, 'sys_member', 'mem_usr_admin')).toBe(true); + expect(modes).toEqual(shape === 'batch' ? ['per-row', 'per-row'] : ['record', 'record']); + }); + } +}); diff --git a/packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts b/packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts new file mode 100644 index 00000000000..a82990adcc7 --- /dev/null +++ b/packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts @@ -0,0 +1,207 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A cascade's batched child delete admits only the children the by-id child + * delete admits: the READ scope included (ruling 6893104201 point 2, kept by + * 6893661036: a refused child rolls the whole cascade back). + * + * Measured through a real `ObjectQL` over a real SQL driver, with the real + * `SecurityPlugin` middleware in front of it. Each case runs on two legs of + * one fixture: + * + * - `batch`: the walk deletes a relation's children as one predicate delete + * per chunk (option F1); + * - `by-id`: the driver's `deleteMany` hidden, so the walk deletes each child + * by id, the path every cascade took before F1. + * + * ## The rig + * + * A child object where record sharing abstains (a `public_read_write` model, + * no `owner_id`), cascading from its parent. Its row-level policies: a + * select-class `using` that shows a caller only the rows it owns, and a + * delete-class `using` that admits every row of team `ops`. So a child owned by + * someone else on team `ops` satisfies the delete policy and is hidden by the + * select policy. + * + * By id (step 2.7), that child is re-read through the read door with the + * delete predicate ANDed on, comes back empty, and the delete answers 403: the + * parent's delete is refused and nothing is deleted. A predicate delete issued + * by the cascade is a nested write, so the read door's scope is not composed + * onto it (`addressedPredicateWrite` answers false); with a delete-class + * policy present, its write scope is that policy alone. The batch therefore + * asks the caller's read door for the chunk's ids first, and deletes the + * chunk by id when any is missing: today's answer, on both legs. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { PermissionSetSchema } from '@objectstack/spec/security'; + +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; +const PACKAGE = 'com.objectstack.qa.cascade-batch-read-scope'; + +const PARENT = 'qa_cbr_parent'; +const CHILD = 'qa_cbr_child'; +const ME = 'usr_cbr_member'; +const OTHER = 'usr_cbr_other'; +const CALLER = { userId: ME, positions: ['qa_pos'], permissions: ['qa_cbr_guard'], posture: 'MEMBER' }; + +type Leg = 'batch' | 'by-id'; +type Outcome = + | { kind: 'landed' } + | { kind: 'refused'; code?: string; status?: number }; + +interface Rig { + engine: ObjectQL; + modes: unknown[]; + stored: (object: string, id: string) => Promise | null>; + teardown: () => Promise; +} +const rigs: Rig[] = []; +afterEach(async () => { + for (const rig of rigs.splice(0)) await rig.teardown(); +}); + +async function boot(leg: Leg): Promise { + const engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + // The control leg: no `deleteMany`, so the walk deletes each child by id. + if (leg === 'by-id') (driver as unknown as { deleteMany?: unknown }).deleteMany = undefined; + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerApp({ + id: PACKAGE, + name: 'Cascade batch: the read scope of the by-id child delete', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [ + { + name: PARENT, + label: 'Parent', + sharingModel: 'public_read_write', + fields: { id: { name: 'id', type: 'text', primaryKey: true }, name: { name: 'name', type: 'text' } }, + }, + { + name: CHILD, + label: 'Child', + sharingModel: 'public_read_write', + fields: { + id: { name: 'id', type: 'text', primaryKey: true }, + name: { name: 'name', type: 'text' }, + owner: { name: 'owner', type: 'text' }, + team: { name: 'team', type: 'text' }, + parent: { name: 'parent', type: 'lookup', reference: PARENT, deleteBehavior: 'cascade' }, + }, + }, + ], + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + await engine.insert(PARENT, [ + { id: 'p_hidden', name: 'has a hidden deletable child' }, + { id: 'p_visible', name: 'has only visible deletable children' }, + ], SYS); + await engine.insert(CHILD, [ + // readable (own) and deletable (team ops) + { id: 'c_own', name: 'mine', owner: ME, team: 'ops', parent: 'p_hidden' }, + // hidden by the select policy, admitted by the delete policy + { id: 'c_hidden', name: 'theirs, hidden, deletable', owner: OTHER, team: 'ops', parent: 'p_hidden' }, + // the control parent's children: readable and deletable + { id: 'c_v1', name: 'mine 1', owner: ME, team: 'ops', parent: 'p_visible' }, + { id: 'c_v2', name: 'mine 2', owner: ME, team: 'ops', parent: 'p_visible' }, + ], SYS); + + const crud = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; + const guard = PermissionSetSchema.parse({ + name: 'qa_cbr_guard', + objects: { [PARENT]: crud, [CHILD]: crud }, + rowLevelSecurity: [ + { name: `${CHILD}_read`, object: CHILD, operation: 'select', using: 'record.owner == current_user.id' }, + { name: `${CHILD}_delete`, object: CHILD, operation: 'delete', using: "record.team == 'ops'" }, + ], + }); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + (type === 'permission' ? [MEMBER_DEFAULT, guard].find((s: any) => s?.name === name) : engine.getSchema(name)) ?? null, + list: async () => [MEMBER_DEFAULT, guard], + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn(), + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + + // Which shape each child delete really ran on this leg. + const modes: unknown[] = []; + engine.registerHook('beforeDelete', (hookCtx: any) => { modes.push(hookCtx?.dispatch?.mode); }, { + object: CHILD, packageId: PACKAGE, + }); + + const rig: Rig = { + engine, + modes, + stored: async (object, id) => + ((await engine.findOne(object, { where: { id }, context: { isSystem: true } } as never)) ?? null) as Record | null, + teardown: async () => { try { await engine.destroy(); } catch { /* noop */ } }, + }; + rigs.push(rig); + return rig; +} + +function deleteParent(r: Rig, id: string): Promise { + return r.engine.delete(PARENT, { where: { id }, context: { ...CALLER } } as never).then( + () => ({ kind: 'landed' as const }), + (e: any) => ({ kind: 'refused' as const, code: e?.code, status: e?.statusCode ?? e?.status }), + ); +} + +describe('a cascade batch keeps the read scope the by-id child delete enforces', () => { + for (const leg of ['batch', 'by-id'] as const) { + it(`[${leg}] a child hidden by a select policy and admitted by a delete policy refuses the parent's delete 403, and nothing is deleted`, async () => { + const r = await boot(leg); + // The preconditions, read off the doors: the caller cannot read the + // child, and the delete policy admits it. + expect(await r.engine.findOne(CHILD, { where: { id: 'c_hidden' }, context: { ...CALLER } } as never)).toBeFalsy(); + expect((await r.stored(CHILD, 'c_hidden'))?.team).toBe('ops'); + + const got = await deleteParent(r, 'p_hidden'); + + expect(got).toMatchObject({ kind: 'refused', code: 'PERMISSION_DENIED', status: 403 }); + expect(await r.stored(CHILD, 'c_hidden')).not.toBeNull(); + expect(await r.stored(CHILD, 'c_own')).not.toBeNull(); + expect(await r.stored(PARENT, 'p_hidden')).not.toBeNull(); + // Both legs refused on the by-id shape: no batch hook ran first. + expect(r.modes.every((m) => m === 'record')).toBe(true); + }); + + it(`[${leg}] children the caller can read and delete are deleted with the parent (control)`, async () => { + const r = await boot(leg); + + const got = await deleteParent(r, 'p_visible'); + + expect(got).toEqual({ kind: 'landed' }); + expect(await r.stored(CHILD, 'c_v1')).toBeNull(); + expect(await r.stored(CHILD, 'c_v2')).toBeNull(); + expect(await r.stored(PARENT, 'p_visible')).toBeNull(); + expect(r.modes).toEqual(leg === 'batch' ? ['per-row', 'per-row'] : ['record', 'record']); + }); + } +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 5217cc260fb..a7d179a120c 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1380,7 +1380,16 @@ export const HookContextSchema = lazySchema(() => z.object({ * * - `mode` — `'record'` when this call is the caller's whole write (a * single-id update/delete, a non-batch insert); `'per-row'` when it is - * one of N dispatches for one caller write. + * one of N dispatches for one caller write. A cascade delete removes a + * relation's children as one predicate delete per chunk of 500 (ruling + * 6893661036), so a cascaded child is `'per-row'` with + * `input.options.multi` set, and within one chunk of one relation every + * child's `beforeDelete` runs before any of that chunk is gone (not + * across chunks or relations). A chunk is deleted by id instead, each + * child keeping `'record'`, when the caller's scope narrows it (a child + * the caller may not read or delete), when the child's driver has no + * `deleteMany` or is a floored external driver, and when the child + * object is the organization object; so one cascade can show both. * - `index` — 0-based position within that fan-out; always 0 when * `mode` is `'record'`. `index === 0` is how a handler does batch-scoped * work exactly once instead of N times. @@ -1786,9 +1795,14 @@ export const HookContextSchema = lazySchema(() => z.object({ * * The engine deletes each child AS THE CALLER: the cascade recurses through * the public delete with the caller's own context, so on the path a real - * request takes (a REST `DELETE` carrying a `userId`) `ctx.user`, - * `ctx.session` and `ctx.input` are identical between a child the cascade - * removes and a user's hand delete of that same child. An app guard that + * request takes (a REST `DELETE` carrying a `userId`) `ctx.user` and + * `ctx.session` are identical between a child the cascade removes and a + * user's hand delete of that same child. `ctx.input` and `ctx.dispatch` + * tell nothing apart either: a batched child carries the same + * `{ where: { id: { $in } }, multi: true }` options and `'per-row'` mode a + * user's own predicate delete of those rows carries, and a child deleted by + * id the same `{ where: { id } }` and `'record'` a hand delete carries. An + * app guard that * freezes settled records (a quote's lines once the quote is accepted) had * no declared way to refuse the hand delete while yielding to the cascade, * and refusing both leaves the parent, and every record whose own cascade @@ -1799,8 +1813,9 @@ export const HookContextSchema = lazySchema(() => z.object({ * Unlike `referentialFieldClear`, this fact has no `__`-prefixed twin on the * ExecutionContext, and nothing on that envelope is the contract. The engine * recognises the delete it issued through an engine-private ambient record - * keyed on the exact object and id its cascade is deleting, claimed by that - * one delete. Two consequences follow, and both are part of the contract: + * keyed on the exact object and id (or, for a batch of children, the exact + * id set) its cascade is deleting, claimed by that one delete. Two + * consequences follow, and both are part of the contract: * * - it does not ride the envelope, so a write a hook issues through * `ctx.api` during a cascade dispatch is NOT marked, a delete included: