Skip to content

Commit 978472f

Browse files
committed
fix(objectql)!: a multi-row insert counts its earlier rows into the parent summary a field-level parent. predicate reads
The multi-row insert read the master-detail header once for the batch, so a detail object's requiredWhen reading a header roll-up (parent.line_count >= 2) judged every row against the summary as it stood before the batch. The batch summary accumulator now overlays the header row too (overlayRow), the way it already overlays the related binding a validation rule reads through a reference, on the write and on the multi-row insert preview. Claude-Session: https://claude.ai/code/session_01ADHkmPgdzD1Rp6LuxSPNpk Co-authored-by: Claude <noreply@anthropic.com>
1 parent b019048 commit 978472f

7 files changed

Lines changed: 227 additions & 17 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a multi-row insert counts its earlier rows into the parent summary a field-level `parent.` predicate reads, as one-by-one inserts do
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. What moves is the summary value a field-level parent. predicate reads during one multi-row insert: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** for a multi-row insert under one master-detail header whose detail object declares a field-level `requiredWhen` that reads a roll-up `summary` of the header (`parent.line_count >= 2`). A bulk create already equals one-by-one creates for a validation rule that reads a parent summary through a reference; this extends that to the header a `requiredWhen` reads as `parent`.
13+
14+
- FROM: `insert(object, rows[])`, `insertMany`, the generic batch create and the import's batched creates read the header once for the batch, so every row judged the summary as it stood before the batch: three bare lines under a header with no lines, against `requiredWhen: 'parent.line_count >= 2'` on `description`, were all admitted.
15+
- TO: each row judges the summary as the batch's earlier admitted rows move it (`count`, and `sum` / `min` / `max` over numbers, the same set the reference arm accumulates): the third line is refused with `VALIDATION_FAILED` (`description`, `required`), as the third of three single inserts is. `insert(array)` refuses the whole batch; `insertMany` reports that row `ok: false` and writes the first two. The multi-row insert preview (`validate` with `mode: 'insert'`, the import's dry run) answers the same.
16+
17+
**Not moved.** A `parent.` predicate that reads a header field that is no summary (`parent.status == 'sent'`), a single-row insert, an update, an unbound header, and an `avg` summary (it keeps reading the stored value) answer as before.
18+
19+
The fix for a caller: supply the field on every row the requirement now names.

‎content/docs/data-modeling/fields.mdx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,11 @@ insert (an import batch, `createManyData`, `insertManyData`) each row's rules
397397
read the summary as it stands after the earlier rows of the same batch that the
398398
rules admitted, accumulated in memory, so two primary contacts in one import
399399
create one row and refuse the other with the rule's error. A row the rules
400-
refuse is not counted. This holds for `count`, and for `sum`, `min` and `max`
400+
refuse is not counted. A detail object's `requiredWhen` that reads the summary
401+
on `parent` (the master-detail header, for example
402+
`requiredWhen: 'parent.line_count >= 2'`) reads it the same way, so the third
403+
of three bare lines in one batch is refused as the third single insert is.
404+
This holds for `count`, and for `sum`, `min` and `max`
401405
over number values. An `avg` summary, a `sum`/`min`/`max` meeting a value that
402406
is not a number, and a summary whose `filter` reads a dotted path through
403407
another reference keep reading the stored value, as they did before.

