Repository navigation
fix(dataset): correct Hours Offset filter bounds and grain-truncation order - #43173
Conversation
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Code Review Agent Run #6831cbActionable Suggestions - 0Additional Suggestions - 2
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
… 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.
7357d03 to
901cb3d
Compare
There was a problem hiding this comment.
Code Review Agent Run #6456e6
Actionable Suggestions - 1
-
tests/unit_tests/models/test_hours_offset_bound_truncation.py - 1
- Consolidate duplicate test setup code · Line 384-384
Additional Suggestions - 1
-
superset/models/sql_lab.py - 1
-
Dead parameters in Query override · Line 440-441The 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
- Unused imports should be removed · Line 45-47
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
| offset=1, | ||
| column_type="TIMESTAMP", | ||
| rows=["2026-08-01 23:30:00", "2026-08-02 10:00:00"], | ||
| ) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
SUMMARY
The dataset "Hours offset" setting had two independent bugs:
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).
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:
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.
The offset is now applied in SQL, before grain truncation, at the
axis-construction call sites -- gated behind a new
apply_dataset_offsetopt-inparameter so filter construction and other callers are unaffected. A new
sql_shifted_temporal_labelssignal tells dataframe normalization which columnswere 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_shiftcapability 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_exproverride 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.timezoneoverride 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 bothbugs 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 offsetset to anon-zero sub-day value (e.g.
1), build an Explore chart with a Day time grain and aspecific 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