diff --git a/.changeset/35287-objectql-face-order-cut.md b/.changeset/35287-objectql-face-order-cut.md new file mode 100644 index 00000000000..bdc936723fa --- /dev/null +++ b/.changeset/35287-objectql-face-order-cut.md @@ -0,0 +1,17 @@ +--- +'@objectstack/objectql': patch +'@objectstack/service-analytics': patch +--- + +fix(objectql,service-analytics): `query_dataset`'s ObjectQL face orders and cuts a top-N in the database instead of reading every group + +Clause-②: yes +Metadata-protocol: none + +A top-N (`order` with a `limit`, optionally an `offset`) on the analytics ObjectQL face — date-bucketed queries, `$field` filters, drivers without raw SQL — used to read every group and cut in memory. On a driver that compiles the engine's order-and-cut (the SQL driver family: `driver-sql`, the WASM SQLite driver, Turso's local and replica faces) the face now hands the engine its order and `offset + limit`, the database orders, cuts and counts in one statement, and only the cut rows are read. `totalGroups` stays the count of every group, taken from that statement. + +Visible change: a text-ordered top-N on such a driver now returns the database's choice of groups — its collation, NULL last in both directions — the same as the native SQL face and `aggregate_records`, instead of the in-memory comparator's (`localeCompare`, `''` read as empty). + +Where the engine cannot serve the cut — the in-memory driver, MongoDB, OData, Turso's remote face, a date bucket or reference timezone the driver does not compile, a measure filter it does not evaluate — the face reads every group and cuts in memory as before, and no refusal reaches the caller. A select or lookup dimension ordered by its display label is still cut in memory, by label. + +`@objectstack/objectql`: an `AGGREGATE_ORDER_CUT` request may set `declinable: true`; where the cut cannot be served the engine then reads nothing, answers `[]`, leaves `outcome` unset and records the reason on the request's new `declined` slot instead of refusing `INVALID_QUERY` / 400. Without the flag nothing changes: `aggregate_records` keeps its refusal, and `AggregateOrderCutOutcome` is unchanged. diff --git a/packages/objectql/src/aggregate-order-cut.test.ts b/packages/objectql/src/aggregate-order-cut.test.ts index b3aa2b6a4ea..dc23f556ee8 100644 --- a/packages/objectql/src/aggregate-order-cut.test.ts +++ b/packages/objectql/src/aggregate-order-cut.test.ts @@ -233,3 +233,50 @@ describe('[aggregate order and cut] engine.aggregate — refused on every driver } }); }); + +describe('[aggregate order and cut] a declinable request is DECLINED where it cannot be served — nothing read, no refusal, no outcome', () => { + const declinable = (): AggregateOrderCutRequest => ({ ...TOP_TWO(), declinable: true }); + + for (const name of ['com.objectstack.driver.memory', 'com.objectstack.driver.mongodb', 'com.objectstack.driver.odata']) { + it(`${name}: answers [] with its decline recorded, the driver never asked`, async () => { + const { engine, rec } = await makeEngine(name); + const request = declinable(); + expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))).toEqual([]); + expect(request.outcome).toBeUndefined(); + expect(request.declined?.reason).toContain(`'${name}'`); + expect(rec.calls).toEqual([]); + }); + } + + it('a having, and an aggregate computed in memory (a zone the driver does not bucket), decline on a compiling driver', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + const having = declinable(); + expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER, having: { revenue: { $gt: 10 } } }, withCut(having))).toEqual([]); + expect(having.declined?.reason).toMatch(/having/); + const zoned: AggregateOrderCutRequest = { orderBy: [{ field: 'n', order: 'desc' }], limit: 3, declinable: true }; + expect(await engine.aggregate(ORDER, { + groupBy: [{ field: 'closed_on', dateGranularity: 'month' }], + aggregations: [{ function: 'count', alias: 'n' }], + timezone: 'Asia/Shanghai', + }, withCut(zoned))).toEqual([]); + expect(zoned.declined?.reason).toMatch(/computed in the application/); + expect(rec.calls).toEqual([]); + }); + + it('on a compiling driver it is served exactly as an undeclinable one', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.sql'); + rec.answer([{ customer: 'c9', area: 'west', revenue: 90, n: 3, [AGGREGATE_TOTAL_GROUPS_COLUMN]: 4 }]); + const request = declinable(); + expect(await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request))).toEqual([{ customer: 'c9', area: 'west', revenue: 90, n: 3 }]); + expect(request.outcome).toEqual({ kind: 'served', totalGroups: 4 }); + expect(request.declined).toBeUndefined(); + }); + + it('a request the caller built wrong is still refused: an order key naming no column of the row is INVALID_SORT', async () => { + const { engine, rec } = await makeEngine('com.objectstack.driver.memory'); + const err = await refusalOf(engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut({ orderBy: [{ field: 'nope', order: 'asc' }], limit: 2, declinable: true }))); + expect(err?.code).toBe('INVALID_SORT'); + expect(err?.status).toBe(400); + expect(rec.calls).toEqual([]); + }); +}); diff --git a/packages/objectql/src/aggregate-order-cut.ts b/packages/objectql/src/aggregate-order-cut.ts index 0760cdd6255..87e75c8693a 100644 --- a/packages/objectql/src/aggregate-order-cut.ts +++ b/packages/objectql/src/aggregate-order-cut.ts @@ -45,17 +45,29 @@ * 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 + * ## Refused, or declined to a caller that asked — 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. + * the Turso driver — is not served, and neither 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), or a relation group join. The + * engine never orders or cuts the groups itself: no in-process sort and no + * slower path exist here. + * + * What "not served" answers is the caller's choice. By default the request is + * refused `INVALID_QUERY` / 400 before anything is read — the answer + * `aggregate_records` gives. A caller that already owns a whole-grid answer + * (the analytics `query_dataset` face, which orders and windows the groups it + * is handed) sets {@link AggregateOrderCutRequest.declinable}: the request is + * then DECLINED instead, exactly as the relation group join declines — nothing + * is read, the read answers `[]`, which is not an answer, the reason is on + * the request's `declined` slot and its `outcome` stays unset — and the + * caller reads the groups the way it always has. A request the caller built wrong (an order key naming no column of the + * row) is refused either way. */ import { StandardErrorCode } from '@objectstack/spec/api'; @@ -116,6 +128,15 @@ export interface AggregateOrderCutOutcome { readonly totalGroups: number; } +/** + * Why the engine declined a {@link AggregateOrderCutRequest.declinable} + * request: set instead of {@link AggregateOrderCutOutcome}, before anything + * was read — the read's `[]` is no answer. + */ +export interface AggregateOrderCutDecline { + readonly reason: string; +} + /** * 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 @@ -126,7 +147,17 @@ export interface AggregateOrderCutRequest { readonly orderBy: readonly AggregateOrderKey[]; /** The most groups to answer; absent = every group, still ordered and counted. */ readonly limit?: number; + /** + * Decline rather than refuse where the cut cannot be served + * ({@link aggregateOrderCutRefusal}): nothing is read, the read answers + * `[]`, `outcome` stays unset and {@link declined} carries the refusal's + * reason. Opt-in — absent, the request is refused `INVALID_QUERY` / 400 as + * before. + */ + readonly declinable?: boolean; outcome?: AggregateOrderCutOutcome; + /** Set by the engine when it declined a {@link declinable} request. */ + declined?: AggregateOrderCutDecline; } /** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */ @@ -268,7 +299,9 @@ export function assertAggregateOrderCutShape( * 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. + * way" inside the engine: every reason is a refusal, which a + * {@link AggregateOrderCutRequest.declinable} request turns into a decline + * ({@link declineAggregateOrderCut}) for its caller to serve. */ export function aggregateOrderCutRefusal( object: string, @@ -312,6 +345,16 @@ export function aggregateOrderCutRefusal( return undefined; } +/** + * Records a decline on a {@link AggregateOrderCutRequest.declinable} request + * (the `refusal`'s message is the reason) and answers the read's `[]`, which + * is not an answer. Nothing has been read. + */ +export function declineAggregateOrderCut(request: AggregateOrderCutRequest, refusal: Error): Record[] { + request.declined = { reason: refusal.message }; + return []; +} + /** * 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 diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 6df5f2aca62..03cd568986d 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -82,6 +82,7 @@ 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, + declineAggregateOrderCut, takeAggregateGroupCount, withAggregateOrderCutDirective, } from './aggregate-order-cut.js'; import { @@ -1549,6 +1550,8 @@ export class DeleteAndAggregateFacet { // [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. + // A caller that opted in (`declinable`) is declined instead, nothing + // read, and serves the groups its own way. if (orderCut !== undefined) { const refused = aggregateOrderCutRefusal(object, { driver: drv, @@ -1556,7 +1559,10 @@ export class DeleteAndAggregateFacet { hasHaving: ast.having != null && typeof ast.having === 'object' && Object.keys(ast.having).length > 0, hasRelationGroup: relationGroup !== undefined, }); - if (refused !== undefined) throw refused; + if (refused !== undefined) { + if (orderCut.declinable === true) return declineAggregateOrderCut(orderCut, refused); + 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); diff --git a/packages/services/service-analytics/src/__tests__/objectql-order-cut-face.test.ts b/packages/services/service-analytics/src/__tests__/objectql-order-cut-face.test.ts new file mode 100644 index 00000000000..456bda9cae2 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/objectql-order-cut-face.test.ts @@ -0,0 +1,236 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [order and cut] `query_dataset`'s ObjectQL face cuts a top-N in the + * database: the strategy hands the engine its order and `offset + limit` + * through the plugin's `executeOrderCutAggregate` bridge, the driver's own + * statement orders, cuts and counts (objectql `aggregate-order-cut.ts`), and + * only the cut rows are read. The composition is the plugin's, over a real + * `ObjectQL` and a real `SqliteWasmDriver`, with the ObjectQL face forced. + * + * Pinned: the driver reads only the cut rows and `totalGroups` stays the + * count of every group; a text order is the database's (its collation, NULL + * last in both directions) — the maintainer's ruling, arm A; where the engine + * declines the cut (a driver that compiles none, a date bucket the driver + * does not compile) the face reads every group and cuts in memory, and no + * refusal reaches the caller; a select or lookup dimension ordered by its + * display label is never cut in the database (the executor windows it in + * memory, so the top-N is picked by label). A `having` never reaches this face; + * its decline is pinned in objectql `aggregate-order-cut.test.ts`. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import type { AnalyticsQuery } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { DatasetSchema } from '@objectstack/spec/ui'; + +import { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import type { GroupCountRequest } from '../dataset-group-count.js'; + +const ORDER = 'zz_oc_order'; +const CUSTOMER = 'zz_oc_customer'; +const DIRECTIVE = Symbol.for('objectstack.driver.aggregate.orderCut'); + +const CUSTOMER_FIELDS = { name: { type: 'text', name: 'name' } }; +const ORDER_FIELDS = { + region: { type: 'text', name: 'region' }, + amount: { type: 'number', name: 'amount' }, + closed_on: { type: 'date', name: 'closed_on' }, + customer: { type: 'lookup', name: 'customer', reference: CUSTOMER }, +}; + +const dataset = DatasetSchema.parse({ + name: 'oc_orders', + label: 'Orders', + object: ORDER, + dimensions: [ + { name: 'region', field: 'region', type: 'string' }, + { name: 'customer', field: 'customer', type: 'string' }, + { name: 'closed_on', field: 'closed_on', type: 'date' }, + ], + measures: [ + { name: 'order_count', aggregate: 'count' }, + { name: 'amount_sum', aggregate: 'sum', field: 'amount' }, + ], +}); + +// Ids and names order differently: by id c1 < c2 < c3 < c4, by name Amy (c4) < Bob (c3) < Cat (c2) < Zed (c1). +const CUSTOMERS = [ + { id: 'c1', name: 'Zed' }, { id: 'c2', name: 'Cat' }, { id: 'c3', name: 'Bob' }, { id: 'c4', name: 'Amy' }, +]; +// Five region groups: four texts — `Emea` sorts first under the database's binary collation, after +// `amer` and `apac` under `localeCompare` — and NULL. amount_sum: amer 40, apac 30, Emea 20, zulu 10, NULL 50. +const ORDERS = [ + { id: 'o1', region: 'amer', amount: 25, closed_on: '2026-01-10', customer: 'c1' }, + { id: 'o2', region: 'amer', amount: 15, closed_on: '2026-02-10', customer: 'c2' }, + { id: 'o3', region: 'apac', amount: 30, closed_on: '2026-02-11', customer: 'c3' }, + { id: 'o4', region: 'Emea', amount: 20, closed_on: '2026-03-10', customer: 'c4' }, + { id: 'o5', region: 'zulu', amount: 10, closed_on: '2026-03-11', customer: 'c1' }, + { id: 'o6', region: null, amount: 50, closed_on: '2026-03-12', customer: 'c2' }, +]; + +const CALLER = { userId: 'u_admin', tenantId: 'org_A' } as ExecutionContext; +const OLD_POSTURE = process.env.OS_TENANCY_POSTURE; +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; + +interface Read { readonly object: string; readonly directive: unknown; readonly rows: number } + +async function pluginService(engine: ObjectQL): Promise { + const registered: Record = {}; + const ctx = { + getService: (name: string) => (name === 'data' ? engine : registered[name]), + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + logger: quiet, + }; + await new AnalyticsServicePlugin({ + queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), + }).init(ctx as never); + const service = registered.analytics as AnalyticsService; + service.registerDataset(dataset); + return service; +} + +/** A driver that compiles no cut: named as the in-memory driver, it answers rows and the engine groups them. */ +function rowsOnlyDriver(rows: Record, reads: Read[]) { + return { + name: 'com.objectstack.driver.memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async find(object: string) { + const out = (rows[object] ?? []).map((r) => ({ ...(r as object) })); + reads.push({ object, directive: undefined, rows: out.length }); + return out; + }, + async findOne() { return null; }, async count() { return 0; }, + 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() {}, + }; +} + +const byRegion = (limit: number, order: 'asc' | 'desc', offset?: number) => ({ + dimensions: ['region'], measures: ['amount_sum'], order: { region: order }, limit, ...(offset != null ? { offset } : {}), +}); + +describe('[order and cut] the ObjectQL face on a compiling driver reads only the cut rows', () => { + let driver: SqliteWasmDriver; + let service: AnalyticsService; + const reads: Read[] = []; + + beforeAll(async () => { + process.env.OS_TENANCY_POSTURE = 'isolated'; + driver = new SqliteWasmDriver({ filename: ':memory:' }); + (driver as unknown as { logger: unknown }).logger = quiet; + const engine = new ObjectQL({ logger: quiet }); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerObject({ name: CUSTOMER, label: 'Customer', fields: CUSTOMER_FIELDS } as never); + engine.registerObject({ name: ORDER, label: 'Order', fields: ORDER_FIELDS } as never); + await engine.syncSchemas(); + for (const row of CUSTOMERS) await driver.create(CUSTOMER, { ...row, organization_id: 'org_A' }, { bypassTenantAudit: true } as never); + for (const row of ORDERS) await driver.create(ORDER, { ...row, organization_id: 'org_A' }, { bypassTenantAudit: true } as never); + const aggregate = driver.aggregate.bind(driver); + (driver as unknown as { aggregate: unknown }).aggregate = async (object: string, ast: Record, options?: unknown) => { + const rows = await aggregate(object, ast as never, options as never); + reads.push({ object, directive: ast?.[DIRECTIVE], rows: Array.isArray(rows) ? rows.length : -1 }); + return rows; + }; + service = await pluginService(engine); + }); + + afterAll(async () => { + await driver?.disconnect?.(); + if (OLD_POSTURE === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = OLD_POSTURE; + }); + + it('top two by a measure: one statement, cut to two rows, totalGroups every group', async () => { + reads.length = 0; + const groupCount: GroupCountRequest = {}; + const { rows } = await service.queryDataset(dataset, { + dimensions: ['region'], measures: ['amount_sum'], order: { amount_sum: 'desc' }, limit: 2, + } as never, CALLER, { groupCount }); + expect(rows.map((r) => [r.region, r.amount_sum])).toEqual([[null, 50], ['amer', 40]]); + expect(reads).toEqual([{ object: ORDER, directive: expect.objectContaining({ limit: 2 }), rows: 2 }]); + expect(groupCount.outcome).toEqual({ groupCount: 5 }); + }); + + it('an offset is cut as offset + limit in the statement and skipped here', async () => { + reads.length = 0; + const groupCount: GroupCountRequest = {}; + const { rows } = await service.queryDataset(dataset, { + dimensions: ['region'], measures: ['amount_sum'], order: { amount_sum: 'desc' }, limit: 2, offset: 1, + } as never, CALLER, { groupCount }); + expect(rows.map((r) => r.region)).toEqual(['amer', 'apac']); + expect(reads).toEqual([{ object: ORDER, directive: expect.objectContaining({ limit: 3 }), rows: 3 }]); + expect(groupCount.outcome).toEqual({ groupCount: 5 }); + }); + + it('a text order is the database\'s: its collation picks the top-N, NULL last ascending and descending', async () => { + reads.length = 0; + const asc = await service.queryDataset(dataset, byRegion(1, 'asc') as never, CALLER); + // Binary collation: `Emea` before `amer`; `localeCompare` (the in-memory comparator) would pick `amer`. + expect(asc.rows.map((r) => r.region)).toEqual(['Emea']); + const ascAll = await service.queryDataset(dataset, byRegion(4, 'asc') as never, CALLER); + expect(ascAll.rows.map((r) => r.region)).not.toContain(null); + const descAll = await service.queryDataset(dataset, byRegion(4, 'desc') as never, CALLER); + expect(descAll.rows.map((r) => r.region)).not.toContain(null); + expect(reads.map((r) => r.rows)).toEqual([1, 4, 4]); + expect(reads.every((r) => r.directive !== undefined)).toBe(true); + }); + + it('the analytics query door is the same face: order and limit cut in the statement', async () => { + reads.length = 0; + const { rows } = await service.query({ + cube: dataset.name, dimensions: ['region'], measures: ['order_count'], order: { order_count: 'desc' }, limit: 1, + } as AnalyticsQuery, CALLER); + expect(rows).toEqual([{ region: 'amer', order_count: 2 }]); + expect(reads).toEqual([{ object: ORDER, directive: expect.objectContaining({ limit: 1 }), rows: 1 }]); + }); + + it('a date bucket the driver does not compile (a reference zone) declines: every group read, cut in memory, no refusal', async () => { + reads.length = 0; + const { rows } = await service.query({ + cube: dataset.name, measures: ['order_count'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }], + order: { order_count: 'desc' }, limit: 1, timezone: 'Asia/Shanghai', + } as AnalyticsQuery, CALLER); + expect(rows).toEqual([{ closed_on: '2026-03', order_count: 3 }]); + expect(reads.some((r) => r.directive !== undefined)).toBe(false); + }); + + it('a lookup dimension ordered by its display label is never cut in the database: the top-N is picked by name', async () => { + reads.length = 0; + const groupCount: GroupCountRequest = {}; + const { rows } = await service.queryDataset(dataset, { + dimensions: ['customer'], measures: ['order_count'], order: { customer: 'asc' }, limit: 2, + } as never, CALLER, { groupCount }); + // By name Amy (c4), Bob (c3), rendered by name; a cut on the stored id would have kept c1 (Zed) and c2 (Cat). + expect(rows.map((r) => r.customer)).toEqual(['Amy', 'Bob']); + expect(reads.some((r) => r.directive !== undefined)).toBe(false); + expect(reads.find((r) => r.object === ORDER)?.rows).toBe(4); + expect(groupCount.outcome).toEqual({ groupCount: 4 }); + }); +}); + +describe('[order and cut] on a driver that compiles no cut the face declines to its in-memory cut, no refusal', () => { + it('the in-memory driver: every group read, the top two cut here, totalGroups exact', async () => { + const reads: Read[] = []; + const engine = new ObjectQL({ logger: quiet }); + engine.registerDriver(rowsOnlyDriver({ [ORDER]: ORDERS }, reads) as never, true); + await engine.init(); + engine.registerObject({ name: CUSTOMER, label: 'Customer', fields: CUSTOMER_FIELDS } as never); + engine.registerObject({ name: ORDER, label: 'Order', fields: ORDER_FIELDS } as never); + const service = await pluginService(engine); + const groupCount: GroupCountRequest = {}; + const { rows } = await service.queryDataset(dataset, { + dimensions: ['region'], measures: ['amount_sum'], order: { amount_sum: 'desc' }, limit: 2, + } as never, CALLER, { groupCount }); + expect(rows.map((r) => [r.region, r.amount_sum])).toEqual([[null, 50], ['amer', 40]]); + expect(reads).toEqual([{ object: ORDER, directive: undefined, rows: ORDERS.length }]); + expect(groupCount.outcome).toEqual({ groupCount: 5 }); + }); +}); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 4a5d0c5ee62..040278e1fc4 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -1363,6 +1363,14 @@ export interface AnalyticsServiceConfig { * nothing serves every cross-object dimension by the FK-expand, as before. */ executeRelationGroupAggregate?: DatasetScopedStrategyContext['executeRelationGroupAggregate']; + /** + * The data engine's aggregate ordered and cut by the database. See + * `DatasetScopedStrategyContext.executeOrderCutAggregate` + * (`strategies/types.ts`). `AnalyticsServicePlugin` wires it only when it + * bridges `executeAggregate` itself; a host that wires nothing cuts every + * top-N in memory, as before. + */ + executeOrderCutAggregate?: DatasetScopedStrategyContext['executeOrderCutAggregate']; /** Pre-defined datasets to compile + register at construction (ADR-0021). */ datasets?: Dataset[]; /** @@ -1776,6 +1784,9 @@ export class AnalyticsService implements IAnalyticsService { // The engine's relation group join, passed through untouched; absent, // `ObjectQLStrategy` serves a cross-object dimension by its FK-expand. executeRelationGroupAggregate: config.executeRelationGroupAggregate, + // The engine's order and cut, passed through untouched; absent, + // `ObjectQLStrategy` cuts every top-N in memory. + executeOrderCutAggregate: config.executeOrderCutAggregate, }; // [#21080] …and a host that wires raw SQL without that answer is told so, // once: the native path then serves every object, gated ones included. diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index 0d4a9de1c52..9c1d3969dc6 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -70,6 +70,13 @@ type BridgedAggregateInput = Parameters & Partial> @@ -381,6 +388,7 @@ export class AnalyticsServicePlugin implements Plugin { // without re-implementing the bridge in every app. let executeAggregate = this.options.executeAggregate; let executeRelationGroupAggregate: AnalyticsServiceConfig['executeRelationGroupAggregate']; + let executeOrderCutAggregate: AnalyticsServiceConfig['executeOrderCutAggregate']; let autoBridged = false; // [#19995, ruling C] The engine's judge-only `where` admission, filled below // ONLY when this plugin bridges `executeAggregate` itself, and then to the @@ -518,6 +526,30 @@ export class AnalyticsServicePlugin implements Plugin { reason: request.outcome?.reason ?? 'the "data" engine does not serve a relation group join', }; }; + // [order and cut] …and the same aggregate ordered, cut and counted by + // the driver's own statement. Declinable: where the engine cannot serve + // the cut it reads nothing and says so, and `ObjectQLStrategy` reads + // every group and cuts in memory. Same engine as the executor above. + executeOrderCutAggregate = async (objectName, input, cut) => { + const request: { + orderBy: typeof cut.orderBy; limit: number; declinable: true; + outcome?: { kind?: unknown; totalGroups?: unknown }; + declined?: { reason?: unknown }; + } = { orderBy: cut.orderBy, limit: cut.limit, declinable: true }; + const engine = requireDataEngine(); + const aggregate = engine.aggregate as unknown as ( + object: string, query: unknown, options: Record, + ) => Promise; + const rows = await aggregate.call(engine, objectName, engineAggregateQuery(input), { + [AGGREGATE_ORDER_CUT]: request, + }); + const totalGroups = request.outcome?.totalGroups; + if (request.outcome?.kind === 'served' && typeof totalGroups === 'number') { + return { served: true, rows: rows as Record[], totalGroups }; + } + const reason = request.declined?.reason; + return { served: false, reason: typeof reason === 'string' ? reason : 'the "data" engine did not order and cut the groups' }; + }; autoBridged = true; // [#19995, ruling C] …and the judge, resolved per call through the same @@ -1608,6 +1640,9 @@ export class AnalyticsServicePlugin implements Plugin { // [relation group join] The executing engine's relation group join — // see beside the `executeAggregate` auto-bridge above. executeRelationGroupAggregate, + // [order and cut] The executing engine's order and cut — see beside + // the `executeAggregate` auto-bridge above. + executeOrderCutAggregate, // [#21080] The data engine's per-object middleware answer — see // `hasObjectMiddleware` above. Wired whoever executes raw SQL: the // middlewares live in the engine either way. diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index ec06fe1f2b8..c581598c72a 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -719,7 +719,7 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // ADR-0021 D-C — the base object's read scope (tenant + RLS) MUST be ANDed // in before the query leaves the strategy (#3597). A base-only query has a // single object in play, so one base-object scope is sufficient here. - const rows = await ctx.executeAggregate!(objectName, { + const aggregateInput = { // Structured groupBy items ({field, dateGranularity}) pass through the // executeAggregate bridge to engine.aggregate, which buckets them. The // contract types groupBy as string[]; the cast carries the richer shape. @@ -737,7 +737,12 @@ export class ObjectQLStrategy implements AnalyticsStrategy { // principal-less, which plugin-security used to let through — the #3597 // shape — and since ADR-0096 D5 refuses. context: ctx.context, - }); + }; + // [order and cut] A top-N is ordered and cut by the database where the + // engine can serve that (`readOrderCut`); declined, the face reads every + // group, as it always has, and cuts in memory. + const cut = await this.readOrderCut(query, cube, objectName, aggregateInput, ctx); + const rows = cut?.rows ?? await ctx.executeAggregate!(objectName, aggregateInput); // Remap short field names back to cube-qualified names. Driven by // `projectedDimensions`, so a `timeDimensions`-only bucket — grouped by @@ -774,19 +779,76 @@ export class ObjectQLStrategy implements AnalyticsStrategy { } catch { sql = undefined; } - const answer = this.orderAndWindow(query, mappedRows); + const answer = cut ? this.windowServedCut(query, mappedRows, cut.totalGroups) : this.orderAndWindow(query, mappedRows); return sql ? { rows: answer, fields, sql } : { rows: answer, fields }; } + /** + * [order and cut] The query's top-N read as the database's own ordered and + * cut statement (objectql `aggregate-order-cut.ts`): `order` becomes the + * engine's `orderBy` over the aggregated row's columns, the cut is `offset + + * limit` groups, and the count of groups before it comes back with them. A + * text order is the database's (its collation, NULL last) — the order the + * native face's `ORDER BY` gives, ruled for this face too (arm A of the + * maintainer's ruling on the top-N card). + * + * `undefined` — and the caller reads every group and cuts in memory + * ({@link orderAndWindow}) — when there is nothing to cut (no `limit`), an + * order key names no column of the row, the host wires no seam, or the + * engine declines: a driver that compiles no cut (memory, MongoDB, OData), + * a date bucket or zone the driver does not compile, a measure filter it + * does not evaluate. The request is declinable, so no refusal reaches the + * caller. A label-ordered key (a select or lookup dimension ordered by its + * display label) never reaches here: the dataset executor orders those in + * memory and hands this face no window (`canPushDownWindow`). + */ + private async readOrderCut( + query: AnalyticsQuery, + cube: Cube, + objectName: string, + input: Parameters>[1], + ctx: StrategyContext, + ): Promise<{ rows: Record[]; totalGroups: number } | undefined> { + const seam = (ctx as DatasetScopedStrategyContext).executeOrderCutAggregate; + if (typeof seam !== 'function' || query.limit == null) return undefined; + const limit = (query.offset != null && query.offset > 0 ? query.offset : 0) + query.limit; + if (!Number.isInteger(limit) || limit < 1) return undefined; + const dimensions = new Set(this.projectedDimensions(query)); + const measures = new Set(query.measures ?? []); + const orderBy: Array<{ field: string; order: 'asc' | 'desc' }> = []; + for (const [member, order] of Object.entries(query.order ?? {})) { + const field = measures.has(member) ? member + : dimensions.has(member) ? this.resolveFieldName(cube, member, 'dimension') : undefined; + if (field === undefined) return undefined; + // A second key on a column already ordered breaks no tie: dropped, as + // the comparator would pass over it. + if (!orderBy.some((k) => k.field === field)) orderBy.push({ field, order }); + } + const answer = await seam.call(ctx, objectName, input, { orderBy, limit }); + return answer.served ? { rows: answer.rows, totalGroups: answer.totalGroups } : undefined; + } + + /** + * [order and cut] The window over rows the database already ordered and cut + * to `offset + limit` groups: only the `offset` is left to skip, and the + * rows keep the database's order. The group count is the statement's. + */ + private windowServedCut(query: AnalyticsQuery, rows: Record[], totalGroups: number): Record[] { + const groupCount = groupCountRequestOf(query); + if (groupCount) groupCount.outcome = { groupCount: totalGroups }; + return applyWindow(rows, query.limit, query.offset); + } + /** * [#21316] Apply the query's `order`, then its `offset` and `limit`, to the * aggregated answer — the statement {@link generateSql} echoes, and the * clauses `NativeSQLStrategy` compiles from the same three keys. * - * `engine.aggregate` has no ordering or window grammar - * (`EngineAggregateOptions` declares neither), so the engine returns every - * group in its own arrival order and the face is where these keys are - * applied. Before this, the face dropped all three: every date-bucketed + * `engine.aggregate`'s query has no ordering or window grammar + * (`EngineAggregateOptions` declares neither), and where the engine does + * not order and cut the groups itself ({@link readOrderCut}: no `limit`, or + * a read it declines) it returns every group in its own arrival order and + * the face is where these keys are applied. Before this, the face dropped all three: every date-bucketed * query — which the native face declines, so it lands here — answered every * bucket unordered while its echoed `sql` and `/analytics/sql` rendered * `ORDER BY … LIMIT …`. @@ -814,11 +876,11 @@ export class ObjectQLStrategy implements AnalyticsStrategy { */ private orderAndWindow(query: AnalyticsQuery, rows: Record[]): Record[] { // [query_dataset totalGroups] The rows in hand are every group: no read - // above hands `engine.aggregate` an order or a window, so it answers the - // whole grid, and the cut is this line's. A caller that asked for the - // group count (`dataset-group-count.ts`) gets the grid's length before the - // cut — no read is added for it. A read that ever hands the engine a - // window must take the count from the engine instead, never from here. + // here handed `engine.aggregate` an order or a window (a cut the engine + // served answers through `windowServedCut`), so it answered the whole + // grid, and the cut is this line's. A caller that asked for the group + // count (`dataset-group-count.ts`) gets the grid's length before the cut + // — no read is added for it. const groupCount = groupCountRequestOf(query); if (groupCount) answerWholeGrid(rows, groupCount); return applyWindow(applyOrdering(rows, query.order), query.limit, query.offset); diff --git a/packages/services/service-analytics/src/strategies/types.ts b/packages/services/service-analytics/src/strategies/types.ts index 1d471dd5b66..4ac6878070b 100644 --- a/packages/services/service-analytics/src/strategies/types.ts +++ b/packages/services/service-analytics/src/strategies/types.ts @@ -294,8 +294,41 @@ export interface DatasetScopedStrategyContext extends StrategyContext { options: Parameters>[1], relations: readonly RelationGroupAggregateRelation[], ): Promise; + /** + * The data engine's aggregate of `objectName` ordered by `cut.orderBy` (the + * aggregated row's columns), cut to `cut.limit` groups and counted before + * the cut, all in the driver's own statement (objectql + * `aggregate-order-cut.ts`) — or `undefined` when the host cannot run it. + * + * `ObjectQLStrategy` reads a top-N through it first. The request is + * declinable: where the engine cannot serve the cut (a driver that compiles + * none, an aggregate it computes in memory, a `having`) it reads nothing and + * answers `served: false`, and the strategy reads every group and cuts in + * memory, as before. `AnalyticsServicePlugin` wires it only when it bridges + * `executeAggregate` itself, to the same engine. Declared HERE rather than on + * the spec's {@link StrategyContext} for the reason `getDatasetScope` is: + * nothing about it is an authorable surface. + */ + executeOrderCutAggregate?( + objectName: string, + options: Parameters>[1], + cut: OrderCutAggregateRequest, + ): Promise; +} + +/** The order and cut a {@link DatasetScopedStrategyContext.executeOrderCutAggregate} asks of the engine. */ +export interface OrderCutAggregateRequest { + /** Aggregated-row columns (a group key's column, a measure's alias), in priority order. */ + readonly orderBy: ReadonlyArray<{ readonly field: string; readonly order: 'asc' | 'desc' }>; + /** The most groups to answer, 1 or more. */ + readonly limit: number; } +/** The engine's answer: the cut rows and the count of groups before the cut, or why it declined (nothing read). */ +export type OrderCutAggregateAnswer = + | { readonly served: true; readonly rows: Record[]; readonly totalGroups: number } + | { readonly served: false; readonly reason: string }; + /** One relation a {@link DatasetScopedStrategyContext.executeRelationGroupAggregate} groups through. */ export interface RelationGroupAggregateRelation { /** The single-valued relation (FK) field of the aggregated object. */