Skip to content

fix(charts): align grain-less time comparisons safely - #43315

Merged
sadpandajoe merged 1 commit into
masterfrom
fix-grainless-time-comparison-dst-alignment
Aug 20, 2026
Merged

sadpandajoe merged 1 commit into
masterfrom
fix-grainless-time-comparison-dst-alignment

Conversation

@sadpandajoe

Copy link
Copy Markdown
Member

SUMMARY

A post-merge review of #42054 (grain-less time-comparison alignment) found three concrete correctness bugs in the new alignment path in superset/models/helpers.py and superset/utils/date_parser.py. This PR fixes all three:

  1. DST-fold row duplication: the synthetic wall-clock join key used for grain-less alignment discarded UTC-offset/fold information, so a repeated local hour (the DST "fall back" transition) could collapse two distinct historical instants onto one join key. A left join then fanned a single main-series row out into duplicates, inflating totals. This now raises an actionable validation error identifying the ambiguous alignment instead of silently duplicating rows. Duplicates already present in the raw (pre-normalization) data, and duplicates from ordinary dimension multiplicity or month-end date clamping, are correctly left alone.
  2. Weekday/month-name offset anchors misclassified as constant deltas: is_constant_human_timedelta() probed only two same-date timestamps, so date-dependent anchors like friday or june passed as if they were constant deltas (like 1 month ago), producing misaligned or duplicated comparison rows. A third, differently-dated probe now correctly rejects these anchors while leaving genuine relative deltas (1 month ago, 52 weeks ago, 1 year ago, ...) unaffected.
  3. Custom SQL / string-backed temporal axes silently bypassing alignment: the alignment path required the temporal axis to already be datetime64 dtype, so a Custom SQL temporal expression resolving to a string/object-dtype column (e.g. on SQLite) silently fell back to an unaligned raw-key join — in the worst case, comparing a period against itself. Axes that are direct references to a physical dataset column with authoritative temporal metadata (is_dttm/type_generic) are now losslessly coerced and aligned; a value that fails to parse raises an actionable error instead of silently misaligning.

