|
| 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 | +}); |
0 commit comments