Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/35287-objectql-face-order-cut.md
Original file line number Diff line number Diff line change
@@ -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.
47 changes: 47 additions & 0 deletions packages/objectql/src/aggregate-order-cut.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
});
});
59 changes: 51 additions & 8 deletions packages/objectql/src/aggregate-order-cut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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}. */
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, unknown>[] {
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
Expand Down
8 changes: 7 additions & 1 deletion packages/objectql/src/engine-delete-and-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -1549,14 +1550,19 @@ 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,
nativeAggregate,
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);
Expand Down
Loading
Loading