Skip to content

Commit 8742938

Browse files
committed
fix(objectql, mcp): unlisted rank values keep their own order; review should-fixes
Contract review S1: a column named by a rank key now stays among the directive's trailing ascending keys (NULL last), so the values the rank does not list, which share one rank, keep a deterministic order and a cut among them answers the same groups on every run. Pinned over real SQLite in runtime (two unlisted values and a NULL at a cut boundary, same answer twice, the tie-break in the statement); the engine and stdio directive pins now show the ranked column among the trailing keys. S2: the aggregate_records description states that a per-record-currency amount ranks by bare numbers across currencies and says to rank inside one currency by filtering on the currency code field; pinned in tools/list. S3: a runtime pin with a registered read middleware narrowing ast.where: the cut rows and totalGroups count only the admitted groups, the uncut aggregate agreeing. N1: the changeset, the engine docblocks and the driver comments say what a rank does in each direction and how the unlisted values order. N3: a pin measures the tool's rank maximum against the engine's at the boundary (500 sent and served, 501 not sent and refused). N4: the stdio read-option constants sit above unwrapRows' docblock. The changeset also names KEY__label on the cut answer. Claude-Session: https://claude.ai/code/session_01JQwxbWDsbbJizuYnDwBxT8 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 32a240b commit 8742938

9 files changed

Lines changed: 204 additions & 56 deletions

‎.changeset/35144-aggregate-order-cut.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ A ranking question ("the top five customers by revenue") over more groups than t
1515

1616
- An order key that names no column of the aggregated row is refused `INVALID_SORT` / 400, naming the columns the query projects.
1717
- 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.
18-
- A NULL ranks last in either direction, except a `sum` or a count with no value, which ranks as the `0` it is served as. Group keys the order does not name break ties, ascending.
19-
- An order key may carry a `rank`, a list of the column's values: the statement ranks each listed value by its position and every other value (a NULL among them) after them, before the cut. It is the tool's own, never an `aggregate_records` argument.
18+
- 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.
19+
- 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.
2020
- 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.
21-
- A fixed-currency amount names its currency in `currencies` on the cut answer too.
21+
- 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.
22+
- 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.
2223
- Without `orderBy` and `limit` the tool answers as before.
2324

