: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(marketing-analytics): warm sessions through the local day end (#105883)
Javier Bahamondes8b1c98ce710d
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.mdindex b8111e7c50a5..595647c93021 100644--- a/docs/internal/marketing-attribution-session-precompute.md+++ b/docs/internal/marketing-attribution-session-precompute.md@@ -8,13 +8,17 @@ The writer query change invalidates existing job hashes. Deploy both writer and`MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` covers calendar display days in the project timezone.The warmer starts at local midnight that many days before the run's local date, then subtracts the team's attribution lookback and one reachback day in UTC.+It warms through the end of that local day so reports that include today have complete UTC daily-window coverage.+For projects west of UTC, this can warm a UTC window before it starts.+A job computed before its window starts stops being eligible at that start, including for stale reads.+The reader falls back to live calculation until the window is refreshed after it starts, so the earlier snapshot cannot hide new sessions.The reader uses the same calendar boundary to check its maximum range.This includes the complete starting day for relative ranges such as `-90d`, even across daylight saving changes.Query overrides that extend before that boundary remain ineligible.Calendar alignment does not change the writer query or existing job hashes.-Run the updated warmer to populate any missing oldest daily windows before testing the full display range.-Existing ready jobs remain reusable, and missing coverage still falls back to live calculation.+Run the updated warmer to populate missing daily windows at either end before testing the full display range.+Existing ready jobs remain reusable if they satisfy the freshness policy, and missing coverage still falls back to live calculation.The allowlist, daily chunk size, and query execution limits are unchanged.With the existing serve-stale flag, readers may use jobs expired within six hours and enqueue debounced revalidation. Only that task runs reader-initiated inserts; it takes no stale grace. Scheduled writers also require fresh jobs. Classifier expression changes and the explicit dictionary version change the shared job hash, requiring fresh materialization.diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 7c08793f0856..fa512fc9a827 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -250,6 +250,10 @@ class TtlSchedule:non-UTC teams, whose UTC-aligned edge windows can land in a long-TTL band whilestill settling. `None` disables the check.+ `invalidate_at_window_start` rejects jobs computed before their window starts once+ that start is reached, even within stale grace. A future window can be warmed in+ advance, but its snapshot must not hide new data after the window begins.+`empty_result_ttl_seconds` caps the TTL of a job that wrote no rows. A zero-row insert isindistinguishable from a productive one at the SQL level, but it leaves the window only*provisionally* computed: either the source genuinely had no activity, or it hadn't been@@ -290,6 +294,7 @@ class TtlSchedule:empty_result_ttl_seconds: int | None = Noneempty_result_max_age_seconds: int | None = Nonedefault_ttl_jitter_seconds: int | None = None+ invalidate_at_window_start: bool = Falsedef get_ttl(self, window_start: datetime, *, jittered: bool = False) -> int:"""TTL for a window. `jittered=True` adds the default-band jitter offset.@@ -347,6 +352,7 @@ def parse_ttl_schedule(empty_result_ttl_seconds: int | None = None,empty_result_max_age_seconds: int | None = None,default_ttl_jitter_seconds: int | None = None,+ invalidate_at_window_start: bool = False,) -> TtlSchedule:"""Parse a TTL specification into a TtlSchedule.@@ -384,6 +390,7 @@ def parse_ttl_schedule(empty_result_ttl_seconds=empty_result_ttl_seconds,empty_result_max_age_seconds=empty_result_max_age_seconds,default_ttl_jitter_seconds=default_ttl_jitter_seconds,+ invalidate_at_window_start=invalidate_at_window_start,)tz = ZoneInfo(team_timezone)@@ -415,6 +422,7 @@ def parse_ttl_schedule(empty_result_ttl_seconds=empty_result_ttl_seconds,empty_result_max_age_seconds=empty_result_max_age_seconds,default_ttl_jitter_seconds=default_ttl_jitter_seconds,+ invalidate_at_window_start=invalidate_at_window_start,)@@ -1554,6 +1562,9 @@ class LazyComputationExecutor:TTL. `grace_seconds` is only non-zero for the serve-stale path and relaxes bothcaps uniformly.+ `invalidate_at_window_start` is a hard boundary: stale grace cannot make a+ snapshot taken before the window began cover data arriving after it began.+This is per-query: a job created by executor A with a long TTL may berejected by executor B using a stricter schedule for the same hash."""@@ -1564,6 +1575,8 @@ class LazyComputationExecutor:if job.status == PreaggregationJob.Status.PENDING:result.append(job)continue+ if self.ttl_schedule.invalidate_at_window_start and job.created_at < job.time_range_start <= now:+ continuedesired_ttl = self.ttl_schedule.get_ttl(job.time_range_start, jittered=True)fresh_until = job.created_at + timedelta(seconds=desired_ttl + grace_seconds)if settling_period is not None:diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.pyindex e923d492017b..80e1a77e7bc6 100644--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py@@ -2237,6 +2237,32 @@ class TestComputationExecutorExecute(BaseTest):assert job.id not in result.job_idsassert insert_count[0] == 1+ @parameterized.expand(+ [+ ("default_policy", False, None, True),+ ("invalidated", True, None, False),+ ("invalidated_with_grace", True, 6 * 60 * 60, False),+ ]+ )+ def test_future_job_invalidation_is_opt_in(+ self, _name: str, invalidate: bool, grace: int | None, expected_ready: bool+ ) -> None:+ query_info, _ = self._make_query_info()+ start = datetime(2026, 9, 11, tzinfo=UTC)+ end = start + timedelta(days=1)+ schedule = parse_ttl_schedule(2 * 60 * 60, invalidate_at_window_start=invalidate)+ with time_machine.travel(start - timedelta(minutes=25), tick=False) as clock:+ warmed = LazyComputationExecutor(ttl_schedule=schedule).execute(+ team=self.team, query_info=query_info, start=start, end=end, run_insert=lambda t, j: 0+ )+ assert warmed.ready+ clock.shift(timedelta(minutes=25))+ cached = LazyComputationExecutor(+ ttl_schedule=schedule, run_inserts=False, stale_while_revalidate_seconds=grace+ ).execute(team=self.team, query_info=query_info, start=start, end=end, run_insert=lambda t, j: 0)+ assert cached.ready is expected_ready+ assert cached.job_ids == (warmed.job_ids if expected_ready else [])+@parameterized.expand([# Expired 1h ago (created 2h ago, 1h TTL) — within the 6h grace: served as-is.diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.pyindex ef217c00c9de..64df9d90a9e0 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py@@ -133,6 +133,7 @@ def ensure_marketing_sessions_precomputed(team.timezone,max_window_days=CHUNK_DAYS,settling_period_seconds=SESSION_SETTLING_PERIOD_SECONDS,+ invalidate_at_window_start=True,),table=LazyComputationTable.WEB_SESSIONS_DIMENSIONAL_PREAGGREGATED,modifiers=modifiers,diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.pyindex c013bf190580..17f98559c127 100644--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py@@ -32,6 +32,52 @@ from products.marketing_analytics.backend.hogql_queries.marketing_sessions_preco@time_machine.travel("2026-09-10T12:00:00Z", tick=False)class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):+ def test_future_window_requires_refresh_when_it_starts(self) -> None:+ self.team.timezone = "America/Los_Angeles"+ start = datetime(2026, 9, 11, tzinfo=UTC)+ end = start + timedelta(hours=7)+ with time_machine.travel(start - timedelta(minutes=25), tick=False) as clock:+ warmed = ensure_marketing_sessions_precomputed(self.team, start, end)+ assert warmed.ready, warmed.errors+ assert warmed.job_ids+ cached = ensure_marketing_sessions_precomputed(self.team, start, end, run_inserts=False)+ assert cached.ready+ assert cached.job_ids == warmed.job_ids++ clock.shift(timedelta(minutes=25))+ for grace in (None, 6 * 60 * 60):+ cached = ensure_marketing_sessions_precomputed(+ self.team, start, end, run_inserts=False, stale_while_revalidate_seconds=grace+ )+ assert not cached.ready+ assert not cached.job_ids++ clock.shift(timedelta(minutes=1))+ timestamp = datetime.now(UTC)+ session_id = uuid7(int(timestamp.timestamp() * 1000))+ create_person(team=self.team, distinct_ids=["new-window-visitor"])+ _create_event(+ team=self.team,+ distinct_id="new-window-visitor",+ event="$pageview",+ timestamp=timestamp,+ properties={"$session_id": str(session_id)},+ )+ flush_persons_and_events()+ refreshed = ensure_marketing_sessions_precomputed(self.team, start, end)+ assert refreshed.ready, refreshed.errors+ assert set(refreshed.job_ids).isdisjoint(warmed.job_ids)+ cached = ensure_marketing_sessions_precomputed(+ self.team, start, end, run_inserts=False, stale_while_revalidate_seconds=6 * 60 * 60+ )+ assert cached.ready+ assert cached.job_ids == refreshed.job_ids+ assert sync_execute(+ "SELECT session_id_v7 FROM web_sessions_dimensional_preaggregated "+ "WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s",+ {"team_id": self.team.pk, "job_ids": cached.job_ids},+ ) == [(session_id.int,)]+@parameterized.expand([(version, legacy_value)diff --git a/products/marketing_analytics/dags/marketing_sessions_precompute.py b/products/marketing_analytics/dags/marketing_sessions_precompute.pyindex a8d01be27c67..bfc747285acd 100644--- a/products/marketing_analytics/dags/marketing_sessions_precompute.py+++ b/products/marketing_analytics/dags/marketing_sessions_precompute.py@@ -74,11 +74,11 @@ def _ensure_for_team(@dagster.opdef ensure_marketing_sessions_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:- end = datetime.now(UTC)+ now = datetime.now(UTC)team_ids = get_selected_team_ids()context.log.info(- f"marketing_sessions_precompute_start teams={len(team_ids)} display_days={PRECOMPUTE_WINDOW_DAYS} end={end} chunk_days={CHUNK_DAYS}"+ f"marketing_sessions_precompute_start teams={len(team_ids)} display_days={PRECOMPUTE_WINDOW_DAYS} now={now} chunk_days={CHUNK_DAYS}")if not team_ids:context.log.info(f"marketing_sessions_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")@@ -95,7 +95,13 @@ def ensure_marketing_sessions_precompute_op(context: dagster.OpExecutionContext)if team is None:context.log.warning(f"marketing_sessions_precompute_team_missing team_id={team_id}")continue- start = precompute_window_start(team, end)+ start = precompute_window_start(team, now)+ # Attribution reads include the full local day, which can cross into the next UTC day.+ end = (+ now.astimezone(team.timezone_info)+ .replace(hour=23, minute=59, second=59, microsecond=999999)+ .astimezone(UTC)+ )failures += _ensure_for_team(context, team, start, end, CHUNK_DAYS)processed += 1diff --git a/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.pyindex 93ea6040cc62..d61868b09da8 100644--- a/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py+++ b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py@@ -9,6 +9,9 @@ from unittest.mock import MagicMock, patchimport dagsterfrom parameterized import parameterized+from posthog.schema import DateRange, IntervalType++from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models import Teamfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult@@ -54,10 +57,13 @@ class TestMarketingSessionsPrecomputeDag(APIBaseTest):[("default", "UTC", "2024-07-05T12:00:00Z", 90, "2024-01-06T00:00:00Z"),("short", "UTC", "2024-07-05T12:00:00Z", 7, "2024-03-29T00:00:00Z"),- ("west", "America/Los_Angeles", "2024-07-05T02:00:00Z", 30, "2024-03-05T07:00:00Z"),+ ("west_before_midnight", "America/Los_Angeles", "2024-07-05T02:00:00Z", 30, "2024-03-05T07:00:00Z"),+ ("west_after_midnight", "America/Los_Angeles", "2024-07-05T12:00:00Z", 30, "2024-03-06T07:00:00Z"),("east", "Pacific/Auckland", "2024-07-05T16:00:00Z", 30, "2024-03-06T11:00:00Z"),("spring", "America/Los_Angeles", "2024-03-15T18:00:00Z", 30, "2023-11-15T08:00:00Z"),("fall", "America/Los_Angeles", "2024-11-15T18:00:00Z", 30, "2024-07-17T07:00:00Z"),+ ("spring_day", "America/Los_Angeles", "2024-03-10T09:00:00Z", 30, "2023-11-10T08:00:00Z"),+ ("fall_day", "America/Los_Angeles", "2024-11-03T08:00:00Z", 30, "2024-07-05T07:00:00Z"),])def test_warmer_covers_display_plus_team_lookback_and_reachback(@@ -82,4 +88,7 @@ class TestMarketingSessionsPrecomputeDag(APIBaseTest):assert ensure_marketing_sessions_precompute_op(context) == {"teams": 1, "failures": 0}args = ensure.call_args.argsassert args[2] == datetime.fromisoformat(expected_start)- assert args[3] == datetime.fromisoformat(now)+ date_range = QueryDateRange(+ DateRange(date_from="-90d"), self.team, IntervalType.DAY, datetime.fromisoformat(now)+ )+ assert args[3] == date_range.date_to().astimezone(UTC)