Repository navigation
Expand file tree
/
Copy pathengine-insert.ts
More file actions
1727 lines (1698 loc) · 107 KB
/
Copy pathengine-insert.ts
File metadata and controls
1727 lines (1698 loc) · 107 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 "Write preparation and insert" section of `ObjectQL`:
* the bodies of `staticReadonlyCreateStrip`, `updateByIdExpecting`,
* `ownershipQueueService`, `assignment`, `readUpdatePriorRow`, `insert`,
* `insertMany` moved out of `engine.ts` whole by
* `scripts/codemod-split-engine.mjs`.
*
* A MOVE, not a redesign. {@link InsertFacet} 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 InsertHost}: exactly the `ObjectQL`
* members they read, private ones included. Every stub hands its body, by a
* `.call`, the same host: `insertHost` 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 type { DataEngineInsertOptions, EngineCountOptions, EngineQueryOptions, HookContext, QueryAST } from '@objectstack/spec/data';
import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
import type { PendingSecretRow } from './engine-secret-internal-fields.js';
import { referencesCheckedBeforeRules } from './engine-referential-integrity.js';
import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import type { IDataDriver } from '@objectstack/core';
import { ConcurrentUpdateError } from './concurrent-update-error.js';
import { SummaryRecomputeError } from './summary-errors.js';
import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js';
import { DuplicateRecordError } from './duplicate-record-error.js';
import { NotNullRefusalError, envelopeDriverWriteRefusal } from './not-null-refusal-error.js';
import { ASSIGNMENT_RULE_TYPE, AssignmentRuleEvaluator, OWNERSHIP_QUEUE_SOURCE_SLOT } from './assignment-rules.js';
import type { AssignmentQueueService } from './assignment-rules.js';
import { redactBoundStatement } from '@objectstack/types';
import { ORGANIZATION_OBJECT } from './tenancy/system-write-organization.js';
import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs } from './validation/record-currency-code.js';
import { planHomeAmounts, projectHomeAmounts } from './home-amount-projection.js';
import { stripSearchCompanion } from './search-companion.js';
import type { EvalPermissions } from '@objectstack/formula';
import { declaredOptionLabels } from './formula-option-labels.js';
import { coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFields, normalizeNumericStringValues, validateRecordInScope } from './validation/record-validator.js';
import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedRequiredWhen, preserveAuditIgnoredOnInsertWarning, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js';
import type { staticReadonlyInsertSubject } from './validation/rule-validator.js';
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
import { recordHookPayloadWrites } from './hook-write-provenance.js';
import type { HookWriteRecording } from './hook-write-provenance.js';
import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js';
import { declaredColumnSet, rowsWithDeclaredColumnsOnly, selectedStoredColumns, storedColumnsLeftUnwritten, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js';
import {
WRITE_PRECONDITION_OPTION, autonumberFieldNames, callerKeySets, callerSuppliedRow, computeStoredExpressions,
droppedFieldEvents, handBackWithheldInsertReadonly, hydrateWriteFormulas, insertStaticReadonlySubject,
planStoredExpressions, recomputeAutonumberReaders, replacedStoredExpressionFields, shouldSkipStateMachine,
storedExpressionsReading, stripComputedWriteFields, undeclaredWriteFieldErrors, withholdInsertReadonlyFromHooks,
callerInputRefusalLogMeta, writeFailureLogMeta,
} from './engine-top-level.js';
import type {
AutonumberReaders, IssuedAutonumber, OperationContext, PermissionResolution, StoredExpressionServing,
} from './engine-top-level.js';
import { ObjectQLStatics as ObjectQL } from './engine.js';
import type { InsertManyRowOutcome, ObjectQL as ObjectQLClass } from './engine.js';
/**
* The `ObjectQL` members the bodies of {@link InsertFacet} 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 InsertHost {
readonly _registry: ObjectQLClass['_registry'];
admittedViolationSink: ObjectQLClass['admittedViolationSink'];
applyAutonumbers: ObjectQLClass['applyAutonumbers'];
applyFieldDefaults: ObjectQLClass['applyFieldDefaults'];
assertReferencesResolve: ObjectQLClass['assertReferencesResolve'];
assertWriteAllowed: ObjectQLClass['assertWriteAllowed'];
assignment: ObjectQLClass['assignment'];
assignmentEvaluator: ObjectQLClass['assignmentEvaluator'];
readonly autonumberCounters: ObjectQLClass['autonumberCounters'];
buildDriverOptions: ObjectQLClass['buildDriverOptions'];
buildEvalUser: ObjectQLClass['buildEvalUser'];
buildHookApi: ObjectQLClass['buildHookApi'];
buildProvenance: ObjectQLClass['buildProvenance'];
buildSession: ObjectQLClass['buildSession'];
buildUser: ObjectQLClass['buildUser'];
count: ObjectQLClass['count'];
createWithAutonumberResync: ObjectQLClass['createWithAutonumberResync'];
encryptSecretFields: ObjectQLClass['encryptSecretFields'];
enforceTransactionOrigin: ObjectQLClass['enforceTransactionOrigin'];
executeWithMiddleware: ObjectQLClass['executeWithMiddleware'];
/** The engine itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */
readonly facade: ObjectQLClass;
find: ObjectQLClass['find'];
formulaFaultSink: ObjectQLClass['formulaFaultSink'];
formulaOptionLabels: ObjectQLClass['formulaOptionLabels'];
getDriver: ObjectQLClass['getDriver'];
getSchema: ObjectQLClass['getSchema'];
getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors'];
homeAmountServing: ObjectQLClass['homeAmountServing'];
inAfterAbortUnit: ObjectQLClass['inAfterAbortUnit'];
initializeSummaryFields: ObjectQLClass['initializeSummaryFields'];
insert: ObjectQLClass['insert'];
readonly insertRecomputeListeners: ObjectQLClass['insertRecomputeListeners'];
invalidateOrganizationProbe: ObjectQLClass['invalidateOrganizationProbe'];
isIssuedAutonumberCollision: ObjectQLClass['isIssuedAutonumberCollision'];
readonly logger: ObjectQLClass['logger'];
mediaValueShapeStrictFor: ObjectQLClass['mediaValueShapeStrictFor'];
opensAfterAbortUnit: ObjectQLClass['opensAfterAbortUnit'];
ownershipQueueService: ObjectQLClass['ownershipQueueService'];
permissionResolution: ObjectQLClass['permissionResolution'];
persistSecretRows: ObjectQLClass['persistSecretRows'];
preconditionDegradedWarned: ObjectQLClass['preconditionDegradedWarned'];
publishDataEvent: ObjectQLClass['publishDataEvent'];
readonly realtimeService: ObjectQLClass['realtimeService'];
recomputeSummaries: ObjectQLClass['recomputeSummaries'];
refuseEmptyPasswordFields: ObjectQLClass['refuseEmptyPasswordFields'];
releaseSecretHandles: ObjectQLClass['releaseSecretHandles'];
resolveDefaultPermissions: ObjectQLClass['resolveDefaultPermissions'];
resolveFormulaPermissions: ObjectQLClass['resolveFormulaPermissions'];
resolveFormulaRelated: ObjectQLClass['resolveFormulaRelated'];
resolveMasterDetailParents: ObjectQLClass['resolveMasterDetailParents'];
resolveObjectName: ObjectQLClass['resolveObjectName'];
resolveOptionPermissions: ObjectQLClass['resolveOptionPermissions'];
resolvePredicateRelated: ObjectQLClass['resolvePredicateRelated'];
resolveSystemInsertOrganization: ObjectQLClass['resolveSystemInsertOrganization'];
staticReadonlyCreateStrip: ObjectQLClass['staticReadonlyCreateStrip'];
triggerHooks: ObjectQLClass['triggerHooks'];
update: ObjectQLClass['update'];
validationMessageContext: ObjectQLClass['validationMessageContext'];
valueShapeStrictFor: ObjectQLClass['valueShapeStrictFor'];
warnAutonumberReadersUnserved: ObjectQLClass['warnAutonumberReadersUnserved'];
}
/** The bodies of the "Write preparation and insert" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
export class InsertFacet {
/**
* [#20805] The create path's static-`readonly` strip of ONE row, together
* with the re-default of every key it takes — the door as `insert()` runs it,
* lifted out so that {@link ObjectQL.validate} runs the same door over its
* preview rows instead of a copy of it (one function per door). `insert()`
* owns everything around it: the `isSystem` gate, the per-call
* `insertDropped` union, the `preserveAudit`-ignored WARN and partial-mode
* culling; `validate()` passes no logger, because a preview writes nothing
* and a strip line would say otherwise.
*
* The field's `defaultValue` is RE-DERIVED for every key the strip took,
* which is #3043's stated contract and a guarantee in its own right: a forged
* `approval_status` becomes `draft` — the enforced initial state — never
* NULL, so a stripped forgery cannot leave a row in a state the object's own
* rules (`requiredWhen`, the state machine) were written to exclude. The
* deleted ingress copy got this for free by running BEFORE
* `applyFieldDefaults`; a strip that runs after the hooks has to ask. Asked
* over the STRIPPED row, so a `defaultValue` expression reads the payload it
* will really be stored beside, and copied back key by key:
* `applyFieldDefaults` also fills every OTHER absent field, and a hook that
* deliberately wrote `null` must keep its null (the first defaults pass,
* ahead of the hooks, is the one that owns those keys).
*
* [#20082] A re-derived `can` default takes the write's map too — from the
* same resolution, so this asks nothing new unless it is the first pass to
* need it. Scoped to the TAKEN keys: those are the only defaults this pass
* keeps, so no other field's default can make it ask, or fail.
*
* @returns the row as the strip leaves it (the SAME reference when nothing
* was taken) and the keys taken, in the row's key order. When the
* re-default's permission resolution fails, `error` carries it and `row`
* is the row as it arrived: the caller decides whether that fails the
* write or culls the row, and the taken keys are still reported.
*/
static async staticReadonlyCreateStrip(this: Pick<InsertHost, 'applyFieldDefaults' | 'resolveDefaultPermissions'>, object: string, readonlySubject: NonNullable<ReturnType<typeof staticReadonlyInsertSubject>>, row: Record<string, unknown>, supplied: Readonly<Record<string, unknown>>, context: ExecutionContext | undefined, pass: {
logger: Parameters<typeof stripReadonlyFields>[3];
strictReadonlyWrites: boolean;
hookWrittenKeys: ReadonlySet<string> | undefined;
nowSnap: Date;
permissionResolution: PermissionResolution | undefined;
}): Promise<{ row: Record<string, unknown>; taken: string[]; error?: unknown }> {
const stripped = stripReadonlyFields(
readonlySubject as any, row, supplied, pass.logger,
{
strictReadonlyWrites: pass.strictReadonlyWrites,
hookWrittenKeys: pass.hookWrittenKeys,
verb: 'insert',
},
) as Record<string, unknown>;
if (stripped === row) return { row, taken: [] };
const taken = Object.keys(row).filter((k) => !(k in stripped));
if (taken.length > 0) {
let redefaultPermissions: EvalPermissions | undefined;
try {
redefaultPermissions = (await this.resolveDefaultPermissions(
object, [stripped], context, pass.permissionResolution, taken,
))(stripped);
} catch (err) {
return { row, taken, error: err };
}
const redefaulted = this.applyFieldDefaults(object, stripped, context, pass.nowSnap, redefaultPermissions);
for (const k of taken) {
if (redefaulted[k] !== undefined) stripped[k] = redefaulted[k];
}
}
return { row: stripped, taken };
}
/**
* [#22445] The by-id update's prior-row read: the STORED row an update of
* `id` judges, or `null` when the store holds none. One spelling, read by
* `update()`'s by-id branch and by the `update`-mode preview
* ({@link ObjectQL.validate}), so the preview judges the image the write
* judges rather than a second reading of it.
*
* A raw driver read, not the read door: the rules judge the row as STORED,
* so no formula is evaluated, no file reference resolved, no read hook run.
* ⛔ It answers no access question — `update()` reaches it only after the
* write gates in its middleware chain, and the preview asks the read door
* first (see `storedRows` in `validate()`).
*
* `buildDriverOptions` carries the open transaction and the tenant scope onto
* the raw read, as on every engine read. [#21613] The row is shaped like
* every other row this engine reads off a driver: the declared field set, so
* the update's `previous` (bound for its hooks, and the audit ledger's side
* of every update diff) and its returned row are ONE view. Shaping only the
* returned row would make every update of a row carrying a retired column
* record that column as changed, its stored value included.
*/
/**
* [ADR-0142 D4] The by-id write under {@link OperationContext.writePrecondition}:
* the driver's conditional `updateMany` over `{ id, ...expect }`, then a
* readback by id. Zero rows matched is {@link ConcurrentUpdateError}. A driver
* with no `updateMany` writes unconditionally, logged once per process.
*/
static async updateByIdExpecting(this: Pick<InsertHost, 'logger' | 'preconditionDegradedWarned'>, driver: IDataDriver, object: string, id: unknown, data: Record<string, unknown>, expect: Readonly<Record<string, unknown>>, options: Parameters<IDataDriver['findOne']>[2]): Promise<unknown> {
if (typeof driver.updateMany !== 'function') {
if (!this.preconditionDegradedWarned) {
this.preconditionDegradedWarned = true;
this.logger.warn(
`[objectql] the driver for '${object}' has no conditional update (updateMany), so a by-id write ` +
'precondition degrades to the pre-image check and the write goes through unconditionally: two ' +
'concurrent claims of one record may both land, and the round-robin cursor may repeat a member.',
{ object },
);
}
return driver.update(object, id as string, data, options);
}
const affected = await driver.updateMany(object, { object, where: { ...expect, id } } as QueryAST, data, options);
if (!(Number(affected) > 0)) throw new ConcurrentUpdateError(object, String(id));
return driver.findOne(object, { object, where: { id }, limit: 1 } as QueryAST, options);
}
/** The registered ownership-queue service, through the plugin's slot — `null` on every other state. */
static ownershipQueueService(this: Pick<InsertHost, 'facade'>): AssignmentQueueService | null {
const source = (this.facade as unknown as Record<symbol, unknown>)[OWNERSHIP_QUEUE_SOURCE_SLOT];
if (typeof source !== 'function') return null;
try {
const svc = (source as () => unknown)();
return svc && typeof (svc as AssignmentQueueService).resolveQueue === 'function'
&& typeof (svc as AssignmentQueueService).expandMembers === 'function'
? (svc as AssignmentQueueService)
: null;
} catch {
return null;
}
}
/** The body of `ObjectQL#assignment`; the method's docblock there is its contract. */
static assignment(this: Pick<InsertHost, '_registry' | 'assignmentEvaluator' | 'count' | 'find' | 'insert' | 'logger' | 'ownershipQueueService' | 'update'>): AssignmentRuleEvaluator {
if (!this.assignmentEvaluator) {
this.assignmentEvaluator = new AssignmentRuleEvaluator({
listRules: () => this._registry.listItems(ASSIGNMENT_RULE_TYPE) as unknown[],
getSchema: (object) => this._registry.getObject(object),
hasObject: (object) => Boolean(this._registry.getObject(object)),
queues: () => this.ownershipQueueService(),
find: async (object, where, context, limit) =>
(await this.find(object, { where, ...(limit ? { limit } : {}) } as EngineQueryOptions, { context: context as ExecutionContext })) as Record<string, unknown>[],
count: (object, where, context) => this.count(object, { where } as EngineCountOptions, { context: context as ExecutionContext }),
insert: (object, data, context) => this.insert(object, data, { context: context as ExecutionContext }),
updateExpecting: (object, id, data, expect, context) =>
this.update(object, { ...data, id }, { context: context as ExecutionContext, [WRITE_PRECONDITION_OPTION]: expect } as any),
logger: this.logger,
});
}
return this.assignmentEvaluator;
}
/** The body of `ObjectQL#readUpdatePriorRow`; the method's docblock there is its contract. */
static async readUpdatePriorRow(this: Pick<InsertHost, '_registry' | 'buildDriverOptions' | 'getDriver'>, object: string, id: unknown, context: ExecutionContext | undefined, base?: unknown): Promise<Record<string, unknown> | null> {
const priorAst: QueryAST = { object, where: { id }, limit: 1 } as QueryAST;
const preOpts = this.buildDriverOptions(object, context, base as any);
return withDeclaredColumnsOnly(
await this.getDriver(object).findOne(object, priorAst, preOpts) as Record<string, unknown> | null,
declaredColumnSet(this._registry.getObject(object)),
);
}
/** The body of `ObjectQL#insert`; the method's docblock there is its contract. */
static async insert(this: Pick<InsertHost, '_registry' | 'admittedViolationSink' | 'applyAutonumbers' | 'applyFieldDefaults' | 'assertReferencesResolve' | 'assertWriteAllowed' | 'assignment' | 'autonumberCounters' | 'buildDriverOptions' | 'buildEvalUser' | 'buildHookApi' | 'buildProvenance' | 'buildSession' | 'buildUser' | 'createWithAutonumberResync' | 'encryptSecretFields' | 'enforceTransactionOrigin' | 'executeWithMiddleware' | 'facade' | 'formulaFaultSink' | 'formulaOptionLabels' | 'getDriver' | 'getSchema' | 'getSummaryDescriptors' | 'homeAmountServing' | 'inAfterAbortUnit' | 'initializeSummaryFields' | 'insert' | 'insertRecomputeListeners' | 'invalidateOrganizationProbe' | 'isIssuedAutonumberCollision' | 'logger' | 'mediaValueShapeStrictFor' | 'opensAfterAbortUnit' | 'permissionResolution' | 'persistSecretRows' | 'publishDataEvent' | 'realtimeService' | 'recomputeSummaries' | 'refuseEmptyPasswordFields' | 'releaseSecretHandles' | 'resolveDefaultPermissions' | 'resolveFormulaPermissions' | 'resolveFormulaRelated' | 'resolveMasterDetailParents' | 'resolveObjectName' | 'resolveOptionPermissions' | 'resolvePredicateRelated' | 'resolveSystemInsertOrganization' | 'staticReadonlyCreateStrip' | 'triggerHooks' | 'validationMessageContext' | 'valueShapeStrictFor' | 'warnAutonumberReadersUnserved'>, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise<any> {
object = this.resolveObjectName(object);
// [#22782] An aborting `afterInsert` rolls this write back — see `opensAfterAbortUnit`.
if (this.opensAfterAbortUnit('afterInsert', object, options?.context)) {
return this.inAfterAbortUnit(() => this.insert(object, data, options));
}
this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) });
this.assertWriteAllowed(object, 'insert');
// [#8844] The organization set is about to change. Dropped BEFORE the write
// rather than after it, so a concurrent read cannot repopulate the memo from
// a snapshot this insert is in the middle of invalidating.
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, 'insert');
// [#20308] A blank on a non-string-typed column is `null` from here on —
// before the middleware, the caller snapshot, the defaults, the hooks and
// validation read the payload, so all of them see one image (a blank then
// takes a `defaultValue` exactly as `null` does). See
// `normalizeBlankTypedValues` for the scope; it never mutates the caller's
// rows. [#20309] At the same point, a string on a number field that the
// spec's numeric grammar reads becomes that number, so the validator judges
// the value the driver stores (`normalizeNumericStringValues`).
data = normalizeBlankTypedValues(this._registry.getObject(object), data);
data = normalizeNumericStringValues(this._registry.getObject(object), data);
// [#21682] What the CALLER sent, recorded before any write middleware
// fills the payload. See `callerKeySets`.
const callerKeys = callerKeySets(data);
const opCtx: OperationContext = {
object,
operation: 'insert',
data,
options,
context: options?.context,
};
await this.executeWithMiddleware(opCtx, async () => {
// Resolve field `defaultValue`s (including the `current_user` and
// `NOW()` tokens)
// BEFORE the beforeInsert hook runs, so a hook that DERIVES one field
// from another can read the defaulted value instead of a stale `null`
// (#2703). The hook still has final say — it runs after and may override
// any defaulted field. `applyFieldDefaults` returns a fresh copy and only
// fills fields left `undefined`, so client-supplied values are untouched.
//
// [#5749] Roll-up `summary` fields this object OWNS are seeded in the same
// pass, right after the declared defaults: `count`/`sum` over the empty
// child collection is 0, and a brand-new parent HAS an empty child
// collection. Without it the row stored `null` and stayed there until some
// child write happened to name it — so "never had a child" (null) and
// "had one, deleted it" (0) read differently and `= 0` filters dropped
// rows. Same placement rules as the defaults above: caller-supplied values
// untouched, hooks run after and may override.
const nowSnap = new Date();
const isBatch = Array.isArray(opCtx.data);
// [#21682] Each row's caller key set, looked up NOW, on the row objects
// the middleware chain handed on. The computed-field door below may
// replace a row with a copy. Index-aligned from here on: every pass
// between here and the snapshot keeps the rows' order and count.
const callerKeysPerRow: Array<ReadonlySet<string> | undefined> =
(isBatch ? (opCtx.data as unknown[]) : [opCtx.data]).map(
(row) => (row !== null && typeof row === 'object' ? callerKeys.get(row) : undefined),
);
// [#8682] The declared-field door — see `undeclaredWriteFieldErrors` for
// what used to run below it for a request that was already refused.
// FIRST, so nothing downstream (defaults, summary seeding, the hooks, the
// secret writes, validation, the autonumber) happens for a row the schema
// rejects. Non-partial callers get the refusal thrown here; the
// partial-success path (`insertMany`) carries it per row into `rowErrors`
// below, where the culled rows also skip the hooks and every producer.
const undeclaredPerRow = undeclaredWriteFieldErrors(
object,
this._registry.getObject(object) as { fields?: unknown } | undefined,
isBatch ? (opCtx.data as unknown[]) : [opCtx.data],
);
const partialRowMode = isBatch && (options as any)?.__partialRowErrors === true;
if (!partialRowMode) {
const refusal = undeclaredPerRow.find((e) => e !== undefined);
if (refusal) throw refusal;
}
// [#20805] The computed-field door, beside the declared-field door and
// over the rows it did not refuse — see `stripComputedWriteFields`. In
// EVERY context: unlike the strips further down, no `isSystem` gate,
// because a `formula` value has no column to land in for any caller.
// Everything below reads `opCtx.data`, so it is replaced here and the
// snapshot, the defaults and the hooks all see the payload that will be
// stored. Reported at `insertDrops`, beside the other strips.
const computedStrip = stripComputedWriteFields(
this._registry.getObject(object) as { fields?: unknown } | undefined,
isBatch ? (opCtx.data as unknown[]) : [opCtx.data],
undeclaredPerRow,
);
const computedDropped = computedStrip.dropped;
if (computedDropped.length > 0) {
opCtx.data = (isBatch ? computedStrip.rows : computedStrip.rows[0]) as any;
}
// [#4441] The RAW caller payload per row — before `applyFieldDefaults`
// resolves any `defaultValue` / `current_user` token and before the
// beforeInsert hooks stamp `created_by`. The reference check consults it
// to decide WHAT THE CALLER ACTUALLY SENT, so neither a platform stamp
// nor a backfilled default is ever reported as the caller's bad
// reference.
//
// [#21682] ...and without the keys a write MIDDLEWARE filled, which ran
// before this step: `organization_id` (`@objectstack/organizations`) and
// `owner_id` (`@objectstack/plugin-security`) are filled there, not by a
// hook. Each row keeps only the keys the caller sent (`callerKeySets`,
// recorded at entry), so the strips below report and take only those.
// The values stay as the chain handed them on.
//
// [#6339] It carries the caller's VALUES, and it is taken HERE — ahead of
// the hooks — as an explicit shallow COPY. Both halves are load-bearing:
// - VALUES, because the runtime-owned strip below runs AFTER
// `beforeInsert`, so "the caller named this key" and "this key still
// holds the caller's value" are different facts, and only the second
// one licenses a delete (see `stripRuntimeOwnedFields`).
// - a COPY, taken ahead of the hooks, because `rows[i]` is a different
// object from `opCtx.data` only by the grace of two upstream helpers:
// `applyFieldDefaults` returns `{ ...record }` — except on its
// `!fields` early return, which hands the SAME reference back — and
// `initializeSummaryFields` copies only when it actually seeds. Hooks
// mutate `ctx.input.data` IN PLACE, so an aliased snapshot would
// answer "what did the caller send?" with the post-hook payload.
// Measured on `origin/main`: not aliased today, because that early
// return lines up with the strip's own `!fields` bail — a coincidence
// of three call sites, which the copy turns into an invariant of this
// one. Same spread, same reason, as the update path's `suppliedValues`
// (#5591).
const suppliedPerRow: Array<Record<string, unknown>> =
(isBatch ? (opCtx.data as any[]) : [opCtx.data]).map(
(row, i) => callerSuppliedRow(row, callerKeysPerRow[i]),
);
// ── [#22306] WITHHOLD caller-supplied read-only values from beforeInsert ──
//
// The insert side of #16344's invariant, in the ruling's words:「交给生命
// 周期钩子的记录,就是它打算持久化的那条记录。」— see
// `withholdInsertReadonlyFromHooks` for the measured defect and for WHICH
// keys (the post-hook static strip's own function, subject and options).
//
// ⭐ WITHHOLD, not strip, exactly as on update. The ENFORCEMENT stays
// where ruling C (#14147) put it — after the hooks, the only point that
// can tell a hook's stamp from a caller's forgery (`rowHookWrittenKeys`)
// — and the caller's values are handed straight back after the seal, so
// the strips, their re-default, the WARN, `onFieldsDropped` and
// `strictReadonlyWrites` all judge the payload they judged before.
//
// Placed HERE, after `suppliedPerRow` took the caller's values (the
// strips' evidence) and BEFORE the defaults, the summary seed and the
// recording: the defaults then fill a withheld key exactly as they fill
// an absent one, and nothing this pass does can be recorded as a hook
// write. `opCtx.data` keeps the caller's payload; only the hook view is
// built from the withheld rows. ⛔ `isSystem` withholds nothing — the
// strips do not run for it, so every value it sends is stored.
//
// [#24822] Read ONCE, here, and by both static-`readonly` passes: whether
// the Layer 0 wall judges this insert's `organization_id` on the stored
// rows. The wall declares it on the seam it installed, and the engine
// reads that member and nothing else (`insertStaticReadonlySubject`).
// The middleware chain has run by now, so the seam is in place.
const wallJudgesOrganization =
!opCtx.context?.isSystem && opCtx.postHookWriteImageCheck?.judgesOrganization === true;
const insertWithheld: Array<Record<string, unknown> | undefined> = [];
const hookViewSource: unknown[] = (isBatch ? (opCtx.data as unknown[]) : [opCtx.data]).slice();
if (!opCtx.context?.isSystem) {
const preserveAuditForHide = opCtx.context?.preserveAudit === true;
const hideSchema = this._registry.getObject(object);
for (let i = 0; i < hookViewSource.length; i++) {
const row = hookViewSource[i];
if (undeclaredPerRow[i] !== undefined) continue;
if (!row || typeof row !== 'object' || Array.isArray(row)) continue;
const hidden = withholdInsertReadonlyFromHooks(
hideSchema, row as Record<string, unknown>, suppliedPerRow[i] ?? {}, preserveAuditForHide,
wallJudgesOrganization,
);
insertWithheld[i] = hidden.withheld;
hookViewSource[i] = hidden.row;
}
}
// [#20082] The write's ONE permission resolution, shared by every consumer
// below that needs the map: the CEL defaults here, the re-default after
// the static-`readonly` strip, the option gates at validation, and the
// formula fields on the response. Asked at most once for the whole write.
//
// A CEL default that calls `current_user.can(…)` is evaluated with it. A
// row whose default NEEDED it when the resolution failed is refused with
// the resolution's own error (fail CLOSED, see `resolveDefaultPermissions`)
// before any hook or producer runs for it: the whole write outside partial
// mode; under partial mode that row alone, carried with the declared-field
// door's per-row refusals — the array every later pass already reads as
// "this row is dead on arrival" (no hook, seeded into `rowErrors`).
const permissionResolution = this.permissionResolution(opCtx.context);
// [#22306] The hook view's rows: a withheld key is absent here, so a
// `can` default on it is resolved for this row as for any absent key.
const payloadRows: unknown[] = hookViewSource;
const defaultPermissionsFor = await this.resolveDefaultPermissions(
object, payloadRows.filter((_, i) => undeclaredPerRow[i] === undefined), opCtx.context, permissionResolution,
);
const defaultPermissions: Array<EvalPermissions | undefined> = payloadRows.map((row, i) => {
if (undeclaredPerRow[i] !== undefined) return undefined;
try {
return defaultPermissionsFor(row);
} catch (err) {
if (!partialRowMode) throw err;
undeclaredPerRow[i] = err as Error;
return undefined;
}
});
const defaultedData = isBatch
? payloadRows.map((row, i) =>
this.initializeSummaryFields(
object,
this.applyFieldDefaults(object, row as Record<string, unknown>, opCtx.context, nowSnap, defaultPermissions[i]),
),
)
: this.initializeSummaryFields(
object,
this.applyFieldDefaults(object, payloadRows[0] as Record<string, unknown>, opCtx.context, nowSnap, defaultPermissions[0]),
);
// [#24619] The stored computed fields ({@link planStoredExpressions}),
// computed over the defaulted row BEFORE the beforeInsert hooks run, so
// a hook is handed the value the write stores — the #16344 ruling:
// 「交给生命周期钩子的记录,就是它打算持久化的那条记录。」 Computed
// again after the hooks and the strips (beside validation, below),
// because a hook may change an input, and that pass is the one stored.
const storedExpressionPlan = planStoredExpressions(this._registry.getObject(object));
const storedExpressionServing: StoredExpressionServing = {
permissionsFor: (plan, records) => this.resolveFormulaPermissions(object, plan, records, opCtx.context, permissionResolution),
onFault: this.formulaFaultSink(object),
relatedFor: (plan, records) => this.resolveFormulaRelated(this._registry.getObject(object), plan, records, opCtx.context),
optionLabelsFor: (plan) => declaredOptionLabels(this._registry.getObject(object), plan),
};
if (storedExpressionPlan.length > 0) {
const defaultedRows = (isBatch ? defaultedData : [defaultedData]) as Array<Record<string, unknown>>;
const live = defaultedRows.filter((row, i) => undeclaredPerRow[i] === undefined && row != null && typeof row === 'object');
const computed = await computeStoredExpressions(storedExpressionPlan, live, opCtx.context, storedExpressionServing);
live.forEach((row, k) => Object.assign(row, computed[k]));
}
// [#22306] What each withheld key was SHOWN holding — its default, or
// nothing — read before any hook runs, because the hooks mutate these
// row objects in place. `handBackWithheldInsertReadonly` reads it to tell
// "the hook left the default alone" from "the hook removed it".
const insertShown: Array<ReadonlyMap<string, unknown> | undefined> =
(isBatch ? (defaultedData as any[]) : [defaultedData]).map((row, i) => {
const withheld = insertWithheld[i];
if (!withheld || !row || typeof row !== 'object') return undefined;
const shown = new Map<string, unknown>();
for (const key of Object.keys(withheld)) {
if (Object.prototype.hasOwnProperty.call(row, key)) shown.set(key, (row as Record<string, unknown>)[key]);
}
return shown;
});
// Batch inserts trigger beforeInsert/afterInsert PER ROW, each with the
// exact single-record context shape (`input.data` = one row, `result` =
// its returned record). A single array-shaped context broke every
// consumer built for the single shape — the flat-input proxy read
// `undefined`s, declarative `condition`s evaluated against an array,
// audit rows and flow-trigger contexts came out mangled (#2922).
//
// [#6966] Which is exactly why the fan-out has to be STATED rather than
// inferred: the shape is deliberately identical, so nothing about a
// context tells a handler whether it is one row of a batch. The scratch
// is created once per CALL and shared by every row's context, before and
// after — see `HookContext.dispatch`.
const insertScope: Record<string, unknown> = {};
// ── [#14259] ARM the hook-write recording, one PER ROW ───────────────
//
// The insert-side twin of the update path's single recording (#14088),
// and the reason it has to exist here at all: `stripRuntimeOwnedFields`
// below judges hook-vs-caller by `Object.is`, which cannot separate "the
// hook re-issued the record number the caller also submitted" from "the
// hook never touched the key". #6339 moved that judgement from a key SET
// to values on the argument that the key set made the contract true "only
// BY ACCIDENT" — and values are accidental in the identical way.
//
// PER ROW, not per call: a batch runs `beforeInsert` once per row against
// its own payload object, so one shared record would let a hook that
// stamps row 3 exempt row 4's caller-seeded value. One recording per row
// is what makes the answer mean "a hook assigned THIS key on THIS row".
//
// The two ends of the window are load-bearing, exactly as on the update
// path (the recorder module's own header carries the full argument):
//
// - ARMED HERE, over `defaultedData` — after the caller's payload has
// arrived, after `suppliedPerRow` snapshotted it, and after the
// engine's own defaulting (`applyFieldDefaults` /
// `initializeSummaryFields`) has run, so no engine default and no
// caller key can enter the record. A caller cannot execute an
// assignment; echoing a key, a value, a `null` or a `Proxy` back is
// not a `set` on this object.
// - SEALED immediately below, before the post-hook declared-field door
// reads the payload and long before `encryptSecretFields` writes to
// it. A recorder still armed for an engine-owned pass would report
// ENGINE writes as HOOK writes, which on a caller-forged secret column
// is precisely the escalation this is built to make impossible.
//
// Between those two points the only code that runs is the `beforeInsert`
// dispatch — server code, by definition. Writes through the recording
// land on the SAME row object, so a hook mutating `ctx.input.data.x` in
// place is mutating the engine's row exactly as it always has.
const rowHookWrites: Array<HookWriteRecording | undefined> = [];
const rowHookContexts: HookContext[] = (isBatch ? (defaultedData as any[]) : [defaultedData]).map(
(row, rowIndex) => {
const recording =
row !== null && typeof row === 'object'
? recordHookPayloadWrites(row as Record<string, unknown>)
: undefined;
rowHookWrites[rowIndex] = recording;
return {
object,
event: 'beforeInsert',
input: { data: recording?.payload ?? row, options: opCtx.options },
dispatch: { mode: isBatch ? 'per-row' : 'record', index: rowIndex, scope: insertScope },
session: this.buildSession(opCtx.context),
provenance: this.buildProvenance(opCtx.context),
user: this.buildUser(opCtx.context),
api: this.buildHookApi(opCtx.context),
transaction: opCtx.context?.transaction,
ql: this.facade,
};
},
);
// [#8682] A row the declared-field door refused runs NO hook. In
// non-partial mode the throw above already returned, so this skip only
// ever fires for a culled row of a partial batch — where the whole point
// is that one bad row costs the others nothing, and a hook that stamps a
// ledger or calls out must not fire for a row that will never be written.
for (let i = 0; i < rowHookContexts.length; i++) {
if (undeclaredPerRow[i] !== undefined) continue;
// [#22306] The update path's wrapper (commit 706ad0fcc), so a hook that
// faults reaching THROUGH a key this row's hide withheld names that key
// instead of surfacing as an anonymous crash. Byte-identical to a bare
// dispatch whenever nothing was withheld or the hook refused on purpose.
await dispatchHooksExplainingWithheldReadonly(insertWithheld[i], 'beforeInsert',
() => this.triggerHooks('beforeInsert', rowHookContexts[i]));
}
// ── [#14259] SEAL, before anything engine-owned reads or writes a row ──
//
// Sealing does two things and the write is wrong without either: it
// freezes each record before the engine's own passes can be mis-recorded
// as hook writes, and it puts the RAW row back in `input.data` so no
// recording view reaches a driver.
//
// Every row is sealed, including one the declared-field door culled: that
// row ran no hook, so its record is legitimately EMPTY, and restoring its
// raw payload keeps `rows[i]` a plain object on every branch rather than
// only on the live ones.
//
// `hookWrittenKeys` is `undefined` — not empty — for a row whose hook
// REPLACED the payload object (`ctx.input.data = { …ctx.input.data }`).
// `stripRuntimeOwnedFields` must read that as "fall back to the #6339
// value test", never as "no hook wrote anything": a replacement's keys
// are mostly the CALLER's, so treating them as hook-owned would launder a
// caller-seeded record number into a platform write.
const rowHookWrittenKeys: Array<ReadonlySet<string> | undefined> = [];
for (let i = 0; i < rowHookContexts.length; i++) {
const sealed = rowHookWrites[i]?.seal(rowHookContexts[i]!.input.data);
if (sealed) rowHookContexts[i]!.input.data = sealed.data as any;
rowHookWrittenKeys[i] = sealed?.hookWrittenKeys;
}
// ── [#22306] HAND BACK what was withheld from beforeInsert ─────────────
//
// The other end of the pre-defaults pass, at the line where each row has
// stopped being its hooks' (sealed above) and nothing engine-owned has
// read it yet — the update path's confluence, row by row. AFTER the seal
// so no hand-back can enter the record as a hook write, and BEFORE the
// post-hook declared-field door so every pass from here down sees the
// payload it saw before the hide existed, wherever no hook wrote the key.
// The per-key rule is `handBackWithheldInsertReadonly`'s. A culled row is
// handed back too: it ran no hook, so it gets its caller's row back whole.
//
// A withheld audit provenance value a hook stamped over (the audit
// binder's `created_by`) is recorded per row (`insertSuperseded`) and
// joins the strips' `readonly` drops: reported through `onFieldsDropped`
// and refused under `strictReadonlyWrites`, like every reported drop.
// See `handBackWithheldInsertReadonly`.
const insertSuperseded: string[][] = rowHookContexts.map(() => []);
for (let i = 0; i < rowHookContexts.length; i++) {
const withheld = insertWithheld[i];
if (!withheld) continue;
const target = rowHookContexts[i]!.input.data as Record<string, unknown> | null | undefined;
if (!target || typeof target !== 'object' || Array.isArray(target)) continue;
rowHookWrittenKeys[i] = handBackWithheldInsertReadonly(
target, withheld, insertShown[i] ?? new Map(), rowHookWrittenKeys[i], insertSuperseded[i],
);
}
// ── [commit b003cf2e8] The POST-hook half of the declared-field door ───────────
//
// #8737 moved the door above ahead of the hooks so that no work — no
// autonumber, no secret row — is done for a payload about to be refused.
// That is still right, and this does NOT move it (moving it re-opens
// #8682). What it left uncovered is the payload the HOOKS produce: the
// door judged the caller's keys, then `beforeInsert` ran and could add
// any key at all, and from there the three drivers disagreed —
// `memory` ACCEPTED and stored a shadow column, `driver-sql` threw a raw
// `SQLITE_ERROR` with no `status`, `sqlite-wasm` threw a bare `Error`
// with neither. One app, one hook, three meanings decided by which
// driver a deployment happens to run.
//
// So the same function runs a second time over the POST-hook rows. Same
// predicate, not a second one — a hook-written key and a caller-written
// key are the same defect (`declared = enforced`, PD #10) and must read
// identically to a caller: `INVALID_FIELD` / 400, on every driver.
//
// ## Why the platform's own stamps survive it
//
// The wildcard audit hook (`sys_stamp_audit_insert`, `object: '*'`, in
// plugin.ts) writes `created_at` and `updated_at` UNCONDITIONALLY —
// deliberately, because driver-sql creates those two as built-in columns
// on every table whether or not the object declares them. They are
// exactly two of `PLATFORM_PROVISIONED_COLUMNS`, which this function has
// tolerated since #8682 for that same reason, so the platform's own
// hook is covered by the tolerance that already existed rather than by
// an exemption invented here. Its other three stamps (`created_by`,
// `updated_by`, `tenant_id`) are each guarded by an explicit
// `hasField(objectName, …)`, and every other before-hook that ships in
// this repo either writes a DECLARED key or is structurally unable to
// introduce one (pinyin's `__search` returns early unless the object
// declares the companion; the storage file-reference pass rewrites only
// keys already present). ⛔ Do not add a per-key exemption list here: the
// tolerated set is the platform-provisioned one, and a hook that needs
// more than that is writing a field its object should declare.
//
// ## Placement: immediately after the dispatch, before every producer
//
// #8682's rule applied one step in — a refusal must cost nothing — so
// this runs before `resolveSystemInsertOrganization`, before the
// credential channel (`encryptSecretFields` seals a `sys_secret` row),
// before validation and before `applyAutonumbers`. Pre-statement, so the
// driver is never reached: that is also what puts #8682's Half B
// statement-and-values leak out of reach on this path, since both SQL
// refusals only ever came from the driver's own error string.
//
// Merged into `undeclaredPerRow` rather than thrown directly so partial
// mode behaves exactly as it does for a caller-written key: the row is
// culled, its siblings are unaffected, and the seed into `rowErrors`
// below happens before the first pass with a side effect. A row the
// PRE-hook door already refused ran no hook, so its verdict is kept as
// it stands — re-reporting it would replace the original error object
// with an equal one for no reason.
const postHookUndeclared = undeclaredWriteFieldErrors(
object,
this._registry.getObject(object) as { fields?: unknown } | undefined,
rowHookContexts.map((rowCtx) => rowCtx.input.data),
);
for (let i = 0; i < postHookUndeclared.length; i++) {
if (undeclaredPerRow[i] === undefined) undeclaredPerRow[i] = postHookUndeclared[i];
}
if (!partialRowMode) {
const postRefusal = postHookUndeclared.find((e) => e !== undefined);
if (postRefusal) throw postRefusal;
}
// ── [commit a016f08b8] EVERY VALUE-CHANGING PASS, AHEAD OF THE SEAM ──────────
//
// The two strips below used to run AFTER the seam, and the contract
// review commit a016f08b8 records measured what that cost: a static-`readonly`
// scoping field — the natural shape for a server-stamped column, and
// exactly what an RLS `check` compares (ADR-0055) — was judged by the
// seam with the CALLER’s value still on the row, then stripped and
// re-defaulted, so the store received a value the seam never saw. The
// row that was judged was not the row that was stored, which is this
// card’s own defect one layer down.
//
// So both strips run HERE, ahead of the seam. Neither has a side
// effect — they read `suppliedPerRow`, `rowHookWrittenKeys`, the
// schema and `options`, all resolved above, and they log — so moving
// them costs nothing and buys the seam the final row. What is left
// between the seam and the driver is engine-owned and named in the
// seam’s own comment below.
//
// ⚠️ The REPORTING half (`insertDropped` → `strictReadonlyWrites` /
// `onFieldsDropped`) deliberately stays where it was, after the seam:
// moving it too would put `ReadonlyFieldRejectedError` ahead of the
// gate’s 403 and change which refusal a caller sees. The strips are
// value-changing; their report is not.
const schemaForValidation = this._registry.getObject(object);
// Defaults are already resolved above (pre-hook, #2703); a hook may
// have overridden fields or replaced `input.data` — take its data as-is.
const rows = rowHookContexts.map((rowCtx) => rowCtx.input.data as Record<string, unknown>);
// [#8682] Rows the declared-field door refused are already dead on
// arrival — seeded before the strips, before the seam, and so before
// the credential loop further down, which is the first pass with a
// real side effect (`encryptSecretFields` seals a `sys_secret` row):
// a culled row is neither stripped, nor judged, nor able to mint a
// secret for a write that will never happen.
const rowErrors: (unknown | undefined)[] = new Array(rows.length);
for (let i = 0; i < rows.length; i++) rowErrors[i] = undeclaredPerRow[i];
// [#5503] `autonumber` is RUNTIME-owned: the engine (or the driver's
// persistent sequence) issues the value, so a non-system caller does not
// get to supply or rewrite it. Until now nothing enforced that — a POST
// carrying an explicit record number was stored verbatim, bypassing the
// sequence, and the SQL driver's `supports.autonumber` path adopted it
// too (it only fills a slot left empty). Stripping HERE, in the engine
// and before `applyAutonumbers`, is what makes the fix driver-agnostic:
// every driver — native-sequence or not — is handed a row with no
// caller-supplied record number, so no driver had to change.
//
// Runs BEFORE validation on purpose: a value the caller was never
// allowed to send must not be judged by the object's rules either (a
// `format` rule on the field would otherwise 400 on a payload we are
// about to discard). Symmetric with the UPDATE strip, which likewise
// runs before `evaluateValidationRules`. Exemptions are the update
// path's, unchanged: `isSystem` (seed replay, migration) skips the whole
// pass, and `preserveAudit` (#3493) lets a historical import reinstate
// legacy record numbers.
//
// [#6339] `suppliedPerRow[i]` is handed over WHOLE — values included —
// rather than reduced to its key set. This pass runs after the
// beforeInsert hooks, so a key set could only say "the caller named
// this", and `delete` then took whatever value was standing there: a
// hook that RE-ISSUES the record number lost its write to any caller
// that had also submitted the key, while the same hook's write survived
// on a caller that had not. The update path's twin (#5591).
//
// [#20922] Every key a caller-write strip takes is recorded twice, at
// the strip: into the batch-level union (`insertDropped`, reported once
// per call below, unchanged) and into the taking row's own list, which
// `insertMany` hangs on that row's `ok` outcome. Per row because the
// rows CAN differ (`hookWrittenKeys` is armed per row), so the union
// cannot be resolved back to rows after the fact.
const insertDropped: string[] = [];
const insertDroppedPerRow: string[][] = rows.map(() => []);
const recordInsertTaken = (i: number, taken: readonly string[]): void => {
for (const k of taken) {
if (!insertDropped.includes(k)) insertDropped.push(k);
if (!insertDroppedPerRow[i]!.includes(k)) insertDroppedPerRow[i]!.push(k);
}
};
if (!opCtx.context?.isSystem) {
const preserveAudit = opCtx.context?.preserveAudit === true;
for (let i = 0; i < rows.length; i++) {
if (rowErrors[i] !== undefined) continue;
// [#8214] The insert side carries the same claim and the same
// sequencing — this pass logs, the `ReadonlyFieldRejectedError`
// below throws before any driver dispatch. Measured on
// `origin/main`: `driverCreates 0` while the line said the write
// was "COMMITTED WITHOUT IT". The card marked this half UNVERIFIED;
// it reproduces, so the flag is threaded here too.
// [#14259] `hookWrittenKeys` — THIS row's sealed record, the other
// half of the same question `suppliedPerRow[i]` answers. #6339
// handed values over instead of a key set because "the caller named
// this key" and "this key still holds the caller's value" are
// different facts; the record closes the case values cannot reach,
// where the hook wrote the value the caller also sent. The value
// test stays as the fallback for any row with no record.
const stripped = stripRuntimeOwnedFields(
schemaForValidation as any, rows[i], suppliedPerRow[i] ?? {}, this.logger,
{
preserveAudit,
strictReadonlyWrites: options?.strictReadonlyWrites === true,
hookWrittenKeys: rowHookWrittenKeys[i],
},
) as Record<string, unknown>;
if (stripped === rows[i]) continue;
recordInsertTaken(i, Object.keys(rows[i]).filter((k) => !(k in stripped)));
rows[i] = stripped;
rowHookContexts[i].input.data = stripped;
}
// [#14147] STATIC author-declared `readonly`, enforced HERE — one
// semantics, one enforcement point, per the maintainer ruling of
// 2026-09-03 (option C) which SUPERSEDED the 2026-07-24 row "INSERT
// (all callers) exempt". Until it landed, a non-system caller
// reaching `engine.insert` DIRECTLY wrote a read-only column with no
// refusal, no WARN and no `onFieldsDropped` event, while the very
// same payload through the DataProtocol was stripped — and
// `create_record`'s listener (`@objectstack/service-automation`) was
// wired for a readonly drop it could never receive. The boundary copy
// that produced that asymmetry (`stripReadonlyForInsert`,
// metadata-protocol) is DELETED in the same change rather than kept
// as a second implementation.
//
// The strip is {@link stripReadonlyFields} — the SAME function
// `update` runs, under the SAME `isSystem` gate (the branch above),
// reporting through the SAME channels: `readonlyStripWarning` at
// `warn`, `onFieldsDropped` under reason `readonly`, and
// `strictReadonlyWrites` refusing before any driver dispatch. Its
// guards therefore come across too, and they are wider than the
// deleted ingress copy's: a hook stamp is not caller-supplied
// (`suppliedPerRow`), and a key a `beforeInsert` hook ASSIGNED is the
// hook's write, not a forgery (`rowHookWrittenKeys`, #14259). The
// ingress copy ran BEFORE the hooks and could judge neither.
//
// ⛔ `preserveAudit` is deliberately NOT forwarded — see
// {@link preserveAuditIgnoredOnInsertWarning}: the 2026-08-08 ruling
// narrowed that exemption to the UPDATE path and left `isSystem` as
// the create side's only one. Ruling C moved WHERE this strip runs;
// it did not widen WHAT exempts it.
//
// WHICH fields it may judge is {@link staticReadonlyInsertSubject}'s
// (runtime-owned types belong to the pass above; the `sys_` namespace
// and the PLATFORM-INTERNAL `managedBy` buckets to their own 403
// guards — #15719 narrowed that second exclusion from "`managedBy` set
// to anything", so a user-writable bucket is judged here exactly as it
// is on update); `null` — no such field on this object — is the cheap
// exit every ordinary insert takes.
//
// [#24822] ...without `organization_id` where the Layer 0 wall judges it
// on this insert's stored rows (`wallJudgesOrganization`, read once
// above for the withhold too). That value is stored as sent or refused
// by the wall, never taken here and replaced by the active organization.
// So it is not reported or refused under `strictReadonlyWrites` either:
// strict refuses exactly what this strip takes.
const readonlySubject = insertStaticReadonlySubject(schemaForValidation, wallJudgesOrganization);
if (readonlySubject) {
const preserveAuditIgnored: string[] = [];
for (let i = 0; i < rows.length; i++) {
if (rowErrors[i] !== undefined) continue;
// [#20805] One door, two callers: `validate()` runs this same
// method over its preview rows — see `staticReadonlyCreateStrip`.
const pass = await this.staticReadonlyCreateStrip(
object, readonlySubject, rows[i], suppliedPerRow[i] ?? {}, opCtx.context,
{
logger: this.logger,
strictReadonlyWrites: options?.strictReadonlyWrites === true,
hookWrittenKeys: rowHookWrittenKeys[i],
nowSnap,
permissionResolution,
},
);
if (pass.row === rows[i] && pass.taken.length === 0) continue;
recordInsertTaken(i, pass.taken);
for (const k of pass.taken) {
if (preserveAudit && !preserveAuditIgnored.includes(k)) preserveAuditIgnored.push(k);
}
if (pass.error !== undefined) {
if (!partialRowMode) throw pass.error;
rowErrors[i] = pass.error;
continue;
}
rows[i] = pass.row;
rowHookContexts[i].input.data = pass.row;
}
// One line per CALL, not per row, and only when the exemption was
// ASKED FOR and something was actually removed. Per CALL because a
// log line has no per-row slot: the union of what the batch lost is
// the only view one line can represent — ⛔ NOT because every row
// lost the same set. `hookWrittenKeys: rowHookWrittenKeys[i]` above
// is armed per ROW and its only power is to turn a strip into a
// KEEP, so a hook that stamps a protected key on some rows and not
// others makes those rows lose DIFFERENT sets. Read a name in this
// line as "at least one row lost this field", never "every row did".
if (preserveAuditIgnored.length > 0) {
this.logger.warn(preserveAuditIgnoredOnInsertWarning(object, preserveAuditIgnored));
}
}
}
// ── [commit a016f08b8] The INSERT POST-IMAGE seam ──────────────────────────────
//
// The enforcement layer's write `check` used to be evaluated in its
// middleware, against `opCtx.data` — the caller's payload as it arrived.
// For an `update` that is a merged pre-image, which is the row that will
// exist; for an `insert` it is the row the caller ASKED for, and the
// hooks above have since produced the row that will actually be stored.
// So the judgement is made HERE, on `rowHookContexts[i].input.data` —
// the same objects `rows` is built from below and the driver is handed.
//
// Placement obeys the rule #8682 wrote for the declared-field door and
// commit b003cf2e8 restated for its post-hook half: a refusal must cost nothing.
// This sits after that door and BEFORE every producer —
// `resolveSystemInsertOrganization`, `encryptSecretFields` (which seals
// a `sys_secret` row), `applyAutonumbers` (which CONSUMES a sequence
// number), validation and the statement.
//
// ## What runs between here and the driver — stated, not waved at
//
// The contract review commit a016f08b8 records measured the version of this comment
// that said "nothing between here and the driver adds a value the caller
// could have steered" and then let TWO caller-steerable passes run after
// the seam. Both now run ABOVE (`stripRuntimeOwnedFields` and the static
// `readonly` strip with its re-default), which is why the seam judges the
// row the driver is handed on every key a caller can reach. What is left
// after this point is engine-owned, and it is a CLOSED list rather than a
// reassurance:
//
// - `resolveSystemInsertOrganization` + the driver's `injectTenantOnInsert`
// fill an ABSENT tenant column; an explicit value on the row is left
// alone, and after the strips above that value is a hook's or the
// caller's own organization. (The Layer 0 tenant wall still judges the
// PRE-hook image — filed separately, and the fix's host is this seam.)
// - `encryptSecretFields` replaces a `secret` field's plaintext with a