From 978472fc64dc0b210a774f19455ac2c94635a4c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:03:23 +0000 Subject: [PATCH] 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 --- ...6-batch-insert-parent-summary-predicate.md | 19 +++ content/docs/data-modeling/fields.mdx | 6 +- packages/objectql/src/engine-insert.ts | 13 +- packages/objectql/src/engine-validate.ts | 8 +- .../src/summary-batch-accumulation.test.ts | 24 ++++ .../src/summary-batch-accumulation.ts | 53 ++++++-- packages/objectql/src/summary-rollup.test.ts | 121 ++++++++++++++++++ 7 files changed, 227 insertions(+), 17 deletions(-) create mode 100644 .changeset/34466-batch-insert-parent-summary-predicate.md diff --git a/.changeset/34466-batch-insert-parent-summary-predicate.md b/.changeset/34466-batch-insert-parent-summary-predicate.md new file mode 100644 index 00000000000..af44ad8bfca --- /dev/null +++ b/.changeset/34466-batch-insert-parent-summary-predicate.md @@ -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 + + + +**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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 571a1556abe..9e567187800 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -397,7 +397,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. diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 566b36a8bca..465d01f2f2b 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -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'; @@ -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) => { + 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 @@ -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]); diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 55a80d424bc..25fd9f73b01 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -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'; @@ -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 @@ -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), diff --git a/packages/objectql/src/summary-batch-accumulation.test.ts b/packages/objectql/src/summary-batch-accumulation.test.ts index 7824fed499f..24116c5964e 100644 --- a/packages/objectql/src/summary-batch-accumulation.test.ts +++ b/packages/objectql/src/summary-batch-accumulation.test.ts @@ -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); + }); +}); diff --git a/packages/objectql/src/summary-batch-accumulation.ts b/packages/objectql/src/summary-batch-accumulation.ts index e6bce6af527..6d5e97b4ab7 100644 --- a/packages/objectql/src/summary-batch-accumulation.ts +++ b/packages/objectql/src/summary-batch-accumulation.ts @@ -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 * @@ -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 | null | undefined>(object: string, row: R): R; /** Count `row` in. Call it only once the row's rules have admitted it. */ accept(row: Record): void; } @@ -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): Record | undefined => { + const parentId = singleId(row.id); + if (parentId === undefined) return undefined; + let patched: Record | 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 | 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 | 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 }; @@ -194,5 +214,10 @@ export function createBatchSummaryAccumulator( return out ?? binding; }; - return { accept, overlay }; + const overlayRow = | 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 }; } diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index f12787bed00..0a4236c9c05 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -7,6 +7,8 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { ObjectQL } from './engine.js'; import { ObjectSchema } from '@objectstack/spec/data'; +import { mapDataError } from '@objectstack/types'; +import { ValidationError } from './validation/record-validator.js'; function makeDriver() { const stores = new Map>(); @@ -1260,3 +1262,122 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { expect(aggregateReads(before)).toBe(0); }); }); + +// [#34466] A multi-row insert under one header answers a field-level +// `parent.` predicate the way inserting the rows one by one does +// (#25579's 「批量等于逐条」, extended from the related binding a rule reads +// through a reference to the master-detail header a `requiredWhen` reads as +// `parent`). The header is read once for the batch; the rows the rules have +// admitted are accumulated in memory and overlaid on it for each later row. +// +// Reverse verification, predicted before running: drop the header overlay and +// the atomic, partial, and preview cases go red (every row reads `line_count` +// 0, so all three rows are admitted); the one-by-one, the CONTROL predicate +// reading `parent.status`, and the unbound-header cases stay green. +describe('[#34466] a multi-row insert accumulates its earlier rows into the parent summary a field-level parent. predicate reads', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + status: { type: 'text' }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'count' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'inv_line', + fields: { + amount: { type: 'number' }, + inv: { type: 'master_detail', reference: 'inv' }, + // THE SUBJECT: from the third line on, a line carries a description. + description: { type: 'text', requiredWhen: 'parent.line_count >= 2' }, + // CONTROL: reads a header field that is no summary. + note: { type: 'text', requiredWhen: "parent.status == 'sent'" }, + }, + } as any); + }); + + const lines = (inv: string) => [...storeFor('inv_line').values()].filter((r) => r.inv === inv); + const threeBare = (inv: string) => [{ inv, amount: 1 }, { inv, amount: 2 }, { inv, amount: 3 }]; + + /** The refusal the third row earns: `required` on `description`, in the ADR-0112 envelope the data door maps to 400. */ + function expectDescriptionRequired(err: unknown): void { + expect(err).toBeInstanceOf(ValidationError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => ({ field: f.field, code: f.code }))).toEqual([{ field: 'description', code: 'required' }]); + } + + async function refusalOf(write: Promise): Promise { + try { await write; } catch (err) { return err; } + throw new Error('expected the write to be refused'); + } + + it('one by one (the reference answer): the first two lines are admitted, the third is refused', async () => { + const p = await engine.insert('inv', { name: 'INV-1', status: 'draft' }); + const [a, b, c] = threeBare(p.id); + await engine.insert('inv_line', a); + await engine.insert('inv_line', b); + expectDescriptionRequired(await refusalOf(engine.insert('inv_line', c))); + expect(lines(p.id)).toHaveLength(2); + expect(storeFor('inv').get(p.id).line_count).toBe(2); + }); + + it('insert(array), all or nothing: the third row is refused as one by one refuses it, and nothing is written', async () => { + const p = await engine.insert('inv', { name: 'INV-1', status: 'draft' }); + expectDescriptionRequired(await refusalOf(engine.insert('inv_line', threeBare(p.id)))); + expect(lines(p.id)).toHaveLength(0); + }); + + it('insertMany, per-row outcome: the first two rows land, the third carries the refusal', async () => { + const p = await engine.insert('inv', { name: 'INV-1', status: 'draft' }); + const out = await engine.insertMany('inv_line', threeBare(p.id)); + expect(out.map((o) => o.ok)).toEqual([true, true, false]); + expectDescriptionRequired((out[2] as { ok: false; error: unknown }).error); + expect(lines(p.id)).toHaveLength(2); + expect(storeFor('inv').get(p.id).line_count).toBe(2); + }); + + it('a refused row moves nothing: with the second row refused, the third reads one earlier line and is admitted', async () => { + const p = await engine.insert('inv', { name: 'INV-1', status: 'draft' }); + // The second row is refused on its own (a non-number amount), so the batch + // counts one admitted row before the third, as one by one would store one. + const out = await engine.insertMany('inv_line', [{ inv: p.id, amount: 1 }, { inv: p.id, amount: 'x' }, { inv: p.id, amount: 3 }]); + expect(out.map((o) => o.ok)).toEqual([true, false, true]); + expect(lines(p.id)).toHaveLength(2); + }); + + it('the rows of the batch count per header: two headers, two lines each, all admitted', async () => { + const p = await engine.insert('inv', { name: 'P', status: 'draft' }); + const q = await engine.insert('inv', { name: 'Q', status: 'draft' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 1 }, { inv: q.id, amount: 1 }, { inv: p.id, amount: 2 }, { inv: q.id, amount: 2 }]); + expect(storeFor('inv').get(p.id).line_count).toBe(2); + expect(storeFor('inv').get(q.id).line_count).toBe(2); + }); + + it('CONTROL: a parent. predicate reading a field that is no summary answers as before — draft admits the batch, sent refuses its first row', async () => { + const draft = await engine.insert('inv', { name: 'D', status: 'draft' }); + const sent = await engine.insert('inv', { name: 'S', status: 'sent' }); + await engine.insert('inv_line', [{ inv: draft.id, amount: 1, description: 'x' }, { inv: draft.id, amount: 2, description: 'x' }]); + expect(lines(draft.id)).toHaveLength(2); + const out = await engine.insertMany('inv_line', [{ inv: sent.id, amount: 1, description: 'x' }, { inv: sent.id, amount: 2, description: 'x', note: 'n' }]); + expect(out.map((o) => o.ok)).toEqual([false, true]); + expect((out[0] as { ok: false; error: ValidationError }).error.fields.map((f) => ({ field: f.field, code: f.code }))).toEqual([{ field: 'note', code: 'required' }]); + }); + + it('the multi-row insert preview answers the write: the third row is not valid', async () => { + const p = await engine.insert('inv', { name: 'INV-1', status: 'draft' }); + const out = await engine.validate('inv_line', threeBare(p.id), { mode: 'insert' }); + expect(out.results!.map((r) => r.valid)).toEqual([true, true, false]); + expect(out.results![2]!.errors.map((e) => ({ field: e.field, code: e.code }))).toEqual([{ field: 'description', code: 'required' }]); + expect(lines(p.id)).toHaveLength(0); + }); +});