Skip to content

Commit c321914

Browse files
fix(objectql,service-analytics): query_dataset's ObjectQL face cuts its top-N in the database (#35728)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DDxdrYJq965rUfrZBso8FS3)_ 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. <details><summary>Local runs (head d726cc7 for ratchets and typecheck)</summary> - `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, #34817 merges cleanly). </details> ## 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](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d5ece3e commit c321914

9 files changed

Lines changed: 511 additions & 21 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/service-analytics': patch
4+
---
5+
6+
fix(objectql,service-analytics): `query_dataset`'s ObjectQL face orders and cuts a top-N in the database instead of reading every group
7+
8+
Clause-②: yes
9+
Metadata-protocol: none
10+
11+
A top-N (`order` with a `limit`, optionally an `offset`) on the analytics ObjectQL face — date-bucketed queries, `$field` filters, drivers without raw SQL — used to read every group and cut in memory. On a driver that compiles the engine's order-and-cut (the SQL driver family: `driver-sql`, the WASM SQLite driver, Turso's local and replica faces) the face now hands the engine its order and `offset + limit`, the database orders, cuts and counts in one statement, and only the cut rows are read. `totalGroups` stays the count of every group, taken from that statement.
12+
13+
Visible change: a text-ordered top-N on such a driver now returns the database's choice of groups — its collation, NULL last in both directions — the same as the native SQL face and `aggregate_records`, instead of the in-memory comparator's (`localeCompare`, `''` read as empty).
14+
15+
Where the engine cannot serve the cut — the in-memory driver, MongoDB, OData, Turso's remote face, a date bucket or reference timezone the driver does not compile, a measure filter it does not evaluate — the face reads every group and cuts in memory as before, and no refusal reaches the caller. A select or lookup dimension ordered by its display label is still cut in memory, by label.
16+
17+
`@objectstack/objectql`: an `AGGREGATE_ORDER_CUT` request may set `declinable: true`; where the cut cannot be served the engine then reads nothing, answers `[]`, leaves `outcome` unset and records the reason on the request's new `declined` slot instead of refusing `INVALID_QUERY` / 400. Without the flag nothing changes: `aggregate_records` keeps its refusal, and `AggregateOrderCutOutcome` is unchanged.

‎packages/objectql/src/aggregate-order-cut.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,3 +233,50 @@ describe('[aggregate order and cut] engine.aggregate — refused on every driver
233233
}
234234
});
235235
});
236+
237+
describe('[aggregate order and cut] a declinable request is DECLINED where it cannot be served — nothing read, no refusal, no outcome', () => {
238+
const declinable = (): AggregateOrderCutRequest => ({ ...TOP_TWO(), declinable: true });
239+
240+
for (const name of ['com.objectstack.driver.memory', 'com.objectstack.driver.mongodb', 'com.objectstack.driver.odata']) {
241+
it(`${name}: answers [] with its decline recorded, the driver never asked`, async () => {
242+
const { engine, rec } = await makeEngine(name);
243+
const request = declinable();
244+
expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))).toEqual([]);
245+
expect(request.outcome).toBeUndefined();
246+
expect(request.declined?.reason).toContain(`'${name}'`);
247+
expect(rec.calls).toEqual([]);
248+
});
249+
}
250+
251+
it('a having, and an aggregate computed in memory (a zone the driver does not bucket), decline on a compiling driver', async () => {
252+
const { engine, rec } = await makeEngine('com.objectstack.driver.sql');
253+
const having = declinable();
254+
expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER, having: { revenue: { $gt: 10 } } }, withCut(having))).toEqual([]);
255+
expect(having.declined?.reason).toMatch(/having/);
256+
const zoned: AggregateOrderCutRequest = { orderBy: [{ field: 'n', order: 'desc' }], limit: 3, declinable: true };
257+
expect(await engine.aggregate(ORDER, {
258+
groupBy: [{ field: 'closed_on', dateGranularity: 'month' }],
259+
aggregations: [{ function: 'count', alias: 'n' }],
260+
timezone: 'Asia/Shanghai',
261+
}, withCut(zoned))).toEqual([]);
262+
expect(zoned.declined?.reason).toMatch(/computed in the application/);
263+
expect(rec.calls).toEqual([]);
264+
});
265+
266+
it('on a compiling driver it is served exactly as an undeclinable one', async () => {
267+
const { engine, rec } = await makeEngine('com.objectstack.driver.sql');
268+
rec.answer([{ customer: 'c9', area: 'west', revenue: 90, n: 3, [AGGREGATE_TOTAL_GROUPS_COLUMN]: 4 }]);
269+
const request = declinable();
270+
expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))).toEqual([{ customer: 'c9', area: 'west', revenue: 90, n: 3 }]);
271+
expect(request.outcome).toEqual({ kind: 'served', totalGroups: 4 });
272+
expect(request.declined).toBeUndefined();
273+
});
274+
275+
it('a request the caller built wrong is still refused: an order key naming no column of the row is INVALID_SORT', async () => {
276+
const { engine, rec } = await makeEngine('com.objectstack.driver.memory');
277+
const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut({ orderBy: [{ field: 'nope', order: 'asc' }], limit: 2, declinable: true })));
278+
expect(err?.code).toBe('INVALID_SORT');
279+
expect(err?.status).toBe(400);
280+
expect(rec.calls).toEqual([]);
281+
});
282+
});

