:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(web-analytics): return frozen dataclasses instead of tuples (#76140)
Arno Hillen471e0ade4bdb
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex ff1cdade6014..5f6276299bf5 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -90,7 +90,7 @@ class ClickHouseUser(StrEnum):DICT_READER = "dict_reader"-@dataclass(frozen=True)+@dataclass(frozen=True, kw_only=True, slots=True)class ClickHouseCredentials:user: strpassword: str = field(repr=False)diff --git a/posthog/hogql/database/schema/exchange_rate.py b/posthog/hogql/database/schema/exchange_rate.pyindex 12d786971063..27f4e8890b0a 100644--- a/posthog/hogql/database/schema/exchange_rate.py+++ b/posthog/hogql/database/schema/exchange_rate.py@@ -1,3 +1,4 @@+from dataclasses import dataclassfrom typing import TYPE_CHECKINGfrom posthog.hogql import ast@@ -71,15 +72,20 @@ def currency_expression_for_events(team: "Team", event_config: "RevenueAnalyticsreturn ast.Constant(value=team.base_currency)-# Tuple of (comparison_expr, value_expr) that can be used to:-# - Check whether the event is the one we're looking for-# - Convert the revenue to the base currency if needed+@dataclass(frozen=True, kw_only=True, slots=True)+class RevenueEventExprs:+ # Checks whether the event is the one we're looking for+ comparison_expr: ast.Expr+ # Converts the revenue to the base currency if needed+ value_expr: ast.Expr++def revenue_comparison_and_value_exprs_for_events(team: "Team",event_config: "RevenueAnalyticsEventItem",do_currency_conversion: bool = True,amount_expr: ast.Expr | None = None,-) -> tuple[ast.Expr, ast.Expr]:+) -> RevenueEventExprs:if amount_expr is None:amount_expr = ast.Field(chain=["events", "properties", event_config.revenueProperty])@@ -122,4 +128,4 @@ def revenue_comparison_and_value_exprs_for_events(],)- return (comparison_expr, value_expr)+ return RevenueEventExprs(comparison_expr=comparison_expr, value_expr=value_expr)diff --git a/products/marketing_analytics/backend/services/conversion_goals_inspector.py b/products/marketing_analytics/backend/services/conversion_goals_inspector.pyindex cddf7e9c30bf..93c8f2f0603e 100644--- a/products/marketing_analytics/backend/services/conversion_goals_inspector.py+++ b/products/marketing_analytics/backend/services/conversion_goals_inspector.py@@ -335,16 +335,13 @@ async def _summarize_goal(if kind_raw == "EventsNode":target_label = goal.get("event") or "(all events)"- total, integrated, without_utm, unmatched_with_utm = await _count_event_goal(team, goal, alias_map, user=user)+ counts = await _count_event_goal(team, goal, alias_map, user=user)return _summary_with_split(goal_id,name,kind,target_label,- total,- integrated,- without_utm,- unmatched_with_utm,+ counts,is_approximate=base_approximate,approximation_reason=base_reason,)@@ -367,18 +364,13 @@ async def _summarize_goal(misconfig_reason=action_error or f"Action {target_id} no longer exists",)target_label = f"Action: {action.name}"- total, integrated, without_utm, unmatched_with_utm = await _count_action_goal(- team, action, alias_map, user=user- )+ counts = await _count_action_goal(team, action, alias_map, user=user)return _summary_with_split(goal_id,name,kind,target_label,- total,- integrated,- without_utm,- unmatched_with_utm,+ counts,is_approximate=base_approximate,approximation_reason=base_reason,)@@ -420,30 +412,35 @@ async def _summarize_goal()+@dataclass(frozen=True, kw_only=True, slots=True)+class UtmSplitCounts:+ total: int+ integrated: int+ without_utm: int+ unmatched_with_utm: int++def _summary_with_split(goal_id: str,name: str,kind: GoalKind,target_label: str,- total: int,- integrated: int,- without_utm: int,- unmatched_with_utm: int,+ counts: UtmSplitCounts,*,is_approximate: bool = False,approximation_reason: str | None = None,) -> ConversionGoalSummary:- integrated_pct = round((integrated / total) * 100, 2) if total > 0 else 0.0+ integrated_pct = round((counts.integrated / counts.total) * 100, 2) if counts.total > 0 else 0.0return ConversionGoalSummary(id=goal_id,name=name,kind=kind,target_label=target_label,- last_30d_count=total,- integrated_count=integrated,- events_without_utm_source=without_utm,- events_with_unmatched_utm_source=unmatched_with_utm,- non_integrated_count=without_utm + unmatched_with_utm,+ last_30d_count=counts.total,+ integrated_count=counts.integrated,+ events_without_utm_source=counts.without_utm,+ events_with_unmatched_utm_source=counts.unmatched_with_utm,+ non_integrated_count=counts.without_utm + counts.unmatched_with_utm,integrated_pct=integrated_pct,is_misconfigured=False,misconfig_reason=None,@@ -467,7 +464,7 @@ def _resolve_action(team: Team, goal_id: str) -> tuple[Action | None, str | None@database_sync_to_asyncdef _count_event_goal(team: Team, goal: dict[str, Any], alias_map: dict[str, NativeIntegration], user: User | None = None-) -> tuple[int, int, int, int]:+) -> UtmSplitCounts:"""For EventsNode: count last 30d events matching the goal, split by utm_source match.`goal["event"]` may be None, meaning "match any event" (rare but valid)."""@@ -488,15 +485,13 @@ def _count_event_goal(@database_sync_to_asyncdef _count_action_goal(team: Team, action: Action, alias_map: dict[str, NativeIntegration], user: User | None = None-) -> tuple[int, int, int, int]:+) -> UtmSplitCounts:"""For ActionsNode: count last 30d events matching the action's full definition- (`action_to_expr`, same as the dashboard), split by utm_source.-- Returns (total, integrated, without_utm, unmatched_with_utm)."""+ (`action_to_expr`, same as the dashboard), split by utm_source."""# No steps → `action_to_expr` returns `true`; short-circuit so we don't count# the entire events table.if not action.steps:- return 0, 0, 0, 0+ return UtmSplitCounts(total=0, integrated=0, without_utm=0, unmatched_with_utm=0)since = timezone.now() - timedelta(days=DEFAULT_LOOKBACK_DAYS)return _execute_count_with_split(team, action_to_expr(action), {"since": ast.Constant(value=since)}, alias_map, user=user@@ -509,8 +504,8 @@ def _execute_count_with_split(placeholders: dict[str, ast.Expr],alias_map: dict[str, NativeIntegration],user: User | None = None,-) -> tuple[int, int, int, int]:- """Returns (total, integrated, without_utm, unmatched_with_utm).+) -> UtmSplitCounts:+ """Count matching events, split by utm_source integration status.The split is computed in ClickHouse via `countIf`, not `GROUP BY utm_source`plus a Python sum — a `GROUP BY` inherits the default query row limit and@@ -545,9 +540,14 @@ def _execute_count_with_split(result = execute_hogql_query(hogql, team, placeholders=query_placeholders, user=user)rows = result.results or []if not rows:- return 0, 0, 0, 0+ return UtmSplitCounts(total=0, integrated=0, without_utm=0, unmatched_with_utm=0)total, integrated, without_utm, unmatched_with_utm = rows[0]- return int(total or 0), int(integrated or 0), int(without_utm or 0), int(unmatched_with_utm or 0)+ return UtmSplitCounts(+ total=int(total or 0),+ integrated=int(integrated or 0),+ without_utm=int(without_utm or 0),+ unmatched_with_utm=int(unmatched_with_utm or 0),+ )@database_sync_to_asyncdiff --git a/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.pyindex 48c3aa0b849a..eda7e69f6896 100644--- a/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py+++ b/products/marketing_analytics/backend/services/test_conversion_goals_inspector.py@@ -10,6 +10,7 @@ from posthog.schema import DateRangefrom products.actions.backend.models.action import Actionfrom products.marketing_analytics.backend.services.conversion_goals_inspector import (+ UtmSplitCounts,explain_conversion_goal,list_conversion_goals,)@@ -79,8 +80,12 @@ class _InspectorMixin(APIBaseTest):self.mocks["config"].return_value = ([], 90, "last_touch")self.mocks["alias_map"].return_value = dict(canonical_source_aliases())- self.mocks["event_count"].return_value = (0, 0, 0, 0)- self.mocks["action_count"].return_value = (0, 0, 0, 0)+ self.mocks["event_count"].return_value = UtmSplitCounts(+ total=0, integrated=0, without_utm=0, unmatched_with_utm=0+ )+ self.mocks["action_count"].return_value = UtmSplitCounts(+ total=0, integrated=0, without_utm=0, unmatched_with_utm=0+ )self.mocks["dw_count"].return_value = (0, None)self.mocks["resolve_action"].return_value = (None, None)@@ -97,7 +102,9 @@ class TestListConversionGoals(_InspectorMixin):async def test_events_node_goal_summarized_with_split(self):self.mocks["config"].return_value = ([_events_goal("purchase")], 60, "first_touch")# 200 total: 80 integrated, 70 events without utm_source, 50 with unmatched utm_source- self.mocks["event_count"].return_value = (200, 80, 70, 50)+ self.mocks["event_count"].return_value = UtmSplitCounts(+ total=200, integrated=80, without_utm=70, unmatched_with_utm=50+ )response = await list_conversion_goals(self.team)@@ -119,7 +126,9 @@ class TestListConversionGoals(_InspectorMixin):@pytest.mark.asyncioasync def test_events_node_with_null_event_uses_all_events_label(self):self.mocks["config"].return_value = ([_events_goal("any", event=None)], 90, "last_touch")- self.mocks["event_count"].return_value = (10, 0, 10, 0)+ self.mocks["event_count"].return_value = UtmSplitCounts(+ total=10, integrated=0, without_utm=10, unmatched_with_utm=0+ )response = await list_conversion_goals(self.team)assert response.goals[0].target_label == "(all events)"@@ -147,7 +156,9 @@ class TestListConversionGoals(_InspectorMixin):action_mock.name = "Demo booked"self.mocks["config"].return_value = ([_actions_goal("cg_demos", action_id=42)], 90, "last_touch")self.mocks["resolve_action"].return_value = (action_mock, None)- self.mocks["action_count"].return_value = (10, 10, 0, 0)+ self.mocks["action_count"].return_value = UtmSplitCounts(+ total=10, integrated=10, without_utm=0, unmatched_with_utm=0+ )response = await list_conversion_goals(self.team)@@ -164,7 +175,9 @@ class TestListConversionGoals(_InspectorMixin):self.mocks["config"].return_value = ([_actions_goal("42")], 90, "last_touch")self.mocks["resolve_action"].return_value = (action_mock, None)# 50 total: 30 integrated, 12 without utm_source, 8 with unmatched utm_source.- self.mocks["action_count"].return_value = (50, 30, 12, 8)+ self.mocks["action_count"].return_value = UtmSplitCounts(+ total=50, integrated=30, without_utm=12, unmatched_with_utm=8+ )response = await list_conversion_goals(self.team)goal = response.goals[0]diff --git a/products/revenue_analytics/backend/views/sources/events/charge.py b/products/revenue_analytics/backend/views/sources/events/charge.pyindex 989b15123776..a0ab6849796d 100644--- a/products/revenue_analytics/backend/views/sources/events/charge.py+++ b/products/revenue_analytics/backend/views/sources/events/charge.py@@ -24,17 +24,15 @@ def build(handle: SourceHandle) -> BuiltQuery:prefix = view_prefix_for_event(event.eventName)- comparison_expr, value_expr = revenue_comparison_and_value_exprs_for_events(- team, event, do_currency_conversion=False- )- _, currency_aware_amount_expr = revenue_comparison_and_value_exprs_for_events(+ revenue_exprs = revenue_comparison_and_value_exprs_for_events(team, event, do_currency_conversion=False)+ currency_aware_amount_expr = revenue_comparison_and_value_exprs_for_events(team,event,amount_expr=ast.Field(chain=["currency_aware_amount"]),- )+ ).value_exprfilter_exprs = [- comparison_expr,+ revenue_exprs.comparison_expr,generic_team_expr,ast.CompareOperation(op=ast.CompareOperationOp.NotEq,@@ -53,7 +51,7 @@ def build(handle: SourceHandle) -> BuiltQuery:ast.Alias(alias="session_id", expr=ast.Call(name="toString", args=[ast.Field(chain=["$session_id"])])),ast.Alias(alias="event_name", expr=ast.Field(chain=["event"])),ast.Alias(alias="original_currency", expr=currency_expression_for_events(team, event)),- ast.Alias(alias="original_amount", expr=value_expr),+ ast.Alias(alias="original_amount", expr=revenue_exprs.value_expr),# Being zero-decimal implies we will NOT divide the original amount by 100# We should only do that if we've tagged the event with `currencyAwareDecimal`# Otherwise, we'll just assume it's a non-zero-decimal currencydiff --git a/products/revenue_analytics/backend/views/sources/events/revenue_item.py b/products/revenue_analytics/backend/views/sources/events/revenue_item.pyindex 8e4d05ab6d5c..021645ff9f21 100644--- a/products/revenue_analytics/backend/views/sources/events/revenue_item.py+++ b/products/revenue_analytics/backend/views/sources/events/revenue_item.py@@ -22,19 +22,17 @@ def build(handle: SourceHandle) -> BuiltQuery:generic_team_expr = events_expr_for_team(team)- comparison_expr, value_expr = revenue_comparison_and_value_exprs_for_events(- team, event, do_currency_conversion=False- )- _, currency_aware_amount_expr = revenue_comparison_and_value_exprs_for_events(+ revenue_exprs = revenue_comparison_and_value_exprs_for_events(team, event, do_currency_conversion=False)+ currency_aware_amount_expr = revenue_comparison_and_value_exprs_for_events(team,event,amount_expr=ast.Field(chain=["currency_aware_amount"]),- )+ ).value_exprprefix = view_prefix_for_event(event.eventName)filter_exprs = [- comparison_expr,+ revenue_exprs.comparison_expr,generic_team_expr,ast.CompareOperation(op=ast.CompareOperationOp.NotEq,@@ -85,7 +83,7 @@ def build(handle: SourceHandle) -> BuiltQuery:),ast.Alias(alias="coupon_id", expr=ast.Field(chain=["coupon"])), # Same as above, just copyast.Alias(alias="original_currency", expr=currency_expression_for_events(team, event)),- ast.Alias(alias="original_amount", expr=value_expr),+ ast.Alias(alias="original_amount", expr=revenue_exprs.value_expr),# Being zero-decimal implies we will NOT divide the original amount by 100# We should only do that if we've tagged the event with `currencyAwareDecimal`# Otherwise, we'll just assume it's a non-zero-decimal currencydiff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 53cea1ce295f..b7615bbaea83 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -1,3 +1,4 @@+from dataclasses import dataclassfrom datetime import date, datetime, timedeltafrom json import JSONDecodeError, loadsfrom typing import Any, List, Literal, cast, get_args # noqa: UP035@@ -193,16 +194,22 @@ def anchor_url_pattern(value: str) -> str:return validated_value-def resolve_url_filter(url_exact: str | None, url_pattern: str | None) -> tuple[str | None, str | None]:+@dataclass(frozen=True, kw_only=True, slots=True)+class ResolvedUrlFilter:+ url_exact: str | None+ url_pattern: str | None+++def resolve_url_filter(url_exact: str | None, url_pattern: str | None) -> ResolvedUrlFilter:"""Resolve which of url_exact/url_pattern the query actually filters on when both are supplied,so every caller (the request serializer and the permission check) authorizes and queries thesame value: equal values keep url_exact, differing values keep url_pattern (matchingHeatmapsRequestSerializer.validate())."""if isinstance(url_exact, str) and isinstance(url_pattern, str):if url_exact == url_pattern:- return url_exact, None- return None, url_pattern- return url_exact, url_pattern+ return ResolvedUrlFilter(url_exact=url_exact, url_pattern=None)+ return ResolvedUrlFilter(url_exact=None, url_pattern=url_pattern)+ return ResolvedUrlFilter(url_exact=url_exact, url_pattern=url_pattern)class HeatmapsRequestSerializer(serializers.Serializer):@@ -334,10 +341,10 @@ class HeatmapsRequestSerializer(serializers.Serializer):def validate(self, values) -> dict:url_exact = values.get("url_exact", None)url_pattern = values.get("url_pattern", None)- resolved_exact, resolved_pattern = resolve_url_filter(url_exact, url_pattern)- if resolved_exact is None and url_exact is not None:+ resolved = resolve_url_filter(url_exact, url_pattern)+ if resolved.url_exact is None and url_exact is not None:values.pop("url_exact")- if resolved_pattern is None and url_pattern is not None:+ if resolved.url_pattern is None and url_pattern is not None:values.pop("url_pattern")if values.get("filter_test_accounts") and not isinstance(values.get("filter_test_accounts"), bool):@@ -488,8 +495,8 @@ class HeatmapAggregateQueryScopingPermission(AccessControlPermission):# authorized as an exact match while the anchored pattern actually executes.raw_url_pattern = request.query_params.get("url_pattern")anchored_url_pattern = anchor_url_pattern(raw_url_pattern) if raw_url_pattern else raw_url_pattern- url_exact, _ = resolve_url_filter(request.query_params.get("url_exact"), anchored_url_pattern)- if not url_exact:+ resolved = resolve_url_filter(request.query_params.get("url_exact"), anchored_url_pattern)+ if not resolved.url_exact:# A url_pattern query matches every row whose current_url satisfies the pattern, not# just the granted SavedHeatmap's URL — an object grant can't bound that, so patterns# (and requests with no URL filter at all) require resource-level "heatmap" access.@@ -503,7 +510,7 @@ class HeatmapAggregateQueryScopingPermission(AccessControlPermission):candidate_url = candidate.data_url or candidate.url# Match the same way the aggregate query does: url_exact ignores a trailing slash# (`trimRight(current_url, '/')`).- if candidate_url.rstrip("/") == url_exact.rstrip("/") and uac.check_access_level_for_object(+ if candidate_url.rstrip("/") == resolved.url_exact.rstrip("/") and uac.check_access_level_for_object(candidate, required_level=required_level):return Truediff --git a/products/web_analytics/backend/hogql_queries/notable_changes.py b/products/web_analytics/backend/hogql_queries/notable_changes.pyindex f4bdf87e5f7a..cc160374efc4 100644--- a/products/web_analytics/backend/hogql_queries/notable_changes.py+++ b/products/web_analytics/backend/hogql_queries/notable_changes.py@@ -18,6 +18,7 @@ from posthog.hogql.query import execute_hogql_queryfrom products.web_analytics.backend.hogql_queries.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERSfrom products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (+ PeriodFilters,WebAnalyticsPreAggregatedQueryBuilder,)from products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner@@ -247,12 +248,12 @@ class _NotableChangesPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuisuper().__init__(runner=runner, supported_props_filters=STATS_TABLE_SUPPORTED_FILTERS)def get_query(self) -> Union[ast.SelectQuery, ast.SelectSetQuery]:- previous_period_filter, current_period_filter = self.get_date_ranges()+ period_filters = self.get_date_ranges()table_name = self.stats_tablesubqueries: list[ast.SelectQuery] = []for dim in DIMENSIONS:- subquery = self._build_dimension_subquery(dim, table_name, current_period_filter, previous_period_filter)+ subquery = self._build_dimension_subquery(dim, table_name, period_filters=period_filters)subqueries.append(subquery)return ast.SelectSetQuery.create_from_queries(subqueries, "UNION ALL")@@ -261,8 +262,8 @@ class _NotableChangesPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuiself,dim: DimensionConfig,table_name: str,- current_period_filter: ast.Expr,- previous_period_filter: ast.Expr,+ *,+ period_filters: PeriodFilters,) -> ast.SelectQuery:label = dim["label"]@@ -281,11 +282,11 @@ class _NotableChangesPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuicurrent_visitors = ast.Call(name="uniqMergeIf",- args=[ast.Field(chain=["persons_uniq_state"]), current_period_filter],+ args=[ast.Field(chain=["persons_uniq_state"]), period_filters.current_period],)previous_visitors = ast.Call(name="uniqMergeIf",- args=[ast.Field(chain=["persons_uniq_state"]), previous_period_filter],+ args=[ast.Field(chain=["persons_uniq_state"]), period_filters.previous_period],)filters = self._get_filters(table_name=table_name)diff --git a/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.pyindex 84e4714dc567..303eba3d644d 100644--- a/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py+++ b/products/web_analytics/backend/hogql_queries/pre_aggregated/query_builder.py@@ -1,3 +1,4 @@+from dataclasses import dataclassfrom datetime import timedeltafrom typing import Optional@@ -15,6 +16,12 @@ get_stats_table = lambda use_v2: "web_pre_aggregated_stats"get_bounces_table = lambda use_v2: "web_pre_aggregated_bounces"+@dataclass(frozen=True, kw_only=True, slots=True)+class PeriodFilters:+ previous_period: ast.Expr+ current_period: ast.Expr++class WebAnalyticsPreAggregatedQueryBuilder:def __init__(self, runner, supported_props_filters) -> None:self.runner = runner@@ -145,7 +152,7 @@ class WebAnalyticsPreAggregatedQueryBuilder:return ast.And(exprs=filter_exprs)- def get_date_ranges(self, table_name: Optional[str] = None) -> tuple[ast.Expr, ast.Expr]:+ def get_date_ranges(self, table_name: Optional[str] = None) -> PeriodFilters:current_date_from = self.runner.query_date_range.date_from()current_date_to = self.runner.query_date_range.date_to()@@ -191,4 +198,4 @@ class WebAnalyticsPreAggregatedQueryBuilder:])- return (previous_period_filter, current_period_filter)+ return PeriodFilters(previous_period=previous_period_filter, current_period=current_period_filter)diff --git a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.pyindex 4d295d0ef31b..1f9d6a0e40b8 100644--- a/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py+++ b/products/web_analytics/backend/hogql_queries/stats_table_pre_aggregated.py@@ -13,6 +13,7 @@ from posthog.hogql.property import property_to_exprfrom products.web_analytics.backend.hogql_queries.pre_aggregated.properties import STATS_TABLE_SUPPORTED_FILTERSfrom products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (+ PeriodFilters,WebAnalyticsPreAggregatedQueryBuilder,)@@ -98,7 +99,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)def _bounce_rate_query(self) -> ast.SelectQuery:# Like in the original stats_table, we will need this method to build the "Paths" tile so it is a special breakdown- previous_period_filter, current_period_filter = self.get_date_ranges()+ period_filters = self.get_date_ranges()query = cast(ast.SelectQuery,@@ -125,14 +126,16 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)],),"visitors_tuple": self._period_comparison_tuple(- "persons_uniq_state", "uniqMergeIf", current_period_filter, previous_period_filter+ "persons_uniq_state",+ "uniqMergeIf",+ period_filters=period_filters,),"views_tuple": self._period_comparison_tuple(- "pageviews_count_state", "sumMergeIf", current_period_filter, previous_period_filter- ),- "bounce_rate_tuple": self._bounce_rate_calculation_tuple(- current_period_filter, previous_period_filter+ "pageviews_count_state",+ "sumMergeIf",+ period_filters=period_filters,),+ "bounce_rate_tuple": self._bounce_rate_calculation_tuple(period_filters=period_filters),"filters": self._get_bounce_rate_filters(),},),@@ -147,7 +150,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder))def _path_query(self) -> ast.SelectQuery:- previous_period_filter, current_period_filter = self.get_date_ranges(table_name=self.stats_table)+ period_filters = self.get_date_ranges(table_name=self.stats_table)query = cast(ast.SelectQuery,@@ -179,15 +182,13 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)"visitors_tuple": self._period_comparison_tuple("persons_uniq_state","uniqMergeIf",- current_period_filter,- previous_period_filter,+ period_filters=period_filters,table_prefix=self.stats_table,),"views_tuple": self._period_comparison_tuple("pageviews_count_state","sumMergeIf",- current_period_filter,- previous_period_filter,+ period_filters=period_filters,table_prefix=self.stats_table,),"bounce_subquery": self._bounce_rate_query(),@@ -211,11 +212,11 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)return querydef _default_breakdown_query(self) -> ast.SelectQuery:- previous_period_filter, current_period_filter = self.get_date_ranges()+ period_filters = self.get_date_ranges()if self.runner.query.conversionGoal:# For conversion goals, we need to join events table with pre-aggregated table- return self._default_breakdown_query_with_conversions(current_period_filter, previous_period_filter)+ return self._default_breakdown_query_with_conversions(period_filters=period_filters)query = cast(ast.SelectQuery,@@ -233,10 +234,14 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)"stats_table": ast.Field(chain=[self.stats_table]),"breakdown_field": self._get_breakdown_field(),"visitors_tuple": self._period_comparison_tuple(- "persons_uniq_state", "uniqMergeIf", current_period_filter, previous_period_filter+ "persons_uniq_state",+ "uniqMergeIf",+ period_filters=period_filters,),"views_tuple": self._period_comparison_tuple(- "pageviews_count_state", "sumMergeIf", current_period_filter, previous_period_filter+ "pageviews_count_state",+ "sumMergeIf",+ period_filters=period_filters,),"filters": self._get_filters(table_name=self.stats_table),},@@ -245,15 +250,13 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)return query- def _default_breakdown_query_with_conversions(- self, current_period_filter: ast.Expr, previous_period_filter: ast.Expr- ) -> ast.SelectQuery:+ def _default_breakdown_query_with_conversions(self, *, period_filters: PeriodFilters) -> ast.SelectQuery:"""Hybrid approach: pre-aggregated tables for visitors, raw events for conversions.Much simpler than querying everything from raw events."""# Build stats subquery from pre-aggregated table for visitor counts- stats_subquery = self._build_stats_subquery(current_period_filter, previous_period_filter)+ stats_subquery = self._build_stats_subquery(period_filters.current_period, period_filters.previous_period)# Build conversion subquery from raw eventsconversion_subquery = self._build_conversion_subquery()@@ -437,7 +440,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)Bounce-rate-style approach: Query stats table and LEFT JOIN conversion subquery.Similar pattern to _path_query() which joins stats with bounce rate data."""- previous_period_filter, current_period_filter = self.get_date_ranges(table_name=self.stats_table)+ period_filters = self.get_date_ranges(table_name=self.stats_table)# Build conversion subquery from raw events (reuse existing method)conversion_subquery = self._build_conversion_subquery()@@ -473,8 +476,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)"visitors_tuple": self._period_comparison_tuple("persons_uniq_state","uniqMergeIf",- current_period_filter,- previous_period_filter,+ period_filters=period_filters,table_prefix=self.stats_table,),"conversion_subquery": conversion_subquery,@@ -670,8 +672,8 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)self,state_field: str,function_name: str,- current_period_filter: ast.Expr,- previous_period_filter: ast.Expr,+ *,+ period_filters: PeriodFilters,table_prefix: str | None = None,) -> ast.Tuple:field_chain: list[str | int] = [table_prefix, state_field] if table_prefix else [state_field]@@ -683,7 +685,7 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)name=function_name,args=[ast.Field(chain=field_chain),- previous_period_filter,+ period_filters.previous_period,],))@@ -694,16 +696,14 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)name=function_name,args=[ast.Field(chain=field_chain),- current_period_filter,+ period_filters.current_period,],),previous_expr,])- def _bounce_rate_calculation_tuple(- self, current_period_filter: ast.Expr, previous_period_filter: ast.Expr- ) -> ast.Tuple:+ def _bounce_rate_calculation_tuple(self, *, period_filters: PeriodFilters) -> ast.Tuple:def safe_bounce_rate(period_filter: ast.Expr) -> ast.Call:return ast.Call(name="divide",@@ -735,12 +735,12 @@ class StatsTablePreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder)previous_expr = (ast.Constant(value=None)if not self.runner.query_compare_to_date_range- else safe_bounce_rate(previous_period_filter)+ else safe_bounce_rate(period_filters.previous_period))return ast.Tuple(exprs=[- safe_bounce_rate(current_period_filter),+ safe_bounce_rate(period_filters.current_period),previous_expr,])diff --git a/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py b/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.pyindex f9480e2875cd..a8faf54d2267 100644--- a/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py+++ b/products/web_analytics/backend/hogql_queries/web_overview_pre_aggregated.py@@ -6,6 +6,7 @@ from posthog.hogql.property import property_to_exprfrom products.web_analytics.backend.hogql_queries.pre_aggregated.properties import WEB_OVERVIEW_SUPPORTED_PROPERTIESfrom products.web_analytics.backend.hogql_queries.pre_aggregated.query_builder import (+ PeriodFilters,WebAnalyticsPreAggregatedQueryBuilder,)@@ -18,10 +19,10 @@ class WebOverviewPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuildersuper().__init__(runner, supported_props_filters=WEB_OVERVIEW_SUPPORTED_PROPERTIES)def get_query(self) -> ast.SelectQuery:- previous_period_filter, current_period_filter = self.get_date_ranges()+ period_filters = self.get_date_ranges()if self.runner.query.conversionGoal:- return self._get_conversion_query(current_period_filter, previous_period_filter)+ return self._get_conversion_query(period_filters=period_filters)table_name = self.bounces_table@@ -49,23 +50,23 @@ class WebOverviewPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder""",placeholders={"table_name": ast.Field(chain=[table_name]),- "unique_persons_current": self._uniq_merge_if("persons_uniq_state", current_period_filter),- "unique_persons_previous": self._uniq_merge_if("persons_uniq_state", previous_period_filter),- "pageviews_current": self._sum_merge_if("pageviews_count_state", current_period_filter),- "pageviews_previous": self._sum_merge_if("pageviews_count_state", previous_period_filter),- "unique_sessions_current": self._uniq_merge_if("sessions_uniq_state", current_period_filter),- "unique_sessions_previous": self._uniq_merge_if("sessions_uniq_state", previous_period_filter),+ "unique_persons_current": self._uniq_merge_if("persons_uniq_state", period_filters.current_period),+ "unique_persons_previous": self._uniq_merge_if("persons_uniq_state", period_filters.previous_period),+ "pageviews_current": self._sum_merge_if("pageviews_count_state", period_filters.current_period),+ "pageviews_previous": self._sum_merge_if("pageviews_count_state", period_filters.previous_period),+ "unique_sessions_current": self._uniq_merge_if("sessions_uniq_state", period_filters.current_period),+ "unique_sessions_previous": self._uniq_merge_if("sessions_uniq_state", period_filters.previous_period),"avg_session_duration_current": self._safe_avg_sessions(- "total_session_duration_state", "total_session_count_state", current_period_filter+ "total_session_duration_state", "total_session_count_state", period_filters.current_period),"avg_session_duration_previous": self._safe_avg_sessions(- "total_session_duration_state", "total_session_count_state", previous_period_filter+ "total_session_duration_state", "total_session_count_state", period_filters.previous_period),"bounce_rate_current": self._safe_avg_sessions(- "bounces_count_state", "sessions_uniq_state", current_period_filter+ "bounces_count_state", "sessions_uniq_state", period_filters.current_period),"bounce_rate_previous": self._safe_avg_sessions(- "bounces_count_state", "sessions_uniq_state", previous_period_filter+ "bounces_count_state", "sessions_uniq_state", period_filters.previous_period),},)@@ -78,9 +79,7 @@ class WebOverviewPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilderreturn query- def _get_conversion_query(- self, current_period_filter: ast.Expr, previous_period_filter: ast.Expr- ) -> ast.SelectQuery:+ def _get_conversion_query(self, *, period_filters: PeriodFilters) -> ast.SelectQuery:"""Build query for conversion goals using hybrid approach: pre-agg for visitors, raw events for conversions"""# Build subquery for conversions from raw eventsconversion_subquery = self._build_overview_conversion_subquery()@@ -95,8 +94,8 @@ class WebOverviewPreAggregatedQueryBuilder(WebAnalyticsPreAggregatedQueryBuilder""",placeholders={"table_name": ast.Field(chain=[self.bounces_table]),- "unique_persons_current": self._uniq_merge_if("persons_uniq_state", current_period_filter),- "unique_persons_previous": self._uniq_merge_if("persons_uniq_state", previous_period_filter),+ "unique_persons_current": self._uniq_merge_if("persons_uniq_state", period_filters.current_period),+ "unique_persons_previous": self._uniq_merge_if("persons_uniq_state", period_filters.previous_period),},)diff --git a/products/web_analytics/dags/web_preaggregated_asset_checks.py b/products/web_analytics/dags/web_preaggregated_asset_checks.pyindex 382d2750ed11..d52a419ef54f 100644--- a/products/web_analytics/dags/web_preaggregated_asset_checks.py+++ b/products/web_analytics/dags/web_preaggregated_asset_checks.py@@ -1,4 +1,5 @@import time+from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional, cast@@ -226,9 +227,16 @@ def log_query_sql(context.log.warning(f"Failed to log {query_name}: {e}")-def setup_accuracy_check_config(- context: AssetCheckExecutionContext, check_name: str-) -> tuple[float, int, int, str, str]:+@dataclass(frozen=True, kw_only=True, slots=True)+class AccuracyCheckConfig:+ tolerance_percentage: float+ days_back: int+ team_id: int+ date_from: str+ date_to: str+++def setup_accuracy_check_config(context: AssetCheckExecutionContext, check_name: str) -> AccuracyCheckConfig:full_run_config = cast(dict[str, Any], context.run.run_config)run_config = cast(dict[str, Any], full_run_config.get("ops", {}).get(check_name, {}).get("config", {}))tolerance_percentage = float(run_config.get("tolerance_pct", DEFAULT_TOLERANCE_PCT))@@ -240,12 +248,24 @@ def setup_accuracy_check_config(date_from = start_date.strftime("%Y-%m-%d")date_to = end_date.strftime("%Y-%m-%d")- return tolerance_percentage, days_back, team_id, date_from, date_to+ return AccuracyCheckConfig(+ tolerance_percentage=tolerance_percentage,+ days_back=days_back,+ team_id=team_id,+ date_from=date_from,+ date_to=date_to,+ )+++@dataclass(frozen=True, kw_only=True, slots=True)+class AccuracyCheckRunners:+ pre_aggregated: WebOverviewQueryRunner+ regular: WebOverviewQueryRunnerdef create_runners_for_accuracy_check(team: Team, date_from: str, date_to: str, use_v2_tables: bool = False-) -> tuple[WebOverviewQueryRunner, WebOverviewQueryRunner]:+) -> AccuracyCheckRunners:query_fn = lambda: WebOverviewQuery(dateRange=DateRange(date_from=date_from, date_to=date_to),properties=[],@@ -263,40 +283,43 @@ def create_runners_for_accuracy_check(modifiers=HogQLQueryModifiers(useWebAnalyticsPreAggregatedTables=False, convertToProjectTimezone=False),)- return runner_pre_agg, runner_regular+ return AccuracyCheckRunners(pre_aggregated=runner_pre_agg, regular=runner_regular)def execute_accuracy_check(- runner_pre_agg: WebOverviewQueryRunner,- runner_regular: WebOverviewQueryRunner,- team_id: int,- date_from: str,- date_to: str,context: AssetCheckExecutionContext,- tolerance_percentage: float,table_version: str,+ *,+ runners: AccuracyCheckRunners,+ config: AccuracyCheckConfig,) -> tuple[bool, dict[str, Any]]:"""Execute accuracy check between pre-aggregated and regular query runners."""try:- context.log.info(f"Running {table_version} accuracy check for team {team_id}")+ context.log.info(f"Running {table_version} accuracy check for team {config.team_id}")log_query_sql(- runner_pre_agg, f"Pre-aggregated SQL ({table_version})", context, runner_pre_agg.team, use_pre_agg=True+ runners.pre_aggregated,+ f"Pre-aggregated SQL ({table_version})",+ context,+ runners.pre_aggregated.team,+ use_pre_agg=True,+ )+ log_query_sql(+ runners.regular, f"Regular SQL ({table_version})", context, runners.regular.team, use_pre_agg=False)- log_query_sql(runner_regular, f"Regular SQL ({table_version})", context, runner_regular.team, use_pre_agg=False)context.log.info(f"About to execute pre-aggregated query ({table_version})")start_time = time.time()- pre_agg_response = runner_pre_agg.calculate()+ pre_agg_response = runners.pre_aggregated.calculate()pre_agg_execution_time = time.time() - start_timecontext.log.info(f"About to execute regular query ({table_version})")start_time = time.time()- regular_response = runner_regular.calculate()+ regular_response = runners.regular.calculate()regular_execution_time = time.time() - start_timecontext.log.info(- f"Query execution completed for team {team_id} ({table_version}), pre-agg time: {pre_agg_execution_time}, regular time: {regular_execution_time}"+ f"Query execution completed for team {config.team_id} ({table_version}), pre-agg time: {pre_agg_execution_time}, regular time: {regular_execution_time}")# Convert results to dict for easier comparison@@ -307,13 +330,13 @@ def execute_accuracy_check(regular_metrics = results_to_dict(regular_response.results)comparison_data: dict[str, Any] = {- "team_id": team_id,- "date_from": date_from,- "date_to": date_to,+ "team_id": config.team_id,+ "date_from": config.date_from,+ "date_to": config.date_to,"table_version": table_version,"metrics": {},"all_within_tolerance": True,- "tolerance_pct": tolerance_percentage,+ "tolerance_pct": config.tolerance_percentage,"timing": {"pre_aggregated": pre_agg_execution_time, "regular": regular_execution_time},}@@ -330,7 +353,7 @@ def execute_accuracy_check(within_tolerance = pre_agg_value == 0else:percentage_difference = abs(pre_agg_value - regular_value) / regular_value * 100- within_tolerance = percentage_difference <= tolerance_percentage+ within_tolerance = percentage_difference <= config.tolerance_percentagecomparison_data["metrics"][metric_name] = {"pre_aggregated": pre_agg_value,@@ -346,17 +369,20 @@ def execute_accuracy_check(except Exception as e:logger.error(- f"Error comparing web overview metrics ({table_version})", team_id=team_id, error=str(e), exc_info=True+ f"Error comparing web overview metrics ({table_version})",+ team_id=config.team_id,+ error=str(e),+ exc_info=True,)return False, {- "team_id": team_id,+ "team_id": config.team_id,"error": str(e),- "date_from": date_from,- "date_to": date_to,+ "date_from": config.date_from,+ "date_to": config.date_to,"table_version": table_version,"metrics": {},"all_within_tolerance": False,- "tolerance_pct": tolerance_percentage,+ "tolerance_pct": config.tolerance_percentage,"timing": {"pre_aggregated": 0.0, "regular": 0.0},}@@ -438,7 +464,7 @@ def run_accuracy_check_for_version()try:- tolerance_percentage, days_back, team_id, date_from, date_to = setup_accuracy_check_config(context, check_name)+ config = setup_accuracy_check_config(context, check_name)except Exception as e:context.log.exception(f"Failed to setup accuracy check config: {e}")return AssetCheckResult(@@ -450,26 +476,24 @@ def run_accuracy_check_for_version(get_query_tags().with_dagster(dagster_tags(context))try:- team = Team.objects.get(id=team_id)+ team = Team.objects.get(id=config.team_id)except Team.DoesNotExist:- context.log.exception(f"Team {team_id} not found")+ context.log.exception(f"Team {config.team_id} not found")return AssetCheckResult(passed=False,- description=f"Team {team_id} does not exist",- metadata={"error": MetadataValue.text(f"Team {team_id} not found")},+ description=f"Team {config.team_id} does not exist",+ metadata={"error": MetadataValue.text(f"Team {config.team_id} not found")},)except Exception as e:- context.log.exception(f"Database error while fetching team {team_id}: {e}")+ context.log.exception(f"Database error while fetching team {config.team_id}: {e}")return AssetCheckResult(passed=False,- description=f"Database error for team {team_id}",+ description=f"Database error for team {config.team_id}",metadata={"error": MetadataValue.text(str(e))},)try:- runner_pre_agg, runner_regular = create_runners_for_accuracy_check(- team, date_from, date_to, use_v2_tables=use_v2_tables- )+ runners = create_runners_for_accuracy_check(team, config.date_from, config.date_to, use_v2_tables=use_v2_tables)except Exception as e:context.log.exception(f"Failed to create query runners for {table_version}: {e}")return AssetCheckResult(@@ -480,27 +504,30 @@ def run_accuracy_check_for_version(try:is_valid, comparison_data = execute_accuracy_check(- runner_pre_agg, runner_regular, team_id, date_from, date_to, context, tolerance_percentage, table_version+ context,+ table_version,+ runners=runners,+ config=config,)timing = comparison_data.get("timing", {})context.log.info(f"{table_version.upper()} check - Valid?: {is_valid}. Pre-agg: {timing.get('pre_aggregated', 0):.2f}s, Regular: {timing.get('regular', 0):.2f}s")except Exception as e:- context.log.exception(f"Failed to run {table_version} accuracy check for team {team_id}: {str(e)}")+ context.log.exception(f"Failed to run {table_version} accuracy check for team {config.team_id}: {str(e)}")comparison_data = {- "team_id": team_id,+ "team_id": config.team_id,"error": str(e),- "date_from": date_from,- "date_to": date_to,+ "date_from": config.date_from,+ "date_to": config.date_to,"table_version": table_version,"skipped": True,- "tolerance_pct": tolerance_percentage,+ "tolerance_pct": config.tolerance_percentage,"all_within_tolerance": False,"metrics": {},}- return create_accuracy_check_result(comparison_data, team_id, table_version)+ return create_accuracy_check_result(comparison_data, config.team_id, table_version)# Team selection check for web_pre_aggregated_* tables