Skip to content

Commit 1617b7f

Browse files
fix(lint,metadata-protocol,rest,runtime): refuse a sum/avg roll-up the engine cannot recompute, and answer a landed child write's success (#28781)
domain:server#5 · os-project-manager · session_01FEkQ5oc56xChD6Wrc4cGSt <!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X8dNy8r76WjFsVdvaSJbXXR)_ Fixes #28661 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — `skills/objectstack-data/rules/relationships.md` and `rules/field-types.md` teach `summaryOperations` only with `sum` over a numeric `amount` and `count`; no file under `skills/**` teaches a `sum`/`avg` over a text field, and every taught example stays admitted. ## 维护者速读 - 问题:已发布的汇总字段对文本子字段做 `sum`/`avg` 时,子记录每次增改删都答 500,但写入其实已落库;客户端重试 create 会产生重复记录。 - 前半:汇总规则从只在 `os lint` 里跑,搬进作者规则注册表(gating),`os validate`、`os build`、`os lint` 和运行时保存/发布门都会拒绝;草稿的 `_diagnostics` 也报出来。 - 子对象不存在(`qsf_nope`)没有拒绝:全量 dogfood 测到 unmanaged install 会先写父对象、后写它汇总的子对象,拒绝会打断这种安装;按派单第 2 条放行,列为待决问题。 - 后半:写入已落库、只是父记录汇总重算失败时,REST 和运行时分发器的 POST/PATCH/DELETE 答写入本身的成功响应(201/200,与正常成功同一个 body,不加新字段、不加新错误码);汇总列过期这件事按字段只在日志里以 error 说一次。 - protocol 的 `createData`/`updateData`/`deleteData` 仍抛 `ERR_SUMMARY_RECOMPUTE`(带 `written`),导入和种子加载的契约不变;未改 `packages/spec/**`。 - 需要你看:子对象不存在要不要以别的方式处理(见 Acceptance notes);表单提交、批量写、clone、MCP 等其它写入门未在本 PR 处理。 ## What changes **Half 1 — the doors refuse a roll-up the engine refuses at every recompute.** - `packages/lint`: the roll-up rule (`lintSummaryRollups`, `data-model-rules.ts`) leaves `lintDataModel` and becomes a gating entry of the authoring-rule registry (`authoring-rules.ts`), on all three commands and at the runtime object door (`runtimeTypes: ['object']`). It judges: - `sum`/`avg` over a child field outside the aggregate × field-type table (`isAggregateCompatibleWithFieldType`, `@objectstack/spec`'s `AGGREGATE_FIELD_TYPE_COMPATIBILITY` — the predicate the engine's aggregate door already refuses with) → `rollup/non-numeric-aggregand` at `objects.<parent>.fields.<field>.summaryOperations.field`, naming the accepted child types and `count`; - `min`/`max` (the arm `os lint` already reported, same message and fix) — now also gating at `os validate` and `os build`; - a `summaryOperations.object` naming no object the pass holds stays SILENT at every door — see Acceptance notes for the measured reason. - `os explain rollup/non-numeric-aggregand` now covers `sum`/`avg`. - The draft read already folds the publish verdict into `_diagnostics` (#26707), so a draft carrying such a roll-up now reads `valid: false` with the same entry publish refuses with. **Half 2 — a child write that landed answers its success.** - `packages/metadata-protocol`: `createData`, `updateData` and `deleteData` build the answer the write earned when the engine throws `ERR_SUMMARY_RECOMPUTE` ("the triggering records WERE written"), attach it to the refusal under a non-enumerable symbol, and rethrow — so every existing caller (import runner, seed loader) reads the refusal exactly as before. The carrier lives in `@objectstack/types` (`summary-recompute-answer.ts`), the one package the protocol, `rest` and `runtime` all depend on (`rest` has the protocol as a dev dependency only). - `packages/rest` (`crud-routes.ts`, `stale-summary-answer.ts`) and `packages/runtime` (`domains/data.ts`): `POST`, `PATCH`, `DELETE /data/:object[/:id]` answer that earned body with the write's own success status (201/200), plus the dropped-fields header the success path sets. No member, header or code is added; the body is the one the same write answers when every roll-up recomputes. - The stale summary column is logged at `error`, once per child object and summary field, with the consequence and the fix (AGENTS.md degradation-log rule); the engine's own `warn` per failure is unchanged. **Gate fallout.** `check:engine-double-contract`'s by-id seam scan now also reads a receipt returned through a same-function `const answer = { … }` (the `const opts = { where: { id } }` reading it already makes, applied to the answer), with an A/B self-test pair; its ledger learns the new test file's engine double. Four docs transcripts move from 59 to 60 author-time rules (main's #28775 had already moved them from 58 to 59). ## Tests All red on the merge base `2678600d` and green on the head. - `packages/lint` — `data-model-rules.summary-rollup.test.ts`: `sum`/`avg` over text refused with the exact message, path and fix; table parity over every `FieldType` for both functions; `sum` over `percent` refused, `avg` admitted; `sum` over a number admitted; a missing child raises nothing; `lintDataModel` no longer reports it; `os explain` facts. `runtime-gate.object-writes.test.ts`: the door refuses `sum`/`avg` over text at `objects.qsf_parent.fields.probe_sf.summaryOperations.field`, admits `sum(amount)`, admits a parent whose child does not exist yet (with and without a closure), refuses the CHILD write that turns a summed field into text, does not charge a write for a stored parent already in violation; roster pins list the rule. `data-model-rules.fix-lines.test.ts`: one-line fix. - `packages/metadata-protocol` — `protocol.summary-rollup-publish-gate.test.ts` (9): active save 422 `INVALID_METADATA` for `sum` and `avg`; the draft saves, reads `_diagnostics.valid: false` with `rollup/non-numeric-aggregand`, and both `publishMetaItem` and `publishPackageDrafts` refuse; `sum(amount)` admitted; missing child admitted by save and publish; a draft child in the same package publish is judged with its parent (numeric admitted, text refused). Base: 5 red / 4 green (the controls). - `packages/rest` — `data-write-summary-recompute-refused.test.ts` (5, real `SqlDriver` on better-sqlite3): POST 201 with the created record, persisted once, `child_sum` 295 / `child_count` 3; PATCH 200, `child_sum` 230; DELETE 200 `{object,id,success:true}`, `child_sum` 95 / `child_count` 2; one `error` line naming `qsf_parent.probe_sf`; the protocol's `createData` still throws `ERR_SUMMARY_RECOMPUTE` with `written`. Base: POST/PATCH/DELETE answered 500. - `packages/runtime` — `domains/data-write-summary-recompute-refused.test.ts` (4): the dispatcher's `/data` door answers the same 201/200 bodies, persists once, recomputes the valid roll-ups, and logs once through the host logger. Base: 4/4 red. - Ablations (each mutation landed on disk, restored to the HEAD blob, `git diff HEAD` empty): sum/avg arm off → lint 6 red; registry `runtimeTypes` emptied → lint 4 red; earned-answer symbol detached (dist rebuilt) → REST 4 red; REST POST relay disabled → REST 1 red; runtime `data.ts` at base → runtime 4 red. - Suites: `@objectstack/lint` 7730/7730, `@objectstack/rest` 7203 passed (352 skipped), `@objectstack/runtime` 9194 passed (19 skipped), `@objectstack/metadata-protocol` 21958 passed (26 skipped; 4 reds in two ssl-redaction files from `main` were a stale post-merge dist and went green after rebuilding `spec`), `@objectstack/types` 846/846. - Full dogfood on the head `fe13d22d` (after merging `main` at `5493b884`, closure rebuilt): Test Files 374 passed, 3 skipped (377); Tests 3034 passed, 28 skipped (3062). On the same head: `@objectstack/lint` 7775/7775, and the three new door files 9 / 5 / 4 passed. ## Acceptance notes - **The narrowing is already denied by published text.** `@objectstack/spec`'s `AGGREGATE_FIELD_TYPE_COMPATIBILITY` (the aggregate × field-type table) does not admit `sum`/`avg` over `text`, and the engine's aggregate door refuses the pair with its own message ("sums 'memo', a declared text field, which the engine does not sum") — on a roll-up after the write committed, every time. The lint rule's published message for `rollup/non-numeric-aggregand` already refused the `min`/`max` arm on `os lint`. No roll-up the engine could recompute is newly refused. - **The missing-child half is admitted (open question).** The first full dogfood on this branch refused it and turned 9 cases of `install-local-unmanaged-mode.dogfood.test.ts` red: the unmanaged install saves `crm_opportunity` (`line_total = sum(crm_opportunity_line_item.amount)`) one active save before the child exists. Per the order, the arm was removed and the case is left open; a missing child keeps reading 0 / null, and nothing fails. - **Census.** `examples/app-showcase` (24 objects, 9 roll-ups), `examples/app-crm` (6, 1), `examples/app-todo` (1, 0) through the built rule: 0 findings. `examples/app-multi-package` declares no summary field. `hotcrm`'s one roll-up is `sum` over a `currency` field: admitted. - **Doors not changed.** Form submit (`form-routes.ts`), the batch and `*ManyData` routes, `cloneData`, the MCP `create_record` bridge and `callData`'s ObjectQL fallback (no protocol registered) still surface `ERR_SUMMARY_RECOMPUTE` as before. Only the card's three data doors, on both transports, answer the earned body. - No `packages/spec/**` edit. ## Verification Live probe on a stock showcase boot, card steps 2–4. Sign in as the seeded admin, install a scratch package, author `qsf_parent` (`child_sum = sum(amount)`, `child_count = count`) and `qsf_child` (`memo` text, `amount` number, `parent` master_detail), publish, then seed P and two children: ``` pnpm dev -- --fresh -p <port> curl -X POST /api/v1/auth/sign-in/email -d '{"email":"admin@objectos.ai","password":"admin123"}' curl -X POST /api/v1/packages -d '{"manifest":{"id":"app.qsf","name":"QSF","version":"0.1.0","type":"app","namespace":"qsf"},"enableOnInstall":true}' curl -X PUT '/api/v1/meta/object/qsf_parent?mode=draft&package=app.qsf' -d '<parent + probe_sf = {object:qsf_child, function:sum, field:memo}>' # step 2 curl '/api/v1/meta/object/qsf_parent?state=draft&package=app.qsf' # _diagnostics curl -X POST /api/v1/packages/app.qsf/publish-drafts -d '{}' # step 3 curl -X PATCH /api/v1/data/qsf_child/qsfc1 -d '{"amount":31}' # step 4 curl -X POST /api/v1/data/qsf_child -d '{"id":"qsfy1","name":"y1","amount":60,"parent":"qsfp1"}' curl -X DELETE /api/v1/data/qsf_child/qsfy1 ``` | | base (`lint`/`metadata-protocol`/`rest`/`runtime` at `2678600d`) | head | |---|---|---| | step 2 `_diagnostics` | `{"valid":true}` | `valid:false`, `rollup/non-numeric-aggregand` (sum and avg) | | step 3 publish | `published` | `refused`, `rollup/non-numeric-aggregand` at `…probe_sf.summaryOperations.field` | | step 4 PATCH / POST / DELETE | 500 / 500 / 500 `INTERNAL_ERROR` (row persisted, `child_sum` 91 → 151 → 91) | 200 / 201 / 200 (row persisted once, `child_sum` 168 → 228 → 168), one `[REST]` error line for `qsf_parent.probe_sf` | | `probe_nope` (missing child) | published | published (admitted) | Step 4 on head was taken on a boot with only `@objectstack/lint` at base, because the head gate no longer lets the bad roll-up be stored. Gates: `node scripts/pm/dispatch-gates.mjs --commands` derived 112 commands on the head `fe13d22d`; all 112 exit 0, and `--ran` reconciles 112 derived, 112 run, 0 NOT-MEASURED. Scoped `pnpm lint` over the 17 changed `.ts`/`.mjs` files: exit 0. `pnpm check:nul-bytes`: exit 0. Typecheck (`tsc --noEmit`) of `lint`, `metadata-protocol`, `rest`, `runtime` and `types`: exit 0 each. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kV6ptpTnU6Hjb2mE4)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c064d3a commit 1617b7f

