: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
perf(marketing-analytics): fan the warmer out across processes (#106966)
Lucas Ricoyf7e51e14302f
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 0ae92253fca4..7e37f3871102 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -7,6 +7,7 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom enum import StrEnum+from typing import TYPE_CHECKINGfrom zoneinfo import ZoneInfofrom django.db import DEFAULT_DB_ALIAS@@ -50,6 +51,9 @@ from products.analytics_platform.backend.lazy_computation.computation_notificati)from products.analytics_platform.backend.models import PreaggregationJob+if TYPE_CHECKING:+ from posthog.hogql.database.database import Database+logger = structlog.get_logger(__name__)# Default TTL for lazy computed data (how long before ClickHouse deletes it)@@ -1612,6 +1616,7 @@ def ensure_precomputed(end_is_data_horizon: bool = False,cache_key_context: dict[str, str] | None = None,read_after_write: bool = True,+ database: "Database | None" = None,) -> LazyComputationResult:"""Ensure lazy-computed data exists for the given query and time range.@@ -1691,6 +1696,11 @@ def ensure_precomputed(newest parts until replication catches up — usually fast, butwith no guaranteed bound. The post-build settle wait covers thebuilder's own read-back; later readers accept the residual risk.+ database: A prebuilt HogQL database to print the INSERT against. Without it, every+ INSERT builds the team's database from scratch, which costs Postgres reads+ and CPU per job. A caller that ensures many windows for one team should+ build it once, userless with warehouse access control bypassed and with+ the same `modifiers`, and pass it here.Returns:ComputationResult with job_ids that can be used to query the data@@ -1761,6 +1771,7 @@ def ensure_precomputed(table=table,base_placeholders=base_placeholders,modifiers=modifiers,+ database=database,)print_end = time.monotonic()set_ch_query_started(job.id)@@ -1851,6 +1862,7 @@ def _build_manual_insert_sql(table: LazyComputationTable,base_placeholders: dict[str, ast.Expr] | None = None,modifiers: HogQLQueryModifiers | None = None,+ database: "Database | None" = None,) -> tuple[str, dict]:"""Build INSERT SQL for manual lazy computation.@@ -1902,6 +1914,7 @@ def _build_manual_insert_sql(limit_top_select=False,modifiers=modifiers if modifiers is not None else create_default_modifiers_for_team(team),bypass_warehouse_access_control=True,+ database=database,)select_sql, _ = prepare_and_print_ast(query,diff --git a/products/marketing_analytics/dags/marketing_precompute.py b/products/marketing_analytics/dags/marketing_precompute.pyindex 631b785609eb..71adaf77f827 100644--- a/products/marketing_analytics/dags/marketing_precompute.py+++ b/products/marketing_analytics/dags/marketing_precompute.py@@ -34,9 +34,10 @@ only. `MARKETING_PRECOMPUTE_ACTIVE_DAYS` tunes the `auto` activity window.import osimport timefrom collections.abc import Callable-from concurrent.futures import ThreadPoolExecutor, as_completed+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, waitfrom datetime import UTC, datetime, timedeltafrom functools import partial+from itertools import islicefrom typing import NamedTuplefrom django.db import connections@@ -120,10 +121,16 @@ ACTIVE_DAYS_ENV_VAR = "MARKETING_PRECOMPUTE_ACTIVE_DAYS"DEFAULT_ACTIVE_DAYS = 30ACTIVE_TEAMS_QUERY_TIMEOUT_SECONDS = 60-# Teams warmed in parallel per run. Warming is I/O-bound (ClickHouse INSERTs), so threads overlap the-# waits; the ceiling keeps concurrent ClickHouse load and DB connections bounded. Tunable per environment.+# Teams warmed in parallel per shard. Threads overlap the ClickHouse INSERT waits; shards x this bounds the+# concurrent INSERTs and DB connections across the run. Tunable per environment.TEAM_CONCURRENCY_ENV_VAR = "MARKETING_PRECOMPUTE_TEAM_CONCURRENCY"-DEFAULT_TEAM_CONCURRENCY = 8+DEFAULT_TEAM_CONCURRENCY = 4++# Processes the job fans teams out into. Each shard prints HogQL on its own core; the run pod requests+# 6 CPUs, so more shards than that only contend for cores.+SHARDS_ENV_VAR = "MARKETING_PRECOMPUTE_SHARDS"+DEFAULT_SHARDS = 6+MAX_SHARDS = 16_TOUCHPOINTS_TABLE_LABEL = LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED.value_CONVERSIONS_TABLE_LABEL = LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED.value@@ -234,6 +241,7 @@ def _ensure_chunks(start: datetime,end: datetime,chunk_days: int,+ database: Database | None = None,) -> int:"""Drive ensure_precomputed for one (team, table, query) across the window, one bounded chunk at atime. `build_insert_query` is called fresh per chunk (the executor resolves the time-window@@ -262,6 +270,7 @@ def _ensure_chunks(time_range_end=chunk_end,ttl_seconds=ttl_seconds,table=table,+ database=database,)except Exception:ensure_seconds += time.monotonic() - ensure_started@@ -297,6 +306,7 @@ def _ensure_touchpoints_for_team(start: datetime,end: datetime,chunk_days: int,+ database: Database | None = None,) -> int:"""Warm the goal-agnostic touchpoints table over [start, end] (start already reaches back past theattribution window). One warmed window serves every conversion goal / attribution mode.@@ -316,6 +326,7 @@ def _ensure_touchpoints_for_team(start,end,chunk_days,+ database,)@@ -328,6 +339,7 @@ def _ensure_conversions_for_team(start: datetime,end: datetime,chunk_days: int,+ database: Database | None = None,) -> tuple[int, int]:"""Warm the per-goal conversions table over [start, end] (no attribution backfill — the conversionevent itself must fall in-range). One lazy job per precomputable goal; ineligible goals are skipped@@ -357,10 +369,25 @@ def _ensure_conversions_for_team(start,end,chunk_days,+ database,)return goals_warmed, failures+def _build_team_database(team: Team) -> Database:+ """The HogQL database every INSERT for this team prints against.++ Built userless with warehouse access control bypassed and the default modifiers, which is what the+ executor builds per INSERT when it gets none. Building it once per team instead of once per bucket+ removes most of the warmer's CPU, which the process otherwise spends rebuilding the same schema.+ """+ return Database.create_for(+ team=team,+ modifiers=create_default_modifiers_for_team(team),+ bypass_warehouse_access_control=True,+ )++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@@ -370,7 +397,12 @@ def _team_has_cost_sources(team: Team) -> bool:def _ensure_costs_for_team(- context: dagster.OpExecutionContext, team: Team, start: datetime, end: datetime, chunk_days: int+ context: dagster.OpExecutionContext,+ team: Team,+ start: datetime,+ end: datetime,+ chunk_days: int,+ database: Database | None = None,) -> tuple[int, int]:"""Warm the per-source cost table at every supported grain over [start, end] (no attributionbackfill). The database is built userless with warehouse access control bypassed — the materialization@@ -379,11 +411,8 @@ def _ensure_costs_for_team(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,- )+ if database is None:+ database = _build_team_database(team)base_currency = team.base_currency or DEFAULT_CURRENCYwarmed = 0failures = 0@@ -417,6 +446,7 @@ def _ensure_costs_for_team(start,end,chunk_days,+ database,)return warmed, failures@@ -435,6 +465,7 @@ class _TeamWarmPlan(NamedTuple):attribution_window_days: intfilter_test_accounts: boolwarm_costs: bool+ database: Database | None = None@propertydef warm_conversions(self) -> bool:@@ -509,7 +540,7 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: da# covered including its touchpoints attribution backfill ([date_from - attribution_window, date_to]).tp_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS + plan.attribution_window_days)failures += _ensure_touchpoints_for_team(- context, team, plan.filter_test_accounts, tp_start, end, PRECOMPUTE_CHUNK_DAYS+ context, team, plan.filter_test_accounts, tp_start, end, PRECOMPUTE_CHUNK_DAYS, plan.database)# 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@@ -524,6 +555,7 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: daconv_start,end,PRECOMPUTE_CHUNK_DAYS,+ plan.database,)failures += conv_failuresconversion_teams += 1@@ -536,7 +568,7 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: datry:costs_start = end - timedelta(days=PRECOMPUTE_WINDOW_DAYS)_sources_warmed, costs_failures = _ensure_costs_for_team(- context, team, costs_start, end, PRECOMPUTE_CHUNK_DAYS+ context, team, costs_start, end, PRECOMPUTE_CHUNK_DAYS, plan.database)failures += costs_failurescosts_teams += 1 # after the block, mirroring conversion_teams: not counted if it raised@@ -553,16 +585,19 @@ def _warm_team(context: dagster.OpExecutionContext, plan: _TeamWarmPlan, end: dareturn _WarmCounts(conversion_teams, costs_teams, 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.+def _empty_result() -> dict[str, int]:+ return {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}+++def _warm_teams(context: dagster.OpExecutionContext, team_ids: list[int], end: datetime) -> dict[str, int]:+ """Warm the marketing precompute tables over the rolling window for `team_ids`.Teams are warmed in parallel (`_warm_team` in a thread pool, `MARKETING_PRECOMPUTE_TEAM_CONCURRENCY`- workers), since warming is I/O-bound on ClickHouse and the active fleet is hundreds of teams. Each- team warms touchpoints + conversions when it has conversion goals, deliberately independent of the- `marketing-analytics-precomputation` read flag so the tables are populated before the flip; costs- stay gated on the costs precompute flag plus the team having warehouse tables. Every team, and each- warming block within it, is isolated — one failure never aborts the rest.+ workers), which overlaps the ClickHouse INSERTs. Printing each INSERT is CPU-bound Python, so real+ parallelism across teams comes from running shards in separate processes (see+ `warm_marketing_precompute_shard_op`). Each team warms touchpoints + conversions when it has+ conversion goals; costs stay gated on the costs precompute flag plus the team having warehouse tables.+ Every team, and each warming block within it, is isolated — one failure never aborts the rest.`conversion_teams` / `costs_teams` count teams whose block ran to completion without an unexpectederror (its raw material present — goals / warehouse tables), symmetric to each other. They@@ -571,18 +606,8 @@ def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict["""# Tag the op thread too (workers re-tag themselves). Keeps any op-thread ClickHouse work attributable.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+ return _empty_result()teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}teams = [teams_by_id[team_id] for team_id in team_ids if team_id in teams_by_id]@@ -601,57 +626,149 @@ def ensure_marketing_precompute_op(context: dagster.OpExecutionContext) -> dict[else:plans.append(plan)- concurrency = int(os.getenv(TEAM_CONCURRENCY_ENV_VAR, str(DEFAULT_TEAM_CONCURRENCY)))+ concurrency = max(1, int(os.getenv(TEAM_CONCURRENCY_ENV_VAR, str(DEFAULT_TEAM_CONCURRENCY))))context.log.info(f"marketing_precompute_planned plans={len(plans)} concurrency={concurrency} "f"plan_ms={round((time.monotonic() - plan_started) * 1000)}")conversion_teams = 0costs_teams = 0- if plans:- warm_started = time.monotonic()- with ThreadPoolExecutor(max_workers=max(1, min(concurrency, len(plans))), thread_name_prefix="ma_warm") as pool:- futures = [pool.submit(_warm_team, context, plan, end) for plan in plans]- for done, future in enumerate(as_completed(futures), start=1):+ done = 0+ warm_started = time.monotonic()++ def with_database(plan: _TeamWarmPlan) -> _TeamWarmPlan:+ # Built on the main thread, because it reads Postgres and worker threads must not.+ if not (plan.warm_conversions or plan.warm_costs):+ return plan # nothing to warm, so skip the database build+ try:+ return plan._replace(database=_build_team_database(plan.team))+ except Exception:+ # Without a shared database each block builds its own, as before, so one failure here+ # does not leave both conversions and costs cold.+ MARKETING_PRECOMPUTE_TEAM_FAILED.labels(stage="database").inc()+ logger.exception("marketing_precompute_database_failed", team_id=plan.team.pk)+ return plan++ with ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix="ma_warm") as pool:+ # A sliding window of `concurrency` teams: when one finishes, the next team's database is built+ # and submitted, so a slow team never idles the other workers and at most `concurrency`+ # databases are held in memory.+ pending = iter(plans)+ in_flight = {+ pool.submit(_warm_team, context, with_database(plan), end) for plan in islice(pending, concurrency)+ }+ while in_flight:+ finished, in_flight = wait(in_flight, return_when=FIRST_COMPLETED)+ for future in finished:conv_inc, costs_inc, fail_inc = future.result()conversion_teams += conv_inccosts_teams += costs_incfailures += fail_inc+ done += 1context.log.info(f"marketing_precompute_progress done={done}/{len(plans)} "f"elapsed_s={round(time.monotonic() - warm_started)}")+ next_plan = next(pending, None)+ if next_plan is not None:+ in_flight.add(pool.submit(_warm_team, context, with_database(next_plan), end))context.log.info(f"marketing_precompute_complete teams={len(teams)} conversion_teams={conversion_teams} "f"costs_teams={costs_teams} failures={failures}")- result = {+ return {"teams": len(teams),"conversion_teams": conversion_teams,"costs_teams": costs_teams,"failures": failures,}+++def warm_selected_teams(context: dagster.OpExecutionContext) -> dict[str, int]:+ """Warm every selected team in this process. The job fans out instead; this is the single-process path."""+ return _warm_teams(context, list(dict.fromkeys(get_selected_team_ids())), datetime.now(UTC))+++def _shard_count() -> int:+ return min(MAX_SHARDS, max(1, int(os.getenv(SHARDS_ENV_VAR, str(DEFAULT_SHARDS)))))++[email protected](out=dagster.DynamicOut(dict))+def split_marketing_precompute_teams_op(context: dagster.OpExecutionContext):+ """Select the teams to warm and fan them out into team-disjoint shards.++ Each shard becomes its own mapped op, a separate subprocess with its own GIL. Printing each INSERT is+ CPU-bound Python, so threads inside one process queue on the interpreter and real parallelism needs+ processes. Every shard shares one `end`, so all shards warm the same windows.+ """+ team_ids = list(dict.fromkeys(get_selected_team_ids())) # dedupe so a repeated id doesn't warm twice+ shards = _shard_count()+ context.log.info(+ f"marketing_precompute_start teams={len(team_ids)} shards={shards} 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)")+ return+ end = datetime.now(UTC).isoformat()+ buckets: dict[int, list[int]] = {}+ for team_id in team_ids:+ buckets.setdefault(team_id % shards, []).append(team_id)+ for shard_index in sorted(buckets):+ yield dagster.DynamicOutput({"team_ids": buckets[shard_index], "end": end}, mapping_key=f"shard_{shard_index}")+++def warm_marketing_precompute_shard_op(context: dagster.OpExecutionContext, shard: dict) -> dict[str, int]:+ result = _warm_teams(context, shard["team_ids"], datetime.fromisoformat(shard["end"]))context.add_output_metadata(result)return result+def summarize_marketing_precompute_op(context: dagster.OpExecutionContext, results: list[dict]) -> dict[str, int]:+ total = _empty_result()+ for result in results:+ for key in total:+ total[key] += result[key]+ context.log.info(+ f"marketing_precompute_summary shards={len(results)} teams={total['teams']} "+ f"conversion_teams={total['conversion_teams']} costs_teams={total['costs_teams']} "+ f"failures={total['failures']}"+ )+ context.add_output_metadata(total)+ return total++@dagster.job(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} audience, warming teams in parallel and "- f"gating per table on the same precompute flags the read "+ f"days for the teams in the {SELECTED_TEAM_IDS_ENV_VAR} audience, fanning teams out across "+ f"processes and gating per table on the same precompute flags the read "f"path checks, by driving the lazy-computation framework's ensure_precomputed. Re-runs only "f"recompute expired windows."),tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value,"dagster/max_runtime": str(2 * 60 * 60),+ # One subprocess per shard, each printing HogQL on its own core, so the run pod needs CPU for the+ # shards and memory for that many Django interpreters. Matches the web cache warming job.+ "dagster-k8s/config": {+ "container_config": {+ "resources": {+ "requests": {"cpu": "6000m", "memory": "12Gi"},+ "limits": {"memory": "12Gi"},+ }+ }+ },},)def marketing_precompute_job():- ensure_marketing_precompute_op()+ summarize_marketing_precompute_op(+ split_marketing_precompute_teams_op().map(warm_marketing_precompute_shard_op).collect()+ )@dagster.schedule(diff --git a/products/marketing_analytics/dags/tests/test_marketing_precompute.py b/products/marketing_analytics/dags/tests/test_marketing_precompute.pyindex 3b5051f27878..5c5462fac0f9 100644--- a/products/marketing_analytics/dags/tests/test_marketing_precompute.py+++ b/products/marketing_analytics/dags/tests/test_marketing_precompute.py@@ -24,9 +24,12 @@ from products.marketing_analytics.dags.marketing_precompute import (PRECOMPUTE_CHUNK_DAYS,PRECOMPUTE_WINDOW_DAYS,SELECTED_TEAM_IDS_ENV_VAR,- ensure_marketing_precompute_op,+ SHARDS_ENV_VAR,+ TEAM_CONCURRENCY_ENV_VAR,get_selected_team_ids,marketing_precompute_job,+ split_marketing_precompute_teams_op,+ warm_selected_teams,)_ENSURE = "products.marketing_analytics.dags.marketing_precompute.ensure_precomputed"@@ -127,6 +130,25 @@ class TestGetSelectedTeamIds:assert get_selected_team_ids() == []+class TestShardSplit:+ @parameterized.expand(+ [("one_shard", "1", 1), ("more_teams_than_shards", "3", 3), ("more_shards_than_teams", "8", 5)]+ )+ def test_shards_are_team_disjoint_and_cover_every_team(self, _name, shards, expected_shards):+ # A team in two shards would be warmed twice in parallel; a dropped team would stay cold.+ team_ids = [3, 4, 5, 6, 7]+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ",".join(map(str, team_ids)), SHARDS_ENV_VAR: shards}):+ outputs = list(split_marketing_precompute_teams_op(dagster.build_op_context()))++ assert len(outputs) == expected_shards+ assert sorted(tid for out in outputs for tid in out.value["team_ids"]) == team_ids+ assert len({out.value["end"] for out in outputs}) == 1++ def test_empty_audience_yields_no_shards(self):+ with patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ""}):+ assert list(split_marketing_precompute_teams_op(dagster.build_op_context())) == []++class TestConversionWarming(APIBaseTest):"""Touchpoints + conversions orchestration; ensure_precomputed is patched so no ClickHouse traffic."""@@ -205,7 +227,7 @@ class TestConversionWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result["conversion_teams"] == 1assert result["costs_teams"] == 0tables = _tables(ensure_mock)@@ -218,7 +240,7 @@ class TestConversionWarming(APIBaseTest):# _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())+ result = warm_selected_teams(dagster.build_op_context())assert result["conversion_teams"] == 1assert _tables(ensure_mock) == [LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED]@@ -227,7 +249,7 @@ class TestConversionWarming(APIBaseTest):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())+ warm_selected_teams(dagster.build_op_context())tables = _tables(ensure_mock)assert LazyComputationTable.MARKETING_TOUCHPOINTS_PREAGGREGATED in tablesassert LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED in tables@@ -244,7 +266,7 @@ class TestConversionWarming(APIBaseTest):team.marketing_analytics_config.save()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())+ warm_selected_teams(dagster.build_op_context())warmed = {call.kwargs["table"]: call.kwargs["insert_query"]@@ -275,7 +297,7 @@ class TestConversionWarming(APIBaseTest):# 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())+ warm_selected_teams(dagster.build_op_context())conversion_calls = [t for t in _tables(ensure_mock) if t == LazyComputationTable.MARKETING_CONVERSIONS_PREAGGREGATED]@@ -286,20 +308,32 @@ class TestConversionWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}ensure_mock.assert_not_called()+ @parameterized.expand([("database_built", False), ("database_build_fails", True)])@patch(_ENSURE, new_callable=_ready_mock)- @patch(_SINGLE_CHUNK, _BIG_CHUNK)- def test_pool_warms_every_team(self, ensure_mock):+ def test_pool_warms_every_team(self, _name, database_fails, ensure_mock):# The parallel fan-out must process every team, not just the first — a pool that dropped teams- # would leave them cold. Three teams, each with a precomputable goal, must all warm.+ # would leave them cold. Three teams, each with a precomputable goal, must all warm, and a failed+ # database build must not stop them. With a window of 2, a third team only starts after one finishes.+ # The database is built once per team however many buckets it warms: rebuilding it per bucket is+ # what made the warmer CPU-bound.teams = [self._make_team(name, goals=[_PRECOMPUTABLE_GOAL]) for name in ("A", "B", "C")]ids = ",".join(str(team.pk) for team in teams)- with patch(_FF, _flag_fn(conversion=True)), patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ids}):- result = ensure_marketing_precompute_op(dagster.build_op_context())+ with (+ patch(_FF, _flag_fn(conversion=True)),+ patch.dict(os.environ, {SELECTED_TEAM_IDS_ENV_VAR: ids, TEAM_CONCURRENCY_ENV_VAR: "2"}),+ patch(_DB) as database,+ ):+ if database_fails:+ database.create_for.side_effect = Exception("warehouse source broken")+ result = warm_selected_teams(dagster.build_op_context())+assert result == {"teams": 3, "conversion_teams": 3, "costs_teams": 0, "failures": 0}+ assert ensure_mock.call_count > len(teams)+ assert database.create_for.call_count == len(teams)@patch(_ENSURE, new_callable=_ready_mock)@patch(_SINGLE_CHUNK, _BIG_CHUNK)@@ -307,7 +341,7 @@ class TestConversionWarming(APIBaseTest):team = self._make_team("A", goals=[_INELIGIBLE_GOAL])expected = PRECOMPUTE_WINDOW_DAYS + team.marketing_analytics_config.attribution_window_dayswith 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())+ warm_selected_teams(dagster.build_op_context())kwargs = ensure_mock.call_args_list[0].kwargs # touchpoints is warmed firstassert (kwargs["time_range_end"] - kwargs["time_range_start"]).days == expected@@ -317,7 +351,7 @@ class TestConversionWarming(APIBaseTest):# 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())+ warm_selected_teams(dagster.build_op_context())conv_call = next(cfor c in ensure_mock.call_args_list@@ -335,7 +369,7 @@ class TestConversionWarming(APIBaseTest):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())+ warm_selected_teams(dagster.build_op_context())assert ensure_mock.call_count > 1for call in ensure_mock.call_args_list:assert (call.kwargs["time_range_end"] - call.kwargs["time_range_start"]).days <= 7@@ -356,7 +390,7 @@ class TestConversionWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result["teams"] == 2assert result["failures"] == 1assert ensure_mock.call_count == 2@@ -367,20 +401,20 @@ class TestConversionWarming(APIBaseTest):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())+ result = warm_selected_teams(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())+ result = warm_selected_teams(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())+ result = warm_selected_teams(dagster.build_op_context())assert result == {"teams": 0, "conversion_teams": 0, "costs_teams": 0, "failures": 0}ensure_mock.assert_not_called()@@ -416,7 +450,7 @@ class TestCostsWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result == {"teams": 1, "conversion_teams": 0, "costs_teams": 0, "failures": 0}ensure_mock.assert_not_called()@@ -432,7 +466,7 @@ class TestCostsWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result["costs_teams"] == 1tables = _tables(ensure_mock)assert tables == [LazyComputationTable.MARKETING_COSTS_PREAGGREGATED] * len(COST_MATERIALIZATION_GRAINS)@@ -448,7 +482,7 @@ class TestCostsWarming(APIBaseTest):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())+ result = warm_selected_teams(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@@ -467,7 +501,7 @@ class TestCostsWarming(APIBaseTest):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())+ warm_selected_teams(dagster.build_op_context())_, kwargs = db_mock.create_for.call_argsassert kwargs["bypass_warehouse_access_control"] is Trueassert "user" not in kwargs # no requesting user@@ -489,7 +523,7 @@ class TestCostsWarming(APIBaseTest):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())+ warm_selected_teams(dagster.build_op_context())assert ensure_mock.call_count == 4@patch(_ENSURE, new_callable=_ready_mock)@@ -513,7 +547,7 @@ class TestCostsWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result["teams"] == 2assert result["failures"] == 1 # broken team's costs stageassert result["costs_teams"] == 1 # healthy team still warmed@@ -528,7 +562,7 @@ class TestCostsWarming(APIBaseTest):# 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())+ result = warm_selected_teams(dagster.build_op_context())assert result["costs_teams"] == 0db_mock.create_for.assert_not_called()ensure_mock.assert_not_called()@@ -547,7 +581,7 @@ class TestCostsWarming(APIBaseTest):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())+ result = warm_selected_teams(dagster.build_op_context())assert result["conversion_teams"] == 1assert result["costs_teams"] == 1assert set(_tables(ensure_mock)) == {