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.

feat(web-analytics): default precompute on for enrolled teams (#72645)

Lucas Ricoy4d50703e9331
diff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.md
index aba0ee9b6d7d..dfb0484ca41b 100644
--- a/products/web_analytics/PRECOMPUTATION.md
+++ b/products/web_analytics/PRECOMPUTATION.md
@@ -235,7 +235,7 @@ The runner re-partitions the resulting `(band, path, value)` tuples into the `go
### Eligibility gate
-`can_use_lazy_precompute` in `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` delegates to the shared gate with `require_integer_timezone=False` (see "Bucketing and timezones" above). The shared gate rejects: org feature flag off, per-query opt-in not set, conversion goal, sampling enabled, `sessionsV2JoinMode=uuid`, more than one property filter, anything other than a `$host` exact-equals filter, missing date range, and date range over 90 days.
+`can_use_lazy_precompute` in `products/web_analytics/backend/hogql_queries/web_vitals_paths_lazy_precompute.py` delegates to the shared gate with `require_integer_timezone=False` (see "Bucketing and timezones" above). The shared gate rejects: org feature flag off, explicit per-query opt-out (`useWebAnalyticsPrecompute=False` — an untouched toggle defaults on), conversion goal, sampling enabled, `sessionsV2JoinMode=uuid`, more than one property filter, anything other than a `$host` exact-equals filter, missing date range, and date range over 90 days.
### Observability
@@ -258,7 +258,7 @@ The lazy path computes on first read, but for high-traffic teams the dashboard's
- **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.
+- **Per-query toggle**: every warmer query sets `useWebAnalyticsPrecompute=True` explicitly. Precompute now defaults on for enrolled teams (only an explicit `False` opts out), so this is redundant — kept to make the warmer's intent explicit.
- **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.
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 f69ddb0f73b0..daccbc006175 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
@@ -385,7 +385,7 @@ class TestWebAnalyticsMetrics(TestCase):
("web_stats", "web_stats"),
]
)
- def test_lazy_precompute_per_query_opt_in_not_set_rejection(self, _name, family):
+ def test_lazy_precompute_per_query_opt_out_rejection(self, _name, family):
runner = MagicMock()
runner.team = MagicMock(pk=42, uuid="00000000-0000-0000-0000-000000000000", organization_id=7, id=42)
runner.query = MagicMock(useWebAnalyticsPrecompute=False)
@@ -399,7 +399,7 @@ class TestWebAnalyticsMetrics(TestCase):
assert (
_get_counter_value(
WEB_ANALYTICS_LAZY_PRECOMPUTE_REJECTED,
- {"family": family, "reason": "PerQueryOptInNotSet"},
+ {"family": family, "reason": "PerQueryOptedOut"},
)
== 1.0
)
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 84a9bbdd029d..23f99490cd17 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
@@ -36,7 +36,6 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
SESSION_SETTLING_SECONDS,
STALE_WHILE_REVALIDATE_SECONDS,
PerQueryOptedOut,
- PerQueryOptInNotSet,
TooManyFilters,
UnsupportedFilterKey,
_oom_pin_key,
@@ -114,13 +113,28 @@ class TestCheckCommonEligibilityUnrestricted(BaseTest):
resolve_date_range=_date_range,
)
- def test_restricted_team_rejects_untouched_opt_in(self) -> None:
+ def test_restricted_team_untouched_toggle_defaults_on(self) -> None:
+ # Re-introducing the old opt-in requirement would silently send every
+ # enrolled team without the UI toggle back to the raw path.
with override_settings(
WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],
WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[],
):
- with self.assertRaises(PerQueryOptInNotSet):
- self._check(use_precompute=None)
+ self._check(use_precompute=None)
+ with self.assertRaises(PerQueryOptedOut):
+ self._check(use_precompute=False)
+
+ @override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[],
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[],
+ )
+ @mock.patch(f"{_COMMON}.is_org_feature_flag_enabled", return_value=True)
+ def test_flag_enrolled_team_defaults_on_and_respects_opt_out(self, _flag) -> None:
+ # The fleet-rollout path: enrollment via the org flag alone must grant
+ # default-on reads, and the explicit opt-out must still be honored.
+ self._check(use_precompute=None)
+ with self.assertRaises(PerQueryOptedOut):
+ self._check(use_precompute=False)
def test_unrestricted_team_accepts_untouched_as_opt_out_default(self) -> None:
with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):
@@ -162,6 +176,27 @@ class TestCheckCommonEligibilityUnrestricted(BaseTest):
self._check(use_precompute=True, properties=props)
+class TestCacheKeyVariesWithRolloutState(BaseTest):
+ _RUNNER_MOD = "products.web_analytics.backend.hogql_queries.web_analytics_query_runner"
+
+ def _cache_key(self) -> str:
+ runner = WebOverviewQueryRunner(
+ team=self.team,
+ query=WebOverviewQuery(dateRange=DateRange(date_from="-7d"), properties=[]),
+ )
+ return runner.get_cache_key()
+
+ def test_flipping_enrollment_changes_cache_key(self) -> None:
+ # With default-on reads, disabling the rollout flag (the kill switch)
+ # must invalidate cached precompute-produced results — otherwise a bad
+ # rollout keeps serving from the result cache until it stales.
+ with mock.patch(f"{self._RUNNER_MOD}.is_precompute_enabled_for_team", return_value=True):
+ key_enabled = self._cache_key()
+ with mock.patch(f"{self._RUNNER_MOD}.is_precompute_enabled_for_team", return_value=False):
+ key_disabled = self._cache_key()
+ assert key_enabled != key_disabled
+
+
class TestHostFilterExpr(BaseTest):
def test_empty_properties_is_true_constant(self) -> None:
expr = host_filter_expr([], team=self.team)
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 b58aae8ebca0..f5760f578b6d 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
@@ -128,12 +128,8 @@ class OrgFeatureFlagDisabled(LazyPrecomputeIneligible):
pass
-class PerQueryOptInNotSet(LazyPrecomputeIneligible):
- pass
-
-
class PerQueryOptedOut(LazyPrecomputeIneligible):
- """Unrestricted team where the user explicitly turned precompute off."""
+ """The user explicitly turned the "Allow precompute" toggle off."""
pass
@@ -236,26 +232,21 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
"""
query = runner.query
- # Rollout gate: shared PostHog feature flag AND per-query opt-in.
+ # Rollout gate: shared PostHog feature flag AND per-query opt-out.
# - `web-analytics-precompute-toggle` (PostHog feature flag): the same
# flag the frontend already uses to show/hide the "Allow precompute"
# button in the Web Analytics ScenePanel. The flag is evaluated at the
# organization level. The SDK swallows its own exceptions and returns
# None (falsy) on failure, so a flag-service outage fails-closed.
# - `query.useWebAnalyticsPrecompute` (per-query parameter set by the
- # "Allow precompute" toggle).
+ # "Allow precompute" toggle): precompute defaults ON for every enrolled
+ # team — an untouched toggle (`None`) takes the precompute path; only an
+ # explicit `False` opts a query out.
if not is_precompute_enabled_for_team(runner.team):
raise OrgFeatureFlagDisabled()
- unrestricted = is_precompute_unrestricted_for_team(runner.team)
-
- # Unrestricted teams default to opt-out: only an explicit `False` rejects.
- # Restricted teams keep the opt-in default (`None`/`False` both reject).
- if unrestricted:
- if query.useWebAnalyticsPrecompute is False:
- raise PerQueryOptedOut()
- elif query.useWebAnalyticsPrecompute is not True:
- raise PerQueryOptInNotSet()
+ if query.useWebAnalyticsPrecompute is False:
+ raise PerQueryOptedOut()
# Half-hour-offset timezones (IST +5:30, Newfoundland -3:30, Nepal +5:45, etc.)
# can't be served by UTC hourly buckets without sub-hour precision. Skip them
@@ -283,6 +274,7 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
# arbitrary filters via `property_to_expr`, and each distinct filter set
# becomes a distinct cache key. Filters the INSERT can't express fail the
# job and fall back to the live query automatically.
+ unrestricted = is_precompute_unrestricted_for_team(runner.team)
if not unrestricted:
properties = query.properties or []
if len(properties) > 1:
diff --git a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
index e7d50fa60065..37aecba11467 100644
--- a/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
+++ b/products/web_analytics/backend/hogql_queries/web_analytics_query_runner.py
@@ -52,7 +52,10 @@ from products.web_analytics.backend.hogql_queries.metrics import (
WEB_ANALYTICS_QUERY_ERRORS,
)
from products.web_analytics.backend.hogql_queries.traffic_type import get_traffic_category_expr, get_traffic_type_expr
-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,
+)
logger = structlog.get_logger(__name__)
@@ -701,7 +704,12 @@ WHERE and(
def get_cache_key(self) -> str:
original = super().get_cache_key()
- return f"{original}_{self.team.path_cleaning_filters}"
+ # Precompute enrollment is part of the key so flipping the rollout flag
+ # invalidates cached results: with default-on reads, disabling the flag
+ # (the kill switch) must not keep serving cached precompute-produced
+ # responses until they stale out.
+ precompute = is_precompute_enabled_for_team(self.team)
+ return f"{original}_{self.team.path_cleaning_filters}_pc{int(precompute)}"
@cached_property
def events_session_property(self):
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 7fda3d247d9d..27f5babe3df6 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
@@ -1,7 +1,7 @@
"""Shared eligibility gate + helpers for web-analytics lazy precompute paths.
Both the web overview lazy precompute and the web stats PATHS lazy precompute
-share the same rollout/safety gate (org feature flag + per-query opt-in,
+share the same rollout/safety gate (org feature flag + per-query opt-out,
whole-hour timezone, no conversion goal, no sampling, no v2 UUID sessions,
at most one `$host` exact filter, bounded date range) and the same TTL /
session-pad / UTC-day helpers. Keeping a single source of truth avoids
@@ -406,12 +406,8 @@ class OrgFeatureFlagDisabled(LazyPrecomputeIneligible):
pass
-class PerQueryOptInNotSet(LazyPrecomputeIneligible):
- pass
-
-
class PerQueryOptedOut(LazyPrecomputeIneligible):
- """Unrestricted team where the user explicitly turned precompute off."""
+ """The user explicitly turned the "Allow precompute" toggle off."""
pass
@@ -490,8 +486,7 @@ def is_precompute_unrestricted_for_team(team: Team) -> bool:
"""Whether a team may precompute *any* web analytics query.
Unrestricted teams bypass the single-`$host`-exact filter-shape gate (any
- property filter becomes a distinct cache key) and treat the per-query toggle
- as opt-out rather than opt-in. Driven by the dedicated
+ property filter becomes a distinct cache key). Driven by the dedicated
`WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS` env-var setting.
"""
return team.id in settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS
@@ -547,15 +542,13 @@ def check_common_eligibility(
if not is_precompute_enabled_for_team(team):
raise OrgFeatureFlagDisabled()
- unrestricted = is_precompute_unrestricted_for_team(team)
+ # Precompute defaults ON for every enrolled team: an untouched toggle
+ # (`None`) takes the precompute path; only an explicit `False` (the
+ # "Allow precompute" toggle turned off) opts a query out.
+ if use_web_analytics_precompute is False:
+ raise PerQueryOptedOut()
- # Unrestricted teams default to opt-out: only an explicit `False` rejects.
- # Restricted teams keep the opt-in default (`None`/`False` both reject).
- if unrestricted:
- if use_web_analytics_precompute is False:
- raise PerQueryOptedOut()
- elif use_web_analytics_precompute is not True:
- raise PerQueryOptInNotSet()
+ unrestricted = is_precompute_unrestricted_for_team(team)
if not is_integer_timezone(team.timezone):
raise NonIntegerTimezone()
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.py
index bc6e93053911..ec7a7fba6971 100644
--- a/products/web_analytics/dags/eager_web_analytics_precompute.py
+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py
@@ -290,9 +290,9 @@ def _warm_baseline_for_team(context: dagster.OpExecutionContext, team: Team) ->
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.
+ `useWebAnalyticsPrecompute=True` is set explicitly. Precompute now
+ defaults on for enrolled teams (only an explicit `False` opts out),
+ so this is redundant — kept to make the warmer's intent explicit.
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.