: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): warm audience percentage via dagster run config (#70544)
Lucas Ricoy7a03b89d73e8
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pyindex 780741d20d42..c49562f95cc0 100644--- a/products/web_analytics/dags/eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -80,6 +80,7 @@ from django.db import connectionsfrom django.db.models import Maximport dagster+import pydanticimport structlogfrom prometheus_client import Counter@@ -197,10 +198,51 @@ EAGER_PRECOMPUTE_BASELINE_NOT_PRECOMPUTED = Counter()-def _resolve_eager_audience() -> tuple[list[int], str, dict]:+ACTIVE_AUDIENCE_LOOKBACK_HOURS = 24+# Sanity ceiling on the active-team fetch; ~9k teams open the dashboard daily.+ACTIVE_AUDIENCE_MAX_TEAMS = 20000+++def _fetch_active_wa_team_ids(limit: int) -> list[int]:+ """Top teams by deliberate WA dashboard activity (stats-table tile queries),+ most active first. Powers the warm-audience ramp experiment via the job's+ run config (`active_teams_pct`).++ Best-effort: any failure returns [] so the warmer falls back to the static+ lists rather than skipping a run."""+ from posthog.clickhouse.client import sync_execute # noqa: PLC0415 — keep dagster import path light++ try:+ rows = sync_execute(+ """+ SELECT JSONExtractInt(log_comment, 'team_id') AS team_id, count() AS n+ FROM clusterAllReplicas(%(cluster)s, system, query_log)+ WHERE event_time > now() - INTERVAL %(hours)s HOUR+ AND type = 'QueryFinish' AND is_initial_query = 1+ AND JSONExtractString(log_comment, 'query_type') LIKE 'stats_table%%'+ AND JSONExtractString(log_comment, 'feature') != 'cache_warmup'+ AND JSONExtractString(log_comment, 'trigger') = ''+ AND JSONExtractString(log_comment, 'access_method') != 'personal_api_key'+ AND team_id != 0+ GROUP BY team_id+ ORDER BY n DESC+ LIMIT %(limit)s+ """,+ {"cluster": "posthog", "hours": ACTIVE_AUDIENCE_LOOKBACK_HOURS, "limit": limit},+ )+ return [int(row[0]) for row in rows]+ except Exception:+ logger.exception("eager_warm_active_audience_fetch_failed")+ return []+++def _resolve_eager_audience(active_teams_pct: int = 0) -> tuple[list[int], str, dict]:"""Resolve the audience and return a structured trace of which gatefired. Returns `(team_ids, gate_reason, diagnostics)`.+ `active_teams_pct` (0-100, from the job's run config) adds that share of+ the most active WA dashboard teams (last 24h) on top of the static lists.+`gate_reason` is one of: `not_cloud`, `no_teams_configured`, `ok`."""if not is_cloud():@@ -211,15 +253,28 @@ def _resolve_eager_audience() -> tuple[list[int], str, dict]:# `WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS` must still get its# baseline warmed — otherwise its reads land on cold on-demand inserts.# dict.fromkeys preserves order and dedupes teams in both lists.+ active_team_ids: list[int] = []+ if active_teams_pct > 0:+ all_active = _fetch_active_wa_team_ids(ACTIVE_AUDIENCE_MAX_TEAMS)+ take = max(1, len(all_active) * min(active_teams_pct, 100) // 100) if all_active else 0+ active_team_ids = all_active[:take]++ # Static lists first so the always-enrolled teams warm before the ramp+ # audience when a run is truncated by the job's max_runtime.team_ids = list(dict.fromkeys([*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,+ *active_team_ids,]))- diag = {"teams_configured": len(team_ids)}+ diag = {+ "teams_configured": len(team_ids),+ "active_teams_pct": active_teams_pct,+ "active_teams": len(active_team_ids),+ }if not team_ids:return [], "no_teams_configured", diagreturn team_ids, "ok", diag@@ -370,11 +425,34 @@ def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) ->return warmed, failed+class EagerWarmConfig(dagster.Config):+ # Percentage of the most active WA dashboard teams (last 24h, ranked by+ # tile-query volume) to warm on top of the static enrollment lists. Defaults to+ # 0 = static lists only; set in the run config when launching manually to ramp+ # the warm-audience experiment (e.g. 5 -> 25 -> 100).+ active_teams_pct: int = pydantic.Field(default=0, ge=0, le=100)++@dagster.op-def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int]:+def warm_eager_baseline_op(context: dagster.OpExecutionContext, config: EagerWarmConfig) -> dict[str, int]:"""Run the baseline tile matrix against every team in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` setting."""started = time.monotonic()- team_ids, gate_reason, diagnostics = _resolve_eager_audience()+ team_ids, gate_reason, diagnostics = _resolve_eager_audience(active_teams_pct=config.active_teams_pct)+ # Captured before the ramp enrollment below mutates the setting — this set is+ # what "statically enrolled" means for the priority sort further down.+ static_ids = {+ *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,+ *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,+ }+ if config.active_teams_pct > 0:+ # Enroll the ramp audience for the lifetime of this run's process: the warm+ # queries route through `is_precompute_enabled_for_team`, whose org-flag+ # fallback fails closed in Dagster — without this, ramp teams would silently+ # take the RAW path and the experiment would fan heavy live queries across+ # thousands of teams instead of building precompute windows.+ settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS = list(+ dict.fromkeys([*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS, *team_ids])+ )diag_str = " ".join(f"{k}={v}" for k, v in diagnostics.items())context.log.info(f"eager_baseline_warming_start teams={len(team_ids)} gate_reason={gate_reason} {diag_str}".rstrip()@@ -445,7 +523,12 @@ def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int.values_list("team_id", "last"))never_computed = datetime.min.replace(tzinfo=UTC)- eligible.sort(key=lambda t: last_computed.get(t.pk) or never_computed)+ # Two tiers: statically enrolled teams first (stalest first within the tier),+ # then the ramp audience. A large `active_teams_pct` audience is mostly+ # never-warmed, and a flat staleness sort would push the always-enrolled teams+ # behind thousands of ramp teams whenever a run hits `max_runtime`.+ # `static_ids` was captured before the ramp enrollment mutated the setting.+ eligible.sort(key=lambda t: (t.pk not in static_ids, last_computed.get(t.pk) or never_computed))# Running progress counter for the pool — `itertools.count.__next__` is# atomic under the GIL, so it's safe to call from the worker threads. Eachdiff --git a/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py b/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.pyindex b2f36a807cd8..42aa0c24cb70 100644--- a/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py@@ -67,7 +67,7 @@ class TestResolveEagerAudience:team_ids, reason, diag = _resolve_eager_audience()assert team_ids == [2, 7]assert reason == "ok"- assert diag == {"teams_configured": 2}+ assert diag == {"teams_configured": 2, "active_teams_pct": 0, "active_teams": 0}def test_returns_empty_on_self_hosted(self, _is_cloud):_is_cloud.return_value = False@@ -98,7 +98,30 @@ class TestResolveEagerAudience:team_ids, reason, diag = _resolve_eager_audience()assert team_ids == expectedassert reason == "ok"- assert diag == {"teams_configured": len(expected)}+ assert diag == {"teams_configured": len(expected), "active_teams_pct": 0, "active_teams": 0}++ @parameterized.expand(+ [+ # pct of the 4 fetched actives: 50% -> top 2, 100% -> all 4; static+ # lists stay first and overlaps dedupe.+ ("half", 50, [2, 7, 31], 2),+ ("all", 100, [2, 7, 31, 42, 55], 4),+ ]+ )+ def test_active_audience_pct_appends_after_static_lists(self, _is_cloud, _name, pct, expected, expected_active):+ with (+ override_settings(+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[2, 7], WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[]+ ),+ patch(+ f"{_EAGER_MODULE}._fetch_active_wa_team_ids",+ return_value=[7, 31, 42, 55],+ ),+ ):+ team_ids, reason, diag = _resolve_eager_audience(active_teams_pct=pct)+ assert team_ids == expected+ assert reason == "ok"+ assert diag == {"teams_configured": len(expected), "active_teams_pct": pct, "active_teams": expected_active}@patch("products.web_analytics.dags.eager_web_analytics_precompute.is_cloud", return_value=True)