Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/34466-batch-insert-parent-summary-predicate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/objectql': patch
---

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

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- 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. -->

**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`.

- 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.
- 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.

**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.

The fix for a caller: supply the field on every row the requirement now names.
6 changes: 5 additions & 1 deletion content/docs/data-modeling/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,11 @@ insert (an import batch, `createManyData`, `insertManyData`) each row's rules
read the summary as it stands after the earlier rows of the same batch that the
rules admitted, accumulated in memory, so two primary contacts in one import
create one row and refuse the other with the rule's error. A row the rules
refuse is not counted. This holds for `count`, and for `sum`, `min` and `max`
refuse is not counted. A detail object's `requiredWhen` that reads the summary
on `parent` (the master-detail header, for example
`requiredWhen: 'parent.line_count >= 2'`) reads it the same way, so the third
of three bare lines in one batch is refused as the third single insert is.
This holds for `count`, and for `sum`, `min` and `max`
over number values. An `avg` summary, a `sum`/`min`/`max` meeting a value that
is not a number, and a summary whose `filter` reads a dotted path through
another reference keep reading the stored value, as they did before.
Expand Down
13 changes: 12 additions & 1 deletion packages/objectql/src/engine-insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ import { coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFiel
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 { resolveMasterDetailRelation } from './master-detail.js';
import { recordHookPayloadWrites } from './hook-write-provenance.js';
import type { HookWriteRecording } from './hook-write-provenance.js';
import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js';
Expand Down Expand Up @@ -1315,6 +1316,16 @@ export class InsertFacet {
const batchSummaries = rows.length > 1
? createBatchSummaryAccumulator(this.getSummaryDescriptors(object), (schemaForValidation as any)?.fields)
: undefined;
// [#34466] The same overlay for the master-detail header a field-level
// `parent.` predicate reads (`requiredWhen: parent.line_count >= 3`):
// `insertParentForRow` above was read once too, before the batch.
const insertParentMaster = batchSummaries && insertParentForRow
? resolveMasterDetailRelation(schemaForValidation as any)?.master
: undefined;
const insertParentOf = (row: Record<string, unknown>) => {
const header = insertParentForRow?.(row);
return insertParentMaster ? batchSummaries!.overlayRow(insertParentMaster, header) : header;
};
// [#18783] The subject's effective object permissions, for an option
// gated on `current_user.can(…)`: ONE resolution for the whole batch,
// and none at all unless a row picks such an option. A resolution
Expand Down Expand Up @@ -1348,7 +1359,7 @@ export class InsertFacet {
schemaForValidation, rows[i], suppliedPerRow[i], opCtx.context, msgCtx,
);
if (referencesFirst) await checkReferences();
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);
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);
if (!referencesFirst) await checkReferences();
// [#25579] Admitted: a later row of this batch reads it in the summary.
batchSummaries?.accept(rows[i]);
Expand Down
8 changes: 7 additions & 1 deletion packages/objectql/src/engine-validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js';
import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js';
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
import { resolveMasterDetailRelation } from './master-detail.js';
import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js';
import { assertFollowedCurrencyCodesUnchanged, parentCurrencyLockReads, touchesFollowedCurrencyCode } from './record-currency-parent-lock.js';
import { isHomeAmountRefusal } from './home-amount-projection.js';
Expand Down Expand Up @@ -513,6 +514,11 @@ export async function validate(
const batchSummaries = mode === 'insert' && rows.length > 1
? createBatchSummaryAccumulator(this.getSummaryDescriptors(object), (schemaForValidation as any)?.fields)
: undefined;
// [#34466] And the master-detail header a field-level `parent.` predicate
// reads, overlaid the way the write's `insertParentOf` overlays it.
const previewParentMaster = batchSummaries && previewParents
? resolveMasterDetailRelation(schemaForValidation as any)?.master
: undefined;

// [#26684] Judged one row after another, as the write's validation loop
// judges them: a row's admission (the reference check below) is awaited
Expand Down Expand Up @@ -628,7 +634,7 @@ export async function validate(
// [#22474] The header the write binds: the insert's
// `insertParentForRow`, the update's landing header and, for a
// repoint, `roWhenPreviousParent`.
parent: previewParents?.parents[i],
parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i]) : previewParents?.parents[i],
previousParent: previewParents?.previousParents[i],
related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]),
permissions: previewPermissionsFor(row),
Expand Down
24 changes: 24 additions & 0 deletions packages/objectql/src/summary-batch-accumulation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,27 @@ describe('[#25579] createBatchSummaryAccumulator — what it leaves as it was',
expect(acc.overlay(undefined)).toBeUndefined();
});
});

describe('[#34466] overlayRow — the master-detail header a field-level parent. predicate reads', () => {
it('moves the summary on a header row of the roll-up\'s parent object, on a copy', () => {
const acc = createBatchSummaryAccumulator([desc({ summaryField: 'lines', fn: 'count', sourceField: undefined })], CHILD_FIELDS)!;
const header = { id: 'o1', lines: 1, status: 'draft' };
acc.accept({ order: 'o1' });
acc.accept({ order: 'o1' });
expect(acc.overlayRow('xt_order', header)).toEqual({ id: 'o1', lines: 3, status: 'draft' });
expect(header.lines).toBe(1);
});

it('leaves as it was: an unbound header, another parent, another object, a header not handed the summary', () => {
const acc = createBatchSummaryAccumulator([desc({ summaryField: 'lines', fn: 'count', sourceField: undefined })], CHILD_FIELDS)!;
acc.accept({ order: 'o1' });
expect(acc.overlayRow('xt_order', null)).toBeNull();
expect(acc.overlayRow('xt_order', undefined)).toBeUndefined();
const other = { id: 'o2', lines: 0 };
expect(acc.overlayRow('xt_order', other)).toBe(other);
const elsewhere = { id: 'o1', lines: 0 };
expect(acc.overlayRow('xt_quote', elsewhere)).toBe(elsewhere);
const narrow = { id: 'o1', status: 'draft' };
expect(acc.overlayRow('xt_order', narrow)).toBe(narrow);
});
});
53 changes: 39 additions & 14 deletions packages/objectql/src/summary-batch-accumulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@
* aggregation's own walker ({@link matchesAggregationFilter}), so a row the
* filter excludes counts for nothing, as it counts for nothing in the
* recompute.
* - [#34466] The same value reaches a field-level `parent.` predicate
* (`requiredWhen: parent.line_count >= 3`): the master-detail header it
* reads is one row, not a related binding, and {@link
* BatchSummaryAccumulator.overlayRow} overlays it the same way. An unbound
* header stays unbound.
*
* ## Which roll-ups accumulate exactly
*
Expand Down Expand Up @@ -69,6 +74,15 @@ export interface BatchSummaryAccumulator {
* row moves is returned as it is.
*/
overlay(binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined;
/**
* [#34466] `row`, a stored row of `object`, carrying the summary values the
* batch's admitted rows move it to: the master-detail header a field-level
* `parent.` predicate (`requiredWhen`) reads, which reaches the rules as one
* row and not as a related binding. A copy; `row` itself is never mutated.
* A row no admitted row moves, and an unbound header (`null` /
* `undefined`, the fail-closed signal), are returned as they are.
*/
overlayRow<R extends Record<string, unknown> | null | undefined>(object: string, row: R): R;
/** Count `row` in. Call it only once the row's rules have admitted it. */
accept(row: Record<string, unknown>): void;
}
Expand Down Expand Up @@ -167,25 +181,31 @@ export function createBatchSummaryAccumulator(
}
};

/** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */
const patchRow = (object: string, row: Record<string, unknown>): Record<string, unknown> | undefined => {
const parentId = singleId(row.id);
if (parentId === undefined) return undefined;
let patched: Record<string, unknown> | undefined;
for (const [desc, byParent] of deltas) {
if (dropped.has(desc) || desc.parentObject !== object) continue;
if (!(desc.summaryField in row)) continue; // the reader was not handed this roll-up
const delta = byParent.get(parentId);
if (!delta) continue;
const value = moved(desc, row[desc.summaryField], delta);
if (value === undefined) continue;
patched ??= { ...row };
patched[desc.summaryField] = value;
}
return patched;
};

const overlay = (binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined => {
if (!binding || deltas.size === 0) return binding;
let out: Record<string, RelatedFieldBinding> | undefined;
for (const [fk, entry] of Object.entries(binding)) {
const related = entry.row;
if (!related) continue;
const parentId = singleId(related.id);
if (parentId === undefined) continue;
let patched: Record<string, unknown> | undefined;
for (const [desc, byParent] of deltas) {
if (dropped.has(desc) || desc.parentObject !== entry.object) continue;
if (!(desc.summaryField in related)) continue; // the rule does not read this roll-up
const delta = byParent.get(parentId);
if (!delta) continue;
const value = moved(desc, related[desc.summaryField], delta);
if (value === undefined) continue;
patched ??= { ...related };
patched[desc.summaryField] = value;
}
const patched = patchRow(entry.object, related);
if (patched) {
out ??= { ...binding };
out[fk] = { ...entry, row: patched };
Expand All @@ -194,5 +214,10 @@ export function createBatchSummaryAccumulator(
return out ?? binding;
};

return { accept, overlay };
const overlayRow = <R extends Record<string, unknown> | null | undefined>(object: string, row: R): R => {
if (!row || deltas.size === 0) return row;
return (patchRow(object, row) as R | undefined) ?? row;
};

return { accept, overlay, overlayRow };
}
Loading
Loading