Skip to content

Commit 068a0f9

Browse files
fix(service-analytics): query_dataset never pairs an empty answer with a group count (#35286)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg1XdbbGasMNVx41tq3hZKV4)_ Fixes #35204 — the two contract-review nits (N5, N6). The card's main route (the ObjectQL face handing its cut to the engine's order-and-cut) is closed by seat ruling 6997569008 (route C: the face's in-memory `totalGroups` is already exact); the database top-N and its ordering question moved to #35287. Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`query_dataset` 带 `totals` 时,若 totals 那次读取遇到「源表不存在」被降级成空结果,不再同时返回主网格的 `totalGroups`;另在 `dataset-group-count.ts` 头注释写明「整网格证明」止于策略自己的读取接缝。 - 为什么改:合约评审 6982207184 的 N6:空答案(`rowCount: 0`)与已写入的分组数配对,AI 会读到一个从未返回的网格的分组数;N5 是一句说明边界的注释。 - 风险与回滚:风险低,只改了计数写回调用方槽位的时机(整次调用成功后才写);回滚即 revert 本 PR。 - 先看:`packages/services/service-analytics/src/dataset-executor.ts` 的 `execute()`(`counted` 局部槽位与末尾写回两处),其次新测试。 - 两分钟验证:`pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/dataset-tools.test.ts -t "missing source serves no count"`,预期 2 passed。 - 需要你做的:无,席位落地。 ## What changes - **N6** (`dataset-executor.ts`). `execute` now hands `executeSelection` a local group-count request and copies its outcome into the caller's slot only after the `totals` groupings have run. Before, the slot was written while the primary grid was read; a `totals` read that then threw a missing-source error made `answerDataset` serve `{ rows: [] }`, and `query_dataset` answered `rowCount: 0` beside the primary grid's `totalGroups`. Any throw after the count now leaves the slot empty. - **N5** (`dataset-group-count.ts` header). One sentence: the whole-grid proof stops at the strategy's own read seam (`ctx.executeRawSql`, `ctx.executeAggregate`); a host-supplied bridge or an out-of-repo driver that silently truncates an unwindowed read is counted as whole. No in-repo seam cuts one. - Changeset: `@objectstack/service-analytics` patch. ## Tests New top-level describe in the shared `query_dataset` harness, `src/__tests__/dataset-tools.test.ts`: `[query_dataset totalGroups] a totals read that meets a missing source serves no count`. Real SQLite engine through `AnalyticsServicePlugin`; the second statement of the call fails as `no such table`. - CONTROL: totals served, `{ rowCount: 3, truncated: false, totalGroups: 3 }`, two statements, the first carrying `COUNT(*) OVER ()`. - The fix: totals read fails, the empty answer (`rowCount: 0`) and no `totalGroups`; the primary statement still ran and counted. ## Acceptance notes - **The route is not in this PR.** Measured on `origin/main` `f4dbcc21`: the engine writes the group count to the caller's own request (`request.outcome.totalGroups`, `aggregate-order-cut.ts`), but the ObjectQL face's only read seam, `ctx.executeAggregate` (the spec's `StrategyContext` and the plugin's auto-bridge), carries no read option, and the engine REFUSES (throws `INVALID_QUERY` / 400 before reading) wherever it cannot serve the cut rather than declining. Routing the face's cut therefore needs a new consumer-local bridge (`plugin.ts`, `strategies/types.ts`, `analytics-service.ts`, outside this card's file surface) and either a catch around the engine's refusal or an objectql decline mode, and it changes which rows a text-ordered top-N answers (database collation instead of `applyOrdering`). Returned to the seat as a decision. - `totalGroups` on the ObjectQL face is already the exact count today (the whole grid's length, before the face's own in-memory cut); nothing on that face is approximated. ## Verification Head `cd688d97c`. <details><summary>Package: build, typecheck, test (under the shared verify lock)</summary> - `pnpm --filter @objectstack/service-analytics build && … typecheck && … test`: `VERDICT command-exit 0`; `Test Files 218 passed (218)`, `Tests 5605 passed | 345 skipped (5950)`. </details> <details><summary>Ablation (one-shot, not kept)</summary> - `node scripts/ablation-replace.mjs` replaced `this.executeSelection(compiled, selection, context, counted);` with the pre-fix `…, options?.groupCount);` (anchor 1 to 0, blob `1e56cd1b5e95` to `9ab686e51c1b`). The pin turned red: `AssertionError: expected { rows: [], fields: [], …(7) } to not have property "totalGroups"`, `Tests 1 failed | 1 passed`. Restore proven: blob equals HEAD, `git diff HEAD` empty. No dist leg: the suite imports the executor from `src`. </details> <details><summary>Derived gate families (dispatch-gates, 66)</summary> - 64 exit 0. 2 exit 3, NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test` (shallow clone cannot reach its pinned fixture commit), `check:dual-build-cjs-loads` (reads every package's built output; only the closure was built). CI runs both. - `dispatch-gates --ran`: `66 derived famil(ies) accounted for — 64 run, 2 NOT-MEASURED`. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Utp6CazXu8zyYD5PC6J2u7 <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CazXu8zyYD5PC6J2u7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0188989 commit 068a0f9

4 files changed

Lines changed: 110 additions & 2 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/service-analytics': patch
3+
---
4+
5+
fix(service-analytics): `query_dataset` never pairs an empty answer with a group count
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A selection with `totals` runs its totals reads after the primary grid is counted. When one of those reads met a missing source, the service served the empty answer (`rowCount: 0`), but the group count of the primary grid was already written, so `query_dataset` answered `totalGroups` for a grid it never served. The count now reaches the caller only once the whole call has answered; an answer served empty because a read failed carries no `totalGroups`.
11+
12+
The `dataset-group-count.ts` header also states where the whole-grid proof stops: at the strategy's own read seam (`ctx.executeRawSql`, `ctx.executeAggregate`). A host-supplied bridge or an out-of-repo driver that silently truncates an unwindowed read would be counted as whole.
13+
14+
No key, member or export changes.

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

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,89 @@ describe('[query_dataset totalGroups] a SQL dialect the strategy does not know i
868868
});
869869
});
870870

