Skip to content

feat(timeshift): Add support for date range timeshifts - #34375

Merged
msyavuz merged 20 commits into
masterfrom
msyavuz/fix/timeshift-overrides
Aug 5, 2025
Merged

msyavuz merged 20 commits into
masterfrom
msyavuz/fix/timeshift-overrides

Conversation

@msyavuz

@msyavuz msyavuz commented Jul 28, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR adds support for date range timeshifts in addition to the existing relative time offsets (like "1 year ago"). Users can now specify explicit date ranges in the timeshift field (e.g., "2015-01-03 : 2015-01-04") to compare data from specific time periods.

Here's a comparison table highlighting the new flag:

Aspect Relative Timeshift Date Range Timeshift
Offset Format '1 year ago', '6 months ago', 'inherit' '2021-01-01 : 2021-12-31'
Time Range Calculation Shifts original date range by offset amount Uses exact specified date range
Query Generation WHERE ds >= '2021-01-01' AND ds < '2022-01-01' WHERE ds >= '2020-06-01' AND ds < '2021-06-01'
Filter Handling Existing temporal filters are shifted by offset Temporal filters replaced with offset range
Inner Bounds Sets inner_from_dttm and inner_to_dttm Clears inner bounds (None)
Feature Flag None required (existing functionality) DATE_RANGE_TIMESHIFTS_ENABLED=True
Join Strategy Uses temporal join columns with time grain Aggregates metrics, uses cross-join
Column Names SUM(value)__1 year ago SUM(value)__2021-01-01 : 2021-12-31
Use Case Compare to same period in the past Compare to specific historical period
Example Result 2022 data vs 2021 data (same months) 2022 data vs specific 2020 period

Key Changes

1. Enhanced Time Offset Processing (processing_time_offsets)

  • Added is_valid_date_range() method to detect date range format timeshifts
  • Separate handling logic for date range vs relative offsets
  • Fixed temporal filter conflicts that were causing empty results
  • Proper management of inner_from_dttm/inner_to_dttm bounds for different offset types

2. Improved Join Logic (join_offset_dfs)

  • Dynamic temporal column detection using query granularity and datetime series detection
  • Special aggregation logic for date range offsets to prevent duplicate rows
  • Preserved original behavior for relative time offsets
  • Cross-join with aggregation when no non-temporal dimensions exist

3. Updated Time Delta Normalization (normalize_time_delta)

  • Enhanced to handle date range formats gracefully
  • Maintains backward compatibility with existing relative time expressions

Usage Examples

Relative Offsets (existing functionality):

Time Range: 2024-01-01 to 2024-01-31
Timeshift: "1 year ago"
→ Compares Jan 2024 data with Jan 2023 data

Date Range Offsets (new functionality):

Time Range: 2024-01-01 to 2024-01-31  
Timeshift: "2023-06-15 : 2023-07-15"
→ Compares Jan 2024 data with mid-June to mid-July 2023 data

Testing

  • ✅ Existing relative timeshift functionality preserved
  • ✅ New date range timeshift functionality working
  • ✅ Proper SQL query generation with correct temporal filters
  • ✅ Data aggregation and joining working correctly
  • ✅ No conflicts between different offset types

Backward Compatibility

This change is fully backward compatible. All existing timeshift functionality continues to work exactly as before. The new date range format is additive and doesn't affect existing usage patterns.

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

@dosubot dosubot Bot added the viz:charts:table Related to the Table chart label Jul 28, 2025

@korbit-ai korbit-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I've completed my review and didn't find any issues.

Files scanned ​
File Path Reviewed
superset/common/query_context_processor.py ✅

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

@Antonio-RiveroMartnez

Antonio-RiveroMartnez commented Jul 29, 2025 •

Copy link
Copy Markdown
Member

I like the idea behind this implementation but probably better to have this behind a feature flag? also, adding some tests would be great so we ensure nothing is breaking

