diff --git a/.changeset/35194-query-dataset-total-groups.md b/.changeset/35194-query-dataset-total-groups.md new file mode 100644 index 00000000000..1d961b00655 --- /dev/null +++ b/.changeset/35194-query-dataset-total-groups.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-analytics': patch +--- + +feat(service-analytics): `query_dataset` says how many groups existed before the `limit` cut (`totalGroups`), as `aggregate_records` does + +Clause-②: yes (widening: QueryDatasetOutputSchema gains totalGroups) +Metadata-protocol: added +Skills-docs: follow-up #35203 + +`QueryDatasetOutputSchema` gains an optional `totalGroups`: how many groups the selection formed before `offset` and `limit` cut them, the same name and meaning as `aggregate_records`' `totalGroups`. A client asked "how many are there" after a top-N cut can now answer it: a grouped `query_dataset` whose `limit` is below the group count answers `truncated: true` and the full count, and an answer that was not cut answers `totalGroups` equal to `rowCount`. + +The count never costs a read. Where the window is pushed into the one SQL statement that grouped the answer, the database counts the groups in that statement (`COUNT(*) OVER ()`, after the `GROUP BY` and ahead of the `ORDER BY` and `LIMIT`). Where the window is applied in memory, the count is the length of the grid before the window: an order by a display label (the tool's own order, used when none is sent, sorts every selected dimension, so grouping by any select or reference field brings this in; an order by measures alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, `compareTo`), and a query the engine's aggregate serves, such as a date bucket, a field-to-field filter, an external object or a driver with no raw SQL. That grid is counted only when every read that built it came back whole; a grid that a cap or row guard cut before the window answers no count. + +`totalGroups` is absent when: the window was pushed down and the SQL dialect is not one the analytics strategy knows, or a selected member is itself named `__os_group_count`, or the page came back empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a host adds, or was cut by a cap under it; or the dataset's object is missing and the answer is the empty one served for it. Read `totalGroups` as optional. + +Only the AI tool asks for the count. The REST dataset door, dashboards and reports run the statements they ran before. diff --git a/content/docs/references/ai/dataset-tools.mdx b/content/docs/references/ai/dataset-tools.mdx index efefe0843ae..c4e777c3a6d 100644 --- a/content/docs/references/ai/dataset-tools.mdx +++ b/content/docs/references/ai/dataset-tools.mdx @@ -338,6 +338,7 @@ const result = DatasetNextStepSchema.parse(data); | **sourceLine** | `string` | optional | The answer's source as one finished line, in the caller's locale: composed by the tool from `provenance` after the query ran, never typed by the model. `provenance` stays the structured source and this is the same source in words. The wording is the executor's; the schema declares the slot and fixes no text (ADR-0149 M1). Absent when the tool composed none, never an empty string | | **rowCount** | `integer` | ✅ | How many rows `rows` holds | | **truncated** | `boolean` | ✅ | `true` when more rows existed past the row cap the tool applied and were not returned | +| **totalGroups** | `integer` | optional | How many groups the selection formed before `offset` and `limit` cut them: the rows the same selection answers with no window. The same name and meaning as `aggregate_records`' `totalGroups`. Never paid for with a read. Where the window is pushed into the one SQL statement that grouped the answer, the database counts the groups with a window count in that statement. Where the window is applied in memory, it is the length of the grid before the window: an order by a display label (the tool's own order when none is sent sorts every selected dimension, so any select or reference dimension brings it in; an order by measures alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, `compareTo`), and a query the engine's aggregate serves, such as a date bucket, a field-to-field filter, an external object or a driver with no raw SQL. That grid is counted only when every read that built it came back whole: a grid that any cap or row guard cut before the window answers no count. Equals `rowCount` when the answer was not cut. Absent otherwise, which is when: the window was pushed down and the SQL dialect is not one the tool knows, or a selected member is itself named `__os_group_count`, or the page came back empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a host adds, or was cut by a cap under it; or the dataset's object is missing and the answer is the empty one served for it | | **delegationNarrowed** | `true` | optional | Present, and `true`, when the caller acts as an agent whose authority narrows what it may read on the dataset's object; `warning` states the narrowing (ADR-0090 D10) | | **warning** | `string` | optional | The narrowing statement; present exactly when `delegationNarrowed` is | diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 4d4b4ae03e1..eb23a3e83b0 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -17,20 +17,27 @@ * never a substring, never a withheld member. * - `query_dataset`: one NOT_FOUND for missing and hidden; `provenance` * composed from what ran, which the model's input cannot set; the row cap - * and `truncated`; the delegation statement; no `sql`. + * and `truncated`; `totalGroups`, counted by the statement that grouped the + * answer or as the length of a whole grid windowed in memory, and absent + * where neither holds; the delegation statement; no `sql`. * - [#34919] `nextStep` and `sourceLine` (ADR-0149 M1 note): the decision for * each term, the precedence among mixed cases, the partial-answer rule, the * sentence's language, and that neither sentence names a member the caller * was not admitted to — on a mirror of `examples/app-crm`'s dataset. */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; import { ListDatasetsOutputSchema, QueryDatasetOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { AnalyticsServicePlugin } from '../plugin.js'; import { AnalyticsService } from '../analytics-service.js'; import { createDatasetTools, getDatasetToolDefinitions } from '../dataset-tools.js'; import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; +import { NativeSQLStrategy } from '../strategies/native-sql-strategy.js'; +import type { AnalyticsStrategy } from '../strategies/types.js'; const ME = { userId: 'u_me', tenantId: 'org_a', locale: 'zh-CN' } as ExecutionContext; const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext; @@ -113,11 +120,14 @@ const nativeSql = () => ({ nativeSql: true, objectqlAggregate: false, inMemory: function fakeEngine(rows: Record[]) { const reads: string[] = []; + const statements: string[] = []; return { reads, + statements, engine: { execute: async (sql: unknown, options?: { object?: string }) => { reads.push(`execute:${options?.object ?? String(sql)}`); + statements.push(String((sql as { sql?: string })?.sql ?? sql)); return { rows: rows.map((r) => ({ ...r })) }; }, hasObjectMiddleware: () => false, @@ -146,7 +156,7 @@ const security = { }; async function bootWired(rows: Record[] = [{ stage: 'won', revenue: 100 }]) { - const { engine, reads } = fakeEngine(rows); + const { engine, reads, statements } = fakeEngine(rows); const registered: Record = {}; const warn = vi.fn(); const ctx = { @@ -160,7 +170,7 @@ async function bootWired(rows: Record[] = [{ stage: 'won', reve logger: { info() {}, warn, error() {}, debug() {} }, }; await new AnalyticsServicePlugin({ queryCapabilities: nativeSql }).init(ctx as never); - return { service: registered.analytics as AnalyticsService, reads, warn }; + return { service: registered.analytics as AnalyticsService, reads, statements, warn }; } const loadSaved = vi.fn(async () => SAVED.map((d) => ({ ...d, _diagnostics: { source: 'test' } }))); @@ -372,7 +382,8 @@ describe('query_dataset', () => { expect((dataset as { name: string }).name).toBe('pipeline'); expect(selection).toEqual({ ...input.selection, limit: 51 }); expect(context).toBe(ME); - expect(options).toBeUndefined(); + // [query_dataset totalGroups] The one option the tool hands down: the group-count request. + expect(Object.keys(options ?? {})).toEqual(['groupCount']); expect(out.provenance).toEqual({ kind: 'dataset', @@ -578,6 +589,285 @@ describe('query_dataset', () => { }); }); +// [query_dataset totalGroups] Beside `truncated`: how many groups the selection +// formed before `offset` and `limit` cut them, the same name and meaning as +// `aggregate_records`' `totalGroups` (`dataset-group-count.ts`). Two sources, +// never a read made to count: a window in the ONE statement that grouped and +// cut the answer in the database, or the length of a grid the executor or the +// ObjectQL face windowed in memory, counted only when every read that built it +// is vouched whole. Over a real engine: the SQLite cell always runs, the +// PostgreSQL cell where `OS_TEST_POSTGRES_URL` is set (a named skip otherwise; +// node-postgres answers the count as text). Every read of the object is +// counted, so "no second read" is measured, not assumed. Where neither source +// holds the member is ABSENT — never a number made up from a cut grid. +const TG_OBJECT = 'os_tg_deal'; +const TG_ROWS = [ + { id: 'd1', stage: 'lead', region: 'emea', phase: 'p1', amount: 10, closed_on: '2026-01-05' }, + { id: 'd2', stage: 'lead', region: 'apac', phase: 'p1', amount: 20, closed_on: '2026-01-20' }, + { id: 'd3', stage: 'qualified', region: 'emea', phase: 'p2', amount: 30, closed_on: '2026-02-03' }, + { id: 'd4', stage: 'proposal', region: 'emea', phase: 'p2', amount: 40, closed_on: '2026-02-14' }, + { id: 'd5', stage: 'proposal', region: 'amer', phase: 'p3', amount: 50, closed_on: '2026-03-01' }, + { id: 'd6', stage: 'won', region: 'apac', phase: 'p3', amount: 60, closed_on: '2026-03-09' }, + { id: 'd7', stage: 'lost', region: 'amer', phase: 'p3', amount: 70, closed_on: '2026-03-30' }, +] as const; +const TG_STAGES = new Set(TG_ROWS.map((r) => r.stage)).size; // 5 +const TG_PAIRS = new Set(TG_ROWS.map((r) => `${r.stage}|${r.region}`)).size; // 7 +const TG_MONTHS = new Set(TG_ROWS.map((r) => r.closed_on.slice(0, 7))).size; // 3 +// A select field with options: the plugin's label resolver makes its dimension +// label-bearing, so the tool's default order (every dimension, ascending, which +// `limit: cap + 1` brings in) sorts it by the label in memory and the window is +// applied there, not in SQL. The labels sort in another order than the values. +const TG_PHASE_OPTIONS = [ + { value: 'p1', label: 'Discovery' }, + { value: 'p2', label: 'Negotiation' }, + { value: 'p3', label: 'Closing' }, +]; +const TG_PHASES = new Set(TG_ROWS.map((r) => r.phase)).size; // 3 +const TG_DATASET = { + name: 'tg_pipeline', + label: 'Deal pipeline', + object: TG_OBJECT, + dimensions: [ + { name: 'stage', label: 'Stage', field: 'stage', type: 'string' }, + { name: 'region', label: 'Region', field: 'region', type: 'string' }, + { name: 'phase', label: 'Phase', field: 'phase', type: 'string' }, + { name: 'closed', label: 'Closed', field: 'closed_on', type: 'date' }, + ], + measures: [ + { name: 'revenue', label: 'Revenue', aggregate: 'sum', field: 'amount' }, + { name: 'deals', label: 'Deals', aggregate: 'count' }, + { name: 'emea_revenue', label: 'EMEA revenue', aggregate: 'sum', field: 'amount', filter: { region: 'emea' } }, + { name: 'avg_deal', label: 'Average deal', derived: { op: 'ratio', of: ['revenue', 'deals'] } }, + ], +}; +const TG_CELLS = [ + { id: 'sqlite', config: () => ({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) }, + { + id: 'postgres', + config: () => (process.env.OS_TEST_POSTGRES_URL ? { client: 'pg', connection: process.env.OS_TEST_POSTGRES_URL } : null), + }, +] as const; +const TG_CALLER = { userId: 'u_tg' } as ExecutionContext; +const tgSecurity = { + getReadFilter: async () => undefined, + canReadObject: () => true, + getReadableFields: async () => ['id', 'stage', 'region', 'phase', 'amount', 'closed_on'], + getQueryableFields: async () => ['id', 'stage', 'region', 'phase', 'amount', 'closed_on'], +}; +const tgQuiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return tgQuiet; } }; +const TG_WINDOW = 'COUNT(*) OVER ()'; + +for (const cell of TG_CELLS) { + const config = cell.config(); + describe.skipIf(!config)( + `[query_dataset totalGroups] the groups before the cut, counted by the statement that grouped them (${cell.id})${config ? '' : ' (skipped: set OS_TEST_POSTGRES_URL to run this cell)'}`, + () => { + let driver: SqlDriver; + let engine: ObjectQL; + const reads = { statements: [] as string[], aggregate: 0 }; + const services: Partial> = {}; + const loadTg = async () => [{ ...TG_DATASET }]; + + const run = async ( + face: 'native' | 'objectql' | 'guarded', + selection: Record, + opts: { maxQueryLimit?: number } = {}, + ) => { + const before = { statements: reads.statements.length, aggregate: reads.aggregate }; + const out = await services[face]!.datasetTools({ loadDatasets: loadTg, ...opts }).queryDataset( + { datasetName: TG_DATASET.name, selection }, + TG_CALLER, + ); + return { + out, + statements: reads.statements.slice(before.statements), + aggregate: reads.aggregate - before.aggregate, + }; + }; + + beforeAll(async () => { + driver = new SqlDriver(config as never); + if (cell.id === 'postgres') await (driver as any).execute(`drop table if exists ${TG_OBJECT}`).catch(() => {}); + engine = new ObjectQL({ logger: tgQuiet } as never); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registry.registerObject({ + name: TG_OBJECT, + label: 'Deal', + fields: { + stage: { name: 'stage', type: 'text' }, + region: { name: 'region', type: 'text' }, + phase: { name: 'phase', type: 'select', options: TG_PHASE_OPTIONS }, + amount: { name: 'amount', type: 'number' }, + closed_on: { name: 'closed_on', type: 'date' }, + }, + } as never, '@objectstack/service-analytics'); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + for (const row of TG_ROWS) await engine.insert(TG_OBJECT, { ...row } as never); + + const realExecute = (engine as any).execute.bind(engine); + (engine as any).execute = (sql: unknown, opts?: { object?: string }) => { + if (opts?.object === TG_OBJECT) reads.statements.push(String((sql as { sql?: string })?.sql ?? sql)); + return realExecute(sql, opts); + }; + const realAggregate = engine.aggregate.bind(engine); + (engine as any).aggregate = (object: string, ...rest: unknown[]) => { + if (object === TG_OBJECT) reads.aggregate += 1; + return (realAggregate as any)(object, ...rest); + }; + + for (const [face, caps] of [ + ['native', undefined], + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], + ['guarded', undefined], + ] as const) { + const registered: Record = {}; + await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } 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); + services[face] = registered.analytics as AnalyticsService; + } + // A host strategy ahead of the built-ins with a row guard of its own: + // it serves each query through the native strategy and keeps the first + // two rows. No built-in path cuts an unwindowed read; this is the shape + // a cap anywhere under the executor takes, so the arm is pinned on it. + const native = new NativeSQLStrategy(); + const rowGuard: AnalyticsStrategy = { + name: 'HostRowGuard', + priority: 5, + canHandle: (query, ctx) => native.canHandle(query, ctx), + execute: async (query, ctx) => { + const answer = await native.execute(query, ctx); + return { ...answer, rows: answer.rows.slice(0, 2) }; + }, + generateSql: (query, ctx) => native.generateSql(query, ctx), + }; + (services.guarded as unknown as { strategies: AnalyticsStrategy[] }).strategies.unshift(rowGuard); + }); + + afterAll(async () => { + if (cell.id === 'postgres') await (driver as any)?.execute(`drop table if exists ${TG_OBJECT}`).catch(() => {}); + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('a limit below the group count: truncated, and totalGroups counts every group, in one statement', async () => { + const { out, statements, aggregate } = await run('native', { + measures: ['revenue'], dimensions: ['stage'], order: { revenue: 'desc' }, limit: 2, + }); + expect(out).toMatchObject({ rowCount: 2, truncated: true, totalGroups: TG_STAGES }); + expect(out.rows.map((r) => r.stage), 'proposal 90, lost 70').toEqual(['proposal', 'lost']); + expect(statements, 'one statement grouped, cut and counted').toHaveLength(1); + expect(statements[0]).toContain(TG_WINDOW); + expect(aggregate, 'no engine aggregate').toBe(0); + for (const row of out.rows) expect(row).not.toHaveProperty('__os_group_count'); + expect(QueryDatasetOutputSchema.safeParse(out).success).toBe(true); + }); + + it('an answer not cut: totalGroups equals rowCount', async () => { + const { out, statements } = await run('native', { measures: ['revenue'], dimensions: ['stage'], limit: 10 }); + expect(out).toMatchObject({ rowCount: TG_STAGES, truncated: false, totalGroups: TG_STAGES }); + expect(statements).toHaveLength(1); + }); + + it('the tool\'s own row cap is a cut too, and two dimensions count their pairs', async () => { + const capped = await run('native', { measures: ['revenue'], dimensions: ['stage'] }, { maxQueryLimit: 3 }); + expect(capped.out).toMatchObject({ rowCount: 3, truncated: true, totalGroups: TG_STAGES }); + const pairs = await run('native', { measures: ['deals'], dimensions: ['stage', 'region'], limit: 1 }); + expect(pairs.out).toMatchObject({ rowCount: 1, truncated: true, totalGroups: TG_PAIRS }); + }); + + it('an offset: the count is before the offset; an empty page past the groups says nothing', async () => { + const page = await run('native', { measures: ['revenue'], dimensions: ['stage'], limit: 2, offset: 4 }); + expect(page.out).toMatchObject({ rowCount: 1, truncated: false, totalGroups: TG_STAGES }); + const past = await run('native', { measures: ['revenue'], dimensions: ['stage'], limit: 2, offset: 10 }); + expect(past.out).toMatchObject({ rowCount: 0, truncated: false }); + expect(past.out).not.toHaveProperty('totalGroups'); + }); + + it('no dimension: one group', async () => { + const { out } = await run('native', { measures: ['revenue', 'deals'] }); + expect(out).toMatchObject({ rowCount: 1, truncated: false, totalGroups: 1 }); + expect(out.rows[0]).toEqual({ revenue: 280, deals: 7 }); + }); + + it('a label-bearing dimension in the tool\'s default order, not cut: the grid windowed in memory is counted, totalGroups equals rowCount', async () => { + const { out, statements, aggregate } = await run('native', { measures: ['deals'], dimensions: ['phase'] }); + expect(out).toMatchObject({ rowCount: TG_PHASES, truncated: false, totalGroups: TG_PHASES }); + expect(out.totalGroups).toBe(out.rowCount); + expect(statements, 'the one grouped read, no second read to count').toHaveLength(1); + expect(statements[0], 'no window in SQL: the order is by label, so the window ran in memory').not.toContain(TG_WINDOW); + expect(statements[0]).not.toMatch(/\bLIMIT\b/i); + expect(aggregate).toBe(0); + expect(QueryDatasetOutputSchema.safeParse(out).success).toBe(true); + }); + + it('a label-bearing dimension in the tool\'s default order, cut: truncated, and totalGroups counts the whole grid', async () => { + const capped = await run('native', { measures: ['deals'], dimensions: ['phase'] }, { maxQueryLimit: 2 }); + expect(capped.out).toMatchObject({ rowCount: 2, truncated: true, totalGroups: TG_PHASES }); + expect(capped.statements).toHaveLength(1); + const deals = capped.out.rows.map((r) => r.deals); + expect(deals, 'ordered by label: Closing (p3), Discovery (p1)').toEqual([3, 2]); + // The in-memory window knows the whole grid, so a page past it still counts. + const past = await run('native', { measures: ['deals'], dimensions: ['phase'], limit: 2, offset: 10 }); + expect(past.out).toMatchObject({ rowCount: 0, truncated: false, totalGroups: TG_PHASES }); + }); + + it('an assembled grid (a measure with its own filter, a derived measure) is counted, with nothing extra read to count it', async () => { + for (const [measures, reads] of [[['revenue', 'emea_revenue'], 2], [['avg_deal'], 1]] as const) { + const { out, statements } = await run('native', { measures: [...measures], dimensions: ['stage'], limit: 2 }); + expect(out, measures.join(',')).toMatchObject({ rowCount: 2, truncated: true, totalGroups: TG_STAGES }); + expect(statements, `${measures.join(',')}: the pass's own reads only`).toHaveLength(reads); + for (const sql of statements) expect(sql).not.toContain(TG_WINDOW); + } + }); + + it('the engine\'s aggregate answers every group and the ObjectQL face windows them in memory: a date bucket, and the face itself', async () => { + const bucketed = await run('native', { + measures: ['revenue'], dimensions: ['closed'], timeDimensions: [{ dimension: 'closed', granularity: 'month' }], limit: 1, + }); + expect(bucketed.out).toMatchObject({ rowCount: 1, truncated: true, totalGroups: TG_MONTHS }); + expect(bucketed.aggregate, 'the ObjectQL face answered, once').toBe(1); + const face = await run('objectql', { measures: ['revenue'], dimensions: ['stage'], limit: 2 }); + expect(face.out).toMatchObject({ rowCount: 2, truncated: true, totalGroups: TG_STAGES }); + expect(face.aggregate).toBe(1); + expect(face.statements).toHaveLength(0); + const labelled = await run('objectql', { measures: ['deals'], dimensions: ['phase'] }, { maxQueryLimit: 1 }); + expect(labelled.out).toMatchObject({ rowCount: 1, truncated: true, totalGroups: TG_PHASES }); + expect(labelled.aggregate).toBe(1); + }); + + it('absent where a cap cut the grid before the in-memory window: a host row guard', async () => { + const { out, statements } = await run('guarded', { measures: ['deals'], dimensions: ['phase'] }); + expect(out, 'the guard kept two of the three groups').toMatchObject({ rowCount: 2, truncated: false }); + expect(out).not.toHaveProperty('totalGroups'); + expect(statements).toHaveLength(1); + }); + }, + ); +} + +describe('[query_dataset totalGroups] a SQL dialect the strategy does not know is not guessed at', () => { + it('runs no window and leaves totalGroups out', async () => { + // The engine double names no driver, so the strategy's dialect is `unknown`. + const rows = [{ stage: 'a', revenue: 1 }, { stage: 'b', revenue: 2 }, { stage: 'c', revenue: 3 }]; + const { service, statements } = await bootWired(rows); + const out = await service.datasetTools({ loadDatasets: loadSaved }).queryDataset( + { datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'], limit: 1 } }, + ADMIN, + ); + expect(out).toMatchObject({ rowCount: 1, truncated: true }); + expect(out).not.toHaveProperty('totalGroups'); + expect(statements).toHaveLength(1); + expect(statements[0]).toContain('LIMIT 2'); + expect(statements[0]).not.toContain(TG_WINDOW); + }); +}); + // [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 diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 6322bf7d3e9..c9546718237 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -119,6 +119,7 @@ import { type DateGranularityValue, } from './dataset-executor.js'; import { measureDrillScopes, type MeasureSource } from './drill-scope.js'; +import type { GroupCountRequest } from './dataset-group-count.js'; import { resolveDimensionLabels, createOrderLabelResolver, @@ -3064,12 +3065,19 @@ export class AnalyticsService implements IAnalyticsService { * degraded "backing object unavailable" return and the main return — so an * exit added later inherits it instead of needing its own copy. `query()` * never passes through here, so a cube answer carries none. + * + * [query_dataset totalGroups] `options.groupCount` asks for the number of + * groups the selection formed before its window cut them, written to the + * request's slot by the statement that grouped and cut them, or as the + * length of a whole grid the executor or the ObjectQL face windowed in + * memory (`dataset-group-count.ts`). The draft-preview read and the degraded + * "backing object unavailable" answer count nothing. */ async queryDataset( dataset: Dataset, selection: DatasetSelection, context?: ExecutionContext, - options?: { previewDrafts?: boolean }, + options?: { previewDrafts?: boolean; groupCount?: GroupCountRequest }, ): Promise { // The deployment's read limits judge the selection's own window — the // one a report or dashboard asked for — before anything runs (see @@ -3097,7 +3105,7 @@ export class AnalyticsService implements IAnalyticsService { dataset: Dataset, selection: DatasetSelection, context?: ExecutionContext, - options?: { previewDrafts?: boolean }, + options?: { previewDrafts?: boolean; groupCount?: GroupCountRequest }, ): Promise { // [#21177] The dataset's own dimension/measure `field` text — inline or saved, // whichever branch supplied it — is judged here: a `field` that is not a @@ -3384,7 +3392,10 @@ export class AnalyticsService implements IAnalyticsService { // branch above matches `row[key]`, which already reads the field. const bound = bindDatasetFiltersToObjectFields(resolved.compiled, resolved.selection, this.getObjectFieldNames?.(dataset.object)); const scoped = this.scopedService(this.requestScope(bound.compiled)); - result = await new DatasetExecutor(scoped, orderLabels).execute(bound.compiled, bound.selection, context); + const executor = new DatasetExecutor(scoped, orderLabels); + result = options?.groupCount + ? await executor.execute(bound.compiled, bound.selection, context, { groupCount: options.groupCount }) + : await executor.execute(bound.compiled, bound.selection, context); } catch (err) { // The producer answered the classification question — the route's // envelope reader serves it (4xx as itself; a declared 5xx relayed with diff --git a/packages/services/service-analytics/src/dataset-executor.ts b/packages/services/service-analytics/src/dataset-executor.ts index c8831c5e36e..ad6ee88d3bc 100644 --- a/packages/services/service-analytics/src/dataset-executor.ts +++ b/packages/services/service-analytics/src/dataset-executor.ts @@ -28,6 +28,7 @@ import { explicitDateRangeWindow } from './date-range-array-arm.js'; import { datasetInvalidError } from './dataset-refusal.js'; import { durationMeasureIn } from './duration-measure-sql.js'; import type { OrderLabelResolver } from './dimension-labels.js'; +import { noteWholeRead, withGroupCountRequest, type GroupCountRequest, type WholeGridProof } from './dataset-group-count.js'; // Re-export the shared protocol shapes so existing importers keep working. export type { DatasetSelection } from '@objectstack/spec/contracts'; @@ -1223,18 +1224,26 @@ export class DatasetExecutor { * @param context - The request's ExecutionContext, threaded into every * underlying `IAnalyticsService.query` so the tenant/RLS read scope is * applied per request (ADR-0021 D-C). + * @param options.groupCount - [query_dataset totalGroups] Count the + * selection's groups before its window cut them (`dataset-group-count.ts`). + * For a selection that is ONE query whose order and window the strategy + * applied, by that strategy, when it counted. For a grid this executor + * windows in memory, as the grid's length before the window, when every + * read that built it was vouched whole. The slot is left empty otherwise, + * and no read is ever added to fill it. */ async execute( compiledInput: CompiledDataset, selectionInput: DatasetSelection, context?: ExecutionContext, + options?: { groupCount?: GroupCountRequest }, ): Promise { // framework#3582 — expand `{current_quarter_start}` / `{current_user_id}` // placeholders BEFORE any query is shaped, once for the whole call so every // sub-query (measure-scoped, totals, compareTo) shares one instant. const { compiled, selection } = resolveSelectionTokens(compiledInput, selectionInput, context); - const result = await this.executeSelection(compiled, selection, context); + const result = await this.executeSelection(compiled, selection, context, options?.groupCount); // Server-side totals (#1753) — re-run the selection grouped by each // requested dimension subset, so a subtotal/grand total is the measure's @@ -1276,6 +1285,7 @@ export class DatasetExecutor { compiled: CompiledDataset, selection: DatasetSelection, context?: ExecutionContext, + groupCount?: GroupCountRequest, ): Promise { // Base measures = selected non-derived + the aggregated measures the // selected derived ones reach through `of`, at any depth (#28127). @@ -1317,6 +1327,12 @@ export class DatasetExecutor { const windowQuery = canPushDownWindow ? { order, limit: selection.limit, offset: selection.offset } : undefined; + // [query_dataset totalGroups] Two ways to count, never a read to count. + // Pushed down, the one query counts its own groups (`counted`). Windowed + // here, the grid before the window is the count — but only a grid every + // read of which came back whole, which `wholeness` records read by read. + const counted: GroupCountRequest | undefined = groupCount && canPushDownWindow ? {} : undefined; + const wholeness: WholeGridProof | undefined = groupCount && !canPushDownWindow ? { whole: true } : undefined; // The current-period pass: unfiltered base measures in one query plus one // supplementary query per measure-scoped filter, merged by dimension key. @@ -1325,12 +1341,14 @@ export class DatasetExecutor { dimensions, baseFilter, window: windowQuery, + groupCount: counted, + wholeness, context, }); // compareTo — run the SAME pass over the shifted window and attach. if (selection.compareTo) { - const compareRows = await this.runCompare(compiled, selection, [...baseMeasures], dimensions, baseFilter, context); + const compareRows = await this.runCompare(compiled, selection, [...baseMeasures], dimensions, baseFilter, context, wholeness); result.rows = mergeByDimensions( result.rows, compareRows, @@ -1345,6 +1363,9 @@ export class DatasetExecutor { // the invented rows' measure cells their value. const bucketFill = this.timeBucketFillPlan(compiled, selection, dimensions, order, context); if (bucketFill) fillEmptyTimeBuckets(result.rows, bucketFill); + // [query_dataset totalGroups] Handed on only for a grid this pass did not + // grow: an invented bucket is a group the statement never counted. + if (groupCount && counted?.outcome && !bucketFill) groupCount.outcome = counted.outcome; // Empty-group fill (#4708) — a group a query never reported reads `0` for a // count/sum and stays null for avg/min/max. See {@link fillEmptyGroups} for @@ -1413,6 +1434,12 @@ export class DatasetExecutor { if (labels && labels.size > 0) (sortKeys ??= {})[key] = labels; } result.rows = applyOrdering(result.rows, order, sortKeys); + // [query_dataset totalGroups] The grid in hand is every group the selection + // formed — each read that built it answered whole, and every merge and + // derived pass above keeps or appends rows, never drops one — so its + // length before the window is the count. Not for a grid the time-bucket + // fill grew: an invented bucket is no group any read formed. + if (groupCount && wholeness?.whole && !bucketFill) groupCount.outcome = { groupCount: result.rows.length }; if (!canPushDownWindow) result.rows = applyWindow(result.rows, selection.limit, selection.offset); return result; @@ -1456,10 +1483,18 @@ export class DatasetExecutor { dimensions: string[]; baseFilter?: FilterCondition; window?: { order?: Record; limit?: number; offset?: number }; + /** [query_dataset totalGroups] Rides on the primary query; set only beside `window`. */ + groupCount?: GroupCountRequest; + /** + * [query_dataset totalGroups] Set only WITHOUT `window`: every read this + * pass issues carries its own request, and the ledger turns `false` on + * the first one that does not come back vouched whole. + */ + wholeness?: WholeGridProof; context?: ExecutionContext; }, ): Promise { - const { measures, dimensions, baseFilter, window, context } = opts; + const { measures, dimensions, baseFilter, window, groupCount, wholeness, context } = opts; const { unfiltered, filtered } = splitMeasuresByFilter(measures, compiled.measureFilters); // Primary query: all unfiltered base measures in one pass. When every base @@ -1467,14 +1502,17 @@ export class DatasetExecutor { const primary = unfiltered.length > 0 || filtered.length === 0; let result: AnalyticsResult; if (primary) { - result = await this.service.query(this.buildQuery(compiled, { + const query = this.buildQuery(compiled, { measures: unfiltered, dimensions, where: baseFilter, selection, contextTimezone: context?.timezone, window, - }), context); + }); + const request: GroupCountRequest | undefined = groupCount ?? (wholeness ? {} : undefined); + result = await this.service.query(request ? withGroupCountRequest(query, request) : query, context); + if (wholeness && request) noteWholeRead(wholeness, request, result.rows); } else { result = { rows: [], fields: [] }; } @@ -1483,10 +1521,13 @@ export class DatasetExecutor { const measureNames = new Set(measures); for (const [i, m] of filtered.entries()) { const mFilter = combineFilters(baseFilter, compiled.measureFilters[m]); - const sub = await this.service.query(this.buildQuery(compiled, { + const subQuery = this.buildQuery(compiled, { measures: [m], dimensions, where: mFilter, selection, contextTimezone: context?.timezone, - }), context); + }); + const subRequest: GroupCountRequest | undefined = wholeness ? {} : undefined; + const sub = await this.service.query(subRequest ? withGroupCountRequest(subQuery, subRequest) : subQuery, context); + if (wholeness && subRequest) noteWholeRead(wholeness, subRequest, sub.rows); result.rows = mergeByDimensions(result.rows, sub.rows, dimensions, [m]); // #5537 — with NO primary query there is nothing carrying the grid's // DIMENSION descriptors, and this loop only ever appends MEASURE ones. The @@ -1747,6 +1788,7 @@ export class DatasetExecutor { dimensions: string[], baseFilter: FilterCondition | undefined, context?: ExecutionContext, + wholeness?: WholeGridProof, ): Promise[]> { const cmp = selection.compareTo!; // `dimension` is optional since #5011; resolve it (or fail loudly) before @@ -1810,7 +1852,7 @@ export class DatasetExecutor { const sub = await this.runMeasurePass( compiled, { ...selection, timeDimensions: shiftedTd }, - { measures, dimensions, baseFilter, context }, + { measures, dimensions, baseFilter, wholeness, context }, ); // #6007 — when the anchor is ALSO a grid dimension, the comparison rows key diff --git a/packages/services/service-analytics/src/dataset-group-count.ts b/packages/services/service-analytics/src/dataset-group-count.ts new file mode 100644 index 00000000000..4f5686ab70b --- /dev/null +++ b/packages/services/service-analytics/src/dataset-group-count.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `query_dataset`'s `totalGroups`: how many groups a selection formed before + * its `offset` and `limit` cut them. The same meaning as `aggregate_records`' + * `totalGroups`, which is the length of the rows `engine.aggregate` answered + * (`rows.length`), taken before that tool's own cap cuts them — the same + * reading as Source 2 below. It is never paid for with a read: it comes from + * one of two places, and from nowhere else. + * + * ## Source 1: the database, where the window is pushed down + * + * When the one statement that grouped the answer also cut it, the count is a + * window in that statement — `SELECT …, COUNT(*) OVER () AS + * "__os_group_count" FROM … GROUP BY … ORDER BY … LIMIT n`. A window runs after + * the `GROUP BY` and ahead of the `ORDER BY` and the window, so every row + * carries the number of groups the statement formed: one statement, one round + * trip, and no group is read to be counted. `NativeSQLStrategy` adds it only on + * a dialect it knows ({@link GROUP_COUNT_DIALECTS}), never under a selected + * member's own name, and an empty page after an `offset` says nothing. + * + * ## Source 2: a whole grid, where the window is applied in memory + * + * Where the window is applied in memory, the grid in hand before it IS every + * group: the executor's grid when it cannot push the window down (a + * label-bearing order key, which the tool's default order brings in for any + * select or reference dimension; a measure with its own filter; a derived + * measure; `compareTo`), and the ObjectQL face's rows, which `engine.aggregate` + * answers whole because it is handed no window. The count is then the grid's + * length before the window. "Whole" is vouched for, never assumed: each read + * that built the grid carries a request, and the strategy that served it + * answers it only when it applied no window and no cap — the native strategy + * 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. + * + * ## Asked for, never assumed + * + * The request rides on a {@link GroupCountRequest} the caller hands down: + * `AnalyticsService.queryDataset(…, { groupCount })` → `DatasetExecutor` → + * each query it issues, on the symbol key {@link ANALYTICS_GROUP_COUNT}. + * No wire request, JSON body or spread author input can carry a symbol, so the + * public query vocabulary (`AnalyticsQuery`, `DatasetSelection`) is unchanged, + * and a statement no caller asked to count is the statement it always was. + * + * ## Absent everywhere else + * + * Prime Directive 5 (ruling record 6888468549): no slower path is built for + * the count. An answer neither source covers leaves the request unanswered, + * and the tool then leaves `totalGroups` out: a pushed-down window on a SQL + * dialect the strategy does not know or under a member named + * {@link ANALYTICS_GROUP_COUNT_COLUMN}, an empty page after an `offset` on a + * pushed-down window, a read the strategy that served it did not vouch whole + * (a host-injected strategy or fallback service that does not answer the + * request) or that a cap cut under it, a grid grown by the empty + * time-bucket fill, the draft-preview read, and the answer served for a + * missing object. + */ + +import type { AnalyticsQuery } from '@objectstack/spec/contracts'; +import type { AnalyticsSqlDialect } from './text-match-sql.js'; + +/** What the counting layer found: set only once a statement counted the groups. */ +export interface GroupCountOutcome { + /** How many groups the statement formed before its `offset` and `limit`. */ + readonly groupCount: number; +} + +/** + * A request to count a selection's groups, and the slot the answer is written + * to. A caller hands it down and reads the slot back after the read: a read + * that came back with no outcome was not counted, and its count is unknown — + * never zero. + */ +export interface GroupCountRequest { + outcome?: GroupCountOutcome; +} + +/** + * The `AnalyticsQuery` key a {@link GroupCountRequest} rides to the strategy + * on. A `Symbol.for` key, so every copy of the package agrees on it, and a + * symbol, so no wire request can carry it. Object spreads keep it, so the + * service's copy-on-write passes over the query hand it on unchanged. + */ +export const ANALYTICS_GROUP_COUNT: unique symbol = Symbol.for('objectstack.analytics.groupCount'); + +/** + * The column the statement answers the group count under, on every row. Taken + * off the rows by the strategy before anyone reads them; a selected member of + * the same name leaves the request unanswered, so it never shadows one. + */ +export const ANALYTICS_GROUP_COUNT_COLUMN = '__os_group_count'; + +/** + * The dialects whose grouped statement the strategy adds the window count to: + * every one `COUNT(*) OVER ()` parses on (SQLite ≥ 3.25, PostgreSQL, MySQL 8, + * SQL Server). A dialect the strategy does not know is not guessed at. + */ +export const GROUP_COUNT_DIALECTS: ReadonlySet = new Set(['sqlite', 'postgres', 'mysql', 'mssql']); + +/** + * Answer `request` for rows a strategy read with no window and no cap: every + * group the read formed came back, so the count is the rows'. Called only + * where that holds — never on rows a `LIMIT`, an `OFFSET` or a guard cut. + */ +export function answerWholeGrid(rows: unknown, request: GroupCountRequest): void { + if (Array.isArray(rows)) request.outcome = { groupCount: rows.length }; +} + +/** Whether `window` cuts anything: a `limit` or an `offset` is set. */ +export function hasWindow(window: { readonly limit?: number | null; readonly offset?: number | null }): boolean { + return window.limit != null || window.offset != null; +} + +/** + * The executor's ledger for a grid it builds from several reads and windows in + * memory: whole while every read that built it was. Starts `true`; one read + * that comes back unvouched turns it `false` for good. + */ +export interface WholeGridProof { + whole: boolean; +} + +/** + * Note one read against `proof`. The read was whole only when the strategy + * that served it answered `request` (it applied no window and no cap) AND the + * count it answered equals the rows that came back — a guard that cut the + * rows after the strategy counted them is caught here, by the mismatch. + */ +export function noteWholeRead(proof: WholeGridProof, request: GroupCountRequest, rows: unknown): void { + if (!Array.isArray(rows) || request.outcome?.groupCount !== rows.length) proof.whole = false; +} + +/** `query` carrying `request` under {@link ANALYTICS_GROUP_COUNT}: a copy, the input untouched. */ +export function withGroupCountRequest(query: AnalyticsQuery, request: GroupCountRequest): AnalyticsQuery { + return { ...query, [ANALYTICS_GROUP_COUNT]: request } as AnalyticsQuery; +} + +/** The {@link GroupCountRequest} `query` carries, or `undefined`. */ +export function groupCountRequestOf(query: AnalyticsQuery): GroupCountRequest | undefined { + const request = (query as unknown as Record)[ANALYTICS_GROUP_COUNT]; + return request !== null && typeof request === 'object' ? (request as GroupCountRequest) : undefined; +} + +/** + * Take the count off the rows a counted statement answered, and write it to + * `request`. Every row loses the column. The count is read off the first row — + * the window answers the same number on every row — as the SQL client handed + * it (node-postgres answers a `bigint` as text). No row means no group only + * when the statement skipped none and could answer one: with an `offset`, or a + * `limit` of zero, an empty page says nothing about the groups before it, and + * the request is left unanswered. A value that is not a whole count leaves it + * unanswered too. + */ +export function takeGroupCount( + rows: unknown, + request: GroupCountRequest, + window: { readonly limit?: number; readonly offset?: number }, +): void { + if (!Array.isArray(rows)) return; + let first: unknown; + for (const row of rows) { + if (row === null || typeof row !== 'object') continue; + const record = row as Record; + if (first === undefined) first = record[ANALYTICS_GROUP_COUNT_COLUMN]; + delete record[ANALYTICS_GROUP_COUNT_COLUMN]; + } + if (rows.length === 0) { + if ((window.offset ?? 0) === 0 && window.limit !== 0) request.outcome = { groupCount: 0 }; + return; + } + const count = typeof first === 'bigint' ? Number(first) : typeof first === 'string' && first.trim() !== '' ? Number(first) : first; + if (typeof count === 'number' && Number.isSafeInteger(count) && count >= 0) request.outcome = { groupCount: count }; +} diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 44de1be177b..4ee58e083bb 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -35,6 +35,7 @@ import { } from './dataset-declared-members.js'; import { findDatasetTermCandidates, matchDatasetTerms, type CandidateDataset } from './dataset-term-matcher.js'; import { DATASET_NEXT_STEP_PRECEDENCE, composeDatasetNextStep, composeDatasetSourceLine } from './dataset-next-step.js'; +import type { GroupCountRequest } from './dataset-group-count.js'; /** * The dataset AI tools — `list_datasets` and `query_dataset` — defined once, @@ -572,7 +573,13 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { ? raw.selection.limit : maxRows; const selection: DatasetSelection = { ...raw.selection, limit: cap + 1 }; - const answer: AnalyticsResult = await service.queryDataset(dataset, selection, context); + // [query_dataset totalGroups] The groups before the cut, counted by the + // statement that grouped and cut them, or as the length of a whole grid + // windowed in memory (`dataset-group-count.ts`); an answer neither covers + // leaves the slot empty and the member out. + const groupCount: GroupCountRequest = {}; + const answer: AnalyticsResult = await service.queryDataset(dataset, selection, context, { groupCount }); + const totalGroups = groupCount.outcome?.groupCount; const rows = Array.isArray(answer.rows) ? answer.rows : []; const truncated = rows.length > cap; @@ -600,6 +607,7 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { sourceLine: composeDatasetSourceLine(provenance, sentenceLocales(context)), rowCount: served.length, truncated, + ...(totalGroups !== undefined ? { totalGroups } : {}), ...(narrowing?.narrowed && narrowing.statement ? { delegationNarrowed: true as const, warning: narrowing.statement } : {}), diff --git a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts index 8c01a168639..4f5b33fe51d 100644 --- a/packages/services/service-analytics/src/strategies/native-sql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/native-sql-strategy.ts @@ -54,6 +54,14 @@ import { hasJsonMembershipSql, isJsonStoredShape } from '../contains-membership- import { expandEmptyOperator } from '@objectstack/spec/data'; import { resolveAnalyticsDateRangeString } from '@objectstack/core'; import { dateRangeWindowBounds } from '../dataset-executor.js'; +import { + ANALYTICS_GROUP_COUNT_COLUMN, + GROUP_COUNT_DIALECTS, + answerWholeGrid, + groupCountRequestOf, + hasWindow, + takeGroupCount, +} from '../dataset-group-count.js'; // [#20889] What each aggregate function ANSWERS, and the `'number'` presenter — // the rule `driver-sql`'s own `aggregate()` applies, defined once in core. import { AGGREGATE_ANSWER_KIND, presentAsNumber } from '@objectstack/core'; @@ -672,6 +680,23 @@ function judgedComparands(source: unknown, typeOf: MemberDeclaredType | null): u return judged === condition ? source : { where: judged }; } +/** The window the group count is answered by: `COUNT(*) OVER ()` over the grouped statement. */ +const GROUP_COUNT_WINDOW_SQL = `COUNT(*) OVER () AS "${ANALYTICS_GROUP_COUNT_COLUMN}"`; + +/** + * [query_dataset totalGroups] The statement's projection, with the group-count + * window appended when `query` carries a count request + * (`dataset-group-count.ts`) AND a window to count past, `dialect` parses the + * window, and no selected member already answers under its column. Otherwise + * the projection as compiled. A statement with no window needs none: every + * group it forms comes back, and the request is answered from the rows. + */ +function countedGroupsSql(query: AnalyticsQuery, dialect: AnalyticsSqlDialect, selectClauses: string[]): string[] { + if (!groupCountRequestOf(query) || !hasWindow(query) || !GROUP_COUNT_DIALECTS.has(dialect)) return selectClauses; + if (selectClauses.some((clause) => clause.endsWith(` AS "${ANALYTICS_GROUP_COUNT_COLUMN}"`))) return selectClauses; + return [...selectClauses, GROUP_COUNT_WINDOW_SQL]; +} + /** * NativeSQLStrategy — Priority 1 * @@ -1346,6 +1371,19 @@ export class NativeSQLStrategy implements AnalyticsStrategy { } } + // [query_dataset totalGroups] The count the statement answered on every + // row is taken off the rows before anyone reads them, and written to the + // caller's request (`dataset-group-count.ts`). A statement with no + // `LIMIT` or `OFFSET` handed back every group it formed: the rows ARE the + // count, and the request is answered from them — the executor's proof + // that a grid it windows in memory is whole. + const groupCount = groupCountRequestOf(query); + if (groupCount && sql.includes(GROUP_COUNT_WINDOW_SQL)) { + takeGroupCount(rows, groupCount, { limit: query.limit, offset: query.offset }); + } else if (groupCount && !hasWindow(query)) { + answerWholeGrid(rows, groupCount); + } + // Build field metadata const fields = this.buildFieldMeta(query, cube); @@ -1649,7 +1687,13 @@ export class NativeSQLStrategy implements AnalyticsStrategy { // order states its NULL placement in it. [#31626] SQL Server's lone limit // is a `TOP (n)` after `SELECT` (`windowTopSql`). const dialect = sqlDialectFor(ctx, this.extractObjectName(cube)); - let sql = `SELECT ${windowTopSql(query.limit, query.offset, dialect)}${selectClauses.join(', ')} FROM "${tableName}"`; + // [query_dataset totalGroups] A caller that asked for the group count + // (`dataset-group-count.ts`) gets it from THIS statement: a window over + // its groups runs after the `GROUP BY` and ahead of the `ORDER BY` and the + // window, so every row answers how many groups formed before the cut. Only + // on a dialect it parses on, and never under a member's own name. + const projected = countedGroupsSql(query, dialect, selectClauses); + let sql = `SELECT ${windowTopSql(query.limit, query.offset, dialect)}${projected.join(', ')} FROM "${tableName}"`; if (joins.size > 0) { sql += ' ' + Array.from(joins.values(), (join) => join.sql).join(' '); } diff --git a/packages/services/service-analytics/src/strategies/objectql-strategy.ts b/packages/services/service-analytics/src/strategies/objectql-strategy.ts index 53b62613874..ec06fe1f2b8 100644 --- a/packages/services/service-analytics/src/strategies/objectql-strategy.ts +++ b/packages/services/service-analytics/src/strategies/objectql-strategy.ts @@ -70,6 +70,7 @@ import { // of an offset-only window per dialect, shared with the native face. // [#25907] `orderClauseSql` likewise for the order and its NULL placement. import { aggregateOfMeasure, orderClauseSql, windowClauseSql, windowTopSql } from './native-sql-strategy.js'; +import { answerWholeGrid, groupCountRequestOf } from '../dataset-group-count.js'; /** * [#10861 / commit 399ecad58] Where a member in the cross-object envelope's inventory @@ -812,6 +813,14 @@ export class ObjectQLStrategy implements AnalyticsStrategy { * orders chronologically here.) */ private orderAndWindow(query: AnalyticsQuery, rows: Record[]): Record[] { + // [query_dataset totalGroups] The rows in hand are every group: no read + // above hands `engine.aggregate` an order or a window, so it answers the + // whole grid, and the cut is this line's. A caller that asked for the + // group count (`dataset-group-count.ts`) gets the grid's length before the + // cut — no read is added for it. A read that ever hands the engine a + // window must take the count from the engine instead, never from here. + const groupCount = groupCountRequestOf(query); + if (groupCount) answerWholeGrid(rows, groupCount); return applyWindow(applyOrdering(rows, query.order), query.limit, query.offset); } diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 95b2a780c22..651a1ba4ae8 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -374,6 +374,7 @@ "ai/QueryDatasetOutput:rowCount", "ai/QueryDatasetOutput:rows", "ai/QueryDatasetOutput:sourceLine", + "ai/QueryDatasetOutput:totalGroups", "ai/QueryDatasetOutput:totals", "ai/QueryDatasetOutput:truncated", "ai/QueryDatasetOutput:warning", diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index e9729c3c938..01106cca63b 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -404,7 +404,8 @@ export const DatasetProvenanceSchema = lazySchema(() => z.object({ /** * `query_dataset` output: the dataset answer the REST door serves, without the - * executed SQL, plus `provenance`, `rowCount` and `truncated`. + * executed SQL, plus `provenance`, `rowCount`, `truncated` and, where the + * groups were counted without a read, `totalGroups`. * * The answer's members are taken BY REFERENCE from * `AnalyticsResultResponseSchema`'s `data`, so a column property the REST door @@ -430,6 +431,23 @@ export const QueryDatasetOutputSchema = lazySchema(() => AnalyticsResultResponse truncated: z.boolean().describe( '`true` when more rows existed past the row cap the tool applied and were not returned', ), + totalGroups: z.number().int().nonnegative().optional().describe( + 'How many groups the selection formed before `offset` and `limit` cut them: the rows the same selection ' + + 'answers with no window. The same name and meaning as `aggregate_records`\' `totalGroups`. Never paid for ' + + 'with a read. Where the window is pushed into the one SQL statement that grouped the answer, the database ' + + 'counts the groups with a window count in that statement. Where the window is applied in memory, it is the ' + + 'length of the grid before the window: an order by a display label (the tool\'s own order when none is sent ' + + 'sorts every selected dimension, so any select or reference dimension brings it in; an order by measures ' + + 'alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, ' + + '`compareTo`), and a query the engine\'s aggregate serves, such as a date bucket, a field-to-field filter, an ' + + 'external object or a driver with no raw SQL. That grid is counted only when every read that built it came ' + + 'back whole: a grid that any cap or row guard cut before the window answers no count. Equals `rowCount` when ' + + 'the answer was not cut. Absent otherwise, which is when: the window was pushed down and the SQL dialect is ' + + 'not one the tool knows, or a selected member is itself named `__os_group_count`, or the page came back ' + + 'empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a ' + + 'host adds, or was cut by a cap under it; or the dataset\'s object is missing and the answer is the empty ' + + 'one served for it', + ), delegationNarrowed: z.literal(true).optional().describe( 'Present, and `true`, when the caller acts as an agent whose authority narrows what it may read on the ' + 'dataset\'s object; `warning` states the narrowing (ADR-0090 D10)',