Repository navigation
Expand file tree
/
Copy pathengine-delete-and-aggregate.ts
More file actions
1626 lines (1596 loc) · 105 KB
/
Copy pathengine-delete-and-aggregate.ts
File metadata and controls
1626 lines (1596 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [#29986 codemod] The "Delete, count, aggregate and execute" section of
* `ObjectQL`: the bodies of `delete`, `assertNoInternalFieldEvaluated`,
* `aggregate` moved out of `engine.ts` whole (split
* by #30012 and #31764).
*
* 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`
* method of the same name exactly as it stood: not re-indented, not
* formatted, not edited. The method stays on the class as a one-call stub with
* its signature, so the published surface, an instance spy and a subclass
* override are what they were. A public or protected method keeps its
* docblock on the class, the contract; a private method's docblock moved here
* with its body. The state stays on `ObjectQL`.
*
* The bodies reach the class through {@link DeleteAndAggregateHost}: exactly
* the `ObjectQL` members they read, private ones included. Every stub hands its
* body, by a `.call`, the same host: `deleteAndAggregateHost` in
* `engine-facet-hosts.ts`, built once per engine by the class's static block.
* Methods go as closures that call them on the engine at call time, so a
* subclass override or an instance spy is still the one reached; fields and
* accessors go as GETTERS, read when the body reads them, as they were on the
* class, and a field a body assigns goes with a SETTER that assigns it on the
* engine.
*
* `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, EngineDeleteOptions, FilterCondition, HookContext, QueryAST } from '@objectstack/spec/data';
import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } from '@objectstack/spec/contracts';
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';
import { assertAggregationFieldTypesAccepted } from './aggregate-field-type-door.js';
import { ROLLUP_AGGREGATE_OPTION, assertRecordCurrencyAggregatesGrouped } from './record-currency-aggregate-door.js';
import {
assertAggregatedColumnsAreDistinct,
assertDateBucketTargetsAreTemporal,
assertGroupByTargetsAreStored,
} from './aggregate-query-shape-door.js';
import { applyInMemoryAggregation } from './in-memory-aggregation.js';
import { aggregatedRowColumnClasses, aggregatedRowColumnTypes, aggregatedRowColumns, applyHaving, assertAggregationFilterIsEvaluable, assertFilterNodeShapes, 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_DELETE_OPTION_KEYS, ENGINE_WHERE_SLOTS, declaredDatetimeLowering,
describeNonFilterWhere, foldEngineOptionAliases, isWhereFilterObject, lowerWhereFilterArray, mergeReadContext,
CascadeBatchNarrowed, cascadeBatchIdsOf, organizationPredicateDeleteRefusal, rejectUnknownEngineOptions, resolveThenLowerWhere, whereResolvedTokenJudge,
writeFailureLogMeta,
} from './engine-top-level.js';
import type { EngineReadOptions, OperationContext } from './engine-top-level.js';
import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js';
import {
aggregateOrderCutDirective, aggregateOrderCutRefusal, aggregateOrderCutRequestOf, assertAggregateOrderCutShape,
takeAggregateGroupCount, withAggregateOrderCutDirective,
} from './aggregate-order-cut.js';
import {
assertRelationGroupRequestShape, assertRelationGroupRowsJoined, declineRelationGroup, planRelationGroups,
RELATION_GROUP_JOINS, relationFieldsJudgedAsGroupKeys, relationGroupByRequestOf, relationGroupJoinsAtBoundary,
relationGroupDriverRefusal, relationGroupRegistryDecline, withoutJudgedRelationFields, type PlannedRelationGroup,
} from './relation-group-join.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
* them, and no other. Each is typed AS the class member (an indexed access on
* the class), so a change to a member's signature on the class is a change
* here too. `readonly` members are the getters; the others are fields a body
* assigns.
*/
export interface DeleteAndAggregateHost {
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'];
relationSemiJoinServes: ObjectQLClass['relationSemiJoinServes'];
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<DeleteAndAggregateHost, '_registry' | 'assertBulkPerRowHookBudget' | 'assertWriteAllowed' | 'buildDriverOptions' | 'buildHookApi' | 'buildPerRowAfterContexts' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'cascadeDeleteRelations' | 'claimReferentialCascadeDelete' | 'dispatchPerRowBeforeHooks' | 'dispatchUnscopedMultiWriteHooks' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'getDriver' | 'getSummaryDescriptors' | 'hasHooksFor' | 'inAfterAbortUnit' | 'invalidateOrganizationProbe' | 'logger' | 'openRecycleBinCapture' | 'opensAfterAbortUnit' | 'planCascadeAtomicity' | 'publishBulkDataEvent' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'relatedSchemaOf' | 'releaseSecretHandles' | 'resolveObjectName' | 'summaryForeignKeyColumns' | 'transaction' | 'triggerHooks' | 'warnCascadeNotAtomic' | 'withResolvedWhere'>, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise<boolean | number> {
object = this.resolveObjectName(object);
// [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's
// `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`.
//
// [#35167] As in `insert` and `update`: the unit opens around the ENGINE
// BODY (the executor below), never around the door, so the middleware
// chain — the authorization gate's reads, and whatever a middleware does
// after `next()` — runs outside it. Nothing between here and the executor
// writes; the cascade claim below is an in-memory marker.
const ownUnit = this.opensAfterAbortUnit('afterDelete', object, options?.context);
const inOwnUnit = <T>(body: () => Promise<T>): (() => Promise<T>) =>
ownUnit ? () => this.inAfterAbortUnit(body) : body;
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', options?.context?.transaction);
// 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.
// [ruling 6893661036, F1] A predicate delete hands its `where` instead: a
// cascade batch is claimed by the exact id set it names.
const referentialCascadeDelete = this.claimReferentialCascadeDelete(object, id ?? options?.where);
const opCtx: OperationContext = {
object,
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, inOwnUnit(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<Record<string, unknown> | 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<string, unknown> | null,
declaredDeleteColumns,
);
};
const bindPreImage = (row: Record<string, unknown> | 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<string, unknown> | 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<string, unknown>[] | 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<string, unknown>[] | null = null;
let summaryPriorRows: Record<string, unknown>[] | 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<boolean>` ("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<any>` 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, opCtx.context);
// 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);
// [ruling 6893661036, F1] A cascade batch (the walk's one predicate
// delete per chunk of children, claimed above) always reads its doomed
// rows: they are its scope check and its per-row realtime events.
const cascadeBatch = referentialCascadeDelete === true;
if (perRowBeforeHooks || perRowAfterHooks || cascadeBatch) {
const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict });
// [#21613] Each doomed row is its per-row `previous`: declared set.
const doomed = rowsWithDeclaredColumnsOnly(
(await driver.find(object, ast, preOpts) as Record<string, unknown>[]) ?? [],
declaredDeleteColumns,
);
predicateMatchedRows = doomed;
// [ruling 6893104201 point (2)] The read ran through the AST the
// middleware chain composed for this delete, so it is the caller's
// WRITE scope (the delete-class row filters). The READ scope is not
// on it: the security plugin composes that onto an addressed
// predicate write only, never a nested one, so the walk asked the
// read door for the chunk before issuing it (`readDoorReturnsChunk`).
// A child the walk asked for and this read did not return is one a
// by-id delete would REFUSE (403) where this predicate would skip it:
// before any hook and any write, hand the chunk back to the walk,
// which deletes it by id, so the refusal and the rollback are today's.
if (cascadeBatch) {
const found = new Set(doomed.map((row) => String(row?.id)));
if (!(cascadeBatchIdsOf(options?.where) ?? []).every((v) => found.has(v))) {
throw new CascadeBatchNarrowed(object);
}
}
// [D6] One ceiling, both phases, BEFORE the first per-row dispatch
// and before the driver call.
if (perRowBeforeHooks || perRowAfterHooks) {
this.assertBulkPerRowHookBudget(
object, perRowBeforeHooks ? 'beforeDelete' : 'afterDelete', doomed.length,
);
}
if (perRowAfterHooks) bulkPerRowRows = doomed;
// [D1] Zero matched rows is zero dispatches.
if (perRowBeforeHooks && doomed.length > 0) {
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<string, unknown>[]);
}
// [#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<string, unknown>[]));
}
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).
//
// [#34373] Deleting by id keeps the caller's predicate off the
// final statement, so the read is where the predicate has to
// keep holding: a concurrent commit that moved a matched row
// out of it ("delete only if still pending") between this read
// and the delete would otherwise be deleted anyway, and counted.
// Inside the unit of work, a driver that declares
// `supports.lockRows` takes the read with `lockRows`, so no
// other writer commits a change to a matched row until the
// unit ends. A driver without the bit, or no open transaction
// (the `'split'` plan, a driver with no transactions), reads
// unlocked and keeps that window (`DriverCapabilities.lockRows`).
const runPredicateDelete = async (writeContext?: ExecutionContext): Promise<unknown> => {
const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any);
const readOptions = writeOptions?.transaction != null && driver.supports?.lockRows === true
? { ...writeOptions, lockRows: true }
: writeOptions;
// [#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] }, readOptions)) ?? []) as Array<Record<string, unknown>>;
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 && referentialCascadeDelete && predicateMatchedRows) {
// [ruling 6893104201 point (1)] A cascade batch keeps today's
// events: one `data.record.deleted` per child, each scoped by its
// own pre-image, read before the statement removed it.
for (const row of predicateMatchedRows) {
await this.publishDataEvent('deleted', object, {
recordId: row.id,
organizationRow: row,
context: opCtx.context,
});
}
} else if (isPredicateWrite) {
await this.publishBulkDataEvent('deleted', object, {
matched: result,
context: opCtx.context,
// [#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<DeleteAndAggregateHost, 'relatedSchemaOf'>, object: string, query: InternalFieldEvaluationQuery, options?: InternalFieldEvaluationOptions): void {
assertNoInternalFieldEvaluated(object, query, this.relatedSchemaOf, options);
}
/** The body of `ObjectQL#aggregate`; the method's docblock there is its contract. */
static async aggregate(this: Pick<DeleteAndAggregateHost, '_registry' | 'buildDriverOptions' | 'composeReadableIdsAtBoundary' | 'executeWithMiddleware' | 'expandSearchOnOptions' | 'facade' | 'getDriver' | 'logger' | 'rejectCredentialAggregation' | 'relatedSchemaOf' | 'relationSemiJoinServes' | 'resolveObjectName' | 'resolveWhereTokens'>, object: string, query: EngineAggregateOptions, options?: EngineReadOptions): Promise<any[]> {
object = this.resolveObjectName(object);
// [relation group join] The engine-internal request to group by a
// related record's attributes (`relation-group-join.ts`). The registry
// half of its decline is judged first: a driver that compiles no join,
// a field that is not a single-valued relation to the named object, a
// related read the semi-join rule keeps out — declined before anything
// is read, so the caller's own path runs the doors below itself.
const relationGroup = relationGroupByRequestOf(options);
if (relationGroup !== undefined) {
// [#33876] A driver that compiles no `ReadableIds` leaf refuses the
// dimension outright, before the decline: the caller throws the
// error rather than serve its FK-expand.
const refusal = relationGroupDriverRefusal(
object, relationGroup, this.getDriver(object) as { readonly name?: unknown; readonly supports?: unknown } | undefined,
);
if (refusal !== undefined) {
relationGroup.outcome = { kind: 'refused', error: refusal };
return [];
}
const reason = relationGroupRegistryDecline.call({
getObjectSchema: (name: string) => this._registry.getObject(name),
getDriver: (name: string) => this.getDriver(name) as { readonly name?: unknown; readonly aggregate?: unknown } | undefined,
relationSemiJoinServes: (o: string, t: string) => this.relationSemiJoinServes(o, t),
}, object, relationGroup);
if (reason !== undefined) {
declineRelationGroup(relationGroup, reason);
return [];
}
}
// [relation group join] A PLANNED read (`relation-semi-join.ts`): the
// related read a relation group join is built from is this verb,
// stopped at its driver call. Only the engine's own planner sets it.
const scopePlan = (options as Record<symbol, unknown> | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined;
// [aggregate order and cut] The engine-internal request to order the
// groups by an aggregated column, cut them and count them, in the
// driver's own statement (`aggregate-order-cut.ts`). Its shape is judged
// once every door below has judged the query; the driver and the path
// are judged at the driver call.
const orderCut = aggregateOrderCutRequestOf(options);
// Fold the `filter` alias into `where` (#4346) — the AST below reads
// `query.where` only, so an unfolded `{ filter }` aggregated every row.
query = foldEngineOptionAliases(object, 'aggregate', query, ENGINE_WHERE_SLOTS);
rejectUnknownEngineOptions(object, 'aggregate', query, ENGINE_AGGREGATE_OPTION_KEYS);
query = lowerWhereFilterArray(object, 'aggregate', query, this._registry.getObject(object), this.relatedSchemaOf);
// [ADR-0100] The filter half of the credential-column guard — `where`
// and every `aggregations[i].filter` — before the search term joins
// `where`; the aggregate half (`rejectCredentialAggregation`) follows.
// [internal: true] The flagged-column refusal goes first, over every
// position at once (`where`, `groupBy`, each aggregation's `field` and
// `filter`), so a non-system caller meets the data door's words here