diff --git a/.changeset/35144-aggregate-order-cut.md b/.changeset/35144-aggregate-order-cut.md new file mode 100644 index 00000000000..27d9aa2be7b --- /dev/null +++ b/.changeset/35144-aggregate-order-cut.md @@ -0,0 +1,25 @@ +--- +'@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`) +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, `totalGroups` (the key the tool already answers, now the database's count of the groups before the cut), 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. +- 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. +- 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-aggregate-order-cut.test.ts b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts new file mode 100644 index 00000000000..35cbcadd858 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-aggregate-order-cut.test.ts @@ -0,0 +1,173 @@ +// 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_total_groups'; + +/** + * 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 } : {}), totalGroupsColumn: 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)[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)[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, + 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/drivers/driver-sql/src/sql-driver-aggregation.ts b/packages/drivers/driver-sql/src/sql-driver-aggregation.ts index 1e8180777fa..a75a6004df2 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,52 @@ 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.totalGroupsColumn)) { + throw aggregateOrderCutFault(`the group count column '${orderCut.totalGroupsColumn}' 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.totalGroupsColumn)}`)) + .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 (key.rank !== undefined) { + // 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)) { + 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.totalGroupsColumn, '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 +620,60 @@ 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. A key + * 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; + 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. */ + readonly totalGroupsColumn: 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') + && (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.totalGroupsColumn === 'string' && d.totalGroupsColumn !== ''; + 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 f6397b9db9c..dd5910cf00d 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -3273,6 +3273,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.aggregation-entry.test.ts b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts index 2a89369a29f..8b5e0899dc6 100644 --- a/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts +++ b/packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts @@ -213,6 +213,133 @@ describe('aggregate_records — the aggregation entry (#28550)', () => { }); }); +/** + * [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 (`totalGroups`) 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), totalGroups: 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.totalGroups).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.totalGroups).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 }], totalGroups: 1 }); + const { body } = await call(bridge, { orderBy: [{ field: 'revenue', order: 'desc' }], limit: 5 }); + expect(body).toEqual({ rows: [{ customer: 'a', revenue: 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, totalGroups and no second spelling of it', async () => { + const bridge = makeCutBridge(); + const { body } = await call(bridge, {}); + expect(body).toEqual({ rows: [{ n: 2, all: 5 }], 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(/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/); + }); +}); + /** * [#35138] Two facts `aggregate_records` reads off the object as the caller * is served it (`servedObjectDefinitionOf`): groups keyed by a select field @@ -367,6 +494,127 @@ describe('aggregate_records — select groups in declared option order, a fixed }); }); +/** + * [aggregate order and cut × declared option order] The two rules meet on the + * order-and-cut path. A call with a `limit` and no `orderBy` hands the + * database the declared option order of its leading select keys, each as an + * order key's `rank`, so the order is taken before the cut and the cut keeps + * the first declared groups; the rule is the uncut path's own + * (`declaredOptionRank`), read once. An `orderBy` the caller sent reaches the + * bridge unchanged and overrides the option order. A fixed-currency amount + * names its currency on the cut result too. No served result carries a second + * spelling of `totalGroups`. + * + * The rank's push-down into the statement (a CASE in the ORDER BY) is pinned + * in `@objectstack/driver-sql` (`sql-driver-aggregate-order-cut.test.ts`) and + * over a real SQLite database in `@objectstack/runtime` + * (`mcp-aggregate-order-cut.test.ts`); its passage through the real engine to + * the driver in `stdio-data-bridge.aggregate-order-cut.test.ts`. + */ +describe('aggregate_records — the declared option order on the order-and-cut path', () => { + const STAGES = ['prospect', 'qualified', 'won', 'lost']; + const served = { + name: 'deal', + fields: { + stage: { type: 'select', options: STAGES.map((value) => ({ value })) }, + priority: { type: 'radio', options: [{ value: 'high' }, { value: 'low' }] }, + region: { type: 'text' }, + amount: { type: 'currency', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } }, + wide: { type: 'select', options: Array.from({ length: 501 }, (_, i) => ({ value: `w${i}` })) }, + }, + }; + /** Five stages in the order a database answers them with no order of its own. */ + const DRIVER_ORDER = [ + { stage: 'lost', n: 1 }, { stage: null, n: 9 }, { stage: 'won', n: 2 }, { stage: 'prospect', n: 3 }, { stage: 'qualified', n: 4 }, + ]; + + /** A database that honours the leading key's rank (an unlisted value last) and otherwise answers in its own order. */ + function cutBridge(def: Record | null = served) { + const bridge = makeBridge() as RecordingBridge & { cuts: any[] }; + bridge.cuts = []; + bridge.servedObjectDefinitionOf = async () => def; + bridge.aggregateGroups = async (object: string, opts: any) => { + bridge.cuts.push([object, opts]); + const key = opts.orderBy[0]; + const at = (v: unknown) => (key.rank.indexOf(v) < 0 ? key.rank.length : key.rank.indexOf(v)); + const ordered = key?.rank ? [...DRIVER_ORDER].sort((a: any, b: any) => at(a[key.field]) - at(b[key.field])) : DRIVER_ORDER; + return { rows: ordered.slice(0, opts.limit), totalGroups: DRIVER_ORDER.length }; + }; + return bridge; + } + + async function answer(bridge: RecordingBridge, args: Record) { + const runtime = new MCPServerRuntime({ name: 't', version: '1.0.0' }); + const { refused, text } = await aggregate(runtime, bridge, { objectName: 'deal', aggregations: [{ function: 'count', alias: 'n' }], ...args }); + expect(refused, text).toBe(false); + const body = JSON.parse(text); + expect(body).not.toHaveProperty('groupCount'); + return body as { rows: Array>; totalGroups: number; truncated?: true; currencies?: Record }; + } + + it('a limit with no orderBy: the database is handed the declared option order, and the cut keeps the first declared groups', async () => { + const bridge = cutBridge(); + const out = await answer(bridge, { groupBy: ['stage'], limit: 2 }); + expect(bridge.cuts).toHaveLength(1); + expect(bridge.cuts[0][1].orderBy).toEqual([{ field: 'stage', order: 'asc', rank: STAGES }]); + expect(bridge.cuts[0][1].limit).toBe(3); + expect(out.rows.map((r) => r.stage)).toEqual(['prospect', 'qualified']); + // The database's count of the groups before the cut. + expect(out.totalGroups).toBe(5); + expect(out.truncated).toBe(true); + // The uncut path was never asked, and nothing was sorted here. + expect(bridge.calls).toEqual([]); + }); + + it('the rank is read by the group key\'s alias for each leading select key, and the first key that is not one ends the reading', async () => { + const bridge = cutBridge(); + await answer(bridge, { groupBy: [{ field: 'stage', alias: 's' }, 'priority', 'region', 'stage'], limit: 5 }); + expect(bridge.cuts[0][1].orderBy).toEqual([ + { field: 's', order: 'asc', rank: STAGES }, + { field: 'priority', order: 'asc', rank: ['high', 'low'] }, + ]); + await answer(bridge, { groupBy: ['region', 'stage'], limit: 5 }); + expect(bridge.cuts[1][1].orderBy).toEqual([]); + }); + + it('a declared list longer than the engine ranks ends the reading at its key, rather than send a rank the engine refuses', async () => { + const bridge = cutBridge(); + await answer(bridge, { groupBy: ['stage', 'wide'], limit: 5 }); + expect(bridge.cuts[0][1].orderBy).toEqual([{ field: 'stage', order: 'asc', rank: STAGES }]); + }); + + it('CONTROL — an explicit orderBy overrides the option order: it reaches the bridge unchanged, with no rank', async () => { + const bridge = cutBridge(); + const out = await answer(bridge, { groupBy: ['stage'], orderBy: [{ field: 'n', order: 'desc' }], limit: 5 }); + expect(bridge.cuts[0][1].orderBy).toEqual([{ field: 'n', order: 'desc' }]); + expect(out.rows.map((r) => r.stage)).toEqual(['lost', null, 'won', 'prospect', 'qualified']); + const byStage = cutBridge(); + await answer(byStage, { groupBy: ['stage'], orderBy: [{ field: 'stage', order: 'desc' }], limit: 5 }); + expect(byStage.cuts[0][1].orderBy).toEqual([{ field: 'stage', order: 'desc' }]); + }); + + it('an amount over a fixed-currency field names its currency on the cut result too', async () => { + const bridge = cutBridge(); + const out = await answer(bridge, { + groupBy: ['stage'], + aggregations: [{ function: 'sum', field: 'amount', alias: 'total' }, { function: 'count', alias: 'n' }], + orderBy: [{ field: 'total', order: 'desc' }], + limit: 5, + }); + expect(out.currencies).toEqual({ total: 'USD' }); + }); + + it('CONTROL — a count names no currency, and a bridge without the served definition cuts in the database\'s own order, as before', async () => { + const counted = await answer(cutBridge(), { groupBy: ['stage'], limit: 5 }); + expect(counted).not.toHaveProperty('currencies'); + const bare = cutBridge(); + delete bare.servedObjectDefinitionOf; + const out = await answer(bare, { groupBy: ['stage'], limit: 5 }); + expect(bare.cuts[0][1].orderBy).toEqual([]); + expect(out).toEqual({ rows: DRIVER_ORDER, totalGroups: 5 }); + }); +}); + /** * [#35138] A group keyed by a lookup (or master-detail) field names its * record beside the id, in `__label`: the referenced record's name field @@ -527,6 +775,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 08c2ad71b8b..64686be4c36 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -343,6 +343,38 @@ 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 `totalGroups`, 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; + /** + * 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[]; totalGroups: number }>; /** * [#35138] The caller's locale ladder for a sentence the tools compose into * a result (`ifNotRecorded`): the codes in order, the shared picker @@ -882,6 +914,62 @@ function declaredOptionRank(def: Record | undefined): Map 0 ? rank : undefined; } +/** + * [#35138] The leading group keys whose groups follow a declared option order, + * each with its {@link declaredOptionRank}: read in `groupBy` order while each + * key is a single-option field ({@link OPTION_ORDERED_GROUP_TYPES}) the served + * schema declares options for; the first key that is not one ends the reading. + * Both paths of `aggregate_records` take the rule from here: the uncut path + * sorts by it ({@link inDeclaredOptionOrder}), the order-and-cut path hands it + * to the database ({@link declaredOptionOrderBy}). + */ +function declaredOptionOrderKeys( + groupBy: NonNullable | undefined, + fields: Record, +): Array<{ column: string; rank: Map }> { + const keys: Array<{ column: string; rank: Map }> = []; + for (const entry of groupBy ?? []) { + const item = typeof entry === 'string' ? { field: entry } : (entry as { field?: unknown; alias?: unknown; dateGranularity?: unknown }); + // A bucketed key is a period, not a declared option. + if (item.dateGranularity !== undefined) break; + const rank = declaredOptionRank(servedFieldOf(fields, item.field)); + if (!rank) break; + const column = typeof item.alias === 'string' ? item.alias : (item.field as string); + keys.push({ column, rank }); + } + return keys; +} + +/** + * The most values one order key's `rank` may list: `@objectstack/objectql`'s + * `AGGREGATE_ORDER_RANK_MAX` (a declared option list, not a data set), which + * this package does not import at runtime. A longer declared list ends the + * reading at its key rather than send a rank the engine refuses. + */ +const ORDER_RANK_MAX = 500; + +/** + * [aggregate order and cut] The declared option order of + * {@link declaredOptionOrderKeys} as the order-and-cut path's `orderBy`, for a + * call with a `limit` and no `orderBy` of its own: each leading option-ordered + * key ascending by its `rank`, so the database orders the groups, and a value + * no option declares (a NULL among them) after every declared one, before the + * cut. The engine orders the group keys after these ascending. Empty when no + * leading key has a declared order. + */ +function declaredOptionOrderBy( + groupBy: NonNullable | undefined, + fields: Record, +): Array<{ field: string; order: 'asc'; rank: Array }> { + const orderBy: Array<{ field: string; order: 'asc'; rank: Array }> = []; + for (const { column, rank } of declaredOptionOrderKeys(groupBy, fields)) { + const values = [...rank.keys()]; + if (values.length > ORDER_RANK_MAX || !values.every((v) => typeof v === 'string' || typeof v === 'number')) break; + orderBy.push({ field: column, order: 'asc', rank: values as Array }); + } + return orderBy; +} + /** * [#35138] `aggregate_records`' groups in the option order the caller's * served schema declares, for a call that states no order of its own. @@ -904,16 +992,7 @@ function inDeclaredOptionOrder( groupBy: NonNullable | undefined, fields: Record, ): unknown[] { - const keys: Array<{ column: string; rank: Map }> = []; - for (const entry of groupBy ?? []) { - const item = typeof entry === 'string' ? { field: entry } : (entry as { field?: unknown; alias?: unknown; dateGranularity?: unknown }); - // A bucketed key is a period, not a declared option. - if (item.dateGranularity !== undefined) break; - const rank = declaredOptionRank(servedFieldOf(fields, item.field)); - if (!rank) break; - const column = typeof item.alias === 'string' ? item.alias : (item.field as string); - keys.push({ column, rank }); - } + const keys = declaredOptionOrderKeys(groupBy, fields); if (keys.length === 0) return rows; const position = (row: unknown, key: { column: string; rank: Map }): number => { const value = row !== null && typeof row === 'object' ? (row as Record)[key.column] : undefined; @@ -3768,6 +3847,17 @@ export function registerObjectTools( 'read with the caller\'s own permissions. Name such a group by its __label, never by the id; ' + 'where a group has no __label, its record cannot be named, so say that rather than quoting the id. ' + '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 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( { @@ -3783,6 +3873,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', }, }, { @@ -3826,41 +3923,97 @@ 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 { + // [#35138] Read off the object as the caller is served it: the + // declared option order of a select group key, and the one + // currency of a fixed-currency amount. Only when the call has a + // group key or an amount column to read it for. + const readServedFields = () => (groupBy?.length ?? 0) > 0 + || 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; + // one group past the cap is asked for, so `truncated` is a fact + // (the capped-list key every read tool shares), and `totalGroups` + // 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 fields = await readServedFields(); + const answer = await bridge.aggregateGroups(objectName, { + where, + groupBy, + aggregations, + timezone, + // [#35138] A call that states no order of its own gets the + // declared option order, taken by the database before the cut. + // ⛔ An `orderBy` the caller sent is never changed. + orderBy: orderBy ?? (fields ? declaredOptionOrderBy(groupBy, fields) : []), + limit: cap + 1, + }); + const groups = Array.isArray(answer?.rows) ? answer.rows : []; + const cut = groups.length > cap; + const currencies = fields ? fixedAmountCurrencies(aggregations, fields) : {}; + return textResult({ + rows: await labelServed(cut ? groups.slice(0, cap) : groups, fields), + totalGroups: answer.totalGroups, + ...(cut ? { truncated: true } : {}), + ...(Object.keys(currencies).length > 0 ? { currencies } : {}), + }); + } const rows = (await aggregateFn(objectName, { where, groupBy, aggregations, timezone, })) ?? []; - // [#35138] Read off the object as the caller is served it: the - // declared option order of a select group key, and the one - // currency of a fixed-currency amount. Only when the call has a - // group key or an amount column to read it for. - const fields = (groupBy?.length ?? 0) > 0 - || aggregations.some((a) => AMOUNT_AGGREGATE_FUNCTIONS.has(a.function) && typeof a.field === 'string') - ? await servedFieldsOf(bridge, objectName) - : undefined; + const fields = await readServedFields(); const groups = fields ? inDeclaredOptionOrder(rows, groupBy, fields) : rows; const currencies = fields ? fixedAmountCurrencies(aggregations, fields) : {}; // Group count is unbounded (a high-cardinality groupBy can return // 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 } : {}), 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 b5f491e204f..bd53b41fc6d 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', totalGroups: 1 }; + return [{ n: 1 }]; + }), } as unknown as IDataEngine; } @@ -167,6 +173,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 }, // [#35138] The caller's locale codes: no engine read, no record. userTextLocales: { invoke: (b) => b.userTextLocales(), writesRecords: false }, 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..af4f961c76d --- /dev/null +++ b/packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts @@ -0,0 +1,228 @@ +// 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/core'; +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' }, + stage: { name: 'stage', type: 'select', options: [{ value: 'open', label: 'Open' }, { value: 'won', label: 'Won' }, { value: 'lost', label: 'Lost' }] }, + }, +}; +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; + +/** 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.totalGroupsColumn]: 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, 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'); + 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 { engine, 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.totalGroups).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, + totalGroupsColumn: 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('a limit with no orderBy over a select key: the declared option order reaches the driver as the rank, before the cut', async () => { + const h = await makeStdio(); + try { + const { isError, body } = await h.call({ groupBy: ['stage', 'customer'], limit: 5 }); + expect(isError, JSON.stringify(body)).toBe(false); + expect(body.totalGroups).toBe(80); + 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'] }, + // 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, + }); + } finally { + await h.close(); + } + }); + + 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' }] }, + // 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); + } 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 { + const { isError, body } = await h.call({}); + expect(isError).toBe(false); + expect(body.rows).toHaveLength(50); + expect(body).toMatchObject({ totalGroups: 80, truncated: true }); + expect(body).not.toHaveProperty('groupCount'); + expect(h.asts[0][DIRECTIVE]).toBeUndefined(); + } finally { + await h.close(); + } + }); +}); 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 d4a2f74bb03..ccfb7f86da2 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 @@ -473,6 +473,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/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index e5a253d048c..88696ab488c 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -308,6 +308,20 @@ interface ObjectDef { enable?: Record; } +/** + * 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'); +/** + * The engine's one-row-per-group read option (`@objectstack/objectql`, + * `latest-per.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_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); + /** * [#35145] `query_records`' `expand` on this transport, as the data door * builds it (`assertExpandTargetsExist`, then `servedExpand`): each name is a @@ -371,13 +385,6 @@ async function stdioExpandMap( * 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 one-row-per-group read option (`@objectstack/objectql`, - * `latest-per.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_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer'); - function unwrapRows(res: unknown): Array> { const rows = res && typeof res === 'object' && 'value' in (res as Record) @@ -1722,7 +1729,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 @@ -1753,15 +1767,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'; rank?: ReadonlyArray }>; + limit?: number; + outcome?: { kind?: unknown; totalGroups?: 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 totalGroups = orderCut.outcome?.totalGroups; + if (orderCut.outcome?.kind !== 'served' || typeof totalGroups !== '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, totalGroups }; + }; } return bridge; 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..b3aa2b6a4ea --- /dev/null +++ b/packages/objectql/src/aggregate-order-cut.test.ts @@ -0,0 +1,235 @@ +// 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_TOTAL_GROUPS_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_TOTAL_GROUPS_COLUMN]: 7 }, + { customer: 'c8', area: 'east', revenue: 80, n: 2, [AGGREGATE_TOTAL_GROUPS_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', totalGroups: 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, + totalGroupsColumn: AGGREGATE_TOTAL_GROUPS_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', totalGroups: 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 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 }); + }); + + 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' }] }, + { 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'); + 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', totalGroups: 0 }); + } + }); +}); diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts new file mode 100644 index 00000000000..0760cdd6255 --- /dev/null +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -0,0 +1,375 @@ +// 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_total_groups 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, 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 + * + * The driver answers the number of groups the statement formed before its cut + * on every row, under {@link AGGREGATE_TOTAL_GROUPS_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_TOTAL_GROUPS_COLUMN = '__os_total_groups'; + +/** + * 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`, 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; +} + +/** 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 totalGroups: 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 or names only by a `rank`, ascending. */ + 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 totalGroupsColumn: 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 `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; + 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('INVALID_QUERY', object, 'the request is not an object.'); + } + const orderBy: unknown = request.orderBy; + if (!Array.isArray(orderBy)) { + 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('INVALID_QUERY', object, `\`limit\` must be a whole number of groups, 1 or more; received ${JSON.stringify(limit)}.`); + } + if (columns.includes(AGGREGATE_TOTAL_GROUPS_COLUMN)) { + throw refusal( + 'INVALID_QUERY', + object, + `the aggregated row already projects a column named '${AGGREGATE_TOTAL_GROUPS_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('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}.`, + ); + } + 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.`, + ); + } + } + } +} + +/** + * 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( + '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 ' + + 'an object stored in a SQL database.', + ); + } + 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('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 ' + + '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. 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.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] } : {}) })), + ...groupColumns.filter((c) => !named.has(c)).map((column) => ({ column, order: 'asc' as const })), + ], + ...(request.limit !== undefined ? { limit: request.limit } : {}), + totalGroupsColumn: AGGREGATE_TOTAL_GROUPS_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 totalGroups = 0; + const out = list.map((row, i) => { + const raw = row?.[AGGREGATE_TOTAL_GROUPS_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 !== totalGroups)) { + 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; + } + totalGroups = n; + const { [AGGREGATE_TOTAL_GROUPS_COLUMN]: _count, ...rest } = row; + return rest; + }); + request.outcome = { kind: 'served', totalGroups }; + 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 fc7ea266eba..98cf64e173e 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'; // "Each X with its latest Y": the engine-internal read option a door carries // to `find` for one row per group, and the request it carries. The carriers // that do not import this package spell the key `Symbol.for`, as it does. diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index 5f85b284a42..d138e683b75 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, LATEST_PER, type LatestPerRequest, type PackageScopedRefusal, @@ -990,6 +992,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, { @@ -999,8 +1008,19 @@ export async function callData(deps: ActionExecutionDeps, ...(params.timezone ? { timezone: params.timezone } : {}), ...(executionContext ? { context: executionContext } : {}), }, + ...(orderCut !== undefined + ? [{ [AGGREGATE_ORDER_CUT]: orderCut } as Parameters[2]] 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 ?? [], totalGroups: orderCut.outcome.totalGroups }; } 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 10efc261688..9bfbe0777c7 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 { LATEST_PER, type LatestPerRequest } 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 @@ -1291,6 +1294,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 `totalGroups`; 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?.totalGroups !== '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 ?? [], totalGroups: res.totalGroups }; + }, // [#35138] The caller's locale ladder for a sentence the record tools // compose (`ifNotRecorded`): this request's, as the dataset tools' // `nextStep` reads it on this door (`userTextLocalesOf`). 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..bd9ca53287f --- /dev/null +++ b/packages/runtime/src/mcp-aggregate-order-cut.test.ts @@ -0,0 +1,228 @@ +/** + * [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; 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; 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 + * `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'; +// 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'; +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' }, + 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' }] }; + +/** + * 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 bridge: any; + const statements: string[] = []; + + beforeAll(async () => { + ({ driver, bridge } = await boot(statements)); + }); + + 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 }, + ], + totalGroups: 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.totalGroups).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.totalGroups).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('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('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); + 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_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); + }); +});