Skip to content

Commit 5e4f6b6

Browse files
sadpandajoeclaude
andcommitted
fix(charts): align grain-less time offsets on wall clock
Shifting a timezone-aware series with DateOffset raised out of pandas when the shift landed on a local hour that DST skips or repeats (NonExistentTimeError / AmbiguousTimeError), and the free-form parser branch added its delta as absolute time, silently drifting the wall clock by an hour across a DST boundary. Drop the timezone on both sides of the join and align on wall clock, which is what the offset query's own time range was shifted by, so its rows carry the source wall clock. Free-form offsets are now required to denote a constant shift. Phrases parsedatetime resolves to a fixed point ("yesterday", "last month") anchor every source time within a day onto one 09:00 timestamp, so applied per row they move each row by a different amount and collapse distinct timestamps onto a single join key. They fail with the existing missing-grain error instead. Also express an "inherit" offset in seconds rather than days: the timedelta.days truncation compared a sub-day range against itself ("0 days ago") and overlapped ranges that were not a whole number of days. Whole-day ranges resolve to the same instant as before. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 453965c commit 5e4f6b6

5 files changed

Lines changed: 292 additions & 44 deletions

File tree

‎superset/models/helpers.py‎

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,7 @@
140140
)
141141
from superset.utils.date_parser import (
142142
get_past_or_future,
143+
is_constant_human_timedelta,
143144
is_parseable_human_timedelta,
144145
normalize_time_delta,
145146
TimeDeltaAmbiguousError,
@@ -173,6 +174,16 @@ class ValidationResultDict(TypedDict):
173174
R_SUFFIX = "__right_suffix"
174175

175176

177+
def _as_wall_clock(series: pd.Series) -> pd.Series:
178+
"""
179+
Return a datetime series as local wall-clock readings, dropping any
180+
timezone. Series of other dtypes are returned unchanged.
181+
"""
182+
if isinstance(series.dtype, pd.DatetimeTZDtype):
183+
return series.dt.tz_localize(None)
184+
return series
185+
186+
176187
class CachedTimeOffset(TypedDict):
177188
"""Result type for time offset processing"""
178189

@@ -2190,8 +2201,15 @@ def get_offset_custom_or_inherit(
21902201
:returns: The time offset.
21912202
"""
21922203
if offset == "inherit":
2193-
# return the difference in days between the from and the to dttm formatted as a string with the " days ago" suffix # noqa: E501
2194-
return f"{(outer_to_dttm - outer_from_dttm).days} days ago"
2204+
# Shift back by the full length of the range, so the comparison
2205+
# covers the period immediately preceding it. The duration is
2206+
# expressed in seconds rather than days because ``timedelta.days``
2207+
# truncates: a 12-hour range would yield "0 days ago" and compare
2208+
# the range against itself, and a 36-hour range would shift by a
2209+
# single day and overlap it. Whole-day ranges resolve to the same
2210+
# instant either way.
2211+
duration = outer_to_dttm - outer_from_dttm
2212+
return f"{int(duration.total_seconds())} seconds ago"
21952213
if self.is_valid_date(offset):
21962214
# return the offset as the difference in days between the outer from dttm and the offset date (which is a YYYY-MM-DD string) formatted as a string with the " days ago" suffix # noqa: E501
21972215
offset_date = datetime.strptime(offset, "%Y-%m-%d")
@@ -2353,8 +2371,17 @@ def _align_offset_without_time_grain(
23532371
offsets). Timestamps without an exact counterpart in the offset series
23542372
produce nulls, mirroring the grain-based join, and null timestamps in
23552373
the two series join to each other (both stringify to "NaT"). When
2356-
there is no temporal join key, or the offset cannot be interpreted as
2357-
a time delta, the original join keys are used as-is.
2374+
there is no temporal join key the original join keys are used as-is.
2375+
2376+
The shift is computed on wall-clock time, with any timezone dropped for
2377+
the duration of the alignment. The offset query's own time range was
2378+
shifted the same way -- ``get_past_or_future`` reads naive timestamps
2379+
-- so the rows it returns carry the source wall clock, and matching on
2380+
it is what aligns the two series. Re-localizing the result would only
2381+
reintroduce the DST edge cases that wall-clock arithmetic sidesteps:
2382+
shifting onto a skipped or repeated local hour raises out of pandas.
2383+
Both sides are normalized identically, so the two readings of a
2384+
repeated hour still align with each other.
23582385
23592386
Month, quarter, and year offsets shift via ``DateOffset``, which clamps
23602387
to a valid calendar day (e.g. Mar 29, 30, and 31 all shift back one
@@ -2379,6 +2406,8 @@ def _align_offset_without_time_grain(
23792406
if not temporal_join_key:
23802407
return offset_df, join_keys
23812408

2409+
source = _as_wall_clock(df[temporal_join_key])
2410+
23822411
try:
23832412
delta: DateOffset | None = DateOffset(**normalize_time_delta(offset))
23842413
except (ValueError, TimeDeltaAmbiguousError):
@@ -2388,41 +2417,38 @@ def _align_offset_without_time_grain(
23882417
if delta is not None:
23892418
# DateOffset addition is vectorized over the datetime column; NaT
23902419
# rows shift to NaT (they join to the offset series' NaT rows).
2391-
shifted = df[temporal_join_key] + delta
2420+
shifted = source + delta
23922421
else:
23932422
# Free-form offsets (e.g. "one year ago") don't match the
23942423
# normalize_time_delta grammar; shift with the same parser that
2395-
# shifted the offset query's time range. parsedatetime only
2396-
# handles naive timestamps at second resolution, so compute each
2397-
# row's delta from a truncated copy and apply it to the original
2398-
# value, preserving timezone and sub-second precision.
2399-
def truncate(value: datetime) -> datetime:
2400-
timestamp = pd.Timestamp(value)
2401-
if timestamp.tzinfo is not None:
2402-
timestamp = timestamp.tz_localize(None)
2403-
return timestamp.floor("s").to_pydatetime()
2404-
2405-
if not is_parseable_human_timedelta(offset):
2406-
logger.warning(
2407-
"Cannot interpret time offset %r without a time grain; "
2408-
"the time comparison may be incorrect.",
2409-
offset,
2424+
# shifted the offset query's time range. parsedatetime resolves
2425+
# second resolution only, so compute each row's delta from a
2426+
# truncated copy and apply it to the original value, preserving
2427+
# sub-second precision.
2428+
if not is_constant_human_timedelta(offset):
2429+
# Anchors such as "yesterday" resolve every source time within
2430+
# a day onto one timestamp rather than shifting each by a
2431+
# fixed amount, so they cannot align two series row by row:
2432+
# distinct timestamps would collapse onto a single join key.
2433+
# A time grain gives the join a truncated column to match on
2434+
# instead of a shifted one.
2435+
raise QueryObjectValidationError(
2436+
_("Time Grain must be specified when using Time Comparison.")
24102437
)
2411-
return offset_df, join_keys
24122438

2413-
def shift(value: datetime) -> datetime:
2439+
def shift(value: pd.Timestamp) -> pd.Timestamp:
24142440
if pd.isna(value):
24152441
return value
2416-
truncated = truncate(value)
2442+
truncated = value.floor("s").to_pydatetime()
24172443
return value + (get_past_or_future(offset, truncated) - truncated)
24182444

2419-
shifted = df[temporal_join_key].map(shift)
2445+
shifted = source.map(shift)
24202446

24212447
# Join on string values so that mismatched key dtypes (e.g. an empty
24222448
# offset series materializes its join keys as NaN floats) cannot break
24232449
# the merge.
24242450
df[column_name] = shifted.map(str)
2425-
offset_df[column_name] = offset_df[temporal_join_key].map(str)
2451+
offset_df[column_name] = _as_wall_clock(offset_df[temporal_join_key]).map(str)
24262452

24272453
remaining_keys = [key for key in join_keys if key != temporal_join_key]
24282454
return offset_df, [column_name, *remaining_keys]

‎superset/utils/date_parser.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@
6060

6161
logger = logging.getLogger(__name__)
6262

63+
# Source times used by ``is_constant_human_timedelta`` to tell a delta from an
64+
# anchor. They share a date -- mid-month and mid-year, away from any month or
65+
# year boundary a shift could clamp against -- and differ only in the hour, so
66+
# that the sole thing the comparison can detect is sensitivity to time of day.
67+
# Neither hour is parsedatetime's 09:00 default, so an anchor cannot coincide
68+
# with a probe and masquerade as a zero shift.
69+
_SHIFT_PROBE_TIMES: tuple[datetime, datetime] = (
70+
datetime(2024, 6, 15, 3, 0, 0),
71+
datetime(2024, 6, 15, 21, 0, 0),
72+
)
73+
6374
# Mapping of ordinal words to their numeric values for date expressions
6475
ORDINAL_MAP: dict[str, int] = {
6576
"first": 1,
@@ -158,6 +169,31 @@ def is_parseable_human_timedelta(human_readable: str | None) -> bool:
158169
return cal.parse(_rewrite_quarters_as_months(human_readable))[1] != 0
159170

160171

172+
def is_constant_human_timedelta(human_readable: str | None) -> bool:
173+
"""
174+
Returns whether the phrase shifts every source time by the same amount.
175+
176+
``is_parseable_human_timedelta`` accepts anchors such as "yesterday" and
177+
"last month" alongside true deltas such as "1 year ago", but the two
178+
behave differently when applied per row: an anchor resolves to a single
179+
timestamp (parsedatetime defaults to 09:00) no matter where the source
180+
time sits within the day, so it shifts each row by a different amount.
181+
182+
Probing two source times within the same day separates the two. A delta
183+
shifts both probes equally; an anchor maps both onto one timestamp, which
184+
-- the probes being distinct -- necessarily yields differing shifts. Both
185+
probes share a date, so calendar irregularities such as leap years and
186+
month lengths apply to them identically and cannot skew the comparison.
187+
"""
188+
if not is_parseable_human_timedelta(human_readable):
189+
return False
190+
deltas = {
191+
get_past_or_future(human_readable, probe) - probe
192+
for probe in _SHIFT_PROBE_TIMES
193+
}
194+
return len(deltas) == 1
195+
196+
161197
def parse_human_timedelta(
162198
human_readable: str | None,
163199
source_time: datetime | None = None,

‎tests/unit_tests/common/test_query_context_processor.py‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717

18+
from datetime import datetime, timedelta
1819
from typing import Any
1920
from unittest.mock import MagicMock, patch
2021

@@ -26,6 +27,7 @@
2627
from superset.common.db_query_status import QueryStatus
2728
from superset.common.query_context_processor import QueryContextProcessor
2829
from superset.utils.core import GenericDataType
30+
from superset.utils.date_parser import get_past_or_future
2931

3032

3133
@pytest.fixture
@@ -389,8 +391,45 @@ def test_get_offset_custom_or_inherit_with_inherit(processor):
389391
"inherit", from_dttm, to_dttm
390392
)
391393

392-
# Should return the difference in days
393-
assert result == "9 days ago"
394+
# Should shift back by the length of the range: 9 days, in seconds
395+
assert result == "777600 seconds ago"
396+
397+
398+
@pytest.mark.parametrize(
399+
"hours",
400+
[
401+
# Sub-day ranges truncated to "0 days ago" and compared the range
402+
# against itself.
403+
1,
404+
12,
405+
# Ranges that are not a whole number of days truncated downwards and
406+
# overlapped the range they were compared against.
407+
36,
408+
# Whole-day ranges were already correct and must stay so.
409+
24,
410+
48,
411+
],
412+
)
413+
def test_get_offset_custom_or_inherit_shifts_by_full_range(
414+
processor, hours: int
415+
) -> None:
416+
"""
417+
'inherit' compares a range against the period immediately preceding it,
418+
for any range length. The offset must not be truncated to whole days: it
419+
has to reproduce the range's exact duration, so that the comparison window
420+
neither overlaps the range nor leaves a gap before it.
421+
"""
422+
from_dttm = datetime(2024, 3, 10, 6, 0)
423+
to_dttm = from_dttm + timedelta(hours=hours)
424+
425+
offset = processor._qc_datasource.get_offset_custom_or_inherit(
426+
"inherit", from_dttm, to_dttm
427+
)
428+
429+
shifted_from = get_past_or_future(offset, from_dttm)
430+
shifted_to = get_past_or_future(offset, to_dttm)
431+
assert shifted_to == from_dttm
432+
assert shifted_to - shifted_from == to_dttm - from_dttm
394433

395434

396435
def test_get_offset_custom_or_inherit_with_date(processor):

0 commit comments

Comments
 (0)