diff --git a/.changeset/26893-time-series-empty-buckets.md b/.changeset/26893-time-series-empty-buckets.md new file mode 100644 index 00000000000..a74417c40f7 --- /dev/null +++ b/.changeset/26893-time-series-empty-buckets.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-analytics': patch +--- + +fix(service-analytics): a date-dimension series answers every bucket of its window, the empty ones included (#26893) + +Clause-②: no — no input is refused or newly accepted and no export or type changes; a dataset answer gains the rows for the time buckets no record fell in, which it used to leave out +Metadata-protocol: none + +A grouped query answers one row per bucket that holds records, so a month with no closed-won deal was not a zero in a 12-month revenue trend: it was missing, and a chart's category axis drew the months on either side of it as neighbours. `queryDataset` (and `POST /api/v1/analytics/dataset/query`, which the dashboard's dataset widget calls) now adds those buckets in the dataset executor: + +- **Which buckets.** When the grid's time dimension carries a `timeDimensions[].dateRange` (a preset or an explicit pair), every bucket of that window, in order. With no `dateRange`, only the gaps between the first and last bucket that came back are filled: a window stated only in `runtimeFilter`, or a one-bound filter such as `{ close_date: { $gte: '{12_months_ago}' } }`, does not bound the edges. No window and no rows still answer no rows. +- **Their values.** The same values an empty group already reads: `0` for `count` and `sum`; `avg`, `min` and `max` stay unset (the column is absent from the row, which a chart reads as no value), never `0`. A derived measure is computed over them as over any row. +- **Other dimensions.** With a second grid dimension (month × owner), each combination that already holds a row gets every bucket; a combination no row holds is not added. +- **Keys.** The added keys are spelled by the same bucket labeller the grouping uses, in the selection's timezone, so they sort and merge with the real ones (`2026-05`, `2026-W01`, `2026-10-04`). +- **Not filled.** A selection with a `limit` or `offset`, an `order` on a measure, or a `compareTo`, and a grid with two bucketed time dimensions, answer exactly as before. A fill that would leave more than 2,000 rows in the grid (a `day` series over ten years) does not run at all, so the answer is never filled part-way. diff --git a/packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts b/packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts index b2b0e57c33b..17bf356e0ac 100644 --- a/packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts +++ b/packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts @@ -123,6 +123,8 @@ describe('dogfood: org timezone drives analytics date bucketing (#1982/#2018)', // The regression: before #2018 this stayed on 2024-03-01 (tz dropped) or // returned cnt 0. The org timezone must move it to 2024-02-29. expect(la['2024-02-29']).toBe(N_LEADS); - expect(la['2024-03-01']).toBeUndefined(); + // 2024-03-01 now lies between the boundary leads and the seed's own, so it + // comes back as an empty bucket (#26893): present, and no lead counted. + expect(la['2024-03-01']).toBe(0); }); }); diff --git a/packages/services/service-analytics/src/__tests__/aggregate-datetime-measure-refusal.test.ts b/packages/services/service-analytics/src/__tests__/aggregate-datetime-measure-refusal.test.ts index fdbf0257026..9baa594d6f4 100644 --- a/packages/services/service-analytics/src/__tests__/aggregate-datetime-measure-refusal.test.ts +++ b/packages/services/service-analytics/src/__tests__/aggregate-datetime-measure-refusal.test.ts @@ -403,7 +403,9 @@ describe('#16737 negative controls — aggregation only, and only the incoherent }); it('⭐ a `datetime` used as a DIMENSION is untouched — date-range filtering', async () => { - const { svc, calls } = makeBucketService([{ submitted: '2026-05', row_count: 3 }]); + // Keyed by the FIELD, as the engine answers: the strategy maps it onto the + // `submitted` dimension, so the bucket is a real May rather than the null one. + const { svc, calls } = makeBucketService([{ submitted_at: '2026-05', row_count: 3 }]); const result: any = await svc.queryDataset( dataset( [{ name: 'row_count', aggregate: 'count' }], @@ -415,7 +417,9 @@ describe('#16737 negative controls — aggregation only, and only the incoherent timeDimensions: [{ dimension: 'submitted', dateRange: ['2026-01-01', '2026-12-31'] }], }, ); - expect(result.rows.length).toBe(1); + // #26893 — every month of the window comes back, the empty ones at 0. + expect(result.rows.length).toBe(12); + expect(result.rows.filter((r: any) => r.row_count > 0)).toEqual([{ submitted: '2026-05', row_count: 3 }]); // The window reached the engine as a resolved bound on the datetime column // — the dimension path this card must not have touched. expect(JSON.stringify(calls[0])).toContain('2026-01-01'); diff --git a/packages/services/service-analytics/src/__tests__/bucket-key-readers-four-digit-year.test.ts b/packages/services/service-analytics/src/__tests__/bucket-key-readers-four-digit-year.test.ts index e70fc98fd81..59efaf2e82f 100644 --- a/packages/services/service-analytics/src/__tests__/bucket-key-readers-four-digit-year.test.ts +++ b/packages/services/service-analytics/src/__tests__/bucket-key-readers-four-digit-year.test.ts @@ -136,8 +136,15 @@ describe('[#20867] a draft preview keys 0050-06-15 as the published path does', }, }); + // The buckets that hold rows. Between them the executor fills the empty + // ones (#26893) — up to its bound, so the year axis gains 1,975 empty years + // and the finer ones are left as grouped; either way the keys pinned here are + // the two real ones. const keysOf = (rows: Record[]) => - rows.map((r) => [r.spent_on, r.expense_count]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))); + rows + .filter((r) => Number(r.expense_count) > 0) + .map((r) => [r.spent_on, r.expense_count]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))); it.each([ ['year', '0050', '2026'], diff --git a/packages/services/service-analytics/src/__tests__/dataset-time-axis-order.test.ts b/packages/services/service-analytics/src/__tests__/dataset-time-axis-order.test.ts index dae8e3e12fb..c85ea163bf5 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-time-axis-order.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-time-axis-order.test.ts @@ -139,7 +139,8 @@ describe('#3916 — matrix date columns arrive chronological end-to-end', () => { dimensions: ['closed_quarter'], measures: ['task_count'] }, CTX, ); - expect(result.rows.map((r) => r.closed_quarter)).toEqual(['2025-Q4', '2026-Q1', '2026-Q3']); + // 2026-Q2 holds no row and is filled in its place (#26893). + expect(result.rows.map((r) => r.closed_quarter)).toEqual(['2025-Q4', '2026-Q1', '2026-Q2', '2026-Q3']); }); it('emits a real ORDER BY when native SQL serves the query', async () => { diff --git a/packages/services/service-analytics/src/__tests__/dataset-time-bucket-zero-fill.test.ts b/packages/services/service-analytics/src/__tests__/dataset-time-bucket-zero-fill.test.ts new file mode 100644 index 00000000000..e3136cea1df --- /dev/null +++ b/packages/services/service-analytics/src/__tests__/dataset-time-bucket-zero-fill.test.ts @@ -0,0 +1,409 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #26893 — a date-dimension series answers every bucket of its window, the + * empty ones included. + * + * A grouped query answers one row per bucket that HOLDS rows. HotCRM's + * "Revenue Trend: closed-won revenue over the last 12 months" came back with + * the months that held a deal and nothing for May and August, so the category + * axis drew April next to June and the area between them read as revenue. The + * executor now invents the missing buckets from its own calendar helpers, and + * the empty-group fill gives them their value (count/sum `0`, avg/min/max + * `null`). + * + * Served through the real plugin, the real ObjectQL engine and a real SQLite + * driver (sql.js), the way `objectql-echo-bucket-enumeration.test.ts` serves + * its table: a bucketed query declines native SQL, so every trend reaches the + * engine's `aggregate()` and the driver's own date bucket. + * + * Pinned: + * - the window is the time dimension's `dateRange` — an explicit pair and a + * preset — and the buckets come back in order; + * - with the window only in `runtimeFilter` (the dashboard widget's shape) + * or only a lower bound (HotCRM's `{ $gte: '{12_months_ago}' }`), only the + * gaps between the first and last bucket returned are filled; + * - another grid dimension is filled per combination that holds a row; + * - a non-UTC zone: the keys the fill writes are the keys the query writes; + * - the controls — a full window, a top-N, an order on a measure, no time + * dimension, `compareTo` — come back as they always have; + * - the bound: a fill past `MAX_ZERO_FILLED_GRID_ROWS` does not run at all. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { DatasetSchema } from '@objectstack/spec/ui'; +import type { DatasetSelection } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { AnalyticsService } from '../analytics-service.js'; +import { AnalyticsServicePlugin } from '../plugin.js'; +import { + fillEmptyTimeBuckets, + MAX_ZERO_FILLED_GRID_ROWS, +} from '../dataset-executor.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const DEAL = 'os26893_deal'; +const DEAL_OBJECT = { + name: DEAL, + label: 'Zero-fill deal', + fields: { + close_date: { name: 'close_date', type: 'date' as const }, + closed_at: { name: 'closed_at', type: 'datetime' as const }, + stage: { name: 'stage', type: 'text' as const }, + owner: { name: 'owner', type: 'text' as const }, + amount: { name: 'amount', type: 'number' as const }, + }, +}; + +/** The HotCRM `opportunity_metrics` shape: a month-bucketed close date and the three aggregates. */ +const DATASET = DatasetSchema.parse({ + name: 'os26893_metrics', + label: 'Zero-fill metrics', + object: DEAL, + include: [], + dimensions: [ + { name: 'close_date', field: 'close_date', type: 'date', dateGranularity: 'month' }, + { name: 'closed_at', field: 'closed_at', type: 'date' }, + { name: 'stage', field: 'stage', type: 'string' }, + { name: 'owner', field: 'owner', type: 'string' }, + ], + measures: [ + { name: 'opp_count', aggregate: 'count' }, + { name: 'total_amount', aggregate: 'sum', field: 'amount' }, + { name: 'avg_amount', aggregate: 'avg', field: 'amount' }, + ], +}); + +/** + * Twelve months, 2025-11 through 2026-10, closed-won in ten of them: nothing + * in 2026-05 or 2026-08 (the filing's two months). October holds the daily + * series: 1, 2, 3, 6, 9 and 10 October, so 4–5 and 7–8 are interior gaps and + * 11–30 are past the last row. One `lost` deal sits in May, so the stage + * filter is what empties it. + */ +const DEALS = [ + { id: 'd01', close_date: '2025-11-14', stage: 'closed_won', owner: 'ann', amount: 10 }, + { id: 'd02', close_date: '2025-12-02', stage: 'closed_won', owner: 'bob', amount: 20 }, + { id: 'd03', close_date: '2026-01-20', stage: 'closed_won', owner: 'ann', amount: 30 }, + { id: 'd04', close_date: '2026-02-11', stage: 'closed_won', owner: 'bob', amount: 40 }, + { id: 'd05', close_date: '2026-03-05', stage: 'closed_won', owner: 'ann', amount: 50 }, + { id: 'd06', close_date: '2026-04-18', stage: 'closed_won', owner: 'ann', amount: 60 }, + { id: 'd07', close_date: '2026-05-09', stage: 'lost', owner: 'bob', amount: 999 }, + { id: 'd08', close_date: '2026-06-23', stage: 'closed_won', owner: 'bob', amount: 70 }, + { id: 'd09', close_date: '2026-07-07', stage: 'closed_won', owner: 'ann', amount: 80 }, + { id: 'd10', close_date: '2026-09-30', stage: 'closed_won', owner: 'bob', amount: 90 }, + { id: 'd11', close_date: '2026-10-01', stage: 'closed_won', owner: 'ann', amount: 1 }, + { id: 'd12', close_date: '2026-10-02', stage: 'closed_won', owner: 'ann', amount: 2 }, + { id: 'd13', close_date: '2026-10-03', stage: 'closed_won', owner: 'bob', amount: 3 }, + { id: 'd14', close_date: '2026-10-06', stage: 'closed_won', owner: 'ann', amount: 6 }, + { id: 'd15', close_date: '2026-10-09', stage: 'closed_won', owner: 'ann', amount: 9 }, + { id: 'd16', close_date: '2026-10-10', stage: 'closed_won', owner: 'ann', amount: 10 }, +] as const; + +const WON = { stage: 'closed_won' }; +const TWELVE_MONTHS: [string, string] = ['2025-11-01', '2026-10-31']; +const MONTHS = [ + '2025-11', '2025-12', '2026-01', '2026-02', '2026-03', '2026-04', + '2026-05', '2026-06', '2026-07', '2026-08', '2026-09', '2026-10', +]; + +const quiet = { debug() {}, info() {}, warn() {}, error() {}, child() { return quiet; } }; +const CTX = { tenantId: 'org_default' } as ExecutionContext; + +let engine: ObjectQL; +let analytics: AnalyticsService; + +beforeAll(async () => { + const driver = new SqliteWasmDriver({ filename: ':memory:' }); + engine = new ObjectQL({ logger: quiet } as any); + engine.registerDriver(driver as any, true); + await engine.init(); + engine.registry.registerObject(DEAL_OBJECT as any); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const deal of DEALS) await engine.insert(DEAL, { ...deal } as any); + + const registered: Record = {}; + await new AnalyticsServicePlugin({} as any).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); + analytics = registered.analytics as AnalyticsService; +}); + +afterAll(async () => { + await (engine as any)?.destroy?.(); +}); + +const run = (selection: DatasetSelection) => analytics.queryDataset!(DATASET, selection, CTX); +const series = (rows: Record[], axis = 'close_date', measure = 'total_amount') => + rows.map((row) => [row[axis], row[measure] == null ? row[measure] : Number(row[measure])]); + +describe('[#26893] a month series over a 12-month dateRange answers all twelve months', () => { + it('the two empty months come back in order, with count/sum 0 and no avg', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['opp_count', 'total_amount', 'avg_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: TWELVE_MONTHS }], + }); + expect(res.rows.map((r) => r.close_date)).toEqual(MONTHS); + const may = res.rows.find((r) => r.close_date === '2026-05')!; + const aug = res.rows.find((r) => r.close_date === '2026-08')!; + for (const empty of [may, aug]) { + expect(empty.opp_count).toBe(0); + expect(empty.total_amount).toBe(0); + // An empty group's avg is left unset, not 0 (`emptyGroupValueFor`): the + // invented bucket reads the same. + expect(empty.avg_amount ?? null).toBeNull(); + } + // A real bucket keeps its own numbers. + expect(series(res.rows).find(([k]) => k === '2026-10')).toEqual(['2026-10', 31]); + }); + + it('a window wider than the data fills the edges too, and the response describes no new column', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2025-09-01', '2026-12-31'] }], + }); + expect(res.rows.map((r) => r.close_date)).toEqual(['2025-09', '2025-10', ...MONTHS, '2026-11', '2026-12']); + expect(res.fields.map((f) => f.name)).toEqual(['close_date', 'total_amount']); + }); + + it('a preset window is the one the query filtered by (this_year, frozen at 2026-10-15)', async () => { + vi.useFakeTimers({ now: new Date('2026-10-15T12:00:00.000Z'), toFake: ['Date'] }); + try { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: 'this_year' }], + }); + expect(res.rows.map((r) => r.close_date)).toEqual([ + '2026-01', '2026-02', '2026-03', '2026-04', '2026-05', '2026-06', + '2026-07', '2026-08', '2026-09', '2026-10', '2026-11', '2026-12', + ]); + } finally { + vi.useRealTimers(); + } + }); + + it('a week axis spells its invented keys the way the grouping spells real ones, across a week-year', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['opp_count'], + dateGranularity: 'week', + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2025-12-01', '2026-01-25'] }], + }); + // 2025-12-02 is 2025-W49 and 2026-01-20 is 2026-W04; Monday 2025-12-29 opens 2026-W01. + expect(series(res.rows, 'close_date', 'opp_count')).toEqual([ + ['2025-W49', 1], ['2025-W50', 0], ['2025-W51', 0], ['2025-W52', 0], + ['2026-W01', 0], ['2026-W02', 0], ['2026-W03', 0], ['2026-W04', 1], + ]); + }); +}); + +describe('[#26893] with no dateRange, only the interior gaps are filled', () => { + it('a day series with its 30-day window in runtimeFilter only: the gaps between the first and last day', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['opp_count'], + dateGranularity: 'day', + runtimeFilter: { ...WON, close_date: { $gte: '2026-10-01', $lte: '2026-10-30' } }, + }); + // 11–30 October are past the last row: no seam reads a window out of a + // filter, so they are not invented. + expect(series(res.rows, 'close_date', 'opp_count')).toEqual([ + ['2026-10-01', 1], ['2026-10-02', 1], ['2026-10-03', 1], ['2026-10-04', 0], ['2026-10-05', 0], + ['2026-10-06', 1], ['2026-10-07', 0], ['2026-10-08', 0], ['2026-10-09', 1], ['2026-10-10', 1], + ]); + }); + + it('HotCRM\'s one-bound filter ({ $gte }) fills May and August, and invents no month before the first', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: { ...WON, close_date: { $gte: '2026-03-01' } }, + }); + expect(series(res.rows)).toEqual([ + ['2026-03', 50], ['2026-04', 60], ['2026-05', 0], ['2026-06', 70], + ['2026-07', 80], ['2026-08', 0], ['2026-09', 90], ['2026-10', 31], + ]); + }); + + it('no window and no rows: no buckets', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: { stage: 'no_such_stage' }, + }); + expect(res.rows).toEqual([]); + }); + + it('a window and no rows: the window\'s buckets, all empty', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['opp_count'], + runtimeFilter: { stage: 'no_such_stage' }, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-01-01', '2026-03-31'] }], + }); + expect(series(res.rows, 'close_date', 'opp_count')).toEqual([['2026-01', 0], ['2026-02', 0], ['2026-03', 0]]); + }); +}); + +describe('[#26893] another grid dimension: each combination that holds a row is filled once', () => { + it('month × owner: both owners get every month; an owner no row holds is not invented', async () => { + const res = await run({ + dimensions: ['close_date', 'owner'], + measures: ['opp_count'], + runtimeFilter: { ...WON, owner: { $in: ['ann', 'bob', 'nobody'] } }, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-01-01', '2026-04-30'] }], + }); + const cells = res.rows.map((r) => `${r.close_date}|${r.owner}|${r.opp_count}`).sort(); + expect(cells).toEqual([ + '2026-01|ann|1', '2026-01|bob|0', + '2026-02|ann|0', '2026-02|bob|1', + '2026-03|ann|1', '2026-03|bob|0', + '2026-04|ann|1', '2026-04|bob|0', + ]); + }); +}); + +describe('[#26893] a non-UTC zone: the fill writes the keys the query writes', () => { + it('Asia/Shanghai, last_7_days frozen at 2026-03-06T20:00Z (already 7 March in Shanghai)', async () => { + // 2026-03-04T17:30Z is 01:30 on 5 March in Shanghai: the query keys it + // `2026-03-05`, and the fill must neither re-invent that day nor key the + // window on the UTC calendar (which would end on the 6th). + await engine.insert(DEAL, { id: 'tz1', closed_at: '2026-03-04T17:30:00.000Z', stage: 'tz_probe', owner: 'ann', amount: 5 } as any); + vi.useFakeTimers({ now: new Date('2026-03-06T20:00:00.000Z'), toFake: ['Date'] }); + try { + const res = await run({ + dimensions: ['closed_at'], + measures: ['opp_count'], + dateGranularity: 'day', + timezone: 'Asia/Shanghai', + runtimeFilter: { stage: 'tz_probe' }, + timeDimensions: [{ dimension: 'closed_at', dateRange: 'last_7_days' }], + }); + expect(series(res.rows, 'closed_at', 'opp_count')).toEqual([ + ['2026-02-28', 0], ['2026-03-01', 0], ['2026-03-02', 0], ['2026-03-03', 0], + ['2026-03-04', 0], ['2026-03-05', 1], ['2026-03-06', 0], ['2026-03-07', 0], + ]); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('[#26893] controls — answers the fill must not change', () => { + it('a fully populated window comes back exactly as grouped', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-01-01', '2026-04-30'] }], + }); + expect(series(res.rows)).toEqual([['2026-01', 30], ['2026-02', 40], ['2026-03', 50], ['2026-04', 60]]); + }); + + it('a top-N (limit + order on a measure) picks from the real buckets only', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: TWELVE_MONTHS }], + order: { total_amount: 'asc' }, + limit: 3, + }); + expect(series(res.rows)).toEqual([['2025-11', 10], ['2025-12', 20], ['2026-01', 30]]); + }); + + it('an order on a measure without a limit is not filled either', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: TWELVE_MONTHS }], + order: { total_amount: 'desc' }, + }); + expect(res.rows).toHaveLength(10); + expect(res.rows.map((r) => r.close_date)).not.toContain('2026-05'); + }); + + it('a limit alone is not filled', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: TWELVE_MONTHS }], + limit: 6, + }); + expect(res.rows.map((r) => r.close_date)).toEqual(['2025-11', '2025-12', '2026-01', '2026-02', '2026-03', '2026-04']); + }); + + it('a query with no time dimension is unchanged', async () => { + const res = await run({ dimensions: ['owner'], measures: ['opp_count'], runtimeFilter: WON }); + expect(res.rows.map((r) => `${r.owner}|${r.opp_count}`).sort()).toEqual(['ann|10', 'bob|5']); + }); + + it('compareTo keeps its shape: its empty buckets are not filled', async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['total_amount'], + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2026-05-01', '2026-08-31'] }], + compareTo: { kind: 'previousYear' }, + }); + // May and August hold nothing in either window (2025-05..08 holds no + // deal), and stay absent: the fill does not run under `compareTo`. + expect(series(res.rows)).toEqual([['2026-06', 70], ['2026-07', 80]]); + expect(res.rows.map((r) => r.total_amount__compare)).toEqual([0, 0]); + }); + + it(`a fill past ${MAX_ZERO_FILLED_GRID_ROWS} rows does not run at all — never a partial fill`, async () => { + const res = await run({ + dimensions: ['close_date'], + measures: ['opp_count'], + dateGranularity: 'day', + runtimeFilter: WON, + timeDimensions: [{ dimension: 'close_date', dateRange: ['2017-01-01', '2026-12-31'] }], + }); + expect(res.rows).toHaveLength(DEALS.filter((d) => d.stage === 'closed_won').length); + }); +}); + +describe('[#26893] fillEmptyTimeBuckets — the walk itself', () => { + const plan = { axis: 'm', granularity: 'month' as const, dimensions: ['m'] }; + + it('leaves the null bucket where it is and fills around it', () => { + const rows = [{ m: '2026-01', n: 1 }, { m: null, n: 4 }, { m: '2026-03', n: 2 }]; + fillEmptyTimeBuckets(rows, plan); + expect(rows.map((r) => r.m)).toEqual(['2026-01', null, '2026-03', '2026-02']); + }); + + it('declines a key that is not a bucket key of the plan\'s granularity', () => { + const rows = [{ m: '2026-01-15T10:00:00.000Z' }, { m: '2026-03' }]; + expect(fillEmptyTimeBuckets(rows, plan)).toHaveLength(2); + }); + + it('invents no row it already holds (one-row series, no window)', () => { + const rows = [{ m: '2026-01' }]; + expect(fillEmptyTimeBuckets(rows, plan)).toEqual([{ m: '2026-01' }]); + }); + + it('declines at the bound, and runs just under it', () => { + const day = { axis: 'd', granularity: 'day' as const, dimensions: ['d'] }; + // 2,000 days from 2020-01-01 is 2025-06-22 inclusive; one more is past the bound. + const under = fillEmptyTimeBuckets([], { ...day, window: ['2020-01-01', '2025-06-22'] }); + expect(under).toHaveLength(MAX_ZERO_FILLED_GRID_ROWS); + expect(fillEmptyTimeBuckets([], { ...day, window: ['2020-01-01', '2025-06-23'] })).toEqual([]); + }); +}); diff --git a/packages/services/service-analytics/src/__tests__/dataset-window-timedimension-bucketing.test.ts b/packages/services/service-analytics/src/__tests__/dataset-window-timedimension-bucketing.test.ts index 89ef7f208d2..463891a6c80 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-window-timedimension-bucketing.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-window-timedimension-bucketing.test.ts @@ -300,11 +300,13 @@ describe('#5688 — an entry asking to be bucketed still is (#3588/#4033/#4870 g // Left unbucketed this would group RAW TIMESTAMPS — one bucket per row, // which is the #3588 defect the backfill was introduced to fix. expect(groupByOf(calls[0])).toEqual(['owner_id', { field: 'close_date', dateGranularity: 'month' }]); - // Chronological by default on the time axis (#3916), ties in grouping order. + // Chronological by default on the time axis (#3916), ties in grouping order; + // u2 holds no February row, so its empty bucket is filled at 0 (#26893). expect(result.rows).toEqual([ { owner: 'u1', close_date: '2026-01', opp_count: 1 }, { owner: 'u2', close_date: '2026-01', opp_count: 1 }, { owner: 'u1', close_date: '2026-02', opp_count: 1 }, + { owner: 'u2', close_date: '2026-02', opp_count: 0 }, ]); expect(descriptor(result.fields, 'close_date')).toEqual({ name: 'close_date', type: 'time', label: 'Close Date', diff --git a/packages/services/service-analytics/src/__tests__/drill-sidecars-emission.test.ts b/packages/services/service-analytics/src/__tests__/drill-sidecars-emission.test.ts index 81e70ba8a6f..773572a0f25 100644 --- a/packages/services/service-analytics/src/__tests__/drill-sidecars-emission.test.ts +++ b/packages/services/service-analytics/src/__tests__/drill-sidecars-emission.test.ts @@ -89,12 +89,16 @@ describe('the drill-through sidecars are emitted on the declared AnalyticsResult drillRawTotals: answer.drillRawTotals, drillRanges: answer.drillRanges, }; + // Each stage holds one of the two months, so the other is filled as an + // empty bucket (#26893) and drills like any row: four grid rows, by month. expect(JSON.stringify(sidecars)).toBe( '{"dimensionFields":{"stage":"stage"},' + - '"drillRawRows":[{"stage":"qualification"},{"stage":"won"}],' + + '"drillRawRows":[{"stage":"qualification"},{"stage":"won"},{"stage":"won"},{"stage":"qualification"}],' + '"drillRawTotals":[[{"stage":"qualification"},{"stage":"won"}],[{}]],' + '"drillRanges":[' + '{"close_date":{"field":"close_date","gte":"2026-06-01","lt":"2026-07-01"}},' + + '{"close_date":{"field":"close_date","gte":"2026-06-01","lt":"2026-07-01"}},' + + '{"close_date":{"field":"close_date","gte":"2026-07-01","lt":"2026-08-01"}},' + '{"close_date":{"field":"close_date","gte":"2026-07-01","lt":"2026-08-01"}}]}', ); }); diff --git a/packages/services/service-analytics/src/dataset-executor.ts b/packages/services/service-analytics/src/dataset-executor.ts index 4f55161ea53..55592517a85 100644 --- a/packages/services/service-analytics/src/dataset-executor.ts +++ b/packages/services/service-analytics/src/dataset-executor.ts @@ -43,6 +43,8 @@ export type CompareTo = DatasetCompareTo; * EVERY window it runs, the `compareTo` one included (#4820) — and keeps the * assembled grid's `fields` describing its DIMENSION columns even when there * was no primary query to carry them (#5537), + * - invents the time buckets a grouped query emitted no row for, inside the + * selection's window (#26893), so a trend keeps its empty months, * - fills the empty-group value into columns no query reported, by aggregate * kind (#4708) — a count/sum over an excluded group is 0, avg/min/max null, * - evaluates derived measures (ratio/sum/difference/product) row-by-row (Q1), @@ -233,9 +235,13 @@ export function evaluateDerivedMeasures( * kind→identity mapping is `emptyGroupValueFor` in `@objectstack/spec/data`, * shared with the authoring-side coherence checks so the two cannot drift. * - * **Only rows that already exist are touched** — no group is invented. A + * **Only rows that already exist are touched** — no group is invented here. A * dimension value no query reported at all has genuinely no data and stays out - * of the grid; this fills the cell, never the row. + * of the grid; this fills the cell, never the row. The one place a row IS + * invented is {@link fillEmptyTimeBuckets} (#26893), which runs just before this + * pass and leaves its rows' measure cells empty for this pass to fill — so an + * invented time bucket reads exactly what an empty group reads, from this one + * table. * * Deliberately NOT a `?? 0` in the widget or a `coalesce` in the measure: a * consumer-side patch must be repeated by every author of every ratio widget @@ -1019,6 +1025,157 @@ export function alignedCompareBucketKey( return bucketKeyAtOrdinal(targetOrdinal, granularity); } +// ── zero-filled time buckets (#26893) ──────────────────────────────────────── + +/** + * The most rows one {@link fillEmptyTimeBuckets} call may leave in the grid — + * the window's bucket count times the number of other-dimension combinations. + * + * A fill whose grid would be larger does not run AT ALL: the answer is the + * grouped rows exactly as they came back, never a fill cut off part-way, which + * would draw a series that is dense up to an arbitrary bucket and sparse after + * it. 2,000 lets a `day` axis span five years as one series (or a year per five + * series) and stops a `day` axis over ten years, the shape the fill exists for + * least. + */ +export const MAX_ZERO_FILLED_GRID_ROWS = 2000; + +/** What {@link fillEmptyTimeBuckets} walks — built by `DatasetExecutor`. */ +export interface TimeBucketFillPlan { + /** The grid's one bucketed time dimension: the axis the fill walks. */ + axis: string; + /** Its EFFECTIVE bucket size (`DatasetExecutor.granularityOf`). */ + granularity: DateGranularityValue; + /** Every grid dimension, in selection order — the merge key, axis included. */ + dimensions: string[]; + /** + * The bounded window, as the INCLUSIVE `[first, last]` calendar days it + * covers in the reference zone. Absent when the selection states none, and + * then only the gaps between the first and last bucket returned are filled. + */ + window?: [string, string]; +} + +/** + * Invent the time buckets a `GROUP BY` never emitted — the ones no row fell in + * (#26893). + * + * A grouped query answers one row per bucket that HOLDS rows, so a month with + * no closed-won deal is not a zero in a 12-month revenue trend: it is absent, + * and a category axis then draws the months either side of it as neighbours, + * the area between them reading as revenue. Only the executor knows the bucket + * vocabulary and the window, so the gap is closed here, from the same calendar + * helpers `compareTo` alignment counts with — {@link bucketOrdinalOfDay} to + * place a bucket, {@link bucketKeyAtOrdinal} to spell it (core's + * `bucketDateKey`, the labeller the grouping itself uses) — and ⛔ never by a + * second date walker in a renderer. + * + * **Which buckets.** Every bucket of the plan's `window`, or, with no window, + * every bucket between the first and last one the rows hold. ⛔ Never beyond + * what is known: no window and no rows means no buckets, and the leading and + * trailing edges of an unbounded series stay as they came back. + * + * **Other dimensions.** Each combination of the other grid dimensions that + * already holds a row is filled across the axis once; a combination no row + * holds is not invented (that would be a group, and groups are only ever the + * query's to report). The null bucket (#3839) is not a calendar position: its + * rows count for their combination and are left as they are. + * + * **Values.** An invented row carries only its dimension columns. Its measure + * cells are filled by {@link fillEmptyGroups}, which runs after this, so they + * read what any empty group reads: `0` for count and sum, and avg, min and max + * left unset (`emptyGroupValueFor` has no value for them). ⛔ No second + * empty-value table. + * + * **Declines** (the rows are returned untouched): an axis key that is not a + * bucket key of the plan's granularity, and a filled grid larger than + * {@link MAX_ZERO_FILLED_GRID_ROWS}. + * + * Mutates `rows` in place (they are already this pipeline's own copies) and + * returns them for chaining; invented rows are appended, and the executor's + * ordering pass places them. + */ +export function fillEmptyTimeBuckets( + rows: Record[], + plan: TimeBucketFillPlan, +): Record[] { + const { axis, granularity, dimensions, window } = plan; + const others = dimensions.filter((d) => d !== axis); + + const present = new Set(); + const combinations = new Map>(); + let first = Infinity; + let last = -Infinity; + for (const row of rows) { + present.add(dimensionKeyOf(row, dimensions)); + const combination = dimensionKeyOf(row, others); + if (!combinations.has(combination)) { + combinations.set(combination, Object.fromEntries(others.map((d) => [d, row[d]]))); + } + const key = row[axis]; + if (key == null) continue; + const span = typeof key === 'string' ? bucketKeyToCalendarRange(key, granularity) : null; + if (!span) return rows; + const ordinal = bucketOrdinalOfDay(span.start, granularity); + if (ordinal < first) first = ordinal; + if (ordinal > last) last = ordinal; + } + if (window) { + first = bucketOrdinalOfDay(window[0], granularity); + last = bucketOrdinalOfDay(window[1], granularity); + // A single series over a known window is filled even when no row came back. + if (others.length === 0 && combinations.size === 0) combinations.set('', {}); + } + if (!(last >= first) || combinations.size === 0) return rows; + if ((last - first + 1) * combinations.size > MAX_ZERO_FILLED_GRID_ROWS) return rows; + + for (const combination of combinations.values()) { + for (let ordinal = first; ordinal <= last; ordinal++) { + const bucket = bucketKeyAtOrdinal(ordinal, granularity); + const row = Object.fromEntries(dimensions.map((d) => [d, d === axis ? bucket : combination[d]])); + const key = dimensionKeyOf(row, dimensions); + if (present.has(key)) continue; + present.add(key); + rows.push(row); + } + } + return rows; +} + +/** + * The calendar day one explicit `dateRange` bound names, in `timezone`: a bare + * `YYYY-MM-DD` is that day (the query reads it as the whole day, #3777), and an + * instant is the day it falls on in the reference zone — the zone the query's + * own buckets are keyed in. `undefined` for a bound that is neither; the fill + * then reads no window rather than refusing a query the strategy has already + * answered. + */ +function calendarDayOfBound(bound: string, timezone: string): string | undefined { + if (bound.length === 10) { + const ms = zonedDateStartToUtcMs(bound); + return !Number.isNaN(ms) && calendarDayAt(ms) === bound ? bound : undefined; + } + const ms = Date.parse(bound); + return Number.isNaN(ms) ? undefined : calendarDayAt(ms, timezone); +} + +/** + * The inclusive calendar days a time dimension's `dateRange` covers in + * `timezone` — the {@link TimeBucketFillPlan} window. A preset goes through the + * one lowering `compareTo` uses ({@link lowerDatasetCompareDateRange}, then + * {@link inclusiveCalendarDayWindow}), so a preset's window is the one the + * query path filtered by; an explicit pair is read bound by bound. + */ +function timeBucketFillWindow(dateRange: unknown, timezone: string): [string, string] | undefined { + if (!Array.isArray(dateRange)) { + return inclusiveCalendarDayWindow(lowerDatasetCompareDateRange(dateRange as string, timezone), timezone); + } + const [start, end] = explicitDateRangeWindow(dateRange); + const first = calendarDayOfBound(start, timezone); + const last = calendarDayOfBound(end, timezone); + return first != null && last != null ? [first, last] : undefined; +} + export class DatasetExecutor { /** * @param service - The analytics service the executor issues its queries to. @@ -1166,6 +1323,12 @@ export class DatasetExecutor { for (const m of baseMeasures) result.fields.push({ name: `${m}__compare`, type: 'number' }); } + // [#26893] Empty time buckets — the rows a `GROUP BY` never emitted for a + // bucket no row fell in. Before the empty-group fill below, which gives + // the invented rows' measure cells their value. + const bucketFill = this.timeBucketFillPlan(compiled, selection, dimensions, order, context); + if (bucketFill) fillEmptyTimeBuckets(result.rows, bucketFill); + // 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 // why this belongs to the executor and not to every widget author. @@ -1374,6 +1537,54 @@ export class DatasetExecutor { return resolveDimensionGranularity(selection, name, declaredDefaultGranularity(cd)); } + /** + * Whether this selection's answer gets its empty time buckets filled, and + * over which window (#26893) — `undefined` when it does not. + * + * Filled: a grid with exactly ONE bucketed time dimension (bucketed by the + * same {@link granularityOf} the `GROUP BY` reads). Two bucketed time axes + * name no single axis to walk, and a raw-timestamp axis has no buckets. + * + * Not filled, because filling would change which rows the caller asked for: + * - a `limit` or `offset` — a top-N or a page is a choice OF rows, and an + * invented bucket would compete for its slots; + * - an `order` on anything but a dimension — a measure, a `__compare` + * column or a derived measure ranks rows, and a column of invented + * zeros reorders the ranking; + * - a `compareTo` — its answer keeps the shape it has (its own empty + * buckets are a separate question). + * + * The window is the axis's own `timeDimensions[].dateRange`, read in the + * zone {@link buildQuery} resolves the query in. A window stated only in + * `runtimeFilter` is not read: no seam here lowers a filter into a window, + * and a one-bound filter (`{ $gte: '{12_months_ago}' }`) states none — those + * series get their interior gaps filled. + */ + private timeBucketFillPlan( + compiled: CompiledDataset, + selection: DatasetSelection, + dimensions: string[], + order: Record | undefined, + context?: ExecutionContext, + ): TimeBucketFillPlan | undefined { + if (selection.compareTo || selection.limit != null || selection.offset != null) return undefined; + if (Object.keys(order ?? {}).some((key) => !dimensions.includes(key))) return undefined; + const bucketed = dimensions.flatMap((d) => { + const granularity = this.granularityOf(compiled, selection, d); + return granularity ? [{ axis: d, granularity }] : []; + }); + if (bucketed.length !== 1) return undefined; + const [{ axis, granularity }] = bucketed; + const td = (selection.timeDimensions ?? []).find((t) => t.dimension === axis && t.dateRange != null); + const timezone = selection.timezone ?? context?.timezone ?? 'UTC'; + return { + axis, + granularity, + dimensions, + window: td ? timeBucketFillWindow(td.dateRange, timezone) : undefined, + }; + } + private buildQuery( compiled: CompiledDataset, opts: {