From 88b0ae717750fe9df6a4f3b3ad83c7f6bcba9259 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:28:42 +0000 Subject: [PATCH 1/9] fix(metadata-protocol)!: a seed never stores a roll-up summary value; the load result counts the drop WIP: loader strip, SeedLoadResult.summariesDropped, pins. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- packages/metadata-protocol/src/seed-loader.ts | 65 +++++ .../src/seed-summary-never-stored.test.ts | 236 ++++++++++++++++++ .../src/contracts/seed-loader-service.test.ts | 5 +- packages/spec/src/data/seed-loader.zod.ts | 33 +++ 4 files changed, 338 insertions(+), 1 deletion(-) create mode 100644 packages/objectql/src/seed-summary-never-stored.test.ts diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index b1a215ad8db..71afb8f83de 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -776,6 +776,29 @@ function createOnlySeedColumns(dataset: Seed, externalId: string | string[]): Re return createOnly; } +/** + * [#35655] The roll-up `summary` fields the definition declares — every one, + * whatever its aggregate (`count`, `sum`, `min`, `max`, `avg`) and whether or + * not it is declared `readonly`. A seed never stores a value for one (maintainer + * ruling D, record 7063117450): the engine computes it from the child rows, so + * {@link SeedLoaderService} takes a seed record's value for it out before the + * replay compare and before the write, and reports it in `summariesDropped`. + * + * Keyed on `type === 'summary'` literally, as the engine's roll-up readers + * are (`summaryFieldsLockedOnWrite`, `getSummaryDescriptors`). A definition + * the loader cannot resolve declares none, and its records are written as + * authored: the engine is then the one to judge the columns. + */ +function summaryFieldNames(definition: unknown): readonly string[] { + const fields = (definition as { fields?: unknown } | null | undefined)?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return []; + const names: string[] = []; + for (const [name, field] of Object.entries(fields as Record)) { + if (field && typeof field === 'object' && (field as { type?: unknown }).type === 'summary') names.push(name); + } + return names; +} + /** * [#24562] Field name → storage kind, for every field the definition declares * `datetime`, `date` or `time` — the fields a replay compares in their STORED @@ -1778,6 +1801,7 @@ export class SeedLoaderService implements ISeedLoaderService { referencesDeferred: 0, referencesDropped: 0, summariesStale: 0, + summariesDropped: 0, landedIds: [], insertedIds: [], errors: [error], @@ -2101,6 +2125,12 @@ export class SeedLoaderService implements ISeedLoaderService { // `organization_id`, as it keeps the stamp. const organizationColumn = seedRowTenantColumn(objectDefinition) ?? DEFAULT_TENANT_FIELD; this.warnOnUndeclaredSeedColumns(dataset, objectDefinition); + // [#35655] The roll-up columns a seed never writes (`summaryFieldNames`), + // the values this dataset's records supplied for them, and which of them + // did — reported once, after the record loop. + const summaryFields = summaryFieldNames(objectDefinition); + let summariesDropped = 0; + const summaryFieldsDropped = new Set(); // How a replay compares each field (`isNoOpReplay`): [#24562] a temporal // field in its stored form, [#24624] a field the read path masks never by // its set value, [#29277] a seed blank the write door stores as `null` as @@ -2236,6 +2266,20 @@ export class SeedLoaderService implements ISeedLoaderService { continue; } const record = { ...(seedResult.value as Record) }; + // [#35655] A seed never stores a roll-up (ruling D, record 7063117450). + // Taken out here, before anything reads the record, so every path below + // sees it gone: the no-op replay compare (a stored total that differs + // from the seed's is no difference to undo), the insert (the engine + // starts the column at its empty-child-list value and the child rows + // compute it) and the update (the row keeps the value it holds). + for (const field of summaryFields) { + if (!Object.prototype.hasOwnProperty.call(record, field)) continue; + if (record[field] !== undefined) { + summariesDropped++; + summaryFieldsDropped.add(field); + } + delete record[field]; + } // [#22301] The stored form, not a `Date`, before any hook can see it. seedValuesInStoredForm(record, objectDefinition); /** @@ -3186,6 +3230,24 @@ export class SeedLoaderService implements ISeedLoaderService { .map(([, id]) => id), )]; + // [#35655] Once per dataset, naming the object, the fields and the count: + // the seed asked for a total the platform did not store. `warn`, not + // `error`: nothing claimed persisted is lost — a roll-up is never the + // seed's to write, the rest of every record landed, and the machine trace + // is `summariesDropped` on this object's result. + if (summariesDropped > 0) { + const fields = [...summaryFieldsDropped]; + this.logger.warn( + `[SeedLoader] The ${objectName} seed supplies ${summariesDropped} value(s) for the roll-up summary ` + + `field(s) ${fields.map((f) => `\`${f}\``).join(', ')}, which a seed never stores: the values are not ` + + `written, the rest of each record is, and each roll-up is computed from its child rows, so a record ` + + `with no children reads the empty-child-list value (0 for count and sum, empty for min, max and avg). ` + + `Seed the child rows the total counts, and leave the summary field out of the ${objectName} seed. ` + + `The count is summariesDropped on this object's load result.`, + { object: objectName, fields, summariesDropped }, + ); + } + if (this.loadProgress) this.loadProgress.loading = undefined; return { object: objectName, @@ -3199,6 +3261,7 @@ export class SeedLoaderService implements ISeedLoaderService { referencesDeferred, referencesDropped, summariesStale: this.summariesStale - summariesStaleAtStart, + summariesDropped, landedIds, insertedIds, errors, @@ -5552,6 +5615,8 @@ export class SeedLoaderService implements ISeedLoaderService { // — the field is declared with `.default(0)`, so it survives a parse of a // payload written before it existed (#4998). totalSummariesStale: results.reduce((sum, r) => sum + r.summariesStale, 0), + // [#35655] Every entry is built by `loadDataset`, which always populates it. + totalSummariesDropped: results.reduce((sum, r) => sum + r.summariesDropped, 0), circularDependencyCount: graph.circularDependencies.length, durationMs, }; diff --git a/packages/objectql/src/seed-summary-never-stored.test.ts b/packages/objectql/src/seed-summary-never-stored.test.ts new file mode 100644 index 00000000000..f17a53706c1 --- /dev/null +++ b/packages/objectql/src/seed-summary-never-stored.test.ts @@ -0,0 +1,236 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35655] A seed never stores a roll-up (summary) value (maintainer ruling D, + * record 7063117450). The seed loader takes a seed record's value for every + * `type: 'summary'` field out of the record before the replay compare and the + * write; the roll-up is computed from the child rows; the load result counts + * the dropped values in `summariesDropped`, and one `warn` per dataset names + * the object, the fields and the count. + * + * Measured on unfixed `main` 493ad095d4 with this file's harness (the real + * ObjectQL engine and the real SeedLoaderService), parent `ss_inv` seeded with + * `line_total: 999, line_count: 99` over two lines of 10 and 32: + * + * case stored line_total / line_count + * 3 parent seeded alone, no children 999 / 99 (roll-up over no children: 0 / 0) + * 4 parent re-seeded after its children 999 / 99 (before the re-seed: 42 / 2) + * 6 the same seed loaded twice load 1: 42 / 2, load 2: 999 / 99 + * + * Every case below asserts the parent equal to its roll-up after every load, + * and the drop counted. One rule for every aggregate: a `sum`, a `count` and a + * `max` (no empty-set value, so it stays empty) are seeded side by side, and a + * roll-up an extension contributes is dropped like the base object's own. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { SeedLoaderService } from '@objectstack/metadata-protocol'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { ObjectQL } from './engine.js'; + +/** A store-backed stub driver: the stored row IS the verdict. */ +function makeDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + const checkOp = (value: any, cond: any): boolean => { + if (cond === null || typeof cond !== 'object' || Array.isArray(cond) || cond instanceof Date) return value === cond; + return Object.entries(cond).every(([op, target]: [string, any]) => { + switch (op) { + case '$eq': return value === target; + case '$ne': return value !== target; + case '$in': return Array.isArray(target) && target.includes(value); + case '$nin': return Array.isArray(target) && !target.includes(value); + case '$null': return target ? value == null : value != null; + default: throw new Error(`stub driver: unsupported operator ${op}`); + } + }); + }; + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]: [string, any]) => { + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); + if (k === '$not') return !matches(row, v); + return checkOp(row?.[k], v); + }); + }; + let n = 0; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string, ast: any) { + return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).map((r) => ({ ...r })); + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(object: string, data: Record) { + n += 1; + const id = (data.id as string) ?? `r_${n}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return { ...row }; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return { ...row }; + }, + async updateMany(object: string, ast: any, data: Record) { + const s = storeFor(object); + let count = 0; + for (const [id, r] of Array.from(s.entries())) { + if (matches(r, ast?.where)) { s.set(id, { ...r, ...data, id }); count += 1; } + } + return count; + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async deleteMany(object: string, ast: any) { + const s = storeFor(object); + let count = 0; + for (const [id, r] of Array.from(s.entries())) { + if (matches(r, ast?.where)) { s.delete(id); count += 1; } + } + return count; + }, + async count() { return 0; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor }; +} + +/** No metadata service answer: the loader resolves every definition from the engine's registry. */ +function emptyMetadata(): IMetadataService { + return { + getObject: async () => undefined, listObjects: async () => [], register: async () => {}, get: async () => undefined, + list: async () => [], unregister: async () => {}, exists: async () => false, listNames: async () => [], + } as unknown as IMetadataService; +} + +const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'upsert', batchSize: 1000, transaction: false } as any; +const ENV = ['prod', 'dev', 'test']; +const SUPPLIED = { line_total: 999, line_count: 99, line_max: 500 }; +const LINES = [{ name: 'l1', inv: 'A', amount: 10 }, { name: 'l2', inv: 'A', amount: 32 }]; +const P = (records: any[], mode = 'upsert') => ({ object: 'ss_inv', externalId: 'name', mode, env: ENV, records }); +const C = (records: any[]) => ({ object: 'ss_line', externalId: 'name', mode: 'upsert', env: ENV, records }); + +describe('[#35655] a seed never stores a roll-up value: the children decide it, the drop is reported', () => { + let engine: ObjectQL; + let storeFor: (o: string) => Map; + let warns: Array<{ message: string; meta?: Record }>; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'ss_inv', + fields: { + name: { type: 'text' }, + line_total: { type: 'summary', summaryOperations: { object: 'ss_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'ss_line', field: 'amount', function: 'count' } }, + line_max: { type: 'summary', readonly: true, summaryOperations: { object: 'ss_line', field: 'amount', function: 'max' } }, + }, + } as any, 'test-package'); + engine.registry.registerObject({ + name: 'ss_line', + fields: { name: { type: 'text' }, amount: { type: 'number' }, inv: { type: 'master_detail', reference: 'ss_inv' } }, + } as any, 'test-package'); + warns = []; + }); + + const load = (seeds: any[]) => new SeedLoaderService( + engine as unknown as IDataEngine, + emptyMetadata(), + { info() {}, debug() {}, error() {}, warn: (message: string, meta?: Record) => warns.push({ message, meta }) }, + ).load({ seeds, config: CONFIG } as any); + const inv = (name: string) => [...storeFor('ss_inv').values()].find((r: any) => r.name === name); + const resultOf = (r: any, object: string) => r.results.find((x: any) => x.object === object); + const dropWarns = () => warns.filter((w) => w.message.includes('roll-up summary')); + + it('case 3: a parent seeded with totals and no children stores the empty-set values, and the load reports the drop', async () => { + const r = await load([P([{ name: 'A', ...SUPPLIED }])]); + + expect(r.success).toBe(true); + // sum and count start at 0; max has no empty-set value and stays empty. + expect(inv('A')).toMatchObject({ line_total: 0, line_count: 0 }); + expect(inv('A')?.line_max ?? null).toBeNull(); + expect(resultOf(r, 'ss_inv')).toMatchObject({ inserted: 1, errored: 0, summariesDropped: 3 }); + expect(r.summary.totalSummariesDropped).toBe(3); + // One line for the dataset, naming the object, every field and the count. + expect(dropWarns()).toHaveLength(1); + expect(dropWarns()[0].meta).toEqual({ object: 'ss_inv', fields: ['line_total', 'line_count', 'line_max'], summariesDropped: 3 }); + expect(dropWarns()[0].message).toContain('`line_total`, `line_count`, `line_max`'); + }); + + it('case 1 (control): parent and children in one load store the roll-up, and the drop is still reported', async () => { + const r = await load([P([{ name: 'A', ...SUPPLIED }]), C(LINES)]); + + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + expect(resultOf(r, 'ss_inv').summariesDropped).toBe(3); + expect(resultOf(r, 'ss_line').summariesDropped).toBe(0); + }); + + it('case 4: a re-seed over existing children keeps the computed values, and a roll-up-only difference is no write', async () => { + await load([P([{ name: 'A' }]), C(LINES)]); + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + + const r = await load([P([{ name: 'A', ...SUPPLIED }])]); + + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 3 }); + }); + + it('case 4 under `update` mode: the matched row keeps its computed values', async () => { + await load([P([{ name: 'A' }]), C(LINES)]); + + const r = await load([P([{ name: 'A', ...SUPPLIED }], 'update')]); + + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + expect(resultOf(r, 'ss_inv').summariesDropped).toBe(3); + }); + + it('case 6: the same seed replayed stores the same totals on both loads', async () => { + const seeds = [P([{ name: 'A', ...SUPPLIED }]), C(LINES)]; + + await load(seeds); + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + + const r = await load(seeds); + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 3 }); + }); + + it('a roll-up an extension contributes is dropped like the object\'s own', async () => { + engine.registry.registerObject({ + name: 'ss_inv', + fields: { ext_total: { type: 'summary', summaryOperations: { object: 'ss_line', field: 'amount', function: 'sum' } } }, + } as any, 'ext-package', undefined, 'extend'); + + const r = await load([P([{ name: 'A', ext_total: 7 }])]); + + expect(inv('A')).toMatchObject({ ext_total: 0 }); + expect(resultOf(r, 'ss_inv').summariesDropped).toBe(1); + expect(dropWarns()[0].meta?.fields).toEqual(['ext_total']); + }); + + it('a seed that supplies no roll-up value reports nothing', async () => { + const r = await load([P([{ name: 'A' }]), C(LINES)]); + + expect(r.summary.totalSummariesDropped).toBe(0); + expect(dropWarns()).toEqual([]); + }); +}); diff --git a/packages/spec/src/contracts/seed-loader-service.test.ts b/packages/spec/src/contracts/seed-loader-service.test.ts index affe14afd03..0f1f67120d7 100644 --- a/packages/spec/src/contracts/seed-loader-service.test.ts +++ b/packages/spec/src/contracts/seed-loader-service.test.ts @@ -30,6 +30,7 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, + totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 0, }, @@ -56,6 +57,7 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, + totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 0, }, @@ -87,6 +89,7 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, + totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 42, }, @@ -101,7 +104,7 @@ describe('Seed Loader Service Contract', () => { summary: { objectsProcessed: 0, totalRecords: 0, totalInserted: 0, totalUpdated: 0, totalSkipped: 0, totalErrored: 0, totalReferencesResolved: 0, - totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, + totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 0, }, }), diff --git a/packages/spec/src/data/seed-loader.zod.ts b/packages/spec/src/data/seed-loader.zod.ts index 855aff99898..2959b8e69e7 100644 --- a/packages/spec/src/data/seed-loader.zod.ts +++ b/packages/spec/src/data/seed-loader.zod.ts @@ -412,6 +412,31 @@ export const SeedLoadResultSchema = lazySchema(() => z.object({ summariesStale: z.number().int().min(0).default(0) .describe('Roll-up summary values left stale by writes for this dataset'), + /** + * Number of roll-up summary values this dataset's records SUPPLIED that the + * loader did not write — "the seed named a total, the children decide it". + * + * A roll-up summary is a DERIVED value: the engine computes it from the + * child rows. A seed never stores one, on insert or on update (maintainer + * ruling D, record 7063117450): the loader takes every value a seed record supplies + * for a field its object declares `type: 'summary'` out of the record + * before the replay compare and before the write. A row the load creates + * starts the column at its empty-child-list value (`0` for `count` and + * `sum`, empty for `min`, `max` and `avg`) and the child rows the load + * writes compute it; a row the load matches keeps the value it holds. One + * per record and field, counted whether or not the rest of the record then + * lands. + * + * The rest of each record IS written, so neither `errored` nor `success` + * moves and `inserted + updated + skipped + errored` still reconciles + * against `total` — the reasoning that gave `referencesDropped` and + * `summariesStale` their own counters. Without it the dropped total would be + * visible only as a log line, and a parent seeded with a total and no + * children would read `0` with nothing in the result to say why. + */ + summariesDropped: z.number().int().min(0).default(0) + .describe('Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up)'), + /** * The ids of the stored rows this dataset's records landed on: a row a * record inserted, a row it updated, and a row its key matched on a replay @@ -539,6 +564,14 @@ export const SeedLoaderResultSchema = lazySchema(() => z.object({ totalSummariesStale: z.number().int().min(0).default(0) .describe('Total roll-up summary values left stale across the load'), + /** + * Total roll-up summary values the seed records supplied and the loader + * did not write — "the seed named a total, the children decide it". See + * `SeedLoadResult.summariesDropped`. + */ + totalSummariesDropped: z.number().int().min(0).default(0) + .describe('Total roll-up summary values supplied by seed records and not written'), + /** Number of circular dependency chains detected */ circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'), From 6bc893e3b36074741c192f5566e8103513c079c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:32:35 +0000 Subject: [PATCH 2/9] fix(metadata-protocol)!: docs, ADR-0087 entry, changeset and pins for the roll-up seed drop Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- .../35655-seed-summary-value-not-stored.md | 23 +++ content/docs/data-modeling/fields.mdx | 18 ++- .../src/seed-loader-summary-stale.test.ts | 137 ++++++++++++++++++ packages/metadata-protocol/src/seed-loader.ts | 1 + .../src/engine-summary-update-lock.test.ts | 9 +- packages/objectql/src/engine-top-level.ts | 7 +- .../objectql/src/validation/rule-validator.ts | 9 +- packages/spec/authorable-defaults/data.json | 1 + packages/spec/authorable-surface/data.json | 1 + .../18.seed-summary-value-not-stored.ts | 41 ++++++ 10 files changed, 232 insertions(+), 15 deletions(-) create mode 100644 .changeset/35655-seed-summary-value-not-stored.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts diff --git a/.changeset/35655-seed-summary-value-not-stored.md b/.changeset/35655-seed-summary-value-not-stored.md new file mode 100644 index 00000000000..ffbc6099eaf --- /dev/null +++ b/.changeset/35655-seed-summary-value-not-stored.md @@ -0,0 +1,23 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +--- + +fix(metadata-protocol)!: a seed never stores a roll-up (summary) value; the children compute it, and the load result counts the drop + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for a seed record that supplies a value for a `summary` (roll-up) field, in any seed: a `defineStack({ data })` dataset, `defineSeed`, a `seed` metadata item, or the seed data a package install loads. Every aggregate (`count`, `sum`, `min`, `max`, `avg`) is treated the same, whether or not the field is declared `readonly`. + +- FROM: the seed loader writes as the system principal, so the supplied value was stored as written. It stayed wherever no child write came after it: a parent seeded with a total and no children kept the total; a re-seed over existing children wrote it over the computed value; and a keep-current (`upsert`) seed replayed on the next boot stored the computed total on the first load and the supplied one on the second. +- TO: the loader takes every such value out of the record before the replay compare and the write, on insert and on update, and writes the rest of the record. A created row starts the column at its empty-child-list value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), and the seeded child rows compute it. A matched row keeps the value it holds, so a replay whose only difference is the roll-up writes nothing. A parent seeded with a total and no children now reads `0`. +- Reported, not silent: each dataset's load result carries the new counter `summariesDropped` (the values it did not write), the load summary carries `totalSummariesDropped`, and the load logs one warning per dataset naming the object, the fields and the count. `success`, `errored` and the row counters do not move. A dry run (`validate`) reports the same count. + +Compatibility note for seed authors: to show a total, seed the child rows it is computed from and leave the summary field out of the parent's seed record. A figure no child rows back is not a roll-up: declare it a `number` or `currency` field. A legacy total that must land as written goes through a historical import (`treatAsHistorical: true`), which is unchanged. Rows an earlier load stored a supplied total on are not rewritten by the loader; the next child write recomputes them. + +Also new on `SeedLoadResultSchema` / `SeedLoaderResultSchema`: `summariesDropped` and `summary.totalSummariesDropped`, both `.default(0)`, so a payload written before them still parses. A hand-written `ISeedLoaderService` implementation that builds a `SeedLoaderResultParsed` literal now also sets `summary.totalSummariesDropped`. + +Not changed: the engine (`packages/objectql`), which still keeps a value an `isSystem` write sends (the roll-up recompute, the backfill, a historical import); the import and REST doors; and the runtime's basic-insert fallback seeder, which runs only when the seed loader is unavailable or throws. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 34e6bc16921..6e617badac6 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -409,10 +409,20 @@ person who submitted it is not shown the drop. A record created with its value dropped starts as if no value had been sent: `0` for `count` and `sum`, empty for `min`, `max` and `avg`, and the next child write replaces it with the computed value. Under `strictReadonlyWrites` the whole write -is refused. Server code that runs with `isSystem: true` can still write the -column, as it can any read-only column: seed data, package installs and a -historical import (`treatAsHistorical: true`, which only the system principal may -send) keep a pre-computed total, on create and on update. Undoing an ordinary +is refused. Seed data never stores a summary value, and that includes the seed +data a package install loads, since it goes through the same seed loader: a value a +seed record supplies for a summary field is not written, on create or on +update, and the rest of the record is. The summary is computed from the seeded +child records, so a parent seeded with a total and no children shows the +empty-set value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), +and re-seeding a parent leaves its computed value in place. The load result +counts the values it did not write in `summariesDropped` (per dataset) and +`summary.totalSummariesDropped`, and the load logs one warning per dataset that +names the object and the fields. To show a total, seed the child records it +sums. Server code that runs with `isSystem: true` can still write the column, +as it can any read-only column: a historical import (`treatAsHistorical: true`, +which only the system principal may send) keeps a pre-computed total, on create +and on update. Undoing an ordinary import restores the rows through an ordinary update, so a summary value that an import committed before this rule overwrote is not put back by the undo; it stays until the next child write recomputes it. diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index 2104d167946..64ffced1046 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -308,3 +308,140 @@ describe('the counter survives the contract, and the contract survives older pay expect(SeedLoaderResultSchema.parse(legacyResult).summary.totalSummariesStale).toBe(0); }); }); + +/** + * [#35655] The other half of a seed and a roll-up: a seed never stores a + * value it supplies for a `summary` field (maintainer ruling D, record + * 7063117450). The loader takes it out of the record before the write, counts + * it in `summariesDropped`, and the engine computes the column from the child + * rows. These pins read the engine's CALLS, so they hold whatever the engine + * would do with the key; the stored outcome on the real engine is pinned in + * `packages/objectql/src/seed-summary-never-stored.test.ts`. + */ +describe('a seed never hands the engine a roll-up value (#35655)', () => { + const ROLLUP_OBJECTS: Record = { + drop_invoice: { + name: 'drop_invoice', + fields: { + name: { type: 'text' }, + total: { type: 'number' }, + paid: { type: 'summary', summaryOperations: { object: 'drop_payment', field: 'amount', function: 'sum' } }, + payments: { type: 'summary', readonly: true, summaryOperations: { object: 'drop_payment', field: 'amount', function: 'count' } }, + }, + }, + }; + function rollUpMetadata(objects: Record = ROLLUP_OBJECTS): IMetadataService { + return { + getObject: vi.fn(async (name: string) => objects[name]), + listObjects: vi.fn(async () => Object.values(objects)), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => objects[name]), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; + } + const writtenKeys = (engine: IDataEngine, verb: 'insert' | 'update') => + (engine[verb] as any).mock.calls + .filter(([object]: [string]) => object === 'drop_invoice') + .flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row))); + + it('on insert: neither roll-up reaches the engine, the rest of the row does, and the drop is counted and named once', async () => { + const { engine, store } = createFaithfulEngine(); + const logger = createLogger(); + + const result = await new SeedLoaderService(engine, rollUpMetadata(), logger).load({ + seeds: [seedFor('drop_invoice', [ + { name: 'INV-1', total: 10, paid: 3000, payments: 4 }, + { name: 'INV-2', total: 20, paid: null }, + { name: 'INV-3', total: 30 }, + ])] as any, + config: CONFIG, + }); + + for (const keys of writtenKeys(engine, 'insert')) { + expect(keys).not.toContain('paid'); + expect(keys).not.toContain('payments'); + } + expect(store.drop_invoice.map((r) => r.total)).toEqual([10, 20, 30]); + // A supplied `null` is a supplied value too: three values, two fields. + expect(result.results[0]).toMatchObject({ inserted: 3, errored: 0, summariesDropped: 3 }); + expect(result.summary.totalSummariesDropped).toBe(3); + expect(result.success).toBe(true); + const drops = (logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary')); + expect(drops).toHaveLength(1); + expect(drops[0][1]).toEqual({ object: 'drop_invoice', fields: ['paid', 'payments'], summariesDropped: 3 }); + }); + + it('on a matched row (upsert): the update carries no roll-up, and a roll-up-only difference writes nothing', async () => { + const { engine, store } = createFaithfulEngine(); + store.drop_invoice = [{ id: 'inv-1', name: 'INV-1', total: 10, paid: 42, payments: 2 }]; + + const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).load({ + seeds: [{ ...seedFor('drop_invoice', [ + { name: 'INV-1', total: 10, paid: 999, payments: 99 }, + ]), mode: 'upsert' }] as any, + config: CONFIG, + }); + + expect(writtenKeys(engine, 'update')).toEqual([]); + expect(store.drop_invoice[0]).toMatchObject({ paid: 42, payments: 2 }); + expect(result.results[0]).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 2 }); + }); + + it('on a matched row whose other columns changed: the update writes them and still no roll-up', async () => { + const { engine, store } = createFaithfulEngine(); + store.drop_invoice = [{ id: 'inv-1', name: 'INV-1', total: 10, paid: 42, payments: 2 }]; + + const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).load({ + seeds: [{ ...seedFor('drop_invoice', [ + { name: 'INV-1', total: 11, paid: 999, payments: 99 }, + ]), mode: 'upsert' }] as any, + config: CONFIG, + }); + + const keys = writtenKeys(engine, 'update'); + expect(keys).toHaveLength(1); + expect(keys[0]).toContain('total'); + expect(keys[0]).not.toContain('paid'); + expect(keys[0]).not.toContain('payments'); + expect(store.drop_invoice[0]).toMatchObject({ total: 11, paid: 42, payments: 2 }); + expect(result.results[0]).toMatchObject({ updated: 1, summariesDropped: 2 }); + }); + + it('a dry run (validate) counts the same drop and writes nothing', async () => { + const { engine } = createFaithfulEngine(); + + const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).validate( + [seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any, + ); + + expect(writtenKeys(engine, 'insert')).toEqual([]); + expect(result.results[0].summariesDropped).toBe(1); + }); + + it('CONTROL: a field the definition does not type `summary` is written as authored, and nothing is reported', async () => { + const { engine } = createFaithfulEngine(); + const logger = createLogger(); + const plain = { drop_invoice: { name: 'drop_invoice', fields: { name: { type: 'text' }, total: { type: 'number' }, paid: { type: 'currency' } } } }; + + const result = await new SeedLoaderService(engine, rollUpMetadata(plain), logger).load({ + seeds: [seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any, + config: CONFIG, + }); + + expect(writtenKeys(engine, 'insert')[0]).toContain('paid'); + expect(result.results[0].summariesDropped).toBe(0); + expect((logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary'))).toEqual([]); + }); + + it('defaults to 0 for a payload written before the field existed', () => { + const legacyPerObject = { + object: 'drop_invoice', mode: 'ignore', + inserted: 1, updated: 0, skipped: 0, errored: 0, total: 1, + referencesResolved: 0, referencesDeferred: 0, errors: [], + }; + expect(SeedLoadResultSchema.parse(legacyPerObject).summariesDropped).toBe(0); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 71afb8f83de..f4c52ead764 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -5587,6 +5587,7 @@ export class SeedLoaderService implements ISeedLoaderService { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, + totalSummariesDropped: 0, circularDependencyCount: 0, durationMs, }, diff --git a/packages/objectql/src/engine-summary-update-lock.test.ts b/packages/objectql/src/engine-summary-update-lock.test.ts index 2bf4713b5fb..3f42d8ff034 100644 --- a/packages/objectql/src/engine-summary-update-lock.test.ts +++ b/packages/objectql/src/engine-summary-update-lock.test.ts @@ -22,9 +22,10 @@ * `readonly: true` roll-up, which used to land `null` on such a create. * * Kept, each pinned here: the roll-up recompute's own write (`isSystem`), and - * any other `isSystem` write of the column, on update and on create (seed - * loads, package installs and historical imports write as the system - * principal). + * any other `isSystem` write of the column, on update and on create (historical + * imports write as the system principal). A seed load never sends a roll-up + * value: the seed loader takes it out first (#35655, + * `seed-summary-never-stored.test.ts`). * * The REST and import doors, end to end over HTTP and SQLite: * `packages/rest/src/import-summary-update-lock-34672.test.ts`. @@ -404,7 +405,7 @@ describe('[#34672] a roll-up summary is read-only on create: dropped, reported, expect(acct('a9')).toMatchObject({ order_total: 50, order_total_ro: 50 }); }); - it('an isSystem create keeps its value (seed loads, package installs, historical imports)', async () => { + it('an isSystem create keeps its value (historical imports; a seed load strips the key before the engine, #35655)', async () => { const events: DroppedFieldsEvent[] = []; await engine.insert( 'acct', { id: 'a1', name: 'A', order_total: 90, order_total_ro: 90 }, diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index b81cf3c655d..8391e87068d 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -2544,9 +2544,10 @@ function withSummaryRollUpsReadonly(schema: unknown): unknown { * * On create the taken value is replaced by the empty-child-list seed * (`initializeSummaryFields`, re-run by `staticReadonlyCreateStrip`): `0` - * for `count` / `sum`, nothing for `min` / `max` / `avg`. Seed loads, - * package installs and historical imports write as the system principal and - * keep a pre-computed total. The `summary` note on + * for `count` / `sum`, nothing for `min` / `max` / `avg`. Historical imports + * write as the system principal and keep a pre-computed total; a seed load (a + * package install's too) never sends one, because the seed loader takes a + * seed record's roll-up value out before the write (#35655). The `summary` note on * `RUNTIME_OWNED_FIELD_TYPES` in `validation/rule-validator.ts` says why the * type rides this strip and not the runtime-owned one. * diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index d9bdb2a4693..dacd1338347 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -1970,10 +1970,11 @@ export function stripReadonlyWhenFieldsMulti( * - The exemption. {@link stripRuntimeOwnedFields} keeps a value under * `preserveAudit` as well as `isSystem`. The create-side static strip * honours `isSystem` alone (the `preserveAudit` ruling below), and that is - * the boundary a roll-up needs: seed loads, package installs and - * historical imports (`treatAsHistorical` is system-only) write as the - * system principal and keep a pre-computed total; an in-process caller - * that merely sets `preserveAudit` does not. + * the boundary a roll-up needs: historical imports (`treatAsHistorical` + * is system-only) write as the system principal and keep a pre-computed + * total; an in-process caller that merely sets `preserveAudit` does not. + * (A seed load never sends one: the seed loader takes a seed record's + * roll-up value out before the write, #35655.) * - The seed. The runtime-owned strip judges the RAW caller payload (#6339) * and runs AFTER the seed pass, which skipped the field BECAUSE the caller * supplied it, so taking `task_count: 42` there would land the column diff --git a/packages/spec/authorable-defaults/data.json b/packages/spec/authorable-defaults/data.json index 33667d688be..7c860e9477b 100644 --- a/packages/spec/authorable-defaults/data.json +++ b/packages/spec/authorable-defaults/data.json @@ -105,6 +105,7 @@ "data/SeedLoadResult:insertedIds = []", "data/SeedLoadResult:landedIds = []", "data/SeedLoadResult:referencesDropped = 0", + "data/SeedLoadResult:summariesDropped = 0", "data/SeedLoadResult:summariesStale = 0", "data/SeedLoaderConfig:batchSize = 1000", "data/SeedLoaderConfig:defaultMode = \"ignore\"", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index f8b14bebc70..b7d3db456f9 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -984,6 +984,7 @@ "data/SeedLoadResult:referencesDropped", "data/SeedLoadResult:referencesResolved", "data/SeedLoadResult:skipped", + "data/SeedLoadResult:summariesDropped", "data/SeedLoadResult:summariesStale", "data/SeedLoadResult:total", "data/SeedLoadResult:updated", diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts new file mode 100644 index 00000000000..44f1f7f1053 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts @@ -0,0 +1,41 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of a seed's roll-up value, no longer stored +// (maintainer ruling D, record 7063117450, on objectstack#35655, from the +// decision analysis 7062334196). It narrows the documented "seed data keeps a +// pre-computed total" sentence. No key is added or removed, so there is no +// tombstone and no D2 conversion: whether a supplied total should become seeded +// child rows, a plain number field or a historical import is the author's call. +// The citations live here, not in the printed guidance, which carries no +// tracker number. +export const entry: SemanticMigration = { + id: 'seed-summary-value-not-stored', + surface: + 'data.Seed.records (a seed dataset in `defineStack({ data })`, `defineSeed`, a `seed` metadata item, or a package ' + + 'body\'s seed): a record that supplies a value for a field its object declares `type: \'summary\'` (a roll-up ' + + 'of any aggregate: `count`, `sum`, `min`, `max`, `avg`)', + replacement: + 'Leave the summary field out of the seed record and seed the child rows the total is computed from. A figure ' + + 'that no child rows back is a plain value: model it as a `number` or `currency` field. A legacy total that must ' + + 'land as written goes through a historical import (`treatAsHistorical: true`), not a seed', + reason: + 'A roll-up is computed by the engine from its child rows. The seed loader writes as the system principal, so a ' + + 'value a seed record supplied for one used to be stored as written, and survived wherever no child write came ' + + 'after it: a parent seeded with a total and no children kept the total, a re-seed over existing children wrote ' + + 'it over the computed value, and a seed replayed on the next boot stored the computed total on the first load ' + + 'and the supplied one on the second. A child row a validation rule judged against the supplied total could be ' + + 'refused for it. The loader now takes every such value out of the record before the replay compare and the ' + + 'write, on insert and on update: a created row starts the column at its empty-child-list value (0 for `count` ' + + 'and `sum`, empty for `min`, `max` and `avg`) and the seeded child rows compute it; a matched row keeps the ' + + 'value it holds. The load result counts the values it did not write in `summariesDropped` per dataset and ' + + '`summary.totalSummariesDropped`, and the load logs one warning per dataset naming the object and the fields. ' + + 'There is no mechanical rewrite: only the author knows whether the total stands for child rows that should be ' + + 'seeded or for a figure that is not a roll-up at all. Rows an earlier load stored a supplied total on are data, ' + + 'not metadata: the next child write recomputes them', + acceptanceCriteria: + 'No seed record supplies a value for a `summary` field: every seed load result reports `summariesDropped: 0` ' + + 'for each dataset and the boot log carries no roll-up drop warning, and every seeded roll-up equals the ' + + 'aggregate of its seeded child rows after the first boot and after a restart.', +}; From ee7bc944c88c22fd29eb2256e8f5feea7a1e0fac Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:37:10 +0000 Subject: [PATCH 3/9] docs(spec): regenerate the seed-loader reference for summariesDropped Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- content/docs/references/data/seed-loader.mdx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index 0de1a5b1936..028040dd75c 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -163,6 +163,7 @@ Result of loading a single dataset | **referencesDeferred** | `integer` | ✅ | References deferred to second pass | | **referencesDropped** | `integer` | optional (default: `0`) | Reference fields dropped from records that were still written | | **summariesStale** | `integer` | optional (default: `0`) | Roll-up summary values left stale by writes for this dataset | +| **summariesDropped** | `integer` | optional (default: `0`) | Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up) | | **landedIds** | `string[]` | optional (default: `[]`) | Ids of the stored rows this dataset landed on: inserted, updated, or matched on replay | | **insertedIds** | `string[]` | optional (default: `[]`) | Ids among landedIds whose row this load created (a successful insert); every other landed id was a pre-existing row a record key matched | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | optional (default: `[]`) | Reference resolution errors | @@ -304,6 +305,7 @@ Result of loading a single dataset | **referencesDeferred** | `integer` | ✅ | References deferred to second pass | | **referencesDropped** | `integer` | optional (default: `0`) | Reference fields dropped from records that were still written | | **summariesStale** | `integer` | optional (default: `0`) | Roll-up summary values left stale by writes for this dataset | +| **summariesDropped** | `integer` | optional (default: `0`) | Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up) | | **landedIds** | `string[]` | optional (default: `[]`) | Ids of the stored rows this dataset landed on: inserted, updated, or matched on replay | | **insertedIds** | `string[]` | optional (default: `[]`) | Ids among landedIds whose row this load created (a successful insert); every other landed id was a pre-existing row a record key matched | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | optional (default: `[]`) | Reference resolution errors | @@ -336,6 +338,7 @@ Actionable error for a failed reference resolution | **totalReferencesDeferred** | `integer` | ✅ | Total references deferred | | **totalReferencesDropped** | `integer` | optional (default: `0`) | Total reference fields dropped from written records | | **totalSummariesStale** | `integer` | optional (default: `0`) | Total roll-up summary values left stale across the load | +| **totalSummariesDropped** | `integer` | optional (default: `0`) | Total roll-up summary values supplied by seed records and not written | | **circularDependencyCount** | `integer` | ✅ | Circular dependency chains detected | | **durationMs** | `number` | ✅ | Load duration in milliseconds | From bf794b566b7225fad421fe32a7cb490f245f64bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:58:56 +0000 Subject: [PATCH 4/9] test(objectql): the seed roll-up pin's driver double holds the caller's bound Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- packages/objectql/src/seed-summary-never-stored.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/seed-summary-never-stored.test.ts b/packages/objectql/src/seed-summary-never-stored.test.ts index f17a53706c1..b66e15aa26c 100644 --- a/packages/objectql/src/seed-summary-never-stored.test.ts +++ b/packages/objectql/src/seed-summary-never-stored.test.ts @@ -63,7 +63,9 @@ function makeDriver() { name: 'memory', version: '0.0.0', supports: {}, async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, async find(object: string, ast: any) { - return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).map((r) => ({ ...r })); + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + return page.map((r) => ({ ...r })); }, async findOne(object: string, ast: any) { for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; From e83650e33417e8e21e209e53050fb058f5c73bc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:09:05 +0000 Subject: [PATCH 5/9] fix(metadata-protocol)!: report a dropped seed roll-up through the per-dataset notice only, with no load-result key The seat chose option B on the result key (correction 7064615114): the warn notice is the report. SeedLoadResult.summariesDropped and summary.totalSummariesDropped are removed with their generated rows, and the pins assert on the notice. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- .../35655-seed-summary-value-not-stored.md | 8 +-- content/docs/data-modeling/fields.mdx | 8 +-- content/docs/references/data/seed-loader.mdx | 3 - .../src/seed-loader-summary-stale.test.ts | 69 ++++++++++--------- packages/metadata-protocol/src/seed-loader.ts | 27 +++----- .../src/seed-summary-never-stored.test.ts | 46 ++++++++----- packages/spec/authorable-defaults/data.json | 1 - packages/spec/authorable-surface/data.json | 1 - .../src/contracts/seed-loader-service.test.ts | 5 +- packages/spec/src/data/seed-loader.zod.ts | 33 --------- .../18.seed-summary-value-not-stored.ts | 10 +-- 11 files changed, 89 insertions(+), 122 deletions(-) diff --git a/.changeset/35655-seed-summary-value-not-stored.md b/.changeset/35655-seed-summary-value-not-stored.md index ffbc6099eaf..bea2b765fe0 100644 --- a/.changeset/35655-seed-summary-value-not-stored.md +++ b/.changeset/35655-seed-summary-value-not-stored.md @@ -3,9 +3,9 @@ '@objectstack/metadata-protocol': minor --- -fix(metadata-protocol)!: a seed never stores a roll-up (summary) value; the children compute it, and the load result counts the drop +fix(metadata-protocol)!: a seed never stores a roll-up (summary) value; the children compute it, and the load says what it dropped -Clause-②: yes (narrowing) +Clause-②: no (narrowing) Metadata-protocol: narrowed @@ -14,10 +14,8 @@ Metadata-protocol: narrowed - FROM: the seed loader writes as the system principal, so the supplied value was stored as written. It stayed wherever no child write came after it: a parent seeded with a total and no children kept the total; a re-seed over existing children wrote it over the computed value; and a keep-current (`upsert`) seed replayed on the next boot stored the computed total on the first load and the supplied one on the second. - TO: the loader takes every such value out of the record before the replay compare and the write, on insert and on update, and writes the rest of the record. A created row starts the column at its empty-child-list value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), and the seeded child rows compute it. A matched row keeps the value it holds, so a replay whose only difference is the roll-up writes nothing. A parent seeded with a total and no children now reads `0`. -- Reported, not silent: each dataset's load result carries the new counter `summariesDropped` (the values it did not write), the load summary carries `totalSummariesDropped`, and the load logs one warning per dataset naming the object, the fields and the count. `success`, `errored` and the row counters do not move. A dry run (`validate`) reports the same count. +- Reported, not silent: the load logs one warning per dataset naming the object, the fields and how many values it did not write. A dry run (`validate`) logs the same warning. `success`, `errored` and the row counters do not move, and the load result gains no key. Compatibility note for seed authors: to show a total, seed the child rows it is computed from and leave the summary field out of the parent's seed record. A figure no child rows back is not a roll-up: declare it a `number` or `currency` field. A legacy total that must land as written goes through a historical import (`treatAsHistorical: true`), which is unchanged. Rows an earlier load stored a supplied total on are not rewritten by the loader; the next child write recomputes them. -Also new on `SeedLoadResultSchema` / `SeedLoaderResultSchema`: `summariesDropped` and `summary.totalSummariesDropped`, both `.default(0)`, so a payload written before them still parses. A hand-written `ISeedLoaderService` implementation that builds a `SeedLoaderResultParsed` literal now also sets `summary.totalSummariesDropped`. - Not changed: the engine (`packages/objectql`), which still keeps a value an `isSystem` write sends (the roll-up recompute, the backfill, a historical import); the import and REST doors; and the runtime's basic-insert fallback seeder, which runs only when the seed loader is unavailable or throws. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 6e617badac6..8de58a89b70 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -415,11 +415,9 @@ seed record supplies for a summary field is not written, on create or on update, and the rest of the record is. The summary is computed from the seeded child records, so a parent seeded with a total and no children shows the empty-set value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), -and re-seeding a parent leaves its computed value in place. The load result -counts the values it did not write in `summariesDropped` (per dataset) and -`summary.totalSummariesDropped`, and the load logs one warning per dataset that -names the object and the fields. To show a total, seed the child records it -sums. Server code that runs with `isSystem: true` can still write the column, +and re-seeding a parent leaves its computed value in place. The load logs one +warning per dataset that names the object, the fields and how many values it +did not write. To show a total, seed the child records it sums. Server code that runs with `isSystem: true` can still write the column, as it can any read-only column: a historical import (`treatAsHistorical: true`, which only the system principal may send) keeps a pre-computed total, on create and on update. Undoing an ordinary diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index 028040dd75c..0de1a5b1936 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -163,7 +163,6 @@ Result of loading a single dataset | **referencesDeferred** | `integer` | ✅ | References deferred to second pass | | **referencesDropped** | `integer` | optional (default: `0`) | Reference fields dropped from records that were still written | | **summariesStale** | `integer` | optional (default: `0`) | Roll-up summary values left stale by writes for this dataset | -| **summariesDropped** | `integer` | optional (default: `0`) | Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up) | | **landedIds** | `string[]` | optional (default: `[]`) | Ids of the stored rows this dataset landed on: inserted, updated, or matched on replay | | **insertedIds** | `string[]` | optional (default: `[]`) | Ids among landedIds whose row this load created (a successful insert); every other landed id was a pre-existing row a record key matched | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | optional (default: `[]`) | Reference resolution errors | @@ -305,7 +304,6 @@ Result of loading a single dataset | **referencesDeferred** | `integer` | ✅ | References deferred to second pass | | **referencesDropped** | `integer` | optional (default: `0`) | Reference fields dropped from records that were still written | | **summariesStale** | `integer` | optional (default: `0`) | Roll-up summary values left stale by writes for this dataset | -| **summariesDropped** | `integer` | optional (default: `0`) | Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up) | | **landedIds** | `string[]` | optional (default: `[]`) | Ids of the stored rows this dataset landed on: inserted, updated, or matched on replay | | **insertedIds** | `string[]` | optional (default: `[]`) | Ids among landedIds whose row this load created (a successful insert); every other landed id was a pre-existing row a record key matched | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | optional (default: `[]`) | Reference resolution errors | @@ -338,7 +336,6 @@ Actionable error for a failed reference resolution | **totalReferencesDeferred** | `integer` | ✅ | Total references deferred | | **totalReferencesDropped** | `integer` | optional (default: `0`) | Total reference fields dropped from written records | | **totalSummariesStale** | `integer` | optional (default: `0`) | Total roll-up summary values left stale across the load | -| **totalSummariesDropped** | `integer` | optional (default: `0`) | Total roll-up summary values supplied by seed records and not written | | **circularDependencyCount** | `integer` | ✅ | Circular dependency chains detected | | **durationMs** | `number` | ✅ | Load duration in milliseconds | diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index 64ffced1046..f13d36d761e 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -311,11 +311,14 @@ describe('the counter survives the contract, and the contract survives older pay /** * [#35655] The other half of a seed and a roll-up: a seed never stores a - * value it supplies for a `summary` field (maintainer ruling D, record - * 7063117450). The loader takes it out of the record before the write, counts - * it in `summariesDropped`, and the engine computes the column from the child - * rows. These pins read the engine's CALLS, so they hold whatever the engine - * would do with the key; the stored outcome on the real engine is pinned in + * value it supplies for a `summary` field (maintainer ruling D, as analysed in + * 7062334196; the seat's correction 7064615114). The loader takes it out of + * the record before the write, and the engine computes the column from the + * child rows. The drop is reported by one `warn` per dataset naming the + * object, the fields and the count: that notice is the report, and no + * load-result key carries it. These pins read the engine's CALLS and the + * notice, so they hold whatever the engine would do with the key; the stored + * outcome on the real engine is pinned in * `packages/objectql/src/seed-summary-never-stored.test.ts`. */ describe('a seed never hands the engine a roll-up value (#35655)', () => { @@ -346,8 +349,11 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { (engine[verb] as any).mock.calls .filter(([object]: [string]) => object === 'drop_invoice') .flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row))); + /** The roll-up drop notices the load logged: `[message, meta]` per `warn`. */ + const dropNotices = (logger: ReturnType) => + (logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary')); - it('on insert: neither roll-up reaches the engine, the rest of the row does, and the drop is counted and named once', async () => { + it('on insert: neither roll-up reaches the engine, the rest of the row does, and one notice names the object, fields and count', async () => { const { engine, store } = createFaithfulEngine(); const logger = createLogger(); @@ -365,20 +371,25 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { expect(keys).not.toContain('payments'); } expect(store.drop_invoice.map((r) => r.total)).toEqual([10, 20, 30]); - // A supplied `null` is a supplied value too: three values, two fields. - expect(result.results[0]).toMatchObject({ inserted: 3, errored: 0, summariesDropped: 3 }); - expect(result.summary.totalSummariesDropped).toBe(3); + // The rest of each record landed: nothing about the drop is an error. + expect(result.results[0]).toMatchObject({ inserted: 3, errored: 0 }); expect(result.success).toBe(true); - const drops = (logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary')); + // A supplied `null` is a supplied value too: three values, two fields, ONE notice. + const drops = dropNotices(logger); expect(drops).toHaveLength(1); - expect(drops[0][1]).toEqual({ object: 'drop_invoice', fields: ['paid', 'payments'], summariesDropped: 3 }); + expect(drops[0][1]).toEqual({ object: 'drop_invoice', fields: ['paid', 'payments'], droppedValues: 3 }); + expect(drops[0][0]).toContain('drop_invoice'); + expect(drops[0][0]).toContain('`paid`, `payments`'); + // The notice is the whole report: the load result carries no key for it. + expect(Object.keys(result.results[0])).not.toContain('summariesDropped'); }); - it('on a matched row (upsert): the update carries no roll-up, and a roll-up-only difference writes nothing', async () => { + it('on a matched row (upsert): the update carries no roll-up, a roll-up-only difference writes nothing, and the notice still speaks', async () => { const { engine, store } = createFaithfulEngine(); + const logger = createLogger(); store.drop_invoice = [{ id: 'inv-1', name: 'INV-1', total: 10, paid: 42, payments: 2 }]; - const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).load({ + const result = await new SeedLoaderService(engine, rollUpMetadata(), logger).load({ seeds: [{ ...seedFor('drop_invoice', [ { name: 'INV-1', total: 10, paid: 999, payments: 99 }, ]), mode: 'upsert' }] as any, @@ -387,7 +398,10 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { expect(writtenKeys(engine, 'update')).toEqual([]); expect(store.drop_invoice[0]).toMatchObject({ paid: 42, payments: 2 }); - expect(result.results[0]).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 2 }); + expect(result.results[0]).toMatchObject({ updated: 0, skipped: 1 }); + expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ + { object: 'drop_invoice', fields: ['paid', 'payments'], droppedValues: 2 }, + ]); }); it('on a matched row whose other columns changed: the update writes them and still no roll-up', async () => { @@ -407,41 +421,34 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { expect(keys[0]).not.toContain('paid'); expect(keys[0]).not.toContain('payments'); expect(store.drop_invoice[0]).toMatchObject({ total: 11, paid: 42, payments: 2 }); - expect(result.results[0]).toMatchObject({ updated: 1, summariesDropped: 2 }); + expect(result.results[0]).toMatchObject({ updated: 1 }); }); - it('a dry run (validate) counts the same drop and writes nothing', async () => { + it('a dry run (validate) gives the same notice and writes nothing', async () => { const { engine } = createFaithfulEngine(); + const logger = createLogger(); - const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).validate( + await new SeedLoaderService(engine, rollUpMetadata(), logger).validate( [seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any, ); expect(writtenKeys(engine, 'insert')).toEqual([]); - expect(result.results[0].summariesDropped).toBe(1); + expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ + { object: 'drop_invoice', fields: ['paid'], droppedValues: 1 }, + ]); }); - it('CONTROL: a field the definition does not type `summary` is written as authored, and nothing is reported', async () => { + it('CONTROL: a field the definition does not type `summary` is written as authored, and no notice is logged', async () => { const { engine } = createFaithfulEngine(); const logger = createLogger(); const plain = { drop_invoice: { name: 'drop_invoice', fields: { name: { type: 'text' }, total: { type: 'number' }, paid: { type: 'currency' } } } }; - const result = await new SeedLoaderService(engine, rollUpMetadata(plain), logger).load({ + await new SeedLoaderService(engine, rollUpMetadata(plain), logger).load({ seeds: [seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any, config: CONFIG, }); expect(writtenKeys(engine, 'insert')[0]).toContain('paid'); - expect(result.results[0].summariesDropped).toBe(0); - expect((logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary'))).toEqual([]); - }); - - it('defaults to 0 for a payload written before the field existed', () => { - const legacyPerObject = { - object: 'drop_invoice', mode: 'ignore', - inserted: 1, updated: 0, skipped: 0, errored: 0, total: 1, - referencesResolved: 0, referencesDeferred: 0, errors: [], - }; - expect(SeedLoadResultSchema.parse(legacyPerObject).summariesDropped).toBe(0); + expect(dropNotices(logger)).toEqual([]); }); }); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index f4c52ead764..1807cc25bb9 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -782,7 +782,7 @@ function createOnlySeedColumns(dataset: Seed, externalId: string | string[]): Re * not it is declared `readonly`. A seed never stores a value for one (maintainer * ruling D, record 7063117450): the engine computes it from the child rows, so * {@link SeedLoaderService} takes a seed record's value for it out before the - * replay compare and before the write, and reports it in `summariesDropped`. + * replay compare and before the write, and says so in one `warn` per dataset. * * Keyed on `type === 'summary'` literally, as the engine's roll-up readers * are (`summaryFieldsLockedOnWrite`, `getSummaryDescriptors`). A definition @@ -1801,7 +1801,6 @@ export class SeedLoaderService implements ISeedLoaderService { referencesDeferred: 0, referencesDropped: 0, summariesStale: 0, - summariesDropped: 0, landedIds: [], insertedIds: [], errors: [error], @@ -2129,7 +2128,7 @@ export class SeedLoaderService implements ISeedLoaderService { // the values this dataset's records supplied for them, and which of them // did — reported once, after the record loop. const summaryFields = summaryFieldNames(objectDefinition); - let summariesDropped = 0; + let summaryValuesDropped = 0; const summaryFieldsDropped = new Set(); // How a replay compares each field (`isNoOpReplay`): [#24562] a temporal // field in its stored form, [#24624] a field the read path masks never by @@ -2275,7 +2274,7 @@ export class SeedLoaderService implements ISeedLoaderService { for (const field of summaryFields) { if (!Object.prototype.hasOwnProperty.call(record, field)) continue; if (record[field] !== undefined) { - summariesDropped++; + summaryValuesDropped++; summaryFieldsDropped.add(field); } delete record[field]; @@ -3231,20 +3230,20 @@ export class SeedLoaderService implements ISeedLoaderService { )]; // [#35655] Once per dataset, naming the object, the fields and the count: - // the seed asked for a total the platform did not store. `warn`, not + // the seed asked for a total the platform did not store. This notice IS + // the report (ruling D as analysed in 7062334196, point (e); the seat's + // correction 7064615114): no load-result key carries it. `warn`, not // `error`: nothing claimed persisted is lost — a roll-up is never the - // seed's to write, the rest of every record landed, and the machine trace - // is `summariesDropped` on this object's result. - if (summariesDropped > 0) { + // seed's to write, and the rest of every record landed. + if (summaryValuesDropped > 0) { const fields = [...summaryFieldsDropped]; this.logger.warn( - `[SeedLoader] The ${objectName} seed supplies ${summariesDropped} value(s) for the roll-up summary ` + + `[SeedLoader] The ${objectName} seed supplies ${summaryValuesDropped} value(s) for the roll-up summary ` + `field(s) ${fields.map((f) => `\`${f}\``).join(', ')}, which a seed never stores: the values are not ` + `written, the rest of each record is, and each roll-up is computed from its child rows, so a record ` + `with no children reads the empty-child-list value (0 for count and sum, empty for min, max and avg). ` + - `Seed the child rows the total counts, and leave the summary field out of the ${objectName} seed. ` + - `The count is summariesDropped on this object's load result.`, - { object: objectName, fields, summariesDropped }, + `Seed the child rows the total counts, and leave the summary field out of the ${objectName} seed.`, + { object: objectName, fields, droppedValues: summaryValuesDropped }, ); } @@ -3261,7 +3260,6 @@ export class SeedLoaderService implements ISeedLoaderService { referencesDeferred, referencesDropped, summariesStale: this.summariesStale - summariesStaleAtStart, - summariesDropped, landedIds, insertedIds, errors, @@ -5587,7 +5585,6 @@ export class SeedLoaderService implements ISeedLoaderService { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, - totalSummariesDropped: 0, circularDependencyCount: 0, durationMs, }, @@ -5616,8 +5613,6 @@ export class SeedLoaderService implements ISeedLoaderService { // — the field is declared with `.default(0)`, so it survives a parse of a // payload written before it existed (#4998). totalSummariesStale: results.reduce((sum, r) => sum + r.summariesStale, 0), - // [#35655] Every entry is built by `loadDataset`, which always populates it. - totalSummariesDropped: results.reduce((sum, r) => sum + r.summariesDropped, 0), circularDependencyCount: graph.circularDependencies.length, durationMs, }; diff --git a/packages/objectql/src/seed-summary-never-stored.test.ts b/packages/objectql/src/seed-summary-never-stored.test.ts index b66e15aa26c..9a4a01f9d8a 100644 --- a/packages/objectql/src/seed-summary-never-stored.test.ts +++ b/packages/objectql/src/seed-summary-never-stored.test.ts @@ -4,9 +4,9 @@ * [#35655] A seed never stores a roll-up (summary) value (maintainer ruling D, * record 7063117450). The seed loader takes a seed record's value for every * `type: 'summary'` field out of the record before the replay compare and the - * write; the roll-up is computed from the child rows; the load result counts - * the dropped values in `summariesDropped`, and one `warn` per dataset names - * the object, the fields and the count. + * write; the roll-up is computed from the child rows; and one `warn` per + * dataset names the object, the fields and the count. That notice is the + * report (the seat's correction 7064615114): no load-result key carries it. * * Measured on unfixed `main` 493ad095d4 with this file's harness (the real * ObjectQL engine and the real SeedLoaderService), parent `ss_inv` seeded with @@ -18,7 +18,7 @@ * 6 the same seed loaded twice load 1: 42 / 2, load 2: 999 / 99 * * Every case below asserts the parent equal to its roll-up after every load, - * and the drop counted. One rule for every aggregate: a `sum`, a `count` and a + * and the drop reported by the notice. One rule for every aggregate: a `sum`, a `count` and a * `max` (no empty-set value, so it stays empty) are seeded side by side, and a * roll-up an extension contributes is dropped like the base object's own. */ @@ -162,6 +162,9 @@ describe('[#35655] a seed never stores a roll-up value: the children decide it, const inv = (name: string) => [...storeFor('ss_inv').values()].find((r: any) => r.name === name); const resultOf = (r: any, object: string) => r.results.find((x: any) => x.object === object); const dropWarns = () => warns.filter((w) => w.message.includes('roll-up summary')); + /** The notice's meta, per dataset that dropped anything. */ + const dropMetas = () => dropWarns().map((w) => w.meta); + const ALL = { object: 'ss_inv', fields: ['line_total', 'line_count', 'line_max'], droppedValues: 3 }; it('case 3: a parent seeded with totals and no children stores the empty-set values, and the load reports the drop', async () => { const r = await load([P([{ name: 'A', ...SUPPLIED }])]); @@ -170,39 +173,44 @@ describe('[#35655] a seed never stores a roll-up value: the children decide it, // sum and count start at 0; max has no empty-set value and stays empty. expect(inv('A')).toMatchObject({ line_total: 0, line_count: 0 }); expect(inv('A')?.line_max ?? null).toBeNull(); - expect(resultOf(r, 'ss_inv')).toMatchObject({ inserted: 1, errored: 0, summariesDropped: 3 }); - expect(r.summary.totalSummariesDropped).toBe(3); + expect(resultOf(r, 'ss_inv')).toMatchObject({ inserted: 1, errored: 0 }); // One line for the dataset, naming the object, every field and the count. - expect(dropWarns()).toHaveLength(1); - expect(dropWarns()[0].meta).toEqual({ object: 'ss_inv', fields: ['line_total', 'line_count', 'line_max'], summariesDropped: 3 }); + expect(dropMetas()).toEqual([ALL]); + expect(dropWarns()[0].message).toContain('The ss_inv seed supplies 3 value(s)'); expect(dropWarns()[0].message).toContain('`line_total`, `line_count`, `line_max`'); + // The notice is the whole report: the load result carries no key for it. + expect(Object.keys(resultOf(r, 'ss_inv'))).not.toContain('summariesDropped'); }); it('case 1 (control): parent and children in one load store the roll-up, and the drop is still reported', async () => { const r = await load([P([{ name: 'A', ...SUPPLIED }]), C(LINES)]); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); - expect(resultOf(r, 'ss_inv').summariesDropped).toBe(3); - expect(resultOf(r, 'ss_line').summariesDropped).toBe(0); + // The parent's dataset gives the notice; the children's, which supply no roll-up, gives none. + expect(dropMetas()).toEqual([ALL]); + expect(resultOf(r, 'ss_line')).toMatchObject({ inserted: 2 }); }); it('case 4: a re-seed over existing children keeps the computed values, and a roll-up-only difference is no write', async () => { await load([P([{ name: 'A' }]), C(LINES)]); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + warns = []; const r = await load([P([{ name: 'A', ...SUPPLIED }])]); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); - expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 3 }); + expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1 }); + expect(dropMetas()).toEqual([ALL]); }); it('case 4 under `update` mode: the matched row keeps its computed values', async () => { await load([P([{ name: 'A' }]), C(LINES)]); - const r = await load([P([{ name: 'A', ...SUPPLIED }], 'update')]); + warns = []; + await load([P([{ name: 'A', ...SUPPLIED }], 'update')]); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); - expect(resultOf(r, 'ss_inv').summariesDropped).toBe(3); + expect(dropMetas()).toEqual([ALL]); }); it('case 6: the same seed replayed stores the same totals on both loads', async () => { @@ -211,9 +219,12 @@ describe('[#35655] a seed never stores a roll-up value: the children decide it, await load(seeds); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + warns = []; const r = await load(seeds); expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); - expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1, summariesDropped: 3 }); + expect(resultOf(r, 'ss_inv')).toMatchObject({ updated: 0, skipped: 1 }); + // Every replay says it again: the seed still supplies the totals. + expect(dropMetas()).toEqual([ALL]); }); it('a roll-up an extension contributes is dropped like the object\'s own', async () => { @@ -222,17 +233,16 @@ describe('[#35655] a seed never stores a roll-up value: the children decide it, fields: { ext_total: { type: 'summary', summaryOperations: { object: 'ss_line', field: 'amount', function: 'sum' } } }, } as any, 'ext-package', undefined, 'extend'); - const r = await load([P([{ name: 'A', ext_total: 7 }])]); + await load([P([{ name: 'A', ext_total: 7 }])]); expect(inv('A')).toMatchObject({ ext_total: 0 }); - expect(resultOf(r, 'ss_inv').summariesDropped).toBe(1); - expect(dropWarns()[0].meta?.fields).toEqual(['ext_total']); + expect(dropMetas()).toEqual([{ object: 'ss_inv', fields: ['ext_total'], droppedValues: 1 }]); }); it('a seed that supplies no roll-up value reports nothing', async () => { const r = await load([P([{ name: 'A' }]), C(LINES)]); - expect(r.summary.totalSummariesDropped).toBe(0); + expect(r.success).toBe(true); expect(dropWarns()).toEqual([]); }); }); diff --git a/packages/spec/authorable-defaults/data.json b/packages/spec/authorable-defaults/data.json index 7c860e9477b..33667d688be 100644 --- a/packages/spec/authorable-defaults/data.json +++ b/packages/spec/authorable-defaults/data.json @@ -105,7 +105,6 @@ "data/SeedLoadResult:insertedIds = []", "data/SeedLoadResult:landedIds = []", "data/SeedLoadResult:referencesDropped = 0", - "data/SeedLoadResult:summariesDropped = 0", "data/SeedLoadResult:summariesStale = 0", "data/SeedLoaderConfig:batchSize = 1000", "data/SeedLoaderConfig:defaultMode = \"ignore\"", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index b7d3db456f9..f8b14bebc70 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -984,7 +984,6 @@ "data/SeedLoadResult:referencesDropped", "data/SeedLoadResult:referencesResolved", "data/SeedLoadResult:skipped", - "data/SeedLoadResult:summariesDropped", "data/SeedLoadResult:summariesStale", "data/SeedLoadResult:total", "data/SeedLoadResult:updated", diff --git a/packages/spec/src/contracts/seed-loader-service.test.ts b/packages/spec/src/contracts/seed-loader-service.test.ts index 0f1f67120d7..affe14afd03 100644 --- a/packages/spec/src/contracts/seed-loader-service.test.ts +++ b/packages/spec/src/contracts/seed-loader-service.test.ts @@ -30,7 +30,6 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, - totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 0, }, @@ -57,7 +56,6 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, - totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 0, }, @@ -89,7 +87,6 @@ describe('Seed Loader Service Contract', () => { totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, - totalSummariesDropped: 0, circularDependencyCount: 0, durationMs: 42, }, @@ -104,7 +101,7 @@ describe('Seed Loader Service Contract', () => { summary: { objectsProcessed: 0, totalRecords: 0, totalInserted: 0, totalUpdated: 0, totalSkipped: 0, totalErrored: 0, totalReferencesResolved: 0, - totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, totalSummariesDropped: 0, + totalReferencesDeferred: 0, totalReferencesDropped: 0, totalSummariesStale: 0, circularDependencyCount: 0, durationMs: 0, }, }), diff --git a/packages/spec/src/data/seed-loader.zod.ts b/packages/spec/src/data/seed-loader.zod.ts index 2959b8e69e7..855aff99898 100644 --- a/packages/spec/src/data/seed-loader.zod.ts +++ b/packages/spec/src/data/seed-loader.zod.ts @@ -412,31 +412,6 @@ export const SeedLoadResultSchema = lazySchema(() => z.object({ summariesStale: z.number().int().min(0).default(0) .describe('Roll-up summary values left stale by writes for this dataset'), - /** - * Number of roll-up summary values this dataset's records SUPPLIED that the - * loader did not write — "the seed named a total, the children decide it". - * - * A roll-up summary is a DERIVED value: the engine computes it from the - * child rows. A seed never stores one, on insert or on update (maintainer - * ruling D, record 7063117450): the loader takes every value a seed record supplies - * for a field its object declares `type: 'summary'` out of the record - * before the replay compare and before the write. A row the load creates - * starts the column at its empty-child-list value (`0` for `count` and - * `sum`, empty for `min`, `max` and `avg`) and the child rows the load - * writes compute it; a row the load matches keeps the value it holds. One - * per record and field, counted whether or not the rest of the record then - * lands. - * - * The rest of each record IS written, so neither `errored` nor `success` - * moves and `inserted + updated + skipped + errored` still reconciles - * against `total` — the reasoning that gave `referencesDropped` and - * `summariesStale` their own counters. Without it the dropped total would be - * visible only as a log line, and a parent seeded with a total and no - * children would read `0` with nothing in the result to say why. - */ - summariesDropped: z.number().int().min(0).default(0) - .describe('Roll-up summary values supplied by seed records and not written (a seed never stores a roll-up)'), - /** * The ids of the stored rows this dataset's records landed on: a row a * record inserted, a row it updated, and a row its key matched on a replay @@ -564,14 +539,6 @@ export const SeedLoaderResultSchema = lazySchema(() => z.object({ totalSummariesStale: z.number().int().min(0).default(0) .describe('Total roll-up summary values left stale across the load'), - /** - * Total roll-up summary values the seed records supplied and the loader - * did not write — "the seed named a total, the children decide it". See - * `SeedLoadResult.summariesDropped`. - */ - totalSummariesDropped: z.number().int().min(0).default(0) - .describe('Total roll-up summary values supplied by seed records and not written'), - /** Number of circular dependency chains detected */ circularDependencyCount: z.number().int().min(0).describe('Circular dependency chains detected'), diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts index 44f1f7f1053..137e1b40cd2 100644 --- a/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts +++ b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts @@ -29,13 +29,13 @@ export const entry: SemanticMigration = { + 'refused for it. The loader now takes every such value out of the record before the replay compare and the ' + 'write, on insert and on update: a created row starts the column at its empty-child-list value (0 for `count` ' + 'and `sum`, empty for `min`, `max` and `avg`) and the seeded child rows compute it; a matched row keeps the ' - + 'value it holds. The load result counts the values it did not write in `summariesDropped` per dataset and ' - + '`summary.totalSummariesDropped`, and the load logs one warning per dataset naming the object and the fields. ' + + 'value it holds. The load logs one warning per dataset naming the object, the fields and how many values it ' + + 'did not write. ' + 'There is no mechanical rewrite: only the author knows whether the total stands for child rows that should be ' + 'seeded or for a figure that is not a roll-up at all. Rows an earlier load stored a supplied total on are data, ' + 'not metadata: the next child write recomputes them', acceptanceCriteria: - 'No seed record supplies a value for a `summary` field: every seed load result reports `summariesDropped: 0` ' - + 'for each dataset and the boot log carries no roll-up drop warning, and every seeded roll-up equals the ' - + 'aggregate of its seeded child rows after the first boot and after a restart.', + 'No seed record supplies a value for a `summary` field: the boot log and a seed validation carry no roll-up ' + + 'drop warning for any dataset, and every seeded roll-up equals the aggregate of its seeded child rows after the ' + + 'first boot and after a restart.', }; From ed66759441896681a3c08888d4bb2d821eaa94df Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:09:15 +0000 Subject: [PATCH 6/9] docs(changeset): a roll-up-only replay difference is counted skipped, not updated Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 --- .changeset/35655-seed-summary-value-not-stored.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/35655-seed-summary-value-not-stored.md b/.changeset/35655-seed-summary-value-not-stored.md index bea2b765fe0..edf2321f99e 100644 --- a/.changeset/35655-seed-summary-value-not-stored.md +++ b/.changeset/35655-seed-summary-value-not-stored.md @@ -14,7 +14,7 @@ Metadata-protocol: narrowed - FROM: the seed loader writes as the system principal, so the supplied value was stored as written. It stayed wherever no child write came after it: a parent seeded with a total and no children kept the total; a re-seed over existing children wrote it over the computed value; and a keep-current (`upsert`) seed replayed on the next boot stored the computed total on the first load and the supplied one on the second. - TO: the loader takes every such value out of the record before the replay compare and the write, on insert and on update, and writes the rest of the record. A created row starts the column at its empty-child-list value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), and the seeded child rows compute it. A matched row keeps the value it holds, so a replay whose only difference is the roll-up writes nothing. A parent seeded with a total and no children now reads `0`. -- Reported, not silent: the load logs one warning per dataset naming the object, the fields and how many values it did not write. A dry run (`validate`) logs the same warning. `success`, `errored` and the row counters do not move, and the load result gains no key. +- Reported, not silent: the load logs one warning per dataset naming the object, the fields and how many values it did not write. A dry run (`validate`) logs the same warning. `success` and `errored` do not move, and the load result gains no key. One row counter does: on a replay (`upsert` or `update`), a matched row whose only difference from the seed record was a roll-up value is now counted `skipped`, with nothing written, where it used to be counted `updated`. Compatibility note for seed authors: to show a total, seed the child rows it is computed from and leave the summary field out of the parent's seed record. A figure no child rows back is not a roll-up: declare it a `number` or `currency` field. A legacy total that must land as written goes through a historical import (`treatAsHistorical: true`), which is unchanged. Rows an earlier load stored a supplied total on are not rewritten by the loader; the next child write recomputes them. From 9737321e4677d76265cf71e91712588b5ca9e326 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:40:21 +0000 Subject: [PATCH 7/9] fix(metadata-protocol): strip an extension-contributed roll-up from a seed too; docs name the recompute and the degraded fallback The seed loader's roll-up strip read only the resolved definition, which is the metadata service's copy whenever it has fields; that copy carries no object extension, so an extension's roll-up reached the engine. The strip now unions the resolved definition's summary fields with the engine's merged schema. security.mdx no longer says seeds and package installs write a roll-up; fields.mdx names the runtime's basic-insert fallback seeder as the degraded path that still stores one. The changeset and the migration entry name the manual repair for a childless parent stored with a total. Two stale test comments are corrected. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- .../35655-seed-summary-value-not-stored.md | 2 +- content/docs/data-modeling/fields.mdx | 5 +- content/docs/protocol/objectql/security.mdx | 6 +- ...eed-loader-summary-extension-35655.test.ts | 162 ++++++++++++++++++ packages/metadata-protocol/src/seed-loader.ts | 29 +++- packages/objectql/src/summary-rollup.test.ts | 12 +- .../data/field-autonumber-readonly.test.ts | 4 +- .../18.seed-summary-value-not-stored.ts | 4 +- 8 files changed, 207 insertions(+), 17 deletions(-) create mode 100644 packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts diff --git a/.changeset/35655-seed-summary-value-not-stored.md b/.changeset/35655-seed-summary-value-not-stored.md index edf2321f99e..d185cb0c063 100644 --- a/.changeset/35655-seed-summary-value-not-stored.md +++ b/.changeset/35655-seed-summary-value-not-stored.md @@ -16,6 +16,6 @@ Metadata-protocol: narrowed - TO: the loader takes every such value out of the record before the replay compare and the write, on insert and on update, and writes the rest of the record. A created row starts the column at its empty-child-list value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), and the seeded child rows compute it. A matched row keeps the value it holds, so a replay whose only difference is the roll-up writes nothing. A parent seeded with a total and no children now reads `0`. - Reported, not silent: the load logs one warning per dataset naming the object, the fields and how many values it did not write. A dry run (`validate`) logs the same warning. `success` and `errored` do not move, and the load result gains no key. One row counter does: on a replay (`upsert` or `update`), a matched row whose only difference from the seed record was a roll-up value is now counted `skipped`, with nothing written, where it used to be counted `updated`. -Compatibility note for seed authors: to show a total, seed the child rows it is computed from and leave the summary field out of the parent's seed record. A figure no child rows back is not a roll-up: declare it a `number` or `currency` field. A legacy total that must land as written goes through a historical import (`treatAsHistorical: true`), which is unchanged. Rows an earlier load stored a supplied total on are not rewritten by the loader; the next child write recomputes them. +Compatibility note for seed authors: to show a total, seed the child rows it is computed from and leave the summary field out of the parent's seed record. A figure no child rows back is not a roll-up: declare it a `number` or `currency` field. A legacy total that must land as written goes through a historical import (`treatAsHistorical: true`), which is unchanged. Rows an earlier load stored a supplied total on are not rewritten by the loader; the next child write recomputes them. A parent with no child rows gets no such write, and `os migrate summary-nulls` backfills only `NULL` columns, so repair one by hand: insert a child row under it and delete that row again, and the recompute leaves the empty-set value. Not changed: the engine (`packages/objectql`), which still keeps a value an `isSystem` write sends (the roll-up recompute, the backfill, a historical import); the import and REST doors; and the runtime's basic-insert fallback seeder, which runs only when the seed loader is unavailable or throws. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 8de58a89b70..7e7509c9e49 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -417,7 +417,10 @@ child records, so a parent seeded with a total and no children shows the empty-set value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`), and re-seeding a parent leaves its computed value in place. The load logs one warning per dataset that names the object, the fields and how many values it -did not write. To show a total, seed the child records it sums. Server code that runs with `isSystem: true` can still write the column, +did not write. One degraded path does not go through the seed loader: when the +runtime has no metadata service, or the seed loader throws, it falls back to a +basic insert of the seed records, and that fallback still stores a supplied +summary value. To show a total, seed the child records it sums. Server code that runs with `isSystem: true` can still write the column, as it can any read-only column: a historical import (`treatAsHistorical: true`, which only the system principal may send) keeps a pre-computed total, on create and on update. Undoing an ordinary diff --git a/content/docs/protocol/objectql/security.mdx b/content/docs/protocol/objectql/security.mdx index 916959debb1..1725c892fc6 100644 --- a/content/docs/protocol/objectql/security.mdx +++ b/content/docs/protocol/objectql/security.mdx @@ -286,8 +286,10 @@ starts the column as for an empty child list. That covers a flow's `create_recor `os build` report such a step as the `flow-update-summary-field` warning, which never blocks a build, though like every warning it makes `os validate --strict` and `os lint --strict` exit 1 (a roll-up declared `readonly: true` is the `flow-update-readonly-field` error). Rule 1 below -holds for it: seed data, package installs and the roll-up's own recompute write it from a -system context. See [Calculation types](/docs/data-modeling/fields#calculation-types). +holds for it: the roll-up's own recompute and a historical import (`treatAsHistorical: true`) +write it from a system context. Seed data, including the seed data a package install loads, +does not: the seed loader takes a seed record's value for a roll-up out before the write, and the +child records compute it. See [Calculation types](/docs/data-modeling/fields#calculation-types). Five rules decide whether a given value survives: diff --git a/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts b/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts new file mode 100644 index 00000000000..39e71ec515e --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts @@ -0,0 +1,162 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { SeedLoaderService } from './seed-loader.js'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; + +/** + * [#35655] A seed never stores a roll-up (maintainer ruling D, record + * 7063117450), and that includes a roll-up an object EXTENSION contributes. + * + * The loader resolves a definition from the metadata service first and uses + * that copy whenever it has `fields`, without consulting the engine. The + * metadata service stores the object as registered, with no extension merged + * in, so its copy can lack a roll-up the engine's merged schema declares and + * computes. The strip therefore reads both: the resolved definition and the + * engine's own schema. These pins hand the loader a metadata copy WITHOUT the + * extension's roll-up and an engine schema WITH it. + */ + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** The object as the metadata service stores it: no extension merged in. */ +const METADATA_COPY = { + name: 'ext_invoice', + fields: { + name: { type: 'text' }, + total: { type: 'number' }, + paid: { type: 'summary', summaryOperations: { object: 'ext_payment', field: 'amount', function: 'sum' } }, + }, +}; + +/** The engine's merged schema: the same object plus an extension's roll-up. */ +const ENGINE_SCHEMA = { + ...METADATA_COPY, + fields: { + ...METADATA_COPY.fields, + ext_refunds: { type: 'summary', summaryOperations: { object: 'ext_refund', field: 'amount', function: 'count' } }, + }, +}; + +function createEngine(getSchema: (name: string) => unknown): IDataEngine { + const store: Record = {}; + let idCounter = 0; + const engine = { + getSchema: vi.fn(getSchema), + find: vi.fn(async (objectName: string, query?: any) => { + let records = store[objectName] || []; + if (query?.where) { + records = records.filter((r) => + Object.entries(query.where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), + ); + } + if (typeof query?.limit === 'number') records = records.slice(0, query.limit); + return records; + }), + findOne: vi.fn(async (objectName: string, query?: any) => { + assertEngineFindOnePredicate(objectName, query); + const rows = await (engine.find as any)(objectName, { ...query, limit: 1 }); + return rows[0] ?? null; + }), + insert: vi.fn(async (objectName: string, data: any) => { + if (!store[objectName]) store[objectName] = []; + const rows = (Array.isArray(data) ? data : [data]).map((d) => ({ id: `gen-${++idCounter}`, ...d })); + store[objectName].push(...rows); + return Array.isArray(data) ? rows : rows[0]; + }), + update: vi.fn(async (objectName: string, data: any) => { + assertEngineUpdateDispatch(data, undefined); + const records = store[objectName] || []; + const idx = records.findIndex((r) => r.id === data.id); + if (idx >= 0) { records[idx] = { ...records[idx], ...data }; return records[idx]; } + return data; + }), + delete: vi.fn(async (_objectName: string, options?: any) => { + assertEngineDeleteDispatch(options); + return { deleted: 1 }; + }), + count: vi.fn(async (objectName: string) => (store[objectName] || []).length), + aggregate: vi.fn(async () => []), + } as unknown as IDataEngine; + return engine; +} + +function metadataWith(copy: unknown): IMetadataService { + return { + getObject: vi.fn(async (name: string) => (name === 'ext_invoice' ? copy : undefined)), + listObjects: vi.fn(async () => [copy]), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => (name === 'ext_invoice' ? copy : undefined)), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; +} + +const CONFIG = { + dryRun: false, + haltOnError: false, + multiPass: true, + defaultMode: 'ignore', + batchSize: 1000, + transaction: false, +} as any; + +const SEED = { + object: 'ext_invoice', + externalId: 'name', + mode: 'ignore', + env: ['prod', 'dev', 'test'], + records: [{ name: 'INV-1', total: 10, paid: 3000, ext_refunds: 7 }], +}; + +const insertedKeys = (engine: IDataEngine) => + (engine.insert as any).mock.calls + .filter(([object]: [string]) => object === 'ext_invoice') + .flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row))); +const dropNotices = (logger: ReturnType) => + (logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary')); + +describe('a roll-up an object extension contributes is never seeded either (#35655)', () => { + it('the metadata copy lacks the extension roll-up, the engine schema has it: neither roll-up reaches the engine, and the notice names both', async () => { + const engine = createEngine((name) => (name === 'ext_invoice' ? ENGINE_SCHEMA : undefined)); + const logger = createLogger(); + + const result = await new SeedLoaderService(engine, metadataWith(METADATA_COPY), logger).load({ + seeds: [SEED] as any, + config: CONFIG, + }); + + const keys = insertedKeys(engine); + expect(keys).toHaveLength(1); + expect(keys[0]).toContain('total'); + expect(keys[0]).not.toContain('paid'); + expect(keys[0]).not.toContain('ext_refunds'); + expect(result.results[0]).toMatchObject({ inserted: 1, errored: 0 }); + expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ + { object: 'ext_invoice', fields: ['paid', 'ext_refunds'], droppedValues: 2 }, + ]); + }); + + it('CONTROL: an engine whose schema read throws leaves the metadata copy the only source, and its roll-up is still dropped', async () => { + const engine = createEngine(() => { throw new Error('no schema registry'); }); + const logger = createLogger(); + + await new SeedLoaderService(engine, metadataWith(METADATA_COPY), logger).load({ + seeds: [SEED] as any, + config: CONFIG, + }); + + const keys = insertedKeys(engine); + expect(keys[0]).not.toContain('paid'); + // Nothing declares `ext_refunds` a roll-up here, so it is written as authored. + expect(keys[0]).toContain('ext_refunds'); + expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ + { object: 'ext_invoice', fields: ['paid'], droppedValues: 1 }, + ]); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 1807cc25bb9..7ace59dffee 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -1675,13 +1675,23 @@ export class SeedLoaderService implements ISeedLoaderService { private async resolveObjectDefinition(objectName: string): Promise { const fromMetadata = (await this.metadata.getObject(objectName)) as any; if (fromMetadata?.fields) return fromMetadata; + const engineSchema = this.engineSchemaOf(objectName) as any; + if (engineSchema?.fields) return engineSchema; + return fromMetadata; + } + + /** + * The engine's own registered schema for `objectName` — the merged one, + * object extensions included — or `undefined` when the engine exposes no + * schema registry (or its read throws). + */ + private engineSchemaOf(objectName: string): unknown { try { - const engineSchema = (this.engine as { getSchema?(name: string): unknown }).getSchema?.(objectName) as any; - if (engineSchema?.fields) return engineSchema; + return (this.engine as { getSchema?(name: string): unknown }).getSchema?.(objectName); } catch { - // Engine may not expose a schema registry — the metadata result stands. + // Engine may not expose a schema registry — the caller's other source stands. + return undefined; } - return fromMetadata; } /** @@ -2126,8 +2136,15 @@ export class SeedLoaderService implements ISeedLoaderService { this.warnOnUndeclaredSeedColumns(dataset, objectDefinition); // [#35655] The roll-up columns a seed never writes (`summaryFieldNames`), // the values this dataset's records supplied for them, and which of them - // did — reported once, after the record loop. - const summaryFields = summaryFieldNames(objectDefinition); + // did — reported once, after the record loop. Read from the resolved + // definition AND the engine's merged schema: the metadata service's copy + // wins `resolveObjectDefinition` whenever it has `fields`, and it can lack + // a roll-up an object extension contributed, which the engine still + // computes — so a seed must not write it either. + const summaryFields = [...new Set([ + ...summaryFieldNames(objectDefinition), + ...summaryFieldNames(this.engineSchemaOf(objectName)), + ])]; let summaryValuesDropped = 0; const summaryFieldsDropped = new Set(); // How a replay compares each field (`isNoOpReplay`): [#24562] a temporal diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 375cc98fce0..9093a4e3dfd 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -468,11 +468,13 @@ describe('roll-up summary seeding on the PARENT insert (#5749)', () => { }); // [#34672] These two cases kept an ordinary caller's starting value until the - // create side of the roll-up lock landed. The seed still never overwrites a - // supplied value, but only the system principal (seed loads, package - // installs, historical imports) can still supply one; an ordinary caller's - // is dropped and the seed fills the column. - it('never overwrites a value a system writer supplied on insert (seed data, a historical import)', async () => { + // create side of the roll-up lock landed. The insert-time seed still never + // overwrites a supplied value, but only the system principal (a historical + // import, server code under `isSystem`) can still supply one; an ordinary + // caller's is dropped and the insert-time seed fills the column. The seed + // LOADER never supplies one (#35655): it drops a seed record's roll-up value + // before the write. + it('never overwrites a value a system writer supplied on insert (a historical import)', async () => { const p = await engine.insert('project', { name: 'Imported', task_count: 7, total_estimate: 42 }, { context: { isSystem: true } } as any); expect(row(p.id).task_count).toBe(7); expect(row(p.id).total_estimate).toBe(42); diff --git a/packages/spec/src/data/field-autonumber-readonly.test.ts b/packages/spec/src/data/field-autonumber-readonly.test.ts index b81fe712fed..6de573516a7 100644 --- a/packages/spec/src/data/field-autonumber-readonly.test.ts +++ b/packages/spec/src/data/field-autonumber-readonly.test.ts @@ -86,7 +86,9 @@ describe('RUNTIME_OWNED_FIELD_TYPES is the protocol vocabulary — the types who it('does NOT name the other calculated types, nor ordinary ones', () => { // `formula` is computed on read (no stored caller value to strip); - // `summary` is a stored roll-up a caller MAY legitimately seed (#6014). + // `summary` is a stored roll-up with its own write lock (objectql's + // `summaryFieldsLockedOnWrite`), which still lets a system writer such as a + // historical import supply it (#6014); a seed never does (#35655). for (const t of ['formula', 'summary', 'text', 'number']) { expect(RUNTIME_OWNED_FIELD_TYPES.has(t)).toBe(false); } diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts index 137e1b40cd2..7e0058c83d2 100644 --- a/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts +++ b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts @@ -33,7 +33,9 @@ export const entry: SemanticMigration = { + 'did not write. ' + 'There is no mechanical rewrite: only the author knows whether the total stands for child rows that should be ' + 'seeded or for a figure that is not a roll-up at all. Rows an earlier load stored a supplied total on are data, ' - + 'not metadata: the next child write recomputes them', + + 'not metadata: the next child write recomputes them. A parent with no child rows gets no such write, and ' + + '`os migrate summary-nulls` backfills only NULL columns, so repair one by hand: insert a child row under it and ' + + 'delete that row again, and the recompute leaves the empty-set value', acceptanceCriteria: 'No seed record supplies a value for a `summary` field: the boot log and a seed validation carry no roll-up ' + 'drop warning for any dataset, and every seeded roll-up equals the aggregate of its seeded child rows after the ' From c4dc4261812b398d0fbe94ce86b747b3d790bc60 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:56:10 +0000 Subject: [PATCH 8/9] test(metadata-protocol): the engine-schema-fallback pin allows the roll-up strip's engine read The strip now also reads the engine's merged schema, so the engine is asked once per seeded object even when the metadata service's definition wins. The pin keeps its claim (the definition comes from the metadata service: this engine registers no schema) and names the one probe per object. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- .../src/seed-loader-engine-schema-fallback.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts index 321fdb51e69..6aa2d2247f6 100644 --- a/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts +++ b/packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts @@ -207,7 +207,7 @@ describe('seed reference graph — engine schema fallback (marketplace objects)' expect(result.summary.totalReferencesResolved).toBeGreaterThanOrEqual(4); }); - it('prefers the metadata service definition when it exists (no engine probe)', async () => { + it('prefers the metadata service definition when it exists (the engine is probed only for roll-ups)', async () => { const { engine, store } = createFaithfulEngine({}); const metadata = createEmptyMetadata(); (metadata.getObject as any).mockImplementation(async (name: string) => ENGINE_SCHEMAS[name]); @@ -220,12 +220,18 @@ describe('seed reference graph — engine schema fallback (marketplace objects)' expect(result.success).toBe(true); const acmeId = store.crm_account.find((r) => r.name === 'Acme Corporation')!.id; expect(store.crm_contact.find((r) => r.email === 'john.smith@acme.example.com')!.crm_account).toBe(acmeId); - // No engine probe for any SEEDED object. (The only engine question asked is - // the ADR-0131 D9 registration read for `sys_organization`, which this + // The engine here registers no schema at all (`createFaithfulEngine({})`), + // so the references above resolved from the metadata service's definition. + // The engine is still asked once per seeded object, for the roll-up strip + // alone (#35655): the metadata copy carries no object extension, so the + // strip also reads the engine's merged schema. (The other engine question + // is the ADR-0131 D9 registration read for `sys_organization`, which this // metadata double does not know: does the composition register an // organization object at all? It answers from the same resolver.) const probed = (engine as any).getSchema.mock.calls.map((c: unknown[]) => c[0]); - expect(probed.filter((name: string) => name !== 'sys_organization')).toEqual([]); + expect(probed.filter((name: string) => name !== 'sys_organization').sort()).toEqual( + ['crm_account', 'crm_contact', 'crm_opportunity'], + ); }); it('survives an engine without getSchema (contract-minimal engines keep the old behavior)', async () => { From e6b5e1af11b02b43ab3cb05f98d1016480b8ba91 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:32:23 +0000 Subject: [PATCH 9/9] test(metadata-protocol): the extension roll-up pin lives in the file's existing harness Moved from a new file into seed-loader-summary-stale.test.ts as a top-level describe on that file's already-pinned engine double (with getSchema overridden), so the engine-double ledger needs no new entry. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh --- ...eed-loader-summary-extension-35655.test.ts | 162 ------------------ .../src/seed-loader-summary-stale.test.ts | 77 +++++++++ 2 files changed, 77 insertions(+), 162 deletions(-) delete mode 100644 packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts diff --git a/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts b/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts deleted file mode 100644 index 39e71ec515e..00000000000 --- a/packages/metadata-protocol/src/seed-loader-summary-extension-35655.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -import { describe, it, expect, vi } from 'vitest'; -import { SeedLoaderService } from './seed-loader.js'; -import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; -import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; - -/** - * [#35655] A seed never stores a roll-up (maintainer ruling D, record - * 7063117450), and that includes a roll-up an object EXTENSION contributes. - * - * The loader resolves a definition from the metadata service first and uses - * that copy whenever it has `fields`, without consulting the engine. The - * metadata service stores the object as registered, with no extension merged - * in, so its copy can lack a roll-up the engine's merged schema declares and - * computes. The strip therefore reads both: the resolved definition and the - * engine's own schema. These pins hand the loader a metadata copy WITHOUT the - * extension's roll-up and an engine schema WITH it. - */ - -function createLogger() { - return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; -} - -/** The object as the metadata service stores it: no extension merged in. */ -const METADATA_COPY = { - name: 'ext_invoice', - fields: { - name: { type: 'text' }, - total: { type: 'number' }, - paid: { type: 'summary', summaryOperations: { object: 'ext_payment', field: 'amount', function: 'sum' } }, - }, -}; - -/** The engine's merged schema: the same object plus an extension's roll-up. */ -const ENGINE_SCHEMA = { - ...METADATA_COPY, - fields: { - ...METADATA_COPY.fields, - ext_refunds: { type: 'summary', summaryOperations: { object: 'ext_refund', field: 'amount', function: 'count' } }, - }, -}; - -function createEngine(getSchema: (name: string) => unknown): IDataEngine { - const store: Record = {}; - let idCounter = 0; - const engine = { - getSchema: vi.fn(getSchema), - find: vi.fn(async (objectName: string, query?: any) => { - let records = store[objectName] || []; - if (query?.where) { - records = records.filter((r) => - Object.entries(query.where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), - ); - } - if (typeof query?.limit === 'number') records = records.slice(0, query.limit); - return records; - }), - findOne: vi.fn(async (objectName: string, query?: any) => { - assertEngineFindOnePredicate(objectName, query); - const rows = await (engine.find as any)(objectName, { ...query, limit: 1 }); - return rows[0] ?? null; - }), - insert: vi.fn(async (objectName: string, data: any) => { - if (!store[objectName]) store[objectName] = []; - const rows = (Array.isArray(data) ? data : [data]).map((d) => ({ id: `gen-${++idCounter}`, ...d })); - store[objectName].push(...rows); - return Array.isArray(data) ? rows : rows[0]; - }), - update: vi.fn(async (objectName: string, data: any) => { - assertEngineUpdateDispatch(data, undefined); - const records = store[objectName] || []; - const idx = records.findIndex((r) => r.id === data.id); - if (idx >= 0) { records[idx] = { ...records[idx], ...data }; return records[idx]; } - return data; - }), - delete: vi.fn(async (_objectName: string, options?: any) => { - assertEngineDeleteDispatch(options); - return { deleted: 1 }; - }), - count: vi.fn(async (objectName: string) => (store[objectName] || []).length), - aggregate: vi.fn(async () => []), - } as unknown as IDataEngine; - return engine; -} - -function metadataWith(copy: unknown): IMetadataService { - return { - getObject: vi.fn(async (name: string) => (name === 'ext_invoice' ? copy : undefined)), - listObjects: vi.fn(async () => [copy]), - register: vi.fn(async () => {}), - get: vi.fn(async (_t: string, name: string) => (name === 'ext_invoice' ? copy : undefined)), - list: vi.fn(async () => []), - unregister: vi.fn(async () => {}), - exists: vi.fn(async () => false), - listNames: vi.fn(async () => []), - } as unknown as IMetadataService; -} - -const CONFIG = { - dryRun: false, - haltOnError: false, - multiPass: true, - defaultMode: 'ignore', - batchSize: 1000, - transaction: false, -} as any; - -const SEED = { - object: 'ext_invoice', - externalId: 'name', - mode: 'ignore', - env: ['prod', 'dev', 'test'], - records: [{ name: 'INV-1', total: 10, paid: 3000, ext_refunds: 7 }], -}; - -const insertedKeys = (engine: IDataEngine) => - (engine.insert as any).mock.calls - .filter(([object]: [string]) => object === 'ext_invoice') - .flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row))); -const dropNotices = (logger: ReturnType) => - (logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary')); - -describe('a roll-up an object extension contributes is never seeded either (#35655)', () => { - it('the metadata copy lacks the extension roll-up, the engine schema has it: neither roll-up reaches the engine, and the notice names both', async () => { - const engine = createEngine((name) => (name === 'ext_invoice' ? ENGINE_SCHEMA : undefined)); - const logger = createLogger(); - - const result = await new SeedLoaderService(engine, metadataWith(METADATA_COPY), logger).load({ - seeds: [SEED] as any, - config: CONFIG, - }); - - const keys = insertedKeys(engine); - expect(keys).toHaveLength(1); - expect(keys[0]).toContain('total'); - expect(keys[0]).not.toContain('paid'); - expect(keys[0]).not.toContain('ext_refunds'); - expect(result.results[0]).toMatchObject({ inserted: 1, errored: 0 }); - expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ - { object: 'ext_invoice', fields: ['paid', 'ext_refunds'], droppedValues: 2 }, - ]); - }); - - it('CONTROL: an engine whose schema read throws leaves the metadata copy the only source, and its roll-up is still dropped', async () => { - const engine = createEngine(() => { throw new Error('no schema registry'); }); - const logger = createLogger(); - - await new SeedLoaderService(engine, metadataWith(METADATA_COPY), logger).load({ - seeds: [SEED] as any, - config: CONFIG, - }); - - const keys = insertedKeys(engine); - expect(keys[0]).not.toContain('paid'); - // Nothing declares `ext_refunds` a roll-up here, so it is written as authored. - expect(keys[0]).toContain('ext_refunds'); - expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([ - { object: 'ext_invoice', fields: ['paid'], droppedValues: 1 }, - ]); - }); -}); diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index f13d36d761e..9a6ce12598d 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -452,3 +452,80 @@ describe('a seed never hands the engine a roll-up value (#35655)', () => { expect(dropNotices(logger)).toEqual([]); }); }); + +/** + * [#35655] A roll-up an object EXTENSION contributes is never seeded either. + * The loader resolves a definition from the metadata service first and uses + * that copy whenever it has `fields`; the metadata service stores the object + * as registered, with no extension merged in, so its copy can lack a roll-up + * the engine's merged schema declares and computes. The strip therefore reads + * both the resolved definition and the engine's own schema. These pins hand + * the loader a metadata copy WITHOUT the extension's roll-up and an engine + * schema WITH it. + */ +describe('a roll-up an object extension contributes is never seeded either (#35655)', () => { + const METADATA_COPY = { + name: 'ext_invoice', + fields: { + name: { type: 'text' }, + total: { type: 'number' }, + paid: { type: 'summary', summaryOperations: { object: 'ext_payment', field: 'amount', function: 'sum' } }, + }, + }; + const ENGINE_SCHEMA = { + ...METADATA_COPY, + fields: { + ...METADATA_COPY.fields, + ext_refunds: { type: 'summary', summaryOperations: { object: 'ext_refund', field: 'amount', function: 'count' } }, + }, + }; + const metadataCopy = (): IMetadataService => ({ + getObject: vi.fn(async (name: string) => (name === 'ext_invoice' ? METADATA_COPY : undefined)), + listObjects: vi.fn(async () => [METADATA_COPY]), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => (name === 'ext_invoice' ? METADATA_COPY : undefined)), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + }) as unknown as IMetadataService; + const SEED = seedFor('ext_invoice', [{ name: 'INV-1', total: 10, paid: 3000, ext_refunds: 7 }]); + const insertedKeys = (engine: IDataEngine) => + (engine.insert as any).mock.calls + .filter(([object]: [string]) => object === 'ext_invoice') + .flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row))); + const dropMetas = (logger: ReturnType) => + (logger.warn as any).mock.calls + .filter(([m]: [string]) => m.includes('roll-up summary')) + .map(([, meta]: [string, any]) => meta); + + it('the metadata copy lacks the extension roll-up, the engine schema has it: neither roll-up reaches the engine, and the notice names both', async () => { + const { engine } = createFaithfulEngine(); + (engine as any).getSchema = vi.fn((name: string) => (name === 'ext_invoice' ? ENGINE_SCHEMA : undefined)); + const logger = createLogger(); + + const result = await new SeedLoaderService(engine, metadataCopy(), logger).load({ seeds: [SEED] as any, config: CONFIG }); + + const keys = insertedKeys(engine); + expect(keys).toHaveLength(1); + expect(keys[0]).toContain('total'); + expect(keys[0]).not.toContain('paid'); + expect(keys[0]).not.toContain('ext_refunds'); + expect(result.results[0]).toMatchObject({ inserted: 1, errored: 0 }); + expect(dropMetas(logger)).toEqual([{ object: 'ext_invoice', fields: ['paid', 'ext_refunds'], droppedValues: 2 }]); + }); + + it('CONTROL: an engine whose schema read throws leaves the metadata copy the only source, and its roll-up is still dropped', async () => { + const { engine } = createFaithfulEngine(); + (engine as any).getSchema = vi.fn(() => { throw new Error('no schema registry'); }); + const logger = createLogger(); + + await new SeedLoaderService(engine, metadataCopy(), logger).load({ seeds: [SEED] as any, config: CONFIG }); + + const keys = insertedKeys(engine); + expect(keys[0]).not.toContain('paid'); + // Nothing declares `ext_refunds` a roll-up here, so it is written as authored. + expect(keys[0]).toContain('ext_refunds'); + expect(dropMetas(logger)).toEqual([{ object: 'ext_invoice', fields: ['paid'], droppedValues: 1 }]); + }); +});