: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): align session cache freshness with utc windows (#106687)
Javier Bahamondes8cb29f34e7d4
diff --git a/docs/internal/marketing-sessions-precompute.md b/docs/internal/marketing-sessions-precompute.mdindex 18dfe1874b19..ed76203223a7 100644--- a/docs/internal/marketing-sessions-precompute.md+++ b/docs/internal/marketing-sessions-precompute.md@@ -14,6 +14,10 @@ A failed coverage query also returns `ready=False`; an empty result accompaniedSessions lasting more than one day, including 49-hour sessions, remain supported by the cache.Results are snapshots subject to the configured freshness schedule.+Freshness bands use UTC dates to match the daily job windows, independently of the project timezone.+The current UTC day has a two-hour TTL, the previous two UTC days have a one-day TTL, and older windows have a 90-day TTL subject to the settling boundary.+Freshness checks also apply these bands to existing jobs, including jobs stored with a longer expiry.+These TTLs determine when a job needs renewal; the writer schedule determines when that renewal completes.A start-day window settles three days after it ends, matching the maximum supported session duration.Snapshots computed before that point expire at the settling boundary even when their stored TTL is longer, so a later first pageview cannot leave the window empty for 90 days.Before settlement, the normal freshness schedule still applies; session dimensions are not updated on every event.diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.pyindex 64df9d90a9e0..8d8d1d0ed0f6 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py@@ -19,7 +19,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuparse_ttl_schedule,)-# Today's window refreshes hourly, the last two days daily, everything older is held for 90 days.+# UTC-day bands keep TTL cutoffs aligned with the daily INSERT windows.# The today band is two warmer periods wide: at one, it expires the minute the next run starts, so# any delay in that run makes the window read as cold.SESSIONS_TTL_SECONDS: dict[str, int] = {@@ -130,7 +130,7 @@ def ensure_marketing_sessions_precomputed(# the window was still settling must not freeze that snapshot for the whole band TTL.ttl_seconds=parse_ttl_schedule(SESSIONS_TTL_SECONDS,- team.timezone,+ "UTC",max_window_days=CHUNK_DAYS,settling_period_seconds=SESSION_SETTLING_PERIOD_SECONDS,invalidate_at_window_start=True,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 17f98559c127..a1ea38d2bce5 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@@ -23,6 +23,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuLazyComputationTable,ensure_precomputed,)+from products.analytics_platform.backend.models import PreaggregationJobfrom products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (SESSIONS_INSERT_TEMPLATE,base_placeholders,@@ -32,6 +33,57 @@ from products.marketing_analytics.backend.hogql_queries.marketing_sessions_preco@time_machine.travel("2026-09-10T12:00:00Z", tick=False)class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):+ @parameterized.expand(+ [+ ("UTC", 8),+ ("America/Los_Angeles", 6),+ ("America/Los_Angeles", 8),+ ("America/Santiago", 4),+ ("Asia/Kathmandu", 19),+ ]+ )+ def test_current_utc_window_refreshes_after_two_hours(self, timezone: str, hour: int) -> None:+ self.team.timezone = timezone+ now = time_machine.escape_hatch.datetime.datetime.now(UTC).replace(+ hour=hour, minute=0, second=0, microsecond=0+ ) + timedelta(days=2)+ with time_machine.travel(now, tick=False) as clock:+ created_at = datetime.now(UTC)+ start = created_at.replace(hour=0, minute=0, second=0, microsecond=0)+ end = start + timedelta(days=1)+ initial = ensure_marketing_sessions_precomputed(self.team, start, end)+ assert initial.ready, initial.errors+ job = PreaggregationJob.objects.get(id=initial.job_ids[0])+ assert job.expires_at == created_at + timedelta(hours=2)++ PreaggregationJob.objects.filter(id=job.id).update(expires_at=created_at + timedelta(days=1))+ clock.shift(timedelta(hours=1))+ timestamp = datetime.now(UTC)+ session_id = uuid7(int(timestamp.timestamp() * 1000))+ create_person(team=self.team, distinct_ids=["new-session-visitor"])+ _create_event(+ team=self.team,+ distinct_id="new-session-visitor",+ event="$pageview",+ timestamp=timestamp,+ properties={"$session_id": str(session_id)},+ )+ flush_persons_and_events()+ cached = ensure_marketing_sessions_precomputed(self.team, start, end, run_inserts=False)+ assert cached.ready+ assert cached.job_ids == initial.job_ids++ clock.shift(timedelta(hours=1, seconds=1))+ assert not ensure_marketing_sessions_precomputed(self.team, start, end, run_inserts=False).ready+ refreshed = ensure_marketing_sessions_precomputed(self.team, start, end)+ assert refreshed.ready, refreshed.errors+ assert set(refreshed.job_ids).isdisjoint(initial.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": refreshed.job_ids},+ ) == [(session_id.int,)]+def test_future_window_requires_refresh_when_it_starts(self) -> None:self.team.timezone = "America/Los_Angeles"start = datetime(2026, 9, 11, tzinfo=UTC)