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(marketing-analytics): resolve date_from='all' in warehouse trends path (#62824)

Javier Bahamondesf49b83707549
diff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
index dac59d930c95..caed96961db6 100644
--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py
+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py
@@ -2,7 +2,7 @@ import datetime
from zoneinfo import ZoneInfo
from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.core.cache import cache
from django.test import override_settings
@@ -17,6 +17,7 @@ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.timestamp_utils import (
EARLIEST_EVENT_TIMESTAMP,
_coerce_to_datetime,
+ _get_earliest_timestamp_cache_key,
format_label_date,
get_earliest_timestamp_from_series,
)
@@ -456,3 +457,53 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):
self.assertEqual(captured["a"], Product.MARKETING_ANALYTICS)
self.assertEqual(captured["b"], Product.MARKETING_ANALYTICS)
+
+ def test_cached_raw_value_is_coerced_on_read(self):
+ # Entries cached before the coercion fix shipped hold a raw str/date for up to the
+ # TTL window. A cache hit must still pass through _coerce_to_datetime instead of
+ # returning the raw value, otherwise downstream date math hits AttributeError/TypeError.
+ node = EventsNode(event="$pageview")
+ cache_key = _get_earliest_timestamp_cache_key(self.team, node)
+ # team timezone is UTC in tests; "2021-03-15" is the pre-fix raw Date/String shape.
+ cache.set(cache_key, "2021-03-15", timeout=3600)
+
+ result = get_earliest_timestamp_from_series(self.team, [node])
+
+ self.assertIsInstance(result, datetime.datetime)
+ self.assertEqual(result, datetime.datetime(2021, 3, 15, 0, 0, 0, tzinfo=datetime.UTC))
+
+ @parameterized.expand(
+ [
+ # No caller tags: the earliest-timestamp query must still carry product/feature,
+ # otherwise it raises UntaggedQueryError in dev for uncached series.
+ ("fills_defaults_when_unset", None, None, Product.PRODUCT_ANALYTICS, Feature.INSIGHT),
+ # Caller already attributed the query (e.g. marketing analytics): keep their tags.
+ (
+ "preserves_caller_tags",
+ Product.MARKETING_ANALYTICS,
+ Feature.QUERY,
+ Product.MARKETING_ANALYTICS,
+ Feature.QUERY,
+ ),
+ ]
+ )
+ def test_single_path_query_tags(self, _name, caller_product, caller_feature, expected_product, expected_feature):
+ captured: dict[str, object] = {}
+
+ def capture(query, team):
+ tags = get_query_tags()
+ captured["product"] = tags.product
+ captured["feature"] = tags.feature
+ result = MagicMock()
+ result.results = [[datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)]]
+ return result
+
+ with tags_context(product=caller_product, feature=caller_feature):
+ with patch(
+ "posthog.hogql_queries.utils.timestamp_utils.execute_hogql_query",
+ side_effect=capture,
+ ):
+ get_earliest_timestamp_from_series(self.team, [EventsNode(event="$pageview")])
+
+ self.assertEqual(captured["product"], expected_product)
+ self.assertEqual(captured["feature"], expected_feature)
diff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.py
index 57f6292268f7..fc4534bf0691 100644
--- a/posthog/hogql_queries/utils/timestamp_utils.py
+++ b/posthog/hogql_queries/utils/timestamp_utils.py
@@ -1,6 +1,7 @@
import contextvars
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
+from contextlib import AbstractContextManager
from datetime import date, datetime, timedelta, tzinfo
from typing import Any, Union
@@ -24,6 +25,7 @@ from posthog.hogql.ast import SelectQuery
from posthog.hogql.property import action_to_expr
from posthog.hogql.query import execute_hogql_query
+from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_context
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
from posthog.models.team import WeekStartDay
@@ -155,6 +157,24 @@ def _coerce_to_datetime(value: Any, tz: tzinfo) -> datetime:
return EARLIEST_EVENT_TIMESTAMP
+def _earliest_timestamp_query_tags() -> AbstractContextManager[None]:
+ """Ensure the earliest-timestamp resolution query carries product/feature tags.
+
+ Resolving "all time" date_from runs this query while setting up a date range —
+ often before the main query runner has tagged its execution context. An untagged
+ ClickHouse query raises UntaggedQueryError in local dev. Inherit whatever the
+ caller already set and only fill product/feature when missing, so callers like
+ marketing analytics keep their own attribution.
+ """
+ current = get_query_tags()
+ overrides: dict[str, Any] = {}
+ if current.product is None:
+ overrides["product"] = Product.PRODUCT_ANALYTICS
+ if current.feature is None:
+ overrides["feature"] = Feature.INSIGHT
+ return tags_context(**overrides)
+
+
def _get_earliest_timestamp_from_node(
team: Team,
node: Union[EventsNode, ActionsNode, DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode],
@@ -169,7 +189,10 @@ def _get_earliest_timestamp_from_node(
cache_key = _get_earliest_timestamp_cache_key(team, node)
cached_result = get_safe_cache(cache_key)
if cached_result is not None:
- return cached_result
+ # Coerce on read too: entries cached before the coercion fix shipped hold a raw
+ # str/date for up to the TTL window. Passing them through is idempotent for the
+ # datetime values written after the fix and repairs the stale ones.
+ return _coerce_to_datetime(cached_result, team.timezone_info)
if (
isinstance(node, DataWarehouseNode)
@@ -181,7 +204,8 @@ def _get_earliest_timestamp_from_node(
query = _get_event_earliest_timestamp_query(team, node)
earliest_timestamp = EARLIEST_EVENT_TIMESTAMP
- result = execute_hogql_query(query=query, team=team)
+ with _earliest_timestamp_query_tags():
+ result = execute_hogql_query(query=query, team=team)
if result and len(result.results) > 0 and len(result.results[0]) > 0 and result.results[0][0] is not None:
earliest_timestamp = _coerce_to_datetime(result.results[0][0], team.timezone_info)