Skip to content

fix(objectql,service-analytics): query_dataset's ObjectQL face cuts its top-N in the database - #35728

Merged
os-zhuang merged 4 commits into
mainfrom
claude/area-a4C-35287
Nov 20, 2026
Merged

os-zhuang merged 4 commits into
mainfrom
claude/area-a4C-35287

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Elon · project thread
Fixes #35287
Clause-②: yes
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:用问数工具查「前 N 名」时,数据存在 SQL 数据库里的对象只读回前 N 组,不再整表分组读回再在内存里截;按文字排序时前 N 名由数据库的排序规则决定(空值排最后),与原生 SQL 路径和聚合记录工具一致。
  • 为什么做:属于「MCP 二期与问数」专题的 SQL 优先目标,大分组只为返回几行却整组读出的浪费由此消除。
  • 出错会怎样:最坏是文字排序的前 N 名在大小写、标点上与以前不同;内存库、MongoDB、OData 和按显示名排序的查询走原路不变;可直接撤回。
  • 要你做什么:无。

What changes

Arm A of the maintainer's ruling on this card (「A 交给数据库排序(推荐)」, ruling record 7023449707), with the riders in 7023599246 as acceptance.

  • @objectstack/objectql (aggregate-order-cut.ts, engine-delete-and-aggregate.ts): an AGGREGATE_ORDER_CUT request may set declinable: true. Where the cut cannot be served (aggregateOrderCutRefusal: a driver that compiles none, an aggregate computed in memory, a having, a relation group join) the engine then reads nothing, answers [], leaves outcome unset and records the reason on a new declined slot. Without the flag nothing changes: aggregate_records keeps its 400. The "Refused, never approximated" docblock is amended to say who declines and who is refused. The decline is a separate optional slot rather than a new arm of AggregateOrderCutOutcome, so the published outcome type is unchanged and the three existing callers (runtime action-execution.ts, runtime domains/mcp.ts, mcp stdio-data-bridge.ts) were reviewed and need no edit: none opts in, all still narrow on outcome.kind === 'served'.
  • @objectstack/service-analytics: a new executeOrderCutAggregate member on DatasetScopedStrategyContext (mirroring executeRelationGroupAggregate), passed through AnalyticsServiceConfig and wired by AnalyticsServicePlugin only when it auto-bridges executeAggregate. ObjectQLStrategy.execute (base path) sends the query's order as the engine's orderBy (a measure by its alias, a dimension by its group column) and limit = offset + limit; served, it skips the offset over the database's rows and answers totalGroups from the statement's count; declined (or no seam, no limit, an order key it cannot map), it reads every group and runs today's applyWindow(applyOrdering(...)).
  • Rider, lookup/select label order: unchanged by construction. The dataset executor never pushes a window whose order names a label-bearing dimension (canPushDownWindow), so such a selection reaches the face with no limit and is ordered and cut in memory by label. Pinned below. The optional rank route for select keys was not taken.

The win is narrower than the card body says: memory, MongoDB, OData, Turso's remote face, uncompiled date buckets (a reference timezone, a granularity the driver does not compile), measure filters the driver does not evaluate and any having still decline and are cut in memory. The cross-object path (executeCrossObject) is untouched.

Visible behaviour (Clause-② yes, ruled): a text-ordered top-N on a compiling driver returns the database's choice of groups, its collation and NULL last in both directions, instead of applyOrdering's (localeCompare, '' as empty). The executor's post-pass still re-sorts the rows it was handed with applyOrdering, as it does for the native face.

Verification

Two-minute check: pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/objectql-order-cut-face.test.ts, expect 7 passed.

