From a4462b0b99043eaef332aa33d3e089dafd3bb0f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:01:46 +0000 Subject: [PATCH 01/10] feat(mcp): aggregate_records orders, cuts and counts groups in the driver's statement (wip) Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../driver-sql/src/sql-driver-aggregation.ts | 94 ++++- .../drivers/driver-turso/src/turso-driver.ts | 17 + packages/mcp/src/mcp-http-tools.ts | 93 ++++- packages/mcp/src/stdio-data-bridge.ts | 62 +++- packages/objectql/src/aggregate-order-cut.ts | 327 ++++++++++++++++++ .../src/engine-delete-and-aggregate.ts | 30 ++ packages/objectql/src/index.ts | 6 + packages/runtime/src/action-execution.ts | 20 +- packages/runtime/src/domains/mcp.ts | 38 ++ 9 files changed, 676 insertions(+), 11 deletions(-) create mode 100644 packages/objectql/src/aggregate-order-cut.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 1e8180777fa..8c62b90d1a2 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -84,6 +84,10 @@ export class AggregationFacet { // the engine (`objectql` `relation-group-join.ts`); read once, judged // before anything compiles. const relationJoins = relationGroupJoinsOf(query); + // [aggregate order and cut] The order, cut and group count the engine + // hands (`objectql` `aggregate-order-cut.ts`); read once, judged before + // anything compiles. + const orderCut = aggregateOrderCutOf(query); // [#33697] The reference zone the date buckets are read in // (`DriverAggregateQuery.timezone`, ADR-0053 Phase 2 D2 as amended), judged // before anything compiles. Absent or `UTC` is the UTC bucket every dialect @@ -201,6 +205,10 @@ export class AggregationFacet { // column name the caller will read. See {@link foldEmptyAggregateAnswers}. const foldedOutput = new Map(); + // [aggregate order and cut] Every column the grouped statement projects, + // under the name the caller reads: the only names an order key may name. + const projected = new Set(); + if (query.groupBy) { // groupBy items may be plain strings ('region') or structured objects // ({ field: 'closed_at', dateGranularity: 'quarter' }). For structured @@ -222,6 +230,7 @@ export class AggregationFacet { const column = columnOf(g); builder.groupBy(column); builder.select(column === g ? g : this.knex.raw(`?? as ${this.aliasIdentifierSql(g)}`, [column])); + projected.add(g); const kind = this.readPresentationKind(table, g); if (kind) presentedOutput.set(g, kind); } else if (g && typeof g === 'object' && g.field) { @@ -237,6 +246,7 @@ export class AggregationFacet { // renamed, so the buckets are identical and only their column name // moves. const outKey = g.alias ?? g.field; + projected.add(outKey); if (g.dateGranularity) { const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity, table, columnOf(g.field), bucketZone); if (!bucket) { @@ -309,6 +319,8 @@ export class AggregationFacet { (relationJoins ?? []).forEach((join, i) => { const at = `__rg${i}`; const idColumn = `${at}_id`; + for (const a of join.attrs) projected.add(a.alias); + projected.add(join.resolvedAlias); if (join.parent === null) { for (const a of join.attrs) builder.select(this.knex.raw(`NULL as ${this.aliasIdentifierSql(a.alias)}`)); builder.select(this.knex.raw(`0 as ${this.aliasIdentifierSql(join.resolvedAlias)}`)); @@ -418,6 +430,7 @@ export class AggregationFacet { ? `${lowering.sql}(CASE WHEN (${measureFilter.sql}) THEN 1 END)` : `${lowering.sql}(*)`; if (agg.alias) { + projected.add(agg.alias); if (fieldExpr === '*') { builder.select(this.knex.raw(`${starFunc} as ${this.aliasIdentifierSql(agg.alias)}`, filterBindings)); } else { @@ -522,9 +535,45 @@ export class AggregationFacet { // {@link unsupportedAggregationFilterError}, {@link refuseDateBucketedGroupBy} // — is raised while the statement is BUILT, upstream of this line, so the // catch-all cannot bury a precise refusal under a generic 500. + // [aggregate order and cut] The grouped statement becomes a derived table + // the cut is taken from, so every dialect orders by the row's own columns + // (PostgreSQL and SQL Server refuse an output alias inside an ORDER BY + // expression) and counts the groups it formed BEFORE the cut — a window + // over the derived table runs ahead of its ORDER BY and LIMIT: one + // statement, one round trip. A NULL ranks last in either direction; a + // column that folds to an identity over nothing (`sum`, the counts) ranks + // as that identity, the value its row is served with. + let statement: Knex.QueryBuilder = builder; + if (orderCut !== undefined) { + const unknown = orderCut.orderBy.find((k) => !projected.has(k.column)); + if (unknown !== undefined) { + throw aggregateOrderCutFault(`it orders by '${unknown.column}', which the grouped statement does not project`); + } + if (projected.has(orderCut.groupCountColumn)) { + throw aggregateOrderCutFault(`the group count column '${orderCut.groupCountColumn}' is also a projected column`); + } + const groups = this.aliasIdentifierSql('__os_groups'); + let outer = this.knex + .select(this.knex.raw(`${groups}.*`)) + .select(this.knex.raw(`count(*) over () as ${this.aliasIdentifierSql(orderCut.groupCountColumn)}`)) + .from(builder.as('__os_groups')); + if (options?.transaction) outer = outer.transacting(options.transaction as Knex.Transaction); + for (const key of orderCut.orderBy) { + const ref = `${groups}.${this.aliasIdentifierSql(key.column)}`; + const identity = foldedOutput.get(key.column); + if (identity !== undefined && Number.isFinite(identity)) { + outer.orderByRaw(`coalesce(${ref}, ${String(identity)}) ${key.order}`); + } else { + outer.orderByRaw(`case when ${ref} is null then 1 else 0 end, ${ref} ${key.order}`); + } + } + if (orderCut.limit !== undefined) outer.limit(orderCut.limit); + presentedOutput.set(orderCut.groupCountColumn, 'number'); + statement = outer; + } let rows: unknown[]; try { - rows = await builder; + rows = await statement; } catch (error) { // [#8931, #11541] Attribute what the caller's own query supports, then // fall to the terminal catch-all — see @@ -564,6 +613,49 @@ export class AggregationFacet { */ export const RELATION_GROUP_JOINS: unique symbol = Symbol.for('objectstack.driver.aggregate.relationGroupJoins'); +/** + * [aggregate order and cut] The AST key the engine hands its order, cut and + * group-count request on (`objectql` `aggregate-order-cut.ts`, the same + * `Symbol.for` key — this package does not import the engine). A symbol, so no + * wire request and no JSON query can carry one; set by the engine after every + * middleware ran. + */ +export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectstack.driver.aggregate.orderCut'); + +/** The order, cut and group-count column, as the engine hands them. */ +export interface AggregateOrderCutDirective { + /** The full order, every key a column the grouped statement projects. */ + readonly orderBy: ReadonlyArray<{ readonly column: string; readonly order: 'asc' | 'desc' }>; + /** The most groups to answer; absent = every group. */ + readonly limit?: number; + /** The column every row answers the pre-cut group count under. */ + readonly groupCountColumn: string; +} + +/** A directive the engine did not compose: refused, INTERNAL_ERROR / 500, before anything runs. */ +function aggregateOrderCutFault(detail: string): Error { + const err = new Error( + `aggregate: an order-and-cut directive the engine did not compose was refused (${detail}); the query was NOT run.`, + ) as Error & { code?: string; status?: number }; + err.code = 'INTERNAL_ERROR'; + err.status = 500; + return err; +} + +/** The directive on `query`, or `undefined` when it carries none; a malformed one is refused. */ +export function aggregateOrderCutOf(query: DriverQuery): AggregateOrderCutDirective | undefined { + const directive = (query as unknown as Record)[AGGREGATE_ORDER_CUT_DIRECTIVE]; + if (directive === undefined) return undefined; + const d = directive as Partial | null; + const ok = d !== null && typeof d === 'object' + && Array.isArray(d.orderBy) + && d.orderBy.every((k) => typeof k?.column === 'string' && k.column !== '' && (k.order === 'asc' || k.order === 'desc')) + && (d.limit === undefined || (typeof d.limit === 'number' && Number.isInteger(d.limit) && d.limit >= 1)) + && typeof d.groupCountColumn === 'string' && d.groupCountColumn !== ''; + if (!ok) throw aggregateOrderCutFault('malformed'); + return d as AggregateOrderCutDirective; +} + /** One relation join, as the engine hands it. */ export interface RelationGroupJoin { /** The single-valued relation (FK) column of the aggregated object. */ diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index 828ee38d631..f1bf2753951 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -3258,6 +3258,23 @@ export class TursoDriver extends SqlDriver { ): Promise[]> { this.assertRemoteTransactionUnsupported(options, 'aggregate'); if (this.isRemote) { + // [aggregate order and cut] The remote transport compiles its own + // aggregates and no ordered cut: a statement handed the engine's + // directive (`Symbol.for` key, as `driver-sql` reads it) is refused + // before anything is read, never answered uncut. The engine refuses it + // first; this is the driver's own word for a caller that reaches it + // directly. + if ((query as unknown as Record)[Symbol.for('objectstack.driver.aggregate.orderCut')] !== undefined) { + const err = new Error( + `aggregate('${object}'): ordered and cut groups cannot run on the remote face of this driver, whose ` + + 'transport compiles no ordered cut. The query was NOT run and nothing was read. A local or replica ' + + 'database serves it.', + ) as Error & { code?: string; status?: number; httpStatus?: number }; + err.code = StandardErrorCode.enum.INVALID_QUERY; + err.status = 400; + err.httpStatus = 400; + throw err; + } const table = this.remoteTableFor(object, 'aggregate'); // [#20424] The caller's own query is what the fault is attributed // against, as `SqlDriver.aggregate` does locally: its groupBy and diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 9a18605c784..fd8dde60079 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -279,6 +279,32 @@ export interface McpDataBridge { timezone?: string; }, ): Promise; + /** + * `aggregate_records` with an `orderBy` or a `limit`: the groups ORDERED by + * an aggregated column (an aggregation alias or a group key's projected + * name), CUT to at most `limit`, and `groupCount`, how many groups existed + * before the cut — all three computed by the driver's own statement + * (`@objectstack/objectql` `aggregate-order-cut.ts`, which the bridge + * reaches through `engine.aggregate`'s read option). The bridge runs it + * through every gate {@link aggregate} runs. A driver that cannot order and + * cut groups in its own statement refuses (`INVALID_QUERY` / 400), and the + * bridge throws that refusal; it never orders or cuts the groups itself. + * + * OPTIONAL, separately from {@link aggregate}: a bridge without it registers + * `aggregate_records` as before, and the tool refuses an `orderBy` / `limit` + * rather than cut an unordered list (`NOT_IMPLEMENTED` / 501). + */ + aggregateGroups?( + object: string, + opts: { + where?: Record; + groupBy?: NonNullable; + aggregations: NonNullable; + timezone?: string; + orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; + limit?: number; + }, + ): Promise<{ rows: unknown[]; groupCount: number }>; /** * [ADR-0149 D2] `list_datasets`: the governed datasets this caller may * query, each with its dimensions and measures, their business vocabulary, @@ -3006,6 +3032,12 @@ export function registerObjectTools( 'Aggregate records with GROUP BY: count/sum/avg/min/max/count_distinct over an object, ' + 'optionally grouped by fields (dates can be bucketed by day/week/month/quarter/year). ' + 'Use this instead of paging query_records when a question needs totals or breakdowns. ' + + // [aggregate order and cut] A ranking question ("the top five + // customers by revenue") is answered by the database: ordered, + // cut, and the number of groups before the cut stated. + 'For a ranking (top or bottom N), set orderBy to an aggregation alias or a group key and limit to N: ' + + 'the database orders and cuts the groups, and groupCount says how many groups existed before the cut. ' + + `At most ${maxLimit} groups come back; truncated: true says more existed. ` + 'Runs under the caller\'s permissions, row-level security and field-level security.', inputSchema: strictToolInput( { @@ -3021,6 +3053,13 @@ export function registerObjectTools( aggs: 'aggregations', tz: 'timezone', timeZone: 'timezone', + sort: 'orderBy', + sortBy: 'orderBy', + order: 'orderBy', + order_by: 'orderBy', + top: 'limit', + take: 'limit', + pageSize: 'limit', }, }, { @@ -3064,14 +3103,63 @@ export function registerObjectTools( .string() .optional() .describe('IANA timezone for date bucketing (defaults to UTC)'), + orderBy: z + .array(z.object({ field: z.string(), order: z.enum(['asc', 'desc']) })) + .max(8) + .optional() + .describe( + 'Order of the groups, by an aggregation alias or a group key (its alias when it has one), ' + + 'e.g. [{"field":"total","order":"desc"}]; computed by the database', + ), + limit: z + .number() + .int() + .positive() + .max(maxLimit) + .optional() + .describe(`Most groups to return (≤ ${maxLimit}); the cut is taken by the database, after orderBy`), }, ), annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, }, - async ({ objectName, aggregations, groupBy, where, timezone }) => { + async ({ objectName, aggregations, groupBy, where, timezone, orderBy, limit }) => { const bad = await readGuard(objectName); if (bad) return errorResult(bad); try { + if (orderBy !== undefined || limit !== undefined) { + // [aggregate order and cut] Ordered, cut and counted by the + // driver's own statement, through the bridge's member for it; + // one group past the cap is asked for, so `truncated` is a fact + // (the capped-list key every read tool shares), and `groupCount` + // is the statement's own count of the groups before the cut. + // ⛔ Never sorted or sliced from an uncut list here. + if (typeof bridge.aggregateGroups !== 'function') { + return codedErrorResult({ + code: StandardErrorCode.enum.NOT_IMPLEMENTED, + status: 501, + message: + `aggregate_records on '${objectName}': this server cannot order or cut groups in the database, ` + + 'and never orders or cuts them in the application instead. Ask without orderBy and limit.', + }); + } + const cap = Math.min(limit ?? maxLimit, maxLimit); + const answer = await bridge.aggregateGroups(objectName, { + where, + groupBy, + aggregations, + timezone, + orderBy: orderBy ?? [], + limit: cap + 1, + }); + const groups = Array.isArray(answer?.rows) ? answer.rows : []; + const cut = groups.length > cap; + return textResult({ + rows: cut ? groups.slice(0, cap) : groups, + groupCount: answer.groupCount, + totalGroups: answer.groupCount, + ...(cut ? { truncated: true } : {}), + }); + } const rows = (await aggregateFn(objectName, { where, groupBy, @@ -3083,6 +3171,9 @@ export function registerObjectTools( const truncated = rows.length > maxLimit; return textResult({ rows: truncated ? rows.slice(0, maxLimit) : rows, + // How many groups existed before the cap: the card's + // `groupCount`, beside the earlier `totalGroups` it equals. + groupCount: rows.length, totalGroups: rows.length, ...(truncated ? { truncated: true } : {}), }); diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 70f78a7a4cd..fbf99e424c4 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -311,6 +311,14 @@ interface ObjectDef { * spelling the existing stdio reader already accepts, kept identical so the two * readers on this transport cannot disagree about what a row list is. */ +/** + * The engine's order-cut-count read option for `aggregate` + * (`@objectstack/objectql`, `aggregate-order-cut.ts`), spelled `Symbol.for` + * because this package does not depend on the engine at runtime. A symbol, so + * no tool argument can carry it. + */ +const STDIO_AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectql.aggregateOrderCut'); + function unwrapRows(res: unknown): Array> { const rows = res && typeof res === 'object' && 'value' in (res as Record) @@ -1539,7 +1547,14 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge } if (typeof engine.aggregate === 'function') { - bridge.aggregate = async (object, opts) => { + // [aggregate order and cut] `orderCut`, when set, is the engine's + // order-cut-count request, handed on its read option after every gate + // below; the caller reads the engine's outcome off it. + const runAggregate = async ( + object: string, + opts: Parameters>[1], + orderCut?: object, + ): Promise => { const context = await resolvePrincipal(); // `aggregate` is a list-class read: an object whose whitelist excludes // `list` must not leak row statistics through GROUP BY either. The @@ -1570,15 +1585,46 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // compiles — the two `as unknown as` casts this line used to carry // existed only because the engine option declared `groupBy: string[]` // while reading structured buckets. - const rows = await engine.aggregate(object, { - ...(opts?.where ? { where: opts.where } : {}), - ...(opts?.groupBy ? { groupBy: opts.groupBy } : {}), - aggregations: opts.aggregations, - ...(opts?.timezone ? { timezone: opts.timezone } : {}), - context, - }); + const rows = await engine.aggregate( + object, + { + ...(opts?.where ? { where: opts.where } : {}), + ...(opts?.groupBy ? { groupBy: opts.groupBy } : {}), + aggregations: opts.aggregations, + ...(opts?.timezone ? { timezone: opts.timezone } : {}), + context, + }, + ...(orderCut !== undefined + ? [{ [STDIO_AGGREGATE_ORDER_CUT]: orderCut } as Parameters[2]] as const + : [] as const), + ); return rows ?? []; }; + bridge.aggregate = (object, opts) => runAggregate(object, opts); + // [aggregate order and cut] The same read, through the same gates, ordered, + // cut and counted by the driver's own statement; the engine's outcome slot + // is read back — a read that comes back without it was not served by the + // driver's statement, and its rows are no answer. + bridge.aggregateGroups = async (object, opts) => { + const orderCut: { + orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; + limit?: number; + outcome?: { kind?: unknown; groupCount?: unknown }; + } = { + orderBy: opts.orderBy, + ...(typeof opts.limit === 'number' ? { limit: opts.limit } : {}), + }; + const { orderBy: _orderBy, limit: _limit, ...read } = opts; + const rows = await runAggregate(object, read, orderCut); + const groupCount = orderCut.outcome?.groupCount; + if (orderCut.outcome?.kind !== 'served' || typeof groupCount !== 'number') { + throw new Error( + `aggregate_records on '${object}': the ordered and cut aggregate came back without being served by the ` + + 'driver\'s own statement, so its rows are not the answer and none is returned.', + ); + } + return { rows, groupCount }; + }; } return bridge; diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts new file mode 100644 index 00000000000..5cae4940e53 --- /dev/null +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -0,0 +1,327 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * "The top five customers by revenue": an aggregate whose groups are ORDERED + * by an aggregated column, CUT to a number of groups, and answered with how + * many groups existed before the cut — all three in the database, in the one + * statement that groups: `engine.aggregate('crm_order', query, + * { [AGGREGATE_ORDER_CUT]: { orderBy: [{ field: 'revenue', order: 'desc' }], + * limit: 5 } })` reaches a SQL driver as + * `SELECT g.*, COUNT(*) OVER () AS __os_group_count FROM () g ORDER BY … LIMIT 5`. + * + * ## An engine-internal option, never a wire key + * + * The request rides on {@link AGGREGATE_ORDER_CUT}, a symbol-keyed READ option + * (the `EngineReadOptions` third argument of `aggregate`), exactly as the + * relation group join rides on its own (`relation-group-join.ts`): no wire + * request, JSON body or spread author input can carry a symbol, so the public + * query vocabulary (`EngineAggregateOptions`, `QueryAST`) is unchanged. It is a + * `Symbol.for` key because the doors that carry it to the engine (the MCP + * tools' bridges, the runtime's `callData`) do not all depend on this package + * at runtime. Holding the key grants nothing: the read is still the caller's + * own `aggregate`, through every door, gate and middleware it always runs. + * + * ## Ordered by the aggregated row's own columns + * + * An order key names a column of the AGGREGATED row — an aggregation alias or a + * group key's projected name (`alias ?? field`), the namespace `having` filters + * ({@link aggregatedRowColumns}). Any other name is refused `INVALID_SORT` / + * 400, naming the columns this query projects. The group keys the order does + * not name follow it, ascending, so two runs of one request answer the same + * groups in the same order. A NULL ranks last in either direction, except + * where the column answers an identity over nothing (`sum`, the counts: + * `emptyGroupValueFor`), which ranks as that identity — the value the row is + * served with. + * + * ## The count is the statement's + * + * The driver answers the number of groups the statement formed before its cut + * on every row, under {@link AGGREGATE_GROUP_COUNT_COLUMN}; the engine takes it + * off the rows and writes it to the request's {@link AggregateOrderCutOutcome}. + * A driver that answered rows without it did not serve the cut, and its rows + * are refused as a server fault, never served as an answer. + * + * ## Refused, never approximated + * + * Prime Directive 5 (ruling record 6888468549): only a driver that compiles the + * cut in its own statement serves it ({@link driverCompilesAggregateOrderCut}). + * Every other driver — the in-memory driver, MongoDB, OData, the remote face of + * the Turso driver — is refused `INVALID_QUERY` / 400 before anything is read; + * so is an aggregate the engine would compute in memory (a date bucket the + * driver does not compile, a reference zone it does not bucket, a measure + * filter it does not evaluate), an aggregate with a `having` (applied by the + * engine AFTER the driver, so a cut in the statement would cut before it), and + * a relation group join. No in-process sort and no slower path exist. + */ + +import { StandardErrorCode } from '@objectstack/spec/api'; +import { driverNameOf } from './relation-semi-join.js'; + +/** + * The read-option key of an order-and-cut request: `aggregate(object, query, + * { [AGGREGATE_ORDER_CUT]: request })`. A `Symbol.for` key — its carriers live + * in packages that do not import this one — and a symbol, so no wire request + * can carry it. + */ +export const AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectql.aggregateOrderCut'); + +/** + * The AST key the driver reads the cut from ({@link DriverAggregateOrderCut}); + * `driver-sql`'s aggregate compiler reads the same `Symbol.for` key. Set by the + * engine on the composed AST it hands `driver.aggregate`, after every + * middleware has run — no middleware and no caller sees it. + */ +export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectstack.driver.aggregate.orderCut'); + +/** + * The column the driver answers the group count under, on every row. Taken off + * the rows by the engine before anyone reads them; an aggregated column of the + * same name is refused, so it never shadows one. + */ +export const AGGREGATE_GROUP_COUNT_COLUMN = '__os_group_count'; + +/** One key of a request's order: an aggregated-row column and its direction. */ +export interface AggregateOrderKey { + readonly field: string; + readonly order: 'asc' | 'desc'; +} + +/** What the engine did with an {@link AggregateOrderCutRequest}: set only once the driver answered it. */ +export interface AggregateOrderCutOutcome { + readonly kind: 'served'; + /** How many groups the statement formed before the cut. */ + readonly groupCount: number; +} + +/** + * The request: the order of the groups, how many to answer, and the slot the + * engine writes its {@link AggregateOrderCutOutcome} to. A carrier that hands + * the request on reads the slot back after the read: a read that came back + * without it was not served as ordered and cut, and is never an answer. + */ +export interface AggregateOrderCutRequest { + readonly orderBy: readonly AggregateOrderKey[]; + /** The most groups to answer; absent = every group, still ordered and counted. */ + readonly limit?: number; + outcome?: AggregateOrderCutOutcome; +} + +/** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */ +export interface DriverAggregateOrderCut { + /** The full order: the request's keys, then every group key it does not name, ascending. */ + readonly orderBy: ReadonlyArray<{ readonly column: string; readonly order: 'asc' | 'desc' }>; + readonly limit?: number; + /** The column to answer the pre-cut group count under, on every row. */ + readonly groupCountColumn: string; +} + +/** + * The drivers whose `aggregate` compiles {@link AGGREGATE_ORDER_CUT_DIRECTIVE}, + * named — no capability bit says which drivers compile it, and an unnamed + * driver is never handed one. `driver-sql` covers every dialect it speaks; the + * WASM SQLite driver inherits its `aggregate`. The Turso driver is admitted only + * on its local and replica faces ({@link driverCompilesAggregateOrderCut}), + * which inherit the same `aggregate`; its remote face compiles its own. + */ +export const AGGREGATE_ORDER_CUT_COMPILING_DRIVERS: ReadonlySet = new Set([ + 'com.objectstack.driver.sql', + 'com.objectstack.driver.sqlite-wasm', +]); + +const TURSO_DRIVER = 'com.objectstack.driver.turso'; +const TURSO_SQL_FACES: ReadonlySet = new Set(['local', 'replica']); + +/** The request on a read's options, when one rides there. */ +export function aggregateOrderCutRequestOf(options: unknown): AggregateOrderCutRequest | undefined { + if (options === null || typeof options !== 'object') return undefined; + const request = (options as Record)[AGGREGATE_ORDER_CUT]; + return request === undefined ? undefined : (request as AggregateOrderCutRequest); +} + +/** Does this driver's `aggregate` compile the cut? Named drivers only (see {@link AGGREGATE_ORDER_CUT_COMPILING_DRIVERS}). */ +export function driverCompilesAggregateOrderCut( + driver: { readonly name?: unknown; readonly aggregate?: unknown } | undefined, +): boolean { + if (typeof driver?.aggregate !== 'function') return false; + const name = driver.name; + if (typeof name !== 'string') return false; + if (AGGREGATE_ORDER_CUT_COMPILING_DRIVERS.has(name)) return true; + if (name !== TURSO_DRIVER) return false; + const mode = (driver as { readonly transportMode?: unknown }).transportMode; + return typeof mode === 'string' && TURSO_SQL_FACES.has(mode); +} + +type CodedError = Error & { + code?: string; status?: number; httpStatus?: number; + object?: string; param?: string; +}; + +/** A refusal of the request, `INVALID_QUERY` (or the named code) / 400, nothing read. */ +function refusal(object: string, detail: string, code: string = StandardErrorCode.enum.INVALID_QUERY): CodedError { + const err = new Error( + `aggregate('${object}') ordered or cut by group: ${detail} The query was NOT run and nothing was read.`, + ) as CodedError; + err.code = code; + err.status = 400; + // …and `httpStatus`, the same number under ADR-0112 D5's spelling — what a + // consumer holding the THROWN error reads; `status` stays for the HTTP doors. + err.httpStatus = 400; + err.object = object; + err.param = 'orderBy'; + return err; +} + +/** + * The request's own shape, judged against the aggregated row's columns + * (`columns`: {@link aggregatedRowColumns} of the query) before anything is + * read. An order key naming no column of the row is `INVALID_SORT`, naming + * the columns the query projects. + */ +export function assertAggregateOrderCutShape( + object: string, + request: AggregateOrderCutRequest, + columns: readonly string[], +): void { + if (request === null || typeof request !== 'object') { + throw refusal(object, 'the request is not an object.'); + } + const orderBy: unknown = request.orderBy; + if (!Array.isArray(orderBy)) { + throw refusal(object, '`orderBy` must be a list of { field, order } (an empty list orders by the group keys).'); + } + const limit: unknown = request.limit; + if (limit !== undefined && !(typeof limit === 'number' && Number.isInteger(limit) && limit >= 1)) { + throw refusal(object, `\`limit\` must be a whole number of groups, 1 or more; received ${JSON.stringify(limit)}.`); + } + if (columns.includes(AGGREGATE_GROUP_COUNT_COLUMN)) { + throw refusal( + object, + `the aggregated row already projects a column named '${AGGREGATE_GROUP_COUNT_COLUMN}', the name the group count ` + + 'is answered under. Rename that alias.', + ); + } + const known = columns.length > 0 ? columns.join(', ') : '(none — the query projects no column)'; + const seen = new Set(); + for (const [i, key] of orderBy.entries()) { + const field = (key as { field?: unknown } | null)?.field; + const order = (key as { order?: unknown } | null)?.order; + if (typeof field !== 'string' || field === '' || (order !== 'asc' && order !== 'desc')) { + throw refusal(object, `\`orderBy[${i}]\` must be { field, order: 'asc' | 'desc' }.`); + } + if (!columns.includes(field)) { + throw refusal( + object, + `\`orderBy[${i}]\` names '${field}', which is not a column of the aggregated row. Groups are ordered by ` + + `the row's own columns — the aggregation aliases and the groupBy projections — which here are: ${known}.`, + StandardErrorCode.enum.INVALID_SORT, + ); + } + if (seen.has(field)) throw refusal(object, `\`orderBy\` names '${field}' twice.`); + seen.add(field); + } +} + +/** + * Why the engine cannot serve the cut for this read, or `undefined` when it + * can — judged once the driver and the path the aggregate takes are known, + * before the driver is asked. ⛔ No answer here means "compute it some other + * way": every reason is a refusal. + */ +export function aggregateOrderCutRefusal( + object: string, + facts: { + readonly driver: { readonly name?: unknown; readonly aggregate?: unknown } | undefined; + /** The aggregate is answered by the driver's own statement (no in-memory tier). */ + readonly nativeAggregate: boolean; + readonly hasHaving: boolean; + readonly hasRelationGroup: boolean; + }, +): Error | undefined { + if (!driverCompilesAggregateOrderCut(facts.driver)) { + return refusal( + object, + `this read's driver '${driverNameOf(facts.driver)}' does not order and cut groups in its own statement, and ` + + 'the groups are never ordered or cut in the application instead. Ask without an order and a limit, or query ' + + 'an object stored in a SQL database.', + ); + } + if (facts.hasHaving) { + return refusal( + object, + '`having` is applied after the driver answers, so a cut in the statement would cut before it. Ask without ' + + '`having`, or without an order and a limit.', + ); + } + if (facts.hasRelationGroup) { + return refusal(object, 'grouping through a relation is not ordered or cut. Ask without an order and a limit.'); + } + if (!facts.nativeAggregate) { + return refusal( + object, + 'this aggregate is computed in the application, not by the driver (a date bucket the driver does not ' + + 'compile, a reference timezone it does not bucket, or a measure filter it does not evaluate), and its groups ' + + 'are never ordered or cut there. Ask without the order and the limit, or without that part of the aggregate.', + ); + } + return undefined; +} + +/** + * The full order the driver applies: the request's keys, then every group key + * column the request does not name, ascending — so the answer is the same + * groups in the same order on every run. + */ +export function aggregateOrderCutDirective( + request: AggregateOrderCutRequest, + groupColumns: readonly string[], +): DriverAggregateOrderCut { + const named = new Set(request.orderBy.map((k) => k.field)); + return { + orderBy: [ + ...request.orderBy.map((k) => ({ column: k.field, order: k.order })), + ...groupColumns.filter((c) => !named.has(c)).map((column) => ({ column, order: 'asc' as const })), + ], + ...(request.limit !== undefined ? { limit: request.limit } : {}), + groupCountColumn: AGGREGATE_GROUP_COUNT_COLUMN, + }; +} + +/** `ast` with the directive on it, under its symbol key (a copy; `ast` is not changed). */ +export function withAggregateOrderCutDirective(ast: T, directive: DriverAggregateOrderCut): T { + return { ...ast, [AGGREGATE_ORDER_CUT_DIRECTIVE]: directive } as T; +} + +/** + * Take the group count off the driver's rows and write the outcome. Every row + * must carry the same count; zero rows is zero groups. A row without it means + * the driver did not serve the cut: a server fault, never an answer. + */ +export function takeAggregateGroupCount( + object: string, + driver: { readonly name?: unknown } | undefined, + rows: unknown, + request: AggregateOrderCutRequest, +): Record[] { + const list = Array.isArray(rows) ? (rows as Array>) : []; + let groupCount = 0; + const out = list.map((row, i) => { + const raw = row?.[AGGREGATE_GROUP_COUNT_COLUMN]; + const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : Number.NaN; + if (!Number.isInteger(n) || n < list.length || (i > 0 && n !== groupCount)) { + const err = new Error( + `aggregate('${object}'): the driver '${driverNameOf(driver)}' answered an ordered and cut aggregate without ` + + 'the group count of its own statement, so its rows are not the answer and none is returned.', + ) as CodedError; + err.code = StandardErrorCode.enum.INTERNAL_ERROR; + err.status = 500; + err.httpStatus = 500; + throw err; + } + groupCount = n; + const { [AGGREGATE_GROUP_COUNT_COLUMN]: _count, ...rest } = row; + return rest; + }); + request.outcome = { kind: 'served', groupCount }; + return out; +} diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 135f4476944..8e3eca7ce81 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -80,6 +80,10 @@ import { } from './engine-top-level.js'; import type { EngineReadOptions, OperationContext } from './engine-top-level.js'; import { RELATION_SCOPE_PLAN, type RelationScopePlan } from './relation-semi-join.js'; +import { + aggregateOrderCutDirective, aggregateOrderCutRefusal, aggregateOrderCutRequestOf, assertAggregateOrderCutShape, + takeAggregateGroupCount, withAggregateOrderCutDirective, +} from './aggregate-order-cut.js'; import { assertRelationGroupRequestShape, assertRelationGroupRowsJoined, declineRelationGroup, planRelationGroups, RELATION_GROUP_JOINS, relationFieldsJudgedAsGroupKeys, relationGroupByRequestOf, relationGroupJoinsAtBoundary, @@ -971,6 +975,12 @@ export class DeleteAndAggregateFacet { // related read a relation group join is built from is this verb, // stopped at its driver call. Only the engine's own planner sets it. const scopePlan = (options as Record | undefined)?.[RELATION_SCOPE_PLAN] as RelationScopePlan | undefined; + // [aggregate order and cut] The engine-internal request to order the + // groups by an aggregated column, cut them and count them, in the + // driver's own statement (`aggregate-order-cut.ts`). Its shape is judged + // once every door below has judged the query; the driver and the path + // are judged at the driver call. + const orderCut = aggregateOrderCutRequestOf(options); // Fold the `filter` alias into `where` (#4346) — the AST below reads // `query.where` only, so an unfolded `{ filter }` aggregated every row. query = foldEngineOptionAliases(object, 'aggregate', query, ENGINE_WHERE_SLOTS); @@ -1303,6 +1313,11 @@ export class DeleteAndAggregateFacet { ); if (numeric !== query.having) query = { ...query, having: numeric }; } + // [aggregate order and cut] Every door above has judged the query; now + // the request's order keys against the aggregated row it orders. + if (orderCut !== undefined) { + assertAggregateOrderCutShape(object, orderCut, aggregatedRowColumns(query.groupBy, query.aggregations)); + } const driver = this.getDriver(object); this.logger.debug(`Aggregate on ${object} using ${driver.name}`, query); // [relation group join] Every door above has judged the base query; @@ -1486,6 +1501,21 @@ export class DeleteAndAggregateFacet { }); const aggregationFilterNative = drv?.supports?.aggregationFilter === true; const nativeAggregate = typeof drv.aggregate === 'function' && allStructuredSupported && !tzRequiresInMemory && (!hasAggregationFilter || aggregationFilterNative); + // [aggregate order and cut] Served only as the driver's own statement, + // and refused — before the driver is asked — on every path that is not + // one (`aggregateOrderCutRefusal`): no in-memory sort, no slower path. + if (orderCut !== undefined) { + const refused = aggregateOrderCutRefusal(object, { + driver: drv, + nativeAggregate, + hasHaving: ast.having != null && typeof ast.having === 'object' && Object.keys(ast.having).length > 0, + hasRelationGroup: relationGroup !== undefined, + }); + if (refused !== undefined) throw refused; + const directive = aggregateOrderCutDirective(orderCut, aggregatedRowColumns(ast.groupBy, [])); + const cut = await drv.aggregate(object, withBucketZone(withAggregateOrderCutDirective(ast, directive)), aggregateOptions); + return takeAggregateGroupCount(object, drv, cut, orderCut); + } // [relation group join] Served only as the driver's own statement: // the rows path below cannot join. Each planned related read is // answered at this boundary, under these driver options, by the rule diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 2d6bbf5d74d..99d9360f611 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -269,6 +269,12 @@ export type { DatasourceDef } from './engine.js'; // refuses the filter rather than truncate it, and its words name this number. // Exported so a caller running the two-step route itself can page by it. export { RELATION_FILTER_ID_CAP } from './relation-filter-lowering.js'; +// Groups ordered by an aggregated column, cut and counted in the driver's own +// statement: the engine-internal read option a door carries to `aggregate`, +// and the request it carries. Carriers that do not import this package spell +// the key `Symbol.for`, as it does. +export { AGGREGATE_ORDER_CUT } from './aggregate-order-cut.js'; +export type { AggregateOrderCutRequest, AggregateOrderKey, AggregateOrderCutOutcome } from './aggregate-order-cut.js'; // [#16159] `SUMMARY_RECOMPUTE_CODE` joins the class it names. The refusal's own // docblock tells a caller to identify it by `code` rather than `instanceof` // (the two-realm split #14936 measured: this package declares BOTH realms in diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index d9aad0e2798..590e5fbeeb1 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -114,6 +114,8 @@ import { servedRecordTitle, standaloneActionOwnerKey, SummaryRecomputeError, + AGGREGATE_ORDER_CUT, + type AggregateOrderCutRequest, type PackageScopedRefusal, type PackageScopedRegistry, } from '@objectstack/objectql'; @@ -961,6 +963,13 @@ export async function callData(deps: ActionExecutionDeps, groupBy: params.groupBy, aggregations: params.aggregations, }); + // [aggregate order and cut] The engine's order-cut-count request, + // when an in-process door (the MCP tools) set it on `params` under + // the engine's own symbol key — never a wire key. Handed to the + // engine as its read option and read back: a read that comes back + // without the engine's outcome on it was not ordered and cut in + // the driver's statement, and its rows are no answer. + const orderCut = (params as Record | undefined)?.[AGGREGATE_ORDER_CUT] as AggregateOrderCutRequest | undefined; const rows = await engine.aggregate( params.object, { @@ -970,8 +979,17 @@ export async function callData(deps: ActionExecutionDeps, ...(params.timezone ? { timezone: params.timezone } : {}), ...(executionContext ? { context: executionContext } : {}), }, + ...(orderCut !== undefined ? [{ [AGGREGATE_ORDER_CUT]: orderCut }] as const : [] as const), ); - return { object: params.object, rows: rows ?? [] }; + if (orderCut === undefined) return { object: params.object, rows: rows ?? [] }; + if (orderCut.outcome?.kind !== 'served') { + throw { + statusCode: 500, + message: `The ordered and cut aggregate of '${params.object}' came back without being served by the ` + + 'driver\'s own statement, so its rows are not the answer and none is returned.', + }; + } + return { object: params.object, rows: rows ?? [], groupCount: orderCut.outcome.groupCount }; } throw { statusCode: 503, message: 'Data service not available' }; } diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index fba506411a7..df28bb65ca3 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -48,6 +48,9 @@ import { resolveOpenAuthoringInjection } from './mcp-authoring.js'; // [#28715] The engine's own reading of "this field declares options" (its // `label()` map is built from it), never a second spelling here. import { declaresOptions } from '@objectstack/formula'; +// The engine's order-cut-count read option for `aggregate` (and the request it +// carries): `aggregate_records`' ranking form rides to the engine on it. +import { AGGREGATE_ORDER_CUT, type AggregateOrderCutRequest } from '@objectstack/objectql'; import { RUNTIME_OWNED_FIELD_TYPES, SEARCH_COMPANION_FIELD, isVirtualSearchField } from '@objectstack/spec/data'; // [#15705] The resume door's one refusal table, shared with // `POST /automation/:name/runs/:runId/resume` so the two doors answer one @@ -1243,6 +1246,41 @@ export function buildMcpBridge( ); return res?.rows ?? []; }, + /** + * [aggregate order and cut] `aggregate_records` with an `orderBy` / + * `limit`: the same engine door as `aggregate` above, with the + * engine's request on its own symbol key (never a wire key). `callData` + * reads the engine's outcome back and answers its `groupCount`; a read + * the driver's statement did not serve is refused there. + */ + aggregateGroups: async (object: string, o: any) => { + const orderCut: AggregateOrderCutRequest = { + orderBy: o.orderBy, + ...(typeof o?.limit === 'number' ? { limit: o.limit } : {}), + }; + const res: any = await callData( + 'aggregate', + { + object, + where: o?.where, + groupBy: o?.groupBy, + aggregations: o?.aggregations, + timezone: o?.timezone, + [AGGREGATE_ORDER_CUT]: orderCut, + }, + undefined, + envId, + ec, + ); + if (typeof res?.groupCount !== 'number') { + throw { + statusCode: 500, + message: `The ordered and cut aggregate of '${object}' came back without its group count, so its ` + + 'rows are not the answer and none is returned.', + }; + } + return { rows: res?.rows ?? [], groupCount: res.groupCount }; + }, // ── Skill metadata → MCP prompts (#3905) ────────────────── // ADR-0063 §2 names skills the only third-party extension primitive, From d7c2e8e1a33386a6b63b5c9489f7141083fa34e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:11:34 +0000 Subject: [PATCH 02/10] test(objectql,driver-sql): pin the aggregate order-and-cut directive Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../sql-driver-aggregate-order-cut.test.ts | 163 +++++++++++++ .../objectql/src/aggregate-order-cut.test.ts | 217 ++++++++++++++++++ packages/runtime/src/action-execution.ts | 4 +- 3 files changed, 383 insertions(+), 1 deletion(-) create mode 100644 packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts create mode 100644 packages/objectql/src/aggregate-order-cut.test.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts new file mode 100644 index 00000000000..c40c3ca44f7 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts @@ -0,0 +1,163 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [aggregate order and cut] `aggregate()` compiles the order-and-cut directive + * the engine hands it (objectql `aggregate-order-cut.ts`) into its own + * statement: the grouped statement as a derived table, `count(*) over ()` for + * the groups it formed, and ORDER BY / LIMIT over the derived table's columns. + * + * Pinned here: the top N by a measure, in order, with the count of every group + * before the cut (more groups than the cut, as a top-N over a large set asks); + * an order by a group key; a `sum` whose group has no value ranks as the `0` it + * is served as, in either direction; a NULL group key ranks last in either + * direction; the cut inside the tenant wall and the `where`; the statement + * itself carries the ORDER BY, the LIMIT and the window (a query spy, so an + * in-application sort cannot pass); and a malformed directive, or one ordering + * by a column the statement does not project, refused before anything runs. + * + * Every live cell runs where the suite provisions it (`OS_TEST_POSTGRES_URL`, + * `OS_TEST_MYSQL_URL`); SQLite always runs. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { DriverQuery } from '@objectstack/spec/contracts'; +import { SqlDriver } from './sql-driver.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; +import { AGGREGATE_ORDER_CUT_DIRECTIVE, type AggregateOrderCutDirective } from './sql-driver-aggregation.js'; + +const TABLE = 'os_agg_order_cut_order'; +const COUNT_COLUMN = '__os_group_count'; + +/** + * 60 customers `c00`..`c59` in org_a, each with two orders (`i * 10` and `5`), + * so customer `cNN` totals `NN * 10 + 5`; `cnull` has one order with no amount + * (its `sum` is NULL in SQL, served as `0`); one order has no customer (a NULL + * group key); org_b holds a customer `cz` richer than all of them. + */ +function orders(): Array> { + const rows: Array> = []; + for (let i = 0; i < 60; i++) { + const c = `c${String(i).padStart(2, '0')}`; + rows.push({ id: `${c}-a`, customer: c, amount: i * 10, status: 'won', organization_id: 'org_a' }); + rows.push({ id: `${c}-b`, customer: c, amount: 5, status: i % 2 === 0 ? 'won' : 'lost', organization_id: 'org_a' }); + } + rows.push({ id: 'n-1', customer: 'cnull', amount: null, status: 'won', organization_id: 'org_a' }); + rows.push({ id: 'k-1', customer: null, amount: 1, status: 'won', organization_id: 'org_a' }); + rows.push({ id: 'z-1', customer: 'cz', amount: 99999, status: 'won', organization_id: 'org_b' }); + return rows; +} + +const REVENUE = [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }]; + +const query = (directive: unknown, over: Partial = {}): DriverQuery => ({ + groupBy: ['customer'], + aggregations: REVENUE, + ...over, + [AGGREGATE_ORDER_CUT_DIRECTIVE]: directive, +} as unknown as DriverQuery); + +const cut = ( + orderBy: AggregateOrderCutDirective['orderBy'], + limit?: number, +): AggregateOrderCutDirective => ({ orderBy, ...(limit !== undefined ? { limit } : {}), groupCountColumn: COUNT_COLUMN }); + +const customers = (rows: Array>) => rows.map((r) => r.customer); + +function declareCell(cell: DialectCell): void { + describe(`[aggregate order and cut] driver-sql — aggregate orders, cuts and counts groups (${cell.label})`, () => { + let driver: SqlDriver; + const OLD_POSTURE = process.env.OS_TENANCY_POSTURE; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + driver = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.initObjects([ + { + name: TABLE, + fields: { + customer: { type: 'text' }, amount: { type: 'number' }, status: { type: 'text' }, + organization_id: { type: 'text' }, + }, + }, + ] as never); + for (const row of orders()) await driver.create(TABLE, { ...row }, { bypassTenantAudit: true }); + }); + + afterAll(async () => { + await driver?.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + it('the top five by a measure, in order, and every group counted before the cut', async () => { + const rows = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }, { column: 'customer', order: 'asc' }], 5)), { tenantId: 'org_a' }); + expect(customers(rows)).toEqual(['c59', 'c58', 'c57', 'c56', 'c55']); + expect(rows.map((r) => r.revenue)).toEqual([595, 585, 575, 565, 555]); + // 60 customers, `cnull` and the NULL customer: 62 groups in org_a. + expect(rows.map((r) => r[COUNT_COLUMN])).toEqual([62, 62, 62, 62, 62]); + }); + + it('a sum with no value ranks as the 0 it is served as; a NULL group key ranks last either way', async () => { + const asc = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'asc' }, { column: 'customer', order: 'asc' }], 3)), { tenantId: 'org_a' }); + expect(customers(asc)).toEqual(['cnull', null, 'c00']); + expect(asc.map((r) => r.revenue)).toEqual([0, 1, 5]); + const byKeyAsc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'asc' }])), { tenantId: 'org_a' }); + expect(customers(byKeyAsc).slice(0, 3)).toEqual(['c00', 'c01', 'c02']); + expect(customers(byKeyAsc).at(-1)).toBeNull(); + const byKeyDesc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'desc' }], 62)), { tenantId: 'org_a' }); + expect(customers(byKeyDesc).slice(0, 2)).toEqual(['cnull', 'c59']); + expect(customers(byKeyDesc).at(-1)).toBeNull(); + }); + + it('the cut runs inside the tenant wall and the where', async () => { + const lost = await driver.aggregate( + TABLE, + query(cut([{ column: 'revenue', order: 'desc' }, { column: 'customer', order: 'asc' }], 2), { where: { status: 'lost' } }), + { tenantId: 'org_a' }, + ); + // `lost` orders: the 30 odd customers' 5s — every one ties at 5, the group key breaks it. + expect(customers(lost)).toEqual(['c01', 'c03']); + expect(lost[0][COUNT_COLUMN]).toBe(30); + const other = await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }], 5)), { tenantId: 'org_b' }); + expect(customers(other)).toEqual(['cz']); + expect(other[0][COUNT_COLUMN]).toBe(1); + }); + + it('the ORDER BY, the LIMIT and the group count are in the statement, not applied after it', async () => { + const seen: string[] = []; + const knex = (driver as unknown as { knex: { on: Function; off: Function } }).knex; + const listen = (q: { sql: string }) => { seen.push(q.sql); }; + knex.on('query', listen); + try { + await driver.aggregate(TABLE, query(cut([{ column: 'revenue', order: 'desc' }], 5)), { tenantId: 'org_a' }); + } finally { + knex.off('query', listen); + } + const statement = seen.find((s) => /count\(\*\) over \(\)/i.test(s)); + expect(statement, seen.join('\n')).toBeDefined(); + expect(statement).toMatch(/order by .*revenue/i); + expect(statement).toMatch(/\blimit\b|\bfetch\b|\btop\b/i); + expect(statement).toMatch(/group by/i); + }); + + it('CONTROL — no directive: the grouped answer as before, no count column', async () => { + const rows = await driver.aggregate(TABLE, { groupBy: ['customer'], aggregations: REVENUE } as DriverQuery, { tenantId: 'org_a' }); + expect(rows).toHaveLength(62); + expect(rows[0]).not.toHaveProperty(COUNT_COLUMN); + }); + + it('a malformed directive, or an order by a column the statement does not project, is refused before it runs', async () => { + const malformed = await driver.aggregate(TABLE, query({ orderBy: 'revenue' }), { tenantId: 'org_a' }) + .then(() => null, (e: Error & { code?: string }) => e); + expect(malformed?.code).toBe('INTERNAL_ERROR'); + const unprojected = await driver.aggregate(TABLE, query(cut([{ column: 'amount', order: 'desc' }])), { tenantId: 'org_a' }) + .then(() => null, (e: Error & { code?: string }) => e); + expect(unprojected?.code).toBe('INTERNAL_ERROR'); + expect(unprojected?.message).toMatch(/'amount'/); + }); + }); +} + +for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'aggregate order and cut', declareCell); diff --git a/packages/objectql/src/aggregate-order-cut.test.ts b/packages/objectql/src/aggregate-order-cut.test.ts new file mode 100644 index 00000000000..11ce3b4f51d --- /dev/null +++ b/packages/objectql/src/aggregate-order-cut.test.ts @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [aggregate order and cut] `engine.aggregate` with the order-cut-count read + * option (`aggregate-order-cut.ts`): served only as the driver's own + * statement, judged before the driver is asked. + * + * A recording driver stands in for the SQL family: it is named as one, answers + * the rows a test sets and records the AST it was handed. What `driver-sql` + * compiles from the directive is pinned in + * `driver-sql/src/sql-driver-aggregate-order-cut.test.ts`; end to end over a + * real SQLite database and the MCP tool, in + * `runtime/src/mcp-aggregate-order-cut.test.ts`. + * + * Pinned here: the directive the driver receives (the request's keys, then + * the group keys it does not name, ascending; the limit; the count column); + * the count taken off the rows into the request's outcome; an order key that + * names no column of the aggregated row refused `INVALID_SORT`, naming the + * columns; every driver and path that is not the driver's own statement + * refused `INVALID_QUERY` with the driver never asked (the in-memory driver, + * an unnamed driver, a `having`, a reference zone bucketed in memory); and + * rows that come back without the count refused as a fault, never served. + */ + +import { describe, it, expect, beforeEach } from 'vitest'; +import { ObjectQL } from './engine.js'; +import { + AGGREGATE_GROUP_COUNT_COLUMN, + AGGREGATE_ORDER_CUT, + AGGREGATE_ORDER_CUT_DIRECTIVE, + type AggregateOrderCutRequest, +} from './aggregate-order-cut.js'; + +const ORDER = 'oc_order'; +const ORDER_OBJECT = { + name: ORDER, + label: 'Order', + fields: { + amount: { name: 'amount', type: 'number' }, + customer: { name: 'customer', type: 'text' }, + region: { name: 'region', type: 'text' }, + closed_on: { name: 'closed_on', type: 'date' }, + }, +}; + +interface SeenCall { verb: string; ast: any } + +function makeRecordingDriver(name: string, supports: Record = {}) { + const calls: SeenCall[] = []; + let answer: Array> = []; + const driver: any = { + name, version: '0.0.0', supports, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(_o: string, ast: any) { calls.push({ verb: 'find', ast }); return []; }, + async findOne(_o: string, ast: any) { calls.push({ verb: 'findOne', ast }); return null; }, + async count(_o: string, ast: any) { calls.push({ verb: 'count', ast }); return 0; }, + async aggregate(_o: string, ast: any) { calls.push({ verb: 'aggregate', ast }); return answer.map((r) => ({ ...r })); }, + async create(_o: string, data: Record) { return { ...data }; }, + async update(_o: string, id: string, data: Record) { return { ...data, id }; }, + async delete() { return true; }, + async beginTransaction() { return {}; }, + async commit() {}, async rollback() {}, + }; + return { driver, calls, answer: (rows: Array>) => { answer = rows; } }; +} + +async function makeEngine(driverName: string, supports?: Record) { + const rec = makeRecordingDriver(driverName, supports); + const engine = new ObjectQL(); + engine.registerDriver(rec.driver, true); + await engine.init(); + engine.registry.registerObject(ORDER_OBJECT as any, 'test'); + return { engine, rec }; +} + +type Thrown = (Error & { code?: string; status?: number; httpStatus?: number }) | null; +const refusalOf = async (p: Promise): Promise => p.then(() => null, (e: any) => e); + +const BY_CUSTOMER = { + groupBy: ['customer', { field: 'region', alias: 'area' }], + aggregations: [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }, { function: 'count' as const, alias: 'n' }], +}; +const TOP_TWO = (): AggregateOrderCutRequest => ({ orderBy: [{ field: 'revenue', order: 'desc' }], limit: 2 }); +const withCut = (request: AggregateOrderCutRequest) => ({ [AGGREGATE_ORDER_CUT]: request }) as any; + +describe('[aggregate order and cut] engine.aggregate — served as the driver\'s own statement', () => { + let engine: ObjectQL; + let rec: ReturnType; + + beforeEach(async () => { + ({ engine, rec } = await makeEngine('com.objectstack.driver.sql')); + }); + + it('hands the driver the order (the request\'s keys, then the unnamed group keys ascending), the limit and the count column; takes the count off the rows', async () => { + rec.answer([ + { customer: 'c9', area: 'west', revenue: 90, n: 3, [AGGREGATE_GROUP_COUNT_COLUMN]: 7 }, + { customer: 'c8', area: 'east', revenue: 80, n: 2, [AGGREGATE_GROUP_COUNT_COLUMN]: 7 }, + ]); + const request = TOP_TWO(); + const rows = await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request)); + expect(rows).toEqual([ + { customer: 'c9', area: 'west', revenue: 90, n: 3 }, + { customer: 'c8', area: 'east', revenue: 80, n: 2 }, + ]); + expect(request.outcome).toEqual({ kind: 'served', groupCount: 7 }); + expect(rec.calls).toHaveLength(1); + expect(rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE]).toEqual({ + orderBy: [ + { column: 'revenue', order: 'desc' }, + { column: 'customer', order: 'asc' }, + { column: 'area', order: 'asc' }, + ], + limit: 2, + groupCountColumn: AGGREGATE_GROUP_COUNT_COLUMN, + }); + }); + + it('orders by a group key under its alias; no limit orders and counts every group; zero rows is zero groups', async () => { + rec.answer([]); + const request: AggregateOrderCutRequest = { orderBy: [{ field: 'area', order: 'desc' }] }; + expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))).toEqual([]); + expect(request.outcome).toEqual({ kind: 'served', groupCount: 0 }); + const directive = rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE]; + expect(directive.orderBy[0]).toEqual({ column: 'area', order: 'desc' }); + expect(directive).not.toHaveProperty('limit'); + }); + + it('an order key that names no column of the aggregated row is INVALID_SORT, naming the columns, and the driver is never asked', async () => { + for (const field of ['amount', 'region', 'nope']) { + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut({ orderBy: [{ field, order: 'desc' }] }))); + expect(err?.code, field).toBe('INVALID_SORT'); + expect(err?.status).toBe(400); + expect(err?.message).toContain(`'${field}'`); + expect(err?.message).toContain('customer, area, revenue, n'); + } + expect(rec.calls).toEqual([]); + }); + + it('a malformed request is INVALID_QUERY, and the driver is never asked', async () => { + for (const bad of [ + { orderBy: 'revenue' }, + { orderBy: [{ field: 'revenue', order: 'down' }] }, + { orderBy: [], limit: 0 }, + { orderBy: [], limit: 2.5 }, + { orderBy: [{ field: 'revenue', order: 'asc' }, { field: 'revenue', order: 'desc' }] }, + ]) { + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(bad as any))); + expect(err?.code, JSON.stringify(bad)).toBe('INVALID_QUERY'); + expect(err?.status).toBe(400); + } + expect(rec.calls).toEqual([]); + }); + + it('a having is refused: it is applied after the driver, so a cut in the statement would cut before it', async () => { + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER, having: { revenue: { $gt: 10 } } }, withCut(TOP_TWO()))); + expect(err?.code).toBe('INVALID_QUERY'); + expect(err?.message).toMatch(/having/); + expect(rec.calls).toEqual([]); + }); + + it('an aggregate the engine computes in memory (a zone the driver does not bucket) is refused, never sorted in memory', async () => { + const err = await refusalOf(engine.aggregate(ORDER, { + groupBy: [{ field: 'closed_on', dateGranularity: 'month' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'Asia/Shanghai', + }, withCut({ orderBy: [{ field: 'n', order: 'desc' }], limit: 3 }))); + expect(err?.code).toBe('INVALID_QUERY'); + expect(err?.message).toMatch(/computed in the application/); + expect(rec.calls).toEqual([]); + }); + + it('rows that come back without the group count are a fault, never served', async () => { + rec.answer([{ customer: 'c9', area: 'west', revenue: 90, n: 3 }]); + const request = TOP_TWO(); + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))); + expect(err?.code).toBe('INTERNAL_ERROR'); + expect(err?.status).toBe(500); + expect(request.outcome).toBeUndefined(); + }); + + it('CONTROL — no request: the aggregate reaches the driver with no directive, exactly as before', async () => { + rec.answer([{ customer: 'c9', area: 'west', revenue: 90, n: 3 }]); + expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER })).toEqual([{ customer: 'c9', area: 'west', revenue: 90, n: 3 }]); + expect(rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE]).toBeUndefined(); + }); +}); + +describe('[aggregate order and cut] engine.aggregate — refused on every driver that does not compile it', () => { + for (const [name, mode] of [ + ['com.objectstack.driver.memory', undefined], + ['com.objectstack.driver.mongodb', undefined], + ['com.objectstack.driver.turso', 'remote'], + ['some.unnamed.driver', undefined], + ] as const) { + it(`${name}${mode ? ` (${mode})` : ''}: INVALID_QUERY / 400, the driver never asked`, async () => { + const { engine, rec } = await makeEngine(name); + if (mode) rec.driver.transportMode = mode; + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(TOP_TWO()))); + expect(err?.code).toBe('INVALID_QUERY'); + expect(err?.status).toBe(400); + expect(err?.httpStatus).toBe(400); + expect(err?.message).toContain(`'${name}'`); + expect(rec.calls).toEqual([]); + }); + } + + it('the Turso driver\'s local face and the WASM SQLite driver are served', async () => { + for (const [name, mode] of [['com.objectstack.driver.turso', 'local'], ['com.objectstack.driver.sqlite-wasm', undefined]] as const) { + const { engine, rec } = await makeEngine(name); + if (mode) rec.driver.transportMode = mode; + rec.answer([]); + const request = TOP_TWO(); + await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request)); + expect(request.outcome, name).toEqual({ kind: 'served', groupCount: 0 }); + } + }); +}); diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 590e5fbeeb1..4228ff450f0 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -979,7 +979,9 @@ export async function callData(deps: ActionExecutionDeps, ...(params.timezone ? { timezone: params.timezone } : {}), ...(executionContext ? { context: executionContext } : {}), }, - ...(orderCut !== undefined ? [{ [AGGREGATE_ORDER_CUT]: orderCut }] as const : [] as const), + ...(orderCut !== undefined + ? [{ [AGGREGATE_ORDER_CUT]: orderCut } as Parameters[2]] as const + : [] as const), ); if (orderCut === undefined) return { object: params.object, rows: rows ?? [] }; if (orderCut.outcome?.kind !== 'served') { From 7d9612efabf3a18ab44891260a0a2589e9dc3e49 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:15:36 +0000 Subject: [PATCH 03/10] test(mcp,runtime): pin aggregate_records order, cut and group count over HTTP and stdio; changeset Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .changeset/35144-aggregate-order-cut.md | 21 +++ .../mcp-http-tools.aggregation-entry.test.ts | 124 ++++++++++++++ ...io-data-bridge.aggregate-order-cut.test.ts | 160 ++++++++++++++++++ .../src/mcp-aggregate-order-cut.test.ts | 109 ++++++++++++ 4 files changed, 414 insertions(+) create mode 100644 .changeset/35144-aggregate-order-cut.md create mode 100644 packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts create mode 100644 packages/runtime/src/mcp-aggregate-order-cut.test.ts diff --git a/.changeset/35144-aggregate-order-cut.md b/.changeset/35144-aggregate-order-cut.md new file mode 100644 index 00000000000..b2c37841f00 --- /dev/null +++ b/.changeset/35144-aggregate-order-cut.md @@ -0,0 +1,21 @@ +--- +'@objectstack/mcp': patch +'@objectstack/objectql': patch +'@objectstack/driver-sql': patch +'@objectstack/driver-turso': patch +'@objectstack/runtime': patch +--- + +feat(mcp): `aggregate_records` orders, cuts and counts its groups in the database + +Clause-②: yes (widening: `orderBy` and `limit` arguments on `aggregate_records`, and `groupCount` in its result) +Metadata-protocol: none + +A ranking question ("the top five customers by revenue") over more groups than the tool's row cap used to come back as every group, or the first page of them, in no stated order, and the client ranked what it happened to get. `aggregate_records` now takes `orderBy` — a list of `{ field, order }` naming an aggregation alias or a group key (its alias when it has one) — and `limit` (at most the row cap). The database orders the groups, cuts them, and counts how many groups it formed before the cut, in one statement; the result carries the groups, `groupCount`, and `truncated: true` when more groups existed than came back. + +- An order key that names no column of the aggregated row is refused `INVALID_SORT` / 400, naming the columns the query projects. +- Only a driver that runs the cut in its own SQL statement serves it: `driver-sql` (every dialect it speaks; the window `count(*) over ()` needs MySQL 8 or later), the WASM SQLite driver, and the Turso driver's local and replica faces. Every other driver (the in-memory driver, MongoDB, OData, Turso's remote face), an aggregate the engine computes in memory (a date bucket, a reference timezone or a measure filter the driver does not run), and an aggregate with `having` are refused `INVALID_QUERY` / 400 before anything is read. Groups are never ordered or cut in the application. +- A NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name break ties, ascending. +- Without `orderBy` and `limit` the tool answers as before, now with `groupCount` beside `totalGroups` (the same number). + +`@objectstack/objectql` exports `AGGREGATE_ORDER_CUT`, the engine-internal read option of `aggregate` that carries the request (a symbol, so no wire request can set it), with the `AggregateOrderCutRequest`, `AggregateOrderKey` and `AggregateOrderCutOutcome` types. `McpDataBridge` gains the optional member `aggregateGroups`; a bridge without it refuses `orderBy` / `limit` with `NOT_IMPLEMENTED` / 501 and keeps serving the rest of the tool. Nothing that was accepted before is refused. diff --git a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts index 14a216767aa..cfc4dcf6a45 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -205,3 +205,127 @@ describe('aggregate_records — the aggregation entry (#28550)', () => { expect(entry?.required).toEqual(expect.arrayContaining(['function', 'alias'])); }); }); + +/** + * [aggregate order and cut] A ranking question ("the top five customers by + * revenue") over more groups than the row cap: the tool hands the bridge's + * `aggregateGroups` the order and the cut plus one probe group, serves exactly + * the groups asked for in the order the bridge answered, and states the + * statement's own count of the groups before the cut (`groupCount`) and + * whether more existed (`truncated`). It never sorts or slices an uncut list: + * a bridge without `aggregateGroups` is refused, and the uncut path is not + * asked. The engine and driver halves are pinned in `@objectstack/objectql` + * (`aggregate-order-cut.test.ts`) and `@objectstack/driver-sql` + * (`sql-driver-aggregate-order-cut.test.ts`); the stdio bridge in + * `stdio-data-bridge.aggregate-order-cut.test.ts`; over a real SQLite database + * through the HTTP bridge in `@objectstack/runtime` + * (`mcp-aggregate-order-cut.test.ts`). + */ +describe('aggregate_records — ordered, cut and counted groups', () => { + const CAP = 50; + /** 120 customers, more than the cap: the bridge answers in its own (database) order. */ + const groups = Array.from({ length: 120 }, (_, i) => ({ customer: `c${String(119 - i).padStart(3, '0')}`, revenue: (119 - i) * 10 })); + + function makeCutBridge() { + const bridge = makeBridge() as RecordingBridge & { cuts: any[] }; + bridge.cuts = []; + bridge.aggregateGroups = async (object: string, opts: any) => { + bridge.cuts.push([object, opts]); + const ordered = opts.orderBy[0]?.field === 'customer' && opts.orderBy[0]?.order === 'asc' ? [...groups].reverse() : groups; + return { rows: ordered.slice(0, opts.limit), groupCount: groups.length }; + }; + return bridge; + } + + let runtime: MCPServerRuntime; + beforeEach(() => { runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); }); + + const call = async (bridge: RecordingBridge, args: Record) => { + const res = await aggregate(runtime, bridge, { objectName: 'showcase_project', aggregations: [{ function: 'sum', field: 'amount', alias: 'revenue' }], groupBy: ['customer'], ...args }); + return { ...res, body: res.refused ? undefined : JSON.parse(res.text) }; + }; + + it('top five by a measure over more groups than the cap: exactly five, in order, with the total number of groups', async () => { + const bridge = makeCutBridge(); + const { refused, text, body } = await call(bridge, { orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(refused, text).toBe(false); + expect(body.rows.map((r: any) => r.customer)).toEqual(['c119', 'c118', 'c117', 'c116', 'c115']); + expect(body.groupCount).toBe(120); + expect(body.truncated).toBe(true); + // The order and the cut went to the bridge — one probe group past the limit — and the uncut path was never asked. + expect(bridge.cuts).toHaveLength(1); + expect(bridge.cuts[0][1]).toMatchObject({ orderBy: [{ field: 'revenue', order: 'desc' }], limit: 6, groupBy: ['customer'] }); + expect(bridge.calls).toEqual([]); + }); + + it('ordered by a group key, ascending', async () => { + const bridge = makeCutBridge(); + const { body } = await call(bridge, { orderBy: [{ field: 'customer', order: 'asc' }], limit: 3 }); + expect(body.rows.map((r: any) => r.customer)).toEqual(['c000', 'c001', 'c002']); + expect(body.groupCount).toBe(120); + }); + + it('an order with no limit is cut at the cap, and says so', async () => { + const bridge = makeCutBridge(); + const { body } = await call(bridge, { orderBy: [{ field: 'revenue', order: 'desc' }] }); + expect(body.rows).toHaveLength(CAP); + expect(body.truncated).toBe(true); + expect(bridge.cuts[0][1].limit).toBe(CAP + 1); + }); + + it('a cut that drops nothing carries no truncated flag', async () => { + const bridge = makeBridge() as RecordingBridge; + bridge.aggregateGroups = async () => ({ rows: [{ customer: 'a', revenue: 1 }], groupCount: 1 }); + const { body } = await call(bridge, { orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(body).toEqual({ rows: [{ customer: 'a', revenue: 1 }], groupCount: 1, totalGroups: 1 }); + }); + + it('the engine\'s refusal of an order key (INVALID_SORT, naming the columns) reaches the caller as its envelope', async () => { + const bridge = makeBridge() as RecordingBridge; + bridge.aggregateGroups = async () => { + throw Object.assign(new Error("aggregate('showcase_project') ordered or cut by group: `orderBy[0]` names 'amount', which is not a column of the aggregated row. … which here are: customer, revenue. The query was NOT run and nothing was read."), { + code: 'INVALID_SORT', status: 400, httpStatus: 400, + }); + }; + const { refused, text } = await call(bridge, { orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }); + expect(refused).toBe(true); + const { error } = JSON.parse(text); + expect({ code: error.code, status: error.status }).toEqual({ code: 'INVALID_SORT', status: 400 }); + expect(error.message).toContain('customer, revenue'); + }); + + it('a bridge that cannot order and cut groups refuses (NOT_IMPLEMENTED), and never sorts an uncut list', async () => { + const bridge = makeBridge(); + const { refused, text } = await call(bridge, { orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(refused).toBe(true); + expect(JSON.parse(text).error).toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501 }); + expect(bridge.calls).toEqual([]); + }); + + it('a limit past the cap, a sort spelling and a malformed order are refused at the door', async () => { + const bridge = makeCutBridge(); + expect((await call(bridge, { limit: CAP + 1 })).refused).toBe(true); + const sort = await call(bridge, { sort: [{ field: 'revenue', order: 'desc' }] }); + expect(sort.refused).toBe(true); + expect(sort.text).toContain('orderBy'); + expect((await call(bridge, { orderBy: [{ field: 'revenue', order: 'down' }] })).refused).toBe(true); + expect(bridge.cuts).toEqual([]); + }); + + it('CONTROL — no order and no limit: the uncut path as before, now with groupCount beside totalGroups', async () => { + const bridge = makeCutBridge(); + const { body } = await call(bridge, {}); + expect(body).toEqual({ rows: [{ n: 2, all: 5 }], groupCount: 1, totalGroups: 1 }); + expect(bridge.cuts).toEqual([]); + expect(bridge.calls).toHaveLength(1); + }); + + it('tools/list declares orderBy and limit on aggregate_records', async () => { + const bridge = makeCutBridge(); + const listed = await rpc(runtime, bridge, 'tools/list'); + const tool = listed.result.tools.find((t: any) => t.name === 'aggregate_records'); + expect(Object.keys(tool.inputSchema.properties)).toEqual(expect.arrayContaining(['orderBy', 'limit'])); + expect(tool.inputSchema.properties.limit.maximum).toBe(CAP); + expect(tool.description).toMatch(/groupCount/); + }); +}); diff --git a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts new file mode 100644 index 00000000000..b3a6a55f20c --- /dev/null +++ b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [aggregate order and cut] The stdio bridge's `aggregateGroups`: the same + * gated read as `aggregate`, with the engine's order-cut-count request on the + * engine's own read option (a `Symbol.for` key, since this package does not + * depend on the engine at runtime), and the engine's outcome read back. + * + * Driven against a REAL `ObjectQL` over a recording driver named as the SQL + * driver (the engine hands it the directive and it answers the rows and the + * count column a database would), through `aggregate_records` on an MCP + * client: a top five over more groups than the cap comes back as exactly five + * groups, in the driver's order, with the statement's group count; the + * engine's refusals (an order key naming no column of the row, a driver that + * does not compile the cut) reach the client as their envelopes, and the + * driver is never asked; a read the engine did not serve is never an answer. + */ + +import { describe, it, expect } from 'vitest'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { ObjectQL } from '@objectstack/objectql'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { createStdioDataBridge } from './stdio-data-bridge.js'; +import { registerObjectTools } from './mcp-http-tools.js'; + +const OBJECT = 'oc_order'; +const DEF = { + name: OBJECT, + label: 'Order', + fields: { customer: { name: 'customer', type: 'text' }, amount: { name: 'amount', type: 'number' } }, +}; +const DIRECTIVE = Symbol.for('objectstack.driver.aggregate.orderCut'); +const COUNT_COLUMN = '__os_group_count'; +const PRINCIPAL = { userId: 'u1', isSystem: true } as unknown as ExecutionContext; + +/** 80 groups (more than the cap of 50), answered top-down as a database would after its ORDER BY. */ +const GROUPS = Array.from({ length: 80 }, (_, i) => ({ customer: `c${79 - i}`, revenue: (79 - i) * 10 })); + +function makeDriver(name: string, answerCount = true) { + const asts: any[] = []; + const driver: any = { + name, version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find() { return []; }, async findOne() { return null; }, async count() { return 0; }, + async aggregate(_o: string, ast: any) { + asts.push(ast); + const d = ast[DIRECTIVE]; + if (!d) return GROUPS.map((g) => ({ ...g })); + const rows = GROUPS.slice(0, d.limit ?? GROUPS.length).map((g) => ({ ...g })); + return answerCount ? rows.map((r) => ({ ...r, [d.groupCountColumn]: GROUPS.length })) : rows; + }, + async create(_o: string, data: Record) { return { ...data }; }, + async update(_o: string, id: string, data: Record) { return { ...data, id }; }, + async delete() { return true; }, + async beginTransaction() { return {}; }, async commit() {}, async rollback() {}, + }; + return { driver, asts }; +} + +async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount = true) { + const { driver, asts } = makeDriver(driverName, answerCount); + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(DEF as any, 'test'); + const bridge = createStdioDataBridge({ + engine: engine as unknown as IDataEngine, + metadataService: { getObject: async (n: string) => (n === OBJECT ? DEF : undefined) } as unknown as IMetadataService, + resolvePrincipal: async () => PRINCIPAL, + }); + const server = new McpServer({ name: 'pin', version: '0' }); + registerObjectTools(server, bridge); + const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); + await server.connect(serverSide); + const client = new Client({ name: 'pin', version: '0' }); + await client.connect(clientSide); + const call = async (args: Record) => { + const res = (await client.callTool({ + name: 'aggregate_records', + arguments: { objectName: OBJECT, groupBy: ['customer'], aggregations: [{ function: 'sum', field: 'amount', alias: 'revenue' }], ...args }, + })) as { isError?: boolean; content: Array<{ text: string }> }; + return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text) }; + }; + return { bridge, asts, call, close: () => client.close() }; +} + +describe('[aggregate order and cut] stdio — aggregate_records over the engine', () => { + it('top five over more groups than the cap: exactly five, in order, with the statement\'s group count', async () => { + const h = await makeStdio(); + try { + const { isError, body } = await h.call({ orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(isError, JSON.stringify(body)).toBe(false); + expect(body.rows).toEqual(GROUPS.slice(0, 5)); + expect(body.groupCount).toBe(80); + expect(body.truncated).toBe(true); + // The driver was handed the order, one probe group past the limit, and the count column — the cut is its statement's. + expect(h.asts).toHaveLength(1); + expect(h.asts[0][DIRECTIVE]).toEqual({ + orderBy: [{ column: 'revenue', order: 'desc' }, { column: 'customer', order: 'asc' }], + limit: 6, + groupCountColumn: COUNT_COLUMN, + }); + } finally { + await h.close(); + } + }); + + it('an order key naming no column of the aggregated row: INVALID_SORT naming the columns, the driver never asked', async () => { + const h = await makeStdio(); + try { + const { isError, body } = await h.call({ orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }); + expect(isError).toBe(true); + expect({ code: body.error.code, status: body.error.status }).toEqual({ code: 'INVALID_SORT', status: 400 }); + expect(body.error.message).toContain('customer, revenue'); + expect(h.asts).toEqual([]); + } finally { + await h.close(); + } + }); + + it('a driver that does not compile the cut: INVALID_QUERY, the driver never asked', async () => { + const h = await makeStdio('com.objectstack.driver.memory'); + try { + const { isError, body } = await h.call({ orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(isError).toBe(true); + expect({ code: body.error.code, status: body.error.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(h.asts).toEqual([]); + } finally { + await h.close(); + } + }); + + it('rows the driver answered without the group count are never an answer', async () => { + const h = await makeStdio('com.objectstack.driver.sql', false); + try { + const { isError, body } = await h.call({ orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(isError).toBe(true); + expect(body.error?.status ?? 500).toBe(500); + expect(JSON.stringify(body)).not.toContain('c79'); + } finally { + await h.close(); + } + }); + + it('CONTROL — no order, no limit: the uncut path, no directive, groupCount beside totalGroups', async () => { + const h = await makeStdio(); + try { + const { isError, body } = await h.call({}); + expect(isError).toBe(false); + expect(body.rows).toHaveLength(50); + expect(body).toMatchObject({ groupCount: 80, totalGroups: 80, truncated: true }); + expect(h.asts[0][DIRECTIVE]).toBeUndefined(); + } finally { + await h.close(); + } + }); +}); diff --git a/packages/runtime/src/mcp-aggregate-order-cut.test.ts b/packages/runtime/src/mcp-aggregate-order-cut.test.ts new file mode 100644 index 00000000000..26d6bc2d2aa --- /dev/null +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -0,0 +1,109 @@ +/** + * [aggregate order and cut] End to end over a real SQLite database: the HTTP + * MCP bridge's `aggregateGroups` (`buildMcpBridge`, `domains/mcp.ts`) — the + * member `aggregate_records` calls for an `orderBy` / `limit` — reaches the + * real `ObjectQL` engine and the real `SqlDriver` through `callData`'s + * aggregate arm, and the order, the cut and the group count are the + * database's own statement. + * + * Pinned: a top five over more customers than the tool's row cap answers + * exactly five, in order, with the true number of groups; an order by a group + * key ascending; an order key naming no column of the aggregated row refused + * `INVALID_SORT` with the columns named; `aggregate` with no order answers as + * before; and the statement the driver ran carries the ORDER BY, the LIMIT and + * `count(*) over ()` — so a sort in the application cannot pass. The tool's + * half (the probe group, `truncated`, the rendering) is pinned in + * `@objectstack/mcp` (`mcp-http-tools.aggregation-entry.test.ts`), which this + * package does not depend on. + */ + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { buildMcpBridge } from './domains/mcp.js'; +import type { HttpProtocolContext } from './http-dispatcher.js'; + +const OBJECT = 'oc_e2e_order'; +const DEF = { + name: OBJECT, + label: 'Order', + fields: { + customer: { name: 'customer', label: 'Customer', type: 'text' }, + amount: { name: 'amount', label: 'Amount', type: 'number' }, + }, +}; +/** More customers than the tool's row cap (50): `cNN` totals `NN * 10 + 5`. */ +const CUSTOMERS = 70; +const REVENUE = { groupBy: ['customer'], aggregations: [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }] }; + +describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite database', () => { + let driver: SqlDriver; + let engine: ObjectQL; + let bridge: any; + const statements: string[] = []; + + beforeAll(async () => { + driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.initObjects([DEF] as never); + engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(DEF as any); + for (let i = 0; i < CUSTOMERS; i++) { + const customer = `c${String(i).padStart(2, '0')}`; + await driver.create(OBJECT, { id: `${customer}-a`, customer, amount: i * 10 }); + await driver.create(OBJECT, { id: `${customer}-b`, customer, amount: 5 }); + } + (driver as unknown as { knex: { on: Function } }).knex.on('query', (q: { sql: string }) => { statements.push(q.sql); }); + const deps = { + resolveService: async (_ctx: unknown, name: string) => (name === 'objectql' ? engine : undefined), + getObjectQL: async () => engine, + }; + const context = { request: {}, executionContext: { isSystem: true } } as unknown as HttpProtocolContext; + bridge = buildMcpBridge(deps as any, context); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + }); + + it('top five by revenue over more customers than the cap: exactly five, in order, with the true number of groups', async () => { + statements.length = 0; + const answer = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(answer).toEqual({ + rows: [ + { customer: 'c69', revenue: 695 }, + { customer: 'c68', revenue: 685 }, + { customer: 'c67', revenue: 675 }, + { customer: 'c66', revenue: 665 }, + { customer: 'c65', revenue: 655 }, + ], + groupCount: CUSTOMERS, + }); + // One statement: grouped, counted, ordered and cut in the database. + const ran = statements.filter((s) => /group by/i.test(s)); + expect(ran, statements.join('\n')).toHaveLength(1); + expect(ran[0]).toMatch(/count\(\*\) over \(\)/i); + expect(ran[0]).toMatch(/order by coalesce\([^)]*revenue[^)]*, 0\) desc/i); + expect(ran[0]).toMatch(/limit \?/i); + }); + + it('ordered by a group key, ascending', async () => { + const answer = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'customer', order: 'asc' }], limit: 3 }); + expect(answer.rows.map((r: any) => r.customer)).toEqual(['c00', 'c01', 'c02']); + expect(answer.groupCount).toBe(CUSTOMERS); + }); + + it('an order key naming no column of the aggregated row is refused INVALID_SORT, naming the columns', async () => { + const err: any = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }) + .then(() => undefined, (e: unknown) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_SORT', status: 400 }); + expect(err.message).toContain('customer, revenue'); + }); + + it('CONTROL — aggregate with no order answers every group as before, with no count column', async () => { + const rows = await bridge.aggregate(OBJECT, REVENUE); + expect(rows).toHaveLength(CUSTOMERS); + expect(rows[0]).not.toHaveProperty('__os_group_count'); + }); +}); From 29a69242f860912136d55183aa84d3cad1150306 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:18:00 +0000 Subject: [PATCH 04/10] test(driver-sql): index the last element without Array.prototype.at Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../driver-sql/src/sql-driver-aggregate-order-cut.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts index c40c3ca44f7..0af3ff6063d 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts @@ -105,10 +105,10 @@ function declareCell(cell: DialectCell): void { expect(asc.map((r) => r.revenue)).toEqual([0, 1, 5]); const byKeyAsc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'asc' }])), { tenantId: 'org_a' }); expect(customers(byKeyAsc).slice(0, 3)).toEqual(['c00', 'c01', 'c02']); - expect(customers(byKeyAsc).at(-1)).toBeNull(); + expect(customers(byKeyAsc)[customers(byKeyAsc).length - 1]).toBeNull(); const byKeyDesc = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'desc' }], 62)), { tenantId: 'org_a' }); expect(customers(byKeyDesc).slice(0, 2)).toEqual(['cnull', 'c59']); - expect(customers(byKeyDesc).at(-1)).toBeNull(); + expect(customers(byKeyDesc)[customers(byKeyDesc).length - 1]).toBeNull(); }); it('the cut runs inside the tenant wall and the where', async () => { From 1cf9956efb3be4d9e2ccddd528342a89081b2a8e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:10:00 +0000 Subject: [PATCH 05/10] fix(mcp,objectql): classify the new bridge member in both tripwires; literal refusal codes; alias-clean test imports Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- ...-response-internal-fields.tripwire.test.ts | 11 +++++++++- ...io-data-bridge.aggregate-order-cut.test.ts | 2 +- ...o-data-bridge.stored-metadata-body.test.ts | 1 + packages/objectql/src/aggregate-order-cut.ts | 22 +++++++++++-------- .../src/mcp-aggregate-order-cut.test.ts | 3 +++ 5 files changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts index 602244ee9e8..a34fe465e96 100644 --- a/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts +++ b/packages/mcp/src/mcp-write-response-internal-fields.tripwire.test.ts @@ -101,7 +101,13 @@ function makeSentinelEngine(): IDataEngine { return { deleted: 1 }; }), count: vi.fn(async () => 1), - aggregate: vi.fn(async () => [{ n: 1 }]), + // An order-cut-count request (the engine's `Symbol.for` read option) is + // answered as the engine answers it once its driver served the cut. + aggregate: vi.fn(async (_o: string, _q: unknown, options?: Record) => { + const cut = options?.[Symbol.for('objectstack.objectql.aggregateOrderCut')] as { outcome?: unknown } | undefined; + if (cut) cut.outcome = { kind: 'served', groupCount: 1 }; + return [{ n: 1 }]; + }), } as unknown as IDataEngine; } @@ -164,6 +170,9 @@ const RECIPES: Record = { query: { invoke: (b) => b.query('vault', {}), writesRecords: false }, get: { invoke: (b) => b.get('vault', 'row-1'), writesRecords: false }, aggregate: { invoke: (b) => b.aggregate('vault', {}), writesRecords: false }, + // [aggregate order and cut] The same grouped read, ordered and cut: grouped + // rows and a count, no record body. + aggregateGroups: { invoke: (b) => b.aggregateGroups('vault', { aggregations: [{ function: 'count', alias: 'n' }], orderBy: [] }), writesRecords: false }, // ── write faces: an engine write result rides (or could ride) the response ── create: { invoke: (b) => b.create('vault', { name: CONTROL }), writesRecords: true }, diff --git a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts index b3a6a55f20c..819a29265f0 100644 --- a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts +++ b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts @@ -20,7 +20,7 @@ import { describe, it, expect } from 'vitest'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; -import { ObjectQL } from '@objectstack/objectql'; +import { ObjectQL } from '@objectstack/objectql/core'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { createStdioDataBridge } from './stdio-data-bridge.js'; diff --git a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts index 64fba8a2cd8..b90f976bd9d 100644 --- a/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts +++ b/packages/mcp/src/stdio-data-bridge.stored-metadata-body.test.ts @@ -472,6 +472,7 @@ const BRIDGE_MEMBERS: Record = { query: 'seam — serveStoredMetadataRows; filter / sort on the body column refused', get: 'seam — serveStoredMetadataRow', aggregate: 'refuses — group / filter / aggregate member on the body column', + aggregateGroups: 'refuses — the same gates as aggregate, which it runs through (an order key names an aggregated column, never the body)', create: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', update: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', remove: 'refused by the exposure gate — the stored-body tables admit no write verb (family pin)', diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts index 5cae4940e53..960c132eabf 100644 --- a/packages/objectql/src/aggregate-order-cut.ts +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -157,8 +157,8 @@ type CodedError = Error & { object?: string; param?: string; }; -/** A refusal of the request, `INVALID_QUERY` (or the named code) / 400, nothing read. */ -function refusal(object: string, detail: string, code: string = StandardErrorCode.enum.INVALID_QUERY): CodedError { +/** A refusal of the request, `INVALID_QUERY` or `INVALID_SORT` / 400, nothing read. */ +function refusal(code: 'INVALID_QUERY' | 'INVALID_SORT', object: string, detail: string): CodedError { const err = new Error( `aggregate('${object}') ordered or cut by group: ${detail} The query was NOT run and nothing was read.`, ) as CodedError; @@ -184,18 +184,19 @@ export function assertAggregateOrderCutShape( columns: readonly string[], ): void { if (request === null || typeof request !== 'object') { - throw refusal(object, 'the request is not an object.'); + throw refusal('INVALID_QUERY', object, 'the request is not an object.'); } const orderBy: unknown = request.orderBy; if (!Array.isArray(orderBy)) { - throw refusal(object, '`orderBy` must be a list of { field, order } (an empty list orders by the group keys).'); + throw refusal('INVALID_QUERY', object, '`orderBy` must be a list of { field, order } (an empty list orders by the group keys).'); } const limit: unknown = request.limit; if (limit !== undefined && !(typeof limit === 'number' && Number.isInteger(limit) && limit >= 1)) { - throw refusal(object, `\`limit\` must be a whole number of groups, 1 or more; received ${JSON.stringify(limit)}.`); + throw refusal('INVALID_QUERY', object, `\`limit\` must be a whole number of groups, 1 or more; received ${JSON.stringify(limit)}.`); } if (columns.includes(AGGREGATE_GROUP_COUNT_COLUMN)) { throw refusal( + 'INVALID_QUERY', object, `the aggregated row already projects a column named '${AGGREGATE_GROUP_COUNT_COLUMN}', the name the group count ` + 'is answered under. Rename that alias.', @@ -207,17 +208,17 @@ export function assertAggregateOrderCutShape( const field = (key as { field?: unknown } | null)?.field; const order = (key as { order?: unknown } | null)?.order; if (typeof field !== 'string' || field === '' || (order !== 'asc' && order !== 'desc')) { - throw refusal(object, `\`orderBy[${i}]\` must be { field, order: 'asc' | 'desc' }.`); + throw refusal('INVALID_QUERY', object, `\`orderBy[${i}]\` must be { field, order: 'asc' | 'desc' }.`); } if (!columns.includes(field)) { throw refusal( + 'INVALID_SORT', object, `\`orderBy[${i}]\` names '${field}', which is not a column of the aggregated row. Groups are ordered by ` + `the row's own columns — the aggregation aliases and the groupBy projections — which here are: ${known}.`, - StandardErrorCode.enum.INVALID_SORT, ); } - if (seen.has(field)) throw refusal(object, `\`orderBy\` names '${field}' twice.`); + if (seen.has(field)) throw refusal('INVALID_QUERY', object, `\`orderBy\` names '${field}' twice.`); seen.add(field); } } @@ -240,6 +241,7 @@ export function aggregateOrderCutRefusal( ): Error | undefined { if (!driverCompilesAggregateOrderCut(facts.driver)) { return refusal( + 'INVALID_QUERY', object, `this read's driver '${driverNameOf(facts.driver)}' does not order and cut groups in its own statement, and ` + 'the groups are never ordered or cut in the application instead. Ask without an order and a limit, or query ' @@ -248,16 +250,18 @@ export function aggregateOrderCutRefusal( } if (facts.hasHaving) { return refusal( + 'INVALID_QUERY', object, '`having` is applied after the driver answers, so a cut in the statement would cut before it. Ask without ' + '`having`, or without an order and a limit.', ); } if (facts.hasRelationGroup) { - return refusal(object, 'grouping through a relation is not ordered or cut. Ask without an order and a limit.'); + return refusal('INVALID_QUERY', object, 'grouping through a relation is not ordered or cut. Ask without an order and a limit.'); } if (!facts.nativeAggregate) { return refusal( + 'INVALID_QUERY', object, 'this aggregate is computed in the application, not by the driver (a date bucket the driver does not ' + 'compile, a reference timezone it does not bucket, or a measure filter it does not evaluate), and its groups ' diff --git a/packages/runtime/src/mcp-aggregate-order-cut.test.ts b/packages/runtime/src/mcp-aggregate-order-cut.test.ts index 26d6bc2d2aa..a181336c1be 100644 --- a/packages/runtime/src/mcp-aggregate-order-cut.test.ts +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -18,6 +18,9 @@ */ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +// The bridge's module graph reaches a dynamic `import('@objectstack/metadata')`; +// paid here, at collection, never inside a clocked case. +import '@objectstack/metadata'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { buildMcpBridge } from './domains/mcp.js'; From 431b4645bf3a9556e1517345ef8cd461cbfab858 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:19:58 +0000 Subject: [PATCH 06/10] feat(objectql,driver-sql): an order key's rank pushes a declared value 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 Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 --- .changeset/35144-aggregate-order-cut.md | 1 + .../sql-driver-aggregate-order-cut.test.ts | 10 +++++ .../driver-sql/src/sql-driver-aggregation.ts | 23 +++++++++-- packages/mcp/src/mcp-http-tools.ts | 8 +++- packages/mcp/src/stdio-data-bridge.ts | 2 +- .../objectql/src/aggregate-order-cut.test.ts | 15 +++++++ packages/objectql/src/aggregate-order-cut.ts | 39 ++++++++++++++++++- .../src/mcp-aggregate-order-cut.test.ts | 13 +++++++ 8 files changed, 103 insertions(+), 8 deletions(-) diff --git a/.changeset/35144-aggregate-order-cut.md b/.changeset/35144-aggregate-order-cut.md index b2c37841f00..f73f0f09951 100644 --- a/.changeset/35144-aggregate-order-cut.md +++ b/.changeset/35144-aggregate-order-cut.md @@ -16,6 +16,7 @@ A ranking question ("the top five customers by revenue") over more groups than t - An order key that names no column of the aggregated row is refused `INVALID_SORT` / 400, naming the columns the query projects. - Only a driver that runs the cut in its own SQL statement serves it: `driver-sql` (every dialect it speaks; the window `count(*) over ()` needs MySQL 8 or later), the WASM SQLite driver, and the Turso driver's local and replica faces. Every other driver (the in-memory driver, MongoDB, OData, Turso's remote face), an aggregate the engine computes in memory (a date bucket, a reference timezone or a measure filter the driver does not run), and an aggregate with `having` are refused `INVALID_QUERY` / 400 before anything is read. Groups are never ordered or cut in the application. - A NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name break ties, ascending. +- An order key may carry a `rank`, a list of the column's values: the statement ranks each listed value by its position and every other value (a NULL among them) after them, before the cut. It is the bridge's own (for a group key's declared option order read off the served schema), never an `aggregate_records` argument. - Without `orderBy` and `limit` the tool answers as before, now with `groupCount` beside `totalGroups` (the same number). `@objectstack/objectql` exports `AGGREGATE_ORDER_CUT`, the engine-internal read option of `aggregate` that carries the request (a symbol, so no wire request can set it), with the `AggregateOrderCutRequest`, `AggregateOrderKey` and `AggregateOrderCutOutcome` types. `McpDataBridge` gains the optional member `aggregateGroups`; a bridge without it refuses `orderBy` / `limit` with `NOT_IMPLEMENTED` / 501 and keeps serving the rest of the tool. Nothing that was accepted before is refused. diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts index 0af3ff6063d..ef856064eb8 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts @@ -111,6 +111,16 @@ function declareCell(cell: DialectCell): void { expect(customers(byKeyDesc)[customers(byKeyDesc).length - 1]).toBeNull(); }); + it('a rank orders a group key by its listed values\' positions before the cut, any other value after them', async () => { + const declared = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'asc', rank: ['c05', 'c40', 'c02'] }], 3)), { tenantId: 'org_a' }); + expect(customers(declared)).toEqual(['c05', 'c40', 'c02']); + expect(declared[0][COUNT_COLUMN]).toBe(62); + const reversed = await driver.aggregate(TABLE, query(cut([{ column: 'customer', order: 'desc', rank: ['c05', 'c40', 'c02'] }])), { tenantId: 'org_a' }); + // Descending over the ranks: the 59 unlisted groups (rank 3, the NULL key among them) first, then c02, c40, c05. + expect(customers(reversed).slice(-3)).toEqual(['c02', 'c40', 'c05']); + expect(customers(reversed.slice(0, 59))).toContain(null); + }); + it('the cut runs inside the tenant wall and the where', async () => { const lost = await driver.aggregate( TABLE, diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 8c62b90d1a2..d381c8aae7e 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -561,7 +561,12 @@ export class AggregationFacet { for (const key of orderCut.orderBy) { const ref = `${groups}.${this.aliasIdentifierSql(key.column)}`; const identity = foldedOutput.get(key.column); - if (identity !== undefined && Number.isFinite(identity)) { + if (key.rank !== undefined) { + // A declared order: each listed value ranks by its position, any + // other value (a NULL among them) after every listed one. + const arms = key.rank.map((_, i) => `when ? then ${i}`).join(' '); + outer.orderByRaw(`case ${ref} ${arms} else ${key.rank.length} end ${key.order}`, [...key.rank]); + } else if (identity !== undefined && Number.isFinite(identity)) { outer.orderByRaw(`coalesce(${ref}, ${String(identity)}) ${key.order}`); } else { outer.orderByRaw(`case when ${ref} is null then 1 else 0 end, ${ref} ${key.order}`); @@ -624,8 +629,16 @@ export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectst /** The order, cut and group-count column, as the engine hands them. */ export interface AggregateOrderCutDirective { - /** The full order, every key a column the grouped statement projects. */ - readonly orderBy: ReadonlyArray<{ readonly column: string; readonly order: 'asc' | 'desc' }>; + /** + * The full order, every key a column the grouped statement projects. A key + * with a `rank` orders by each value's position in it, any value it does + * not list after every listed one. + */ + readonly orderBy: ReadonlyArray<{ + readonly column: string; + readonly order: 'asc' | 'desc'; + readonly rank?: ReadonlyArray; + }>; /** The most groups to answer; absent = every group. */ readonly limit?: number; /** The column every row answers the pre-cut group count under. */ @@ -649,7 +662,9 @@ export function aggregateOrderCutOf(query: DriverQuery): AggregateOrderCutDirect const d = directive as Partial | null; const ok = d !== null && typeof d === 'object' && Array.isArray(d.orderBy) - && d.orderBy.every((k) => typeof k?.column === 'string' && k.column !== '' && (k.order === 'asc' || k.order === 'desc')) + && d.orderBy.every((k) => typeof k?.column === 'string' && k.column !== '' && (k.order === 'asc' || k.order === 'desc') + && (k.rank === undefined || (Array.isArray(k.rank) && k.rank.length >= 1 + && k.rank.every((v: unknown) => typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v)))))) && (d.limit === undefined || (typeof d.limit === 'number' && Number.isInteger(d.limit) && d.limit >= 1)) && typeof d.groupCountColumn === 'string' && d.groupCountColumn !== ''; if (!ok) throw aggregateOrderCutFault('malformed'); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index fd8dde60079..919e7719072 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -301,7 +301,13 @@ export interface McpDataBridge { groupBy?: NonNullable; aggregations: NonNullable; timezone?: string; - orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; + /** + * A key's `rank` orders a group key by its values' positions in the list + * (a declared option order read off the served schema), any value it + * does not list after every listed one — the tool's own, never a caller + * argument. + */ + orderBy: Array<{ field: string; order: 'asc' | 'desc'; rank?: ReadonlyArray }>; limit?: number; }, ): Promise<{ rows: unknown[]; groupCount: number }>; diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index fbf99e424c4..e5a9735b161 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -1607,7 +1607,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // driver's statement, and its rows are no answer. bridge.aggregateGroups = async (object, opts) => { const orderCut: { - orderBy: Array<{ field: string; order: 'asc' | 'desc' }>; + orderBy: Array<{ field: string; order: 'asc' | 'desc'; rank?: ReadonlyArray }>; limit?: number; outcome?: { kind?: unknown; groupCount?: unknown }; } = { diff --git a/packages/objectql/src/aggregate-order-cut.test.ts b/packages/objectql/src/aggregate-order-cut.test.ts index 11ce3b4f51d..123a3f8c2cf 100644 --- a/packages/objectql/src/aggregate-order-cut.test.ts +++ b/packages/objectql/src/aggregate-order-cut.test.ts @@ -136,6 +136,17 @@ describe('[aggregate order and cut] engine.aggregate — served as the driver\'s expect(rec.calls).toEqual([]); }); + it('a rank orders a key by its listed values\' positions: handed to the driver as named', async () => { + rec.answer([]); + const request: AggregateOrderCutRequest = { orderBy: [{ field: 'area', order: 'asc', rank: ['west', 'east'] }], limit: 3 }; + await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request)); + expect(rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE].orderBy).toEqual([ + { column: 'area', order: 'asc', rank: ['west', 'east'] }, + { column: 'customer', order: 'asc' }, + ]); + expect(request.outcome).toEqual({ kind: 'served', groupCount: 0 }); + }); + it('a malformed request is INVALID_QUERY, and the driver is never asked', async () => { for (const bad of [ { orderBy: 'revenue' }, @@ -143,6 +154,10 @@ describe('[aggregate order and cut] engine.aggregate — served as the driver\'s { orderBy: [], limit: 0 }, { orderBy: [], limit: 2.5 }, { orderBy: [{ field: 'revenue', order: 'asc' }, { field: 'revenue', order: 'desc' }] }, + { orderBy: [{ field: 'area', order: 'asc', rank: [] }] }, + { orderBy: [{ field: 'area', order: 'asc', rank: ['west', 'west'] }] }, + { orderBy: [{ field: 'area', order: 'asc', rank: [{ v: 1 }] }] }, + { orderBy: [{ field: 'area', order: 'asc', rank: 'west' }] }, ]) { const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(bad as any))); expect(err?.code, JSON.stringify(bad)).toBe('INVALID_QUERY'); diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts index 960c132eabf..cab257b043c 100644 --- a/packages/objectql/src/aggregate-order-cut.ts +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -81,10 +81,26 @@ export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectst */ export const AGGREGATE_GROUP_COUNT_COLUMN = '__os_group_count'; +/** + * The most values a {@link AggregateOrderKey.rank} may list: a declared option + * list, not a data set. + */ +export const AGGREGATE_ORDER_RANK_MAX = 500; + /** One key of a request's order: an aggregated-row column and its direction. */ export interface AggregateOrderKey { readonly field: string; readonly order: 'asc' | 'desc'; + /** + * Order the column by these values' positions instead of by the values + * themselves: a value at position `i` ranks `i`, any value the list does not + * hold (a NULL among them) ranks after every listed one, and `order` runs + * over the ranks. For a group key whose values are declared options, so a + * cut keeps the groups first in the declared order — the order the caller + * reads off the schema it is served, handed down so the statement applies it + * before the cut. Groups the rank does not tell apart fall to the next key. + */ + readonly rank?: ReadonlyArray; } /** What the engine did with an {@link AggregateOrderCutRequest}: set only once the driver answered it. */ @@ -110,7 +126,12 @@ export interface AggregateOrderCutRequest { /** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */ export interface DriverAggregateOrderCut { /** The full order: the request's keys, then every group key it does not name, ascending. */ - readonly orderBy: ReadonlyArray<{ readonly column: string; readonly order: 'asc' | 'desc' }>; + readonly orderBy: ReadonlyArray<{ + readonly column: string; + readonly order: 'asc' | 'desc'; + /** {@link AggregateOrderKey.rank}, as the request named it. */ + readonly rank?: ReadonlyArray; + }>; readonly limit?: number; /** The column to answer the pre-cut group count under, on every row. */ readonly groupCountColumn: string; @@ -220,6 +241,20 @@ export function assertAggregateOrderCutShape( } if (seen.has(field)) throw refusal('INVALID_QUERY', object, `\`orderBy\` names '${field}' twice.`); seen.add(field); + const rank = (key as { rank?: unknown }).rank; + if (rank !== undefined) { + const values = Array.isArray(rank) ? rank : []; + const valid = values.length >= 1 && values.length <= AGGREGATE_ORDER_RANK_MAX + && values.every((v) => typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v))) + && new Set(values).size === values.length; + if (!valid) { + throw refusal( + 'INVALID_QUERY', + object, + `\`orderBy[${i}].rank\` must list 1 to ${AGGREGATE_ORDER_RANK_MAX} distinct strings or numbers, in the order to rank them.`, + ); + } + } } } @@ -283,7 +318,7 @@ export function aggregateOrderCutDirective( const named = new Set(request.orderBy.map((k) => k.field)); return { orderBy: [ - ...request.orderBy.map((k) => ({ column: k.field, order: k.order })), + ...request.orderBy.map((k) => ({ column: k.field, order: k.order, ...(k.rank !== undefined ? { rank: [...k.rank] } : {}) })), ...groupColumns.filter((c) => !named.has(c)).map((column) => ({ column, order: 'asc' as const })), ], ...(request.limit !== undefined ? { limit: request.limit } : {}), diff --git a/packages/runtime/src/mcp-aggregate-order-cut.test.ts b/packages/runtime/src/mcp-aggregate-order-cut.test.ts index a181336c1be..b0f3bf0c30d 100644 --- a/packages/runtime/src/mcp-aggregate-order-cut.test.ts +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -97,6 +97,19 @@ describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite datab expect(answer.groupCount).toBe(CUSTOMERS); }); + it('a declared order (a rank on a group key) reaches the statement: the listed groups first, in their order', async () => { + statements.length = 0; + const answer = await bridge.aggregateGroups(OBJECT, { + ...REVENUE, + orderBy: [{ field: 'customer', order: 'asc', rank: ['c03', 'c01', 'c02'] }], + limit: 3, + }); + expect(answer.rows.map((r: any) => r.customer)).toEqual(['c03', 'c01', 'c02']); + expect(answer.groupCount).toBe(CUSTOMERS); + const ran = statements.filter((s) => /group by/i.test(s)); + expect(ran[0]).toMatch(/order by case [^ ]+ when \? then 0 when \? then 1 when \? then 2 else 3 end asc/i); + }); + it('an order key naming no column of the aggregated row is refused INVALID_SORT, naming the columns', async () => { const err: any = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }) .then(() => undefined, (e: unknown) => e); From f766f5dcc0b275ff1fd1f5ed718a831b23d1e3e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 12:47:51 +0000 Subject: [PATCH 07/10] test(runtime): the declared option order a limit-only aggregate_records call sends, over a real SQLite database Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude --- .../src/mcp-aggregate-order-cut.test.ts | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/mcp-aggregate-order-cut.test.ts b/packages/runtime/src/mcp-aggregate-order-cut.test.ts index 650ae321cdb..9a4149c01b8 100644 --- a/packages/runtime/src/mcp-aggregate-order-cut.test.ts +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -8,7 +8,10 @@ * * Pinned: a top five over more customers than the tool's row cap answers * exactly five, in order, with the true number of groups; an order by a group - * key ascending; an order key naming no column of the aggregated row refused + * key ascending; the declared option order `aggregate_records` sends for a + * `limit` with no `orderBy` (a rank on a select key), taken by the statement's + * CASE before the cut, NULL last, with the true number of groups; an order + * key naming no column of the aggregated row refused * `INVALID_SORT` with the columns named; `aggregate` with no order answers as * before; and the statement the driver ran carries the ORDER BY, the LIMIT and * `count(*) over ()` — so a sort in the application cannot pass. The tool's @@ -33,8 +36,11 @@ const DEF = { fields: { customer: { name: 'customer', label: 'Customer', type: 'text' }, amount: { name: 'amount', label: 'Amount', type: 'number' }, + stage: { name: 'stage', label: 'Stage', type: 'select', options: [{ value: 'open' }, { value: 'won' }, { value: 'lost' }] }, }, }; +/** Each customer's stage, in an order that is neither declared nor alphabetical; every fourth has none. */ +const STAGE_OF = (i: number) => ['lost', 'won', null, 'open'][i % 4]; /** More customers than the tool's row cap (50): `cNN` totals `NN * 10 + 5`. */ const CUSTOMERS = 70; const REVENUE = { groupBy: ['customer'], aggregations: [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }] }; @@ -54,8 +60,8 @@ describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite datab engine.registry.registerObject(DEF as any); for (let i = 0; i < CUSTOMERS; i++) { const customer = `c${String(i).padStart(2, '0')}`; - await driver.create(OBJECT, { id: `${customer}-a`, customer, amount: i * 10 }); - await driver.create(OBJECT, { id: `${customer}-b`, customer, amount: 5 }); + await driver.create(OBJECT, { id: `${customer}-a`, customer, amount: i * 10, stage: STAGE_OF(i) }); + await driver.create(OBJECT, { id: `${customer}-b`, customer, amount: 5, stage: STAGE_OF(i) }); } (driver as unknown as { knex: { on: Function } }).knex.on('query', (q: { sql: string }) => { statements.push(q.sql); }); const deps = { @@ -110,6 +116,22 @@ describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite datab expect(ran[0]).toMatch(/order by case [^ ]+ when \? then 0 when \? then 1 when \? then 2 else 3 end asc/i); }); + it('the declared option order a limit-only aggregate_records call sends: declared groups first, NULL last, the cut after it, the true total', async () => { + // The order key `aggregate_records` derives for a `limit` with no + // `orderBy` over a select group key (`@objectstack/mcp`, pinned there). + const declared = { field: 'stage', order: 'asc' as const, rank: ['open', 'won', 'lost'] }; + const COUNT = { groupBy: ['stage'], aggregations: [{ function: 'count' as const, alias: 'n' }] }; + statements.length = 0; + const cut = await bridge.aggregateGroups(OBJECT, { ...COUNT, orderBy: [declared], limit: 2 }); + expect(cut).toEqual({ rows: [{ stage: 'open', n: 34 }, { stage: 'won', n: 36 }], totalGroups: 4 }); + const ran = statements.filter((s) => /group by/i.test(s)); + expect(ran, statements.join('\n')).toHaveLength(1); + expect(ran[0]).toMatch(/order by case [^ ]+ when \? then 0 when \? then 1 when \? then 2 else 3 end asc/i); + expect(ran[0]).toMatch(/limit \?/i); + const all = await bridge.aggregateGroups(OBJECT, { ...COUNT, orderBy: [declared], limit: 10 }); + expect(all.rows.map((r: any) => r.stage)).toEqual(['open', 'won', 'lost', null]); + }); + it('an order key naming no column of the aggregated row is refused INVALID_SORT, naming the columns', async () => { const err: any = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }) .then(() => undefined, (e: unknown) => e); From 0b8bbf82a0ef693bf67f7720779c2d04ae95800d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:25:41 +0000 Subject: [PATCH 08/10] feat(mcp): the order-and-cut path names each lookup group's record beside 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 --- .../mcp-http-tools.aggregation-entry.test.ts | 21 +++++++++++++++++++ packages/mcp/src/mcp-http-tools.ts | 15 ++++++------- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts index 39f5a9b80fb..fa3b32db429 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -773,6 +773,27 @@ describe('aggregate_records — a lookup group names its record beside the id, r expect(out.rows[1]).toEqual({ account: 'x1', parent: 'a2', parent__label: 'Globex', n: 1 }); }); + it('the order-and-cut path labels the groups it serves the same way, read after the cut', async () => { + const bridge = lookupBridge([]) as LookupBridge & { cuts: any[] }; + bridge.cuts = []; + // The database's answer to the cut: one group past the cap, ordered by n. + bridge.aggregateGroups = async (object: string, o: any) => { + bridge.cuts.push([object, o]); + return { rows: [{ account: 'a2', n: 9 }, { account: 'a1', n: 5 }, { account: 'a4', n: 2 }], totalGroups: 3 }; + }; + const out = await answer(bridge, { aggregations: COUNT, groupBy: ['account'], orderBy: [{ field: 'n', order: 'desc' }], limit: 2 }); + expect(bridge.cuts[0]![1]).toMatchObject({ orderBy: [{ field: 'n', order: 'desc' }], limit: 3 }); + expect(out).toEqual({ + rows: [{ account: 'a2', account__label: 'Globex', n: 9 }, { account: 'a1', account__label: 'Acme', n: 5 }], + totalGroups: 3, + truncated: true, + }); + // One read of the referenced object, for the served groups only: never the probe row past the cut. + expect(bridge.reads).toHaveLength(1); + expect([...bridge.reads[0]![1].where.id.$in].sort()).toEqual(['a1', 'a2']); + expect(bridge.calls).toEqual([]); + }); + it('the stdio door: the name is read through the stdio bridge under the caller\'s own context', async () => { const principal = { userId: 'u1', isSystem: false } as unknown as ExecutionContext; const engine = { diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 22edb46931a..84c75cdaef6 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3606,6 +3606,12 @@ export function registerObjectTools( || aggregations.some((a) => AMOUNT_AGGREGATE_FUNCTIONS.has(a.function) && typeof a.field === 'string') ? servedFieldsOf(bridge, objectName) : Promise.resolve(undefined); + // [#35138] Each lookup key's record named beside it, read as the + // caller, for the groups served only: one rule for both paths, + // applied after the cap or the cut. + const labelServed = async (served: unknown[], fields: Record | undefined) => fields + ? withLookupGroupLabels(bridge, served, groupBy, fields, async (name) => (await readGuard(name)) === undefined) + : served; if (orderBy !== undefined || limit !== undefined) { // [aggregate order and cut] Ordered, cut and counted by the // driver's own statement, through the bridge's member for it; @@ -3639,7 +3645,7 @@ export function registerObjectTools( const cut = groups.length > cap; const currencies = fields ? fixedAmountCurrencies(aggregations, fields) : {}; return textResult({ - rows: cut ? groups.slice(0, cap) : groups, + rows: await labelServed(cut ? groups.slice(0, cap) : groups, fields), totalGroups: answer.totalGroups, ...(cut ? { truncated: true } : {}), ...(Object.keys(currencies).length > 0 ? { currencies } : {}), @@ -3658,13 +3664,8 @@ export function registerObjectTools( // thousands of rows) — cap the tool output like query_records does. const truncated = groups.length > maxLimit; const served = truncated ? groups.slice(0, maxLimit) : groups; - // [#35138] Each lookup key's record named beside it, read as the - // caller, for the groups served only. - const labelled = fields - ? await withLookupGroupLabels(bridge, served, groupBy, fields, async (name) => (await readGuard(name)) === undefined) - : served; return textResult({ - rows: labelled, + rows: await labelServed(served, fields), totalGroups: rows.length, ...(truncated ? { truncated: true } : {}), ...(Object.keys(currencies).length > 0 ? { currencies } : {}), From 87429381cbcb0874ba7c7cd60657aedf2e9d0706 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 16:54:26 +0000 Subject: [PATCH 09/10] fix(objectql, mcp): unlisted rank values keep their own order; review 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 --- .changeset/35144-aggregate-order-cut.md | 7 +- .../driver-sql/src/sql-driver-aggregation.ts | 11 +- .../mcp-http-tools.aggregation-entry.test.ts | 2 + packages/mcp/src/mcp-http-tools.ts | 5 + ...io-data-bridge.aggregate-order-cut.test.ts | 54 +++++++- packages/mcp/src/stdio-data-bridge.ts | 18 +-- .../objectql/src/aggregate-order-cut.test.ts | 5 +- packages/objectql/src/aggregate-order-cut.ts | 37 ++++-- .../src/mcp-aggregate-order-cut.test.ts | 121 +++++++++++++++--- 9 files changed, 204 insertions(+), 56 deletions(-) diff --git a/.changeset/35144-aggregate-order-cut.md b/.changeset/35144-aggregate-order-cut.md index dbc699145c3..27d9aa2be7b 100644 --- a/.changeset/35144-aggregate-order-cut.md +++ b/.changeset/35144-aggregate-order-cut.md @@ -15,10 +15,11 @@ A ranking question ("the top five customers by revenue") over more groups than t - An order key that names no column of the aggregated row is refused `INVALID_SORT` / 400, naming the columns the query projects. - Only a driver that runs the cut in its own SQL statement serves it: `driver-sql` (every dialect it speaks; the window `count(*) over ()` needs MySQL 8 or later), the WASM SQLite driver, and the Turso driver's local and replica faces. Every other driver (the in-memory driver, MongoDB, OData, Turso's remote face), an aggregate the engine computes in memory (a date bucket, a reference timezone or a measure filter the driver does not run), and an aggregate with `having` are refused `INVALID_QUERY` / 400 before anything is read. Groups are never ordered or cut in the application. -- A NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name break ties, ascending. -- An order key may carry a `rank`, a list of the column's values: the statement ranks each listed value by its position and every other value (a NULL among them) after them, before the cut. It is the tool's own, never an `aggregate_records` argument. +- On an order key without a `rank`, a NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name, and a group key it names only by a `rank`, break ties, ascending, NULL last, so two runs of one call answer the same groups in the same order. +- An order key may carry a `rank`, a list of the column's values: the statement ranks each listed value by its position and every other value (a NULL among them) on one rank past them, before the cut, so the unlisted values come after the listed ones ascending and before them descending; among themselves they follow the column's own ascending order, NULL last. It is the tool's own, never an `aggregate_records` argument. - A `limit` with no `orderBy` keeps the declared option order the uncut answer already follows: groups keyed by a leading select or radio field come back in the order the field declares its options, a value no option declares last, and the database takes that order before the cut, so the cut keeps the first declared groups. An `orderBy` the caller sends overrides it. -- A fixed-currency amount names its currency in `currencies` on the cut answer too. +- The cut answer carries what the uncut one does: a fixed-currency amount's currency in `currencies`, and `KEY__label` beside each lookup or master-detail group key, the record's name read with the caller's own permissions. +- An amount whose records each carry their own currency is ranked by its bare numbers across currencies: the tool description says to rank it inside one currency by filtering `where` on its currency code field. - Without `orderBy` and `limit` the tool answers as before. `@objectstack/objectql` exports `AGGREGATE_ORDER_CUT`, the engine-internal read option of `aggregate` that carries the request (a symbol, so no wire request can set it), with the `AggregateOrderCutRequest`, `AggregateOrderKey` and `AggregateOrderCutOutcome` types. `McpDataBridge` gains the optional member `aggregateGroups`; a bridge without it refuses `orderBy` / `limit` with `NOT_IMPLEMENTED` / 501 and keeps serving the rest of the tool. Nothing that was accepted before is refused. diff --git a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 3b6a3f0b985..a75a6004df2 100644 --- a/packages/drivers/driver-sql/src/sql-driver-aggregation.ts +++ b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts @@ -562,8 +562,10 @@ export class AggregationFacet { const ref = `${groups}.${this.aliasIdentifierSql(key.column)}`; const identity = foldedOutput.get(key.column); if (key.rank !== undefined) { - // A declared order: each listed value ranks by its position, any - // other value (a NULL among them) after every listed one. + // A declared order: each listed value ranks by its position, every + // other value (a NULL among them) on one rank past the listed ones; + // `order` runs over the ranks. The engine's trailing keys order the + // values that share that rank. const arms = key.rank.map((_, i) => `when ? then ${i}`).join(' '); outer.orderByRaw(`case ${ref} ${arms} else ${key.rank.length} end ${key.order}`, [...key.rank]); } else if (identity !== undefined && Number.isFinite(identity)) { @@ -631,8 +633,9 @@ export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectst export interface AggregateOrderCutDirective { /** * The full order, every key a column the grouped statement projects. A key - * with a `rank` orders by each value's position in it, any value it does - * not list after every listed one. + * with a `rank` orders by each value's position in it, every value it does + * not list (a NULL among them) on one rank past the listed ones, and `order` + * runs over the ranks. */ readonly orderBy: ReadonlyArray<{ readonly column: string; diff --git a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts index fa3b32db429..8b5e0899dc6 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -334,6 +334,8 @@ describe('aggregate_records — ordered, cut and counted groups', () => { expect(Object.keys(tool.inputSchema.properties)).toEqual(expect.arrayContaining(['orderBy', 'limit'])); expect(tool.inputSchema.properties.limit.maximum).toBe(CAP); expect(tool.description).toMatch(/totalGroups says how many groups existed before the cut/); + // A per-record-currency amount is ranked by its bare numbers: the text keeps the ranking to one currency. + expect(tool.description).toMatch(/Ranking an amount whose records each carry their own currency compares bare numbers across currencies: rank it inside one currency by filtering where on its currency code field\./); expect(tool.description).not.toMatch(/groupCount/); }); }); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 2f6e6bfe209..5afce4020fb 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3812,6 +3812,11 @@ export function registerObjectTools( // cut, and the number of groups before the cut stated. 'For a ranking (top or bottom N), set orderBy to an aggregation alias or a group key and limit to N: ' + 'the database orders and cuts the groups, and totalGroups says how many groups existed before the cut. ' + + // The database ranks a per-record-currency amount by its bare + // numbers, whatever each group's currency; the caller keeps the + // ranking to one currency. + 'Ranking an amount whose records each carry their own currency compares bare numbers across currencies: ' + + 'rank it inside one currency by filtering where on its currency code field. ' + `At most ${maxLimit} groups come back; truncated: true says more existed. ` + 'Runs under the caller\'s permissions, row-level security and field-level security.', inputSchema: strictToolInput( diff --git a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts index 299b1072dc8..01ba9a2d003 100644 --- a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts +++ b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts @@ -37,6 +37,8 @@ const DEF = { }, }; const DIRECTIVE = Symbol.for('objectstack.driver.aggregate.orderCut'); +/** The engine's order-cut read option, spelled as the stdio bridge spells it. */ +const AGGREGATE_ORDER_CUT = Symbol.for('objectstack.objectql.aggregateOrderCut'); const COUNT_COLUMN = '__os_total_groups'; const PRINCIPAL = { userId: 'u1', isSystem: true } as unknown as ExecutionContext; @@ -64,15 +66,15 @@ function makeDriver(name: string, answerCount = true) { return { driver, asts }; } -async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount = true) { +async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount = true, def: typeof DEF | Record = DEF) { const { driver, asts } = makeDriver(driverName, answerCount); const engine = new ObjectQL(); engine.registerDriver(driver, true); await engine.init(); - engine.registry.registerObject(DEF as any, 'test'); + engine.registry.registerObject(def as any, 'test'); const bridge = createStdioDataBridge({ engine: engine as unknown as IDataEngine, - metadataService: { getObject: async (n: string) => (n === OBJECT ? DEF : undefined) } as unknown as IMetadataService, + metadataService: { getObject: async (n: string) => (n === OBJECT ? def : undefined) } as unknown as IMetadataService, resolvePrincipal: async () => PRINCIPAL, }); const server = new McpServer({ name: 'pin', version: '0' }); @@ -88,7 +90,7 @@ async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount })) as { isError?: boolean; content: Array<{ text: string }> }; return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text) }; }; - return { bridge, asts, call, close: () => client.close() }; + return { engine, bridge, asts, call, close: () => client.close() }; } describe('[aggregate order and cut] stdio — aggregate_records over the engine', () => { @@ -158,7 +160,12 @@ describe('[aggregate order and cut] stdio — aggregate_records over the engine' expect(body).not.toHaveProperty('groupCount'); expect(h.asts).toHaveLength(1); expect(h.asts[0][DIRECTIVE]).toEqual({ - orderBy: [{ column: 'stage', order: 'asc', rank: ['open', 'won', 'lost'] }, { column: 'customer', order: 'asc' }], + orderBy: [ + { column: 'stage', order: 'asc', rank: ['open', 'won', 'lost'] }, + // The ranked column stays among the trailing keys: its unlisted values keep their own order. + { column: 'stage', order: 'asc' }, + { column: 'customer', order: 'asc' }, + ], limit: 6, totalGroupsColumn: COUNT_COLUMN, }); @@ -167,6 +174,43 @@ describe('[aggregate order and cut] stdio — aggregate_records over the engine' } }); + it('the tool\'s longest declared order is the engine\'s longest rank: sent and served at the limit, neither past it', async () => { + // The tool mirrors the engine's rank maximum (it has no runtime dependency + // on the engine); this measures both at the boundary, so either moving + // alone goes red. + const wide = (n: number) => ({ + ...DEF, + fields: { ...DEF.fields, wide: { name: 'wide', type: 'select', options: Array.from({ length: n }, (_, i) => ({ value: `w${i}` })) } }, + }); + const AT = 500; + const at = await makeStdio('com.objectstack.driver.sql', true, wide(AT)); + try { + const { isError, body } = await at.call({ groupBy: ['wide'], limit: 5 }); + // The tool sent the whole declared list as the rank, and the engine served it. + expect(isError, JSON.stringify(body)).toBe(false); + expect(at.asts[0][DIRECTIVE].orderBy[0].rank).toHaveLength(AT); + } finally { + await at.close(); + } + const past = await makeStdio('com.objectstack.driver.sql', true, wide(AT + 1)); + try { + const { isError, body } = await past.call({ groupBy: ['wide'], limit: 5 }); + // One past it, the tool sends no rank… + expect(isError, JSON.stringify(body)).toBe(false); + expect(past.asts[0][DIRECTIVE].orderBy).toEqual([{ column: 'wide', order: 'asc' }]); + // …and the engine refuses that rank, the driver never asked. + const rank = Array.from({ length: AT + 1 }, (_, i) => `w${i}`); + const err: any = await past.engine + .aggregate(OBJECT, { groupBy: ['wide'], aggregations: [{ function: 'count', alias: 'n' }] } as any, + { [AGGREGATE_ORDER_CUT]: { orderBy: [{ field: 'wide', order: 'asc', rank }], limit: 5 } } as any) + .then(() => undefined, (e: unknown) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); + expect(past.asts).toHaveLength(1); + } finally { + await past.close(); + } + }); + it('CONTROL — no order, no limit: the uncut path, no directive, totalGroups and no second spelling of it', async () => { const h = await makeStdio(); try { diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index e8042300190..b3513a7eedc 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -302,15 +302,6 @@ interface ObjectDef { enable?: Record; } -/** - * Unwrap what the engine's read path resolves to. - * - * Same shape-tolerance as the ADR-0101 record reader next door: an engine may - * answer a bare array or an envelope carrying `value`. Tolerating BOTH here is - * not the consumer-side aliasing Prime Directive #12 forbids — it is the one - * spelling the existing stdio reader already accepts, kept identical so the two - * readers on this transport cannot disagree about what a row list is. - */ /** * The engine's order-cut-count read option for `aggregate` * (`@objectstack/objectql`, `aggregate-order-cut.ts`), spelled `Symbol.for` @@ -325,6 +316,15 @@ const STDIO_AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectq */ const STDIO_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); +/** + * Unwrap what the engine's read path resolves to. + * + * Same shape-tolerance as the ADR-0101 record reader next door: an engine may + * answer a bare array or an envelope carrying `value`. Tolerating BOTH here is + * not the consumer-side aliasing Prime Directive #12 forbids — it is the one + * spelling the existing stdio reader already accepts, kept identical so the two + * readers on this transport cannot disagree about what a row list is. + */ function unwrapRows(res: unknown): Array> { const rows = res && typeof res === 'object' && 'value' in (res as Record) diff --git a/packages/objectql/src/aggregate-order-cut.test.ts b/packages/objectql/src/aggregate-order-cut.test.ts index ee12694c50d..b3aa2b6a4ea 100644 --- a/packages/objectql/src/aggregate-order-cut.test.ts +++ b/packages/objectql/src/aggregate-order-cut.test.ts @@ -136,13 +136,16 @@ describe('[aggregate order and cut] engine.aggregate — served as the driver\'s expect(rec.calls).toEqual([]); }); - it('a rank orders a key by its listed values\' positions: handed to the driver as named', async () => { + it('a rank orders a key by its listed values\' positions: handed to the driver as named, the ranked column kept among the trailing keys', async () => { rec.answer([]); const request: AggregateOrderCutRequest = { orderBy: [{ field: 'area', order: 'asc', rank: ['west', 'east'] }], limit: 3 }; await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request)); + // Every value the rank does not list shares one rank, so the column's own + // ascending order stays among the trailing keys to tell those groups apart. expect(rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE].orderBy).toEqual([ { column: 'area', order: 'asc', rank: ['west', 'east'] }, { column: 'customer', order: 'asc' }, + { column: 'area', order: 'asc' }, ]); expect(request.outcome).toEqual({ kind: 'served', totalGroups: 0 }); }); diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts index 5b28359612c..0760cdd6255 100644 --- a/packages/objectql/src/aggregate-order-cut.ts +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -28,11 +28,14 @@ * group key's projected name (`alias ?? field`), the namespace `having` filters * ({@link aggregatedRowColumns}). Any other name is refused `INVALID_SORT` / * 400, naming the columns this query projects. The group keys the order does - * not name follow it, ascending, so two runs of one request answer the same - * groups in the same order. A NULL ranks last in either direction, except - * where the column answers an identity over nothing (`sum`, the counts: - * `emptyGroupValueFor`), which ranks as that identity — the value the row is - * served with. + * not name, and every group key a `rank` names, follow it, ascending, so two + * runs of one request answer the same groups in the same order. A NULL ranks + * last in either direction, except where the column answers an identity over + * nothing (`sum`, the counts: `emptyGroupValueFor`), which ranks as that + * identity — the value the row is served with. Under a `rank` key the values + * it does not list (a NULL among them) share one rank past the listed ones, + * so they come after them ascending and before them descending; among + * themselves they follow the trailing ascending keys, NULL last. * * ## The count is the statement's * @@ -93,12 +96,15 @@ export interface AggregateOrderKey { readonly order: 'asc' | 'desc'; /** * Order the column by these values' positions instead of by the values - * themselves: a value at position `i` ranks `i`, any value the list does not - * hold (a NULL among them) ranks after every listed one, and `order` runs - * over the ranks. For a group key whose values are declared options, so a - * cut keeps the groups first in the declared order — the order the caller - * reads off the schema it is served, handed down so the statement applies it - * before the cut. Groups the rank does not tell apart fall to the next key. + * themselves: a value at position `i` ranks `i`, every value the list does + * not hold (a NULL among them) ranks `rank.length`, and `order` runs over the + * ranks, so the unlisted values come after the listed ones ascending and + * before them descending. For a group key whose values are declared options, + * so a cut keeps the groups first in the declared order — the order the + * caller reads off the schema it is served, handed down so the statement + * applies it before the cut. Groups the rank does not tell apart fall to the + * next key, and the ranked column itself stays among the trailing ascending + * keys (NULL last), so the unlisted values keep an order of their own. */ readonly rank?: ReadonlyArray; } @@ -125,7 +131,7 @@ export interface AggregateOrderCutRequest { /** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */ export interface DriverAggregateOrderCut { - /** The full order: the request's keys, then every group key it does not name, ascending. */ + /** The full order: the request's keys, then every group key it does not name or names only by a `rank`, ascending. */ readonly orderBy: ReadonlyArray<{ readonly column: string; readonly order: 'asc' | 'desc'; @@ -309,13 +315,16 @@ export function aggregateOrderCutRefusal( /** * The full order the driver applies: the request's keys, then every group key * column the request does not name, ascending — so the answer is the same - * groups in the same order on every run. + * groups in the same order on every run. A column the request names only by a + * `rank` stays among those trailing keys: the rank leaves every value it does + * not list on one rank, and its own ascending order (NULL last) then tells + * those groups apart. */ export function aggregateOrderCutDirective( request: AggregateOrderCutRequest, groupColumns: readonly string[], ): DriverAggregateOrderCut { - const named = new Set(request.orderBy.map((k) => k.field)); + const named = new Set(request.orderBy.filter((k) => k.rank === undefined).map((k) => k.field)); return { orderBy: [ ...request.orderBy.map((k) => ({ column: k.field, order: k.order, ...(k.rank !== undefined ? { rank: [...k.rank] } : {}) })), diff --git a/packages/runtime/src/mcp-aggregate-order-cut.test.ts b/packages/runtime/src/mcp-aggregate-order-cut.test.ts index 9a4149c01b8..bd9ca53287f 100644 --- a/packages/runtime/src/mcp-aggregate-order-cut.test.ts +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -10,7 +10,10 @@ * exactly five, in order, with the true number of groups; an order by a group * key ascending; the declared option order `aggregate_records` sends for a * `limit` with no `orderBy` (a rank on a select key), taken by the statement's - * CASE before the cut, NULL last, with the true number of groups; an order + * CASE before the cut, NULL last, with the true number of groups; the values + * a rank does not list kept in the column's own order (NULL last), so a cut + * among them answers the same groups on every run; a read middleware's filter + * narrowing the cut rows and `totalGroups` alike; an order * key naming no column of the aggregated row refused * `INVALID_SORT` with the columns named; `aggregate` with no order answers as * before; and the statement the driver ran carries the ORDER BY, the LIMIT and @@ -45,31 +48,40 @@ const STAGE_OF = (i: number) => ['lost', 'won', null, 'open'][i % 4]; const CUSTOMERS = 70; const REVENUE = { groupBy: ['customer'], aggregations: [{ function: 'sum' as const, field: 'amount', alias: 'revenue' }] }; +/** + * A real SQLite database holding the 70 customers, the real engine over it, + * and the HTTP bridge over the engine. `prepare` runs on the engine before + * any read (a read middleware, for one). + */ +async function boot(statements: string[], prepare?: (engine: ObjectQL) => void) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + await driver.initObjects([DEF] as never); + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + prepare?.(engine); + await engine.init(); + engine.registry.registerObject(DEF as any); + for (let i = 0; i < CUSTOMERS; i++) { + const customer = `c${String(i).padStart(2, '0')}`; + await driver.create(OBJECT, { id: `${customer}-a`, customer, amount: i * 10, stage: STAGE_OF(i) }); + await driver.create(OBJECT, { id: `${customer}-b`, customer, amount: 5, stage: STAGE_OF(i) }); + } + (driver as unknown as { knex: { on: Function } }).knex.on('query', (q: { sql: string }) => { statements.push(q.sql); }); + const deps = { + resolveService: async (_ctx: unknown, name: string) => (name === 'objectql' ? engine : undefined), + getObjectQL: async () => engine, + }; + const context = { request: {}, executionContext: { isSystem: true } } as unknown as HttpProtocolContext; + return { driver, bridge: buildMcpBridge(deps as any, context) as any }; +} + describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite database', () => { let driver: SqlDriver; - let engine: ObjectQL; let bridge: any; const statements: string[] = []; beforeAll(async () => { - driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); - await driver.initObjects([DEF] as never); - engine = new ObjectQL(); - engine.registerDriver(driver, true); - await engine.init(); - engine.registry.registerObject(DEF as any); - for (let i = 0; i < CUSTOMERS; i++) { - const customer = `c${String(i).padStart(2, '0')}`; - await driver.create(OBJECT, { id: `${customer}-a`, customer, amount: i * 10, stage: STAGE_OF(i) }); - await driver.create(OBJECT, { id: `${customer}-b`, customer, amount: 5, stage: STAGE_OF(i) }); - } - (driver as unknown as { knex: { on: Function } }).knex.on('query', (q: { sql: string }) => { statements.push(q.sql); }); - const deps = { - resolveService: async (_ctx: unknown, name: string) => (name === 'objectql' ? engine : undefined), - getObjectQL: async () => engine, - }; - const context = { request: {}, executionContext: { isSystem: true } } as unknown as HttpProtocolContext; - bridge = buildMcpBridge(deps as any, context); + ({ driver, bridge } = await boot(statements)); }); afterAll(async () => { @@ -132,6 +144,22 @@ describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite datab expect(all.rows.map((r: any) => r.stage)).toEqual(['open', 'won', 'lost', null]); }); + it('values a rank does not list keep an order of their own: the same groups, in the same order, at a cut among them', async () => { + // One declared value; `lost`, `open` and NULL are unlisted and share the rank past it. + const ranked = { field: 'stage', order: 'asc' as const, rank: ['won'] }; + const COUNT = { groupBy: ['stage'], aggregations: [{ function: 'count' as const, alias: 'n' }] }; + statements.length = 0; + const first = await bridge.aggregateGroups(OBJECT, { ...COUNT, orderBy: [ranked], limit: 3 }); + // The unlisted values follow the column's own ascending order, NULL last, so the cut keeps `lost` and `open`. + expect(first).toEqual({ rows: [{ stage: 'won', n: 36 }, { stage: 'lost', n: 36 }, { stage: 'open', n: 34 }], totalGroups: 4 }); + const ran = statements.filter((s) => /group by/i.test(s)); + expect(ran[0]).toMatch(/order by case [^ ]+ when \? then 0 else 1 end asc, case when [^ ]+stage[^ ]* is null then 1 else 0 end, [^ ]+stage[^ ]* asc/i); + const again = await bridge.aggregateGroups(OBJECT, { ...COUNT, orderBy: [ranked], limit: 3 }); + expect(again).toEqual(first); + const all = await bridge.aggregateGroups(OBJECT, { ...COUNT, orderBy: [ranked], limit: 10 }); + expect(all.rows.map((r: any) => r.stage)).toEqual(['won', 'lost', 'open', null]); + }); + it('an order key naming no column of the aggregated row is refused INVALID_SORT, naming the columns', async () => { const err: any = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'amount', order: 'desc' }], limit: 5 }) .then(() => undefined, (e: unknown) => e); @@ -145,3 +173,56 @@ describe('[aggregate order and cut] the HTTP MCP bridge over a real SQLite datab expect(rows[0]).not.toHaveProperty('__os_total_groups'); }); }); + +/** + * [aggregate order and cut] A read middleware that narrows `ast.where` (the + * shape the security and sharing middlewares inject) narrows the cut too: + * the database orders, cuts and counts only the groups formed from the rows + * it admits. + */ +describe('[aggregate order and cut] a read middleware\'s filter narrows the cut rows and totalGroups', () => { + let driver: SqlDriver; + let bridge: any; + const statements: string[] = []; + + beforeAll(async () => { + ({ driver, bridge } = await boot(statements, (engine) => { + engine.registerMiddleware(async (ctx: any, next: () => Promise) => { + if (ctx.operation === 'aggregate') { + // Admit only the `won` rows: customers c01, c05, … c69, 18 of them. + const ast: any = ctx.ast ?? { object: ctx.object }; + ast.where = ast.where ? { $and: [ast.where, { stage: 'won' }] } : { stage: 'won' }; + ctx.ast = ast; + } + await next(); + }); + })); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + }); + + it('top five by revenue: only admitted groups, and totalGroups counts only them', async () => { + statements.length = 0; + const answer = await bridge.aggregateGroups(OBJECT, { ...REVENUE, orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(answer).toEqual({ + rows: [ + { customer: 'c69', revenue: 695 }, + { customer: 'c65', revenue: 655 }, + { customer: 'c61', revenue: 615 }, + { customer: 'c57', revenue: 575 }, + { customer: 'c53', revenue: 535 }, + ], + totalGroups: 18, + }); + const ran = statements.filter((s) => /group by/i.test(s)); + expect(ran, statements.join('\n')).toHaveLength(1); + expect(ran[0]).toMatch(/count\(\*\) over \(\)/i); + }); + + it('CONTROL — the uncut aggregate through the same middleware answers the same 18 groups', async () => { + const rows = await bridge.aggregate(OBJECT, REVENUE); + expect(rows).toHaveLength(18); + }); +}); From 3eca62301806c15866bb0bb6dc5fbafd91af9061 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 17:51:38 +0000 Subject: [PATCH 10/10] test(mcp): the rank-maximum pin types its engine call 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 --- .../mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts index 01ba9a2d003..af4f961c76d 100644 --- a/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts +++ b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts @@ -201,8 +201,9 @@ describe('[aggregate order and cut] stdio — aggregate_records over the engine' // …and the engine refuses that rank, the driver never asked. const rank = Array.from({ length: AT + 1 }, (_, i) => `w${i}`); const err: any = await past.engine - .aggregate(OBJECT, { groupBy: ['wide'], aggregations: [{ function: 'count', alias: 'n' }] } as any, - { [AGGREGATE_ORDER_CUT]: { orderBy: [{ field: 'wide', order: 'asc', rank }], limit: 5 } } as any) + .aggregate(OBJECT, { groupBy: ['wide'], aggregations: [{ function: 'count', alias: 'n' }] }, + // The engine-internal read option rides on its symbol key, outside the declared options. + { [AGGREGATE_ORDER_CUT]: { orderBy: [{ field: 'wide', order: 'asc', rank }], limit: 5 } } as unknown as Parameters[2]) .then(() => undefined, (e: unknown) => e); expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 }); expect(past.asts).toHaveLength(1);