Skip to content

Commit eb7ad70

Browse files
fix(metadata-protocol)!: a seed never stores a roll-up (summary) value; the children compute it, and the load says what it dropped (#36118)
Fixes #35655 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #36122 ## 维护者速读 - 用户能看到什么变化:应用作者在演示数据或安装包自带的数据里给父记录写的汇总数(如发票的「已收金额」)不再被存下,汇总数一律由明细算出;只写了汇总数、没带明细的父记录现在显示 0,启动日志会点名是哪个对象、哪些字段、丢了几个值。 - 为什么做:按你选的 D「一律不存汇总数」;过去写进去的数时对时错,重启后还会把真实合计盖回去,明细也可能因为写的合计被应用自己的规则拒掉。 - 出错会怎样:受影响的只有在演示数据里写了汇总数的应用作者,他们会看到数字变成明细合计或 0,并在日志里看到提示;不改任何已存数据,撤回本次改动即恢复旧行为。 - 要你做什么:这次改动让演示数据和安装包里原来能存下的汇总数改为不存(收紧),按规则需要你本人批准后才能合并。 ## What changes A seed never stores a value a seed record supplies for a roll-up (`summary`) field, on insert or on update. This follows maintainer ruling D as analysed in 7062334196, with the seat's correction 7064615114. The roll-up is computed from the child rows. The drop is reported by one warn notice per dataset, which is the whole report: no load-result key is added. The change is in the loader only: `packages/objectql/src/engine.ts` is not touched. - `packages/metadata-protocol/src/seed-loader.ts` - Module helper `summaryFieldNames(definition)` returns every field a definition declares `type: 'summary'`, whatever its aggregate and whether or not it is `readonly`. It keys on `type === 'summary'` literally, as the engine's roll-up readers do. - In `loadDataset`, the roll-up fields are the union of `summaryFieldNames` over the resolved definition AND over the engine's merged schema (`engine.getSchema`, read through the new private `engineSchemaOf`, which `resolveObjectDefinition` now shares). The metadata service's copy wins `resolveObjectDefinition` whenever it has `fields`, and that copy carries no object extension, so a roll-up an extension contributes is read from the engine's schema (contract review S1b). An engine without a schema registry, or whose read throws, leaves the resolved definition the only source. - Each such key is deleted right after the record's expressions resolve, before anything else reads the record. So the no-op replay compare, the insert and the update all see the record without it. - A created row starts the column at its empty-child-list value (the engine's existing `initializeSummaryFields`), and the child inserts compute it, as before. - A matched row keeps the value it already holds. - One `warn` per dataset names the object, the fields and how many values were dropped (`{ object, fields, droppedValues }`). A supplied `null` counts as a value. A dry run (`validate`) logs the same notice. - `success` and `errored` do not move. 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. It used to be counted `updated`. - `packages/spec/src/migrations/entries/semantic/18.seed-summary-value-not-stored.ts`: the ADR-0087 semantic entry for the narrowing. No tombstone and no D2 conversion, because no key is added or removed and no rewrite is mechanical. It names the manual repair for a parent with no child rows that an earlier load stored a total on (review nit n3): insert a child row under it and delete that row again. - `.changeset/35655-seed-summary-value-not-stored.md`: `@objectstack/spec` and `@objectstack/metadata-protocol` at `minor`, with a BREAKING banner, `adr-0087: registered seed-summary-value-not-stored`, FROM → TO, the compatibility note for seed authors, and the same manual repair (n3). - `content/docs/data-modeling/fields.mdx`: the sentence "seed data, package installs and a historical import … keep a pre-computed total" is rewritten to the ruled behaviour. The historical import (`treatAsHistorical: true`) keeps its sentence, because it is a separate door. The degraded path is named (review S2): 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. Ruling D keeps the change loader-only. - `content/docs/protocol/objectql/security.mdx` (review S1a): Rule 1's sentence no longer says seed data and package installs write a roll-up from a system context. It names the roll-up's own recompute and a historical import, and says the seed loader takes a seed record's value out before the write. - Comment-only edits in objectql, to text this change made false: - the `summaryFieldsLockedOnWrite` docblock in `engine-top-level.ts`; - the `summary` note in `validation/rule-validator.ts`; - the header and one test name of `engine-summary-update-lock.test.ts`. They no longer say a seed load keeps a pre-computed total. The engine behaviour they describe (an `isSystem` write keeps its value) is unchanged, and so is the test's assertion. - Stale test comments (review nit n1): `packages/objectql/src/summary-rollup.test.ts` (the comment above, and the name of, the "system writer supplied on insert" case no longer list seed loads) and `packages/spec/src/data/field-autonumber-readonly.test.ts` (the `summary` note no longer says a caller may seed one). Assertions unchanged. - `packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts`: the "prefers the metadata service definition" pin asserted that the engine is never probed for a seeded object. The S1b union probes it once per seeded object, for the roll-up strip alone, so the pin now asserts exactly that probe list. Its claim stands: the engine double registers no schema, so the resolved references prove the metadata definition was used. Package installs go through the same loader: - `packages/runtime/src/domains/packages.ts` applies a package's seeds with `new SeedLoaderService(...)`; - so does `packages/metadata-protocol/src/protocol-publish-batch.ts`; - so do the single-tenant boot seed, the per-organization replay and the reseed paths in `packages/runtime/src/app-plugin.ts`. The only seed path outside the loader is the runtime's basic-insert fallback (see above and the Acceptance notes). No existing pin asserted that a seed load keeps a roll-up value. `engine-summary-update-lock.test.ts` "an isSystem create keeps its value" pins the engine's `isSystem` exemption, which this PR does not change. ## Tests Pins. Each asserts the stored rows or the engine's calls, plus the warn notice. None reads a count key. - `packages/objectql/src/seed-summary-never-stored.test.ts`, on the real ObjectQL engine and the real `SeedLoaderService`. The parent has a `sum`, a `count` and a `readonly` `max` roll-up, seeded with 999 / 99 / 500, over lines of 10 and 32. - Case 3: a parent alone stores 0 / 0 / empty, with one notice `{ object: 'ss_inv', fields: [line_total, line_count, line_max], droppedValues: 3 }`. - Case 1 (control): parent and children in one load store 42 / 2 / 32. - Case 4: a re-seed over existing children keeps 42 / 2 / 32 and is `skipped`, in `upsert` and in `update` mode. - Case 6: the same seed replayed stores 42 / 2 / 32 on both loads. - A roll-up an extension contributes (`registerObject(..., 'extend')`, engine-fallback rung) is dropped like the base object's own. - A seed with no roll-up value gives no notice. - `packages/metadata-protocol/src/seed-loader-summary-stale.test.ts`, on the file's existing engine double: - `a seed never hands the engine a roll-up value`: no `insert` or `update` payload carries a roll-up key; a supplied `null` counts; a roll-up-only difference writes nothing; another change is written without the roll-up; `validate` gives the notice and writes nothing; a `currency` CONTROL is written as authored with no notice. - New this round (S1b), `a roll-up an object extension contributes is never seeded either`: the metadata double's copy lacks the extension's roll-up and the engine double's `getSchema` has it. Neither roll-up reaches the engine, and the one notice reads `{ object: 'ext_invoice', fields: ['paid', 'ext_refunds'], droppedValues: 2 }`. CONTROL: an engine whose `getSchema` throws leaves the metadata copy the only source; its roll-up is still dropped, and `ext_refunds` (declared a roll-up nowhere) is written as authored. <details> <summary>Ablation of the S1b union (this round, head e6b5e1a)</summary> The metadata-protocol pins import `./seed-loader.js` from source, so no rebuild is involved. `node scripts/ablation-replace.mjs --file packages/metadata-protocol/src/seed-loader.ts --anchor ' ...summaryFieldNames(this.engineSchemaOf(objectName)),' --delete -- …`: - Mutation: anchor x1 → x0, blob 7ace59d → d6f9588ece80; on-disk count of the union line read 0 inside the wrapped command. - Run: `Tests 2 failed | 15 passed (17)`, VERDICT command-exit 1. Red: the extension pin (`expected [ 'name', 'total', 'ext_refunds' ] to not include 'ext_refunds'`) and the engine-schema-fallback probe pin (`expected [] to deeply equal [ 'crm_account', 'crm_contact', … ]`). The throwing-schema CONTROL stayed green. - Restore: blob after restore 7ace59d == HEAD blob 7ace59d, `git diff HEAD` empty, `git status --porcelain` empty. - Green at the head: `Tests 17 passed (17)`, VERDICT command-exit 0. Round 2's ablation of the strip loop itself (objectql 6 red / 1 green control, metadata-protocol 4 red / 8 green, restore proven) is recorded in dev report 7065542104. </details> <details> <summary>Suite readings (this round)</summary> - `@objectstack/metadata-protocol` typecheck: VERDICT command-exit 0 (at e6b5e1a). - `@objectstack/metadata-protocol` test at 9737321: `Test Files 1 failed | 362 passed | 9 skipped (372)`, `Tests 1 failed | 23311 passed | 45 skipped (23357)`. The one red was the engine-schema-fallback probe pin the S1b union made false; it is updated in c4dc426. At e6b5e1a the two changed files read `Test Files 2 passed (2)`, `Tests 17 passed (17)`; no source file changed after 9737321. - Edited test files in other packages: objectql `summary-rollup.test.ts` + `seed-summary-never-stored.test.ts` `Tests 133 passed (133)`; spec `field-autonumber-readonly.test.ts` `Tests 8 passed (8)`. </details> Dogfood battery at the final head `e6b5e1af11`: `pnpm --filter @objectstack/dogfood test` (no shard, no path) under the verify lock, on the closure built at 9737321 (`pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' --filter '@objectstack/metadata-protocol' build`, VERDICT command-exit 0). Every commit after 9737321 changes test files only, so that build is the head's source. - `Test Files 483 passed | 3 skipped (486)` - `Tests 4101 passed | 68 skipped (4169)` - `os-verify-lock: VERDICT command-exit 0 · held the lock 2099s` - No failures. Gates at the final head `e6b5e1af11`: `dispatch-gates.mjs --commands` derives 123 families; the list is identical at c4dc426. <details> <summary>Gate readings</summary> - All 123 run locally at e6b5e1a, each exit captured before any pipe: 123 exit 0. - `--ran` reconciliation: "123 derived, 123 run, 0 NOT-MEASURED, 0 UNRUN", exit 0. - `check-adr-0087-registration`: `[BREAKING+bang+clause-②-narrowing+metadata-protocol-narrowed] registered seed-summary-value-not-stored`. - At c4dc426, `check:engine-double-contract` exited 1 on the extension pin's new engine double in a new file (ledger RETAINED rows). The pin moved into `seed-loader-summary-stale.test.ts` on that file's already-pinned double (e6b5e1a), and the gate exits 0. `check:skill-examples` and `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, no local `dist/` for packages outside this diff); after building those packages both exit 0. - Local-only `check:dev-prereqs` exit 1: 35 of 108 workspace packages unbuilt in this container (mostly `ui/`), not this diff. - `overlap-check` before each of the three pushes this round: VERDICT clean, exit 0. No `origin/main` merge this round (no conflict, CI green). - CI at e6b5e1a: 70 check-runs, 60 success and 10 skipped, 0 failure. `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core` (all 10 shards), `Build Core`, `Governed Surface Queue Guard`, `Type Check UI`, `Test UI`, `Build & E2E UI`, `Live E2E UI`, `Dogfood Regression Gate` and `Check Changeset` read success; `Lint UI` and the sharded dogfood matrix read skipped. </details> ## Acceptance notes - The runtime's basic-insert fallback seeder (`packages/runtime/src/app-plugin.ts`, the two `ql.insert` loops under "basic insert fallback") writes seed records with a plain `ql.insert`. It runs only when no metadata service is present (logged at debug) or the loader throws (logged at warn). Ruling D routes the change through the loader only, so on that path a roll-up value still reaches the engine. `fields.mdx` and the changeset now both say so. - The loader does not rewrite rows that an earlier load stored a supplied total on. The next child write recomputes them; a parent with no child rows gets none, and `os migrate summary-nulls` backfills only `NULL` columns, so the changeset and the migration entry name the manual repair. - A dataset keyed on a summary field (an `externalId` naming a roll-up) would now see that key blank, and the record would be refused as a blank-key record. No such seed exists in the tree, and a roll-up is not a natural key. - The drop is counted before the record's fate is known: a record later refused or skipped as create-only still counts in the notice (review nit n2, not taken). - The published data skill (`skills/objectstack-data/references/seeds.md:146-147`) gives the right instruction ("Never seed the roll-up"), but its reason ("stored as written") is now out of date. Follow-up #36122. ## Verification Read first, in order of risk: 1. `packages/metadata-protocol/src/seed-loader.ts`: the `summaryFields` union in `loadDataset` and the strip loop right after `const record = { ...(seedResult.value ...) }`. The strip must run before every read of the record. 2. `packages/objectql/src/seed-summary-never-stored.test.ts`: cases 3, 4 and 6. 3. `.changeset/35655-seed-summary-value-not-stored.md`: the FROM → TO, the row-counter sentence, the compatibility note and the manual repair. Two-minute check: `pnpm --filter @objectstack/metadata-protocol exec vitest run --maxWorkers=2 src/seed-loader-summary-stale.test.ts`. Expect `Tests 14 passed (14)`; the extension case's notice names `paid` and `ext_refunds`. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh)_ <!-- signed: repo:objectstack#4 · os-project-manager · session_01FEkQ5krBqrrgxCYgjXmfbv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cbd582f commit eb7ad70

13 files changed

Lines changed: 668 additions & 31 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/metadata-protocol': minor
4+
---
5+
6+
fix(metadata-protocol)!: a seed never stores a roll-up (summary) value; the children compute it, and the load says what it dropped
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
11+
<!-- adr-0087: registered seed-summary-value-not-stored -->
12+
13+
**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`.
14+
15+
- 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.
16+
- 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`.
17+
- 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`.
18+
19+
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.
20+
21+
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.

‎content/docs/data-modeling/fields.mdx‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -409,10 +409,21 @@ person who submitted it is not shown the drop. A record created with its value
409409
dropped starts as if no value had been sent: `0`
410410
for `count` and `sum`, empty for `min`, `max` and `avg`, and the next child write
411411
replaces it with the computed value. Under `strictReadonlyWrites` the whole write
412-
is refused. Server code that runs with `isSystem: true` can still write the
413-
column, as it can any read-only column: seed data, package installs and a
414-
historical import (`treatAsHistorical: true`, which only the system principal may
415-
send) keep a pre-computed total, on create and on update. Undoing an ordinary
412+
is refused. Seed data never stores a summary value, and that includes the seed
413+
data a package install loads, since it goes through the same seed loader: a value a
414+
seed record supplies for a summary field is not written, on create or on
415+
update, and the rest of the record is. The summary is computed from the seeded
416+
child records, so a parent seeded with a total and no children shows the
417+
empty-set value (`0` for `count` and `sum`, empty for `min`, `max` and `avg`),
418+
and re-seeding a parent leaves its computed value in place. The load logs one
419+
warning per dataset that names the object, the fields and how many values it
420+
did not write. One degraded path does not go through the seed loader: when the
421+
runtime has no metadata service, or the seed loader throws, it falls back to a
422+
basic insert of the seed records, and that fallback still stores a supplied
423+
summary value. To show a total, seed the child records it sums. Server code that runs with `isSystem: true` can still write the column,
424+
as it can any read-only column: a historical import (`treatAsHistorical: true`,
425+
which only the system principal may send) keeps a pre-computed total, on create
426+
and on update. Undoing an ordinary
416427
import restores the rows through an ordinary update, so a summary value that an
417428
import committed before this rule overwrote is not put back by the undo; it stays
418429
until the next child write recomputes it.

‎content/docs/protocol/objectql/security.mdx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,8 +286,10 @@ starts the column as for an empty child list. That covers a flow's `create_recor
286286
`os build` report such a step as the `flow-update-summary-field` warning, which never blocks a
287287
build, though like every warning it makes `os validate --strict` and `os lint --strict` exit 1
288288
(a roll-up declared `readonly: true` is the `flow-update-readonly-field` error). Rule 1 below
289-
holds for it: seed data, package installs and the roll-up's own recompute write it from a
290-
system context. See [Calculation types](/docs/data-modeling/fields#calculation-types).
289+
holds for it: the roll-up's own recompute and a historical import (`treatAsHistorical: true`)
290+
write it from a system context. Seed data, including the seed data a package install loads,
291+
does not: the seed loader takes a seed record's value for a roll-up out before the write, and the
292+
child records compute it. See [Calculation types](/docs/data-modeling/fields#calculation-types).
291293

292294
Five rules decide whether a given value survives:
293295

‎packages/metadata-protocol/src/seed-loader-engine-schema-fallback.test.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ describe('seed reference graph — engine schema fallback (marketplace objects)'
207207
expect(result.summary.totalReferencesResolved).toBeGreaterThanOrEqual(4);
208208
});
209209

210-
it('prefers the metadata service definition when it exists (no engine probe)', async () => {
210+
it('prefers the metadata service definition when it exists (the engine is probed only for roll-ups)', async () => {
211211
const { engine, store } = createFaithfulEngine({});
212212
const metadata = createEmptyMetadata();
213213
(metadata.getObject as any).mockImplementation(async (name: string) => ENGINE_SCHEMAS[name]);
@@ -220,12 +220,18 @@ describe('seed reference graph — engine schema fallback (marketplace objects)'
220220
expect(result.success).toBe(true);
221221
const acmeId = store.crm_account.find((r) => r.name === 'Acme Corporation')!.id;
222222
expect(store.crm_contact.find((r) => r.email === 'john.smith@acme.example.com')!.crm_account).toBe(acmeId);
223-
// No engine probe for any SEEDED object. (The only engine question asked is
224-
// the ADR-0131 D9 registration read for `sys_organization`, which this
223+
// The engine here registers no schema at all (`createFaithfulEngine({})`),
224+
// so the references above resolved from the metadata service's definition.
225+
// The engine is still asked once per seeded object, for the roll-up strip
226+
// alone (#35655): the metadata copy carries no object extension, so the
227+
// strip also reads the engine's merged schema. (The other engine question
228+
// is the ADR-0131 D9 registration read for `sys_organization`, which this
225229
// metadata double does not know: does the composition register an
226230
// organization object at all? It answers from the same resolver.)
227231
const probed = (engine as any).getSchema.mock.calls.map((c: unknown[]) => c[0]);
228-
expect(probed.filter((name: string) => name !== 'sys_organization')).toEqual([]);
232+
expect(probed.filter((name: string) => name !== 'sys_organization').sort()).toEqual(
233+
['crm_account', 'crm_contact', 'crm_opportunity'],
234+
);
229235
});
230236

231237
it('survives an engine without getSchema (contract-minimal engines keep the old behavior)', async () => {

‎packages/metadata-protocol/src/seed-loader-summary-stale.test.ts‎

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,3 +308,224 @@ describe('the counter survives the contract, and the contract survives older pay
308308
expect(SeedLoaderResultSchema.parse(legacyResult).summary.totalSummariesStale).toBe(0);
309309
});
310310
});
311+
312+
/**
313+
* [#35655] The other half of a seed and a roll-up: a seed never stores a
314+
* value it supplies for a `summary` field (maintainer ruling D, as analysed in
315+
* 7062334196; the seat's correction 7064615114). The loader takes it out of
316+
* the record before the write, and the engine computes the column from the
317+
* child rows. The drop is reported by one `warn` per dataset naming the
318+
* object, the fields and the count: that notice is the report, and no
319+
* load-result key carries it. These pins read the engine's CALLS and the
320+
* notice, so they hold whatever the engine would do with the key; the stored
321+
* outcome on the real engine is pinned in
322+
* `packages/objectql/src/seed-summary-never-stored.test.ts`.
323+
*/
324+
describe('a seed never hands the engine a roll-up value (#35655)', () => {
325+
const ROLLUP_OBJECTS: Record<string, any> = {
326+
drop_invoice: {
327+
name: 'drop_invoice',
328+
fields: {
329+
name: { type: 'text' },
330+
total: { type: 'number' },
331+
paid: { type: 'summary', summaryOperations: { object: 'drop_payment', field: 'amount', function: 'sum' } },
332+
payments: { type: 'summary', readonly: true, summaryOperations: { object: 'drop_payment', field: 'amount', function: 'count' } },
333+
},
334+
},
335+
};
336+
function rollUpMetadata(objects: Record<string, any> = ROLLUP_OBJECTS): IMetadataService {
337+
return {
338+
getObject: vi.fn(async (name: string) => objects[name]),
339+
listObjects: vi.fn(async () => Object.values(objects)),
340+
register: vi.fn(async () => {}),
341+
get: vi.fn(async (_t: string, name: string) => objects[name]),
342+
list: vi.fn(async () => []),
343+
unregister: vi.fn(async () => {}),
344+
exists: vi.fn(async () => false),
345+
listNames: vi.fn(async () => []),
346+
} as unknown as IMetadataService;
347+
}
348+
const writtenKeys = (engine: IDataEngine, verb: 'insert' | 'update') =>
349+
(engine[verb] as any).mock.calls
350+
.filter(([object]: [string]) => object === 'drop_invoice')
351+
.flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row)));
352+
/** The roll-up drop notices the load logged: `[message, meta]` per `warn`. */
353+
const dropNotices = (logger: ReturnType<typeof createLogger>) =>
354+
(logger.warn as any).mock.calls.filter(([m]: [string]) => m.includes('roll-up summary'));
355+
356+
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 () => {
357+
const { engine, store } = createFaithfulEngine();
358+
const logger = createLogger();
359+
360+
const result = await new SeedLoaderService(engine, rollUpMetadata(), logger).load({
361+
seeds: [seedFor('drop_invoice', [
362+
{ name: 'INV-1', total: 10, paid: 3000, payments: 4 },
363+
{ name: 'INV-2', total: 20, paid: null },
364+
{ name: 'INV-3', total: 30 },
365+
])] as any,
366+
config: CONFIG,
367+
});
368+
369+
for (const keys of writtenKeys(engine, 'insert')) {
370+
expect(keys).not.toContain('paid');
371+
expect(keys).not.toContain('payments');
372+
}
373+
expect(store.drop_invoice.map((r) => r.total)).toEqual([10, 20, 30]);
374+
// The rest of each record landed: nothing about the drop is an error.
375+
expect(result.results[0]).toMatchObject({ inserted: 3, errored: 0 });
376+
expect(result.success).toBe(true);
377+
// A supplied `null` is a supplied value too: three values, two fields, ONE notice.
378+
const drops = dropNotices(logger);
379+
expect(drops).toHaveLength(1);
380+
expect(drops[0][1]).toEqual({ object: 'drop_invoice', fields: ['paid', 'payments'], droppedValues: 3 });
381+
expect(drops[0][0]).toContain('drop_invoice');
382+
expect(drops[0][0]).toContain('`paid`, `payments`');
383+
// The notice is the whole report: the load result carries no key for it.
384+
expect(Object.keys(result.results[0])).not.toContain('summariesDropped');
385+
});
386+
387+
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 () => {
388+
const { engine, store } = createFaithfulEngine();
389+
const logger = createLogger();
390+
store.drop_invoice = [{ id: 'inv-1', name: 'INV-1', total: 10, paid: 42, payments: 2 }];
391+
392+
const result = await new SeedLoaderService(engine, rollUpMetadata(), logger).load({
393+
seeds: [{ ...seedFor('drop_invoice', [
394+
{ name: 'INV-1', total: 10, paid: 999, payments: 99 },
395+
]), mode: 'upsert' }] as any,
396+
config: CONFIG,
397+
});
398+
399+
expect(writtenKeys(engine, 'update')).toEqual([]);
400+
expect(store.drop_invoice[0]).toMatchObject({ paid: 42, payments: 2 });
401+
expect(result.results[0]).toMatchObject({ updated: 0, skipped: 1 });
402+
expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([
403+
{ object: 'drop_invoice', fields: ['paid', 'payments'], droppedValues: 2 },
404+
]);
405+
});
406+
407+
it('on a matched row whose other columns changed: the update writes them and still no roll-up', async () => {
408+
const { engine, store } = createFaithfulEngine();
409+
store.drop_invoice = [{ id: 'inv-1', name: 'INV-1', total: 10, paid: 42, payments: 2 }];
410+
411+
const result = await new SeedLoaderService(engine, rollUpMetadata(), createLogger()).load({
412+
seeds: [{ ...seedFor('drop_invoice', [
413+
{ name: 'INV-1', total: 11, paid: 999, payments: 99 },
414+
]), mode: 'upsert' }] as any,
415+
config: CONFIG,
416+
});
417+
418+
const keys = writtenKeys(engine, 'update');
419+
expect(keys).toHaveLength(1);
420+
expect(keys[0]).toContain('total');
421+
expect(keys[0]).not.toContain('paid');
422+
expect(keys[0]).not.toContain('payments');
423+
expect(store.drop_invoice[0]).toMatchObject({ total: 11, paid: 42, payments: 2 });
424+
expect(result.results[0]).toMatchObject({ updated: 1 });
425+
});
426+
427+
it('a dry run (validate) gives the same notice and writes nothing', async () => {
428+
const { engine } = createFaithfulEngine();
429+
const logger = createLogger();
430+
431+
await new SeedLoaderService(engine, rollUpMetadata(), logger).validate(
432+
[seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any,
433+
);
434+
435+
expect(writtenKeys(engine, 'insert')).toEqual([]);
436+
expect(dropNotices(logger).map(([, meta]: [string, any]) => meta)).toEqual([
437+
{ object: 'drop_invoice', fields: ['paid'], droppedValues: 1 },
438+
]);
439+
});
440+
441+
it('CONTROL: a field the definition does not type `summary` is written as authored, and no notice is logged', async () => {
442+
const { engine } = createFaithfulEngine();
443+
const logger = createLogger();
444+
const plain = { drop_invoice: { name: 'drop_invoice', fields: { name: { type: 'text' }, total: { type: 'number' }, paid: { type: 'currency' } } } };
445+
446+
await new SeedLoaderService(engine, rollUpMetadata(plain), logger).load({
447+
seeds: [seedFor('drop_invoice', [{ name: 'INV-1', total: 10, paid: 3000 }])] as any,
448+
config: CONFIG,
449+
});
450+
451+
expect(writtenKeys(engine, 'insert')[0]).toContain('paid');
452+
expect(dropNotices(logger)).toEqual([]);
453+
});
454+
});
455+
456+
/**
457+
* [#35655] A roll-up an object EXTENSION contributes is never seeded either.
458+
* The loader resolves a definition from the metadata service first and uses
459+
* that copy whenever it has `fields`; the metadata service stores the object
460+
* as registered, with no extension merged in, so its copy can lack a roll-up
461+
* the engine's merged schema declares and computes. The strip therefore reads
462+
* both the resolved definition and the engine's own schema. These pins hand
463+
* the loader a metadata copy WITHOUT the extension's roll-up and an engine
464+
* schema WITH it.
465+
*/
466+
describe('a roll-up an object extension contributes is never seeded either (#35655)', () => {
467+
const METADATA_COPY = {
468+
name: 'ext_invoice',
469+
fields: {
470+
name: { type: 'text' },
471+
total: { type: 'number' },
472+
paid: { type: 'summary', summaryOperations: { object: 'ext_payment', field: 'amount', function: 'sum' } },
473+
},
474+
};
475+
const ENGINE_SCHEMA = {
476+
...METADATA_COPY,
477+
fields: {
478+
...METADATA_COPY.fields,
479+
ext_refunds: { type: 'summary', summaryOperations: { object: 'ext_refund', field: 'amount', function: 'count' } },
480+
},
481+
};
482+
const metadataCopy = (): IMetadataService => ({
483+
getObject: vi.fn(async (name: string) => (name === 'ext_invoice' ? METADATA_COPY : undefined)),
484+
listObjects: vi.fn(async () => [METADATA_COPY]),
485+
register: vi.fn(async () => {}),
486+
get: vi.fn(async (_t: string, name: string) => (name === 'ext_invoice' ? METADATA_COPY : undefined)),
487+
list: vi.fn(async () => []),
488+
unregister: vi.fn(async () => {}),
489+
exists: vi.fn(async () => false),
490+
listNames: vi.fn(async () => []),
491+
}) as unknown as IMetadataService;
492+
const SEED = seedFor('ext_invoice', [{ name: 'INV-1', total: 10, paid: 3000, ext_refunds: 7 }]);
493+
const insertedKeys = (engine: IDataEngine) =>
494+
(engine.insert as any).mock.calls
495+
.filter(([object]: [string]) => object === 'ext_invoice')
496+
.flatMap(([, data]: [string, any]) => (Array.isArray(data) ? data : [data]).map((row: any) => Object.keys(row)));
497+
const dropMetas = (logger: ReturnType<typeof createLogger>) =>
498+
(logger.warn as any).mock.calls
499+
.filter(([m]: [string]) => m.includes('roll-up summary'))
500+
.map(([, meta]: [string, any]) => meta);
501+
502+
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 () => {
503+
const { engine } = createFaithfulEngine();
504+
(engine as any).getSchema = vi.fn((name: string) => (name === 'ext_invoice' ? ENGINE_SCHEMA : undefined));
505+
const logger = createLogger();
506+
507+
const result = await new SeedLoaderService(engine, metadataCopy(), logger).load({ seeds: [SEED] as any, config: CONFIG });
508+
509+
const keys = insertedKeys(engine);
510+
expect(keys).toHaveLength(1);
511+
expect(keys[0]).toContain('total');
512+
expect(keys[0]).not.toContain('paid');
513+
expect(keys[0]).not.toContain('ext_refunds');
514+
expect(result.results[0]).toMatchObject({ inserted: 1, errored: 0 });
515+
expect(dropMetas(logger)).toEqual([{ object: 'ext_invoice', fields: ['paid', 'ext_refunds'], droppedValues: 2 }]);
516+
});
517+
518+
it('CONTROL: an engine whose schema read throws leaves the metadata copy the only source, and its roll-up is still dropped', async () => {
519+
const { engine } = createFaithfulEngine();
520+
(engine as any).getSchema = vi.fn(() => { throw new Error('no schema registry'); });
521+
const logger = createLogger();
522+
523+
await new SeedLoaderService(engine, metadataCopy(), logger).load({ seeds: [SEED] as any, config: CONFIG });
524+
525+
const keys = insertedKeys(engine);
526+
expect(keys[0]).not.toContain('paid');
527+
// Nothing declares `ext_refunds` a roll-up here, so it is written as authored.
528+
expect(keys[0]).toContain('ext_refunds');
529+
expect(dropMetas(logger)).toEqual([{ object: 'ext_invoice', fields: ['paid'], droppedValues: 1 }]);
530+
});
531+
});

0 commit comments

Comments
 (0)