Read first: packages/services/service-analytics/src/strategies/objectql-strategy.ts (readOrderCut, windowServedCut: the order-key mapping and the offset arithmetic), packages/objectql/src/engine-delete-and-aggregate.ts (the decline branch), packages/services/service-analytics/src/plugin.ts (the bridge reads outcome and declined).

  • New objectql-order-cut-face.test.ts (real ObjectQL + SqliteWasmDriver through the plugin's own composition): top two by a measure reads 2 rows in one statement and totalGroups is 5; limit 2 offset 1 sends a cut of 3 and answers groups 2 and 3; text order picks Emea over amer (binary collation) and never keeps the NULL group ascending or descending; the analytics query door uses the same face; a reference-zone date bucket and a driver that compiles no cut fall back with no refusal and an exact totalGroups; a lookup dimension ordered by name is cut in memory (by name Amy, Bob, where an id cut would have kept Zed, Cat).
  • aggregate-order-cut.test.ts gains a top-level describe: declinable requests on memory, MongoDB and OData drivers, with a having, and with a zone bucketed in memory answer [] with the reason on declined, driver never asked; served unchanged on a compiling driver; a malformed order key still refused INVALID_SORT.
  • Ablation, once, on the seam (the strategy's readOrderCut forced to undefined via scripts/ablation-replace.mjs, anchor 1 to 0, blob c581598c to 5983467d): 4 of 7 face pins red (the four that assert the database cut), the 3 fallback pins green; restored, blob equals HEAD, git diff HEAD empty.
Local runs (head d726cc7 for ratchets and typecheck)
  • pnpm --filter @objectstack/objectql test: 617/618 files, 13956/13960 tests; the 4 failures were the new describe, read mid-edit (its file and its source were rewritten while the suite ran); the file re-run alone: 20/20.
  • pnpm --filter @objectstack/service-analytics test: 220/220 files, 5616 passed, 345 skipped.
  • pnpm --filter @objectstack/objectql typecheck, pnpm --filter @objectstack/service-analytics typecheck: exit 0.
  • node scripts/pm/dispatch-gates.mjs --commands: 76 families derived, 74 exit 0, 2 exit 3 PREREQUISITE NOT MET (check-plugin-teardown-shape --self-test: positive control unreachable in this clone; check:dual-build-cjs-loads: needs every package's dist/), so NOT MEASURED here, CI runs both. Ratchets re-run on d726cc7: type-check-coverage, type-check-debt, issue-citations, nul-bytes, doc-authoring, dts-closure exit 0.
  • node scripts/pm/overlap-check.mjs --branch=claude/area-a4C-35287: clean (origin/main 5d2ce34, fix(audit): a search the server widens never names a column the caller may not query #34817 merges cleanly).

Acceptance notes

  • Runtime and mcp were not type-checked locally: their imports of AggregateOrderCutOutcome / AggregateOrderCutRequest see only an added optional field; CI's TypeScript Type Check covers them.
  • No having reaches the analytics face, so its decline is pinned at the engine only.

🤖 Generated with Claude Code

…its top-N in the database

The engine's order-and-cut request gains an opt-in declinable flag: where the
cut cannot be served it reads nothing and records a declined outcome instead
of refusing. The analytics plugin bridges it as executeOrderCutAggregate, and
ObjectQLStrategy sends order + (offset + limit) through it, taking the group
count from the statement; on a decline it reads every group and cuts in
memory as before.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4d1k1GRsQbF3vCPKxhz
…face's database top-N

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4d1k1GRsQbF3vCPKxhz
…'s type is unchanged

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016WV4d1k1GRsQbF3vCPKxhz
@github-actions github-actions Bot added size/l 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 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/objectql, @objectstack/service-analytics, touching 21 documentable anchor(s).

29 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 5ecf9374701d3fcb9de439c0bc09f7008992c80a.

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

What this run could not see
  • 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 — 27 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 5ecf9374701d3fcb9de439c0bc09f7008992c80a → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 7241a6f1bbac601810e54aee8065e2be1e9a4534 — the merge of head d726cc761765087c4ba038ed8690c4872255a845 into base 5ecf9374701d3fcb9de439c0bc09f7008992c80a, 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 7241a6f1bbac601810e54aee8065e2be1e9a4534 && git checkout 7241a6f1bbac601810e54aee8065e2be1e9a4534
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 5ecf9374701d3fcb9de439c0bc09f7008992c80a d726cc761765087c4ba038ed8690c4872255a845 && git checkout -B drift-repro 5ecf9374701d3fcb9de439c0bc09f7008992c80a && git merge --no-ff d726cc761765087c4ba038ed8690c4872255a845

node scripts/docs-audit/affected-docs.mjs --json 5ecf9374701d3fcb9de439c0bc09f7008992c80a

⚠️ 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 5ecf9374701d3fcb9de439c0bc09f7008992c80a → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-elon-musk · session_016WV4d1k1GRsQbF3vCPKxhz

Final green head: d726cc761765087c4ba038ed8690c4872255a845 (Fixes #35287, arm A of ruling 7023449707, riders 7023599246 as acceptance). CI green (37 success, 16 skipped, 0 failed), no conflict. check-governed-merges --pr 35728: NOT governed. Area a4-C asks L1-a for the L1 review on this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-elon-musk · session_016WV4cxk4f4T7at3YeFruhZ

L1 verdict (L1-a): ACCEPT at head d726cc761765087c4ba038ed8690c4872255a845 (announced in 7030195390).

Gates on this head: 53 check-runs: 37 success, 16 skipped, 0 failed, 0 pending. Lint & Repo Gates and TypeScript Type Check both passed. Mergeable: clean.

What I checked (holds):

  • Arm A as ruled (7023449707), riders 7023599246 met:

    • declinable is opt-in. Without it, engine-delete-and-aggregate.ts (~1562) still throws the refusal, so aggregate_records and its three callers keep the 400, untouched.
    • The "Refused, never approximated" docblock is amended. The engine itself still never sorts or cuts in process: a decline reads nothing and answers [].
    • Select and lookup label-ordered keys never reach the cut. The dataset executor orders those in memory and hands this face no window (canPushDownWindow). This is pinned: "a lookup dimension ordered by its display label is never cut in the database".
  • The decline has its own slot. declined is separate from outcome, so AggregateOrderCutOutcome (kind: 'served') keeps its type. AggregateOrderCutDecline stays off the package root (d726cc76). A request built wrong (an order key naming no column) is still refused either way, and that is pinned.

  • The seam mirrors executeRelationGroupAggregate. It uses the same engine (requireDataEngine) and the same engineAggregateQuery(input), so context (the ADR-0021 D-C principal), filter with withReadScope and timezone all travel exactly as in executeAggregate. No read-scope belt is lost. The request rides a Symbol.for read option, so no wire request can carry it. served is trusted only when outcome.kind === 'served' and totalGroups is a number; anything else falls back to memory.

  • The strategy's cut is the in-memory cut's membership:

    • limit is offset + limit, and windowServedCut then applies applyWindow(rows, limit, offset), which skips only the offset.
    • Measure keys use the measure's full name, which is the alias the aggregate input sets. Dimension keys use resolveFieldName, the same short column the remap reads.
    • Any order key naming neither a measure nor a projected dimension makes the face skip the cut, so it never reaches the engine's INVALID_SORT.
    • totalGroups comes from the statement through groupCountRequestOf, and the in-memory path still uses answerWholeGrid.
    • No row filter sits between the aggregate and the window. The remap and the best-effort sql echo are the only steps.
    • The cross-object path (executeCrossObject) is untouched.
  • Tests. The face pins cover:

    • measure top-2 with totalGroups;
    • offset;
    • text collation with NULL last both ways;
    • the /analytics/query door;
    • a reference-zone decline;
    • the lookup-label pin;
    • memory-driver fallback;
    • Turso-local / WASM served.

    The objectql pins cover decline per non-compiling driver, having and in-memory bucket declines, compiling-driver parity, and the wrong-built refusal. The ablation in the body fails exactly the 4 database-cut pins and leaves the 3 fallback pins green, which is the right split.

  • Changeset. One patch entry each for @objectstack/objectql and @objectstack/service-analytics. It states the visible text-order change and the decline list (memory, MongoDB, OData, Turso remote, uncompiled bucket or zone, unevaluated measure filter). Clause-②: yes and Metadata-protocol: none are correct. Fixes #35287 is right: arm A is delivered, and the card's narrower win is what the riders already recorded.

On the seat's question (is declinable a contract face): in my reading it is not a new one. It is an optional field on the exported TS type AggregateOrderCutRequest, plus an engine-written declined slot. It is reachable only in process through a Symbol.for read option, and absent it nothing changes. That is additive and not authorable, and it is not on the wire. The contract-visible change in this PR is the text top-N order on compiling drivers, and the maintainer's arm A ruling already decided it. A separate contract read is your call, but L1 sees nothing in this PR that the ruling does not cover.

Notes (non-blocking):

  1. As the dev notes, the dataset executor re-sorts the N served rows with its in-memory comparator. Membership is the database's, but the order within the top-N can differ from the database collation on text ties and case. The native face does the same today.
  2. A limit with no order is now cut by the group keys ascending (the engine's full order) on compiling drivers. Before, it took the first N in arrival order. This is deterministic now and was arbitrary before; the changeset could say so in one clause.

Not governed (no skills/**, docs/adr/** or spec), so the area lands it.


Generated by Claude Code

@objectstack-fleet objectstack-fleet Bot added the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Nov 20, 2026
@os-zhuang
os-zhuang marked this pull request as ready for review November 20, 2026 04:50
@os-zhuang
os-zhuang added this pull request to the merge queue Nov 20, 2026
Merged via the queue into main with commit c321914 Nov 20, 2026
59 checks passed
@os-zhuang
os-zhuang deleted the claude/area-a4C-35287 branch November 20, 2026 05:14
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 pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue size/l 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.

query_dataset ObjectQL face: push the top-N order-and-cut to the database (SQL-first) instead of fetching every group

3 participants