Skip to content

Commit 4c2d8d7

Browse files
fix(runtime)!: an analytics query that selects nothing answers 400 VALIDATION_FAILED at the entry (#35771)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao6bxiPKCvVuzoFTExumbxoz)_ Fixes #33840 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — nothing under skills/ covers analytics/query projection or an empty measures ## 维护者速读 - 用户能看到什么变化:调用分析查询接口却既没选指标也没选维度的调用方,现在立刻收到“请至少选择一个指标或维度”的 400 提示,而不是服务器内部错误 500;预览生成语句的接口同样拒绝,不再回显一条坏语句。 - 为什么做:来自质检回归发现的仪表板查询负例,修补分析查询入口校验的缺口,让调用方的输入错误不再被报成服务器故障。 - 出错会怎样:属破坏性收窄(BREAKING):此前预览生成语句的接口对这种空查询回 200,现在回 400;最坏情况是把本来合法的查询误拒为 400,调用方会立刻看到;改动只在入口多一条校验,可直接撤回。 - 要你做什么:这是申报的收窄,按 #35610 需要你在 GitHub 上点一次 Approve;之后席位自主落地。 - 席位意见:通过,没有必改项(席位记录见本 PR 评论)。 ## What changes `POST /api/v1/analytics/query` with `measures: []` and no dimensions passed the entry check (the schema accepts an empty `measures` because a dimension-only query is legal, and it has no cross-field rule), reached the native SQL strategy, which assembled `SELECT FROM "TABLE"`, and answered `500 DATABASE_ERROR`. The `/analytics/sql` door echoed the same statement as a 200. `assertAnalyticsQueryBody` (runtime, `packages/runtime/src/domains/analytics.ts`) now runs one more rule after the schema parse succeeds: a query that selects no measure, no dimension and no `timeDimensions` entry carrying a `granularity` is refused with the existing `400 VALIDATION_FAILED` and one `details.fields[]` entry `{ field: 'measures', code: 'min_items' }` whose message tells the caller to select at least one measure or dimension. Both `/analytics/query` and `/analytics/sql` call this one function, so the `/sql` echo is covered by the same guard with no extra code. The body is still forwarded untouched when it passes. What counts as a projection follows what the strategies group or aggregate by: a measure, a dimension, or a bucketed time dimension (the ObjectQL strategy turns each granularity into a group key). A time dimension with only a `dateRange` is a filter and selects nothing on its own, so it does not rescue an empty projection. No spec change, no new error code (`VALIDATION_FAILED` and the `min_items` field code are existing catalog members). Changeset: `@objectstack/runtime` patch. **BREAKING (narrowing).** `AnalyticsQuerySchema` admits `measures: []` with no minimum, so the refused body was inside the published accept set, and `/analytics/sql` answered it with a 200 before this change. Where the engine refused such a body before choosing a strategy, that refusal now becomes the same 400 at `measures`, measured on the engine at this head for both strategies and both doors: an unknown or `public: false` cube (`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. Declared `Clause-②: no (narrowing)`, as the dataset-door twin was; the changeset carries the FROM/TO, the caller's one-line fix and the ADR-0087 disposition `not-required (no-migration-prescription)`: no schema key, export, stored row or authored value moves. **Read first (by risk):** 1. `packages/runtime/src/domains/analytics.ts`, the new `assertAnalyticsQuerySelectsSomething` and its call at the end of `assertAnalyticsQueryBody` (the risk hunk: the bucketed time-dimension exemption, which keeps a granularity-only query reaching the engine). 2. `packages/runtime/src/analytics-empty-projection-refusal.test.ts` (refusal and preservation pins on both doors). **Two-minute check:** `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/analytics-empty-projection-refusal.test.ts` shows 20 passed. ## Tests New `packages/runtime/src/analytics-empty-projection-refusal.test.ts`, driving the mounted routes through `dispatcher-plugin` with the harness of the sibling empty-cube test, on both `/analytics/query` and `/analytics/sql`: - refusal: `{measures: []}`, `{measures: [], dimensions: []}`, and `{measures: []}` with a date-range-only time dimension each answer 400, `error.code` `VALIDATION_FAILED`, `error.httpStatus` 400, one field entry at `measures` with code `min_items`, and the service is never called; - the envelope parses against `ApiErrorSchema`; - preservation: one measure and no dimension, a dimension-only query, and a bucketed time dimension alone each reach the service with the body untouched; - precedence: an unknown cube with an empty projection gets the 400 at `measures` and never reaches a stub engine that answers `CUBE_NOT_FOUND` / 404 for that cube; control: the same cube with one measure reaches it and answers the 404; and `where`, `order` and `limit` with an empty projection are still refused. <details><summary>Readings (head d8fc051 unless noted)</summary> - new file + sibling empty-cube test at d8fc051: `Test Files 2 passed (2)`, `Tests 24 passed (24)`, lock VERDICT command-exit 0. - `pnpm --filter @objectstack/runtime test` at 5aeaf59 (before the last commit, which only adds a module-top side-effect import to the new test): `Test Files 633 passed (633)`, `Tests 11669 passed | 25 skipped (11694)`, lock VERDICT command-exit 0. - `pnpm --filter @objectstack/runtime typecheck` at 5aeaf59: exit 0 (tsc and check:test-typecheck OK). - Ablation (fix committed first; `scripts/ablation-replace.mjs` deleted the call line, anchor 1 to 0, blob 2fa8f93 to 614cfcb88): `Tests 8 failed | 6 passed (14)`, the 8 being the refusal and envelope cases on both doors, the 6 the preservation cases; restore verified blob equals HEAD and `git diff HEAD` empty. This red run is also the door-level reproduction: without the rule the empty projection reaches the service. - Round 2 at d229284: the pin file has 20 tests, `Test Files 1 passed (1)` / `Tests 20 passed (20)`, VERDICT command-exit 0; runtime typecheck exit 0. Ablation again (call line deleted, blob 2fa8f93 to 614cfcb88): `Tests 12 failed | 8 passed (20)`, the 12 being every refusal, envelope and precedence case on both doors, the 8 being the preservation cases and the 404 controls; restored to the HEAD blob with `git diff HEAD` empty. - Engine readings behind the BREAKING sentence, from a scratch test against `AnalyticsService` (deleted, not committed), body `measures: []`, on `query` and `generateSql` under each of the native SQL and ObjectQL strategies: unknown cube and `public: false` cube gave `CUBE_NOT_FOUND` 404; a walled object gave `PERMISSION_DENIED` 403; `order` on an unselected key gave `INVALID_FIELD` 400; the plain empty projection gave `SELECT FROM` on `generateSql`, and on `query` a 200 with one columnless row under the ObjectQL strategy. </details> ## Acceptance notes - The live 500 was not re-measured on a booted showcase in this run; the card thread carries six live reproductions at f6f5b50 (QA run, comment 6946115523), and the door-level reproduction above shows the unfixed entry forwards the body. - `/analytics/sql`: covered by the same guard with no extra code (both doors call `assertAnalyticsQueryBody`). - The engine itself (`native-sql-strategy`) still builds an empty SELECT list for a caller that reaches it in-process without this door; not changed here (the card's route is the runtime door). ## Verification <details><summary>Local gate subset</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 68 families for this diff; all 68 run locally, reconciled with `--ran`: "68 derived famil(ies) accounted for, 68 run, 0 NOT-MEASURED (a DERIVED zero)". Two needed a second run: `check:dual-build-cjs-loads` first answered PREREQUISITE NOT MET (no full build yet) and then exit 0 once the type-check-debt re-measure had built the tree; `check:test-source-alias` was red on the new test (a metadata load paid inside a clocked window) and green after the module-top import fix at d8fc051. `node scripts/pm/overlap-check.mjs` before each push: VERDICT clean exit 0. CI owns the full farm. At head 806d7f5 (the changeset re-declaration): `check-adr-0087-registration --base origin/main` exit 0 ("1 declared-breaking changeset(s), each carrying an ADR-0087 disposition", BREAKING+bang+clause-②-narrowing, not-required (no-migration-prescription)); `check-changeset-no-major --base origin/main` exit 0 ("This diff introduces no `major` bump"); `check-empty-changeset`, `check-closing-keyword-parity`, `check:doc-authoring`, `check:nul-bytes`, `check:issue-citations`, `check:changeset-gate-self-tests` exit 0. The code and test files are unchanged since d8fc051. Round 2 at d229284 (test file and changeset only): 66 of the 68 derived families run, all exit 0; `--ran` reports 2 UNRUN, `check:type-check-debt` and `check:dual-build-cjs-loads`, which need a full-tree build this worktree does not have. Both read built output and compiled types, which this round does not change; CI runs both. </details> <details><summary>Full dogfood battery (head 806d7f5)</summary> Closure built under the lock (`pnpm --filter '@objectstack/dogfood^...' build`, VERDICT command-exit 0), then `pnpm --filter @objectstack/dogfood test` with no shard and no path: VERDICT command-exit 0, `Test Files 482 passed | 3 skipped (485)`, `Tests 4094 passed | 68 skipped (4162)`, no failure. Not re-run at d229284: `analytics.ts` is unchanged since then, and round 2 changes only the pin file and the changeset text. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7)_ <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibwJEh7hMPPvagWM1g7 --> <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibvvVzM5KhCWkT5f45c --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ecd4b2b commit 4c2d8d7

3 files changed

Lines changed: 242 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
fix(runtime)!: an analytics query that selects nothing answers 400 `VALIDATION_FAILED` at the entry instead of the engine's 500
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. What moves is the answer the two analytics REST doors give a request body that selects no measure, no dimension and no bucketed time dimension: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**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`.
13+
14+
- FROM: the body passed the entry check and reached the engine. `/analytics/query` ran `SELECT FROM "<table>"` and answered `500 DATABASE_ERROR`; `/analytics/sql` echoed the same broken statement as a 200.
15+
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.
16+
- 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.
17+
18+
**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.
19+
20+
The fix for a caller: name at least one measure or dimension (or a time dimension with a `granularity`) in the query.
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `POST /analytics/query` and `POST /analytics/sql` refuse a query that SELECTS
5+
* NOTHING at the door: no measure, no dimension and no `timeDimensions` entry
6+
* with a `granularity` answers `400 VALIDATION_FAILED` with a `fields[]` entry
7+
* at `measures`, and the analytics service is never reached.
8+
*
9+
* The defect this pins shut: the schema accepts `measures: []` (a
10+
* dimension-only query is legal) and has no cross-field rule, so the empty
11+
* projection reached the engine, which ran `SELECT FROM "<table>"` and
12+
* answered `500 DATABASE_ERROR`; the `/analytics/sql` echo of the same body
13+
* printed that statement as a 200. Both doors share one body check.
14+
*
15+
* Harness: the shape `analytics-empty-cube-refusal.test.ts` uses to drive the
16+
* mounted route through `dispatcher-plugin`'s thrown-error exit.
17+
*/
18+
19+
// Paid at collection, not inside a case's clock (check:test-source-alias).
20+
import '@objectstack/metadata';
21+
import { describe, it, expect } from 'vitest';
22+
import { ApiErrorSchema } from '@objectstack/spec/api';
23+
24+
import { createDispatcherPlugin } from './dispatcher-plugin.js';
25+
26+
// [#21061] The analytics domain refuses an anonymous caller first (ADR-0056 D2),
27+
// so this harness signs its caller in; only identity is stubbed.
28+
const SIGNED_IN_AUTH = { api: { getSession: async () => ({ user: { id: 'usr_analytics_caller' } }) } };
29+
30+
function makeFakeServer() {
31+
const handlers: Record<string, (req: any, res: any) => any> = {};
32+
const rec = (verb: string) => (path: string, handler: any) => {
33+
handlers[`${verb} ${path}`] = handler;
34+
};
35+
return {
36+
handlers,
37+
server: { get: rec('GET'), post: rec('POST'), put: rec('PUT'), delete: rec('DELETE'), patch: rec('PATCH') },
38+
};
39+
}
40+
41+
const UNKNOWN_CUBE = 'no_such_cube';
42+
43+
function makeCtx(fakeServer: any, calls: { query: unknown[]; sql: unknown[] }) {
44+
// The engine's own first refusal, stood in for: a cube it cannot find
45+
// answers `CUBE_NOT_FOUND` / 404 (service-analytics `cube-visibility.ts`),
46+
// judged before any strategy runs. The precedence pins below read it.
47+
const refuseUnknownCube = (body: unknown) => {
48+
if ((body as { cube?: unknown } | undefined)?.cube === UNKNOWN_CUBE) {
49+
throw Object.assign(new Error(`Cube '${UNKNOWN_CUBE}' not found`), { status: 404, code: 'CUBE_NOT_FOUND' });
50+
}
51+
};
52+
const analytics = {
53+
query: async (body: unknown) => { calls.query.push(body); refuseUnknownCube(body); return { rows: [], fields: [] }; },
54+
getMeta: async () => [],
55+
generateSql: async (body: unknown) => { calls.sql.push(body); refuseUnknownCube(body); return { sql: 'SELECT 1', params: [] }; },
56+
};
57+
const kernel = {
58+
getService: (name: string) => (name === 'analytics' ? analytics : name === 'auth' ? SIGNED_IN_AUTH : undefined),
59+
getServiceAsync: async (name: string) => (name === 'analytics' ? analytics : name === 'auth' ? SIGNED_IN_AUTH : undefined),
60+
};
61+
return {
62+
getKernel: () => kernel,
63+
getService: (name: string) => (name === 'http.server' ? fakeServer : undefined),
64+
environmentId: undefined,
65+
logger: { info() {}, warn() {}, error() {}, debug() {} },
66+
hook: () => {},
67+
on: () => {},
68+
} as any;
69+
}
70+
71+
function makeRes() {
72+
const res: any = {
73+
statusCode: undefined as number | undefined,
74+
body: undefined as any,
75+
status(c: number) { res.statusCode = c; return res; },
76+
header() { return res; },
77+
json(b: any) { res.body = b; return res; },
78+
};
79+
return res;
80+
}
81+
82+
type Door = '/analytics/query' | '/analytics/sql';
83+
84+
async function post(path: Door, body: unknown) {
85+
const { server, handlers } = makeFakeServer();
86+
const calls = { query: [] as unknown[], sql: [] as unknown[] };
87+
const plugin = createDispatcherPlugin({ prefix: '/api/v1', securityHeaders: false });
88+
await plugin.start?.(makeCtx(server, calls));
89+
const handler = handlers[`POST /api/v1${path}`];
90+
expect(handler, `POST /api/v1${path} must be mounted`).toBeTypeOf('function');
91+
const res = makeRes();
92+
await handler({ body, query: {} }, res);
93+
return { res, calls };
94+
}
95+
96+
const serviceCalls = (calls: { query: unknown[]; sql: unknown[] }) => [...calls.query, ...calls.sql];
97+
98+
const EMPTY_PROJECTIONS: Array<[string, Record<string, unknown>]> = [
99+
['`measures: []`, no dimensions', { cube: 'orders', measures: [] }],
100+
['`measures: []`, `dimensions: []`', { cube: 'orders', measures: [], dimensions: [] }],
101+
[
102+
'`measures: []` with a date-range-only time dimension',
103+
{ cube: 'orders', measures: [], timeDimensions: [{ dimension: 'orders.created_at', dateRange: ['2026-01-01', '2026-01-31'] }] },
104+
],
105+
];
106+
107+
describe.each<Door>(['/analytics/query', '/analytics/sql'])('%s — an empty projection', (door) => {
108+
it.each(EMPTY_PROJECTIONS)('%s answers 400 VALIDATION_FAILED at `measures`, and never calls the service', async (_label, body) => {
109+
const { res, calls } = await post(door, body);
110+
111+
expect(res.statusCode).toBe(400);
112+
expect(res.body.success).toBe(false);
113+
expect(res.body.error.httpStatus).toBe(400);
114+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
115+
expect(res.body.error.details.fields).toEqual([
116+
expect.objectContaining({ field: 'measures', code: 'min_items' }),
117+
]);
118+
// The whole point: a client input mistake is no longer the engine's 500.
119+
expect(serviceCalls(calls)).toEqual([]);
120+
});
121+
122+
it('the envelope parses against ApiErrorSchema', async () => {
123+
const { res } = await post(door, { cube: 'orders', measures: [] });
124+
const parsed = ApiErrorSchema.safeParse(res.body.error);
125+
expect(parsed.success, JSON.stringify(parsed.success ? null : parsed.error.issues)).toBe(true);
126+
});
127+
128+
it.each<[string, Record<string, unknown>]>([
129+
['one measure, no dimension', { cube: 'orders', measures: ['orders.count'] }],
130+
['a dimension-only query', { cube: 'orders', measures: [], dimensions: ['orders.status'] }],
131+
[
132+
'a bucketed time dimension only',
133+
{ cube: 'orders', measures: [], timeDimensions: [{ dimension: 'orders.created_at', granularity: 'month' }] },
134+
],
135+
])('preservation: %s reaches the service with the body untouched', async (_label, body) => {
136+
const { res, calls } = await post(door, body);
137+
138+
expect(res.statusCode ?? 200).toBe(200);
139+
expect(res.body.success).toBe(true);
140+
expect(serviceCalls(calls)).toEqual([body]);
141+
});
142+
});
143+
144+
describe.each<Door>(['/analytics/query', '/analytics/sql'])('%s — the empty-projection refusal answers ahead of the engine', (door) => {
145+
it('an unknown cube with an empty projection gets the 400 at `measures`, not the engine\'s 404', async () => {
146+
const { res, calls } = await post(door, { cube: UNKNOWN_CUBE, measures: [] });
147+
148+
expect(res.statusCode).toBe(400);
149+
expect(res.body.error.httpStatus).toBe(400);
150+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
151+
expect(res.body.error.details.fields).toEqual([
152+
expect.objectContaining({ field: 'measures', code: 'min_items' }),
153+
]);
154+
expect(serviceCalls(calls)).toEqual([]);
155+
});
156+
157+
it('control: the same unknown cube with one measure reaches the engine and answers its 404', async () => {
158+
const { res, calls } = await post(door, { cube: UNKNOWN_CUBE, measures: [`${UNKNOWN_CUBE}.count`] });
159+
160+
expect(res.statusCode).toBe(404);
161+
expect(res.body.error.code).toBe('CUBE_NOT_FOUND');
162+
expect(serviceCalls(calls)).toHaveLength(1);
163+
});
164+
165+
it('`where`, `order` and `limit` do not make a selection', async () => {
166+
const { res, calls } = await post(door, {
167+
cube: 'orders',
168+
measures: [],
169+
where: { status: 'open' },
170+
order: { 'orders.status': 'asc' },
171+
limit: 10,
172+
});
173+
174+
expect(res.statusCode).toBe(400);
175+
expect(res.body.error.httpStatus).toBe(400);
176+
expect(res.body.error.code).toBe('VALIDATION_FAILED');
177+
expect(res.body.error.details.fields).toEqual([
178+
expect.objectContaining({ field: 'measures', code: 'min_items' }),
179+
]);
180+
expect(serviceCalls(calls)).toEqual([]);
181+
});
182+
});

‎packages/runtime/src/domains/analytics.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,46 @@ function assertAnalyticsQueryBody(body: unknown): void {
9797
}
9898
throw validationFailure(message, fields);
9999
}
100+
assertAnalyticsQuerySelectsSomething(parsed.data);
101+
}
102+
103+
/** The sentence an empty projection is refused with. */
104+
const ANALYTICS_EMPTY_PROJECTION_MESSAGE =
105+
'Select at least one measure or dimension: this query names no `measures`, no `dimensions` and no '
106+
+ '`timeDimensions` entry with a `granularity`, so it selects nothing.';
107+
108+
/**
109+
* Refuse a query that SELECTS NOTHING at the entry, with the same
110+
* `400 VALIDATION_FAILED` + `fields[]` the schema refusals above answer.
111+
*
112+
* The schema accepts `measures: []` on purpose — a dimension-only query is
113+
* legal and answers its distinct groups — and has no cross-field rule, so a
114+
* body with no measure and no dimension passed this door and reached the
115+
* engine, where the native SQL strategy assembled `SELECT FROM "<table>"`
116+
* and the driver's syntax error came back as `500 DATABASE_ERROR`: a client
117+
* input mistake answered as a server fault. `/analytics/sql` echoed the same
118+
* broken statement as a 200.
119+
*
120+
* What counts as a projection is what the strategies group or aggregate by:
121+
* a measure, a dimension, or a `timeDimensions` entry carrying a
122+
* `granularity` (the ObjectQL strategy turns each into a bucketed group key).
123+
* A `timeDimensions` entry without one is only a date-range filter, so it
124+
* selects nothing on its own. Validation only — the body is still forwarded
125+
* untouched by the caller.
126+
*/
127+
function assertAnalyticsQuerySelectsSomething(query: {
128+
measures?: readonly unknown[];
129+
dimensions?: readonly unknown[];
130+
timeDimensions?: ReadonlyArray<{ granularity?: unknown }>;
131+
}): void {
132+
const selectsMeasure = (query.measures?.length ?? 0) > 0;
133+
const selectsDimension = (query.dimensions?.length ?? 0) > 0;
134+
const selectsBucket = (query.timeDimensions ?? []).some((td) => !!td.granularity);
135+
if (selectsMeasure || selectsDimension || selectsBucket) return;
136+
throw validationFailure(
137+
`Invalid AnalyticsQuery body: measures: ${ANALYTICS_EMPTY_PROJECTION_MESSAGE}`,
138+
[{ field: 'measures', code: 'min_items', message: ANALYTICS_EMPTY_PROJECTION_MESSAGE }],
139+
);
100140
}
101141

102142
export function createAnalyticsDomain(deps: DomainHandlerDeps): DomainRoute {

0 commit comments

Comments
 (0)