Skip to content

: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.

fix(web-analytics): gate lazy precompute on a team-id setting (#61942)

Lucas Ricoydd57f4029e00
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index f05cff3a82f1..da91d1179ae7 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -6,7 +6,7 @@ import structlog
from corsheaders.defaults import default_headers
from posthog.scopes import get_scope_descriptions
-from posthog.settings.base_variables import BASE_DIR, DEBUG, TEST
+from posthog.settings.base_variables import BASE_DIR, CLOUD_DEPLOYMENT, DEBUG, TEST
from posthog.settings.utils import get_from_env, get_list, str_to_bool
from posthog.utils_cors import CORS_ALLOWED_TRACING_HEADERS
@@ -829,3 +829,19 @@ ELEMENT_STATS_DEFAULT_LIMIT = get_from_env("ELEMENT_STATS_DEFAULT_LIMIT", 50_000
# Sharing configuration settings
SHARING_TOKEN_GRACE_PERIOD_SECONDS = 60 * 5 # 5 minutes
+
+# Teams force-enrolled in web analytics lazy precompute: the eligibility gate
+# bypasses the org rollout flag for these, and the eager warmer uses the same
+# list as its audience — one source of truth so warmer and reader cannot drift.
+# The default enrolls the Cloud dogfooding team (project 2) ONLY on Cloud —
+# never self-hosted, where lazy precompute is Cloud-only and project id 2 is an
+# arbitrary customer project. A comma-separated env var overrides it on any
+# deployment; changing enrollment is a deploy-time env-var change (Django +
+# Dagster), not runtime-overridable.
+_LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS = (
+ "2" if (CLOUD_DEPLOYMENT or "").upper() in ("EU", "US", "DEV", "E2E") and not TEST else ""
+)
+WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS: list[int] = [
+ int(team_id)
+ for team_id in get_list(get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))
+]
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
index e3a2b2fb6d1f..8edb471a5446 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_analytics_metrics.py
@@ -368,7 +368,7 @@ class TestWebAnalyticsMetrics(TestCase):
runner.query = MagicMock(useWebAnalyticsPrecompute=True)
with patch(
- "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
return_value=False,
):
assert can_use_lazy_precompute(runner, log_prefix=family) is False
@@ -393,7 +393,7 @@ class TestWebAnalyticsMetrics(TestCase):
runner.query = MagicMock(useWebAnalyticsPrecompute=False)
with patch(
- "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
return_value=True,
):
assert can_use_lazy_precompute(runner, log_prefix=family) is False
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
index f578cf77c6fe..bc86eb864a17 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -1,6 +1,8 @@
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin
from unittest import mock
+from django.test import override_settings
+
from structlog.contextvars import get_contextvars
from posthog.schema import (
@@ -16,9 +18,32 @@ from posthog.schema import (
from posthog.clickhouse.query_tagging import get_query_tag_value
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
-from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import compute_filters_eligibility_hash
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
+ compute_filters_eligibility_hash,
+ is_precompute_enabled_for_team,
+)
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+_COMMON = "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common"
+
+
+class TestIsPrecomputeEnabledForTeam(BaseTest):
+ @mock.patch(f"{_COMMON}.is_org_feature_flag_enabled", return_value=False)
+ def test_team_in_setting_bypasses_org_flag(self, flag) -> None:
+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):
+ assert is_precompute_enabled_for_team(self.team) is True
+ flag.assert_not_called() # short-circuits before the flag is ever evaluated
+
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])
+ @mock.patch(f"{_COMMON}.is_org_feature_flag_enabled", return_value=True)
+ def test_team_not_in_setting_falls_back_to_enabled_flag(self, _flag) -> None:
+ assert is_precompute_enabled_for_team(self.team) is True
+
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])
+ @mock.patch(f"{_COMMON}.is_org_feature_flag_enabled", return_value=False)
+ def test_team_not_in_setting_with_flag_off_is_ineligible(self, _flag) -> None:
+ assert is_precompute_enabled_for_team(self.team) is False
+
def _overview(
*,
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
index 7ca10a6cd9ca..75c6642b9db4 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_overview_lazy_precompute.py
@@ -45,7 +45,7 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# team. Outside this context manager the default `posthoganalytics.feature_enabled`
# returns False (no API key in tests), which models a flag-disabled org.
return patch(
- "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
return_value=True,
)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
index 0218b54594a1..5b0d4d62b7b1 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
@@ -57,7 +57,7 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# manager the default `posthoganalytics.feature_enabled` returns False
# (no API key in tests), which models a flag-disabled org.
return patch(
- "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
return_value=True,
)
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
index fe7b473608fd..b1086b87d327 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_vitals_paths_lazy_precompute.py
@@ -49,7 +49,7 @@ class TestWebVitalsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# manager the default `posthoganalytics.feature_enabled` returns False
# (no API key in tests), which models a flag-disabled org.
return patch(
- "products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute.posthoganalytics.feature_enabled",
+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
return_value=True,
)
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
index 8279e2f59a8e..a34c6de10d1d 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_lazy_precompute.py
@@ -13,7 +13,6 @@ from datetime import UTC, datetime, timedelta
from typing import Optional, Protocol, Union
import structlog
-import posthoganalytics
from prometheus_client import Counter
from posthog.schema import (
@@ -30,6 +29,8 @@ from posthog.hogql.transforms.preaggregated_table_transformation import is_integ
from posthog.models.team import Team
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import is_precompute_enabled_for_team
+
logger = structlog.get_logger(__name__)
@@ -241,20 +242,7 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
# None (falsy) on failure, so a flag-service outage fails-closed.
# - `query.useWebAnalyticsPrecompute` (per-query parameter set by the
# "Allow precompute" toggle).
- if not posthoganalytics.feature_enabled(
- "web-analytics-precompute-toggle",
- str(runner.team.uuid),
- groups={
- "organization": str(runner.team.organization_id),
- "project": str(runner.team.id),
- },
- group_properties={
- "organization": {"id": str(runner.team.organization_id)},
- "project": {"id": str(runner.team.id)},
- },
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- ):
+ if not is_precompute_enabled_for_team(runner.team):
raise OrgFeatureFlagDisabled()
if query.useWebAnalyticsPrecompute is not True:
diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
index 95dfad93d53c..2b49996de9be 100644
--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
@@ -14,6 +14,8 @@ from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import Any, Optional
+from django.conf import settings
+
import structlog
import posthoganalytics
@@ -159,6 +161,21 @@ def is_org_feature_flag_enabled(team: Team) -> bool:
)
+def is_precompute_enabled_for_team(team: Team) -> bool:
+ """Whether a team should take the lazy precompute path.
+
+ Short-circuits on the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` env-var
+ setting before evaluating the org rollout flag. The list is the shared
+ source of truth with the eager warmer, and — unlike the flag — does not rely
+ on local flag-definition evaluation, which isn't reliably available outside
+ the Django app (e.g. the Dagster warmer, where `only_evaluate_locally`
+ returned falsy and silently dropped the warmer onto the raw path).
+ """
+ if team.id in settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS:
+ return True
+ return is_org_feature_flag_enabled(team)
+
+
def check_common_eligibility(
*,
team: Team,
@@ -179,7 +196,7 @@ def check_common_eligibility(
(org flag off, etc.) without touching `QueryDateRange.date_from()` —
which can trigger a ClickHouse min-timestamp lookup for `-all` ranges.
"""
- if not is_org_feature_flag_enabled(team):
+ if not is_precompute_enabled_for_team(team):
raise OrgFeatureFlagDisabled()
if use_web_analytics_precompute is not True:
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.py
index a4aaaba7397a..b1e60688e2f4 100644
--- a/products/web_analytics/dags/eager_web_analytics_precompute.py
+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py
@@ -2,7 +2,7 @@
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 in the hardcoded `EAGER_BASELINE_TEAM_IDS` list.
+for every team in the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` setting.
The job is intentionally thin: it enumerates the dashboard's query
families and dispatches each through `get_query_runner(...).run(...)`.
@@ -20,11 +20,13 @@ cache perpetually warm, so user requests turn into pure reads.
Audience
--------
-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 audience is the `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` env-var
+setting (defaults to the Cloud dogfooding team on Cloud, empty elsewhere).
+The runtime read-path gate (`is_precompute_enabled_for_team`) consults the
+*same* setting to bypass the org rollout flag, so warmer and reader read
+one source of truth and cannot drift. Enrolling or removing a team is a
+deploy-time change to the env var (Django + Dagster pods), not
+runtime-overridable.
The job is a no-op on self-hosted instances (`is_cloud()` returns False)
since the lazy precompute infrastructure is Cloud-only.
@@ -36,6 +38,8 @@ the replay covers the long tail (custom hosts, custom filters, etc.).
import time
+from django.conf import settings
+
import dagster
import structlog
from prometheus_client import Counter
@@ -51,17 +55,12 @@ 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.backend.hogql_queries.web_lazy_precompute_common import is_precompute_enabled_for_team
from products.web_analytics.dags.web_preaggregated_utils import check_for_concurrent_runs
logger = structlog.get_logger(__name__)
-# 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
# request for a sub-window (today, last 7d, etc.) via the lazy CH cache.
@@ -109,6 +108,11 @@ EAGER_PRECOMPUTE_BASELINE_FAILED = Counter(
"Total baseline queries that failed during eager web analytics warming, labeled by query kind and exception type.",
["query_kind", "error_type"],
)
+EAGER_PRECOMPUTE_NOT_LAZY_ELIGIBLE = Counter(
+ "web_analytics_eager_precompute_not_lazy_eligible_total",
+ "Teams skipped by the eager warmer because they are not lazy-precompute eligible "
+ "(the gate would route every tile through the raw path).",
+)
def _resolve_eager_audience() -> tuple[list[int], str, dict]:
@@ -120,7 +124,7 @@ def _resolve_eager_audience() -> tuple[list[int], str, dict]:
if not is_cloud():
return [], "not_cloud", {}
- team_ids = list(EAGER_BASELINE_TEAM_IDS)
+ team_ids = list(settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS)
diag = {"teams_configured": len(team_ids)}
if not team_ids:
return [], "no_teams_configured", diag
@@ -234,7 +238,7 @@ def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) ->
@dagster.op
def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int]:
- """Run the baseline tile matrix against every team in `EAGER_BASELINE_TEAM_IDS`."""
+ """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()
diag_str = " ".join(f"{k}={v}" for k, v in diagnostics.items())
@@ -260,6 +264,20 @@ def warm_eager_baseline_op(context: dagster.OpExecutionContext) -> dict[str, int
skipped += 1
continue
+ # Eligibility pre-check. The audience IS the precompute team list, so a
+ # team reaching here should always be eligible. If it isn't, the gate
+ # and the warmer audience have drifted and every tile would silently
+ # warm via the raw path — skip loudly rather than burn compute on it.
+ if not is_precompute_enabled_for_team(team):
+ EAGER_PRECOMPUTE_NOT_LAZY_ELIGIBLE.inc()
+ context.log.error(
+ f"eager_baseline_warming_not_lazy_eligible team={team_id} — "
+ f"skipping; the lazy gate would route every tile through the raw path"
+ )
+ logger.error("eager_baseline_warming_not_lazy_eligible", team_id=team_id)
+ skipped += 1
+ continue
+
team_started = time.monotonic()
team_warmed, team_failed = _warm_baseline_for_team(context, team)
logger.info(
@@ -294,7 +312,7 @@ 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 in `EAGER_BASELINE_TEAM_IDS`. Each query is "
+ f"{BASELINE_WINDOW_DAYS} days for every team in `WEB_ANALYTICS_LAZY_PRECOMPUTE_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."
),
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.py
index 1ba72d7d17fc..2d31f9014760 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,9 +1,12 @@
from collections.abc import MutableMapping
+from contextlib import contextmanager
from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import Mock, patch
+from django.test import override_settings
+
import dagster
from structlog.testing import capture_logs
@@ -14,24 +17,34 @@ from posthog.models import Organization, Team
from products.web_analytics.dags.eager_web_analytics_precompute import (
BASELINE_BREAKDOWNS,
BASELINE_WINDOW_DAYS,
- EAGER_BASELINE_TEAM_IDS,
_resolve_eager_audience,
_warm_baseline_for_team,
warm_eager_baseline_op,
web_analytics_eager_baseline_warming_job,
)
+_EAGER_MODULE = "products.web_analytics.dags.eager_web_analytics_precompute"
+
# Total queries per team: WebOverview + WebGoals + WebVitalsPathBreakdown + each WebStats breakdown.
_QUERIES_PER_TEAM = 3 + len(BASELINE_BREAKDOWNS)
-@patch("products.web_analytics.dags.eager_web_analytics_precompute.is_cloud", return_value=True)
+@contextmanager
+def _eager_audience(team_ids):
+ """Set the warmer audience (and, since the gate reads the same setting, the
+ lazy-eligibility list) to `team_ids`."""
+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=list(team_ids)):
+ yield
+
+
+@patch(f"{_EAGER_MODULE}.is_cloud", return_value=True)
class TestResolveEagerAudience:
- def test_returns_hardcoded_team_ids_on_cloud(self, _is_cloud):
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[2, 7])
+ def test_returns_team_ids_from_setting_on_cloud(self, _is_cloud):
team_ids, reason, diag = _resolve_eager_audience()
- assert team_ids == list(EAGER_BASELINE_TEAM_IDS)
+ assert team_ids == [2, 7]
assert reason == "ok"
- assert diag == {"teams_configured": len(EAGER_BASELINE_TEAM_IDS)}
+ assert diag == {"teams_configured": 2}
def test_returns_empty_on_self_hosted(self, _is_cloud):
_is_cloud.return_value = False
@@ -39,7 +52,7 @@ class TestResolveEagerAudience:
assert team_ids == []
assert reason == "not_cloud"
- @patch("products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS", ())
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])
def test_returns_empty_when_no_teams_configured(self, _is_cloud):
team_ids, reason, _diag = _resolve_eager_audience()
assert team_ids == []
@@ -70,10 +83,7 @@ class TestWarmEagerBaselineOp(APIBaseTest):
get_runner.side_effect = runner_factory
- with patch(
- "products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS",
- (t1.pk, t2.pk),
- ):
+ with _eager_audience([t1.pk, t2.pk]):
result = warm_eager_baseline_op(dagster.build_op_context())
assert result["teams"] == 2
@@ -92,22 +102,19 @@ class TestWarmEagerBaselineOp(APIBaseTest):
# Tagging fires for every query so query_log attribution is intact.
assert tag_queries_mock.call_count == _QUERIES_PER_TEAM * 2
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])
@patch("products.web_analytics.dags.eager_web_analytics_precompute.get_query_runner")
- @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()
+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[99999999])
@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())
+ # A team ID in the setting might be removed from the DB before the
+ # setting is updated; the run should not crash.
+ result = warm_eager_baseline_op(dagster.build_op_context())
assert result == {"teams": 1, "warmed": 0, "failed": 0, "skipped": 1}
get_runner.assert_not_called()
@@ -202,13 +209,7 @@ class TestEagerBaselineLogging(APIBaseTest):
def test_emits_structured_lifecycle_events_on_success(self, get_runner, _tag, _is_cloud):
get_runner.return_value = Mock(run=Mock(return_value=None))
- with (
- patch(
- "products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS",
- (self.team.pk,),
- ),
- capture_logs() as cap_logs,
- ):
+ with _eager_audience([self.team.pk]), capture_logs() as cap_logs:
warm_eager_baseline_op(dagster.build_op_context())
start = self._events(cap_logs, "eager_baseline_warming_start")
@@ -224,6 +225,9 @@ class TestEagerBaselineLogging(APIBaseTest):
tile_done = self._events(cap_logs, "eager_baseline_warming_tile_done")
assert len(tile_done) == _QUERIES_PER_TEAM
+ # Verify the tile indices cover the full matrix (symmetric with tile_start)
+ # so a wrong/constant idx in the done line can't slip through.
+ assert {t["tile"] for t in tile_done} == set(range(1, _QUERIES_PER_TEAM + 1))
assert all(t["status"] == "warmed" and "duration_ms" in t for t in tile_done)
team_logs = self._events(cap_logs, "eager_baseline_warming_team")
@@ -245,13 +249,7 @@ class TestEagerBaselineLogging(APIBaseTest):
def test_emits_query_failed_event_with_error_type(self, get_runner, _tag, _is_cloud):
get_runner.return_value = Mock(run=Mock(side_effect=RuntimeError("boom")))
- with (
- patch(
- "products.web_analytics.dags.eager_web_analytics_precompute.EAGER_BASELINE_TEAM_IDS",
- (self.team.pk,),
- ),
- capture_logs() as cap_logs,
- ):
+ with _eager_audience([self.team.pk]), capture_logs() as cap_logs:
warm_eager_baseline_op(dagster.build_op_context())
failed = self._events(cap_logs, "eager_baseline_warming_query_failed")
@@ -265,6 +263,30 @@ class TestEagerBaselineLogging(APIBaseTest):
assert self._events(cap_logs, "eager_baseline_warming_tile_done") == []
+@patch(f"{_EAGER_MODULE}.is_cloud", return_value=True)
+class TestEagerLazyEligibilityGuards(APIBaseTest):
+ """The warmer must never silently warm via the raw path: it skips
+ lazy-ineligible teams and alarms when a warm run inserts no cache keys."""
+
+ @patch(f"{_EAGER_MODULE}.tag_queries")
+ @patch(f"{_EAGER_MODULE}.get_query_runner")
+ def test_skips_team_that_is_not_lazy_eligible(self, get_runner, _tag, _is_cloud):
+ # The team is in the audience but the gate reports it ineligible — a
+ # drift the guard must catch rather than warm raw.
+ with (
+ override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]),
+ patch(f"{_EAGER_MODULE}.is_precompute_enabled_for_team", return_value=False),
+ capture_logs() as cap_logs,
+ ):
+ result = warm_eager_baseline_op(dagster.build_op_context())
+
+ assert result == {"teams": 1, "warmed": 0, "failed": 0, "skipped": 1}
+ get_runner.assert_not_called() # never warms a team it can't serve lazily
+ events = [log for log in cap_logs if log.get("event") == "eager_baseline_warming_not_lazy_eligible"]
+ assert len(events) == 1
+ assert events[0]["team_id"] == self.team.pk
+
+
class TestJobConfiguration:
def test_job_carries_dagster_max_runtime_tag(self):
# Dagster terminates the run if it exceeds this; the next scheduled