Skip to content

fix(dataset): correct Hours Offset filter bounds and grain-truncation order - #43173

Merged
rusackas merged 3 commits into
masterfrom
fix-dataset-hours-offset-bound-truncation
Aug 24, 2026
Merged

rusackas merged 3 commits into
masterfrom
fix-dataset-hours-offset-bound-truncation

Conversation

@sadpandajoe

@sadpandajoe sadpandajoe commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

The dataset "Hours offset" setting had two independent bugs:

  1. Filter bounds could admit or drop a day. For a DATE-typed column, the filter
    bound was shifted by the raw Hours Offset before being rendered as a date-only
    literal. Any sub-24h offset could move which calendar day a bound truncated to --
    silently admitting an out-of-range day on one end while dropping the last
    requested day on the other. TIMESTAMP-typed columns were unaffected (they keep
    exact-hour precision).

  2. Displayed labels could disagree with the filter bounds. The offset was applied
    only in pandas, after the database had already truncated a temporal axis to its
    time grain using the raw (unshifted) value. A row near a grain boundary could
    bucket to the wrong day, so the label shown to the user could disagree with which
    rows the filter actually selected. Related: Setting a Dataset Hour Offset makes Day Interval group incorrectly.  #40871.

Fix:

  1. The offset is now quantized to whole days (truncating toward zero) before being
    applied to a DATE column's filter bounds, so a sub-day offset never moves the
    selected day window. This part is engine-agnostic.

  2. The offset is now applied in SQL, before grain truncation, at the
    axis-construction call sites -- gated behind a new apply_dataset_offset opt-in
    parameter so filter construction and other callers are unaffected. A new
    sql_shifted_temporal_labels signal tells dataframe normalization which columns
    were already shifted in SQL, so the offset isn't re-applied on top in pandas.

    Since the SQL-side shift depends on dialect-specific interval syntax, it's gated
    behind a new BaseEngineSpec.supports_temporal_column_shift capability flag
    (default False), enabled explicitly on the two engines it's verified against
    (PostgreSQL, SQLite). Engines that don't opt in keep the prior pandas-only
    behavior for bug 2 -- no new regression -- while unconditionally gaining the
    bound-quantization fix for bug 1, which is engine-agnostic. Extending bug 2's fix
    to other dialects (e.g. MSSQL) is a follow-up: each engine needs its own
    get_temporal_column_shift_expr override before it can opt in.

Out of scope for this change: grained temporal filters combined with a shifted
grained axis (the filter path is unchanged), DST handling, and the
extra.timezone override path.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A -- backend query-generation fix, no UI change. See Testing Instructions to
reproduce the corrected date-range/day-grouping behavior in Explore.

TESTING INSTRUCTIONS

Added tests/unit_tests/models/test_hours_offset_bound_truncation.py, covering both
bugs across an offset x grain x column-type matrix: DATE-column filter bounds across
offsets 0/+1/+24/+25/-1/-25 (with a TIMESTAMP control), grained physical and adhoc
BASE_AXIS temporal axes applying the offset exactly once before truncation, negative
sub-day DATE offsets that must not move the bucket, byte-identical SQL for the
explicitly out-of-scope grained-filter paths, and the new per-engine capability gate
(including its pandas-fallback path for unsupported engines).

To verify manually: create a Postgres or SQLite dataset with Hours offset set to a
non-zero sub-day value (e.g. 1), build an Explore chart with a Day time grain and a
specific date range on a DATE-typed column, and confirm the full requested range is
returned (no day dropped or added) with day labels matching the filter.

ADDITIONAL INFORMATION

  • Has associated issue: related to Setting a Dataset Hour Offset makes Day Interval group incorrectly.  #40871
  • 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

@netlify

netlify Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit 901cb3d
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a8742977f8b9d0008868627
😎 Deploy Preview https://deploy-preview-43173--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.

@codecov

codecov Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.33333% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.73%. Comparing base (148ffaf) to head (901cb3d).

