From 4371684fac79d6b822255c90288ceca509dcd185 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:42:18 +0000 Subject: [PATCH 01/10] feat(objectql): batch a cascade's children into one predicate delete per chunk Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ --- .../objectql/src/engine-cascade-planning.ts | 98 +++++++++++++++---- .../src/engine-delete-and-aggregate.ts | 45 +++++++-- .../src/engine-middleware-and-context.ts | 13 ++- packages/objectql/src/engine-top-level.ts | 49 ++++++++-- 4 files changed, 172 insertions(+), 33 deletions(-) diff --git a/packages/objectql/src/engine-cascade-planning.ts b/packages/objectql/src/engine-cascade-planning.ts index 9c00176f6f6..82bd011420e 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -50,8 +50,10 @@ import { isMissingTableError } from '@objectstack/metadata/errors'; 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 +858,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 +996,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 +1099,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 +1177,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 +1401,67 @@ 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 batch's caller-scoped 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 + * the 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); + 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; + if (batchable) { + try { + await host.cascadeIssuedDeletes.run( + { object: childName, ids: new Set(chunk.map((depId) => String(depId))), claimed: false }, + () => host.delete(childName, { where: { id: { $in: chunk } }, 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 chunk) cascadeSetAdd(cascadeSet.entered, childName, depId); + continue; + } 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), + ); + } + } +} diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 9e62210aa02..e18c63ae445 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,25 @@ export class DeleteAndAggregateFacet { declaredDeleteColumns, ); predicateMatchedRows = doomed; + // [ruling 6893104201 point (2)] The read ran through the AST the + // middleware chain composed, so it is the caller's scope. A child the + // walk asked for and the 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 +835,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 4229f070195..c3856aaab49 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -42,6 +42,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'; @@ -207,7 +208,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 6d0821fe358..cdf3a11bb4f 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 @@ -5165,8 +5202,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, From 4678f633da0c20afd22a12b1d3a2a287d455edaa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 11:54:24 +0000 Subject: [PATCH 02/10] test(objectql,plugin-auth): pin the batched cascade's order, shape, fallback and guard verdict Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ --- .../src/engine-cascade-delete-batch.test.ts | 355 ++++++++++++++++++ .../engine-cascade-summary-rollback.test.ts | 8 +- .../plugin-auth/src/last-admin-guard.test.ts | 98 +++++ 3 files changed, 459 insertions(+), 2 deletions(-) create mode 100644 packages/objectql/src/engine-cascade-delete-batch.test.ts 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..4298f3e46fb --- /dev/null +++ b/packages/objectql/src/engine-cascade-delete-batch.test.ts @@ -0,0 +1,355 @@ +// 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; + * - a driver with no `deleteMany` keeps the by-id path. + */ + +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 } } as any); + + // 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('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 (ctx: any) => { + remaining.push((await engine.find('line', { where: { acct: 'a1' } } as any)).length); + }); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + // 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 } } as any); + + 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 } } as any); + 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 } } as any); + + 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 } } as any).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 } } as any).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 } } as any).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 } } as any); + + 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 } } as any); + 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']); + }); +}); 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/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']); + }); + } +}); From df2c20cea74b2e0d9c16652374e76185de9c3240 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:16:26 +0000 Subject: [PATCH 03/10] docs(spec): a cascaded child delete dispatches per-row; changeset for the batched cascade Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ --- .changeset/33699-cascade-delete-batch.md | 23 +++++++++++++++++++++++ packages/spec/src/data/hook.zod.ts | 11 ++++++++--- 2 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 .changeset/33699-cascade-delete-batch.md diff --git a/.changeset/33699-cascade-delete-batch.md b/.changeset/33699-cascade-delete-batch.md new file mode 100644 index 00000000000..c2280c31e15 --- /dev/null +++ b/.changeset/33699-cascade-delete-batch.md @@ -0,0 +1,23 @@ +--- +'@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) +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, 57 after, on SQLite and on PostgreSQL alike. + +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. +- 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 (a child the caller may not delete, which a predicate delete would skip) 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. Such a chunk keeps today's shape, `'record'` with no `multi`, so one cascade can show both shapes. A driver with no `deleteMany` keeps the by-id path too. + +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/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index e4aa4890305..d195e258e08 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1359,7 +1359,12 @@ 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 (ruling + * 6893661036), so a cascaded child is `'per-row'` with + * `input.options.multi` set, and every child's `beforeDelete` runs before + * any of them is gone; a chunk the caller's scope narrows is deleted by + * id instead and keeps `'record'`, 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. @@ -1765,8 +1770,8 @@ 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: From cb2cafef68038b79912ac7cbd2db020b5423f464 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 12:40:07 +0000 Subject: [PATCH 04/10] test(objectql): drop an unused hook parameter the test typecheck refuses Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ --- packages/objectql/src/engine-cascade-delete-batch.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-cascade-delete-batch.test.ts b/packages/objectql/src/engine-cascade-delete-batch.test.ts index 4298f3e46fb..bf8c654164d 100644 --- a/packages/objectql/src/engine-cascade-delete-batch.test.ts +++ b/packages/objectql/src/engine-cascade-delete-batch.test.ts @@ -195,7 +195,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', 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 (ctx: any) => { + engine.on('beforeDelete', 'line', async () => { remaining.push((await engine.find('line', { where: { acct: 'a1' } } as any)).length); }); await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); From d31c13d0ac27a28ffcb71b1ee6833be324297289 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:09:57 +0000 Subject: [PATCH 05/10] test(objectql): type the batched cascade test's engine option bags; changeset carries the claim's declaration line verbatim Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ --- .changeset/33699-cascade-delete-batch.md | 2 +- .../src/engine-cascade-delete-batch.test.ts | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.changeset/33699-cascade-delete-batch.md b/.changeset/33699-cascade-delete-batch.md index c2280c31e15..74daa9273b4 100644 --- a/.changeset/33699-cascade-delete-batch.md +++ b/.changeset/33699-cascade-delete-batch.md @@ -5,7 +5,7 @@ perf(objectql)!: a cascade delete removes a relation's children as one predicate delete per chunk -Clause-②: no (narrowing) +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 diff --git a/packages/objectql/src/engine-cascade-delete-batch.test.ts b/packages/objectql/src/engine-cascade-delete-batch.test.ts index bf8c654164d..3eadaac98f5 100644 --- a/packages/objectql/src/engine-cascade-delete-batch.test.ts +++ b/packages/objectql/src/engine-cascade-delete-batch.test.ts @@ -167,7 +167,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', 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 } } as any); + await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } }); // Every before ran with nothing written; ONE set delete; then every after. expect(order).toEqual([ @@ -196,9 +196,9 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', const { engine } = await makeEngine(); const remaining: number[] = []; engine.on('beforeDelete', 'line', async () => { - remaining.push((await engine.find('line', { where: { acct: 'a1' } } as any)).length); + remaining.push((await engine.find('line', { where: { acct: 'a1' } })).length); }); - await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + 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]); }); @@ -211,7 +211,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', const seen: Seen[] = []; listen(engine, seen, 'line_note'); - await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + 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([ @@ -222,7 +222,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', 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 } } as any); + 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([]); @@ -238,7 +238,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', } as any; engine.setRealtimeService(realtime); - await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + 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']); @@ -251,7 +251,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', 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 } } as any).then(() => null, (e: unknown) => e); + 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([]); @@ -264,7 +264,7 @@ describe('[F1] a cascade deletes a relation\'s children as one batch per chunk', 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 } } as any).then(() => null, (e: unknown) => e); + 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); @@ -302,7 +302,7 @@ describe('[F1] a chunk the caller\'s scope narrows falls back to today\'s by-id listen(engine, seen, 'line'); const byIdAttempts = narrowAndRefuse(engine, 'line', 'l2'); - const err: any = await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any).then(() => null, (e: unknown) => e); + 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); @@ -331,7 +331,7 @@ describe('[F1] a chunk the caller\'s scope narrows falls back to today\'s by-id listen(engine, seen, 'line', ['beforeDelete']); listen(engine, seen, 'memo', ['beforeDelete']); - await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + 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([ @@ -348,7 +348,7 @@ describe('[F1] a chunk the caller\'s scope narrows falls back to today\'s by-id const { engine, driver } = await makeEngine({ deleteMany: false }); const seen: Seen[] = []; listen(engine, seen, 'line', ['beforeDelete']); - await engine.delete('acct', { where: { id: 'a1' }, context: { ...CALLER } } as any); + 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']); }); From 4029ca241db4b916713822ede386922613125a4d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:33:50 +0000 Subject: [PATCH 06/10] fix(objectql): a cascade batch asks the caller's read door for its chunk before batching it A by-id child delete re-reads its row through the read door, so a child the caller cannot read refuses and the cascade rolls back. A nested predicate delete carries the write-class scope only, so the walk now asks the read door for each chunk's ids and deletes the chunk by id when any is missing. A cascade into the organization object keeps the by-id path. Pinned on a real security stack on both legs; spec TSDoc and changeset name every fallback and the absent afterDelete result. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .changeset/33699-cascade-delete-batch.md | 3 +- .../src/engine-cascade-delete-batch.test.ts | 98 ++++++++- .../objectql/src/engine-cascade-planning.ts | 55 ++++- .../src/engine-delete-and-aggregate.ts | 14 +- .../src/cascade-batch-read-scope.test.ts | 207 ++++++++++++++++++ packages/spec/src/data/hook.zod.ts | 26 ++- 6 files changed, 381 insertions(+), 22 deletions(-) create mode 100644 packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts diff --git a/.changeset/33699-cascade-delete-batch.md b/.changeset/33699-cascade-delete-batch.md index 74daa9273b4..42708776534 100644 --- a/.changeset/33699-cascade-delete-batch.md +++ b/.changeset/33699-cascade-delete-batch.md @@ -17,7 +17,8 @@ Deleting a record now deletes the children each `cascade` relation reaches as ON 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. - 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 (a child the caller may not delete, which a predicate delete would skip) 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. Such a chunk keeps today's shape, `'record'` with no `multi`, so one cascade can show both shapes. A driver with no `deleteMany` keeps the by-id path too. +- 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. 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 index 3eadaac98f5..02cf60b36f8 100644 --- a/packages/objectql/src/engine-cascade-delete-batch.test.ts +++ b/packages/objectql/src/engine-cascade-delete-batch.test.ts @@ -21,7 +21,11 @@ * 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; - * - a driver with no `deleteMany` keeps the by-id path. + * - 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'; @@ -353,3 +357,95 @@ describe('[F1] a chunk the caller\'s scope narrows falls back to today\'s by-id 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 82bd011420e..e5cacb69332 100644 --- a/packages/objectql/src/engine-cascade-planning.ts +++ b/packages/objectql/src/engine-cascade-planning.ts @@ -47,6 +47,7 @@ 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 { @@ -1425,21 +1426,31 @@ export class CascadePlanningFacet { * 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 batch's caller-scoped read misses a child it was asked for + * - 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 - * the refusal rolls the whole cascade back (ruling 6893104201 point 2). - * So one cascade can show both shapes. + * delete of that child refuses where a predicate one would skip it. + * 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 { +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); + 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; - if (batchable) { + if (batchable && await readDoorReturnsChunk(host, childName, chunk, context)) { try { await host.cascadeIssuedDeletes.run( { object: childName, ids: new Set(chunk.map((depId) => String(depId))), claimed: false }, @@ -1465,3 +1476,33 @@ async function deleteCascadedChildren(host: Pick