: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): precompute any filter shape, capped per team (#73303)
Lucas Ricoy0f48c52f77e1
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 2e2a12af9bcf..ec97ef61650f 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1179,20 +1179,15 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS: list[int] = [for team_id in get_list(get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))]-# Teams allowed to precompute *any* web analytics query, not just the-# single-`$host`-exact filter shape the general gate permits. For these teams the-# eligibility gate skips the filter-shape restriction (arbitrary property filters-# become distinct cache keys via `property_to_expr`) and flips the per-query-# toggle from opt-in to opt-out (precompute runs unless the user explicitly turns-# it off). Membership here also implies precompute enrollment, so a team need not-# also appear in `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS`. Same Cloud-only-# default (project 2) and comma-separated env-var override as the enrollment list.-WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS: list[int] = [- int(team_id)- for team_id in get_list(- get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS)- )-]+# Upper bound on the number of distinct precompute shapes (query cache keys) a single+# team may have live at once. Any filter combination becomes its own shape, so a+# pathological team could otherwise mint unbounded namespaces. This is a coarse backstop,+# not a quota: a team builds shapes freely until it reaches this many, after which only+# *new* shapes fall back to the live query — existing shapes keep serving and refreshing.+# Sized well above any realistic team; 0 disables the cap.+WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM: int = get_from_env(+ "WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM", 1000, type_cast=int+)# Teams whose web analytics queries (overview, paths tile) skip the events↔sessions join# when nothing in the query (property filters, conversion goal, test-account filters,diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.pyindex 70942165a955..770c7a143778 100644--- a/products/access_control/backend/facade/api.py+++ b/products/access_control/backend/facade/api.py@@ -27,6 +27,7 @@ from posthog.models import OrganizationMembership, PropertyDefinition, Teamfrom ee.models.rbac.role import Rolefrom ..models.property_access_control import PropertyAccessControl+from ..property_access_control import is_property_access_control_enabledfrom . import contractsfrom .contracts import PropertyAccessLevel@@ -102,6 +103,19 @@ def get_property_access_state()+def team_has_property_access_rules(*, team_id: int) -> bool:+ """Whether the team has any property-level access-control rules in effect.++ True only when the feature is available for the org AND at least one rule+ targeting a property definition exists. Callers that share results across+ users (e.g. userless precompute) use this to opt out entirely, since a+ result computed without a user cannot honor per-user property restrictions.+ """+ if not is_property_access_control_enabled(team_id=team_id):+ return False+ return PropertyAccessControl.objects.filter(team_id=team_id, property_definition__isnull=False).exists()++# --- Write API ---diff --git a/products/access_control/backend/tests/test_property_access_control_api.py b/products/access_control/backend/tests/test_property_access_control_api.pyindex 017d265e52fd..5a696647d894 100644--- a/products/access_control/backend/tests/test_property_access_control_api.py+++ b/products/access_control/backend/tests/test_property_access_control_api.py@@ -5,6 +5,7 @@ from posthog.models import PropertyDefinitionfrom posthog.models.event.util import ClickhouseEventSerializerfrom posthog.test.persons import create_person+from products.access_control.backend.facade.api import team_has_property_access_rulesfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevel@@ -251,3 +252,29 @@ class TestPropertyAccessControlHelpers(BaseTest):props = {"a": 1, "b": 2}result = strip_restricted_properties(props, set())assert result == {"a": 1, "b": 2}+++class TestTeamHasPropertyAccessRules(BaseTest):+ def _prop(self) -> PropertyDefinition:+ return PropertyDefinition.objects.create(+ team=self.team, name="secret", property_type="String", type=PropertyDefinition.Type.EVENT+ )++ def test_false_when_feature_unavailable_even_with_rules(self):+ # No feature entitlement short-circuits before any rule query, so a stray rule+ # (e.g. left over after a downgrade) never re-enables the restriction path.+ PropertyAccessControl.objects.create(+ team=self.team, property_definition=self._prop(), access_level=PropertyAccessLevel.NONE.value+ )+ assert team_has_property_access_rules(team_id=self.team.id) is False++ def test_false_when_enabled_but_no_rules(self):+ _enable_property_access_control(self.organization)+ assert team_has_property_access_rules(team_id=self.team.id) is False++ def test_true_when_enabled_and_a_rule_targets_a_property(self):+ _enable_property_access_control(self.organization)+ PropertyAccessControl.objects.create(+ team=self.team, property_definition=self._prop(), access_level=PropertyAccessLevel.NONE.value+ )+ assert team_has_property_access_rules(team_id=self.team.id) is Truediff --git a/products/web_analytics/PRECOMPUTATION.md b/products/web_analytics/PRECOMPUTATION.mdindex dfb0484ca41b..525e755a4388 100644--- a/products/web_analytics/PRECOMPUTATION.md+++ b/products/web_analytics/PRECOMPUTATION.md@@ -80,11 +80,12 @@ The 24 h pad matches the JS SDK's hard `SESSION_LENGTH_LIMIT` and covers effecti- `query.conversionGoal` is set- `query.sampling.enabled` is True- `query.modifiers.sessionsV2JoinMode == "uuid"` (column type mismatch — temporary; should be re-enabled by re-typing `uniq_sessions_state` to `(uniq, UUID)`)-- `query.properties` contains more than one filter-- The single filter is not `EventPropertyFilter(key="$host", operator="exact", value=<non-empty string>)`+- The team has any property-level access controls (`team_has_property_access_rules`) — precompute results are built userless and shared by a user-independent cache key, so they can't honor per-user property restrictions; the query falls through to the live path, which enforces them per requesting user- Date range exceeds `MAX_PRECOMPUTE_DAYS` (90)- Either date_from or date_to is None+Any event/person filter shape is accepted: the `query.properties` list is translated via `property_to_expr`, and each distinct filter set becomes its own cache key (namespace). Session and cohort filters are refused (they fall through to the live path) — the userless precompute INSERT would apply them, but the live runners handle those types differently per family (web vitals drops them), so precomputing them would serve a different population than the live fallback. Filters the INSERT can't express fail the job and fall back to the live query automatically. Because any filter combination mints a new namespace, `web_ensure_precomputed` enforces a per-team distinct-shape ceiling (`WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM`, default 1000): once a team holds that many live shapes, a build for a _new_ shape drops to a check-only pass and serves live instead, while shapes the team already holds keep serving and refreshing. It is a coarse backstop, not a quota; 0 disables it.+When the gate returns False the runner silently falls through to v2 / raw. **Today there is no telemetry on gate rejections** — operators tuning the rollout have to read the source to know why a team isn't seeing the lazy path. A `web_overview_lazy_gate_rejected_total{reason}` counter would close that gap (open issue).### TTL schedule@@ -235,7 +236,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, 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.+`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`, missing date range, and date range over 90 days. Any event/person property-filter shape is accepted (each distinct set becomes its own cache key, bounded by the per-team shape ceiling — see the web overview eligibility gate above); session/cohort filters fall through to live.### Observabilitydiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.pyindex 5515f60b8967..367c833b1e40 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py@@ -8,7 +8,6 @@ from django.test import override_settingsfrom posthog.schema import (CompareFilter,DateRange,- EventPropertyFilter,HogQLQueryModifiers,PropertyOperator,SessionPropertyFilter,@@ -150,22 +149,6 @@ class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):is False)- def test_rejected_for_unsupported_filter_key(self):- self._create_action("Pageview")- with self._enable_lazy():- assert (- can_use_lazy_precompute(- self._runner(- self._build_query(- properties=[- EventPropertyFilter(key="$browser", operator=PropertyOperator.EXACT, value="Chrome")- ]- )- )- )- is False- )-def test_rejected_for_non_event_property_filter(self):self._create_action("Pageview")with self._enable_lazy():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.pyindex 23f99490cd17..851f827bae5b 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@@ -9,10 +9,13 @@ from parameterized import parameterizedfrom structlog.contextvars import get_contextvarsfrom posthog.schema import (+ CohortPropertyFilter,CompareFilter,DateRange,EventPropertyFilter,+ PersonPropertyFilter,PropertyOperator,+ SessionPropertyFilter,WebOverviewQuery,WebStatsBreakdown,WebStatsTableQuery,@@ -35,18 +38,21 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common impREVALIDATION_TRIGGER,SESSION_SETTLING_SECONDS,STALE_WHILE_REVALIDATE_SECONDS,+ TEAM_SHAPE_SET_TTL_SECONDS,PerQueryOptedOut,- TooManyFilters,- UnsupportedFilterKey,+ PropertyAccessControlled,+ UnsupportedFilterType,_oom_pin_key,+ _team_shape_set_key,check_common_eligibility,compute_filters_eligibility_hash,+ compute_shape_cap_key,handle_stale_served,host_filter_expr,is_precompute_enabled_for_team,- is_precompute_unrestricted_for_team,is_team_oom_pinned,pin_team_oom,+ try_reserve_precompute_shape,web_ensure_precomputed,)from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner@@ -85,23 +91,8 @@ class TestIsPrecomputeEnabledForTeam(BaseTest):assert is_precompute_enabled_for_team(self.team) is Trueflag.assert_not_called()- @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])- @mock.patch(f"{_COMMON}.is_org_feature_flag_enabled", return_value=False)- def test_unrestricted_team_is_enrolled_without_being_in_enrollment_list(self, flag) -> None:- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):- assert is_precompute_enabled_for_team(self.team) is True- flag.assert_not_called()- @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[])- def test_team_not_in_unrestricted_list_is_restricted(self) -> None:- assert is_precompute_unrestricted_for_team(self.team) is False-- def test_team_in_unrestricted_list_is_unrestricted(self) -> None:- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):- assert is_precompute_unrestricted_for_team(self.team) is True---class TestCheckCommonEligibilityUnrestricted(BaseTest):+class TestCheckCommonEligibility(BaseTest):def _check(self, *, use_precompute, properties=None) -> None:check_common_eligibility(team=self.team,@@ -113,21 +104,15 @@ class TestCheckCommonEligibilityUnrestricted(BaseTest):resolve_date_range=_date_range,)- def test_restricted_team_untouched_toggle_defaults_on(self) -> None:+ def test_enrolled_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 override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):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=[],- )+ @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_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@@ -136,44 +121,43 @@ class TestCheckCommonEligibilityUnrestricted(BaseTest):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]):- self._check(use_precompute=None)- self._check(use_precompute=True)-- def test_unrestricted_team_rejects_explicit_opt_out(self) -> None:- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):- with self.assertRaises(PerQueryOptedOut):- self._check(use_precompute=False)-- def test_unrestricted_team_accepts_arbitrary_multi_filter(self) -> None:+ def test_enrolled_team_accepts_arbitrary_filters(self) -> None:+ # The filter gate is loosened for every enrolled team: multiple, non-`$host`,+ # non-`exact` filters that the old restriction rejected must pass. Re-introducing+ # that restriction would silently send every filtered dashboard back to live.props = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT),EventPropertyFilter(key="$os", value="Mac OS X", operator=PropertyOperator.IS_NOT),]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._check(use_precompute=None, properties=props)- def test_restricted_team_rejects_multi_filter(self) -> None:- props = [- EventPropertyFilter(key="$host", value="a.com", operator=PropertyOperator.EXACT),- EventPropertyFilter(key="$host", value="b.com", operator=PropertyOperator.EXACT),+ @parameterized.expand(+ [+ ("session", SessionPropertyFilter(key="$session_duration", value=10, operator=PropertyOperator.GT)),+ ("cohort", CohortPropertyFilter(value=1)),]- with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[],- ):- with self.assertRaises(TooManyFilters):- self._check(use_precompute=True, properties=props)-- def test_restricted_team_rejects_non_host_filter(self) -> None:- props = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]- with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[],- ):- with self.assertRaises(UnsupportedFilterKey):- self._check(use_precompute=True, properties=props)+ )+ def test_session_and_cohort_filters_fall_through_to_live(self, _name, prop) -> None:+ # The userless precompute INSERT would apply these, but the live runners handle+ # session/cohort filters differently per family (web vitals drops them), so+ # precomputing them would serve a different population than the live fallback.+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ with self.assertRaises(UnsupportedFilterType):+ self._check(use_precompute=None, properties=[prop])++ def test_person_filter_is_accepted(self) -> None:+ prop = PersonPropertyFilter(key="email", value="[email protected]", operator=PropertyOperator.EXACT)+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ self._check(use_precompute=None, properties=[prop])++ @mock.patch(f"{_COMMON}.team_has_property_access_rules", return_value=True)+ def test_team_with_property_access_controls_falls_through_to_live(self, _mock) -> None:+ # Userless shared precompute can't honor per-user property restrictions, so a team+ # with property access controls must not precompute — the live path enforces them.+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):+ with self.assertRaises(PropertyAccessControlled):+ self._check(use_precompute=None)class TestCacheKeyVariesWithRolloutState(BaseTest):@@ -203,19 +187,18 @@ class TestHostFilterExpr(BaseTest):assert isinstance(expr, ast.Constant)assert expr.value is True- def test_restricted_team_builds_single_host_equals(self) -> None:- props = [EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[]):- expr = host_filter_expr(props, team=self.team)- assert isinstance(expr, ast.Call)- assert expr.name == "equals"-- def test_unrestricted_team_translates_arbitrary_filters(self) -> None:- props = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):- expr = host_filter_expr(props, team=self.team)- # property_to_expr produces a comparison/AST node; it must not be the trivial True constant.- assert not (isinstance(expr, ast.Constant) and expr.value is True)+ def test_translates_the_whole_filter_list(self) -> None:+ # Every filter must reach the AST via property_to_expr. A regression to the+ # old single-`$host` hand-built `equals` would keep only the first filter,+ # so a two-filter query would silently share a cache key with a one-filter one.+ props = [+ EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT),+ EventPropertyFilter(key="$os", value="Mac OS X", operator=PropertyOperator.EXACT),+ ]+ expr = host_filter_expr(props, team=self.team)+ rendered = str(expr)+ assert "$browser" in rendered+ assert "$os" in rendereddef _overview(@@ -324,6 +307,44 @@ class TestComputeFiltersEligibilityHash(BaseTest):int(h, 16)+class TestComputeShapeCapKey(BaseTest):+ def test_date_range_variants_share_one_slot(self) -> None:+ # Buckets are reused across requested ranges (the namespace sentinelizes time+ # windows), so date-range variants of one shape must map to one cap key —+ # otherwise a user could exhaust the ceiling by replaying different timestamps.+ a = compute_shape_cap_key(_overview(date_from="-7d"), "UTC")+ b = compute_shape_cap_key(_overview(date_from="-30d"), "UTC")+ assert a == b++ def test_compare_filter_does_not_fragment(self) -> None:+ # A compare query's current and previous period share the same namespace.+ assert compute_shape_cap_key(_overview(compare=True), "UTC") == compute_shape_cap_key(_overview(), "UTC")++ def test_test_account_filters_fragment_the_slot(self) -> None:+ # Test-account filters resolve from team config into the INSERT namespace but not+ # the query payload, so changing them must mint a distinct slot — otherwise an admin+ # could alias many namespaces onto one slot by editing the filters (veria review).+ taf_a = [EventPropertyFilter(key="email", value="@acme.com", operator=PropertyOperator.NOT_ICONTAINS)]+ taf_b = [EventPropertyFilter(key="email", value="@test.com", operator=PropertyOperator.NOT_ICONTAINS)]+ assert compute_shape_cap_key(_overview(), "UTC", taf_a) != compute_shape_cap_key(_overview(), "UTC", taf_b)+ # No filters is the same as an empty list.+ assert compute_shape_cap_key(_overview(), "UTC", None) == compute_shape_cap_key(_overview(), "UTC", [])++ def test_filters_and_breakdown_still_fragment(self) -> None:+ # Genuinely distinct namespaces must still occupy distinct slots.+ base = compute_shape_cap_key(_stats(breakdown_by=WebStatsBreakdown.BROWSER), "UTC")+ other_breakdown = compute_shape_cap_key(_stats(breakdown_by=WebStatsBreakdown.DEVICE_TYPE), "UTC")+ filtered = compute_shape_cap_key(+ _stats(+ breakdown_by=WebStatsBreakdown.BROWSER,+ properties=[EventPropertyFilter(key="$host", value="a.com", operator=PropertyOperator.EXACT)],+ ),+ "UTC",+ )+ assert base != other_breakdown+ assert base != filtered++class TestFiltersEligibilityHashContextvarBinding(ClickhouseTestMixin, APIBaseTest):"""Verifies that `WebAnalyticsQueryRunner.calculate()` binds `filters_eligibility_hash`on `structlog.contextvars` so every log emitted inside the request —@@ -634,7 +655,8 @@ class TestServeLiveWarmBehind(BaseTest):def _runner(self):runner = mock.Mock()runner.team = self.team- runner.query = mock.Mock()+ runner.query = _overview()+ runner._test_account_filters = []return runner@mock.patch(f"{_COMMON}.enqueue_stale_revalidation")@@ -670,3 +692,80 @@ class TestServeLiveWarmBehind(BaseTest):assert mock_ensure.call_args.kwargs["run_inserts"] is True# The warmer IS the refresh mechanism; a miss must not re-enqueue itself.mock_enqueue.assert_not_called()+++class TestTryReservePrecomputeShape(BaseTest):+ def setUp(self):+ super().setUp()+ redis.get_client().delete(_team_shape_set_key(self.team.pk))++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=2)+ def test_new_shapes_admitted_to_ceiling_then_only_known_ones(self):+ assert try_reserve_precompute_shape(self.team.pk, "a") is True+ assert try_reserve_precompute_shape(self.team.pk, "b") is True+ # At the ceiling a brand-new shape is dropped early so the team stops minting namespaces,+ assert try_reserve_precompute_shape(self.team.pk, "c") is False+ # but a shape it already holds keeps building — capping refreshes would freeze live shapes stale.+ assert try_reserve_precompute_shape(self.team.pk, "a") is True++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=0)+ def test_zero_ceiling_disables_the_cap(self):+ for i in range(5):+ assert try_reserve_precompute_shape(self.team.pk, f"shape-{i}") is True++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=10)+ def test_shape_set_gets_a_ttl_so_the_counter_self_heals(self):+ try_reserve_precompute_shape(self.team.pk, "a")+ ttl = redis.get_client().ttl(_team_shape_set_key(self.team.pk))+ assert 0 < ttl <= TEAM_SHAPE_SET_TTL_SECONDS++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=1)+ @mock.patch(f"{_COMMON}.redis.get_client", side_effect=Exception("redis down"))+ def test_redis_failure_fails_open(self, _client):+ # A backstop must never block a legitimate build: a Redis blip has to admit the shape.+ assert try_reserve_precompute_shape(self.team.pk, "a") is True+++class TestPrecomputeShapeCapWiring(BaseTest):+ def setUp(self):+ super().setUp()+ redis.get_client().delete(_team_shape_set_key(self.team.pk))++ def _runner(self):+ runner = mock.Mock()+ runner.team = self.team+ runner.query = _overview()+ runner._test_account_filters = []+ return runner++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=1)+ @mock.patch(f"{_COMMON}.enqueue_stale_revalidation")+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_at_ceiling_new_shape_build_becomes_check_only(self, mock_ensure, _enqueue):+ # With the team already at its ceiling, a background build for a new shape must drop to+ # a check-only pass (run_inserts False) — otherwise the cap is computed and ignored and+ # bounds nothing.+ redis.get_client().sadd(_team_shape_set_key(self.team.pk), "an-existing-shape")+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=False)+ with tags_context(trigger="webAnalyticsQueryWarming"):+ web_ensure_precomputed(+ team=self.team, runner=self._runner(), family="web_overview", ttl_seconds={"default": 3600}, table=None+ )+ assert mock_ensure.call_args.kwargs["run_inserts"] is False++ @override_settings(WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM=1)+ @mock.patch(f"{_COMMON}.enqueue_stale_revalidation")+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_user_read_never_consults_the_cap(self, mock_ensure, _enqueue):+ # User reads are already check-only; consulting the cap there would spend a Redis+ # round-trip per dashboard load and count read-only shapes against the build ceiling.+ redis.get_client().sadd(_team_shape_set_key(self.team.pk), "an-existing-shape")+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=False)+ web_ensure_precomputed(+ team=self.team, runner=self._runner(), family="web_overview", ttl_seconds={"default": 3600}, table=None+ )+ # The new shape was never added to the set (cap not consulted on the read path).+ assert not redis.get_client().sismember(+ _team_shape_set_key(self.team.pk),+ compute_shape_cap_key(self._runner().query, self.team.timezone),+ )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.pyindex 61c47af312ab..a0b88fbdc39b 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@@ -188,24 +188,10 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):f"different $host values must produce distinct cache keys, got overlap: {example_jobs & other_jobs}")- @freeze_time("2024-01-15T12:00:00Z")- def test_disqualifying_filter_falls_through(self):- self._seed_two_sessions()- # $pathname is not in the MVP allowlist → gate returns False → no job created.- with self._enable_lazy():- self._run(- self._build_query(- properties=[- EventPropertyFilter(key="$pathname", value="/a", operator=PropertyOperator.EXACT),- ]- )- )-- assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-@freeze_time("2024-01-15T12:00:00Z")def test_session_property_falls_through(self):- # Session-level filters never qualify for MVP — only EventPropertyFilter on $host.+ # Session and cohort filters fall through — precompute only serves event/person+ # filters, since the live path applies session/cohort filters differently.with self._enable_lazy():self._run(self._build_query(@@ -397,18 +383,6 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):# --- Group B: gate strictness -------------------------------------------- @freeze_time("2024-01-15T12:00:00Z")- def test_multiple_host_filters_fall_through(self):- # Gate accepts at most one user-supplied property — multi-host inputs- # collide on a single-filter cache key and must be rejected.- self._seed_two_sessions()- host_a = EventPropertyFilter(key="$host", value="example.com", operator=PropertyOperator.EXACT)- host_b = EventPropertyFilter(key="$host", value="other.com", operator=PropertyOperator.EXACT)- with self._enable_lazy():- self._run(self._build_query(properties=[host_a, host_b]))-- assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-@freeze_time("2024-01-15T12:00:00Z")def test_uuid_session_mode_falls_through(self):# `events.$session_id_uuid` would produce `uniqState(UUID)` which the@@ -421,22 +395,6 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0- @parameterized.expand(- [- ("none_value", None),- ("list_value", ["example.com", "other.com"]),- ("empty_string", ""),- ]- )- @freeze_time("2024-01-15T12:00:00Z")- def test_non_string_host_value_falls_through(self, _name: str, host_value) -> None:- self._seed_two_sessions()- prop = EventPropertyFilter(key="$host", value=host_value, operator=PropertyOperator.EXACT)- with self._enable_lazy():- self._run(self._build_query(properties=[prop]))-- assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-@freeze_time("2024-01-15T12:00:00Z")def test_window_over_max_days_falls_through(self):# 365 days >> MAX_PRECOMPUTE_DAYS — gate refuses to avoid spawning@@ -617,28 +575,27 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):assert result is None, f"expected fall-back to raw when current precompute not ready, got {result!r}"- # --- Group D: unrestricted teams ----------------------------------------+ # --- Group D: enrolled teams (arbitrary filters) ----------------------------------------@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_creates_job_for_multi_non_host_filter(self):- # Filters the restricted gate rejects (multiple, non-`$host`,- # non-`exact`) precompute fine for an unrestricted team. No org flag- # needed — membership in the unrestricted list implies enrollment.+ def test_enrolled_team_creates_job_for_multi_non_host_filter(self):+ # Filters the old restriction rejected (multiple, non-`$host`, non-`exact`)+ # precompute fine for any enrolled team.self._seed_two_sessions()props = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT),EventPropertyFilter(key="$os", value="Mac OS X", operator=PropertyOperator.IS_NOT),]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(properties=props))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_distinct_filters_get_distinct_cache_entries(self):+ def test_enrolled_team_distinct_filters_get_distinct_cache_entries(self):self._seed_two_sessions()chrome = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]firefox = [EventPropertyFilter(key="$browser", value="Firefox", operator=PropertyOperator.EXACT)]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(properties=chrome))chrome_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}PreaggregationJob.objects.filter(team_id=self.team.pk).delete()@@ -652,20 +609,20 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):)@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_untouched_toggle_creates_job(self):- # Unrestricted teams default to opt-out: an untouched toggle (None) still+ def test_enrolled_team_untouched_toggle_creates_job(self):+ # Enrolled teams default to opt-out: an untouched toggle (None) still# precomputes.self._seed_two_sessions()query = self._build_query()query.useWebAnalyticsPrecompute = None- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(query)assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_explicit_opt_out_falls_through(self):+ def test_enrolled_team_explicit_opt_out_falls_through(self):self._seed_two_sessions()- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(opt_in_precompute=False))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0@@ -756,7 +713,7 @@ class TestWebOverviewSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):return LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=allowlist,):runner = self._make_runner(properties=properties, filter_test_accounts=cohort_test_filter)@@ -825,7 +782,7 @@ class TestWebOverviewSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):)with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk],):runner = self._make_runner(diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.pyindex 81f6e127fdb2..4ecf1154c412 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_frustration_lazy_precompute.py@@ -10,7 +10,6 @@ from parameterized import parameterizedfrom posthog.schema import (CompareFilter,DateRange,- EventPropertyFilter,HogQLQueryModifiers,PropertyOperator,SessionPropertyFilter,@@ -197,7 +196,7 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):)def test_rejected_for_non_event_property_filter(self):- # SessionPropertyFilter is not in the gate's allowlist (only EventPropertyFilter on $host).+ # Precompute only serves event/person filters; session/cohort fall through to live.with self._enable_lazy():assert (can_use_lazy_precompute(@@ -214,21 +213,6 @@ class TestWebStatsFrustrationLazyPrecompute(ClickhouseTestMixin, APIBaseTest):is False)- def test_rejected_for_unsupported_filter_key(self):- with self._enable_lazy():- assert (- can_use_lazy_precompute(- self._runner(- self._build_query(- properties=[- EventPropertyFilter(key="$browser", operator=PropertyOperator.EXACT, value="Chrome")- ]- )- )- )- is False- )-def test_rejected_for_sessions_v2_uuid_mode(self):with self._enable_lazy():modifiers = HogQLQueryModifiers(sessionsV2JoinMode=SessionsV2JoinMode.UUID)diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.pyindex 6e69344fe754..279299cc8f1c 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py@@ -305,19 +305,6 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):)assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0- @freeze_time("2024-01-15T12:00:00Z")- def test_disqualifying_filter_falls_through(self):- # $pathname filter is outside the MVP allowlist.- with self._enable_lazy():- self._run(- self._build_query(- properties=[- EventPropertyFilter(key="$pathname", value="/a", operator=PropertyOperator.EXACT),- ]- )- )- assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-@freeze_time("2024-01-15T12:00:00Z")def test_sampling_falls_through(self):with self._enable_lazy():@@ -555,20 +542,6 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):self._run(self._build_query(date_from="2023-01-01", date_to="2024-01-07"))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0- @parameterized.expand(- [- ("none_value", None),- ("list_value", ["example.com", "other.com"]),- ("empty_string", ""),- ]- )- @freeze_time("2024-01-15T12:00:00Z")- def test_non_string_host_value_falls_through(self, _name: str, host_value) -> None:- prop = EventPropertyFilter(key="$host", value=host_value, operator=PropertyOperator.EXACT)- with self._enable_lazy():- self._run(self._build_query(properties=[prop]))- assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-@parameterized.expand([("utc", "UTC"),@@ -754,25 +727,24 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):return out@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_creates_job_for_multi_non_host_filter(self):- # Filters the restricted gate would reject (multiple, non-`$host`,- # non-`exact`) precompute fine for an unrestricted team — no org flag- # needed, since membership in the unrestricted list implies enrollment.+ def test_enrolled_team_creates_job_for_multi_non_host_filter(self):+ # Filters the old restriction rejected (multiple, non-`$host`, non-`exact`)+ # precompute fine for any enrolled team.self._seed_two_sessions()props = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT),EventPropertyFilter(key="$os", value="Mac OS X", operator=PropertyOperator.IS_NOT),]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(properties=props))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_distinct_filters_get_distinct_cache_entries(self):+ def test_enrolled_team_distinct_filters_get_distinct_cache_entries(self):self._seed_two_sessions()chrome = [EventPropertyFilter(key="$browser", value="Chrome", operator=PropertyOperator.EXACT)]firefox = [EventPropertyFilter(key="$browser", value="Firefox", operator=PropertyOperator.EXACT)]- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(properties=chrome))chrome_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}PreaggregationJob.objects.filter(team_id=self.team.pk).delete()@@ -786,20 +758,20 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):)@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_untouched_toggle_creates_job(self):- # Unrestricted teams default to opt-out: an untouched toggle (None) still+ def test_enrolled_team_untouched_toggle_creates_job(self):+ # Enrolled teams default to opt-out: an untouched toggle (None) still# precomputes.self._seed_two_sessions()query = self._build_query()query.useWebAnalyticsPrecompute = None- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(query)assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0@freeze_time("2024-01-15T12:00:00Z")- def test_unrestricted_team_explicit_opt_out_falls_through(self):+ def test_enrolled_team_explicit_opt_out_falls_through(self):self._seed_two_sessions()- with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk]):self._run(self._build_query(opt_in_precompute=False))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0@@ -1019,7 +991,7 @@ class TestWebStatsPathsSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):return LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk] if allowlisted else [],):runner = self._make_runner(properties=properties, breakdown_by=breakdown_by)@@ -1104,7 +1076,7 @@ class TestWebStatsPathsSessionIdSetInsert(ClickhouseTestMixin, APIBaseTest):)with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk],+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[self.team.pk],WEB_ANALYTICS_SESSION_ID_SET_TEAM_IDS=[self.team.pk],):runner = self._make_runner(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.pyindex f5760f578b6d..43ea11c1c1f3 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@@ -15,27 +15,21 @@ from typing import Optional, Protocol, Unionimport structlogfrom prometheus_client import Counter-from posthog.schema import (- EventPropertyFilter,- PropertyOperator,- WebOverviewQuery,- WebStatsTableQuery,- WebVitalsPathBreakdownQuery,-)+from posthog.schema import WebOverviewQuery, WebStatsTableQuery, WebVitalsPathBreakdownQueryfrom posthog.hogql import astfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.placeholders import find_placeholders-from posthog.hogql.property import property_to_expr+from posthog.hogql.property import get_property_type, property_to_exprfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezonefrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_exprfrom posthog.models.team import Team+from products.access_control.backend.facade.api import team_has_property_access_rulesfrom products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (LAZY_TTL_SECONDS, # noqa: F401 — re-exported; several runners import it from this moduleis_precompute_enabled_for_team,- is_precompute_unrestricted_for_team,)logger = structlog.get_logger(__name__)@@ -174,6 +168,20 @@ class NonStringOrEmptyFilterValue(LazyPrecomputeIneligible):pass+class UnsupportedFilterType(LazyPrecomputeIneligible):+ """A filter is not an event/person property — precompute only handles those,+ since session/cohort filters are applied differently on the live path per family."""++ def __init__(self, filter_type: object):+ self.filter_type = filter_type+ super().__init__(f"type={filter_type!r}")+++class PropertyAccessControlled(LazyPrecomputeIneligible):+ """The team has property-level access controls — userless shared precompute+ can't honor per-user property restrictions, so the query stays on the live path."""++class MissingDateRange(LazyPrecomputeIneligible):pass@@ -270,24 +278,23 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timezif query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid":raise SessionsV2UuidMode()- # Unrestricted teams accept any filter shape — `user_filter_expr` translates- # 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:- raise TooManyFilters()- for prop in properties:- if not isinstance(prop, EventPropertyFilter):- raise NonEventPropertyFilter()- if prop.key not in SUPPORTED_USER_FILTER_KEYS:- raise UnsupportedFilterKey(prop.key)- if prop.operator != PropertyOperator.EXACT:- raise UnsupportedFilterOperator(prop.operator)- if not isinstance(prop.value, str) or not prop.value:- raise NonStringOrEmptyFilterValue()+ # Any event/person filter shape is accepted (any key, operator, count), translated+ # as a whole via `user_filter_expr`; each distinct set becomes its own cache key,+ # bounded by the per-team shape ceiling in `web_ensure_precomputed`. Session and+ # cohort filters are refused: the precompute INSERT applies the whole list userlessly,+ # but the live runners handle those types differently per family (web vitals drops+ # them entirely), so precomputing them would serve a different population than the+ # live fallback. Those queries fall through to the live path, which applies them right.+ for prop in query.properties or []:+ if get_property_type(prop) not in ("event", "person"):+ raise UnsupportedFilterType(get_property_type(prop))++ # Precompute results are built userless and shared by a user-independent cache+ # key, so they cannot honor per-user property restrictions. If the team has any+ # property-level access controls, skip precompute and let the live path enforce+ # them per requesting user.+ if team_has_property_access_rules(team_id=runner.team.id):+ raise PropertyAccessControlled()date_from = runner.query_date_range.date_from() # type: ignore[attr-defined]date_to = runner.query_date_range.date_to() # type: ignore[attr-defined]@@ -415,22 +422,10 @@ def user_filter_expr(runner: LazyPrecomputeRunner) -> ast.Expr:if not runner.query.properties:return ast.Constant(value=True)- # Unrestricted teams may pass arbitrary filters — translate the whole list- # via the general `property_to_expr`. Each distinct filter set becomes a- # distinct cache key.- if is_precompute_unrestricted_for_team(runner.team):- return property_to_expr(runner.query.properties, team=runner.team)-- # Gate already enforces single EventPropertyFilter with $host exact + string value.- host_filter = runner.query.properties[0]- assert isinstance(host_filter, EventPropertyFilter)- return ast.Call(- name="equals",- args=[- ast.Field(chain=["events", "properties", host_filter.key]),- ast.Constant(value=host_filter.value),- ],- )+ # Any filter list is translated via the general `property_to_expr`; 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.+ return property_to_expr(runner.query.properties, team=runner.team)def test_account_filter_expr(runner: LazyPrecomputeRunner) -> ast.Expr: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.pyindex 27f5babe3df6..6b025995206f 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@@ -3,9 +3,10 @@Both the web overview lazy precompute and the web stats PATHS lazy precomputeshare 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-the two paths drifting apart.+any event/person filter shape, bounded date range) and the same TTL / session-pad+/ UTC-day helpers. Keeping a single source of truth avoids the paths drifting apart.+The per-team distinct-shape ceiling (`try_reserve_precompute_shape`) lives here+too, bounding how many namespaces the loosened filter gate lets a team mint."""import json@@ -21,16 +22,17 @@ import structlogimport posthoganalyticsfrom prometheus_client import Counter-from posthog.schema import EventPropertyFilter, PropertyOperator, SessionsV2JoinMode+from posthog.schema import SessionsV2JoinModefrom posthog.hogql import ast-from posthog.hogql.property import property_to_expr+from posthog.hogql.property import get_property_type, property_to_exprfrom posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezonefrom posthog import redisfrom posthog.clickhouse.query_tagging import tag_queriesfrom posthog.models import Team+from products.access_control.backend.facade.api import team_has_property_access_rulesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,TtlSchedule,@@ -97,6 +99,53 @@ def list_oom_pinned_team_ids() -> list[int]:return sorted(team_ids)+# Per-team distinct-shape ceiling. With the filter gate loosened, any filter combination+# becomes its own precompute namespace, so a pathological team could mint unbounded shapes.+# This is a coarse backstop, not a quota: a team builds shapes freely until it holds this+# many distinct ones, after which *new* shapes fall back to the live query (existing shapes+# keep serving and refreshing). Enforced only on build paths and only here, on the+# web-analytics side of the framework boundary, so the shared lazy_computation framework —+# and its other consumers (e.g. experiments) — is never capped. The set's TTL is stamped+# once when its first shape is added, so the whole counter resets periodically rather than+# accreting cold shapes forever; a still-exploding team simply refills within the window.+TEAM_SHAPE_SET_REDIS_PREFIX = "preagg:team_shapes:"+TEAM_SHAPE_SET_TTL_SECONDS = 30 * 24 * 60 * 60 # matches the warmed -30d depth+++def _team_shape_set_key(team_id: int) -> str:+ return f"{TEAM_SHAPE_SET_REDIS_PREFIX}{team_id}"+++def try_reserve_precompute_shape(team_id: int, shape_hash: str) -> bool:+ """Reserve a build slot for `shape_hash` under the team's distinct-shape ceiling.++ Returns True when the shape may build — it was already counted, the cap is disabled,+ or there was room (and it's now counted). Returns False only when the team is at the+ ceiling AND this shape is new: the one case we drop early. Best-effort: any Redis+ failure returns True (fail open — a backstop must never block a legitimate build).++ The count is approximate under concurrency (sismember/scard/sadd aren't atomic), which+ is fine for a coarse ceiling: a few concurrent new shapes may overshoot by a handful."""+ ceiling = settings.WEB_ANALYTICS_PRECOMPUTE_MAX_SHAPES_PER_TEAM+ if ceiling <= 0:+ return True+ try:+ client = redis.get_client()+ key = _team_shape_set_key(team_id)+ if client.sismember(key, shape_hash):+ return True+ count = client.scard(key)+ if count >= ceiling:+ return False+ client.sadd(key, shape_hash)+ if count == 0:+ client.expire(key, TEAM_SHAPE_SET_TTL_SECONDS)+ return True+ except Exception:+ logger.warning("web_precompute.shape_cap_check_failed", team_id=team_id, exc_info=True)+ return True++# --- Stale-while-revalidate (RFC 5861) -------------------------------------------------## The lazy executor's `stale_while_revalidate_seconds` is the *serve* half: user-facing@@ -144,6 +193,12 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_CHECK_MISS = Counter(labelnames=["family"],)+WEB_ANALYTICS_LAZY_PRECOMPUTE_SHAPE_CAPPED = Counter(+ "web_analytics_lazy_precompute_shape_capped_total",+ "Precompute builds skipped because the team was at its distinct-shape ceiling; the query served live instead.",+ labelnames=["family"],+)+WEB_ANALYTICS_LAZY_PRECOMPUTE_STALE_SERVED = Counter("web_analytics_lazy_precompute_stale_served_total","Reads served from expired-within-grace jobs instead of recomputing inline (stale-while-revalidate).",@@ -287,6 +342,17 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResul# must not pay for its own backfill.if "run_inserts" not in kwargs:kwargs["run_inserts"] = background+ # Per-team distinct-shape backstop. Only build paths can mint a new namespace, so this+ # only bites there (a user read is already run_inserts=False). At the ceiling, a *new*+ # shape drops back to a check-only pass — not ready → the caller serves live — instead+ # of building; shapes the team already holds are unaffected. Reuses the eligibility hash+ # so a shape counts the same however it reaches this build path.+ if kwargs.get("run_inserts") and runner is not None:+ shape_hash = compute_shape_cap_key(runner.query, team.timezone, getattr(runner, "_test_account_filters", None))+ if not try_reserve_precompute_shape(team.id, shape_hash):+ kwargs["run_inserts"] = False+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SHAPE_CAPPED.labels(family=family or "unknown").inc()+ logger.info("web_precompute.shape_capped", team_id=team.id, family=family)pinned = is_team_oom_pinned(team.id)if "ttl_seconds" in kwargs:existing = kwargs["ttl_seconds"]@@ -452,6 +518,20 @@ class NonStringOrEmptyFilterValue(LazyPrecomputeIneligible):pass+class UnsupportedFilterType(LazyPrecomputeIneligible):+ """A filter is not an event/person property — precompute only handles those,+ since session/cohort filters are applied differently on the live path per family."""++ def __init__(self, filter_type: object):+ self.filter_type = filter_type+ super().__init__(f"type={filter_type!r}")+++class PropertyAccessControlled(LazyPrecomputeIneligible):+ """The team has property-level access controls — userless shared precompute+ can't honor per-user property restrictions, so the query stays on the live path."""++class MissingDateRange(LazyPrecomputeIneligible):pass@@ -482,16 +562,6 @@ def is_org_feature_flag_enabled(team: Team) -> bool:)-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). 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--def is_precompute_enabled_for_team(team: Team) -> bool:"""Whether a team should take the lazy precompute path.@@ -501,19 +571,14 @@ def is_precompute_enabled_for_team(team: Team) -> bool:on local flag-definition evaluation, which isn't reliably available outsidethe Django app (e.g. the Dagster warmer, where `only_evaluate_locally`returned falsy and silently dropped the warmer onto the raw path).-- Unrestricted teams are implicitly enrolled — membership in the unrestricted- list is enough, so a team need not appear in both settings."""if team.id in settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS:return True- if is_precompute_unrestricted_for_team(team):- return True# Background warmers build buckets for every active team regardless of the# rollout flag: warming precedes read enablement, and flag evaluation is not# reliably available in the Dagster processes the warmers run in. User-facing- # reads still require flag enrollment; the restricted filter-shape gate keeps- # the warmed set bounded to canonical shapes.+ # reads still require flag enrollment; the per-team shape ceiling keeps the+ # warmed set bounded.if is_background_warming_request():return Truereturn is_org_feature_flag_enabled(team)@@ -548,8 +613,6 @@ def check_common_eligibility(if use_web_analytics_precompute is False:raise PerQueryOptedOut()- unrestricted = is_precompute_unrestricted_for_team(team)-if not is_integer_timezone(team.timezone):raise NonIntegerTimezone()@@ -562,22 +625,24 @@ def check_common_eligibility(if modifiers and getattr(modifiers, "sessionsV2JoinMode", None) == SessionsV2JoinMode.UUID:raise SessionsV2UuidMode()- # Unrestricted teams accept any filter shape — `host_filter_expr` translates- # 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.- if not unrestricted:- if len(properties) > 1:- raise TooManyFilters()- for prop in properties:- if not isinstance(prop, EventPropertyFilter):- raise NonEventPropertyFilter()- if prop.key not in SUPPORTED_USER_FILTER_KEYS:- raise UnsupportedFilterKey(prop.key)- if prop.operator != PropertyOperator.EXACT:- raise UnsupportedFilterOperator(prop.operator)- if not isinstance(prop.value, str) or not prop.value:- raise NonStringOrEmptyFilterValue()+ # Any event/person filter shape is accepted (any key, any operator, any number),+ # translated as a whole via `property_to_expr`; each distinct set becomes its own+ # cache key, bounded by the per-team shape ceiling in `web_ensure_precomputed`.+ # Session and cohort filters are refused: the precompute INSERT applies the whole+ # list userlessly, but the live runners handle those types differently per family+ # (web vitals drops them entirely), so precomputing them would serve a different+ # population than the live fallback. Those queries fall through to the live path,+ # which applies them correctly.+ for prop in properties:+ if get_property_type(prop) not in ("event", "person"):+ raise UnsupportedFilterType(get_property_type(prop))++ # Precompute results are built userless and shared across users by a+ # user-independent cache key, so they cannot honor per-user property+ # restrictions. If the team has any property-level access controls, skip+ # precompute entirely and let the live path enforce them per requesting user.+ if team_has_property_access_rules(team_id=team.id):+ raise PropertyAccessControlled()date_from, date_to = resolve_date_range()if date_from is None or date_to is None:@@ -618,8 +683,43 @@ def compute_filters_eligibility_hash(query: Any, team_timezone: str) -> str:filters (with values), date range, breakdown, conversion goal, sampling,interval, compare filter, test-accounts toggle, and team timezone."""+ return _hash_query_fields(query, team_timezone, _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS)+++# The precompute namespace (`compute_query_hash`) sentinelizes its time-window+# placeholders, so buckets are reused across requested date ranges: different+# ranges — and a compare query's current vs. previous period — of the same+# filter/breakdown shape map to ONE namespace. The shape cap therefore drops the+# range-varying fields on top of the eligibility-hash ignores, so it counts+# distinct namespaces rather than per-request shapes. Otherwise a user could+# exhaust the ceiling by replaying one filter with different ISO timestamps until+# new legitimate shapes are forced onto the live path (veria review).+_SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS: frozenset[str] = _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS | frozenset(+ {"dateRange", "compareFilter"}+)+++def compute_shape_cap_key(query: Any, team_timezone: str, test_account_filters: Optional[list] = None) -> str:+ """Namespace-identity key for the per-team shape cap: the eligibility hash with the+ time-window fields dropped (so date-range variants of one shape share a slot), plus+ the team's resolved test-account filters. Those resolve from team config into the+ INSERT AST — part of the namespace but absent from the query payload — so folding them+ in stops an admin from minting fresh namespaces onto one cap slot by editing the+ test-account filters (veria review)."""dumped = query.model_dump(mode="json", exclude_none=True, by_alias=False)- for key in _FILTERS_ELIGIBILITY_HASH_IGNORED_QUERY_FIELDS:+ for key in _SHAPE_CAP_KEY_IGNORED_QUERY_FIELDS:+ dumped.pop(key, None)+ tafs = [+ f.model_dump(mode="json", exclude_none=True) if hasattr(f, "model_dump") else f+ for f in (test_account_filters or [])+ ]+ payload = {"query": dumped, "timezone": team_timezone, "test_account_filters": tafs}+ return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()+++def _hash_query_fields(query: Any, team_timezone: str, ignored_fields: frozenset[str]) -> str:+ dumped = query.model_dump(mode="json", exclude_none=True, by_alias=False)+ for key in ignored_fields:dumped.pop(key, None)payload = {"query": dumped, "timezone": team_timezone}return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()@@ -629,25 +729,13 @@ def host_filter_expr(properties: list, *, team: Team) -> ast.Expr:"""Translate the user filter list to an AST expression.The returned AST is what `ensure_precomputed` hashes into the cache key —- different filter values therefore become different precomputed jobs.-- Unrestricted teams may pass arbitrary filters, so their list is translated- via the general `property_to_expr`. Restricted teams keep the hand-built- single-`$host` `equals` so their existing cache keys don't churn.+ different filter values therefore become different precomputed jobs. Any filter+ list is translated via the general `property_to_expr`; filters the INSERT can't+ express fail the job and fall back to the live query automatically."""if not properties:return ast.Constant(value=True)- if is_precompute_unrestricted_for_team(team):- return property_to_expr(properties, team=team)- host_filter = properties[0]- assert isinstance(host_filter, EventPropertyFilter)- return ast.Call(- name="equals",- args=[- ast.Field(chain=["events", "properties", host_filter.key]),- ast.Constant(value=host_filter.value),- ],- )+ return property_to_expr(properties, team=team)def test_account_filter_expr(*, test_account_filters: list, team: Team) -> ast.Expr:diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.pyindex ec7a7fba6971..b3fa69f62453 100644--- a/products/web_analytics/dags/eager_web_analytics_precompute.py+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py@@ -52,14 +52,12 @@ cache perpetually warm, so user requests turn into pure reads.Audience---------The audience is the union of `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` and-`WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS` (each defaults to the-Cloud dogfooding team on Cloud, empty elsewhere). The runtime read-path gate-(`is_precompute_enabled_for_team`) treats membership in *either* list as-enrollment, so warmer and reader read the same sources and cannot drift —-a team enrolled solely as unrestricted still gets its baseline warmed.-Enrolling or removing a team is a deploy-time change to the env vars-(Django + Dagster pods), not runtime-overridable.+The static audience is `WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS` (defaults to the+Cloud dogfooding team on Cloud, empty elsewhere) — the same list the runtime+read-path gate (`is_precompute_enabled_for_team`) treats as enrollment, so+warmer and reader read the same source 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.@@ -248,24 +246,19 @@ def _resolve_eager_audience(active_teams_pct: int = 0, active_lookback_hours: inif not is_cloud():return [], "not_cloud", {}- # Union both enrollment lists: unrestricted teams are implicitly enrolled- # (see `is_precompute_enabled_for_team`), so a team enrolled solely via- # `WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS` must still get its- # baseline warmed — otherwise its reads land on cold on-demand inserts.- # dict.fromkeys preserves order and dedupes teams in both lists.active_team_ids: list[int] = []if active_teams_pct > 0:all_active = _fetch_active_wa_team_ids(ACTIVE_AUDIENCE_MAX_TEAMS, lookback_hours=active_lookback_hours)take = max(1, len(all_active) * min(active_teams_pct, 100) // 100) if all_active else 0active_team_ids = all_active[:take]- # Static lists first so the always-enrolled teams warm before the ramp- # audience when a run is truncated by the job's max_runtime.+ # Static enrollment list first so the always-enrolled teams warm before the+ # ramp audience when a run is truncated by the job's max_runtime.+ # dict.fromkeys preserves order and dedupes.team_ids = list(dict.fromkeys([*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,- *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,*active_team_ids,])@@ -462,10 +455,7 @@ def warm_eager_baseline_op(context: dagster.OpExecutionContext, config: EagerWar)# Captured before the ramp enrollment below mutates the setting — this set is# what "statically enrolled" means for the priority sort further down.- static_ids = {- *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,- *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,- }+ static_ids = {*settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS}original_enrollment = settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDSif config.active_teams_pct > 0:# Enroll the ramp audience for the duration of this run: the warm queriesdiff --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 42aa0c24cb70..6c2a2f5b7ad8 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@@ -75,9 +75,7 @@ class TestResolveEagerAudience:assert team_ids == []assert reason == "not_cloud"- @override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[], WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_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 == []@@ -85,16 +83,13 @@ class TestResolveEagerAudience:@parameterized.expand([- ("unrestricted_only", [], [5], [5]),- ("union_with_overlap", [2, 7], [7, 9], [2, 7, 9]),- ("restricted_only", [2, 7], [], [2, 7]),+ ("single", [5], [5]),+ ("dedupes_repeats", [2, 7, 7], [2, 7]),+ ("preserves_order", [7, 2], [7, 2]),])- def test_audience_unions_restricted_and_unrestricted(self, _is_cloud, _name, restricted, unrestricted, expected):- with override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=restricted,- WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=unrestricted,- ):+ def test_audience_is_the_enrollment_list(self, _is_cloud, _name, enrolled, expected):+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=enrolled):team_ids, reason, diag = _resolve_eager_audience()assert team_ids == expectedassert reason == "ok"@@ -110,9 +105,7 @@ class TestResolveEagerAudience:)def test_active_audience_pct_appends_after_static_lists(self, _is_cloud, _name, pct, expected, expected_active):with (- override_settings(- WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[2, 7], WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[]- ),+ override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[2, 7]),patch(f"{_EAGER_MODULE}._fetch_active_wa_team_ids",return_value=[7, 31, 42, 55],diff --git a/tach.toml b/tach.tomlindex 6d77f9bdded2..5b84cd97839d 100644--- a/tach.toml+++ b/tach.toml@@ -763,6 +763,7 @@ layer = "modules"[[modules]]path = "products.web_analytics"depends_on = [+ "products.access_control","products.cohorts","ee","posthog",