Skip to content

fix(service-analytics): a date-dimension series answers every bucket of its window, the empty ones included - #27109

Merged
objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/project-thread-up6vo3
Oct 28, 2026
Merged

objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/project-thread-up6vo3

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread

Fixes #26893

Clause-②: no
Metadata-protocol: none

维护者速读

  • 改了什么:按日期维度分桶的数据集查询(仪表盘趋势图走的 POST /api/v1/analytics/dataset/query),现在会把窗口内没有记录的月/日/周补成空桶返回:count、sum 为 0,avg/min/max 不给值。有 dateRange 时补满整个窗口;没有 dateRange 时只补首尾之间的空缺。
  • 为什么改:HotCRM「近 12 个月成交收入」把 5 月、8 月整个漏掉,图上 4 月直接连到 6 月,看起来那两个月有收入;「近 30 天工单量」同样跳过零值的日子。
  • 风险与回滚:低到中。只改 dataset-executor.ts 的后处理,不动 SQL;带 limit/offset、按度量排序、compareTo 的查询不补;补完超过 2000 行的不补(整体不补,绝不补一半)。回滚即 revert。
  • 先看:packages/services/service-analytics/src/dataset-executor.ts 的 fillEmptyTimeBuckets 与 timeBucketFillPlan;src/__tests__/dataset-time-bucket-zero-fill.test.ts。
  • 两分钟验证:pnpm --filter @objectstack/service-analytics exec vitest run --maxWorkers=2 src/__tests__/dataset-time-bucket-zero-fill.test.ts,预期 21/21 通过。
  • 需要你做的:无,席位落地。

What changes