23 files changed

Lines changed: 1406 additions & 122 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/lint': minor
3+
'@objectstack/metadata-protocol': minor
4+
'@objectstack/types': minor
5+
'@objectstack/rest': patch
6+
'@objectstack/runtime': patch
7+
---
8+
9+
fix(lint,metadata-protocol,rest,runtime,types): a roll-up the engine refuses at every recompute is refused at save and publish, and a child write that landed answers its success (#28661)
10+
11+
Clause-②: no (narrowing)
12+
Metadata-protocol: narrowed
13+
Skills-docs: none — `skills/objectstack-data/rules/relationships.md` and `rules/field-types.md` teach `summaryOperations` only with `sum` over a numeric `amount` and `count`; no file under `skills/**` teaches a `sum`/`avg` over a text field, and every taught example stays admitted.
14+
15+
**BREAKING** (narrowing) for a `summary` field whose `sum` or `avg` names a child field the engine does not aggregate (and, on `os validate`, `os build` and the runtime object save/publish door, a `min` / `max` whose answer is not a number, which `os lint` already refused).
16+
17+
- **Before.** A published `summary` field with `sum` or `avg` over a child `text` field published as valid (`publish-drafts`, the draft's `_diagnostics: { valid: true }`, `os validate`, `os build`). Every later create, update and delete of a child then answered `500 INTERNAL_ERROR`, though the write had landed and the parent's valid roll-ups had recomputed: the recompute's aggregate refuses the pair after the commit. A client that retried a create made a duplicate.
18+
- **Now, at the doors.** The roll-up rule moves from `os lint` alone into the authoring-rule registry (`lintSummaryRollups`, gating, on `os validate`, `os build`, `os lint` and the runtime object save/publish door). A `sum` or `avg` over a child field outside the aggregate × field-type table (`AGGREGATE_FIELD_TYPE_COMPATIBILITY`, the table the engine's aggregate door reads) is refused under `rollup/non-numeric-aggregand`, at `objects.<parent>.fields.<field>.summaryOperations.field`, with the accepted child types and `count` as the fix. The `min`/`max` arm `os lint` already reported keeps its message and now also gates `os validate`, `os build` and the runtime object save/publish door. A child staged as a draft in the same publish batch is judged with it. `os lint` no longer reports the rule a second time.
19+
- **Now, after a write.** When a parent's roll-up cannot be recomputed after a child write — a roll-up stored before this gate, or any other recompute failure — `POST`, `PATCH` and `DELETE /api/v1/data/:object[/:id]` answer the write's own success (`201`/`200`, the same body the write answers when every roll-up recomputes), on both `RestServer` and the runtime dispatcher. The stale summary column is logged at `error`, with the fix, once per field per process (the memory is never cleared; a restart reports it again). The protocol's `createData`/`updateData`/`deleteData` still throw `ERR_SUMMARY_RECOMPUTE` carrying `written`, so the import runner and seed loader read it as before. The recogniser and the earned-answer carrier (`isSummaryRecomputeRefusal`, `earnedAnswerOf`, `staleSummaryAnswerLines`) are new exports of `@objectstack/types`, the one package the protocol, `rest` and `runtime` all depend on.
20+
- **Not refused.** A `summaryOperations.object` naming no object (the card's `qsf_nope`) is still admitted: an unmanaged install (`install-local --unmanaged`) saves a package's parent before the child its roll-up reads, so a door refusing a missing child would refuse that install.
21+
- **Who moves.** No `examples/**` or `hotcrm` roll-up is refused: every `sum`/`avg`/`min`/`max` there aggregates a `number` or `currency` child field.
22+
23+
<!-- adr-0087: not-required (no-migration-prescription) the diff registers no retirement and no key changes shape: a roll-up summing or averaging a non-numeric child field never answered a value, and the fix is an authoring choice (a numeric child field, or count) that no mechanical rewrite can make -->

‎content/docs/deployment/cli.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,7 @@ os compile --json # JSON output for CI pipelines
771771
→ Normalizing stack definition...
772772
→ Lowering inline handlers...
773773
→ Validating protocol compliance...
774-
→ Running author-time rules (59)...
774+
→ Running author-time rules (60)...
775775
→ Checking that every required capability has a provider installable in this edition...
776776
→ Collecting package docs (ADR-0046)... 0 collected
777777
→ Writing artifact...

‎content/docs/deployment/validating-metadata.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -759,7 +759,7 @@ A clean run walks the registry and reports timing:
759759
Config: /path/to/support-desk/objectstack.config.ts
760760
Load time: 21ms
761761
→ Validating against ObjectStack Protocol...
762-
→ Running author-time rules (59)...
762+
→ Running author-time rules (60)...
763763
→ Checking that every required capability has a provider installable in this edition...
764764
→ Checking package docs (ADR-0046)...
765765

‎content/docs/getting-started/build-with-claude-code.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ visible: 'status != "resolved"'
305305
◆ Validate
306306
────────────────────────────────────────
307307
→ Validating against ObjectStack Protocol...
308-
→ Running author-time rules (59)...
308+
→ Running author-time rules (60)...
309309
310310
✗ Author-time rules failed (1 issue)
311311
• stack · action 'resolve_ticket' visible: bare reference `status` — a

‎content/docs/ui/react-pages.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ objectstack validate
404404
────────────────────────────────────────
405405
→ Loading configuration...
406406
→ Validating against ObjectStack Protocol...
407-
→ Running author-time rules (59)...
407+
→ Running author-time rules (60)...
408408
→ Checking that every required capability has a provider installable in this edition...
409409
→ Checking package docs (ADR-0046)...
410410

‎packages/lint/src/authoring-rules.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ import {
161161
lintUniqueDeclarations,
162162
lintUnscopedDeclaredIndexes,
163163
lintLegacyOrganizationComposites,
164+
lintSummaryRollups,
164165
} from './data-model-rules.js';
165166

166167
import type { IObjectQLEngine } from '@objectstack/spec/contracts';
@@ -2144,6 +2145,44 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [
21442145
hint: f.fix ?? '',
21452146
})),
21462147
},
2148+
// R13 — a roll-up's aggregand and child object (`lintSummaryRollups`). A
2149+
// `sum` / `avg` over a child field the aggregate × field-type table refuses
2150+
// (a `text`, `select`, `formula` or `percent` field, …) published clean, and
2151+
// from then on every create, update and delete of the child answered 500
2152+
// although each write had landed: the recompute's `engine.aggregate` refuses
2153+
// the pair after the commit, every time. A `min` / `max` whose answer is not
2154+
// a number computes a value the summary column cannot store. `os lint` alone judged the `min` / `max` arm; no door refused any of it,
2155+
// and the runtime write door — the only one a Studio, REST or MCP author
2156+
// has — judged none of it.
2157+
//
2158+
// GATING on all three commands, so `lintDataModel` stopped calling it in the
2159+
// same change and `os lint` reports it here, once. On the runtime publish
2160+
// gate's `object` writes, where the snapshot carries the child objects
2161+
// (`stack.objects`, the collection every per-write snapshot holds), so the
2162+
// aggregand arms have no missing-collection false-positive channel: a child
2163+
// the snapshot does not hold is not judged — nor is a child object nothing
2164+
// holds, which an unmanaged install legitimately writes after its parent
2165+
// (see the rule's docblock). The gate's
2166+
// differential charges a STORED parent's finding to this write only when the
2167+
// write creates it (a child write that turns a summed field into text).
2168+
{
2169+
name: 'lintSummaryRollups',
2170+
tier: 'gating',
2171+
input: 'parsed',
2172+
commands: ALL,
2173+
source: 'packages/lint/src/data-model-rules.ts',
2174+
surfaces: CLI_AND_RUNTIME,
2175+
runtimeTypes: ['object'],
2176+
run: (stack) =>
2177+
lintSummaryRollups(Array.isArray(stack.objects) ? (stack.objects as unknown[]) : []).map((f) => ({
2178+
severity: f.severity === 'suggestion' ? ('info' as const) : f.severity,
2179+
rule: f.rule,
2180+
where: f.where,
2181+
path: f.path,
2182+
message: f.message,
2183+
hint: f.fix ?? '',
2184+
})),
2185+
},
21472186
// #3991 / ADR-0120 D5b — a column carrying BOTH a field-level `unique` and a
21482187
// single-column declared unique index states two scopes of which at most one
21492188
// takes effect (`unique/double-declaration`, the four-quadrant matrix).

‎packages/lint/src/data-model-rules.fix-lines.test.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22

33
// [#22161] Every `data-model-rules.ts` finding's `fix` is one remedy line of at
44
// most 200 characters. `os lint --fix` prints it as the `→ fix:` line, and the
5-
// three ADR-0120 uniqueness ids carry it as the `hint` `os validate` and
6-
// `os build` print. What the hints used to explain is `os explain` text.
5+
// three ADR-0120 uniqueness ids and the two roll-up ids carry it as the `hint`
6+
// `os validate`, `os build` and the publish door print. What the hints used to
7+
// explain is `os explain` text.
78
//
8-
// The four `lintDataModel` sweep ids (`object/missing-name-field`,
9-
// `field/select-missing-options`, `rollup/non-numeric-aggregand`,
10-
// `field/embedded-sub-fields`) are never
9+
// The three `lintDataModel` sweep ids (`object/missing-name-field`,
10+
// `field/select-missing-options`, `field/embedded-sub-fields`) are never
1111
// adapted into an `AuthoringFinding`, so a census that reads `hint` never sees
1212
// them. This file reads `fix` directly, over every arm each rule has, with long
1313
// object and field names where a name is interpolated.
@@ -18,6 +18,7 @@ import {
1818
FIELD_EMBEDDED_SUB_FIELDS,
1919
lintDataModel,
2020
lintLegacyOrganizationComposites,
21+
lintSummaryRollups,
2122
lintUniqueDeclarations,
2223
lintUnscopedDeclaredIndexes,
2324
ROLLUP_NON_NUMERIC_AGGREGAND,
@@ -192,13 +193,14 @@ describe('[#22161] data-model-rules.ts — one remedy line per fix', () => {
192193
});
193194

194195
it('rollup/non-numeric-aggregand: one line naming the child type, not the parent', () => {
195-
expect(fixOf(record(lintDataModel(rollup('datetime', LONG_OBJECT))), ROLLUP_NON_NUMERIC_AGGREGAND)).toBe(
196+
expect(fixOf(record(lintSummaryRollups(rollup('datetime', LONG_OBJECT))), ROLLUP_NON_NUMERIC_AGGREGAND)).toBe(
196197
"Aggregate a numeric or boolean child field, or use function: 'count'; a roll-up cannot store a " +
197198
'datetime, so declare a datetime field and maintain it from a flow.',
198199
);
199200
for (const type of ['date', 'time', 'text', 'select', 'multiselect', 'lookup', 'json', 'autonumber', 'textarea']) {
200-
for (const fn of ['min', 'max']) record(lintDataModel(rollup(type, LONG_OBJECT, fn)));
201+
for (const fn of ['min', 'max', 'sum', 'avg']) record(lintSummaryRollups(rollup(type, LONG_OBJECT, fn)));
201202
}
203+
record(lintSummaryRollups(rollup('percent', LONG_OBJECT, 'sum')));
202204
});
203205

204206
it('every fix the cases above fired is one line of at most 200 characters', () => {

‎packages/lint/src/data-model-rules.summary-rollup.test.ts‎

Lines changed: 83 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@ import {
2828
isAggregateCompatibleWithFieldType,
2929
} from '@objectstack/spec/data';
3030

31-
import { lintDataModel as lintDataModelUnrecorded, ROLLUP_NON_NUMERIC_AGGREGAND } from './data-model-rules.js';
31+
import {
32+
lintDataModel,
33+
lintSummaryRollups as lintSummaryRollupsUnrecorded,
34+
ROLLUP_NON_NUMERIC_AGGREGAND,
35+
} from './data-model-rules.js';
3236
import { explainRule } from './rule-explanations.js';
3337

3438
const RULE = 'rollup/non-numeric-aggregand';
@@ -39,8 +43,8 @@ const RULE = 'rollup/non-numeric-aggregand';
3943
// of at most 200 characters — every child type this suite refuses, not a
4044
// chosen few. Run the whole file: those cases read what the cases above fired.
4145
const fired: Array<{ rule: string; message: string }> = [];
42-
const lintDataModel: typeof lintDataModelUnrecorded = (...args) => {
43-
const issues = lintDataModelUnrecorded(...args);
46+
const lintSummaryRollups: typeof lintSummaryRollupsUnrecorded = (...args) => {
47+
const issues = lintSummaryRollupsUnrecorded(...args);
4448
fired.push(...issues);
4549
return issues;
4650
};
@@ -67,7 +71,7 @@ const model = (childType: string | undefined, fn = 'max', overrides: Record<stri
6771
},
6872
];
6973

70-
const findings = (objects: unknown[]) => lintDataModel(objects as any[]).filter((i) => i.rule === RULE);
74+
const findings = (objects: unknown[]) => lintSummaryRollups(objects as any[]).filter((i) => i.rule === RULE);
7175

7276
describe('rollup/non-numeric-aggregand — refuses a min/max roll-up whose answer cannot fit the column', () => {
7377
it('refuses the card\'s own example: max over a datetime child field', () => {
@@ -153,15 +157,76 @@ describe('rollup/non-numeric-aggregand — discriminates from the analytics tabl
153157
});
154158
});
155159

160+
describe('rollup/non-numeric-aggregand — sum / avg judged by the table the engine\'s aggregate door asks', () => {
161+
// A roll-up recompute is an `engine.aggregate` call, and the engine's
162+
// aggregate door refuses every pair the aggregate × field-type table refuses
163+
// — after the child write has committed, on every write of the child. So the
164+
// sum / avg arms ARE that table, never a second list: the authoring verdict
165+
// and the recompute verdict cannot disagree.
166+
it('refuses the card\'s own example: sum over a text child field, naming the field and the route', () => {
167+
const found = findings(model('text', 'sum'));
168+
expect(found).toHaveLength(1);
169+
const issue = found[0]!;
170+
expect(issue.severity).toBe('error');
171+
expect(issue.path).toBe('objects[0].fields.rolled_up.summaryOperations.field');
172+
expect(issue.message).toBe(
173+
'summary field "invoice.rolled_up" rolls up sum(invoice_line.shipped_at), a text field the engine ' +
174+
'does not sum: every recompute is refused',
175+
);
176+
expect(issue.fix).toBe(
177+
'Aggregate a child field of type number, currency, rating, slider, progress, summary, boolean or ' +
178+
"toggle, or use function: 'count'.",
179+
);
180+
});
181+
182+
it('refuses avg over a text child field, with avg\'s own accepted set (percent included)', () => {
183+
const [issue] = findings(model('text', 'avg'));
184+
expect(issue?.message).toContain('avg(invoice_line.shipped_at), a text field the engine does not average');
185+
expect(issue?.fix).toBe(
186+
'Aggregate a child field of type number, currency, percent, rating, slider, progress, summary, ' +
187+
"boolean or toggle, or use function: 'count'.",
188+
);
189+
});
190+
191+
it('accepts sum over a number child field (the control)', () => {
192+
expect(findings(model('number', 'sum'))).toEqual([]);
193+
expect(findings(model('number', 'avg'))).toEqual([]);
194+
});
195+
196+
it('refuses exactly the pairs the table refuses, over every declared FieldType, for both functions', () => {
197+
for (const fn of ['sum', 'avg']) {
198+
const refused = FieldType.options.filter((t) => findings(model(t, fn)).length > 0);
199+
expect(refused.sort(), fn).toEqual(
200+
FieldType.options.filter((t) => !isAggregateCompatibleWithFieldType(fn, t)).sort(),
201+
);
202+
// A floor, so a rule that stops firing cannot make the equality vacuous.
203+
expect(refused.length, fn).toBeGreaterThan(10);
204+
}
205+
});
206+
207+
it('refuses sum over percent and accepts avg over it — a rate averages but does not add', () => {
208+
expect(findings(model('percent', 'sum'))).toHaveLength(1);
209+
expect(findings(model('percent', 'avg'))).toEqual([]);
210+
});
211+
});
212+
156213
describe('rollup/non-numeric-aggregand — stays silent where it cannot resolve, and outside its scope', () => {
157214
// "A consumer that cannot resolve a field's type must NOT call the predicate
158215
// with a guess" — `aggregate-field-type-compatibility.ts`. A refusal fired on
159216
// a partially-loaded model would redden an app over metadata never seen.
160-
it('is silent when the child object is not in the pass\'s object set', () => {
217+
it('is silent on the aggregand when the child object is not in the pass\'s object set', () => {
161218
const objects = model('datetime').slice(0, 1); // parent only — no `invoice_line`
162219
expect(findings(objects)).toEqual([]);
163220
});
164221

222+
// [#28661] A child object nothing holds is not refused under ANY rule id: an
223+
// unmanaged install saves the parent before its child (measured on the
224+
// `install-local-unmanaged-mode` dogfood: `crm_opportunity.line_total`
225+
// before `crm_opportunity_line_item`).
226+
it('raises nothing at all for a sum whose child object is not in the pass — a parent written before its child', () => {
227+
expect(lintSummaryRollups(model('number', 'sum').slice(0, 1))).toEqual([]);
228+
});
229+
165230
it('is silent when the named field is not declared on the child', () => {
166231
expect(findings(model(undefined))).toEqual([]);
167232
});
@@ -178,24 +243,22 @@ describe('rollup/non-numeric-aggregand — stays silent where it cannot resolve,
178243
expect(findings(model('datetime', 'max', { object: '' }))).toEqual([]);
179244
});
180245

181-
it('is scoped to min/max — count reads no value off the field', () => {
182-
expect(findings(model('datetime', 'count'))).toEqual([]);
183-
});
184-
185-
// `sum` / `avg` over a non-numeric child is a different shape, whose accept
186-
// set the analytics table's own rows already exclude, and is deliberately not
187-
// this rule's. (Nothing in this tree consults that table — an open gap
188-
// reported with this change, not one this rule silently absorbs.)
189-
it('does not fire for sum or avg', () => {
190-
expect(findings(model('datetime', 'sum'))).toEqual([]);
191-
expect(findings(model('datetime', 'avg'))).toEqual([]);
246+
it('never judges count — count reads no value off the field', () => {
247+
for (const childType of ['datetime', 'text', 'json']) {
248+
expect(findings(model(childType, 'count')), childType).toEqual([]);
249+
}
192250
});
193251

194252
it('is silent for a field that is not a summary at all', () => {
195253
const objects = model('datetime') as any[];
196254
objects[0].fields.rolled_up.type = 'number';
197255
expect(findings(objects)).toEqual([]);
198256
});
257+
258+
it('is no longer `lintDataModel`\'s — the gate entry reports it under `os lint`, once', () => {
259+
expect(lintDataModel(model('datetime') as any[]).filter((i) => i.rule.startsWith('rollup/'))
260+
.filter((i) => i.rule !== 'rollup/missing-summary')).toEqual([]);
261+
});
199262
});
200263

201264
describe('[#22161] one-line verdicts — rollup/non-numeric-aggregand', () => {
@@ -232,8 +295,12 @@ describe('[#22161] one-line verdicts — rollup/non-numeric-aggregand', () => {
232295
'analytics aggregate table',
233296
'`count` reads no value',
234297
'does not resolve in this stack',
298+
'after the child write has committed',
299+
'`sum` over a `percent`',
300+
'`valid: false`',
235301
]) {
236302
expect(text, `explanation names ${fact}`).toContain(fact);
237303
}
238304
});
305+
239306
});

0 commit comments

Comments
 (0)