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.

feat(marketing-analytics): materialize the session-grain table (#90937)

Javier Bahamondes94c89cc6090e
diff --git a/docs/internal/marketing-sessions-precompute.md b/docs/internal/marketing-sessions-precompute.md
new file mode 100644
index 000000000000..c05456d8c6b9
--- /dev/null
+++ b/docs/internal/marketing-sessions-precompute.md
@@ -0,0 +1,34 @@
+# Marketing session precompute writer
+
+The writer partitions sessions by the UTC hour of their start in `web_sessions_dimensional_preaggregated`.
+Window membership uses the exact start timestamp; hourly buckets are rounded explicitly in UTC, including for projects with half-hour or quarter-hour timezone offsets.
+It writes `session_id_v7` as the numeric UUID representation from `events.$session_id_uuid` and stores the first and last pageview timestamps.
+Each insert covers at most one day of session starts and scans events through three days after that window ends.
+Before writing or accepting cached jobs, it checks the corresponding daily windows for sessions longer than three days.
+If it finds one, it returns `ready=False` so the reader can use live attribution without truncating that session.
+A failed coverage query also returns `ready=False`; an empty result accompanied by an error does not prove coverage.
+Sessions lasting more than one day, including 49-hour sessions, remain supported by the cache.
+
+Results are snapshots subject to the configured freshness schedule.
+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.
+The writer respects the team's session table version: v3 when configured, otherwise v2; v1 requests fall back to live attribution.
+Resolved query modifiers are part of the cache identity, so different source versions and channel rules cannot reuse the same jobs.
+
+Stored person IDs are snapshots too: a merge after materialization can leave a touchpoint under its previous person ID until refresh.
+The reader must resolve current identity before enabling this path for merged-person attribution.
+
+## Deployment configuration
+
+Before enabling this writer, wire these environment variables through the deployment configuration in `PostHog/charts` and `PostHog/secrets`:
+
+| Variable | Consumers | Default | Operational meaning |
+| ------------------------------------------- | ---------------------------------------------------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
+| `MARKETING_SESSIONS_PRECOMPUTE_TEAM_IDS` | Dagster code location running the marketing session job | Empty in every deployment | Comma-separated team IDs. An unset or explicitly empty value disables writes. |
+| `MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS` | Dagster writer and every process importing the shared coverage setting | `90` | Display history in days. Add team attribution lookback and one session reachback day; the defaults cover 181 days. Keep deployments consistent. |
+
+Deploy the table migration before running the job. Verify the effective variables in each target deployment, including that an empty allowlist produces a no-op. A definition in this repository alone does not wire deployment variables; changes and verification in the deployment repositories are a rollout prerequisite.
+
+The `marketing_sessions_precompute_chunk_done_total` and `marketing_sessions_precompute_chunk_failed_total` metrics count daily chunks.
+Job metadata reports the number of teams and failed chunks separately.
diff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.py
index 20dc94474570..229c7bbceed8 100644
--- a/posthog/dags/locations/web_analytics.py
+++ b/posthog/dags/locations/web_analytics.py
@@ -2,7 +2,7 @@ import dagster
from posthog.settings import TEST
-from products.marketing_analytics.dags import marketing_precompute
+from products.marketing_analytics.dags import marketing_precompute, marketing_sessions_precompute
from products.web_analytics.dags import (
cache_favicons,
cache_warming,
@@ -28,6 +28,7 @@ schedules = [
eager_web_analytics_precompute.web_analytics_eager_baseline_warming_schedule,
web_dimensional_precompute.web_dimensional_precompute_schedule,
marketing_precompute.marketing_precompute_schedule,
+ marketing_sessions_precompute.marketing_sessions_precompute_schedule,
cache_favicons.cache_authorized_domain_favicons_schedule,
web_analytics_watchdog.web_analytics_watchdog_schedule,
]
@@ -61,6 +62,7 @@ defs = dagster.Definitions(
eager_web_analytics_precompute.web_analytics_eager_backfill_job,
web_dimensional_precompute.web_dimensional_precompute_job,
marketing_precompute.marketing_precompute_job,
+ marketing_sessions_precompute.marketing_sessions_precompute_job,
cache_favicons.cache_authorized_domain_favicons_job,
clear_oom_pins.web_analytics_clear_precompute_oom_pins_job,
migrate_custom_bot_rules.web_analytics_migrate_custom_bot_rules_job,
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 3197ef084d95..f69352e4fbc6 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -554,6 +554,7 @@ class LazyComputationTable(StrEnum):
# Dagster job (the precomputation-framework successor to v2 pre-aggregation).
WEB_STATS_DIMENSIONAL_PREAGGREGATED = "web_stats_dimensional_preaggregated"
WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED = "web_bounces_dimensional_preaggregated"
+ WEB_SESSIONS_DIMENSIONAL_PREAGGREGATED = "web_sessions_dimensional_preaggregated"
# Tables where expires_at is a Date (not DateTime64). Date truncates to midnight,
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py
new file mode 100644
index 000000000000..259e1373488f
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_sessions_precompute.py
@@ -0,0 +1,169 @@
+"""Materialize session touchpoints with their channel classified before attribution reads."""
+
+import os
+import hashlib
+from datetime import datetime
+
+from posthog.hogql import ast
+from posthog.hogql.database.schema.channel_type import expand_default_channel_type_call
+from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.models.team import Team
+from posthog.schema_enums import SessionTableVersion
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationResult,
+ LazyComputationTable,
+ ensure_precomputed,
+ get_daily_windows,
+ parse_ttl_schedule,
+)
+
+# Today's window refreshes hourly, the last two days daily, everything older is held for 90 days.
+# 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] = {
+ "0d": 2 * 60 * 60,
+ "2d": 24 * 60 * 60,
+ "default": 90 * 24 * 60 * 60,
+}
+
+# One INSERT per UTC day. The framework merges a fully-missing range into one INSERT, so without a
+# cap a cold backfill scans the whole span at once.
+CHUNK_DAYS = 1
+
+# Display history; the shared window helper adds team lookback and session reachback.
+PRECOMPUTE_WINDOW_DAYS = int(os.getenv("MARKETING_SESSIONS_PRECOMPUTE_WINDOW_DAYS", "90"))
+
+# Bump for changes to the lookup dictionaries used by the builtin classifier.
+SESSION_CHANNEL_CLASSIFIER_VERSION = 1
+SESSION_READ_REACHBACK_DAYS = 1
+
+MAX_PRECOMPUTED_SESSION_SECONDS = 3 * 24 * 60 * 60
+SESSION_SETTLING_PERIOD_SECONDS = MAX_PRECOMPUTED_SESSION_SECONDS
+
+# Keep start predicates unwrapped so the sessions resolver pushes them into raw sessions.
+UNSUPPORTED_SESSIONS_QUERY = """
+SELECT 1
+FROM sessions
+WHERE $start_timestamp >= {time_window_min}
+ AND $start_timestamp < {time_window_max}
+ AND $end_timestamp > $start_timestamp + toIntervalSecond({max_session_seconds})
+LIMIT 1
+"""
+
+SESSIONS_INSERT_TEMPLATE = """
+SELECT
+ toStartOfHour(toTimeZone(min(events.session.$start_timestamp), 'UTC')) AS period_bucket,
+ events.$session_id_uuid AS session_id_v7,
+ events.person_id AS person_id,
+ min(events.session.$start_timestamp) AS start_timestamp,
+ min(events.timestamp) AS min_event_timestamp,
+ max(events.timestamp) AS max_event_timestamp,
+ any(if(notEmpty(ifNull(events.session.$channel_type, '')), events.session.$channel_type, 'Unknown')) AS channel_type,
+ any(toString(ifNull(events.session.$entry_utm_source, ''))) AS utm_source,
+ any(toString(ifNull(events.session.$entry_utm_medium, ''))) AS utm_medium,
+ any(toString(ifNull(events.session.$entry_utm_campaign, ''))) AS utm_campaign,
+ any(toString(ifNull(events.session.$entry_utm_term, ''))) AS utm_term,
+ any(toString(ifNull(events.session.$entry_utm_content, ''))) AS utm_content,
+ any(toString(ifNull(events.session.$entry_referring_domain, ''))) AS referring_domain,
+ any(toString(ifNull(events.session.$entry_pathname, ''))) AS entry_pathname,
+ count() AS pageview_count
+FROM events
+WHERE and(
+ {classifier_version} = {classifier_version},
+ events.$session_id_uuid IS NOT NULL,
+ equals(events.event, '$pageview'),
+ events.timestamp >= {time_window_min},
+ events.timestamp < {time_window_max} + toIntervalSecond({max_session_seconds})
+)
+GROUP BY session_id_v7, person_id
+HAVING and(
+ min(events.session.$start_timestamp) >= {time_window_min},
+ min(events.session.$start_timestamp) < {time_window_max}
+)
+"""
+
+
+def base_placeholders() -> dict[str, ast.Expr]:
+ classifier = expand_default_channel_type_call(
+ [
+ ast.Field(chain=[name])
+ for name in ("campaign", "medium", "source", "referring_domain", "has_gclid", "has_fbclid", "gad_source")
+ ]
+ )
+ fingerprint = hashlib.sha256(classifier.to_hogql().encode()).hexdigest()
+ # The executor hashes before resolving $channel_type, so carry its identity in the input AST.
+ return {
+ "classifier_version": ast.Constant(value=f"{SESSION_CHANNEL_CLASSIFIER_VERSION}:{fingerprint}"),
+ "max_session_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),
+ }
+
+
+def precompute_window_days(team: Team) -> int:
+ return (
+ PRECOMPUTE_WINDOW_DAYS + team.marketing_analytics_config.attribution_window_days + SESSION_READ_REACHBACK_DAYS
+ )
+
+
+def ensure_marketing_sessions_precomputed(
+ team: Team,
+ time_range_start: datetime,
+ time_range_end: datetime,
+ *,
+ run_inserts: bool = True,
+ stale_while_revalidate_seconds: float | None = None,
+) -> LazyComputationResult:
+ modifiers = create_default_modifiers_for_team(team)
+ if modifiers.sessionTableVersion == SessionTableVersion.V1:
+ return LazyComputationResult(ready=False, job_ids=[], errors=["Session precompute requires sessions v2 or v3"])
+ if modifiers.sessionTableVersion == SessionTableVersion.AUTO:
+ modifiers.sessionTableVersion = SessionTableVersion.V2
+
+ windows = get_daily_windows(time_range_start, time_range_end)
+ if not windows:
+ return LazyComputationResult(ready=True, job_ids=[])
+
+ # Check cache hits too: a session can outgrow the scan budget after its window was materialized.
+ unsupported = execute_hogql_query(
+ UNSUPPORTED_SESSIONS_QUERY,
+ team,
+ modifiers=modifiers,
+ query_type="marketing_sessions_precompute_coverage",
+ placeholders={
+ "time_window_min": ast.Constant(value=windows[0][0]),
+ "time_window_max": ast.Constant(value=windows[-1][1]),
+ "max_session_seconds": ast.Constant(value=MAX_PRECOMPUTED_SESSION_SECONDS),
+ },
+ )
+ if unsupported.error:
+ return LazyComputationResult(ready=False, job_ids=[], errors=["Could not verify session precompute coverage"])
+ if unsupported.results:
+ return LazyComputationResult(
+ ready=False,
+ job_ids=[],
+ errors=["Session duration exceeds the precompute scan budget; use live attribution"],
+ )
+
+ return ensure_precomputed(
+ run_inserts=run_inserts,
+ stale_while_revalidate_seconds=stale_while_revalidate_seconds,
+ team=team,
+ insert_query=SESSIONS_INSERT_TEMPLATE,
+ time_range_start=time_range_start,
+ time_range_end=time_range_end,
+ # Sessions opened inside a window keep evolving until they close, so a job computed while
+ # 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,
+ max_window_days=CHUNK_DAYS,
+ settling_period_seconds=SESSION_SETTLING_PERIOD_SECONDS,
+ ),
+ table=LazyComputationTable.WEB_SESSIONS_DIMENSIONAL_PREAGGREGATED,
+ modifiers=modifiers,
+ cache_key_context={"modifiers": modifiers.model_dump_json(exclude_none=True)},
+ placeholders=base_placeholders(),
+ query_type="marketing_sessions_dimensional_insert",
+ )
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.py
new file mode 100644
index 000000000000..3beb52a90723
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_sessions_precompute.py
@@ -0,0 +1,211 @@
+import re
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import time_machine
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQueryModifiers, HogQLQueryResponse
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models import Team
+from posthog.schema_enums import SessionTableVersion
+from posthog.test.persons import create_person
+from posthog.uuidt import uuid7
+
+from products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (
+ SESSIONS_INSERT_TEMPLATE,
+ base_placeholders,
+ ensure_marketing_sessions_precomputed,
+)
+
+
+@time_machine.travel("2026-09-10T12:00:00Z", tick=False)
+class TestMarketingSessionsPrecompute(ClickhouseTestMixin, APIBaseTest):
+ @parameterized.expand([("UTC",), ("America/Santiago",), ("Asia/Kolkata",), ("Asia/Kathmandu",)])
+ def test_session_start_windows_use_utc_boundaries(self, timezone: str) -> None:
+ self.team.timezone = timezone
+ start = datetime(2026, 9, 1, tzinfo=UTC)
+ end = start + timedelta(days=1)
+ create_person(team=self.team, distinct_ids=["visitor"])
+ expected = []
+ for seconds in (-1, 0, 86399, 86400):
+ timestamp = start + timedelta(seconds=seconds)
+ session_id = uuid7(int(timestamp.timestamp() * 1000))
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event="$pageview",
+ timestamp=timestamp,
+ properties={"$session_id": str(session_id)},
+ )
+ if 0 <= seconds < 86400:
+ expected.append((session_id.int, timestamp.replace(minute=0, second=0)))
+
+ response = execute_hogql_query(
+ SESSIONS_INSERT_TEMPLATE,
+ self.team,
+ placeholders={
+ **base_placeholders(),
+ "time_window_min": ast.Constant(value=start),
+ "time_window_max": ast.Constant(value=end),
+ },
+ )
+ assert response.columns is not None
+ session_column = response.columns.index("session_id_v7")
+ bucket_column = response.columns.index("period_bucket")
+ assert sorted((row[session_column], row[bucket_column]) for row in response.results) == expected
+
+ @parameterized.expand(
+ [(version, hours) for version in (SessionTableVersion.V2, SessionTableVersion.V3) for hours in (2, 49, 97)]
+ )
+ def test_pageview_bounds_include_the_full_session(self, version: SessionTableVersion, duration_hours: int) -> None:
+ self.team.modifiers = {"sessionTableVersion": version}
+ start = datetime(2026, 9, 1, tzinfo=UTC)
+ end = start + timedelta(days=1)
+ first_pageview = start + timedelta(minutes=30) if duration_hours > 72 else end - timedelta(minutes=5)
+ last_pageview = first_pageview + timedelta(hours=duration_hours)
+ session_id = str(uuid7(int(first_pageview.timestamp() * 1000)))
+ create_person(team=self.team, distinct_ids=["visitor"])
+ for event, timestamp in [
+ ("$pageview", first_pageview),
+ ("$pageview", last_pageview),
+ ("purchase", last_pageview + timedelta(minutes=1)),
+ ]:
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event=event,
+ timestamp=timestamp,
+ properties={"$session_id": session_id, "utm_source": "google"},
+ )
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event="$pageview",
+ timestamp=end + timedelta(minutes=1),
+ properties={"$session_id": str(uuid7(int((end + timedelta(minutes=1)).timestamp() * 1000)))},
+ )
+ flush_persons_and_events()
+
+ result = ensure_marketing_sessions_precomputed(self.team, start + timedelta(hours=1), end)
+ if duration_hours > 72:
+ assert not result.ready
+ assert not result.job_ids
+ return
+ assert result.ready
+ assert sync_execute(
+ "SELECT session_id_v7, pageview_count 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": result.job_ids},
+ ) == [(uuid.UUID(session_id).int, 2)]
+
+ response = execute_hogql_query(
+ SESSIONS_INSERT_TEMPLATE,
+ self.team,
+ modifiers=HogQLQueryModifiers(sessionTableVersion=version),
+ placeholders={
+ **base_placeholders(),
+ "time_window_min": ast.Constant(value=start),
+ "time_window_max": ast.Constant(value=end),
+ },
+ )
+
+ assert len(response.results) == 1
+ assert response.columns is not None
+ row = dict(zip(response.columns, response.results[0]))
+ assert row["session_id_v7"] == uuid.UUID(session_id).int
+ assert row["min_event_timestamp"] == first_pageview
+ assert row["max_event_timestamp"] == last_pageview
+ assert row["pageview_count"] == 2
+
+ sessions_scans = re.findall(
+ r"FROM\s+raw_sessions(?:_v3)?\s+WHERE(.*?)GROUP BY", response.clickhouse or "", re.S
+ )
+ assert sessions_scans
+ for where in sessions_scans:
+ assert "session_timestamp" in where if version == SessionTableVersion.V3 else "session_id_v7, 80" in where
+
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event="$pageview",
+ timestamp=first_pageview + timedelta(hours=97),
+ properties={"$session_id": session_id},
+ )
+ flush_persons_and_events()
+ cached = ensure_marketing_sessions_precomputed(self.team, start, end, run_inserts=False)
+ assert not cached.ready
+ assert not cached.job_ids
+
+ @parameterized.expand([(SessionTableVersion.V2,), (SessionTableVersion.V3,)])
+ def test_window_refreshes_after_a_long_sessions_first_pageview(self, version: SessionTableVersion) -> None:
+ self.team.modifiers = {"sessionTableVersion": version}
+ start = time_machine.escape_hatch.datetime.datetime.now(UTC).replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) - timedelta(days=4)
+ end = start + timedelta(days=1)
+ opened_at = start + timedelta(hours=23)
+ session_id = str(uuid7(int(opened_at.timestamp() * 1000)))
+ create_person(team=self.team, distinct_ids=["long-session-visitor"])
+ _create_event(
+ team=self.team,
+ distinct_id="long-session-visitor",
+ event="$autocapture",
+ timestamp=opened_at,
+ properties={"$session_id": session_id},
+ )
+ flush_persons_and_events()
+
+ with time_machine.travel(start + timedelta(days=3, minutes=35), tick=False):
+ initial = ensure_marketing_sessions_precomputed(self.team, start, end)
+ assert initial.ready, initial.errors
+
+ with time_machine.travel(start + timedelta(days=3, hours=1), tick=False):
+ _create_event(
+ team=self.team,
+ distinct_id="long-session-visitor",
+ event="$pageview",
+ timestamp=start + timedelta(days=3, hours=1),
+ properties={"$session_id": session_id, "utm_campaign": "late-pageview"},
+ )
+ flush_persons_and_events()
+
+ with time_machine.travel(start + timedelta(days=4, minutes=1), tick=False):
+ 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, pageview_count 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},
+ ) == [(uuid.UUID(session_id).int, 1)]
+
+
+class TestSessionPrecomputeCoverageFailure(SimpleTestCase):
+ def test_query_error_does_not_prove_session_coverage(self) -> None:
+ with (
+ patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute.create_default_modifiers_for_team",
+ return_value=HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2),
+ ),
+ patch(
+ "products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute.execute_hogql_query",
+ return_value=HogQLQueryResponse(results=[], error="Coverage query failed"),
+ ),
+ ):
+ result = ensure_marketing_sessions_precomputed(
+ Team(id=1), datetime(2026, 9, 1, tzinfo=UTC), datetime(2026, 9, 2, tzinfo=UTC)
+ )
+ self.assertFalse(result.ready)
+ self.assertEqual(result.job_ids, [])
+ self.assertEqual(result.errors, ["Could not verify session precompute coverage"])
diff --git a/products/marketing_analytics/dags/marketing_sessions_precompute.py b/products/marketing_analytics/dags/marketing_sessions_precompute.py
new file mode 100644
index 000000000000..58d32fd5bf98
--- /dev/null
+++ b/products/marketing_analytics/dags/marketing_sessions_precompute.py
@@ -0,0 +1,136 @@
+"""Scheduled population of the marketing session-grain precompute table.
+
+The table is only useful for teams whose windows this job keeps warm. Configure
+`MARKETING_SESSIONS_PRECOMPUTE_TEAM_IDS` to enable the job; an empty or unset value disables it.
+"""
+
+import os
+from datetime import UTC, datetime, timedelta
+
+import dagster
+import structlog
+from prometheus_client import Counter
+
+from posthog.dags.common import JobOwners, check_for_concurrent_runs, chunk_ranges, skip_on_kill_switch
+from posthog.models import Team
+
+from products.marketing_analytics.backend.hogql_queries.marketing_sessions_precompute import (
+ CHUNK_DAYS,
+ PRECOMPUTE_WINDOW_DAYS,
+ ensure_marketing_sessions_precomputed,
+ precompute_window_days,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+SELECTED_TEAM_IDS_ENV_VAR = "MARKETING_SESSIONS_PRECOMPUTE_TEAM_IDS"
+
+MARKETING_SESSIONS_PRECOMPUTE_CHUNK_DONE = Counter(
+ "marketing_sessions_precompute_chunk_done_total",
+ "Daily chunks whose marketing session precompute window was ensured.",
+)
+MARKETING_SESSIONS_PRECOMPUTE_CHUNK_FAILED = Counter(
+ "marketing_sessions_precompute_chunk_failed_total",
+ "Daily chunks whose marketing session precompute failed, by error type.",
+ ["error_type"],
+)
+
+
+def get_selected_team_ids() -> list[int]:
+ raw = os.getenv(SELECTED_TEAM_IDS_ENV_VAR, "")
+ return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]
+
+
+def _ensure_for_team(
+ context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int
+) -> int:
+ """Keep each failed chunk isolated so the rest of the team's history can still warm."""
+ failures = 0
+ for chunk_start, chunk_end in chunk_ranges(start, end, chunk_days):
+ try:
+ result = ensure_marketing_sessions_precomputed(team, chunk_start, chunk_end)
+ # The executor reports a failed insert in the result rather than by raising, so a chunk
+ # that never materialized would otherwise be counted as done.
+ if not result.ready:
+ MARKETING_SESSIONS_PRECOMPUTE_CHUNK_FAILED.labels(
+ error_type="memory_exceeded" if result.memory_exceeded else "not_ready"
+ ).inc()
+ context.log.error(
+ f"marketing_sessions_precompute_not_ready team={team.pk} "
+ f"chunk=[{chunk_start}, {chunk_end}) errors={result.errors}"
+ )
+ failures += 1
+ continue
+ MARKETING_SESSIONS_PRECOMPUTE_CHUNK_DONE.inc()
+ except Exception as exc:
+ MARKETING_SESSIONS_PRECOMPUTE_CHUNK_FAILED.labels(error_type=type(exc).__name__).inc()
+ context.log.exception(
+ f"marketing_sessions_precompute_failed team={team.pk} chunk=[{chunk_start}, {chunk_end})"
+ )
+ failures += 1
+ return failures
+
+
+def ensure_marketing_sessions_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:
+ end = 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}"
+ )
+ if not team_ids:
+ context.log.info(f"marketing_sessions_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")
+ result = {"teams": 0, "failures": 0}
+ context.add_output_metadata(result)
+ return result
+
+ teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}
+
+ failures = 0
+ processed = 0
+ for team_id in team_ids:
+ team = teams_by_id.get(team_id)
+ 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))
+ failures += _ensure_for_team(context, team, start, end, CHUNK_DAYS)
+ processed += 1
+
+ context.log.info(f"marketing_sessions_precompute_complete teams={processed} failures={failures}")
+ result = {"teams": processed, "failures": failures}
+ context.add_output_metadata(result)
+ return result
+
+
+ description=(
+ f"Populates web_sessions_dimensional_preaggregated over the trailing "
+ f"{PRECOMPUTE_WINDOW_DAYS} display days plus team attribution lookback and session reachback for the teams in the {SELECTED_TEAM_IDS_ENV_VAR} allowlist. "
+ f"No-op when the allowlist is empty."
+ ),
+ tags={
+ "owner": JobOwners.TEAM_WEB_ANALYTICS.value,
+ "dagster/max_runtime": str(2 * 60 * 60),
+ },
+)
+def marketing_sessions_precompute_job() -> None:
+ ensure_marketing_sessions_precompute_op()
+
+
+ cron_schedule="35 * * * *",
+ job=marketing_sessions_precompute_job,
+ execution_timezone="UTC",
+ tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},
+)
+@skip_on_kill_switch
+def marketing_sessions_precompute_schedule(
+ context: dagster.ScheduleEvaluationContext,
+) -> "dagster.RunRequest | dagster.SkipReason":
+ skip_reason = check_for_concurrent_runs(context, tags={})
+ if skip_reason:
+ return skip_reason
+ return dagster.RunRequest()
diff --git a/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py
new file mode 100644
index 000000000000..a2283b0ec997
--- /dev/null
+++ b/products/marketing_analytics/dags/tests/test_marketing_sessions_precompute.py
@@ -0,0 +1,70 @@
+import os
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+import dagster
+from parameterized import parameterized
+
+from posthog.models import Team
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
+from products.marketing_analytics.dags.marketing_sessions_precompute import (
+ _ensure_for_team,
+ ensure_marketing_sessions_precompute_op,
+ get_selected_team_ids,
+)
+
+_ENSURE = "products.marketing_analytics.dags.marketing_sessions_precompute.ensure_marketing_sessions_precomputed"
+
+START = datetime(2026, 1, 1, tzinfo=UTC)
+END = datetime(2026, 1, 2, tzinfo=UTC)
+
+
+class TestMarketingSessionsPrecomputeDag(APIBaseTest):
+ @parameterized.expand([(None, []), ("", []), ("12, 34", [12, 34])])
+ def test_rollout_requires_an_explicit_allowlist(self, value: str | None, expected: list[int]) -> None:
+ with patch.dict(os.environ, {}, clear=False):
+ os.environ.pop("MARKETING_SESSIONS_PRECOMPUTE_TEAM_IDS", None)
+ if value is not None:
+ os.environ["MARKETING_SESSIONS_PRECOMPUTE_TEAM_IDS"] = value
+ assert get_selected_team_ids() == expected
+
+ def _run(self, side_effect: Callable[[Team, datetime, datetime], LazyComputationResult] | Exception) -> int:
+ with patch(_ENSURE, side_effect=side_effect):
+ return _ensure_for_team(MagicMock(), self.team, START, END, chunk_days=1)
+
+ def test_a_chunk_the_executor_reports_as_not_ready_counts_as_a_failure(self) -> None:
+ # The executor signals a failed insert through the result, not by raising. Counting that
+ # chunk as done leaves a window unmaterialized while the DAG reports a clean run.
+ result = LazyComputationResult(ready=False, job_ids=[], errors=["insert failed"])
+ assert self._run(lambda *args, **kwargs: result) == 1
+
+ def test_a_ready_chunk_counts_as_a_success(self) -> None:
+ result = LazyComputationResult(ready=True, job_ids=[])
+ assert self._run(lambda *args, **kwargs: result) == 0
+
+ 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:
+ config = self.team.marketing_analytics_config
+ config.attribution_window_days = lookback
+ config.save()
+ module = "products.marketing_analytics.dags.marketing_sessions_precompute"
+ with (
+ 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,
+ ),
+ patch(f"{module}._ensure_for_team", return_value=0) as ensure,
+ ):
+ 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)