: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): add eager precomputation in dagster for web analytics queries (#59529)
Lucas Ricoy94382508df58
diff --git a/posthog/dags/locations/web_analytics.py b/posthog/dags/locations/web_analytics.pyindex 3538996c30d8..093872050ba3 100644--- a/posthog/dags/locations/web_analytics.py+++ b/posthog/dags/locations/web_analytics.py@@ -5,6 +5,7 @@ from posthog.settings import TESTfrom products.web_analytics.dags import (cache_favicons,cache_warming,+ eager_web_analytics_precompute,web_analytics_watchdog,web_pre_aggregated_accuracy,web_preaggregated,@@ -20,6 +21,7 @@ schedules = [web_preaggregated.web_pre_aggregate_current_day_schedule,web_preaggregated_team_selection.web_analytics_team_candidates_schedule,cache_warming.web_analytics_cache_warming_schedule,+ eager_web_analytics_precompute.web_analytics_eager_baseline_warming_schedule,cache_favicons.cache_authorized_domain_favicons_schedule,web_analytics_watchdog.web_analytics_watchdog_schedule,]@@ -48,6 +50,7 @@ defs = dagster.Definitions(web_preaggregated_team_selection.web_analytics_team_candidates_job,web_analytics_watchdog.web_analytics_watchdog_job,cache_warming.web_analytics_cache_warming_job,+ eager_web_analytics_precompute.web_analytics_eager_baseline_warming_job,cache_favicons.cache_authorized_domain_favicons_job,],schedules=schedules,diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex 9d2cf828ef06..b81a27dd5d3f 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -147,7 +147,7 @@ Roughly:8. **Tests** — round-trip (lazy == raw) parameterized over team timezones, gate fallthrough for each disqualifying condition, half-hour-offset fallthrough, cache hit (second call doesn't create new jobs).9. **Cache warmer** — add the new `query_type` to the warmer DAG's allowlist in `products/web_analytics/dags/cache_warming.py`.-Roadmap order in `~/notes/work/posthog/web-analytics/investigations/2026-05-19-lazy-computation-candidates.md`: `web_overview_query` (shipped), `stats_table_path_bounce_query` (shipped — this PR), `stats_table_main_query` (next), then `web_goals_query` deferred for custom-goal-definition complexity.+Rollout order across query families: `web_overview_query` (shipped), `stats_table_path_bounce_query` (shipped — this PR), `stats_table_main_query` (next), then `web_goals_query` deferred for custom-goal-definition complexity.## Lazy computation for the PATHS tile@@ -250,6 +250,24 @@ The runner re-partitions the resulting `(band, path, value)` tuples into the `go2. **Adding a metric** (e.g. TTFB) is a schema change — add the column to `web_vitals_paths_preaggregated`, the HogQL table registration, the INSERT template, and the `_METRIC_STATE_COLUMN` map.3. **Bands are computed in ClickHouse from the runtime thresholds**, not stored — so a threshold change is free on the read side.+## Eager baseline warming (hourly Dagster job)++The lazy path computes on first read, but for high-traffic teams the dashboard's main tiles are requested constantly — there's no reason to make the first user of every cycle pay the INSERT cost. The eager job pre-warms the same lazy precompute cache (and the Django response cache) for a fixed query matrix, ahead of users.++- **Location**: `products/web_analytics/dags/eager_web_analytics_precompute.py`+- **Schedule**: `5 * * * *` (hourly, offset 5 min from the existing `cache_warming_schedule` at `0 * * * *`); skipped if a prior run is still in flight (`check_for_concurrent_runs`).+- **Window**: trailing 28 days. The lazy precompute stores per-day buckets, so a 28-day warm naturally covers any sub-window the dashboard asks for.+- **Matrix per team**: `WebOverviewQuery` + `WebGoalsQuery` + `WebVitalsPathBreakdownQuery` + one `WebStatsTableQuery` per `WebStatsBreakdown` rendered by the dashboard (~23 breakdowns including `FrustrationMetrics`).+- **Per-query opt-in**: every warmer query sets `useWebAnalyticsPrecompute=True` so the lazy precompute path accepts it; without this the gate rejects via `PerQueryOptInNotSet` and the warming is a silent no-op.+- **Freshness handoff**: each payload is dispatched via `get_query_runner(...).run(...)`. The runner routes through its family's `*_lazy_precompute.py` module, which calls `ensure_*_precomputed` — already idempotent. The DAG does not enumerate windows or inspect job state; the runner is the source of truth for what's stale.+- **Audience**: teams belonging to organizations rolled out on the `web-analytics-precompute-toggle` feature flag — the same flag the runtime lazy read path checks. The job parses the flag's `Match organizations against id equals <uuid>` group conditions and resolves them to teams via `Team.objects.filter(organization_id__in=...)`. The flag lives on PostHog's internal dogfooding project; self-hosted instances are gated out via `is_cloud()` so a same-keyed flag on someone else's team-2 doesn't trigger anything.+- **Audience cap**: 200 teams. A typo in the flag config fails-loudly (op returns with `skipped=N` and zero warmed) rather than silently overloading ClickHouse.+- **Cycle budget**: 45 minutes of wall-clock; remaining teams are reported as `skipped` if the budget is exhausted. The concurrency guard absorbs the next tick.++Because the eager job and the lazy read path consult the same flag, the warming audience never drifts from the audience the read path will actually serve — there is no second flag to keep in sync.++This job is complementary to `cache_warming.py`, which replays whatever queries users actually ran in the last N days. The eager job covers the fixed UI matrix; the replay job covers the long tail of team-specific filter combinations.+## Related code- `posthog/hogql_queries/web_analytics/web_overview.py` — runner@@ -264,3 +282,4 @@ The runner re-partitions the resulting `(band, path, value)` tuples into the `go- `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` — vitals lazy path- `posthog/clickhouse/preaggregation/web_vitals_paths_preaggregated_sql.py` — vitals schema- `products/analytics_platform/backend/lazy_computation/` — framework + CONSISTENCY.md + README+- `products/web_analytics/dags/eager_web_analytics_precompute.py` — hourly baseline pre-warmerdiff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pynew file mode 100644index 000000000000..1567a5d17a68--- /dev/null+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -0,0 +1,326 @@+"""Eager web analytics precompute — hourly baseline warming.++A single Dagster job that pre-warms the lazy precompute cache for the+Web 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.++The job is intentionally thin: it enumerates the dashboard's query+families and dispatches each through `get_query_runner(...).run(...)`.+The runner routes through its family's lazy precompute path, which+already knows what's stale and INSERTs only what's missing. This DAG is+the *trigger*; the runner is the source of truth for freshness.++Why this exists+---------------+The lazy precompute path caches per-day buckets in `web_*_preaggregated`+tables with a 2h TTL. For high-traffic teams the dashboard's main tiles+are requested constantly — there is no reason to compute them reactively.+Running the same query set ahead of every reasonable visit keeps the+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 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.++This job is complementary to `cache_warming.py`, which replays whatever+queries users actually ran. The eager job covers the fixed UI matrix;+the replay covers the long tail (custom hosts, custom filters, etc.).+"""++import dagster+import structlog+import posthoganalytics+from prometheus_client import Counter++from posthog.schema import WebStatsBreakdown++from posthog.hogql.constants import LimitContext++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.cloud_utils import is_cloud+from posthog.dags.common import JobOwners+from posthog.event_usage import EventSource+from posthog.hogql_queries.query_runner import get_query_runner+from posthog.models import Team++from products.web_analytics.dags.web_preaggregated_utils import check_for_concurrent_runs++logger = structlog.get_logger(__name__)+++EAGER_FLAG_KEY = "web-analytics-precompute-toggle"++# Single warming window: the trailing 28 days. The lazy precompute path+# stores per-day buckets, so a 28-day warm naturally serves any user+# request for a sub-window (today, last 7d, etc.) via the lazy CH cache.+BASELINE_WINDOW_DAYS = 28+++# The set of `WebStatsBreakdown` values rendered as tiles in the Web+# analytics dashboard (see `frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx`).+# `FrustrationMetrics` is treated as a regular breakdown — the dashboard+# renders it via the same `WebStatsTableQuery` shape.+BASELINE_BREAKDOWNS: tuple[WebStatsBreakdown, ...] = (+ WebStatsBreakdown.PAGE,+ WebStatsBreakdown.INITIAL_PAGE,+ WebStatsBreakdown.EXIT_PAGE,+ WebStatsBreakdown.SCREEN_NAME,+ WebStatsBreakdown.INITIAL_CHANNEL_TYPE,+ WebStatsBreakdown.INITIAL_REFERRING_DOMAIN,+ WebStatsBreakdown.INITIAL_REFERRING_URL,+ WebStatsBreakdown.INITIAL_UTM_SOURCE,+ WebStatsBreakdown.INITIAL_UTM_MEDIUM,+ WebStatsBreakdown.INITIAL_UTM_CAMPAIGN,+ WebStatsBreakdown.INITIAL_UTM_CONTENT,+ WebStatsBreakdown.INITIAL_UTM_TERM,+ WebStatsBreakdown.INITIAL_UTM_SOURCE_MEDIUM_CAMPAIGN,+ WebStatsBreakdown.BROWSER,+ WebStatsBreakdown.OS,+ WebStatsBreakdown.VIEWPORT,+ WebStatsBreakdown.DEVICE_TYPE,+ WebStatsBreakdown.COUNTRY,+ WebStatsBreakdown.REGION,+ WebStatsBreakdown.CITY,+ WebStatsBreakdown.LANGUAGE,+ WebStatsBreakdown.TIMEZONE,+ WebStatsBreakdown.FRUSTRATION_METRICS,+)+++EAGER_PRECOMPUTE_BASELINE_WARMED = Counter(+ "web_analytics_eager_precompute_baseline_warmed_total",+ "Total baseline queries warmed by the eager web analytics precompute job, labeled by query kind.",+ ["query_kind"],+)+EAGER_PRECOMPUTE_BASELINE_FAILED = Counter(+ "web_analytics_eager_precompute_baseline_failed_total",+ "Total baseline queries that failed during eager web analytics warming, labeled by query kind and exception type.",+ ["query_kind", "error_type"],+)+++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 get_eager_team_ids() -> list[int]:+ """Resolve the audience: teams belonging to organizations rolled out+ on the `web-analytics-precompute-toggle` flag.++ Returns `[]` for any of: not running on PostHog Cloud, flag absent+ from the SDK's local-evaluation cache (e.g. inactive/deleted), no+ organization-id conditions parsed. The empty-list result cleanly+ turns the warming op into a no-op.+ """+ if not is_cloud():+ return []++ flag = _find_flag_definition(EAGER_FLAG_KEY)+ if flag is None:+ return []++ org_ids = _extract_organization_ids_from_flag(flag)+ if not org_ids:+ return []++ return list(Team.objects.filter(organization_id__in=org_ids).values_list("pk", flat=True).distinct().order_by("pk"))+++def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) -> tuple[int, int]:+ """Run the full tile matrix for one team. Returns (warmed, failed).++ The matrix mirrors the Web analytics dashboard's main tiles — overview,+ goals, vitals path breakdown, and one `WebStatsTableQuery` per+ breakdown in `BASELINE_BREAKDOWNS`. Each payload is handed to+ `get_query_runner(...).run(...)`, which dispatches into the family's+ lazy precompute path; the runner — not this DAG — decides what's+ stale and inserts only what's missing.++ `useWebAnalyticsPrecompute=True` is required — without it the lazy+ path rejects the query via `PerQueryOptInNotSet` and the warmer+ silently falls back to legacy compute.++ Failures per query are caught so one broken breakdown doesn't poison+ the rest of the team's matrix or the rest of the run.+ """+ common = {+ "dateRange": {"date_from": f"-{BASELINE_WINDOW_DAYS}d"},+ "properties": [],+ "filterTestAccounts": True,+ "useWebAnalyticsPrecompute": True,+ }+ queries: list[dict] = [+ {"kind": "WebOverviewQuery", **common},+ {"kind": "WebGoalsQuery", "limit": 10, **common},+ # Vitals path-breakdown lazy precompute keys its cache on `doPathCleaning`+ # (see `web_vitals_paths_lazy_precompute._build_placeholders`). The+ # dashboard defaults this to True (the team's `isPathCleaningEnabled`+ # selector). Warming with True matches the dashboard's request.+ {"kind": "WebVitalsPathBreakdownQuery", "doPathCleaning": True, **common},+ ]+ for breakdown in BASELINE_BREAKDOWNS:+ query: dict = {"kind": "WebStatsTableQuery", "breakdownBy": breakdown.value, "limit": 10, **common}+ # PAGE and INITIAL_PAGE route through `web_stats_paths_lazy_precompute`,+ # which gates on `includeBounceRate=True` (the dashboard's Paths and+ # Entry-paths tiles enable it). Without this flag the warmer falls+ # through to the raw stats query and the paths preagg table stays cold.+ if breakdown in (WebStatsBreakdown.PAGE, WebStatsBreakdown.INITIAL_PAGE):+ query["includeBounceRate"] = True+ queries.append(query)++ warmed = 0+ failed = 0+ for query in queries:+ kind = str(query.get("kind"))+ breakdown_value = query.get("breakdownBy")+ label = f"{kind}:{breakdown_value}" if breakdown_value else kind+ try:+ # Tag BEFORE constructing the runner. `tag_queries` writes to+ # a contextvar; any I/O the runner does at construction time+ # inherits these tags, so attribution stays consistent.+ tag_queries(+ team_id=team.pk,+ trigger="webAnalyticsEagerBaselineWarming",+ feature=Feature.CACHE_WARMUP,+ product=Product.WEB_ANALYTICS,+ )+ runner = get_query_runner(query=query, team=team, limit_context=LimitContext.QUERY_ASYNC)+ runner.run(analytics_props={"source": EventSource.CACHE_WARMING})+ EAGER_PRECOMPUTE_BASELINE_WARMED.labels(query_kind=label).inc()+ warmed += 1+ except Exception as exc:+ EAGER_PRECOMPUTE_BASELINE_FAILED.labels(query_kind=label, error_type=type(exc).__name__).inc()+ context.log.exception(f"eager_baseline_warming_query_failed team={team.pk} query={label}")+ failed += 1+ return warmed, failed+++def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int]:+ """Run the baseline tile matrix against every flag-enrolled team."""+ team_ids = get_eager_team_ids()+ context.log.info(f"eager_baseline_warming_start teams={len(team_ids)}")++ # Bulk-load teams once instead of N+1 per-team get().+ teams_by_id = {t.pk: t for t in Team.objects.filter(pk__in=team_ids).select_related("organization")}++ warmed = 0+ failed = 0+ skipped = 0+ for team_id in team_ids:+ team = teams_by_id.get(team_id)+ if team is None:+ context.log.warning(f"eager_baseline_warming_team_missing team_id={team_id}")+ skipped += 1+ continue++ team_warmed, team_failed = _warm_baseline_for_team(context, team)+ warmed += team_warmed+ failed += team_failed++ context.log.info(f"eager_baseline_warming_complete warmed={warmed} failed={failed} skipped={skipped}")+ result = {"teams": len(team_ids), "warmed": warmed, "failed": failed, "skipped": skipped}+ context.add_output_metadata(result)+ return result+++ 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."+ ),+ tags={+ "owner": JobOwners.TEAM_WEB_ANALYTICS.value,+ # Dagster terminates the run if it exceeds this; the next scheduled+ # tick (5 min later) starts fresh.+ "dagster/max_runtime": str(45 * 60),+ },+)+def web_analytics_eager_baseline_warming_job():+ warm_eager_baseline_op()+++ # Hourly. The lazy cache's 2h TTL absorbs a single missed cycle, so+ # there's no need to align with shorter cadences. Offset by 5 min from+ # the top of the hour to avoid colliding with the existing+ # `web_analytics_cache_warming_schedule` (`0 * * * *`).+ cron_schedule="5 * * * *",+ job=web_analytics_eager_baseline_warming_job,+ execution_timezone="UTC",+ tags={"owner": JobOwners.TEAM_WEB_ANALYTICS.value},+)+def web_analytics_eager_baseline_warming_schedule(+ context: dagster.ScheduleEvaluationContext,+) -> "dagster.RunRequest | dagster.SkipReason":+ skip_reason = check_for_concurrent_runs(context)+ if skip_reason:+ return skip_reason+ return dagster.RunRequest()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.pynew file mode 100644index 000000000000..a96189059ee4--- /dev/null+++ b/products/web_analytics/dags/tests/test_eager_web_analytics_precompute.py@@ -0,0 +1,351 @@+from uuid import uuid4++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import Mock, patch++import dagster++from posthog.schema import WebStatsBreakdown++from posthog.models import Organization, Team++from products.web_analytics.dags.eager_web_analytics_precompute import (+ BASELINE_BREAKDOWNS,+ BASELINE_WINDOW_DAYS,+ EAGER_FLAG_KEY,+ _extract_organization_ids_from_flag,+ _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):+ _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]+++@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 TestWarmEagerBaselineOp(APIBaseTest):+ """Integration-shaped tests for the op. Query runners are patched so+ no ClickHouse traffic is needed — we assert orchestration semantics."""++ 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)++ @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, _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)])]++ ok_runner = Mock()+ ok_runner.run.return_value = None+ bad_runner = Mock()+ bad_runner.run.side_effect = RuntimeError("boom")++ def runner_factory(query, team, limit_context):+ return bad_runner if team.pk == t1.pk else ok_runner++ get_runner.side_effect = runner_factory++ context = dagster.build_op_context()+ result = warm_eager_baseline_op(context)++ assert result["teams"] == 2+ assert result["warmed"] == _QUERIES_PER_TEAM # only t2 succeeds+ assert result["failed"] == _QUERIES_PER_TEAM # only t1 fails+ assert result["skipped"] == 0+ assert ok_runner.run.call_count == _QUERIES_PER_TEAM+ assert 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).pk+ for call in get_runner.call_args_list+ }+ assert called_team_ids == {t1.pk, t2.pk}++ # Tagging fires for every query so query_log attribution is intact.+ 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, _is_cloud):+ defs.return_value = []+ context = dagster.build_op_context()+ result = warm_eager_baseline_op(context)+ assert result == {"teams": 0, "warmed": 0, "failed": 0, "skipped": 0}+ get_runner.assert_not_called()+++class TestWarmBaselineForTeam(APIBaseTest):+ @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_warms_full_matrix(self, get_runner, tag_queries_mock):+ runner = Mock()+ runner.run.return_value = None+ get_runner.return_value = runner++ warmed, failed = _warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)++ assert warmed == _QUERIES_PER_TEAM+ assert failed == 0+ assert runner.run.call_count == _QUERIES_PER_TEAM++ @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_warms_every_breakdown_with_correct_quirks(self, get_runner, tag_queries_mock):+ # PAGE/INITIAL_PAGE need includeBounceRate; vitals needs doPathCleaning.+ # Other breakdowns must NOT carry includeBounceRate.+ captured: list[dict] = []++ def capture(query, team, limit_context):+ captured.append(query)+ return Mock(run=Mock())++ get_runner.side_effect = capture+ _warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)++ kinds = {q["kind"] for q in captured}+ assert {"WebOverviewQuery", "WebGoalsQuery", "WebVitalsPathBreakdownQuery"}.issubset(kinds)++ windows = {q["dateRange"]["date_from"] for q in captured}+ assert windows == {f"-{BASELINE_WINDOW_DAYS}d"}++ # Every query must opt in to precompute and filter test accounts.+ assert all(q["useWebAnalyticsPrecompute"] is True for q in captured)+ assert all(q["filterTestAccounts"] is True for q in captured)++ vitals = next(q for q in captured if q["kind"] == "WebVitalsPathBreakdownQuery")+ assert vitals["doPathCleaning"] is True++ for q in captured:+ if q["kind"] != "WebStatsTableQuery":+ continue+ if q["breakdownBy"] in (WebStatsBreakdown.PAGE.value, WebStatsBreakdown.INITIAL_PAGE.value):+ assert q["includeBounceRate"] is True+ else:+ assert "includeBounceRate" not in q++ # Every baseline breakdown must be covered.+ seen_breakdowns = {q["breakdownBy"] for q in captured if q["kind"] == "WebStatsTableQuery"}+ assert seen_breakdowns == {b.value for b in BASELINE_BREAKDOWNS}++ @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_tag_queries_fires_before_get_query_runner(self, get_runner, tag_queries_mock):+ # Order matters: tag_queries writes to a contextvar; any I/O the+ # runner does at construction time must inherit the warmer's tags.+ call_order: list[str] = []++ def record_tag(**kwargs):+ call_order.append("tag")++ def record_get_runner(**kwargs):+ call_order.append("get_runner")+ return Mock(run=Mock())++ tag_queries_mock.side_effect = record_tag+ get_runner.side_effect = record_get_runner++ _warm_baseline_for_team(Mock(spec=dagster.OpExecutionContext), self.team)++ # For each query in the matrix the order must be tag then get_runner.+ pairs = list(zip(call_order[0::2], call_order[1::2]))+ assert pairs and all(p == ("tag", "get_runner") for p in pairs)+++class TestJobConfiguration:+ def test_job_carries_dagster_max_runtime_tag(self):+ # Dagster terminates the run if it exceeds this; the next scheduled+ # tick (5 min later) starts fresh. Matches `web_preaggregated.py`.+ tags = web_analytics_eager_baseline_warming_job.tags+ assert tags is not None+ assert "dagster/max_runtime" in tags+ assert int(tags["dagster/max_runtime"]) >= 60