diff --git a/.changeset/33840-analytics-empty-projection.md b/.changeset/33840-analytics-empty-projection.md
new file mode 100644
index 00000000000..e6abce5d8dc
--- /dev/null
+++ b/.changeset/33840-analytics-empty-projection.md
@@ -0,0 +1,20 @@
+---
+'@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 (narrowing)
+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.
+
+The fix for a caller: name at least one measure or dimension (or a time dimension with a `granularity`) in the query.
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..86188bbebc4
--- /dev/null
+++ b/packages/runtime/src/analytics-empty-projection-refusal.test.ts
@@ -0,0 +1,182 @@
+// 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.
+ */
+
+// 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';
+
+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') },
+ };
+}
+
+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); refuseUnknownCube(body); return { rows: [], fields: [] }; },
+ getMeta: async () => [],
+ 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),
+ 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]);
+ });
+});
+
+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([]);
+ });
+});
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 {