: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): use hardcoded team id list for eager precompute (#61318)
Lucas Ricoyb99606f0b9d3
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pyindex 1f3c80b0ed25..ac8751c58237 100644--- a/products/web_analytics/dags/eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -2,8 +2,7 @@A single Dagster job that pre-warms the lazy precompute cache for theWeb analytics dashboard's main tile matrix over the trailing 28 days,-for every team belonging to an organization rolled out on the-`web-analytics-precompute-toggle` feature flag.+for every team in the hardcoded `EAGER_BASELINE_TEAM_IDS` list.The job is intentionally thin: it enumerates the dashboard's queryfamilies and dispatches each through `get_query_runner(...).run(...)`.@@ -21,31 +20,14 @@ cache perpetually warm, so user requests turn into pure reads.Audience---------Source of truth is the `web-analytics-precompute-toggle` feature flag,-the same flag the runtime lazy read path checks before serving from the-precompute cache. The flag is structured as one group per enrolled-organization (`Match organizations against id equals <uuid>`).--The flag definition is read from the `posthoganalytics` SDK's local-evaluation cache (`feature_flag_definitions()`), which mirrors the-server's `/api/feature_flag/local_evaluation/` payload — same JSON shape-the Django `FeatureFlag` model stores. Reading via the SDK keeps this-module self-contained within `products.web_analytics`'s allowed tach-dependencies and avoids any cross-product import.--Reusing the runtime flag for the audience guarantees the eager warming-audience never drifts from the audience the read path will actually-serve — there is no second flag to keep in sync.+The audience is a hardcoded `EAGER_BASELINE_TEAM_IDS` tuple kept in+source. To enroll or remove a team, open a PR editing the constant.+The list intentionally mirrors `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`+on the runtime read path so warmer and reader stay in sync; do not+silently let them drift.The job is a no-op on self-hosted instances (`is_cloud()` returns False)-where the SDK isn't configured against PostHog Cloud's project.--Composition with the lazy read path-------------------------------------This job and the lazy read path consult the same flag, so an-organization rolled out on the flag is both warmed by this job and-served from the warmed cache at request time. No two-flag coordination-needed.+since the lazy precompute infrastructure is Cloud-only.This job is complementary to `cache_warming.py`, which replays whateverqueries users actually ran. The eager job covers the fixed UI matrix;@@ -54,7 +36,6 @@ the replay covers the long tail (custom hosts, custom filters, etc.).import dagsterimport structlog-import posthoganalyticsfrom prometheus_client import Counterfrom posthog.schema import WebStatsBreakdown@@ -73,7 +54,11 @@ from products.web_analytics.dags.web_preaggregated_utils import check_for_concurlogger = structlog.get_logger(__name__)-EAGER_FLAG_KEY = "web-analytics-precompute-toggle"+# Audience: teams that should have the dashboard's main tile matrix+# perpetually warmed. Keep this in sync with the runtime read-path+# `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` env var on Django pods —+# warming a team here that the reader doesn't serve is wasted compute.+EAGER_BASELINE_TEAM_IDS: tuple[int, ...] = (2,)# Single warming window: the trailing 28 days. The lazy precompute path# stores per-day buckets, so a 28-day warm naturally serves any user@@ -124,95 +109,22 @@ EAGER_PRECOMPUTE_BASELINE_FAILED = Counter()-def _extract_organization_ids_from_flag(flag: dict) -> list[str]:- """Pull `id equals <uuid>` values out of a flag definition's filter groups.-- Expects org-aggregated flags shaped as one group per enrolled org- with a `{type: "group", key: "id", operator: "exact", value: <uuid>}`- property — the shape the product UI produces for "Match organizations- against id equals <uuid>" conditions. Trusts the shape since the flag- is internal config.- """- org_ids: list[str] = []- for group in flag.get("filters", {}).get("groups", []):- for prop in group.get("properties", []):- if prop.get("type") != "group" or prop.get("key") != "id":- continue- # `exact` is the default operator when not specified.- if prop.get("operator", "exact") != "exact":- continue- value = prop.get("value")- if isinstance(value, list):- org_ids.extend(v for v in value if v)- elif value:- org_ids.append(value)- return org_ids---def _find_flag_definition(key: str) -> dict | None:- """Look up `key` in the posthoganalytics SDK's local flag-definition cache.-- The cache is populated by the SDK's background poller against the- PostHog project the cloud deployment is configured for, so this- avoids importing the `FeatureFlag` Django model from another product- and stays self-contained within `products.web_analytics`'s allowed- tach dependencies.- """- for flag in posthoganalytics.feature_flag_definitions() or []:- if flag.get("key") != key:- continue- if flag.get("deleted") or flag.get("active") is False:- continue- return flag- return None--def _resolve_eager_audience() -> tuple[list[int], str, dict]:"""Resolve the audience and return a structured trace of which gatefired. Returns `(team_ids, gate_reason, diagnostics)`.- `gate_reason` is one of: `not_cloud`, `flag_not_found`,- `flag_no_org_conditions`, `no_teams_for_orgs`, `ok`. The- `diagnostics` dict carries the inputs each gate saw — enough to- explain a `teams=0` run without re-running the job.+ `gate_reason` is one of: `not_cloud`, `no_teams_configured`, `ok`."""if not is_cloud():- return [], "not_cloud", {"flag_key": EAGER_FLAG_KEY}-- flag = _find_flag_definition(EAGER_FLAG_KEY)- if flag is None:- flag_count = len(posthoganalytics.feature_flag_definitions() or [])- return [], "flag_not_found", {"flag_key": EAGER_FLAG_KEY, "flags_in_cache": flag_count}-- org_ids = _extract_organization_ids_from_flag(flag)- if not org_ids:- group_count = len(flag.get("filters", {}).get("groups", []))- return (- [],- "flag_no_org_conditions",- {"flag_key": EAGER_FLAG_KEY, "flag_groups": group_count},- )-- team_ids = list(- Team.objects.filter(organization_id__in=org_ids).values_list("pk", flat=True).distinct().order_by("pk")- )- diag = {- "flag_key": EAGER_FLAG_KEY,- "org_ids_in_flag": len(org_ids),- "teams_resolved": len(team_ids),- }+ return [], "not_cloud", {}++ team_ids = list(EAGER_BASELINE_TEAM_IDS)+ diag = {"teams_configured": len(team_ids)}if not team_ids:- return [], "no_teams_for_orgs", diag+ return [], "no_teams_configured", diagreturn team_ids, "ok", diag-def get_eager_team_ids() -> list[int]:- """Thin wrapper kept for external callers and tests; see- `_resolve_eager_audience` for the gate-by-gate logic."""- team_ids, _, _ = _resolve_eager_audience()- return team_ids--def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) -> tuple[int, int]:"""Run the full tile matrix for one team. Returns (warmed, failed).@@ -282,22 +194,9 @@ def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) ->return warmed, failed[email protected](required_resource_keys={"posthoganalytics"})def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int]:- """Run the baseline tile matrix against every flag-enrolled team.-- Declaring the `posthoganalytics` resource ensures Dagster runs- `PostHogAnalyticsResource.create_resource` first, which sets- `posthoganalytics.personal_api_key` from `EnvVar("PERSONAL_API_KEY")`.- The op then forces a synchronous load of flag definitions — the- SDK's background poller runs on a 90s interval and would not fire- before this short-lived op subprocess exits.- """- try:- posthoganalytics.load_feature_flags()- except Exception:- context.log.exception("eager_baseline_warming_load_feature_flags_failed")-+ """Run the baseline tile matrix against every team in `EAGER_BASELINE_TEAM_IDS`."""team_ids, gate_reason, diagnostics = _resolve_eager_audience()diag_str = " ".join(f"{k}={v}" for k, v in diagnostics.items())context.log.info(@@ -333,10 +232,9 @@ def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int@dagster.job(description=("Hourly pre-warmer for Web analytics: runs the dashboard's main tile matrix over the last "- f"{BASELINE_WINDOW_DAYS} days for every team belonging to an organization rolled out on the "- f"`{EAGER_FLAG_KEY}` flag. Each query is dispatched through its standard runner, which routes "- f"through the family's lazy precompute path — the runner decides what's stale and inserts only "- f"what's missing."+ f"{BASELINE_WINDOW_DAYS} days for every team in `EAGER_BASELINE_TEAM_IDS`. Each query is "+ "dispatched through its standard runner, which routes through the family's lazy precompute "+ "path — the runner decides what's stale and inserts only what's missing."),tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value,diff --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 7d7e4c01f1cd..85d3df525753 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@@ -1,6 +1,3 @@-from uuid import uuid4--import pytestfrom posthog.test.base import APIBaseTestfrom unittest.mock import Mock, patch@@ -13,227 +10,51 @@ from posthog.models import Organization, Teamfrom products.web_analytics.dags.eager_web_analytics_precompute import (BASELINE_BREAKDOWNS,BASELINE_WINDOW_DAYS,- EAGER_FLAG_KEY,- _extract_organization_ids_from_flag,+ EAGER_BASELINE_TEAM_IDS,+ _resolve_eager_audience,_warm_baseline_for_team,- get_eager_team_ids,warm_eager_baseline_op,web_analytics_eager_baseline_warming_job,)-# Generic placeholder UUIDs for tests — these never touch customer data and-# the flag conditions in production are opaque organization IDs.-_ORG_UUID_A = "11111111-1111-4111-8111-111111111111"-_ORG_UUID_B = "22222222-2222-4222-8222-222222222222"-_ORG_UUID_C = "33333333-3333-4333-8333-333333333333"-# Total queries per team: WebOverview + WebGoals + WebVitalsPathBreakdown + each WebStats breakdown._QUERIES_PER_TEAM = 3 + len(BASELINE_BREAKDOWNS)-def _flag(*, groups: list[dict], active: bool = True, deleted: bool = False) -> dict:- """Build a flag-definition dict matching the SDK's local-evaluation shape."""- return {- "key": EAGER_FLAG_KEY,- "active": active,- "deleted": deleted,- "filters": {"groups": groups, "aggregation_group_type_index": 0},- }---def _org_id_group(org_id: str, *, operator: str | None = "exact") -> dict:- prop: dict = {"key": "id", "type": "group", "group_type_index": 0, "value": org_id}- if operator is not None:- prop["operator"] = operator- return {"properties": [prop], "rollout_percentage": 100}---class TestExtractOrganizationIdsFromFlag:- @pytest.mark.parametrize(- "flag,expected",- [- pytest.param(- _flag(groups=[_org_id_group(_ORG_UUID_A)]),- [_ORG_UUID_A],- id="single_group_single_org",- ),- pytest.param(- _flag(groups=[_org_id_group(_ORG_UUID_A), _org_id_group(_ORG_UUID_B), _org_id_group(_ORG_UUID_C)]),- [_ORG_UUID_A, _ORG_UUID_B, _ORG_UUID_C],- id="multiple_groups_preserved_in_order",- ),- pytest.param(- _flag(- groups=[- {- "properties": [- {- "key": "id",- "type": "group",- "group_type_index": 0,- "value": [_ORG_UUID_A, _ORG_UUID_B],- "operator": "exact",- }- ],- "rollout_percentage": 100,- }- ]- ),- [_ORG_UUID_A, _ORG_UUID_B],- id="list_value",- ),- pytest.param(- _flag(groups=[_org_id_group(_ORG_UUID_A, operator=None)]),- [_ORG_UUID_A],- id="missing_operator_defaults_to_exact",- ),- pytest.param(_flag(groups=[]), [], id="empty_groups"),- pytest.param(- _flag(groups=[_org_id_group(_ORG_UUID_A, operator="icontains")]),- [],- id="ignores_non_exact_operator",- ),- pytest.param(- _flag(- groups=[- {- "properties": [- {"key": "id", "type": "person", "value": _ORG_UUID_A, "operator": "exact"},- ]- }- ]- ),- [],- id="ignores_person_type",- ),- pytest.param(- _flag(- groups=[- {- "properties": [- {- "key": "name",- "type": "group",- "group_type_index": 0,- "value": "x",- "operator": "exact",- }- ]- }- ]- ),- [],- id="ignores_non_id_key",- ),- ],- )- def test_extracts_expected_org_ids(self, flag, expected):- assert _extract_organization_ids_from_flag(flag) == expected--@patch("products.web_analytics.dags.eager_web_analytics_precompute.is_cloud", return_value=True)-@patch("products.web_analytics.dags.eager_web_analytics_precompute.posthoganalytics.feature_flag_definitions")-class TestGetEagerTeamIds(APIBaseTest):- """The flag definition is read from the posthoganalytics SDK's local- evaluation cache. Tests patch the SDK accessor to return a stubbed- definitions list; `is_cloud` is forced True so the prod gate doesn't- refuse to resolve."""-- def _make_org_with_team(self, *, name: str = "Org") -> tuple[Team, str]:- org = Organization.objects.create(name=name)- team = Team.objects.create(organization=org, name=f"{name}-team")- return team, str(org.id)-- def test_returns_empty_when_flag_absent(self, defs, _is_cloud):- defs.return_value = []- assert get_eager_team_ids() == []-- def test_returns_empty_when_flag_inactive(self, defs, _is_cloud):- _, org_id = self._make_org_with_team()- defs.return_value = [_flag(groups=[_org_id_group(org_id)], active=False)]- assert get_eager_team_ids() == []-- def test_returns_empty_when_flag_deleted(self, defs, _is_cloud):- _, org_id = self._make_org_with_team()- defs.return_value = [_flag(groups=[_org_id_group(org_id)], deleted=True)]- assert get_eager_team_ids() == []-- def test_returns_empty_when_no_org_id_conditions(self, defs, _is_cloud):- defs.return_value = [_flag(groups=[{"rollout_percentage": 100}])]- assert get_eager_team_ids() == []-- def test_returns_empty_on_self_hosted(self, defs, _is_cloud):+class TestResolveEagerAudience:+ def test_returns_hardcoded_team_ids_on_cloud(self, _is_cloud):+ team_ids, reason, diag = _resolve_eager_audience()+ assert team_ids == list(EAGER_BASELINE_TEAM_IDS)+ assert reason == "ok"+ assert diag == {"teams_configured": len(EAGER_BASELINE_TEAM_IDS)}++ def test_returns_empty_on_self_hosted(self, _is_cloud):_is_cloud.return_value = False- _, org_id = self._make_org_with_team()- defs.return_value = [_flag(groups=[_org_id_group(org_id)])]- assert get_eager_team_ids() == []-- def test_returns_empty_when_sdk_returns_none(self, defs, _is_cloud):- defs.return_value = None- assert get_eager_team_ids() == []-- def test_resolves_single_org_to_team(self, defs, _is_cloud):- target, org_id = self._make_org_with_team(name="A")- self._make_org_with_team(name="Other")- defs.return_value = [_flag(groups=[_org_id_group(org_id)])]- assert get_eager_team_ids() == [target.pk]-- def test_unions_teams_across_multiple_org_groups(self, defs, _is_cloud):- a, org_a = self._make_org_with_team(name="A")- b, org_b = self._make_org_with_team(name="B")- self._make_org_with_team(name="C")- defs.return_value = [_flag(groups=[_org_id_group(org_a), _org_id_group(org_b)])]- assert get_eager_team_ids() == sorted([a.pk, b.pk])-- def test_returns_all_teams_in_an_enrolled_org(self, defs, _is_cloud):- org = Organization.objects.create(name="Multi")- team_a = Team.objects.create(organization=org, name="multi-a")- team_b = Team.objects.create(organization=org, name="multi-b")- defs.return_value = [_flag(groups=[_org_id_group(str(org.id))])]- assert get_eager_team_ids() == sorted([team_a.pk, team_b.pk])-- def test_unknown_org_id_resolves_to_empty(self, defs, _is_cloud):- # A flag listing an org UUID that no longer exists should not- # crash; the resolver just returns no teams.- defs.return_value = [_flag(groups=[_org_id_group(str(uuid4()))])]- assert get_eager_team_ids() == []-- def test_ignores_other_flags_in_the_sdk_cache(self, defs, _is_cloud):- target, org_id = self._make_org_with_team(name="Target")- defs.return_value = [- {"key": "some-other-flag", "active": True, "filters": {"groups": [_org_id_group(str(uuid4()))]}},- _flag(groups=[_org_id_group(org_id)]),- {"key": "yet-another-flag", "active": True, "filters": {"groups": [_org_id_group(str(uuid4()))]}},- ]- assert get_eager_team_ids() == [target.pk]+ team_ids, reason, _diag = _resolve_eager_audience()+ assert team_ids == []+ assert reason == "not_cloud"++ @patch("products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS", ())+ def test_returns_empty_when_no_teams_configured(self, _is_cloud):+ team_ids, reason, _diag = _resolve_eager_audience()+ assert team_ids == []+ assert reason == "no_teams_configured"@patch("products.web_analytics.dags.eager_web_analytics_precompute.is_cloud", return_value=True)-@patch("products.web_analytics.dags.eager_web_analytics_precompute.posthoganalytics.load_feature_flags")-@patch("products.web_analytics.dags.eager_web_analytics_precompute.posthoganalytics.feature_flag_definitions")class TestWarmEagerBaselineOp(APIBaseTest):"""Integration-shaped tests for the op. Query runners are patched sono ClickHouse traffic is needed — we assert orchestration semantics."""- @staticmethod- def _op_context() -> dagster.OpExecutionContext:- # The op declares the `posthoganalytics` resource so Dagster can- # initialize `personal_api_key` before the body runs; supply a- # mock for direct invocation.- return dagster.build_op_context(resources={"posthoganalytics": Mock()})-- def _enroll_org(self, *, name: str) -> tuple[Team, str]:- org = Organization.objects.create(name=name)- return Team.objects.create(organization=org, name=f"{name}-team"), str(org.id)+ def _enroll_teams(self, *, count: int) -> list[Team]:+ org = Organization.objects.create(name="Audience")+ return [Team.objects.create(organization=org, name=f"team-{i}") for i in range(count)]@patch("products.web_analytics.dags.eager_web_analytics_precompute.tag_queries")@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")- def test_one_team_failure_does_not_poison_other_teams(- self, get_runner, tag_queries_mock, defs, _load_flags, _is_cloud- ):- t1, org_a = self._enroll_org(name="A")- t2, org_b = self._enroll_org(name="B")- defs.return_value = [_flag(groups=[_org_id_group(org_a), _org_id_group(org_b)])]+ def test_one_team_failure_does_not_poison_other_teams(self, get_runner, tag_queries_mock, _is_cloud):+ t1, t2 = self._enroll_teams(count=2)ok_runner = Mock()ok_runner.run.return_value = None@@ -245,8 +66,11 @@ class TestWarmEagerBaselineOp(APIBaseTest):get_runner.side_effect = runner_factory- context = self._op_context()- result = warm_eager_baseline_op(context)+ with patch(+ "products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS",+ (t1.pk, t2.pk),+ ):+ result = warm_eager_baseline_op(dagster.build_op_context())assert result["teams"] == 2assert result["warmed"] == _QUERIES_PER_TEAM # only t2 succeeds@@ -255,7 +79,6 @@ class TestWarmEagerBaselineOp(APIBaseTest):assert ok_runner.run.call_count == _QUERIES_PER_TEAMassert bad_runner.run.call_count == _QUERIES_PER_TEAM- # Both teams must hit the same matrix.called_team_ids = {call.kwargs.get("team", call.args[1] if len(call.args) > 1 else None).pkfor call in get_runner.call_args_list@@ -266,28 +89,23 @@ class TestWarmEagerBaselineOp(APIBaseTest):assert tag_queries_mock.call_count == _QUERIES_PER_TEAM * 2@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")- def test_returns_zeroed_metadata_when_no_teams_enrolled(self, get_runner, defs, _load_flags, _is_cloud):- defs.return_value = []- context = self._op_context()- result = warm_eager_baseline_op(context)+ @patch("products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS", ())+ def test_returns_zeroed_metadata_when_no_teams_configured(self, get_runner, _is_cloud):+ result = warm_eager_baseline_op(dagster.build_op_context())assert result == {"teams": 0, "warmed": 0, "failed": 0, "skipped": 0}get_runner.assert_not_called()- def test_forces_synchronous_flag_load_before_resolving_audience(self, defs, load_flags, _is_cloud):- # The SDK's background poller runs on a 90s interval; this op- # subprocess finishes in seconds, so we must force a sync load- # or `feature_flag_definitions()` returns empty.- defs.return_value = []- warm_eager_baseline_op(self._op_context())- load_flags.assert_called_once_with()-- def test_load_failure_does_not_abort_the_run(self, defs, load_flags, _is_cloud):- # A flaky local-evaluation endpoint should not crash the op —- # the run continues with whatever the SDK already has cached.- load_flags.side_effect = RuntimeError("network blip")- defs.return_value = []- result = warm_eager_baseline_op(self._op_context())- assert result == {"teams": 0, "warmed": 0, "failed": 0, "skipped": 0}+ @patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")+ def test_skips_team_ids_that_do_not_exist_in_db(self, get_runner, _is_cloud):+ # A team ID in the hardcoded list might be removed from the DB+ # before the constant is updated; the run should not crash.+ with patch(+ "products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS",+ (99999999,),+ ):+ result = warm_eager_baseline_op(dagster.build_op_context())+ assert result == {"teams": 1, "warmed": 0, "failed": 0, "skipped": 1}+ get_runner.assert_not_called()class TestWarmBaselineForTeam(APIBaseTest):