: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): run all-time earliest-timestamp query as the insight user (#67906)
Alex Lider86a039a56e23
diff --git a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.pyindex 57027f731848..6a650f356b7c 100644--- a/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py+++ b/posthog/hogql_queries/insights/lifecycle/lifecycle_query_runner.py@@ -300,7 +300,9 @@ class LifecycleQueryRunner(AnalyticsQueryRunner[LifecycleQueryResponse]):def _earliest_timestamp(self) -> datetime | None:if self.query.dateRange and self.query.dateRange.date_from == "all":# Get earliest timestamp across all series in this insight- return get_earliest_timestamp_from_series(team=self.team, series=list(self.query.series or []))+ return get_earliest_timestamp_from_series(+ team=self.team, series=list(self.query.series or []), user=self.user+ )return Nonediff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.pyindex d4f2d15a26b5..562bff9fde99 100644--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py@@ -775,7 +775,9 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):def _earliest_timestamp(self) -> datetime | None:if self.query.dateRange and self.query.dateRange.date_from == "all":# Get earliest timestamp across all series in this insight- return get_earliest_timestamp_from_series(team=self.team, series=[series.series for series in self.series])+ return get_earliest_timestamp_from_series(+ team=self.team, series=[series.series for series in self.series], user=self.user+ )return Nonediff --git a/posthog/hogql_queries/utils/test/test_timestamp_utils.py b/posthog/hogql_queries/utils/test/test_timestamp_utils.pyindex 106a327322fc..1fae477d79da 100644--- a/posthog/hogql_queries/utils/test/test_timestamp_utils.py+++ b/posthog/hogql_queries/utils/test/test_timestamp_utils.py@@ -483,7 +483,7 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):# run untagged and raise UntaggedQueryError in dev (DEBUG and not TEST).captured: dict[str, object] = {}- def capture(team, node):+ def capture(team, node, user=None):captured[node.table_name] = get_query_tags().productreturn datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)@@ -531,7 +531,7 @@ class TestTimestampUtils(APIBaseTest, ClickhouseDestroyTablesMixin):def test_single_path_query_tags(self, _name, caller_product, caller_feature, expected_product, expected_feature):captured: dict[str, object] = {}- def capture(query, team):+ def capture(query, team, user=None):tags = get_query_tags()captured["product"] = tags.productcaptured["feature"] = tags.featurediff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.pyindex 50c42c24697c..c2f9ab3e50ae 100644--- a/posthog/hogql_queries/utils/timestamp_utils.py+++ b/posthog/hogql_queries/utils/timestamp_utils.py@@ -3,7 +3,7 @@ from collections.abc import Sequencefrom concurrent.futures import ThreadPoolExecutorfrom contextlib import AbstractContextManagerfrom datetime import date, datetime, timedelta, tzinfo-from typing import Any, Union+from typing import Any, Optional, Unionfrom django.conf import settingsfrom django.core.cache import cache@@ -28,7 +28,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, tags_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRange-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.event import DEFAULT_EARLIEST_TIME_DELTAfrom posthog.models.team import WeekStartDayfrom posthog.utils import get_safe_cache@@ -182,14 +182,18 @@ def _earliest_timestamp_query_tags() -> AbstractContextManager[None]:def _get_earliest_timestamp_from_node(team: Team,node: Union[EventsNode, ActionsNode, DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode],+ user: Optional[User] = None,) -> datetime:"""Get the earliest timestamp from a single series node:param team: The team:param node: The series node+ :param user: The user the query runs as, for warehouse table access control:return: The earliest timestamp as a datetime object."""+ # The cache is team-wide (keyed by team + node, not user): the value is table metadata, and row+ # access is still enforced on the insight's main query, so per-user entries aren't worth the misses.cache_key = _get_earliest_timestamp_cache_key(team, node)cached_result = get_safe_cache(cache_key)if cached_result is not None:@@ -209,7 +213,7 @@ def _get_earliest_timestamp_from_node(earliest_timestamp = EARLIEST_EVENT_TIMESTAMPwith _earliest_timestamp_query_tags():- result = execute_hogql_query(query=query, team=team)+ result = execute_hogql_query(query=query, team=team, user=user)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)@@ -224,6 +228,7 @@ def get_earliest_timestamp_from_series(EventsNode, ActionsNode, DataWarehouseNode, FunnelsDataWarehouseNode, LifecycleDataWarehouseNode, GroupNode]],+ user: Optional[User] = None,) -> datetime:"""Get the earliest timestamp for specific events/actions in a series.@@ -232,6 +237,7 @@ def get_earliest_timestamp_from_series(:param team: The team:param series: A list of series nodes (EventsNode, ActionsNode, DataWarehouseNode, or GroupNode)+ :param user: The user the queries run as, for warehouse table access control:return: The earliest timestamp across all series"""# Expand GroupNode nodes into individual nodes@@ -246,14 +252,14 @@ def get_earliest_timestamp_from_series(timestamps = []if len(nodes) == 1 or settings.IN_UNIT_TESTING:- timestamps = [_get_earliest_timestamp_from_node(team, node) for node in nodes]+ timestamps = [_get_earliest_timestamp_from_node(team, node, user) for node in nodes]else:with ThreadPoolExecutor(max_workers=min(len(nodes), 4)) as executor:# ThreadPoolExecutor does not inherit contextvars (query tags) by default; copy the# current context into each worker so tagged sync_execute calls don't fail untagged.futures = [- executor.submit(contextvars.copy_context().run, _get_earliest_timestamp_from_node, team, node)+ executor.submit(contextvars.copy_context().run, _get_earliest_timestamp_from_node, team, node, user)for node in nodes]timestamps = [future.result() for future in futures]