Files with missing lines Patch % Lines
superset/connectors/sqla/models.py 47.36% 7 Missing and 3 partials ⚠️
superset/models/helpers.py 85.71% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #43173      +/-   ##
==========================================
+ Coverage   57.32%   66.73%   +9.40%     
==========================================
  Files        2876     2876              
  Lines      164228   164263      +35     
  Branches    37891    37896       +5     
==========================================
+ Hits        94151   109620   +15469     
+ Misses      69184    52480   -16704     
- Partials      893     2163    +1270     
Flag Coverage Δ
hive 38.10% <31.11%> (-0.01%) ⬇️
mysql 57.76% <53.33%> (?)
postgres 57.80% <68.88%> (?)
presto 40.04% <40.00%> (-0.01%) ⬇️
python 59.19% <73.33%> (+19.09%) ⬆️
sqlite 57.44% <66.66%> (?)
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 18, 2026 05:54
@dosubot dosubot Bot added change:backend Requires changing the backend data:dataset Related to dataset configurations labels Aug 18, 2026
@bito-code-review

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

Copy link
Copy Markdown
Contributor

Code Review Agent Run #6831cb

Actionable Suggestions - 0
Additional Suggestions - 2
  • tests/unit_tests/models/test_hours_offset_bound_truncation.py - 1
    • Redundant inline import of QueryObject · Line 674-674
      Move import to module-level (line 44 already imports `QueryObject`). Inline imports are only justified for circular dependency resolution with documentation — this import is not circular. All 15 other test functions in this file use the module-level import, making this pattern inconsistent.
  • superset/db_engine_specs/base.py - 1
    • Incomplete method docstring · Line 1209-1219
      The docstring for `get_temporal_column_shift_expr` lacks parameter and return documentation. Other methods in this file like `get_timestamp_expr` include @PARAM and @return blocks. Add `:param col:`, `:param offset_hours:`, and `:return:` documentation for consistency and clarity.
Review Details
  • Files reviewed - 8 · Commit Range: 14c6b42..7357d03
    • superset/connectors/sqla/models.py
    • superset/db_engine_specs/base.py
    • superset/db_engine_specs/postgres.py
    • superset/db_engine_specs/sqlite.py
    • superset/models/helpers.py
    • superset/models/sql_lab.py
    • tests/unit_tests/common/test_query_context_processor.py
    • tests/unit_tests/models/test_hours_offset_bound_truncation.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
sadpandajoe removed the request for review from rusackas August 20, 2026 17:33
… order

The dataset "Hours offset" setting had two independent bugs:

1. Filter bounds shifted a DATE-typed column's literal bound by the raw
   offset before rendering it as a date-only value. A sub-24h offset could
   move which calendar day a bound truncated to, silently admitting an
   out-of-range day on one end and dropping the last requested day on the
   other. The offset is now quantized to whole days (truncating toward
   zero) before it's applied to a DATE column's bounds, so a sub-day offset
   never moves the selected day window.

2. The offset was applied only in pandas, after the database had already
   truncated a temporal axis to its time grain using the raw (unshifted)
   value. A row near a grain boundary could bucket to the wrong day, and
   the displayed label (computed via a different path) could disagree with
   the filter bounds. The offset is now applied in SQL, before grain
   truncation, at the axis-construction call sites -- gated behind a new
   `apply_dataset_offset` opt-in so filter construction and other unrelated
   callers are unaffected. A new `sql_shifted_temporal_labels` signal tells
   dataframe normalization which columns were already shifted in SQL so the
   legacy pandas-side offset isn't re-applied on top.

Since the SQL-side shift depends on dialect-specific interval syntax, it's
gated behind a new `BaseEngineSpec.supports_temporal_column_shift` capability
flag (default False), enabled explicitly on the two engines it's been
verified against (Postgres, SQLite). Engines that don't opt in keep the
prior pandas-only behavior for the grain-truncation-order bug -- no new
regression -- while gaining the DATE-bound quantization fix unconditionally
(that part is engine-agnostic).
Covers both defects across an offset x grain x column-type matrix:

- DATE-column filter bounds stay on the requested whole-day window for
  offsets 0/+1/+24/+25/-1/-25 (the bug admitted/dropped a day for any
  sub-24h offset); TIMESTAMP columns keep exact-hour bounds as a control.