‎packages/objectql/src/aggregate-order-cut.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,29 @@
4545
* A driver that answered rows without it did not serve the cut, and its rows
4646
* are refused as a server fault, never served as an answer.
4747
*
48-
* ## Refused, never approximated
48+
* ## Refused, or declined to a caller that asked — never approximated
4949
*
5050
* Prime Directive 5 (ruling record 6888468549): only a driver that compiles the
5151
* cut in its own statement serves it ({@link driverCompilesAggregateOrderCut}).
5252
* Every other driver — the in-memory driver, MongoDB, OData, the remote face of
53-
* the Turso driver — is refused `INVALID_QUERY` / 400 before anything is read;
54-
* so is an aggregate the engine would compute in memory (a date bucket the
55-
* driver does not compile, a reference zone it does not bucket, a measure
56-
* filter it does not evaluate), an aggregate with a `having` (applied by the
57-
* engine AFTER the driver, so a cut in the statement would cut before it), and
58-
* a relation group join. No in-process sort and no slower path exist.
53+
* the Turso driver — is not served, and neither is an aggregate the engine
54+
* would compute in memory (a date bucket the driver does not compile, a
55+
* reference zone it does not bucket, a measure filter it does not evaluate),
56+
* an aggregate with a `having` (applied by the engine AFTER the driver, so a
57+
* cut in the statement would cut before it), or a relation group join. The
58+
* engine never orders or cuts the groups itself: no in-process sort and no
59+
* slower path exist here.
60+
*
61+
* What "not served" answers is the caller's choice. By default the request is
62+
* refused `INVALID_QUERY` / 400 before anything is read — the answer
63+
* `aggregate_records` gives. A caller that already owns a whole-grid answer
64+
* (the analytics `query_dataset` face, which orders and windows the groups it
65+
* is handed) sets {@link AggregateOrderCutRequest.declinable}: the request is
66+
* then DECLINED instead, exactly as the relation group join declines — nothing
67+
* is read, the read answers `[]`, which is not an answer, the reason is on
68+
* the request's `declined` slot and its `outcome` stays unset — and the
69+
* caller reads the groups the way it always has. A request the caller built wrong (an order key naming no column of the
70+
* row) is refused either way.
5971
*/
6072

6173
import { StandardErrorCode } from '@objectstack/spec/api';
@@ -116,6 +128,15 @@ export interface AggregateOrderCutOutcome {
116128
readonly totalGroups: number;
117129
}
118130

