: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
feat(marketing-analytics): warm precompute tables via dagster (#68276)
Javier Bahamondesd03da63fd554
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex de18a3e46bf3..e390e2a43214 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -142,6 +142,7 @@ jobs:- 'products/error_tracking/backend/**/*.py'- 'products/event_definitions/backend/**/*.py'- 'products/growth/backend/**/*.py'+ - 'products/marketing_analytics/backend/**/*.py'- 'products/ai_observability/backend/**/*.py'- 'products/llm_analytics/backend/**/*.py'- 'products/posthog_ai/backend/**/*.py'diff --git a/posthog/dags/common/__init__.py b/posthog/dags/common/__init__.pyindex a27e3f8d5936..ed112200e685 100644--- a/posthog/dags/common/__init__.py+++ b/posthog/dags/common/__init__.py@@ -1,9 +1,16 @@-from .common import check_for_concurrent_runs, dagster_tags, settings_with_log_comment, skip_if_already_running+from .common import (+ check_for_concurrent_runs,+ chunk_ranges,+ dagster_tags,+ settings_with_log_comment,+ skip_if_already_running,+)from .owners import JobOwners__all__ = ["JobOwners","check_for_concurrent_runs",+ "chunk_ranges","dagster_tags","settings_with_log_comment","skip_if_already_running",diff --git a/posthog/dags/common/common.py b/posthog/dags/common/common.pyindex 3c4cd4fbd45c..31717fe4d9b8 100644--- a/posthog/dags/common/common.py+++ b/posthog/dags/common/common.py@@ -1,5 +1,6 @@from collections.abc import Callablefrom contextlib import suppress+from datetime import datetime, timedeltafrom functools import wrapsfrom typing import Optional@@ -100,3 +101,19 @@ def skip_if_already_running(fn: Callable) -> Callable:return fn(context)return wrapper+++def chunk_ranges(start: datetime, end: datetime, chunk_days: int) -> list[tuple[datetime, datetime]]:+ """Split [start, end) into <=chunk_days sub-windows, newest first.++ Newest-first so recent data (which carries the shortest TTL and is requested+ most) is refreshed before older history is backfilled.+ """+ chunks = []+ cur_end = end+ step = timedelta(days=max(chunk_days, 1))+ while cur_end > start:+ cur_start = max(start, cur_end - step)+ chunks.append((cur_start, cur_end))+ cur_end = cur_start+ return chunksdiff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.pyindex 65bf553655de..0426486155e3 100644--- a/posthog/dags/locations/web_analytics.py+++ b/posthog/dags/locations/web_analytics.py@@ -2,6 +2,7 @@ import dagsterfrom posthog.settings import TEST+from products.marketing_analytics.dags import marketing_precomputefrom products.web_analytics.dags import (cache_favicons,cache_warming,@@ -24,6 +25,7 @@ schedules = [cache_warming.web_analytics_cache_warming_schedule,eager_web_analytics_precompute.web_analytics_eager_baseline_warming_schedule,web_dimensional_precompute.web_dimensional_precompute_schedule,+ marketing_precompute.marketing_precompute_schedule,cache_favicons.cache_authorized_domain_favicons_schedule,web_analytics_watchdog.web_analytics_watchdog_schedule,]@@ -54,6 +56,7 @@ defs = dagster.Definitions(cache_warming.web_analytics_cache_warming_job,eager_web_analytics_precompute.web_analytics_eager_baseline_warming_job,web_dimensional_precompute.web_dimensional_precompute_job,+ marketing_precompute.marketing_precompute_job,cache_favicons.cache_authorized_domain_favicons_job,],schedules=schedules,diff --git a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.pyindex c1445d16e657..263bda11a0e2 100644--- a/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/conversion_goal_processor.py@@ -42,6 +42,12 @@ LN2 = math.log(2) # ≈ 0.693, used in half-life formula: weight = exp(-ln(2) *# This follows the industry standard (Google Analytics, Adobe, Mixpanel all use 7-day half-life).TIME_DECAY_HALF_LIFE_DIVISOR = 4+# Freshness windows for the precompute read path. The Dagster warmer+# (products/marketing_analytics/dags/marketing_precompute.py) MUST drive ensure_precomputed with this+# exact schedule — otherwise the read path's freshness check would treat warmed rows as stale and+# recompute them inline, defeating the warm-up.+PRECOMPUTE_TTL_SECONDS = {"0d": 15 * 60, "1d": 60 * 60, "7d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}+logger = structlog.get_logger(__name__)@@ -349,12 +355,14 @@ class ConversionGoalProcessor:array_collection = self.build_array_collection_query(additional_conditions)return self.build_attribution_pipeline(array_collection)- def _should_use_precompute(self, date_from: Optional[datetime], date_to: Optional[datetime]) -> bool:- """Eligibility check: flag on, explicit date range, Events/Actions goal, no person/cohort filters."""- if not self.config.conversion_goal_precomputation_enabled:- return False- if date_from is None or date_to is None:- return False+ def is_goal_precomputable(self) -> bool:+ """Goal-level precompute eligibility, independent of the requesting user, date range, or flag.++ Shared by the live read path (`_should_use_precompute`) and the Dagster warmer+ (products/marketing_analytics/dags/marketing_precompute.py) so both agree on which goals get a+ conversions precompute job — otherwise the warmer could materialize jobs the read never asks for,+ or skip ones it does.+ """if self.goal.kind not in ("EventsNode", "ActionsNode"):return Falseif self.goal.kind == "EventsNode" and not self.goal.event:@@ -372,6 +380,18 @@ class ConversionGoalProcessor:# schema_map would read mismatched columns on the conversion side, so use the direct path.if any(self._resolve_field_name(field) != field.event_property for field in TRACKED_FIELDS):return False+ return True++ def _should_use_precompute(self, date_from: Optional[datetime], date_to: Optional[datetime]) -> bool:+ """Read-path eligibility: flag on, explicit date range, goal precomputable, no restricted props."""+ if not self.config.conversion_goal_precomputation_enabled:+ return False+ if date_from is None or date_to is None:+ return False+ if not self.is_goal_precomputable():+ return False+ # User-scoped: the precompute path materializes some event properties as plain columns, bypassing+ # per-user masking. When any is restricted for THIS user, fall back to the masked direct path.if self._precompute_properties_restricted_for_user():return Falsereturn True@@ -464,7 +484,6 @@ class ConversionGoalProcessor:collection through the existing pipeline (all modes). Neither precompute depends on attributionmode or window. Returns None if either set of jobs isn't ready — caller falls back."""- ttl_seconds = {"0d": 15 * 60, "1d": 60 * 60, "7d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}window = timedelta(days=self.config.attribution_window_days)# Touchpoints extend back by the attribution window; conversions only span the query range.@@ -473,7 +492,7 @@ class ConversionGoalProcessor:insert_query=build_touchpoints_precompute_query(),time_range_start=date_from - window,time_range_end=date_to,- ttl_seconds=ttl_seconds,+ ttl_seconds=PRECOMPUTE_TTL_SECONDS,table=LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,)if not touchpoints_result.ready:@@ -484,7 +503,7 @@ class ConversionGoalProcessor:insert_query=self.build_conversions_precompute_query(),time_range_start=date_from,time_range_end=date_to,- ttl_seconds=ttl_seconds,+ ttl_seconds=PRECOMPUTE_TTL_SECONDS,table=LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,)if not conversions_result.ready:diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.pyindex 36bef92e8aa7..8c9faa8e3c49 100644--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py@@ -55,6 +55,12 @@ COMPARE_PERIOD_FIELD = "_period"COMPARE_PERIOD_CURRENT = "current"COMPARE_PERIOD_PREVIOUS = "previous"+# TTL schedule for the native cost materialization: recent windows carry a short TTL so an hourly+# refresh keeps them fresh; older windows are computed once. Kept as a module constant so the Dagster+# warmer (products/marketing_analytics/dags/marketing_precompute.py) drives ensure_precomputed with the+# SAME freshness the read path expects — a mismatch would warm jobs the read then treats as stale.+COSTS_PRECOMPUTE_TTL_SECONDS = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}+class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC, Generic[ResponseType]):"""Base class for marketing analytics query runners with shared functionality."""@@ -244,7 +250,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,)return None- ttl_seconds = {"0d": 6 * 60 * 60, "1d": 24 * 60 * 60, "default": 7 * 24 * 60 * 60}+ ttl_seconds = COSTS_PRECOMPUTE_TTL_SECONDS# Per source: read the native table when it materializes, otherwise keep that one source on the# live S3 union. A single unmaterializable/syncing source must not force every source back to S3.materialized_source_ids: list = []diff --git a/products/marketing_analytics/dags/__init__.py b/products/marketing_analytics/dags/__init__.pynew file mode 100644index 000000000000..f129b95db83f--- /dev/null+++ b/products/marketing_analytics/dags/__init__.py@@ -0,0 +1 @@+"""Dagster jobs for marketing analytics (registered via posthog/dags/locations/web_analytics.py)."""diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.pynew file mode 100644index 000000000000..c83a6d2f3d5b--- /dev/null+++ b/products/marketing_analytics/dags/marketing_precompute.py@@ -0,0 +1,453 @@+"""Scheduled warming of the marketing analytics precompute tables.++Marketing analytics' first page load is dominated by cold reads the lazy-computation framework serves+from three config-agnostic / per-goal / per-source preaggregated tables — but only once the rows are+there. Nothing populates them ahead of time, so the first visitor after a cache miss pays the full+materialization inline (`ensure_precomputed` runs the INSERT synchronously on the request thread):++ * `marketing_touchpoints_preaggregated` — pageview/UTM side of conversion-goal attribution. Scans+ `$pageview` events over the range *plus* the attribution window (up to 90 extra days). Config-+ agnostic: one warmed window serves every goal / attribution mode for a team.+ * `marketing_conversions_preaggregated` — the conversion-event side. Per goal (the query embeds the+ goal's event/action + filters + math), independent of attribution mode/window.+ * `marketing_costs_preaggregated` — native ad-spend cost rows. Per source, materialized at each+ supported grain (campaign/ad_group/ad); replaces a cold S3 read of the platform tables.++This job moves that cost off the request path: per team it drives `ensure_precomputed` over a rolling+window so a later read is a cheap warm hit. Re-runs are cheap — already-fresh windows are skipped via+the framework's Postgres job tracking.++Gating mirrors the read path exactly. Touchpoints + conversions are warmed only when the team's+`marketing-analytics-precomputation` flag is on (the same flag `_should_use_precompute` checks) and the+team has conversion goals; costs only when `marketing-analytics-costs-precomputation` is on. Warming a+table the read won't consult would be wasted ClickHouse work, so both are evaluated from the same+`MarketingAnalyticsConfig.from_team` the runners use. The materialization INSERT is printed userless in+both paths, so a warmed job is byte-identical to the one a real read would create — same query hash,+same job, no poisoning and no access-control bypass.++Rollout mirrors the web dimensional precompute job: the audience is a small built-in list on PostHog+Cloud (`DEFAULT_ROLLOUT_TEAM_IDS`), fully overridable via the `MARKETING_PRECOMPUTE_TEAM_IDS` env var+(comma-separated team IDs; set it to empty to disable). Self-hosted defaults to no teams.+"""++import os+from collections.abc import Callable+from datetime import UTC, datetime, timedelta+from functools import partial++import dagster+import structlog+from prometheus_client import Counter++from posthog.schema import MarketingAnalyticsDrillDownLevel++from posthog.hogql import ast+from posthog.hogql.database.database import Database+from posthog.hogql.modifiers import create_default_modifiers_for_team++from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.cloud_utils import is_cloud+from posthog.dags.common import JobOwners, check_for_concurrent_runs, chunk_ranges+from posthog.models import Team+from posthog.models.team.team import DEFAULT_CURRENCY+from posthog.settings import TEST++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationTable,+ ensure_precomputed,+)+from products.marketing_analytics.backend.hogql_queries.adapters.base import QueryContext+from products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory+from products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import (+ PRECOMPUTE_TTL_SECONDS,+ ConversionGoalProcessor,+ build_touchpoints_precompute_query,+)+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner import (+ COSTS_PRECOMPUTE_TTL_SECONDS,+)+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig+from products.marketing_analytics.backend.hogql_queries.utils import convert_team_conversion_goals_to_objects+from products.warehouse_sources.backend.facade.models import DataWarehouseTable++logger = structlog.get_logger(__name__)++# Rolling window of user-facing lookback kept warm. A read for [date_from, date_to] ensures touchpoints+# over [date_from - attribution_window, date_to], so the effective touchpoints scan reaches back+# WINDOW + attribution_window days (see _ensure_touchpoints_for_team). Conversions and costs span the+# plain window (no attribution backfill).+PRECOMPUTE_WINDOW_DAYS = int(os.getenv("MARKETING_PRECOMPUTE_WINDOW_DAYS", "90"))++# Each ensure_precomputed call covers at most this many days. The framework merges a fully-missing+# range into ONE INSERT, so without chunking a cold backfill would scan the whole window in a single+# query — the real memory risk for a high-volume team. Chunking bounds each INSERT's scan; combined+# with the job's max_runtime and ensure_precomputed's idempotency, a cold backfill self-paces across+# runs. Defaults to 1 so every INSERT scans a single day.+PRECOMPUTE_CHUNK_DAYS = int(os.getenv("MARKETING_PRECOMPUTE_CHUNK_DAYS", "1"))++# Fallback attribution window when a team has no explicit config. Matches the model default and the+# 1–90 validation bound (TeamMarketingAnalyticsConfig.attribution_window_days).+DEFAULT_ATTRIBUTION_WINDOW_DAYS = 90++# Cost rows are materialized at each grain a source supports; the read side picks the matching grain per+# drill-down (a campaign-stats row is not the roll-up of its ads). Warming all three keeps every drill-+# down warm — campaign serves CHANNEL/SOURCE/CAMPAIGN/UTM, ad_group/ad serve their own levels.+COST_MATERIALIZATION_GRAINS = (+ MarketingAnalyticsDrillDownLevel.CAMPAIGN,+ MarketingAnalyticsDrillDownLevel.AD_GROUP,+ MarketingAnalyticsDrillDownLevel.AD,+)++# Built-in rollout audience used when the env var is unset: PostHog's internal dogfood project.+# Applied on PostHog Cloud only (see get_selected_team_ids).+DEFAULT_ROLLOUT_TEAM_IDS = [2]++# Comma-separated team IDs to warm. Overrides DEFAULT_ROLLOUT_TEAM_IDS; set to empty to disable.+SELECTED_TEAM_IDS_ENV_VAR = "MARKETING_PRECOMPUTE_TEAM_IDS"++_TOUCHPOINTS_TABLE_LABEL = LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED.value+_CONVERSIONS_TABLE_LABEL = LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED.value+_COSTS_TABLE_LABEL = LazyComputationTable.MARKETING_COSTS_PREAGGREGATED.value++MARKETING_PRECOMPUTE_CHUNK_DONE = Counter(+ "marketing_analytics_precompute_chunk_done_total",+ "Marketing precompute chunks ensured warm, by table.",+ ["table"],+)+MARKETING_PRECOMPUTE_CHUNK_FAILED = Counter(+ "marketing_analytics_precompute_chunk_failed_total",+ "Marketing precompute chunks that failed, by table and error type.",+ ["table", "error_type"],+)+MARKETING_PRECOMPUTE_TEAM_FAILED = Counter(+ "marketing_analytics_precompute_team_failed_total",+ "Per-team warming aborted by an unexpected setup/orchestration error, by stage.",+ ["stage"],+)+++def get_selected_team_ids() -> list[int]:+ """Resolve the team allowlist.++ The env var wins if set (even to empty): a comma-separated list, blank/invalid entries skipped.+ If unset, fall back to DEFAULT_ROLLOUT_TEAM_IDS — but only on PostHog Cloud; self-hosted defaults+ to none so the job never warms unrelated teams that happen to share those IDs.+ """+ raw = os.getenv(SELECTED_TEAM_IDS_ENV_VAR)+ if raw is None:+ return list(DEFAULT_ROLLOUT_TEAM_IDS) if is_cloud() else []+ return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]+++def _ensure_chunks(+ context: dagster.OpExecutionContext,+ team: Team,+ table: LazyComputationTable,+ build_insert_query: Callable[[], ast.SelectQuery | None],+ ttl_seconds: dict[str, int],+ start: datetime,+ end: datetime,+ chunk_days: int,+) -> int:+ """Drive ensure_precomputed for one (team, table, query) across the window, one bounded chunk at a+ time. `build_insert_query` is called fresh per chunk (the executor resolves the time-window+ placeholders in place). Failures per chunk are isolated so one bad chunk doesn't poison the rest;+ already-fresh chunks are cheap PG checks with no INSERT. Returns the failure count.+ """+ table_label = table.value+ failures = 0+ for chunk_start, chunk_end in chunk_ranges(start, end, chunk_days):+ insert_query = build_insert_query()+ if insert_query is None:+ continue # source can't materialize this chunk (deterministic) — nothing to warm+ try:+ result = ensure_precomputed(+ team=team,+ insert_query=insert_query,+ time_range_start=chunk_start,+ time_range_end=chunk_end,+ ttl_seconds=ttl_seconds,+ table=table,+ )+ except Exception:+ MARKETING_PRECOMPUTE_CHUNK_FAILED.labels(table=table_label, error_type="exception").inc()+ context.log.exception(+ f"marketing_precompute_failed team={team.pk} table={table_label} chunk=[{chunk_start}, {chunk_end})"+ )+ failures += 1+ continue++ if result.ready:+ MARKETING_PRECOMPUTE_CHUNK_DONE.labels(table=table_label).inc()+ else:+ MARKETING_PRECOMPUTE_CHUNK_FAILED.labels(table=table_label, error_type="not_ready").inc()+ context.log.warning(+ f"marketing_precompute_not_ready team={team.pk} table={table_label} "+ f"chunk=[{chunk_start}, {chunk_end}) errors={result.errors}"+ )+ failures += 1+ return failures+++def _ensure_touchpoints_for_team(+ context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int+) -> int:+ """Warm the config-agnostic touchpoints table over [start, end] (start already reaches back past the+ attribution window). One warmed window serves every conversion goal / attribution mode.+ """+ return _ensure_chunks(+ context,+ team,+ LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,+ build_touchpoints_precompute_query,+ PRECOMPUTE_TTL_SECONDS,+ start,+ end,+ chunk_days,+ )+++def _ensure_conversions_for_team(+ context: dagster.OpExecutionContext,+ team: Team,+ config: MarketingAnalyticsConfig,+ start: datetime,+ end: datetime,+ chunk_days: int,+) -> tuple[int, int]:+ """Warm the per-goal conversions table over [start, end] (no attribution backfill — the conversion+ event itself must fall in-range). One lazy job per precomputable goal; ineligible goals are skipped+ with the same rule the read path uses (is_goal_precomputable). Returns (goals_warmed, failures).+ """+ goals = convert_team_conversion_goals_to_objects(team.marketing_analytics_config.conversion_goals, team.pk)+ goals_warmed = 0+ failures = 0+ for index, goal in enumerate(goals):+ processor = ConversionGoalProcessor(goal=goal, index=index, team=team, config=config, user=None)+ if not processor.is_goal_precomputable():+ continue+ goals_warmed += 1+ failures += _ensure_chunks(+ context,+ team,+ LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,+ processor.build_conversions_precompute_query,+ PRECOMPUTE_TTL_SECONDS,+ start,+ end,+ chunk_days,+ )+ return goals_warmed, failures+++def _team_has_cost_sources(team: Team) -> bool:+ """Cheap indexed check for the prerequisite every cost adapter (native/external/self-managed) shares:+ at least one warehouse table. A safe superset — having tables doesn't guarantee a valid marketing+ source, but having none guarantees there isn't one, so we skip the ~550ms Database.create_for.+ """+ return DataWarehouseTable.objects.filter(team_id=team.pk, deleted=False).exists()+++def _ensure_costs_for_team(+ context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int+) -> tuple[int, int]:+ """Warm the per-source cost table at every supported grain over [start, end] (no attribution+ backfill). The database is built userless with warehouse access control bypassed — the materialization+ INSERT is printed userless anyway, so this yields the maximal (and read-identical) adapter set without+ a requesting user. Caller gates on _team_has_cost_sources, so at least one warehouse table exists.+ Returns (source_grain_pairs_warmed, failures).+ """+ # Database.create_for is ~550ms; build once and share across grains/sources for this team.+ database = Database.create_for(+ team=team,+ modifiers=create_default_modifiers_for_team(team),+ bypass_warehouse_access_control=True,+ )+ base_currency = team.base_currency or DEFAULT_CURRENCY+ warmed = 0+ failures = 0+ for grain in COST_MATERIALIZATION_GRAINS:+ ctx = QueryContext(+ date_range=None, # materialization filters on time_window placeholders, not the range+ team=team,+ base_currency=base_currency,+ drill_down_level=grain,+ database=database,+ )+ factory = MarketingSourceFactory(context=ctx)+ adapters = [a for a in factory.get_valid_adapters(factory.create_adapters()) if a.supports_level(grain)]+ for adapter in adapters:+ source_id = adapter.get_source_id()+ # A source that can't build a materialization query (e.g. missing table) does so deterministically+ # regardless of window — probe once, skip the whole source rather than every chunk.+ if adapter.build_materialization_query(source_id) is None:+ context.log.info(+ f"marketing_precompute_skip_source team={team.pk} table={_COSTS_TABLE_LABEL} "+ f"grain={grain.value} source_id={source_id} reason=unmaterializable"+ )+ continue+ warmed += 1+ failures += _ensure_chunks(+ context,+ team,+ LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,+ partial(adapter.build_materialization_query, source_id),+ COSTS_PRECOMPUTE_TTL_SECONDS,+ start,+ end,+ chunk_days,+ )+ return warmed, failures+++def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[str, int]:+ """Drive ensure_precomputed for the marketing precompute tables over the rolling window per team.++ Per team, gated on the same flags the read path checks: touchpoints + conversions when the+ conversion precompute flag is on and the team has goals; costs when the costs precompute flag is on+ and the team has warehouse tables. Each team's setup and each warming block is isolated: an+ unexpected error (e.g. a broken warehouse source failing Database.create_for) is logged and counted,+ never aborting the rest of the allowlist.++ `conversion_teams` / `costs_teams` count teams whose block ran to completion without an unexpected+ error (flag on + its raw material present — goals / warehouse tables), symmetric to each other. They+ are not success counts: per-chunk outcomes live in `failures` and the MARKETING_PRECOMPUTE_CHUNK_*+ metrics (a block can complete having warmed zero chunks, e.g. all goals ineligible).+ """+ # Tag every ClickHouse query this op drives (schema introspection during Database.create_for and the+ # materialization INSERTs) so warmer-driven load is attributable in query_log, distinct from the+ # on-read materialization the query runner triggers. The read path is tagged via its runner context.+ tag_queries(product=Product.MARKETING_ANALYTICS, feature=Feature.CACHE_WARMUP)++ end = datetime.now(UTC)+ team_ids = list(dict.fromkeys(get_selected_team_ids())) # dedupe so a repeated id doesn't warm twice+ context.log.info(+ f"marketing_precompute_start teams={len(team_ids)} window_days={PRECOMPUTE_WINDOW_DAYS} "+ f"chunk_days={PRECOMPUTE_CHUNK_DAYS}"+ )+ if not team_ids:+ context.log.info(f"marketing_precompute_noop ({SELECTED_TEAM_IDS_ENV_VAR} is empty)")+ result = {"teams": 0, "conversion_teams": 0, "costs_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+ conversion_teams = 0+ costs_teams = 0+ for team_id in team_ids:+ team = teams_by_id.get(team_id)+ if team is None:+ context.log.warning(f"marketing_precompute_team_missing team_id={team_id}")+ continue+ processed += 1++ try:+ # from_team evaluates both precompute flags once (cached on the team instance) — the same+ # evaluation the runners use, so the warmer and read path always agree on what to precompute.+ config = MarketingAnalyticsConfig.from_team(team)+ ma_config = team.marketing_analytics_config+ except Exception:+ MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="setup").inc()+ context.log.exception(f"marketing_precompute_setup_failed team={team_id}")+ failures += 1+ continue++ # Conversions and costs are independent products behind independent flags — isolate each so a+ # failure in one (e.g. Database.create_for on a broken warehouse source) still lets the other run.+ if config.conversion_goal_precomputation_enabled and ma_config.conversion_goals:+ try:+ attribution_window_days = ma_config.attribution_window_days or DEFAULT_ATTRIBUTION_WINDOW_DAYS+ # Reach back far enough that a read with up to PRECOMPUTE_WINDOW_DAYS of lookback is fully+ # covered including its touchpoints attribution backfill ([date_from - attribution_window, date_to]).+ tp_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS + attribution_window_days)+ failures += _ensure_touchpoints_for_team(context, team, tp_start, end, PRECOMPUTE_CHUNK_DAYS)+ # Conversions need no attribution backfill — the conversion event must fall in the query range.+ # Goals that aren't precomputable (non-Events/Actions, schema remaps, person/cohort filters) are+ # skipped inside; a team can warm touchpoints but no conversions if no goal qualifies.+ conv_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)+ _goals_warmed, conv_failures = _ensure_conversions_for_team(+ context, team, config, conv_start, end, PRECOMPUTE_CHUNK_DAYS+ )+ failures += conv_failures+ conversion_teams += 1+ except Exception:+ MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="conversions").inc()+ context.log.exception(f"marketing_precompute_conversions_failed team={team_id}")+ failures += 1++ # Symmetric with the conversions gate: costs' prerequisite "raw material" is warehouse tables+ # (every cost adapter needs one) the way conversions' is goals. Gating here also skips the+ # ~550ms Database.create_for for teams that can't have any cost source.+ if config.costs_precomputation_enabled:+ try:+ if _team_has_cost_sources(team):+ costs_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)+ _sources_warmed, costs_failures = _ensure_costs_for_team(+ context, team, costs_start, end, PRECOMPUTE_CHUNK_DAYS+ )+ failures += costs_failures+ costs_teams += 1 # after the block, mirroring conversion_teams: not counted if it raised+ except Exception:+ MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="costs").inc()+ context.log.exception(f"marketing_precompute_costs_failed team={team_id}")+ failures += 1++ context.log.info(+ f"marketing_precompute_complete teams={processed} conversion_teams={conversion_teams} "+ f"costs_teams={costs_teams} failures={failures}"+ )+ result = {+ "teams": processed,+ "conversion_teams": conversion_teams,+ "costs_teams": costs_teams,+ "failures": failures,+ }+ context.add_output_metadata(result)+ return result+++ description=(+ f"Warms the marketing analytics precompute tables ({_TOUCHPOINTS_TABLE_LABEL}, "+ f"{_CONVERSIONS_TABLE_LABEL}, {_COSTS_TABLE_LABEL}) over the trailing {PRECOMPUTE_WINDOW_DAYS} "+ f"days for the teams in the {SELECTED_TEAM_IDS_ENV_VAR} allowlist, gated per table on the same "+ f"precompute flags the read path checks, by driving the lazy-computation framework's "+ f"ensure_precomputed. No-op when the allowlist is empty. Re-runs only recompute expired windows."+ ),+ tags={+ "owner": JobOwners.TEAM_WEB_ANALYTICS.value,+ "dagster/max_runtime": str(2 * 60 * 60),+ },+)+def marketing_precompute_job():+ ensure_marketing_precompute_op()+++ # Hourly. Keeps the expensive part warm — the older windows / attribution backfill, computed once+ # then skipped. The today-slice carries a deliberately short TTL (PRECOMPUTE_TTL_SECONDS "0d" = 15m,+ # data still changing), so it can still be stale between hourly runs and recompute inline on read;+ # that slice is one day, not the backfill, so the cost is bounded. Offset from the web jobs.+ cron_schedule="35 * * * *",+ job=marketing_precompute_job,+ execution_timezone="UTC",+ tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},+)+def marketing_precompute_schedule(+ context: dagster.ScheduleEvaluationContext,+) -> "dagster.RunRequest | dagster.SkipReason":+ if not TEST:+ kill_switch_level = get_kill_switch_level()+ if kill_switch_level != KillSwitchLevel.OFF:+ context.log.info(f"Skipping due to ClickHouse kill switch: {kill_switch_level}")+ return dagster.SkipReason(f"ClickHouse kill switch is enabled ({kill_switch_level})")++ 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/__init__.py b/products/marketing_analytics/dags/tests/__init__.pynew file mode 100644index 000000000000..9399762eceeb--- /dev/null+++ b/products/marketing_analytics/dags/tests/__init__.py@@ -0,0 +1 @@+"""Tests for marketing analytics Dagster jobs."""diff --git a/products/marketing_analytics/dags/tests/test_marketing_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_precompute.pynew file mode 100644index 000000000000..c49b7e8da3ef--- /dev/null+++ b/products/marketing_analytics/dags/tests/test_marketing_precompute.py@@ -0,0 +1,465 @@+import os+from datetime import UTC, datetime++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++import dagster+from parameterized import parameterized++from posthog.schema import MarketingAnalyticsDrillDownLevel++from posthog.dags.common import chunk_ranges+from posthog.models import Organization, Team++from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationTable+from products.marketing_analytics.dags.marketing_precompute import (+ COST_MATERIALIZATION_GRAINS,+ DEFAULT_ROLLOUT_TEAM_IDS,+ PRECOMPUTE_CHUNK_DAYS,+ PRECOMPUTE_WINDOW_DAYS,+ SELECTED_TEAM_IDS_ENV_VAR,+ ensure_marketing_precompute_op,+ get_selected_team_ids,+ marketing_precompute_job,+)++_IS_CLOUD = "products.marketing_analytics.dags.marketing_precompute.is_cloud"+_ENSURE = "products.marketing_analytics.dags.marketing_precompute.ensure_precomputed"+_FF = "products.marketing_analytics.backend.hogql_queries.marketing_analytics_config.feature_enabled_or_false"+_DB = "products.marketing_analytics.dags.marketing_precompute.Database"+_FACTORY = "products.marketing_analytics.dags.marketing_precompute.MarketingSourceFactory"+_DWT = "products.marketing_analytics.dags.marketing_precompute.DataWarehouseTable"+# Patch chunking to a single chunk so call counts are deterministic in the op tests. Must exceed+# PRECOMPUTE_WINDOW_DAYS + the team's attribution window (default 90) to collapse to one chunk.+_SINGLE_CHUNK = "products.marketing_analytics.dags.marketing_precompute.PRECOMPUTE_CHUNK_DAYS"+_BIG_CHUNK = 100000++# Converts cleanly but is_goal_precomputable() rejects it (schema_map remaps a tracked UTM field, which+# the config-agnostic touchpoints table can't serve), so a team with only this goal warms touchpoints but+# no conversions.+_INELIGIBLE_GOAL = {+ "name": "Remapped",+ "kind": "EventsNode",+ "event": "signup",+ "conversion_goal_id": "goal_remapped",+ "conversion_goal_name": "Remapped",+ "schema_map": {"utm_campaign_name": "custom_campaign"},+ "properties": [],+}+# Fully-specified EventsNode goal that IS precomputable (see ConversionGoalProcessor.is_goal_precomputable).+_PRECOMPUTABLE_GOAL = {+ "name": "Signup", # required by validate_conversion_goals+ "kind": "EventsNode",+ "event": "signup",+ "conversion_goal_id": "goal_signup",+ "conversion_goal_name": "Signup",+ "math": "total",+ "schema_map": {},+ "properties": [],+}+++def _ready_mock() -> MagicMock:+ mock = MagicMock()+ mock.return_value.ready = True+ return mock+++def _flag_fn(*, conversion: bool = False, costs: bool = False):+ """Stand-in for feature_enabled_or_false that toggles the two precompute flags independently."""++ def _fn(flag, *args, **kwargs):+ return {+ "marketing-analytics-precomputation": conversion,+ "marketing-analytics-costs-precomputation": costs,+ }.get(flag, False)++ return _fn+++def _tables(ensure_mock) -> list[LazyComputationTable]:+ return [call.kwargs["table"] for call in ensure_mock.call_args_list]+++class TestChunkRanges:+ def test_splits_newest_first_and_bounds_each_chunk(self):+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 1, 31, tzinfo=UTC)+ chunks = chunk_ranges(start, end, 7)+ assert chunks[0][1] == end+ assert chunks[-1][0] == start+ assert all((c_end - c_start).days <= 7 for c_start, c_end in chunks)+ for newer, older in zip(chunks, chunks[1:]):+ assert older[1] == newer[0] # contiguous+ assert len(chunks) == 5 # 30 days / 7++ def test_single_chunk_when_window_fits(self):+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 1, 5, tzinfo=UTC)+ assert chunk_ranges(start, end, 90) == [(start, end)]++ def test_default_chunk_is_one_day(self):+ # Conservative default: each INSERT scans a single day to bound CH memory.+ assert PRECOMPUTE_CHUNK_DAYS == 1+++class TestGetSelectedTeamIds:+ @parameterized.expand(+ [+ ("comma_separated", "2, 47074 ,55348", [2, 47074, 55348]),+ ("skips_blank_and_invalid", " , abc, 2 ,", [2]),+ ]+ )+ def test_env_override_parses(self, _name, raw, expected):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: raw}):+ assert get_selected_team_ids() == expected++ def test_env_set_empty_disables(self):+ with patch(_IS_CLOUD, return_value=True), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):+ assert get_selected_team_ids() == []++ @parameterized.expand(+ [+ ("cloud_uses_default_rollout", True, DEFAULT_ROLLOUT_TEAM_IDS),+ ("off_cloud_is_empty", False, []),+ ]+ )+ def test_unset_behavior_depends_on_cloud(self, _name, cloud, expected):+ with patch(_IS_CLOUD, return_value=cloud), patch.dict(os.environ, {}, clear=False):+ os.environ.pop(SELECTED_TEAM_IDS_ENV_VAR, None)+ assert get_selected_team_ids() == expected+++class TestConversionWarming(APIBaseTest):+ """Touchpoints + conversions orchestration; ensure_precomputed is patched so no ClickHouse traffic."""++ def _make_team(self, name: str, *, goals: list | None = None) -> Team:+ org = Organization.objects.create(name=name)+ team = Team.objects.create(organization=org, name=f"{name}-team")+ if goals is not None:+ team.marketing_analytics_config.conversion_goals = goals+ team.marketing_analytics_config.save()+ return team++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_conversion_flag_off_skips_everything(self, ensure_mock):+ team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL])+ with (+ patch(_FF, _flag_fn(conversion=False, costs=False)),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_warms_touchpoints_but_no_conversions_for_ineligible_goal(self, ensure_mock):+ # _INELIGIBLE_GOAL remaps a tracked UTM field → not precomputable. Touchpoints (config-agnostic) still warms.+ team = self._make_team("A", goals=[_INELIGIBLE_GOAL])+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["conversion_teams"] == 1+ assert _tables(ensure_mock) == [LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED]++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_warms_conversions_for_precomputable_goal(self, ensure_mock):+ team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL])+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ ensure_marketing_precompute_op(dagster.build_op_context())+ tables = _tables(ensure_mock)+ assert LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED in tables+ assert LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED in tables++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_only_precomputable_goals_warm_conversions(self, ensure_mock):+ # One eligible + one ineligible goal → exactly one conversions job.+ team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL, _INELIGIBLE_GOAL])+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ ensure_marketing_precompute_op(dagster.build_op_context())+ conversion_calls = [+ t for t in _tables(ensure_mock) if t == LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED+ ]+ assert len(conversion_calls) == 1++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_skips_team_without_conversion_goals(self, ensure_mock):+ team = self._make_team("A", goals=None)+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_touchpoints_window_reaches_back_past_attribution_window(self, ensure_mock):+ team = self._make_team("A", goals=[_INELIGIBLE_GOAL])+ expected = PRECOMPUTE_WINDOW_DAYS + team.marketing_analytics_config.attribution_window_days+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ ensure_marketing_precompute_op(dagster.build_op_context())+ kwargs = ensure_mock.call_args_list[0].kwargs # touchpoints is warmed first+ assert (kwargs["time_range_end"] - kwargs["time_range_start"]).days == expected++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_conversions_window_has_no_attribution_backfill(self, ensure_mock):+ # Conversions span only the query window — the conversion event must fall in-range.+ team = self._make_team("A", goals=[_PRECOMPUTABLE_GOAL])+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ ensure_marketing_precompute_op(dagster.build_op_context())+ conv_call = next(+ c+ for c in ensure_mock.call_args_list+ if c.kwargs["table"] == LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED+ )+ assert (+ conv_call.kwargs["time_range_end"] - conv_call.kwargs["time_range_start"]+ ).days == PRECOMPUTE_WINDOW_DAYS++ @patch(_ENSURE, new_callable=_ready_mock)+ def test_chunking_issues_multiple_bounded_calls(self, ensure_mock):+ team = self._make_team("A", goals=[_INELIGIBLE_GOAL])+ with (+ patch(_SINGLE_CHUNK, 7),+ patch(_FF, _flag_fn(conversion=True)),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ ensure_marketing_precompute_op(dagster.build_op_context())+ assert ensure_mock.call_count > 1+ for call in ensure_mock.call_args_list:+ assert (call.kwargs["time_range_end"] - call.kwargs["time_range_start"]).days <= 7++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_one_team_failure_does_not_poison_others(self, ensure_mock):+ t1 = self._make_team("A", goals=[_INELIGIBLE_GOAL])+ t2 = self._make_team("B", goals=[_INELIGIBLE_GOAL])++ def side_effect(*args, **kwargs):+ if kwargs["team"].pk == t1.pk:+ raise RuntimeError("boom")+ return MagicMock(ready=True)++ ensure_mock.side_effect = side_effect+ with (+ patch(_FF, _flag_fn(conversion=True)),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{t1.pk},{t2.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["teams"] == 2+ assert result["failures"] == 1+ assert ensure_mock.call_count == 2++ @patch(_ENSURE)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ def test_not_ready_counts_as_failure(self, ensure_mock):+ ensure_mock.return_value = MagicMock(ready=False, errors=["still pending"])+ team = self._make_team("A", goals=[_INELIGIBLE_GOAL])+ with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["failures"] == 1++ @patch(_ENSURE, new_callable=_ready_mock)+ def test_empty_allowlist_is_a_noop(self, ensure_mock):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result == {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ def test_missing_team_is_skipped(self, ensure_mock):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: "999999999"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result == {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+ ensure_mock.assert_not_called()++ def test_job_has_owner_and_runtime_tags(self):+ tags = marketing_precompute_job.tags+ assert tags["owner"] == "team-web-analytics"+ assert "dagster/max_runtime" in tags+++class TestCostsWarming(APIBaseTest):+ """Costs orchestration; the source factory + database are patched so no warehouse/CH access is needed."""++ def _make_team(self, name: str) -> Team:+ org = Organization.objects.create(name=name)+ return Team.objects.create(organization=org, name=f"{name}-team")++ def _fake_adapter(self, *, materializable: bool = True) -> MagicMock:+ adapter = MagicMock()+ adapter.get_source_id.return_value = "src1"+ adapter.supports_level.return_value = True+ adapter.build_materialization_query.return_value = MagicMock() if materializable else None+ return adapter++ def _fake_factory(self, adapters: list) -> MagicMock:+ factory = MagicMock()+ factory.create_adapters.return_value = adapters+ factory.get_valid_adapters.side_effect = lambda a: a+ return factory++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_costs_flag_off_skips_costs(self, _db, ensure_mock):+ team = self._make_team("A")+ with patch(_FF, _flag_fn(costs=False)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_warms_costs_per_source_at_every_grain(self, _db, ensure_mock):+ # One source materializable at all 3 grains → one costs job per grain, independent of conversion goals.+ team = self._make_team("A")+ with (+ patch(_FF, _flag_fn(costs=True)),+ patch(_DWT), # team has warehouse tables → reach the factory (real emptiness tested separately)+ patch(_FACTORY, return_value=self._fake_factory([self._fake_adapter()])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["costs_teams"] == 1+ tables = _tables(ensure_mock)+ assert tables == [LazyComputationTable.MARKETING_COSTS_PREAGGREGATED] * len(COST_MATERIALIZATION_GRAINS)++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_unmaterializable_source_is_skipped(self, _db, ensure_mock):+ team = self._make_team("A")+ with (+ patch(_FF, _flag_fn(costs=True)),+ patch(_DWT), # team has warehouse tables → reach the factory (real emptiness tested separately)+ patch(_FACTORY, return_value=self._fake_factory([self._fake_adapter(materializable=False)])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ # Team has warehouse tables (patched) so costs was attempted (costs_teams=1); the unmaterializable+ # source just produces no ensure_precomputed calls — nothing is warmed.+ assert result["costs_teams"] == 1+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_costs_database_built_userless_with_access_control_bypassed(self, db_mock, ensure_mock):+ # The safety property: warmer materializes with the same userless, access-bypassed database the+ # read path's INSERT is printed with — so a warmed cost job is identical to the one a read creates.+ team = self._make_team("A")+ with (+ patch(_FF, _flag_fn(costs=True)),+ patch(_DWT), # team has warehouse tables → reach the factory (real emptiness tested separately)+ patch(_FACTORY, return_value=self._fake_factory([self._fake_adapter()])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ ensure_marketing_precompute_op(dagster.build_op_context())+ _, kwargs = db_mock.create_for.call_args+ assert kwargs["bypass_warehouse_access_control"] is True+ assert "user" not in kwargs # no requesting user++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_costs_filters_sources_by_supported_grain(self, _db, ensure_mock):+ # src_all materializes at every grain; src_campaign only at campaign → 3 + 1 = 4 ensure calls.+ team = self._make_team("A")+ src_all = self._fake_adapter()+ src_all.get_source_id.return_value = "src_all"+ src_campaign = self._fake_adapter()+ src_campaign.get_source_id.return_value = "src_campaign"+ src_campaign.supports_level.side_effect = lambda g: g == MarketingAnalyticsDrillDownLevel.CAMPAIGN+ with (+ patch(_FF, _flag_fn(costs=True)),+ patch(_DWT), # team has warehouse tables → reach the factory (real emptiness tested separately)+ patch(_FACTORY, return_value=self._fake_factory([src_all, src_campaign])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ ensure_marketing_precompute_op(dagster.build_op_context())+ assert ensure_mock.call_count == 4++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_setup_failure_on_one_team_does_not_halt_the_rest(self, db_mock, ensure_mock):+ # A broken warehouse source failing Database.create_for for one team must not abort the op or+ # skip later teams in the allowlist — the failure is counted, the rest still warm.+ broken = self._make_team("A")+ healthy = self._make_team("B")++ def create_for(*, team, **kwargs):+ if team.pk == broken.pk:+ raise RuntimeError("broken warehouse source")+ return MagicMock()++ db_mock.create_for.side_effect = create_for+ with (+ patch(_FF, _flag_fn(costs=True)),+ patch(_DWT), # team has warehouse tables → reach the factory (real emptiness tested separately)+ patch(_FACTORY, return_value=self._fake_factory([self._fake_adapter()])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{broken.pk},{healthy.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["teams"] == 2+ assert result["failures"] == 1 # broken team's costs stage+ assert result["costs_teams"] == 1 # healthy team still warmed+ warmed_teams = {c.kwargs["team"].pk for c in ensure_mock.call_args_list}+ assert warmed_teams == {healthy.pk}++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_costs_skipped_when_team_has_no_warehouse_tables(self, db_mock, ensure_mock):+ # No DataWarehouseTable (real emptiness) → skip before the ~550ms Database.create_for; every cost+ # adapter needs a warehouse table, so there is nothing to warm.+ team = self._make_team("A")+ with patch(_FF, _flag_fn(costs=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["costs_teams"] == 0+ db_mock.create_for.assert_not_called()+ ensure_mock.assert_not_called()++ @patch(_ENSURE, new_callable=_ready_mock)+ @patch(_SINGLE_CHUNK, _BIG_CHUNK)+ @patch(_DB)+ def test_both_flags_on_warm_conversions_and_costs_for_one_team(self, _db, ensure_mock):+ # Both products, one team, one pass: the two independent blocks each run and each counter fires.+ team = self._make_team("A")+ team.marketing_analytics_config.conversion_goals = [_PRECOMPUTABLE_GOAL]+ team.marketing_analytics_config.save()+ with (+ patch(_FF, _flag_fn(conversion=True, costs=True)),+ patch(_DWT),+ patch(_FACTORY, return_value=self._fake_factory([self._fake_adapter()])),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: f"{team.pk}"}),+ ):+ result = ensure_marketing_precompute_op(dagster.build_op_context())+ assert result["conversion_teams"] == 1+ assert result["costs_teams"] == 1+ assert set(_tables(ensure_mock)) == {+ LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED,+ LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED,+ LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,+ }+++class TestSchedule:+ def test_skips_when_clickhouse_kill_switch_engaged(self):+ # Production safety: never add warming load to ClickHouse while a kill switch is engaged.+ from products.marketing_analytics.dags import marketing_precompute as mp++ non_off = next(level for level in mp.KillSwitchLevel if level != mp.KillSwitchLevel.OFF)+ with (+ patch("products.marketing_analytics.dags.marketing_precompute.TEST", False),+ patch("products.marketing_analytics.dags.marketing_precompute.get_kill_switch_level", return_value=non_off),+ ):+ result = mp.marketing_precompute_schedule(dagster.build_schedule_context())+ assert isinstance(result, dagster.SkipReason)diff --git a/products/web_analytics/dags/web_dimensional_precompute.py b/products/web_analytics/dags/web_dimensional_precompute.pyindex ac44a0fca4df..897e4c1ac9fd 100644--- a/products/web_analytics/dags/web_dimensional_precompute.py+++ b/products/web_analytics/dags/web_dimensional_precompute.py@@ -28,7 +28,7 @@ import structlogfrom prometheus_client import Counterfrom posthog.cloud_utils import is_cloud-from posthog.dags.common import JobOwners+from posthog.dags.common import JobOwners, chunk_rangesfrom posthog.models import Teamfrom products.web_analytics.backend.hogql_queries.web_dimensional_precompute import (@@ -79,22 +79,6 @@ def get_selected_team_ids() -> list[int]:return [int(part.strip()) for part in raw.split(",") if part.strip().isdigit()]-def chunk_ranges(start: datetime, end: datetime, chunk_days: int) -> list[tuple[datetime, datetime]]:- """Split [start, end) into <=chunk_days sub-windows, newest first.-- Newest-first so recent data (which carries the shortest TTL and is requested- most) is refreshed before older history is backfilled.- """- chunks = []- cur_end = end- step = timedelta(days=max(chunk_days, 1))- while cur_end > start:- cur_start = max(start, cur_end - step)- chunks.append((cur_start, cur_end))- cur_end = cur_start- return chunks--WEB_DIMENSIONAL_PRECOMPUTE_TEAM_DONE = Counter("web_dimensional_precompute_team_done_total","Teams whose dimensional precompute window was ensured, by table.",