@msyavuz
msyavuz force-pushed the msyavuz/fix/timeshift-overrides branch from 8aa9f3c to 3bfb6da Compare July 30, 2025 19:21
@msyavuz msyavuz changed the title feat(timeshift): Add support for date range timeshifts in table charts feat(timeshift): Add support for date range timeshifts in supporting charts Jul 31, 2025
@msyavuz msyavuz changed the title feat(timeshift): Add support for date range timeshifts in supporting charts feat(timeshift): Add support for date range timeshifts Jul 31, 2025
@msyavuz
msyavuz marked this pull request as draft July 31, 2025 11:02
@msyavuz
msyavuz marked this pull request as ready for review July 31, 2025 13:23
@dosubot dosubot Bot added the explore:time Related to the time filters in Explore label Jul 31, 2025

@korbit-ai korbit-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Documentation Incomplete Time Offsets Validation Docstring ▹ view 🧠 Incorrect
Functionality Missing Date Range Order Validation ▹ view 🧠 Incorrect
Documentation Vague Cleanup Logic Documentation ▹ view 🧠 Not in scope
Functionality Conflicting Time Range Bounds ▹ view 🧠 Not in standard
Files scanned ​
File Path Reviewed
superset/common/query_object.py ✅
superset/common/query_context_processor.py ✅
superset/config.py ✅

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

Comment on lines +306 to +317
def _validate_time_offsets(self) -> None:
"""Validate time_offsets configuration"""
if not self.time_offsets:
return

for offset in self.time_offsets:
# Check if this is a date range offset (YYYY-MM-DD : YYYY-MM-DD format)
if self._is_valid_date_range(offset):
if not feature_flag_manager.is_feature_enabled(
"DATE_RANGE_TIMESHIFTS_ENABLED"
):
raise QueryObjectValidationError(

This comment was marked as resolved.

Comment on lines +328 to +330
start_date, end_date = date_range.split(":")
datetime.strptime(start_date.strip(), "%Y-%m-%d")
datetime.strptime(end_date.strip(), "%Y-%m-%d")

This comment was marked as resolved.

Comment on lines +842 to +849
def _apply_cleanup_logic(
self,
df: pd.DataFrame,
offset: str,
time_grain: str | None,
join_keys: list[str],
is_date_range_offset: bool,
) -> pd.DataFrame:

This comment was marked as resolved.

Comment on lines +552 to +553
query_object_clone.inner_from_dttm = query_object_clone.from_dttm
query_object_clone.inner_to_dttm = query_object_clone.to_dttm

This comment was marked as resolved.

Comment on lines +788 to +792
for offset_key, offset_df in offset_dfs.items():
logger.info(f"Offset '{offset_key}' DataFrame shape: {offset_df.shape}")
logger.info(
f"Offset '{offset_key}' DataFrame:\n{offset_df.to_string()}"
)

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.

Let's remove all these logs for readability

offset, outer_to_dttm
)

# For relative offsets, keep the original behavior

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.

Not quite sure why altering the existing behavior, if we go this path then the FF doesn't guarantee we're not affecting the existing API

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I am not really altering the existing behaviour just moving it into the else block for feature flag.

)

else:
# RELATIVE OFFSETS: Original logic but fixed

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.

Wondering if the fix should live on a different PR (and probably be shipped before this one?) otherwise your PR is not "just adding feature behind a FF"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same here, I am not really altering the existing behaviour just moving it into the else block for feature flag.

@michael-s-molina

Copy link
Copy Markdown
Member

@msyavuz Could you add some screenshots demonstrating the new filters?

@msyavuz

msyavuz commented Aug 2, 2025 •

Copy link
Copy Markdown
Member Author

Hey, this is a multi part implementation, frontend might be contributed later

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

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

lgtm -- comments addressed and all changes behind a feature flag so no unexpected changes to existing APIs. Thanks for this

@msyavuz
msyavuz merged commit 761daec into master Aug 5, 2025
@msyavuz
msyavuz deleted the msyavuz/fix/timeshift-overrides branch August 5, 2025 16:31
LisaHusband pushed a commit to LisaHusband/superset that referenced this pull request Aug 17, 2025
@github-actions github-actions Bot added 🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels 🚢 6.0.0 First shipped in 6.0.0 labels Dec 18, 2025
qfcwell pushed a commit to qfcwell/superset that referenced this pull request May 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels explore:time Related to the time filters in Explore size/XL viz:charts:table Related to the Table chart 🚢 6.0.0 First shipped in 6.0.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants