From 9a4757769c80336a07d744bc9009d692f9dcb9ba Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:27:09 +0000 Subject: [PATCH 1/5] fix(runtime): refuse an analytics query that selects nothing at the entry with 400 VALIDATION_FAILED Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- ...analytics-empty-projection-refusal.test.ts | 130 ++++++++++++++++++ packages/runtime/src/domains/analytics.ts | 40 ++++++ 2 files changed, 170 insertions(+) create mode 100644 packages/runtime/src/analytics-empty-projection-refusal.test.ts diff --git a/packages/runtime/src/analytics-empty-projection-refusal.test.ts b/packages/runtime/src/analytics-empty-projection-refusal.test.ts new file mode 100644 index 00000000000..375d668fec9 --- /dev/null +++ b/packages/runtime/src/analytics-empty-projection-refusal.test.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `POST /analytics/query` and `POST /analytics/sql` refuse a query that SELECTS + * NOTHING at the door: no measure, no dimension and no `timeDimensions` entry + * with a `granularity` answers `400 VALIDATION_FAILED` with a `fields[]` entry + * at `measures`, and the analytics service is never reached. + * + * The defect this pins shut: the schema accepts `measures: []` (a + * dimension-only query is legal) and has no cross-field rule, so the empty + * projection reached the engine, which ran `SELECT FROM ""` and + * answered `500 DATABASE_ERROR`; the `/analytics/sql` echo of the same body + * printed that statement as a 200. Both doors share one body check. + * + * Harness: the shape `analytics-empty-cube-refusal.test.ts` uses to drive the + * mounted route through `dispatcher-plugin`'s thrown-error exit. + */ + +import { describe, it, expect } from 'vitest'; +import { ApiErrorSchema } from '@objectstack/spec/api'; + +import { createDispatcherPlugin } from './dispatcher-plugin.js'; + +// [#21061] The analytics domain refuses an anonymous caller first (ADR-0056 D2), +// so this harness signs its caller in; only identity is stubbed. +const SIGNED_IN_AUTH = { api: { getSession: async () => ({ user: { id: 'usr_analytics_caller' } }) } }; + +function makeFakeServer() { + const handlers: Record any> = {}; + const rec = (verb: string) => (path: string, handler: any) => { + handlers[`${verb} ${path}`] = handler; + }; + return { + handlers, + server: { get: rec('GET'), post: rec('POST'), put: rec('PUT'), delete: rec('DELETE'), patch: rec('PATCH') }, + }; +} + +function makeCtx(fakeServer: any, calls: { query: unknown[]; sql: unknown[] }) { + const analytics = { + query: async (body: unknown) => { calls.query.push(body); return { rows: [], fields: [] }; }, + getMeta: async () => [], + generateSql: async (body: unknown) => { calls.sql.push(body); return { sql: 'SELECT 1', params: [] }; }, + }; + const kernel = { + getService: (name: string) => (name === 'analytics' ? analytics : name === 'auth' ? SIGNED_IN_AUTH : undefined), + getServiceAsync: async (name: string) => (name === 'analytics' ? analytics : name === 'auth' ? SIGNED_IN_AUTH : undefined), + }; + return { + getKernel: () => kernel, + getService: (name: string) => (name === 'http.server' ? fakeServer : undefined), + environmentId: undefined, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + hook: () => {}, + on: () => {}, + } as any; +} + +function makeRes() { + const res: any = { + statusCode: undefined as number | undefined, + body: undefined as any, + status(c: number) { res.statusCode = c; return res; }, + header() { return res; }, + json(b: any) { res.body = b; return res; }, + }; + return res; +} + +type Door = '/analytics/query' | '/analytics/sql'; + +async function post(path: Door, body: unknown) { + const { server, handlers } = makeFakeServer(); + const calls = { query: [] as unknown[], sql: [] as unknown[] }; + const plugin = createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false }); + await plugin.start?.(makeCtx(server, calls)); + const handler = handlers[`POST /api/v1${path}`]; + expect(handler, `POST /api/v1${path} must be mounted`).toBeTypeOf('function'); + const res = makeRes(); + await handler({ body, query: {} }, res); + return { res, calls }; +} + +const serviceCalls = (calls: { query: unknown[]; sql: unknown[] }) => [...calls.query, ...calls.sql]; + +const EMPTY_PROJECTIONS: Array<[string, Record]> = [ + ['`measures: []`, no dimensions', { cube: 'orders', measures: [] }], + ['`measures: []`, `dimensions: []`', { cube: 'orders', measures: [], dimensions: [] }], + [ + '`measures: []` with a date-range-only time dimension', + { cube: 'orders', measures: [], timeDimensions: [{ dimension: 'orders.created_at', dateRange: ['2026-01-01', '2026-01-31'] }] }, + ], +]; + +describe.each(['/analytics/query', '/analytics/sql'])('%s — an empty projection', (door) => { + it.each(EMPTY_PROJECTIONS)('%s answers 400 VALIDATION_FAILED at `measures`, and never calls the service', async (_label, body) => { + const { res, calls } = await post(door, body); + + expect(res.statusCode).toBe(400); + expect(res.body.success).toBe(false); + expect(res.body.error.httpStatus).toBe(400); + expect(res.body.error.code).toBe('VALIDATION_FAILED'); + expect(res.body.error.details.fields).toEqual([ + expect.objectContaining({ field: 'measures', code: 'min_items' }), + ]); + // The whole point: a client input mistake is no longer the engine's 500. + expect(serviceCalls(calls)).toEqual([]); + }); + + it('the envelope parses against ApiErrorSchema', async () => { + const { res } = await post(door, { cube: 'orders', measures: [] }); + const parsed = ApiErrorSchema.safeParse(res.body.error); + expect(parsed.success, JSON.stringify(parsed.success ? null : parsed.error.issues)).toBe(true); + }); + + it.each<[string, Record]>([ + ['one measure, no dimension', { cube: 'orders', measures: ['orders.count'] }], + ['a dimension-only query', { cube: 'orders', measures: [], dimensions: ['orders.status'] }], + [ + 'a bucketed time dimension only', + { cube: 'orders', measures: [], timeDimensions: [{ dimension: 'orders.created_at', granularity: 'month' }] }, + ], + ])('preservation: %s reaches the service with the body untouched', async (_label, body) => { + const { res, calls } = await post(door, body); + + expect(res.statusCode ?? 200).toBe(200); + expect(res.body.success).toBe(true); + expect(serviceCalls(calls)).toEqual([body]); + }); +}); diff --git a/packages/runtime/src/domains/analytics.ts b/packages/runtime/src/domains/analytics.ts index 57bd7f6ac55..2fa8f933604 100644 --- a/packages/runtime/src/domains/analytics.ts +++ b/packages/runtime/src/domains/analytics.ts @@ -97,6 +97,46 @@ function assertAnalyticsQueryBody(body: unknown): void { } throw validationFailure(message, fields); } + assertAnalyticsQuerySelectsSomething(parsed.data); +} + +/** The sentence an empty projection is refused with. */ +const ANALYTICS_EMPTY_PROJECTION_MESSAGE = + 'Select at least one measure or dimension: this query names no `measures`, no `dimensions` and no ' + + '`timeDimensions` entry with a `granularity`, so it selects nothing.'; + +/** + * Refuse a query that SELECTS NOTHING at the entry, with the same + * `400 VALIDATION_FAILED` + `fields[]` the schema refusals above answer. + * + * The schema accepts `measures: []` on purpose — a dimension-only query is + * legal and answers its distinct groups — and has no cross-field rule, so a + * body with no measure and no dimension passed this door and reached the + * engine, where the native SQL strategy assembled `SELECT FROM "
"` + * and the driver's syntax error came back as `500 DATABASE_ERROR`: a client + * input mistake answered as a server fault. `/analytics/sql` echoed the same + * broken statement as a 200. + * + * What counts as a projection is what the strategies group or aggregate by: + * a measure, a dimension, or a `timeDimensions` entry carrying a + * `granularity` (the ObjectQL strategy turns each into a bucketed group key). + * A `timeDimensions` entry without one is only a date-range filter, so it + * selects nothing on its own. Validation only — the body is still forwarded + * untouched by the caller. + */ +function assertAnalyticsQuerySelectsSomething(query: { + measures?: readonly unknown[]; + dimensions?: readonly unknown[]; + timeDimensions?: ReadonlyArray<{ granularity?: unknown }>; +}): void { + const selectsMeasure = (query.measures?.length ?? 0) > 0; + const selectsDimension = (query.dimensions?.length ?? 0) > 0; + const selectsBucket = (query.timeDimensions ?? []).some((td) => !!td.granularity); + if (selectsMeasure || selectsDimension || selectsBucket) return; + throw validationFailure( + `Invalid AnalyticsQuery body: measures: ${ANALYTICS_EMPTY_PROJECTION_MESSAGE}`, + [{ field: 'measures', code: 'min_items', message: ANALYTICS_EMPTY_PROJECTION_MESSAGE }], + ); } export function createAnalyticsDomain(deps: DomainHandlerDeps): DomainRoute { From 5aeaf5975caa7249622320c55d2ba2005c0aa593 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:32:01 +0000 Subject: [PATCH 2/5] chore(changeset): runtime patch for the analytics empty-projection refusal Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/33840-analytics-empty-projection.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/33840-analytics-empty-projection.md diff --git a/.changeset/33840-analytics-empty-projection.md b/.changeset/33840-analytics-empty-projection.md new file mode 100644 index 00000000000..942405aa122 --- /dev/null +++ b/.changeset/33840-analytics-empty-projection.md @@ -0,0 +1,10 @@ +--- +'@objectstack/runtime': patch +--- + +fix(runtime): an analytics query that selects nothing answers 400 `VALIDATION_FAILED` at the entry instead of the engine's 500 + +Clause-②: no +Metadata-protocol: none + +`POST /api/v1/analytics/query` with `measures: []`, no `dimensions` and no `timeDimensions` entry carrying a `granularity` used to pass the entry check and reach the engine, which ran `SELECT FROM "
"` and answered `500 DATABASE_ERROR`; `POST /api/v1/analytics/sql` echoed the same broken statement as a 200. Both doors now refuse that body with `400 VALIDATION_FAILED` and one `details.fields[]` entry at `measures` (code `min_items`) telling the caller to select at least one measure or dimension, and the analytics service is not called. A dimension-only query, a query with one measure, and a query whose only selection is a bucketed time dimension are unchanged. From d8fc05159ae1f75ea8ecb71e9eaf10ae72830cb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:12:51 +0000 Subject: [PATCH 3/5] test(runtime): pay the metadata load at collection in the empty-projection pin Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- packages/runtime/src/analytics-empty-projection-refusal.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/runtime/src/analytics-empty-projection-refusal.test.ts b/packages/runtime/src/analytics-empty-projection-refusal.test.ts index 375d668fec9..b4419d3da9f 100644 --- a/packages/runtime/src/analytics-empty-projection-refusal.test.ts +++ b/packages/runtime/src/analytics-empty-projection-refusal.test.ts @@ -16,6 +16,8 @@ * mounted route through `dispatcher-plugin`'s thrown-error exit. */ +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; import { describe, it, expect } from 'vitest'; import { ApiErrorSchema } from '@objectstack/spec/api'; From 806d7f5bd1440ecfaa89f00092f4e511c82404e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:49:23 +0000 Subject: [PATCH 4/5] chore(changeset)!: declare the analytics empty-projection refusal as a narrowing, with its ADR-0087 disposition Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/33840-analytics-empty-projection.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.changeset/33840-analytics-empty-projection.md b/.changeset/33840-analytics-empty-projection.md index 942405aa122..50e94b0eb3a 100644 --- a/.changeset/33840-analytics-empty-projection.md +++ b/.changeset/33840-analytics-empty-projection.md @@ -2,9 +2,18 @@ '@objectstack/runtime': patch --- -fix(runtime): an analytics query that selects nothing answers 400 `VALIDATION_FAILED` at the entry instead of the engine's 500 +fix(runtime)!: an analytics query that selects nothing answers 400 `VALIDATION_FAILED` at the entry instead of the engine's 500 -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none -`POST /api/v1/analytics/query` with `measures: []`, no `dimensions` and no `timeDimensions` entry carrying a `granularity` used to pass the entry check and reach the engine, which ran `SELECT FROM "
"` and answered `500 DATABASE_ERROR`; `POST /api/v1/analytics/sql` echoed the same broken statement as a 200. Both doors now refuse that body with `400 VALIDATION_FAILED` and one `details.fields[]` entry at `measures` (code `min_items`) telling the caller to select at least one measure or dimension, and the analytics service is not called. A dimension-only query, a query with one measure, and a query whose only selection is a bucketed time dimension are unchanged. + + +**BREAKING** for a caller of `POST /api/v1/analytics/query` or `POST /api/v1/analytics/sql` whose body has `measures: []`, no `dimensions` (absent or empty) and no `timeDimensions` entry carrying a `granularity`. + +- FROM: the body passed the entry check and reached the engine. `/analytics/query` ran `SELECT FROM "
"` and answered `500 DATABASE_ERROR`; `/analytics/sql` echoed the same broken statement as a 200. +- TO: both doors refuse that body with `400 VALIDATION_FAILED` and one `details.fields[]` entry at `measures` (code `min_items`) telling the caller to select at least one measure or dimension, and the analytics service is not called. + +**Not moved.** A dimension-only query, a query with one measure, and a query whose only selection is a bucketed time dimension are unchanged. A time dimension that carries only a `dateRange` is a filter and does not count as a selection. + +The fix for a caller: name at least one measure or dimension (or a time dimension with a `granularity`) in the query. From d22928425cfe2a262b74fcce52bead222f7edc84 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:32:46 +0000 Subject: [PATCH 5/5] test(runtime): pin the empty-projection refusal ahead of the engine; name the prior engine refusals it supersedes Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .../33840-analytics-empty-projection.md | 1 + ...analytics-empty-projection-refusal.test.ts | 54 ++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.changeset/33840-analytics-empty-projection.md b/.changeset/33840-analytics-empty-projection.md index 50e94b0eb3a..e6abce5d8dc 100644 --- a/.changeset/33840-analytics-empty-projection.md +++ b/.changeset/33840-analytics-empty-projection.md @@ -12,6 +12,7 @@ Metadata-protocol: none **BREAKING** for a caller of `POST /api/v1/analytics/query` or `POST /api/v1/analytics/sql` whose body has `measures: []`, no `dimensions` (absent or empty) and no `timeDimensions` entry carrying a `granularity`. - FROM: the body passed the entry check and reached the engine. `/analytics/query` ran `SELECT FROM "
"` and answered `500 DATABASE_ERROR`; `/analytics/sql` echoed the same broken statement as a 200. + Where the engine refused such a body before choosing a strategy, it answered that refusal instead, and those answers move to the 400 too: an unknown cube or a `public: false` one (`404 CUBE_NOT_FOUND`), a cube over an object the caller may not read (`403 PERMISSION_DENIED`), and an `order` key naming no selected member (`400 INVALID_FIELD`). On a deployment the ObjectQL strategy serves, `/analytics/query` answered a 200 with one row that carries no column. - TO: both doors refuse that body with `400 VALIDATION_FAILED` and one `details.fields[]` entry at `measures` (code `min_items`) telling the caller to select at least one measure or dimension, and the analytics service is not called. **Not moved.** A dimension-only query, a query with one measure, and a query whose only selection is a bucketed time dimension are unchanged. A time dimension that carries only a `dateRange` is a filter and does not count as a selection. diff --git a/packages/runtime/src/analytics-empty-projection-refusal.test.ts b/packages/runtime/src/analytics-empty-projection-refusal.test.ts index b4419d3da9f..86188bbebc4 100644 --- a/packages/runtime/src/analytics-empty-projection-refusal.test.ts +++ b/packages/runtime/src/analytics-empty-projection-refusal.test.ts @@ -38,11 +38,21 @@ function makeFakeServer() { }; } +const UNKNOWN_CUBE = 'no_such_cube'; + function makeCtx(fakeServer: any, calls: { query: unknown[]; sql: unknown[] }) { + // The engine's own first refusal, stood in for: a cube it cannot find + // answers `CUBE_NOT_FOUND` / 404 (service-analytics `cube-visibility.ts`), + // judged before any strategy runs. The precedence pins below read it. + const refuseUnknownCube = (body: unknown) => { + if ((body as { cube?: unknown } | undefined)?.cube === UNKNOWN_CUBE) { + throw Object.assign(new Error(`Cube '${UNKNOWN_CUBE}' not found`), { status: 404, code: 'CUBE_NOT_FOUND' }); + } + }; const analytics = { - query: async (body: unknown) => { calls.query.push(body); return { rows: [], fields: [] }; }, + query: async (body: unknown) => { calls.query.push(body); refuseUnknownCube(body); return { rows: [], fields: [] }; }, getMeta: async () => [], - generateSql: async (body: unknown) => { calls.sql.push(body); return { sql: 'SELECT 1', params: [] }; }, + generateSql: async (body: unknown) => { calls.sql.push(body); refuseUnknownCube(body); return { sql: 'SELECT 1', params: [] }; }, }; const kernel = { getService: (name: string) => (name === 'analytics' ? analytics : name === 'auth' ? SIGNED_IN_AUTH : undefined), @@ -130,3 +140,43 @@ describe.each(['/analytics/query', '/analytics/sql'])('%s — an empty pro expect(serviceCalls(calls)).toEqual([body]); }); }); + +describe.each(['/analytics/query', '/analytics/sql'])('%s — the empty-projection refusal answers ahead of the engine', (door) => { + it('an unknown cube with an empty projection gets the 400 at `measures`, not the engine\'s 404', async () => { + const { res, calls } = await post(door, { cube: UNKNOWN_CUBE, measures: [] }); + + expect(res.statusCode).toBe(400); + expect(res.body.error.httpStatus).toBe(400); + expect(res.body.error.code).toBe('VALIDATION_FAILED'); + expect(res.body.error.details.fields).toEqual([ + expect.objectContaining({ field: 'measures', code: 'min_items' }), + ]); + expect(serviceCalls(calls)).toEqual([]); + }); + + it('control: the same unknown cube with one measure reaches the engine and answers its 404', async () => { + const { res, calls } = await post(door, { cube: UNKNOWN_CUBE, measures: [`${UNKNOWN_CUBE}.count`] }); + + expect(res.statusCode).toBe(404); + expect(res.body.error.code).toBe('CUBE_NOT_FOUND'); + expect(serviceCalls(calls)).toHaveLength(1); + }); + + it('`where`, `order` and `limit` do not make a selection', async () => { + const { res, calls } = await post(door, { + cube: 'orders', + measures: [], + where: { status: 'open' }, + order: { 'orders.status': 'asc' }, + limit: 10, + }); + + expect(res.statusCode).toBe(400); + expect(res.body.error.httpStatus).toBe(400); + expect(res.body.error.code).toBe('VALIDATION_FAILED'); + expect(res.body.error.details.fields).toEqual([ + expect.objectContaining({ field: 'measures', code: 'min_items' }), + ]); + expect(serviceCalls(calls)).toEqual([]); + }); +});