Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tracing): support minute/second window shorthand in spans API (#66382)

Jon McCallume45e3790030b
diff --git a/products/tracing/backend/presentation/date_window.py b/products/tracing/backend/presentation/date_window.py
new file mode 100644
index 000000000000..4d731af56c63
--- /dev/null
+++ b/products/tracing/backend/presentation/date_window.py
@@ -0,0 +1,93 @@
+"""Relative time-window parsing for the tracing (APM) API.
+
+Tracing is a short-window product — trace retention is measured in hours and days,
+not months or years — so the relative-window shorthand it accepts is intentionally
+different from PostHog's global ``relative_date_parse`` grammar in one place: here a
+bare lowercase ``m`` means **minutes**, whereas the global parser reads ``m`` as
+months (and only an uppercase ``M`` as minutes). ``-30m`` meaning "30 minutes ago"
+is what an APM user expects, and anything coarser than a few weeks is meaningless
+for span data.
+
+We translate the friendly tracing shorthand onto the global parser's token
+vocabulary so the rest of the date-range machinery is unchanged, pass ISO 8601
+timestamps and the broader global relative grammar (``-1dStart``, ``-3q`` …) through
+untouched so nothing that worked before regresses, and reject everything else with a
+``ValidationError`` (HTTP 400) instead of silently falling back to "now" — which
+previously turned a typo'd window into stale data with no error.
+"""
+
+import re
+
+from dateutil import parser as dateutil_parser
+from rest_framework import serializers
+
+# Friendly tracing window: an integer with a single short unit, e.g. "-30m", "90s", "-2w".
+# Case-insensitive; the leading minus is optional because windows are always in the past.
+_TRACING_WINDOW_RE = re.compile(r"^-?(?P<number>\d+)(?P<unit>[smhdw])$", re.IGNORECASE)
+
+# Map the friendly unit onto the token that posthog.utils.relative_date_parse understands.
+# The deliberate part is "m" -> "M" (minutes): the global parser reads lowercase "m" as months.
+_UNIT_TO_RELATIVE_TOKEN = {"s": "s", "m": "M", "h": "h", "d": "d", "w": "w"}
+
+# The global relative-date grammar (kept in sync with posthog.utils.relative_date_parse).
+# Used only to let already-supported formats — week/day/month boundaries, quarters, years —
+# pass through unchanged rather than rejecting them. A match needs either a number (position
+# optional) or a bare unit WITH a Start/End boundary; a bare unit alone (e.g. "h") is rejected,
+# since the global parser would silently resolve it to "now" — the fail-open this module prevents.
+_GLOBAL_RELATIVE_RE = re.compile(r"-?(?:\d+[hdwmqysHDWMQY](?:Start|End)?|[hdwmqysHDWMQY](?:Start|End))")
+
+
+def normalize_tracing_window(value: str | None) -> str | None:
+ """Normalize a single ``date_from``/``date_to`` value for the tracing API.
+
+ Returns the normalized string (or ``None`` for an empty value, so the caller's
+ default applies). Raises ``rest_framework.serializers.ValidationError`` for input
+ that is neither a recognized relative window nor an ISO 8601 timestamp.
+ """
+ if value is None:
+ return None
+ stripped = value.strip()
+ if not stripped:
+ return None
+
+ match = _TRACING_WINDOW_RE.match(stripped)
+ if match:
+ token = _UNIT_TO_RELATIVE_TOKEN[match.group("unit").lower()]
+ return f"-{match.group('number')}{token}"
+
+ # Absolute ISO 8601 timestamps pass through untouched.
+ try:
+ dateutil_parser.isoparse(stripped)
+ return stripped
+ except ValueError:
+ pass
+
+ # Preserve the broader global relative grammar (e.g. "-1dStart", "wStart", "-3q", "-1y")
+ # so anything that already worked keeps working.
+ if _GLOBAL_RELATIVE_RE.fullmatch(stripped):
+ return stripped
+
+ raise serializers.ValidationError(
+ f"Invalid date range value {value!r}. Use a relative window like '-30m' (minutes), "
+ "'-90s', '-6h', '-7d', '-2w', or an ISO 8601 timestamp."
+ )
+
+
+def normalize_tracing_date_range(raw: object, *, default_date_from: str = "-1h") -> dict:
+ """Normalize a raw ``dateRange`` dict from request input.
+
+ Falls back to ``{"date_from": default_date_from}`` when the input is missing or not
+ a dict. ``date_from`` is normalized (defaulting when absent); ``date_to`` is
+ normalized when present and left out otherwise (meaning "now" downstream).
+ """
+ if not isinstance(raw, dict) or not raw:
+ return {"date_from": default_date_from}
+
+ normalized: dict = dict(raw)
+ normalized["date_from"] = normalize_tracing_window(raw.get("date_from")) or default_date_from
+ date_to = normalize_tracing_window(raw.get("date_to"))
+ if date_to is None:
+ normalized.pop("date_to", None)
+ else:
+ normalized["date_to"] = date_to
+ return normalized
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 07a77ab9c7ae..0549dc221551 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -58,6 +58,7 @@ from ..logic import (
run_tree_query,
)
from ..sparkline_query_runner import TraceSpansSparklineQueryRunner
+from .date_window import normalize_tracing_date_range
# Serializers below are used exclusively for OpenAPI spec generation via
# drf-spectacular. They are NOT used for request validation — the existing
@@ -599,9 +600,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
search = request.GET.get("search", "")
try:
- date_range = self.get_model(json.loads(request.GET.get("dateRange", '{"date_from": "-1h"}')), DateRange)
- except (json.JSONDecodeError, Exception):
- date_range = DateRange(date_from="-1h")
+ raw_date_range = json.loads(request.GET.get("dateRange", '{"date_from": "-1h"}'))
+ except json.JSONDecodeError:
+ raw_date_range = {"date_from": "-1h"}
+ date_range = self.get_model(normalize_tracing_date_range(raw_date_range), DateRange)
results = run_service_names_query(team=self.team, date_range=date_range, search=search)
return Response({"results": results}, status=status.HTTP_200_OK)
@@ -629,7 +631,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
query_data = request.data.get("query", {})
after_cursor = query_data.get("after", None)
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
order_by = query_data.get("orderBy")
if order_by not in ("timestamp", "duration"):
@@ -744,7 +746,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data.get("query", {})
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
filter_group = (
self.get_model(self._normalize_filter_group(query_data.get("filterGroup")), PropertyGroupFilter)
if query_data.get("filterGroup")
@@ -822,7 +824,9 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_400_BAD_REQUEST,
)
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-24h"}), DateRange)
+ date_range = self.get_model(
+ normalize_tracing_date_range(query_data.get("dateRange"), default_date_from="-24h"), DateRange
+ )
response = run_symbol_stats_query(team=self.team, file_path=file_path, date_range=date_range, symbols=symbols)
granularity = response.granularity.value
@@ -849,7 +853,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
def sparkline(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data.get("query", {})
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
try:
filter_group = (
@@ -879,7 +883,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
def duration_histogram(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data.get("query", {})
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
try:
filter_group = (
@@ -905,7 +909,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
def aggregate(self, request: Request, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data.get("query", {}) or {}
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
try:
filter_group = (
@@ -959,7 +963,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_400_BAD_REQUEST,
)
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
try:
filter_group = (
@@ -1027,7 +1031,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
status=status.HTTP_400_BAD_REQUEST,
)
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-1h"}), DateRange)
+ date_range = self.get_model(normalize_tracing_date_range(query_data.get("dateRange")), DateRange)
try:
filter_group = (
@@ -1072,7 +1076,9 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
def trace(self, request: Request, trace_id: str, *args, **kwargs) -> Response:
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
query_data = request.data or {}
- date_range = self.get_model(query_data.get("dateRange", {"date_from": "-24h"}), DateRange)
+ date_range = self.get_model(
+ normalize_tracing_date_range(query_data.get("dateRange"), default_date_from="-24h"), DateRange
+ )
try:
# verify the trace_id is valid
bytes.fromhex(trace_id)
@@ -1142,9 +1148,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
offset = int(request.GET.get("offset", "0"))
try:
- date_range = self.get_model(json.loads(request.GET.get("dateRange", "{}")), DateRange)
- except (json.JSONDecodeError, ValidationError, ValueError):
- date_range = DateRange(date_from="-1h")
+ raw_date_range = json.loads(request.GET.get("dateRange", "{}"))
+ except json.JSONDecodeError:
+ raw_date_range = {}
+ date_range = self.get_model(normalize_tracing_date_range(raw_date_range), DateRange)
attribute_type = request.GET.get("attribute_type", "span_attribute")
if attribute_type not in ("span_attribute", "span_resource_attribute"):
@@ -1175,9 +1182,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
offset = int(request.GET.get("offset", "0"))
try:
- date_range = self.get_model(json.loads(request.GET.get("dateRange", "{}")), DateRange)
- except (json.JSONDecodeError, ValidationError, ValueError):
- date_range = DateRange(date_from="-1h")
+ raw_date_range = json.loads(request.GET.get("dateRange", "{}"))
+ except json.JSONDecodeError:
+ raw_date_range = {}
+ date_range = self.get_model(normalize_tracing_date_range(raw_date_range), DateRange)
attribute_type = request.GET.get("attribute_type", "span_attribute")
if attribute_type not in ("span", "span_attribute", "span_resource_attribute"):
diff --git a/products/tracing/backend/tests/test_date_window.py b/products/tracing/backend/tests/test_date_window.py
new file mode 100644
index 000000000000..8d553c1f36de
--- /dev/null
+++ b/products/tracing/backend/tests/test_date_window.py
@@ -0,0 +1,93 @@
+import pytest
+
+from parameterized import parameterized
+from rest_framework import serializers
+
+from products.tracing.backend.presentation.date_window import normalize_tracing_date_range, normalize_tracing_window
+
+
+class TestNormalizeTracingWindow:
+ @parameterized.expand(
+ [
+ # Friendly shorthand is translated onto the global parser's tokens.
+ # The headline case: lowercase "m" is minutes here (the global parser reads it as months).
+ ("-30m", "-30M"),
+ ("30m", "-30M"),
+ ("-90s", "-90s"),
+ ("-6h", "-6h"),
+ ("-7d", "-7d"),
+ ("-2w", "-2w"),
+ # Units are case-insensitive; uppercase M stays minutes.
+ ("-30M", "-30M"),
+ ("-6H", "-6h"),
+ # Whitespace is tolerated.
+ (" -30m ", "-30M"),
+ ]
+ )
+ def test_friendly_shorthand_is_normalized(self, value: str, expected: str) -> None:
+ assert normalize_tracing_window(value) == expected
+
+ @parameterized.expand(
+ [
+ # ISO 8601 timestamps pass through untouched.
+ ("2026-06-26T14:55:00Z",),
+ ("2026-06-26",),
+ # The broader global relative grammar (boundaries, quarters, years) is preserved,
+ # so anything that worked before keeps working — note "-1mStart" stays month-based.
+ ("-1dStart",),
+ ("wStart",),
+ ("-3q",),
+ ("-1y",),
+ ("-1mStart",),
+ ]
+ )
+ def test_supported_formats_pass_through_unchanged(self, value: str) -> None:
+ assert normalize_tracing_window(value) == value.strip()
+
+ @parameterized.expand([(None,), ("",), (" ",)])
+ def test_empty_values_return_none(self, value) -> None:
+ assert normalize_tracing_window(value) is None
+
+ @parameterized.expand(
+ [
+ ("soon",),
+ ("-30 minutes",),
+ ("last week",),
+ ("-30x",),
+ ("30",),
+ # A bare unit with no number and no Start/End boundary would resolve to "now" in the
+ # global parser — reject it rather than fail open. (Bare-unit-with-boundary like
+ # "wStart" stays valid, covered above.)
+ ("h",),
+ ("-m",),
+ ("d",),
+ ]
+ )
+ def test_unparseable_values_raise(self, value: str) -> None:
+ # The key behavior: garbage windows 400 instead of silently falling back to "now".
+ with pytest.raises(serializers.ValidationError):
+ normalize_tracing_window(value)
+
+
+class TestNormalizeTracingDateRange:
+ def test_missing_or_non_dict_uses_default(self) -> None:
+ assert normalize_tracing_date_range(None) == {"date_from": "-1h"}
+ assert normalize_tracing_date_range({}) == {"date_from": "-1h"}
+ assert normalize_tracing_date_range("nonsense") == {"date_from": "-1h"}
+
+ def test_respects_custom_default(self) -> None:
+ assert normalize_tracing_date_range({}, default_date_from="-24h") == {"date_from": "-24h"}
+
+ def test_normalizes_both_bounds(self) -> None:
+ assert normalize_tracing_date_range({"date_from": "-30m", "date_to": "-5m"}) == {
+ "date_from": "-30M",
+ "date_to": "-5M",
+ }
+
+ def test_absent_date_to_is_dropped(self) -> None:
+ result = normalize_tracing_date_range({"date_from": "-30m", "date_to": None})
+ assert result == {"date_from": "-30M"}
+
+ def test_invalid_bound_raises(self) -> None:
+ with pytest.raises(serializers.ValidationError):
+ normalize_tracing_date_range({"date_from": "-30 minutes"})