2425
`@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.

‎packages/drivers/driver-sql/src/sql-driver-aggregation.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -562,8 +562,10 @@ export class AggregationFacet {
562562
const ref = `${groups}.${this.aliasIdentifierSql(key.column)}`;
563563
const identity = foldedOutput.get(key.column);
564564
if (key.rank !== undefined) {
565-
// A declared order: each listed value ranks by its position, any
566-
// other value (a NULL among them) after every listed one.
565+
// A declared order: each listed value ranks by its position, every
566+
// other value (a NULL among them) on one rank past the listed ones;
567+
// `order` runs over the ranks. The engine's trailing keys order the
568+
// values that share that rank.
567569
const arms = key.rank.map((_, i) => `when ? then ${i}`).join(' ');
568570
outer.orderByRaw(`case ${ref} ${arms} else ${key.rank.length} end ${key.order}`, [...key.rank]);
569571
} else if (identity !== undefined && Number.isFinite(identity)) {
@@ -631,8 +633,9 @@ export const AGGREGATE_ORDER_CUT_DIRECTIVE: unique symbol = Symbol.for('objectst
631633
export interface AggregateOrderCutDirective {
632634
/**
633635
* The full order, every key a column the grouped statement projects. A key
634-
* with a `rank` orders by each value's position in it, any value it does
635-
* not list after every listed one.
636+
* with a `rank` orders by each value's position in it, every value it does
637+
* not list (a NULL among them) on one rank past the listed ones, and `order`
638+
* runs over the ranks.
636639
*/
637640
readonly orderBy: ReadonlyArray<{
638641
readonly column: string;

‎packages/mcp/src/mcp-http-tools.aggregation-entry.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,8 @@ describe('aggregate_records — ordered, cut and counted groups', () => {
334334
expect(Object.keys(tool.inputSchema.properties)).toEqual(expect.arrayContaining(['orderBy', 'limit']));
335335
expect(tool.inputSchema.properties.limit.maximum).toBe(CAP);
336336
expect(tool.description).toMatch(/totalGroups says how many groups existed before the cut/);
337+
// A per-record-currency amount is ranked by its bare numbers: the text keeps the ranking to one currency.
338+
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\./);
337339
expect(tool.description).not.toMatch(/groupCount/);
338340
});
339341
});

‎packages/mcp/src/mcp-http-tools.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3812,6 +3812,11 @@ export function registerObjectTools(
38123812
// cut, and the number of groups before the cut stated.
38133813
'For a ranking (top or bottom N), set orderBy to an aggregation alias or a group key and limit to N: ' +
38143814
'the database orders and cuts the groups, and totalGroups says how many groups existed before the cut. ' +
3815+
// The database ranks a per-record-currency amount by its bare
3816+
// numbers, whatever each group's currency; the caller keeps the
3817+
// ranking to one currency.
3818+
'Ranking an amount whose records each carry their own currency compares bare numbers across currencies: ' +
3819+
'rank it inside one currency by filtering where on its currency code field. ' +
38153820
`At most ${maxLimit} groups come back; truncated: true says more existed. ` +
38163821
'Runs under the caller\'s permissions, row-level security and field-level security.',
38173822
inputSchema: strictToolInput(

‎packages/mcp/src/stdio-data-bridge.aggregate-order-cut.test.ts‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ const DEF = {
3737
},
3838
};
3939
const DIRECTIVE = Symbol.for('objectstack.driver.aggregate.orderCut');
40+
/** The engine's order-cut read option, spelled as the stdio bridge spells it. */
41+
const AGGREGATE_ORDER_CUT = Symbol.for('objectstack.objectql.aggregateOrderCut');
4042
const COUNT_COLUMN = '__os_total_groups';
4143
const PRINCIPAL = { userId: 'u1', isSystem: true } as unknown as ExecutionContext;
4244

@@ -64,15 +66,15 @@ function makeDriver(name: string, answerCount = true) {
6466
return { driver, asts };
6567
}
6668

67-
async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount = true) {
69+
async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount = true, def: typeof DEF | Record<string, any> = DEF) {
6870
const { driver, asts } = makeDriver(driverName, answerCount);
6971
const engine = new ObjectQL();
7072
engine.registerDriver(driver, true);
7173
await engine.init();
72-
engine.registry.registerObject(DEF as any, 'test');
74+
engine.registry.registerObject(def as any, 'test');
7375
const bridge = createStdioDataBridge({
7476
engine: engine as unknown as IDataEngine,
75-
metadataService: { getObject: async (n: string) => (n === OBJECT ? DEF : undefined) } as unknown as IMetadataService,
77+
metadataService: { getObject: async (n: string) => (n === OBJECT ? def : undefined) } as unknown as IMetadataService,
7678
resolvePrincipal: async () => PRINCIPAL,
7779
});
7880
const server = new McpServer({ name: 'pin', version: '0' });
@@ -88,7 +90,7 @@ async function makeStdio(driverName = 'com.objectstack.driver.sql', answerCount
8890
})) as { isError?: boolean; content: Array<{ text: string }> };
8991
return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text) };
9092
};
91-
return { bridge, asts, call, close: () => client.close() };
93+
return { engine, bridge, asts, call, close: () => client.close() };
9294
}
9395

9496
describe('[aggregate order and cut] stdio — aggregate_records over the engine', () => {
@@ -158,7 +160,12 @@ describe('[aggregate order and cut] stdio — aggregate_records over the engine'
158160
expect(body).not.toHaveProperty('groupCount');
159161
expect(h.asts).toHaveLength(1);
160162
expect(h.asts[0][DIRECTIVE]).toEqual({
161-
orderBy: [{ column: 'stage', order: 'asc', rank: ['open', 'won', 'lost'] }, { column: 'customer', order: 'asc' }],
163+
orderBy: [
164+
{ column: 'stage', order: 'asc', rank: ['open', 'won', 'lost'] },
165+
// The ranked column stays among the trailing keys: its unlisted values keep their own order.
166+
{ column: 'stage', order: 'asc' },
167+
{ column: 'customer', order: 'asc' },
168+
],
162169
limit: 6,
163170
totalGroupsColumn: COUNT_COLUMN,
164171
});
@@ -167,6 +174,43 @@ describe('[aggregate order and cut] stdio — aggregate_records over the engine'
167174
}
168175
});
169176

177+
it('the tool\'s longest declared order is the engine\'s longest rank: sent and served at the limit, neither past it', async () => {
178+
// The tool mirrors the engine's rank maximum (it has no runtime dependency
179+
// on the engine); this measures both at the boundary, so either moving
180+
// alone goes red.
181+
const wide = (n: number) => ({
182+
...DEF,
183+
fields: { ...DEF.fields, wide: { name: 'wide', type: 'select', options: Array.from({ length: n }, (_, i) => ({ value: `w${i}` })) } },
184+
});
185+
const AT = 500;
186+
const at = await makeStdio('com.objectstack.driver.sql', true, wide(AT));
187+
try {
188+
const { isError, body } = await at.call({ groupBy: ['wide'], limit: 5 });
189+
// The tool sent the whole declared list as the rank, and the engine served it.
190+
expect(isError, JSON.stringify(body)).toBe(false);
191+
expect(at.asts[0][DIRECTIVE].orderBy[0].rank).toHaveLength(AT);
192+
} finally {
193+
await at.close();
194+
}
195+
const past = await makeStdio('com.objectstack.driver.sql', true, wide(AT + 1));
196+
try {
197+
const { isError, body } = await past.call({ groupBy: ['wide'], limit: 5 });
198+
// One past it, the tool sends no rank…
199+
expect(isError, JSON.stringify(body)).toBe(false);
200+
expect(past.asts[0][DIRECTIVE].orderBy).toEqual([{ column: 'wide', order: 'asc' }]);
201+
// …and the engine refuses that rank, the driver never asked.
202+
const rank = Array.from({ length: AT + 1 }, (_, i) => `w${i}`);
203+
const err: any = await past.engine
204+
.aggregate(OBJECT, { groupBy: ['wide'], aggregations: [{ function: 'count', alias: 'n' }] } as any,
205+
{ [AGGREGATE_ORDER_CUT]: { orderBy: [{ field: 'wide', order: 'asc', rank }], limit: 5 } } as any)
206+
.then(() => undefined, (e: unknown) => e);
207+
expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_QUERY', status: 400 });
208+
expect(past.asts).toHaveLength(1);
209+
} finally {
210+
await past.close();
211+
}
212+
});
213+
170214
it('CONTROL — no order, no limit: the uncut path, no directive, totalGroups and no second spelling of it', async () => {
171215
const h = await makeStdio();
172216
try {

‎packages/mcp/src/stdio-data-bridge.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -302,15 +302,6 @@ interface ObjectDef {
302302
enable?: Record<string, unknown>;
303303
}
304304

305-
/**
306-
* Unwrap what the engine's read path resolves to.
307-
*
308-
* Same shape-tolerance as the ADR-0101 record reader next door: an engine may
309-
* answer a bare array or an envelope carrying `value`. Tolerating BOTH here is
310-
* not the consumer-side aliasing Prime Directive #12 forbids — it is the one
311-
* spelling the existing stdio reader already accepts, kept identical so the two
312-
* readers on this transport cannot disagree about what a row list is.
313-
*/
314305
/**
315306
* The engine's order-cut-count read option for `aggregate`
316307
* (`@objectstack/objectql`, `aggregate-order-cut.ts`), spelled `Symbol.for`
@@ -325,6 +316,15 @@ const STDIO_AGGREGATE_ORDER_CUT: unique symbol = Symbol.for('objectstack.objectq
325316
*/
326317
const STDIO_LATEST_PER: unique symbol = Symbol.for('objectstack.objectql.latestPer');
327318

319+
/**
320+
* Unwrap what the engine's read path resolves to.
321+
*
322+
* Same shape-tolerance as the ADR-0101 record reader next door: an engine may
323+
* answer a bare array or an envelope carrying `value`. Tolerating BOTH here is
324+
* not the consumer-side aliasing Prime Directive #12 forbids — it is the one
325+
* spelling the existing stdio reader already accepts, kept identical so the two
326+
* readers on this transport cannot disagree about what a row list is.
327+
*/
328328
function unwrapRows(res: unknown): Array<Record<string, unknown>> {
329329
const rows =
330330
res && typeof res === 'object' && 'value' in (res as Record<string, unknown>)

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,16 @@ describe('[aggregate order and cut] engine.aggregate — served as the driver\'s
136136
expect(rec.calls).toEqual([]);
137137
});
138138

139-
it('a rank orders a key by its listed values\' positions: handed to the driver as named', async () => {
139+
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 () => {
140140
rec.answer([]);
141141
const request: AggregateOrderCutRequest = { orderBy: [{ field: 'area', order: 'asc', rank: ['west', 'east'] }], limit: 3 };
142142
await engine.aggregate(ORDER, { ...BY_CUSTOMER }, withCut(request));
143+
// Every value the rank does not list shares one rank, so the column's own
144+
// ascending order stays among the trailing keys to tell those groups apart.
143145
expect(rec.calls[0].ast[AGGREGATE_ORDER_CUT_DIRECTIVE].orderBy).toEqual([
144146
{ column: 'area', order: 'asc', rank: ['west', 'east'] },
145147
{ column: 'customer', order: 'asc' },
148+
{ column: 'area', order: 'asc' },
146149
]);
147150
expect(request.outcome).toEqual({ kind: 'served', totalGroups: 0 });
148151
});

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

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,14 @@
2828
* group key's projected name (`alias ?? field`), the namespace `having` filters
2929
* ({@link aggregatedRowColumns}). Any other name is refused `INVALID_SORT` /
3030
* 400, naming the columns this query projects. The group keys the order does
31-
* not name follow it, ascending, so two runs of one request answer the same
32-
* groups in the same order. A NULL ranks last in either direction, except
33-
* where the column answers an identity over nothing (`sum`, the counts:
34-
* `emptyGroupValueFor`), which ranks as that identity — the value the row is
35-
* served with.
31+
* not name, and every group key a `rank` names, follow it, ascending, so two
32+
* runs of one request answer the same groups in the same order. A NULL ranks
33+
* last in either direction, except where the column answers an identity over
34+
* nothing (`sum`, the counts: `emptyGroupValueFor`), which ranks as that
35+
* identity — the value the row is served with. Under a `rank` key the values
36+
* it does not list (a NULL among them) share one rank past the listed ones,
37+
* so they come after them ascending and before them descending; among
38+
* themselves they follow the trailing ascending keys, NULL last.
3639
*
3740
* ## The count is the statement's
3841
*
@@ -93,12 +96,15 @@ export interface AggregateOrderKey {
9396
readonly order: 'asc' | 'desc';
9497
/**
9598
* Order the column by these values' positions instead of by the values
96-
* themselves: a value at position `i` ranks `i`, any value the list does not
97-
* hold (a NULL among them) ranks after every listed one, and `order` runs
98-
* over the ranks. For a group key whose values are declared options, so a
99-
* cut keeps the groups first in the declared order — the order the caller
100-
* reads off the schema it is served, handed down so the statement applies it
101-
* before the cut. Groups the rank does not tell apart fall to the next key.
99+
* themselves: a value at position `i` ranks `i`, every value the list does
100+
* not hold (a NULL among them) ranks `rank.length`, and `order` runs over the
101+
* ranks, so the unlisted values come after the listed ones ascending and
102+
* before them descending. For a group key whose values are declared options,
103+
* so a cut keeps the groups first in the declared order — the order the
104+
* caller reads off the schema it is served, handed down so the statement
105+
* applies it before the cut. Groups the rank does not tell apart fall to the
106+
* next key, and the ranked column itself stays among the trailing ascending
107+
* keys (NULL last), so the unlisted values keep an order of their own.
102108
*/
103109
readonly rank?: ReadonlyArray<string | number>;
104110
}
@@ -125,7 +131,7 @@ export interface AggregateOrderCutRequest {
125131

126132
/** What the driver is handed, on the AST under {@link AGGREGATE_ORDER_CUT_DIRECTIVE}. */
127133
export interface DriverAggregateOrderCut {
128-
/** The full order: the request's keys, then every group key it does not name, ascending. */
134+
/** The full order: the request's keys, then every group key it does not name or names only by a `rank`, ascending. */
129135
readonly orderBy: ReadonlyArray<{
130136
readonly column: string;
131137
readonly order: 'asc' | 'desc';
@@ -309,13 +315,16 @@ export function aggregateOrderCutRefusal(
309315
/**
310316
* The full order the driver applies: the request's keys, then every group key
311317
* column the request does not name, ascending — so the answer is the same
312-
* groups in the same order on every run.
318+
* groups in the same order on every run. A column the request names only by a
319+
* `rank` stays among those trailing keys: the rank leaves every value it does
320+
* not list on one rank, and its own ascending order (NULL last) then tells
321+
* those groups apart.
313322
*/
314323
export function aggregateOrderCutDirective(
315324
request: AggregateOrderCutRequest,
316325
groupColumns: readonly string[],
317326
): DriverAggregateOrderCut {
318-
const named = new Set(request.orderBy.map((k) => k.field));
327+
const named = new Set(request.orderBy.filter((k) => k.rank === undefined).map((k) => k.field));
319328
return {
320329
orderBy: [
321330
...request.orderBy.map((k) => ({ column: k.field, order: k.order, ...(k.rank !== undefined ? { rank: [...k.rank] } : {}) })),

0 commit comments

Comments
 (0)