: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(web-analytics): shard the warm pass across subprocesses (#74471)
Lucas Ricoy587136525dbf
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex bfa215b653ac..c67252ec0c52 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -319,12 +319,21 @@ CONSTANCE_CONFIG = {"of more background compute.",int,),- "WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY": (- get_from_env("WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY", default=16, type_cast=int),- "Worker threads for the web analytics warm pass. Cold bucket builds dominate a first run "- "(each shape builds one bucket per day of its range), so a higher value drains the selection "- "faster but adds load to the offline ClickHouse pool. Clamped to 1-64; the pool is fixed per "- "pass, so a change applies when the next warming run starts — no redeploy needed.",+ # Renamed from WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY when its meaning changed+ # from total workers to per-shard workers, so stale overrides sized for the old+ # semantics (e.g. 24 total) can't silently become 24 threads in every shard.+ "WEB_ANALYTICS_WARMING_SHARD_THREADS": (+ get_from_env("WEB_ANALYTICS_WARMING_SHARD_THREADS", default=6, type_cast=int),+ "Worker threads inside each warm shard (total ClickHouse-side concurrency is shards x this). "+ "Threads overlap the IO-bound parts; CPU-bound HogQL compilation parallelizes across shards, "+ "not threads. Clamped to 1-64; applies when the next warming run starts.",+ int,+ ),+ "WEB_ANALYTICS_WARMING_SHARDS": (+ get_from_env("WEB_ANALYTICS_WARMING_SHARDS", default=8, type_cast=int),+ "Number of team-disjoint shards the warm pass fans out into, one subprocess each. Each shard "+ "compiles HogQL on its own core, so this bounds real CPU parallelism; the run pod requests "+ "CPU to match (dagster-k8s/config on the job). Clamped to 1-16; applies at the next run.",int,),}@@ -384,7 +393,8 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS","WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT","WEB_ANALYTICS_WARMING_MAX_SHAPES",- "WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY",+ "WEB_ANALYTICS_WARMING_SHARD_THREADS",+ "WEB_ANALYTICS_WARMING_SHARDS",)# SECRET_SETTINGS can only be updated but will never be exposed through the API (we do store them plain text in the DB)diff --git a/posthog/settings/logs.py b/posthog/settings/logs.pyindex f63516f460f5..e02139e4fa5f 100644--- a/posthog/settings/logs.py+++ b/posthog/settings/logs.py@@ -164,6 +164,13 @@ LOGGING: dict[str, Any] = {"handlers": ["console_stdout_info", "console_stderr_warning"],"propagate": False,},+ # The web analytics warmer logs one line per shape per pass (up to the+ # 400k selection cap) — keep the INFO burst off stderr for the same reason.+ "products.web_analytics.dags.cache_warming": {+ "level": "INFO",+ "handlers": ["console_stdout_info", "console_stderr_warning"],+ "propagate": False,+ },"posthog.auth.mfa": {"level": "INFO", "handlers": ["console"], "propagate": False},"posthog.security.command_exec_audit": {"level": "INFO", "handlers": ["console"], "propagate": False},"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load": {diff --git a/products/web_analytics/dags/README.md b/products/web_analytics/dags/README.mdnew file mode 100644index 000000000000..1b16c882c585--- /dev/null+++ b/products/web_analytics/dags/README.md@@ -0,0 +1,63 @@+# Web analytics cache warming++Hourly Dagster job (`web_analytics_cache_warming_job`) that keeps web analytics+precompute buckets and result caches fresh for the fleet's hot query shapes.+Selection scans `system.query_log` for shapes real users ran, groups them by+normalized shape, and replays a representative per shape through the production+query runners.++## Architecture++`get_warmable_queries_op` (fleet-wide selection, cached in object storage)+→ `warm_queries_op` (the split: scopes the selection and fans it into+team-disjoint shards) → mapped `warm_queries_shard_op` per shard.++Each shard runs as its own subprocess under the multiprocess executor. HogQL+compilation is CPU-bound Python, so parallelism comes from shard processes, not+threads; threads inside a shard overlap the IO-bound parts (ClickHouse reads+and inserts, cache lookups). Sharding is by `team_id % shards`, which keeps+every potential duplicate `(team, cache_key)` inside one shard so per-shard+dedupe needs no coordination. The run pod requests CPU/memory to match the+shard count via the `dagster-k8s/config` tag on the job.++## Live-tunable settings (instance settings, no redeploy)++| Setting | Default | Meaning |+| --------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `WEB_ANALYTICS_WARMING_SHARDS` | 8 | Shard subprocesses per run (clamp 1-16). Bounds real CPU parallelism; keep the job's `dagster-k8s/config` CPU request in step. |+| `WEB_ANALYTICS_WARMING_SHARD_THREADS` | 6 | Worker threads inside each shard (clamp 1-64). Total ClickHouse-side concurrency ≈ shards × this. |+| `WEB_ANALYTICS_WARMING_DAYS` | 14 | query_log lookback for demand selection. |+| `WEB_ANALYTICS_WARMING_MIN_QUERY_COUNT` | 2 | Per-shape demand floor for selection. |+| `WEB_ANALYTICS_WARMING_MAX_SHAPES` | 400000 | Fleet-wide selection cap. |+| `WEB_ANALYTICS_WARMING_SELECTION_TTL_SECONDS` | 21600 | Selection cache TTL (the expensive fleet scan re-runs on this cadence). |++Settings are read at run start; changes apply to the next run.++## Targeted runs (Launchpad)++Config binds under `ops.warm_queries_op.config`:++```yaml+ops:+ warm_queries_op:+ config:+ mode: backfill # full (default) | refresh | backfill+ team_ids: [] # optional scoping+ limit: 0 # hottest-first cap; bound manual backfills+```++- `full`: everything selected — skip fresh, refresh stale, cold-build the rest.+- `refresh`: only shapes already warmed once (cache entry exists) — cheap freshness pass.+- `backfill`: only never-warmed shapes — coverage expansion without re-touching the warm set.++Launches share a concurrent-run guard with the hourly schedule, so bound manual+backfills with `limit`.++## Observability++- Per-shape log line (`web_analytics_warming_shape`): outcome, duration, team,+ kind, breakdown, requested and replayed date range. Slow shapes (≥15s full+ wall-clock) escalate to WARNING.+- Per-shard heartbeat every ~2 minutes: progress, rate, ETA, outcome breakdown.+- Prometheus: `posthog_web_analytics_warming_queries_total{outcome=...}`,+ `posthog_web_analytics_warming_shapes_selected`.diff --git a/products/web_analytics/dags/cache_warming.py b/products/web_analytics/dags/cache_warming.pyindex 8ac7c461e7e6..722cc1cde3fc 100644--- a/products/web_analytics/dags/cache_warming.py+++ b/products/web_analytics/dags/cache_warming.py@@ -593,17 +593,23 @@ RAW_REPLAY_MIN_QUERY_COUNT = 10# reads/inserts), so a pool cuts wall time at the widened selection size. A cold# first run is dominated by per-day bucket builds — hundreds of thousands of them# — so this is the main throughput lever, but raising it adds load to the offline-# ClickHouse pool. Overridable via WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY without+# ClickHouse pool. Overridable via WEB_ANALYTICS_WARMING_SHARD_THREADS without# a redeploy; the pool is fixed for the life of a pass, so a change applies when# the next run starts. This is the fallback when the setting is unset.-WARMING_SHAPE_CONCURRENCY = 16+WARMING_SHARD_THREADS = 6++# Fallback shard count for the sharded warm pass (see split_warmable_queries_op);+# overridable live via WEB_ANALYTICS_WARMING_SHARDS. Total ClickHouse-side+# concurrency is shards x per-shard threads.+WARMING_SHARDS = 8# Heartbeat cadence for the warm pass. Cold bucket builds run ~1s each, so a full# selection can take hours; without a heartbeat the op is silent start to finish# and a long run is indistinguishable from a hung one.WARMING_PROGRESS_LOG_INTERVAL_SECONDS = 120-# Per-shape wall-clock above which the warm is logged with its shape details.+# Full per-shape wall-clock (runner construction, cache lookups, and the warm+# itself) above which the shape's log line escalates to WARNING.# Aggregate counters say a run is slow but not WHICH shapes made it slow — the# forensic gap when diagnosing why passes overrun (deep ranges rebuilding, bucket# identity churn re-warming old days, one team's pathological filters).@@ -636,8 +642,7 @@ class WarmQueriesConfig(dagster.Config):limit: int = 0[email protected](retry_policy=cache_warming_retry_policy)-def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfig, queries: list[dict]) -> None:+def _scope_queries(config: WarmQueriesConfig, queries: list[dict]) -> tuple[str, list[dict]]:if config.mode not in ("full", "refresh", "backfill"):raise ValueError(f"Unknown warming mode {config.mode!r} (expected full, refresh, or backfill)")if config.team_ids:@@ -645,7 +650,45 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfqueries = [q for q in queries if q["team_id"] in wanted]if config.limit > 0:queries = queries[: config.limit]+ return config.mode, queries++[email protected](retry_policy=cache_warming_retry_policy)+def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfig, queries: list[dict]) -> None:+ mode, queries = _scope_queries(config, queries)+ _warm_queries(context, mode, queries)++[email protected](out=dagster.DynamicOut(dict), retry_policy=cache_warming_retry_policy)+def split_warmable_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfig, queries: list[dict]):+ """Scope the selection and fan it out into team-disjoint shards.++ Each shard becomes its own mapped op — a separate subprocess under the+ multiprocess executor, with its own GIL. HogQL compilation is CPU-bound+ Python, so threads inside one process serialize on the interpreter; real+ parallelism needs processes. Sharding by team keeps every potential+ duplicate cache key inside one shard (the dedupe set is keyed on+ (team_id, cache_key)), so no cross-process coordination is needed.+ """+ mode, queries = _scope_queries(config, queries)+ shards_setting = get_instance_setting("WEB_ANALYTICS_WARMING_SHARDS")+ # `if None` rather than `or`: an explicit 0 must clamp to the documented+ # minimum of one shard, not silently fall back to the default of eight.+ shards = min(16, max(1, WARMING_SHARDS if shards_setting is None else shards_setting))+ buckets: dict[int, list[dict]] = {}+ for query_info in queries:+ buckets.setdefault(query_info["team_id"] % shards, []).append(query_info)+ context.log.info(f"Split {len(queries)} shapes into {len(buckets)} shards (mode={mode})")+ for shard_index in sorted(buckets):+ yield dagster.DynamicOutput({"mode": mode, "queries": buckets[shard_index]}, mapping_key=f"shard_{shard_index}")+[email protected](retry_policy=cache_warming_retry_policy)+def warm_queries_shard_op(context: dagster.OpExecutionContext, shard: dict) -> None:+ _warm_queries(context, shard["mode"], shard["queries"])+++def _warm_queries(context: dagster.OpExecutionContext, mode: str, queries: list[dict]) -> None:team_ids = {q["team_id"] for q in queries}teams: dict[int, Team] = {t.pk: t for t in Team.objects.filter(pk__in=team_ids)}missing_teams = team_ids - teams.keys()@@ -664,17 +707,27 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConf# deep-range rebuilds); per-shape logs make the composition greppable.started = time.monotonic()outcome = _warm_one_inner(query_info)- query_json = query_info.get("query_json") or {}- logger.info(- "web_analytics_warming_shape",- outcome=outcome,- seconds=round(time.monotonic() - started, 2),- team_id=query_info.get("team_id"),- kind=query_json.get("kind"),- breakdown_by=query_json.get("breakdownBy"),- date_from=(query_json.get("dateRange") or {}).get("date_from"),- normalized_query_hash=query_info.get("normalized_query_hash"),- )+ seconds = round(time.monotonic() - started, 2)+ try:+ query_json = query_info.get("query_json") or {}+ date_range = query_json.get("dateRange") if isinstance(query_json, dict) else None+ log = logger.warning if seconds >= WARMING_SLOW_SHAPE_SECONDS else logger.info+ log(+ "web_analytics_warming_shape",+ outcome=outcome,+ seconds=seconds,+ team_id=query_info.get("team_id"),+ kind=query_json.get("kind") if isinstance(query_json, dict) else None,+ breakdown_by=query_json.get("breakdownBy") if isinstance(query_json, dict) else None,+ date_from=date_range.get("date_from") if isinstance(date_range, dict) else None,+ replay_date_from=query_info.get("_replay_date_from"),+ was_cold=query_info.get("_was_cold"),+ normalized_query_hash=query_info.get("normalized_query_hash"),+ )+ except Exception:+ # Observability must never abort the pass: a malformed shape already+ # produced its outcome above; a logging error is not a warm failure.+ logger.exception("web_analytics_warming_shape_log_failed")return outcomedef _warm_one_inner(query_info: dict) -> str:@@ -702,6 +755,10 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfrunner, query_json, lazy_eligible = build_replay_runner(team, query_json, query_info.get("observed_date_froms", []))+ # Stashed for the wrapper's per-shape log: the REPLAYED range (after+ # widening/deepening) is what actually executes, and it differs from+ # the selected shape's range in exactly the cases worth debugging.+ query_info["_replay_date_from"] = (query_json.get("dateRange") or {}).get("date_from")if runner is None:WARMING_QUERIES_COUNTER.labels(outcome="unsupported").inc()return "unsupported"@@ -727,15 +784,16 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfseen_cache_keys.add((team.pk, cache_key))entry = QueryCache(team_id=team.pk, cache_key=cache_key).lookup().entry+ query_info["_was_cold"] = entry is None# The cache entry doubles as the warm/cold discriminator: a shape# warmed at least once has one (possibly stale); a never-warmed shape# doesn't. refresh keeps the warm set fresh without paying for cold# builds; backfill expands coverage without re-touching the warm set.- if config.mode == "refresh" and entry is None:+ if mode == "refresh" and entry is None:WARMING_QUERIES_COUNTER.labels(outcome="skipped_cold").inc()return "skipped_cold"- if config.mode == "backfill" and entry is not None:+ if mode == "backfill" and entry is not None:WARMING_QUERIES_COUNTER.labels(outcome="skipped_already_warmed").inc()return "skipped_already_warmed"@@ -748,21 +806,7 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConfreturn "skipped_fresh"# TODO: We shouldn't try to run a query if it failed last run- run_started = time.monotonic()runner.run(analytics_props={"source": EventSource.CACHE_WARMING})- warm_seconds = time.monotonic() - run_started- if warm_seconds >= WARMING_SLOW_SHAPE_SECONDS:- # Module logger: worker thread (see the failure handler below).- logger.warning(- "web_analytics_warming_slow_shape",- team_id=team.pk,- kind=query_json.get("kind"),- breakdown_by=query_json.get("breakdownBy"),- date_from=(query_json.get("dateRange") or {}).get("date_from"),- seconds=round(warm_seconds, 1),- was_cold=entry is None,- normalized_query_hash=query_info["normalized_query_hash"],- )WARMING_QUERIES_COUNTER.labels(outcome="warmed").inc()return "warmed"except Exception as e:@@ -796,17 +840,14 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConf# Clamped: a non-positive value would abort every run at pool construction and# an oversized one can exhaust process threads. The pool is fixed for the life# of the pass, so a settings change applies when the next run starts.- concurrency = min(- 64, max(1, get_instance_setting("WEB_ANALYTICS_WARMING_SHAPE_CONCURRENCY") or WARMING_SHAPE_CONCURRENCY)- )+ concurrency_setting = get_instance_setting("WEB_ANALYTICS_WARMING_SHARD_THREADS")+ concurrency = min(64, max(1, WARMING_SHARD_THREADS if concurrency_setting is None else concurrency_setting))outcomes: dict[str, int] = {}total = len(queries)processed = 0started_at = time.monotonic()last_log_at = started_at- context.log.info(- f"Warming {total} shapes across {len(teams)} teams (mode={config.mode}, concurrency={concurrency})"- )+ context.log.info(f"Warming {total} shapes across {len(teams)} teams (mode={mode}, concurrency={concurrency})")with ThreadPoolExecutor(max_workers=concurrency) as pool:# Futures are consumed by completion, not input order: with pool.map one# slow early shape would block this loop — and the heartbeat — while later@@ -837,7 +878,7 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConffinal_breakdown = ", ".join(f"{k}={v}" for k, v in sorted(outcomes.items()))context.log.info(f"Warmed {queries_warmed} queries in {(time.monotonic() - started_at) / 60:.1f}m "- f"(mode={config.mode}: {final_breakdown})"+ f"(mode={mode}: {final_breakdown})")context.add_output_metadata({@@ -851,7 +892,7 @@ def warm_queries_op(context: dagster.OpExecutionContext, config: WarmQueriesConf"queries_failed": queries_failed,"queries_unsupported": queries_unsupported,"concurrency": concurrency,- "mode": config.mode,+ "mode": mode,})@@ -897,11 +938,26 @@ def report_warming_plan_op(context: dagster.OpExecutionContext, queries: list[ditags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value,"dagster/web_analytics_cache_warming": "web_analytics_cache_warming",+ # The agent default is 2 CPUs / 8Gi (charts: argocd/dagster/values). The+ # sharded pass runs one subprocess per shard, each compiling HogQL on its+ # own core, so the run pod needs CPU for the shards and memory for that+ # many Django interpreters.+ "dagster-k8s/config": {+ "container_config": {+ "resources": {+ "requests": {"cpu": "8000m", "memory": "12Gi"},+ "limits": {"memory": "12Gi"},+ }+ }+ },},)def web_analytics_cache_warming_job():queries = get_warmable_queries_op()- warm_queries_op(queries)+ # Aliased so the config path stays ops.warm_queries_op.config — the split op+ # takes the same WarmQueriesConfig, so saved Launchpad configs written for+ # the pre-sharding single op keep binding unchanged.+ split_warmable_queries_op.alias("warm_queries_op")(queries).map(warm_queries_shard_op)@dagster.job(diff --git a/products/web_analytics/dags/tests/test_cache_warming.py b/products/web_analytics/dags/tests/test_cache_warming.pyindex 9e5097a777ea..2bb1bc63a7b1 100644--- a/products/web_analytics/dags/tests/test_cache_warming.py+++ b/products/web_analytics/dags/tests/test_cache_warming.py@@ -19,6 +19,7 @@ from products.web_analytics.dags.cache_warming import (maybe_expand_warming_date_range,maybe_opt_into_lazy_precompute,queries_to_keep_fresh,+ split_warmable_queries_op,warm_queries_op,)@@ -255,6 +256,55 @@ class TestBuildReplayRunner(BaseTest):self.assertEqual(used_json["dateRange"]["date_from"], "-7d")+class TestSplitWarmableQueries(BaseTest):+ def _shape(self, team_id: int, n: int) -> dict:+ return {+ "team_id": team_id,+ "query_json": {"kind": "WebOverviewQuery", "n": n},+ "query_count": 5,+ "representative_query_count": 5,+ "normalized_query_hash": f"h{n}",+ }++ def test_shards_are_team_disjoint_and_lossless(self) -> None:+ # A team split across shards breaks the per-shard (team, cache_key)+ # dedupe and warms duplicates; a dropped or duplicated shape silently+ # under- or over-warms. Both fail here.+ queries = [self._shape(team, n) for n, team in enumerate([1, 2, 3, 9, 10, 17, 2, 9, 1])]++ outputs = list(split_warmable_queries_op(dagster.build_op_context(), WarmQueriesConfig(), queries))++ team_to_shard: dict[int, str] = {}+ seen_hashes = []+ for out in outputs:+ for q in out.value["queries"]:+ seen_hashes.append(q["normalized_query_hash"])+ previously = team_to_shard.setdefault(q["team_id"], out.mapping_key)+ self.assertEqual(previously, out.mapping_key)+ self.assertEqual(sorted(seen_hashes), sorted(q["normalized_query_hash"] for q in queries))++ def test_scoping_applies_before_sharding(self) -> None:+ # team_ids/limit moved from the warm op to the split — if they stop+ # applying, a scoped Launchpad launch warms the whole fleet while+ # holding the schedule's slot.+ queries = [self._shape(team, n) for n, team in enumerate([1, 2, 1, 3, 1])]++ outputs = list(+ split_warmable_queries_op(+ dagster.build_op_context(), WarmQueriesConfig(mode="backfill", team_ids=[1], limit=2), queries+ )+ )++ shapes = [q for out in outputs for q in out.value["queries"]]+ self.assertEqual(len(shapes), 2)+ self.assertTrue(all(q["team_id"] == 1 for q in shapes))+ self.assertTrue(all(out.value["mode"] == "backfill" for out in outputs))++ def test_unknown_mode_fails_before_fanout(self) -> None:+ with self.assertRaises(ValueError):+ list(split_warmable_queries_op(dagster.build_op_context(), WarmQueriesConfig(mode="bogus"), []))++class TestFleetQuerySelection(BaseTest):@patch("products.web_analytics.dags.cache_warming.sync_execute")def test_parses_fleet_rows_into_query_infos(self, mock_exec: MagicMock) -> None:@@ -577,7 +627,7 @@ class TestWarmQueriesOp(BaseTest):shape = {"team_id": self.team.pk, "query_json": {"kind": "WebOverviewQuery", "properties": []}}with (- patch("products.web_analytics.dags.cache_warming.WARMING_SHAPE_CONCURRENCY", 1),+ patch("products.web_analytics.dags.cache_warming.WARMING_SHARD_THREADS", 1),patch("products.web_analytics.dags.cache_warming.get_query_runner_or_none", side_effect=fake_runner_or_none),