- Grained physical and adhoc BASE_AXIS temporal axes apply the offset
  exactly once, before grain truncation, matching the exact SQL literal
  and the resulting bucket for each combination -- including the case
  that previously applied the offset zero times for an ungrained axis,
  and negative sub-day DATE offsets that must not move the bucket.
  Physical and adhoc filter SQL are asserted byte-identical to pre-fix
  output for the explicitly out-of-scope grained-filter paths.
- The new per-engine capability gate correctly excludes every engine
  that doesn't support the SQL-side shift (falls back to the pre-fix
  pandas-only offset, verified against the real code path with no
  shift SQL emitted) and correctly includes Postgres/SQLite (compiled
  SQL asserted exactly, across signed and >=24h offsets).
…t param

normalize_df now accepts an optional third sql_shifted_temporal_labels
parameter (passed positionally from processing_time_offsets). Three
pre-existing mocks in this file stubbed normalize_df with a fixed two-argument
lambda, which broke when the call site started passing a third positional
argument.
@sadpandajoe
sadpandajoe force-pushed the fix-dataset-hours-offset-bound-truncation branch from 7357d03 to 901cb3d Compare August 20, 2026 18:08

@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 #6456e6

Actionable Suggestions - 1
  • tests/unit_tests/models/test_hours_offset_bound_truncation.py - 1
Additional Suggestions - 1
  • superset/models/sql_lab.py - 1
    • Dead parameters in Query override · Line 440-441
      The two new parameters `apply_dataset_offset` and `sql_shifted_temporal_labels` are declared on line 440–441 but are never read in this method body — the `is_dttm and has_timegrain` block calls `get_timestamp_expr(col, pdf, time_grain)` with no shift logic and `grep -c _shift_temporal` returns 0 hits. These are dead parameters that will never be exercised unless `Query.adhoc_column_to_sqla` also delegates to or re-implements the temporal-shift logic found in `TableColumn.adhoc_column_to_sqla` at models.py line 2117.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • tests/unit_tests/models/test_hours_offset_bound_truncation.py - 1
Review Details
  • Files reviewed - 8 · Commit Range: e023dbf..901cb3d
    • superset/connectors/sqla/models.py
    • superset/db_engine_specs/base.py
    • superset/db_engine_specs/postgres.py
    • superset/db_engine_specs/sqlite.py
    • superset/models/helpers.py
    • superset/models/sql_lab.py
    • tests/unit_tests/common/test_query_context_processor.py
    • tests/unit_tests/models/test_hours_offset_bound_truncation.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

offset=1,
column_type="TIMESTAMP",
rows=["2026-08-01 23:30:00", "2026-08-02 10:00:00"],
)

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.

Consolidate duplicate test setup code

Found duplicated test code (21 lines) in tests/unit_tests/models/test_hours_offset_bound_truncation.py at lines 384-404 and 419-439. The duplicate includes AdhocColumn setup, QueryObject creation, and get_query_result assertions. Consider extracting this into a test fixture or helper function to reduce duplication.

Code Review Run #6456e6


Should Bito avoid suggestions like this for future reviews? (Manage Rules)

  • Yes, avoid them

@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: correct fix, no blocking issues, one outstanding bot style nit.

I traced the two headline risks (non-opted-in engines, and raw interpolation of offset_hours) and both resolve in the PR's favour. This is a focused, well-tested temporal-correctness fix in the same family as #43315. Ran the new test suite (52 pass; 40 fail on a Rule‑26 revert of the production hunks, confirming they pin the behaviour). Not approving solely because of the unresolved bot thread below — see the note at the end.


1. Behaviour on the ~40 engines that did not opt in — NOT a regression (not blocking).
supports_temporal_column_shift defaults False; only postgres and sqlite set it True. On every other engine the offset is not silently dropped: sql_shifted_temporal_labels stays empty, so normalize_df keeps applying offset=self.offset in pandas post-processing — byte-for-byte the pre-PR path (master applied offset=self.offset unconditionally in _offset_only_dttm_cols/normalize_df). The two opted-in engines now shift in SQL before truncation and set offset=0 for those labels to avoid a double shift. So this is progress with a documented gap (grain-correct bucketing lands on pg/sqlite; other engines retain the pre-existing post-hoc labelling), not a regression. The fail-closed posture from #43315/#43031/#43348 doesn't apply here because nothing is dropped — but a one-line note in the capability docstring naming which engines get grain-correct offset would help future readers.

