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
2 changes: 1 addition & 1 deletion .changeset/34465-predicate-update-parent-summary-rule.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/objectql': patch
---
Expand All @@ -9,7 +9,7 @@

<!-- 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 rule reads while one predicate update is judged: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** for a predicate update (`update(object, patch, { where, multi: true })`, a flow `update_record` step with `multi: true`) of a child object whose validation rule reads a roll-up `summary` of a parent one hop through a reference (`record.inv.primaries > 0`), or whose field-level `requiredWhen` reads one on `parent` (`parent.line_count >= 3`), or that reads a `formula` or stored computed field of the parent calculated from one (`record.project.remaining`, `remaining = budget - spent`). A bulk create and a bulk update already equal one-by-one writes for a rule reading the summary itself (a bulk create does not yet for a rule reading a parent field calculated from one: its accumulator moves the summary key alone, #34821); this extends that to the update that selects its rows by a filter, calculated parent fields included.
**BREAKING** for a predicate update (`update(object, patch, { where, multi: true })`, a flow `update_record` step with `multi: true`) of a child object whose validation rule reads a roll-up `summary` of a parent one hop through a reference (`record.inv.primaries > 0`), or whose field-level `requiredWhen` reads one on `parent` (`parent.line_count >= 3`), or that reads a `formula` or stored computed field of the parent calculated from one (`record.project.remaining`, `remaining = budget - spent`). A bulk create and a bulk update already equal one-by-one writes for a rule reading the summary itself; this extends that to the update that selects its rows by a filter, calculated parent fields included.

- FROM: the matched rows' related parents and master-detail headers were read once, and every row judged the summary as it stood before the update: "one primary line per invoice" (`record.is_primary == true && record.inv.primaries > 0`) refused the second of two lines made primary one by one, and admitted both made primary by one predicate update.
- TO: each matched row judges the summary as the rows judged before it leave it, for `count`, `sum`, `min`, `max` and `avg`, a row moving to another parent included: the base is read in the database (every child as stored for `count` / `sum` / `avg`, the children outside the matched set for `min` / `max`, one grouped aggregate per summary a rule reads) and the matched rows are folded in memory. A parent field calculated from a folded summary is computed again over the parent with the folded value. The update is refused with `VALIDATION_FAILED` and writes nothing, as it does for any refused row. Only an object with such a rule, on an update matching more than one row, reads the base (and, when a calculated field reads a folded summary, the parents' stored rows once).
Expand Down
23 changes: 23 additions & 0 deletions .changeset/34821-rollup-fold-followups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/objectql': patch
---

fix(objectql)!: a multi-row insert judges a rule reading a parent field calculated from a roll-up as one-by-one inserts judge it

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 of the package entry changes shape. What moves is the value a rule reads for a parent formula or stored computed field while one multi-row insert is judged, and the value a predicate update's rule reads for a roll-up its patch cannot move: 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 (`insert(object, rows)`, an import batch, `insertMany`) of a child object whose validation rule, or field-level `requiredWhen` on `parent`, reads a `formula` or stored computed field of the parent calculated from a roll-up `summary` (`record.bud.remaining`, `remaining = budget - total`).

- FROM: the batch moved the parent roll-up itself by the rows admitted before each row, but a parent field calculated from it kept its stored value: "a line may not exceed the remaining budget" (`record.amount > record.bud.remaining`) refused the third line of 40 against a budget of 100 written one by one, and admitted all three written in one call.
- TO: the field is computed again over the moved roll-ups, as a predicate update already computes it, carrying the parent's stored image from row to row as each one-by-one recompute stores it. The batch is refused with `VALIDATION_FAILED` and writes nothing, as for any refused row; the insert preview (`validate` with `mode: 'insert'`) answers the same row invalid, and judges a master-detail header column the caller is not served as empty at every row. Only a batch with a rule reading that parent pays one read of its parent rows.
- The answer moves both ways. Mostly it narrows: a row main admitted against the stored calculated value is refused when the rows before it move that value over the rule's line. It also admits a row main refused when the rows before it move the value back under the line, as one by one does.
- A calculated field that also reads a roll-up the insert does not move (an `avg`, a filter through a reference, or one left stored from the row where it meets a value that is not a number) is computed over the moved and the stored values as they stand.

The insert accumulation also leaves out a roll-up whose `filter` reads a related record in the nested form (`{ account: { status: 'x' } }`), as it already left out the dotted form and as the predicate update leaves out both.

A predicate update (`multi: true`) whose patch writes no foreign key, source field or field the filter reads (as a key, or as a `{ $field }` comparand or `addDays` offset) of a roll-up its rules read no longer aggregates a base for it: its rules read the stored value, as the by-id update does, with no aggregate read. So the 34465 note's "one grouped aggregate per summary a rule reads" and its three stored-value cases hold for the roll-ups the patch can move; one it cannot move is neither aggregated nor folded. Each roll-up a predicate update leaves unfolded now logs one debug line naming the object, parent, field and reason (`filter`, `not_a_number`, `exclusion_budget`).

The fix for a caller: insert the rows the rule refuses on their own, or split the batch so each part fits the rule.
20 changes: 16 additions & 4 deletions content/docs/data-modeling/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -468,10 +468,19 @@ 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.
A rule that reads a formula or a stored computed field of the parent calculated
from the summary (`record.budget.remaining`, `parent.headroom < 50`) reads it
calculated over the summary as the earlier rows moved it, so a row is refused,
or admitted, as the same row inserted on its own after them would be.
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.
is not a number, and a summary whose `filter` reads through another reference,
as a dotted path or in the nested form `{ account: { status: 'x' } }`, keep
reading the stored value, as they did before; a field calculated from one of
them and from a summary that moves reads the first as stored. A preview of the
batch (`validate` in insert mode) judges each row the same way, except that a
column of the master-detail header the caller is not served reads as empty at
every row.
An import's **dry run** previews its create rows in the batches the import
writes them in (200 rows each) and refuses the rows the import refuses, with
the same message. It writes nothing, so a row in a later batch reads the
Expand Down Expand Up @@ -505,8 +514,11 @@ reference, a detail object's `requiredWhen` reading it on `parent`, and a rule
reading a formula or stored computed field of the parent calculated from it,
read it as the matched rows judged before leave it, for every summary function,
`avg` included, and a row that moves to another parent leaves the old one and
joins the new one. If any row is refused, none is written. Three cases keep
reading the stored value for every parent the update reads that summary for: a
joins the new one. If any row is refused, none is written. Four cases keep
reading the stored value for every parent the update reads that summary for,
as a by-id update reads it: a summary the patch cannot move (it writes neither
the reference to the parent, nor the summed field, nor a field the summary's
`filter` reads, as a key or as a `{ $field }` comparand), a
summary whose `filter` reads through another reference, as a dotted path or in
the nested form `{ account: { status: 'x' } }` (or one the in-memory filter
cannot evaluate), a summary meeting a value that is not a number, and a `min` / `max`
Expand Down
14 changes: 14 additions & 0 deletions packages/objectql/src/engine-insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,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 { attachInsertSummaryDependents } from './engine-update.js';
import { resolveMasterDetailRelation } from './master-detail.js';
import { recordHookPayloadWrites } from './hook-write-provenance.js';
import type { HookWriteRecording } from './hook-write-provenance.js';
Expand Down Expand Up @@ -1363,6 +1364,19 @@ export class InsertFacet {
const header = insertParentForRow?.(row);
return insertParentMaster ? batchSummaries!.overlayRow(insertParentMaster, header) : header;
};
// [#34821] And a formula or stored computed field of such a parent
// calculated from an accumulated roll-up (`remaining = budget -
// total`), computed again over the moved values as the predicate
// update's fold computes it. Loaded only for the parents a rule of
// this batch reads (a related binding or a header): an insert no rule
// reads a parent of pays nothing here.
if (batchSummaries) {
await attachInsertSummaryDependents(
this, batchSummaries, rows, insertRelatedForRow, insertParentMaster,
insertParentForRow ? (i) => insertParentForRow(rows[i]) : undefined,
opCtx.context, (i) => rowErrors[i] !== undefined,
);
}
// [#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
9 changes: 8 additions & 1 deletion packages/objectql/src/engine-master-detail-related.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,9 @@ export async function settleMasterDetailLanding<H>(
* is judged as empty: the header is materialised over the master's declared
* fields after the columns are kept, so such a column reads `null`. So the
* verdict never depends on a header value the caller could not have read in
* full.
* full. [#34821] `servedColumns[i]` names the columns kept for `parents[i]`:
* a multi-row preview moves and computes the batch's roll-ups onto those
* only, so a withheld column reads `null` at every row.
*/
export async function resolvePreviewParents(
this: Pick<MasterDetailRelatedHost, 'find' | 'logger' | 'resolveMasterDetailParents' | 'materializeParentHeader'>,
Expand All @@ -300,6 +302,7 @@ export async function resolvePreviewParents(
): Promise<{
parents: Array<Record<string, unknown> | null>;
previousParents: Array<Record<string, unknown> | null | undefined>;
servedColumns: Array<ReadonlySet<string> | null>;
}> {
const rel = resolveMasterDetailRelation(schema as any);
const landingIds = views.map((view) => (rel ? masterIdOf(rel.fk, null, view) : undefined));
Expand All @@ -318,6 +321,8 @@ export async function resolvePreviewParents(
priorIds.forEach((id, i) => { if (repoints[i]) ids.add(String(id)); });

const headers = new Map<string, Record<string, unknown>>();
/** [#34821] Header id → the columns kept: what a batch overlay may move or compute onto. */
const keptColumns = new Map<string, ReadonlySet<string>>();
// [#24358] ⛔ A stored-metadata-body header is never read here either, as
// the write's own header read never reads one: every header binds unbound.
if (rel && ids.size > 0 && !isStoredMetadataBodyObject(rel.master)) {
Expand Down Expand Up @@ -351,13 +356,15 @@ export async function resolvePreviewParents(
}
}
headers.set(id, this.materializeParentHeader(rel.master, kept));
keptColumns.set(id, new Set(Object.keys(kept)));
}
}
}
const headerOf = (id: string | number | undefined) => (id == null ? null : (headers.get(String(id)) ?? null));
return {
parents: landingIds.map(headerOf),
previousParents: priorIds.map((id, i) => (priorUnknown[i] ? null : repoints[i] ? headerOf(id) : undefined)),
servedColumns: landingIds.map((id) => (id == null ? null : (keptColumns.get(String(id)) ?? null))),
};
}

Expand Down
56 changes: 51 additions & 5 deletions packages/objectql/src/engine-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@ import type { ReferentialClearExemption } from './validation/rule-validator.js';
import { recordHookPayloadWrites } from './hook-write-provenance.js';
import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js';
import { resolveMasterDetailRelation } from './master-detail.js';
import { createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases } from './summary-batch-accumulation.js';
import type { SummaryDependents } from './summary-batch-accumulation.js';
import { createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases, summaryPatchCanMove } from './summary-batch-accumulation.js';
import type { BatchSummaryAccumulator, SummaryDependents, SummaryFoldStandDownSink } from './summary-batch-accumulation.js';
import type { RelatedRecordBinding } from './validation/rule-validator.js';
import { SUMMARY_GROUPED_AGGREGATE_CHUNK } from './summary-aggregate.js';
import { declaredColumnSet, rowsWithDeclaredColumnsOnly, selectedStoredColumns, storedColumnsLeftUnwritten, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js';
import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external-driver-floor.js';
Expand Down Expand Up @@ -2221,15 +2222,25 @@ export class UpdateFacet {
// rule reads one and more than one row matched; still all
// rows judged before the one `updateMany`.
const matchedRows = priorRows ?? [];
const readSummaries = matchedRows.length > 1 ? this.summaryDescriptorsReadByRules(object) : [];
// [#34821] A roll-up the patch cannot move (it writes no
// foreign key, source or filter field of it) is not folded:
// its rules read the stored value, as the by-id update does.
const readSummaries = matchedRows.length > 1
? this.summaryDescriptorsReadByRules(object).filter((desc) => summaryPatchCanMove(desc, bulkPatch))
: [];
const matchedStates = readSummaries.length > 0
? matchedRows.map((row) => ({ previous: row ?? {}, next: { ...(row ?? {}), ...bulkPatch } }))
: [];
// [#34821] A roll-up left unfolded leaves one trace, naming it and why.
const standDown: SummaryFoldStandDownSink = (desc, reason) => this.logger.debug('Roll-up left unfolded in a predicate update: its rules read the stored value', {
object, parentObject: desc.parentObject, field: desc.summaryField, reason,
});
const summaryFold = readSummaries.length > 0
? createPredicateUpdateSummaryFold(
await loadPredicateUpdateSummaryBases(this.facade, readSummaries, matchedStates, { ...(opCtx.context ?? {}), isSystem: true }),
await loadPredicateUpdateSummaryBases(this.facade, readSummaries, matchedStates, { ...(opCtx.context ?? {}), isSystem: true }, standDown),
matchedStates,
(updateSchema as any)?.fields,
standDown,
)
: undefined;
if (summaryFold) {
Expand Down Expand Up @@ -2510,6 +2521,8 @@ export class UpdateFacet {
* through another such field (`remaining = budget - spent`, `spent` a
* roll-up). A rule reading `record.project.remaining` reads such a field, and
* one by one it would read it over the roll-up the earlier rows moved.
* [#34821] A multi-row insert's accumulator reads the same, for the roll-ups
* its admitted rows move (`engine-insert.ts`).
*
* Read the way a by-id update's rule reads the parent: the values as SYSTEM
* (`resolvePredicateRelated` reads related rows under system authority). So
Expand Down Expand Up @@ -2551,7 +2564,38 @@ export class UpdateFacet {
* ({@link applyFormulaPlan}). An object no such field reads a folded roll-up
* of reads nothing.
*/
async function loadSummaryFoldDependents(
/**
* [#34821] Hand a multi-row insert's accumulator what computes its parents'
* fields calculated from the roll-ups it moves ({@link loadSummaryFoldDependents}),
* for the parents a rule of the batch reads: a related row bound for a row
* (`relatedFor`) or the master-detail header (`master`, through `headerFor`).
* An insert no rule of which reads a parent reads nothing here. One door for
* the write (`insert()`) and its preview (`validate()`, mode insert), so the
* preview judges the batch the way the write does. `skip(i)` names a row the
* door already refused.
*/
export async function attachInsertSummaryDependents(
host: Parameters<typeof loadSummaryFoldDependents>[0],
accumulator: BatchSummaryAccumulator,
rows: readonly Record<string, unknown>[],
relatedFor: (row: Record<string, unknown>) => RelatedRecordBinding | undefined,
master: string | undefined,
headerFor: ((i: number) => unknown) | undefined,
context: Parameters<typeof loadSummaryFoldDependents>[2],
skip: (i: number) => boolean = () => false,
): Promise<void> {
const readParents = new Set<string>();
for (let i = 0; i < rows.length; i++) {
if (skip(i)) continue;
for (const entry of Object.values(relatedFor(rows[i]!) ?? {})) if (entry?.row) readParents.add(entry.object);
if (master && headerFor?.(i)) readParents.add(master);
}
if (readParents.size === 0) return;
const folded = accumulator.foldedSummaries(rows, readParents);
if (folded.size > 0) accumulator.setDependents(await loadSummaryFoldDependents(host, folded, context));
}

export async function loadSummaryFoldDependents(
host: Pick<UpdateHost, 'facade' | 'getSchema' | 'permissionResolution' | 'resolveFormulaPermissions' | 'resolveFormulaRelated' | 'formulaOptionLabels'>,
folded: Map<string, { fields: Set<string>; parentIds: Set<string> }>,
context: Parameters<UpdateHost['resolveFormulaPermissions']>[3],
Expand Down Expand Up @@ -2636,5 +2680,7 @@ async function loadSummaryFoldDependents(
const key = `${object}|${parentId}`;
images.set(key, written(entry, images.get(key) ?? stored, moved));
};
// [#34821] The parent as stored: the base a bulk insert's accumulator moves a roll-up from.
dependents.stored = (object, parentId) => served.get(object)?.rows.get(parentId);
return dependents;
}
Loading
Loading