DatasetExecutor.executeSelection gains one step, after the measure-scoped and compareTo merges and before the empty-group fill: fillEmptyTimeBuckets invents a row for every time bucket the grouped query emitted none for. The bucket is placed with bucketOrdinalOfDay and spelled with bucketKeyAtOrdinal (core's bucketDateKey, the labeller the grouping uses), the same helpers compareTo alignment counts with. No second date walker; nothing under ui/.

  • Which buckets. Every bucket of the time dimension's timeDimensions[].dateRange window, in the zone buildQuery resolves the query in. A preset goes through the lowering compareTo uses (lowerDatasetCompareDateRange + inclusiveCalendarDayWindow); an explicit pair is read bound by bound (a bare day is that day, an instant is its day in the reference zone). With no dateRange, only the gaps between the first and last bucket returned. ⛔ Never beyond what is known: no window and no rows answer no rows.
  • Values. An invented row carries only its dimension columns; fillEmptyGroups then gives its measures what an empty group already reads through emptyGroupValueFor: 0 for count/sum, avg/min/max left unset. No second empty-value table. fillEmptyGroups' docblock now names the one place a row is invented.
  • 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. The null bucket stays as it is.
  • Skipped (rows come back exactly as grouped): a limit or offset; an order on anything but a dimension (a measure, __compare column or derived measure); a compareTo; a grid with two bucketed time dimensions; an axis key that is not a bucket key of the granularity.
  • The bound. MAX_ZERO_FILLED_GRID_ROWS = 2000 (window buckets × combinations). Past it the fill does not run at all, never a partial fill. 2,000 lets a day axis span five years as one series and stops a day axis over ten years. Not re-exported from the package index, so the public surface is unchanged.

Seat rulings, as measured

  1. Default, not opt-in. No spec key, no new export on src/index.ts, no type change, no input refused: Clause-②: no, Metadata-protocol: none, patch.
  2. The window. dateRange is read. runtimeFilter is NOT: measured, no server seam lowers a filter into a window (the only reader of a closed bound pair, extractDateWindows / boundedDateWindow, lives in ui/packages/plugin-dashboard/src/DatasetWidget.tsx; grep over packages/services/service-analytics/src and packages/core/src finds none), and HotCRM's two filed widgets carry a ONE-bound filter (executive.dashboard.ts revenue_trend: close_date: { $gte: '{12_months_ago}' }; service.dashboard.ts daily_case_volume: created_at: { $gte: '{30_days_ago}' }, on hotcrm 173b488), so there is no closed pair to read anyway. Those series get their interior gaps filled, which is exactly the filed May/August and Sep 30/Oct 1 gaps.
  3. Top-N skips it, pinned as controls (limit + measure order, measure order alone, limit alone).

Tests

  • New src/__tests__/dataset-time-bucket-zero-fill.test.ts (21): served through the real AnalyticsServicePlugin, a real ObjectQL engine and SqliteWasmDriver. Month series over a 12-month explicit window with May/August empty → 12 rows in order, count/sum 0, avg unset; a wider window fills the edges and adds no field; a preset (this_year, frozen clock); week keys across the 2025/2026 ISO week-year; day series with the 30-day window only in runtimeFilter → interior gaps only; HotCRM's one-bound filter → May/August filled, nothing before March; no window + no rows → none; window + no rows → the window's buckets; month × owner → each owner filled, an owner with no row not invented; non-UTC pin: Asia/Shanghai, last_7_days frozen at 2026-03-06T20:00Z → eight Shanghai days ending 2026-03-07 (the UTC calendar would end on the 6th), the real row keyed 2026-03-05 by the query and not re-invented. Controls: full window unchanged, top-N, measure order, limit, no time dimension, compareTo (previousYear, the two empty months stay absent), the bound (day over ten years untouched). Unit: null bucket kept, non-bucket key declines, bound exact at 2,000 / 2,001.
  • Fixture triage, sparse grids that now carry their empty buckets (expectations updated, each with a #26893 comment): aggregate-datetime-measure-refusal.test.ts (its double keyed the row by the dimension name, so it landed in the null bucket; now keyed by the field as the engine answers → 12 months, May 3), bucket-key-readers-four-digit-year.test.ts (pins the two real keys; the year axis gains 1,975 empty years, finer ones exceed the bound), dataset-time-axis-order.test.ts (+2026-Q2), dataset-window-timedimension-bucketing.test.ts (+ u2 February at 0), drill-sidecars-emission.test.ts (four grid rows).
  • packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts (claim amendment 6461493732): under America/Los_Angeles, 2024-03-01 lies between the boundary leads and the seed's own, so it is now present at 0; asserted toBe(0) exactly, so an absent bucket (the base behaviour) still reds it.
Live red/green through the REST door (app-crm, opportunity_metrics)

pnpm dev:crm -- --fresh, signed in as the dev admin, POST /api/v1/analytics/dataset/query with datasetName: opportunity_metrics. Red = base blob of dataset-executor.ts (fbc16563) written over the file and @objectstack/service-analytics rebuilt (dist marker MAX_ZERO_FILLED_GRID_ROWS: 0 hits); green = HEAD rebuilt (2 hits); restore proven by git diff HEAD empty and the blob hash equal to HEAD's.

A — month, dateRange: ['2025-11-01','2026-10-31'], runtimeFilter: { stage: 'closed_won' }:

RED    rows 2   2026-07 170000 · 2026-10 235000
GREEN  rows 12  2025-11 0 … 2026-06 0 · 2026-07 170000 (avg 85000) · 2026-08 0 · 2026-09 0 · 2026-10 235000 (avg 78333.33)

B — HotCRM revenue_trend shape, runtimeFilter: { stage: 'closed_won', close_date: { $gte: '{12_months_ago}' } }:

RED    rows 2   2026-07 170000 · 2026-10 235000
GREEN  rows 4   2026-07 170000 · 2026-08 0 · 2026-09 0 · 2026-10 235000

C — top-N control (order: { total_amount: 'desc' }, limit: 3): 2 rows on both, identical.

The dogfood file above is red on the base dist (expected 0, received undefined, 1 failed / 1 passed) and green on HEAD (2/2).

Acceptance notes

  • compareTo drops empty buckets too (measured, not widened into): a bucket empty in both windows stays absent (compareTo keeps its shape control: May–August vs previous year answers only June and July). A bucket empty only in the current window already appears through the comparison merge. Filling under compareTo is a separate change.
  • The leading edge of a one-bound series stays unfilled. HotCRM's revenue_trend asks { $gte: '{12_months_ago}' } with no upper bound, so a trailing-twelve-months chart whose earliest months are empty still starts at its first deal. Bounding that edge needs the widget to state its window (a dateRange, or a closed pair the server could read); the order rules that the server does not read a window out of runtimeFilter.
  • avg/min/max on an invented bucket are absent keys on the wire (as on any empty group today), not explicit nulls.

Verification

All at head 32cdaee7.

  • pnpm --filter @objectstack/service-analytics test: 192 files, 4668 passed / 282 skipped, VERDICT command-exit 0.
  • pnpm --filter @objectstack/service-analytics typecheck + packages/qa/dogfood tsc --noEmit: exit 0.
  • eslint --no-inline-config packages/services/service-analytics/src packages/qa/dogfood/test/analytics-timezone.dogfood.test.ts: exit 0.
  • Downstream (after rebuilding @objectstack/service-analytics): @objectstack/rest analytics dataset suites (5 files, 83/83), @objectstack/runtime analytics-authored-cube-format-granularity.test.ts (3/3), and every dogfood file that posts a dataset query (9 files + empty-group-bucket-parity.test.ts, 96 tests; the one red was the timezone file above, then fixed).
  • node scripts/pm/dispatch-gates.mjs --commands: 63 derived families, all run, all exit 0 (check-plugin-teardown-shape --self-test after the documented git fetch --depth=1 of its fixture commit); --ran reconciliation: 63 derived, 63 run, 0 NOT-MEASURED.
  • Not run locally: test:repo (the diff touches no repo-project test; CI's Test Core runs it); the full dogfood battery (no !, no (narrowing) arm).

Generated by Claude Code

…of its window, the empty ones included

A grouped query answers one row per bucket that holds rows, so a month
with no closed-won deal disappeared from a 12-month revenue trend and the
chart drew its neighbours side by side. The dataset executor now invents
the missing buckets from its own calendar helpers (bucketOrdinalOfDay,
bucketKeyAtOrdinal), inside the time dimension's dateRange window, or
between the first and last bucket returned when no window is stated;
fillEmptyGroups then gives them the empty-group value (count/sum 0,
avg/min/max unset). A limit/offset, an order on a measure and compareTo
skip the fill, and a fill past 2,000 grid rows does not run at all.

Claude-Session: https://claude.ai/code/session_01FEkQ5poCcDpczhMAcc1W8M
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Oct 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

8 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run.

What this run could not see
  • 4 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 55 of 207 client-bound route-ledger rows — the other 152 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 152: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 55 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 97 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 10 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json a27f889a0508a8c27c0e3b8bfa7ae844ccd4764d → packageMentionDocs.

Which tree this was computed on

This run read content/docs from e2e3b2581efd91f9d7615b19707177f77a5e7fc6 — the merge of head 32cdaee790422299976f49e2a125fb1ca1fadb79 into base a27f889a0508a8c27c0e3b8bfa7ae844ccd4764d, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin e2e3b2581efd91f9d7615b19707177f77a5e7fc6 && git checkout e2e3b2581efd91f9d7615b19707177f77a5e7fc6
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin a27f889a0508a8c27c0e3b8bfa7ae844ccd4764d 32cdaee790422299976f49e2a125fb1ca1fadb79 && git checkout -B drift-repro a27f889a0508a8c27c0e3b8bfa7ae844ccd4764d && git merge --no-ff 32cdaee790422299976f49e2a125fb1ca1fadb79

node scripts/docs-audit/affected-docs.mjs --json a27f889a0508a8c27c0e3b8bfa7ae844ccd4764d

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

席位核对

ACCEPT · domain:server seat 2 · os-project-manager · session_0186vfjHHMsRXC9EUT9hTFMo · 2026-10-28T06:22Z · head 32cdaee7 · #26893

The maintainer's standing authorisation for landing reviewed PRs, verbatim: 「按照 pm-dispatch 规则复核过的都授权」.

  1. Shape:

    • A draft against main, assignee os-project-manager. The body carries Fixes #26893, Clause-②: no and Metadata-protocol: none, all line-initial.
    • The changeset is a patch on @objectstack/service-analytics.
    • check-governed-merges --pr 27109: NOT governed, 674 changed lines.
    • The claim (6461199296) names this PR's branch. The dogfood file is inside the amended surface (6461493732).
  2. Against the retriage (6457795584) and the seat rulings:

    • One bucketing rule. fillEmptyTimeBuckets walks with bucketOrdinalOfDay / bucketKeyAtOrdinal, the helpers compareTo alignment uses. It runs before fillEmptyGroups, so an invented row's measures read the one emptyGroupValueFor table: count and sum are 0, avg, min and max are unset. There is no second walker and no second empty-value table.
    • Ruling 1 (default): no spec key.
    • Ruling 2 (window): the axis's own dateRange is read in the same zone buildQuery uses (selection.timezone ?? context.timezone ?? 'UTC'). A preset goes through the compareTo lowering. The dev measured that no seam lowers a runtimeFilter into a window, so such series get their interior gaps filled. With no window and no rows, no bucket is invented.
    • Ruling 3 (top-N): a limit, offset, or order on a non-dimension declines the fill. So does compareTo, filed as analytics: a dataset query with compareTo still drops a time bucket that is empty in both windows, so a period-over-period trend keeps the #26893 gap #27111.
    • Other dimensions: each existing combination is filled across the axis, and no combination is invented. The null bucket is left alone.
    • Bound: above MAX_ZERO_FILLED_GRID_ROWS (2,000) the fill does not run at all. It is never cut off part-way, so the bound is not a silent cap.
    • Storage, ui/** and packages/spec/** are untouched.
  3. Red first and live (the dev's): the new 21-test suite runs on the real AnalyticsServicePlugin + ObjectQL + SQLite. It covers:

    • a 12-month window with May and Aug empty, giving 12 rows in order;
    • a preset;
    • ISO week-year keys;
    • a runtimeFilter-only window, which is filled interior-only;
    • month × owner;
    • a non-UTC pin (Asia/Shanghai);
    • the controls.

    Live on app-crm through POST /api/v1/analytics/dataset/query, the base answered the sparse rows and the head answers the full window.

  4. Fixture fallout: five existing tests asserted sparse grids and now assert the filled bucket in place (for example 2025-Q4, 2026-Q1, 2026-Q2, 2026-Q3). The dogfood neighbour-day assertion is exact (toBe(0)): red on the base dist, green on HEAD.

  5. Tests: the package passes 192 files (4,668 passed). Downstream, the rest analytics suites passed 83 of 83, and the 9 dogfood files that post dataset queries passed 96.

  6. Gates:

    • Locally 63 of 63 derived families exit 0, with 0 NOT-MEASURED.
    • CI on head 32cdaee7: 35 success, 13 skipped, 0 red.
  7. Overlap: git merge-tree reports no conflict against main d8a9cc59.

  8. Filed / noted:


Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Time-series charts drop empty date buckets and draw straight through them (a month with 0 revenue disappears from a 12-month trend)

2 participants