Scope and known follow-ups

  • Item 3 is scoped to direct references to a physical dataset column with declared temporal metadata, and to a single offset. Fully computed/derived Custom SQL temporal expressions (e.g. DATE_TRUNC(...)) are not covered by this PR and keep today's behavior; adding coverage would mean either a new AdhocColumn metadata field or forcing a per-request DB type probe, both real design decisions out of scope here.
  • Two related, independently-reachable correctness gaps found in the same review are explicitly out of scope for this PR and are recommended as follow-ups:
    • superset/semantic_layers/mapper.py's time-comparison path merges on raw (unaligned) temporal keys. This is a separate pipeline (not touched by fix(charts): render time comparison without a time grain #42054) gated behind the SEMANTIC_LAYERS feature flag, which defaults off.
    • processing_time_offsets() derives each additional offset's temporal filter from the previous offset's already-shifted filter rather than the original query, on the branch used by a non-datetime x-axis. This is pre-existing (predates fix(charts): render time comparison without a time grain #42054) and means a single offset on a string/Custom-SQL axis is now correctly aligned by this PR, but multiple offsets on such an axis are not yet.
  • Two narrow, non-blocking edge cases remain from independent review and are good starter follow-ups: the DST-vs-generic validation message can be imprecise when unrelated duplicate groups coexist in the same query (the query still correctly fails either way); and the out-of-range-date retry path uses strict parsing for a declared-but-non-exact datetime format, which can raise on a combination that the primary parse path would otherwise tolerate (fails loudly, not silently-wrong).

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Not applicable — this is a backend query-result correctness fix with no UI/rendering change. Behavior is demonstrated by the unit and integration tests below.

TESTING INSTRUCTIONS

  • pytest tests/unit_tests/common/test_time_shifts.py tests/unit_tests/utils/date_parser_tests.py
  • pytest tests/integration_tests/query_context_tests.py::test_time_offset_without_grain_aligns_direct_custom_sql_temporal_axis (requires the SQLite integration test database)

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

@codecov

codecov Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 37.71930% with 71 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.66%. Comparing base (34cd50c) to head (d818548).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
superset/models/helpers.py 37.16% 56 Missing and 15 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43315      +/-   ##
==========================================
- Coverage   66.67%   66.66%   -0.01%     
==========================================
  Files        2876     2876              
  Lines      164007   164106      +99     
  Branches    37834    37854      +20     
==========================================
+ Hits       109347   109405      +58     
- Misses      52514    52542      +28     
- Partials     2146     2159      +13     
Flag Coverage Δ
hive 38.07% <10.52%> (-0.04%) ⬇️
mysql 57.71% <19.29%> (-0.05%) ⬇️
postgres 57.74% <19.29%> (-0.05%) ⬇️
presto 40.00% <10.52%> (-0.04%) ⬇️
python 59.17% <37.71%> (-0.01%) ⬇️
sqlite 57.43% <37.71%> (+<0.01%) ⬆️
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
sadpandajoe marked this pull request as ready for review August 19, 2026 00:09
@dosubot dosubot Bot added change:backend Requires changing the backend explore:time Related to the time filters in Explore labels Aug 19, 2026
@bito-code-review

bito-code-review Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #f23f93

Actionable Suggestions - 0
Review Details
  • Files reviewed - 5 · Commit Range: d818548..d818548
    • superset/models/helpers.py
    • superset/utils/date_parser.py
    • tests/integration_tests/query_context_tests.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

@aminghadersohi aminghadersohi 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.

Review — APPROVE ✅

A careful, well-documented fix of three correctness bugs found in the post-merge review of #42054. I traced the call sites, adversarially attacked the classification heuristic in a REPL, ran the unit suite, and revert-tested. The fix is sound, narrowly scoped, and the test ratio is excellent. The scope section in the PR body is accurate — I verified each claim rather than taking it. Nothing blocking; one non-blocking note on the honestly-declared N>1 residual.

CI at review time: 105 SUCCESS / 23 SKIPPED / 3 NEUTRAL, zero failures (rollup incl. legacy status contexts).

Bug 2 heuristic held under adversarial attack (the headline check)

I reproduced is_constant_human_timedelta faithfully standalone (parsedatetime 2.6) and threw ~90 candidate anchors at the new three-probe set, including everything that shares June/2024 with the probes. No anchor survives as "constant." Every anchor that slipped through the old two-probe version is now correctly rejected:

phrase old (2 probes) new (3 probes)
june, january, march, september, in june constant ❌ anchor ✅
friday, monday, sunday, saturday constant ❌ anchor ✅
june 15, june 2024, june 18, end of year constant ❌ anchor ✅
this year, jan 1, q2, q3 anchor anchor ✅
1 year ago, 2 quarters, a year ago, 36 hours ago constant constant ✅ (correct)

The reason it's now complete for the fixed-anchor-vs-delta distinction: a fixed-target anchor gives shifts T − p_i, which can only be equal across probes if the probes are identical instants — they aren't. The third probe (different date and weekday) closes the same-date coincidence the two-probe version left open. I could not construct a survivor; the heuristic is robust.

Bug 1 (DST fold) — failure-mode inversion is the right trade, detection is narrow

Converting silent row-duplication into a hard error is correct here — a wrong (inflated) number is worse than a clear error. The detection is genuinely narrow: it fires only on introduced_duplicate_mask = normalized_duplicate_mask & ~raw_duplicate_mask, i.e. only when wall-clock normalization newly collapses two distinct raw keys for the same dimensions. I confirmed against the tests that:

  • ordinary dimension multiplicity and pre-existing raw duplicates are not flagged (preserves_raw_duplicate_offsets),
  • month-end DateOffset clamping on the main/left side is not flagged (allows_month_end_clamp_on_left, fans to [5, 5] with no error),
  • a genuine fold is still caught even when masked by a raw duplicate (rejects_dst_fold_with_raw_duplicate).

Both error messages are actionable ("Add a Time Grain or filter the source to one UTC offset" / "Standardize the source values or add a Time Grain"). Blast radius: an autumn fold crossing the repeated hour on a tz-aware grain-less hourly comparison now hard-fails instead of silently inflating — acceptable, and the message tells the user exactly what to change.

Bug 3 gating — new helpers cannot touch the ordinary query path

Confirmed. _get_temporal_physical_column_metadata is only invoked inside if offset_dfs: in processing_time_offsets, so a query with no time offsets never reaches it. _coerce_temporal_join_series / _has_multiple_utc_offsets / _shift_grainless_temporal_source are reachable only through _align_offset_without_time_grain, itself gated behind (offsets present) → (no time grain) → x_axis_is_temporal → non-datetime64 dtype. The +282 lines in this shared file are inert for every ordinary chart.

Scope claim on derived expressions also holds: the coercion keys off datasource.get_column(sqlExpression), so DATE_TRUNC(...) and other adhoc expressions resolve to None → non-temporal → the existing raw-key join, unchanged. Only direct physical-column references the dataset declares temporal enter the new path. And SEMANTIC_LAYERS defaults to False (config.py:704), so the mapper.py follow-up is a genuinely separate, off-by-default pipeline.

Non-blocking: the N>1 string-axis residual is real and unguarded

The PR body honestly declares this, and I confirmed it: query_object_clone is built once (copy.copy, helpers.py:2433) before the offset loop. In the datetime-axis branch each iteration re-derives from_dttm/to_dttm from the immutable outer_* bounds, so N>1 is fine. In the non-datetime (string) axis branch it reads flt.get("val") — the clone's own filter, mutated in the prior iteration — and shifts that, so a second offset compounds on the first's already-shifted range. This PR correctly aligns the single-offset string-axis case (net improvement) but does not add a guard for N>1, which stays silently wrong. This branch is pre-existing and untouched by the diff, so it's not a regression — but the false-confidence hazard is real: a user who sees single-offset comparisons fixed may reasonably trust the multi-offset case.

Not blocking (pre-existing, correctly scoped out), but I'd suggest a minimal guard as a fast follow: raise on len(time_offsets) > 1 when the axis takes the non-datetime string-shift branch, so the multi-offset case fails loudly rather than returning a wrong number — the same fail-closed principle this PR applies everywhere else. A # TODO at that branch pointing at the follow-up would also do.

Tests — RAN, not just inspected

superset_core is importable in this sandbox after adding it to PYTHONPATH, and the noted sqlglot.dialects.singlestore breakage did not bite.

  • tests/unit_tests/common/test_time_shifts.py: 51 passed.
  • Rule 26 (revert production, keep tests): date_parser_tests.py::test_is_constant_human_timedelta fails on assert not is_constant_human_timedelta("friday") (old code returns True) — the exact bug-2 regression, no wrong-reason pass. test_time_shifts.py fails to even collect on full revert because it imports the new _get_temporal_physical_column_metadata — legitimate coupling to new code.
  • Negative legs are present and prove the right things: preserves_categorical_string_axis (no over-eager coercion), numeric_temporal_without_format_uses_raw_key, preserves_raw_duplicate_offsets, allows_month_end_clamp_on_left, all_null_anchor_still_raises.

Nice work — the honest scope section and the three-probe reasoning in the docstring make this easy to trust.

@sadpandajoe
sadpandajoe merged commit 7441ce9 into master Aug 20, 2026
131 checks passed
@sadpandajoe
sadpandajoe deleted the fix-grainless-time-comparison-dst-alignment branch August 20, 2026 21:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:backend Requires changing the backend explore:time Related to the time filters in Explore size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants