Skip to content

Commit 28eaade

Browse files
committed
fix(spec)!: an aggregation entry refuses an undeclared key by name on every door
AggregationNodeSchema becomes a strictObject (the unknown-key campaign's message, hints where/filters/conditions -> filter and as -> alias); the retired distinct keeps its tombstone sentence. REST POST /data/:object/query answered 200 with the key stripped; it now answers 400 VALIDATION_FAILED naming the key, before any read. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5m158G1nvmxNYr7Jwq
1 parent 0b6a52e commit 28eaade

2 files changed

Lines changed: 195 additions & 2 deletions

File tree

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#28609] An aggregation entry is closed at the producer: a key
5+
* `AggregationNodeSchema` does not declare is refused by name, on the door a
6+
* caller actually uses — `POST /api/v1/data/:object/query` → `RestServer` →
7+
* `ObjectStackProtocolImplementation.findData` → `ObjectQL.aggregate` → a real
8+
* sqlite `SqlDriver` (the harness `aggregation-filter-where-doors.test.ts`
9+
* boots).
10+
*
11+
* Measured on the base through this door: an entry carrying `bogusKey` (or
12+
* `where`, meant as the entry's own `filter`) answered `200` with the
13+
* unfiltered counts, because the node was a plain `z.object` and zod's
14+
* `.strip` default deleted the key before anyone read it. The MCP tool
15+
* `aggregate_records` had refused the same entry by name since #28550, so one
16+
* entry shape got two verdicts depending on the door. Now the node itself is a
17+
* `strictObject`: REST, the runtime dispatcher's twin (both parse
18+
* `FindDataRequestSchema`) and MCP (which takes the node as its entry) read
19+
* the one refusal, word for word.
20+
*/
21+
22+
import { describe, it, expect, afterEach } from 'vitest';
23+
import { AggregationNodeSchema } from '@objectstack/spec/data';
24+
import { ObjectQL } from '@objectstack/objectql';
25+
import { SqlDriver } from '@objectstack/driver-sql';
26+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
27+
import { RestServer } from './rest-server';
28+
import { installDefaultOrganization } from './default-organization.testkit.js';
29+
30+
const OBJECT = 'ledger_order';
31+
32+
const LEDGER_ORDER = {
33+
name: OBJECT,
34+
label: 'Ledger Order',
35+
fields: {
36+
customer_id: { name: 'customer_id', type: 'text' as const },
37+
amount: { name: 'amount', type: 'number' as const },
38+
},
39+
};
40+
41+
const ROWS = [
42+
{ id: 'o1', customer_id: 'c1', amount: 100 },
43+
{ id: 'o2', customer_id: 'c1', amount: 400 },
44+
{ id: 'o3', customer_id: 'c2', amount: 900 },
45+
{ id: 'o4', customer_id: 'c2', amount: 300 },
46+
{ id: 'o5', customer_id: 'c2', amount: 50 },
47+
];
48+
49+
const liveEngines: ObjectQL[] = [];
50+
afterEach(async () => {
51+
while (liveEngines.length) {
52+
try { await liveEngines.pop()?.destroy(); } catch { /* noop */ }
53+
}
54+
});
55+
56+
function createMockServer() {
57+
const noop = () => {};
58+
return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} };
59+
}
60+
61+
function makeRes() {
62+
const res: any = {
63+
write: () => true, end: () => {},
64+
header: () => res,
65+
status: (code: number) => { res._status = code; return res; },
66+
json: (body: any) => { res._json = body; return res; },
67+
};
68+
return res;
69+
}
70+
71+
async function boot() {
72+
const driver: any = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
73+
const engine = new ObjectQL();
74+
liveEngines.push(engine);
75+
engine.registerDriver(driver, true);
76+
await engine.init();
77+
engine.registry.registerObject(LEDGER_ORDER as any);
78+
await engine.syncSchemas();
79+
await installDefaultOrganization(engine);
80+
await engine.insert(OBJECT, ROWS as any);
81+
82+
const calls = { aggregate: 0, find: 0 };
83+
const find = driver.find.bind(driver);
84+
const aggregate = driver.aggregate.bind(driver);
85+
driver.find = (o: string, ...rest: unknown[]) => { if (o === OBJECT) calls.find += 1; return find(o, ...rest); };
86+
driver.aggregate = (o: string, ...rest: unknown[]) => { if (o === OBJECT) calls.aggregate += 1; return aggregate(o, ...rest); };
87+
88+
const protocol = new ObjectStackProtocolImplementation(engine as any);
89+
const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any);
90+
(rest as any).resolveExecCtx = async () => ({ userId: 'test-user' });
91+
rest.registerRoutes();
92+
const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/query');
93+
expect(route).toBeDefined();
94+
const post = async (body: Record<string, unknown>) => {
95+
const res = makeRes();
96+
await route!.handler({ params: { object: OBJECT }, body: JSON.parse(JSON.stringify(body)) } as any, res);
97+
return res;
98+
};
99+
return { post, calls };
100+
}
101+
102+
/** The refusal the spec node itself prints for one entry — the words every door shares. */
103+
function nodeRefusal(entry: Record<string, unknown>): string {
104+
const parsed = AggregationNodeSchema.safeParse(entry);
105+
expect(parsed.success, 'the spec node refuses this entry').toBe(false);
106+
return parsed.error!.issues[0]!.message;
107+
}
108+
109+
const grouped = (entry: Record<string, unknown>) => ({
110+
groupBy: ['customer_id'],
111+
aggregations: [{ function: 'count', alias: 'n' }, entry],
112+
});
113+
114+
describe('[#28609] POST /data/:object/query — an aggregation entry refuses an undeclared key by name', () => {
115+
const REFUSED: ReadonlyArray<readonly [string, Record<string, unknown>, string, string | undefined]> = [
116+
['a slip (`bogusKey`)', { function: 'sum', field: 'amount', alias: 's', bogusKey: true }, 'bogusKey', undefined],
117+
['`where` meant as the entry\'s own `filter`', { function: 'count', alias: 'm', where: { amount: { $gt: 100 } } }, 'where', 'filter'],
118+
['`as` meant as `alias`', { function: 'sum', field: 'amount', alias: 's', as: 'total' }, 'as', 'alias'],
119+
];
120+
121+
for (const [name, entry, key, canonical] of REFUSED) {
122+
it(`${name}: 400 VALIDATION_FAILED naming the key, before any read`, async () => {
123+
const { post, calls } = await boot();
124+
const res = await post(grouped(entry));
125+
expect(res._status).toBe(400);
126+
expect(res._json.code).toBe('VALIDATION_FAILED');
127+
expect(calls).toEqual({ aggregate: 0, find: 0 });
128+
const fields = res._json.fields as Array<{ field: string; message: string }>;
129+
expect(fields.map((f) => f.field)).toContain('query.aggregations.1');
130+
const message = fields.find((f) => f.field === 'query.aggregations.1')!.message;
131+
// The spec node's own words — the sentence MCP's `aggregate_records` relays too.
132+
expect(message).toBe(nodeRefusal(entry));
133+
expect(message.split('\n')[0]).toContain(`\`${key}\``);
134+
if (canonical) expect(message).toContain(`\`${key}\` → \`${canonical}\``);
135+
});
136+
}
137+
138+
it('CONTROL — the retired `distinct` keeps its tombstone sentence, not the generic refusal', async () => {
139+
const { post, calls } = await boot();
140+
const entry = { function: 'sum', field: 'amount', alias: 's', distinct: true };
141+
const res = await post(grouped(entry));
142+
expect(res._status).toBe(400);
143+
expect(res._json.code).toBe('VALIDATION_FAILED');
144+
expect(calls).toEqual({ aggregate: 0, find: 0 });
145+
const fields = res._json.fields as Array<{ field: string; message: string }>;
146+
const tombstone = fields.find((f) => f.field === 'query.aggregations.1.distinct');
147+
expect(tombstone?.message.split(' — ')[0]).toBe('`query.aggregations[].distinct` was removed in @objectstack/spec 17 (ADR-0049)');
148+
expect(fields.some((f) => f.message.startsWith('Unrecognized key'))).toBe(false);
149+
});
150+
151+
it('CONTROL — entries with only declared members answer as before, filtered and unfiltered', async () => {
152+
const { post, calls } = await boot();
153+
const res = await post({
154+
groupBy: ['customer_id'],
155+
aggregations: [
156+
{ function: 'count', alias: 'n' },
157+
{ function: 'sum', field: 'amount', alias: 's' },
158+
{ function: 'count', alias: 'big', filter: { amount: { $gt: 100 } } },
159+
],
160+
orderBy: [{ field: 'customer_id', order: 'asc' }],
161+
});
162+
expect(res._status ?? 200).toBe(200);
163+
const rows = (res._json.records ?? res._json.data) as Array<Record<string, unknown>>;
164+
const byCustomer = Object.fromEntries(rows.map((r) => [r.customer_id, { n: Number(r.n), s: Number(r.s), big: Number(r.big) }]));
165+
expect(byCustomer).toEqual({ c1: { n: 2, s: 500, big: 1 }, c2: { n: 3, s: 1250, big: 2 } });
166+
expect(calls.aggregate + calls.find).toBeGreaterThan(0);
167+
});
168+
});

‎packages/spec/src/data/query.zod.ts‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,8 +270,32 @@ const AGGREGATION_DISTINCT_REMOVED =
270270
* ],
271271
* groupBy: ['lead_source']
272272
* }
273+
*
274+
* Closed (#28609): a key this node does not declare is refused by name, with
275+
* the unknown-key campaign's message, on every door that takes an entry —
276+
* `POST /data/:object/query` (REST and the runtime dispatcher, both through
277+
* `FindDataRequestSchema`), `EngineAggregateOptionsSchema.aggregations`, and the
278+
* MCP tool `aggregate_records`, which takes this node as its entry. Before, the
279+
* key was stripped and the call answered; MCP alone refused it, from a copy of
280+
* the entry (#28550), so one entry shape got two verdicts by door. The retired
281+
* `distinct` keeps its own tombstone sentence: a declared-but-unwritable key is
282+
* answered by its prescription, never by the generic refusal.
273283
*/
274-
export const AggregationNodeSchema = lazySchema(() => z.object({
284+
export const AggregationNodeSchema = lazySchema(() => strictObject(
285+
{
286+
surface: 'this aggregation entry',
287+
history:
288+
'Until this shape was closed (#28609), an undeclared key here was dropped silently and the '
289+
+ 'aggregation answered as if it had not been sent — a `where` meant as the entry\'s own `filter` '
290+
+ 'computed over every row of the group under an ordinary 200.',
291+
// `where` is the QUERY's filter one level up; the entry's own predicate is
292+
// `filter`. `filters` / `conditions` are the plural and the third-party
293+
// spellings of the same intent, and `as` is SQL's alias keyword. The MCP
294+
// tool `aggregate_records` hinted exactly these from its own copy of the
295+
// entry (#28550) until this node closed and the copy folded into it.
296+
aliases: { where: 'filter', filters: 'filter', conditions: 'filter', as: 'alias' },
297+
},
298+
{
275299
function: AggregationFunction.describe('Aggregation function'),
276300
field: z.string().optional().describe('Field to aggregate (optional for COUNT(*))'),
277301
alias: z.string().describe('Result column alias'),
@@ -295,7 +319,8 @@ export const AggregationNodeSchema = lazySchema(() => z.object({
295319
* and avg/min/max answer null (`emptyGroupValueFor`, aggregation-policy.ts).
296320
*/
297321
filter: FilterConditionSchema.optional().describe('Per-aggregation filter (SQL FILTER (WHERE …) semantics): narrows the source rows THIS aggregation reads, leaving sibling aggregations unfiltered. Enforced by engine.aggregate: lowered in memory for drivers without native conditional aggregation; a driver reached directly refuses rather than silently dropping it.'),
298-
}));
322+
},
323+
));
299324

300325
// ─── Joins: REMOVED (#4286, ADR-0049) ────────────────────────────────────────
301326
// The whole join cluster — `JoinType`, `JoinStrategy`, the internal

0 commit comments

Comments
 (0)