Skip to content

fix(charts): render time comparison without a time grain - #42054

Merged
rusackas merged 14 commits into
masterfrom
claude/superset-time-comparison-grain-dd1acc
Jul 17, 2026
Merged

rusackas merged 14 commits into
masterfrom
claude/superset-time-comparison-grain-dd1acc

Conversation

@sadpandajoe

@sadpandajoe sadpandajoe commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

A time-series chart using a relative time-comparison offset with no time grain returns HTTP 400 Time Grain must be specified when using Time Comparison. instead of rendering. The validation was introduced as a side effect of #39344, which turned a previously-dead guard into a live one. Before that change, grain-less comparisons didn't error — but they weren't correct either: the join matched current timestamps against historic ones, so the comparison series was silently empty.

This PR replaces the error with an exact alignment, so saved charts that started 400-ing render again — and now with a correct comparison series:

  • Grain-less relative offsets are aligned exactly. The main series' timestamps are shifted by the offset delta (e.g. -1 year for "1 year ago") and joined against the offset series' raw timestamps — the same convention generate_join_column uses for the grain path, just without truncation. Timestamps with no exact counterpart yield nulls, mirroring the grain-based join. The join uses stringified values so an empty offset series (which materializes join keys as NaN floats) can't crash the merge on a dtype mismatch.
  • normalize_time_delta converts quarters to months ("1 quarter ago" → {"months": -3}), since pd.DateOffset rejects a quarters argument. This also fixes a pre-existing crash for grain-based quarter offsets in generate_join_column.
  • Free-form offsets (e.g. "one year ago") that don't match normalize_time_delta's digit-only grammar are shifted per-row with get_past_or_future — the same parser that shifted the offset query's time range — instead of silently degrading. If the offset can't be interpreted at all, the join falls back to the raw keys and logs a warning.
  • The query's x-axis label selects the temporal join key, rather than whichever datetime column happens to come first, so results with multiple datetime columns align on the actual temporal axis.
  • Column order is preserved for grain-less joins. left_join_df's set_index().join().reset_index() round-trip moves join keys to the front; the original order is restored so chart payloads and CSV exports don't reorder dimensions.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Before:

Screen.Recording.2026-07-16.at.2.41.37.PM.mov

After:

Screen.Recording.2026-07-16.at.2.42.05.PM.mov

TESTING INSTRUCTIONS

  1. Create a time-series chart (e.g. ECharts Time-series Line) with a temporal x-axis.
  2. Set Time Grain to "None" (clear it).
  3. Enable a Time Comparison / time shift of "1 year ago" (any relative offset).
  4. On master this returns a 400 error; with this PR the chart renders and the comparison series aligns with the main series wherever shifted timestamps match exactly.
  5. Unit coverage: pytest tests/unit_tests/common/test_time_shifts.py tests/unit_tests/utils/date_parser_tests.py

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

🤖 Generated with Claude Code

