Skip to content

feat(mcp): aggregate_records orders, cuts and counts groups in the database - #35193

Merged
objectstack-fleet[bot] merged 15 commits into
mainfrom
claude/issue-35144-aggregate-order-cut
Nov 18, 2026
Merged

objectstack-fleet[bot] merged 15 commits into
mainfrom
claude/issue-35144-aggregate-order-cut

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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 字段声明的选项顺序在数据库里排序后再截断(与 feat(mcp): aggregate_records returns select groups in declared option order and names a fixed amount's currency #35186 的无序默认路径同一条规则);固定币种金额在截断结果上同样给出 currencies;按 lookup/主从字段分组时,截断结果与默认路径一样在键旁给出 KEY__label(以调用者权限读取的记录名称,feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller #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 feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller #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), feat(mcp): aggregate_records returns select groups in declared option order and names a fixed amount's currency #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 mcp: the result members the hosted ask tools add over the framework tools are either moved into the framework or stated as hosted-only, one by one #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

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.

Round 5 ablation: the ranked column in the trailing keys (S1)

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 0760cdd6255f 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 (0760cdd6255f) 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.
Round 3 ablation: the label call on the order-and-cut path

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 84c75cdaef65 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 (84c75cdaef65), git diff HEAD empty.
Round 2 ablation (unchanged code): the declared-order derivation on the limit-only path

Replacing the declaredOptionOrderBy fallback with orderBy ?? [] reddened 4 of 40: the three limit-only pins and the stdio rank pin; restored, blob equals HEAD.

Round 1 ablations (unchanged code): the order push-down and the rank arm
  • 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.
Suites and typecheck
  • 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.

Generated by Claude Code

…iver's statement (wip)

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…ver HTTP and stdio; changeset

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…literal refusal codes; alias-clean test imports

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…e order into the cut

An AggregateOrderKey may carry rank, a list of the column's values: the SQL
driver orders by each listed value's position (case ... when ? then i ... end),
every other value after them, before the cut. The bridge typings carry it so a
declared option order read off the served schema can reach the statement.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
@github-actions github-actions Bot added size/xl documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 18, 2026
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 5 package(s): @objectstack/driver-sql, @objectstack/driver-turso, @objectstack/mcp, @objectstack/objectql, @objectstack/runtime, touching 51 documentable anchor(s). ⚠️ 1 changed file(s) yielded no anchor (packages/objectql/src/index.ts), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

43 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json b02484e13a2e43f12d2c942e9a8966ece9cfa31e.

⛔ 12 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 1 changed file(s) yielded no anchor (packages/objectql/src/index.ts) — pages documenting those are invisible to this run
  • 6 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 56 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json b02484e13a2e43f12d2c942e9a8966ece9cfa31e → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 32ac78af08ebaa367bd2ebbf97c9536948275160 — the merge of head 5839005b034da9ceec1329a3e9c288625ca8e717 into base b02484e13a2e43f12d2c942e9a8966ece9cfa31e, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 32ac78af08ebaa367bd2ebbf97c9536948275160 && git checkout 32ac78af08ebaa367bd2ebbf97c9536948275160
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin b02484e13a2e43f12d2c942e9a8966ece9cfa31e 5839005b034da9ceec1329a3e9c288625ca8e717 && git checkout -B drift-repro b02484e13a2e43f12d2c942e9a8966ece9cfa31e && git merge --no-ff 5839005b034da9ceec1329a3e9c288625ca8e717

node scripts/docs-audit/affected-docs.mjs --json b02484e13a2e43f12d2c942e9a8966ece9cfa31e

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs b02484e13a2e43f12d2c942e9a8966ece9cfa31e → pass the list as
args.docs, on the commit named under Which tree this was computed on.

…ate order and cut

Resolves the two conflicts in packages/mcp (mcp-http-tools.ts and the
aggregation-entry test) and carries the agreed items as the second PR to
merge main:

- A limit with no orderBy hands the database the declared option order of
  the leading select/radio group keys, each as an order key's rank, derived
  by the uncut path's own declaredOptionRank (the leading-key reading is
  now one helper, declaredOptionOrderKeys, used by both paths).
- The cut result carries currencies (fixedAmountCurrencies) like the uncut
  one, and keeps groups on the uncut path.
- Seat ruling: the result keeps totalGroups and adds no groupCount; on the
  cut path totalGroups is the statement's count of the groups before the
  cut. The engine outcome, the bridge member and the driver directive spell
  it totalGroups too.
- Pins: the limit-only push-down (tool and stdio engine), the explicit-order
  CONTROL, currencies on the cut result, and no groupCount in a served
  result.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…ds call sends, over a real SQLite database

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
… the aggregate order and cut

Five adjacent-insertion conflicts, each resolved keeping both sides: the
engine exports and the runtime imports of AGGREGATE_ORDER_CUT beside
LATEST_PER (objectql index, runtime action-execution and domains/mcp), the
two Symbol.for read options in the stdio bridge, and the aggregation-entry
test, where the order-and-cut describe block and #35202's lookup-label
block both land after the served-schema block. mcp-http-tools.ts merged
without conflict.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…side its id

An aggregate_records call with orderBy or limit now answers each lookup or
master-detail group key with KEY__label exactly as the default path does:
both paths call one local labelServed closure over withLookupGroupLabels,
applied to the rows served, after the cut, so the name read never covers
the probe row past the cap. Pin: an orderBy+limit call grouped by a lookup
returns the labelled rows, one read for the served ids only.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
…totalGroups, #35179 withheld fields) into the aggregate order and cut

