Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/35655-seed-summary-value-not-stored.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: registered seed-summary-value-not-stored -->

**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.
19 changes: 15 additions & 4 deletions content/docs/data-modeling/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions content/docs/protocol/objectql/security.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand All @@ -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 () => {
Expand Down
221 changes: 221 additions & 0 deletions packages/metadata-protocol/src/seed-loader-summary-stale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> = {
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<string, any> = 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<typeof createLogger>) =>
(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<typeof createLogger>) =>
(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 }]);
});
});
Loading
Loading