From b8e99813623cceb45a4a06c2befbfd83439a8462 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 15:56:07 +0000 Subject: [PATCH 1/5] wip(analytics): per-measure drill scope on the dataset answer Claude-Session: https://claude.ai/code/session_01L6bhgXexAhb1ogpnymn5Jb Co-authored-by: Claude --- .../src/analytics-service.ts | 51 ++++++- .../service-analytics/src/dataset-executor.ts | 7 +- .../service-analytics/src/drill-scope.ts | 134 ++++++++++++++++++ packages/spec/src/api/analytics.zod.ts | 15 ++ .../spec/src/contracts/analytics-service.ts | 44 +++++- 5 files changed, 246 insertions(+), 5 deletions(-) create mode 100644 packages/services/service-analytics/src/drill-scope.ts diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index fe12deab3d9..bca6a0582f4 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -112,8 +112,10 @@ import { DatasetExecutor, declaredDefaultGranularity, resolveDimensionGranularity, + resolveSelectionTokens, type DateGranularityValue, } from './dataset-executor.js'; +import { measureDrillScopes, type MeasureSource } from './drill-scope.js'; import { resolveDimensionLabels, createOrderLabelResolver, @@ -126,7 +128,7 @@ import { assertDatasetGroupColumnsDistinct } from './dataset-group-column-door.j import { assertDatasetDateBucketsTemporal } from './dataset-date-bucket-door.js'; // [#25778] The one lookup of a dataset duration measure by name. import { durationMeasureIn } from './duration-measure-sql.js'; -import { scopedMeasureFilter } from './scoped-measure-key.js'; +import { scopedMeasureFilter, scopedMeasureKey } from './scoped-measure-key.js'; // [#5918] The measure mint refuses a dotted member through the SAME constructor // the strategies' member-level refusals use — `INVALID_FIELD` / 400, naming the // member as the request spelled it (see `dataset-refusal.ts`'s header for why @@ -3066,6 +3068,12 @@ export class AnalyticsService implements IAnalyticsService { // #5033 symptom wearing the opposite disguise — the caller's own mistake // reported as "no data", with no exception, no 4xx, no 5xx, just a warn and // a confident empty chart. See {@link hasDeclaredErrorEnvelope}. + // [#30526] Tokens resolved ONCE, here, for both readers of the filters: the + // executor, which computes the numbers (its own resolution is then the + // identity), and `drillScopes` below, which states the same filters to the + // drill. Two resolutions could straddle a period boundary, and the drill + // would list another period than the number counted. + const resolved = resolveSelectionTokens(compiled, selection, context); let result: AnalyticsResult; try { // [#20356] Through the call's own scope, never `this`: every query the @@ -3076,7 +3084,7 @@ export class AnalyticsService implements IAnalyticsService { // fields they name, never by a dimension that happens to share the name: // see `dataset-filter-field-binding.ts`. Only this face: the draft-preview // branch above matches `row[key]`, which already reads the field. - const bound = bindDatasetFiltersToObjectFields(compiled, selection, this.getObjectFieldNames?.(dataset.object)); + 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); } catch (err) { @@ -3244,6 +3252,22 @@ export class AnalyticsService implements IAnalyticsService { }); } + // [#30526] The MEASURE drill scope: what each number counted beyond the + // bucket and the widget filter (the dataset's and the measure's own + // filters, and the aggregated column holding a value), which the host + // cannot read anywhere else. From the token-resolved filters BEFORE the + // field binding above, whose minted member names no record list knows. + // See `drill-scope.ts` for what is left out and why. + if (result.rows.length) { + const scoped = resolved.compiled; + result.drillScopes = measureDrillScopes({ + measures: selection.measures ?? [], + filter: scoped.filter, + measureFilterOf: (m) => scopedMeasureFilter(scoped, m, scoped.cube.name), + sourceOf: (m) => datasetMeasureSource(scoped, m), + }); + } + // ADR-0021 — resolve grouped dimension values to human display labels // (select option label, lookup related-record name). Charts render the // dimension key verbatim, so this is the single place that turns a stored @@ -4925,6 +4949,29 @@ function mintCallerMeasures( return minted; } +/** + * [#30526] What the selected measure `m` aggregates on `compiled`, resolved the + * way the queries resolved it — the input `measureDrillScopes` reads + * (`drill-scope.ts`): a derived measure by name, bare or `.`-qualified; a + * duration measure through {@link durationMeasureIn}; a declared cube measure + * through {@link scopedMeasureKey}; and an undeclared one through + * {@link mintCallerMeasures}, the mint `ensureCube` ran for the query. + * `undefined` when none of them answers. + */ +function datasetMeasureSource(compiled: CompiledDataset, m: string): MeasureSource | undefined { + const cubeName = compiled.cube.name; + if (compiled.derived.some((d) => d.name === m || `${cubeName}.${d.name}` === m)) return { kind: 'derived' }; + const duration = durationMeasureIn(compiled.durations, m, cubeName); + if (duration) return { kind: 'duration', from: duration.from, to: duration.to }; + const key = scopedMeasureKey(compiled.cube.measures, m, cubeName); + const metric = key !== undefined + ? compiled.cube.measures[key] + : mintCallerMeasures([m], compiled.cube, cubeName, compiled.durations)[mintableMeasureKey(m, cubeName)]; + const sql = typeof metric?.sql === 'string' ? metric.sql.trim() : ''; + if (!sql) return undefined; + return sql === '*' ? { kind: 'rows' } : { kind: 'field', field: sql }; +} + /** * The aggregation suffixes {@link inferMeasure} strips, in the order it tries * them — the ONE list. `_count_distinct` precedes the shorter suffixes so the diff --git a/packages/services/service-analytics/src/dataset-executor.ts b/packages/services/service-analytics/src/dataset-executor.ts index 8aec2467b1d..c8831c5e36e 100644 --- a/packages/services/service-analytics/src/dataset-executor.ts +++ b/packages/services/service-analytics/src/dataset-executor.ts @@ -119,8 +119,13 @@ export type CompareTo = DatasetCompareTo; * registry across requests, so resolving in place would bake one request's * user id (and one day's dates) into every later render. New objects are * allocated only when the tree actually held a placeholder. + * + * [#30526] Exported for `AnalyticsService.queryDataset`, which resolves once + * ahead of the executor so the answer's `drillScopes` and its numbers read one + * instant; the executor's own call is then the identity (nothing is left to + * resolve, so the same trees come back). */ -function resolveSelectionTokens( +export function resolveSelectionTokens( compiled: CompiledDataset, selection: DatasetSelection, context?: ExecutionContext, diff --git a/packages/services/service-analytics/src/drill-scope.ts b/packages/services/service-analytics/src/drill-scope.ts new file mode 100644 index 00000000000..e767ad85891 --- /dev/null +++ b/packages/services/service-analytics/src/drill-scope.ts @@ -0,0 +1,134 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#30526] The per-measure drill scope a dataset answer carries + * (`AnalyticsResult.drillScopes`, ADR-0021 D2): for each selected measure, the + * list filter on the dataset's object that selects the records that measure + * aggregates. + * + * ## Why the server says it + * + * A dataset number is computed under three filters at once (`DatasetExecutor`): + * the dataset's own `filter`, the measure's own `filter` (one supplementary + * query per filtered measure), and the selection's `runtimeFilter`. A host that + * drills a clicked number holds only the last one: it has no read of the + * dataset definition, and ADR-0021 D2 keeps it that way (the server answers the + * drill bounds, the client never restates dataset semantics). So a drill built + * from the bucket and the widget filter alone lists a superset of the records + * a filtered measure counted. This module states the missing two, in the one + * filter vocabulary both the dataset and the record list speak + * (`FilterCondition`). + * + * ## What a scope is + * + * `dataset.filter` AND the measure's `filter` AND, for a measure that + * aggregates a column, that column holding a value. The last leg is what every + * aggregate does with an empty value: it skips it, so a `count` over a field is + * the number of records where the field is set (`COUNT(field)`, #10298), and a + * duration reads only records with both instants set. A `count` over rows has + * no such leg. When no leg applies the scope is `{}`. + * + * The inputs are the filters AFTER token resolution, at the instant the query + * resolved them (`queryDataset` resolves once and hands the same trees to the + * executor and here), and BEFORE the dataset door's field binding + * (`dataset-filter-field-binding.ts`), whose minted member names are a + * request-local spelling no record list knows. + * + * ## What has no scope (absence means "offers no drill") + * + * - A derived measure: it combines other measures, so no single record set is + * behind its number. + * - A measure the dataset neither declares nor mints, which the caller cannot + * have been answered for anyway. + * - A scope naming a RELATIONSHIP PATH, as a dotted filter key + * (`account.region`) or a dotted `$field` reference: the dataset door joins + * it through `include`, while the record list refuses a dotted filter key + * (`INVALID_FIELD`, `@objectstack/objectql`'s explicit filter field gate). + * The nested-relation form (`{ account: { region: 'emea' } }`) is kept: the + * engine serves it on the list as it does on the analytics face. + * - A filter that is not a plain condition object. + * + * The scope is a deep copy: the filters are the dataset definition's own + * objects, which outlive the request, and an answer is handed to callers that + * may compose into it. + */ + +import type { FilterCondition } from '@objectstack/spec/data'; + +/** What one selected measure aggregates, as the executor runs it. */ +export type MeasureSource = + /** Combines other measures; has no record set of its own. */ + | { kind: 'derived' } + /** `count` over rows: every record in scope counts. */ + | { kind: 'rows' } + /** An aggregate over one column, which skips an empty value. */ + | { kind: 'field'; field: string } + /** A duration measure, which reads only records with both instants set. */ + | { kind: 'duration'; from: string; to: string }; + +/** A plain condition object: not `null`, not an array, not a `Date`. */ +function isConditionObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date); +} + +/** + * Does `node` name a relationship path anywhere: a dotted field key, or a + * dotted `$field` reference? Walks `$and` / `$or` / `$not`, operator maps, + * nested-relation specs and comparand lists alike; a string comparand is data + * and is never read as a path. + */ +export function namesRelationshipPath(node: unknown): boolean { + if (Array.isArray(node)) return node.some(namesRelationshipPath); + if (!isConditionObject(node)) return false; + for (const [key, value] of Object.entries(node)) { + if (key === '$field') { + if (typeof value === 'string' && value.includes('.')) return true; + continue; + } + if (!key.startsWith('$') && key.includes('.')) return true; + if (namesRelationshipPath(value)) return true; + } + return false; +} + +/** The value legs of a measure: the column(s) its aggregate reads must hold a value. */ +function valueLegs(source: MeasureSource): FilterCondition[] { + switch (source.kind) { + case 'field': + return [{ [source.field]: { $null: false } }]; + case 'duration': + return [{ [source.from]: { $null: false } }, { [source.to]: { $null: false } }]; + default: + return []; + } +} + +/** + * The drill scope of every selected measure that has one, keyed by the + * selection's measure name. See the module header for what is left out. + */ +export function measureDrillScopes(input: { + /** The selection's measure names, as the answer's columns are keyed. */ + measures: readonly string[]; + /** The dataset's own `filter`, token-resolved, in object-field names. */ + filter: FilterCondition | undefined; + /** The measure's own `filter`, token-resolved, or `undefined` for none. */ + measureFilterOf: (measure: string) => FilterCondition | undefined; + /** What the measure aggregates, or `undefined` when it is not one the dataset answers. */ + sourceOf: (measure: string) => MeasureSource | undefined; +}): Record { + // A Map, then `Object.fromEntries`: every key lands as an own property, a + // measure named like an `Object.prototype` member included. + const scopes = new Map(); + for (const measure of input.measures) { + if (scopes.has(measure)) continue; + const source = input.sourceOf(measure); + if (!source || source.kind === 'derived') continue; + const parts: unknown[] = [input.filter, input.measureFilterOf(measure), ...valueLegs(source)] + .filter((part) => part !== undefined && !(isConditionObject(part) && Object.keys(part).length === 0)); + if (!parts.every(isConditionObject) || parts.some(namesRelationshipPath)) continue; + const scope = parts.length === 0 ? {} : parts.length === 1 ? parts[0] : { $and: parts }; + scopes.set(measure, structuredClone(scope) as FilterCondition); + } + return Object.fromEntries(scopes); +} diff --git a/packages/spec/src/api/analytics.zod.ts b/packages/spec/src/api/analytics.zod.ts index 73d6676181c..14f60bfe088 100644 --- a/packages/spec/src/api/analytics.zod.ts +++ b/packages/spec/src/api/analytics.zod.ts @@ -251,6 +251,21 @@ export const AnalyticsResultResponseSchema = lazySchema(() => BaseResponseSchema + 'dimension with a `field`; independent of `dimensionFields`. Absent on a cube ' + 'query answer.', ), + drillScopes: z.record(z.string(), FilterConditionSchema).optional().describe( + 'Drill-through sidecar per measure: each selected measure name to the list filter, on ' + + 'the answer\'s `object`, that selects the records that measure aggregates: the ' + + 'dataset\'s own `filter`, AND the measure\'s own `filter`, AND, for a measure over a ' + + '`field`, that field holding a value (`{ "$null": false }`; both instants for a ' + + 'duration measure), with each `{token}` resolved as the query resolved it; `{}` when ' + + 'none of these applies. A drill lists the clicked bucket (`dimensionFields` / ' + + '`drillRawRows` / `drillRawTotals`, `drillRanges`) AND the widget\'s own filter AND ' + + 'this scope. A measure is left out when no list filter on `object` selects its records ' + + '(a derived measure; a scope that names a relationship path such as `account.region`, ' + + 'as a key or as a `$field` reference), and a measure left out offers no drill. Keyed ' + + 'by measure name: a `__compare` column has no entry. Set on every dataset answer ' + + '(`POST /analytics/dataset/query`) that has rows; absent on a cube query answer and ' + + 'on a draft-preview answer.', + ), }), })); diff --git a/packages/spec/src/contracts/analytics-service.ts b/packages/spec/src/contracts/analytics-service.ts index 4dc111f8f53..43914d1ceb8 100644 --- a/packages/spec/src/contracts/analytics-service.ts +++ b/packages/spec/src/contracts/analytics-service.ts @@ -220,8 +220,9 @@ export interface AnalyticsResult { object?: string; // ── Drill-through sidecars (ADR-0021 D2) ──────────────────────────────── - // Four keys a `queryDataset` answer carries so a host can drill a clicked - // bucket back to the records behind it. Each is set only on a drillable + // Five keys a `queryDataset` answer carries so a host can drill a clicked + // number back to the records behind it: four for the bucket, and + // `drillScopes` for the measure. Each is set only on a drillable // answer, by the conditions stated per member; none is set on a `query` // (cube) answer, on an answer with no rows, or on a draft-preview answer // computed over pending seed rows (`previewDrafts`). @@ -297,6 +298,45 @@ export interface AnalyticsResult { * `drillRanges` and none of the equality sidecars. */ drillRanges?: Array>; + /** + * [#30526] The per-MEASURE drill scope: each selected measure NAME → the + * list filter, on `object`, that selects the records that measure + * aggregates. A number is computed under three filters at once: the + * dataset's own `filter`, the measure's own `filter`, and the request's + * `runtimeFilter` (a widget's filter). The host holds only the last one + * and has no read of the dataset definition (ADR-0021 D2: the server + * answers the drill bounds), so this member states the other two: + * + * - the dataset's `filter` AND the measure's `filter`, each `{token}` + * resolved at the instant the query resolved it; + * - AND, for a measure that aggregates a `field`, that field holding a + * value (`{ field: { $null: false } }`), since every aggregate skips an + * empty value (a `count` over a field counts the records where it is + * set); for a duration measure, both of its instants; + * - `{}` when none of these applies (a `count` over rows on a dataset + * with no `filter`). + * + * A drill lists the clicked bucket (`dimensionFields` / `drillRawRows` + * or `drillRawTotals`, and `drillRanges`) AND the request's + * `runtimeFilter` AND this scope, which is the set of records the clicked + * number counted. + * + * A measure is LEFT OUT when no list filter on `object` can select its + * records, and a measure left out offers no drill: a derived measure + * (it combines other measures, so it has no record set of its own), and a + * measure whose scope names a relationship path (`account.region`, as a + * filter key or inside a `$field` reference), which the record list + * refuses as a filter key. The nested-relation form + * (`{ account: { region: 'emea' } }`) is kept: the record list serves it. + * Keyed by the selection's measure names, so a `__compare` + * column has no entry: its records lie in another window. + * + * Set on every `queryDataset` answer that has rows, `{}` included when no + * selected measure has a scope; absent on a `query` (cube) answer, on an + * answer with no rows, and on a draft-preview answer, like the other + * drill sidecars. + */ + drillScopes?: Record; } /** From c5e7669741e727ad2177597da0660985e1360d93 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:03:33 +0000 Subject: [PATCH 2/5] test(analytics): pin the per-measure drill scope on both faces Claude-Session: https://claude.ai/code/session_01L6bhgXexAhb1ogpnymn5Jb Co-authored-by: Claude --- .../__tests__/dataset-drill-scopes.test.ts | 390 ++++++++++++++++++ .../spec/dropped-refinements.baseline.json | 9 +- 2 files changed, 397 insertions(+), 2 deletions(-) create mode 100644 packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts diff --git a/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts b/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts new file mode 100644 index 00000000000..64939fdba02 --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/dataset-drill-scopes.test.ts @@ -0,0 +1,390 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#30526] A dataset answer carries each selected measure's drill scope + * (`AnalyticsResult.drillScopes`), so a drill on a number lists the records + * that number counted, not the records of its bucket. + * + * MEASURED on `origin/main` `c23eafa8`, before the change: a dataset number is + * computed under the dataset's own `filter` AND the measure's own `filter` AND + * the selection's `runtimeFilter` (`DatasetExecutor.executeSelection` and + * `runMeasurePass`), while the answer's drill sidecars described the bucket + * only. The host holds the runtime filter and nothing else, so a drill on the + * showcase's `paid_count` (`aggregate: 'count', filter: { status: 'paid' }`, + * `examples/app-showcase/src/ui/datasets/revenue-pulse.dataset.ts`) listed + * every invoice of the bucket. + * + * The unit half drives `queryDataset` over a mocked engine aggregate and reads + * the scope beside what the engine was handed. The real-engine half (SQLite + * through the plugin's own composition, both strategies) runs each row's drill + * as a host composes it, bucket AND runtime filter AND scope, through the + * engine's own `find`, and counts what it lists against the number. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { DatasetSchema } from '@objectstack/spec/ui'; +import { AnalyticsResultResponseSchema } from '@objectstack/spec/api'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { AnalyticsResult } from '@objectstack/spec/contracts'; +import { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import { measureDrillScopes, namesRelationshipPath } from '../drill-scope.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const CTX = { tenantId: 'org_A', userId: 'usr_7' } as ExecutionContext; + +/** + * The showcase's invoice dataset (`ShowcaseInvoiceDataset`), measure for + * measure: a count over rows, a sum over a field, the filtered `paid_count` + * and the derived `paid_rate` over it. + */ +const SHOWCASE_MEASURES = [ + { name: 'invoice_count', label: 'Invoices', aggregate: 'count' }, + { name: 'subtotal_sum', label: 'Subtotal', aggregate: 'sum', field: 'total', format: '0,0' }, + { name: 'paid_count', label: 'Paid Invoices', aggregate: 'count', filter: { status: 'paid' } }, + { name: 'paid_rate', label: 'Paid Rate', derived: { op: 'ratio', of: ['paid_count', 'invoice_count'] }, format: '0.0%' }, +]; + +function invoiceDataset(extra: Record = {}, measures: unknown[] = SHOWCASE_MEASURES) { + return DatasetSchema.parse({ + name: 'showcase_invoice_metrics', + label: 'Invoice Metrics', + object: 'showcase_invoice', + dimensions: [ + { name: 'status', label: 'Status', field: 'status', type: 'string' }, + { name: 'region', label: 'Region', field: 'region', type: 'string' }, + ], + measures, + ...extra, + }); +} + +/** The ObjectQL face over fixed rows, recording every engine aggregate's filter. */ +function mockedService(rows: Array>, seen: unknown[] = []) { + return new AnalyticsService({ + queryCapabilities: () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false }), + executeAggregate: async (_object: string, opts: { filter?: unknown }) => { seen.push(opts.filter); return rows; }, + }); +} + +const ROWS = [{ region: 'emea', invoice_count: 3, subtotal_sum: 30, paid_count: 2 }]; +const ALL = ['invoice_count', 'subtotal_sum', 'paid_count', 'paid_rate']; + +describe('[#30526] the dataset answer carries each measure\'s drill scope', () => { + it('measure filter only — the showcase shape: paid_count drills by its filter, the sum by its column holding a value, the derived rate not at all', async () => { + const answer: AnalyticsResult = await mockedService(ROWS).queryDataset( + invoiceDataset(), { dimensions: ['region'], measures: ALL }, CTX, + ); + expect(answer.drillScopes).toEqual({ + invoice_count: {}, + subtotal_sum: { total: { $null: false } }, + paid_count: { status: 'paid' }, + }); + expect('paid_rate' in answer.drillScopes!).toBe(false); + }); + + it('dataset filter only, and both: the dataset filter is in every scope, conjoined with the measure\'s own', async () => { + const answer = await mockedService(ROWS).queryDataset( + invoiceDataset({ filter: { kind: 'sale' } }), { dimensions: ['region'], measures: ALL }, CTX, + ); + expect(answer.drillScopes).toEqual({ + invoice_count: { kind: 'sale' }, + subtotal_sum: { $and: [{ kind: 'sale' }, { total: { $null: false } }] }, + paid_count: { $and: [{ kind: 'sale' }, { status: 'paid' }] }, + }); + }); + + it('a count over a field drills the records where it is set', async () => { + const answer = await mockedService([{ region: 'emea', totalled: 2 }]).queryDataset( + invoiceDataset({}, [{ name: 'totalled', aggregate: 'count', field: 'total' }]), + { dimensions: ['region'], measures: ['totalled'] }, + CTX, + ); + expect(answer.drillScopes).toEqual({ totalled: { total: { $null: false } } }); + }); + + it('keeps the nested-relation form and a same-record $field reference as written', async () => { + const answer = await mockedService(ROWS).queryDataset( + invoiceDataset({}, [ + { name: 'gold_nested', aggregate: 'count', filter: { account: { tier: 'gold' } } }, + { name: 'over_floor', aggregate: 'count', filter: { total: { $gt: { $field: 'floor' } } } }, + ]), + { dimensions: ['region'], measures: ['gold_nested', 'over_floor'] }, + CTX, + ); + expect(answer.drillScopes).toEqual({ + gold_nested: { account: { tier: 'gold' } }, + over_floor: { total: { $gt: { $field: 'floor' } } }, + }); + }); + + it('tokens are resolved as the query resolved them, and the engine was handed the same value', async () => { + const seen: unknown[] = []; + const answer = await mockedService([{ region: 'emea', mine: 1 }], seen).queryDataset( + invoiceDataset({}, [{ name: 'mine', aggregate: 'count', filter: { owner: '{current_user_id}' } }]), + { dimensions: ['region'], measures: ['mine'] }, + CTX, + ); + expect(answer.drillScopes).toEqual({ mine: { owner: 'usr_7' } }); + expect(JSON.stringify(seen)).toContain('"usr_7"'); + expect(JSON.stringify(seen)).not.toContain('current_user_id'); + }); + + it('keys by the selection\'s spelling: a cube-qualified measure carries its own filter', async () => { + const answer = await mockedService([{ region: 'emea', 'showcase_invoice_metrics.paid_count': 2 }]).queryDataset( + invoiceDataset(), { dimensions: ['region'], measures: ['showcase_invoice_metrics.paid_count'] }, CTX, + ); + expect(answer.drillScopes).toEqual({ 'showcase_invoice_metrics.paid_count': { status: 'paid' } }); + }); + + it('a dimensionless KPI answer carries it; an answer with no rows does not', async () => { + const kpi = await mockedService([{ paid_count: 2 }]).queryDataset(invoiceDataset(), { measures: ['paid_count'] }, CTX); + expect(kpi.drillScopes).toEqual({ paid_count: { status: 'paid' } }); + + const empty = await mockedService([]).queryDataset(invoiceDataset(), { dimensions: ['region'], measures: ['paid_count'] }, CTX); + expect(empty.rows).toEqual([]); + expect('drillScopes' in empty).toBe(false); + }); + + it('a scope is the answer\'s own copy: composing into it leaves the dataset definition untouched', async () => { + const dataset = invoiceDataset({ filter: { kind: 'sale' } }); + const svc = mockedService(ROWS); + const first = await svc.queryDataset(dataset, { dimensions: ['region'], measures: ['paid_count'] }, CTX); + (first.drillScopes!.paid_count as { $and: unknown[] }).$and.push({ region: 'emea' }); + ((first.drillScopes!.paid_count as { $and: Array> }).$and[0]).kind = 'refund'; + expect(dataset.filter).toEqual({ kind: 'sale' }); + expect(dataset.measures.find((m) => m.name === 'paid_count')!.filter).toEqual({ status: 'paid' }); + const second = await svc.queryDataset(dataset, { dimensions: ['region'], measures: ['paid_count'] }, CTX); + expect(second.drillScopes).toEqual({ paid_count: { $and: [{ kind: 'sale' }, { status: 'paid' }] } }); + }); + + it('the wire shape: the spec\'s answer schema keeps every scope the service answers, byte for byte', async () => { + const answer = await mockedService(ROWS).queryDataset( + invoiceDataset({ filter: { kind: 'sale' } }), { dimensions: ['region'], measures: ALL }, CTX, + ); + const wire = JSON.parse(JSON.stringify(answer)); + const parsed = AnalyticsResultResponseSchema.parse({ success: true, data: wire }); + expect(parsed.data.drillScopes).toEqual(wire.drillScopes); + expect(Object.keys(parsed.data.drillScopes!)).toEqual(['invoice_count', 'subtotal_sum', 'paid_count']); + }); +}); + +describe('[#30526] the scope walk', () => { + it('reads a dotted key or a dotted $field reference anywhere as a relationship path, and a dotted string comparand as data', () => { + expect(namesRelationshipPath({ 'account.tier': 'gold' })).toBe(true); + expect(namesRelationshipPath({ $and: [{ status: 'paid' }, { $or: [{ 'owner.region': 'NA' }] }] })).toBe(true); + expect(namesRelationshipPath({ $not: { total: { $lt: { $field: 'account.floor', addDays: 1 } } } })).toBe(true); + expect(namesRelationshipPath({ due: { $lte: { $field: 'due_on', addDays: { $field: 'duty.grace_days' } } } })).toBe(true); + expect(namesRelationshipPath({ account: { 'owner.name': 'x' } })).toBe(true); + expect(namesRelationshipPath({ email: 'a.b@example.com', host: { $in: ['x.example.com'] } })).toBe(false); + expect(namesRelationshipPath({ account: { tier: 'gold' } })).toBe(false); + }); + + it('leaves out a measure no source answers, and one whose filter is not a condition object', () => { + const scopes = measureDrillScopes({ + measures: ['ghost', 'listed', 'counted', 'counted'], + filter: undefined, + measureFilterOf: (m) => (m === 'listed' ? ([['status', '=', 'paid']] as never) : undefined), + sourceOf: (m) => (m === 'ghost' ? undefined : { kind: 'rows' }), + }); + expect(scopes).toEqual({ counted: {} }); + }); +}); + +// ── The real engine: a drill lists exactly what the number counted ──────────── + +const OBJECT = 'invoice_30526'; +const ACCOUNT = 'account_30526'; +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; + +/** + * Invoices across two regions: sales and refunds (the dataset's own filter + * keeps sales), paid and open (`paid_count`'s filter), with and without a + * total (a sum and a count over `total` skip the empty ones). + */ +const D = (day: number) => `2026-10-${String(day).padStart(2, '0')}T00:00:00.000Z`; + +const INVOICES: Array<{ + id: string; region: string; kind: string; status: string; channel: string; total: number | null; account: string | null; + issued_at?: string; paid_at?: string; +}> = [ + { id: 'i1', region: 'emea', kind: 'sale', status: 'paid', channel: 'web', total: 10, account: 'a1', issued_at: D(1), paid_at: D(4) }, + { id: 'i2', region: 'emea', kind: 'sale', status: 'paid', channel: 'store', total: null, account: 'a2', issued_at: D(2) }, + { id: 'i3', region: 'emea', kind: 'sale', status: 'open', channel: 'web', total: 5, account: 'a1' }, + { id: 'i4', region: 'emea', kind: 'refund', status: 'paid', channel: 'web', total: 7, account: 'a1' }, + { id: 'i5', region: 'apac', kind: 'sale', status: 'paid', channel: 'web', total: 20, account: 'a1', issued_at: D(3), paid_at: D(13) }, + { id: 'i6', region: 'apac', kind: 'sale', status: 'open', channel: 'web', total: null, account: null }, + { id: 'i7', region: 'apac', kind: 'refund', status: 'open', channel: 'store', total: 3, account: 'a2' }, + { id: 'i8', region: 'apac', kind: 'sale', status: 'paid', channel: 'store', total: 4, account: 'a2', issued_at: D(5), paid_at: D(7) }, +]; + +const invoices = DatasetSchema.parse({ + name: 'invoices_30526', label: 'Invoices', object: OBJECT, include: [], + filter: { kind: 'sale' }, + dimensions: [{ name: 'region', field: 'region', type: 'string' }], + measures: [ + { name: 'invoice_count', aggregate: 'count' }, + { name: 'paid_count', aggregate: 'count', filter: { status: 'paid' } }, + { name: 'totalled_count', aggregate: 'count', field: 'total' }, + { name: 'subtotal_sum', aggregate: 'sum', field: 'total' }, + { name: 'paid_rate', derived: { op: 'ratio', of: ['paid_count', 'invoice_count'] } }, + ], +}); + +describe('[#30526] on a real engine, a drill composed with the scope lists exactly what the number counted', () => { + let engine: ObjectQL; + const faces: Record<'native' | 'objectql', AnalyticsService> = {} as never; + + beforeAll(async () => { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); + engine = new ObjectQL({ logger: quiet } as never); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registry.registerObject({ + name: ACCOUNT, + label: 'Account', + fields: { tier: { name: 'tier', type: 'text' } }, + } as never); + engine.registry.registerObject({ + name: OBJECT, + label: 'Invoice', + fields: { + region: { name: 'region', type: 'text' }, + kind: { name: 'kind', type: 'text' }, + status: { name: 'status', type: 'text' }, + channel: { name: 'channel', type: 'text' }, + total: { name: 'total', type: 'number' }, + account: { name: 'account', type: 'lookup', reference: ACCOUNT }, + issued_at: { name: 'issued_at', type: 'datetime' }, + paid_at: { name: 'paid_at', type: 'datetime' }, + }, + } as never); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + await engine.insert(ACCOUNT, { id: 'a1', tier: 'gold' } as never); + await engine.insert(ACCOUNT, { id: 'a2', tier: 'silver' } as never); + for (const inv of INVOICES) await engine.insert(OBJECT, { ...inv } as never); + for (const [face, caps] of [ + ['native', undefined], + ['objectql', () => ({ nativeSql: false, objectqlAggregate: true, inMemory: false })], + ] as const) { + const registered: Record = {}; + await new AnalyticsServicePlugin({ ...(caps ? { queryCapabilities: caps } : {}) } as never).init({ + getService: (name: string) => (name === 'data' ? engine : registered[name]), + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, + hook: () => {}, + logger: quiet, + } as never); + faces[face] = registered.analytics as AnalyticsService; + } + }); + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + /** What the drill on row `i` × `measure` lists: bucket AND runtime filter AND scope, as a host composes it. */ + async function drilled(answer: AnalyticsResult, i: number, measure: string, runtimeFilter?: Record) { + const bucket: Record = {}; + for (const [dim, field] of Object.entries(answer.dimensionFields ?? {})) bucket[field] = answer.drillRawRows![i][dim]; + const where = { $and: [bucket, ...(runtimeFilter ? [runtimeFilter] : []), answer.drillScopes![measure]] }; + return (await engine.find(OBJECT, { where, fields: ['id', 'total', 'issued_at', 'paid_at'] } as never)) as Array<{ + id: string; total: number | null; issued_at: string | null; paid_at: string | null; + }>; + } + + for (const face of ['native', 'objectql'] as const) { + for (const runtimeFilter of [undefined, { channel: 'web' }]) { + it(`${face} face${runtimeFilter ? ', under a widget filter' : ''}: every count lists as many records as it says, and the sum adds up`, async () => { + const answer = await faces[face].queryDataset( + invoices, + { dimensions: ['region'], measures: ['invoice_count', 'paid_count', 'totalled_count', 'subtotal_sum', 'paid_rate'], ...(runtimeFilter ? { runtimeFilter } : {}) }, + CTX, + ); + expect(answer.rows.length).toBe(2); + expect(Object.keys(answer.drillScopes!).sort()).toEqual(['invoice_count', 'paid_count', 'subtotal_sum', 'totalled_count']); + for (const [i, row] of answer.rows.entries()) { + for (const m of ['invoice_count', 'paid_count', 'totalled_count']) { + expect((await drilled(answer, i, m, runtimeFilter)).length, `${row.region} ${m}`).toBe(Number(row[m])); + } + const summed = (await drilled(answer, i, 'subtotal_sum', runtimeFilter)).reduce((s, r) => s + Number(r.total), 0); + expect(summed, `${row.region} subtotal_sum`).toBe(Number(row.subtotal_sum)); + } + }); + } + } + + it('CONTROL the bucket and the widget filter alone list more than paid_count counts — the gap the scope closes', async () => { + const answer = await faces.native.queryDataset(invoices, { dimensions: ['region'], measures: ['paid_count'] }, CTX); + const emea = answer.rows.findIndex((r) => r.region === 'emea'); + const bucketOnly = (await engine.find(OBJECT, { where: { region: 'emea' }, fields: ['id'] } as never)) as unknown[]; + expect(Number(answer.rows[emea].paid_count)).toBe(2); + expect(bucketOnly.length).toBe(4); + expect((await drilled(answer, emea, 'paid_count')).map((r) => r.id).sort()).toEqual(['i1', 'i2']); + }); + + it('a duration measure (native face, SQLite) drills the records with both instants set, and their mean is the number', async () => { + const timed = DatasetSchema.parse({ + ...invoices, + name: 'invoices_timed_30526', + measures: [{ name: 'days_to_pay', aggregate: 'avg', duration: { from: 'issued_at', to: 'paid_at', unit: 'days' }, filter: { status: 'paid' } }], + }); + const answer = await faces.native.queryDataset(timed, { dimensions: ['region'], measures: ['days_to_pay'] }, CTX); + expect(answer.drillScopes).toEqual({ + days_to_pay: { $and: [{ kind: 'sale' }, { status: 'paid' }, { issued_at: { $null: false } }, { paid_at: { $null: false } }] }, + }); + for (const [i, row] of answer.rows.entries()) { + const listed = await drilled(answer, i, 'days_to_pay'); + const days = listed.map((r) => (Date.parse(String(r.paid_at)) - Date.parse(String(r.issued_at))) / 86_400_000); + expect(days.reduce((s, d) => s + d, 0) / days.length, String(row.region)).toBeCloseTo(Number(row.days_to_pay), 9); + } + }); + + it('a nested-relation DATASET filter keeps its scope, and the record list serves it: the drill lists what the number counted', async () => { + const nested = DatasetSchema.parse({ + ...invoices, + name: 'invoices_nested_30526', + filter: { account: { tier: 'gold' } }, + measures: [{ name: 'invoice_count', aggregate: 'count' }, { name: 'paid_count', aggregate: 'count', filter: { status: 'paid' } }], + }); + for (const face of ['native', 'objectql'] as const) { + const answer = await faces[face].queryDataset(nested, { dimensions: ['region'], measures: ['invoice_count', 'paid_count'] }, CTX); + expect(answer.drillScopes, face).toEqual({ + invoice_count: { account: { tier: 'gold' } }, + paid_count: { $and: [{ account: { tier: 'gold' } }, { status: 'paid' }] }, + }); + for (const [i, row] of answer.rows.entries()) { + for (const m of ['invoice_count', 'paid_count']) { + expect((await drilled(answer, i, m)).length, `${face} ${row.region} ${m}`).toBe(Number(row[m])); + } + } + } + }); + + it('a relationship path in a measure\'s or the dataset\'s filter (native face, which joins it) leaves that scope out', async () => { + const joined = DatasetSchema.parse({ + ...invoices, + name: 'invoices_joined_30526', + include: ['account'], + measures: [ + { name: 'invoice_count', aggregate: 'count' }, + { name: 'gold_dotted', aggregate: 'count', filter: { 'account.tier': 'gold' } }, + ], + }); + const answer = await faces.native.queryDataset(joined, { dimensions: ['region'], measures: ['invoice_count', 'gold_dotted'] }, CTX); + expect(answer.rows.map((r) => [r.region, Number(r.gold_dotted)]).sort()).toEqual([['apac', 1], ['emea', 2]]); + expect(answer.drillScopes).toEqual({ invoice_count: { kind: 'sale' } }); + + const scoped = DatasetSchema.parse({ ...joined, name: 'invoices_joined_scope_30526', filter: { 'account.tier': 'gold' } }); + const whole = await faces.native.queryDataset(scoped, { dimensions: ['region'], measures: ['invoice_count'] }, CTX); + expect(whole.rows.length).toBe(2); + expect(whole.drillScopes).toEqual({}); + }); + + it('CONTROL the record list refuses a relationship path as a filter key, which is why such a scope is left out', async () => { + const err = await engine.find(OBJECT, { where: { 'account.tier': 'gold' } } as never).then(() => null, (e: { code?: string; status?: number }) => e); + expect({ code: err?.code, status: err?.status }).toEqual({ code: 'INVALID_FIELD', status: 400 }); + }); +}); diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index bc451089254..0b90a9406e0 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 251, - "droppedRefinementSites": 1019, + "publishedSchemasWithDroppedRefinements": 252, + "droppedRefinementSites": 1020, "refinementSitesThatDidProject": 369, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -60,6 +60,11 @@ "where.lazy" ] }, + "api/AnalyticsResultResponse": { + "sites": [ + "data.drillScopes.valueType.lazy" + ] + }, "api/AppDefinitionResponse": { "sites": [ "data", From 46d0df3de0fb2cbb2f4d12fc50499ffe2020a050 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:11:30 +0000 Subject: [PATCH 3/5] feat(spec,data-objectstack): drillScopes slot on the dataset answer, passed through by the adapter The response schema and the AnalyticsResult contract carry `drillScopes` (measure name -> FilterCondition on the answer's object); the spec pins accept every scope verbatim and refuse a non-condition value. The data-objectstack adapter hand-picks the keys it returns, so it now lists `drillScopes` too, typed as the spec slot. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXexAhb1ogpnymn5Jb --- packages/spec/src/api/analytics.test.ts | 30 ++++++++- .../src/contracts/analytics-service.test.ts | 8 ++- ui/packages/data-objectstack/src/index.ts | 21 ++++++- .../data-objectstack/src/queryDataset.test.ts | 62 +++++++++++++++++++ 4 files changed, 118 insertions(+), 3 deletions(-) diff --git a/packages/spec/src/api/analytics.test.ts b/packages/spec/src/api/analytics.test.ts index cf919943de4..81db0c4d83c 100644 --- a/packages/spec/src/api/analytics.test.ts +++ b/packages/spec/src/api/analytics.test.ts @@ -413,11 +413,39 @@ describe('AnalyticsResultResponseSchema', () => { // Optional: a cube query answer, and a non-drillable dataset answer, carry none. const bare = AnalyticsResultResponseSchema.parse({ success: true, data: { rows: [], fields: [] } }); - for (const key of ['dimensionFields', 'drillRawRows', 'drillRawTotals', 'drillRanges']) { + for (const key of ['dimensionFields', 'drillRawRows', 'drillRawTotals', 'drillRanges', 'drillScopes']) { expect(key in bare.data).toBe(false); } }); + // [#30526] The per-measure drill scope, in the spec's one filter vocabulary: + // a measure filter, a dataset filter conjoined with it, a column holding a + // value, the nested-relation form, and `{}` for a count over rows. + const scopes = { + invoice_count: {}, + paid_count: { $and: [{ kind: 'sale' }, { status: 'paid' }] }, + subtotal_sum: { $and: [{ kind: 'sale' }, { total: { $null: false } }] }, + gold_count: { account: { tier: 'gold' } }, + }; + + it('should preserve every measure\'s drill scope, byte for byte', () => { + const resp = AnalyticsResultResponseSchema.parse({ success: true, data: { ...drillable, drillScopes: scopes } }); + expect(resp.data.drillScopes).toEqual(scopes); + expect(JSON.stringify(resp.data.drillScopes)).toBe(JSON.stringify(scopes)); + }); + + it.each([ + ['a scope that is not a condition object', { paid_count: 'status = paid' }, ['data.drillScopes.paid_count']], + ['a list in an equality slot', { paid_count: { status: ['paid', 'open'] } }, ['data.drillScopes.paid_count.status']], + ['an $and that is not a list', { paid_count: { $and: { status: 'paid' } } }, ['data.drillScopes.paid_count.$and']], + ['a map keyed by row instead of by measure', [{ status: 'paid' }], ['data.drillScopes']], + ])('should refuse %s at its own path', (_label, drillScopes, paths) => { + const bad = AnalyticsResultResponseSchema.safeParse({ success: true, data: { ...drillable, drillScopes } }); + expect(bad.success).toBe(false); + const issued = bad.success ? [] : bad.error.issues.map((i) => i.path.join('.')); + for (const path of paths) expect(issued.some((p) => p.startsWith(path)), `${path} in ${issued.join(' | ')}`).toBe(true); + }); + it.each([ ['dimensionFields', { account: 42 }, 'data.dimensionFields.account'], ['drillRawRows', { account: 'acc_1' }, 'data.drillRawRows'], diff --git a/packages/spec/src/contracts/analytics-service.test.ts b/packages/spec/src/contracts/analytics-service.test.ts index 31154e6d0a8..4f2afa9f33d 100644 --- a/packages/spec/src/contracts/analytics-service.test.ts +++ b/packages/spec/src/contracts/analytics-service.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; import type { IAnalyticsService, AnalyticsResult, CubeMeta } from './analytics-service'; +import type { FilterCondition } from '../data/filter.zod'; describe('Analytics Service Contract', () => { it('should allow a minimal IAnalyticsService implementation with required methods', () => { @@ -150,6 +151,7 @@ describe('Analytics Service Contract', () => { drillRawRows: [{ account: 'acc_1' }], drillRawTotals: [[{}]], drillRanges: [{ close_date: { field: 'close_date', gte: '2026-04-01', lt: '2026-07-01' } }], + drillScopes: { revenue: { $and: [{ kind: 'sale' }, { amount: { $null: false } }] } }, }), }; @@ -163,6 +165,8 @@ describe('Analytics Service Contract', () => { expect(answer.drillRawTotals?.[0]?.[0]).toEqual({}); const range: { field: string; gte: string; lt: string } | undefined = answer.drillRanges?.[0]?.close_date; expect(range).toEqual({ field: 'close_date', gte: '2026-04-01', lt: '2026-07-01' }); + const scope: FilterCondition | undefined = answer.drillScopes?.revenue; + expect(scope).toEqual({ $and: [{ kind: 'sale' }, { amount: { $null: false } }] }); const offType: AnalyticsResult[] = [ // @ts-expect-error — `dimensionFields` maps a dimension name to a field NAME, a string @@ -173,8 +177,10 @@ describe('Analytics Service Contract', () => { { rows: [], fields: [], drillRawTotals: [{ account: 'acc_1' }] }, // @ts-expect-error — a `drillRanges` entry carries both bounds { rows: [], fields: [], drillRanges: [{ close_date: { field: 'close_date', gte: '2026-04-01' } }] }, + // @ts-expect-error — a `drillScopes` entry is a filter condition, not a string + { rows: [], fields: [], drillScopes: { revenue: 'kind = sale' } }, ]; - expect(offType).toHaveLength(4); + expect(offType).toHaveLength(5); }); it('should generate SQL without executing', async () => { diff --git a/ui/packages/data-objectstack/src/index.ts b/ui/packages/data-objectstack/src/index.ts index 2098bca38af..5a612773422 100644 --- a/ui/packages/data-objectstack/src/index.ts +++ b/ui/packages/data-objectstack/src/index.ts @@ -7300,6 +7300,18 @@ export class ObjectStackAdapter implements DataSource { * `DatasetDrillRange` declares them `unknown`. */ drillRanges?: Array>; + /** + * The per-MEASURE drill scope (objectstack-ai/objectstack#30526): measure + * NAME → the list filter that selects the records that measure aggregates + * (the dataset's own `filter` AND the measure's own `filter` AND the + * aggregated column holding a value), which the host has no other read of. + * A drill composes the clicked bucket AND the widget filter AND this; a + * measure with no entry offers no drill. The spec's `AnalyticsResult` + * member BY REFERENCE, like `fields`, so its meaning is read in one place. + * Only the MAP is validated below; each scope is the server's filter as + * sent. + */ + drillScopes?: AnalyticsResult['drillScopes']; /** Server-computed marginal aggregates, one entry per requested grouping. */ totals?: Array<{ dimensions: string[]; rows: Array> }>; }> { @@ -7466,8 +7478,15 @@ export class ObjectStackAdapter implements DataSource { // away, the whole drill entry point disappeared, and a mixed grouping // drilled to a superset (every bucket, not the clicked one). const drillRanges = Array.isArray((data as any)?.drillRanges) ? (data as any).drillRanges : undefined; + // objectstack-ai/objectstack#30526 — the measure drill scope. Hand-picked + // like every key above, so it is named here or it never reaches a drill: + // the fourth key of this family, after objectui#3613, #3752 and #3813. + const rawScopes = (data as any)?.drillScopes; + const drillScopes = rawScopes && typeof rawScopes === 'object' && !Array.isArray(rawScopes) + ? (rawScopes as NonNullable) + : undefined; const totals = Array.isArray((data as any)?.totals) ? (data as any).totals : undefined; - return { rows, fields, object, dimensionFields, drillRawRows, drillRanges, totals }; + return { rows, fields, object, dimensionFields, drillRawRows, drillRanges, drillScopes, totals }; } /** Client-side aggregation fallback */ diff --git a/ui/packages/data-objectstack/src/queryDataset.test.ts b/ui/packages/data-objectstack/src/queryDataset.test.ts index 516b33fb705..32a7aac3427 100644 --- a/ui/packages/data-objectstack/src/queryDataset.test.ts +++ b/ui/packages/data-objectstack/src/queryDataset.test.ts @@ -832,3 +832,65 @@ describe('queryDataset passes the server drillRanges sidecar through (#1752)', ( expect(true).toBe(true); }); }); + +/* -------------------------------------------------------------------------- */ +/* objectstack-ai/objectstack#30526 — the per-measure drill scope. A dataset */ +/* number is computed under the dataset's own `filter` and the measure's own */ +/* `filter`, which a host never reads; the server states them per measure in */ +/* `drillScopes`. The return here is hand-picked, so an unlisted key is dropped */ +/* (measured: before this section the sidecar never reached a consumer). */ +/* -------------------------------------------------------------------------- */ + +describe('queryDataset passes the server drillScopes sidecar through (#30526)', () => { + beforeEach(() => clearSharedDiscoveryCache()); + + const scopes = { + paid_count: { $and: [{ kind: 'sale' }, { status: 'paid' }] }, + invoice_count: {}, + }; + + async function answer(body: Record) { + const { fetchImpl } = makeFetch({ + ok: true, + body: { + rows: [{ region: 'NA', paid_count: 2, invoice_count: 4 }], + fields: [{ name: 'paid_count', type: 'number' }, { name: 'invoice_count', type: 'number' }], + object: 'invoice', + dimensionFields: { region: 'region' }, + drillRawRows: [{ region: 'NA' }], + ...body, + }, + }); + const adapter = new ObjectStackAdapter({ baseUrl: 'http://localhost:3000', autoReconnect: false, fetch: fetchImpl as any }); + return adapter.queryDataset(inlineDataset as any, { dimensions: ['region'], measures: ['paid_count', 'invoice_count'] } as any); + } + + it('keeps every scope verbatim, an empty `{}` scope included', async () => { + const result = await answer({ drillScopes: scopes }); + expect(result.drillScopes).toEqual(scopes); + // `{}` is "drillable, no extra condition", distinct from an absent key + // ("offers no drill"): the passthrough must not drop or collapse it. + expect(Object.keys(result.drillScopes ?? {})).toEqual(['paid_count', 'invoice_count']); + }); + + it('leaves drillScopes undefined when the server sends none', async () => { + const result = await answer({}); + expect(result.drillScopes).toBeUndefined(); + }); + + it.each([ + ['an array', [scopes.paid_count]], + ['a string', 'kind = sale'], + ['null', null], + ])('drops %s in the drillScopes slot rather than handing it on', async (_label, value) => { + const result = await answer({ drillScopes: value }); + expect(result.drillScopes).toBeUndefined(); + }); + + it('is pinned at compile time as the spec AnalyticsResult drillScopes', () => { + type _Declared = Assert>; + type _IsTheSpecSlot = Assert>; + type _SpecSlotNotAny = Assert, false>>; + expect(true).toBe(true); + }); +}); From fbfef58e2bc31fbfa22d830fba5f1195ae57c1d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:16:17 +0000 Subject: [PATCH 4/5] docs(spec): regenerate the analytics reference for drillScopes `pnpm --filter @objectstack/spec gen:docs`, the one artifact `check:generated` proved stale. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXexAhb1ogpnymn5Jb --- content/docs/references/api/analytics.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/content/docs/references/api/analytics.mdx b/content/docs/references/api/analytics.mdx index f5ce1ff31af..45e2b64d227 100644 --- a/content/docs/references/api/analytics.mdx +++ b/content/docs/references/api/analytics.mdx @@ -159,6 +159,7 @@ const result = AnalyticsEndpoint.parse(data); | **drillRawRows** | `Record[]` | optional | Drill-through sidecar, aligned to `rows` by index: each `dimensionFields` dimension name to the stored value that row was grouped by (a select option's value, a lookup's record id), captured before label resolution rewrites the row to its display label. An exact-match drill filter is built from these, not from the labels in `rows`. Set exactly when `dimensionFields` is. | | **drillRawTotals** | `Record[][]` | optional | Drill-through sidecar for `totals`: entry `[i][j]` aligns to `totals[i].rows[j]` and holds the stored value of the `dimensionFields` dimensions that grouping groups by, so the grand-total grouping yields an empty map per row. Set only when `dimensionFields` is and the answer carries at least one `totals` grouping. | | **drillRanges** | `Record[]` | optional | Drill-through sidecar for date ranges, aligned to `rows` by index: date dimension name to the half-open range `[gte, lt)` that row's records fall in on that dimension's field. A time bucket gets the span it covers; a `timeDimensions[].dateRange` window gets the window the query filtered by on every row, or narrows the bucket entry on the same field to the part inside the window. Bounds are `YYYY-MM-DD` calendar days, or ISO-8601 instants when the source field is `datetime` (a bucket's at midnight in the reference timezone); a row whose bucket value is null gets no bucket entry, and a window whose end is an instant or the last supported day gets none. Set only on a dataset answer that has rows and groups by at least one `type: 'date'` dimension with a `field` and a granularity, or carries a `dateRange` on a dimension with a `field`; independent of `dimensionFields`. Absent on a cube query answer. | +| **drillScopes** | `Record` | optional | Drill-through sidecar per measure: each selected measure name to the list filter, on the answer's `object`, that selects the records that measure aggregates: the dataset's own `filter`, AND the measure's own `filter`, AND, for a measure over a `field`, that field holding a value (`{ "$null": false }`; both instants for a duration measure), with each `{token}` resolved as the query resolved it; `{}` when none of these applies. A drill lists the clicked bucket (`dimensionFields` / `drillRawRows` / `drillRawTotals`, `drillRanges`) AND the widget's own filter AND this scope. A measure is left out when no list filter on `object` selects its records (a derived measure; a scope that names a relationship path such as `account.region`, as a key or as a `$field` reference), and a measure left out offers no drill. Keyed by measure name: a `__compare` column has no entry. Set on every dataset answer (`POST /analytics/dataset/query`) that has rows; absent on a cube query answer and on a draft-preview answer. | --- From 25fc5696be45c20156cf69cfb8581a372ef4f08b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 5 Nov 2026 16:28:28 +0000 Subject: [PATCH 5/5] chore(changeset): drillScopes on the dataset answer Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgXexAhb1ogpnymn5Jb --- .changeset/30526-dataset-measure-drill-scopes.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/30526-dataset-measure-drill-scopes.md diff --git a/.changeset/30526-dataset-measure-drill-scopes.md b/.changeset/30526-dataset-measure-drill-scopes.md new file mode 100644 index 00000000000..36c557e8275 --- /dev/null +++ b/.changeset/30526-dataset-measure-drill-scopes.md @@ -0,0 +1,14 @@ +--- +'@objectstack/spec': patch +'@objectstack/service-analytics': patch +'@object-ui/data-objectstack': patch +--- + +feat(spec,service-analytics,data-objectstack): a dataset answer says, per measure, which records that measure counted (`drillScopes`) + +Clause-②: yes (widening) +Metadata-protocol: none + +- **`@objectstack/spec`: `AnalyticsResult.drillScopes?: Record`**, also declared on the `AnalyticsResultResponse` wire schema. Each selected measure name maps to the list filter, on the answer's `object`, that selects the records the measure aggregates: the dataset's own `filter`, AND the measure's own `filter`, AND, for a measure over a field, that field holding a value (both instants for a duration measure), with each `{token}` resolved as the query resolved it. It is `{}` when none of these applies. A measure that no list filter can select is left out: a derived measure, or a scope that names a relationship path (`account.region`, as a key or a `$field` reference). A measure left out offers no drill. A `__compare` column has no entry. +- **`@objectstack/service-analytics`: `queryDataset` sets `drillScopes` on every dataset answer that has rows**, on both query faces, from the same token-resolved filters the numbers were computed under. A drill that lists the clicked bucket (`dimensionFields` / `drillRawRows` / `drillRawTotals`, `drillRanges`) AND the widget's own filter AND this scope lists exactly the records the number counted. Before this, a drill built from the bucket and the widget filter alone listed every record in the bucket, so a filtered measure such as "paid invoices" showed 4 records behind the number 2. +- **`@object-ui/data-objectstack`: `queryDataset` passes `drillScopes` through**, typed as the spec slot. The adapter lists the keys it returns, so until now the sidecar was dropped before it reached a widget.