Three adjacent-insertion conflicts, each resolved keeping both sides: the
McpDataBridge members aggregateGroups and #35198's userTextLocales (the
interface in mcp-http-tools.ts and the runtime HTTP bridge in
domains/mcp.ts), and both members in the write-response tripwire roster.
#35179's withheld-field naming applies to query_records and get_record
only and merged without conflict; #35201 touches service-analytics only.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Head for review · 2026-11-18T16:39Z: 32a240bd7c83f803f2537d0bff30c99b4d710979 (round 4, merge-main only over round 3 0b8bbf82a0e; main ec227fc7b18 with #35198, #35201, #35179 merged in, three adjacent-insertion conflicts kept both sides; dev reports 6982922337 and 6984951759 on #35144). Not governed, +1849/-36 over 17 files. Carries the seat ruling 6978086158 (Q2 = C: totalGroups, no groupCount), hand-on 6977042103 and carry note 6980343159 (the cut path labels lookup groups as the default path does). CI at this head still converging (0 red so far); landing waits for green. Fixes #35144. Owed: full L1-b and the seat contract review at this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Contract-review-claim: session_01JQwxbWDsbbJizuYnDwBxT8 · head 32a240bd7c83f803f2537d0bff30c99b4d710979 · 2026-11-18T16:40Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 32a240bd7c83f803f2537d0bff30c99b4d710979
Local-runs: none

Read: card #35144 (its body and all 11 comments, including the claim, the hand-on, seat ruling 6978086158, carry note 6980343159 and the four dev reports), the PR body, the 17-file list, the net diff origin/main...32a240bd7c8 (merge base ec227fc7b18), the PR comments, the head's check-runs, and the round-4 merge's own resolutions (git show --remerge-diff). Code outside the diff was read at the head to judge the diff's claims, and was not reviewed: the engine's aggregate path, the SQL driver's aggregate compiler, the Turso driver, the aggregate_records handler with its helpers, both bridges with callData's aggregate arm, the security middleware's aggregate input gate, and withLookupGroupLabels.

① Derived judgments

  • aggregate_records accepts orderBy (up to 8 { field, order } entries) and limit (a whole number from 1 to the row cap). Right. Before this PR, the strict top-level door refused both keys as undeclared, so this widens the tool and refuses nothing it used to accept. The tool asks for limit + 1 groups, so truncated reports a fact. An orderBy with no limit is cut at the cap and says so. These behaviours are pinned.
  • New aliases: sort, sortBy, order and order_by map to orderBy; top, take and pageSize map to limit. Right. None of these names was taken on main. A scalar sent under order fails the array shape and is refused, so it is never misread.
  • The cut result is { rows, totalGroups, truncated?, currencies? }. Right, and it matches seat ruling 6978086158 (Q2 = C). totalGroups keeps its published meaning, the number of groups before the cut. On the cut path the statement's own count(*) over () answers it. No groupCount appears in the result, the tool text, the changeset or the PR body, and the pins assert that it is absent on both paths.
  • The new refusals appear only on the new inputs. Right. They are: NOT_IMPLEMENTED/501 for a bridge without the member; INVALID_QUERY/400 for a driver not on the compiling list, an aggregate computed in memory, a having, or a relation group; INVALID_SORT/400 for an order key that names no column of the aggregated row; and INTERNAL_ERROR/500 for rows that come back without the count. Each one is raised before the driver is asked, or before rows are served.
  • A call without the new arguments behaves exactly as on main. Right. The default path's inline label call moved into the labelServed closure with the same arguments, and the served-schema read still happens after the aggregate. The diff shows no other change on that path.
  • @objectstack/objectql exports AGGREGATE_ORDER_CUT and the AggregateOrderCutRequest, AggregateOrderKey and AggregateOrderCutOutcome types. Right. The option is a Symbol.for read option, so no JSON body or tool argument can carry it. The caller cannot supply rank either: the tool's orderBy entry drops any key it does not declare.
  • engine.aggregate serves the request only from inside executeWithMiddleware. Right. It uses the ast that composeReadableIdsAtBoundary returns and the same aggregateOptions that the default native call uses. So the cut, the window count and the default path read the same rows under the same read filter, tenant wall and field gate. The order keys can name only columns of the aggregated row, which means aggregation aliases or group projections that the field-level input gate has already judged. totalGroups therefore counts only groups formed from rows the caller may read. The structure is right. Its pin is S3.
  • driver-sql wraps the grouped statement as a derived table, then applies count(*) over () and ORDER BY/LIMIT over the derived table's columns. Right. NULLs rank last. An identity-folded measure (sum or a count) ranks as the 0 it is served as. Unnamed group keys break ties ascending. A key that names an unprojected column, or a malformed directive, is refused before the statement runs. The pins cover the statement, the tenant wall plus where, NULLs, the identity and rank.
  • The Turso driver's remote face refuses the directive. Its local and replica faces inherit the SQL driver. Right. The engine checks drivers against a named list (com.objectstack.driver.sql, com.objectstack.driver.sqlite-wasm, and Turso only when transportMode is local or replica), and that list matches the drivers' own name and transportMode members. A driver missing from the list is refused, never served uncut.
  • McpDataBridge.aggregateGroups is a new optional member. Right. Both implementers in the repo carry it, and the long-lived stdio wiring (bridgeDataTools) passes the bridge through unchanged. A bridge without the member keeps compiling and keeps serving aggregate_records, and the tool answers 501 for the new arguments. Both member-roster tripwires classify it.
  • callData's aggregate arm returns totalGroups only when the in-process symbol is set, and refuses with a 500 when the engine does not report that the cut was served. Right. Everything that runs before it still runs on both paths: the aggregation requirement, the relation-target exposure check and the internal-field door. The stdio bridge also runs the cut through the same runAggregate gates: the exposure whitelist, the relation-target exposure and the stored-metadata body and hash refusals.
  • Select-option order on a limit-only call: right. Both paths derive it from one helper, declaredOptionOrderKeys, over declaredOptionRank, so the rule is not restated. The cut path sends it as rank keys, which the database takes before the cut. A caller's own orderBy reaches the bridge unchanged, and the explicit-order CONTROL pin shows it. Ties among undeclared values are S1.
  • Currency: right for fixed-mode amounts. fixedAmountCurrencies is on the cut result, as on the uncut one, and is pinned. Record-mode ranking is S2.
  • Lookup-group labels: right, and carry 6980343159 is met. The cut path calls the same withLookupGroupLabels through labelServed, with the same read-admission check (readGuard), on the rows served after the slice. The probe group is never labelled. One pin was added, and the label pins from feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller #35202 remain in the file.
  • Round-4 merge resolutions keep both sides. Right. The remerge diff shows three conflicts, all adjacent insertions: the bridge interface in mcp-http-tools.ts, the runtime HTTP bridge in domains/mcp.ts, and the write-response tripwire roster. Each kept both aggregateGroups and feat(mcp): a refused record read says what is not recorded, in the caller's language #35198's userTextLocales, with no hunk dropped from either side.