‎packages/objectql/src/engine-insert.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import { coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFiel
6060
import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedRequiredWhen, preserveAuditIgnoredOnInsertWarning, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js';
6161
import type { staticReadonlyInsertSubject } from './validation/rule-validator.js';
6262
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
63+
import { resolveMasterDetailRelation } from './master-detail.js';
6364
import { recordHookPayloadWrites } from './hook-write-provenance.js';
6465
import type { HookWriteRecording } from './hook-write-provenance.js';
6566
import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js';
@@ -1315,6 +1316,16 @@ export class InsertFacet {
13151316
const batchSummaries = rows.length > 1
13161317
? createBatchSummaryAccumulator(this.getSummaryDescriptors(object), (schemaForValidation as any)?.fields)
13171318
: undefined;
1319+
// [#34466] The same overlay for the master-detail header a field-level
1320+
// `parent.` predicate reads (`requiredWhen: parent.line_count >= 3`):
1321+
// `insertParentForRow` above was read once too, before the batch.
1322+
const insertParentMaster = batchSummaries && insertParentForRow
1323+
? resolveMasterDetailRelation(schemaForValidation as any)?.master
1324+
: undefined;
1325+
const insertParentOf = (row: Record<string, unknown>) => {
1326+
const header = insertParentForRow?.(row);
1327+
return insertParentMaster ? batchSummaries!.overlayRow(insertParentMaster, header) : header;
1328+
};
13181329
// [#18783] The subject's effective object permissions, for an option
13191330
// gated on `current_user.can(…)`: ONE resolution for the whole batch,
13201331
// and none at all unless a row picks such an option. A resolution
@@ -1348,7 +1359,7 @@ export class InsertFacet {
13481359
schemaForValidation, rows[i], suppliedPerRow[i], opCtx.context, msgCtx,
13491360
);
13501361
if (referencesFirst) await checkReferences();
1351-
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentForRow?.(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]) }), this.logger, object);
1362+
emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(schemaForValidation as any, rows[i], 'insert', { logger: this.logger, currentUser: this.buildEvalUser(opCtx.context), skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: msgCtx, parent: insertParentOf(rows[i]), related: batchSummaries ? batchSummaries.overlay(insertRelatedForRow(rows[i])) : insertRelatedForRow(rows[i]), permissions: insertPermissionsFor(rows[i]) }), this.logger, object);
13521363
if (!referencesFirst) await checkReferences();
13531364
// [#25579] Admitted: a later row of this batch reads it in the summary.
13541365
batchSummaries?.accept(rows[i]);

‎packages/objectql/src/engine-validate.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
5050
import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js';
5151
import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js';
5252
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
53+
import { resolveMasterDetailRelation } from './master-detail.js';
5354
import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js';
5455
import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js';
5556
import { isHomeAmountRefusal } from './home-amount-projection.js';
@@ -513,6 +514,11 @@ export async function validate(
513514
const batchSummaries = mode === 'insert' && rows.length > 1
514515
? createBatchSummaryAccumulator(this.getSummaryDescriptors(object), (schemaForValidation as any)?.fields)
515516
: undefined;
517+
// [#34466] And the master-detail header a field-level `parent.` predicate
518+
// reads, overlaid the way the write's `insertParentOf` overlays it.
519+
const previewParentMaster = batchSummaries && previewParents
520+
? resolveMasterDetailRelation(schemaForValidation as any)?.master
521+
: undefined;
516522

517523
// [#26684] Judged one row after another, as the write's validation loop
518524
// judges them: a row's admission (the reference check below) is awaited
@@ -628,7 +634,7 @@ export async function validate(
628634
// [#22474] The header the write binds: the insert's
629635
// `insertParentForRow`, the update's landing header and, for a
630636
// repoint, `roWhenPreviousParent`.
631-
parent: previewParents?.parents[i],
637+
parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i]) : previewParents?.parents[i],
632638
previousParent: previewParents?.previousParents[i],
633639
related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]),
634640
permissions: previewPermissionsFor(row),

‎packages/objectql/src/summary-batch-accumulation.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,27 @@ describe('[#25579] createBatchSummaryAccumulator — what it leaves as it was',
130130
expect(acc.overlay(undefined)).toBeUndefined();
131131
});
132132
});
133+
134+
describe('[#34466] overlayRow — the master-detail header a field-level parent. predicate reads', () => {
135+
it('moves the summary on a header row of the roll-up\'s parent object, on a copy', () => {
136+
const acc = createBatchSummaryAccumulator([desc({ summaryField: 'lines', fn: 'count', sourceField: undefined })], CHILD_FIELDS)!;
137+
const header = { id: 'o1', lines: 1, status: 'draft' };
138+
acc.accept({ order: 'o1' });
139+
acc.accept({ order: 'o1' });
140+
expect(acc.overlayRow('xt_order', header)).toEqual({ id: 'o1', lines: 3, status: 'draft' });
141+
expect(header.lines).toBe(1);
142+
});
143+
144+
it('leaves as it was: an unbound header, another parent, another object, a header not handed the summary', () => {
145+
const acc = createBatchSummaryAccumulator([desc({ summaryField: 'lines', fn: 'count', sourceField: undefined })], CHILD_FIELDS)!;
146+
acc.accept({ order: 'o1' });
147+
expect(acc.overlayRow('xt_order', null)).toBeNull();
148+
expect(acc.overlayRow('xt_order', undefined)).toBeUndefined();
149+
const other = { id: 'o2', lines: 0 };
150+
expect(acc.overlayRow('xt_order', other)).toBe(other);
151+
const elsewhere = { id: 'o1', lines: 0 };
152+
expect(acc.overlayRow('xt_quote', elsewhere)).toBe(elsewhere);
153+
const narrow = { id: 'o1', status: 'draft' };
154+
expect(acc.overlayRow('xt_order', narrow)).toBe(narrow);
155+
});
156+
});

‎packages/objectql/src/summary-batch-accumulation.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
* aggregation's own walker ({@link matchesAggregationFilter}), so a row the
3232
* filter excludes counts for nothing, as it counts for nothing in the
3333
* recompute.
34+
* - [#34466] The same value reaches a field-level `parent.` predicate
35+
* (`requiredWhen: parent.line_count >= 3`): the master-detail header it
36+
* reads is one row, not a related binding, and {@link
37+
* BatchSummaryAccumulator.overlayRow} overlays it the same way. An unbound
38+
* header stays unbound.
3439
*
3540
* ## Which roll-ups accumulate exactly
3641
*
@@ -69,6 +74,15 @@ export interface BatchSummaryAccumulator {
6974
* row moves is returned as it is.
7075
*/
7176
overlay(binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined;
77+
/**
78+
* [#34466] `row`, a stored row of `object`, carrying the summary values the
79+
* batch's admitted rows move it to: the master-detail header a field-level
80+
* `parent.` predicate (`requiredWhen`) reads, which reaches the rules as one
81+
* row and not as a related binding. A copy; `row` itself is never mutated.
82+
* A row no admitted row moves, and an unbound header (`null` /
83+
* `undefined`, the fail-closed signal), are returned as they are.
84+
*/
85+
overlayRow<R extends Record<string, unknown> | null | undefined>(object: string, row: R): R;
7286
/** Count `row` in. Call it only once the row's rules have admitted it. */
7387
accept(row: Record<string, unknown>): void;
7488
}
@@ -167,25 +181,31 @@ export function createBatchSummaryAccumulator(
167181
}
168182
};
169183

184+
/** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */
185+
const patchRow = (object: string, row: Record<string, unknown>): Record<string, unknown> | undefined => {
186+
const parentId = singleId(row.id);
187+
if (parentId === undefined) return undefined;
188+
let patched: Record<string, unknown> | undefined;
189+
for (const [desc, byParent] of deltas) {
190+
if (dropped.has(desc) || desc.parentObject !== object) continue;
191+
if (!(desc.summaryField in row)) continue; // the reader was not handed this roll-up
192+
const delta = byParent.get(parentId);
193+
if (!delta) continue;
194+
const value = moved(desc, row[desc.summaryField], delta);
195+
if (value === undefined) continue;
196+
patched ??= { ...row };
197+
patched[desc.summaryField] = value;
198+
}
199+
return patched;
200+
};
201+
170202
const overlay = (binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined => {
171203
if (!binding || deltas.size === 0) return binding;
172204
let out: Record<string, RelatedFieldBinding> | undefined;
173205
for (const [fk, entry] of Object.entries(binding)) {
174206
const related = entry.row;
175207
if (!related) continue;
176-
const parentId = singleId(related.id);
177-
if (parentId === undefined) continue;
178-
let patched: Record<string, unknown> | undefined;
179-
for (const [desc, byParent] of deltas) {
180-
if (dropped.has(desc) || desc.parentObject !== entry.object) continue;
181-
if (!(desc.summaryField in related)) continue; // the rule does not read this roll-up
182-
const delta = byParent.get(parentId);
183-
if (!delta) continue;
184-
const value = moved(desc, related[desc.summaryField], delta);
185-
if (value === undefined) continue;
186-
patched ??= { ...related };
187-
patched[desc.summaryField] = value;
188-
}
208+
const patched = patchRow(entry.object, related);
189209
if (patched) {
190210
out ??= { ...binding };
191211
out[fk] = { ...entry, row: patched };
@@ -194,5 +214,10 @@ export function createBatchSummaryAccumulator(
194214
return out ?? binding;
195215
};
196216

197-
return { accept, overlay };
217+
const overlayRow = <R extends Record<string, unknown> | null | undefined>(object: string, row: R): R => {
218+
if (!row || deltas.size === 0) return row;
219+
return (patchRow(object, row) as R | undefined) ?? row;
220+
};
221+
222+
return { accept, overlay, overlayRow };
198223
}

0 commit comments

Comments
 (0)