131+
/**
132+
* Why the engine declined a {@link AggregateOrderCutRequest.declinable}
133+
* request: set instead of {@link AggregateOrderCutOutcome}, before anything
134+
* was read — the read's `[]` is no answer.
135+
*/
136+
export interface AggregateOrderCutDecline {
137+
readonly reason: string;
138+
}
139+
119140
/**
120141
* The request: the order of the groups, how many to answer, and the slot the
121142
* engine writes its {@link AggregateOrderCutOutcome} to. A carrier that hands
@@ -126,7 +147,17 @@ export interface AggregateOrderCutRequest {
126147
readonly orderBy: readonly AggregateOrderKey[];
127148
/** The most groups to answer; absent = every group, still ordered and counted. */
128149
readonly limit?: number;
150+
/**
151+
* Decline rather than refuse where the cut cannot be served
152+
* ({@link aggregateOrderCutRefusal}): nothing is read, the read answers
153+
* `[]`, `outcome` stays unset and {@link declined} carries the refusal's
154+
* reason. Opt-in — absent, the request is refused `INVALID_QUERY` / 400 as
155+
* before.
156+
*/
157+
readonly declinable?: boolean;
129158
outcome?: AggregateOrderCutOutcome;
159+
/** Set by the engine when it declined a {@link declinable} request. */
160+
declined?: AggregateOrderCutDecline;
130161
}
131162

132163
/** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */
@@ -268,7 +299,9 @@ export function assertAggregateOrderCutShape(
268299
* Why the engine cannot serve the cut for this read, or `undefined` when it
269300
* can — judged once the driver and the path the aggregate takes are known,
270301
* before the driver is asked. ⛔ No answer here means "compute it some other
271-
* way": every reason is a refusal.
302+
* way" inside the engine: every reason is a refusal, which a
303+
* {@link AggregateOrderCutRequest.declinable} request turns into a decline
304+
* ({@link declineAggregateOrderCut}) for its caller to serve.
272305
*/
273306
export function aggregateOrderCutRefusal(
274307
object: string,
@@ -312,6 +345,16 @@ export function aggregateOrderCutRefusal(
312345
return undefined;
313346
}
314347

348+
/**
349+
* Records a decline on a {@link AggregateOrderCutRequest.declinable} request
350+
* (the `refusal`'s message is the reason) and answers the read's `[]`, which
351+
* is not an answer. Nothing has been read.
352+
*/
353+
export function declineAggregateOrderCut(request: AggregateOrderCutRequest, refusal: Error): Record<string, unknown>[] {
354+
request.declined = { reason: refusal.message };
355+
return [];
356+
}
357+
315358
/**
316359
* The full order the driver applies: the request's keys, then every group key
317360
* column the request does not name, ascending — so the answer is the same

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import type { EngineReadOptions, OperationContext } from './engine-top-level.js'
8282
import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js';
8383
import {
8484
aggregateOrderCutDirective, aggregateOrderCutRefusal, aggregateOrderCutRequestOf, assertAggregateOrderCutShape,
85+
declineAggregateOrderCut,
8586
takeAggregateGroupCount, withAggregateOrderCutDirective,
8687
} from './aggregate-order-cut.js';
8788
import {
@@ -1549,14 +1550,19 @@ export class DeleteAndAggregateFacet {
15491550
// [aggregate order and cut] Served only as the driver's own statement,
15501551
// and refused — before the driver is asked — on every path that is not
15511552
// one (`aggregateOrderCutRefusal`): no in-memory sort, no slower path.
1553+
// A caller that opted in (`declinable`) is declined instead, nothing
1554+
// read, and serves the groups its own way.
15521555
if (orderCut !== undefined) {
15531556
const refused = aggregateOrderCutRefusal(object, {
15541557
driver: drv,
15551558
nativeAggregate,
15561559
hasHaving: ast.having != null && typeof ast.having === 'object' && Object.keys(ast.having).length > 0,
15571560
hasRelationGroup: relationGroup !== undefined,
15581561
});
1559-
if (refused !== undefined) throw refused;
1562+
if (refused !== undefined) {
1563+
if (orderCut.declinable === true) return declineAggregateOrderCut(orderCut, refused);
1564+
throw refused;
1565+
}
15601566
const directive = aggregateOrderCutDirective(orderCut, aggregatedRowColumns(ast.groupBy, []));
15611567
const cut = await drv.aggregate(object, withBucketZone(withAggregateOrderCutDirective(ast, directive)), aggregateOptions);
15621568
return takeAggregateGroupCount(object, drv, cut, orderCut);

0 commit comments

Comments
 (0)