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): precompute channel-filtered overview, stats and paths tiles (#102712)

Lucas Ricoybbc504ee9187
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 eb69634ad92d..c7d2201d9149 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
@@ -42,6 +42,7 @@ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTab
from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import can_use_lazy_precompute
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
_VOLUME_FLOOR_LOCAL_CACHE,
+ CHANNEL_MAX_WINDOW_DAYS,
OOM_PIN_TTL_SECONDS,
REVALIDATION_START_DELAY_SECONDS,
REVALIDATION_TRIGGER,
@@ -59,6 +60,7 @@ from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common imp
_oom_pin_key,
_sticky_team_count_key,
_team_shape_set_key,
+ channel_ttl_schedule,
check_common_eligibility,
compute_filters_eligibility_hash,
compute_shape_cap_key,
@@ -116,6 +118,41 @@ class TestIsPrecomputeEnabledForTeam(BaseTest):
flag.assert_not_called()
+class TestChannelModifiersShapeKey(BaseTest):
+ def _runner(self, modifiers=None):
+ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
+
+ query = WebOverviewQuery(
+ dateRange=DateRange(date_from="-7d"),
+ properties=[SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)],
+ )
+ query.modifiers = modifiers
+ return WebOverviewQueryRunner(team=self.team, query=query)
+
+ def test_semantic_overrides_key_apart_and_defaults_stay_stable(self) -> None:
+ from posthog.schema import HogQLQueryModifiers
+
+ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import channel_rules_shape_key
+
+ # Default requests must share one namespace across constructions, while a
+ # request-controlled semantic override (the reviewers' bounce-threshold
+ # example) must mint its own — never write into the shared buckets.
+ default_key = channel_rules_shape_key(self._runner())
+ assert channel_rules_shape_key(self._runner()) == default_key
+ override_key = channel_rules_shape_key(self._runner(HogQLQueryModifiers(bounceRateDurationSeconds=42)))
+ assert override_key != default_key
+
+
+class TestChannelTtlSchedule(BaseTest):
+ def test_schedule_caps_job_width_and_holds_old_days(self) -> None:
+ # Without max_window_days, `split_ranges_by_ttl` merges a year-long span's
+ # 90-day-band tail into ONE insert; without the long default hold, annual
+ # shapes re-scan a year of events every three weeks.
+ schedule = channel_ttl_schedule(self.team)
+ assert schedule.max_window_days == CHANNEL_MAX_WINDOW_DAYS
+ assert schedule.default_ttl_seconds == 90 * 24 * 60 * 60
+
+
class TestCheckCommonEligibility(BaseTest):
def _check(self, *, use_precompute, properties=None) -> None:
check_common_eligibility(
@@ -1126,6 +1163,31 @@ class TestStaleRevalidationEnqueue(BaseTest):
handle_stale_served(runner=stats_runner, family="web_stats")
assert delay.call_count == 2
+ def test_channel_rule_variants_get_distinct_debounce_keys(self):
+ # Channel-filtered shapes are distinct per custom-rules set (the rules join
+ # the job hash), so one rule set's stale serve must not debounce-suppress
+ # revalidating another's.
+ query = WebOverviewQuery(
+ dateRange=DateRange(date_from="-7d"),
+ properties=[SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)],
+ )
+ rules = [
+ {
+ "channel_type": "Partners",
+ "combiner": "OR",
+ "id": "r1",
+ "items": [{"id": "c1", "key": "utm_source", "op": "exact", "value": ["partner"]}],
+ }
+ ]
+ default_runner = WebOverviewQueryRunner(team=self.team, query=query)
+ self.team.modifiers = {"customChannelTypeRules": rules}
+ self.team.save()
+ rules_runner = WebOverviewQueryRunner(team=self.team, query=query)
+ with self._delay_patch() as delay:
+ handle_stale_served(runner=default_runner, family="web_overview")
+ handle_stale_served(runner=rules_runner, family="web_overview")
+ assert delay.call_count == 2
+
def test_per_team_budget_bounds_distinct_shape_enqueues(self):
# Filters/dates are request-controlled, so distinct shapes are unbounded;
# the per-team budget must cap total enqueues per window regardless.
@@ -1300,3 +1362,20 @@ class TestPrecomputeShapeCapWiring(BaseTest):
_team_shape_set_key(self.team.pk),
compute_shape_cap_key(self._runner().query, self.team.timezone),
)
+
+ @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_changed_channel_rules_consume_a_distinct_shape(self, mock_ensure, _enqueue):
+ mock_ensure.return_value = LazyComputationResult(ready=False, job_ids=[], memory_exceeded=False)
+ with tags_context(trigger="webAnalyticsQueryWarming"):
+ for rules_key in ("first-rule-set", "first-rule-set", "second-rule-set"):
+ web_ensure_precomputed(
+ team=self.team,
+ runner=self._runner(),
+ family="web_overview",
+ ttl_seconds={"default": 3600},
+ table=None,
+ shape_key_extra=rules_key,
+ )
+ assert [call.kwargs["run_inserts"] for call in mock_ensure.call_args_list] == [True, True, False]
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 277cefc2417c..d9e68a1ecff5 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
@@ -1,3 +1,4 @@
+import math
import uuid
from datetime import UTC, datetime
@@ -23,12 +24,16 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client import sync_execute
from posthog.models.utils import uuid7
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
+from products.web_analytics.backend.hogql_queries import web_overview_lazy_precompute as overview_precompute
+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import ORG_FEATURE_FLAG_KEY
from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner
@@ -47,9 +52,12 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
# Mock the org-level feature flag check to True so the gate accepts our test
# team. Outside this context manager the default `posthoganalytics.feature_enabled`
# returns False (no API key in tests), which models a flag-disabled org.
+ # Scoped to the precompute rollout flag: `posthoganalytics` is one shared
+ # module, so an unscoped True would also enable result-changing flags
+ # (first-pageview attribution), which makes channel filters ineligible.
return patch(
"products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
- return_value=True,
+ side_effect=lambda key, *args, **kwargs: key == ORG_FEATURE_FLAG_KEY,
)
def _seed_two_sessions(self) -> None:
@@ -190,19 +198,143 @@ class TestWebOverviewLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_property_falls_through(self):
- # 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(
properties=[
- SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT),
+ SessionPropertyFilter(key="$entry_pathname", value="/", operator=PropertyOperator.EXACT),
]
)
)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+ @parameterized.expand(
+ [
+ ("string", "2024-01-02T00:00:00", "2024-01-04T23:59:59", False, "Paid Search", 7),
+ ("uuid", "2024-01-02T00:00:00", "2024-01-04T23:59:59", False, "Paid Search", 7),
+ ("string", "2023-01-05T00:00:00", "2024-01-04T23:59:59", False, "Paid Search", 7),
+ ("string", "2024-01-02T00:00:00", "2024-01-03T23:59:59", False, "Paid Search", 6),
+ ("string", "2024-01-02T10:02:00", "2024-01-06T00:00:00", False, "Paid Search", 5),
+ ("string", "2024-01-03T00:00:00", "2024-01-04T23:59:59", True, "Paid Search", 3),
+ ("string", "2024-01-02T00:00:00", "2024-01-04T23:59:59", False, "Synthetic channel", 1),
+ ("string", "2024-01-04T00:05:00", "2024-01-04T00:05:00", False, "Paid Search", 0),
+ ("string", "2024-01-02T00:00:00", "2024-01-03T11:00:00", False, "Paid Search", 5),
+ ("string", "2024-01-03T11:00:00", "2024-01-03T11:00:00", False, "Paid Search", 1),
+ ]
+ )
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_channel_precompute_matches_live(
+ self, mode: str, start: str, end: str, compare: bool, channel: str, expected_views: int
+ ) -> None:
+ fixtures = [
+ ("a", ["2024-01-02T10:00:00", "2024-01-02T10:05:00"], "cpc"),
+ ("a", ["2024-01-03T11:00:00"], "cpc"),
+ ("b", ["2024-01-02T23:55:00", "2024-01-03T00:05:00"], "cpc"),
+ ("c", ["2024-01-03T12:00:00"], "synthetic"),
+ ("d", ["2024-01-02T12:00:00"], ""),
+ ("e", ["2024-01-03T23:55:00", "2024-01-04T00:05:00"], "cpc"),
+ ]
+ for person in {person for person, _, _ in fixtures}:
+ _create_person(team_id=self.team.pk, distinct_ids=[person])
+ for person, timestamps, medium in fixtures:
+ session_id = str(uuid7(timestamps[0]))
+ for timestamp in timestamps:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=person,
+ timestamp=timestamp,
+ properties={
+ "$session_id": session_id,
+ "$current_url": "https://example.com/page",
+ "utm_source": "google",
+ "utm_medium": medium,
+ "$referring_domain": "$direct",
+ },
+ )
+ query = self._build_query(
+ date_from=start,
+ date_to=end,
+ compare=compare,
+ properties=[SessionPropertyFilter(key="$channel_type", value=channel, operator=PropertyOperator.EXACT)],
+ )
+ query.filterTestAccounts = False
+ assert query.dateRange is not None
+ query.dateRange.explicitDate = True
+ query.modifiers = HogQLQueryModifiers(
+ sessionsV2JoinMode=SessionsV2JoinMode(mode),
+ customChannelTypeRules=[
+ {
+ "channel_type": "Synthetic channel",
+ "combiner": "OR",
+ "id": "synthetic-rule",
+ "items": [
+ {"id": "synthetic-condition", "key": "utm_medium", "op": "exact", "value": ["synthetic"]}
+ ],
+ }
+ ],
+ )
+ runner = WebOverviewQueryRunner(team=self.team, query=query)
+ context = HogQLContext(
+ team=self.team, team_id=self.team.pk, modifiers=runner.modifiers, enable_select_queries=True
+ )
+ sql, _ = prepare_and_print_ast(runner.to_query(), context=context, dialect="clickhouse")
+ expected = list(sync_execute(sql, context.values)[0])
+ self.assertEqual(expected[2], expected_views)
+ ensure = overview_precompute.web_ensure_precomputed
+ with (
+ self._enable_lazy(),
+ patch.object(
+ overview_precompute,
+ "web_ensure_precomputed",
+ side_effect=lambda **kwargs: ensure(**kwargs, run_inserts=True),
+ ),
+ ):
+ self.assertTrue(overview_precompute.can_use_lazy_precompute(runner))
+ actual = overview_precompute.execute_lazy_precomputed_read(runner)
+ self.assertIsNotNone(actual)
+ assert actual is not None
+ cached = overview_precompute.execute_lazy_precomputed_read(WebOverviewQueryRunner(team=self.team, query=query))
+ self.assertIsNotNone(cached)
+ assert cached is not None
+ for row in (actual, cached):
+ for expected_value, actual_value in zip(expected, row):
+ if isinstance(expected_value, float) and math.isnan(expected_value):
+ self.assertTrue(math.isnan(actual_value))
+ else:
+ self.assertAlmostEqual(expected_value, actual_value)
+ if channel == "Synthetic channel":
+ assert query.modifiers.customChannelTypeRules is not None
+ query.modifiers.customChannelTypeRules[0].items[0].value = ["unused-medium"]
+ changed_runner = WebOverviewQueryRunner(team=self.team, query=query)
+ self.assertIsNone(overview_precompute.execute_lazy_precomputed_read(changed_runner))
+ with patch.object(
+ overview_precompute,
+ "web_ensure_precomputed",
+ side_effect=lambda **kwargs: ensure(**kwargs, run_inserts=True),
+ ):
+ changed = overview_precompute.execute_lazy_precomputed_read(changed_runner)
+ self.assertIsNotNone(changed)
+ assert changed is not None
+ self.assertEqual(changed[2], 0)
+
+ @parameterized.expand([("2023-01-15", True), ("2023-01-01", False)])
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_channel_precompute_year_limit(self, start: str, eligible: bool) -> None:
+ query = self._build_query(
+ date_from=start,
+ date_to="2024-01-15",
+ properties=[
+ SessionPropertyFilter(key="$channel_type", value="Paid Search", operator=PropertyOperator.EXACT)
+ ],
+ )
+ with self._enable_lazy():
+ self.assertEqual(
+ overview_precompute.can_use_lazy_precompute(WebOverviewQueryRunner(team=self.team, query=query)),
+ eligible,
+ )
+
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
self._seed_two_sessions()
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
index 5c0dc9226771..a9d6dc054076 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_lazy_precompute.py
@@ -12,6 +12,7 @@ from posthog.schema import (
DateRange,
EventPropertyFilter,
PropertyOperator,
+ SessionPropertyFilter,
WebAnalyticsOrderByDirection,
WebAnalyticsOrderByFields,
WebAnalyticsPreComputeStrategy,
@@ -30,7 +31,10 @@ from products.analytics_platform.backend.models.preaggregation_job import Preagg
from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTableQueryRunner
from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import SESSION_ID_SET_FEATURE_FLAG_KEY
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import ORG_FEATURE_FLAG_KEY
-from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import _breakdown_having_expr
+from products.web_analytics.backend.hogql_queries.web_stats_lazy_precompute import (
+ _breakdown_having_expr,
+ can_use_lazy_precompute as can_use_stats_lazy_precompute,
+)
# Low-cardinality breakdowns with a generic seed that have data and are cheap to
# assert parity on. VIEWPORT is exercised separately — the raw query compares
@@ -221,6 +225,77 @@ class TestWebStatsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
assert lazy == raw, f"lazy/raw mismatch for {breakdown_by}: raw={raw}, lazy={lazy}"
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_channel_filtered_lazy_matches_raw(self):
+ # The one admitted session filter: `$channel_type` resolves inside the
+ # INSERT via the sessions virtual field, so a channel-filtered breakdown
+ # precomputes and must agree with the live path. The seed's google.com
+ # referrer classifies as Organic Search with no UTMs.
+ props = [SessionPropertyFilter(key="$channel_type", value="Organic Search", operator=PropertyOperator.EXACT)]
+ self._seed()
+
+ raw = self._metrics(self._run(self._build_query(properties=props)))
+
+ with self._enable_lazy():
+ lazy_response = self._run(self._build_query(properties=props))
+ lazy = self._metrics(lazy_response)
+
+ assert self._job_count() > 0, "channel-filtered read should create precompute jobs"
+ assert lazy_response.preComputeStrategy == WebAnalyticsPreComputeStrategy.LAZY_PRECOMPUTE
+ assert lazy == raw, f"lazy/raw mismatch under channel filter: raw={raw}, lazy={lazy}"
+
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_channel_filter_over_max_days_still_admitted(self):
+ # The gate check the customer path depends on: a channel-filtered range
+ # past MAX_PRECOMPUTE_DAYS (90) but under CHANNEL_MAX_PRECOMPUTE_DAYS
+ # (366) must stay eligible instead of DateRangeOverMax falling to live.
+ props = [SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)]
+ runner = WebStatsTableQueryRunner(
+ team=self.team,
+ query=self._build_query(properties=props, date_from="2023-06-01", date_to="2024-01-07"),
+ )
+ with self._enable_lazy():
+ assert can_use_stats_lazy_precompute(runner)
+
+ unfiltered = WebStatsTableQueryRunner(
+ team=self.team,
+ query=self._build_query(date_from="2023-06-01", date_to="2024-01-07"),
+ )
+ with self._enable_lazy():
+ assert not can_use_stats_lazy_precompute(unfiltered), "the 366-day cap is channel-scoped, not general"
+
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_uuid_session_mode_stays_rejected_with_channel_filter(self):
+ # The UUID join-mode bypass is overview-only (its channel template carries
+ # the UUID-safe session-id handling); the stats insert does not, so a
+ # channel filter must not smuggle uuid-mode teams past the rejection.
+ from posthog.schema import HogQLQueryModifiers, SessionsV2JoinMode
+
+ query = self._build_query(
+ properties=[SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)]
+ )
+ query.modifiers = HogQLQueryModifiers(sessionsV2JoinMode=SessionsV2JoinMode.UUID)
+ runner = WebStatsTableQueryRunner(team=self.team, query=query)
+ with self._enable_lazy():
+ assert not can_use_stats_lazy_precompute(runner)
+
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_rewritten_first_pageview_channel_filter_stays_live(self):
+ # With first-pageview attribution on, the live path rewrites the channel
+ # filter to first-pageview semantics; the insert would apply raw session
+ # attribution, so the gate must refuse rather than serve diverging rows.
+ props = [SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)]
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(properties=props))
+ with (
+ self._enable_lazy(),
+ patch.object(
+ WebStatsTableQueryRunner,
+ "rewritten_first_pageview_filters",
+ new_callable=lambda: property(lambda self: props),
+ ),
+ ):
+ assert not can_use_stats_lazy_precompute(runner)
+
@parameterized.expand(PARITY_BREAKDOWNS)
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_lazy_matches_raw_with_compare(self, _name: str, breakdown_by: WebStatsBreakdown):
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 7e8dd5276fbe..c45746b2d478 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
@@ -1,5 +1,6 @@
import uuid
import dataclasses
+from datetime import UTC, datetime
import unittest
import time_machine
@@ -29,7 +30,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
-from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries
+from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries, tags_context
from posthog.models.utils import uuid7
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
@@ -38,6 +39,7 @@ from products.web_analytics.backend.hogql_queries.stats_table import WebStatsTab
# Aliased so pytest doesn't collect this `test_`-prefixed helper as a test case.
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
+ ORG_FEATURE_FLAG_KEY,
SESSION_FORWARD_PAD_MINUTES,
host_filter_expr,
test_account_filter_expr as _test_account_filter_expr,
@@ -49,6 +51,7 @@ from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precomput
_events_session_id_expr,
_top_k_ranking_expr,
can_use_lazy_precompute,
+ ensure_web_stats_paths_precomputed,
)
@@ -59,9 +62,12 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
PreaggregationJob.objects.filter(team_id=self.team.pk).delete()
def _enable_lazy(self):
+ # Scoped to the precompute rollout flag: `posthoganalytics` is one shared
+ # module, so an unscoped True would also enable result-changing flags
+ # (first-pageview attribution), which makes channel filters ineligible.
return patch(
"products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",
- return_value=True,
+ side_effect=lambda key, *args, **kwargs: key == ORG_FEATURE_FLAG_KEY,
)
def _seed_two_sessions(self) -> None:
@@ -296,16 +302,63 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_session_property_filter_falls_through(self):
+ # `$channel_type` is the ONE admitted session filter; every other session
+ # property must keep falling through to the live path.
with self._enable_lazy():
self._run(
self._build_query(
properties=[
- SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT),
+ SessionPropertyFilter(key="$session_duration", value=10, operator=PropertyOperator.GT),
]
)
)
assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0
+ @time_machine.travel("2024-01-15T12:00:00Z", tick=False)
+ def test_channel_type_filter_creates_precompute_job(self):
+ self._seed_two_sessions()
+ with self._enable_lazy():
+ self._run(
+ self._build_query(
+ properties=[
+ SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT),
+ ]
+ )
+ )
+ assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() > 0
+
+ def test_channel_rules_rotate_the_job_hash(self):
+ # A custom-channel-rules edit reclassifies sessions, so the buckets built
+ # under the old rules must not be reused — the rules join the job hash.
+ # Driven through the warmer's ensure (inline inserts allowed) so job
+ # creation is deterministic; the user path defers builds to a debounced
+ # background enqueue that this test must not depend on.
+ props = [SessionPropertyFilter(key="$channel_type", value="Direct", operator=PropertyOperator.EXACT)]
+ start, end = datetime(2024, 1, 1, tzinfo=UTC), datetime(2024, 1, 8, tzinfo=UTC)
+ self._seed_two_sessions()
+ with self._enable_lazy(), tags_context(trigger="webAnalyticsQueryWarming"):
+ runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query(properties=props))
+ ensure_web_stats_paths_precomputed(runner=runner, time_range_start=start, time_range_end=end)
+ hashes_before = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+ assert hashes_before, "channel-filtered ensure should create precompute jobs"
+
+ self.team.modifiers = {
+ "customChannelTypeRules": [
+ {
+ "channel_type": "Partners",
+ "combiner": "OR",
+ "id": "partner-rule",
+ "items": [{"id": "c1", "key": "utm_source", "op": "exact", "value": ["partner"]}],
+ }
+ ]
+ }
+ self.team.save()
+ runner_after = WebStatsTableQueryRunner(team=self.team, query=self._build_query(properties=props))
+ ensure_web_stats_paths_precomputed(runner=runner_after, time_range_start=start, time_range_end=end)
+ hashes_after = {str(j.query_hash) for j in PreaggregationJob.objects.filter(team_id=self.team.pk)}
+
+ assert hashes_after - hashes_before, "a rules edit must mint new job hashes, not reuse the old buckets"
+
@time_machine.travel("2024-01-15T12:00:00Z", tick=False)
def test_sampling_falls_through(self):
with self._enable_lazy():
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 d89536ec5f1c..cfc0920a23b5 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
@@ -8,6 +8,7 @@ here so both `web_overview_lazy_precompute.py` and `web_stats_lazy_precompute.py
share one implementation.
"""
+import json
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import Optional, Protocol, Union
@@ -15,12 +16,12 @@ from typing import Optional, Protocol, Union
import structlog
from prometheus_client import Counter
-from posthog.schema import WebOverviewQuery, WebStatsTableQuery, WebVitalsPathBreakdownQuery
+from posthog.schema import HogQLQueryModifiers, WebOverviewQuery, WebStatsTableQuery, WebVitalsPathBreakdownQuery
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.placeholders import find_placeholders
-from posthog.hogql.property import get_property_type, property_to_expr
+from posthog.hogql.property import get_property_key, get_property_type, property_to_expr
from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr
@@ -29,6 +30,7 @@ from posthog.models.team import Team
from products.access_control.backend.facade.api import team_has_property_access_rules
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
+ channel_ttl_schedule, # noqa: F401 — re-exported alongside the channel constants below
is_precompute_enabled_for_team,
is_team_above_volume_floor,
set_lazy_precompute_ineligible_reason,
@@ -72,6 +74,13 @@ SUPPORTED_USER_FILTER_KEYS: set[str] = {"$host"}
# enough daily jobs that the first request burns INSERT slots for minutes.
MAX_PRECOMPUTE_DAYS = 90
+# Channel-filtered shapes accept a full year (+leap): the whole point of admitting
+# the `$channel_type` filter is the long-range dashboards it appears on, and
+# `channel_ttl_schedule`'s job-width cap bounds each insert regardless of span.
+# Cold spans build behind the live fallback, so the first request never burns
+# the slots itself.
+CHANNEL_MAX_PRECOMPUTE_DAYS = 366
+
# Forward pad on the per-job event-scan window. The lazy_computation framework
# chunks the precompute span into daily UTC jobs; each job covers
# `[time_window_min, time_window_max)`. A session starting at 23:50 with events
@@ -110,6 +119,9 @@ class LazyPrecomputeRunner(Protocol):
@property
def events_session_property(self) -> ast.Expr: ...
+ @property
+ def modifiers(self) -> HogQLQueryModifiers: ...
+
class LazyPrecomputeIneligible(Exception):
"""Base class for reasons the lazy precompute path is not eligible.
@@ -201,9 +213,9 @@ class MissingDateRange(LazyPrecomputeIneligible):
class DateRangeOverMax(LazyPrecomputeIneligible):
- def __init__(self, days: int):
+ def __init__(self, days: int, max_days: int = MAX_PRECOMPUTE_DAYS):
self.days = days
- super().__init__(f"days={days} max={MAX_PRECOMPUTE_DAYS}")
+ super().__init__(f"days={days} max={max_days}")
def can_use_lazy_precompute(
@@ -212,6 +224,9 @@ def can_use_lazy_precompute(
log_prefix: str,
extra_check: Optional[Callable[[LazyPrecomputeRunner], None]] = None,
require_integer_timezone: bool = True,
+ allow_channel_type_filter: bool = False,
+ allow_uuid_session_join: bool = False,
+ max_days: int = MAX_PRECOMPUTE_DAYS,
) -> bool:
"""Return True iff the lazy precompute gate is eligible. Logs the rejection
reason at INFO level so every fall-through can be attributed.
@@ -224,7 +239,13 @@ def can_use_lazy_precompute(
timezone (and therefore aligns cleanly for half-hour-offset teams too).
"""
try:
- check_common_eligible(runner, require_integer_timezone=require_integer_timezone)
+ check_common_eligible(
+ runner,
+ require_integer_timezone=require_integer_timezone,
+ allow_channel_type_filter=allow_channel_type_filter,
+ allow_uuid_session_join=allow_uuid_session_join,
+ max_days=max_days,
+ )
if extra_check is not None:
extra_check(runner)
except LazyPrecomputeIneligible as exc:
@@ -246,7 +267,14 @@ def can_use_lazy_precompute(
return True
-def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timezone: bool = True) -> None:
+def check_common_eligible(
+ runner: LazyPrecomputeRunner,
+ *,
+ require_integer_timezone: bool = True,
+ allow_channel_type_filter: bool = False,
+ allow_uuid_session_join: bool = False,
+ max_days: int = MAX_PRECOMPUTE_DAYS,
+) -> None:
"""Raise a `LazyPrecomputeIneligible` subclass if the query can't go through
the lazy path on grounds that apply to every web analytics runner. Returns
None on success.
@@ -298,7 +326,9 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
# web stats table has no session-uniq column (it stores `uniq, UUID` user
# state only), so this gate is conservative there — kept shared for
# simplicity until the web overview column is re-typed in a follow-up.
- if query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid":
+ # Only the overview channel path may bypass this: its insert template carries
+ # the UUID-safe session-id handling; the stats template does not.
+ if query.modifiers and query.modifiers.sessionsV2JoinMode == "uuid" and not allow_uuid_session_join:
raise SessionsV2UuidMode()
# Any event/person filter shape is accepted (any key, operator, count), translated
@@ -309,6 +339,12 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
# 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 (
+ allow_channel_type_filter
+ and get_property_type(prop) == "session"
+ and get_property_key(prop) == "$channel_type"
+ ):
+ continue
if get_property_type(prop) not in ("event", "person"):
raise UnsupportedFilterType(get_property_type(prop))
@@ -325,8 +361,8 @@ def check_common_eligible(runner: LazyPrecomputeRunner, *, require_integer_timez
raise MissingDateRange()
days = (date_to - date_from).days
- if days > MAX_PRECOMPUTE_DAYS:
- raise DateRangeOverMax(days)
+ if days > max_days:
+ raise DateRangeOverMax(days, max_days)
def is_constant_true(expr: ast.Expr) -> bool:
@@ -335,6 +371,65 @@ def is_constant_true(expr: ast.Expr) -> bool:
return isinstance(expr, ast.Constant) and expr.value is True
+def has_channel_type_filter(runner: LazyPrecomputeRunner) -> bool:
+ """True when the query carries the one admitted session filter, `$channel_type`.
+
+ False when first-pageview attribution rewrites the filter: the live path then
+ serves first-pageview semantics while the insert would apply raw session
+ attribution, so the query must stay live rather than diverge. The rewritten
+ list is empty unless the team's flag is on, so this is a no-op elsewhere.
+ """
+ if getattr(runner, "rewritten_first_pageview_filters", None):
+ return False
+ return any(
+ get_property_type(prop) == "session" and get_property_key(prop) == "$channel_type"
+ for prop in runner.query.properties or []
+ )
+
+
+# Modifier fields that change what a channel-filtered INSERT stores: channel
+# classification rules, the bounce computation, and the session-id join mode.
+CHANNEL_SEMANTIC_MODIFIER_FIELDS: tuple[str, ...] = (
+ "customChannelTypeRules",
+ "bounceRateDurationSeconds",
+ "bounceRatePageViewMode",
+ "sessionsV2JoinMode",
+ "sessionTableVersion",
+)
+
+
+def channel_rules_shape_key(runner: LazyPrecomputeRunner) -> str:
+ """The request's effective modifiers, serialized deterministically.
+
+ The channel INSERT resolves `session.$channel_type` (and bounce state on the
+ paths/overview templates) through the request's effective modifiers — custom
+ channel rules, bounce thresholds — but modifiers are absent from the lazy
+ job hash. Folding this whole serialization into the job identity (via
+ `with_channel_rules_key`), the shape-cap key (`shape_key_extra`) and the
+ revalidation debounce key means a request with different semantics gets its
+ OWN buckets instead of contaminating or reusing another member's: a default
+ dashboard resolves to the team-default modifiers and shares one namespace,
+ while an explicit override is keyed apart. A team rules edit rotates the
+ buckets the same way.
+
+ The list is the modifiers the channel INSERT templates actually read —
+ channel classification, bounce computation, and the session-id join mode —
+ rather than the whole modifiers object, whose incidental execution fields
+ would fragment the namespace without changing any stored value."""
+ dump = runner.modifiers.model_dump(mode="json")
+ return json.dumps(
+ {field: dump.get(field) for field in CHANNEL_SEMANTIC_MODIFIER_FIELDS},
+ sort_keys=True,
+ )
+
+
+def with_channel_rules_key(user_filter: ast.Expr, runner: LazyPrecomputeRunner) -> ast.Expr:
+ """AND a no-op `rules = rules` predicate onto the insert's user filter so the
+ channel rules join the executor's query hash without changing what it scans."""
+ rules = ast.Constant(value=channel_rules_shape_key(runner))
+ return ast.And(exprs=[user_filter, ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=rules, right=rules)])
+
+
# The line every no-join insert template's sessions-side WHERE ends with; the
# session-id-set variants splice their id filter right after it.
_SESSIONS_SIDE_ANCHOR = "or(sessions.$pageview_count > 0, sessions.$screen_count > 0),"
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 e46b54ed45b2..8227c90068d7 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
@@ -29,7 +29,7 @@ from posthog.schema import SessionsV2JoinMode, WebAnalyticsPreComputeStrategy
from posthog.hogql import ast
from posthog.hogql.modifiers import create_default_modifiers_for_team
-from posthog.hogql.property import get_property_type, property_to_expr
+from posthog.hogql.property import get_property_key, get_property_type, property_to_expr
from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
from posthog import redis
@@ -510,7 +510,7 @@ def get_sticky_warm_shapes() -> list[dict]:
return entries
-def enqueue_stale_revalidation(*, team: Team, query: Any, family: str) -> None:
+def enqueue_stale_revalidation(*, team: Team, query: Any, family: str, debounce_extra: Optional[str] = None) -> None:
"""Enqueue a background re-run of `query` so a stale-served read gets fresh data next time.
Debounced via Redis per (team, family, query shape). Best-effort: this runs on the
@@ -527,7 +527,10 @@ def enqueue_stale_revalidation(*, team: Team, query: Any, family: str) -> None:
try:
client = redis.get_client()
- debounce_key = f"web_swr_reval:{team.id}:{family}:{compute_filters_eligibility_hash(query, team.timezone)[:16]}"
+ shape_part = compute_filters_eligibility_hash(query, team.timezone)[:16]
+ if debounce_extra:
+ shape_part = hashlib.sha256(f"{shape_part}:{debounce_extra}".encode()).hexdigest()[:16]
+ debounce_key = f"web_swr_reval:{team.id}:{family}:{shape_part}"
if not client.set(debounce_key, "1", ex=REVALIDATION_DEBOUNCE_SECONDS, nx=True):
return
budget_key = f"web_swr_reval_budget:{team.id}"
@@ -568,10 +571,36 @@ def handle_stale_served(*, runner: Any, family: str) -> None:
"""
WEB_ANALYTICS_LAZY_PRECOMPUTE_STALE_SERVED.labels(family=family).inc()
tag_queries(precompute_stale=True)
- enqueue_stale_revalidation(team=runner.team, query=runner.query, family=family)
+ # Channel-filtered shapes are distinct per custom-rules set (the rules join the
+ # job hash), so the debounce identity must carry them too — otherwise one rule
+ # set's miss suppresses revalidating another's for the whole debounce window.
+ debounce_extra = None
+ if any(
+ get_property_type(prop) == "session" and get_property_key(prop) == "$channel_type"
+ for prop in getattr(runner.query, "properties", None) or []
+ ):
+ # Mirror `channel_rules_shape_key` (import would cycle): only the fields
+ # that change what the channel INSERT stores join the debounce identity.
+ dump = runner.modifiers.model_dump(mode="json")
+ debounce_extra = json.dumps(
+ {
+ field: dump.get(field)
+ for field in (
+ "customChannelTypeRules",
+ "bounceRateDurationSeconds",
+ "bounceRatePageViewMode",
+ "sessionsV2JoinMode",
+ "sessionTableVersion",
+ )
+ },
+ sort_keys=True,
+ )
+ enqueue_stale_revalidation(team=runner.team, query=runner.query, family=family, debounce_extra=debounce_extra)
-def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResult:
+def web_ensure_precomputed(
+ *, team: Team, shape_key_extra: Optional[str] = None, **kwargs: Any
+) -> LazyComputationResult:
"""`ensure_precomputed` for web analytics, with reactive per-team OOM capping and
the web-wide stale-while-revalidate policy.
@@ -628,6 +657,8 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResul
# 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 shape_key_extra is not None:
+ shape_hash = hashlib.sha256(f"{shape_hash}:{shape_key_extra}".encode()).hexdigest()
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()
@@ -742,6 +773,24 @@ LAZY_TTL_SECONDS: dict[str, int] = {
"default": 21 * 24 * 60 * 60, # days 36+
}
+# TTL schedule for channel-filtered shapes: same graded bands for recent days,
+# but old immutable days are held for 90 days instead of 21 — without the longer
+# hold, a year-long shape re-scans a year of events every three weeks per shape.
+CHANNEL_TTL_SECONDS: dict[str, int] = {**LAZY_TTL_SECONDS, "default": 90 * 24 * 60 * 60}
+
+# Job-width cap for channel shapes. `split_ranges_by_ttl` merges consecutive days
+# sharing one TTL band into a single job, so the 90-day band above would put a
+# year-long span's whole tail into ONE insert without this cap. Seven days keeps
+# each insert bounded (a 366-day backfill runs as ~53 jobs) while the reactive
+# OOM pin can still tighten a pathological team to 1-day windows.
+CHANNEL_MAX_WINDOW_DAYS = 7
+
+
+def channel_ttl_schedule(team: Team) -> TtlSchedule:
+ """The channel-filtered shapes' TTL schedule, with the job-width cap applied."""
+ return parse_ttl_schedule(CHANNEL_TTL_SECONDS, team.timezone, max_window_days=CHANNEL_MAX_WINDOW_DAYS)
+
+
# MVP user-filter allowlist: only an EventPropertyFilter on `$host` with
# operator `exact` is admitted. Test-account filters are always allowed
# (their content is hashed into the cache key).
@@ -849,9 +898,9 @@ class MissingDateRange(LazyPrecomputeIneligible):
class DateRangeOverMax(LazyPrecomputeIneligible):
- def __init__(self, days: int):
+ def __init__(self, days: int, max_days: int = MAX_PRECOMPUTE_DAYS):
self.days = days
- super().__init__(f"days={days} max={MAX_PRECOMPUTE_DAYS}")
+ super().__init__(f"days={days} max={max_days}")
def is_org_feature_flag_enabled(team: Team) -> bool:
@@ -905,6 +954,8 @@ def check_common_eligibility(
modifiers: Any,
properties: list,
resolve_date_range: Callable[[], tuple[Optional[datetime], Optional[datetime]]],
+ allow_channel_type_filter: bool = False,
+ max_days: int = MAX_PRECOMPUTE_DAYS,
) -> None:
"""Run the gate checks shared by all web-analytics lazy precompute paths.
@@ -953,6 +1004,12 @@ def check_common_eligibility(
# population than the live fallback. Those queries fall through to the live path,
# which applies them correctly.
for prop in properties:
+ if (
+ allow_channel_type_filter
+ and get_property_type(prop) == "session"
+ and get_property_key(prop) == "$channel_type"
+ ):
+ continue
if get_property_type(prop) not in ("event", "person"):
raise UnsupportedFilterType(get_property_type(prop))
@@ -968,8 +1025,8 @@ def check_common_eligibility(
raise MissingDateRange()
days = (date_to - date_from).days
- if days > MAX_PRECOMPUTE_DAYS:
- raise DateRangeOverMax(days)
+ if days > max_days:
+ raise DateRangeOverMax(days, max_days)
def log_eligibility_outcome(*, log_prefix: str, team_id: int, error: Optional[LazyPrecomputeIneligible]) -> None:
diff --git a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
index 30ea5d0edb22..234562935757 100644
--- a/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_overview_lazy_precompute.py
@@ -1,5 +1,5 @@
import time
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Optional
import structlog
@@ -8,28 +8,37 @@ from prometheus_client import Counter
from posthog.schema import HogQLQueryModifiers
from posthog.hogql import ast
+from posthog.hogql.context import HogQLContext
from posthog.hogql.modifiers import create_default_modifiers_for_team
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.preaggregation.web_overview_preaggregated_sql import (
DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE,
)
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
LazyComputationResult,
LazyComputationTable,
)
from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ CHANNEL_MAX_PRECOMPUTE_DAYS,
LAZY_TTL_SECONDS,
+ MAX_PRECOMPUTE_DAYS,
SESSION_FORWARD_PAD_MINUTES,
WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,
can_use_lazy_precompute as _can_use_lazy_precompute_shared,
ceil_utc_day,
+ channel_rules_shape_key,
+ channel_ttl_schedule,
check_common_eligible,
events_session_id_expr,
floor_utc_day,
+ has_channel_type_filter,
is_constant_true,
test_account_filter_expr,
user_filter_expr,
@@ -56,14 +65,23 @@ WEB_OVERVIEW_LAZY_FAILED = Counter(
def can_use_lazy_precompute(runner: "WebOverviewQueryRunner") -> bool:
- """Return True iff the lazy precompute path is eligible for this web
- overview query. Web overview has no checks beyond the shared gate."""
- return _can_use_lazy_precompute_shared(runner, log_prefix="web_overview")
+ return _can_use_lazy_precompute_shared(
+ runner,
+ log_prefix="web_overview",
+ allow_channel_type_filter=has_channel_type_filter(runner),
+ # Overview-only: its channel template carries the UUID-safe session-id handling.
+ allow_uuid_session_join=has_channel_type_filter(runner),
+ max_days=CHANNEL_MAX_PRECOMPUTE_DAYS if has_channel_type_filter(runner) else MAX_PRECOMPUTE_DAYS,
+ )
-# Re-exported so callers (and tests) can still reach the eligibility checker
-# through this module.
-_check_lazy_precompute_eligible = check_common_eligible
+def _check_lazy_precompute_eligible(runner: "WebOverviewQueryRunner") -> None:
+ check_common_eligible(
+ runner,
+ allow_channel_type_filter=has_channel_type_filter(runner),
+ allow_uuid_session_join=has_channel_type_filter(runner),
+ max_days=CHANNEL_MAX_PRECOMPUTE_DAYS if has_channel_type_filter(runner) else MAX_PRECOMPUTE_DAYS,
+ )
# HogQL template for the precompute INSERT. The lazy_computation framework
@@ -173,6 +191,28 @@ LEFT JOIN (
SESSION_ID_SET_INSERT_QUERY_TEMPLATE = with_insert_session_id_set_filter(NO_JOIN_INSERT_QUERY_TEMPLATE)
+CHANNEL_INSERT_QUERY_TEMPLATE = (
+ JOIN_INSERT_QUERY_TEMPLATE.replace(
+ "{user_filter},", "{user_filter}, {channel_rules_key} = {channel_rules_key}, {event_period_filter},"
+ )
+ .replace("toStartOfHour(min(session.$start_timestamp))", "min(session.$start_timestamp)")
+ .replace("uniqState(session_id)", "uniqState(assumeNotNull(session_id))")
+)
+
+
+def channel_insert_placeholders(runner: "WebOverviewQueryRunner") -> dict[str, ast.Expr]:
+ return {
+ "events_session_id": ast.Call(name="toString", args=[events_session_id_expr(runner)]),
+ "event_type_filter": runner.event_type_expr,
+ "user_filter": user_filter_expr(runner),
+ "test_account_filter": test_account_filter_expr(runner),
+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
+ "event_period_filter": ast.Constant(value=True),
+ # Modifiers are absent from the lazy job hash, but channel rules change its population.
+ "channel_rules_key": ast.Constant(value=channel_rules_shape_key(runner)),
+ }
+
+
def ensure_web_overview_precomputed(
runner: "WebOverviewQueryRunner",
time_range_start: datetime,
@@ -192,7 +232,11 @@ def ensure_web_overview_precomputed(
# property user filters, event/person test filters) take the two-scan shape
# with a session-id-set link; anything else keeps the join template.
modifiers: Optional[HogQLQueryModifiers] = None
- if is_unfiltered:
+ if has_channel_type_filter(runner):
+ insert_query = CHANNEL_INSERT_QUERY_TEMPLATE
+ placeholders = channel_insert_placeholders(runner)
+ modifiers = runner.modifiers
+ elif is_unfiltered:
insert_query = NO_JOIN_INSERT_QUERY_TEMPLATE
elif runner._session_id_set_common_eligibility():
insert_query = SESSION_ID_SET_INSERT_QUERY_TEMPLATE
@@ -208,11 +252,12 @@ def ensure_web_overview_precomputed(
insert_query=insert_query,
time_range_start=time_range_start,
time_range_end=time_range_end,
- ttl_seconds=LAZY_TTL_SECONDS,
+ ttl_seconds=channel_ttl_schedule(runner.team) if has_channel_type_filter(runner) else LAZY_TTL_SECONDS,
table=LazyComputationTable.WEB_OVERVIEW_PREAGGREGATED,
placeholders=placeholders,
query_type="web_overview_lazy_insert",
modifiers=modifiers,
+ shape_key_extra=channel_rules_shape_key(runner) if has_channel_type_filter(runner) else None,
)
@@ -306,6 +351,9 @@ def execute_lazy_precomputed_read(
team_id = runner.team.pk
overall_started = time.perf_counter()
try:
+ if has_channel_type_filter(runner):
+ return execute_channel_precomputed_read(runner)
+
date_from = runner.query_date_range.date_from()
date_to = runner.query_date_range.date_to()
assert date_from is not None and date_to is not None
@@ -446,3 +494,104 @@ def execute_lazy_precomputed_read(
total_duration_ms=int((time.perf_counter() - overall_started) * 1000),
)
return None
+
+
+_CHANNEL_STATE_COLUMNS = (
+ "uniq_users_state, uniq_sessions_state, sum_pageviews_state, avg_duration_state, avg_bounce_state"
+)
+
+
+@frozen
+class ChannelPrecomputeWindows:
+ """How a channel-filtered period splits into cached interior days and live boundaries."""
+
+ interior_start: datetime
+ interior_end: datetime
+ boundaries: list[tuple[datetime, datetime]]
+
+
+def channel_precompute_windows(start: datetime, end: datetime) -> ChannelPrecomputeWindows:
+ interior_start = ceil_utc_day(start)
+ interior_end = floor_utc_day(end - timedelta(minutes=SESSION_FORWARD_PAD_MINUTES))
+ exclusive_end = end + timedelta(microseconds=1)
+ if interior_start >= interior_end:
+ return ChannelPrecomputeWindows(
+ interior_start=interior_start, interior_end=interior_start, boundaries=[(start, exclusive_end)]
+ )
+ boundaries = [(interior_end, exclusive_end)]
+ if start < interior_start:
+ boundaries.insert(0, (start, interior_start))
+ return ChannelPrecomputeWindows(interior_start=interior_start, interior_end=interior_end, boundaries=boundaries)
+
+
+def execute_channel_period_read(runner: "WebOverviewQueryRunner", start: datetime, end: datetime) -> Optional[list]:
+ windows = channel_precompute_windows(start, end)
+ sources: list[str] = []
+ params: dict[str, object] = {}
+ if windows.interior_start < windows.interior_end:
+ result = ensure_web_overview_precomputed(runner, windows.interior_start, windows.interior_end)
+ if not result.ready or not result.job_ids:
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK.labels(family=_FAMILY, reason="current_not_ready").inc()
+ return None
+ if result.stale:
+ handle_stale_served(runner=runner, family=_FAMILY)
+ sources.append(
+ f"SELECT {_CHANNEL_STATE_COLUMNS} FROM {DISTRIBUTED_WEB_OVERVIEW_PREAGGREGATED_TABLE()} "
+ "WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s "
+ "AND time_window_start >= %(interior_start)s AND time_window_start < %(interior_end)s"
+ )
+ params.update(
+ team_id=runner.team.pk,
+ job_ids=tuple(str(job_id) for job_id in result.job_ids),
+ interior_start=windows.interior_start,
+ interior_end=windows.interior_end,
+ )
+
+ context = HogQLContext(
+ team=runner.team, team_id=runner.team.pk, modifiers=runner.modifiers, enable_select_queries=True
+ )
+ for boundary_start, boundary_end in windows.boundaries:
+ placeholders = channel_insert_placeholders(runner)
+ placeholders.update(
+ time_window_min=ast.Constant(value=boundary_start),
+ time_window_max=ast.Constant(value=boundary_end),
+ # The live comparison scans events from both periods before assigning sessions to a period.
+ event_period_filter=runner._periods_expression("timestamp"),
+ )
+ query = parse_select(CHANNEL_INSERT_QUERY_TEMPLATE, placeholders=placeholders)
+ sql, _ = prepare_and_print_ast(query, context=context, dialect="clickhouse")
+ sources.append(f"SELECT {_CHANNEL_STATE_COLUMNS} FROM ({sql})")
+
+ params.update(context.values or {})
+ # Merge states together so a visitor present in a cached day and a live boundary counts once.
+ sql = (
+ """
+SELECT uniqMerge(uniq_users_state), sumMerge(sum_pageviews_state), uniqMerge(uniq_sessions_state),
+ avgMerge(avg_duration_state), if(uniqMerge(uniq_sessions_state) = 0, NULL, avgMerge(avg_bounce_state))
+FROM (
+"""
+ + " UNION ALL ".join(sources)
+ + ")"
+ )
+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_overview_lazy_query")
+ rows = sync_execute(sql, params, settings=_READ_SETTINGS, team_id=runner.team.pk)
+ return list(rows[0]) if rows else [0, 0, 0, 0, 0]
+
+
+def execute_channel_precomputed_read(runner: "WebOverviewQueryRunner") -> Optional[list]:
+ periods = [runner.query_date_range]
+ if runner.query_compare_to_date_range is not None:
+ periods.append(runner.query_compare_to_date_range)
+ metrics: list[list] = []
+ for period in periods:
+ start, end = period.date_from(), period.date_to()
+ if start is None or end is None or start > end:
+ return None
+ row = execute_channel_period_read(runner, start.astimezone(UTC), end.astimezone(UTC))
+ if row is None:
+ return None
+ metrics.append(row)
+ if len(metrics) == 1:
+ metrics.append([None] * 5)
+ WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS.labels(family=_FAMILY).inc()
+ return [value for pair in zip(metrics[0], metrics[1]) for value in pair]
diff --git a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
index 7869a49ee7f2..b21d70b35a44 100644
--- a/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
+++ b/products/web_analytics/backend/hogql_queries/web_stats_lazy_precompute.py
@@ -25,7 +25,9 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
LazyComputationTable,
)
from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ CHANNEL_MAX_PRECOMPUTE_DAYS,
LAZY_TTL_SECONDS,
+ MAX_PRECOMPUTE_DAYS,
SESSION_FORWARD_PAD_MINUTES,
WEB_ANALYTICS_LAZY_PRECOMPUTE_FALLBACK,
WEB_ANALYTICS_LAZY_PRECOMPUTE_SUCCESS,
@@ -33,10 +35,14 @@ from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute
LazyPrecomputeRunner,
can_use_lazy_precompute as _can_use_lazy_precompute_shared,
ceil_utc_day,
+ channel_rules_shape_key,
+ channel_ttl_schedule,
events_session_id_expr,
floor_utc_day,
+ has_channel_type_filter,
test_account_filter_expr,
user_filter_expr,
+ with_channel_rules_key,
)
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
handle_stale_served,
@@ -206,7 +212,14 @@ def can_use_lazy_precompute(runner: "WebStatsTableQueryRunner") -> bool:
set_lazy_precompute_ineligible_reason("BreakdownRemapped")
logger.info(f"{_FAMILY}_lazy_precompute_rejected", team_id=runner.team.pk, reason="BreakdownRemapped")
return False
- return _can_use_lazy_precompute_shared(runner, log_prefix="web_stats", extra_check=_check_stats_eligible)
+ channel = has_channel_type_filter(runner)
+ return _can_use_lazy_precompute_shared(
+ runner,
+ log_prefix="web_stats",
+ extra_check=_check_stats_eligible,
+ allow_channel_type_filter=channel,
+ max_days=CHANNEL_MAX_PRECOMPUTE_DAYS if channel else MAX_PRECOMPUTE_DAYS,
+ )
# HogQL template for the precompute INSERT. The lazy_computation framework
@@ -287,6 +300,14 @@ def ensure_web_stats_precomputed(
"pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),
}
+ # A channel filter resolves through the request's effective modifiers inside
+ # the INSERT, so the full modifier serialization joins the job hash and the
+ # shape key (`channel_rules_shape_key`) — an override or rules edit mints its
+ # own buckets instead of contaminating the shared team-default namespace.
+ channel = has_channel_type_filter(runner)
+ if channel:
+ placeholders["user_filter"] = with_channel_rules_key(placeholders["user_filter"], runner)
+
return web_ensure_precomputed(
runner=runner,
family=_FAMILY,
@@ -294,11 +315,13 @@ def ensure_web_stats_precomputed(
insert_query=INSERT_QUERY_TEMPLATE,
time_range_start=time_range_start,
time_range_end=time_range_end,
- ttl_seconds=LAZY_TTL_SECONDS,
+ ttl_seconds=channel_ttl_schedule(runner.team) if channel else LAZY_TTL_SECONDS,
table=LazyComputationTable.WEB_STATS_PREAGGREGATED,
placeholders=placeholders,
query_type=f"web_stats_{runner.query.breakdownBy.value}_lazy_insert",
spill_to_disk=True, # high-cardinality breakdown GROUP BY; can build a large hash table
+ modifiers=runner.modifiers if channel else None,
+ shape_key_extra=channel_rules_shape_key(runner) if channel else None,
)
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 17f560a832b1..8844cee9c772 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
@@ -36,14 +36,20 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu
LazyComputationTable,
)
from products.web_analytics.backend.hogql_queries.web_analytics_lazy_precompute import (
+ CHANNEL_MAX_PRECOMPUTE_DAYS,
build_insert_select_ast,
+ channel_rules_shape_key,
+ has_channel_type_filter,
is_constant_true,
+ with_channel_rules_key,
)
from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (
LAZY_TTL_SECONDS,
+ MAX_PRECOMPUTE_DAYS,
SESSION_FORWARD_PAD_MINUTES,
LazyPrecomputeIneligible,
ceil_utc_day,
+ channel_ttl_schedule,
check_common_eligibility,
floor_utc_day,
handle_stale_served,
@@ -170,6 +176,7 @@ def _check_eligible(runner: "WebStatsTableQueryRunner") -> None:
if order_field == WebAnalyticsOrderByFields.BOUNCE_RATE and not query.includeBounceRate:
raise UnsupportedOrderBy(order_field)
+ channel = has_channel_type_filter(runner)
check_common_eligibility(
team=runner.team,
use_web_analytics_precompute=query.useWebAnalyticsPrecompute,
@@ -178,6 +185,8 @@ def _check_eligible(runner: "WebStatsTableQueryRunner") -> None:
modifiers=query.modifiers,
properties=query.properties or [],
resolve_date_range=lambda: (runner.query_date_range.date_from(), runner.query_date_range.date_to()),
+ allow_channel_type_filter=channel,
+ max_days=CHANNEL_MAX_PRECOMPUTE_DAYS if channel else MAX_PRECOMPUTE_DAYS,
)
@@ -641,6 +650,15 @@ def ensure_web_stats_paths_precomputed(
wait_timeout = wait_budget_seconds
else:
wait_timeout = PATHS_USER_ENSURE_WAIT_SECONDS
+ # A channel filter resolves through the team's custom channel rules inside the
+ # INSERT, so the rules join the job hash and the shape key (see
+ # `with_channel_rules_key`); old immutable days get the longer channel hold.
+ channel = has_channel_type_filter(runner)
+ if channel:
+ if placeholders:
+ placeholders["user_filter"] = with_channel_rules_key(placeholders["user_filter"], runner)
+ modifiers = runner.modifiers
+
return web_ensure_precomputed(
runner=runner,
family=_FAMILY,
@@ -648,10 +666,11 @@ def ensure_web_stats_paths_precomputed(
insert_query=insert_query,
time_range_start=time_range_start,
time_range_end=time_range_end,
- ttl_seconds=LAZY_TTL_SECONDS,
+ ttl_seconds=channel_ttl_schedule(runner.team) if channel else LAZY_TTL_SECONDS,
table=LazyComputationTable.WEB_STATS_PATHS_PREAGGREGATED,
placeholders=placeholders,
query_type="web_stats_paths_lazy_insert",
+ shape_key_extra=channel_rules_shape_key(runner) if channel else None,
spill_to_disk=True, # high-cardinality path breakdown GROUP BY; can build a large hash table
wait_timeout_seconds=wait_timeout,
modifiers=modifiers,
diff --git a/products/web_analytics/docs/web-overview-channel-precompute.md b/products/web_analytics/docs/web-overview-channel-precompute.md
new file mode 100644
index 000000000000..7bb3335d5d32
--- /dev/null
+++ b/products/web_analytics/docs/web-overview-channel-precompute.md
@@ -0,0 +1,39 @@
+# Web overview channel precompute
+
+Web overview can reuse lazy precomputation for session `$channel_type` filters,
+including custom channel rules. Event and person filters can accompany the channel
+filter. Other session properties and cohorts retain their existing fallback.
+The channel path accepts up to 366 whole days; other web precompute paths retain
+their existing range limits. Feature enrollment, per-query opt-out, sampling,
+conversion goals, timezone eligibility, and property access controls still apply.
+
+## Exact range boundaries
+
+Daily jobs store full session aggregates. A session starting near midnight can
+include pageviews after the requested end. Reading its cached total would count
+those pageviews incorrectly.
+
+The channel path reads complete UTC days from the cache, excluding the leading
+partial day and the trailing session forward-pad interval (24 hours, rounded back
+to a UTC day). It computes those boundary sessions from events with the original
+query's exact timestamp predicate. Cached and boundary aggregate states merge in
+ClickHouse, preserving distinct visitor counts across both sources. Short ranges
+without complete interior days use only the boundary query.
+
+Comparison periods are read separately, while their boundary event filters retain
+the live query's union of both periods. Session IDs are converted to non-null
+strings in the aggregate state, matching the preaggregation table in both string
+and UUID join modes. Custom channel rules participate in the job hash, so a rule
+change cannot reuse results computed with a different classification.
+
+## Cache misses and operational limits
+
+User-facing requests do not backfill missing jobs inline. The existing background
+warming and stale revalidation mechanisms build interior jobs. Missing or failed
+jobs still fall back to the live query, so enabling this path alone does not make
+a cold annual query fast. Existing shape limits, insert resource limits, and OOM
+window capping continue to apply.
+
+This path covers overview metrics only. Other dashboard tables and tiles have
+independent precompute eligibility and performance characteristics. Correctness
+with synthetic data does not establish production latency or memory usage.