Skip to content

Commit b4ce310

Browse files
fix(service-analytics)!: query_dataset refuses measures and dimensions the dataset does not declare (#33958)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbKnsd8ZLsq9hBbRRm5JvJb2)_ Fixes #33745 Clause-②: no (narrowing) — query_dataset stops accepting measures and dimensions the dataset does not declare; one CONTRACT_REVIEW_TIER review owed before the queue Metadata-protocol: none Skills-docs: none — `skills/**` and `content/docs/**` teach no raw field or ad-hoc `count` through `query_dataset`; the MCP-served skill text (`packages/mcp/src/skill-md.ts`) already says `selection` takes members "by the names `list_datasets` gives", which is what is now enforced. ## 维护者速读 - **改了什么**:AI 的数据集查询工具 `query_dataset` 现在只接受数据集里声明过的指标和维度;传入原始字段(如 `amount`)、临时的 `count` 或未声明的维度时,直接返回 400 `INVALID_FIELD`,并列出该用户可用的指标与维度。 - **为什么改**:之前这类请求会被分析服务临时拼出一个聚合并照常返回,答案的「来源」却把它标成数据集的正式指标(「来源:指标 amount · 数据集 …」),把非指标口径冒充成治理指标;ADR-0149 规定数据集是唯一的声明定义。 - **风险与回滚**:对 AI/MCP 调用方是收紧(BREAKING):以前能答的未声明成员现在被拒,模型需改选声明成员或退回对象查询(非指标口径)。REST 数据集接口、仪表盘、报表不走此工具,不受影响。回滚 = revert 本 PR。 - **先看**:`packages/services/service-analytics/src/dataset-tools.ts` 的 `assertDeclaredMembers`(判定与报错文案,只列本用户可见成员);同文件 `queryDataset` 中调用它的位置(在数据集解析之后、任何读取之前);测试 `src/__tests__/dataset-tools.test.ts` 新增的 describe 块。 - **两分钟验证**:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/dataset-tools.test.ts`,预期 43 个用例全部通过,其中「refuses a member the dataset does not declare」一组 11 个。 - **需要你做的**:无,席位落地(落地前欠一次 CONTRACT_REVIEW_TIER 契约复审记录)。 ## What changes - `createDatasetTools` (`@objectstack/service-analytics`, the one executor behind the product AI's chat tool and the MCP `query_dataset` on both bridges) judges the selection against the dataset it resolved, after the dataset resolves and before anything is read. 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` is refused `400 INVALID_FIELD` with `member`, `param` and `cube` (the dataset name), through `invalidMemberError`, the envelope the service's member-level refusals already answer. No new error code. - The message names the measures and dimensions this caller may use (the catalogue admission `list_datasets` lists from), never a withheld member or one over an `internal` field, and points at the D3 fallback (object query tools, 非指标口径). - Judged against every declared member, so a declared member the caller may not read still reaches the service's own field gate (`403 PERMISSION_DENIED`), unchanged. A missing or hidden dataset is still `404 NOT_FOUND` first. `totals.groupings` and `order` keys are already judged downstream against the selected members. - `query_dataset`'s tool description now states the rule. - Changeset `.changeset/33745-query-dataset-declared-members.md`: patch (`Metadata-protocol: none`), BREAKING banner, ADR-0087 disposition `not-required (no-migration-prescription)`. ## Tests - New top-level `describe('query_dataset refuses a member the dataset does not declare')` in `packages/services/service-analytics/src/__tests__/dataset-tools.test.ts`: a raw field as a measure, the ad-hoc `count`, a suffix spelling `amount_sum`, a dataset-qualified `pipeline.revenue`, an undeclared measure beside a declared one, a raw field as a dimension and as a time dimension — each `INVALID_FIELD` / 400 with `member` / `param` / `cube`, on both faces (`queryDataset` and `execute`), the service never called, no read. Plus: the message names only caller-usable members; a missing or hidden dataset stays `NOT_FOUND`; two CONTROLs (every declared measure, a derived one included, and dimensions are served; a declared time dimension reaches the service). - Red first on the `origin/main` executor: 7 failed / 35 passed (before the qualified-spelling case was added). - Ablation 1 (the call to `assertDeclaredMembers` removed, via `scripts/ablation-replace.mjs`, anchor 1 -> 0): 8 failed / 35 passed; restored, blob equal to HEAD, `git diff HEAD` empty. - Ablation 2 (the caller-visible filter on the named members widened to every declared member): 1 failed (`expected ... not to contain 'margin_total'`); restored the same way. ## Acceptance notes - Hypothesis readings: H1 held (on `origin/main` the executor served `measures: ['amount']`, `['count']`, `dimensions: ['amount']`, `pipeline.revenue` and `pipeline.stage`, each with provenance citing the raw name as a member). H2: the MCP tool (HTTP and stdio bridges, `packages/runtime/src/domains/mcp.ts`) and the chat registry face share this executor, so one refusal covers them; the REST door `POST /analytics/dataset/query` does NOT go through it (it calls `AnalyticsService.queryDataset` directly) and is not changed: it serves dashboards, reports and ad-hoc selections, and the card's ruling names the tool's executor. H3: a dataset declares no implicit `count`; `count` is minted by the service's `inferMeasure`, so it is refused here. H4: `INVALID_FIELD` / 400 (ADR-0149 D2 lists it among the codes the tool may answer; the tool invents no code). - A `dataset.member` qualified spelling of a DECLARED member is refused too: it is not a name `list_datasets` lists, and its provenance used to cite the raw spelling with no label. Called out in case a consumer relies on it. - The REST door's closed-member question and the ADR-0149 D2 line are on #34005 (maintainer decision). ## Dogfood battery (head `3f717733a13e3d0b4cbd952afa4148c5b35b196c`) - Local run: NOT MEASURED (the shared verify lock was held by long sibling suites; five attempts ended queue-timeout 99). - The battery of record is the merge group's required `Dogfood Regression Gate`, accepted as such by the seat (15:54Z condition, reading accepted 15:57Z). Its selector runs the full dogfood suite for this diff: in `ci.yml` the job's `if:` needs `filter.outputs.core != 'false'`, and the `filter` job forces `core` to `'true'` on `merge_group`; `OS_SEED_ONLY` is `queue-verdict.outputs.covered == 'true'`, and `queue-verdict` runs on `push` only, so on `merge_group` all three shards run `turbo run test --filter=@objectstack/dogfood` in full. `@objectstack/dogfood` depends on `@objectstack/service-analytics`, so its test hash moves with this diff (no cache hit). - The tree it judges is this head merged into the queue base. A red shard ejects the PR from the queue; it is then reported here with its signature, never re-queued blind. - No dogfood path selects an undeclared member today (the only `query_dataset` callers select `row_count` / `task_count`), so the battery guards against regressions rather than exercising the refusal. ## Verification Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh — readings at the final head are in the os-dev report comment on the card. Head `3f717733` is `a711894f` with `origin/main` merged (net diff byte-identical, same patch-id). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 04d4114 commit b4ce310

3 files changed

Lines changed: 183 additions & 6 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(service-analytics)!: `query_dataset` refuses measures and dimensions the dataset does not declare, naming the members the caller may use
6+
7+
Clause-②: no (narrowing) — query_dataset stops accepting measures and dimensions the dataset does not declare; one CONTRACT_REVIEW_TIER review owed before the queue
8+
Metadata-protocol: none
9+
Skills-docs: none — `skills/**` and `content/docs/**` teach no raw field or ad-hoc `count` through `query_dataset`; the MCP-served skill text (`packages/mcp/src/skill-md.ts`) already says `selection` takes members "by the names `list_datasets` gives", which is what is now enforced.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) a runtime tool input refusal: no metadata key, value or stored row changes, so `os migrate meta` has nothing to rewrite; a caller picks a declared member instead -->
12+
13+
**BREAKING** for an AI or MCP client that sends `query_dataset` (the dataset AI tool, ADR-0149) a measure or dimension the saved 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) and grouped by a raw field named as a dimension, and the answer's `provenance` then cited that ad-hoc aggregate as a governed metric of the dataset. ADR-0149 makes the dataset the one declared definition, so a member outside it is now refused before anything is read.
14+
15+
- 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` is refused `400 INVALID_FIELD` with `member`, `param` and `cube` (the dataset's name), the envelope the service's member-level refusals already answer. A `<dataset>.`-qualified spelling is not a listed name and is refused the same way; use the bare name `list_datasets` lists.
16+
- The refusal names the measures and dimensions THIS caller may use (what `list_datasets` lists for it), never a withheld member or one over an `internal` field, so the model can pick one, or fall back to the object query tools and say that no governed metric was used (非指标口径, the ADR-0149 D3 fallback).
17+
- Unchanged: a missing or hidden dataset is still `404 NOT_FOUND` first; a declared member the caller may not read is still the service's own `403 PERMISSION_DENIED`; field-level permissions apply as before. The REST door (`POST /analytics/dataset/query`), dashboards and reports do not go through this tool and are not changed.
18+
- `query_dataset`'s tool description now states the rule, so a model reads it before it calls.

‎packages/services/service-analytics/src/__tests__/dataset-tools.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,92 @@ describe('query_dataset', () => {
535535
});
536536
});
537537

538+
// [ADR-0149] The dataset is the one declared definition: `query_dataset`
539+
// answers only the members it declares. A raw field (`amount`), the
540+
// service's ad-hoc `count`, a suffix spelling (`amount_sum`) or an
541+
// undeclared dimension used to reach `service.queryDataset`, which minted an
542+
// aggregate for it, and the answer's provenance then cited that aggregate as
543+
// a governed metric. The tool refuses it before anything is read, on both
544+
// faces, naming the members this caller may use, so the model picks one or
545+
// falls back to the object query tools.
546+
describe('query_dataset refuses a member the dataset does not declare', () => {
547+
it.each([
548+
['a raw field as a measure', { measures: ['amount'] }, 'amount', 'measures'],
549+
['the ad-hoc count', { measures: ['count'] }, 'count', 'measures'],
550+
['a suffix spelling', { measures: ['amount_sum'] }, 'amount_sum', 'measures'],
551+
['a dataset-qualified spelling of a declared measure', { measures: ['pipeline.revenue'] }, 'pipeline.revenue', 'measures'],
552+
['an undeclared measure beside a declared one', { measures: ['revenue', 'amount'] }, 'amount', 'measures'],
553+
['a raw field as a dimension', { measures: ['revenue'], dimensions: ['amount'] }, 'amount', 'dimensions'],
554+
[
555+
'a raw field as a time dimension',
556+
{ measures: ['revenue'], timeDimensions: [{ dimension: 'closed_on', granularity: 'month' }] },
557+
'closed_on',
558+
'timeDimensions',
559+
],
560+
])('%s: 400 INVALID_FIELD naming the member and the declared ones, on both faces, reading nothing', async (_case, selection, member, param) => {
561+
const { service, reads } = await bootWired();
562+
const spy = vi.spyOn(service, 'queryDataset');
563+
const tools = service.datasetTools({ loadDatasets: loadSaved });
564+
const input = { datasetName: 'pipeline', selection };
565+
const direct = await tools.queryDataset(input, ADMIN).catch((e) => e);
566+
const chat = await tools.execute({ toolName: 'query_dataset', input }, ADMIN).catch((e) => e);
567+
for (const e of [direct, chat]) {
568+
expect(e).toBeInstanceOf(Error);
569+
expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member, param, cube: 'pipeline' });
570+
// The declared members the caller may use are named, so the model can pick one.
571+
for (const declared of ['revenue', 'margin_total', 'deal_count', 'margin_rate', 'stage', 'region']) {
572+
expect(messageOf(e)).toContain(declared);
573+
}
574+
}
575+
expect(spy).not.toHaveBeenCalled();
576+
expect(reads).toEqual([]);
577+
});
578+
579+
it('names only the members THIS caller may use: never a withheld one, never one over an internal field', async () => {
580+
const { service } = await bootWired();
581+
const e = await service
582+
.datasetTools({ loadDatasets: loadSaved })
583+
.queryDataset({ datasetName: 'pipeline', selection: { measures: ['amount'] } }, ME)
584+
.catch((err) => err);
585+
expect(e).toMatchObject({ code: 'INVALID_FIELD', status: 400, member: 'amount' });
586+
expect(messageOf(e)).toContain('revenue');
587+
expect(messageOf(e)).not.toContain('margin_total');
588+
expect(messageOf(e)).not.toContain('secret');
589+
});
590+
591+
it('a dataset that is missing or hidden is still NOT_FOUND first, whatever the members', async () => {
592+
const { service } = await bootWired();
593+
const tools = service.datasetTools({ loadDatasets: loadSaved });
594+
for (const datasetName of ['nope', 'locked_ds']) {
595+
await expect(
596+
tools.queryDataset({ datasetName, selection: { measures: ['amount'] } }, ME),
597+
).rejects.toMatchObject({ code: 'NOT_FOUND', status: 404 });
598+
}
599+
});
600+
601+
it('CONTROL: every declared measure (a derived one included) and dimension is served', async () => {
602+
const { service } = await bootWired([{ stage: 'won', revenue: 100 }]);
603+
const spy = vi.spyOn(service, 'queryDataset');
604+
const tools = service.datasetTools({ loadDatasets: loadSaved });
605+
const out = await tools.queryDataset(
606+
{ datasetName: 'pipeline', selection: { measures: ['revenue', 'deal_count', 'margin_rate'], dimensions: ['stage', 'region'] } },
607+
ADMIN,
608+
);
609+
expect(spy).toHaveBeenCalledTimes(1);
610+
expect(out.provenance.measures.map((m) => m.name)).toEqual(['revenue', 'deal_count', 'margin_rate']);
611+
});
612+
613+
it('CONTROL: a time dimension the dataset declares reaches the service', async () => {
614+
const { service } = await bootWired();
615+
const spy = vi.spyOn(service, 'queryDataset');
616+
await service
617+
.datasetTools({ loadDatasets: loadSaved })
618+
.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'], timeDimensions: [{ dimension: 'stage' }] } }, ADMIN)
619+
.catch(() => undefined);
620+
expect(spy).toHaveBeenCalledTimes(1);
621+
});
622+
});
623+
538624
// ── [#32072, ADR-0150 D3] query_dataset resolves the name by package ────────
539625
// The tools' callers (the MCP bridges) belong to no package, and the input
540626
// carries none, so `datasetName` resolves by the one package-scoped rule for a

‎packages/services/service-analytics/src/dataset-tools.ts‎

Lines changed: 79 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,9 @@ import type { ExecutionContext } from '@objectstack/spec/kernel';
1919
import { stripReadDecorations } from '@objectstack/spec/kernel';
2020
import { DatasetSchema, resolveI18nLabel, type Dataset } from '@objectstack/spec/ui';
2121
import { fieldsFromZodIssues } from '@objectstack/types';
22-
import type { AnalyticsService } from './analytics-service.js';
22+
import type { AnalyticsService, DatasetCatalogAdmission } from './analytics-service.js';
2323
import { dimensionType } from './dataset-compiler.js';
24+
import { invalidMemberError, type AnalyticsRequestKey } from './dataset-refusal.js';
2425
import { matchDatasetTerms } from './dataset-term-matcher.js';
2526

2627
/**
@@ -54,8 +55,9 @@ import { matchDatasetTerms } from './dataset-term-matcher.js';
5455
*
5556
* `provenance` is composed here, after the query ran, from the dataset the
5657
* tool resolved and the selection the service answered. Nothing in it is read
57-
* from the model's input except the selection's own member names (which the
58-
* service just judged) and its `runtimeFilter`, echoed as sent. The input is a
58+
* from the model's input except the selection's own member names (each one a
59+
* member the dataset declares, {@link assertDeclaredMembers}, which the service
60+
* then judged) and its `runtimeFilter`, echoed as sent. The input is a
5961
* strict object, so a `provenance` (or any other key) the model puts beside
6062
* `datasetName` / `selection` is refused, never merged.
6163
*/
@@ -89,7 +91,9 @@ const LIST_DATASETS_DESCRIPTION =
8991

9092
const QUERY_DATASET_DESCRIPTION =
9193
'Run a selection (measures, optional dimensions, filter, time window, order, limit) against one saved business '
92-
+ 'dataset, by the name `list_datasets` lists, under the caller\'s permissions. Answers the rows plus '
94+
+ 'dataset, by the name `list_datasets` lists, under the caller\'s permissions. Measures and dimensions are the '
95+
+ 'member names `list_datasets` lists for that dataset; any other name (a raw field, `count`) is refused '
96+
+ 'INVALID_FIELD, naming the members you may use. Answers the rows plus '
9397
+ '`provenance` naming the dataset and the measures used — render the answer\'s source from `provenance` '
9498
+ '(e.g. 「指标:营收(数据集:销售分析)」), and explain a number with its measure\'s description. A dataset that '
9599
+ 'does not exist and one this caller may not query both answer NOT_FOUND. Rows are capped; `truncated` says '
@@ -472,12 +476,15 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools {
472476
// candidate and is never named. An item the parse left out is refused for
473477
// every caller, so it is admitted to none.
474478
const admitted = new Map<string | null, Dataset>();
479+
const admissions = new Map<Dataset, Extract<DatasetCatalogAdmission, { admitted: true }>>();
475480
let unresolved = false;
476481
for (const [holder, candidate] of savedHoldersOf(loaded, datasetName)) {
477482
if (candidate === undefined) continue;
478483
const admission = await service.admitDatasetCatalogEntry(candidate, context);
479-
if (admission.admitted) admitted.set(holder, candidate);
480-
else if (admission.unresolved) unresolved = true;
484+
if (admission.admitted) {
485+
admitted.set(holder, candidate);
486+
admissions.set(candidate, admission);
487+
} else if (admission.unresolved) unresolved = true;
481488
}
482489
// A holder whose admission could not be judged may be one the caller can
483490
// query: with fewer than two admitted, whether the answer is that holder,
@@ -504,6 +511,9 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools {
504511
}
505512
const dataset = resolveAdmittedDataset(admitted, datasetName);
506513
if (!dataset) throw notFound();
514+
// [ADR-0149] Judged against the dataset it resolved, before anything is
515+
// read: a member it does not declare is refused, never minted.
516+
assertDeclaredMembers(dataset, raw.selection, admissions.get(dataset));
507517

508518
// The row cap: the caller's own `limit` when it is within the cap, the cap
509519
// otherwise; one row past it is asked for, so `truncated` is a fact.
@@ -554,6 +564,69 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools {
554564
};
555565
}
556566

567+
/**
568+
* [ADR-0149] `query_dataset` answers only the members the dataset declares.
569+
*
570+
* The dataset is the one declared definition (D1): a selection member it does
571+
* not declare is outside it. `AnalyticsService.queryDataset` serves the REST
572+
* door, the dashboard and the report too, and mints a caller-named measure the
573+
* cube does not declare (`count`, a raw field read as its `sum`, an
574+
* `<field>_sum` suffix spelling) and groups by a raw field named as a
575+
* dimension. Through this tool such an answer was cited in `provenance` as a
576+
* governed metric, which is exactly what D3's fallback rule keeps apart
577+
* (非指标口径). So the tool refuses it here, before anything is read.
578+
*
579+
* Declared means one of the dataset's own `measures[].name` /
580+
* `dimensions[].name`, spelled as `list_datasets` lists it: a
581+
* `<dataset>.`-qualified spelling is not a listed name and is refused too.
582+
* Judged against every declared member, so a declared member the caller may
583+
* not read still reaches the service's own field gate (403), unchanged. The
584+
* refusal names only the members THIS caller may use (the catalogue's
585+
* admission): a withheld member, or one over an `internal` field, is never
586+
* named (ADR-0100). `selection.totals.groupings` and `order` keys are judged
587+
* downstream against the selected members, so they need no second check here.
588+
*
589+
* `INVALID_FIELD` / 400, the code the service's member-level refusals answer
590+
* (`invalidMemberError`, `member` / `param` / `cube`): the tool invents no code.
591+
*/
592+
function assertDeclaredMembers(
593+
dataset: Dataset,
594+
selection: DatasetSelection,
595+
admission: Extract<DatasetCatalogAdmission, { admitted: true }> | undefined,
596+
): void {
597+
const measures = new Set((dataset.measures ?? []).map((m) => m.name));
598+
const dimensions = new Set((dataset.dimensions ?? []).map((d) => d.name));
599+
const undeclared: Array<{ member: string; param: AnalyticsRequestKey }> = [];
600+
const judge = (names: readonly unknown[], declared: ReadonlySet<string>, param: AnalyticsRequestKey) => {
601+
for (const name of names) {
602+
if (typeof name === 'string' && !declared.has(name) && !undeclared.some((u) => u.member === name && u.param === param)) {
603+
undeclared.push({ member: name, param });
604+
}
605+
}
606+
};
607+
judge(selection.measures ?? [], measures, 'measures');
608+
judge(selection.dimensions ?? [], dimensions, 'dimensions');
609+
judge(
610+
((selection as { timeDimensions?: Array<{ dimension?: unknown }> }).timeDimensions ?? []).map((td) => td?.dimension),
611+
dimensions,
612+
'timeDimensions',
613+
);
614+
if (undeclared.length === 0) return;
615+
616+
const usable = (declared: ReadonlyArray<{ name: string }>, admitted: ReadonlySet<string> | undefined) =>
617+
declared.map((m) => m.name).filter((name) => admitted?.has(name) === true);
618+
const list = (names: string[]) => (names.length > 0 ? names.join(', ') : '(none)');
619+
const named = undeclared.map((u) => `${u.param === 'measures' ? 'measure' : 'dimension'} "${u.member}"`).join(', ');
620+
const first = undeclared[0];
621+
throw invalidMemberError(
622+
`The dataset "${dataset.name}" does not declare the ${named}. query_dataset answers only the members a dataset `
623+
+ `declares, by the names list_datasets lists. Measures you may use: ${list(usable(dataset.measures ?? [], admission?.measures))}. `
624+
+ `Dimensions you may use: ${list(usable(dataset.dimensions ?? [], admission?.dimensions))}. Pick one of these; when none `
625+
+ 'fits the question, answer with the object query tools and say that no governed metric was used (非指标口径).',
626+
{ member: first.member, param: first.param, cube: dataset.name },
627+
);
628+
}
629+
557630
/**
558631
* [ADR-0149 D3] The answer's source, from the dataset the tool resolved and
559632
* the selection the service answered: the dataset's name and label, each

0 commit comments

Comments
 (0)