diff --git a/.changeset/30020-objectql-delete-facet.md b/.changeset/30020-objectql-delete-facet.md new file mode 100644 index 00000000000..8ec172d5cfd --- /dev/null +++ b/.changeset/30020-objectql-delete-facet.md @@ -0,0 +1,11 @@ +--- +'@objectstack/objectql': patch +--- + +refactor(objectql): the `ObjectQL#delete` body moves into the delete-and-aggregate facet + +Clause-②: no +Metadata-protocol: none + +- The body of `delete` moves out of `engine.ts` into `engine-delete-and-aggregate.ts`, beside `aggregate`. The method stays on the class as a one-call stub with its signature and its docblock. Where the body handed the engine itself on (`ql: this` in the hook context), it reads the same engine through the host's `facade` entry, and its one static read (the reference probe batch size) goes through the forwarder the other facets already use. +- No behaviour changes and nothing to do on upgrade: the same statements run in the same order. The built declaration files are unchanged; the source maps move. diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index d369164d0d2..18f96a2ff99 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -2,8 +2,9 @@ /** * [#29986 codemod] The "Delete, count, aggregate and execute" section of - * `ObjectQL`: the bodies of `assertNoInternalFieldEvaluated`, `aggregate` moved - * out of `engine.ts` whole by `scripts/codemod-split-engine.mjs`. + * `ObjectQL`: the bodies of `delete`, `assertNoInternalFieldEvaluated`, + * `aggregate` moved out of `engine.ts` whole by + * `scripts/codemod-split-engine.mjs`. * * A MOVE, not a redesign. {@link DeleteAndAggregateFacet} is a stateless facet of `ObjectQL` * (ruling 6624345766): each static method of it is the body of the `ObjectQL` @@ -24,17 +25,36 @@ * class, and a field a body assigns goes with a SETTER that assigns it on the * engine. * - * The module imports `engine.ts` for types only, so the two modules form no - * evaluation cycle. `index.ts` re-exports nothing from this module. + * `ObjectQL` here is `ObjectQLStatics` (imported AS `ObjectQL`): forwarders to the + * statics the bodies read, private ones included, which the class fills in a + * static block; the class as a type is `ObjectQLClass`. + * + * Values that stayed in `engine.ts` are imported from it (lever (a) of + * ruling 6591753301); every use is inside a function body, so the import + * cycle is never read at evaluation time. `index.ts` re-exports nothing from + * this module. */ import { normalizeFilterComparandTypes } from '@objectstack/spec/data'; -import type { EngineAggregateOptions, QueryAST } from '@objectstack/spec/data'; +import type { EngineAggregateOptions, EngineDeleteOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts'; -import { assertFilterIsMaterializable, assertListComparandShapes, invalidFilterError } from './filter-comparand-shape.js'; +import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; import { assertHavingTemporalComparandsInterpretable, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js'; import { assertTextOperatorTargetsAreStringCapable } from './text-operator-declared-type-door.js'; import { narrowHavingNumberComparands, narrowNumberComparands } from './number-comparand-declared-type-door.js'; +import { deletedSecretColumns, deletedSecretSlots } from './engine-secret-internal-fields.js'; +import type { SecretHandleSlot } from './engine-secret-internal-fields.js'; +import { readPermanentDelete } from './recycle-bin/purge.js'; +import type { RecycleBinDeleteObservability } from './recycle-bin/list.js'; +import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { recordNotFoundError } from '@objectstack/core'; +import { SummaryRecomputeError, cascadeStoppedRefusal } from './summary-errors.js'; +import { withoutDeletedSelfParents } from './summary-aggregate.js'; +import { HookTargetRebindError } from './hook-target-rebind-errors.js'; +import { DeleteHookResultNotWriteShapeError, isDeleteResultShape } from './verb-hook-result-shape.js'; +import { redactBoundStatement } from '@objectstack/types'; +import { ORGANIZATION_OBJECT } from './tenancy/system-write-organization.js'; import { rejectCredentialEvaluation } from './credential-evaluation-guard.js'; import { assertNoInternalFieldEvaluated, rejectInternalFieldEvaluation } from './internal-field-evaluation-guard.js'; import { assertGroupByNamesNoJsonStoredField } from './group-by-structured-json-door.js'; @@ -47,13 +67,20 @@ import { } from './aggregate-query-shape-door.js'; import { applyInMemoryAggregation } from './in-memory-aggregation.js'; import { aggregatedRowColumnClasses, aggregatedRowColumnTypes, aggregatedRowColumns, applyHaving, assertAggregationFilterIsEvaluable, assertHavingIsEvaluable, assertHavingIsFilterCondition } from './having-filter.js'; +import { coerceBooleanFields } from './validation/record-validator.js'; +import { declaredColumnSet, rowsWithDeclaredColumnsOnly, withDeclaredColumnsOnly } from './declared-read-columns.js'; +import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external-driver-floor.js'; +import { ENGINE_DELETE_REJECT_MESSAGE, resolveEngineDeleteDispatch } from './engine-delete-dispatch.js'; +import type { EngineDeleteDispatchInput } from './engine-delete-dispatch.js'; import { - ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, declaredDatetimeLowering, describeNonFilterWhere, - foldEngineOptionAliases, isWhereFilterObject, lowerWhereFilterArray, mergeReadContext, rejectUnknownEngineOptions, - resolveThenLowerWhere, whereResolvedTokenJudge, + ENGINE_AGGREGATE_OPTION_KEYS, ENGINE_DELETE_OPTION_KEYS, ENGINE_WHERE_SLOTS, declaredDatetimeLowering, + describeNonFilterWhere, foldEngineOptionAliases, isWhereFilterObject, lowerWhereFilterArray, mergeReadContext, + organizationPredicateDeleteRefusal, rejectUnknownEngineOptions, resolveThenLowerWhere, whereResolvedTokenJudge, + writeFailureLogMeta, } from './engine-top-level.js'; import type { EngineReadOptions, OperationContext } from './engine-top-level.js'; -import type { ObjectQL } from './engine.js'; +import { ObjectQLStatics as ObjectQL } from './engine.js'; +import type { ObjectQL as ObjectQLClass } from './engine.js'; /** * The `ObjectQL` members the bodies of {@link DeleteAndAggregateFacet} read — every one of @@ -63,21 +90,789 @@ import type { ObjectQL } from './engine.js'; * assigns. */ export interface DeleteAndAggregateHost { - readonly _registry: ObjectQL['_registry']; - buildDriverOptions: ObjectQL['buildDriverOptions']; - composeReadableIdsAtBoundary: ObjectQL['composeReadableIdsAtBoundary']; - executeWithMiddleware: ObjectQL['executeWithMiddleware']; - expandSearchOnOptions: ObjectQL['expandSearchOnOptions']; - getDriver: ObjectQL['getDriver']; - readonly logger: ObjectQL['logger']; - rejectCredentialAggregation: ObjectQL['rejectCredentialAggregation']; - readonly relatedSchemaOf: ObjectQL['relatedSchemaOf']; - resolveObjectName: ObjectQL['resolveObjectName']; - resolveWhereTokens: ObjectQL['resolveWhereTokens']; + readonly _registry: ObjectQLClass['_registry']; + assertBulkPerRowHookBudget: ObjectQLClass['assertBulkPerRowHookBudget']; + assertWriteAllowed: ObjectQLClass['assertWriteAllowed']; + buildDriverOptions: ObjectQLClass['buildDriverOptions']; + buildHookApi: ObjectQLClass['buildHookApi']; + buildPerRowAfterContexts: ObjectQLClass['buildPerRowAfterContexts']; + buildProvenance: ObjectQLClass['buildProvenance']; + buildSession: ObjectQLClass['buildSession']; + buildUser: ObjectQLClass['buildUser']; + cascadeDeleteRelations: ObjectQLClass['cascadeDeleteRelations']; + claimReferentialCascadeDelete: ObjectQLClass['claimReferentialCascadeDelete']; + composeReadableIdsAtBoundary: ObjectQLClass['composeReadableIdsAtBoundary']; + delete: ObjectQLClass['delete']; + dispatchPerRowBeforeHooks: ObjectQLClass['dispatchPerRowBeforeHooks']; + dispatchUnscopedMultiWriteHooks: ObjectQLClass['dispatchUnscopedMultiWriteHooks']; + enforceTransactionOrigin: ObjectQLClass['enforceTransactionOrigin']; + executeWithMiddleware: ObjectQLClass['executeWithMiddleware']; + expandSearchOnOptions: ObjectQLClass['expandSearchOnOptions']; + /** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */ + readonly facade: ObjectQLClass; + getDriver: ObjectQLClass['getDriver']; + getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors']; + hasHooksFor: ObjectQLClass['hasHooksFor']; + inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit']; + invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe']; + readonly logger: ObjectQLClass['logger']; + openRecycleBinCapture: ObjectQLClass['openRecycleBinCapture']; + opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit']; + planCascadeAtomicity: ObjectQLClass['planCascadeAtomicity']; + publishBulkDataEvent: ObjectQLClass['publishBulkDataEvent']; + publishDataEvent: ObjectQLClass['publishDataEvent']; + readonly realtimeService: ObjectQLClass['realtimeService']; + recomputeSummaries: ObjectQLClass['recomputeSummaries']; + rejectCredentialAggregation: ObjectQLClass['rejectCredentialAggregation']; + readonly relatedSchemaOf: ObjectQLClass['relatedSchemaOf']; + releaseSecretHandles: ObjectQLClass['releaseSecretHandles']; + resolveObjectName: ObjectQLClass['resolveObjectName']; + resolveWhereTokens: ObjectQLClass['resolveWhereTokens']; + summaryForeignKeyColumns: ObjectQLClass['summaryForeignKeyColumns']; + transaction: ObjectQLClass['transaction']; + triggerHooks: ObjectQLClass['triggerHooks']; + warnCascadeNotAtomic: ObjectQLClass['warnCascadeNotAtomic']; + withResolvedWhere: ObjectQLClass['withResolvedWhere']; } /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { + /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + object = this.resolveObjectName(object); + // [#22782] An aborting `afterDelete` rolls this write back — see `opensAfterAbortUnit`. + if (this.opensAfterAbortUnit('afterDelete', object, options?.context)) { + return this.inAfterAbortUnit(() => this.delete(object, options)); + } + this.logger.debug('Delete operation starting', { object }); + this.assertWriteAllowed(object, 'delete'); + // [#8844] See the insert face — deleting the install's only organization + // must not leave the memo answering with it. + if (object === ORGANIZATION_OBJECT) this.invalidateOrganizationProbe(); + const driver = this.getDriver(object); + // [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write, + // carve an append-only system ledger out of the transaction. Before any + // hook, default or validation runs, so a refusal costs nothing. + this.enforceTransactionOrigin(object, driver, 'delete'); + + // Fold the `filter` alias into `where` first — same reasoning as update() + // above (#4346): unfolded, a `multi: true` delete with `{ filter }` had no + // predicate on its AST and emptied the table. + options = foldEngineOptionAliases(object, 'delete', options, ENGINE_WHERE_SLOTS); + rejectUnknownEngineOptions(object, 'delete', options, ENGINE_DELETE_OPTION_KEYS); + // [#5158] Same ordering reason as update(): the dispatch decision below + // reads `where.id`, which an unlowered array never carries. + options = lowerWhereFilterArray(object, 'delete', options, this._registry.getObject(object), this.relatedSchemaOf); + // [ADR-0100] Same credential-column refusal as update(). + rejectCredentialEvaluation(object, 'delete', options, options?.context, this.relatedSchemaOf); + + // Expand `{filter-placeholder}` values before the id is extracted — same + // reasoning as update() above (#3810). + // [ADR-0053 D-D1, amended — #5930] …and lowered in the same stage. + options = await this.withResolvedWhere(object, 'delete', options, declaredDatetimeLowering(this._registry.getObject(object))); + + // Extract ID logic mirroring update(): only a SCALAR `where.id` means + // "delete one row by primary key". An operator object ({ $in: [...] }, …) + // is a multi-row predicate — treating it as an id would bind the object + // literally (driver.delete(object, {$in:[…]})) and both skip the #2982 AST + // seeding below AND bypass the by-id RLS pre-image check. Leave `id` + // undefined so the call routes to deleteMany with the scoped AST. + // + // [#4550] The decision lives in `engine-delete-dispatch.ts` so the fake + // engines that stand in for this method import it instead of re-deriving + // it. #4434 shipped a dead REST route green because plugin-sharing's fake + // accepted the one shape the `reject` branch below refuses; a double that + // reads THIS predicate cannot be looser than this method. + const dispatch = resolveEngineDeleteDispatch(options as EngineDeleteDispatchInput | undefined); + const id: any = dispatch.kind === 'by-id' ? dispatch.id : undefined; + // [#30237, ADR-0148, Q3 = A] A permanent delete writes no recycle-bin entry + // and is authorized as `purge`, the recycle-bin manager's verb. Refused here, + // before any middleware or hook, unless it is a by-id delete of an object + // the bin takes (see `readPermanentDelete`). + 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); + + const opCtx: OperationContext = { + object, + operation: permanent ? 'purge' : 'delete', + options, + context: options?.context, + }; + + // [#2982] Same seam as update: a no-single-id delete routes to + // `driver.deleteMany` with an AST that used to be rebuilt from + // `options.where` after the middleware chain, discarding any row-scoping a + // middleware composed onto `opCtx.ast`. Seed the caller's predicate before + // the chain, keyed on the SAME falsy-`id` test the multi branch dispatches + // on; the multi branch consumes the composed result. + if (!id) { + opCtx.ast = { object, ...(options?.where !== undefined ? { where: options.where } : {}) } as QueryAST; + } + + await this.executeWithMiddleware(opCtx, async () => { + // [ADR-0139 D1] As in `update`: a leaf the middleware chain wrote into a + // delete's predicate is refused at the executor's entry, before the + // pre-image reads reach the driver. + collectComposableReadableIds(object, 'delete', opCtx.ast?.where, 'where'); + const hookContext: HookContext = { + object, + event: 'beforeDelete', + input: { id, options: opCtx.options }, + session: this.buildSession(opCtx.context), + provenance: this.buildProvenance(opCtx.context), + // [#23221] The declared cascade-delete marker, the delete twin of + // `update()`'s `referentialFieldClear` spread: conditional for the + // same reason, "absent unless true". Bound once on this context, + // which `afterDelete` reuses, so both phases carry it. + ...(referentialCascadeDelete ? { referentialCascadeDelete: true as const } : {}), + user: this.buildUser(opCtx.context), + api: this.buildHookApi(opCtx.context), + transaction: opCtx.context?.transaction, + ql: this.facade + }; + + // [#5272] The pre-image of the row this delete is about to remove. + // + // `HookContext.previous` is documented — in the spec, since it was + // written — as "the state of the record BEFORE the operation (for + // update/delete)", and `update()` has bound it all along. `delete()` + // never did: `previous` was `undefined` in `beforeDelete` AND in + // `afterDelete`, so a legal, contract-shaped delete-side transition + // condition (`previous.status == "done"`) was unevaluable — and since + // #4775 unevaluable REJECTS the operation. Worse, it was reported + // through the generic branch, which reads as "you misspelled a key" + // when the key was fine and the engine simply never bound it (#5037's + // shape, one path over). + // + // #5038 made the asymmetry visible from the other side: a predicate + // bulk delete already binds each doomed row's own pre-image on its + // per-row `afterDelete`, so the SINGLE-record path was strictly worse + // than the bulk one — the exact inversion #4800/#4862 ruled against. + // + // Demand-driven, like `update()`'s `priorRecord`: read only when + // something on this object actually consumes it — + // * a delete-side hook, EITHER phase (its `condition` may read + // `previous`; its handler — plugin-audit, the record-change + // trigger — reads `ctx.previous` directly); + // * a roll-up summary aggregating this object, which needs the + // doomed row's FK value to find the parent to recompute. + // Those two used to be separate reads at separate times (the summary + // one fetched only after `beforeDelete` had run); they are ONE read + // now — and a RAW driver read, which is exactly what `update()` + // already hands `recomputeSummaries` as its `previous` argument, so + // the two write paths now agree on what a pre-image is. + // + // `needsPriorRecord(schema)` is deliberately NOT part of this gate + // even though `update()`'s twin carries it: object validation rules + // are evaluated on insert/update only — `delete()` evaluates none — + // so including it would buy a read with no reader. + // + // Read BEFORE `beforeDelete` fires. A delete's `before` phase is the + // one that has nothing else to look at (its `input` carries an id and + // no data), and the pre-image has to be taken before the row is gone + // either way, so a single read serves both phases. + // + // [#5574] The same read now serves the PER-ROW `beforeDelete` dispatch on + // the predicate path — see the pre-phase below. `delete()` was already + // the right shape here; what changed is that the predicate branch grew + // the same discipline the by-id branch has had since #5272. + // + // [#5929] The gate's THREE terms, unchanged by that card and enumerated + // here because it had to enumerate them to answer it: + // 1. `hasHooksFor('beforeDelete', object)` + // 2. `hasHooksFor('afterDelete', object)` + // 3. `getSummaryDescriptors(object).length > 0` + // No validation term, deliberately — see `needsPriorRecord` above. + // + // What #5929 changed is not this expression but what term 1 MEANS. Until + // then, objectql's own `ObjectQLPlugin` registered a builtin + // `sys_fetch_previous_delete` on `beforeDelete` with `object: '*'`, so on + // every kernel-hosted engine term 1 was true for every object and the + // per-object skip this gate exists to perform could never happen. The + // builtin's only remaining effect WAS holding this gate open: the read + // below binds `previous` before `beforeDelete` dispatches, so its own + // `!ctx.previous` guard was already unreachable. Retiring it (plugin.ts, + // ADR-0049 enforce-or-remove) makes term 1 an honest question. + // + // ⚠️ Honest is not the same as usually-false, and the difference is worth + // knowing before anyone reads a skip into a production trace. Every + // delete-phase hook below registers with NO `object` — global — so each + // holds term 1 or term 2 open for every object on a kernel that loads it: + // + // * `plugin-auth` identity-write-guard beforeDelete (filters by + // `isManaged(ctx.object)` inside the handler) + // * `plugin-sharing` record-share-cascade before+afterDelete (filters + // by `targets(objectName)` inside the handler) + // * `service-storage` file-reference-lifecycle before+afterDelete + // (filters by `activeFileFields(object)` inside) + // * `plugin-audit` writeAudit afterDelete only — #6656 retired + // `captureBefore`, which was its `beforeDelete` half, + // so it holds term 2 open and no longer term 1; + // global MINUS `excludeObjects: AUDIT_EXCLUDED_OBJECTS` + // (#5860) — the one that narrows at the ENGINE face, + // so `hookMatchesObject` can subtract it and an + // excluded object really does skip this read. + // + // The first three are real handlers with real work, merely deciding their + // own applicability at dispatch time rather than at registration time; + // this gate answering "yes" for them is the gate WORKING, not a second + // instance of the #5929 defect. Narrowing any of them to the objects it + // actually serves — plugin-audit's `excludeObjects` face is the worked + // example — is what would convert them into skips, and that is each + // package's own card, not this one's. + // [#7867] ⚠️ RETIRED — the three-term `wantsPreImage` gate the paragraphs + // above describe is GONE, and the paragraphs are kept because what they + // record (which registrants hold which term open, and why an honest gate + // is not the same as a usually-false one) is still the reason the removal + // costs nothing measurable. + // + // It asked "does anything CONSUME the pre-image?" and skipped the read + // when nothing did. Existence is a consumer it never counted — and it is + // the one consumer EVERY by-id delete has, because a delete against an id + // that names no row must answer 404 rather than run. So the by-id branch + // below reads the pre-image unconditionally and gates on it; the + // predicate branch reads its doomed rows under its own `perRowBefore/ + // AfterHooks` gate, which is untouched. On any kernel loading the global + // registrants enumerated above, term 1 or 2 was already true for every + // object, so this skipped nothing there anyway; the read becomes + // genuinely new only for a bare embedder whose object has no delete-side + // hook and no roll-up — and that embedder is buying a 404 it did not have. + // + // ⛔ Do not reintroduce it as a guard around the by-id read. A gate on + // whether to LOOK is not compatible with a rule about what to do when + // nothing is there. See `update()`'s twin. + // + // [#7933] The first three entries were carried here UNVERIFIED when + // #7707 corrected the `plugin-audit` one, which was wrong on BOTH halves + // — hook name and term. All three have since been read against the + // function that binds them — `registerIdentityWriteGuard`, + // `bindRecordShareCascade`, `installFileReferenceHooks` — and all three + // match what is claimed above: same events, same object-less + // registration, same in-handler filter. Nothing above needed changing. + // That audit is what the retirement note's "term 1 or 2 was already true + // for every object" stands on, so it is recorded here rather than left + // in a closed issue: the enumeration outlived the gate it was written + // for, and it is now load-bearing for a different claim than the one it + // was written to support. + const deleteSchema = this._registry.getObject(object); + // `buildDriverOptions` is what carries the open transaction and the + // tenant scope onto a raw driver read. Skipping it here would read + // outside this write's transaction and across the tenant boundary — + // `update()`'s prior read passes the same bag for the same reason. + // [#21613] Both pre-image reads below are shaped to the declared field + // set, as `update()`'s are: the pre-image is the delete's `previous`, and + // the audit ledger records it whole as the delete's `old_value`, so a + // column no metadata declares reached that served row with its value. + const declaredDeleteColumns = declaredColumnSet(deleteSchema); + const readPreImage = async (targetId: unknown): Promise | null> => { + const preAst: QueryAST = { object, where: { id: targetId }, limit: 1 }; + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + return withDeclaredColumnsOnly( + (await driver.findOne(object, preAst, preOpts)) as Record | null, + declaredDeleteColumns, + ); + }; + const bindPreImage = (row: Record | null): void => { + // Never fabricate: a row that is not there leaves `previous` UNBOUND + // rather than `{}`/`null`, so a condition reading it faults loudly + // instead of answering for a record nobody read (#4649/#4775). + hookContext.previous = row ? (coerceBooleanFields(deleteSchema as any, row as any) as any) : undefined; + }; + let priorRecord: Record | null = null; + // [#5038] Matched rows for the per-row `afterDelete` dispatch — see the + // twin in update(). A bulk delete is N record changes too, so a + // `record-after-delete` flow must see each deleted row rather than one + // context that names none of them. + let bulkPerRowRows: Record[] | null = null; + // [#26950] The predicate path's matched rows as the per-row hook read + // below took them (`null` when no delete-side hook asked for them), and + // the rows whose foreign keys `recomputeSummaries` is handed after the + // delete (`null` when no roll-up aggregates this object). + let predicateMatchedRows: Record[] | null = null; + let summaryPriorRows: Record[] | null = null; + // [#27581] The `secret` columns this object declares, and the handles the + // removed rows held in them: the by-id pre-image, or the predicate + // path's matched rows, read before the statement takes them away. + const secretColumns = deletedSecretColumns(deleteSchema); + let deletedSecrets: SecretHandleSlot[] = []; + + // [#5574] The dispatch ladder, resolved BEFORE the before phase — see + // update()'s twin for the full reasoning. Keyed on the SAME falsy-`id` + // test the #2982 AST seed above uses. + const isByIdDelete = Boolean(id); + // [#11009] Keyed on the LADDER's verdict, not on `options?.multi` — the + // update twin says why; for every pre-#11009 input the two spellings + // agree. + const isPredicatePath = !isByIdDelete && dispatch.kind === 'multi' && typeof driver.deleteMany === 'function'; + // [#24948] An organization is deleted by id or not at all: plugin-auth's + // organization delete refuses one that still owns records and removes its + // auth structure per organization, which a predicate delete would skip + // (see `organizationPredicateDeleteRefusal`). Any delete not by id is + // refused here, whatever the driver offers, before any hook or write. + if (!isByIdDelete && object === ORGANIZATION_OBJECT) { + throw organizationPredicateDeleteRefusal(); + } + if (!isByIdDelete && !isPredicatePath) { + // [#4550] The `reject` verdict of resolveEngineDeleteDispatch. It used + // to be re-asked after the before phase because a hook could still bind + // the id; with the ladder resolved first there is no such conversion. + // + // [#11009] The dispatch's OWN message — the unhonoured-predicate + // refusal names the dropped `where` keys; the classic shape keeps + // `ENGINE_DELETE_REJECT_MESSAGE`; the fallback arm is a `multi` + // verdict against a driver with no `deleteMany`. + if (dispatch.kind === 'reject') throw new Error(dispatch.message); + // [#27277] See update()'s twin: a floored plugin driver offers no `deleteMany`. + if (isExternalDriverFloor(driver)) throw externalPredicateWriteRefusal(driver.name, object, 'delete'); + throw new Error(ENGINE_DELETE_REJECT_MESSAGE); + } + + // [#6966] See update()'s twin — same rule, same single binding point. + hookContext.dispatch = { + mode: isPredicatePath ? 'per-row' : 'record', + index: 0, + scope: {}, + }; + + if (isByIdDelete) { + // [#7867] Read first, then GATE — the twin of `update()`'s, and #5138's + // own record names `delete` as the worst of the three when the gate was + // missing: "the delete ran and the answer was `200 { deleted: true }` + // for any string in the path, so a typo'd id, an already-deleted row + // and a real deletion were indistinguishable" — the shape #4435 removed + // from `protocol.deleteData` and #5138 removed from `callData`, still + // live here on the path an action body's `.delete()` actually takes. + // + // The pre-image is the only honest place to ask. `IDataDriver.delete` + // does declare `Promise` ("true if deleted, false if not + // found"), so the answer exists downstream — but downstream is AFTER + // `beforeDelete` has dispatched and after `cascadeDeleteRelations` has + // run, i.e. after handlers have fired and children have been touched + // for a parent that was never there. `IDataEngine.delete` also declares + // `Promise` and passes its driver's result through the hook chain, + // so testing it for `=== false` here would read a signal this layer's + // contract does not promise — #5138's argument, unchanged. + priorRecord = await readPreImage(id); + if (!priorRecord) throw recordNotFoundError(object, id); + // Bound unconditionally now that the row is proven present. + // `bindPreImage`'s never-fabricate rule (#4649/#4775) is unchanged and + // still the reason the binding goes through it rather than around it. + bindPreImage(priorRecord); + await this.triggerHooks('beforeDelete', hookContext); + // [#6752] The retired lever, refused — the `update()` twin's check, + // verbatim, because the rule is now ONE rule: a by-id target is + // immutable in a `before*` handler. + // + // Both halves of it used to be answered separately here. CLEARING the + // id was already refused (ADR-0058 Amendment II.1): it worked by + // falling through to the predicate branch, and the ladder is now + // resolved before any handler runs, so there is no ladder left to + // re-enter. REBINDING to another id was still HONOURED, by re-reading + // the new target's pre-image and rebinding `previous` (#5272) so + // nothing stale reached `afterDelete` or the summary recompute. + // + // The 2026-08-09 ruling on #6752 retires that second half. #5272's + // mechanism was internally correct — that is not what was weighed. What + // was weighed: the measured compatibility cost is zero (no consumer in + // the repository repoints), one rule across both verbs beats two + // individually-correct rules an author has to memorize, and a hook that + // silently redirects WHICH ROW GETS DELETED is a top-grade footgun for + // authored — especially AI-authored — handlers. Correctness of the + // mechanism does not justify the surface. + // + // ⛔ Route 3 (growing the same re-resolution for `update()`) stays + // excluded by #5574's ruling: "do not silently pick re-resolution + // instead". The alignment goes the other way, and this is that edit. + // + // The re-read that used to sit here is GONE, not merely bypassed: its + // guard was `input.id !== id && input.id`, which is exactly the case + // this refusal now throws on, so it became unreachable. `readPreImage` + // survives for the pre-dispatch read above — the only read left. A + // handler writing back the SAME id is untouched, as on `update()`. + if (hookContext.input.id !== id) { + throw new HookTargetRebindError({ + object, event: 'beforeDelete', path: 'by-id', + expectedId: id, observedId: hookContext.input.id, + }); + } + } else { + // [#2982] Consume the middleware-composed AST seeded above so the + // injected row-scoping binds every read AND the delete. Fail CLOSED if + // it is absent rather than rebuilding an unscoped `{ object, where }` + // (AGENTS.md PD #12). + const ast = opCtx.ast; + if (!ast) { + throw new Error( + `[Security] Refusing bulk delete on '${object}': row-scoping AST was not seeded ` + + `(the predicate branch was reached without the AST seeded before the middleware ` + + `chain — the one RLS and sharing compose their row-scoping onto, so that a bulk ` + + `write reaches only the rows this caller may edit).`, + ); + } + // [#9719] The unscoped-multi shape check, BEFORE the matched-row read: + // a `multi: true` delete carrying no caller predicate at all dispatches + // ONCE, whole-operation-shaped, to the registrations that declared for + // it — so a shape-of-the-operation refusal (#4757) fires regardless of + // what the predicate would match, zero rows included. Read from the + // caller's RAW options — the same slot the handler contract reads + // (`input.options.where`, hook.zod.ts's upper-bound rule) — never from + // the AST, which middleware may have narrowed and only ever narrows. + // `where: {}` is a REAL (match-all) query and stays on the per-row + // authorize path; only an absent or `null` predicate is unscoped. + // `update()`'s predicate branch carries the identical check (#9974). + const rawWhere = (hookContext.input.options as { where?: unknown } | undefined)?.where; + if (rawWhere === undefined || rawWhere === null) { + await this.dispatchUnscopedMultiWriteHooks('beforeDelete', object, hookContext); + } + // [#5038/#5574] Read the doomed rows ONCE, before they are gone — the + // only moment their pre-image exists — and serve BOTH phases from it + // (D7). Gated on this object actually having delete-side hooks, so a + // bulk delete with none pays for no read. + const perRowBeforeHooks = this.hasHooksFor('beforeDelete', object); + const perRowAfterHooks = this.hasHooksFor('afterDelete', object); + if (perRowBeforeHooks || perRowAfterHooks) { + 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( + (await driver.find(object, ast, preOpts) as Record[]) ?? [], + declaredDeleteColumns, + ); + predicateMatchedRows = doomed; + // [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 (perRowAfterHooks) bulkPerRowRows = doomed; + // [D1] Zero matched rows is zero dispatches. + if (perRowBeforeHooks && doomed.length > 0) { + await this.dispatchPerRowBeforeHooks(object, 'beforeDelete', doomed, hookContext); + } + } + } + + // Every driver call below is handed `driverOptions` — the declared driver + // options and nothing else; `input.options` is the hooks' additive view. + const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); + + try { + let result; + // [#4639] See update()'s twin: recorded at the branch that chose the + // driver call, not inferred later from a missing id. + let isPredicateWrite = false; + if (isByIdDelete) { + // Honor referential delete behavior (cascade/set_null/restrict) + // for relations pointing at this record before removing it. + // + // [#7413] ONE UNIT OF WORK — the cascade and the parent's own row + // removal, or neither. These two statements used to run bare, and + // the cascade re-enters `this.delete()`/`this.update()` per + // dependent, each committing as it executed; a refusal partway + // (the `restrict` branch, a child's permission check, a later + // child's `beforeDelete` hook) stranded an arbitrary prefix of the + // children deleted while the caller got 409/403 and read it as + // "nothing happened". #4620's changeset already ruled the shape + // for the batch path: atomic honoured for real, or refused — a + // partial delete has no natural undo. + // + // The recursion COMPOSES rather than deadlocking because + // `transaction()` publishes its handle into the ambient `txStore` + // and joins an already-open one (ADR-0067 D2 / #5696): the child + // `delete()` calls below receive `trxContext` explicitly AND see + // the ambient entry, so a grandchild's own wrap JOINS with + // `owned: false` instead of opening a second driver transaction on + // a second connection. + // + // The driver options are rebuilt INSIDE the callback on purpose: + // the ones computed above were built before any transaction + // existed, so they carry no handle and the parent's own + // `driver.delete` would execute outside the very transaction + // wrapping its cascade. `buildDriverOptions` only fills keys that + // are still `undefined`, so re-running it adds the handle and + // changes nothing else. + // + // A dependent's stale-roll-up refusal stops the walk before this + // row is removed, so it is not this delete's answer: + // `cascadeStoppedRefusal` says what it is instead. + // + // [#30237, ADR-0148 D1] The recycle bin rides the same unit: the + // capture opens before the cascade (a retention defect refuses + // here, before any write), reads the collected set before the + // walk touches it, and writes the one entry after the walk and + // before this row goes. A removal that throws takes the entry + // with it: the transaction's rollback when one covers the bin, + // the capture's compensation otherwise. [#31630] A removal the + // driver answers as removing nothing withdraws the entry inside + // the same unit, so no entry stays for a row that is still live + // (`capture.ts` says why it is not written after instead). + // A caller's `multi: true` opens none, even here: the lifecycle + // sweep reaps by id with it. Nor does a permanent delete, which + // is the point of it. + // + // [#30237] The entry's id is told to the caller + // (`options.onRecycleBinEntry`) only once the unit has landed: + // after the transaction commits, never from inside it. + let binEntryId: string | undefined; + const runByIdDelete = async (writeContext?: ExecutionContext) => { + const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent); + await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected) + .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); + const entry = await bin?.write(); + try { + const removed = await driver.delete( + object, + hookContext.input.id as string, + this.buildDriverOptions(object, writeContext, hookContext.input.options as any), + ); + // Told only for a row the driver says it removed: `false` + // (not found) and an off-contract count of 0 (kept) name no + // deletion an undo could reverse, and their entry is + // withdrawn. + if (removed !== false && (removed as unknown) !== 0) binEntryId = entry?.id; + else await entry?.withdraw(); + return removed; + } catch (e) { + await entry?.compensate(); + throw e; + } + }; + // WHEN to open one is `planCascadeAtomicity`'s call — see there. + // `'none'` (nothing references this object) keeps the pre-#7413 + // path exactly, so a plain non-cascade delete opens no + // transaction and emits no degrade warning; `'split'` keeps it + // too, because a transaction on the default driver cannot cover a + // cross-datasource cascade and would refuse it outright. + const plan = this.planCascadeAtomicity(object); + if (plan === 'atomic') { + // No `require: true` — see the changeset. `delete()` never + // asked for atomicity, so it must not start REFUSING on a + // runtime that cannot roll back; `transaction()`'s declared + // degrade (ADR-0119 D1) already warns once per driver (#4619). + result = await this.transaction( + async (trxCtx: any) => await runByIdDelete(trxCtx as ExecutionContext), + opCtx.context, + ); + } else { + if (plan === 'split') this.warnCascadeNotAtomic(object); + result = await runByIdDelete(opCtx.context); + } + if (binEntryId !== undefined && typeof options?.onRecycleBinEntry === 'function') { + options.onRecycleBinEntry(binEntryId); + } + // [#27581] The handles the removed row held, off its pre-image. + deletedSecrets = deletedSecretSlots(deleteSchema, [priorRecord]); + } else { + // [#2982] The AST asserted present and already used for the + // pre-phase row read above. + // `deleteMany` presence is part of the ladder verdict resolved above. + // + // [#26871] A predicate delete honours `deleteBehavior` as the + // by-id branch does: a `restrict` refuses, a `cascade` (a + // `master_detail` by default) deletes the dependents, a + // `set_null` clears them. This arm used to go straight to + // `deleteMany`, so a flow's `delete_record` with `multi: true` + // skipped every declared rule the same delete done record by + // record honours. + // + // `planCascadeAtomicity` is the by-id branch's own question: + // `'none'` means no relation of the delete family points at + // this object, so the walk could write nothing and the arm keeps + // its single `deleteMany`, no rows read and no transaction. + // + // [#26950] A roll-up over this object needs the matched rows' + // foreign keys, read BEFORE the delete, to find the parents to + // recompute after it: the by-id branch hands `recomputeSummaries` + // its pre-image, and this arm hands it the matched rows. Only the + // descriptors' FK columns are read, through the composed AST and + // the write's driver options, and only once: the walk's own id + // read carries them below, and with no walk the per-row hook + // read serves when it was made. An object no roll-up aggregates + // reads nothing new. + const summaryKeyColumns = this.summaryForeignKeyColumns(object); + const plan = this.planCascadeAtomicity(object); + if (plan === 'none') { + if (summaryKeyColumns.length > 0) { + summaryPriorRows = predicateMatchedRows + ?? (((await driver.find(object, { ...opCtx.ast!, fields: summaryKeyColumns }, driverOptions)) ?? []) as Record[]); + } + // [#27581] The handles the matched rows hold, read BEFORE the + // statement removes them: the per-row hook read when it was + // made, otherwise only `id` and the secret columns, through + // this write's AST and options. No secret column, no read. + if (secretColumns.length > 0) { + deletedSecrets = deletedSecretSlots(deleteSchema, predicateMatchedRows + ?? (((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...secretColumns] }, driverOptions)) ?? []) as Record[])); + } + result = await driver.deleteMany!(object, opCtx.ast!, driverOptions); + } else { + // Otherwise: resolve the matched rows through the composed, + // row-scoped AST, run `cascadeDeleteRelations` once over them + // as one root set (#27004), then delete exactly those rows by + // id. By id, not by re-running the + // predicate: the walk's own writes (a `set_null` on a + // self-reference) can move a row into or out of the predicate, + // and the rows deleted must be the rows walked. The ids were + // read under this caller's scope inside the same unit of work, + // as the by-id branch deletes its id after reading its + // pre-image under that scope. The unit of work is the by-id + // branch's, for the same reasons (#7413). + const runPredicateDelete = async (writeContext?: ExecutionContext): Promise => { + const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any); + // [#27581] The same read carries the secret columns, so the + // handles released are those of the rows deleted. + const matched = ((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...summaryKeyColumns, ...secretColumns] }, writeOptions)) ?? []) as Array>; + const matchedIds = matched.map((row) => row?.id).filter((v): v is string | number => v != null); + if (summaryKeyColumns.length > 0) summaryPriorRows = withoutDeletedSelfParents(object, matched, matchedIds, this.getSummaryDescriptors(object)); + deletedSecrets = deletedSecretSlots(deleteSchema, matched); + // [#27004] One walk, rooted at the whole matched set. A + // dependent's stale-roll-up refusal is not this delete's + // answer, as in the by-id branch. + await this.cascadeDeleteRelations(object, matchedIds, writeContext) + .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); + // The id set rides an `$in`; batched so one statement never + // outgrows a driver's bind-parameter limit. + const batchSize = ObjectQL.REFERENCE_PROBE_BATCH; + let removed = 0; + for (let i = 0; i < matchedIds.length; i += batchSize) { + const batchAst: QueryAST = { object, where: { id: { $in: matchedIds.slice(i, i + batchSize) } } }; + const count = await driver.deleteMany!(object, batchAst, writeOptions); + // A non-count answer goes back as the driver gave it, so + // the `isDeleteResultShape` check below refuses it. + if (typeof count !== 'number') return count; + removed += count; + } + return removed; + }; + if (plan === 'atomic') { + result = await this.transaction( + async (trxCtx: any) => await runPredicateDelete(trxCtx as ExecutionContext), + opCtx.context, + ); + } else { + this.warnCascadeNotAtomic(object); + result = await runPredicateDelete(opCtx.context); + } + } + isPredicateWrite = true; + } + + hookContext.event = 'afterDelete'; + hookContext.result = result; + if (bulkPerRowRows) { + // [#5038] One dispatch per deleted row. No payload is passed, so + // each context carries `previous` = the deleted row and no + // `result`: after a delete there IS no post-state, and every + // consumer (hook `condition`, the record-change trigger, the audit + // diff) already falls back to the pre-image for `record` on a + // delete-shaped context. + for (const rowCtx of this.buildPerRowAfterContexts( + object, 'afterDelete', bulkPerRowRows, hookContext, + )) { + await this.triggerHooks('afterDelete', rowCtx); + } + } else { + await this.triggerHooks('afterDelete', hookContext); + } + + // [#16231] The `delete()` twin, on its own declaration: whether the + // by-id row was there (`boolean`), or how many rows a predicate + // delete removed (`number`). ⚠️ `false` and `0` are the two most + // ordinary answers this verb gives, so `isDeleteResultShape` is a + // pair of `typeof` tests and never a truthiness check — a lenient + // guard here would refuse exactly the answers + // `metadata-protocol`'s `deleteData` turns into its 404. + if (!isDeleteResultShape(hookContext.result)) { + throw new DeleteHookResultNotWriteShapeError({ + object, + event: 'afterDelete', + result: hookContext.result, + }); + } + + // [#27581] The delete is complete: release the handles the removed + // rows held, through the release a committed update uses, so each one + // goes only once storage confirms no row of its column still names it, + // inside this write's unit. After the `afterDelete` chain, so a hook + // can still dereference the value and a refusal that rolls the delete + // back never reaches here. + await this.releaseSecretHandles(object, deletedSecrets, opCtx.context, 'retired'); + + // Roll-up: recompute the parent summary now that the child is gone, + // from the row's FK values captured BEFORE deletion. [#5272] That + // capture is now the same single pre-image read `previous` rides on + // (it used to be its own later `findOne`), which is also what + // `update()` passes here. [#26950] A predicate delete passes the + // matched rows it read before the delete. + const summaryPrevious = priorRecord ?? summaryPriorRows; + const summaryFailures = summaryPrevious + ? await this.recomputeSummaries(object, null, summaryPrevious, opCtx.context) + : []; + + // Same split as update(): per-record `data.record.deleted` (#4626), + // or the aggregate `data.records.deleted` when the delete was by + // predicate (#4639). + if (this.realtimeService) { + if (isPredicateWrite) { + await this.publishBulkDataEvent('deleted', object, { + matched: result, + context: opCtx.context, + // [#15813] Same seam as the update branch. + tenantLayer0Verdict: opCtx.tenantLayer0Verdict, + }); + } else { + const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined; + await this.publishDataEvent('deleted', object, { + recordId: hookContext.input.id ?? resultId, + // [#14970] The pre-image — a delete has no post-state, and + // this branch is the by-id one, where `priorRecord` was read + // unconditionally by #7867's existence gate and proven + // non-null before `beforeDelete` ever fired. So the row is + // already in hand and NO new read is bought here. + organizationRow: priorRecord, + context: opCtx.context, + }); + } + } + + // The record IS deleted; a summary that could not recompute after + // retries must surface, not stay silent (framework#3147). + if (summaryFailures.length > 0) throw new SummaryRecomputeError(summaryFailures, hookContext.result); + return hookContext.result; + } catch (e) { + // [#7307] `Error.message` is now the END USER's localized sentence for + // a `DELETE_RESTRICTED`, and the logger serializes only `message` + + // `stack` — so without this the operator-facing half (API names, the + // `deleteBehavior:'cascade'` remedy) would reach no channel at all, + // and the server log of a zh-CN deployment would read in Chinese. An + // error that carries no `developerMessage` logs exactly as before. + // [#8682] Same redaction as the insert/update loggers. A DELETE's + // statement carries the caller's values in its `where` clause — which + // is how a record is addressed, so it is the same class of payload. + // `developerMessage` is read off the ORIGINAL error: it is written by + // our own throw sites (#7307), never by a driver, so it carries no + // statement and the redaction has no opinion about it. + // [#17052] The third write door, moved with its two siblings: this + // catch also ends in `throw e`, so the caller is told and the entry + // is not a degradation report. `developerMessage` keeps its place in + // the meta and the redaction is unchanged. + const devDetail = (e as any)?.developerMessage; + this.logger.warn( + 'Delete operation failed', + writeFailureLogMeta(redactBoundStatement(e), { + object, + ...(typeof devDetail === 'string' && devDetail.length > 0 ? { developerMessage: devDetail } : {}), + }), + ); + throw e; + } + }); + + return opCtx.result; + } + /** The body of `ObjectQL#assertNoInternalFieldEvaluated`; the method's docblock there is its contract. */ static assertNoInternalFieldEvaluated(this: Pick, object: string, query: InternalFieldEvaluationQuery, options?: InternalFieldEvaluationOptions): void { assertNoInternalFieldEvaluated(object, query, this.relatedSchemaOf, options); diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 07a6e2c0881..f7d9b9c5717 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -62,8 +62,6 @@ import { publishBulkDataEvent, publishDataEvent } from './engine-realtime-publis // [#25522 cut 5] The secret and internal-field bodies; the methods of the same // names below hand each body the members it reads (`SecretInternalFieldsHost`). import { - deletedSecretColumns, - deletedSecretSlots, encryptSecretFields, maskSecretFields, omitInternalFields, @@ -84,7 +82,7 @@ import { // [#30237, ADR-0148] The recycle bin's write side: the capture body, and the // retention seam the host hands over (`RecycleBinCaptureHost`). import { openRecycleBinCapture, type RecycleBinCapture } from './recycle-bin/capture.js'; -import { emptyRecycleBin, purgeRecycleBinEntry, readPermanentDelete, type RecycleBinRemovalOptions } from './recycle-bin/purge.js'; +import { emptyRecycleBin, purgeRecycleBinEntry, type RecycleBinRemovalOptions } from './recycle-bin/purge.js'; import type { RecycleBinRetentionSettings } from './recycle-bin/retention.js'; import { restoreRecycleBinEntry, type RecycleBinRestoreOptions, type RecycleBinRestoreResult } from './recycle-bin/restore.js'; import { listRecycleBin, type RecycleBinDeleteObservability, type RecycleBinListOptions, type RecycleBinListResult } from './recycle-bin/list.js'; @@ -143,10 +141,9 @@ import { recordNotFoundError, } from '@objectstack/core'; import { WriteEpoch } from './write-epoch.js'; -import { SummaryRecomputeError, cascadeStoppedRefusal, type SummaryRecomputeFailure } from './summary-errors.js'; +import { SummaryRecomputeError, type SummaryRecomputeFailure } from './summary-errors.js'; import { TransactionUnsupportedError } from './transaction-errors.js'; import { - withoutDeletedSelfParents, type SummaryDescriptor, } from './summary-aggregate.js'; import { refreshSummariesExtendedBy, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js'; @@ -154,9 +151,7 @@ import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js'; import { HookTargetRebindError } from './hook-target-rebind-errors.js'; import { isUpdateResultShape, - isDeleteResultShape, UpdateHookResultNotWriteShapeError, - DeleteHookResultNotWriteShapeError, } from './verb-hook-result-shape.js'; import { DriverConnectError, @@ -314,11 +309,6 @@ import { composeReadableIdsChain, findUnservableControlledByParentMasters, permi // evaluation order is what it was. // [#28001] …and the object-level closure of that walk the metadata read serves. import { collectCascadeDeleteSet, deleteRestrictedError, recordReferenceCheckElevation, referenceProbeFilter, refuseRestrictsInsideOwnCascade } from './engine-delete-cascade.js'; -import { - resolveEngineDeleteDispatch, - ENGINE_DELETE_REJECT_MESSAGE, - type EngineDeleteDispatchInput, -} from './engine-delete-dispatch.js'; import { resolveEngineUpdateDispatch, ENGINE_UPDATE_REJECT_MESSAGE, @@ -344,15 +334,14 @@ import { } from './integrity/dangling-reference-audit.js'; // [#29986 codemod] The top-level declarations that moved whole to `engine-top-level.ts`, as this file still reads them. import { - DISPATCHABLE_HOOK_EVENTS, ENGINE_DELETE_OPTION_KEYS, ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, - SECURITY_SERVICE_SOURCE_SLOT, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, assertDispatchableHookEvent, + DISPATCHABLE_HOOK_EVENTS, ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, SECURITY_SERVICE_SOURCE_SLOT, + WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, assertDispatchableHookEvent, assertValidHookExcludeObjects, autonumberFieldNames, callerKeySets, callerSuppliedRow, computeStoredExpressions, declaredDatetimeLowering, droppedFieldEvents, foldEngineOptionAliases, handBackWithheldInsertReadonly, - hydrateWriteFormulas, insertStaticReadonlySubject, lowerWhereFilterArray, masterIdOf, - organizationPredicateDeleteRefusal, planStoredExpressions, recomputeAutonumberReaders, rejectUnknownEngineOptions, - replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, - storedExpressionsReading, stripComputedWriteFields, undeclaredWriteFieldErrors, updateStaticReadonlySubject, - withholdInsertReadonlyFromHooks, writeFailureLogMeta, + hydrateWriteFormulas, insertStaticReadonlySubject, lowerWhereFilterArray, masterIdOf, planStoredExpressions, + recomputeAutonumberReaders, rejectUnknownEngineOptions, replacedStoredExpressionFields, settleBulkStoredExpressions, + shouldSkipStateMachine, staticReadonlyStoredView, storedExpressionsReading, stripComputedWriteFields, + undeclaredWriteFieldErrors, updateStaticReadonlySubject, withholdInsertReadonlyFromHooks, writeFailureLogMeta, } from './engine-top-level.js'; import type { AdmittedValueShapeViolationTally, AutonumberReaders, CascadeDeleteSet, CascadeIssuedDelete, DatasourceDef, @@ -8588,739 +8577,9 @@ export class ObjectQL implements IObjectQLEngine { return CascadePlanningFacet.organizationOwnedRowCounts.call(cascadePlanningHost.of(this), organizationId, options); } - async delete(object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { - object = this.resolveObjectName(object); - // [#22782] An aborting `afterDelete` rolls this write back — see `opensAfterAbortUnit`. - if (this.opensAfterAbortUnit('afterDelete', object, options?.context)) { - return this.inAfterAbortUnit(() => this.delete(object, options)); - } - this.logger.debug('Delete operation starting', { object }); - this.assertWriteAllowed(object, 'delete'); - // [#8844] See the insert face — deleting the install's only organization - // must not leave the memo answering with it. - if (object === ORGANIZATION_OBJECT) this.invalidateOrganizationProbe(); - const driver = this.getDriver(object); - // [#5351/#5696] Same-origin gate: refuse a cross-driver BUSINESS write, - // carve an append-only system ledger out of the transaction. Before any - // hook, default or validation runs, so a refusal costs nothing. - this.enforceTransactionOrigin(object, driver, 'delete'); - - // Fold the `filter` alias into `where` first — same reasoning as update() - // above (#4346): unfolded, a `multi: true` delete with `{ filter }` had no - // predicate on its AST and emptied the table. - options = foldEngineOptionAliases(object, 'delete', options, ENGINE_WHERE_SLOTS); - rejectUnknownEngineOptions(object, 'delete', options, ENGINE_DELETE_OPTION_KEYS); - // [#5158] Same ordering reason as update(): the dispatch decision below - // reads `where.id`, which an unlowered array never carries. - options = lowerWhereFilterArray(object, 'delete', options, this._registry.getObject(object), this.relatedSchemaOf); - // [ADR-0100] Same credential-column refusal as update(). - rejectCredentialEvaluation(object, 'delete', options, options?.context, this.relatedSchemaOf); - - // Expand `{filter-placeholder}` values before the id is extracted — same - // reasoning as update() above (#3810). - // [ADR-0053 D-D1, amended — #5930] …and lowered in the same stage. - options = await this.withResolvedWhere(object, 'delete', options, declaredDatetimeLowering(this._registry.getObject(object))); - - // Extract ID logic mirroring update(): only a SCALAR `where.id` means - // "delete one row by primary key". An operator object ({ $in: [...] }, …) - // is a multi-row predicate — treating it as an id would bind the object - // literally (driver.delete(object, {$in:[…]})) and both skip the #2982 AST - // seeding below AND bypass the by-id RLS pre-image check. Leave `id` - // undefined so the call routes to deleteMany with the scoped AST. - // - // [#4550] The decision lives in `engine-delete-dispatch.ts` so the fake - // engines that stand in for this method import it instead of re-deriving - // it. #4434 shipped a dead REST route green because plugin-sharing's fake - // accepted the one shape the `reject` branch below refuses; a double that - // reads THIS predicate cannot be looser than this method. - const dispatch = resolveEngineDeleteDispatch(options as EngineDeleteDispatchInput | undefined); - const id: any = dispatch.kind === 'by-id' ? dispatch.id : undefined; - // [#30237, ADR-0148, Q3 = A] A permanent delete writes no recycle-bin entry - // and is authorized as `purge`, the recycle-bin manager's verb. Refused here, - // before any middleware or hook, unless it is a by-id delete of an object - // the bin takes (see `readPermanentDelete`). - 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); - - const opCtx: OperationContext = { - object, - operation: permanent ? 'purge' : 'delete', - options, - context: options?.context, - }; - - // [#2982] Same seam as update: a no-single-id delete routes to - // `driver.deleteMany` with an AST that used to be rebuilt from - // `options.where` after the middleware chain, discarding any row-scoping a - // middleware composed onto `opCtx.ast`. Seed the caller's predicate before - // the chain, keyed on the SAME falsy-`id` test the multi branch dispatches - // on; the multi branch consumes the composed result. - if (!id) { - opCtx.ast = { object, ...(options?.where !== undefined ? { where: options.where } : {}) } as QueryAST; - } - - await this.executeWithMiddleware(opCtx, async () => { - // [ADR-0139 D1] As in `update`: a leaf the middleware chain wrote into a - // delete's predicate is refused at the executor's entry, before the - // pre-image reads reach the driver. - collectComposableReadableIds(object, 'delete', opCtx.ast?.where, 'where'); - const hookContext: HookContext = { - object, - event: 'beforeDelete', - input: { id, options: opCtx.options }, - session: this.buildSession(opCtx.context), - provenance: this.buildProvenance(opCtx.context), - // [#23221] The declared cascade-delete marker, the delete twin of - // `update()`'s `referentialFieldClear` spread: conditional for the - // same reason, "absent unless true". Bound once on this context, - // which `afterDelete` reuses, so both phases carry it. - ...(referentialCascadeDelete ? { referentialCascadeDelete: true as const } : {}), - user: this.buildUser(opCtx.context), - api: this.buildHookApi(opCtx.context), - transaction: opCtx.context?.transaction, - ql: this - }; - - // [#5272] The pre-image of the row this delete is about to remove. - // - // `HookContext.previous` is documented — in the spec, since it was - // written — as "the state of the record BEFORE the operation (for - // update/delete)", and `update()` has bound it all along. `delete()` - // never did: `previous` was `undefined` in `beforeDelete` AND in - // `afterDelete`, so a legal, contract-shaped delete-side transition - // condition (`previous.status == "done"`) was unevaluable — and since - // #4775 unevaluable REJECTS the operation. Worse, it was reported - // through the generic branch, which reads as "you misspelled a key" - // when the key was fine and the engine simply never bound it (#5037's - // shape, one path over). - // - // #5038 made the asymmetry visible from the other side: a predicate - // bulk delete already binds each doomed row's own pre-image on its - // per-row `afterDelete`, so the SINGLE-record path was strictly worse - // than the bulk one — the exact inversion #4800/#4862 ruled against. - // - // Demand-driven, like `update()`'s `priorRecord`: read only when - // something on this object actually consumes it — - // * a delete-side hook, EITHER phase (its `condition` may read - // `previous`; its handler — plugin-audit, the record-change - // trigger — reads `ctx.previous` directly); - // * a roll-up summary aggregating this object, which needs the - // doomed row's FK value to find the parent to recompute. - // Those two used to be separate reads at separate times (the summary - // one fetched only after `beforeDelete` had run); they are ONE read - // now — and a RAW driver read, which is exactly what `update()` - // already hands `recomputeSummaries` as its `previous` argument, so - // the two write paths now agree on what a pre-image is. - // - // `needsPriorRecord(schema)` is deliberately NOT part of this gate - // even though `update()`'s twin carries it: object validation rules - // are evaluated on insert/update only — `delete()` evaluates none — - // so including it would buy a read with no reader. - // - // Read BEFORE `beforeDelete` fires. A delete's `before` phase is the - // one that has nothing else to look at (its `input` carries an id and - // no data), and the pre-image has to be taken before the row is gone - // either way, so a single read serves both phases. - // - // [#5574] The same read now serves the PER-ROW `beforeDelete` dispatch on - // the predicate path — see the pre-phase below. `delete()` was already - // the right shape here; what changed is that the predicate branch grew - // the same discipline the by-id branch has had since #5272. - // - // [#5929] The gate's THREE terms, unchanged by that card and enumerated - // here because it had to enumerate them to answer it: - // 1. `hasHooksFor('beforeDelete', object)` - // 2. `hasHooksFor('afterDelete', object)` - // 3. `getSummaryDescriptors(object).length > 0` - // No validation term, deliberately — see `needsPriorRecord` above. - // - // What #5929 changed is not this expression but what term 1 MEANS. Until - // then, objectql's own `ObjectQLPlugin` registered a builtin - // `sys_fetch_previous_delete` on `beforeDelete` with `object: '*'`, so on - // every kernel-hosted engine term 1 was true for every object and the - // per-object skip this gate exists to perform could never happen. The - // builtin's only remaining effect WAS holding this gate open: the read - // below binds `previous` before `beforeDelete` dispatches, so its own - // `!ctx.previous` guard was already unreachable. Retiring it (plugin.ts, - // ADR-0049 enforce-or-remove) makes term 1 an honest question. - // - // ⚠️ Honest is not the same as usually-false, and the difference is worth - // knowing before anyone reads a skip into a production trace. Every - // delete-phase hook below registers with NO `object` — global — so each - // holds term 1 or term 2 open for every object on a kernel that loads it: - // - // * `plugin-auth` identity-write-guard beforeDelete (filters by - // `isManaged(ctx.object)` inside the handler) - // * `plugin-sharing` record-share-cascade before+afterDelete (filters - // by `targets(objectName)` inside the handler) - // * `service-storage` file-reference-lifecycle before+afterDelete - // (filters by `activeFileFields(object)` inside) - // * `plugin-audit` writeAudit afterDelete only — #6656 retired - // `captureBefore`, which was its `beforeDelete` half, - // so it holds term 2 open and no longer term 1; - // global MINUS `excludeObjects: AUDIT_EXCLUDED_OBJECTS` - // (#5860) — the one that narrows at the ENGINE face, - // so `hookMatchesObject` can subtract it and an - // excluded object really does skip this read. - // - // The first three are real handlers with real work, merely deciding their - // own applicability at dispatch time rather than at registration time; - // this gate answering "yes" for them is the gate WORKING, not a second - // instance of the #5929 defect. Narrowing any of them to the objects it - // actually serves — plugin-audit's `excludeObjects` face is the worked - // example — is what would convert them into skips, and that is each - // package's own card, not this one's. - // [#7867] ⚠️ RETIRED — the three-term `wantsPreImage` gate the paragraphs - // above describe is GONE, and the paragraphs are kept because what they - // record (which registrants hold which term open, and why an honest gate - // is not the same as a usually-false one) is still the reason the removal - // costs nothing measurable. - // - // It asked "does anything CONSUME the pre-image?" and skipped the read - // when nothing did. Existence is a consumer it never counted — and it is - // the one consumer EVERY by-id delete has, because a delete against an id - // that names no row must answer 404 rather than run. So the by-id branch - // below reads the pre-image unconditionally and gates on it; the - // predicate branch reads its doomed rows under its own `perRowBefore/ - // AfterHooks` gate, which is untouched. On any kernel loading the global - // registrants enumerated above, term 1 or 2 was already true for every - // object, so this skipped nothing there anyway; the read becomes - // genuinely new only for a bare embedder whose object has no delete-side - // hook and no roll-up — and that embedder is buying a 404 it did not have. - // - // ⛔ Do not reintroduce it as a guard around the by-id read. A gate on - // whether to LOOK is not compatible with a rule about what to do when - // nothing is there. See `update()`'s twin. - // - // [#7933] The first three entries were carried here UNVERIFIED when - // #7707 corrected the `plugin-audit` one, which was wrong on BOTH halves - // — hook name and term. All three have since been read against the - // function that binds them — `registerIdentityWriteGuard`, - // `bindRecordShareCascade`, `installFileReferenceHooks` — and all three - // match what is claimed above: same events, same object-less - // registration, same in-handler filter. Nothing above needed changing. - // That audit is what the retirement note's "term 1 or 2 was already true - // for every object" stands on, so it is recorded here rather than left - // in a closed issue: the enumeration outlived the gate it was written - // for, and it is now load-bearing for a different claim than the one it - // was written to support. - const deleteSchema = this._registry.getObject(object); - // `buildDriverOptions` is what carries the open transaction and the - // tenant scope onto a raw driver read. Skipping it here would read - // outside this write's transaction and across the tenant boundary — - // `update()`'s prior read passes the same bag for the same reason. - // [#21613] Both pre-image reads below are shaped to the declared field - // set, as `update()`'s are: the pre-image is the delete's `previous`, and - // the audit ledger records it whole as the delete's `old_value`, so a - // column no metadata declares reached that served row with its value. - const declaredDeleteColumns = declaredColumnSet(deleteSchema); - const readPreImage = async (targetId: unknown): Promise | null> => { - const preAst: QueryAST = { object, where: { id: targetId }, limit: 1 }; - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); - return withDeclaredColumnsOnly( - (await driver.findOne(object, preAst, preOpts)) as Record | null, - declaredDeleteColumns, - ); - }; - const bindPreImage = (row: Record | null): void => { - // Never fabricate: a row that is not there leaves `previous` UNBOUND - // rather than `{}`/`null`, so a condition reading it faults loudly - // instead of answering for a record nobody read (#4649/#4775). - hookContext.previous = row ? (coerceBooleanFields(deleteSchema as any, row as any) as any) : undefined; - }; - let priorRecord: Record | null = null; - // [#5038] Matched rows for the per-row `afterDelete` dispatch — see the - // twin in update(). A bulk delete is N record changes too, so a - // `record-after-delete` flow must see each deleted row rather than one - // context that names none of them. - let bulkPerRowRows: Record[] | null = null; - // [#26950] The predicate path's matched rows as the per-row hook read - // below took them (`null` when no delete-side hook asked for them), and - // the rows whose foreign keys `recomputeSummaries` is handed after the - // delete (`null` when no roll-up aggregates this object). - let predicateMatchedRows: Record[] | null = null; - let summaryPriorRows: Record[] | null = null; - // [#27581] The `secret` columns this object declares, and the handles the - // removed rows held in them: the by-id pre-image, or the predicate - // path's matched rows, read before the statement takes them away. - const secretColumns = deletedSecretColumns(deleteSchema); - let deletedSecrets: SecretHandleSlot[] = []; - - // [#5574] The dispatch ladder, resolved BEFORE the before phase — see - // update()'s twin for the full reasoning. Keyed on the SAME falsy-`id` - // test the #2982 AST seed above uses. - const isByIdDelete = Boolean(id); - // [#11009] Keyed on the LADDER's verdict, not on `options?.multi` — the - // update twin says why; for every pre-#11009 input the two spellings - // agree. - const isPredicatePath = !isByIdDelete && dispatch.kind === 'multi' && typeof driver.deleteMany === 'function'; - // [#24948] An organization is deleted by id or not at all: plugin-auth's - // organization delete refuses one that still owns records and removes its - // auth structure per organization, which a predicate delete would skip - // (see `organizationPredicateDeleteRefusal`). Any delete not by id is - // refused here, whatever the driver offers, before any hook or write. - if (!isByIdDelete && object === ORGANIZATION_OBJECT) { - throw organizationPredicateDeleteRefusal(); - } - if (!isByIdDelete && !isPredicatePath) { - // [#4550] The `reject` verdict of resolveEngineDeleteDispatch. It used - // to be re-asked after the before phase because a hook could still bind - // the id; with the ladder resolved first there is no such conversion. - // - // [#11009] The dispatch's OWN message — the unhonoured-predicate - // refusal names the dropped `where` keys; the classic shape keeps - // `ENGINE_DELETE_REJECT_MESSAGE`; the fallback arm is a `multi` - // verdict against a driver with no `deleteMany`. - if (dispatch.kind === 'reject') throw new Error(dispatch.message); - // [#27277] See update()'s twin: a floored plugin driver offers no `deleteMany`. - if (isExternalDriverFloor(driver)) throw externalPredicateWriteRefusal(driver.name, object, 'delete'); - throw new Error(ENGINE_DELETE_REJECT_MESSAGE); - } - - // [#6966] See update()'s twin — same rule, same single binding point. - hookContext.dispatch = { - mode: isPredicatePath ? 'per-row' : 'record', - index: 0, - scope: {}, - }; - - if (isByIdDelete) { - // [#7867] Read first, then GATE — the twin of `update()`'s, and #5138's - // own record names `delete` as the worst of the three when the gate was - // missing: "the delete ran and the answer was `200 { deleted: true }` - // for any string in the path, so a typo'd id, an already-deleted row - // and a real deletion were indistinguishable" — the shape #4435 removed - // from `protocol.deleteData` and #5138 removed from `callData`, still - // live here on the path an action body's `.delete()` actually takes. - // - // The pre-image is the only honest place to ask. `IDataDriver.delete` - // does declare `Promise` ("true if deleted, false if not - // found"), so the answer exists downstream — but downstream is AFTER - // `beforeDelete` has dispatched and after `cascadeDeleteRelations` has - // run, i.e. after handlers have fired and children have been touched - // for a parent that was never there. `IDataEngine.delete` also declares - // `Promise` and passes its driver's result through the hook chain, - // so testing it for `=== false` here would read a signal this layer's - // contract does not promise — #5138's argument, unchanged. - priorRecord = await readPreImage(id); - if (!priorRecord) throw recordNotFoundError(object, id); - // Bound unconditionally now that the row is proven present. - // `bindPreImage`'s never-fabricate rule (#4649/#4775) is unchanged and - // still the reason the binding goes through it rather than around it. - bindPreImage(priorRecord); - await this.triggerHooks('beforeDelete', hookContext); - // [#6752] The retired lever, refused — the `update()` twin's check, - // verbatim, because the rule is now ONE rule: a by-id target is - // immutable in a `before*` handler. - // - // Both halves of it used to be answered separately here. CLEARING the - // id was already refused (ADR-0058 Amendment II.1): it worked by - // falling through to the predicate branch, and the ladder is now - // resolved before any handler runs, so there is no ladder left to - // re-enter. REBINDING to another id was still HONOURED, by re-reading - // the new target's pre-image and rebinding `previous` (#5272) so - // nothing stale reached `afterDelete` or the summary recompute. - // - // The 2026-08-09 ruling on #6752 retires that second half. #5272's - // mechanism was internally correct — that is not what was weighed. What - // was weighed: the measured compatibility cost is zero (no consumer in - // the repository repoints), one rule across both verbs beats two - // individually-correct rules an author has to memorize, and a hook that - // silently redirects WHICH ROW GETS DELETED is a top-grade footgun for - // authored — especially AI-authored — handlers. Correctness of the - // mechanism does not justify the surface. - // - // ⛔ Route 3 (growing the same re-resolution for `update()`) stays - // excluded by #5574's ruling: "do not silently pick re-resolution - // instead". The alignment goes the other way, and this is that edit. - // - // The re-read that used to sit here is GONE, not merely bypassed: its - // guard was `input.id !== id && input.id`, which is exactly the case - // this refusal now throws on, so it became unreachable. `readPreImage` - // survives for the pre-dispatch read above — the only read left. A - // handler writing back the SAME id is untouched, as on `update()`. - if (hookContext.input.id !== id) { - throw new HookTargetRebindError({ - object, event: 'beforeDelete', path: 'by-id', - expectedId: id, observedId: hookContext.input.id, - }); - } - } else { - // [#2982] Consume the middleware-composed AST seeded above so the - // injected row-scoping binds every read AND the delete. Fail CLOSED if - // it is absent rather than rebuilding an unscoped `{ object, where }` - // (AGENTS.md PD #12). - const ast = opCtx.ast; - if (!ast) { - throw new Error( - `[Security] Refusing bulk delete on '${object}': row-scoping AST was not seeded ` + - `(the predicate branch was reached without the AST seeded before the middleware ` + - `chain — the one RLS and sharing compose their row-scoping onto, so that a bulk ` + - `write reaches only the rows this caller may edit).`, - ); - } - // [#9719] The unscoped-multi shape check, BEFORE the matched-row read: - // a `multi: true` delete carrying no caller predicate at all dispatches - // ONCE, whole-operation-shaped, to the registrations that declared for - // it — so a shape-of-the-operation refusal (#4757) fires regardless of - // what the predicate would match, zero rows included. Read from the - // caller's RAW options — the same slot the handler contract reads - // (`input.options.where`, hook.zod.ts's upper-bound rule) — never from - // the AST, which middleware may have narrowed and only ever narrows. - // `where: {}` is a REAL (match-all) query and stays on the per-row - // authorize path; only an absent or `null` predicate is unscoped. - // `update()`'s predicate branch carries the identical check (#9974). - const rawWhere = (hookContext.input.options as { where?: unknown } | undefined)?.where; - if (rawWhere === undefined || rawWhere === null) { - await this.dispatchUnscopedMultiWriteHooks('beforeDelete', object, hookContext); - } - // [#5038/#5574] Read the doomed rows ONCE, before they are gone — the - // only moment their pre-image exists — and serve BOTH phases from it - // (D7). Gated on this object actually having delete-side hooks, so a - // bulk delete with none pays for no read. - const perRowBeforeHooks = this.hasHooksFor('beforeDelete', object); - const perRowAfterHooks = this.hasHooksFor('afterDelete', object); - if (perRowBeforeHooks || perRowAfterHooks) { - 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( - (await driver.find(object, ast, preOpts) as Record[]) ?? [], - declaredDeleteColumns, - ); - predicateMatchedRows = doomed; - // [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 (perRowAfterHooks) bulkPerRowRows = doomed; - // [D1] Zero matched rows is zero dispatches. - if (perRowBeforeHooks && doomed.length > 0) { - await this.dispatchPerRowBeforeHooks(object, 'beforeDelete', doomed, hookContext); - } - } - } - - // Every driver call below is handed `driverOptions` — the declared driver - // options and nothing else; `input.options` is the hooks' additive view. - const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); - hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); - - try { - let result; - // [#4639] See update()'s twin: recorded at the branch that chose the - // driver call, not inferred later from a missing id. - let isPredicateWrite = false; - if (isByIdDelete) { - // Honor referential delete behavior (cascade/set_null/restrict) - // for relations pointing at this record before removing it. - // - // [#7413] ONE UNIT OF WORK — the cascade and the parent's own row - // removal, or neither. These two statements used to run bare, and - // the cascade re-enters `this.delete()`/`this.update()` per - // dependent, each committing as it executed; a refusal partway - // (the `restrict` branch, a child's permission check, a later - // child's `beforeDelete` hook) stranded an arbitrary prefix of the - // children deleted while the caller got 409/403 and read it as - // "nothing happened". #4620's changeset already ruled the shape - // for the batch path: atomic honoured for real, or refused — a - // partial delete has no natural undo. - // - // The recursion COMPOSES rather than deadlocking because - // `transaction()` publishes its handle into the ambient `txStore` - // and joins an already-open one (ADR-0067 D2 / #5696): the child - // `delete()` calls below receive `trxContext` explicitly AND see - // the ambient entry, so a grandchild's own wrap JOINS with - // `owned: false` instead of opening a second driver transaction on - // a second connection. - // - // The driver options are rebuilt INSIDE the callback on purpose: - // the ones computed above were built before any transaction - // existed, so they carry no handle and the parent's own - // `driver.delete` would execute outside the very transaction - // wrapping its cascade. `buildDriverOptions` only fills keys that - // are still `undefined`, so re-running it adds the handle and - // changes nothing else. - // - // A dependent's stale-roll-up refusal stops the walk before this - // row is removed, so it is not this delete's answer: - // `cascadeStoppedRefusal` says what it is instead. - // - // [#30237, ADR-0148 D1] The recycle bin rides the same unit: the - // capture opens before the cascade (a retention defect refuses - // here, before any write), reads the collected set before the - // walk touches it, and writes the one entry after the walk and - // before this row goes. A removal that throws takes the entry - // with it: the transaction's rollback when one covers the bin, - // the capture's compensation otherwise. [#31630] A removal the - // driver answers as removing nothing withdraws the entry inside - // the same unit, so no entry stays for a row that is still live - // (`capture.ts` says why it is not written after instead). - // A caller's `multi: true` opens none, even here: the lifecycle - // sweep reaps by id with it. Nor does a permanent delete, which - // is the point of it. - // - // [#30237] The entry's id is told to the caller - // (`options.onRecycleBinEntry`) only once the unit has landed: - // after the transaction commits, never from inside it. - let binEntryId: string | undefined; - const runByIdDelete = async (writeContext?: ExecutionContext) => { - const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent); - await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected) - .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); - const entry = await bin?.write(); - try { - const removed = await driver.delete( - object, - hookContext.input.id as string, - this.buildDriverOptions(object, writeContext, hookContext.input.options as any), - ); - // Told only for a row the driver says it removed: `false` - // (not found) and an off-contract count of 0 (kept) name no - // deletion an undo could reverse, and their entry is - // withdrawn. - if (removed !== false && (removed as unknown) !== 0) binEntryId = entry?.id; - else await entry?.withdraw(); - return removed; - } catch (e) { - await entry?.compensate(); - throw e; - } - }; - // WHEN to open one is `planCascadeAtomicity`'s call — see there. - // `'none'` (nothing references this object) keeps the pre-#7413 - // path exactly, so a plain non-cascade delete opens no - // transaction and emits no degrade warning; `'split'` keeps it - // too, because a transaction on the default driver cannot cover a - // cross-datasource cascade and would refuse it outright. - const plan = this.planCascadeAtomicity(object); - if (plan === 'atomic') { - // No `require: true` — see the changeset. `delete()` never - // asked for atomicity, so it must not start REFUSING on a - // runtime that cannot roll back; `transaction()`'s declared - // degrade (ADR-0119 D1) already warns once per driver (#4619). - result = await this.transaction( - async (trxCtx: any) => await runByIdDelete(trxCtx as ExecutionContext), - opCtx.context, - ); - } else { - if (plan === 'split') this.warnCascadeNotAtomic(object); - result = await runByIdDelete(opCtx.context); - } - if (binEntryId !== undefined && typeof options?.onRecycleBinEntry === 'function') { - options.onRecycleBinEntry(binEntryId); - } - // [#27581] The handles the removed row held, off its pre-image. - deletedSecrets = deletedSecretSlots(deleteSchema, [priorRecord]); - } else { - // [#2982] The AST asserted present and already used for the - // pre-phase row read above. - // `deleteMany` presence is part of the ladder verdict resolved above. - // - // [#26871] A predicate delete honours `deleteBehavior` as the - // by-id branch does: a `restrict` refuses, a `cascade` (a - // `master_detail` by default) deletes the dependents, a - // `set_null` clears them. This arm used to go straight to - // `deleteMany`, so a flow's `delete_record` with `multi: true` - // skipped every declared rule the same delete done record by - // record honours. - // - // `planCascadeAtomicity` is the by-id branch's own question: - // `'none'` means no relation of the delete family points at - // this object, so the walk could write nothing and the arm keeps - // its single `deleteMany`, no rows read and no transaction. - // - // [#26950] A roll-up over this object needs the matched rows' - // foreign keys, read BEFORE the delete, to find the parents to - // recompute after it: the by-id branch hands `recomputeSummaries` - // its pre-image, and this arm hands it the matched rows. Only the - // descriptors' FK columns are read, through the composed AST and - // the write's driver options, and only once: the walk's own id - // read carries them below, and with no walk the per-row hook - // read serves when it was made. An object no roll-up aggregates - // reads nothing new. - const summaryKeyColumns = this.summaryForeignKeyColumns(object); - const plan = this.planCascadeAtomicity(object); - if (plan === 'none') { - if (summaryKeyColumns.length > 0) { - summaryPriorRows = predicateMatchedRows - ?? (((await driver.find(object, { ...opCtx.ast!, fields: summaryKeyColumns }, driverOptions)) ?? []) as Record[]); - } - // [#27581] The handles the matched rows hold, read BEFORE the - // statement removes them: the per-row hook read when it was - // made, otherwise only `id` and the secret columns, through - // this write's AST and options. No secret column, no read. - if (secretColumns.length > 0) { - deletedSecrets = deletedSecretSlots(deleteSchema, predicateMatchedRows - ?? (((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...secretColumns] }, driverOptions)) ?? []) as Record[])); - } - result = await driver.deleteMany!(object, opCtx.ast!, driverOptions); - } else { - // Otherwise: resolve the matched rows through the composed, - // row-scoped AST, run `cascadeDeleteRelations` once over them - // as one root set (#27004), then delete exactly those rows by - // id. By id, not by re-running the - // predicate: the walk's own writes (a `set_null` on a - // self-reference) can move a row into or out of the predicate, - // and the rows deleted must be the rows walked. The ids were - // read under this caller's scope inside the same unit of work, - // as the by-id branch deletes its id after reading its - // pre-image under that scope. The unit of work is the by-id - // branch's, for the same reasons (#7413). - const runPredicateDelete = async (writeContext?: ExecutionContext): Promise => { - const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any); - // [#27581] The same read carries the secret columns, so the - // handles released are those of the rows deleted. - const matched = ((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...summaryKeyColumns, ...secretColumns] }, writeOptions)) ?? []) as Array>; - const matchedIds = matched.map((row) => row?.id).filter((v): v is string | number => v != null); - if (summaryKeyColumns.length > 0) summaryPriorRows = withoutDeletedSelfParents(object, matched, matchedIds, this.getSummaryDescriptors(object)); - deletedSecrets = deletedSecretSlots(deleteSchema, matched); - // [#27004] One walk, rooted at the whole matched set. A - // dependent's stale-roll-up refusal is not this delete's - // answer, as in the by-id branch. - await this.cascadeDeleteRelations(object, matchedIds, writeContext) - .catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); }); - // The id set rides an `$in`; batched so one statement never - // outgrows a driver's bind-parameter limit. - const batchSize = ObjectQL.REFERENCE_PROBE_BATCH; - let removed = 0; - for (let i = 0; i < matchedIds.length; i += batchSize) { - const batchAst: QueryAST = { object, where: { id: { $in: matchedIds.slice(i, i + batchSize) } } }; - const count = await driver.deleteMany!(object, batchAst, writeOptions); - // A non-count answer goes back as the driver gave it, so - // the `isDeleteResultShape` check below refuses it. - if (typeof count !== 'number') return count; - removed += count; - } - return removed; - }; - if (plan === 'atomic') { - result = await this.transaction( - async (trxCtx: any) => await runPredicateDelete(trxCtx as ExecutionContext), - opCtx.context, - ); - } else { - this.warnCascadeNotAtomic(object); - result = await runPredicateDelete(opCtx.context); - } - } - isPredicateWrite = true; - } - - hookContext.event = 'afterDelete'; - hookContext.result = result; - if (bulkPerRowRows) { - // [#5038] One dispatch per deleted row. No payload is passed, so - // each context carries `previous` = the deleted row and no - // `result`: after a delete there IS no post-state, and every - // consumer (hook `condition`, the record-change trigger, the audit - // diff) already falls back to the pre-image for `record` on a - // delete-shaped context. - for (const rowCtx of this.buildPerRowAfterContexts( - object, 'afterDelete', bulkPerRowRows, hookContext, - )) { - await this.triggerHooks('afterDelete', rowCtx); - } - } else { - await this.triggerHooks('afterDelete', hookContext); - } - - // [#16231] The `delete()` twin, on its own declaration: whether the - // by-id row was there (`boolean`), or how many rows a predicate - // delete removed (`number`). ⚠️ `false` and `0` are the two most - // ordinary answers this verb gives, so `isDeleteResultShape` is a - // pair of `typeof` tests and never a truthiness check — a lenient - // guard here would refuse exactly the answers - // `metadata-protocol`'s `deleteData` turns into its 404. - if (!isDeleteResultShape(hookContext.result)) { - throw new DeleteHookResultNotWriteShapeError({ - object, - event: 'afterDelete', - result: hookContext.result, - }); - } - - // [#27581] The delete is complete: release the handles the removed - // rows held, through the release a committed update uses, so each one - // goes only once storage confirms no row of its column still names it, - // inside this write's unit. After the `afterDelete` chain, so a hook - // can still dereference the value and a refusal that rolls the delete - // back never reaches here. - await this.releaseSecretHandles(object, deletedSecrets, opCtx.context, 'retired'); - - // Roll-up: recompute the parent summary now that the child is gone, - // from the row's FK values captured BEFORE deletion. [#5272] That - // capture is now the same single pre-image read `previous` rides on - // (it used to be its own later `findOne`), which is also what - // `update()` passes here. [#26950] A predicate delete passes the - // matched rows it read before the delete. - const summaryPrevious = priorRecord ?? summaryPriorRows; - const summaryFailures = summaryPrevious - ? await this.recomputeSummaries(object, null, summaryPrevious, opCtx.context) - : []; - - // Same split as update(): per-record `data.record.deleted` (#4626), - // or the aggregate `data.records.deleted` when the delete was by - // predicate (#4639). - if (this.realtimeService) { - if (isPredicateWrite) { - await this.publishBulkDataEvent('deleted', object, { - matched: result, - context: opCtx.context, - // [#15813] Same seam as the update branch. - tenantLayer0Verdict: opCtx.tenantLayer0Verdict, - }); - } else { - const resultId = (typeof result === 'object' && result && 'id' in result) ? (result as any).id : undefined; - await this.publishDataEvent('deleted', object, { - recordId: hookContext.input.id ?? resultId, - // [#14970] The pre-image — a delete has no post-state, and - // this branch is the by-id one, where `priorRecord` was read - // unconditionally by #7867's existence gate and proven - // non-null before `beforeDelete` ever fired. So the row is - // already in hand and NO new read is bought here. - organizationRow: priorRecord, - context: opCtx.context, - }); - } - } - - // The record IS deleted; a summary that could not recompute after - // retries must surface, not stay silent (framework#3147). - if (summaryFailures.length > 0) throw new SummaryRecomputeError(summaryFailures, hookContext.result); - return hookContext.result; - } catch (e) { - // [#7307] `Error.message` is now the END USER's localized sentence for - // a `DELETE_RESTRICTED`, and the logger serializes only `message` + - // `stack` — so without this the operator-facing half (API names, the - // `deleteBehavior:'cascade'` remedy) would reach no channel at all, - // and the server log of a zh-CN deployment would read in Chinese. An - // error that carries no `developerMessage` logs exactly as before. - // [#8682] Same redaction as the insert/update loggers. A DELETE's - // statement carries the caller's values in its `where` clause — which - // is how a record is addressed, so it is the same class of payload. - // `developerMessage` is read off the ORIGINAL error: it is written by - // our own throw sites (#7307), never by a driver, so it carries no - // statement and the redaction has no opinion about it. - // [#17052] The third write door, moved with its two siblings: this - // catch also ends in `throw e`, so the caller is told and the entry - // is not a degradation report. `developerMessage` keeps its place in - // the meta and the redaction is unchanged. - const devDetail = (e as any)?.developerMessage; - this.logger.warn( - 'Delete operation failed', - writeFailureLogMeta(redactBoundStatement(e), { - object, - ...(typeof devDetail === 'string' && devDetail.length > 0 ? { developerMessage: devDetail } : {}), - }), - ); - throw e; - } - }); - - return opCtx.result; + delete(object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + // [#29986 codemod] The body moved to `engine-delete-and-aggregate.ts` (see `DeleteAndAggregateHost`). + return DeleteAndAggregateFacet.delete.call(deleteAndAggregateHost.of(this), object, options); } async count(object: string, query?: EngineCountOptions, options?: EngineReadOptions): Promise { @@ -9835,16 +9094,47 @@ export class ObjectQL implements IObjectQLEngine { })); deleteAndAggregateHost.install((engine) => ({ get _registry() { return engine._registry; }, + assertBulkPerRowHookBudget: (...a) => engine.assertBulkPerRowHookBudget(...a), + assertWriteAllowed: (...a) => engine.assertWriteAllowed(...a), buildDriverOptions: (...a) => engine.buildDriverOptions(...a), + buildHookApi: (...a) => engine.buildHookApi(...a), + buildPerRowAfterContexts: (...a) => engine.buildPerRowAfterContexts(...a), + buildProvenance: (...a) => engine.buildProvenance(...a), + buildSession: (...a) => engine.buildSession(...a), + buildUser: (...a) => engine.buildUser(...a), + cascadeDeleteRelations: (...a) => engine.cascadeDeleteRelations(...a), + claimReferentialCascadeDelete: (...a) => engine.claimReferentialCascadeDelete(...a), composeReadableIdsAtBoundary: (...a) => engine.composeReadableIdsAtBoundary(...a), + delete: (...a) => engine.delete(...a), + dispatchPerRowBeforeHooks: (...a) => engine.dispatchPerRowBeforeHooks(...a), + dispatchUnscopedMultiWriteHooks: (...a) => engine.dispatchUnscopedMultiWriteHooks(...a), + enforceTransactionOrigin: (...a) => engine.enforceTransactionOrigin(...a), executeWithMiddleware: (...a) => engine.executeWithMiddleware(...a), expandSearchOnOptions: (...a) => engine.expandSearchOnOptions(...a), + facade: engine, getDriver: (...a) => engine.getDriver(...a), + getSummaryDescriptors: (...a) => engine.getSummaryDescriptors(...a), + hasHooksFor: (...a) => engine.hasHooksFor(...a), + inAfterAbortUnit: (...a) => engine.inAfterAbortUnit(...a), + invalidateOrganizationProbe: (...a) => engine.invalidateOrganizationProbe(...a), get logger() { return engine.logger; }, + openRecycleBinCapture: (...a) => engine.openRecycleBinCapture(...a), + opensAfterAbortUnit: (...a) => engine.opensAfterAbortUnit(...a), + planCascadeAtomicity: (...a) => engine.planCascadeAtomicity(...a), + publishBulkDataEvent: (...a) => engine.publishBulkDataEvent(...a), + publishDataEvent: (...a) => engine.publishDataEvent(...a), + get realtimeService() { return engine.realtimeService; }, + recomputeSummaries: (...a) => engine.recomputeSummaries(...a), rejectCredentialAggregation: (...a) => engine.rejectCredentialAggregation(...a), get relatedSchemaOf() { return engine.relatedSchemaOf; }, + releaseSecretHandles: (...a) => engine.releaseSecretHandles(...a), resolveObjectName: (...a) => engine.resolveObjectName(...a), resolveWhereTokens: (...a) => engine.resolveWhereTokens(...a), + summaryForeignKeyColumns: (...a) => engine.summaryForeignKeyColumns(...a), + transaction: (...a) => engine.transaction(...a), + triggerHooks: (...a) => engine.triggerHooks(...a), + warnCascadeNotAtomic: (...a) => engine.warnCascadeNotAtomic(...a), + withResolvedWhere: (...a) => engine.withResolvedWhere(...a), })); findHost.install((engine) => ({ get _registry() { return engine._registry; }, diff --git a/scripts/codemod-split-engine.mjs b/scripts/codemod-split-engine.mjs index 96827b88b2d..dabe909eaa1 100644 --- a/scripts/codemod-split-engine.mjs +++ b/scripts/codemod-split-engine.mjs @@ -1589,6 +1589,17 @@ const TYPES_CYCLE_PARA = [ ' * evaluation cycle. `index.ts` re-exports nothing from this module.', ].join('\n'); +/** + * A routed facet module's header paragraph on the statics route: what + * `ObjectQL` names there. The first pass writes it for a module it routes, and + * the fourth pass's R10 (#30020) for one it reroutes. + */ +const STATICS_PARA = [ + ` * \`${CLASS_NAME}\` here is \`${STATICS_NAME}\` (imported AS \`${CLASS_NAME}\`): forwarders to the`, + ' * statics the bodies read, private ones included, which the class fills in a', + ` * static block; the class as a type is \`${CLASS_TYPE_ALIAS}\`.`, +].join('\n'); + /** Does a facet module import a VALUE from `./engine.js`? */ const importsEngineValues = (text) => /^import \{[^}]*\} from '\.\/engine\.js';$/m.test(text); @@ -1651,9 +1662,7 @@ function moduleText(moduleFile, title, movers, scope, leafNames, routed = false) } if (routed) { out.push(' *'); - out.push(` * \`ObjectQL\` here is \`${STATICS_NAME}\` (imported AS \`ObjectQL\`): forwarders to the`); - out.push(' * statics the bodies read, private ones included, which the class fills in a'); - out.push(` * static block; the class as a type is \`${CLASS_TYPE_ALIAS}\`.`); + out.push(STATICS_PARA); } out.push(' *'); out.push(readsHostValues ? VALUES_CYCLE_PARA : TYPES_CYCLE_PARA); @@ -4027,9 +4036,9 @@ async function mainHandDocs(tm, argv) { // module of its section that the first pass wrote, in class order. That // module's header, host interface and import lines grow by what the moved // bodies read, and so do the class's statics route and that facet's host -// factory. Nothing else moves, and the pass never starts a facet, reroutes a -// module or widens a generated export list: each refuses (exit 2), and is a -// decision someone writes here. +// factory. Nothing else moves, and the pass never starts a facet or widens a +// generated export list: each refuses (exit 2), and is a decision someone +// writes here. It reroutes a module onto the statics route only by R10 below. // // The proof (`--members --verify --base REF` re-runs it) undoes the moves from // the head, as the first pass's does: each moved body, docblock and `async` @@ -4080,6 +4089,20 @@ async function mainHandDocs(tm, argv) { // other write to such a field keeps the constructor whole // (`definite-assignment`). // +// One more rule puts a written module on the statics route (#30020 E4): +// +// - R10, the statics route for a written module. A body that reads a +// non-public static (`ObjectQL.REFERENCE_PROBE_BATCH`) moving into a module +// the first pass wrote off the route takes the route the first pass would +// have given it (`rerouteModule`): the one `import type { ObjectQL }` line +// becomes the routed pair, the host interface types its members by +// `ObjectQLClass`, and the header gains `STATICS_PARA`. A module of any +// other shape refuses, and so does one whose code names `ObjectQL` anywhere +// else. The undo (`unrouteModule`) is the inverse rewrite, applied to the +// head before the moved members come out, due only where the base module +// was off the route and a moved member reads a static; a member the module +// keeps that reads one fails it. +// // A statement the hand grew on one line past the wrap width (`runStyles`) is // kept on one line by the move and by the undo alike. @@ -4259,6 +4282,138 @@ function staticsRegionOf(text) { return { kinds, ahead: { start: a, end: a + t.ahead.length }, block: { start: b, end: b + t.block.length } }; } +// R10 (#30020 E4), the statics route for a written module. The first pass +// routes a module when one of its bodies reads a non-public static, and a +// module it wrote without one carries `import type { ObjectQL }`. A body the +// fourth pass moves into such a module that reads a non-public static takes +// the route the first pass would have given the module: the one `./engine.js` +// line becomes the routed pair (`ObjectQLStatics` AS `ObjectQL`, the class as +// `ObjectQLClass`), the host interface types its members by `ObjectQLClass`, +// and the header gains `STATICS_PARA`, so the module is the text the first +// pass writes for a routed module. The members the module already held name +// `ObjectQL` nowhere else (a hand edit that does refuses), so they read what +// they read. The undo is the one inverse rewrite, applied to the head before +// the moved members are taken out, and is due only when the base module was +// not routed and a moved member reads a static. + +/** Is a facet module on the statics route (`ObjectQLStatics` imported AS `ObjectQL`)? */ +const routesStatics = (text) => new RegExp(`^import \\{[^}]*\\b${STATICS_NAME} as ${CLASS_NAME}\\b[^}]*\\} from '\\./engine\\.js';$`, 'm').test(text); + +/** The one `./engine.js` line of a written module off the route, and the pair R10 turns it into. */ +const unroutedEngineImport = () => `import type { ${CLASS_NAME} } from './engine.js';`; +const routedEngineImports = () => importPair('./engine.js', new Map([ + [`${STATICS_NAME} as ${CLASS_NAME}`, { value: true }], + [`${CLASS_NAME} as ${CLASS_TYPE_ALIAS}`, { value: false }], +])).join('\n'); + +/** The identifiers named `name` in a module's code (comments are not code), outside its import declarations and the `skip` regions. */ +function codeIdentifiersNamed(tm, file, text, name, skip = []) { + const ts = tm.ts; + const sf = parseSourceFile(join(SRC_DIR, file), text); + const hits = []; + const visit = (node) => { + if (ts.isImportDeclaration(node)) return; + const at = node.getStart(sf); + if (skip.some(([a, b]) => at >= a && node.getEnd() <= b)) return; + if (ts.isIdentifier(node) && node.text === name) hits.push(at); + ts.forEachChild(node, visit); + }; + ts.forEachChild(sf, visit); + return hits; +} + +/** + * Does a module's code read a static off `ObjectQL` (`ObjectQL.x`)? Comments + * are not code. `members`, when given, narrows the reading to the facet + * class's members of those names. + */ +function readsClassStatic(tm, file, text, members = null) { + const ts = tm.ts; + const sf = parseSourceFile(join(SRC_DIR, file), text); + const facet = facetNameOf(file); + let found = false; + const visit = (node) => { + if (found) return; + if (members && ts.isClassElement(node) && ts.isClassDeclaration(node.parent) && node.parent.name?.text === facet && + !(node.name && ts.isIdentifier(node.name) && members.includes(node.name.text))) return; + if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === CLASS_NAME) { found = true; return; } + ts.forEachChild(node, visit); + }; + ts.forEachChild(sf, (node) => { + // Narrowed to members, only the facet class is read. + if (members && !(ts.isClassDeclaration(node) && node.name?.text === facet)) return; + visit(node); + }); + return found; +} + +/** The header's statics paragraph, in the place the first pass writes it: between the host paragraph and the import paragraph. */ +const staticsParaAt = (text) => { + const cycle = text.includes(VALUES_CYCLE_PARA) ? VALUES_CYCLE_PARA : TYPES_CYCLE_PARA; + return { routed: `\n *\n${STATICS_PARA}\n *\n${cycle}`, plain: `\n *\n${cycle}` }; +}; + +/** + * R10's rewrite: a written module off the statics route, put on it. Refuses + * (exit 2) any module that is not exactly the first pass's unrouted shape for + * it: on the route already, a `./engine.js` import other than the one + * type-only `ObjectQL`, no host interface, a header without one import + * paragraph, or `ObjectQL` / `ObjectQLClass` named anywhere else in its code. + */ +function rerouteModule(tm, file, text) { + if (routesStatics(text)) refuse(`${file}: already on the statics route`); + const engineDecls = importDeclsOf(tm, file, text).filter((d) => d.specifier === './engine.js'); + if (engineDecls.length !== 1 || text.slice(engineDecls[0].start, engineDecls[0].end) !== unroutedEngineImport()) { + refuse(`${file}: its \`./engine.js\` import is not the one \`${unroutedEngineImport()}\` a module off the statics route carries: this pass reroutes only that shape`); + } + const iface = interfaceRegionOf(text, hostNameOf(file)); + if (!iface || iface.classType !== CLASS_NAME) refuse(`${file}: it has no host interface typed by \`${CLASS_NAME}\`: this pass reroutes a module with a host only`); + const others = codeIdentifiersNamed(tm, file, text, CLASS_NAME, [[iface.start, iface.end]]); + if (others.length > 0) refuse(`${file}: its code names \`${CLASS_NAME}\` outside its import and its host interface (static-route-conflict: the route makes that name the statics)`); + if (codeIdentifiersNamed(tm, file, text, CLASS_TYPE_ALIAS).length > 0 || text.includes(`as ${CLASS_TYPE_ALIAS}`)) { + refuse(`${file}: it names \`${CLASS_TYPE_ALIAS}\`, the name the statics route gives the class`); + } + const para = staticsParaAt(text); + if (text.includes(STATICS_PARA) || text.indexOf(para.plain) < 0 || text.indexOf(para.plain) !== text.lastIndexOf(para.plain)) { + refuse(`${file}: its header carries no single import paragraph as the first pass writes one`); + } + const ifaceText = text.slice(iface.start, iface.end) + .replace(new RegExp(`: ${CLASS_NAME}\\['`, 'g'), `: ${CLASS_TYPE_ALIAS}['`) + .replace(`readonly ${FACADE_MEMBER}: ${CLASS_NAME};`, `readonly ${FACADE_MEMBER}: ${CLASS_TYPE_ALIAS};`); + const out = applyOrderedEdits(text, [ + { start: engineDecls[0].start, end: engineDecls[0].end, text: routedEngineImports() }, + { start: iface.start, end: iface.end, text: ifaceText }, + ]); + return withCyclePara(out.replace(para.plain, para.routed), file); +} + +/** + * R10's undo: a module the fourth pass put on the statics route, taken off + * it, from its head text alone (its moved members still in it). Checks the + * shape on the way (`fail`): exactly the routed pair from `./engine.js`, the + * statics paragraph once, in its place, and `ObjectQLClass` named only by the + * host interface. Returns the text, or null after a failure. + */ +function unrouteModule(tm, file, text, fail) { + const engineDecls = importDeclsOf(tm, file, text).filter((d) => d.specifier === './engine.js'); + const span = engineDecls.length > 0 ? text.slice(engineDecls[0].start, engineDecls.at(-1).end) : ''; + if (engineDecls.length !== 2 || span !== routedEngineImports()) { fail(`${file}: its \`./engine.js\` lines are not the statics route's pair as R10 writes it`); return null; } + const iface = interfaceRegionOf(text, hostNameOf(file)); + if (!iface || iface.classType !== CLASS_TYPE_ALIAS) { fail(`${file}: its host interface is not typed by \`${CLASS_TYPE_ALIAS}\``); return null; } + if (codeIdentifiersNamed(tm, file, text, CLASS_TYPE_ALIAS, [[iface.start, iface.end]]).length > 0) { fail(`${file}: its code names \`${CLASS_TYPE_ALIAS}\` outside its host interface`); return null; } + const para = staticsParaAt(text); + const at = text.indexOf(para.routed); + if (at < 0 || text.indexOf(STATICS_PARA) !== text.lastIndexOf(STATICS_PARA)) { fail(`${file}: its header does not carry the statics paragraph once, in its place`); return null; } + const ifaceText = text.slice(iface.start, iface.end) + .replace(new RegExp(`: ${CLASS_TYPE_ALIAS}\\['`, 'g'), `: ${CLASS_NAME}['`) + .replace(`readonly ${FACADE_MEMBER}: ${CLASS_TYPE_ALIAS};`, `readonly ${FACADE_MEMBER}: ${CLASS_NAME};`); + return applyOrderedEdits(text, [ + { start: engineDecls[0].start, end: engineDecls.at(-1).end, text: unroutedEngineImport() }, + { start: iface.start, end: iface.end, text: ifaceText }, + { start: at, end: at + para.routed.length, text: para.plain }, + ]); +} + /** The facet class of a module and its members' texts, each from its line start; null unless they are joined by one blank line. */ function facetMembersOf(tm, moduleFile, text) { const sf = parse(tm, join(SRC_DIR, moduleFile), text); @@ -4393,10 +4548,19 @@ function planMembers(tm, text, moduleTexts, names, { anchors = SECTION_ANCHORS, records.sort((a, b) => a.node.getStart() - b.node.getStart()); const modules = new Map(); for (const r of records) modules.set(r.module, [...(modules.get(r.module) ?? []), r]); + const reroutes = new Set(); for (const [file, movers] of modules) { const mod = moduleTexts.get(file); if (mod == null || !mod.includes(MARK)) refuse(`${file} is not on disk as the first pass wrote it: this pass adds to a written facet, never starts one`); - const routed = new RegExp(`^import \\{[^}]*\\b${STATICS_NAME} as ${CLASS_NAME}\\b[^}]*\\} from '\\./engine\\.js';$`, 'm').test(mod); + // R10 (#30020 E4): a mover that reads a non-public static puts a module + // off the route on it, as the first pass routes a module for one; the + // rewrite refuses any module that is not the first pass's unrouted shape. + let routed = routesStatics(mod); + if (!routed && movers.some((r) => r.readsNonPublicStatic)) { + rerouteModule(tm, file, mod); + reroutes.add(file); + routed = true; + } const hasHost = interfaceRegionOf(mod, hostNameOf(file)) !== null; const typeImportsClass = new RegExp(`^import type \\{[^}]*\\b${CLASS_NAME}\\b[^}]*\\} from '\\./engine\\.js';$`, 'm').test(mod); for (const r of movers) { @@ -4409,7 +4573,8 @@ function planMembers(tm, text, moduleTexts, names, { anchors = SECTION_ANCHORS, if (r.host.size > 0 && r.node.getParameters().some((p) => p.getName() === hostVarOf(file))) { refuse(`${r.name}: a parameter is named ${hostVarOf(file)}, which its stub reads as the facet's host`); } - if (r.classStatics.size > 0 && !routed) refuse(`${r.name} reads statics of ${CLASS_NAME}, and ${file} does not take the statics route: this pass does not reroute a module`); + if (r.classStatics.size > 0 && !routed) refuse(`${r.name} reads statics of ${CLASS_NAME}, none of them non-public, and ${file} does not take the statics route: this pass reroutes a module only for a body that reads a non-public static (R10)`); + if (routed && (r.imports.has(CLASS_TYPE_ALIAS) || r.moduleRefs.has(CLASS_TYPE_ALIAS))) refuse(`${file}: ${r.name} reads ${CLASS_TYPE_ALIAS}, a name the statics route generates in that module`); if (routed) { const blockers = [...r.routeBlockers, ...(r.classOther ? ['static-route-conflict'] : [])]; if (blockers.length > 0) refuse(`${r.name} stays on the class, as the first pass would keep it in a routed module: ${blockers.join('; ')}`); @@ -4430,7 +4595,7 @@ function planMembers(tm, text, moduleTexts, names, { anchors = SECTION_ANCHORS, } } } - return { ctx, records, modules }; + return { ctx, records, modules, reroutes }; } /** Apply a `planMembers` plan. Returns `{ host, modules, pruned }` (`modules`: the receiving modules' new texts). Pure. */ @@ -4485,7 +4650,8 @@ function generateMembers(tm, text, moduleTexts, planned) { const moduleOut = new Map(); for (const [file, movers] of modules) { - const mod = moduleTexts.get(file); + // R10: a module this plan reroutes is put on the statics route first, and grows from there. + const mod = planned.reroutes?.has(file) ? rerouteModule(tm, file, moduleTexts.get(file)) : moduleTexts.get(file); const title = movers[0].section; const modEdits = []; // The members, in class order among the ones the module holds. @@ -4675,7 +4841,17 @@ function importEditsOf(tm, file, baseText, headText, movedText, fail) { * interface is the union of the `Pick`s, and no import binding is unread. * Returns the text, or null when the head is not a module this pass can read. */ -function undoMembersModule(tm, file, text, names, title, fail, baseText) { +function undoMembersModule(tm, file, headText, names, title, fail, baseText) { + if (importsEngineValues(headText) !== headText.includes(VALUES_CYCLE_PARA)) fail(`${file}: its header's import paragraph does not say what its \`./engine.js\` lines import`); + // R10's undo first: a module its base held off the statics route comes off + // it, its moved members still in it, when one of them reads a static. + let text = headText; + if (!routesStatics(headText) && readsClassStatic(tm, file, headText, names)) fail(`${file}: a member this pass moved reads a static, and the module is off the statics route (R10)`); + if (routesStatics(headText) && !routesStatics(baseText)) { + if (!readsClassStatic(tm, file, headText, names)) fail(`${file}: on the statics route at head and off it at base, and no member this pass moved reads a static (R10)`); + text = unrouteModule(tm, file, headText, fail); + if (text === null) return null; + } const facet = facetMembersOf(tm, file, text); const header = headerNamesOf(text, title); if (!facet || !header) { fail(`${file}: not a facet module as the first pass writes one`); return null; } @@ -4698,8 +4874,9 @@ function undoMembersModule(tm, file, text, names, title, fail, baseText) { const kept = union(keep); edits.push({ start: iface.start, end: iface.end, text: [...iface.members].filter(([k]) => kept.has(k)).map(([, v]) => v.line).join('\n') }); } - if (importsEngineValues(text) !== text.includes(VALUES_CYCLE_PARA)) fail(`${file}: its header's import paragraph does not say what its \`./engine.js\` lines import`); - return withCyclePara(pruneModuleImports(tm, file, applyOrderedEdits(text, edits), inverse), file); + const undone = applyOrderedEdits(text, edits); + if (text !== headText && readsClassStatic(tm, file, undone)) fail(`${file}: R10 took it off the statics route, and a member it keeps reads a static`); + return withCyclePara(pruneModuleImports(tm, file, undone, inverse), file); } /** The statics `ObjectQL.x` each routed module's text reads. */ @@ -5494,6 +5671,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'identity port, computed keys and exported names (fourth pass, #30020)': 23, 'hand-series host slots (fifth pass, #30020)': 17, 'constructor and definite-assignment wiring (fourth pass, #30020 R8)': 17, + 'statics route for a written module (fourth pass, #30020 R10)': 18, 'scoped members, instance identity port and symbol keys (second pass, #30020 S1)': 25, }); const SELF_TEST_BATTERY_FLOOR = 5; @@ -5907,7 +6085,7 @@ const IDENTITY_FIXTURE_ANCHORS = Object.freeze([ ['seed', 'Identity', 'engine-identity.ts'], ['keptSection', 'Kept', null], ]); -function identityFixtureSource({ facadeField = false } = {}) { +function identityFixtureSource({ facadeField = false, staticReader = false } = {}) { const pad = Array.from({ length: 12 }, (_, i) => ` const p${i} = ${i};`).join('\n'); const extra = ` protected seed(): number { @@ -5955,7 +6133,14 @@ ${pad} ${pad} return this.facade; } -`; +${staticReader ? ` + /** Reads a private static (R10) and hands the engine on (R1). */ + protected staticReader(n: number): number { +${pad} + const self = (this as any)._flag ? this : null; + return n + ObjectQL.SECRET + this.count + (self ? 1 : 0); + } +` : ''}`; const source = `${fixtureSource(extra)} export class Scoped { constructor(readonly n: number, readonly q: ObjectQL) {} @@ -6576,6 +6761,84 @@ async function selfTest() { } } + open('statics route for a written module (fourth pass, #30020 R10)'); + { + const opts = { anchors: IDENTITY_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; + const source = identityFixtureSource({ staticReader: true }); + const split = generate(tm, source, plan(tm, source, opts)); + const input = split.host; + const mods = split.modules; + const baseIdm = mods.get('engine-identity.ts') ?? ''; + const routedLife = mods.get('engine-lifecycle.ts') ?? ''; + check('the first pass keeps the static reader on the class (bare-this) and writes its section\'s module off the statics route', + input.includes(' protected staticReader(n: number): number {\n const p0') && baseIdm.includes('static seed(') && + !routesStatics(baseIdm) && baseIdm.includes(`\n${unroutedEngineImport()}\n`) && routesStatics(routedLife)); + const planned = planMembers(tm, input, mods, ['staticReader'], opts); + check('the plan reroutes that module for a mover that reads a non-public static', + [...planned.reroutes].join() === 'engine-identity.ts' && planned.records.map((r) => r.name).join() === 'staticReader'); + const out = generateMembers(tm, input, mods, planned); + const again = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['staticReader'], opts)); + const head = new Map([...mods, ...out.modules]); + const v = verifyMembers(tm, input, out.host, mods, head, opts); + check('the generated move proves against its base', v.failures.length === 0 && v.moved.join() === 'staticReader', v.failures.join(' | ')); + check('two runs on one input write byte-identical trees', + treeHash(new Map([['h', out.host], ...out.modules])) === treeHash(new Map([['h', again.host], ...again.modules]))); + const idm = out.modules.get('engine-identity.ts') ?? ''; + const engineLines = (t) => importDeclsOf(tm, 'x.ts', t).filter((d) => d.specifier === './engine.js').map((d) => t.slice(d.start, d.end)).join('\n'); + check('the `./engine.js` line becomes the routed pair, exactly as the first pass writes it for a module it routes', + engineLines(idm) === routedEngineImports() && !idm.includes(unroutedEngineImport()) && + engineLines(routedLife).includes("import { ObjectQLStatics as ObjectQL, ") && engineLines(routedLife).endsWith("\nimport type { ObjectQL as ObjectQLClass } from './engine.js';"), engineLines(idm)); + check('the host interface types every member by the class alias, the identity port too', + idm.includes(" readonly count: ObjectQLClass['count'];") && idm.includes(`${FACADE_DOC}\n readonly facade: ObjectQLClass;`) && + !/: ObjectQL\[/.test(idm) && !idm.includes('facade: ObjectQL;')); + check('the header gains the statics paragraph between the host paragraph and the import paragraph, which now says values', + idm.includes(`\n *\n${STATICS_PARA}\n *\n${VALUES_CYCLE_PARA}\n */`) && routedLife.includes(`\n *\n${STATICS_PARA}\n *\n`) && + baseIdm.includes(`\n *\n${TYPES_CYCLE_PARA}\n */`) && !baseIdm.includes(STATICS_PARA)); + check('the moved body reads `ObjectQL.SECRET` unedited, through the forwarder the route already carries', + idm.includes(' return n + ObjectQL.SECRET + this.count + (self ? 1 : 0);') && out.host === pruneHostImports(tm, out.host, usedImportNames(tm, out.host)).text && + out.host.includes(" readonly SECRET: (typeof ObjectQL)['SECRET'];")); + { + // The move without R10's rewrite: the body reads `ObjectQL.SECRET` through a type-only import. + const offRoute = generateMembers(tm, input, mods, { ...planned, reroutes: new Set() }); + const ov = verifyMembers(tm, input, offRoute.host, mods, new Map([...mods, ...offRoute.modules]), opts); + check('a moved member that reads a static in a module left off the route fails', + !routesStatics(offRoute.modules.get('engine-identity.ts') ?? '') && ov.failures.some((f) => f.includes('off the statics route')), ov.failures.join(' | ')); + } + check('the rewrite and its undo are inverses on the base module', + withCyclePara(unrouteModule(tm, 'engine-identity.ts', rerouteModule(tm, 'engine-identity.ts', baseIdm), () => {}) ?? '', 'engine-identity.ts') === baseIdm); + // A negative control whose edit changed nothing would pass for the wrong reason: it fails the case instead. + const fails = (edited, re = null) => { + if (edited.every(([f, t]) => t === head.get(f))) return false; + const fs = verifyMembers(tm, input, out.host, mods, new Map([...head, ...edited]), opts).failures; + return fs.length > 0 && (!re || fs.some((f) => re.test(f))); + }; + check('a head without the statics paragraph fails', fails([['engine-identity.ts', idm.replace(`\n *\n${STATICS_PARA}`, '')]], /statics paragraph/)); + check('a head whose `./engine.js` lines are not the routed pair fails', + fails([['engine-identity.ts', idm.replace(`import type { ObjectQL as ObjectQLClass } from './engine.js';`, `import type { ObjectQL as ObjectQLClass, Scoped } from './engine.js';`)]], /routed pair|statics route's pair/)); + check('a host interface member left typed by the class itself fails', + fails([['engine-identity.ts', idm.replace(" readonly count: ObjectQLClass['count'];", " readonly count: ObjectQL['count'];")]])); + { + // A module put on the route though no moved member reads a static: the undo refuses it. + const plain = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['computed'], opts)); + const plainIdm = plain.modules.get('engine-identity.ts') ?? ''; + const forced = rerouteModule(tm, 'engine-identity.ts', plainIdm); + const pv = verifyMembers(tm, input, plain.host, mods, new Map([...mods, ...plain.modules, ['engine-identity.ts', forced]]), opts); + check('a module rerouted though no member the pass moved reads a static fails', + !routesStatics(plainIdm) && routesStatics(forced) && pv.failures.some((f) => f.includes('no member this pass moved reads a static')), pv.failures.join(' | ')); + } + check('a module whose code names `ObjectQL` outside its import and host interface refuses the route (static-route-conflict)', + /static-route-conflict/.test(refusalOf(() => planMembers(tm, input, new Map([...mods, ['engine-identity.ts', baseIdm.replace(' return this.count;', ' return this.count as ObjectQL[\'count\'];')]]), ['staticReader'], opts)))); + check('R4 into a module this pass reroutes refuses, as it does for a routed one', + /takes the statics route/.test(refusalOf(() => planMembers(tm, input, mods, ['identity', 'staticReader'], opts)))); + { + const r4 = generateMembers(tm, input, mods, planMembers(tm, input, mods, ['identity'], opts)); + const r4Mods = new Map([...mods, ...r4.modules]); + check('a module whose `./engine.js` import is not the one type-only line refuses the route', + /not the one/.test(refusalOf(() => planMembers(tm, r4.host, r4Mods, ['staticReader'], opts)))); + } + check('a module already on the route is not rerouted', refused(() => rerouteModule(tm, 'engine-lifecycle.ts', routedLife))); + } + open('constructor and definite-assignment wiring (fourth pass, #30020 R8)'); { const opts = { anchors: IDENTITY_FIXTURE_ANCHORS, pins: FIXTURE_PINS, needles: FIXTURE_NEEDLES, classNeedles: FIXTURE_CLASS_NEEDLES }; diff --git a/scripts/facade-delegation-registry.json b/scripts/facade-delegation-registry.json index 13e7aee6a68..47b71c125f9 100644 --- a/scripts/facade-delegation-registry.json +++ b/scripts/facade-delegation-registry.json @@ -59,13 +59,6 @@ "card": "#30020", "reason": "state-owning: bare-this, the body hands the instance itself on (#29986 report: stays on the class)" }, - { - "file": "packages/objectql/src/engine.ts", - "class": "ObjectQL", - "member": "delete", - "card": "#30020", - "reason": "state-owning: bare-this, the body hands the instance itself on (#29986 report: stays on the class)" - }, { "file": "packages/drivers/driver-sql/src/sql-driver.ts", "member": "constructor", diff --git a/scripts/measure-durability-swallow-family.mjs b/scripts/measure-durability-swallow-family.mjs index a7bf3f3712c..b298f0e7f69 100644 --- a/scripts/measure-durability-swallow-family.mjs +++ b/scripts/measure-durability-swallow-family.mjs @@ -546,15 +546,19 @@ const RESOLUTION_CONTROLS = [ + 'two apart — which is the whole reason this family reads the resolver instead of the output.', }, { - file: 'packages/objectql/src/engine.ts', + file: 'packages/objectql/src/engine-delete-and-aggregate.ts', callee: 'delete', - fromClass: 'ObjectQL', - resolvesIn: 'ObjectQL', + fromClass: 'DeleteAndAggregateFacet', + resolvesIn: 'DeleteAndAggregateFacet', why: - 'The same collision on the sharpest name in the vocabulary. `delete` is the callee the AWAITED ' - + 'discriminator exists to police, and `ObjectRepository.delete` is a different method from ' - + '`ObjectQL.delete`; resolving one into the other is exactly the "invents a write" failure the ' - + '`sameFileCallee` rule was written for, arriving one layer further in.', + 'The sharpest name in the vocabulary: `delete` is the callee the AWAITED discriminator exists to ' + + 'police. Its one `this.delete(...)` re-entry (the after-abort unit re-running the delete) moved ' + + 'out of `ObjectQL` in `engine.ts` with the body that holds it, into the facet module, where ' + + '`this` is the facet host and its `delete` is the class\'s stub, which calls the facet\'s own ' + + '`delete`. So the hop must land in `DeleteAndAggregateFacet`, the body the stub reaches, and in ' + + 'no other. The cross-class collision in `engine.ts` (`ObjectRepository` and `ScopedContext` ' + + 'declaring a method of an `ObjectQL` name) stays pinned by the `update` and `transaction` ' + + 'controls beside this one.', }, { file: 'packages/objectql/src/engine.ts',