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): allow unrestricted lazy precompute per team (#62833)

Lucas Ricoy212d09b53c2c
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
index fbc9f98c2e60..998f1dd34a76 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx
@@ -74,10 +74,11 @@ export const WebAnalyticsMenu = (): JSX.Element => {
<ButtonPrimitive
menuItem
onClick={() => {
- setUseWebAnalyticsPrecompute(!useWebAnalyticsPrecompute)
+ // `null` (untouched) is treated as on, so toggling off opts out explicitly.
+ setUseWebAnalyticsPrecompute(!(useWebAnalyticsPrecompute ?? true))
}}
>
- <LemonSwitch checked={useWebAnalyticsPrecompute} size="xsmall" />
+ <LemonSwitch checked={useWebAnalyticsPrecompute ?? true} size="xsmall" />
Allow precompute
</ButtonPrimitive>
</Tooltip>
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
index aebc3de7085d..c8ccf7f231e2 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts
@@ -271,3 +271,48 @@ describe('webAnalyticsLogic focus mode', () => {
})
})
})
+
+describe('webAnalyticsLogic precompute payload', () => {
+ let logic: ReturnType<typeof webAnalyticsLogic.build>
+
+ const setToggleFlag = (enabled: boolean): void => {
+ featureFlagLogic.actions.setFeatureFlags(
+ enabled ? [FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE] : [],
+ enabled ? { [FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE]: true } : {}
+ )
+ }
+
+ beforeEach(() => {
+ localStorage.clear()
+ initKeaTests()
+ jest.spyOn(api.propertyDefinitions, 'list').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api, 'update').mockResolvedValue({} as any)
+ featureFlagLogic.mount()
+ logic = webAnalyticsLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ // `null`/`false` ignore the flag; only an explicit `true` is gated on it. With the flag off
+ // an opt-in falls back to `undefined` (team default) rather than flipping to `false`, which
+ // would wrongly opt an unrestricted team out.
+ it.each([
+ [null, true, undefined],
+ [null, false, undefined],
+ [true, true, true],
+ [true, false, undefined],
+ [false, true, false],
+ [false, false, false],
+ ])('toggle=%s flagOn=%s → payload %s', async (toggle, flagOn, expected) => {
+ setToggleFlag(flagOn as boolean)
+ logic.actions.setUseWebAnalyticsPrecompute(toggle as boolean | null)
+ await expectLogic(logic).toMatchValues({
+ controls: expect.objectContaining({ useWebAnalyticsPrecompute: expected }),
+ })
+ })
+})
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
index 032844c4312e..9b2e9c69f81c 100644
--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx
@@ -218,7 +218,7 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
}),
setIsPathCleaningEnabled: (isPathCleaningEnabled: boolean) => ({ isPathCleaningEnabled }),
setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => ({ shouldFilterTestAccounts }),
- setUseWebAnalyticsPrecompute: (useWebAnalyticsPrecompute: boolean) => ({ useWebAnalyticsPrecompute }),
+ setUseWebAnalyticsPrecompute: (useWebAnalyticsPrecompute: boolean | null) => ({ useWebAnalyticsPrecompute }),
setShouldStripQueryParams: (shouldStripQueryParams: boolean) => ({ shouldStripQueryParams }),
setIncludeHostPath: (includeHostPath: boolean) => ({ includeHostPath }),
setConversionGoal: (conversionGoal: WebAnalyticsConversionGoal | null) => ({ conversionGoal }),
@@ -296,6 +296,11 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
})),
reducers(() => {
const persistConfig = { persist: true, prefix: `${getCurrentTeamId()}__` }
+ // The precompute toggle changed from opt-in (default `false`) to a tri-state where
+ // `null` means "use the team default". Legacy users persisted the old `false`, which
+ // would now read as an explicit opt-out. A versioned prefix orphans that stale value so
+ // they rehydrate `null` and the backend's per-team default applies.
+ const precomputePersistConfig = { persist: true, prefix: `${getCurrentTeamId()}__precompute_optout_v2__` }
return {
surveyModalPath: [
null as string | null,
@@ -449,8 +454,11 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
},
],
useWebAnalyticsPrecompute: [
- false as boolean,
- persistConfig,
+ // Tri-state: `null` means the user never touched the toggle, so the
+ // backend's per-team default decides (opt-out for unrestricted teams,
+ // opt-in for everyone else). An explicit `true`/`false` overrides it.
+ null as boolean | null,
+ precomputePersistConfig,
{
setUseWebAnalyticsPrecompute: (_, { useWebAnalyticsPrecompute }) => useWebAnalyticsPrecompute,
},
@@ -828,17 +836,26 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([
filterTestAccounts: boolean,
shouldStripQueryParams: boolean,
includeHostPath: boolean,
- useWebAnalyticsPrecompute: boolean,
+ useWebAnalyticsPrecompute: boolean | null,
featureFlags: Record<string, boolean>
) => ({
isPathCleaningEnabled,
filterTestAccounts,
shouldStripQueryParams,
includeHostPath: !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_INCLUDE_HOST] && includeHostPath,
- // Gate the persisted opt-in on the flag so killing the flag can never send a stale `true`
- // to the backend for a team that had it enabled — belt-and-suspenders, not a backend guard.
+ // `null` (untouched) → omitted, so the backend's per-team default decides.
+ // Explicit `false` (opt-out) → always sent, even if the flag is later killed.
+ // Explicit `true` (opt-in) → only sent while the flag is on; with the flag off we
+ // omit it (fall back to the default) rather than flipping it to `false`, which on an
+ // unrestricted team would wrongly opt the user out instead of leaving them default-on.
useWebAnalyticsPrecompute:
- useWebAnalyticsPrecompute && !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE],
+ useWebAnalyticsPrecompute == null
+ ? undefined
+ : useWebAnalyticsPrecompute === false
+ ? false
+ : featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE]
+ ? true
+ : undefined,
}),
],
filters: [
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 096f1d72a589..4aac7687bd2d 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -922,3 +922,18 @@ 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))
]
+
+# 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)
+ )
+]
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 bc86eb864a17..8f958c0453d6 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,3 +1,5 @@
+from datetime import UTC, datetime
+
from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin
from unittest import mock
@@ -15,18 +17,31 @@ from posthog.schema import (
WebStatsTableQuery,
)
+from posthog.hogql import ast
+
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 (
+ PerQueryOptedOut,
+ PerQueryOptInNotSet,
+ TooManyFilters,
+ UnsupportedFilterKey,
+ check_common_eligibility,
compute_filters_eligibility_hash,
+ host_filter_expr,
is_precompute_enabled_for_team,
+ is_precompute_unrestricted_for_team,
)
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
_COMMON = "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common"
+def _date_range() -> tuple[datetime, datetime]:
+ return (datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC))
+
+
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:
@@ -44,6 +59,102 @@ class TestIsPrecomputeEnabledForTeam(BaseTest):
def test_team_not_in_setting_with_flag_off_is_ineligible(self, _flag) -> None:
assert is_precompute_enabled_for_team(self.team) is False
+ @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):
+ def _check(self, *, use_precompute, properties=None) -> None:
+ check_common_eligibility(
+ team=self.team,
+ use_web_analytics_precompute=use_precompute,
+ conversion_goal=None,
+ sampling=None,
+ modifiers=None,
+ properties=properties or [],
+ resolve_date_range=_date_range,
+ )
+
+ def test_restricted_team_rejects_untouched_opt_in(self) -> None:
+ 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)
+
+ 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:
+ 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]):
+ 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),
+ ]
+ 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)
+
+
+class TestHostFilterExpr(BaseTest):
+ def test_empty_properties_is_true_constant(self) -> None:
+ expr = host_filter_expr([], team=self.team)
+ 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 _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 75c6642b9db4..ed27aa726582 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
@@ -613,3 +613,55 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
result = execute_lazy_precomputed_read(runner)
assert result is None, f"expected fall-back to raw when current precompute not ready, got {result!r}"
+
+ # --- Group D: unrestricted teams ----------------------------------------
+
+ @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.
+ 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]):
+ 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):
+ 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]):
+ 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()
+
+ self._run(self._build_query(properties=firefox))
+ firefox_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert chrome_hashes and firefox_hashes, "both filtered runs should create jobs"
+ assert chrome_hashes.isdisjoint(firefox_hashes), (
+ f"distinct filter values must produce distinct cache keys, got overlap: {chrome_hashes & firefox_hashes}"
+ )
+
+ @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
+ # 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]):
+ 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):
+ self._seed_two_sessions()
+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_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
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.py
index fb1f9361e912..ab89ea6796da 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
@@ -556,3 +556,53 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
"prev_bounce_rate": row[3][1],
}
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.
+ 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]):
+ 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):
+ 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]):
+ 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()
+
+ self._run(self._build_query(properties=firefox))
+ firefox_hashes = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert chrome_hashes and firefox_hashes, "both filtered runs should create jobs"
+ assert chrome_hashes.isdisjoint(firefox_hashes), (
+ f"distinct filter values must produce distinct cache keys, got overlap: {chrome_hashes & firefox_hashes}"
+ )
+
+ @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
+ # 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]):
+ 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):
+ self._seed_two_sessions()
+ with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_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
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 bcaa37d72825..54a874b5bb49 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
@@ -32,6 +32,7 @@ from posthog.models.team import Team
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
LAZY_TTL_SECONDS, # noqa: F401 — re-exported; several runners import it from this module
is_precompute_enabled_for_team,
+ is_precompute_unrestricted_for_team,
)
logger = structlog.get_logger(__name__)
@@ -128,6 +129,12 @@ class PerQueryOptInNotSet(LazyPrecomputeIneligible):
pass
+class PerQueryOptedOut(LazyPrecomputeIneligible):
+ """Unrestricted team where the user explicitly turned precompute off."""
+
+ pass
+
+
class NonIntegerTimezone(LazyPrecomputeIneligible):
pass
@@ -237,7 +244,14 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
if not is_precompute_enabled_for_team(runner.team):
raise OrgFeatureFlagDisabled()
- if query.useWebAnalyticsPrecompute is not True:
+ 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()
# Half-hour-offset timezones (IST +5:30, Newfoundland -3:30, Nepal +5:45, etc.)
@@ -262,18 +276,23 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
if query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid":
raise SessionsV2UuidMode()
- 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()
+ # 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.
+ 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()
date_from = runner.query_date_range.date_from() # type: ignore[attr-defined]
date_to = runner.query_date_range.date_to() # type: ignore[attr-defined]
@@ -294,6 +313,12 @@ 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)
diff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
index c8f5b38c788a..08c252586f0e 100644
--- a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py
@@ -287,7 +287,7 @@ def ensure_web_goals_precomputed(
placeholders: dict[str, ast.Expr] = {
"events_session_id": _events_session_id_expr(runner),
"action_or_expr": _action_or_expr(actions),
- "user_filter": host_filter_expr(runner.query.properties or []),
+ "user_filter": host_filter_expr(runner.query.properties or [], team=runner.team),
"test_account_filter": test_account_filter_expr(
test_account_filters=runner._test_account_filters, team=runner.team
),
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 2ffc4b410baf..d622d51a5e9d 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
@@ -104,6 +104,12 @@ class PerQueryOptInNotSet(LazyPrecomputeIneligible):
pass
+class PerQueryOptedOut(LazyPrecomputeIneligible):
+ """Unrestricted team where the user explicitly turned precompute off."""
+
+ pass
+
+
class NonIntegerTimezone(LazyPrecomputeIneligible):
pass
@@ -174,6 +180,17 @@ 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) and treat the per-query toggle
+ as opt-out rather than opt-in. 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.
@@ -183,9 +200,14 @@ def is_precompute_enabled_for_team(team: Team) -> bool:
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).
+
+ 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
return is_org_feature_flag_enabled(team)
@@ -212,7 +234,14 @@ def check_common_eligibility(
if not is_precompute_enabled_for_team(team):
raise OrgFeatureFlagDisabled()
- if use_web_analytics_precompute is not True:
+ unrestricted = is_precompute_unrestricted_for_team(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 use_web_analytics_precompute is False:
+ raise PerQueryOptedOut()
+ elif use_web_analytics_precompute is not True:
raise PerQueryOptInNotSet()
if not is_integer_timezone(team.timezone):
@@ -227,17 +256,22 @@ def check_common_eligibility(
if modifiers and getattr(modifiers, "sessionsV2JoinMode", None) == SessionsV2JoinMode.UUID:
raise SessionsV2UuidMode()
- 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()
+ # 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()
date_from, date_to = resolve_date_range()
if date_from is None or date_to is None:
@@ -285,14 +319,20 @@ def compute_filters_eligibility_hash(query: Any, team_timezone: str) -> str:
return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()
-def host_filter_expr(properties: list) -> ast.Expr:
- """Translate the (gated-down-to-≤1) user filter list to an AST expression.
+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.
"""
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(
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
index 12aea0aa4578..c3f5215532ed 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_frustration_lazy_precompute.py
@@ -256,7 +256,7 @@ def ensure_web_stats_frustration_precomputed(
"events_session_id": _events_session_id_expr(runner),
"breakdown_value_expr": _breakdown_value_expr(runner),
"event_scan_filter": _event_scan_filter_expr(),
- "user_filter": host_filter_expr(runner.query.properties or []),
+ "user_filter": host_filter_expr(runner.query.properties or [], team=runner.team),
"test_account_filter": test_account_filter_expr(
test_account_filters=runner._test_account_filters, team=runner.team
),
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
index 846ebcc52252..6a66b583109d 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py
@@ -283,7 +283,7 @@ def ensure_web_stats_paths_precomputed(
"breakdown_value_expr": _breakdown_value_expr(runner),
"entry_breakdown_value_expr": _entry_breakdown_value_expr(runner),
"event_type_filter": runner.event_type_expr,
- "user_filter": host_filter_expr(runner.query.properties or []),
+ "user_filter": host_filter_expr(runner.query.properties or [], team=runner.team),
"test_account_filter": test_account_filter_expr(
test_account_filters=runner._test_account_filters, team=runner.team
),
diff --git a/products/web_analytics/dags/eager_web_analytics_precompute.py b/products/web_analytics/dags/eager_web_analytics_precompute.py
index 1a16a7e2cc49..a97482eee008 100644
--- a/products/web_analytics/dags/eager_web_analytics_precompute.py
+++ b/products/web_analytics/dags/eager_web_analytics_precompute.py
@@ -33,13 +33,14 @@ cache perpetually warm, so user requests turn into pure reads.
Audience
--------
-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 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 job is a no-op on self-hosted instances (`is_cloud()` returns False)
since the lazy precompute infrastructure is Cloud-only.
@@ -186,7 +187,19 @@ def _resolve_eager_audience() -> tuple[list[int], str, dict]:
if not is_cloud():
return [], "not_cloud", {}
- team_ids = list(settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS)
+ # 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.
+ team_ids = list(
+ dict.fromkeys(
+ [
+ *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS,
+ *settings.WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS,
+ ]
+ )
+ )
diag = {"teams_configured": len(team_ids)}
if not team_ids:
return [], "no_teams_configured", diag
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 cb4ed9eb0096..535266ad7aa2 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
@@ -10,6 +10,7 @@ from django.test import override_settings
from django.utils import timezone
import dagster
+from parameterized import parameterized
from structlog.testing import capture_logs
from posthog.schema import WebAnalyticsPreComputeStrategy, WebStatsBreakdown
@@ -74,12 +75,31 @@ class TestResolveEagerAudience:
assert team_ids == []
assert reason == "not_cloud"
- @override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[])
+ @override_settings(
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_TEAM_IDS=[], WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[]
+ )
def test_returns_empty_when_no_teams_configured(self, _is_cloud):
team_ids, reason, _diag = _resolve_eager_audience()
assert team_ids == []
assert reason == "no_teams_configured"
+ @parameterized.expand(
+ [
+ ("unrestricted_only", [], [5], [5]),
+ ("union_with_overlap", [2, 7], [7, 9], [2, 7, 9]),
+ ("restricted_only", [2, 7], [], [2, 7]),
+ ]
+ )
+ 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,
+ ):
+ team_ids, reason, diag = _resolve_eager_audience()
+ assert team_ids == expected
+ assert reason == "ok"
+ assert diag == {"teams_configured": len(expected)}
+
@patch("products.web_analytics.dags.eager_web_analytics_precompute.is_cloud", return_value=True)
class TestWarmEagerBaselineOp(APIBaseTest):