A time-series chart using a relative time-comparison offset with no time
grain returned a 400 ("Time Grain must be specified when using Time
Comparison") instead of rendering. The validation was introduced as a
side effect of the time-shift join-column rework; before that, grain-less
comparisons joined current against historic timestamps and silently
produced an empty comparison series.

Instead of raising (or restoring the silently-broken raw join), align
grain-less relative offsets exactly: shift the main series' timestamps by
the offset delta and join them against the offset series' raw timestamps,
mirroring the grain-based join without truncation. Joining on stringified
values keeps the merge safe when an empty offset series materializes its
join keys as NaN floats.

Also, as part of this path:
- normalize_time_delta converts quarters to months, since pd.DateOffset
  rejects a `quarters` argument (this previously crashed grain-based
  quarter offsets too)
- free-form offsets (e.g. "one year ago") that fail the digit-only
  grammar are shifted with the same parser used for the offset query's
  time range, with a logged fallback when the offset is uninterpretable
- the query's x-axis label picks the temporal join key instead of the
  first datetime column
- grain-less joins preserve the original column order, which the
  set_index/join/reset_index round-trip otherwise rearranges

Co-Authored-By: Claude Fable 5 <[email protected]>
@dosubot dosubot Bot added explore:time Related to the time filters in Explore viz:charts:timeseries Related to Timeseries labels Jul 14, 2026

@bito-code-review bito-code-review Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review Agent Run #52d6f6

Actionable Suggestions - 1
  • tests/unit_tests/utils/date_parser_tests.py - 1
Review Details
  • Files reviewed - 4 · Commit Range: daae66f..daae66f
    • superset/models/helpers.py
    • superset/utils/date_parser.py
    • tests/unit_tests/common/test_time_shifts.py
    • tests/unit_tests/utils/date_parser_tests.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@sadpandajoe

Copy link
Copy Markdown
Member Author

The unit-tests failure is unrelated to this PR: test collection errors on tests/unit_tests/migrations/test_strip_metricsqlexpressions_from_ag_grid_params.py because the migration it imports uses the deprecated sqlalchemy.ext.declarative.declarative_base, which SQLALCHEMY_WARN_20=1 + the pytest filter turns into an error. Fix is pending in #42080 — will update this branch once it lands.

🤖 Generated with Claude Code

Comment thread superset/utils/date_parser.py Resolved
The regex matches case-insensitively but preserved the original casing,
so "1 QUARTER ago" skipped the quarters-to-months conversion and
"1 year AGO" shifted forward instead of back.

Co-Authored-By: Claude Fable 5 <[email protected]>
@sadpandajoe

Copy link
Copy Markdown
Member Author

The pre-commit (current) failure is also unrelated to this PR — it's a master breakage: superset/semantic_layers/mapper.py defines _get_time_axis_column twice (mypy no-redef, plus the duplicated tests), from overlapping semantic-layers merges. This PR doesn't touch those files. Upstream fix pending in #42093; once it (and #42080 for the unit-tests failure) lands, I'll update this branch to re-run CI.

🤖 Generated with Claude Code

@sadpandajoe

Copy link
Copy Markdown
Member Author

Status update on the unrelated CI failures: the declarative_base collection error is already fixed on master (#42056 landed), so unit-tests collection now succeeds. The remaining 3 unit-test failures and the pre-commit failure are all the semantic_layers/mapper.py duplicate _get_time_axis_column master breakage, fixed by the pending #42093. This PR's own tests all pass (10240 passed otherwise). I'll update the branch once #42093 lands.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 31.48148% with 37 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.98%. Comparing base (6fe4655) to head (47b829d).
⚠️ Report is 28 commits behind head on master.

Files with missing lines Patch % Lines
superset/models/helpers.py 13.88% 30 Missing and 1 partial ⚠️
superset/utils/date_parser.py 66.66% 5 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #42054      +/-   ##
==========================================
+ Coverage   64.43%   64.98%   +0.54%     
==========================================
  Files        2747     2751       +4     
  Lines      153977   154323     +346     
  Branches    35318    35346      +28     
==========================================
+ Hits        99216   100286    +1070     
+ Misses      52849    52123     -726     
- Partials     1912     1914       +2     
Flag Coverage Δ
hive 39.00% <12.96%> (-0.03%) ⬇️
mysql 57.73% <31.48%> (-0.12%) ⬇️
postgres 57.79% <31.48%> (?)
presto 40.98% <12.96%> (-0.04%) ⬇️
python 59.22% <31.48%> (+1.23%) ⬆️
sqlite 57.40% <31.48%> (-0.12%) ⬇️
unit 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sadpandajoe

Copy link
Copy Markdown
Member Author

CI is green after the master update. One note on the Codecov patch-coverage number: it understates this PR because of a pre-existing quirk in superset-python-unittest.yml — the "100% coverage" gate steps re-run pytest with scoped --cov targets after the full unit suite, overwriting the coverage data file before the Codecov upload, so unit-test coverage of files like superset/models/helpers.py never reaches Codecov. The changed lines here are covered directly by the unit tests added in this PR (tests/unit_tests/common/test_time_shifts.py, tests/unit_tests/utils/date_parser_tests.py).

🤖 Generated with Claude Code

Addresses three review findings on the grain-less time comparison fix:

- Quarter offsets queried the wrong period: parsedatetime does not
  understand "N quarters", so get_past_or_future silently left the
  offset query's window unshifted while the join keys moved back three
  months, yielding an all-null comparison. Quarter phrases are now
  rewritten to the equivalent months before parsing, fixing the window
  for both the grain and grain-less paths (and time_shift handling,
  which funnels through the same parser).

- Unparseable offsets duplicated current data: the same silent
  parser fallback fetched the current period, and the raw-key join then
  presented those rows as the comparison series. processing_time_offsets
  now rejects relative offsets that parse to a zero delta with a
  validation error (the grain path previously crashed with an unhandled
  TimeDeltaAmbiguousError on such offsets).

- Free-form offsets dropped timezone/sub-second precision: the
  per-row parser shift rebuilt timestamps at naive second resolution, so
  shifted keys could never match timezone-aware or fractional-second
  offset timestamps. Each row's delta is now computed from a truncated
  copy and applied to the original value; the unparseable-offset probe
  compares against the truncated value for the same reason.

The new processing_time_offsets tests run the real method against a
fake query that derives rows from the requested window, so a wrong
window fails the test instead of being masked by fabricated frames.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread superset/utils/date_parser.py Fixed
CodeQL flagged the quarter-rewrite pattern as polynomial: an unbounded
digit run followed by a failing match is re-scanned from every suffix.
A negative lookbehind restricts match attempts to the start of a digit
run and a bounded repetition caps the int() conversion; longer digit
runs fall through to parsedatetime like any other unparseable phrase.

Co-Authored-By: Claude Fable 5 <[email protected]>
@sadpandajoe
sadpandajoe force-pushed the claude/superset-time-comparison-grain-dd1acc branch from 9453ad3 to feaf01e Compare July 16, 2026 00:03
…ilure

processing_time_offsets rejects uninterpretable relative offsets with
QueryObjectValidationError, which get_df_payload catches and returns as
a failed payload, instead of leaking TimeDeltaAmbiguousError as an
unhandled exception.

Co-Authored-By: Claude Fable 5 <[email protected]>
@bito-code-review

bito-code-review Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #c5f563

Actionable Suggestions - 0
Review Details
  • Files reviewed - 6 · Commit Range: daae66f..06bdd54
    • tests/unit_tests/utils/date_parser_tests.py
    • tests/unit_tests/common/test_time_shifts.py
    • superset/utils/date_parser.py
    • superset/models/helpers.py
    • tests/unit_tests/common/test_query_context_processor.py
    • tests/integration_tests/query_context_tests.py
  • Files skipped - 0
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

…oundary alignment

Replace the per-row ``.map(lambda value: value + delta)`` in the grain-less time-comparison join with vectorized ``DateOffset`` addition over the datetime column (byte-identical output; NaT rows still shift to NaT). Add a docstring note that month/quarter/year offsets clamp to a valid calendar day, so several end-of-month rows can align to one offset timestamp when there is no time grain to truncate against.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@netlify

netlify Bot commented Jul 16, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 6be3395
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a5871fa91763200084568a8
😎 Deploy Preview https://deploy-preview-42054--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Comment thread superset/utils/date_parser.py Resolved
Comment thread superset/models/helpers.py Resolved
Comment thread superset/models/helpers.py Resolved
Annotate the _QUARTERS_PATTERN module constant, the two new
processing_time_offsets test signatures (with a typed Any alias for the
MagicMock datasource the tests bind real methods onto), and the caplog
fixture parameter.

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🎪 Showtime deployed environment on GHA for 5e4f6b6

• Environment: http://35.86.252.225:8080 (admin/admin)
• Lifetime: 48h auto-cleanup
• Updates: New commits create fresh environments automatically

This reverts commit 41eaa74.

Annotating the fixture as QueryContextProcessor resolves _qc_datasource to
the Explorable protocol, which does not declare get_offset_custom_or_inherit
-- the `processor` fixture binds it (and several other ExploreMixin methods)
onto a mock at runtime. The annotation therefore broke mypy:

    tests/unit_tests/common/test_query_context_processor.py:425: error:
    "Explorable" has no attribute "get_offset_custom_or_inherit"

The tests that reach through _qc_datasource for these bound methods are
deliberately left unannotated for this reason.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

🎪 Showtime is building environment on GHA for 47b829d

@github-actions

Copy link
Copy Markdown
Contributor

🎪 Showtime deployed environment on GHA for 47b829d

• Environment: http://54.191.82.136:8080 (admin/admin)
• Lifetime: 48h auto-cleanup
• Updates: New commits create fresh environments automatically

@bito-code-review

Copy link
Copy Markdown
Contributor

Bito Automatic Review Failed - Technical Failure

Bito encountered technical difficulties while generating code feedback . To retry, type /review in a comment and save. If the issue persists, contact [email protected] and provide the following details:

Agent Run ID: 67810da5-8efc-4e7d-b956-cdbfbc15bc88

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for digging into this, Joe. Nice catch that #39344 turned a dead guard into a regression.

This touches a good chunk of processing_time_offsets and _determine_join_keys though, DST edge cases, quarter-to-month conversion, and free-form offset parsing all folded into one join path.

Bot comments look addressed, LGTM

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

Labels

explore:time Related to the time filters in Explore merge-if-green If approved and tests are green, please go ahead and merge it for me size/XXL viz:charts:timeseries Related to Timeseries

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants