Repository navigation
Commit 65b67be
feat(mcp): aggregate_records orders, cuts and counts groups in the database (#35193)
Fixes #35144
Clause-②: yes (widening: `orderBy` and `limit` arguments on
`aggregate_records`)
Metadata-protocol: none
The card's `query_dataset` half is split to #35194 (seat ruling
6978086158, Q1), which carries the group total on
`QueryDatasetOutputSchema`; this PR closes the card on the
`aggregate_records` half. Per the same ruling (Q2 = C) the answer keeps
the published `totalGroups` (the groups before the cut) and adds no
second key.
## 维护者速读
- 改了什么:MCP 的 `aggregate_records` 新增 `orderBy` 与
`limit`。排名类问题(如“收入前五的客户”)由数据库一条语句完成排序、截断和分组计数;结果沿用已发布的
`totalGroups`(截断前的分组总数),并在有截断时给出 `truncated: true`。只给 `limit` 不给
`orderBy` 时,按单选/radio 字段声明的选项顺序在数据库里排序后再截断(与 #35186
的无序默认路径同一条规则);固定币种金额在截断结果上同样给出 `currencies`;按
lookup/主从字段分组时,截断结果与默认路径一样在键旁给出 `KEY__label`(以调用者权限读取的记录名称,#35202 的同一个
`withLookupGroupLabels`)。
- 为什么改:分组数超过行上限(50)时,原来只能拿到无序的前 50 组,客户端在不完整的数据上自行排名,答案会错。
- 风险与回滚:只有 SQL 驱动(含 WASM SQLite、Turso 本地/副本)执行;其余驱动、内存计算路径和带 `having`
的聚合一律以 INVALID_QUERY/400 拒绝,不会退化成内存排序。不带新参数的调用行为与 main 完全一致。回滚即 revert 本
PR。窗口函数 `count(*) over ()` 要求 MySQL 8 及以上。
- 先看:`packages/drivers/driver-sql/src/sql-driver-aggregation.ts`(派生表加
ORDER BY/LIMIT/窗口计数、rank 编译成 CASE
的那段)、`packages/mcp/src/mcp-http-tools.ts`(截断路径:未给 `orderBy` 时由
`declaredOptionOrderBy` 推导声明顺序、探测组与
`truncated`、`currencies`)、`packages/objectql/src/aggregate-order-cut.ts`(判定谁能执行、哪些情况拒绝)。
- 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run
src/mcp-aggregate-order-cut.test.ts`,预期 6 个用例全绿;其中一条断言真实 SQLite 语句里带
`order by case ... end asc` 与 `limit`,声明顺序在前、NULL 在最后、`totalGroups` 为 4。
- 需要你做的:无,席位落地。
## What changes
- **Engine (`@objectstack/objectql`).** `engine.aggregate` takes an
engine-internal read option, `AGGREGATE_ORDER_CUT`. It is a `Symbol.for`
key, so no wire request or JSON query can set it.
- The request has `orderBy` (aggregation aliases and group keys), an
optional `limit`, and an outcome slot that the engine writes once the
driver has served the request: `{ kind: 'served', totalGroups }`.
- The engine checks the request before it asks the driver. An order key
that names no column of the aggregated row is `INVALID_SORT`/400, and
the message names the columns.
- Each of these is `INVALID_QUERY`/400: any driver not on the compiling
list, an aggregate the engine computes in memory, a `having`, and a
relation group.
- Rows that come back without the count column are `INTERNAL_ERROR`/500
and are never served.
- An order key may also carry a `rank`: a list of the column's values in
declared order. This is how a declared option order reaches the
statement.
- **SQL driver (`@objectstack/driver-sql`).** The grouped statement
becomes a derived table, with `count(*) over ()` and `ORDER BY`/`LIMIT`
over its columns. It is one statement and one round trip.
- On a key without a `rank`, a NULL ranks last in either direction.
- A `sum` or count with no value ranks as the `0` it is served as.
- A `rank` key compiles to a `case ... when ? then i ... else n end`
expression: every unlisted value (a NULL among them) shares rank `n`, so
the unlisted values come after the listed ones ascending and before them
descending.
- Tie-breakers are the group keys the request does not name, plus any
group key it names only by a `rank`, ascending, NULL last (engine,
`aggregateOrderCutDirective`). So the unlisted values of a ranked column
keep their own order, and a cut among them answers the same groups on
every run (contract review S1).
- **Turso driver.** Its remote face refuses the directive
(`INVALID_QUERY`/400). The local and replica faces inherit the SQL
driver.
- **Runtime HTTP bridge and stdio bridge.** Both have a new optional
member, `McpDataBridge.aggregateGroups`, answering `{ rows, totalGroups
}`. It runs through the same gates as `aggregate`, carries the request,
and reads the engine's outcome back.
- **`aggregate_records`.**
- New arguments: `orderBy` and `limit` (at most the row cap).
- Aliases: `sort`, `sortBy`, `order` and `order_by` map to `orderBy`;
`top`, `take` and `pageSize` map to `limit`.
- The tool asks for one probe group beyond the cap, so `truncated` is a
fact rather than a guess.
- On the order-and-cut path `totalGroups` is the statement's own count
of the groups before the cut.
- A `limit` with no `orderBy`: the leading select/radio group keys'
declared option order is handed to the database as `rank` keys, so it is
taken before the cut. The leading-key reading is one helper
(`declaredOptionOrderKeys`) that both paths call: the uncut path sorts
by it, the cut path sends it. A declared list longer than the engine's
rank maximum (500) ends the reading at its key rather than send a rank
the engine refuses. An `orderBy` the caller sends is passed unchanged
and overrides the option order.
- `currencies` (a fixed-currency amount's ISO code, by alias) is on the
cut result as on the uncut one.
- A lookup or master-detail group key carries `KEY__label` on the cut
result as on the uncut one: both paths call one local closure over
#35202's `withLookupGroupLabels`, applied to the served rows after the
cut, so the name read never covers the probe group past the cap.
- The description says that ranking an amount whose records each carry
their own currency compares bare numbers across currencies, and to rank
it inside one currency by filtering `where` on its currency code field
(contract review S2, option 1; no refusal added).
- A bridge without `aggregateGroups` answers `NOT_IMPLEMENTED`/501.
- Calls without the new arguments answer exactly as on `main`.
## Tests
- New `packages/objectql/src/aggregate-order-cut.test.ts` (14): the
directive the driver receives, the count taken off the rows,
`INVALID_SORT` naming the columns, malformed requests and ranks,
`having`, a timezone bucket computed in memory, a missing count, refusal
on every driver that does not compile the cut, and the Turso local face
and WASM driver served.
- New
`packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts`:
live dialect cells, where SQLite always runs and Postgres/MySQL run
where they are provisioned. It covers the top five of 62 groups; NULL
and the 0 identity ranking; rank order; tenant wall plus `where`; a
query spy showing ORDER BY, LIMIT and the window in the statement;
CONTROL with no directive; a malformed or unprojected directive refused.
- New `packages/runtime/src/mcp-aggregate-order-cut.test.ts` (6): HTTP
bridge `buildMcpBridge`, over a real `ObjectQL`, a real `SqlDriver` and
SQLite in memory. It covers the top five of 70 customers in order with
`totalGroups` 70 and the statement regex; a group key ascending; a
declared rank; the declared option order a limit-only call sends
(declared groups first, NULL last, the cut after the CASE, `totalGroups`
4); `INVALID_SORT`; CONTROL.
- New `packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts`
(6): stdio, through a real MCP client against a real `ObjectQL`. It
covers the top five of 80 groups (exactly 5, in order, `totalGroups` 80,
`truncated`); `INVALID_SORT`; a memory driver refused; a missing count
never answered; a limit-only call over a select key reaching the driver
directive as a `rank` before the cut; CONTROL with no order and no limit
(`totalGroups`, no `groupCount`).
- Updated `packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts`:
the tool half (probe group, `truncated`, aliases, 501 without the
member, CONTROL), #35186's option-order and currency block unchanged,
and a new block for the carried items: the limit-only push-down (the
bridge receives `{ field, order: 'asc', rank }` and the cut keeps the
first declared groups, `totalGroups` 5), the rank read by alias for each
leading select key and ending at the first that is not one, the
over-long declared list, the explicit-order CONTROL (an `orderBy`
reaches the bridge unchanged, with no rank), `currencies` on the cut
result, and a bridge without the served definition cutting as before.
Every served result in that block is pinned to carry no `groupCount`.
- The #35138 lookup-label block in the same file gains one pin: an
`orderBy` + `limit` call grouped by a lookup answers the served groups
with `account__label`, `totalGroups` 3 and `truncated`, from one read of
the referenced object for the served ids only (never the probe group).
- Round 5 (contract review 6985265817):
- S1, `runtime` real SQLite: one declared value and three unlisted
(`lost`, `open`, NULL), cut at 3: the answer is `won`, `lost`, `open`
twice over, the statement carries the column's null-last ascending
tie-break after the CASE, and the uncut order ends with NULL. The engine
directive pin and the stdio directive pin show the ranked column among
the trailing keys.
- S2, the `tools/list` pin asserts the record-mode ranking sentence.
- S3, `runtime` real SQLite: a registered read middleware that narrows
`ast.where` to one stage leaves the cut and `totalGroups` with only the
18 admitted groups (top five c69, c65, c61, c57, c53), and the uncut
aggregate through the same middleware agrees.
- N3, stdio over the real engine: a 500-value declared list is sent as
the rank and served; a 501-value list is not sent, and the engine
refuses a 501-value rank. Either maximum moving alone goes red.
- The bridge-member tripwires
(`mcp-write-response-internal-fields.tripwire.test.ts`,
`stdio-data-bridge.stored-metadata-body.test.ts`) classify
`aggregateGroups`.
## Acceptance notes
- **Carried from #35186 as the second PR to merge `main`** (rule
6977042103): the limit-only push-down of the declared option order
through `rank`, derived from #35186's `declaredOptionRank` (the
leading-key loop moved into `declaredOptionOrderKeys`, which
`inDeclaredOptionOrder` now calls; the rule is not restated); `groups`
kept on the default path; `totalGroups` kept; the explicit-order CONTROL
pin, which #35186 recorded as NOT MEASURED until both were in;
`currencies` on the cut result.
- **Carried from #35202 as the second PR to merge `main`** (carry note
6980343159): the order-and-cut path labels its served rows through the
same `withLookupGroupLabels`, after the cut; the default path keeps
`groups`, `totalGroups` and the labels; #35202's pins stay green.
- **One spelling.** `groupCount` is gone from the result, the tool text,
the pins and the changeset; the engine outcome, the bridge member's
answer and the driver directive's column field spell it `totalGroups`
too (`totalGroupsColumn`, column `__os_total_groups`). None of these was
released.
- **The rank maximum is mirrored, not imported.** `@objectstack/mcp`
does not depend on `@objectstack/objectql` at runtime, so the tool
carries `ORDER_RANK_MAX = 500` beside a comment naming
`AGGREGATE_ORDER_RANK_MAX`.
- **Out of scope, noted and not filed (reach not measured at a public
door).** The REST grouped-query branch
(`metadata-protocol/src/protocol-data-crud.ts`, the grouped arm) does
not apply `orderBy` on a grouped query and slices `limit` in memory.
- `count(*) over ()` needs MySQL 8 or later. MySQL 5.7 would fail the
statement rather than return a wrong answer.
- **Contract review 6985265817 should-fixes (round 5).** S1: the ranked
column stays among the trailing ascending keys (the first of the
review's two routes); unlisted values still come first under a
descending rank, and the changeset says so (N1). S2: option 1, text
only. S3: pinned, green with no behaviour change. N3: the boundary pin
above. N4: the two `Symbol.for` read-option constants in
`stdio-data-bridge.ts` now sit above `unwrapRows`' docblock. #35199's
`STDIO_LATEST_PER` moved with ours, because it held the same position.
N2 skipped by order.
- Overlap at `5839005b034` (`overlap-check --branch=HEAD`, VERDICT clean
exit 0): `origin/main` (`b02484e13a2`, #35240 landed after the merge and
touches none of this PR's packages) and #34817 merge cleanly. #35225
landed first and is merged in (`dbb2f6805b0`). Its one conflict, in
`packages/mcp/src/stdio-data-bridge.ts`, was resolved keeping both
sides: the two `Symbol.for` read-option constants each under their own
docblock, then #35225's `stdioExpandMap`, byte-identical to main, then
`unwrapRows` under its docblock.
## Verification
Readings at head `5839005b034` (`origin/main` `dbb2f6805b0` merged, with
#35225). The round-5 ablation and the `objectql` and `driver-sql` full
suites were read at `87429381cbc`; that merge changes no code they
exercise. The gate union and the reconciliation are quoted in the dev
report on #35144.
<details><summary>Round 5 ablation: the ranked column in the trailing
keys (S1)</summary>
The engine line `const named = new Set(request.orderBy.filter((k) =>
k.rank === undefined).map((k) => k.field));` was replaced with `const
named = new Set(request.orderBy.map((k) => k.field));` (`node
scripts/ablation-replace.mjs`, blob 0760cdd to the mutation). Then
`@objectstack/objectql` was rebuilt, and `ablation-dist-preflight` found
the marker in 4 built files.
- Red: runtime 1 of 9. The cut answered `won`, NULL, `lost` instead of
`won`, `lost`, `open`, so SQLite really did keep NULL at the boundary.
Also red: objectql 1 of 14 (the directive pin) and stdio 1 of 7 (the
directive pin).
- Restore: blob equals HEAD (0760cdd) and `git diff HEAD` is empty.
After the rebuild, preflight `--absent` exited 0.
- The first attempt was a no-op. Its replacement text already occurred
elsewhere in the file, so the tool refused it and restored, and the run
read green on the pristine build. It was redone with a unique anchor.
</details>
<details><summary>Round 3 ablation: the label call on the order-and-cut
path</summary>
`node scripts/ablation-replace.mjs` replaced `rows: await
labelServed(cut ? groups.slice(0, cap) : groups, fields),` with `rows:
cut ? groups.slice(0, cap) : groups,` in
`packages/mcp/src/mcp-http-tools.ts` (anchor 1 to 0, blob 84c75cd
to 529eafa55eaf; the test imports the source, not `dist/`).
- Red, 1 failed / 42 passed: the new cut-path label pin, and nothing
else.
- Restore: blob after restore equals HEAD (84c75cd), `git diff
HEAD` empty.
</details>
<details><summary>Round 2 ablation (unchanged code): the declared-order
derivation on the limit-only path</summary>
Replacing the `declaredOptionOrderBy` fallback with `orderBy ?? []`
reddened 4 of 40: the three limit-only pins and the stdio rank pin;
restored, blob equals HEAD.
</details>
<details><summary>Round 1 ablations (unchanged code): the order
push-down and the rank arm</summary>
- The order push-down (`for (const key of orderCut.orderBy) {` replaced
with an empty list, rebuilt, preflighted against `dist/`): three driver
pins red; restored, blob equals HEAD.
- The `rank` arm made unreachable (rebuilt, marker in `dist/`): the
driver rank pin and the runtime rank pin red; restored, marker absent,
tree clean.
</details>
<details><summary>Suites and typecheck</summary>
- After a full `pnpm build` (120/120): `objectql`
`src/aggregate-order-cut.test.ts` 14/14; `driver-sql`
`src/sql-driver-aggregate-order-cut.test.ts` 7 passed, 2 skipped (live
Postgres/MySQL cells, unprovisioned); `runtime`
`src/mcp-aggregate-order-cut.test.ts` 9/9; `mcp` stdio order-cut +
aggregation-entry + both tripwires: 4 files, 92 passed. Lock VERDICT 0.
- `mcp` full suite at `5839005b034`: Test Files 77 passed (77), Tests
1400 passed (1400). At `87429381cbc`: `objectql` full suite: Test Files
615 passed (615), Tests 13881 passed (13881). `driver-sql` full suite:
Test Files 263 passed, 13 skipped (276), Tests 4387 passed, 257 skipped
(4644). Each VERDICT command-exit 0.
- Typecheck `objectql`, `driver-sql`, `driver-turso`, `mcp`, `runtime`
(incl. `check:test-typecheck` ledgers): VERDICT command-exit 0.
- `dispatch-gates --commands` at `5839005b034`: 75 families, all exit 0.
`--ran` with exit codes: 75 derived, 75 run, 0 NOT-MEASURED (a derived
zero). `check:query-options-erasure` test surface is 236, at its
ceiling.
- `check-governed-merges --branch HEAD`: NOT governed, 0 of 17 paths,
+2005/-43. `check-platform-checklist --changed-from origin/main`: OK, 29
anchors judged, 0 lost.
</details>
---
_Generated by [Claude
Code](https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8)_
<!-- signed: repo:objectstack#1 · os-warren ·
session_01JQwxbWDsbbJizuYnDwBxT8 -->
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent 00110fd commit 65b67be
17 files changed
Lines changed: 2005 additions & 43 deletions
File tree
- .changeset
- packages
- drivers
- driver-sql/src
- driver-turso/src
- mcp/src
- objectql/src
- runtime/src
- domains
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
| 96 | + | |
| 97 | + | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | + | |
| 103 | + | |
| 104 | + | |
| 105 | + | |
| 106 | + | |
| 107 | + | |
| 108 | + | |
| 109 | + | |
| 110 | + | |
| 111 | + | |
| 112 | + | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
| 164 | + | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
0 commit comments