② Semver level

  • The changeset gives patch to each of the five packages the diff moves: @objectstack/mcp, @objectstack/objectql, @objectstack/driver-sql, @objectstack/driver-turso and @objectstack/runtime. That matches AGENTS.md: a non-protocol widening ships patch. Nothing under packages/spec changes.
  • Metadata-protocol: none is right, because there is no authorable metadata key, value or type.
  • Clause-②: yes (widening: ...) is line-initial in both the PR body and the changeset, and it matches what the diff publishes. The diff adds two accepted tool arguments, aliases, an optional bridge member and an engine export, and refuses nothing that was accepted before. Following ruling 6978086158, the line no longer names groupCount, which is right.

③ Boundary flags

Findings

  • S1 (should-fix) — A rank key does not order the values it leaves unlisted.
    • The engine appends only the group columns that the request does not name as ascending tie-breaks. A column named by a rank key is therefore excluded. In the driver, every value missing from the list falls into one else n arm and gets no ordering of its own.
    • Result: on a limit-only call over a select key whose data holds two or more undeclared values (a NULL among them), the order among those groups is not deterministic, and nor is which of them survives a cut at the boundary. This breaks the engine module's own claim that "two runs of one request answer the same groups in the same order". The driver's descending rank pin asserts only membership for that bucket.
    • Fix: keep a rank-keyed column in the trailing ascending tie-break (NULL last), or emit the column's own null-last ascending order right after the rank arm. Add a pin with two undeclared values at a cut boundary.
  • S2 (should-fix) — Ordering by a record-mode amount ranks bare numbers across currencies.
    • The engine admits such a measure only when it is grouped by its currency-code field, so each row carries its code. Even so, the database ranks the bare numbers across currencies and cuts by them. A "top N by amount" over mixed currencies keeps the largest numbers, not the largest amounts, and drops the other groups without saying so. Before the cut, every group came back and could be compared by hand.
    • Fix, in increasing strength:
      1. State the rule in the tool description: rank a record-mode amount inside one currency, by filtering on the code field.
      2. Or refuse an order key over a record-mode amount alias unless where pins one currency.
    • Add a pin for whichever is chosen.
  • S3 (should-fix) — The cut path has no pin that a read filter injected by middleware narrows both the cut and totalGroups.
    • The runtime end-to-end cells run as a system context. The driver cell covers the tenant wall and where, but no middleware-injected read scope.
    • The structure is right (see ①), and the new tool text advertises row-level security on this path, so the claim should be measured.
    • Fix: add one engine-level or runtime-level pin where a registered read middleware narrows ast.where, showing that the cut rows and totalGroups count only the admitted groups.
  • N1 (nit) — The changeset says "A NULL ranks last in either direction", and its rank bullet says unlisted values rank "after" the listed ones. Under a descending rank key, both the unlisted values and the NULL come first; the driver pin shows this. The tool sends only asc, so the problem is latent. Correct the wording, or keep unlisted values last regardless of direction.
  • N2 (nit) — The orderBy entry is an open z.object. An undeclared entry key is silently dropped, not refused, whereas the aggregations entries are closed at the producer (spec/rest: the query door's aggregation entry still strips an undeclared key, while MCP's aggregate_records now refuses it by name (#28550) #28609). A caller-supplied rank is dropped either way, which is safe.
  • N3 (nit) — ORDER_RANK_MAX = 500 mirrors the engine's AGGREGATE_ORDER_RANK_MAX, but no pin ties the two values together, so drift would go undetected.
  • N4 (nit) — In stdio-data-bridge.ts, STDIO_AGGREGATE_ORDER_CUT sits between unwrapRows' docblock and the function, which leaves that docblock on the constant. The dev flagged this in round 3. Moving the constant above the docblock fixes it.

SQL push-down (AGENTS.md Prime Directive 5)

  • The ordering, the cut and the group count run in one statement and one round trip: a derived table, a window count, ORDER BY and LIMIT, with the probe group as one extra row of the same statement.
  • No in-memory fallback exists. Every path the database cannot serve is refused before the driver is asked, and named: other drivers, the in-memory tier, having and relation groups.
  • Beyond the aggregate, the call reads the served schema once per call. Labels come from one batched read per referenced object, for the served ids only (feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller #35202's existing shape).
  • No query runs per row or per group. No finding.

Answers to the dev reports

  • Round-1 open_questions:
  • Hand-on items:
    • The explicit-order CONTROL pin: present.
    • currencies on the cut: present and pinned.
    • The rows: conflict: superseded by Q2 = C, with no groupCount.
  • Carry note 6980343159: met (see ①).
  • Deviations:
    • Round 1 (4), MySQL 8 or later for the window: accepted. On MySQL 5.7 the statement fails loudly and never returns a wrong answer, driver-sql already relies on window functions (latest-per), and the changeset states the requirement.
    • Round 2 (1), the Clause-② line rewritten to the ruling: correct.
    • Round 2 (3), unreleased internals renamed to totalGroups: accepted.
    • Round 3 (2), the labelServed closure: accepted, because it preserves the default path's behaviour.
    • The rest (vitest flag pass-through, trailer pair, single push, gate-union rerun, PR-body head notes) are process. None changes the contract.
  • out_of_scope_findings:
    • The REST grouped-query arm (orderBy ignored, limit sliced in memory) is escalated to the seat. As reported, it is a Prime Directive 5 and Prime Directive 10 candidate with "carrier: none". It needs a measured repro and a card, or a recorded reason not to file one. It was not read here because it is outside this review's inputs.
    • The objectstack-ask SKILL.md follow-up is escalated to the seat to give it a carrier card.
    • The unwrapRows docblock placement is N4.
  • security_findings: none is consistent with this read. The cut path reads as the caller through the same read admission, read scope and field gate as the default path, and it serves no group, count or label that the default path would not.

Gates (check-runs at the head, read once at 16:47Z without waiting)

  • 25 success, 18 skipped, 0 failed.
  • Still in_progress, with no verdict yet: Build Core, Test Core 1/10 to 10/10, and Type Check · workspace.
  • This PASS is the contract record. Landing still waits for those 12 runs to turn green.

No must-fix. Should-fix: S1, S2, S3.

Implemented-by: claude/issue-35144-aggregate-order-cut
Reviewed-by: area o1-C isolated reviewer (sub-agent of session_01JQwxbWDsbbJizuYnDwBxT8)

VERDICT: PASS

… should-fixes

Contract review S1: a column named by a rank key now stays among the
directive's trailing ascending keys (NULL last), so the values the rank
does not list, which share one rank, keep a deterministic order and a cut
among them answers the same groups on every run. Pinned over real SQLite
in runtime (two unlisted values and a NULL at a cut boundary, same answer
twice, the tie-break in the statement); the engine and stdio directive
pins now show the ranked column among the trailing keys.

S2: the aggregate_records description states that a per-record-currency
amount ranks by bare numbers across currencies and says to rank inside one
currency by filtering on the currency code field; pinned in tools/list.

S3: a runtime pin with a registered read middleware narrowing ast.where:
the cut rows and totalGroups count only the admitted groups, the uncut
aggregate agreeing.

N1: the changeset, the engine docblocks and the driver comments say what a
rank does in each direction and how the unlisted values order. N3: a pin
measures the tool's rank maximum against the engine's at the boundary
(500 sent and served, 501 not sent and refused). N4: the stdio read-option
constants sit above unwrapRows' docblock. The changeset also names
KEY__label on the cut answer.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
The engine call in the boundary pin passes a typed query and spells the
symbol read option as a deliberate off-contract cast, so the
query-options-erasure test surface stays at its ceiling (236).

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Head for delta review · 2026-11-18T18:24Z: 3eca62301806c15866bb0bb6dc5fbafd91af9061 (round 5, delta 32a240bd7c83..3eca62301806: answers contract review 6985265817 S1 (a rank-keyed column stays in the trailing ascending tie-break, NULL last), S2 (option 1: the tool description states the per-record-currency ranking rule; no refusal), S3 (runtime pin with a read middleware narrowing the cut and totalGroups), N1 (changeset wording, now also naming the lookup KEY__label on the cut answer), N3 (boundary pin tying the two rank maxima), N4 (constant placement); N2 skipped; dev report 6987634040 on #35144). Not governed, +2005/-43. CI converging. Fixes #35144. Owed: L1-b delta and the seat contract review delta, then landing.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Contract-review-claim: session_01JQwxbWDsbbJizuYnDwBxT8 · head 3eca62301806c15866bb0bb6dc5fbafd91af9061 · 2026-11-18T18:25Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 3eca62301806c15866bb0bb6dc5fbafd91af9061
Local-runs: none

This is a DELTA review over PASS record 6985265817 at 32a240bd7c83f803f2537d0bff30c99b4d710979. Everything that record judged and the delta does not touch stands as it was judged there.

Read: record 6985265817, head note 6987666833 on this PR, dev report 6987634040 on card #35144, the PR body at this head, the delta 32a240bd7c8..3eca6230180 (two commits, 9 files, +205/-56), and the head's check-runs. Code outside the delta was read at the head to judge the delta's claims, and was not reviewed: the rest of the engine's order-cut module (the shape check and its rank limit), the SQL driver's order-cut statement builder, and the tool's declared-option rank helpers (declaredOptionOrderKeys, declaredOptionOrderBy, inDeclaredOptionOrder). The dev report and head note cite a review addendum for N3 and the changeset's KEY__label clause. That addendum is not among this review's inputs, so both are judged against the code only.

① Derived judgments

  • S1 is closed. Right. In aggregateOrderCutDirective, the only behaviour change in the delta, a column named only by a rank key no longer counts as named. It therefore stays among the trailing ascending keys, and the driver orders a trailing key null-flag first, then by value, so NULL comes last. Every group column now appears in the full order as a plain key, which makes the order total on every path, the ranked bucket included. Two runs of one call answer the same groups, and the module's own determinism claim holds again.

    • The pin would go red without the fix. The runtime real-SQLite cell cuts inside the unlisted bucket and asserts the cut membership, the same answer on a second run, the full order with NULL last, and the statement's null-last ascending tie-break after the CASE. The engine and stdio directive pins assert the ranked column among the trailing keys.
    • The dev ablated the one engine line. On the second, valid attempt, all three pins went red, and the runtime cell's received order shows SQLite really did keep a NULL group inside the cut. The dev reports the first attempt as a no-op that read green, and says so. That disclosure is right.
  • Deviation (3): with several group keys, the ranked column joins the trailing keys in groupBy order. Accepted. The tool sends rank keys only for a leading run of option keys (declaredOptionOrderKeys stops at the first key that is not one), so no unnamed key ever precedes a ranked one on the tool's path. Determinism does not depend on the position, because every group column is in the order. With two or more leading rank keys, the wording is slightly too broad (nit n1).

  • S2 is closed by option 1, the seat's choice. Right. The aggregate_records description now states that ranking a per-record-currency amount compares bare numbers across currencies, and that the ranking belongs inside one currency, filtered by where on the code field. No refusal was added, so nothing accepted before is refused. The tools/list pin matches the exact sentence, so it goes red if the sentence is removed or changed. The changeset gains a matching bullet.

  • S3 is closed. Right. A runtime real-SQLite describe block registers a read middleware that narrows ast.where. It asserts that the cut rows and totalGroups count only the admitted groups, that one grouped statement carries the window, and, in a CONTROL, that the uncut aggregate through the same middleware agrees. The pin discriminates: if the cut read the pre-middleware AST, both the cut's members and totalGroups would differ from the asserted values. The CONTROL also proves that the middleware itself takes effect, so the cell cannot pass because of a middleware that never runs. There is no code change, consistent with record 6985265817 finding the structure right.

  • N1 is closed. Right. The changeset, the engine docblocks, the driver comments and the PR body now say what the driver does:

    • On a key without a rank, NULL ranks last in either direction.
    • Under a rank, every unlisted value, NULL included, shares one rank past the listed values. So the unlisted values come after the listed ones under an ascending rank and before them under a descending rank.
    • Inside that bucket, the trailing ascending keys order the values, NULL last, in both directions.

    These statements match the CASE arm (else n, with order applied over the ranks) and the trailing-key arm in the driver.

  • N3 is closed, with a behavioural pin instead of an export (deviation 2). Accepted. Exporting AGGREGATE_ORDER_RANK_MAX would publish a new engine export, and this round was not ordered to make that change. The stdio-over-real-engine cell covers both sides of the boundary:

    • A declared list at the limit is sent as a rank and served.
    • One value past the limit, the tool sends no rank, and the engine refuses that rank before the driver is asked.

    Each one-sided drift goes red: the tool raising or lowering its limit alone, or the engine doing so alone. The refusal arm asserts only the code and status (nit n2).

  • N4 is closed. Right. Each Symbol.for constant in stdio-data-bridge.ts now carries its own docblock, and unwrapRows carries its own. Deviation (1), moving feat(mcp, objectql, driver-sql): query_records latestPer, each X with its latest Y in one call #35199's STDIO_LATEST_PER with ours, is placement only: the value and spelling are unchanged. The conflict this move creates with the draft feat(mcp): query_records expand and get_record related, every reached object judged by the read guard #35225 is an adjacent insertion, a landing-order matter rather than a contract matter.

  • Nothing else in the delta changes behaviour.

    • The driver hunks are comments.
    • The tool hunk is one description sentence.
    • The second commit types the N3 pin's engine call. The query-options-erasure surface is back at its ceiling, and its CI lane is green.
    • The test harness refactor (boot and a def parameter on makeStdio) is test-only.
  • The changeset's new KEY__label clause matches the code that record 6985265817 judged. The cut path labels lookup and master-detail group keys through the same label helper, reading as the caller, on the served rows only. N2 was skipped as ordered.

  • Read-as-caller is not weakened. The only new order key is a group column the statement already projects and the field gate has already judged. The delta adds no read, column, label source or count path. The row filter, totalGroups and labels reach the cut exactly as before, and S3 now measures the row filter and totalGroups.

② Semver level

  • The changeset frontmatter is unchanged: patch for @objectstack/mcp, @objectstack/objectql, @objectstack/driver-sql, @objectstack/driver-turso and @objectstack/runtime. The delta moves no other package and touches nothing under packages/spec. Patch is still right.
  • Clause-②: yes (widening: ...) is unchanged and line-initial in both the PR body and the changeset. The delta adds no argument, alias, member or export, and refuses nothing it used to accept. It adds one description sentence and wording, so the line still matches what is published. Metadata-protocol: none stands.

③ Boundary flags

Findings

  • n1 (nit) — The changeset's rank bullet says that among themselves the unlisted values "follow the column's own ascending order, NULL last". The engine module docblock says they follow "the trailing ascending keys". Both are exact for one ranked key, which is the common case. When the tool sends two or more leading rank keys, groups that share an unlisted value of the first key are ordered first by the next key's rank, and only then by the column's own value. The order stays total and the cut stays deterministic. Suggested wording: "groups the rank does not tell apart fall to the next key, and finally to the column's own ascending order, NULL last". The AggregateOrderKey docblock already says this.
  • n2 (nit) — The N3 cell's engine-refusal arm asserts INVALID_QUERY/400, a pair that every shape refusal in that module shares. The served at-limit arm uses the same driver and shape, so in practice the rank limit is the only difference. Asserting that the message names the rank's bound would tie the red to the maximum explicitly.
  • n3 (nit) — The PR body's test list keeps round-4 counts: "(6)" for the runtime and stdio files, which now hold 9 and 7 cases. The Round-5 sub-list names the additions, so nothing is hidden.
  • Carried from record 6985265817 and unchanged by this delta: N2, which was skipped as ordered.

SQL push-down (AGENTS.md Prime Directive 5)

  • The delta adds one ORDER BY term to the same single statement: the derived table, the window count, ORDER BY and LIMIT. It adds no round trip, in-memory ordering, id materialisation or per-group query. No finding.

Answers to the dev report (6987634040)

  • open_questions: none.

  • security_findings: none is consistent with this read (see ①, read-as-caller).

  • Deviations:

    • (1) Both constants moved: accepted.
    • (2) Behavioural N3 pin: accepted.
    • (3) Ranked column in groupBy order: accepted; wording nit n1.
    • (4) The typing commit: accepted; it is test-only.
    • (5) The main fetch ran together with the push: process, and the dev reports that the moved main merges cleanly and touches none of this PR's packages.
    • (6) The trailer pair: process.

    None of these changes the contract.

  • out_of_scope_findings are unchanged from round 4 and are already escalated to the seat by record 6985265817: the REST grouped-query arm, and the objectstack-ask SKILL.md follow-up.

Gates (check-runs at the head, read once at 18:27Z without waiting)

  • 54 runs: 20 success, 18 skipped, 0 failed.
  • Still in_progress, with no verdict yet: Build Core, Test Core 1/10 to 10/10, Lint · CI, release & engine gates, Lint · docs & code guards, Type Check · consumer gates, Type Check · debt ledger, and Type Check · workspace.
  • This PASS is the contract record. Landing still waits for those 16 runs to turn green.

No must-fix, no should-fix.

Implemented-by: claude/issue-35144-aggregate-order-cut
Reviewed-by: area o1-C isolated reviewer (sub-agent of session_01JQwxbWDsbbJizuYnDwBxT8)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbXr9wLAH24MEgxaLud

席位核对

L1 full · ACCEPT · Head-sha: 3eca62301806c15866bb0bb6dc5fbafd91af9061 · card #35144 (Fixes #35144) · full read at 32a240bd, held while round 5 answered the contract review, then the delta 32a240bd..3eca6230 read · read 2026-11-18T19:01Z

Net diff at 32a240bd against merge base ec227fc7b18: 17 files, +1849 / -36. aggregate_records gains orderBy and limit. The order, the cut and the count of groups before the cut are all taken in the one SQL statement that groups, and every other path is refused.

Against the card

  • Fixes is right. Seat ruling 6978086158 Q1 split the card's query_dataset line to query_dataset: say how many groups existed before the limit cut (totalGroups), as aggregate_records does #35194, so this PR carries the rest of the card. The merge should close it.
  • Done when. "A top-N question over more groups than the row cap returns exactly N groups, in order, with the total number of groups, and a pin shows it."
    • The stdio pin asks for the top five of 80 groups and gets exactly 5, in order, with totalGroups 80 and truncated.
    • The runtime pin runs over a real engine, SQL driver and SQLite: the top five of 70, with totalGroups 70. It also reads the statement and finds ORDER BY, LIMIT and the window count in it.
  • The card's key name. The card says groupCount. Ruling Q2 = C keeps the published totalGroups with the same meaning, the groups before the cut. groupCount is absent from the result, the tool text, the pins and the changeset, and a CONTROL pin checks that.
  • "Refuses with a stable code, never a slower path built for parity." Held. Each of these is refused INVALID_QUERY/400 before the driver is asked: a driver not on the compiling list, Turso's remote face, an aggregate the engine would compute in memory, a having, and a relation group. There is no in-process sort or slice of an uncut list on any path.
  • Carried items.
    • Hand-on 6977042103: a limit-only call pushes the declared option order down as rank keys, read by the one helper both paths call. The explicit-order CONTROL is pinned. currencies is on the cut answer.
    • Carry note 6980343159: the cut path labels its served rows through the same withLookupGroupLabels, after the cut, so the probe group is never read. feat(mcp): aggregate_records names a lookup group's record beside its id, read as the caller #35202's pins are unchanged and one cut-path label pin is added.

Read at the head

  • Engine (aggregate-order-cut.ts, engine-delete-and-aggregate.ts).
    • The request rides a Symbol.for read option, so no wire request or JSON body can set it. callData and the stdio bridge pass it only from the in-process tool.
    • The request's shape is judged after every door has judged the query. An order key may name only a column of the aggregated row, which is one of the caller's own aggregation aliases or group-key projections. So ordering exposes nothing the aggregate does not already answer, and the INVALID_SORT message lists only those names.
    • The cut is judged on the same composed AST and under the same driver options as the native path, after scope and middleware. It returns before the uncut paths.
    • The count is taken off the rows and checked: it must be an integer, the same on every row and not smaller than the row count. Otherwise the answer is a 500 and no rows are served. Zero rows means zero groups.
  • SQL driver.
    • The grouped builder becomes a derived table. It keeps its tenant scope and where, and inherits the transaction.
    • The window count is evaluated before ORDER BY and LIMIT, so it counts the groups before the cut.
    • asc/desc and the finite identity are the only values interpolated into the statement. Rank values are bound.
    • The driver checks the directive again: an unprojected order column, or a count column that collides with a projected one, is a 500 before anything runs.
  • The doors.
    • The runtime's aggregateGroups takes the same callData aggregate arm as aggregate. That covers the relation-target refusal and the internal-field refusal, and it reaches the engine through the security middleware.
    • The stdio member runs the same runAggregate closure as aggregate, with every gate it runs.
    • Both read the engine's outcome back and refuse a read that comes back without it.
    • The tool's orderBy item schema has only field and order, so a caller cannot send rank. limit is at most the row cap. One probe group past the cap makes truncated a fact.
  • Published text. connect-mcp.mdx, natural-language-queries.mdx, the mcp README and the ask skill each describe aggregate_records without claiming that it has no order or limit, so none becomes false.
  • Changeset, read sentence by sentence. It is one file, five packages, all patch. Clause-②: yes (widening) is right: there are new arguments and aliases, and no reply loses a key. Metadata-protocol: none is right: what an author can write is unchanged. Each refusal, ranking rule and default it states matches the code and a pin. No changeset already on main is edited.
  • Merges cleanly onto origin/main ad15579576.
  • Check-runs at this head: 57 in total, all completed, none failed (39 success, 18 skipped).

Round 5 delta (32a240bd..3eca6230, 9 files, +205 / -56)

  • S1 is closed. A column ordered only by a rank stays among the trailing ascending keys, with NULL last. Values the rank does not list now keep an order of their own, so a cut among them answers the same groups on every run. The engine pin and the stdio pin both show the ranked column in the directive's tail, and a runtime pin over SQLite runs the same cut twice.
  • S2 is closed (description). The tool text says an amount whose records each carry their own currency is ranked by bare numbers, and that ranking inside one currency means filtering where on its currency code field. The changeset says the same, and a pin holds the sentence.
  • S3 is closed. The new runtime pin registers a read middleware that narrows where over a real engine and SQLite. The cut rows and totalGroups count only the admitted groups (18), and a CONTROL through the same middleware answers the same 18 uncut. It is green with no behaviour change, as expected from the cut being taken on the composed AST.
  • N1 is closed, along with my changeset nit. The NULL and unlisted-value sentences now hold under either direction. The changeset now names KEY__label on the cut answer beside currencies.
  • N3 is closed, along with my rank-maximum nit. The stdio pin measures both bounds over a real engine. At 500 declared options the tool sends the whole rank and the engine serves it. At 501 the tool sends no rank, and the engine refuses a 501-value rank directly. If either value moves alone, the pin goes red.
  • N4 is closed. Both Symbol.for constants now sit above unwrapRows' docblock, which is back on its function.
  • My other two nits. The REST grouped arm stays noted and not filed. The ask-skill line is carried by Ask skill: teach withheldFields and top-N aggregate (orderBy, limit, totalGroups) #35191. Both are fine under the no-new-cards word.

Nit (does not block)

Not mine, still owed before landing

  • Contract review at this head (claim 6987678357).
  • Landing after that, through the seat.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Landing · 2026-11-18T19:03Z · head 3eca62301806c15866bb0bb6dc5fbafd91af9061 (round 5)

Probe Reading
L1 ACCEPT 6988574149 at this head (full read with the round-5 delta folded in)
Contract review PASS 6985265817 at 32a240bd7c83 (S1-S3), delta PASS 6987793676 at this head (S1-S3, N1, N3, N4 closed; no must-fix, no should-fix)
CI on head 39 success, 18 skipped, 0 red
check-governed-merges NOT governed, +2005/-43
K (first-parent behind main) 6

Status: ready + auto-merge. Fixes #35144. Carried: seat ruling 6978086158 (Q2 = C), hand-on 6977042103, carry note 6980343159. The ask-skill ranking line stays with #35191. Overlap: #35225 also edits packages/mcp/src/stdio-data-bridge.ts; it merges main after this lands.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 18, 2026 19:03
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 18, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 18, 2026
…e order and cut

One conflict, in packages/mcp/src/stdio-data-bridge.ts, resolved keeping
both sides: the two Symbol.for read-option constants (this branch's
STDIO_AGGREGATE_ORDER_CUT and #35199's STDIO_LATEST_PER), each under its
own docblock, then #35225's stdioExpandMap byte-identical to main, then
unwrapRows under its own docblock. mcp-http-tools.ts and runtime
domains/mcp.ts merged without conflict.

Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbXr9wLAH24MEgxaLud

席位核对

L1 delta · ACCEPT · Head-sha: 5839005b034da9ceec1329a3e9c288625ca8e717 · card #35144 (Fixes #35144) · delta 3eca6230..5839005b, a merge of main only (with #35225) · read 2026-11-18T20:41Z

What the delta changes

  • Every file but one is unchanged. I compared each file's net diff against its own merge base at both heads (git patch-id --stable, at ec227fc7b18..3eca6230 and dbb2f6805b0..5839005b). 16 of the 17 files are identical. The only one that differs is packages/mcp/src/stdio-data-bridge.ts.
  • That file's one conflict (git show --remerge-diff 5839005b) sat beside feat(mcp): query_records expand and get_record related, every reached object judged by the read guard #35225's stdioExpandMap, and both sides are kept. The two Symbol.for read-option constants, STDIO_AGGREGATE_ORDER_CUT and STDIO_LATEST_PER, now each sit under their own docblock, above stdioExpandMap. stdioExpandMap is byte-identical to main: I hashed the function at origin/main and at this head, and the hashes match. unwrapRows is directly under its own docblock again. The rest of the file's net diff is the same runAggregate / aggregateGroups change I read at 3eca6230.
  • No behaviour moved. The resolution only reorders declarations. No line of stdioExpandMap, runAggregate or aggregateGroups changed.

Read at the head

  • My verdict 6988574149 carries for everything else.
  • Merges cleanly onto origin/main b02484e13a.
  • Check-runs at this head (20:41Z): none has failed so far. 14 are success, 18 skipped, and 22 are still running. Landing waits for green, which is the seat's to read.

Not mine, still owed

  • CI green at this head, then landing through the seat.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Contract review

Served-tier: TIER_DEFAULT
Head-sha: 5839005b034da9ceec1329a3e9c288625ca8e717
Local-runs: none

This is a DELTA review over PASS record 6987793676 at 3eca62301806c15866bb0bb6dc5fbafd91af9061. The new head is a two-parent merge: the old head and dbb2f6805b0 (an ancestor of origin/main, carrying #35225 and seven other main commits). Everything 6987793676 judged stands unless this delta touches it. The merge claim was verified from git objects, not trusted.

① Derived judgments

  • Net diff vs main is unchanged on 16 of 17 files. I compared each head's diff against its own merge base with origin/main: ec227fc7b18 for the old head, dbb2f6805b0 for the new one. Both diffs name the same 17 files, with the same +2005/-43. git patch-id --stable matches per file on all 16 files other than the stdio bridge. So the PR's own change lands on the new base byte-for-byte as it was reviewed.
  • On the stdio bridge, the only difference is placement. Right. The diff of the two net diffs differs only in where the existing Symbol.for read-option constant from main sits. It now sits next to this PR's constant, both above the expand helper, each under its own docblock. Before, it sat between the row-unwrap docblock and its function. The other hunks of that file differ only in their line-offset headers. The constant's spelling and value are unchanged. The file declares each constant and each helper exactly once, and has no conflict markers.
  • feat(mcp): query_records expand and get_record related, every reached object judged by the read guard #35225's expand helper is byte-identical to main. Its extracted body hashes the same at dbb2f6805b0, at the current origin/main tip b02484e13a2 and at the new head. --remerge-diff shows the one conflict resolved by keeping both sides, as the merge message says. The resolution also restores the row-unwrap docblock next to its own function, which closes on main the stray-docblock defect that N4 had already fixed on this branch.
  • No interaction with this PR's behaviour. Main's changes to the three files that both sides touch (the HTTP tool module, the stdio bridge and the runtime MCP domain) add read-side expand and related handling. They do not touch the aggregate path, the order-cut option or the row unwrapping it uses. The runtime hunk forwards expand on the query read only.

② Semver level

  • Unchanged. The changeset file's patch-id is identical: patch for the same five packages, with the same Clause-②: yes (widening) line. The merge adds nothing to this PR's published surface. Main's additions belong to main's own changesets.

③ Boundary flags

  • The delta brings no new dev flags or open questions. The nits n1 to n3 and the carried N2 from 6987793676 stand as they were.
  • SQL push-down: the delta adds no read, statement or in-app join to this PR's path. No finding.
  • Gates: check-runs at the new head, read without waiting at about 20:41Z: 54 runs, 15 success, 18 skipped, 0 failed, 21 still in_progress with no verdict yet. Those include Build Core, Test Core 1/10 to 10/10, the Type Check lanes and most Lint lanes. This PASS is the contract record. Landing still waits for those runs to turn green.

No must-fix, no should-fix.

Implemented-by: claude/issue-35144-aggregate-order-cut
Reviewed-by: area o1-C isolated reviewer (sub-agent of session_01JQwxbWDsbbJizuYnDwBxT8)

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-warren · session_01JQwxbWDsbbJizuYnDwBxT8

Landing · 2026-11-18T21:15Z · head 5839005b034da9ceec1329a3e9c288625ca8e717 (round 6, merge-main only after #35225 landed first and the 19:04Z enqueue went dirty)

Probe Reading
L1 ACCEPT 6988574149 at 3eca6230; round-6 delta ACCEPT 6991038702 at this head
Contract review PASS 6985265817 at 32a240bd, delta PASS 6987793676 at 3eca6230, merge delta PASS 6991049449 at this head (16 of 17 files patch-id equal; the one conflict reorders declarations only)
CI on head 39 success, 18 skipped, 0 red
check-governed-merges NOT governed, +2005/-43
K (first-parent behind main) 2

Status: ready + auto-merge. Fixes #35144. Supersedes landing record 6988602710.

@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 18, 2026
Merged via the queue into main with commit 65b67be Nov 18, 2026
57 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-35144-aggregate-order-cut branch November 18, 2026 21:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/xl tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mcp: aggregate_records can order and cut its groups and says how many groups there were

2 participants