2. Raw f-string interpolation of offset_hours — NOT injectable (not blocking).
Traced every path into get_temporal_column_shift_expr. The value originates only from SqlaTable.offset, which is Column(Integer, default=0) at the model layer and validated as fields.Integer on both the write path (DatasetPutSchema, schemas.py:198) and the import path (schemas.py:388). Between the source and the base f-string it passes through get_effective_hours_offset, which returns int(...)*24 or the int unchanged. A string bearing a ' (needed to break out of INTERVAL '…' HOUR) cannot survive marshmallow Integer, so a dataset editor cannot inject. The asymmetry — sqlite forces f"{offset_hours:+d}" while the base builds '{offset_hours}' unguarded — is a robustness nit, not a vulnerability; adding a :+d/int() assertion to the base for defence-in-depth would be a nice, cheap parity fix.

3. Truncation order — correct and consistent (not blocking).
Both TableColumn.get_timestamp_expression and adhoc_column_to_sqla now shift first, then wrap in get_timestamp_expr → TRUNC(col + offset). The WHERE bounds in helpers.py subtract the effective offset from the literals, so col ∈ [start−off, end−off] ⇔ col+off ∈ [start, end] — SELECT and WHERE agree, which is exactly what keeps boundary rows from going missing. test_hours_offset_is_applied_before_time_grain_truncation proves it end-to-end against a live sqlite engine with a 23:30 boundary row.

4. models/sql_lab.py (+2). Purely signature parity: Query.adhoc_column_to_sqla accepts the two new kwargs so the shared get_sqla_query (which now passes apply_dataset_offset=True) doesn't raise TypeError on a SQL Lab datasource. The body ignores them — SQL Lab has no dataset offset, so no behaviour change. Coherent.

5. Tests. Both halves are pinned (bounds and truncation order) with real negative legs: test_engine_without_temporal_shift_capability_uses_pandas_fallback, test_adhoc_axis_without_temporal_shift_capability_uses_pandas_fallback, test_negative_subday_date_offset_does_not_move_grained_bucket, and ..._applied_exactly_once. The DATE-vs-TIMESTAMP matrix and the +1 hours / INTERVAL '1' HOUR compilation checks are a good touch.


On the open thread (test_hours_offset_bound_truncation.py:384, consolidate duplicate setup into a fixture): I'd leave it as-is. The shared dataset setup is already factored into _sqlite_dataset; what remains inline is the base_axis AdhocColumn and QueryObject literal, and the two tests deliberately diverge (one asserts the SQL shift + {"ts"} shifted-labels, the other patches supports_temporal_column_shift = False and asserts the pandas fallback + empty labels + no +1 hours). Keeping each scenario readable top-to-bottom is worth more than de-duplicating 16 lines here; a fixture would couple two intentionally-opposite cases. A reviewer can resolve this thread as "won't fix, deliberate for readability." Once it's resolved this is good to approve.

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

Reviewed the diff, tests, and threads independently. Traced the injection concern raised in review (offset_hours is a validated Integer column, not raw user input reaching the f-string) and the truncation-order fix (shift-before-truncate on postgres/sqlite, unchanged pandas fallback elsewhere) — both check out. Test coverage is thorough (702 lines, full offset x grain x column-type matrix). The one open bot thread (consolidate duplicate test setup) is a style nit on two deliberately-divergent test scenarios — leaving as won't-fix per the in-thread reasoning. LGTM.

@rusackas
rusackas merged commit 31f06c0 into master Aug 24, 2026
73 checks passed
@rusackas
rusackas deleted the fix-dataset-hours-offset-bound-truncation branch August 24, 2026 18:47
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 data:dataset Related to dataset configurations size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants