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..d185cb0c063 --- /dev/null +++ b/.changeset/35655-seed-summary-value-not-stored.md @@ -0,0 +1,21 @@ +--- +'@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 says what it dropped + +Clause-②: no (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: 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. 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 34e6bc16921..7e7509c9e49 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -409,10 +409,21 @@ 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 logs one +warning per dataset that names the object, the fields and how many values it +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 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/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-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 () => { 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..9a6ce12598d 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,224 @@ 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, 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)', () => { + 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))); + /** 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 one notice names the object, fields and count', 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]); + // 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); + // 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'], 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, 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(), logger).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 }); + 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 () => { + 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 }); + }); + + it('a dry run (validate) gives the same notice and writes nothing', async () => { + const { engine } = createFaithfulEngine(); + const logger = createLogger(); + + 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(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 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' } } } }; + + 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(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 }]); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index b1a215ad8db..7ace59dffee 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 says so in one `warn` per dataset. + * + * 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 @@ -1652,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; } /** @@ -2101,6 +2134,19 @@ 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. 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 // 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 +2282,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) { + summaryValuesDropped++; + summaryFieldsDropped.add(field); + } + delete record[field]; + } // [#22301] The stored form, not a `Date`, before any hook can see it. seedValuesInStoredForm(record, objectDefinition); /** @@ -3186,6 +3246,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. 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, and the rest of every record landed. + if (summaryValuesDropped > 0) { + const fields = [...summaryFieldsDropped]; + this.logger.warn( + `[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.`, + { object: objectName, fields, droppedValues: summaryValuesDropped }, + ); + } + if (this.loadProgress) this.loadProgress.loading = undefined; return { object: objectName, 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/seed-summary-never-stored.test.ts b/packages/objectql/src/seed-summary-never-stored.test.ts new file mode 100644 index 00000000000..9a4a01f9d8a --- /dev/null +++ b/packages/objectql/src/seed-summary-never-stored.test.ts @@ -0,0 +1,248 @@ +// 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; 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 + * `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 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. + */ + +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) { + 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 }; + 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')); + /** 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 }])]); + + 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 }); + // One line for the dataset, naming the object, every field and the count. + 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 }); + // 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 }); + 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)]); + + warns = []; + await load([P([{ name: 'A', ...SUPPLIED }], 'update')]); + + expect(inv('A')).toMatchObject({ line_total: 42, line_count: 2, line_max: 32 }); + expect(dropMetas()).toEqual([ALL]); + }); + + 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 }); + + 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 }); + // 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 () => { + 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'); + + await load([P([{ name: 'A', ext_total: 7 }])]); + + expect(inv('A')).toMatchObject({ ext_total: 0 }); + 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.success).toBe(true); + expect(dropWarns()).toEqual([]); + }); +}); 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/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/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 new file mode 100644 index 00000000000..7e0058c83d2 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts @@ -0,0 +1,43 @@ +// 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 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. 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 ' + + 'first boot and after a restart.', +};