From 1b6d8cc943127f32c2624f728d1222087f85a51b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:38:28 +0000 Subject: [PATCH 01/16] test(service-analytics): pin the dataset query door refusing undeclared members (red first) Lifts the closed-member judgment out of the query_dataset tool into dataset-declared-members.ts so every face reads one rule, and adds the service-level pin, red until AnalyticsService.queryDataset asks it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../dataset-query-declared-members.test.ts | 211 ++++++++++++++++++ .../src/dataset-declared-members.ts | 116 ++++++++++ .../service-analytics/src/dataset-tools.ts | 53 ++--- 3 files changed, 348 insertions(+), 32 deletions(-) create mode 100644 packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts create mode 100644 packages/services/service-analytics/src/dataset-declared-members.ts diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts new file mode 100644 index 00000000000..3b8d0061f88 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -0,0 +1,211 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0021, ADR-0149 D1] `AnalyticsService.queryDataset` — the method + * `POST /analytics/dataset/query` (single and batch), the dashboard, the + * report and the AI tool all reach — answers only the members the dataset + * declares. + * + * Before, it minted a measure the dataset does not declare (`count`, a raw + * field read as its `sum`, an `_sum` suffix spelling, a + * `.`-qualified spelling) and grouped by a raw field named as a + * dimension or a time dimension, so a dashboard tile could show a number the + * dataset never defines. `query_dataset` refused those since it gained the + * closed-member rule; the service now refuses them on every face, with the + * same `INVALID_FIELD` / 400 (`member` / `param` / `cube`), before anything + * is read, naming the members THIS caller may use and the remedy. + * + * Unchanged, and pinned as controls: every declared member is served; a + * declared member over a field the caller may not read still reaches the + * field gate (403); a caller who may not read the object at all gets the read + * refusal (403), never a member list; the cube door (`query()`, not a + * dataset) still mints `count`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { DatasetSchema, type Dataset } from '@objectstack/spec/ui'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import type { AnalyticsService } from '../analytics-service.js'; + +const ME = { userId: 'u_me', tenantId: 'org_a' } as ExecutionContext; +const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; + +const OBJECTS: Record> }> = { + crm_opp: { + fields: { + id: { type: 'text' }, + stage: { type: 'text' }, + region: { type: 'text' }, + amount: { type: 'number' }, + margin: { type: 'number' }, + closed_on: { type: 'date' }, + secret: { type: 'number', internal: true }, + }, + }, + crm_locked: { fields: { id: { type: 'text' }, amount: { type: 'number' } } }, +}; + +const PIPELINE: Dataset = DatasetSchema.parse({ + name: 'pipeline', + label: 'Pipeline', + object: 'crm_opp', + dimensions: [ + { name: 'stage', label: 'Stage', field: 'stage', type: 'string' }, + { name: 'region', label: 'Region', field: 'region', type: 'string' }, + { name: 'close_month', label: 'Close month', field: 'closed_on', type: 'date' }, + ], + measures: [ + { name: 'revenue', label: 'Revenue', aggregate: 'sum', field: 'amount' }, + { name: 'margin_total', label: 'Margin', aggregate: 'sum', field: 'margin' }, + { name: 'deal_count', label: 'Deals', aggregate: 'count' }, + { name: 'secret_sum', label: 'Secret', aggregate: 'sum', field: 'secret' }, + ], +}); +const LOCKED: Dataset = DatasetSchema.parse({ + name: 'locked_ds', + label: 'Locked', + object: 'crm_locked', + dimensions: [], + measures: [{ name: 'total', label: 'Total', aggregate: 'sum', field: 'amount' }], +}); + +const nativeSql = () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }); + +/** u_me may not read `crm_locked` nor the `margin` field; u_admin reads everything. */ +const security = { + getReadFilter: async () => undefined, + canReadObject: (object: string, ctx?: ExecutionContext) => !(ctx?.userId === 'u_me' && object === 'crm_locked'), + getReadableFields: async (object: string, ctx?: ExecutionContext) => { + const all = Object.keys(OBJECTS[object]?.fields ?? {}); + return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all; + }, + getQueryableFields: async (object: string, ctx?: ExecutionContext) => { + const all = Object.keys(OBJECTS[object]?.fields ?? {}); + return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all; + }, +}; + +async function boot(rows: Record[] = [{ stage: 'won', revenue: 100 }]) { + const reads: string[] = []; + const engine = { + execute: async (sql: unknown, options?: { object?: string }) => { + reads.push(`execute:${options?.object ?? String(sql)}`); + return { rows: rows.map((r) => ({ ...r })) }; + }, + hasObjectMiddleware: () => false, + getObject: (name: string) => OBJECTS[name], + resolveEffectiveDatasource: () => undefined, + }; + const registered: Record = {}; + const ctx = { + getService: (name: string) => (name === 'security' ? security : name === 'data' ? engine : registered[name]), + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + }; + await new AnalyticsServicePlugin({ queryCapabilities: nativeSql }).init(ctx as never); + return { service: registered.analytics as AnalyticsService, reads }; +} + +const messageOf = (e: unknown) => String((e as Error)?.message ?? e); + +describe('queryDataset refuses a selection member the dataset does not declare', () => { + it.each([ + ['the ad-hoc count', { measures: ['count'] }, 'count', 'measures'], + ['a raw field as a measure', { measures: ['amount'] }, 'amount', 'measures'], + ['a suffix spelling', { measures: ['amount_sum'] }, 'amount_sum', 'measures'], + ['a dataset-qualified spelling of a declared measure', { measures: ['pipeline.revenue'] }, 'pipeline.revenue', 'measures'], + ['an undeclared measure beside a declared one', { measures: ['revenue', 'amount'] }, 'amount', 'measures'], + ['a raw field as a dimension', { measures: ['revenue'], dimensions: ['region', 'amount'] }, 'amount', 'dimensions'], + [ + 'a raw field as a time dimension', + { measures: ['revenue'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }] }, + 'closed_on', + 'timeDimensions', + ], + ])('%s: 400 INVALID_FIELD naming the member, the declared ones and the remedy, reading nothing', async (_case, selection, member, param) => { + const { service, reads } = await boot(); + const e = await service.queryDataset(PIPELINE, selection as never, ADMIN).catch((err) => err); + expect(e).toBeInstanceOf(Error); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member, param, cube: 'pipeline' }); + expect(messageOf(e)).toContain(`The dataset "pipeline" does not declare the ${param === 'measures' ? 'measure' : 'dimension'} "${member}".`); + for (const declared of ['revenue', 'margin_total', 'deal_count', 'stage', 'region', 'close_month']) { + expect(messageOf(e)).toContain(declared); + } + expect(messageOf(e)).toContain('declare the member on the dataset'); + expect(reads).toEqual([]); + }); + + it('names every undeclared member, and only the members THIS caller may use', async () => { + const { service, reads } = await boot(); + const e = await service + .queryDataset(PIPELINE, { measures: ['count'], dimensions: ['amount'] } as never, ME) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'count', param: 'measures' }); + expect(messageOf(e)).toContain('the measure "count", dimension "amount"'); + expect(messageOf(e)).toContain('revenue'); + // `margin` is withheld from u_me; `secret` is an internal field. + expect(messageOf(e)).not.toContain('margin_total'); + expect(messageOf(e)).not.toContain('secret'); + expect(reads).toEqual([]); + }); + + it('an inline dataset is judged against its own declaration', async () => { + const { service, reads } = await boot(); + const inline = DatasetSchema.parse({ + name: 'draft_ds', + label: 'Draft', + object: 'crm_opp', + dimensions: [], + measures: [{ name: 'opp_count', label: 'Count', aggregate: 'count' }], + }); + await expect(service.queryDataset(inline, { measures: ['count'] } as never, ADMIN)).rejects.toMatchObject({ + code: 'INVALID_FIELD', + status: 400, + member: 'count', + cube: 'draft_ds', + }); + expect(reads).toEqual([]); + const served = await service.queryDataset(inline, { measures: ['opp_count'] } as never, ADMIN); + expect(Array.isArray(served.rows)).toBe(true); + }); + + it('CONTROL: a caller who may not read the object gets the read refusal, never a member list', async () => { + const { service, reads } = await boot(); + const e = await service.queryDataset(LOCKED, { measures: ['count'] } as never, ME).catch((err) => err); + expect(e).toMatchObject({ status: 403 }); + expect(messageOf(e)).not.toContain('Measures you may use'); + expect(reads).toEqual([]); + }); + + it('CONTROL: a declared member over a field the caller may not read still reaches the field gate (403)', async () => { + const { service, reads } = await boot(); + const e = await service.queryDataset(PIPELINE, { measures: ['margin_total'] } as never, ME).catch((err) => err); + expect(e).toMatchObject({ status: 403 }); + expect(reads).toEqual([]); + }); + + it('CONTROL: every declared measure and dimension, a declared time dimension included, is served', async () => { + const { service, reads } = await boot([{ stage: 'won', revenue: 100, deal_count: 1 }]); + const out = await service.queryDataset( + PIPELINE, + { + measures: ['revenue', 'deal_count'], + dimensions: ['stage', 'region'], + timeDimensions: [{ dimension: 'close_month', dateRange: ['2026-01-01', '2026-12-31'] }], + } as never, + ADMIN, + ); + expect(Array.isArray(out.rows)).toBe(true); + expect(reads.length).toBeGreaterThan(0); + }); + + it('CONTROL: the cube door (query(), not a dataset) still mints `count`', async () => { + const { service } = await boot([{ count: 3 }]); + const spy = vi.fn(); + const out = await service.query({ cube: 'crm_opp', measures: ['count'] } as never, ADMIN).catch((e) => spy(e)); + expect(spy).not.toHaveBeenCalled(); + expect(out).toBeDefined(); + }); +}); diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts new file mode 100644 index 00000000000..8debc3377ad --- /dev/null +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -0,0 +1,116 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { DatasetSelection } from '@objectstack/spec/contracts'; +import type { Dataset } from '@objectstack/spec/ui'; +import { invalidMemberError, type AnalyticsRequestKey } from './dataset-refusal.js'; + +/** + * [ADR-0021, ADR-0149 D1] A dataset selection names only the members its + * dataset declares — the one rule every face of a dataset query reads. + * + * The dataset is a declarative, closed surface (ADR-0021): its `measures[]` + * and `dimensions[]` are the definition a dashboard tile, a report, the REST + * door and the AI tool `query_dataset` all quote by name. A selection member + * it does not declare is outside it. Before this rule the dataset path minted + * one on the fly (`count`, a raw field read as its `sum`, a `_sum` + * suffix spelling) and grouped by a raw field named as a dimension, so a tile + * could show a number labelled as a dataset metric the dataset never defines, + * and two faces could disagree about the same name. + * + * Declared means one of the dataset's own `measures[].name` / + * `dimensions[].name`, spelled exactly so: a `.`-qualified spelling + * is not a declared name and is refused too. Judged in the three positions + * that name a member — `measures`, `dimensions` and each + * `timeDimensions[].dimension`. `order` keys and `totals.groupings` are judged + * downstream against the selected members, so they need no second check. + * + * Judged against EVERY declared member, never against the caller's admitted + * subset: a declared member the caller may not read still reaches the field + * gate (403), unchanged. Only the refusal's list of usable members is + * narrowed to the caller's admission (ADR-0100: a withheld member, or one + * over an `internal` field, is never named). + * + * Both faces call {@link undeclaredSelectionMembers}; each words its own + * refusal, because what the caller should do next differs (an AI caller falls + * back to the object query tools, an author declares the member). + */ +export interface UndeclaredSelectionMember { + /** The entry as the selection spelled it. */ + member: string; + /** The selection key it was found under. */ + param: Extract; +} + +/** + * The members `selection` names that `dataset` does not declare, in request + * order, each `(member, param)` pair once. Empty when every member is + * declared. A non-string entry is left to the selection parse, which refuses + * it on its own terms. + */ +export function undeclaredSelectionMembers( + dataset: Pick, + selection: Pick & { timeDimensions?: ReadonlyArray<{ dimension?: unknown } | null | undefined> }, +): UndeclaredSelectionMember[] { + const measures = new Set((dataset.measures ?? []).map((m) => m.name)); + const dimensions = new Set((dataset.dimensions ?? []).map((d) => d.name)); + const undeclared: UndeclaredSelectionMember[] = []; + const judge = (names: readonly unknown[], declared: ReadonlySet, param: UndeclaredSelectionMember['param']) => { + for (const name of names) { + if (typeof name === 'string' && !declared.has(name) && !undeclared.some((u) => u.member === name && u.param === param)) { + undeclared.push({ member: name, param }); + } + } + }; + judge(Array.isArray(selection.measures) ? selection.measures : [], measures, 'measures'); + judge(Array.isArray(selection.dimensions) ? selection.dimensions : [], dimensions, 'dimensions'); + judge( + (Array.isArray(selection.timeDimensions) ? selection.timeDimensions : []).map((td) => td?.dimension), + dimensions, + 'timeDimensions', + ); + return undeclared; +} + +/** `measure "x", dimension "y"` — the members a refusal names, in request order. */ +export function describeUndeclaredMembers(undeclared: readonly UndeclaredSelectionMember[]): string { + return undeclared.map((u) => `${u.param === 'measures' ? 'measure' : 'dimension'} "${u.member}"`).join(', '); +} + +/** + * The declared member names the caller may use, in declaration order: those + * the caller's admission admitted, or none when there is no admission. + */ +export function usableDeclaredMembers( + declared: ReadonlyArray<{ name: string }> | undefined, + admitted: ReadonlySet | undefined, +): string[] { + return (declared ?? []).map((m) => m.name).filter((name) => admitted?.has(name) === true); +} + +/** A list for a refusal sentence: the names, or `(none)`. */ +export function listMemberNames(names: readonly string[]): string { + return names.length > 0 ? names.join(', ') : '(none)'; +} + +/** + * The dataset query door's refusal for a selection that names a member its + * dataset does not declare: `INVALID_FIELD` / 400 (`invalidMemberError`, + * `member` / `param` / `cube` of the first undeclared entry), naming every + * undeclared member, the members THIS caller may use, and the remedy — select + * a declared name, or declare the member on the dataset. + */ +export function undeclaredMembersRefusal( + dataset: Pick, + undeclared: readonly UndeclaredSelectionMember[], + admitted: { measures: ReadonlySet; dimensions: ReadonlySet } | undefined, +): Error { + const first = undeclared[0]; + return invalidMemberError( + `The dataset "${dataset.name}" does not declare the ${describeUndeclaredMembers(undeclared)}. A dataset query ` + + 'answers only the members its dataset declares, by their declared names. ' + + `Measures you may use: ${listMemberNames(usableDeclaredMembers(dataset.measures, admitted?.measures))}. ` + + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admitted?.dimensions))}. ` + + 'Select one of these, or declare the member on the dataset (its `measures` or `dimensions`) and select it by that name.', + { member: first.member, param: first.param, cube: dataset.name }, + ); +} diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 310aa0a78aa..cc4635da312 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -21,7 +21,13 @@ import { DatasetSchema, resolveI18nLabel, type Dataset } from '@objectstack/spec import { fieldsFromZodIssues } from '@objectstack/types'; import type { AnalyticsService, DatasetCatalogAdmission } from './analytics-service.js'; import { dimensionType } from './dataset-compiler.js'; -import { invalidMemberError, type AnalyticsRequestKey } from './dataset-refusal.js'; +import { invalidMemberError } from './dataset-refusal.js'; +import { + describeUndeclaredMembers, + listMemberNames, + undeclaredSelectionMembers, + usableDeclaredMembers, +} from './dataset-declared-members.js'; import { matchDatasetTerms } from './dataset-term-matcher.js'; /** @@ -568,13 +574,14 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { * [ADR-0149] `query_dataset` answers only the members the dataset declares. * * The dataset is the one declared definition (D1): a selection member it does - * not declare is outside it. `AnalyticsService.queryDataset` serves the REST - * door, the dashboard and the report too, and mints a caller-named measure the - * cube does not declare (`count`, a raw field read as its `sum`, an - * `_sum` suffix spelling) and groups by a raw field named as a - * dimension. Through this tool such an answer was cited in `provenance` as a - * governed metric, which is exactly what D3's fallback rule keeps apart - * (非指标口径). So the tool refuses it here, before anything is read. + * not declare is outside it. Through this tool an answer over one (`count`, a + * raw field read as its `sum`, an `_sum` suffix spelling, a raw field + * named as a dimension) would be cited in `provenance` as a governed metric, + * which is exactly what D3's fallback rule keeps apart (非指标口径). So the + * tool refuses it here, before anything is read. `AnalyticsService.queryDataset` + * — the REST door, the dashboard and the report — refuses the same members by + * the same rule ({@link undeclaredSelectionMembers}); the tool judges first so + * its refusal carries the AI caller's fallback, which the service's does not. * * Declared means one of the dataset's own `measures[].name` / * `dimensions[].name`, spelled as `list_datasets` lists it: a @@ -594,34 +601,16 @@ function assertDeclaredMembers( selection: DatasetSelection, admission: Extract | undefined, ): void { - const measures = new Set((dataset.measures ?? []).map((m) => m.name)); - const dimensions = new Set((dataset.dimensions ?? []).map((d) => d.name)); - const undeclared: Array<{ member: string; param: AnalyticsRequestKey }> = []; - const judge = (names: readonly unknown[], declared: ReadonlySet, param: AnalyticsRequestKey) => { - for (const name of names) { - if (typeof name === 'string' && !declared.has(name) && !undeclared.some((u) => u.member === name && u.param === param)) { - undeclared.push({ member: name, param }); - } - } - }; - judge(selection.measures ?? [], measures, 'measures'); - judge(selection.dimensions ?? [], dimensions, 'dimensions'); - judge( - ((selection as { timeDimensions?: Array<{ dimension?: unknown }> }).timeDimensions ?? []).map((td) => td?.dimension), - dimensions, - 'timeDimensions', - ); + // The one rule every face of a dataset query reads (`dataset-declared-members.ts`); + // this face words its own refusal, because an AI caller's next step differs. + const undeclared = undeclaredSelectionMembers(dataset, selection); if (undeclared.length === 0) return; - const usable = (declared: ReadonlyArray<{ name: string }>, admitted: ReadonlySet | undefined) => - declared.map((m) => m.name).filter((name) => admitted?.has(name) === true); - const list = (names: string[]) => (names.length > 0 ? names.join(', ') : '(none)'); - const named = undeclared.map((u) => `${u.param === 'measures' ? 'measure' : 'dimension'} "${u.member}"`).join(', '); const first = undeclared[0]; throw invalidMemberError( - `The dataset "${dataset.name}" does not declare the ${named}. query_dataset answers only the members a dataset ` - + `declares, by the names list_datasets lists. Measures you may use: ${list(usable(dataset.measures ?? [], admission?.measures))}. ` - + `Dimensions you may use: ${list(usable(dataset.dimensions ?? [], admission?.dimensions))}. Pick one of these; when none ` + `The dataset "${dataset.name}" does not declare the ${describeUndeclaredMembers(undeclared)}. query_dataset answers only the members a dataset ` + + `declares, by the names list_datasets lists. Measures you may use: ${listMemberNames(usableDeclaredMembers(dataset.measures, admission?.measures))}. ` + + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admission?.dimensions))}. Pick one of these; when none ` + 'fits the question, answer with the object query tools and say that no governed metric was used (非指标口径).', { member: first.member, param: first.param, cube: dataset.name }, ); From e1463945becc04b6204b2c46b82e851b47cf49bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 22:52:45 +0000 Subject: [PATCH 02/16] fix(service-analytics)!: the dataset query door refuses measures and dimensions the dataset does not declare AnalyticsService.queryDataset (POST /analytics/dataset/query, single and batch, dashboards, reports) asks the closed-member rule query_dataset asks: an undeclared measure, dimension or time dimension is refused with 400 INVALID_FIELD before anything is read, naming the members this caller may use and the remedy (declare the member on the dataset). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- content/docs/data-modeling/analytics.mdx | 12 +++++ .../src/analytics-service.ts | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/content/docs/data-modeling/analytics.mdx b/content/docs/data-modeling/analytics.mdx index 3876dfd94cc..0235acb8461 100644 --- a/content/docs/data-modeling/analytics.mdx +++ b/content/docs/data-modeling/analytics.mdx @@ -269,6 +269,18 @@ with `400 VALIDATION_FAILED` naming it (a `runtimeFilter` beside `selection` answers "did you mean `selection.runtimeFilter`?"), and so is a body naming both `dataset` and `datasetName`. +A selection names only the members its dataset declares: each `measures` entry +is one of the dataset's `measures[].name`, and each `dimensions` entry and +`timeDimensions[].dimension` one of its `dimensions[].name`, spelled exactly so. +Anything else — the ad-hoc `count`, a raw field such as `amount`, a suffix +spelling such as `amount_sum`, a `.revenue` spelling, a raw field named +as a dimension — is refused with `400 INVALID_FIELD` before anything is read. +The refusal names the member (`member`, `param`, `cube`), lists the measures +and dimensions you may use, and the fix is to select one of them or declare the +member on the dataset. An inline `dataset` is judged against its own +`measures` and `dimensions`. The cube query (`POST {basePath}/analytics/query`) +is not a dataset and keeps its ad-hoc members. + A `datasetName` is read the way `GET /meta/dataset/:name` reads it: the environment's own dataset, else the one package that holds the name. A name two packages hold answers `409 RESOURCE_CONFLICT` naming both, and nothing runs. To diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 9dd5c474235..386a29b96ee 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -137,6 +137,8 @@ import { scopedMeasureFilter, scopedMeasureKey } from './scoped-measure-key.js'; // member as the request spelled it (see `dataset-refusal.ts`'s header for why // that code and not `DATASET_INVALID`). import { invalidMemberError } from './dataset-refusal.js'; +// [ADR-0021, ADR-0149 D1] The closed-member rule every dataset face reads. +import { undeclaredMembersRefusal, undeclaredSelectionMembers } from './dataset-declared-members.js'; // [#20807] A grouped dimension on a structured-JSON field is refused in // `ensureCube`, ahead of both strategies, naming the member the caller wrote. import { assertNoStructuredJsonDimension } from './structured-json-dimension-door.js'; @@ -2977,6 +2979,46 @@ export class AnalyticsService implements IAnalyticsService { ); } + /** + * [ADR-0021, ADR-0149 D1] Refuse a selection member the dataset does not + * declare — `INVALID_FIELD` / 400, before anything is read. + * + * The dataset is a declarative, closed surface: a dashboard tile, a report, + * `POST /analytics/dataset/query` (single and batch) and the AI tool all + * quote its `measures[].name` / `dimensions[].name`. This method used to + * mint a measure the dataset does not declare (`count`, a raw field read as + * its `sum`, an `_sum` suffix spelling) and group by a raw field named + * as a dimension or time dimension, so a tile could show a number labelled + * as a dataset metric that the dataset never defines. The rule is + * {@link undeclaredSelectionMembers}, the one `query_dataset` asks; an + * inline dataset (a Studio draft) is judged against its own declaration. + * The cube door, {@link query}, is not a dataset and keeps its ad-hoc + * members. + * + * The refusal names the members THIS caller may use, from the catalogue's + * admission ({@link admitDatasetCatalogEntry}), asked only on this refusal + * path. A caller the admission does not admit at all is answered by the read + * gate the query would have asked (403, or 503 when it cannot decide), never + * with a member list. A declared member the caller may not read is not + * judged here: it still reaches the field gate (403). + */ + private async assertSelectionMembersDeclared( + dataset: Dataset, + compiled: CompiledDataset, + selection: DatasetSelection, + context?: ExecutionContext, + ): Promise { + const undeclared = undeclaredSelectionMembers(dataset, selection ?? ({} as DatasetSelection)); + if (undeclared.length === 0) return; + const admission = await this.admitDatasetCatalogEntry(dataset, context); + if (!admission.admitted) { + const objects = this.cubeObjects(compiled.cube); + this.assertQueryObjectsExposed(objects); + await this.assertReadAdmitted(objects, context); + } + throw undeclaredMembersRefusal(dataset, undeclared, admission.admitted ? admission : undefined); + } + /** * Execute a semantic-layer dataset (ADR-0021). Compiles the dataset (saved or * inline draft — Studio preview) for THIS call, then runs the selection @@ -3041,6 +3083,11 @@ export class AnalyticsService implements IAnalyticsService { this.assertQueryObjectsExposed([dataset.object]); this.assertDatasetFieldsJudgeable(dataset, context); const compiled = this.compile(dataset); + // [ADR-0021, ADR-0149 D1] The selection names only the members the + // dataset declares, judged here — after the dataset compiled, before the + // draft-preview branch and before anything is read — on every face this + // method serves. See {@link assertSelectionMembersDeclared}. + await this.assertSelectionMembersDeclared(dataset, compiled, selection, context); this.logger.debug(`[Analytics] queryDataset "${dataset.name}" (object=${dataset.object}, include=${(dataset.include ?? []).join(',') || '—'})`); // ── ADR-0037 P3 — draft data preview ──────────────────────────────────── From 73500966f1a4b57073b88191ebca0adfa23ba910 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:11:26 +0000 Subject: [PATCH 03/16] test(service-analytics): triage the dataset-face pins the closed-member rule moves Pins whose subject was minting or judging an undeclared selection member on the dataset path now assert the closed-member refusal on every face; pins whose subject is still reachable through declared members are re-spelled to declared dimensions over the same columns. Adds the REST-door dogfood pin. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...s-dataset-declared-members.dogfood.test.ts | 95 +++++++++++++ .../__tests__/dataset-drill-scopes.test.ts | 14 +- .../dimension-source-field-gate.test.ts | 27 ++-- ...ted-dimension-unbacked-join-parity.test.ts | 61 +++------ .../dotted-path-preview-parity.test.ts | 72 +++++----- ...filter-field-json-dimension-parity.test.ts | 42 ++++-- .../preview-time-filter-fk-parity.test.ts | 125 +++++++++++------- ...review-undeclared-dimension-parity.test.ts | 97 ++++++-------- .../preview-undeclared-measure-parity.test.ts | 90 ++++--------- .../query-dataset-request-scope.test.ts | 21 ++- .../src/dataset-declared-members.ts | 2 +- 11 files changed, 361 insertions(+), 285 deletions(-) create mode 100644 packages/qa/dogfood/test/analytics-dataset-declared-members.dogfood.test.ts diff --git a/packages/qa/dogfood/test/analytics-dataset-declared-members.dogfood.test.ts b/packages/qa/dogfood/test/analytics-dataset-declared-members.dogfood.test.ts new file mode 100644 index 00000000000..c2976c14a7a --- /dev/null +++ b/packages/qa/dogfood/test/analytics-dataset-declared-members.dogfood.test.ts @@ -0,0 +1,95 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// END-TO-END gate: `POST /analytics/dataset/query` with a saved `datasetName` +// answers only the members the dataset declares (ADR-0021, ADR-0149 D1), +// proven on the stock showcase through the real stack (HTTP → REST → the +// dataset query door → AnalyticsService.queryDataset). +// +// Before, the door minted a member the dataset does not declare: the ad-hoc +// `count`, a raw field read as its `sum`, an `_sum` suffix spelling, a +// `.`-qualified spelling, and a raw field named as a dimension or a +// time dimension, each answered 200. Each now answers 400 INVALID_FIELD with +// the same refusal the AI tool `query_dataset` gives, on the single door and +// on each entry of the batch door. +// +// Controls: the declared members are served (200) on both doors; a missing +// dataset is still 404 first. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootShowcase } from './showcase-boot.js'; + +const DATASET = 'showcase_task_metrics'; + +describe('dogfood: the dataset query door refuses members the dataset does not declare', () => { + let stack: VerifyStack; + let token: string; + + beforeAll(async () => { + stack = await bootShowcase(); + token = await stack.signIn(); + }, 180_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + async function datasetQuery(body: Record): Promise<{ status: number; body: Record }> { + const res = await stack.apiAs(token, 'POST', '/analytics/dataset/query', body); + return { status: res.status, body: (await res.json()) as Record }; + } + const codeOf = (body: Record) => body.error?.code ?? body.code; + const messageOf = (body: Record) => String(body.error?.message ?? body.message ?? ''); + + it('CONTROL: declared measures and dimensions, a declared time dimension included, are served', async () => { + const res = await datasetQuery({ + datasetName: DATASET, + selection: { + measures: ['task_count', 'est_hours'], + dimensions: ['status'], + timeDimensions: [{ dimension: 'created_at', dateRange: ['2000-01-01', '2100-12-31'] }], + }, + }); + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(Array.isArray(res.body.rows)).toBe(true); + }); + + it.each([ + ['the ad-hoc count', { measures: ['count'] }, 'measure "count"'], + ['a raw field as a measure', { measures: ['estimate_hours'] }, 'measure "estimate_hours"'], + ['a suffix spelling', { measures: ['estimate_hours_sum'] }, 'measure "estimate_hours_sum"'], + ['a dataset-qualified spelling', { measures: [`${DATASET}.task_count`] }, `measure "${DATASET}.task_count"`], + ['a raw field as a dimension', { measures: ['task_count'], dimensions: ['estimate_hours'] }, 'dimension "estimate_hours"'], + [ + 'a raw field as a time dimension', + { measures: ['task_count'], timeDimensions: [{ dimension: 'updated_at', granularity: 'month' }] }, + 'dimension "updated_at"', + ], + ])('%s → 400 INVALID_FIELD naming it and the declared members', async (_case, selection, named) => { + const res = await datasetQuery({ datasetName: DATASET, selection }); + expect(res.status, JSON.stringify(res.body)).toBe(400); + expect(codeOf(res.body)).toBe('INVALID_FIELD'); + expect(messageOf(res.body)).toContain(`The dataset "${DATASET}" does not declare the ${named}.`); + expect(messageOf(res.body)).toContain('task_count'); + expect(messageOf(res.body)).toContain('declare the member on the dataset'); + }); + + it('the batch door refuses the same entry with the same answer, and serves its declared sibling', async () => { + const res = await stack.apiAs(token, 'POST', '/analytics/dataset/query/batch', { + queries: [ + { datasetName: DATASET, selection: { measures: ['count'] } }, + { datasetName: DATASET, selection: { measures: ['task_count'] } }, + ], + }); + expect(res.status).toBe(200); + const [refused, served] = ((await res.json()) as any).data.results; + expect([refused.status, refused.error.code]).toEqual([400, 'INVALID_FIELD']); + expect(refused.error.message).toContain(`The dataset "${DATASET}" does not declare the measure "count".`); + expect(Array.isArray(served.data?.rows)).toBe(true); + }); + + it('CONTROL: a missing dataset is still 404 first, whatever the members', async () => { + const res = await datasetQuery({ datasetName: 'no_such_dataset', selection: { measures: ['count'] } }); + expect(res.status, JSON.stringify(res.body)).toBe(404); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts b/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts index 64939fdba02..6312e689be7 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts @@ -132,11 +132,15 @@ describe('[#30526] the dataset answer carries each measure\'s drill scope', () = expect(JSON.stringify(seen)).not.toContain('current_user_id'); }); - it('keys by the selection\'s spelling: a cube-qualified measure carries its own filter', async () => { - const answer = await mockedService([{ region: 'emea', 'showcase_invoice_metrics.paid_count': 2 }]).queryDataset( - invoiceDataset(), { dimensions: ['region'], measures: ['showcase_invoice_metrics.paid_count'] }, CTX, - ); - expect(answer.drillScopes).toEqual({ 'showcase_invoice_metrics.paid_count': { status: 'paid' } }); + it('a cube-qualified spelling is not a declared name: refused before any read, no scope keyed by it', async () => { + // The dataset is a closed surface (ADR-0149 D1): `.paid_count` is + // not the declared `paid_count`, so the door refuses it rather than + // keying a drill scope by that spelling. + await expect( + mockedService([{ region: 'emea', 'showcase_invoice_metrics.paid_count': 2 }]).queryDataset( + invoiceDataset(), { dimensions: ['region'], measures: ['showcase_invoice_metrics.paid_count'] }, CTX, + ), + ).rejects.toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'showcase_invoice_metrics.paid_count', param: 'measures' }); }); it('a dimensionless KPI answer carries it; an answer with no rows does not', async () => { diff --git a/packages/services/service-analytics/src/__tests__/dimension-source-field-gate.test.ts b/packages/services/service-analytics/src/__tests__/dimension-source-field-gate.test.ts index 4e0d9f3dbb2..e03d168725f 100644 --- a/packages/services/service-analytics/src/__tests__/dimension-source-field-gate.test.ts +++ b/packages/services/service-analytics/src/__tests__/dimension-source-field-gate.test.ts @@ -309,8 +309,10 @@ describe('#5520 — the dataset face: refused before SQL exists, so nothing can measures: ['account_count'], dimensions: ['bogus_dim'], } as any), - ).rejects.toMatchObject({ ...INVALID_FIELD, field: 'bogus_dim', dimension: 'bogus_dim' }); + ).rejects.toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'bogus_dim', param: 'dimensions' }); + // [ADR-0149 D1] On the dataset face an undeclared dimension is refused by + // the closed-member rule, ahead of this gate, with the same code/status. // Repro ③'s leak, at its source: no statement was ever built, so there is // no SQL for the REST envelope to echo. (`rest-server`'s 500 branch is // sanitised as well — see `analytics-dataset-dimension-gate.test.ts` — @@ -329,9 +331,9 @@ describe('#5520 — the dataset face: refused before SQL exists, so nothing can } as any), ); - // It names the object and the field — a caller-shaped fact — and neither - // a SELECT list, a quoted table name, nor a GROUP BY clause. - expect(err.message).toContain("object 'crm_account' does not have"); + // It names the dataset and the member — a caller-shaped fact — and + // neither a SELECT list, a quoted table name, nor a GROUP BY clause. + expect(err.message).toContain('does not declare the dimension "bogus_dim"'); expect(err.message).not.toMatch(/SELECT/i); expect(err.message).not.toMatch(/GROUP BY/i); expect(err.message).not.toMatch(/no such column/); @@ -383,20 +385,17 @@ describe('#5520 — what the gate must NOT do', () => { expect(aggregated).toEqual(['crm_account']); }); - it('lets an UNDECLARED but REAL field group, on the dataset path', async () => { - // Same contract through `queryDataset`: `phone` is not one of - // `account_metrics`' declared dimensions, and still groups. + it('refuses an UNDECLARED but REAL field on the dataset path, which the cube path lets group', async () => { + // `phone` is not one of `account_metrics`' declared dimensions. The cube + // path above lets it group; the dataset is a closed surface (ADR-0149 + // D1), so `queryDataset` refuses it before any statement is built. const { service, sqls } = makeService({ native: true }); - const result = await service.queryDataset(ACCOUNT_METRICS, { + await expect(service.queryDataset(ACCOUNT_METRICS, { measures: ['account_count'], dimensions: ['phone'], - } as any); - - expect(result.rows).toEqual([{ account_count: 1 }]); - expect(sqls).toEqual([ - 'SELECT "phone" AS "phone", COUNT(*) AS "account_count" FROM "crm_account" GROUP BY "phone"', - ]); + } as any)).rejects.toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'phone', param: 'dimensions' }); + expect(sqls).toEqual([]); }); it('admits the engine-assigned columns the data path admits', async () => { diff --git a/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts b/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts index 29a1a233fc4..9b1fb6b5c12 100644 --- a/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts @@ -23,6 +23,13 @@ * undeclared plain dimension (`bogus`, #28201) keeps its own refusal. A * `runtimeFilter` member through an unbacked path is refused by the same * gate since #28557 (pinned in that file too). + * + * [ADR-0149 D1] On `queryDataset` a SELECTED dimension is one of the dataset's + * declared names, so every dotted spelling above, backed or not, and the plain + * `bogus` are refused by the closed-member rule on every face, ahead of the + * relationship-path gate, with one message. That gate stays pinned through + * what still reaches it: a `runtimeFilter` member (filter keys are fields, not + * members) and the cube faces further down this file. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -93,11 +100,6 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do face === 'preview' ? { previewDrafts: true } : undefined, ); - const groupsOf = (rows: unknown, dimension: string) => - (rows as Array>) - .map((r) => ({ key: r[dimension], total: Number(r.total) })) - .sort((a, b) => String(a.key).localeCompare(String(b.key))); - beforeAll(async () => { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); engine = new ObjectQL({ logger: quiet } as never); @@ -148,10 +150,13 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do try { await engine?.destroy(); } catch { /* noop */ } }); - for (const [label, dataset, member, path] of [ - ["'os28258_deal.bogus' (the object's own name as a hop)", UNBACKED, 'os28258_deal.bogus', 'os28258_deal'], - ["'account.name' (a real lookup the dataset does not include)", UNBACKED, 'account.name', 'account'], - ["'account.owner.name' (one hop past the included 'account')", BACKED, 'account.owner.name', 'account.owner'], + for (const [label, dataset, member] of [ + ["'os28258_deal.bogus' (the object's own name as a hop)", UNBACKED, 'os28258_deal.bogus'], + ["'account.name' (a real lookup the dataset does not include)", UNBACKED, 'account.name'], + ["'account.owner.name' (one hop past the included 'account')", BACKED, 'account.owner.name'], + ["'account.name' (backed by 'include', but not a declared dimension)", BACKED, 'account.name'], + ["'os28258_deal.region' (a spelling of the declared 'region')", UNBACKED, 'os28258_deal.region'], + ["'bogus' (a plain name the dataset does not declare)", UNBACKED, 'bogus'], ] as const) { it(`refuses ${label} INVALID_FIELD / 400 with one message on every face`, async () => { const refusals = await Promise.all( @@ -163,7 +168,7 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do expect(err.param).toBe('dimensions'); expect(err.member).toBe(member); expect(err.cube).toBe(dataset.name); - expect(err.message).toContain(`Dimension '${member}' on cube '${dataset.name}' traverses relationship path '${path}'`); + expect(err.message).toContain(`The dataset "${dataset.name}" does not declare the dimension "${member}".`); } const [native, objectql, preview] = refusals; expect(objectql.message).toBe(native.message); @@ -184,42 +189,6 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do expect(refusals[2].message).toBe(refusals[0].message); }); - it("CONTROL: a backed 'account.name' serves on both live strategies, the same groups", async () => { - const expected = [{ key: 'Acme', total: 130 }, { key: 'Globex', total: 50 }]; - for (const face of ['native', 'objectql'] as const) { - const result = await ask(face, BACKED, { dimensions: ['account.name'], measures: ['total'] }); - expect(groupsOf(result.rows, 'account.name'), face).toEqual(expected); - } - // [#28555] The preview joins nothing, so it refuses the backed path with - // its own refusal rather than this gate's (which judges only unbacked ones). - const err = await refusalOf(ask('preview', BACKED, { dimensions: ['account.name'], measures: ['total'] })); - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); - expect(err.message).not.toContain('which the dataset does not declare'); - }); - - it("CONTROL: '.region', which resolves to the declared 'region', still serves on every face", async () => { - const expected = [{ key: 'amer', total: 150 }, { key: 'emea', total: 30 }]; - for (const face of ['native', 'objectql'] as const) { - const result = await ask(face, UNBACKED, { dimensions: ['os28258_deal.region'], measures: ['total'] }); - expect(groupsOf(result.rows, 'os28258_deal.region'), face).toEqual(expected); - } - const preview = await ask('preview', UNBACKED, { dimensions: ['os28258_deal.region'], measures: ['total'] }); - expect(Array.isArray(preview.rows)).toBe(true); - }); - - it("CONTROL: an undeclared plain 'bogus' (#28201) keeps its own refusal on every face", async () => { - const refusals = await Promise.all( - FACES.map((face) => refusalOf(ask(face, UNBACKED, { dimensions: ['bogus'], measures: ['total'] }))), - ); - for (const err of refusals) { - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); - expect(err.field).toBe('bogus'); - expect(err.message).toContain("Dimension 'bogus' on cube 'os28258_deals' groups by field 'bogus'"); - } - }); - it("CONTROL: a measure mistake beside an unbacked dotted dimension is answered about the measure on every face", async () => { const refusals = await Promise.all( FACES.map((face) => refusalOf(ask(face, UNBACKED, { dimensions: ['account.name'], measures: ['nope'] }))), diff --git a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts index 7937f91563c..1e58ff070cb 100644 --- a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts @@ -28,6 +28,15 @@ * every face with one message, also under an `$or`. Before: `DATASET_INVALID` * (native), the cross-object filter refusal (ObjectQL), `[]` or the other * arm's rows (preview). + * + * [ADR-0149 D1] A SELECTION member is one of the dataset's declared names: a + * dotted spelling the dataset does not declare (`account.name`, + * `account.bogus`, `account.founded_at`, `OBJECT.region`, `CUBE.region`, the + * bare lookup column `account`) is refused by the closed-member rule on every + * face, ahead of the path gates above, with one message. The path gates stay + * pinned through what still reaches them: a declared member over a related + * field, a declared measure over a missing column, and a `runtimeFilter` + * member (filter keys are fields, not members). */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -83,7 +92,6 @@ const BOGUS_MEASURE = DatasetSchema.parse({ type Face = 'native' | 'objectql' | 'preview'; const FACES: readonly Face[] = ['native', 'objectql', 'preview']; -const LIVE = ['native', 'objectql'] as const; const quiet = { debug() {}, info() {}, warn() {}, error() {}, trace() {}, fatal() {}, child() { return quiet; } }; @@ -145,6 +153,13 @@ describe('[#28555–#28558] members read through a relationship path, on the nat return refusals[0]; }; + /** The closed-member refusal, alike on every face. */ + const undeclaredAlike = async (dataset: typeof UNBACKED, selection: Selection, param: string, member: string) => { + const err = await refusedAlike(dataset, selection, param, member); + expect(err.message).toContain(`The dataset "${dataset.name}" does not declare the dimension "${member}".`); + return err; + }; + beforeAll(async () => { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); engine = new ObjectQL({ logger: quiet } as never); @@ -196,27 +211,14 @@ describe('[#28555–#28558] members read through a relationship path, on the nat }); describe('#28555 — the draft preview joins nothing', () => { - it("refuses a backed 'account.name' that both live strategies serve, where it served one null group", async () => { - for (const face of LIVE) { - expect(await rowsOf(face, BACKED, { dimensions: ['account.name'], measures: ['total'] }, 'account.name'), face) - .toEqual([{ key: 'Acme', total: 130 }, { key: 'Globex', total: 50 }]); - } - const err = await refusalOf(ask('preview', BACKED, { dimensions: ['account.name'], measures: ['total'] })); - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); - expect(err.param).toBe('dimensions'); - expect(err.member).toBe('account.name'); - expect(err.cube).toBe(BACKED.name); - expect(err.message).toContain( - `Dimension 'account.name' on cube '${BACKED.name}' reads 'account.name' through relationship path 'account'. ${PREVIEW_JOINS_NOTHING}`, - ); + it("refuses a backed but undeclared 'account.name' on every face, live strategies included", async () => { + await undeclaredAlike(BACKED, { dimensions: ['account.name'], measures: ['total'] }, 'dimensions', 'account.name'); }); for (const [label, dataset, selection, param, member] of [ ["a declared dimension over 'account.name'", DECLARED, { dimensions: ['account_name'], measures: ['total'] }, 'dimensions', 'account_name'], ["a declared measure over 'account.score'", DECLARED, { dimensions: ['region'], measures: ['score_max'] }, 'measures', 'score_max'], ["a backed 'runtimeFilter' member", BACKED, { dimensions: ['region'], measures: ['total'], runtimeFilter: { 'account.name': 'Acme' } }, 'where', 'account.name'], - ['a backed windowed time dimension', BACKED, { measures: ['total'], timeDimensions: [{ dimension: 'account.founded_at', dateRange: ['2026-01-01', '2026-01-31'] }] }, 'timeDimensions', 'account.founded_at'], ] satisfies Array<[string, typeof UNBACKED, Selection, string, string]>) { it(`refuses ${label} with the same refusal`, async () => { const err = await refusalOf(ask('preview', dataset, selection)); @@ -228,33 +230,37 @@ describe('[#28555–#28558] members read through a relationship path, on the nat }); } - it('CONTROL: the native strategy serves the backed runtimeFilter member and the windowed time dimension', async () => { + it('refuses an undeclared backed windowed time dimension on every face', async () => { + await undeclaredAlike( + BACKED, + { measures: ['total'], timeDimensions: [{ dimension: 'account.founded_at', dateRange: ['2026-01-01', '2026-01-31'] }] }, + 'timeDimensions', + 'account.founded_at', + ); + }); + + it('CONTROL: the native strategy serves the backed runtimeFilter member', async () => { expect(await rowsOf('native', BACKED, { dimensions: ['region'], measures: ['total'], runtimeFilter: { 'account.name': 'Acme' } }, 'region')) .toEqual([{ key: 'amer', total: 100 }, { key: 'emea', total: 30 }]); - expect(await rowsOf('native', BACKED, { measures: ['total'], timeDimensions: [{ dimension: 'account.founded_at', dateRange: ['2026-01-01', '2026-01-31'] }] }, 'none')) - .toEqual([{ key: undefined, total: 130 }]); }); for (const member of [`${OBJECT}.region`, `${UNBACKED.name}.region`]) { - it(`answers '${member}', which resolves to the declared 'region', with the live faces' groups`, async () => { - for (const face of FACES) { - expect(await rowsOf(face, UNBACKED, { dimensions: [member], measures: ['total'] }, member), face) - .toEqual([{ key: 'amer', total: 150 }, { key: 'emea', total: 30 }]); - } + it(`refuses '${member}', a spelling the dataset does not declare, on every face`, async () => { + await undeclaredAlike(UNBACKED, { dimensions: [member], measures: ['total'] }, 'dimensions', member); }); } - it('CONTROL: the base lookup column itself groups alike on every face', async () => { - for (const face of FACES) { - expect(await rowsOf(face, BACKED, { dimensions: ['account'], measures: ['total'] }, 'account'), face) - .toEqual([{ key: 'a1', total: 130 }, { key: 'a2', total: 50 }]); - } + it('refuses the undeclared base lookup column on every face', async () => { + await undeclaredAlike(BACKED, { dimensions: ['account'], measures: ['total'] }, 'dimensions', 'account'); }); }); describe('#28558 — a declared path to a column the related object lacks', () => { + it('as an undeclared selection dimension, is refused on every face by the closed-member rule', async () => { + await undeclaredAlike(BACKED, { dimensions: ['account.bogus'], measures: ['total'] }, 'dimensions', 'account.bogus'); + }); + for (const [label, selection, param, member] of [ - ['as a dimension', { dimensions: ['account.bogus'], measures: ['total'] }, 'dimensions', 'account.bogus'], ['as a runtimeFilter member', { dimensions: ['region'], measures: ['total'], runtimeFilter: { 'account.bogus': 'x' } }, 'where', 'account.bogus'], ] satisfies Array<[string, Selection, string, string]>) { it(`is refused before SQL on every face ${label}, with one message`, async () => { @@ -284,10 +290,8 @@ describe('[#28555–#28558] members read through a relationship path, on the nat ['windowed', { dimension: 'account.founded_at', dateRange: ['2026-01-01', '2026-01-31'] }], ] as const) { it(`is refused on every face when ${label}, with one message`, async () => { - const err = await refusedAlike(UNBACKED, { measures: ['total'], timeDimensions: [{ ...entry }] }, 'timeDimensions', 'account.founded_at'); - expect(err.message).toContain( - `Time dimension 'account.founded_at' on cube '${UNBACKED.name}' traverses relationship path 'account', which the dataset does not declare`, - ); + // [ADR-0149 D1] The closed-member rule answers it, ahead of the path gate. + await undeclaredAlike(UNBACKED, { measures: ['total'], timeDimensions: [{ ...entry }] }, 'timeDimensions', 'account.founded_at'); }); } }); diff --git a/packages/services/service-analytics/src/__tests__/preview-filter-field-json-dimension-parity.test.ts b/packages/services/service-analytics/src/__tests__/preview-filter-field-json-dimension-parity.test.ts index 60730066620..ac62f90417e 100644 --- a/packages/services/service-analytics/src/__tests__/preview-filter-field-json-dimension-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-filter-field-json-dimension-parity.test.ts @@ -20,6 +20,10 @@ * - The preview asks both gates in the live order: the JSON door after the * dimension-field gate and before the field-type door, the `where` gate last * among `ensureCube`'s and before the column-reference gate. + * - [ADR-0149 D1] A selection member the dataset does not declare (the raw + * `payload`, `region_sum`, `amount + 1`) is refused by the closed-member rule + * ahead of all of these, on every face alike; the JSON door is pinned + * through the declared `payload_dim`. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -163,20 +167,34 @@ describe('[#28257] an unknown filter field and a json dimension on the native, O }); } - for (const dimension of ['payload', 'payload_dim'] as const) { - it(`refuses the json dimension '${dimension}' INVALID_FIELD / 400 param dimensions, with one message on every face`, async () => { - const err = await refusedAlike({ dimensions: [dimension], measures: ['total'] }, 'dimensions', 'payload'); - expect(err.message).toContain('declares as json'); - }); - } + it("refuses the json dimension 'payload_dim' INVALID_FIELD / 400 param dimensions, with one message on every face", async () => { + const err = await refusedAlike({ dimensions: ['payload_dim'], measures: ['total'] }, 'dimensions', 'payload'); + expect(err.message).toContain('declares as json'); + }); + + it("CONTROL: the json field 'payload' named raw is not a declared dimension: the closed-member refusal, alike on every face", async () => { + const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, { dimensions: ['payload'], measures: ['total'] })))); + for (const err of refusals) { + expect(err).toMatchObject({ code: 'INVALID_FIELD', status: 400, param: 'dimensions', member: 'payload' }); + expect(err.message).toContain('The dataset "os28257_deals" does not declare the dimension "payload".'); + } + expect(refusals[2].message).toBe(refusals[0].message); + }); - for (const [label, selection, param, field] of [ - ['a json dimension beside a bogus filter: the json door', { dimensions: ['payload'], measures: ['total'], runtimeFilter: { ghost: 1 } }, 'dimensions', 'payload'], - ["a json dimension beside 'region_sum': the json door", { dimensions: ['payload'], measures: ['region_sum'] }, 'dimensions', 'payload'], - ["'amount + 1' beside a bogus filter: the where gate", { dimensions: ['region'], measures: ['amount + 1'], runtimeFilter: { ghost: 1 } }, 'where', 'ghost'], + it('two mistakes, a json dimension beside a bogus filter: the json door first, on every face', async () => { + await refusedAlike({ dimensions: ['payload_dim'], measures: ['total'], runtimeFilter: { ghost: 1 } }, 'dimensions', 'payload'); + }); + + for (const [label, selection, member] of [ + ["a json dimension beside 'region_sum'", { dimensions: ['payload_dim'], measures: ['region_sum'] }, 'region_sum'], + ["'amount + 1' beside a bogus filter", { dimensions: ['region'], measures: ['amount + 1'], runtimeFilter: { ghost: 1 } }, 'amount + 1'], ] as const) { - it(`two mistakes, ${label} first, on every face`, async () => { - await refusedAlike(selection, param, field); + it(`two mistakes, ${label}: the undeclared measure first, on every face`, async () => { + const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, selection)))); + for (const err of refusals) { + expect(err).toMatchObject({ code: 'INVALID_FIELD', status: 400, param: 'measures', member }); + } + expect(refusals[2].message).toBe(refusals[0].message); }); } }); diff --git a/packages/services/service-analytics/src/__tests__/preview-time-filter-fk-parity.test.ts b/packages/services/service-analytics/src/__tests__/preview-time-filter-fk-parity.test.ts index e82c5bcd27a..7bfa884cc09 100644 --- a/packages/services/service-analytics/src/__tests__/preview-time-filter-fk-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-time-filter-fk-parity.test.ts @@ -42,6 +42,15 @@ * (drop the raw dimension or its bucket's granularity; ask one granularity). * Before, every face prescribed the engine's "own 'alias'", which no dataset * selection can spell. A direct `engine.aggregate` caller keeps that one. + * + * [ADR-0149 D1] A selection member is one of the dataset's declared names, so + * the second key over one column is spelled here by a declared dimension + * (`closed_on` over `closed_at`, as `zone` is over `region`), and the backed + * relationship members by declared dimensions over them (`account_id`, + * `account_name`, `account_ref`). The undeclared spellings these pins used + * before (`OBJECT.closed_at`, `account.id`, `account.name`, the bare + * `account`) are refused by the closed-member rule on every face, pinned once + * below; `runtimeFilter` keys are fields, not members, and keep their spellings. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -72,13 +81,24 @@ const shape = { { name: 'region', field: 'region', type: 'string' }, { name: 'closed_at', field: 'closed_at', type: 'date' }, { name: 'zone', field: 'region', type: 'string' }, + { name: 'closed_on', field: 'closed_at', type: 'date' }, ], measures: [{ name: 'total', aggregate: 'sum', field: 'amount' }], }; /** Declares no relationship. */ const UNBACKED = DatasetSchema.parse({ name: 'os28690_deals', ...shape }); /** Declares `account`. */ -const BACKED = DatasetSchema.parse({ name: 'os28690_deals_by_account', include: ['account'], ...shape }); +const BACKED = DatasetSchema.parse({ + name: 'os28690_deals_by_account', + include: ['account'], + ...shape, + dimensions: [ + ...shape.dimensions, + { name: 'account_id', field: 'account.id', type: 'string' }, + { name: 'account_name', field: 'account.name', type: 'string' }, + { name: 'account_ref', field: 'account', type: 'string' }, + ], +}); type Face = 'native' | 'objectql' | 'preview'; const FACES: readonly Face[] = ['native', 'objectql', 'preview']; @@ -198,12 +218,23 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member ); }); - it('keys an OBJECT-qualified time dimension by its spelling, as the live faces do', async () => { - const member = `${OBJECT}.closed_at`; - await answeredAlike(FACES, UNBACKED, { measures: ['total'], timeDimensions: [{ dimension: member, granularity: 'month' }] }, { - rows: [{ [member]: '2026-03', total: 100 }, { [member]: '2026-04', total: 80 }], - fields: [`${member}:time`, 'total:number'], - }); + it.each([ + ['an OBJECT-qualified time dimension', { measures: ['total'], timeDimensions: [{ dimension: `${OBJECT}.closed_at`, granularity: 'month' }] }, 'timeDimensions', `${OBJECT}.closed_at`], + ["a backed 'account.id'", { dimensions: ['account.id'], measures: ['total'] }, 'dimensions', 'account.id'], + ["a backed 'account.name'", { dimensions: ['account.name'], measures: ['total'] }, 'dimensions', 'account.name'], + ["the bare FK column 'account'", { dimensions: ['account'], measures: ['total'] }, 'dimensions', 'account'], + ])('[ADR-0149 D1] refuses %s, which the dataset does not declare, alike on every face', async (_label, selection, param, member) => { + const refusals: Array> = []; + for (const face of FACES) { + const err = (await ask(face, BACKED, selection as Selection).then( + () => { throw new Error(`${face}: expected a refusal, but the query resolved`); }, + (e: unknown) => e, + )) as Error & Record; + expect(err, face).toMatchObject({ code: 'INVALID_FIELD', status: 400, param, member, cube: BACKED.name }); + expect(err.message, face).toContain(`The dataset "${BACKED.name}" does not declare the dimension "${member}".`); + refusals.push({ message: err.message }); + } + for (const r of refusals) expect(r).toEqual(refusals[0]); }); it('buckets a windowed year, where the preview answered the total with no key', async () => { @@ -289,41 +320,43 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member }); describe('#28692 — the ObjectQL strategy groups a backed FK path once', () => { - it("serves a backed 'account.id' with the native strategy's groups, where it answered INVALID_QUERY", async () => { - await answeredAlike(LIVE, BACKED, { dimensions: ['account.id'], measures: ['total'] }, { - rows: [{ 'account.id': 'a1', total: 130 }, { 'account.id': 'a2', total: 50 }], - fields: ['account.id:string', 'total:number'], + it("serves a backed 'account_id' (over 'account.id') with the native strategy's groups, where it answered INVALID_QUERY", async () => { + await answeredAlike(LIVE, BACKED, { dimensions: ['account_id'], measures: ['total'] }, { + rows: [{ account_id: 'a1', total: 130 }, { account_id: 'a2', total: 50 }], + fields: ['account_id:string', 'total:number'], }); }); - it("serves 'account.id' beside 'account.name', where it answered INVALID_QUERY", async () => { - await answeredAlike(LIVE, BACKED, { dimensions: ['account.id', 'account.name'], measures: ['total'] }, { + it("serves 'account_id' beside 'account_name', where it answered INVALID_QUERY", async () => { + await answeredAlike(LIVE, BACKED, { dimensions: ['account_id', 'account_name'], measures: ['total'] }, { rows: [ - { 'account.id': 'a1', 'account.name': 'Acme', total: 130 }, - { 'account.id': 'a2', 'account.name': 'Globex', total: 50 }, + { account_id: 'a1', account_name: 'Acme', total: 130 }, + { account_id: 'a2', account_name: 'Globex', total: 50 }, ], - fields: ['account.id:string', 'account.name:string', 'total:number'], + fields: ['account_id:string', 'account_name:string', 'total:number'], }); }); it.each([ - ['after', ['account.name', 'account']], - ['before', ['account', 'account.name']], - ])("serves the FK column 'account' %s 'account.name'", async (_label, dimensions) => { + ['after', ['account_name', 'account_ref']], + ['before', ['account_ref', 'account_name']], + ])("serves the FK column 'account_ref' %s 'account_name'", async (_label, dimensions) => { await answeredAlike(LIVE, BACKED, { dimensions, measures: ['total'] }, { + // A declared dimension over the lookup column answers the related + // record's display name (ADR-0021 server-side display values). rows: [ - { account: 'a1', 'account.name': 'Acme', total: 130 }, - { account: 'a2', 'account.name': 'Globex', total: 50 }, + { account_ref: 'Acme', account_name: 'Acme', total: 130 }, + { account_ref: 'Globex', account_name: 'Globex', total: 50 }, ], fields: [...dimensions.map((d) => `${d}:string`), 'total:number'], }); }); it('leaves the draft preview refusing a backed relationship path (#28555)', async () => { - await expect(ask('preview', BACKED, { dimensions: ['account.id'], measures: ['total'] })).rejects.toMatchObject({ + await expect(ask('preview', BACKED, { dimensions: ['account_id'], measures: ['total'] })).rejects.toMatchObject({ code: 'INVALID_FIELD', status: 400, - member: 'account.id', + member: 'account_id', }); }); }); @@ -358,7 +391,7 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member }); it("still refuses a column raw beside its bucket (two values under one name)", async () => { - // `closed_at` raw and `OBJECT.closed_at` bucketed by month are different + // `closed_at` raw and `closed_on` bucketed by month are different // keys over one column: nothing is merged, and the duplicate-column // refusal (the dataset's since #28798) stands on both live faces. for (const face of LIVE) { @@ -366,21 +399,21 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member ask(face, UNBACKED, { dimensions: ['closed_at'], measures: ['total'], - timeDimensions: [{ dimension: `${OBJECT}.closed_at`, granularity: 'month' }], + timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }], }), face, ).rejects.toMatchObject({ code: 'INVALID_QUERY', status: 400 }); } }); - it("serves them beside a cross-object 'account.name' dimension", async () => { - await answeredAlike(LIVE, BACKED, { dimensions: ['region', 'zone', 'account.name'], measures: ['total'] }, { + it("serves them beside a cross-object 'account_name' dimension", async () => { + await answeredAlike(LIVE, BACKED, { dimensions: ['region', 'zone', 'account_name'], measures: ['total'] }, { rows: [ - { region: 'amer', zone: 'amer', 'account.name': 'Acme', total: 100 }, - { region: 'amer', zone: 'amer', 'account.name': 'Globex', total: 50 }, - { region: 'emea', zone: 'emea', 'account.name': 'Acme', total: 30 }, + { region: 'amer', zone: 'amer', account_name: 'Acme', total: 100 }, + { region: 'amer', zone: 'amer', account_name: 'Globex', total: 50 }, + { region: 'emea', zone: 'emea', account_name: 'Acme', total: 30 }, ], - fields: ['region:string', 'zone:string', 'account.name:string', 'total:number'], + fields: ['region:string', 'zone:string', 'account_name:string', 'total:number'], }); }); }); @@ -427,12 +460,12 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member it('refuses a column raw beside its own month bucket, where the preview served both', async () => { await refusedAsLive( - { dimensions: ['closed_at'], measures: ['total'], timeDimensions: [{ dimension: `${OBJECT}.closed_at`, granularity: 'month' }] }, + { dimensions: ['closed_at'], measures: ['total'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }] }, 'groupBy.1.field', // Spelled out once in full; the cases below build the same sentence. "aggregate('os28690_deal'): groupBy.1.field names the column 'closed_at', which groupBy.0 already names — " + 'one row cannot carry two values under one column. The query was NOT run. The selection asks for ' - + "'closed_at' both raw and bucketed (`dimensions` 'closed_at'; `timeDimensions` 'os28690_deal.closed_at' " + + "'closed_at' both raw and bucketed (`dimensions` 'closed_at'; `timeDimensions` 'closed_on' " + 'by month). Drop the raw dimension from `dimensions`, or drop the granularity from the `timeDimensions` ' + 'entry. A repeated column name kept only the last value written under it: a count overwritten by a sum, ' + 'or the group keys replaced by the numbers, while the answer looked served.', @@ -441,19 +474,19 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member it('refuses it after another dimension, naming the later position', async () => { await refusedAsLive( - { dimensions: ['region', 'closed_at'], measures: ['total'], timeDimensions: [{ dimension: `${OBJECT}.closed_at`, granularity: 'month' }] }, + { dimensions: ['region', 'closed_at'], measures: ['total'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }] }, 'groupBy.2.field', - askedTwice('groupBy.2.field', 'groupBy.1', 'closed_at', rawAndBucketed("'closed_at'", `'${OBJECT}.closed_at' by month`)), + askedTwice('groupBy.2.field', 'groupBy.1', 'closed_at', rawAndBucketed("'closed_at'", "'closed_on' by month")), ); }); it('[#28798] names only the raw member when the bucketed dimension is listed too', async () => { // `closed_at` is bucketed by its own entry, so its key is the bucket; - // `OBJECT.closed_at` reads the same column raw. + // `closed_on` reads the same column raw. await refusedAsLive( - { dimensions: ['closed_at', `${OBJECT}.closed_at`], measures: ['total'], timeDimensions: [{ dimension: 'closed_at', granularity: 'month' }] }, + { dimensions: ['closed_at', 'closed_on'], measures: ['total'], timeDimensions: [{ dimension: 'closed_at', granularity: 'month' }] }, 'groupBy.1', - askedTwice('groupBy.1', 'groupBy.0.field', 'closed_at', rawAndBucketed(`'${OBJECT}.closed_at'`, "'closed_at' by month")), + askedTwice('groupBy.1', 'groupBy.0.field', 'closed_at', rawAndBucketed("'closed_on'", "'closed_at' by month")), ); }); @@ -463,11 +496,11 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member measures: ['total'], timeDimensions: [ { dimension: 'closed_at', granularity: 'month' }, - { dimension: `${OBJECT}.closed_at`, granularity: 'year' }, + { dimension: 'closed_on', granularity: 'year' }, ], }, 'groupBy.1.field', - askedTwice('groupBy.1.field', 'groupBy.0.field', 'closed_at', twoGranularities(`'closed_at' by month, '${OBJECT}.closed_at' by year`)), + askedTwice('groupBy.1.field', 'groupBy.0.field', 'closed_at', twoGranularities("'closed_at' by month, 'closed_on' by year")), ); }); @@ -482,17 +515,17 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member ); }); - it('[#28799] refuses the same pair spelled OBJECT.closed_at', async () => { + it('[#28799] refuses the same pair spelled by the second declared dimension over the column', async () => { await refusedAsLive( { measures: ['total'], timeDimensions: [ - { dimension: `${OBJECT}.closed_at`, granularity: 'month' }, - { dimension: `${OBJECT}.closed_at`, granularity: 'year' }, + { dimension: 'closed_on', granularity: 'month' }, + { dimension: 'closed_on', granularity: 'year' }, ], }, 'groupBy.1.field', - askedTwice('groupBy.1.field', 'groupBy.0.field', 'closed_at', twoGranularities(`'${OBJECT}.closed_at' by month, '${OBJECT}.closed_at' by year`)), + askedTwice('groupBy.1.field', 'groupBy.0.field', 'closed_at', twoGranularities("'closed_on' by month, 'closed_on' by year")), ); }); @@ -522,11 +555,11 @@ describe('[#28690–#28692] time-dimension buckets, column-spelled filter member ); }); - it("[#28799] refuses the pair beside a cross-object 'account.name' dimension on both live faces", async () => { + it("[#28799] refuses the pair beside a cross-object 'account_name' dimension on both live faces", async () => { // `executeCrossObject` calls the door on its own keys (the FK column first). await refusedAsLive( { - dimensions: ['account.name'], + dimensions: ['account_name'], measures: ['total'], timeDimensions: [{ dimension: 'closed_at', granularity: 'month' }, { dimension: 'closed_at', granularity: 'year' }], }, diff --git a/packages/services/service-analytics/src/__tests__/preview-undeclared-dimension-parity.test.ts b/packages/services/service-analytics/src/__tests__/preview-undeclared-dimension-parity.test.ts index 6b1a372b3e9..dba890c99e6 100644 --- a/packages/services/service-analytics/src/__tests__/preview-undeclared-dimension-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-undeclared-dimension-parity.test.ts @@ -6,18 +6,18 @@ * * ## What these pins hold * - * - A dimension whose field the object does not have (`bogus`) is refused - * `INVALID_FIELD` / 400 on every face, with the same message naming the - * member and the valid dimensions, alone or beside a declared dimension. - * Before, the preview grouped every row under one `null` key and served the - * total. - * - CONTROL: a declared dimension and an undeclared one naming a real field - * (`amount`) serve the same groups on every face. - * - The preview asks its gates in the live order, so a query with two mistakes - * is answered about the same one first on every face: a measure field the - * object does not have before a bogus dimension, a bogus dimension before - * the field-type door, and the field-type door before the column-reference - * gate. + * The dataset is a closed surface (ADR-0021, ADR-0149 D1): a selection + * dimension the dataset does not declare is refused by the closed-member rule + * (`dataset-declared-members.ts`) before any face reads anything — whether its + * field is missing (`bogus`) or real (`amount`), alone or beside a declared + * dimension — `INVALID_FIELD` / 400 with one message on every face, naming + * the member, the declared members and the remedy. Before, the faces judged + * the dimension's field, and a real one grouped. + * + * - CONTROL: a declared dimension serves the same groups on every face. + * - A query with two undeclared members names both and is answered about the + * first in the closed-member rule's order (measures, then dimensions, then + * time dimensions), the same on every face. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -118,58 +118,49 @@ describe('[#28201] an undeclared dimension on the native, ObjectQL and draft-pre try { await engine?.destroy(); } catch { /* noop */ } }); - it("refuses 'bogus' INVALID_FIELD / 400 with one message on every face", async () => { - const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, { dimensions: ['bogus'], measures: ['total'] })))); - for (const err of refusals) { - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); - expect(err.param).toBe('dimensions'); - expect(err.field).toBe('bogus'); - expect(err.dimension).toBe('bogus'); - expect(err.message).toContain("Dimension 'bogus' on cube 'os28201_deals' groups by field 'bogus'"); - expect(err.message).toContain('Valid dimensions: region.'); - } - const [native, objectql, preview] = refusals; - expect(preview.message).toBe(native.message); - expect(objectql.message).toBe(native.message); - }); - - it("refuses 'bogus' beside a declared dimension with one message on every face", async () => { - const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, { dimensions: ['region', 'bogus'], measures: ['deals'] })))); - for (const err of refusals) { - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); - expect(err.field).toBe('bogus'); - } - expect(refusals[2].message).toBe(refusals[0].message); - }); - - for (const [dimension, expected] of [ - ['region', [{ key: 'amer', total: 150 }, { key: 'emea', total: 30 }]], - ['amount', [{ key: 30, total: 30 }, { key: 50, total: 50 }, { key: 100, total: 100 }]], + for (const [label, selection, member] of [ + ["'bogus'", { dimensions: ['bogus'], measures: ['total'] }, 'bogus'], + ["'bogus' beside a declared dimension", { dimensions: ['region', 'bogus'], measures: ['deals'] }, 'bogus'], + ["'amount', a real field the dataset does not declare", { dimensions: ['amount'], measures: ['total'] }, 'amount'], ] as const) { - it(`CONTROL: '${dimension}' serves the same groups on every face`, async () => { - for (const face of FACES) { - const result = await ask(face, { dimensions: [dimension], measures: ['total'] }); - const groups = (result.rows as Array>) - .map((r) => ({ key: r[dimension], total: Number(r.total) })) - .sort((a, b) => String(a.key).localeCompare(String(b.key), undefined, { numeric: true })); - expect(groups, face).toEqual(expected); + it(`refuses ${label} INVALID_FIELD / 400 with one message on every face`, async () => { + const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, selection)))); + for (const err of refusals) { + expect(err.code, err.message).toBe('INVALID_FIELD'); + expect(err.status).toBe(400); + expect(err.param).toBe('dimensions'); + expect((err as { member?: string }).member).toBe(member); + expect(err.message).toContain(`The dataset "os28201_deals" does not declare the dimension "${member}".`); + expect(err.message).toContain('Dimensions you may use: region.'); } + const [native, objectql, preview] = refusals; + expect(preview.message).toBe(native.message); + expect(objectql.message).toBe(native.message); }); } - for (const [label, selection, param] of [ - ["'nope' beside 'bogus': the measure's missing field", { dimensions: ['bogus'], measures: ['nope'] }, 'measures'], - ["'region_sum' beside 'bogus': the dimension's missing field", { dimensions: ['bogus'], measures: ['region_sum'] }, 'dimensions'], - ["'amount + 1' beside 'region_sum': the field-type door", { dimensions: ['region'], measures: ['amount + 1', 'region_sum'] }, 'measures'], + it("CONTROL: 'region' serves the same groups on every face", async () => { + for (const face of FACES) { + const result = await ask(face, { dimensions: ['region'], measures: ['total'] }); + const groups = (result.rows as Array>) + .map((r) => ({ key: r.region, total: Number(r.total) })) + .sort((x, y) => String(x.key).localeCompare(String(y.key))); + expect(groups, face).toEqual([{ key: 'amer', total: 150 }, { key: 'emea', total: 30 }]); + } + }); + + for (const [label, selection, param, named] of [ + ["'nope' beside 'bogus': the measure", { dimensions: ['bogus'], measures: ['nope'] }, 'measures', 'measure "nope", dimension "bogus"'], + ["'region_sum' beside 'bogus': the measure", { dimensions: ['bogus'], measures: ['region_sum'] }, 'measures', 'measure "region_sum", dimension "bogus"'], + ["'amount + 1' beside 'region_sum': the first measure", { dimensions: ['region'], measures: ['amount + 1', 'region_sum'] }, 'measures', 'measure "amount + 1", measure "region_sum"'], ] as const) { - it(`two mistakes, ${label} first, on every face`, async () => { + it(`two mistakes, ${label} first, both named, on every face`, async () => { const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, selection)))); for (const err of refusals) { expect(err.code, err.message).toBe('INVALID_FIELD'); expect(err.status).toBe(400); expect(err.param).toBe(param); + expect(err.message).toContain(`does not declare the ${named}.`); } expect(refusals[2].message).toBe(refusals[0].message); }); diff --git a/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts b/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts index a97f7346aa2..f61481648c3 100644 --- a/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts @@ -6,28 +6,21 @@ * * ## What these pins hold * - * The live faces mint an undeclared measure (`mintableMeasureKey` + - * `inferMeasure`: `amount_sum` is `SUM(amount)`, a bare `amount` is - * `SUM(amount)`) and judge it before a strategy reads anything. The draft - * preview now mints and judges it the same way: + * The dataset is a closed surface (ADR-0021, ADR-0149 D1): a selection + * measure the dataset does not declare is refused by the closed-member rule + * (`dataset-declared-members.ts`) before a strategy, the preview evaluator or + * any gate behind them reads anything, so every face answers it the same way: + * `INVALID_FIELD` / 400 naming the member, the declared measures and the + * remedy. That covers every spelling the faces used to mint and then judge — + * a field the object does not have (`nope`, `ghost_avg`), a suffix or bare + * field over a real one (`amount_sum`, `amount`), a minted aggregate the + * field-type table refuses (`region_sum`), a spelling that is not a column + * reference (`amount + 1`), the ad-hoc `count`, and a minted `secret_sum` + * over a field the caller may not read. * - * - A spelling whose field the object does not have (`nope`, `ghost_avg`) is - * refused `INVALID_FIELD` / 400 on every face, with the same message naming - * the member and the valid measures. Before, the preview served a row count - * per group under the misspelled name. - * - A spelling over a real field (`amount_sum`, `amount`) serves the live value - * on every face. Before, the preview served the row count. - * - A minted aggregate the field-type table refuses (`region_sum` over text) - * and a spelling that is not a column reference (`amount + 1`) get the live - * faces' refusals on the preview too, rather than `0` or a sum of nothing. - * - CONTROL: a declared measure and the undeclared `count` serve the same - * values on every face. + * - CONTROL: a declared measure serves the same values on every face. * - The evaluator refuses a measure the cube it is handed does not carry, * instead of reading it as `count(*)`. - * - A minted measure is judged by the field it aggregates: the field-level read - * gate refuses `secret_sum` on the preview, as on a live strategy, when the - * caller may not read `secret`. Without that, minting on the preview would - * sum a field the caller may not read. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -135,17 +128,16 @@ describe('[#28172] an undeclared measure on the native, ObjectQL and draft-previ try { await engine?.destroy(); } catch { /* noop */ } }); - for (const [measure, field] of [['nope', 'nope'], ['ghost_avg', 'ghost']] as const) { - it(`refuses '${measure}' INVALID_FIELD / 400 with one message on every face`, async () => { + for (const measure of ['nope', 'ghost_avg', 'amount_sum', 'amount', 'region_sum', 'amount + 1', 'count'] as const) { + it(`refuses '${measure}', which the dataset does not declare, INVALID_FIELD / 400 with one message on every face`, async () => { const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, measure)))); for (const err of refusals) { expect(err.code, err.message).toBe('INVALID_FIELD'); expect(err.status).toBe(400); expect(err.param).toBe('measures'); - expect(err.field).toBe(field); - expect(err.measure).toBe(measure); - expect(err.message).toContain(`Measure '${measure}' on cube 'os28172_deals' aggregates field '${field}'`); - expect(err.message).toContain('Valid measures: total, deals.'); + expect(err.member).toBe(measure); + expect(err.message).toContain(`The dataset "os28172_deals" does not declare the measure "${measure}".`); + expect(err.message).toContain('Measures you may use: total, deals.'); } const [native, objectql, preview] = refusals; expect(preview.message).toBe(native.message); @@ -153,42 +145,13 @@ describe('[#28172] an undeclared measure on the native, ObjectQL and draft-previ }); } - for (const measure of ['amount_sum', 'amount'] as const) { - it(`serves '${measure}' as SUM(amount) on every face`, async () => { - for (const face of FACES) { - const result = await ask(face, measure); - expect(byRegion(result, measure), face).toEqual({ amer: 150, emea: 30 }); - } - }); - } - - it("refuses 'region_sum' over a text field INVALID_FIELD / 400 with one message on every face", async () => { - const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, 'region_sum')))); - for (const err of refusals) { - expect(err.code, err.message).toBe('INVALID_FIELD'); - expect(err.status).toBe(400); + it("CONTROL: 'total' serves the same values on every face", async () => { + for (const face of FACES) { + const result = await ask(face, 'total'); + expect(byRegion(result, 'total'), face).toEqual({ amer: 150, emea: 30 }); } - expect(refusals[2].message).toBe(refusals[0].message); }); - it("refuses 'amount + 1', which is not a column reference, PERMISSION_DENIED / 403 on every face", async () => { - const refusals = await Promise.all(FACES.map((face) => refusalOf(ask(face, 'amount + 1')))); - for (const err of refusals) { - expect(err.code, err.message).toBe('PERMISSION_DENIED'); - expect(err.status).toBe(403); - } - expect(refusals[2].message).toBe(refusals[0].message); - }); - - for (const [measure, expected] of [['total', { amer: 150, emea: 30 }], ['count', { amer: 2, emea: 1 }]] as const) { - it(`CONTROL: '${measure}' serves the same values on every face`, async () => { - for (const face of FACES) { - const result = await ask(face, measure); - expect(byRegion(result, measure), face).toEqual(expected); - } - }); - } - it('the evaluator refuses a measure the cube it is handed does not carry, instead of counting rows', () => { const cube = { name: 'c', @@ -213,7 +176,7 @@ describe('[#28172] an undeclared measure on the native, ObjectQL and draft-previ }); }); -describe('[#28172] a minted measure on the draft preview meets the field-level read gate', () => { +describe('[#28172] a measure over a field the caller may not read, undeclared, is refused before any gate reads it', () => { const CALLER = { userId: 'u_member', tenantId: 'org_a' } as ExecutionContext; const DEAL = 'os28172_secret_deal'; const dataset = DatasetSchema.parse({ @@ -233,7 +196,7 @@ describe('[#28172] a minted measure on the draft preview meets the field-level r executeAggregate: async () => [], } as never); - it("refuses 'secret_sum' PERMISSION_DENIED / 403 naming 'secret' on the preview and on the live strategy", async () => { + it("refuses 'secret_sum' INVALID_FIELD / 400 on the preview and on the live strategy, never minting it", async () => { for (const draft of [false, true]) { const err = await refusalOf( service(draft).queryDataset( @@ -243,9 +206,10 @@ describe('[#28172] a minted measure on the draft preview meets the field-level r draft ? { previewDrafts: true } : undefined, ), ); - expect(err.code, err.message).toBe('PERMISSION_DENIED'); - expect(err.status).toBe(403); - expect((err as Refusal & { fields?: string[] }).fields).toEqual(['secret']); + expect(err.code, err.message).toBe('INVALID_FIELD'); + expect(err.status).toBe(400); + expect(err.member).toBe('secret_sum'); + expect(err.message).toContain('The dataset "os28172_secret" does not declare the measure "secret_sum".'); } }); }); diff --git a/packages/services/service-analytics/src/__tests__/query-dataset-request-scope.test.ts b/packages/services/service-analytics/src/__tests__/query-dataset-request-scope.test.ts index c2d9d991de3..a2b62e64fe2 100644 --- a/packages/services/service-analytics/src/__tests__/query-dataset-request-scope.test.ts +++ b/packages/services/service-analytics/src/__tests__/query-dataset-request-scope.test.ts @@ -195,7 +195,7 @@ describe.each(STRATEGY_PATHS)('queryDataset leaves the shared registries alone expect(entry?.public).toBe(false); }); - it('a request under a fresh name leaves no entry — refused or admitted, augmented measures included', async () => { + it('a request under a fresh name leaves no entry — refused (by read admission or by the closed-member rule) or admitted', async () => { const h = makeService(capabilities); const names = h.svc.cubeRegistry.names(); const before = await observe(h); @@ -203,19 +203,18 @@ describe.each(STRATEGY_PATHS)('queryDataset leaves the shared registries alone await expect( h.svc.queryDataset(inline('fresh_walled', WALLED), { measures: ['inline_total'] }, CALLER_A), ).rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); - // `amount_sum` is not declared by the dataset: `ensureCube` augments the - // request's cube with a suffix-inferred measure, and that augmentation is - // the request's too. + // `amount_sum` is not declared by the dataset: the dataset door refuses it + // (ADR-0149 D1) before `ensureCube` could augment the request's cube with + // a suffix-inferred measure, and nothing reaches the driver. + const refusedFrom = h.calls.length; + await expect( + h.svc.queryDataset(inline('fresh_open', 'other_obj'), { measures: ['inline_total', 'amount_sum'] }, CALLER_A), + ).rejects.toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'amount_sum' }); + expect(h.calls.slice(refusedFrom)).toEqual([]); const from = h.calls.length; - await h.svc.queryDataset( - inline('fresh_open', 'other_obj'), - { measures: ['inline_total', 'amount_sum'] }, - CALLER_A, - ); + await h.svc.queryDataset(inline('fresh_open', 'other_obj'), { measures: ['inline_total'] }, CALLER_A); const driven = h.calls.slice(from); expect(driven.map((c) => c.object)).toEqual(['other_obj']); - // …and the augmented measure really reached the driver (`SUM(amount)`). - expect(JSON.stringify(driven[0].detail)).toContain('amount'); expect(h.svc.cubeRegistry.names()).toEqual(names); expect(await observe(h)).toEqual(before); diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts index 8debc3377ad..d8ee5372ecd 100644 --- a/packages/services/service-analytics/src/dataset-declared-members.ts +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -110,7 +110,7 @@ export function undeclaredMembersRefusal( + 'answers only the members its dataset declares, by their declared names. ' + `Measures you may use: ${listMemberNames(usableDeclaredMembers(dataset.measures, admitted?.measures))}. ` + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admitted?.dimensions))}. ` - + 'Select one of these, or declare the member on the dataset (its `measures` or `dimensions`) and select it by that name.', + + 'Use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.', { member: first.member, param: first.param, cube: dataset.name }, ); } From 484714eed4d2ce7dcb908360c70429d7f44e4403 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 23:23:45 +0000 Subject: [PATCH 04/16] chore(service-analytics): changeset for the dataset door closed-member refusal Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34005-dataset-door-declared-members.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/34005-dataset-door-declared-members.md diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md new file mode 100644 index 00000000000..2cf52473c0b --- /dev/null +++ b/.changeset/34005-dataset-door-declared-members.md @@ -0,0 +1,17 @@ +--- +'@objectstack/service-analytics': patch +--- + +fix(service-analytics)!: the dataset query door refuses measures and dimensions the dataset does not declare, as `query_dataset` does + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: none — `skills/**` teach dataset selections only by the dataset's own names (objectstack-ui: a report selects `rows` and `values` "from that dataset"), which is what the door now enforces; `content/docs/data-modeling/analytics.mdx` states the rule in this change. + + + +**BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. + +- A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` with `member`, `param` and `cube` (the dataset's name) before anything is read. This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. +- The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. +- Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. From d9106e8c037e66d1df0276670f50be420be811a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:14:58 +0000 Subject: [PATCH 05/16] test(rest): move the dataset-door pins the closed-member rule reaches first Four rest pins selected members their dataset never declared and so now meet the closed-member refusal before the gate they pin: - dimension-gate: the source-field gate is reached through a stale declared dimension; the raw-field leg is now its own closed-member pin, and the positive control groups a declared dimension over phone. - refusal-envelope: the include positive control reads account.region through a declared dimension. - unlisted-refusal-envelope: profit_sum is refused as undeclared; a stale declared measure keeps the aggregates-field assertion. - relationship-path-admission: the undeclared path member is refused 400 before any read; the declared-join reference stays 403. The REST body is { code, message }; docs and changeset no longer claim member, param and cube on the wire. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34005-dataset-door-declared-members.md | 2 +- content/docs/data-modeling/analytics.mdx | 4 +- .../analytics-dataset-dimension-gate.test.ts | 55 +++++++++++++++---- ...analytics-dataset-refusal-envelope.test.ts | 14 +++-- ...-dataset-unlisted-refusal-envelope.test.ts | 32 +++++++---- ...lytics-relationship-path-admission.test.ts | 18 ++++-- 6 files changed, 92 insertions(+), 33 deletions(-) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index 2cf52473c0b..f31859f1d7a 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -12,6 +12,6 @@ Skills-docs: none — `skills/**` teach dataset selections only by the dataset's **BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. -- A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` with `member`, `param` and `cube` (the dataset's name) before anything is read. This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. +- A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. - The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/content/docs/data-modeling/analytics.mdx b/content/docs/data-modeling/analytics.mdx index 0235acb8461..cbde749655a 100644 --- a/content/docs/data-modeling/analytics.mdx +++ b/content/docs/data-modeling/analytics.mdx @@ -275,8 +275,8 @@ is one of the dataset's `measures[].name`, and each `dimensions` entry and Anything else — the ad-hoc `count`, a raw field such as `amount`, a suffix spelling such as `amount_sum`, a `.revenue` spelling, a raw field named as a dimension — is refused with `400 INVALID_FIELD` before anything is read. -The refusal names the member (`member`, `param`, `cube`), lists the measures -and dimensions you may use, and the fix is to select one of them or declare the +The refusal's message names every undeclared member, lists the measures and +dimensions you may use, and the fix is to select one of them or declare the member on the dataset. An inline `dataset` is judged against its own `measures` and `dimensions`. The cube query (`POST {basePath}/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/packages/rest/src/analytics-dataset-dimension-gate.test.ts b/packages/rest/src/analytics-dataset-dimension-gate.test.ts index 9f74815a4bb..08fa1602797 100644 --- a/packages/rest/src/analytics-dataset-dimension-gate.test.ts +++ b/packages/rest/src/analytics-dataset-dimension-gate.test.ts @@ -102,6 +102,23 @@ const dataset = { measures: [{ name: 'account_count', aggregate: 'count' }], }; +/** + * [ADR-0021, ADR-0149 D1] The same dataset with a STALE declaration: a declared + * dimension (and a declared time dimension) reading a field the object does not + * have — e.g. one dropped after the dataset was saved. A dataset query answers + * only declared members, so this is how the source-field gate is reached on the + * dataset door now: an undeclared `bogus_dim` is refused earlier, as an + * undeclared member (pinned below), and never reaches this gate. + */ +const staleDataset = { + ...dataset, + dimensions: [ + ...dataset.dimensions, + { name: 'bogus_dim', field: 'bogus_dim', type: 'string' }, + { name: 'bogus_at', field: 'bogus_dim', type: 'date' }, + ], +}; + const ACCOUNT_FIELDS = ['id', 'name', 'phone', 'industry', 'annual_revenue']; function buildRoute(analyticsProvider?: any) { @@ -168,7 +185,7 @@ describe('[#5520] a bogus selection dimension answers 400 INVALID_FIELD, end to it('names the field and the object — and is not a 500 (repro ③)', async () => { const route = buildRoute(async () => realAnalytics()); const res = await post(route, { - dataset, + dataset: staleDataset, selection: { measures: ['account_count'], dimensions: ['bogus_dim'] }, }); @@ -190,7 +207,7 @@ describe('[#5520] a bogus selection dimension answers 400 INVALID_FIELD, end to // is the field-naming 400, and that answer carries no statement. const route = buildRoute(async () => realAnalytics()); const res = await post(route, { - dataset, + dataset: staleDataset, selection: { measures: ['account_count'], dimensions: ['bogus_dim'] }, }); @@ -205,8 +222,8 @@ describe('[#5520] a bogus selection dimension answers 400 INVALID_FIELD, end to it('a POSITIVE control: the same wiring with a real field → 200 with rows', async () => { // Without this the cases above could pass for any reason that makes the // route 400, including a pipeline that never reaches the gate. It also pins - // the contract the gate must not kill: `phone` is a REAL column that this - // dataset never declared as a dimension, and it still groups. + // the contract the gate must not kill: a dimension DECLARED over a real + // column that is not the dataset's first one (`phone`) still groups. const route = buildRoute(async () => realAnalytics()); const declared = await post(route, { @@ -216,26 +233,44 @@ describe('[#5520] a bogus selection dimension answers 400 INVALID_FIELD, end to expect(declared.statusCode).toBe(200); expect(declared.body.rows).toEqual([{ industry: 'tech', account_count: 3 }]); - const undeclaredButReal = await post(route, { - dataset, - selection: { measures: ['account_count'], dimensions: ['phone'] }, + const declaredOverReal = await post(route, { + dataset: { ...dataset, dimensions: [...dataset.dimensions, { name: 'phone_dim', field: 'phone', type: 'string' }] }, + selection: { measures: ['account_count'], dimensions: ['phone_dim'] }, }); - expect(undeclaredButReal.statusCode).toBe(200); + expect(declaredOverReal.statusCode).toBe(200); + }); + + it('[ADR-0021, ADR-0149 D1] a real field the dataset does not DECLARE is refused as an undeclared member, before this gate', async () => { + // Until the closed-member rule, `dimensions: ['phone']` grouped by the raw + // column (the dimension twin of measure auto-inference). A dataset query now + // answers only the members its dataset declares, so the raw field — real + // or bogus — is refused 400 INVALID_FIELD by that rule, naming the member + // and the declared ones, and never reaches the source-field gate above. + const route = buildRoute(async () => realAnalytics()); + for (const member of ['phone', 'bogus_dim']) { + const res = await post(route, { dataset, selection: { measures: ['account_count'], dimensions: [member] } }); + expect(res.statusCode).toBe(400); + expect(res.body.code).toBe('INVALID_FIELD'); + expect(String(res.body.message)).toContain(`The dataset "account_metrics" does not declare the dimension "${member}".`); + expect(String(res.body.message)).toContain('Dimensions you may use: industry.'); + expect(String(res.body.message)).not.toMatch(/groups by field/); + } }); it('a bogus TIME dimension answers the same way, naming that request key', async () => { const route = buildRoute(async () => realAnalytics()); const res = await post(route, { - dataset, + dataset: staleDataset, selection: { measures: ['account_count'], dimensions: [], - timeDimensions: [{ dimension: 'bogus_dim', granularity: 'month' }], + timeDimensions: [{ dimension: 'bogus_at', granularity: 'month' }], }, }); expect(res.statusCode).toBe(400); expect(res.body.code).toBe('INVALID_FIELD'); + expect(String(res.body.message)).toMatch(/buckets field 'bogus_dim'/); }); }); diff --git a/packages/rest/src/analytics-dataset-refusal-envelope.test.ts b/packages/rest/src/analytics-dataset-refusal-envelope.test.ts index e18349a865b..2ab1d6db00e 100644 --- a/packages/rest/src/analytics-dataset-refusal-envelope.test.ts +++ b/packages/rest/src/analytics-dataset-refusal-envelope.test.ts @@ -323,12 +323,18 @@ describe('[#5367] a dataset refusal answers 400 DATASET_INVALID from its own env it('POSITIVE control (raw-SQL path): a DECLARED relationship still joins → 200 with rows', async () => { // The allowlist case's twin: `include: ['account']` makes the same dotted - // selection legal, so case ⑤ above is a verdict about the allowlist rather - // than about dotted members being rejected outright. + // path legal, so case ⑤ above is a verdict about the allowlist rather + // than about dotted paths being rejected outright. [ADR-0021, ADR-0149 D1] + // A dataset selection names only declared members, so the path is read + // through a dimension the dataset DECLARES over it, as an author writes it. const route = buildRoute(async () => nativeAnalytics()); const res = await post(route, { - dataset: { ...dataset, include: ['account'] }, - selection: { dimensions: ['account.region'], measures: ['revenue'] }, + dataset: { + ...dataset, + include: ['account'], + dimensions: [...dataset.dimensions, { name: 'account_region', field: 'account.region', type: 'string' }], + }, + selection: { dimensions: ['account_region'], measures: ['revenue'] }, }); expect(res.statusCode).toBe(200); expect(res.body.rows).toEqual([{ stage: 'won', revenue: 100 }]); diff --git a/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts b/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts index 35e46ff65e2..bb3e9820e21 100644 --- a/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts +++ b/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts @@ -366,25 +366,37 @@ describe('[#5716] the two sites this route cannot show, and why', () => { expect(String(res.body.detail)).toMatch(/3-hop limit/); }); - it('an undeclared MEASURE never reaches the strategy — `ensureCube` mints one, and the #4437 gate judges it', async () => { + it('an undeclared MEASURE never reaches the strategy — the closed-member rule refuses it, and a stale declared one meets the #4437 gate', async () => { // The twelfth site (`native-sql-strategy`'s "cube declares no measure") is // enveloped, and its producer test drives it — but it cannot be shown from - // this route, and the measurement is worth writing down rather than faking: - // `AnalyticsService.ensureCube` AUGMENTS a registered cube with a - // suffix-inferred `Metric` for every measure name the query carries, so the - // strategy is handed a cube that declares `profit` and compiles - // `SUM(profit)`. Reaching the refusal means calling the strategy directly - // (`measure-expression-sql.test.ts` does). + // this route, and the measurement is worth writing down rather than faking. + // [ADR-0021, ADR-0149 D1] A dataset query answers only the members its + // dataset declares, so an undeclared `profit_sum` is refused + // `400 INVALID_FIELD` as an undeclared member before anything is read — no + // measure is minted for it, so neither the strategy nor the source-field + // gate is reached. Reaching the strategy's refusal means calling the + // strategy directly (`measure-expression-sql.test.ts` does). // - // What answers on THIS face is the #4437 source-field gate, as soon as a - // field probe can say the object has no such column — and it answers + // What a DECLARED measure over a column the object does not have (a stale + // declaration) meets on THIS face is the #4437 source-field gate, as soon + // as a field probe can say the object has no such column — and it answers // `400 INVALID_FIELD`, the same code this PR gives the strategy's own // refusal. That agreement is the point of the choice, so it is asserted // rather than asserted about. const route = buildRoute(async () => nativeAnalytics({ getObjectFieldNames: () => ['stage', 'amount', 'close_date', 'created_at'] }), ); - const res = await post(route, { dataset, selection: { dimensions: ['stage'], measures: ['profit_sum'] } }); + const undeclared = await post(route, { dataset, selection: { dimensions: ['stage'], measures: ['profit_sum'] } }); + + expect(undeclared.statusCode).toBe(400); + expect(undeclared.body.code).toBe('INVALID_FIELD'); + expect(String(undeclared.body.message)).toContain('The dataset "pipeline" does not declare the measure "profit_sum".'); + expect(String(undeclared.body.message)).not.toMatch(/aggregates field/); + + const res = await post(route, { + dataset: { ...dataset, measures: [...dataset.measures, { name: 'profit_total', aggregate: 'sum', field: 'profit' }] }, + selection: { dimensions: ['stage'], measures: ['profit_total'] }, + }); expect(res.statusCode).toBe(400); expect(res.body.code).toBe('INVALID_FIELD'); diff --git a/packages/rest/src/analytics-relationship-path-admission.test.ts b/packages/rest/src/analytics-relationship-path-admission.test.ts index 9f5080b42bc..24428934bb2 100644 --- a/packages/rest/src/analytics-relationship-path-admission.test.ts +++ b/packages/rest/src/analytics-relationship-path-admission.test.ts @@ -371,21 +371,27 @@ for (const strategy of ['native', 'objectql'] as const) { expect(await answerOf(() => h.service.generateSql({ cube: LEDGER, measures: ['count'], dimensions: [`${OPEN}.name`] } as never, MEMBER_CTX as never))).toEqual({ answered: 'string' }); }); - it('the dataset door refuses a related object without a read grant, named through a relationship the dataset does not declare, as a declared one', async () => { + it('the dataset door never reads a related object without a read grant: refused 403 through a declared join, and refused before any read when named through a relationship the dataset does not declare', async () => { const reference = await h.datasetDoor( dataset([DENIED], [{ name: 'denied_dim', field: `${DENIED}.label`, type: 'string' }]), { measures: ['row_count'], dimensions: ['denied_dim'] }, ); expect({ status: reference.status, code: reference.body?.code }).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + // [ADR-0021, ADR-0149 D1] A dataset selection names only the members its + // dataset declares. `${DENIED}.label` is not one of them, so the door + // refuses it as an undeclared member before anything is read — the path + // never reaches the related object, so it can be neither served nor + // admitted. The caller may read this dataset's own objects (the ledger and + // the included open object), so the dataset's read refusal does not apply + // and the closed-member 400 answers, naming only the members THIS + // dataset declares. const answer = await h.datasetDoor( dataset([OPEN], [{ name: 'open_dim', field: `${OPEN}.name`, type: 'string' }]), { measures: ['row_count'], dimensions: [`${DENIED}.label`] }, ); - expect({ status: answer.status, code: answer.body?.code, message: answer.body?.message }).toEqual({ - status: reference.status, - code: reference.body?.code, - message: reference.body?.message, - }); + expect({ status: answer.status, code: answer.body?.code }).toEqual({ status: 400, code: 'INVALID_FIELD' }); + expect(String(answer.body?.message)).toContain(`The dataset "rpa_inline" does not declare the dimension "${DENIED}.label".`); + expect(String(answer.body?.message)).toContain('Dimensions you may use: title_dim, open_dim.'); expect(answer.body?.rows).toBeUndefined(); }); }); From b25fa01d873682cfc3cb1db9d90806af7334e8b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:18:05 +0000 Subject: [PATCH 06/16] docs(api): say the cube query's inferred measure spellings stop at the dataset query The "How to spell a measure" callout under POST /analytics/query lists the inferred spellings (count, FIELD_sum and the rest) without saying they belong to the cube query only. The dataset query answers only its dataset's declared members and refuses any other name 400 INVALID_FIELD; the callout now says so and points to the Analytics page. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- content/docs/api/data-api.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index 6a6bbf9c019..1e9a78bcb99 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -490,6 +490,12 @@ Any other dotted spelling — `revenue.sum`, `owner.amount_sum` — is refused w traverse relationships, only dimensions do, so there is no related column for a dotted measure to aggregate. To aggregate a related column, declare a Cube whose measure names it in its own `sql`. + +These inferred spellings belong to the cube query only. The dataset query +(`POST /analytics/dataset/query`) answers only the measures and dimensions its dataset +declares, by their declared names, and refuses any other name — `count`, a raw field, a +suffix spelling — with `400 INVALID_FIELD` before anything is read; see +[Analytics](/docs/data-modeling/analytics). From 8e358c311d942975b378dd6edbd9b32382801358 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:38:05 +0000 Subject: [PATCH 07/16] test(rest): pay the objectql load at module top in two dataset-door pins Both files reach a dynamic import of @objectstack/objectql inside a handler, so the first case to get past the source's gates paid that load inside its clocked window. A module-top side-effect import moves the load to collection, as check:test-source-alias prescribes. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- packages/rest/src/analytics-dataset-dimension-gate.test.ts | 4 ++++ packages/rest/src/analytics-dataset-refusal-envelope.test.ts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/packages/rest/src/analytics-dataset-dimension-gate.test.ts b/packages/rest/src/analytics-dataset-dimension-gate.test.ts index 08fa1602797..f552428d8d5 100644 --- a/packages/rest/src/analytics-dataset-dimension-gate.test.ts +++ b/packages/rest/src/analytics-dataset-dimension-gate.test.ts @@ -61,6 +61,10 @@ import type { Logger } from '@objectstack/spec/contracts'; import { AnalyticsService } from '@objectstack/service-analytics'; import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; import { RestServer } from './rest-server'; +// The server reaches `@objectstack/objectql` only through a dynamic import inside a +// handler; paid here at module scope so the first load lands during collection, +// not inside a clocked window (`pnpm check:test-source-alias`). +import '@objectstack/objectql'; // [#17865] This file observes the REST fault log, so it declares the level it // asserts against instead of inheriting the suite's quiet one. 'info' is the diff --git a/packages/rest/src/analytics-dataset-refusal-envelope.test.ts b/packages/rest/src/analytics-dataset-refusal-envelope.test.ts index 2ab1d6db00e..73f20ff9d53 100644 --- a/packages/rest/src/analytics-dataset-refusal-envelope.test.ts +++ b/packages/rest/src/analytics-dataset-refusal-envelope.test.ts @@ -59,6 +59,10 @@ import { describe, it, expect, vi } from 'vitest'; import type { Logger } from '@objectstack/spec/contracts'; import { AnalyticsService } from '@objectstack/service-analytics'; import { RestServer } from './rest-server'; +// The server reaches `@objectstack/objectql` only through a dynamic import inside a +// handler; paid here at module scope so the first load lands during collection, +// not inside a clocked window (`pnpm check:test-source-alias`). +import '@objectstack/objectql'; // ── harness (the shape `analytics-filter-refusal-envelope.test.ts` uses) ────── From 5a127a4cc93d728f1e94f78d84224a4ec10a87ce Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:59:12 +0000 Subject: [PATCH 08/16] fix(service-analytics): word the source-field remedy for the dataset door The measure and dimension source-field gates ended every refusal with the cube door's hint: measures are inferred from the object's own fields as FIELD_sum and the rest, and any own field may be used as a dimension without declaring it. The dataset door now answers only declared members, so it reaches these gates only through a declared member over a field the object does not have, and that hint is false there. A dataset call's scope now carries datasetDoor, which ensureCube and the draft preview pass to both gates; on the dataset door the refusal points at the member's declared field (point it at one of the object's fields, or remove the member). The cube door's message is byte-identical. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../analytics-dataset-dimension-gate.test.ts | 4 ++ ...-dataset-unlisted-refusal-envelope.test.ts | 2 + .../dataset-query-declared-members.test.ts | 63 +++++++++++++++++++ .../preview-undeclared-measure-parity.test.ts | 29 +++++++++ .../src/analytics-service.ts | 61 +++++++++++++----- 5 files changed, 143 insertions(+), 16 deletions(-) diff --git a/packages/rest/src/analytics-dataset-dimension-gate.test.ts b/packages/rest/src/analytics-dataset-dimension-gate.test.ts index f552428d8d5..cf45ee779d3 100644 --- a/packages/rest/src/analytics-dataset-dimension-gate.test.ts +++ b/packages/rest/src/analytics-dataset-dimension-gate.test.ts @@ -200,6 +200,10 @@ describe('[#5520] a bogus selection dimension answers 400 INVALID_FIELD, end to expect(res.body.code).not.toBe('ANALYTICS_QUERY_FAILED'); expect(String(res.body.message)).toMatch(/groups by field 'bogus_dim'/); expect(String(res.body.message)).toMatch(/object 'crm_account' does not have/); + // [ADR-0021, ADR-0149 D1] The dataset door's remedy is the declared field, + // never the cube door's "own fields need no declaration" hint. + expect(String(res.body.message)).toContain("The dataset declares this dimension over 'bogus_dim': point its `field` at one of the object's fields, or remove the dimension"); + expect(String(res.body.message)).not.toMatch(/without the cube declaring it/); }); it('carries no generated SQL — because the statement was never built', async () => { diff --git a/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts b/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts index bb3e9820e21..2fe2c987b85 100644 --- a/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts +++ b/packages/rest/src/analytics-dataset-unlisted-refusal-envelope.test.ts @@ -401,5 +401,7 @@ describe('[#5716] the two sites this route cannot show, and why', () => { expect(res.statusCode).toBe(400); expect(res.body.code).toBe('INVALID_FIELD'); expect(String(res.body.message)).toMatch(/aggregates field 'profit', which object 'crm_opportunity' does not have/); + expect(String(res.body.message)).toContain("The dataset declares this measure over 'profit': point its `field` at one of the object's fields, or remove the measure"); + expect(String(res.body.message)).not.toMatch(/inferred from the object's OWN fields/); }); }); diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts index 3b8d0061f88..e99f2a1acfc 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -209,3 +209,66 @@ describe('queryDataset refuses a selection member the dataset does not declare', expect(out).toBeDefined(); }); }); + +/** + * [ADR-0021, ADR-0149 D1] The source-field gates' remedy on each door. A + * dataset reaches them only through a DECLARED member whose field the object + * does not have (a stale declaration): an undeclared one is refused first, + * above. Their cube-door hint — measures are inferred from the object's own + * fields as `FIELD_sum` …, and any own field may be used as a dimension + * without declaring it — is false on the dataset door, so there the refusal + * points at the member's declared field. The cube door keeps its hint. + */ +describe('the source-field gates word their remedy for the door that asked', () => { + const STALE: Dataset = DatasetSchema.parse({ + name: 'stale_pipeline', + label: 'Stale pipeline', + object: 'crm_opp', + dimensions: [ + { name: 'stage', label: 'Stage', field: 'stage', type: 'string' }, + { name: 'ghost_dim', label: 'Ghost', field: 'ghost', type: 'string' }, + ], + measures: [ + { name: 'revenue', label: 'Revenue', aggregate: 'sum', field: 'amount' }, + { name: 'ghost_total', label: 'Ghost total', aggregate: 'sum', field: 'ghost' }, + ], + }); + const MEASURE_HINT = /inferred from the object's OWN fields/; + const DIMENSION_HINT = /without the cube declaring it/; + + it('the dataset door: a stale declared measure names its field and the fix, never the inferred-measure hint', async () => { + const { service, reads } = await boot(); + const e = await service.queryDataset(STALE, { measures: ['ghost_total'] } as never, ADMIN).catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, field: 'ghost', param: 'measures' }); + expect(messageOf(e)).toMatch(/aggregates field 'ghost', which object 'crm_opp' does not have/); + expect(messageOf(e)).toContain("The dataset declares this measure over 'ghost': point its `field` at one of the object's fields, or remove the measure"); + expect(messageOf(e)).not.toMatch(MEASURE_HINT); + expect(reads).toEqual([]); + }); + + it('the dataset door: a stale declared dimension names its field and the fix, never the undeclared-dimension hint', async () => { + const { service, reads } = await boot(); + const e = await service + .queryDataset(STALE, { measures: ['revenue'], dimensions: ['ghost_dim'] } as never, ADMIN) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, field: 'ghost', param: 'dimensions' }); + expect(messageOf(e)).toMatch(/groups by field 'ghost', which object 'crm_opp' does not have/); + expect(messageOf(e)).toContain("The dataset declares this dimension over 'ghost': point its `field` at one of the object's fields, or remove the dimension"); + expect(messageOf(e)).not.toMatch(DIMENSION_HINT); + expect(reads).toEqual([]); + }); + + it('CONTROL: the cube door keeps both hints, because there they are true', async () => { + const { service } = await boot(); + const measure = await service.query({ cube: 'crm_opp', measures: ['ghost_sum'] } as never, ADMIN).catch((err) => err); + expect(measure).toMatchObject({ code: 'INVALID_FIELD', status: 400, field: 'ghost' }); + expect(messageOf(measure)).toMatch(MEASURE_HINT); + expect(messageOf(measure)).not.toContain('The dataset declares'); + const dimension = await service + .query({ cube: 'crm_opp', measures: ['count'], dimensions: ['ghost'] } as never, ADMIN) + .catch((err) => err); + expect(dimension).toMatchObject({ code: 'INVALID_FIELD', status: 400, field: 'ghost' }); + expect(messageOf(dimension)).toMatch(DIMENSION_HINT); + expect(messageOf(dimension)).not.toContain('The dataset declares'); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts b/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts index f61481648c3..c10a4d85179 100644 --- a/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/preview-undeclared-measure-parity.test.ts @@ -145,6 +145,35 @@ describe('[#28172] an undeclared measure on the native, ObjectQL and draft-previ }); } + it('a stale DECLARED measure over a field the object does not have: one dataset-door remedy on every face, the draft preview included', async () => { + // [ADR-0021, ADR-0149 D1] The source-field gate meets a dataset only + // through a declared member, so its refusal points at the declared field + // and never offers the cube door's suffix-inferred measures. + const stale = DatasetSchema.parse({ ...DATASET, measures: [...DATASET.measures, { name: 'ghost_total', aggregate: 'sum', field: 'ghost' }] }); + const refusals = await Promise.all( + FACES.map((face) => + refusalOf( + services[face === 'preview' ? 'objectql' : face]!.queryDataset( + stale, + { dimensions: ['region'], measures: ['ghost_total'] } as never, + undefined, + face === 'preview' ? { previewDrafts: true } : undefined, + ), + ), + ), + ); + for (const err of refusals) { + expect(err.code, err.message).toBe('INVALID_FIELD'); + expect(err.status).toBe(400); + expect(err.field).toBe('ghost'); + expect(err.message).toContain("The dataset declares this measure over 'ghost': point its `field` at one of the object's fields, or remove the measure"); + expect(err.message).not.toMatch(/inferred from the object's OWN fields/); + } + const [native, objectql, preview] = refusals; + expect(preview.message).toBe(native.message); + expect(objectql.message).toBe(native.message); + }); + it("CONTROL: 'total' serves the same values on every face", async () => { for (const face of FACES) { const result = await ask(face, 'total'); diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 386a29b96ee..74714b8ca72 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -1458,6 +1458,14 @@ interface CubeScope { getCompiledDataset(name: string): CompiledDataset | undefined; /** Record a cube this call minted — `ensureCube`'s inference or augmentation. */ register(cube: Cube): void; + /** + * [ADR-0021, ADR-0149 D1] True for one `queryDataset` call's scope: the + * dataset door answers only the members its dataset declares, so its + * source-field refusals must not tell the author that an undeclared member is + * inferred or allowed. Absent on the shared scope and on the ad-hoc doors, + * which keep their ad-hoc members and their hint. + */ + readonly datasetDoor?: boolean; } /** The strategy context's three name-keyed reads, answered from one {@link CubeScope}. */ @@ -2812,6 +2820,7 @@ export class AnalyticsService implements IAnalyticsService { register: (cube) => { cubes.set(cube.name, cube); }, + datasetDoor: compiled !== undefined, }; } @@ -3146,8 +3155,8 @@ export class AnalyticsService implements IAnalyticsService { // (`bogus`) is refused `INVALID_FIELD` / 400 with the same message, // where the evaluator grouped every row under one `null` key. One // that names a real field (`amount`) groups by it, here as there. - this.assertMeasureFields(q, cube, Object.keys(compiled.cube.measures)); - this.assertDimensionFields(q, cube, Object.keys(compiled.cube.dimensions)); + this.assertMeasureFields(q, cube, Object.keys(compiled.cube.measures), true); + this.assertDimensionFields(q, cube, Object.keys(compiled.cube.dimensions), true); // [#28257] …and the structured-JSON dimension door (#20807): a // grouped dimension over a `json` column is refused there, where // the evaluator grouped by each row's object value. @@ -4036,6 +4045,7 @@ export class AnalyticsService implements IAnalyticsService { private ensureCube(query: AnalyticsQuery, scope: CubeScope): void { const name = query.cube!; let cube = scope.getCube(name); + const datasetDoor = scope.datasetDoor === true; if (!cube) { // [#3867] Auto-inference below sets `cube.sql = name`, so from here on @@ -4050,12 +4060,12 @@ export class AnalyticsService implements IAnalyticsService { // is registered — a rejected query must leave no trace in the registry // (same rule the #3867 gate above keeps), or a retry would find a // "registered" cube carrying the bogus measure and sail straight to SQL. - this.assertMeasureFields(query, cube, Object.keys(cube.measures)); + this.assertMeasureFields(query, cube, Object.keys(cube.measures), datasetDoor); // [#5520] …and the dimensions', for exactly the same reason. On this path // `cube.dimensions` was minted from the query moments ago, so the bogus // spelling is in there — which is why the suggestion list is computed by // subtraction inside the gate rather than echoed verbatim. - this.assertDimensionFields(query, cube, Object.keys(cube.dimensions)); + this.assertDimensionFields(query, cube, Object.keys(cube.dimensions), datasetDoor); // [#20807] …and a grouped dimension's column must not be structured JSON. this.assertDimensionsGroupScalarColumns(query, cube); // [#21044] …and a measure's aggregate must be one the aggregate × @@ -4132,11 +4142,11 @@ export class AnalyticsService implements IAnalyticsService { // vocabulary. Snapshot the declared list BEFORE registering the augmented // cube so the rejection can suggest what the caller could have meant — // and so a rejected query leaves the registry as it found it. - this.assertMeasureFields(query, augmented, Object.keys(cube.measures)); + this.assertMeasureFields(query, augmented, Object.keys(cube.measures), datasetDoor); // [#5520] Dimensions are never augmented (nothing infers one), so the // authored/compiled list IS the vocabulary a caller may name — and the one // the rejection suggests. - this.assertDimensionFields(query, augmented, Object.keys(cube.dimensions)); + this.assertDimensionFields(query, augmented, Object.keys(cube.dimensions), datasetDoor); this.assertDimensionsGroupScalarColumns(query, augmented); // [#21044] Judged on the AUGMENTED cube: a suffix-inferred measure and an // authored one are one population for the aggregate × field-type table. @@ -4154,8 +4164,8 @@ export class AnalyticsService implements IAnalyticsService { } else { // No inference happened — every measure is declared. Still validate: an // authored cube can declare a measure over a field the object dropped. - this.assertMeasureFields(query, cube, Object.keys(cube.measures)); - this.assertDimensionFields(query, cube, Object.keys(cube.dimensions)); + this.assertMeasureFields(query, cube, Object.keys(cube.measures), datasetDoor); + this.assertDimensionFields(query, cube, Object.keys(cube.dimensions), datasetDoor); this.assertDimensionsGroupScalarColumns(query, cube); this.assertMeasureFieldTypes(query, cube); this.assertRecordCurrencyGrouped(query, cube); @@ -4326,8 +4336,14 @@ export class AnalyticsService implements IAnalyticsService { * What changed is what can reach it: a dotted measure is now either a * `.` qualifier or a key the cube itself declares, because every other * dotted spelling is refused at the mint before this gate runs. + * + * [ADR-0021, ADR-0149 D1] `datasetDoor` words the remedy for a dataset + * query, which reaches this gate only through a DECLARED measure (an + * undeclared one is refused first, as undeclared): the hint about + * suffix-inferred measures is true of the cube door alone, so on the dataset + * door the refusal points at the measure's declared field instead. */ - private assertMeasureFields(query: AnalyticsQuery, cube: Cube, declaredMeasures: string[]): void { + private assertMeasureFields(query: AnalyticsQuery, cube: Cube, declaredMeasures: string[], datasetDoor = false): void { const probe = this.getObjectFieldNames; if (!probe) return; const measures = query.measures ?? []; @@ -4372,9 +4388,13 @@ export class AnalyticsService implements IAnalyticsService { `Measure '${measure}' on cube '${cube.name}' aggregates field '${source}', which object ` + `'${object}' does not have. ` + `Valid measures: ${usable.join(', ') || '(none)'}. ` + - `Other measures are inferred from the object's OWN fields as ` + - `'_sum' / '_avg' / '_min' / '_max' / '_count_distinct', so check the spelling of ` + - `'${source}' — known fields: ${[...fieldNames].sort().join(', ')}.`, + (datasetDoor + ? `The dataset declares this measure over '${source}': point its \`field\` at one of the ` + + `object's fields, or remove the measure` + : `Other measures are inferred from the object's OWN fields as ` + + `'_sum' / '_avg' / '_min' / '_max' / '_count_distinct', so check the spelling of ` + + `'${source}'`) + + ` — known fields: ${[...fieldNames].sort().join(', ')}.`, ) as Error & { code?: string; status?: number; field?: string; object?: string; param?: string; measure?: string }; err.code = 'INVALID_FIELD'; err.status = 400; @@ -4436,8 +4456,14 @@ export class AnalyticsService implements IAnalyticsService { * Runs after the measure gate and before the `where` gate on each `ensureCube` * path, so a query that gets several wrong is answered about its measure * first — one rejection at a time, naming a real mistake either way. + * + * [ADR-0021, ADR-0149 D1] On the dataset door (`datasetDoor`) an undeclared + * dimension is refused first, as undeclared, so this gate meets only a + * DECLARED one, and "the object's own fields may be used without declaring + * them" is false there: the refusal points at the dimension's declared + * field instead. The cube door keeps the hint. */ - private assertDimensionFields(query: AnalyticsQuery, cube: Cube, declaredDimensions: string[]): void { + private assertDimensionFields(query: AnalyticsQuery, cube: Cube, declaredDimensions: string[], datasetDoor = false): void { const probe = this.getObjectFieldNames; if (!probe) return; /** Every dimension this query names, tagged with the request key it came from. */ @@ -4486,9 +4512,12 @@ export class AnalyticsService implements IAnalyticsService { `${kind} '${member}' on cube '${cube.name}' ${verb} field '${source}', which object ` + `'${object}' does not have. ` + `Valid dimensions: ${usable.join(', ') || '(none)'}. ` + - `Any of the object's OWN fields may also be used as a dimension without the cube ` + - `declaring it, so check the spelling of ` + - `'${source}' — known fields: ${[...fieldNames].sort().join(', ')}.`, + (datasetDoor + ? `The dataset declares this dimension over '${source}': point its \`field\` at one of the ` + + `object's fields, or remove the dimension` + : `Any of the object's OWN fields may also be used as a dimension without the cube ` + + `declaring it, so check the spelling of '${source}'`) + + ` — known fields: ${[...fieldNames].sort().join(', ')}.`, ) as Error & { code?: string; status?: number; field?: string; object?: string; param?: string; dimension?: string }; err.code = 'INVALID_FIELD'; err.status = 400; From e2a0a9c2058446638b3132a1acf5efac553317be Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:59:19 +0000 Subject: [PATCH 09/16] chore(service-analytics): note the dataset-door source-field remedy in the changeset Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .changeset/34005-dataset-door-declared-members.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index f31859f1d7a..770af4fe3b1 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -14,4 +14,5 @@ Skills-docs: none — `skills/**` teach dataset selections only by the dataset's - A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. - The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. +- A declared member over a field the object does not have is still refused `400 INVALID_FIELD`; on the dataset door its message now points at the member's declared field (point it at one of the object's fields, or remove the member) instead of the cube door's hint that undeclared members are inferred or allowed. The cube door's message is unchanged. - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. From 5c5966f907ca5f7ad234d8043dbc6585ed2066fd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:24:13 +0000 Subject: [PATCH 10/16] fix(service-analytics): name the compare widget's remedy, pin the refusal's order against the read gate - The undeclared-member refusal names the compare widget's remedy when the refused member is a comparison window's date key. - Pin the read gate's 503 and denial ahead of the member list, in process and through the REST door. - Restore a served control for a declared dimension over a backed path. - Note at the draft-preview gates that selection members no longer reach them. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...analytics-read-gate-fault-envelope.test.ts | 45 ++++++++++++- .../dataset-query-declared-members.test.ts | 66 ++++++++++++++++++- ...ted-dimension-unbacked-join-parity.test.ts | 35 +++++++++- .../src/analytics-service.ts | 7 ++ .../src/dataset-declared-members.ts | 55 +++++++++++++--- 5 files changed, 195 insertions(+), 13 deletions(-) diff --git a/packages/rest/src/analytics-read-gate-fault-envelope.test.ts b/packages/rest/src/analytics-read-gate-fault-envelope.test.ts index fefede8f743..0b6bdabb71e 100644 --- a/packages/rest/src/analytics-read-gate-fault-envelope.test.ts +++ b/packages/rest/src/analytics-read-gate-fault-envelope.test.ts @@ -110,7 +110,7 @@ const body = { selection: { dimensions: ['stage'], measures: ['revenue'] }, }; -async function post(gates: Gates) { +async function post(gates: Gates, request: unknown = body) { const executed: string[] = []; const { logger, lines } = recordingLogger(); const service = analytics(gates, executed, logger); @@ -119,7 +119,7 @@ async function post(gates: Gates) { const logSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); let routeLog: string; try { - await route.handler({ method: 'POST', params: {}, headers: {}, body } as any, res); + await route.handler({ method: 'POST', params: {}, headers: {}, body: request } as any, res); // Read the calls BEFORE restoring: `mockRestore` clears them. routeLog = logSpy.mock.calls.map((args) => args.map(String).join(' ')).join('\n'); } finally { @@ -192,3 +192,44 @@ describe('[#25561] a read gate that could not decide answers 503 SERVICE_UNAVAIL }); }); }); + +/** + * [ADR-0021] A selection naming a member the dataset does not declare is + * refused with a list of the members THIS caller may use. That list is only + * ever built for a caller the read gate admits: one it denies gets the + * denial, and one it cannot decide for gets the 503, both with no member + * list — the same answers the declared query above gets. + */ +describe('[ADR-0021] an undeclared selection member is answered by the read gate first, through the REST door', () => { + const undeclared = { ...body, selection: { dimensions: ['amount'], measures: ['count'] } }; + const NO_MEMBER_LIST = (res: { body: unknown }) => { + const text = JSON.stringify(res.body); + expect(text).not.toContain('you may use'); + expect(text).not.toContain('revenue'); + expect(text).not.toContain('does not declare'); + }; + + it('the control: an admitted caller gets the undeclared-member refusal, naming the members it may use', async () => { + const res = await post({ admitObjectRead: () => true, getReadableFields: () => ['stage', 'amount'] }, undeclared); + expect(res.status).toBe(400); + expect(res.body.code).toBe('INVALID_FIELD'); + expect(String(res.body.message)).toContain('Measures you may use: revenue.'); + expect(res.executed).toEqual([]); + }); + + it('a caller the read gate denies gets 403 PERMISSION_DENIED and no member list', async () => { + const res = await post({ admitObjectRead: () => false }, undeclared); + expect(res.status).toBe(403); + expect(res.body.code).toBe('PERMISSION_DENIED'); + NO_MEMBER_LIST(res); + expect(res.executed).toEqual([]); + }); + + it('a caller the read gate cannot decide for gets 503 SERVICE_UNAVAILABLE and no member list', async () => { + const res = await post({ admitObjectRead: exploded }, undeclared); + expect(res.status).toBe(503); + expect(res.body.code).toBe('SERVICE_UNAVAILABLE'); + NO_MEMBER_LIST(res); + expect(res.executed).toEqual([]); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts index e99f2a1acfc..c105fba2264 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -18,7 +18,8 @@ * Unchanged, and pinned as controls: every declared member is served; a * declared member over a field the caller may not read still reaches the * field gate (403); a caller who may not read the object at all gets the read - * refusal (403), never a member list; the cube door (`query()`, not a + * refusal (403), and one the read gate cannot decide for gets its 503, never + * a member list either way; the cube door (`query()`, not a * dataset) still mints `count`. */ @@ -44,6 +45,7 @@ const OBJECTS: Record> }, }, crm_locked: { fields: { id: { type: 'text' }, amount: { type: 'number' } } }, + crm_flaky: { fields: { id: { type: 'text' }, amount: { type: 'number' } } }, }; const PIPELINE: Dataset = DatasetSchema.parse({ @@ -70,12 +72,24 @@ const LOCKED: Dataset = DatasetSchema.parse({ measures: [{ name: 'total', label: 'Total', aggregate: 'sum', field: 'amount' }], }); +/** The read gate cannot reach a verdict on `crm_flaky` for u_me (its lookup throws: the 503 answer). */ +const FLAKY: Dataset = DatasetSchema.parse({ + name: 'flaky_ds', + label: 'Flaky', + object: 'crm_flaky', + dimensions: [], + measures: [{ name: 'total', label: 'Total', aggregate: 'sum', field: 'amount' }], +}); + const nativeSql = () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }); /** u_me may not read `crm_locked` nor the `margin` field; u_admin reads everything. */ const security = { getReadFilter: async () => undefined, - canReadObject: (object: string, ctx?: ExecutionContext) => !(ctx?.userId === 'u_me' && object === 'crm_locked'), + canReadObject: (object: string, ctx?: ExecutionContext) => { + if (ctx?.userId === 'u_me' && object === 'crm_flaky') throw new Error('permission store unreachable'); + return !(ctx?.userId === 'u_me' && object === 'crm_locked'); + }, getReadableFields: async (object: string, ctx?: ExecutionContext) => { const all = Object.keys(OBJECTS[object]?.fields ?? {}); return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all; @@ -179,6 +193,15 @@ describe('queryDataset refuses a selection member the dataset does not declare', expect(reads).toEqual([]); }); + it('CONTROL: a caller the read gate cannot decide for gets that gate\'s 503, never a member list', async () => { + const { service, reads } = await boot(); + const e = await service.queryDataset(FLAKY, { measures: ['count'] } as never, ME).catch((err) => err); + expect(e).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(messageOf(e)).not.toContain('Measures you may use'); + expect(messageOf(e)).not.toContain('total'); + expect(reads).toEqual([]); + }); + it('CONTROL: a declared member over a field the caller may not read still reaches the field gate (403)', async () => { const { service, reads } = await boot(); const e = await service.queryDataset(PIPELINE, { measures: ['margin_total'] } as never, ME).catch((err) => err); @@ -186,6 +209,45 @@ describe('queryDataset refuses a selection member the dataset does not declare', expect(reads).toEqual([]); }); + it('a comparison window over an undeclared date key names the compare widget\'s remedy', async () => { + // A dashboard compare widget lowers the dashboard date-range filter into + // `timeDimensions` under the filtered FIELD's name (`closed_on`), which + // this dataset declares only as `close_month`. + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['revenue'], + timeDimensions: [{ dimension: 'closed_on', dateRange: ['2026-01-01', '2026-03-31'] }], + compareTo: { kind: 'previousPeriod' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'closed_on', param: 'timeDimensions', cube: 'pipeline' }); + expect(messageOf(e)).toContain('The dataset "pipeline" does not declare the dimension "closed_on".'); + expect(messageOf(e)).toContain( + 'The dimension "closed_on" is the date key of this query\'s comparison window (`compareTo`)', + ); + expect(messageOf(e)).toContain('Declare a date dimension named "closed_on" on the dataset (over that field)'); + expect(messageOf(e)).toContain("or set the widget's `compareTo.dimension` to a declared date dimension"); + expect(reads).toEqual([]); + }); + + it('CONTROL: the same undeclared time dimension with no comparison gets no compare-widget remedy', async () => { + const { service } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { measures: ['revenue'], timeDimensions: [{ dimension: 'closed_on', dateRange: ['2026-01-01', '2026-03-31'] }] } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'closed_on' }); + expect(messageOf(e)).not.toContain('comparison window'); + }); + it('CONTROL: every declared measure and dimension, a declared time dimension included, is served', async () => { const { service, reads } = await boot([{ stage: 'won', revenue: 100, deal_count: 1 }]); const out = await service.queryDataset( diff --git a/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts b/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts index 9b1fb6b5c12..6a26409d4d4 100644 --- a/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/dotted-dimension-unbacked-join-parity.test.ts @@ -29,7 +29,9 @@ * `bogus` are refused by the closed-member rule on every face, ahead of the * relationship-path gate, with one message. That gate stays pinned through * what still reaches it: a `runtimeFilter` member (filter keys are fields, not - * members) and the cube faces further down this file. + * members) and the cube faces further down this file. The served case stays + * pinned as a DECLARED dimension over the backed path (`account_name`, which + * reads `account.name`), on both live strategies. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -65,6 +67,17 @@ const shape = { const UNBACKED = DatasetSchema.parse({ name: 'os28258_deals', ...shape }); /** Declares `account`, and nothing past it. */ const BACKED = DatasetSchema.parse({ name: 'os28258_deals_by_account', include: ['account'], ...shape }); +/** + * Declares `account` AND a dimension over it (`account_name` reads + * `account.name`): the backed relationship path, spelled the way a dataset + * query may select it — by its declared name. + */ +const BACKED_DECLARED = DatasetSchema.parse({ + name: 'os28258_deals_by_account_name', + include: ['account'], + ...shape, + dimensions: [...shape.dimensions, { name: 'account_name', field: 'account.name', type: 'string' }], +}); type Face = 'native' | 'objectql' | 'preview'; const FACES: readonly Face[] = ['native', 'objectql', 'preview']; @@ -100,6 +113,11 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do face === 'preview' ? { previewDrafts: true } : undefined, ); + const groupsOf = (rows: unknown, dimension: string) => + (rows as Array>) + .map((r) => ({ key: r[dimension], total: Number(r.total) })) + .sort((a, b) => String(a.key).localeCompare(String(b.key))); + beforeAll(async () => { const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); engine = new ObjectQL({ logger: quiet } as never); @@ -189,6 +207,21 @@ describe('[#28258] a dotted dimension through a relationship path the dataset do expect(refusals[2].message).toBe(refusals[0].message); }); + it("CONTROL: a DECLARED dimension over the backed 'account.name' serves on both live strategies, the same groups", async () => { + const expected = [{ key: 'Acme', total: 130 }, { key: 'Globex', total: 50 }]; + for (const face of ['native', 'objectql'] as const) { + const result = await ask(face, BACKED_DECLARED, { dimensions: ['account_name'], measures: ['total'] }); + expect(groupsOf(result.rows, 'account_name'), face).toEqual(expected); + } + // [#28555] The preview joins nothing, so it refuses the backed path with + // its own refusal — neither this gate's nor the closed-member rule's. + const err = await refusalOf(ask('preview', BACKED_DECLARED, { dimensions: ['account_name'], measures: ['total'] })); + expect(err.code, err.message).toBe('INVALID_FIELD'); + expect(err.status).toBe(400); + expect(err.message).not.toContain('which the dataset does not declare'); + expect(err.message).not.toContain('does not declare the dimension'); + }); + it("CONTROL: a measure mistake beside an unbacked dotted dimension is answered about the measure on every face", async () => { const refusals = await Promise.all( FACES.map((face) => refusalOf(ask(face, UNBACKED, { dimensions: ['account.name'], measures: ['nope'] }))), diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 74714b8ca72..2334035dc91 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -3144,6 +3144,10 @@ export class AnalyticsService implements IAnalyticsService { // measures, as the published gates read the cube after // `ensureCube`, so a minted measure is judged by the field it // aggregates. + // [ADR-0021] No undeclared SELECTION member reaches this branch + // now: `assertSelectionMembersDeclared` refuses it above, before + // the branch, so the minting described above no longer serves a + // caller-named measure on this path. const minted = mintCallerMeasures(q.measures, compiled.cube, compiled.cube.name, compiled.durations); const cube: Cube = Object.keys(minted).length > 0 ? { ...compiled.cube, measures: { ...compiled.cube.measures, ...minted } } @@ -3155,6 +3159,9 @@ export class AnalyticsService implements IAnalyticsService { // (`bogus`) is refused `INVALID_FIELD` / 400 with the same message, // where the evaluator grouped every row under one `null` key. One // that names a real field (`amount`) groups by it, here as there. + // [ADR-0021] An undeclared selection dimension no longer reaches + // this branch (`assertSelectionMembersDeclared` refuses it first); + // these gates now meet only a declared member over a stale field. this.assertMeasureFields(q, cube, Object.keys(compiled.cube.measures), true); this.assertDimensionFields(q, cube, Object.keys(compiled.cube.dimensions), true); // [#28257] …and the structured-JSON dimension door (#20807): a diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts index d8ee5372ecd..66df0586d74 100644 --- a/packages/services/service-analytics/src/dataset-declared-members.ts +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -39,8 +39,22 @@ export interface UndeclaredSelectionMember { member: string; /** The selection key it was found under. */ param: Extract; + /** + * True for a `timeDimensions` entry carrying a `dateRange` in a selection + * that asks for a `compareTo`: the date key of a comparison window. A + * dashboard compare widget lowers its date window into `timeDimensions` + * under the filtered field's name, so this is how a dashboard date-range + * field that is not also a declared dimension's name arrives here. + */ + compareWindow?: boolean; } +/** The selection shape {@link undeclaredSelectionMembers} reads. */ +export type JudgedSelection = Pick & { + timeDimensions?: ReadonlyArray<{ dimension?: unknown; dateRange?: unknown } | null | undefined>; + compareTo?: unknown; +}; + /** * The members `selection` names that `dataset` does not declare, in request * order, each `(member, param)` pair once. Empty when every member is @@ -49,7 +63,7 @@ export interface UndeclaredSelectionMember { */ export function undeclaredSelectionMembers( dataset: Pick, - selection: Pick & { timeDimensions?: ReadonlyArray<{ dimension?: unknown } | null | undefined> }, + selection: JudgedSelection, ): UndeclaredSelectionMember[] { const measures = new Set((dataset.measures ?? []).map((m) => m.name)); const dimensions = new Set((dataset.dimensions ?? []).map((d) => d.name)); @@ -63,14 +77,36 @@ export function undeclaredSelectionMembers( }; judge(Array.isArray(selection.measures) ? selection.measures : [], measures, 'measures'); judge(Array.isArray(selection.dimensions) ? selection.dimensions : [], dimensions, 'dimensions'); - judge( - (Array.isArray(selection.timeDimensions) ? selection.timeDimensions : []).map((td) => td?.dimension), - dimensions, - 'timeDimensions', - ); + const timeDimensions = Array.isArray(selection.timeDimensions) ? selection.timeDimensions : []; + judge(timeDimensions.map((td) => td?.dimension), dimensions, 'timeDimensions'); + if (selection.compareTo != null) { + for (const u of undeclared) { + if (u.param === 'timeDimensions' && timeDimensions.some((td) => td?.dimension === u.member && td?.dateRange != null)) { + u.compareWindow = true; + } + } + } return undeclared; } +/** + * The remedy sentence for an undeclared comparison-window date key, or `''` + * when no undeclared member is one. A bare "not declared" does not tell a + * dashboard author what to change: the key is the dashboard date-range field, + * which the dashboard names against the object, not against the dataset. + */ +export function compareWindowRemedy(undeclared: readonly UndeclaredSelectionMember[]): string { + const keys = undeclared.filter((u) => u.compareWindow).map((u) => u.member); + if (keys.length === 0) return ''; + const quoted = keys.map((k) => `"${k}"`).join(', '); + return ` ${keys.length === 1 ? 'The dimension' : 'The dimensions'} ${quoted} ${keys.length === 1 ? 'is' : 'are'} the date key of ` + + 'this query\'s comparison window (`compareTo`): a dashboard compare widget lowers its date window into ' + + '`timeDimensions` under the filtered field\'s name, which is usually the dashboard date-range field. ' + + `Declare a date dimension named ${quoted} on the dataset (over that field), or set the widget's ` + + '`compareTo.dimension` to a declared date dimension (the widget then compares only over a window its ' + + 'own filter states on that dimension).'; +} + /** `measure "x", dimension "y"` — the members a refusal names, in request order. */ export function describeUndeclaredMembers(undeclared: readonly UndeclaredSelectionMember[]): string { return undeclared.map((u) => `${u.param === 'measures' ? 'measure' : 'dimension'} "${u.member}"`).join(', '); @@ -97,7 +133,9 @@ export function listMemberNames(names: readonly string[]): string { * dataset does not declare: `INVALID_FIELD` / 400 (`invalidMemberError`, * `member` / `param` / `cube` of the first undeclared entry), naming every * undeclared member, the members THIS caller may use, and the remedy — select - * a declared name, or declare the member on the dataset. + * a declared name, or declare the member on the dataset. When the member is a + * comparison window's date key ({@link compareWindowRemedy}), the refusal also + * names the compare widget's remedy. */ export function undeclaredMembersRefusal( dataset: Pick, @@ -110,7 +148,8 @@ export function undeclaredMembersRefusal( + 'answers only the members its dataset declares, by their declared names. ' + `Measures you may use: ${listMemberNames(usableDeclaredMembers(dataset.measures, admitted?.measures))}. ` + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admitted?.dimensions))}. ` - + 'Use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.', + + 'Use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.' + + compareWindowRemedy(undeclared), { member: first.member, param: first.param, cube: dataset.name }, ); } From 8d7e39c9eae6d001e53b30dd9980105e984f39a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:31:40 +0000 Subject: [PATCH 11/16] test(rest): load @objectstack/objectql at module top in the read-gate envelope pin Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- packages/rest/src/analytics-read-gate-fault-envelope.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/rest/src/analytics-read-gate-fault-envelope.test.ts b/packages/rest/src/analytics-read-gate-fault-envelope.test.ts index 0b6bdabb71e..9942d1d079e 100644 --- a/packages/rest/src/analytics-read-gate-fault-envelope.test.ts +++ b/packages/rest/src/analytics-read-gate-fault-envelope.test.ts @@ -34,6 +34,10 @@ import type { Logger } from '@objectstack/spec/contracts'; import { INTERNAL_ERROR_MESSAGE } from '@objectstack/types'; import { AnalyticsService, type AnalyticsServiceConfig } from '@objectstack/service-analytics'; import { RestServer } from './rest-server'; +// The server reaches `@objectstack/objectql` only through a dynamic import inside a +// handler; paid here at module scope so the first load lands during collection, +// not inside a clocked window (`pnpm check:test-source-alias`). +import '@objectstack/objectql'; function mockServer() { return { From 43b494b8729217bd883eb5c0d905887b9600eeef Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:32:48 +0000 Subject: [PATCH 12/16] docs(service-analytics): name the compare widget's date key in the changeset and the dashboards page Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34005-dataset-door-declared-members.md | 3 +- content/docs/ui/dashboards.mdx | 37 ++++++++++++++++--- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index 770af4fe3b1..b84adb363d6 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -8,11 +8,12 @@ Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — `skills/**` teach dataset selections only by the dataset's own names (objectstack-ui: a report selects `rows` and `values` "from that dataset"), which is what the door now enforces; `content/docs/data-modeling/analytics.mdx` states the rule in this change. - + **BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. - A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. - The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. - A declared member over a field the object does not have is still refused `400 INVALID_FIELD`; on the dataset door its message now points at the member's declared field (point it at one of the object's fields, or remove the member) instead of the cube door's hint that undeclared members are inferred or allowed. The cube door's message is unchanged. +- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares and its `compareTo.dimension` names no declared one. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. For this class the refusal names the remedy in its message: declare a date dimension named after the date-range field (over that field), or set the widget's `compareTo.dimension` to a declared date dimension, which then compares only over a window the widget's own filter states on that dimension. - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index a84c2b15e86..dc6a853d9e7 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -103,7 +103,7 @@ selects `dimensions` (X / group / split) and `values` (the measures to plot): | `layout` | `object` | optional | Grid position and size (auto-flowed into the grid when omitted) | | `chartConfig` | `object` | optional | Chart **appearance**: `title`, `subtitle`, `description`, `colors`, `height`, `showLegend`, `showDataLabels`, `annotations`, `interaction`. The bound dataset decides which series exist and which column each one reads, so `type`, `xAxis`, `yAxis` and `series` are refused here — see below | | `colorVariant` | `enum` | optional | KPI/card accent color | -| `compareTo` | `object` | optional | Period-over-period comparison: `{ kind: 'previousPeriod' \| 'previousYear', dimension? }`. Omit `dimension` when the selection dates exactly one time dimension — the runtime resolves it, and errors naming the candidates rather than guessing when it cannot. The delta is coloured by the measure's `polarity`: `'lower'` draws a rise red and a fall green, `'neutral'` draws neither; undeclared, a rise is green. | +| `compareTo` | `object` | optional | Period-over-period comparison: `{ kind: 'previousPeriod' \| 'previousYear', dimension? }`. Omit `dimension` when the selection dates exactly one time dimension — the runtime resolves it, and errors naming the candidates rather than guessing when it cannot. The window's date key must be a dimension the dataset declares — see [The Date Key of a Compare Widget](#the-date-key-of-a-compare-widget). The delta is coloured by the measure's `polarity`: `'lower'` draws a rise red and a fall green, `'neutral'` draws neither; undeclared, a rise is green. | | `options` | `object` | optional | The query keys below. Presentation does not go here — see below | ### What `chartConfig` does **not** carry @@ -494,11 +494,36 @@ both refuse the board rather than shipping it — see Opt a single widget out with `filterBindings: { : false }` (see [Per-Widget Filter Bindings](#per-widget-filter-bindings) below). -This describes the **authorable surface** — what a dashboard may declare, and what -author-time validation accepts. It is not a claim about the analytics query API, -which does accept an object's own field as an ad-hoc dimension without the dataset -declaring it; `widget-dimension-unknown` is what holds the line for authored -dashboards. +The dataset query that renders a widget holds the same line at runtime: it +answers only the measures and dimensions its dataset declares, by their declared +names, and refuses an object's own field named as a dimension with +`400 INVALID_FIELD` (see [Datasets](/docs/data-modeling/analytics)). +`widget-dimension-unknown` refuses the same mistake at author time. Only the +cube query (`POST /analytics/query`), which is not a dataset, still groups by an +object's own field without a declaration. + +### The Date Key of a Compare Widget + +A widget with `compareTo` compares over a date window, and the runtime takes that +window from the widget's filter, the dashboard's `dateRange` filter included. The +window is sent to the dataset query as a time dimension named after the filtered +**field** (`dateRange.field`, `created_at` by default). A dataset query answers +only declared dimensions, so that field name must also be the **name** of a date +dimension the dataset declares: + +```typescript +dimensions: [ + // The dashboard's dateRange filters `close_date`, so a compare widget's + // window arrives as the dimension "close_date". + { name: 'close_date', label: 'Close date', field: 'close_date', type: 'date' }, +], +``` + +Otherwise the widget's query is refused with `400 INVALID_FIELD`, and the message +names this remedy: declare a date dimension named after the date-range field, or +set the widget's `compareTo.dimension` to a declared date dimension. With the +second, the widget compares only over a window its own filter states on that +dimension. No author-time rule checks a compare widget's date key yet. ### Filtering on a Related Record's Field From 75e3e0618cb94a53f65b32ab6a9eaef7374a1659 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:16:27 +0000 Subject: [PATCH 13/16] fix(service-analytics): name one remedy for an undeclared compare-window date key The refusal, the dashboards page, the changeset bullet and the ADR-0087 marker no longer offer pointing `compareTo.dimension` at a declared dimension: the renderer still lowers the dashboard window on the undeclared field, so the comparison is dropped or refused again. The one remedy left is declaring a date dimension named after the date-range field. The plural arm now reads "The dimensions "a" and "b" are the date keys" and "Declare a date dimension for each ... named "a" and "b"". New pins: a selection whose compareTo.dimension names a declared dimension beside a second, undeclared dated entry, and the plural arm. The changeset's Skills-docs line now cites the skills follow-up for the compare widget's date key. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34005-dataset-door-declared-members.md | 6 +- content/docs/ui/dashboards.mdx | 6 +- .../dataset-query-declared-members.test.ts | 59 ++++++++++++++++++- .../src/dataset-declared-members.ts | 24 +++++--- 4 files changed, 79 insertions(+), 16 deletions(-) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index b84adb363d6..767e86cf6a8 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -6,14 +6,14 @@ fix(service-analytics)!: the dataset query door refuses measures and dimensions Clause-②: no (narrowing) Metadata-protocol: none -Skills-docs: none — `skills/**` teach dataset selections only by the dataset's own names (objectstack-ui: a report selects `rows` and `values` "from that dataset"), which is what the door now enforces; `content/docs/data-modeling/analytics.mdx` states the rule in this change. +Skills-docs: follow-up #34328 — `skills/**` teach dataset selections by the dataset's declared measures and dimensions (objectstack-ui: a report selects `rows` and `values` "from that dataset"), which the door now enforces; they do not yet say that a compare widget's date key must be the name of a declared date dimension, and that teaching is carried by #34328; `content/docs/data-modeling/analytics.mdx` and `content/docs/ui/dashboards.mdx` state the rule in this change. - + **BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. - A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. - The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. - A declared member over a field the object does not have is still refused `400 INVALID_FIELD`; on the dataset door its message now points at the member's declared field (point it at one of the object's fields, or remove the member) instead of the cube door's hint that undeclared members are inferred or allowed. The cube door's message is unchanged. -- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares and its `compareTo.dimension` names no declared one. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. For this class the refusal names the remedy in its message: declare a date dimension named after the date-range field (over that field), or set the widget's `compareTo.dimension` to a declared date dimension, which then compares only over a window the widget's own filter states on that dimension. +- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. For this class the refusal names the remedy in its message: declare a date dimension named after the date-range field (over that field). - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index dc6a853d9e7..27f0c6e0657 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -520,10 +520,8 @@ dimensions: [ ``` Otherwise the widget's query is refused with `400 INVALID_FIELD`, and the message -names this remedy: declare a date dimension named after the date-range field, or -set the widget's `compareTo.dimension` to a declared date dimension. With the -second, the widget compares only over a window its own filter states on that -dimension. No author-time rule checks a compare widget's date key yet. +names the remedy: declare a date dimension named after the date-range field. +No author-time rule checks a compare widget's date key yet. ### Filtering on a Related Record's Field diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts index c105fba2264..99947f5d341 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -230,8 +230,63 @@ describe('queryDataset refuses a selection member the dataset does not declare', expect(messageOf(e)).toContain( 'The dimension "closed_on" is the date key of this query\'s comparison window (`compareTo`)', ); - expect(messageOf(e)).toContain('Declare a date dimension named "closed_on" on the dataset (over that field)'); - expect(messageOf(e)).toContain("or set the widget's `compareTo.dimension` to a declared date dimension"); + expect(messageOf(e)).toContain('Declare a date dimension named "closed_on" on the dataset (over that field).'); + expect(messageOf(e)).not.toContain('compareTo.dimension'); + expect(reads).toEqual([]); + }); + + it('a comparison whose compareTo.dimension names a declared dimension still refuses a second, undeclared dated key, with the one remedy', async () => { + // Setting `compareTo.dimension` is no remedy: the renderer still lowers the + // dashboard window on the undeclared field beside the declared one. + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['revenue'], + timeDimensions: [ + { dimension: 'close_month', dateRange: ['2026-01-01', '2026-03-31'] }, + { dimension: 'closed_on', dateRange: ['2026-01-01', '2026-03-31'] }, + ], + compareTo: { kind: 'previousPeriod', dimension: 'close_month' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'closed_on', param: 'timeDimensions', cube: 'pipeline' }); + expect(messageOf(e)).toContain('The dataset "pipeline" does not declare the dimension "closed_on".'); + expect(messageOf(e)).toContain( + 'The dimension "closed_on" is the date key of this query\'s comparison window (`compareTo`)', + ); + expect(messageOf(e)).toContain('Declare a date dimension named "closed_on" on the dataset (over that field).'); + expect(messageOf(e)).not.toContain('compareTo.dimension'); + expect(reads).toEqual([]); + }); + + it('two undeclared comparison date keys are named together, in the plural, with one remedy', async () => { + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['revenue'], + timeDimensions: [ + { dimension: 'closed_on', dateRange: ['2026-01-01', '2026-03-31'] }, + { dimension: 'created_at', dateRange: ['2026-01-01', '2026-03-31'] }, + ], + compareTo: { kind: 'previousYear' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'closed_on', param: 'timeDimensions', cube: 'pipeline' }); + expect(messageOf(e)).toContain( + 'The dimensions "closed_on" and "created_at" are the date keys of this query\'s comparison window (`compareTo`)', + ); + expect(messageOf(e)).toContain( + 'Declare a date dimension for each on the dataset, named "closed_on" and "created_at", each over the field of the same name.', + ); + expect(messageOf(e)).not.toContain('compareTo.dimension'); expect(reads).toEqual([]); }); diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts index 66df0586d74..e0e203e9d11 100644 --- a/packages/services/service-analytics/src/dataset-declared-members.ts +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -94,17 +94,27 @@ export function undeclaredSelectionMembers( * when no undeclared member is one. A bare "not declared" does not tell a * dashboard author what to change: the key is the dashboard date-range field, * which the dashboard names against the object, not against the dataset. + * + * It names one remedy only, declaring a date dimension named after the key. + * Pointing the widget's `compareTo.dimension` at a declared dimension is not + * one: the renderer still lowers the dashboard's window on the undeclared + * field, so the comparison is either dropped or refused again. */ export function compareWindowRemedy(undeclared: readonly UndeclaredSelectionMember[]): string { const keys = undeclared.filter((u) => u.compareWindow).map((u) => u.member); if (keys.length === 0) return ''; - const quoted = keys.map((k) => `"${k}"`).join(', '); - return ` ${keys.length === 1 ? 'The dimension' : 'The dimensions'} ${quoted} ${keys.length === 1 ? 'is' : 'are'} the date key of ` - + 'this query\'s comparison window (`compareTo`): a dashboard compare widget lowers its date window into ' - + '`timeDimensions` under the filtered field\'s name, which is usually the dashboard date-range field. ' - + `Declare a date dimension named ${quoted} on the dataset (over that field), or set the widget's ` - + '`compareTo.dimension` to a declared date dimension (the widget then compares only over a window its ' - + 'own filter states on that dimension).'; + const quoted = keys.map((k) => `"${k}"`); + const list = quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`; + const one = keys.length === 1; + return ` ${one ? `The dimension ${list} is the date key` : `The dimensions ${list} are the date keys`} of ` + + `this query's comparison window (\`compareTo\`): a dashboard compare widget lowers ` + + (one + ? 'its date window into `timeDimensions` under the filtered field\'s name, ' + : 'every date window its filter states into `timeDimensions`, each under its filtered field\'s name, ') + + 'which is usually the dashboard date-range field. ' + + (one + ? `Declare a date dimension named ${list} on the dataset (over that field).` + : `Declare a date dimension for each on the dataset, named ${list}, each over the field of the same name.`); } /** `measure "x", dimension "y"` — the members a refusal names, in request order. */ From ab7c7ca8096b976571ff85b3db09208ec4a69fbd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:51:56 +0000 Subject: [PATCH 14/16] fix(service-analytics): a compare-window date key no dimension can be named gets no declare-it remedy A dotted relationship.field key (or any key the dimension-name grammar refuses) cannot be a declared dimension's name, so the refusal now says the comparison needs a date field of the dataset's own object that a declared date dimension names; a nameable key keeps its remedy, and a mixed set scopes each sentence to the keys it is true for. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../dataset-query-declared-members.test.ts | 65 +++++++++++++++++ .../dotted-path-preview-parity.test.ts | 24 +++++++ .../src/dataset-declared-members.ts | 71 +++++++++++++++---- 3 files changed, 148 insertions(+), 12 deletions(-) diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts index 99947f5d341..94a1b37feb1 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -28,6 +28,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { DatasetSchema, type Dataset } from '@objectstack/spec/ui'; import { AnalyticsServicePlugin } from '../plugin.js'; import type { AnalyticsService } from '../analytics-service.js'; +import { compareWindowRemedy } from '../dataset-declared-members.js'; const ME = { userId: 'u_me', tenantId: 'org_a' } as ExecutionContext; const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; @@ -290,6 +291,39 @@ describe('queryDataset refuses a selection member the dataset does not declare', expect(reads).toEqual([]); }); + it('mixed comparison date keys: a related record\'s field gets the own-object requirement, a nameable key keeps its declare-it remedy', async () => { + // Seat ruling (option A): a dotted key cannot be a dimension name, so no + // sentence tells the author to declare a dimension named after it. + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['revenue'], + timeDimensions: [ + { dimension: 'closed_on', dateRange: ['2026-01-01', '2026-03-31'] }, + { dimension: 'account.signed_at', dateRange: ['2026-01-01', '2026-03-31'] }, + ], + compareTo: { kind: 'previousPeriod' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'closed_on', param: 'timeDimensions', cube: 'pipeline' }); + expect(messageOf(e)).toContain( + 'The dimensions "closed_on" and "account.signed_at" are the date keys of this query\'s comparison window (`compareTo`)', + ); + expect(messageOf(e)).toContain('"account.signed_at" cannot be a dimension name'); + expect(messageOf(e)).toContain( + 'this comparison cannot run on a dataset query unless that date field is a field of the dataset\'s own object that a declared date dimension names.', + ); + expect(messageOf(e)).toContain( + 'For the key that can be a dimension name, declare a date dimension named "closed_on" on the dataset (over that field).', + ); + expect(messageOf(e)).not.toMatch(/declare a date dimension[^.]*"account\.signed_at"/i); + expect(reads).toEqual([]); + }); + it('CONTROL: the same undeclared time dimension with no comparison gets no compare-widget remedy', async () => { const { service } = await boot(); const e = await service @@ -389,3 +423,34 @@ describe('the source-field gates word their remedy for the door that asked', () expect(messageOf(dimension)).not.toContain('The dataset declares'); }); }); + +describe('compareWindowRemedy — a true sentence for every key, in every mix', () => { + const windows = (...keys: string[]) => + keys.map((member) => ({ member, param: 'timeDimensions' as const, compareWindow: true })); + const ownObject = 'is a field of the dataset\'s own object that a declared date dimension names.'; + + // [nameable keys, unnameable keys, the sentences after the intro] + for (const [nameable, unnameable, tail] of [ + [['closed_on'], [], 'Declare a date dimension named "closed_on" on the dataset (over that field).'], + [['closed_on', 'created_at'], [], 'Declare a date dimension for each on the dataset, named "closed_on" and "created_at", each over the field of the same name.'], + [[], ['account.founded_at'], `"account.founded_at" cannot be a dimension name (a dimension name is a snake_case identifier, with no dot, so a related record's field is never one), so no date dimension can be declared under it: this comparison cannot run on a dataset query unless the dashboard's date field ${ownObject}`], + [[], ['CloseDate'], `"CloseDate" cannot be a dimension name (a dimension name is a snake_case identifier, with no dot, so a related record's field is never one), so no date dimension can be declared under it: this comparison cannot run on a dataset query unless the dashboard's date field ${ownObject}`], + [[], ['account.founded_at', 'owner.hired_at'], `"account.founded_at" and "owner.hired_at" cannot be dimension names (a dimension name is a snake_case identifier, with no dot, so a related record's field is never one), so no date dimension can be declared under them: this comparison cannot run on a dataset query unless each of those date fields ${ownObject}`], + [['closed_on'], ['account.founded_at', 'owner.hired_at'], `"account.founded_at" and "owner.hired_at" cannot be dimension names (a dimension name is a snake_case identifier, with no dot, so a related record's field is never one), so no date dimension can be declared under them: this comparison cannot run on a dataset query unless each of those date fields ${ownObject} For the key that can be a dimension name, declare a date dimension named "closed_on" on the dataset (over that field).`], + [['closed_on', 'created_at'], ['account.founded_at'], `"account.founded_at" cannot be a dimension name (a dimension name is a snake_case identifier, with no dot, so a related record's field is never one), so no date dimension can be declared under it: this comparison cannot run on a dataset query unless that date field ${ownObject} For the keys that can be dimension names, declare a date dimension for each on the dataset, named "closed_on" and "created_at", each over the field of the same name.`], + ] as Array<[string[], string[], string]>) { + it(`${nameable.length} nameable, ${unnameable.length} unnameable`, () => { + const keys = [...nameable, ...unnameable]; + const text = compareWindowRemedy(windows(...keys)); + expect(text.endsWith(` ${tail}`), text).toBe(true); + expect(text).toContain(keys.length === 1 ? 'is the date key of' : 'are the date keys of'); + for (const key of unnameable) { + expect(text).not.toMatch(new RegExp(`declare a date dimension[^.]*"${key.replace('.', '\\.')}"`, 'i')); + } + }); + } + + it('CONTROL: no comparison-window key, no sentence', () => { + expect(compareWindowRemedy([{ member: 'account.founded_at', param: 'timeDimensions' }])).toBe(''); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts index 1e58ff070cb..e5cae8beef3 100644 --- a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts @@ -103,6 +103,7 @@ type Selection = { measures: string[]; runtimeFilter?: Record; timeDimensions?: Array>; + compareTo?: Record; }; const refusalOf = (p: Promise): Promise => @@ -239,6 +240,29 @@ describe('[#28555–#28558] members read through a relationship path, on the nat ); }); + it('CONTROL, in place of the served windowed key: a compare window over the backed \'account.founded_at\' is refused on every face, naming no declare-it remedy', async () => { + // A dashboard compare widget lowers a dotted date filter into this very + // key. No dimension can be named `account.founded_at` (the dimension + // name grammar has no dot), so the refusal states what the comparison + // needs instead: a date field of the dataset's own object. + const err = await undeclaredAlike( + BACKED, + { + measures: ['total'], + timeDimensions: [{ dimension: 'account.founded_at', dateRange: ['2026-01-01', '2026-01-31'] }], + compareTo: { kind: 'previousPeriod' }, + }, + 'timeDimensions', + 'account.founded_at', + ); + expect(err.message).toContain('the date key of this query\'s comparison window'); + expect(err.message).not.toMatch(/declare a date dimension named/i); + expect(err.message).toContain('"account.founded_at" cannot be a dimension name'); + expect(err.message).toContain( + 'this comparison cannot run on a dataset query unless the dashboard\'s date field is a field of the dataset\'s own object that a declared date dimension names.', + ); + }); + it('CONTROL: the native strategy serves the backed runtimeFilter member', async () => { expect(await rowsOf('native', BACKED, { dimensions: ['region'], measures: ['total'], runtimeFilter: { 'account.name': 'Acme' } }, 'region')) .toEqual([{ key: 'amer', total: 100 }, { key: 'emea', total: 30 }]); diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts index e0e203e9d11..0b0a70f0de1 100644 --- a/packages/services/service-analytics/src/dataset-declared-members.ts +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -2,6 +2,7 @@ import type { DatasetSelection } from '@objectstack/spec/contracts'; import type { Dataset } from '@objectstack/spec/ui'; +import { SnakeCaseIdentifierSchema } from '@objectstack/spec/shared'; import { invalidMemberError, type AnalyticsRequestKey } from './dataset-refusal.js'; /** @@ -89,32 +90,76 @@ export function undeclaredSelectionMembers( return undeclared; } +/** `"a"`, `"a" and "b"`, `"a", "b" and "c"`. */ +function quotedList(names: readonly string[]): string { + const quoted = names.map((k) => `"${k}"`); + return quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`; +} + +/** + * Whether `key` can be a declared dimension's name at all: the dataset + * schema's own dimension-name grammar (`SnakeCaseIdentifierSchema`) decides. + * A related record's field (`account.founded_at`) never can — the grammar + * has no dot. + */ +function canBeDimensionName(key: string): boolean { + return SnakeCaseIdentifierSchema.safeParse(key).success; +} + /** * The remedy sentence for an undeclared comparison-window date key, or `''` * when no undeclared member is one. A bare "not declared" does not tell a * dashboard author what to change: the key is the dashboard date-range field, * which the dashboard names against the object, not against the dataset. * - * It names one remedy only, declaring a date dimension named after the key. - * Pointing the widget's `compareTo.dimension` at a declared dimension is not - * one: the renderer still lowers the dashboard's window on the undeclared - * field, so the comparison is either dropped or refused again. + * For a key that can be a dimension name it names one remedy only, declaring + * a date dimension named after the key. Pointing the widget's + * `compareTo.dimension` at a declared dimension is not one: the renderer + * still lowers the dashboard's window on the undeclared field, so the + * comparison is either dropped or refused again. + * + * A key that cannot be a dimension name (a dotted `relationship.field`, or any + * key the dimension-name grammar refuses) gets no declare-it remedy, because + * no declaration can carry that name. Its sentence says what the comparison + * needs instead: the dashboard's date field must be a field of the dataset's + * own object that a declared date dimension names. When the keys are mixed, + * each kind gets its own sentence, scoped to the keys it is true for. */ export function compareWindowRemedy(undeclared: readonly UndeclaredSelectionMember[]): string { const keys = undeclared.filter((u) => u.compareWindow).map((u) => u.member); if (keys.length === 0) return ''; - const quoted = keys.map((k) => `"${k}"`); - const list = quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(', ')} and ${quoted[quoted.length - 1]}`; const one = keys.length === 1; - return ` ${one ? `The dimension ${list} is the date key` : `The dimensions ${list} are the date keys`} of ` + const nameable = keys.filter(canBeDimensionName); + const unnameable = keys.filter((k) => !canBeDimensionName(k)); + const intro = ` ${one ? `The dimension ${quotedList(keys)} is the date key` : `The dimensions ${quotedList(keys)} are the date keys`} of ` + `this query's comparison window (\`compareTo\`): a dashboard compare widget lowers ` + (one ? 'its date window into `timeDimensions` under the filtered field\'s name, ' : 'every date window its filter states into `timeDimensions`, each under its filtered field\'s name, ') - + 'which is usually the dashboard date-range field. ' - + (one - ? `Declare a date dimension named ${list} on the dataset (over that field).` - : `Declare a date dimension for each on the dataset, named ${list}, each over the field of the same name.`); + + 'which is usually the dashboard date-range field.'; + const sentences: string[] = []; + if (unnameable.length > 0) { + const single = unnameable.length === 1; + sentences.push( + (single + ? `${quotedList(unnameable)} cannot be a dimension name` + : `${quotedList(unnameable)} cannot be dimension names`) + + ' (a dimension name is a snake_case identifier, with no dot, so a related record\'s field is never one), ' + + `so no date dimension can be declared under ${single ? 'it' : 'them'}: this comparison cannot run on a dataset query ` + + `unless ${!single ? 'each of those date fields' : one ? 'the dashboard\'s date field' : 'that date field'} ` + + 'is a field of the dataset\'s own object that a declared date dimension names.', + ); + } + if (nameable.length > 0) { + const remedy = nameable.length === 1 + ? `declare a date dimension named ${quotedList(nameable)} on the dataset (over that field).` + : `declare a date dimension for each on the dataset, named ${quotedList(nameable)}, each over the field of the same name.`; + // Mixed: scope the declare-it remedy to the keys it is true for. + if (unnameable.length === 0) sentences.push(`D${remedy.slice(1)}`); + else if (nameable.length === 1) sentences.push(`For the key that can be a dimension name, ${remedy}`); + else sentences.push(`For the keys that can be dimension names, ${remedy}`); + } + return `${intro} ${sentences.join(' ')}`; } /** `measure "x", dimension "y"` — the members a refusal names, in request order. */ @@ -145,7 +190,9 @@ export function listMemberNames(names: readonly string[]): string { * undeclared member, the members THIS caller may use, and the remedy — select * a declared name, or declare the member on the dataset. When the member is a * comparison window's date key ({@link compareWindowRemedy}), the refusal also - * names the compare widget's remedy. + * says what the compare widget needs: a date dimension named after the key, + * or, for a key no dimension can be named (a related record's field), a date + * field of the dataset's own object. */ export function undeclaredMembersRefusal( dataset: Pick, From d782833df35dca258250609d42f377ee71330439 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:55:21 +0000 Subject: [PATCH 15/16] docs(service-analytics): a dotted compare-window date key is a break with no in-dataset remedy The dashboards page, the changeset bullet and the ADR-0087 marker now say that a related record's dotted date field cannot be a dimension name, so the comparison needs a date field of the dataset's own object. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34005-dataset-door-declared-members.md | 4 ++-- content/docs/ui/dashboards.mdx | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index 767e86cf6a8..1fd074660c4 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -8,12 +8,12 @@ Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: follow-up #34328 — `skills/**` teach dataset selections by the dataset's declared measures and dimensions (objectstack-ui: a report selects `rows` and `values` "from that dataset"), which the door now enforces; they do not yet say that a compare widget's date key must be the name of a declared date dimension, and that teaching is carried by #34328; `content/docs/data-modeling/analytics.mdx` and `content/docs/ui/dashboards.mdx` state the rule in this change. - + **BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. - A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. - The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. - A declared member over a field the object does not have is still refused `400 INVALID_FIELD`; on the dataset door its message now points at the member's declared field (point it at one of the object's fields, or remove the member) instead of the cube door's hint that undeclared members are inferred or allowed. The cube door's message is unchanged. -- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. For this class the refusal names the remedy in its message: declare a date dimension named after the date-range field (over that field). +- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. When the date-range field is a field of the dataset's own object, the refusal names the remedy in its message: declare a date dimension named after it (over that field). When it is a related record's field — a dotted `relationship.field` such as `account.signed_at`, which a dashboard filter may name and which a dataset query used to answer through the dataset's `include` — this is a break with no in-dataset remedy: a dimension name is a snake_case identifier with no dot, so no declaration can carry that key, and declaring a dimension over the path under another name does not help, because the widget still sends the window under the dotted name. The refusal says so and names what the comparison needs: a date field of the dataset's own object that a declared date dimension names. The renderer mapping a dotted date key onto a declared dimension over that path is carried by #34350. - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index 27f0c6e0657..2d9f57d9961 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -103,7 +103,7 @@ selects `dimensions` (X / group / split) and `values` (the measures to plot): | `layout` | `object` | optional | Grid position and size (auto-flowed into the grid when omitted) | | `chartConfig` | `object` | optional | Chart **appearance**: `title`, `subtitle`, `description`, `colors`, `height`, `showLegend`, `showDataLabels`, `annotations`, `interaction`. The bound dataset decides which series exist and which column each one reads, so `type`, `xAxis`, `yAxis` and `series` are refused here — see below | | `colorVariant` | `enum` | optional | KPI/card accent color | -| `compareTo` | `object` | optional | Period-over-period comparison: `{ kind: 'previousPeriod' \| 'previousYear', dimension? }`. Omit `dimension` when the selection dates exactly one time dimension — the runtime resolves it, and errors naming the candidates rather than guessing when it cannot. The window's date key must be a dimension the dataset declares — see [The Date Key of a Compare Widget](#the-date-key-of-a-compare-widget). The delta is coloured by the measure's `polarity`: `'lower'` draws a rise red and a fall green, `'neutral'` draws neither; undeclared, a rise is green. | +| `compareTo` | `object` | optional | Period-over-period comparison: `{ kind: 'previousPeriod' \| 'previousYear', dimension? }`. Omit `dimension` when the selection dates exactly one time dimension — the runtime resolves it, and errors naming the candidates rather than guessing when it cannot. The window's date key must be a dimension the dataset declares, so the date field it comes from must be a field of the dataset's own object — see [The Date Key of a Compare Widget](#the-date-key-of-a-compare-widget). The delta is coloured by the measure's `polarity`: `'lower'` draws a rise red and a fall green, `'neutral'` draws neither; undeclared, a rise is green. | | `options` | `object` | optional | The query keys below. Presentation does not go here — see below | ### What `chartConfig` does **not** carry @@ -508,8 +508,9 @@ A widget with `compareTo` compares over a date window, and the runtime takes tha window from the widget's filter, the dashboard's `dateRange` filter included. The window is sent to the dataset query as a time dimension named after the filtered **field** (`dateRange.field`, `created_at` by default). A dataset query answers -only declared dimensions, so that field name must also be the **name** of a date -dimension the dataset declares: +only declared dimensions, so when that field is a field of the dataset's own +object, its name must also be the **name** of a date dimension the dataset +declares: ```typescript dimensions: [ @@ -521,6 +522,18 @@ dimensions: [ Otherwise the widget's query is refused with `400 INVALID_FIELD`, and the message names the remedy: declare a date dimension named after the date-range field. + +A date field of a related record — a dotted `relationship.field` such as +`account.signed_at`, which a dashboard filter may otherwise name (see +[Filtering on a Related Record's Field](#filtering-on-a-related-records-field)) — +has no such remedy. A dimension name is a snake_case identifier with no dot, so +no dimension can carry that key, and the dataset query refuses the comparison +with `400 INVALID_FIELD`; the message says the comparison needs a date field of +the dataset's own object that a declared date dimension names. Declaring a +dimension over the path under another name does not help, because the widget +still sends the window under the dotted field's name. A compare widget's date +window must therefore be a field of the dataset's own object. + No author-time rule checks a compare widget's date key yet. ### Filtering on a Related Record's Field From 7a6aa7d0edb698dfef0e5e628978d728072e989e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:58:38 +0000 Subject: [PATCH 16/16] fix(service-analytics): a refusal whose only member is an unnameable compare-window date key tells the author to declare nothing The select-or-declare sentence ("use one of these, or declare the member on the dataset and query it by that name") preceded the compare-window sentence even when the only undeclared member was a dotted date key, which no declaration can carry. It now covers only the members it can fix: left out when every undeclared member is such a key, scoped by name when some are. Which members are refused, the code, status, member/param/cube and the nameable-key text are unchanged. Co-Authored-By: Claude --- .../34005-dataset-door-declared-members.md | 4 +- content/docs/ui/dashboards.mdx | 5 +- .../dataset-query-declared-members.test.ts | 57 +++++++++++++++++++ .../dotted-path-preview-parity.test.ts | 2 + .../src/dataset-declared-members.ts | 18 +++++- 5 files changed, 80 insertions(+), 6 deletions(-) diff --git a/.changeset/34005-dataset-door-declared-members.md b/.changeset/34005-dataset-door-declared-members.md index 1fd074660c4..d28ffec2321 100644 --- a/.changeset/34005-dataset-door-declared-members.md +++ b/.changeset/34005-dataset-door-declared-members.md @@ -13,7 +13,7 @@ Skills-docs: follow-up #34328 — `skills/**` teach dataset selections by the da **BREAKING** for a caller of `POST /api/v1/analytics/dataset/query` (and each query of `/analytics/dataset/query/batch`), or of `AnalyticsService.queryDataset` in process, that names a measure or dimension the dataset does not declare. Such a selection used to be answered: the analytics service minted an aggregate for an undeclared measure (`count` counted rows, a raw field such as `amount` was summed, `amount_sum` likewise, a `.revenue` spelling was resolved) and grouped by a raw field named as a dimension or a time dimension, so a dashboard tile could show a number labelled as a dataset metric that the dataset never defines. ADR-0021 makes the dataset a declarative, closed surface, and the AI tool `query_dataset` already refused these members; every face of a dataset query now reads the dataset the same way. - A name in `selection.measures`, `selection.dimensions` or a `selection.timeDimensions` entry's `dimension` that is not one of the dataset's own `measures[].name` / `dimensions[].name`, spelled exactly so, is refused `400 INVALID_FIELD` before anything is read; the REST body is `{ code, message }`, and in process the thrown error also carries `member`, `param` and `cube` (the dataset's name). This applies to a saved `datasetName` and to an inline `dataset`, which is judged against its own `measures` and `dimensions`. -- The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. +- The refusal names every undeclared member, the measures and dimensions THIS caller may use (never a withheld member or one over an `internal` field), and the fix: use one of those, or declare the member on the dataset and query it by that name. That fix is not offered for a compare window's date key that no dimension can be named (below), because it cannot apply to it. - A declared member over a field the object does not have is still refused `400 INVALID_FIELD`; on the dataset door its message now points at the member's declared field (point it at one of the object's fields, or remove the member) instead of the cube door's hint that undeclared members are inferred or allowed. The cube door's message is unchanged. -- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. When the date-range field is a field of the dataset's own object, the refusal names the remedy in its message: declare a date dimension named after it (over that field). When it is a related record's field — a dotted `relationship.field` such as `account.signed_at`, which a dashboard filter may name and which a dataset query used to answer through the dataset's `include` — this is a break with no in-dataset remedy: a dimension name is a snake_case identifier with no dot, so no declaration can carry that key, and declaring a dimension over the path under another name does not help, because the widget still sends the window under the dotted name. The refusal says so and names what the comparison needs: a date field of the dataset's own object that a declared date dimension names. The renderer mapping a dotted date key onto a declared dimension over that path is carried by #34350. +- **A dashboard compare widget can be refused by this change, and no save gate catches it yet.** A widget with `compareTo` sends its date window, the dashboard's `dateRange` filter included, as a `timeDimensions` entry named after the filtered field (`dateRange.field`, `created_at` by default). The date-range field resolves against the object, not the dataset, so a dashboard that passes every save and publish check is refused when that field is not also the name of a date dimension the dataset declares. A census of the dashboards authored in this repository found none in this class; a dashboard saved at runtime or by a third party has no such guarantee. When the date-range field is a field of the dataset's own object, the refusal names the remedy in its message: declare a date dimension named after it (over that field). When it is a related record's field — a dotted `relationship.field` such as `account.signed_at`, which a dashboard filter may name and which a dataset query used to answer through the dataset's `include` — this is a break with no in-dataset remedy: a dimension name is a snake_case identifier with no dot, so no declaration can carry that key, and declaring a dimension over the path under another name does not help, because the widget still sends the window under the dotted name. The refusal says so, tells the author to declare nothing for that key, and names what the comparison needs: a date field of the dataset's own object that a declared date dimension names. The renderer mapping a dotted date key onto a declared dimension over that path is carried by #34350. - Unchanged: a missing dataset is still `404 NOT_FOUND` first; a caller who may not read the dataset's object still gets the read refusal (`403`), never a member list; a declared member over a field the caller may not read is still `403 PERMISSION_DENIED`; `runtimeFilter` keys are fields, not members, and are judged as before. The cube query (`POST /api/v1/analytics/query`) is not a dataset and keeps its ad-hoc members. diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index 2d9f57d9961..9caf5f02de6 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -528,8 +528,9 @@ A date field of a related record — a dotted `relationship.field` such as [Filtering on a Related Record's Field](#filtering-on-a-related-records-field)) — has no such remedy. A dimension name is a snake_case identifier with no dot, so no dimension can carry that key, and the dataset query refuses the comparison -with `400 INVALID_FIELD`; the message says the comparison needs a date field of -the dataset's own object that a declared date dimension names. Declaring a +with `400 INVALID_FIELD`; the message offers no declaration for that key and +says the comparison needs a date field of the dataset's own object that a +declared date dimension names. Declaring a dimension over the path under another name does not help, because the widget still sends the window under the dotted field's name. A compare widget's date window must therefore be a field of the dataset's own object. diff --git a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts index 94a1b37feb1..86fe0494d6f 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-query-declared-members.test.ts @@ -321,6 +321,63 @@ describe('queryDataset refuses a selection member the dataset does not declare', 'For the key that can be a dimension name, declare a date dimension named "closed_on" on the dataset (over that field).', ); expect(messageOf(e)).not.toMatch(/declare a date dimension[^.]*"account\.signed_at"/i); + // The select-or-declare sentence names the member it is for, never the dotted key. + expect(messageOf(e)).toContain( + 'For the dimension "closed_on", use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.', + ); + expect(reads).toEqual([]); + }); + + it('a related record\'s field as the only undeclared member: the refusal tells the author to declare nothing', async () => { + // Seat ruling (option A): the message must be true for that class. The + // select-or-declare sentence would name the dotted key, which no + // declaration can carry, so it is left out; the compare-window sentence is + // the whole remedy. + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['revenue'], + timeDimensions: [{ dimension: 'account.signed_at', dateRange: ['2026-01-01', '2026-03-31'] }], + compareTo: { kind: 'previousPeriod' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'account.signed_at', param: 'timeDimensions', cube: 'pipeline' }); + expect(messageOf(e)).toContain('Dimensions you may use: stage, region, close_month. The dimension "account.signed_at" is the date key'); + expect(messageOf(e)).not.toMatch(/\bdeclare (the member|a date dimension named)/i); + expect(messageOf(e)).not.toContain('Use one of these'); + expect(messageOf(e)).toContain( + '"account.signed_at" cannot be a dimension name (a dimension name is a snake_case identifier, with no dot, so a related record\'s field is never one), ' + + 'so no date dimension can be declared under it: this comparison cannot run on a dataset query unless the dashboard\'s date field ' + + 'is a field of the dataset\'s own object that a declared date dimension names.', + ); + expect(reads).toEqual([]); + }); + + it('a related record\'s date key beside an undeclared measure: the select-or-declare sentence names the measure only', async () => { + const { service, reads } = await boot(); + const e = await service + .queryDataset( + PIPELINE, + { + measures: ['amount_sum'], + timeDimensions: [{ dimension: 'account.signed_at', dateRange: ['2026-01-01', '2026-03-31'] }], + compareTo: { kind: 'previousPeriod' }, + } as never, + ADMIN, + ) + .catch((err) => err); + expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'amount_sum', param: 'measures', cube: 'pipeline' }); + expect(messageOf(e)).toContain('does not declare the measure "amount_sum", dimension "account.signed_at".'); + expect(messageOf(e)).toContain( + 'For the measure "amount_sum", use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.', + ); + expect(messageOf(e)).not.toContain('Use one of these'); + expect(messageOf(e)).toContain('"account.signed_at" cannot be a dimension name'); + expect(messageOf(e)).not.toMatch(/declare a date dimension[^.]*"account\.signed_at"/i); expect(reads).toEqual([]); }); diff --git a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts index e5cae8beef3..0368450ac2e 100644 --- a/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts +++ b/packages/services/service-analytics/src/__tests__/dotted-path-preview-parity.test.ts @@ -257,6 +257,8 @@ describe('[#28555–#28558] members read through a relationship path, on the nat ); expect(err.message).toContain('the date key of this query\'s comparison window'); expect(err.message).not.toMatch(/declare a date dimension named/i); + // Nor the generic select-or-declare sentence: the key is the only member. + expect(err.message).not.toContain('declare the member on the dataset'); expect(err.message).toContain('"account.founded_at" cannot be a dimension name'); expect(err.message).toContain( 'this comparison cannot run on a dataset query unless the dashboard\'s date field is a field of the dataset\'s own object that a declared date dimension names.', diff --git a/packages/services/service-analytics/src/dataset-declared-members.ts b/packages/services/service-analytics/src/dataset-declared-members.ts index 0b0a70f0de1..17f2d8f2442 100644 --- a/packages/services/service-analytics/src/dataset-declared-members.ts +++ b/packages/services/service-analytics/src/dataset-declared-members.ts @@ -193,6 +193,13 @@ export function listMemberNames(names: readonly string[]): string { * says what the compare widget needs: a date dimension named after the key, * or, for a key no dimension can be named (a related record's field), a date * field of the dataset's own object. + * + * The select-or-declare sentence covers only the members it can fix. A + * comparison window's date key that cannot be a dimension name is never + * covered by it: the widget sends the window under that very name, which no + * declaration can carry. When every undeclared member is such a key, the + * sentence is left out and the compare-window sentence is the whole remedy; + * when some are, it names the members it is for. */ export function undeclaredMembersRefusal( dataset: Pick, @@ -200,12 +207,19 @@ export function undeclaredMembersRefusal( admitted: { measures: ReadonlySet; dimensions: ReadonlySet } | undefined, ): Error { const first = undeclared[0]; + // A comparison window's date key no dimension can be named is not fixed by + // selecting or declaring it: compareWindowRemedy says what it needs instead. + const fixable = undeclared.filter((u) => !(u.compareWindow && !canBeDimensionName(u.member))); + const selectOrDeclare = fixable.length === 0 + ? '' + : ` ${fixable.length === undeclared.length ? 'Use' : `For the ${describeUndeclaredMembers(fixable)}, use`} one of these, ` + + 'or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.'; return invalidMemberError( `The dataset "${dataset.name}" does not declare the ${describeUndeclaredMembers(undeclared)}. A dataset query ` + 'answers only the members its dataset declares, by their declared names. ' + `Measures you may use: ${listMemberNames(usableDeclaredMembers(dataset.measures, admitted?.measures))}. ` - + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admitted?.dimensions))}. ` - + 'Use one of these, or declare the member on the dataset (its `measures` or `dimensions`) and query it by that name.' + + `Dimensions you may use: ${listMemberNames(usableDeclaredMembers(dataset.dimensions, admitted?.dimensions))}.` + + selectOrDeclare + compareWindowRemedy(undeclared), { member: first.member, param: first.param, cube: dataset.name }, );