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): align session cache with calendar ranges (#105637)

Javier Bahamondes754fa69e9d80
diff --git a/docs/internal/marketing-attribution-session-precompute.md b/docs/internal/marketing-attribution-session-precompute.md
index 2e89b6e1c03f..b8111e7c50a5 100644
--- a/docs/internal/marketing-attribution-session-precompute.md
+++ b/docs/internal/marketing-attribution-session-precompute.md
@@ -6,7 +6,16 @@ The writer excludes sessions longer than its scan budget. The reader also replac
The writer query change invalidates existing job hashes. Deploy both writer and reader before warming the new jobs; keep the reader flag off until the controlled rollout validates coverage and query cost.
-`MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` covers display days. The proposed warmer adds the team's attribution lookback and one reachback day: default 90 + 90 + 1 = 181 trailing days, previously 90. This approximately doubles initial daily chunks and retained job coverage; actual scan/storage cost depends on session volume and duration. The allowlist and environment values are unchanged. Evaluate this cost before rollout. Query overrides beyond the total warmed span remain ineligible.
+`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.
+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.
+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/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
index 6c2df04a3343..f462bb708a74 100644
--- a/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/attribution_sessions_read.py
@@ -24,7 +24,7 @@ from products.analytics_platform.backend.lazy_computation.stale_policy import re
from products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (
SESSION_READ_REACHBACK_DAYS,
ensure_marketing_sessions_precomputed,
- precompute_window_days,
+ precompute_window_start,
)
from .attribution_base import MAX_CONVERSIONS_PER_PERSON, MAX_TOUCHPOINTS_PER_PERSON, PERSON_CONVERSION_COUNT
@@ -114,9 +114,7 @@ def ineligible_reason(runner: "AttributionQueryRunnerBase", date_range: QueryDat
return "test_account_filters"
read = window(runner, date_range)
- if (read.end - read.start).total_seconds() > (
- precompute_window_days(runner.team) - SESSION_READ_REACHBACK_DAYS
- ) * 86400:
+ if read.start - timedelta(days=SESSION_READ_REACHBACK_DAYS) < precompute_window_start(runner.team, read.end):
return "window_over_max"
return None
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py
index 355941096736..ef217c00c9de 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py
@@ -2,7 +2,7 @@
import os
import hashlib
-from datetime import datetime
+from datetime import UTC, datetime, timedelta
from posthog.hogql import ast
from posthog.hogql.database.schema.channel_type import expand_default_channel_type_call
@@ -91,9 +91,13 @@ def base_placeholders() -> dict[str, ast.Expr]:
}
-def precompute_window_days(team: Team) -> int:
- return (
- PRECOMPUTE_WINDOW_DAYS + team.marketing_analytics_config.attribution_window_days + SESSION_READ_REACHBACK_DAYS
+def precompute_window_start(team: Team, end: datetime) -> datetime:
+ # Relative display ranges start at local midnight; attribution lookback uses elapsed UTC seconds.
+ display_start = end.astimezone(team.timezone_info).replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(
+ days=PRECOMPUTE_WINDOW_DAYS
+ )
+ return display_start.astimezone(UTC) - timedelta(
+ days=team.marketing_analytics_config.attribution_window_days + SESSION_READ_REACHBACK_DAYS
)
diff --git a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
index 25f3f46da7b3..3a3d08a0993b 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_attribution_sessions_read.py
@@ -1,6 +1,7 @@
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from uuid import UUID
+import time_machine
from unittest.mock import PropertyMock, patch
from django.test import SimpleTestCase
@@ -104,27 +105,53 @@ class TestAttributionSessionsRead(SimpleTestCase):
assert "AS first_conversion" in sql
assert ("conv.last_conversion" in sql) is repeat
- def test_default_lookback_and_ninety_display_days_fit_writer_coverage(self) -> None:
- runner = MarketingAnalyticsAttributionQueryRunner(
- team=self.team,
- modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
- query=MarketingAnalyticsAttributionQuery(
- conversionGoalId="goal",
- properties=[],
- dateRange=DateRange(date_from="2023-01-01", date_to="2023-03-31"),
- ),
- )
- assert runner.lookback_window_days == 90
- assert marketing_sessions_precompute.precompute_window_days(self.team) == 181
- assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) is None
- with patch.object(
- attribution_sessions_read,
- "window",
- return_value=attribution_sessions_read.ReadWindow(
- start=datetime(2023, 1, 1, tzinfo=UTC), end=datetime(2023, 7, 1, tzinfo=UTC)
- ),
+ @parameterized.expand(
+ [
+ ("fixed", "UTC", "2023-04-01T12:00:00Z", "2023-01-01", "2023-03-31", 90, 90, None),
+ ("utc", "UTC", "2024-07-05T12:00:00Z", "-90d", None, 30, 90, None),
+ ("west", "America/Los_Angeles", "2024-07-05T02:00:00Z", "-90d", None, 30, 90, None),
+ ("east", "Pacific/Auckland", "2024-07-05T16:00:00Z", "-90d", None, 90, 90, None),
+ ("spring", "America/Los_Angeles", "2024-03-15T18:00:00Z", "-90d", None, 30, 90, None),
+ ("fall", "America/Los_Angeles", "2024-11-15T18:00:00Z", "-90d", None, 30, 90, None),
+ ("configured", "UTC", "2024-07-05T12:00:00Z", "-7d", None, 7, 7, None),
+ ("too_wide", "UTC", "2024-07-05T12:00:00Z", "-91d", None, 30, 90, "window_over_max"),
+ ]
+ )
+ def test_display_window_fits_writer_coverage(
+ self,
+ _name: str,
+ timezone: str,
+ now: str,
+ date_from: str,
+ date_to: str | None,
+ lookback: int,
+ display_days: int,
+ expected_reason: str | None,
+ ) -> None:
+ self.team.timezone = timezone
+ self.team.marketing_analytics_config.attribution_window_days = lookback
+ with (
+ time_machine.travel(now, tick=False),
+ patch.object(marketing_sessions_precompute, "PRECOMPUTE_WINDOW_DAYS", display_days),
):
- assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == "window_over_max"
+ runner = MarketingAnalyticsAttributionQueryRunner(
+ team=self.team,
+ modifiers=HogQLQueryModifiers(personsOnEventsMode="person_id_override_properties_on_events"),
+ query=MarketingAnalyticsAttributionQuery(
+ conversionGoalId="goal",
+ properties=[],
+ dateRange=DateRange(date_from=date_from, date_to=date_to),
+ ),
+ )
+ assert runner.lookback_window_days == lookback
+ assert attribution_sessions_read.ineligible_reason(runner, runner.query_date_range) == expected_reason
+ if expected_reason is None:
+ read = attribution_sessions_read.window(runner, runner.query_date_range)
+ required_start = read.start - timedelta(days=marketing_sessions_precompute.SESSION_READ_REACHBACK_DAYS)
+ assert (
+ marketing_sessions_precompute.precompute_window_start(self.team, datetime.now(UTC))
+ <= required_start
+ )
@parameterized.expand(
[
diff --git a/products/marketing_analytics/dags/marketing_sessions_precompute.py b/products/marketing_analytics/dags/marketing_sessions_precompute.py
index 58d32fd5bf98..a8d01be27c67 100644
--- a/products/marketing_analytics/dags/marketing_sessions_precompute.py
+++ b/products/marketing_analytics/dags/marketing_sessions_precompute.py
@@ -5,7 +5,7 @@ The table is only useful for teams whose windows this job keeps warm. Configure
"""
import os
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
import dagster
import structlog
@@ -18,7 +18,7 @@ from products.marketing_analytics.backend.hogql_queries.marketing_sessions_preco
CHUNK_DAYS,
PRECOMPUTE_WINDOW_DAYS,
ensure_marketing_sessions_precomputed,
- precompute_window_days,
+ precompute_window_start,
)
logger = structlog.get_logger(__name__)
@@ -95,7 +95,7 @@ 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 = end - timedelta(days=precompute_window_days(team))
+ start = precompute_window_start(team, end)
failures += _ensure_for_team(context, team, start, end, CHUNK_DAYS)
processed += 1
diff --git a/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py
index a2283b0ec997..93ea6040cc62 100644
--- a/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py
+++ b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py
@@ -1,7 +1,8 @@
import os
from collections.abc import Callable
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, datetime
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -49,15 +50,28 @@ class TestMarketingSessionsPrecomputeDag(APIBaseTest):
def test_a_raising_chunk_still_counts_as_a_failure(self) -> None:
assert self._run(RuntimeError("boom")) == 1
- @parameterized.expand([("default", 90, 181), ("short", 7, 98)])
- def test_warmer_covers_display_plus_team_lookback_and_reachback(self, _name: str, lookback: int, span: int) -> None:
+ @parameterized.expand(
+ [
+ ("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"),
+ ("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"),
+ ]
+ )
+ def test_warmer_covers_display_plus_team_lookback_and_reachback(
+ self, _name: str, timezone: str, now: str, lookback: int, expected_start: str
+ ) -> None:
+ self.team.timezone = timezone
+ self.team.save(update_fields=["timezone"])
config = self.team.marketing_analytics_config
config.attribution_window_days = lookback
config.save()
module = "products.marketing_analytics.dags.marketing_sessions_precompute"
with (
+ time_machine.travel(now, tick=False),
patch(f"{module}.get_selected_team_ids", return_value=[self.team.pk]),
- patch(f"{module}.PRECOMPUTE_WINDOW_DAYS", 90),
patch(
"products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute.PRECOMPUTE_WINDOW_DAYS",
90,
@@ -67,4 +81,5 @@ class TestMarketingSessionsPrecomputeDag(APIBaseTest):
with dagster.build_op_context() as context:
assert ensure_marketing_sessions_precompute_op(context) == {"teams": 1, "failures": 0}
args = ensure.call_args.args
- assert args[3] - args[2] == timedelta(days=span)
+ assert args[2] == datetime.fromisoformat(expected_start)
+ assert args[3] == datetime.fromisoformat(now)