Skip to content

Commit 702c562

Browse files
fix(service-analytics): a truncated query_dataset answer carries drill sidecars for the served rows only (#33146)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoF1nguV8Pdh9hoikrSfbcXx)_ Fixes #32944 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:AI 调用 `query_dataset`(MCP 工具和产品内 AI 对话工具共用同一个执行器)在按 `limit` 截断结果时,`drillRawRows` 和 `drillRanges` 这两个按行对齐的钻取附表现在与 `rows` 一起截到同样长度,第 i 项对应第 i 行。 - 为什么改:工具为了判断 `truncated` 会多取一行,过去只把 `rows` 截掉,附表原样返回,于是 `limit: 1` 时有 1 行却有 2 条 `drillRawRows`,客户端按下标钻取会多出一个看不到的分组。 - 风险与回滚:很小。只影响被截断的回答;未截断的回答完全不变(有对照用例);`totals`、`drillRawTotals`、`dimensionFields`、`drillScopes` 不按行对齐,保持原样。回滚 = revert 本 PR,不涉及数据。 - 先看:`packages/services/service-analytics/src/dataset-tools.ts` 新增的 `ROW_ALIGNED_ANSWER_MEMBERS` 常量和 `queryDataset` 中截断后的循环;`src/__tests__/dataset-tools.test.ts` 新增的 `a truncated answer serves every row-aligned sidecar` 一组用例。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run src/__tests__/dataset-tools.test.ts`,预期 32/32 通过,其中 4 条 `row-aligned sidecar` 用例为绿。 - 需要你做的:无,席位落地。 ## What changes - **`@objectstack/service-analytics`**: `createDatasetTools(...).queryDataset` asks the service for `cap + 1` rows so `truncated` is a fact, and serves `cap`. It now serves the answer's row-aligned members to the same length as `rows` when it truncates. They are listed once, in `ROW_ALIGNED_ANSWER_MEMBERS`, typed against `keyof AnalyticsResult`. - **The sidecars, enumerated from `AnalyticsResult` (`packages/spec/src/contracts/analytics-service.ts`):** - Aligned to `rows` by index, trimmed: `drillRawRows` ("aligned to `rows` by index") and `drillRanges` ("aligned to `rows` by index"). - Not row-indexed, served as answered: `fields` (one entry per column), `totals` (one per requested grouping, computed over the underlying data, not the capped rows), `drillRawTotals` (aligned to `totals`), `dimensionFields` and `drillScopes` (keyed by dimension or measure name), `object`. `sql` is still stripped. - **One fix, both faces.** The MCP `query_dataset` tool (`packages/runtime/src/domains/mcp.ts`) and the chat tool (`execute`) call this executor, so both are fixed here. - **The REST door has no over-read.** `POST /analytics/dataset/query` (`packages/rest/src/analytics-routes.ts`) passes the caller's `selection` to `AnalyticsService.queryDataset` unchanged and does not truncate, so its `rows` and sidecars come from one query at one limit. No change there. ## Tests `packages/services/service-analytics/src/__tests__/dataset-tools.test.ts` (+4, one `describe` in the `query_dataset` block): - `limit: 1` and `limit: 2`, through the plugin-wired service: `truncated: true`, `rowCount` equals the limit, `drillRawRows.length === rows.length`, and `drillRawRows[i]` equals `{ stage: rows[i].stage }` for every i. - A service answer carrying every sidecar (`limit: 2` over three rows): `drillRawRows` and `drillRanges` keep their first two entries; `totals`, `drillRawTotals`, `dimensionFields` and `drillScopes` equal the service's answer. - CONTROL: `limit: 3` over three rows: `truncated: false`, and `rows` and `drillRawRows` equal the service's own answer. ## Acceptance notes - Ruling grep on the touched surface (`ruling|Ruling-ref|maintainer|⛔`): `dataset-tools.ts` L295 and its test L472/L513 cite the admission-first ruling 6766102988 (which holders are candidates). The change runs after resolution and names no holder, so it does not touch that ruling. - Not changed: a `limit: 0` call (cap 0) serves no rows, but `dimensionFields` and `drillScopes` stay on the answer, though their contract says they are set only on an answer with rows. `drillRawRows` / `drillRanges` are now `[]` there. This is a narrow edge that nobody has reported; left as is. - New row-aligned members: a future `AnalyticsResult` member aligned to `rows` has to be added to `ROW_ALIGNED_ANSWER_MEMBERS`. The `satisfies` check catches a misspelled or removed key at compile time, but it cannot tell whether a new key is row-aligned. - Live reproduction: the card's showcase MCP run (QA #32940 P-1) was not repeated here. The unit pins drive the plugin-wired service, whose `drillRawRows` comes from the same `analytics-service.ts` pass the showcase uses. ## Verification All readings at head `bbc366d8` (base `bf02d33b`; `origin/main` merged before the PR, already up to date). <details><summary>Measured at origin/main first (the premise holds)</summary> New pins over the unfixed executor (`bf02d33b`), `-t 'row-aligned sidecar'`: **3 failed | 1 passed (4)**. - `limit 1`: `expected [ { stage: 'draft' }, …(2) ] to have a length of 1 but got 3` - `limit 2`: `expected [ { stage: 'draft' }, …(2) ] to have a length of 2 but got 3` - sidecars: `drillRawRows` kept three entries where two rows were served. The engine double returns every row it holds, so at `limit: 1` the measured surplus is two entries, not one. On a SQL driver, which applies `LIMIT cap + 1`, it is the single probe row the card shows. The CONTROL passed. </details> <details><summary>Package tests and typecheck (service-analytics)</summary> - `pnpm --filter @objectstack/service-analytics test`: Test Files 215 passed (215), Tests 5199 passed | 332 skipped (5531) - `pnpm --filter @objectstack/service-analytics typecheck`: exit 0; `tsc --listFiles` includes `src/__tests__/dataset-tools.test.ts` (1 hit) - `dataset-tools.test.ts`: Tests 32 passed (32) </details> <details><summary>Ablations (both red, both restored)</summary> The test imports the source (`../dataset-tools.js`), so there is no `dist/` leg. - Trim removed: `scripts/ablation-replace.mjs` on `dataset-tools.ts`, anchor `if (truncated) {` + the loop line x1 -> x0, replacement `if (false as boolean) {` x0 -> x1, blob `b32f38f4` -> `a31b8c2b`. Result: **3 failed | 1 passed**, every truncation case. Restored: blob == HEAD (`b32f38f4`), `git diff HEAD` empty. - `drillRanges` dropped from the list: anchor `['drillRawRows', 'drillRanges'] as const` x1 -> x0, replacement `['drillRawRows'] as const`, blob `b32f38f4` -> `e1acd138`. Result: **1 failed | 3 passed**, the sidecar case (`drillRanges` kept 3 entries, expected 2). Restored: blob == HEAD, `git diff HEAD` empty. </details> <details><summary>Derived gates and lint</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at `bbc366d8`: 62 families, each run with stdin closed and its exit code recorded before any pipe. `--ran` reconciles **62 accounted, 61 run, 1 NOT MEASURED**: - `pnpm check:dual-build-cjs-loads`: exit 3, PREREQUISITE NOT MET. Its self-test passed (93 cases); the scan needs `dist/` of packages outside this diff's closure (hono, account, setup, studio, client, client-react, …). NOT MEASURED; CI runs it. The other 61 exit 0, `check:nul-bytes`, `check:engine-double-contract`, `check:test-source-alias`, `check:cross-package-test-inputs`, `check:published-files` and `check:adr-0087-registration` among them. `node scripts/check-plugin-teardown-shape.mjs --self-test` first exited 3 (its pinned fixture commit was not in the clone); after `git fetch origin 621a487`, exit 0, 48 cases. `pnpm lint`: exit 0. No export was renamed or removed, so `check-platform-checklist.mjs` is not owed. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibxxaZKwWGECdLG6N1s)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 796e9d4 commit 702c562

3 files changed

Lines changed: 99 additions & 0 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(service-analytics): a truncated `query_dataset` answer carries drill sidecars for the served rows only
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`query_dataset` asks the dataset query for one row past its cap so `truncated` is a fact, and serves `cap` rows. The two answer members aligned to `rows` by index, `drillRawRows` and `drillRanges`, were served untrimmed, so each held one more entry than `rows` (a `limit: 1` answer carried two `drillRawRows` entries). They are now served to the same length as `rows`, entry i beside row i, on the MCP tool and on the chat tool alike. Members that are not row-indexed (`totals`, `drillRawTotals`, `dimensionFields`, `drillScopes`, `fields`, `object`) are served as before, and an answer within the cap is unchanged.

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

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,78 @@ describe('query_dataset', () => {
402402
expect(plain).not.toHaveProperty('warning');
403403
});
404404

405+
// The tool asks the service for one row past the cap so `truncated` is a
406+
// fact, then serves `cap` rows. Every member of the answer aligned to `rows`
407+
// by index is served to the same length, entry i beside row i: a drill
408+
// sidecar that kept the probe row described a bucket the caller was never
409+
// shown. Members aligned to something else are served as the service
410+
// answered them.
411+
describe('a truncated answer serves every row-aligned sidecar to the served rows', () => {
412+
const rows = [
413+
{ stage: 'draft', revenue: 1 },
414+
{ stage: 'paid', revenue: 2 },
415+
{ stage: 'void', revenue: 3 },
416+
];
417+
418+
for (const limit of [1, 2]) {
419+
it(`limit ${limit}: drillRawRows holds exactly the served rows' raw values, in row order`, async () => {
420+
const { service } = await bootWired(rows);
421+
const out = await service.datasetTools({ loadDatasets: loadSaved }).queryDataset(
422+
{ datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'], limit } },
423+
ADMIN,
424+
);
425+
expect(out).toMatchObject({ rowCount: limit, truncated: true, dimensionFields: { stage: 'stage' } });
426+
expect(out.rows).toHaveLength(limit);
427+
expect(out.drillRawRows).toHaveLength(out.rows.length);
428+
out.rows.forEach((row, i) => expect(out.drillRawRows?.[i]).toEqual({ stage: row.stage }));
429+
});
430+
}
431+
432+
it('trims drillRanges with the rows and leaves totals, drillRawTotals, dimensionFields and drillScopes as answered', async () => {
433+
const { service } = await bootWired();
434+
const range = (gte: string, lt: string) => ({ closed_on: { field: 'closed_on', gte, lt } });
435+
const totals = [{ dimensions: [], rows: [{ revenue: 6 }] }];
436+
const drillRawTotals = [[{}]];
437+
const drillScopes = { revenue: { amount: { $null: false } } };
438+
vi.spyOn(service, 'queryDataset').mockResolvedValue({
439+
rows: rows.map((r) => ({ ...r })),
440+
fields: [{ name: 'stage', type: 'string' }, { name: 'revenue', type: 'number' }],
441+
object: 'crm_opp',
442+
totals,
443+
dimensionFields: { stage: 'stage' },
444+
drillRawRows: rows.map((r) => ({ stage: r.stage })),
445+
drillRawTotals,
446+
drillRanges: [range('2026-01-01', '2026-02-01'), range('2026-02-01', '2026-03-01'), range('2026-03-01', '2026-04-01')],
447+
drillScopes,
448+
});
449+
const out = await service.datasetTools({ loadDatasets: loadSaved }).queryDataset(
450+
{ datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'], limit: 2 } },
451+
ADMIN,
452+
);
453+
expect(out).toMatchObject({ rowCount: 2, truncated: true });
454+
expect(out.drillRawRows).toEqual([{ stage: 'draft' }, { stage: 'paid' }]);
455+
expect(out.drillRanges).toEqual([range('2026-01-01', '2026-02-01'), range('2026-02-01', '2026-03-01')]);
456+
// Aligned to `totals`, keyed by name, or describing the whole answer: not row-indexed.
457+
expect(out.totals).toEqual(totals);
458+
expect(out.drillRawTotals).toEqual(drillRawTotals);
459+
expect(out.dimensionFields).toEqual({ stage: 'stage' });
460+
expect(out.drillScopes).toEqual(drillScopes);
461+
});
462+
463+
it('CONTROL: an answer within the cap is served as the service answered it', async () => {
464+
const { service } = await bootWired(rows);
465+
const direct = await service.queryDataset(PIPELINE as never, { measures: ['revenue'], dimensions: ['stage'] } as never, ADMIN);
466+
const out = await service.datasetTools({ loadDatasets: loadSaved }).queryDataset(
467+
{ datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'], limit: 3 } },
468+
ADMIN,
469+
);
470+
expect(out).toMatchObject({ rowCount: 3, truncated: false });
471+
expect(out.rows).toEqual(direct.rows);
472+
expect(out.drillRawRows).toEqual(direct.drillRawRows);
473+
expect(out.drillRawRows).toEqual([{ stage: 'draft' }, { stage: 'paid' }, { stage: 'void' }]);
474+
});
475+
});
476+
405477
it('answers 503 when the dataset read itself fails, never NOT_FOUND', async () => {
406478
const { service } = await bootWired();
407479
const tools = service.datasetTools({ loadDatasets: async () => { throw new Error('loader down'); } });

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,17 @@ import { matchDatasetTerms } from './dataset-term-matcher.js';
6363
/** `query_dataset`'s row cap when the host sets none — `query_records`' default. */
6464
export const DATASET_TOOL_DEFAULT_MAX_ROWS = 50;
6565

66+
/**
67+
* The members of an `AnalyticsResult` aligned to `rows` by index (entry i
68+
* describes row i, per their contract in `spec/contracts`). `query_dataset`
69+
* serves them to the length it serves `rows`, so a truncated answer holds no
70+
* drill bucket for the probe row it asked for past the cap. The others are not
71+
* row-indexed and are served as answered: `fields` (columns), `totals` and
72+
* `drillRawTotals` (aligned to `totals`), `dimensionFields` and `drillScopes`
73+
* (keyed by member name), `object`.
74+
*/
75+
const ROW_ALIGNED_ANSWER_MEMBERS = ['drillRawRows', 'drillRanges'] as const satisfies readonly (keyof AnalyticsResult)[];
76+
6677
const LIST_DATASETS_DESCRIPTION =
6778
'List the governed business datasets this caller may query: each dataset\'s dimensions (what an answer can be '
6879
+ 'grouped by) and measures (the numbers it can answer), with their business definitions and synonyms. Pass '
@@ -506,6 +517,12 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools {
506517
const truncated = rows.length > cap;
507518
const served = truncated ? rows.slice(0, cap) : rows;
508519
const { sql: _sql, ...rest } = answer as AnalyticsResult & { sql?: unknown };
520+
if (truncated) {
521+
for (const member of ROW_ALIGNED_ANSWER_MEMBERS) {
522+
const aligned = rest[member];
523+
if (Array.isArray(aligned)) (rest as Record<string, unknown>)[member] = aligned.slice(0, cap);
524+
}
525+
}
509526

510527
let narrowing: { narrowed: boolean; statement?: string } | undefined;
511528
if (deps.diagnoseDelegation) {

0 commit comments

Comments
 (0)