Skip to content

Commit b863d2b

Browse files
feat(service-analytics): query_dataset says how many groups existed before the limit cut (totalGroups) (#35201)
Fixes #35194 Clause-②: yes (widening: QueryDatasetOutputSchema gains totalGroups) Metadata-protocol: added Skills-docs: follow-up #35203 ## 维护者速读 - 改了什么:问数工具 `query_dataset` 在结果被截断时返回 `totalGroups`(截断前一共有多少组,与 `aggregate_records` 同名同义)。本轮按修订后的席位答复(路线 B)补上常见情形:工具默认按全部维度升序排序,只要按下拉选项或关联字段分组(阶段、负责人、客户),窗口就在内存里截取;现在对这份内存里的完整分组表直接数行数作为总数。上一轮在这些情形下一律不返回该字段。 - 为什么改:合同评审 S1 指出,“每个阶段多少单”这类最常见的问题恰好走内存截取,总数缺失,违背了卡片的完成条件(未截断时 `totalGroups` 等于 `rowCount`)。 - 风险与回滚:不新增任何查询,计数来自本来就已取回的分组;只有当构成这份表的每一次读取都由内置策略确认“没有被任何上限截断”(策略亲自应答且应答的组数与返回行数一致)时才计数,任何一次读取被截断或无法确认就不返回该字段,绝不拿被截断的表凑数。只有 AI 工具请求计数,REST 数据集接口、仪表盘、报表执行的语句不变。回滚即 revert 本 PR;字段本就是可选的。 - 先看:`packages/services/service-analytics/src/dataset-executor.ts`(`wholeness` 账本与 `applyWindow` 之前那一行计数)、`packages/services/service-analytics/src/dataset-group-count.ts`(`noteWholeRead` 的“应答且行数相符”判定)、`packages/spec/src/ai/dataset-tools.zod.ts`(`totalGroups` 的 describe 是否如实写清两种来源与全部缺失情形)。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/dataset-tools.test.ts -t totalGroups`,预期 SQLite 一组 11 条全绿(PostgreSQL 一组未设 `OS_TEST_POSTGRES_URL` 时为具名跳过)。 - 需要你做的:无,席位落地。 ## What changes This round answers contract review 6980602474 (S1, N1, N3) under the revised seat answer on #35194 (comment 6980624450, route B: count the complete in-memory grid) and the filing seat's confirmation that a grid any cap cut answers no count. - **Two sources, never a read.** `totalGroups` is either (1) the database's `COUNT(*) OVER ()` in the one statement that grouped and cut the answer, where the window is pushed down (unchanged), or (2) the length of the grid before the window, where the window is applied in memory. Source 2 covers the executor's in-memory window (`canPushDownWindow` false: a label-bearing order key, which the tool's default order brings in for any select or reference dimension; a measure with its own filter; a derived measure; `compareTo`) and the ObjectQL face's own window over the rows `engine.aggregate` answers whole (a date bucket, a field-to-field filter, an external object, a driver with no raw SQL, and other routes to that face). - **Whole is vouched, never assumed.** In the executor's in-memory path every read that builds the grid (the primary query, each measure-filter supplementary query, the `compareTo` pass) carries its own `GroupCountRequest`. A strategy answers it only for an answer it read with no window and no cap: `NativeSQLStrategy` for a statement with no `LIMIT`/`OFFSET` (`answerWholeGrid`, no window function added there), the ObjectQL face for the engine's answer before its own `orderAndWindow`. `noteWholeRead` keeps the grid whole only while every read was answered AND its answered count equals the rows it handed back, so a read a cap or row guard cut after the strategy counted is caught by the mismatch, and a read no built-in strategy served (a host-added strategy, a fallback service that does not answer) is caught by the missing answer. The count is written before `applyWindow`; a grid the empty time-bucket fill grew is not counted (not reachable from the tool, which always sends a limit). - **Completeness trace (no cap cuts the grid before the window).** Native-SQL in-memory path: the executor hands no window, the statement carries no `LIMIT`, and the raw-SQL bridge (`plugin.ts` to `engine.execute` to `driver-sql`'s raw execution) applies no row limit. The tool's `cap + 1` probe and `maxQueryLimit` are the selection's own `limit`, applied by `applyWindow` after the count. `OS_DATA_*` read limits judge only the selection's window at `queryDataset` (the tool always names a limit, so no default-page probe), and the executor's sub-queries go through `queryIn`, which plans no window. Assembled grids: `mergeByDimensions` appends and never drops; the derived pass and the empty-group fill keep the row count. ObjectQL face: `engine.aggregate` takes no order or window, native `driver.aggregate` and the `find` plus in-memory fallback read with no limit (the OData driver follows `nextLink` to the end), and the engine's relation and nested-relation caps refuse rather than truncate. Where completeness cannot be shown (a strategy outside the two built-ins) the member stays absent, by construction rather than by trace. - **Spec describe (S1, N1).** States both sources, that the tool's own order (used when none is sent) sorts every selected dimension so a select or reference dimension brings in the in-memory window while an order by measures alone does not, the whole-grid rule with the cap arm, and every remaining absence case; the engine-aggregate list now reads "such as". Old and new text are in the report on #35194. References regenerated (`gen:schema`, `gen:docs`; `check:generated` all 14 up to date); `authorable-surface/ai.json` did not move. - **N3.** The `dataset-group-count.ts` header no longer says `aggregate_records` counts "with the same window": on main it answers `rows.length`, the length of the rows `engine.aggregate` answered before that tool's cap, which is the same reading as Source 2. - **Changeset prose** restated for the two sources and the remaining absences; level and declaration lines unchanged. - No file draft #35193 touches is edited. ## Tests `packages/services/service-analytics/src/__tests__/dataset-tools.test.ts`, inside the existing real-engine describe (`ObjectQL` + `SqlDriver`, SQLite always, PostgreSQL where `OS_TEST_POSTGRES_URL` is set), every read of the object counted. The fixture gains `phase`, a `select` field with options whose labels sort in another order than their values, so the plugin's `labelResolver` makes the dimension label-bearing in the real wiring. - New: default order, no cut, on `phase`: `totalGroups === rowCount === 3`, one statement, no window function and no `LIMIT` in it, no engine aggregate. - New: default order with a cut (`maxQueryLimit: 2`): `truncated: true`, `totalGroups` 3, rows in label order; an empty page past the grid (`offset: 10`) still answers 3, since the in-memory window knows the whole grid. - Rewritten from "absent" to "present": the assembled grid (a measure with its own filter: two statements; a derived measure: one) answers `totalGroups` 5 with no window function in any statement; the date bucket and the ObjectQL face answer 3 and 5, and the ObjectQL face with `phase` answers 3, one engine aggregate each. - New absence arm: a host strategy ahead of the built-ins serves each query through `NativeSQLStrategy` and keeps two rows; the grid it cut answers no `totalGroups`. - Kept: every pushed-down pin, the empty page after an offset on a pushed-down window (absent), the unknown dialect (absent). <details><summary>Red on the previous head, green, one ablation of the count, one mutation of the cap arm</summary> - Red: the six analytics sources restored from 5911cff (the previous head), the new pins kept: `Tests 4 failed | 7 passed | 89 skipped (100)`. The four failures are the label-bearing pair, the assembled grid and the engine-aggregate pin, each `expected … to match object { rowCount: …, truncated: …, totalGroups: … }`. The cap-arm pin passes there, as absence was that head's behaviour. Restored with `git checkout HEAD`, `git diff HEAD` empty. - Green at efd8097: `Tests 11 passed | 89 skipped (100)`. - Ablation of the grid-length count (`dataset-executor.ts`, the line before `applyWindow`, through `scripts/ablation-replace.mjs`: anchor 1 to 0, blob ad6ee88 to 790809994577): `Tests 4 failed | 7 passed`, the same four. Restored: blob equals HEAD, `git diff HEAD` empty. - Mutation of the cap arm (`noteWholeRead` stops comparing the answered count with the rows: blob 4f5686a to 57f707b58e33): `Tests 1 failed | 10 passed`, the host row-guard pin. Restored: blob equals HEAD, `git diff HEAD` empty. - The suite imports the package's sources by relative path, so no `dist/` was in the path and no dist preflight applies. </details> ## Acceptance notes - **N2, accepted.** Two of the four dialects in `GROUP_COUNT_DIALECTS` are claimed by reading, not measured: MySQL and SQL Server (no server here). The gate is the dialect name, not the server version, so a `mysql` server older than 8.0 would fail to parse the pushed-down statement; the repo assumes MySQL 8 elsewhere. The in-memory source needs no window function and is dialect-free. A follow-up card for the two unmeasured cells is the remedy. - **N4, accepted.** `takeGroupCount` trusts the first row; #35193's `takeAggregateGroupCount` checks that every row agrees and that the count is not below the rows returned. Not a correctness gap on the four dialects; worth closing when #35204 joins the two readers. - **#35204 shrinks** to what is still absent after this round: an ObjectQL-face window that the engine itself cuts (once a read hands `engine.aggregate` an order-and-cut, the count must come from the engine's statement; the ObjectQL strategy's comment says so at the count). - `skills/objectstack-ask/SKILL.md` teaches `truncated` and could teach `totalGroups`, including the S1 sentence; that is `skills/**` and follow-up #35203. ## Verification <details><summary>Local runs at head a2abbca (this round's final commit; base c787255, the branch point; every exit captured before any pipe)</summary> - `pnpm --filter @objectstack/service-analytics typecheck`: exit 0 (`dataset-tools.test.ts` is in the program, `--listFiles`: 1). - `pnpm --filter @objectstack/service-analytics exec vitest run`: `Test Files 218 passed (218)`, `Tests 5603 passed | 345 skipped (5948)`, VERDICT command-exit 0. - `pnpm --filter @objectstack/spec typecheck` then `vitest run`: `Test Files 944 passed (944)`, `Tests 28892 passed | 1 todo (28893)`, VERDICT command-exit 0. - `pnpm --filter @objectstack/spec check:generated` after `build`, `gen:schema`, `gen:docs`: `All 14 generated artifacts are up to date`. Its first run, before the regeneration, also reported `check:test-typecheck` with `tsc … failed without diagnostics` on a loaded box; the rerun was green with no change to the spec tests. - `node scripts/pm/dispatch-gates.mjs --commands`: 118 families, each run with its exit captured; `--ran` with the `:: exit N` record: `118 derived famil(ies) accounted for — 116 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)`. - NOT MEASURED: `check:skill-examples` and `check:dual-build-cjs-loads`, both exit 3 (they need the whole workspace built, `Run pnpm build first. This is NOT a pass`). Neither reads a file this diff changes; CI's lint and type-check lanes carry them. - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` against origin/main 1caee8c, 0 open PR heads sharing a file. - The derivation printed a stale-tree note (origin/main 3 commits ahead, one changed file `scripts/check-skills-token-ratchet.mjs`, not a derived family here). </details> <details><summary>CI on a2abbca, read when this body was written</summary> 70 check-runs: 60 `success`, 10 `skipped`, none failed or pending. Among the required contexts: `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core` (all 10 shards), `Build Core`, `Governed Surface Queue Guard`, `Type Check UI`, `Test UI` (all 16 shards), `Build & E2E UI`, `Live E2E UI`, `Dogfood Regression Gate`: `success`; `Lint UI`: `skipped` (path-filtered). Also `success`: `Check Changeset`, `Spec property liveness`, `PR-body guards`, `Check PR Size`, `Build Docs`. `Temporal Conformance (live PG + MySQL)` is `skipped` (opt-in). Whether a Test Core shard sets `OS_TEST_POSTGRES_URL` for the PostgreSQL cell is not read here. </details> <details><summary>Earlier rounds</summary> - Round 2 (5911cff): `Check Changeset` fix, `Metadata-protocol: added` and `@objectstack/spec` `minor` declared; `check-changeset-no-major` exit 0 with that body and exit 1 with the previous one as control. - Round 1 (ed57ac3): package typecheck and tests green, `check:generated` up to date, 118 derived families run, `check:skill-examples` and `check:dual-build-cjs-loads` NOT MEASURED (exit 3, need a whole-workspace build; CI runs both). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbXGvw43spR79ztEvWt)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbXGvw43spR79ztEvWt --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8856afc commit b863d2b

11 files changed

Lines changed: 636 additions & 19 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-analytics': patch
4+
---
5+
6+
feat(service-analytics): `query_dataset` says how many groups existed before the `limit` cut (`totalGroups`), as `aggregate_records` does
7+
8+
Clause-②: yes (widening: QueryDatasetOutputSchema gains totalGroups)
9+
Metadata-protocol: added
10+
Skills-docs: follow-up #35203
11+
12+
`QueryDatasetOutputSchema` gains an optional `totalGroups`: how many groups the selection formed before `offset` and `limit` cut them, the same name and meaning as `aggregate_records`' `totalGroups`. A client asked "how many are there" after a top-N cut can now answer it: a grouped `query_dataset` whose `limit` is below the group count answers `truncated: true` and the full count, and an answer that was not cut answers `totalGroups` equal to `rowCount`.
13+
14+
The count never costs a read. Where the window is pushed into the one SQL statement that grouped the answer, the database counts the groups in that statement (`COUNT(*) OVER ()`, after the `GROUP BY` and ahead of the `ORDER BY` and `LIMIT`). Where the window is applied in memory, the count is the length of the grid before the window: an order by a display label (the tool's own order, used when none is sent, sorts every selected dimension, so grouping by any select or reference field brings this in; an order by measures alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, `compareTo`), and a query the engine's aggregate serves, such as a date bucket, a field-to-field filter, an external object or a driver with no raw SQL. That grid is counted only when every read that built it came back whole; a grid that a cap or row guard cut before the window answers no count.
15+
16+
`totalGroups` is absent when: the window was pushed down and the SQL dialect is not one the analytics strategy knows, or a selected member is itself named `__os_group_count`, or the page came back empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a host adds, or was cut by a cap under it; or the dataset's object is missing and the answer is the empty one served for it. Read `totalGroups` as optional.
17+
18+
Only the AI tool asks for the count. The REST dataset door, dashboards and reports run the statements they ran before.

‎content/docs/references/ai/dataset-tools.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ const result = DatasetNextStepSchema.parse(data);
338338
| **sourceLine** | `string` | optional | The answer's source as one finished line, in the caller's locale: composed by the tool from `provenance` after the query ran, never typed by the model. `provenance` stays the structured source and this is the same source in words. The wording is the executor's; the schema declares the slot and fixes no text (ADR-0149 M1). Absent when the tool composed none, never an empty string |
339339
| **rowCount** | `integer` | ✅ | How many rows `rows` holds |
340340
| **truncated** | `boolean` | ✅ | `true` when more rows existed past the row cap the tool applied and were not returned |
341+
| **totalGroups** | `integer` | optional | How many groups the selection formed before `offset` and `limit` cut them: the rows the same selection answers with no window. The same name and meaning as `aggregate_records`' `totalGroups`. Never paid for with a read. Where the window is pushed into the one SQL statement that grouped the answer, the database counts the groups with a window count in that statement. Where the window is applied in memory, it is the length of the grid before the window: an order by a display label (the tool's own order when none is sent sorts every selected dimension, so any select or reference dimension brings it in; an order by measures alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, `compareTo`), and a query the engine's aggregate serves, such as a date bucket, a field-to-field filter, an external object or a driver with no raw SQL. That grid is counted only when every read that built it came back whole: a grid that any cap or row guard cut before the window answers no count. Equals `rowCount` when the answer was not cut. Absent otherwise, which is when: the window was pushed down and the SQL dialect is not one the tool knows, or a selected member is itself named `__os_group_count`, or the page came back empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a host adds, or was cut by a cap under it; or the dataset's object is missing and the answer is the empty one served for it |
341342
| **delegationNarrowed** | `true` | optional | Present, and `true`, when the caller acts as an agent whose authority narrows what it may read on the dataset's object; `warning` states the narrowing (ADR-0090 D10) |
342343
| **warning** | `string` | optional | The narrowing statement; present exactly when `delegationNarrowed` is |
343344

0 commit comments

Comments
 (0)