871+
// [query_dataset totalGroups] The count is the served answer's, or absent. The
872+
// primary grid is counted by its own statement; the `totals` reads run after
873+
// it. When one of them meets a missing source, the service serves the empty
874+
// answer, and a count already written would pair `rowCount: 0` with the groups
875+
// of a grid that was never served. Over a real SQLite engine: the second
876+
// statement of the call fails as a table that vanished between the two would.
877+
describe('[query_dataset totalGroups] a totals read that meets a missing source serves no count', () => {
878+
const OBJECT = 'os_tg_vanish';
879+
const DATASET = {
880+
name: 'tg_vanish',
881+
label: 'Vanishing pipeline',
882+
object: OBJECT,
883+
dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string' }],
884+
measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum', field: 'amount' }],
885+
};
886+
let engine: ObjectQL;
887+
let service: AnalyticsService;
888+
const statements: string[] = [];
889+
let failFrom = Number.POSITIVE_INFINITY;
890+
891+
beforeAll(async () => {
892+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
893+
engine = new ObjectQL({ logger: tgQuiet } as never);
894+
engine.registerDriver(driver as never, true);
895+
await engine.init();
896+
engine.registry.registerObject({
897+
name: OBJECT,
898+
label: 'Deal',
899+
fields: { stage: { name: 'stage', type: 'text' }, amount: { name: 'amount', type: 'number' } },
900+
} as never, '@objectstack/service-analytics');
901+
await engine.syncSchemas();
902+
await installDefaultOrganization(engine as never);
903+
for (const [i, stage] of ['lead', 'qualified', 'won'].entries()) {
904+
await engine.insert(OBJECT, { id: `v${i}`, stage, amount: 10 * (i + 1) } as never);
905+
}
906+
const realExecute = (engine as any).execute.bind(engine);
907+
(engine as any).execute = (sql: unknown, opts?: { object?: string }) => {
908+
if (opts?.object === OBJECT) {
909+
statements.push(String((sql as { sql?: string })?.sql ?? sql));
910+
if (statements.length >= failFrom) return Promise.reject(new Error(`SQLITE_ERROR: no such table: ${OBJECT}`));
911+
}
912+
return realExecute(sql, opts);
913+
};
914+
const registered: Record<string, unknown> = {};
915+
await new AnalyticsServicePlugin({} as never).init({
916+
getService: (name: string) => (name === 'data' ? engine : name === 'security' ? tgSecurity : registered[name]),
917+
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
918+
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
919+
hook: () => {},
920+
logger: tgQuiet,
921+
} as never);
922+
service = registered.analytics as AnalyticsService;
923+
});
924+
925+
afterAll(async () => {
926+
try { await engine?.destroy(); } catch { /* noop */ }
927+
});
928+
929+
const ask = () => service.datasetTools({ loadDatasets: async () => [{ ...DATASET }] }).queryDataset(
930+
{ datasetName: DATASET.name, selection: { measures: ['revenue'], dimensions: ['stage'], totals: { groupings: [[]] } } },
931+
TG_CALLER,
932+
);
933+
934+
it('CONTROL: with the totals read served, the primary statement counts the groups', async () => {
935+
failFrom = Number.POSITIVE_INFINITY;
936+
statements.length = 0;
937+
const out = await ask();
938+
expect(out).toMatchObject({ rowCount: 3, truncated: false, totalGroups: 3 });
939+
expect(statements).toHaveLength(2);
940+
expect(statements[0]).toContain(TG_WINDOW);
941+
});
942+
943+
it('with the totals read failing as a missing source: the empty answer, and no totalGroups', async () => {
944+
statements.length = 0;
945+
failFrom = 2;
946+
const out = await ask();
947+
expect(statements, 'the primary statement ran and counted before the totals read failed').toHaveLength(2);
948+
expect(statements[0]).toContain(TG_WINDOW);
949+
expect(out).toMatchObject({ rowCount: 0 });
950+
expect(out).not.toHaveProperty('totalGroups');
951+
});
952+
});
953+
871954
// [ADR-0149] The dataset is the one declared definition: `query_dataset`
872955
// answers only the members it declares. A raw field (`amount`), the
873956
// service's ad-hoc `count`, a suffix spelling (`amount_sum`) or an

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1243,7 +1243,13 @@ export class DatasetExecutor {
12431243
// sub-query (measure-scoped, totals, compareTo) shares one instant.
12441244
const { compiled, selection } = resolveSelectionTokens(compiledInput, selectionInput, context);
12451245

1246-
const result = await this.executeSelection(compiled, selection, context, options?.groupCount);
1246+
// [query_dataset totalGroups] The count reaches the caller's slot only once
1247+
// the whole call has answered. The `totals` reads below can still throw — a
1248+
// missing-source error the service then serves as an empty answer — and a
1249+
// count already written would pair `rowCount: 0` with the groups of a grid
1250+
// that was never served.
1251+
const counted: GroupCountRequest | undefined = options?.groupCount ? {} : undefined;
1252+
const result = await this.executeSelection(compiled, selection, context, counted);
12471253

12481254
// Server-side totals (#1753) — re-run the selection grouped by each
12491255
// requested dimension subset, so a subtotal/grand total is the measure's
@@ -1278,6 +1284,7 @@ export class DatasetExecutor {
12781284
result.totals = totals;
12791285
}
12801286

1287+
if (options?.groupCount && counted?.outcome) options.groupCount.outcome = counted.outcome;
12811288
return result;
12821289
}
12831290

‎packages/services/service-analytics/src/dataset-group-count.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,11 @@
3333
* for a statement with no `LIMIT`, the ObjectQL face for the engine's answer.
3434
* The executor counts only when every read was answered and each answer's
3535
* count equals the rows it handed back, so a read cut by any cap under it (a
36-
* host strategy's row guard, say) leaves the count out.
36+
* host strategy's row guard, say) leaves the count out. The proof stops at the
37+
* strategy's own read seam: a strategy counts the rows `ctx.executeRawSql` or
38+
* `ctx.executeAggregate` handed it, so a host-supplied bridge or an
39+
* out-of-repo driver that silently truncates an unwindowed read is counted as
40+
* whole. No in-repo seam cuts an unwindowed read.
3741
*
3842
* ## Asked for, never assumed
3943
*

0 commit comments

Comments
 (0)