Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/35204-query-dataset-group-count-totals-arm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/service-analytics': patch
---

fix(service-analytics): `query_dataset` never pairs an empty answer with a group count

Clause-②: no
Metadata-protocol: none

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`.

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.

No key, member or export changes.
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,89 @@ describe('[query_dataset totalGroups] a SQL dialect the strategy does not know i
});
});

// [query_dataset totalGroups] The count is the served answer's, or absent. The
// primary grid is counted by its own statement; the `totals` reads run after
// it. When one of them meets a missing source, the service serves the empty
// answer, and a count already written would pair `rowCount: 0` with the groups
// of a grid that was never served. Over a real SQLite engine: the second
// statement of the call fails as a table that vanished between the two would.
describe('[query_dataset totalGroups] a totals read that meets a missing source serves no count', () => {
const OBJECT = 'os_tg_vanish';
const DATASET = {
name: 'tg_vanish',
label: 'Vanishing pipeline',
object: OBJECT,
dimensions: [{ name: 'stage', label: 'Stage', field: 'stage', type: 'string' }],
measures: [{ name: 'revenue', label: 'Revenue', aggregate: 'sum', field: 'amount' }],
};
let engine: ObjectQL;
let service: AnalyticsService;
const statements: string[] = [];
let failFrom = Number.POSITIVE_INFINITY;

beforeAll(async () => {
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never);
engine = new ObjectQL({ logger: tgQuiet } as never);
engine.registerDriver(driver as never, true);
await engine.init();
engine.registry.registerObject({
name: OBJECT,
label: 'Deal',
fields: { stage: { name: 'stage', type: 'text' }, amount: { name: 'amount', type: 'number' } },
} as never, '@objectstack/service-analytics');
await engine.syncSchemas();
await installDefaultOrganization(engine as never);
for (const [i, stage] of ['lead', 'qualified', 'won'].entries()) {
await engine.insert(OBJECT, { id: `v${i}`, stage, amount: 10 * (i + 1) } as never);
}
const realExecute = (engine as any).execute.bind(engine);
(engine as any).execute = (sql: unknown, opts?: { object?: string }) => {
if (opts?.object === OBJECT) {
statements.push(String((sql as { sql?: string })?.sql ?? sql));
if (statements.length >= failFrom) return Promise.reject(new Error(`SQLITE_ERROR: no such table: ${OBJECT}`));
}
return realExecute(sql, opts);
};
const registered: Record<string, unknown> = {};
await new AnalyticsServicePlugin({} as never).init({
getService: (name: string) => (name === 'data' ? engine : name === 'security' ? tgSecurity : registered[name]),
registerService: (name: string, svc: unknown) => { registered[name] = svc; },
replaceService: (name: string, svc: unknown) => { registered[name] = svc; },
hook: () => {},
logger: tgQuiet,
} as never);
service = registered.analytics as AnalyticsService;
});

afterAll(async () => {
try { await engine?.destroy(); } catch { /* noop */ }
});

const ask = () => service.datasetTools({ loadDatasets: async () => [{ ...DATASET }] }).queryDataset(
{ datasetName: DATASET.name, selection: { measures: ['revenue'], dimensions: ['stage'], totals: { groupings: [[]] } } },
TG_CALLER,
);

it('CONTROL: with the totals read served, the primary statement counts the groups', async () => {
failFrom = Number.POSITIVE_INFINITY;
statements.length = 0;
const out = await ask();
expect(out).toMatchObject({ rowCount: 3, truncated: false, totalGroups: 3 });
expect(statements).toHaveLength(2);
expect(statements[0]).toContain(TG_WINDOW);
});

it('with the totals read failing as a missing source: the empty answer, and no totalGroups', async () => {
statements.length = 0;
failFrom = 2;
const out = await ask();
expect(statements, 'the primary statement ran and counted before the totals read failed').toHaveLength(2);
expect(statements[0]).toContain(TG_WINDOW);
expect(out).toMatchObject({ rowCount: 0 });
expect(out).not.toHaveProperty('totalGroups');
});
});

// [ADR-0149] The dataset is the one declared definition: `query_dataset`
// answers only the members it declares. A raw field (`amount`), the
// service's ad-hoc `count`, a suffix spelling (`amount_sum`) or an
Expand Down
9 changes: 8 additions & 1 deletion packages/services/service-analytics/src/dataset-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1243,7 +1243,13 @@ export class DatasetExecutor {
// sub-query (measure-scoped, totals, compareTo) shares one instant.
const { compiled, selection } = resolveSelectionTokens(compiledInput, selectionInput, context);

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

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

if (options?.groupCount && counted?.outcome) options.groupCount.outcome = counted.outcome;
return result;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@
* for a statement with no `LIMIT`, the ObjectQL face for the engine's answer.
* The executor counts only when every read was answered and each answer's
* count equals the rows it handed back, so a read cut by any cap under it (a
* host strategy's row guard, say) leaves the count out.
* host strategy's row guard, say) leaves the count out. The proof stops at the
* strategy's own read seam: a strategy counts the rows `ctx.executeRawSql` or
* `ctx.executeAggregate` handed it, so 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 an unwindowed read.
*
* ## Asked for, never assumed
*
Expand Down
Loading