:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): serve goals from lazy precompute (#59993)
Lucas Ricoy00a672b16368
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 96c0bb6b5895..a2c00359cf3d 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -9644,6 +9644,14 @@"types": {"items": {},"type": "array"+ },+ "usedLazyPrecompute": {+ "description": "Whether the response was served from the lazy precompute path.",+ "type": "boolean"+ },+ "usedPreAggregatedTables": {+ "description": "Whether the response was served from a precomputed table.",+ "type": "boolean"}},"required": [@@ -12083,6 +12091,14 @@"types": {"items": {},"type": "array"+ },+ "usedLazyPrecompute": {+ "description": "Whether the response was served from the lazy precompute path.",+ "type": "boolean"+ },+ "usedPreAggregatedTables": {+ "description": "Whether the response was served from a precomputed table.",+ "type": "boolean"}},"required": ["results"],@@ -29405,6 +29421,14 @@"types": {"items": {},"type": "array"+ },+ "usedLazyPrecompute": {+ "description": "Whether the response was served from the lazy precompute path.",+ "type": "boolean"+ },+ "usedPreAggregatedTables": {+ "description": "Whether the response was served from a precomputed table.",+ "type": "boolean"}},"required": ["results"],@@ -30448,6 +30472,14 @@"types": {"items": {},"type": "array"+ },+ "usedLazyPrecompute": {+ "description": "Whether the response was served from the lazy precompute path.",+ "type": "boolean"+ },+ "usedPreAggregatedTables": {+ "description": "Whether the response was served from a precomputed table.",+ "type": "boolean"}},"required": ["results"],@@ -39820,6 +39852,10 @@"deprecated": "ignored, always treated as enabled *","type": "boolean"},+ "useWebAnalyticsPrecompute": {+ "description": "Opt this specific query into the web_goals_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. *",+ "type": "boolean"+ },"version": {"description": "version of the node, used for schema migrations","type": "number"@@ -39881,6 +39917,14 @@"types": {"items": {},"type": "array"+ },+ "usedLazyPrecompute": {+ "description": "Whether the response was served from the lazy precompute path.",+ "type": "boolean"+ },+ "usedPreAggregatedTables": {+ "description": "Whether the response was served from a precomputed table.",+ "type": "boolean"}},"required": ["results"],diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 3e709fb4f0a5..57857f5ddcdc 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2421,6 +2421,8 @@ export type CachedWebExternalClicksTableQueryResponse = CachedQueryResponse<WebEexport interface WebGoalsQuery extends WebAnalyticsQueryBase<WebGoalsQueryResponse> {kind: NodeKind.WebGoalsQuerylimit?: integer+ /** Opt this specific query into the web_goals_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/+ useWebAnalyticsPrecompute?: boolean}export interface WebGoalsQueryResponse extends AnalyticsQueryResponseBase {@@ -2432,6 +2434,10 @@ export interface WebGoalsQueryResponse extends AnalyticsQueryResponseBase {hasMore?: booleanlimit?: integeroffset?: integer+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean}export type CachedWebGoalsQueryResponse = CachedQueryResponse<WebGoalsQueryResponse>diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsxindex d0c649c61dde..c60784c01c2d 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsMenu.tsx@@ -60,7 +60,7 @@ export const WebAnalyticsMenu = (): JSX.Element => {Filter out internal and test users</ButtonPrimitive>{featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_PRECOMPUTE_TOGGLE] && (- <Tooltip title="When on, eligible web analytics tiles (currently overview and paths) load from a pre-computed result instead of running a live query. Results are faster but may be a few minutes behind the latest events. Other tiles run live as usual.">+ <Tooltip title="When on, eligible web analytics tiles load from a pre-computed result instead of running a live query. Results are faster but may be a few minutes behind the latest events. Other tiles run live as usual."><ButtonPrimitivemenuItemonClick={() => {diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxindex 48f99493ca14..bd6d17d2da62 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx@@ -2184,6 +2184,9 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([orderBy: tablesOrderBy ?? undefined,filterTestAccounts,tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,+ // Backend gate decides whether this query is actually served+ // from the precomputed table; we just pass the per-team opt-in.+ useWebAnalyticsPrecompute,},embedded: true,showActions: true,diff --git a/posthog/schema.py b/posthog/schema.pyindex 4a306821fe7f..810838452d86 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -9259,6 +9259,14 @@ class WebGoalsQueryResponse(BaseModel):description=("Measured timings for different parts of the query generation process"),)types: list | None = None+ usedLazyPrecompute: bool | None = Field(+ default=None,+ description="Whether the response was served from the lazy precompute path.",+ )+ usedPreAggregatedTables: bool | None = Field(+ default=None,+ description="Whether the response was served from a precomputed table.",+ )class WebNotableChangesQueryResponse(BaseModel):@@ -12653,6 +12661,14 @@ class CachedWebGoalsQueryResponse(BaseModel):description=("Measured timings for different parts of the query generation process"),)types: list | None = None+ usedLazyPrecompute: bool | None = Field(+ default=None,+ description="Whether the response was served from the lazy precompute path.",+ )+ usedPreAggregatedTables: bool | None = Field(+ default=None,+ description="Whether the response was served from a precomputed table.",+ )class CachedWebNotableChangesQueryResponse(BaseModel):@@ -13420,6 +13436,46 @@ class Response6(BaseModel):types: list | None = None+class Response7(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ columns: list | None = None+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ samplingRate: SamplingRate | None = None+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = None+ usedLazyPrecompute: bool | None = Field(+ default=None,+ description="Whether the response was served from the lazy precompute path.",+ )+ usedPreAggregatedTables: bool | None = Field(+ default=None,+ description="Whether the response was served from a precomputed table.",+ )++class Response8(BaseModel):model_config = ConfigDict(extra="forbid",@@ -16312,6 +16368,46 @@ class QueryResponseAlternative25(BaseModel):types: list | None = None+class QueryResponseAlternative26(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ columns: list | None = None+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ samplingRate: SamplingRate | None = None+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = None+ usedLazyPrecompute: bool | None = Field(+ default=None,+ description="Whether the response was served from the lazy precompute path.",+ )+ usedPreAggregatedTables: bool | None = Field(+ default=None,+ description="Whether the response was served from a precomputed table.",+ )++class QueryResponseAlternative27(BaseModel):model_config = ConfigDict(extra="forbid",@@ -16848,6 +16944,46 @@ class QueryResponseAlternative45(BaseModel):types: list | None = None+class QueryResponseAlternative46(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ columns: list | None = None+ error: str | None = Field(+ default=None,+ description=(+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."+ ),+ )+ hasMore: bool | None = None+ hogql: str | None = Field(default=None, description="Generated HogQL query.")+ limit: int | None = None+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")+ offset: int | None = None+ query_status: QueryStatus | None = Field(+ default=None,+ description=("Query status indicates whether next to the provided data, a query is still running."),+ )+ resolved_date_range: ResolvedDateRangeResponse | None = Field(+ default=None, description="The date range used for the query"+ )+ results: list+ samplingRate: SamplingRate | None = None+ timings: list[QueryTiming] | None = Field(+ default=None,+ description=("Measured timings for different parts of the query generation process"),+ )+ types: list | None = None+ usedLazyPrecompute: bool | None = Field(+ default=None,+ description="Whether the response was served from the lazy precompute path.",+ )+ usedPreAggregatedTables: bool | None = Field(+ default=None,+ description="Whether the response was served from a precomputed table.",+ )++class QueryResponseAlternative47(BaseModel):model_config = ConfigDict(extra="forbid",@@ -18670,6 +18806,14 @@ class WebGoalsQuery(BaseModel):samplingFactor: float | None = Field(default=None, description="Sampling rate")tags: QueryLogTags | None = NoneuseSessionsTable: bool | None = None+ useWebAnalyticsPrecompute: bool | None = Field(+ default=None,+ description=(+ "Opt this specific query into the web_goals_query precompute path. Requires"+ " the `web-analytics-precompute-toggle` PostHog feature flag to be on for"+ " the team's organization for the gate to pass. *"+ ),+ )version: float | None = Field(default=None, description="version of the node, used for schema migrations")@@ -22322,6 +22466,7 @@ class QueryResponseAlternative(| QueryResponseAlternative23| QueryResponseAlternative24| QueryResponseAlternative25+ | QueryResponseAlternative26| QueryResponseAlternative27| QueryResponseAlternative28| QueryResponseAlternative29@@ -22342,6 +22487,7 @@ class QueryResponseAlternative(| QueryResponseAlternative43| QueryResponseAlternative44| QueryResponseAlternative45+ | QueryResponseAlternative46| QueryResponseAlternative47| QueryResponseAlternative48| QueryResponseAlternative49@@ -22412,6 +22558,7 @@ class QueryResponseAlternative(| QueryResponseAlternative23| QueryResponseAlternative24| QueryResponseAlternative25+ | QueryResponseAlternative26| QueryResponseAlternative27| QueryResponseAlternative28| QueryResponseAlternative29@@ -22432,6 +22579,7 @@ class QueryResponseAlternative(| QueryResponseAlternative43| QueryResponseAlternative44| QueryResponseAlternative45+ | QueryResponseAlternative46| QueryResponseAlternative47| QueryResponseAlternative48| QueryResponseAlternative49@@ -23251,6 +23399,7 @@ class DataTableNode(BaseModel):| Response4| Response5| Response6+ | Response7| Response8| Response9| Response10diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 4d1bdd267f83..fa4bfdc0d2d6 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -3140,6 +3140,32 @@ export interface Response6Api {types?: unknown[] | null}+export interface Response7Api {+ columns?: unknown[] | null+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null+ hasMore?: boolean | null+ /** Generated HogQL query. */+ hogql?: string | null+ limit?: number | null+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiersApi | null+ offset?: number | null+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatusApi | null+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponseApi | null+ results: unknown[]+ samplingRate?: SamplingRateApi | null+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTimingApi[] | null+ types?: unknown[] | null+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null+}+export interface WebVitalsPathBreakdownResultItemApi {path: stringvalue: number@@ -4895,6 +4921,10 @@ export interface WebGoalsQueryResponseApi {/** Measured timings for different parts of the query generation process */timings?: QueryTimingApi[] | nulltypes?: unknown[] | null+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null}export interface WebGoalsQueryApi {@@ -4927,6 +4957,8 @@ export interface WebGoalsQueryApi {samplingFactor?: number | nulltags?: QueryLogTagsApi | nulluseSessionsTable?: boolean | null+ /** Opt this specific query into the web_goals_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null/** version of the node, used for schema migrations */version?: number | null}@@ -6358,6 +6390,7 @@ export type DataTableNodeApiResponse =| Response4Api| Response5Api| Response6Api+ | Response7Api| Response8Api| Response9Api| Response10Apidiff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.pynew file mode 100644index 000000000000..14bc430bd2ce--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals_lazy_precompute.py@@ -0,0 +1,240 @@+import unittest+from freezegun import freeze_time+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person+from unittest.mock import patch++from django.test import override_settings++from posthog.schema import (+ CompareFilter,+ DateRange,+ EventPropertyFilter,+ HogQLQueryModifiers,+ PropertyOperator,+ SessionPropertyFilter,+ SessionsV2JoinMode,+ WebAnalyticsSampling,+ WebGoalsQuery,+)++from posthog.models.utils import uuid7++from products.actions.backend.models.action import Action+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob+from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner+from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import can_use_lazy_precompute+++@override_settings(IN_UNIT_TESTING=True)+class TestWebGoalsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ PreaggregationJob.objects.filter(team_id=self.team.pk).delete()+ Action.objects.filter(team__project_id=self.team.project_id).delete()++ def _enable_lazy(self):+ # Same flag the paths/frustration tests patch — the gate evaluates the+ # `web-analytics-precompute-toggle` org flag via posthoganalytics.+ return patch(+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",+ return_value=True,+ )++ def _create_action(self, name: str, event: str = "$pageview") -> Action:+ return Action.objects.create(+ team=self.team,+ name=name,+ steps_json=[{"event": event}],+ )++ def _seed_goal_events(self) -> None:+ s1 = str(uuid7("2024-01-02"))+ s2 = str(uuid7("2024-01-03"))+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})+ _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p1",+ timestamp="2024-01-02T10:00:00Z",+ properties={+ "$session_id": s1,+ "$host": "example.com",+ "$pathname": "/landing",+ "$current_url": "https://example.com/landing",+ },+ )+ _create_event(+ team=self.team,+ event="$autocapture",+ distinct_id="p1",+ timestamp="2024-01-02T10:00:05Z",+ properties={+ "$session_id": s1,+ "$host": "example.com",+ "$pathname": "/landing",+ },+ )+ _create_event(+ team=self.team,+ event="$pageview",+ distinct_id="p2",+ timestamp="2024-01-03T11:00:00Z",+ properties={+ "$session_id": s2,+ "$host": "example.com",+ "$pathname": "/landing",+ "$current_url": "https://example.com/landing",+ },+ )++ def _build_query(+ self,+ *,+ date_from: str = "2024-01-01",+ date_to: str = "2024-01-07",+ properties: list | None = None,+ compare: bool = False,+ opt_in_precompute: bool = True,+ sampling: WebAnalyticsSampling | None = None,+ order_by: list | None = None,+ modifiers: HogQLQueryModifiers | None = None,+ ) -> WebGoalsQuery:+ return WebGoalsQuery(+ dateRange=DateRange(date_from=date_from, date_to=date_to),+ properties=properties or [],+ compareFilter=CompareFilter(compare=compare) if compare else None,+ useWebAnalyticsPrecompute=opt_in_precompute,+ sampling=sampling,+ orderBy=order_by,+ modifiers=modifiers,+ )++ def _runner(self, query: WebGoalsQuery) -> WebGoalsQueryRunner:+ return WebGoalsQueryRunner(team=self.team, query=query)++ # ----------------------------------------------------------------------+ # Eligibility — no ClickHouse needed for these.+ # ----------------------------------------------------------------------++ def test_eligible_when_flag_on_opt_in_set_and_actions_exist(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ assert can_use_lazy_precompute(self._runner(self._build_query())) is True++ def test_rejected_when_no_actions_configured(self):+ # No actions: even with flag + opt-in, the gate refuses since there's+ # nothing to precompute (matches the live `NoActionsError` behaviour).+ with self._enable_lazy():+ assert can_use_lazy_precompute(self._runner(self._build_query())) is False++ def test_rejected_when_org_flag_off(self):+ self._create_action("Pageview")+ with patch(+ "products.web_analytics.backend.hogql_queries.web_lazy_precompute_common.posthoganalytics.feature_enabled",+ return_value=False,+ ):+ assert can_use_lazy_precompute(self._runner(self._build_query())) is False++ def test_rejected_when_per_query_opt_in_missing(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ assert can_use_lazy_precompute(self._runner(self._build_query(opt_in_precompute=False))) is False++ def test_rejected_when_sampling_enabled(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ assert (+ can_use_lazy_precompute(self._runner(self._build_query(sampling=WebAnalyticsSampling(enabled=True))))+ is False+ )++ def test_rejected_for_unsupported_filter_key(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ assert (+ can_use_lazy_precompute(+ self._runner(+ self._build_query(+ properties=[+ EventPropertyFilter(key="$browser", operator=PropertyOperator.EXACT, value="Chrome")+ ]+ )+ )+ )+ is False+ )++ def test_rejected_for_non_event_property_filter(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ assert (+ can_use_lazy_precompute(+ self._runner(+ self._build_query(+ properties=[+ SessionPropertyFilter(+ key="$entry_pathname", operator=PropertyOperator.EXACT, value="/x"+ )+ ]+ )+ )+ )+ is False+ )++ def test_rejected_for_sessions_v2_uuid_mode(self):+ self._create_action("Pageview")+ with self._enable_lazy():+ modifiers = HogQLQueryModifiers(sessionsV2JoinMode=SessionsV2JoinMode.UUID)+ assert can_use_lazy_precompute(self._runner(self._build_query(modifiers=modifiers))) is False++ # ----------------------------------------------------------------------+ # Round-trip — these exercise the real INSERT + read. They mirror the+ # paths/frustration tests and inherit the same CI-flake skip while the+ # read-after-write visibility issue tracked on the paths tests is open.+ # ----------------------------------------------------------------------++ @freeze_time("2024-01-15T12:00:00Z")+ def test_round_trip_creates_precompute_job(self):+ self._create_action("Pageview")+ self._seed_goal_events()+ with self._enable_lazy():+ self._runner(self._build_query()).calculate()++ jobs = list(PreaggregationJob.objects.filter(team_id=self.team.pk))+ assert len(jobs) > 0, "expected at least one precompute job to be created"++ @unittest.skip(+ "Mirrors the CI-only flake in test_web_stats_paths_lazy_precompute.py — "+ "lazy path returns empty rows despite READY job. Re-enable once the "+ "read-after-write visibility issue tracked there is resolved."+ )+ @freeze_time("2024-01-15T12:00:00Z")+ def test_lazy_response_matches_live(self):+ """Compare the goals response between the live and lazy paths."""+ action = self._create_action("Pageview")+ self._seed_goal_events()++ live_response = self._runner(self._build_query()).calculate()++ with self._enable_lazy():+ lazy_response = self._runner(self._build_query()).calculate()++ assert lazy_response.usedLazyPrecompute is True+ assert lazy_response.usedPreAggregatedTables is True++ live_by_action = {r[0]: (r[1], r[2], r[3]) for r in live_response.results}+ lazy_by_action = {r[0]: (r[1], r[2], r[3]) for r in lazy_response.results}+ assert lazy_by_action == live_by_action, (+ f"lazy/live mismatch for action={action.name!r}: lazy={lazy_by_action}, live={live_by_action}"+ )++ def test_max_actions_constant_matches_live_runner_slice(self):+ """The lazy `MAX_ACTIONS` cap must equal the live runner's hard slice;+ otherwise we'd be precomputing rows the runner never reads (extra+ INSERT load) or, worse, missing rows the runner asks for."""+ from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import MAX_ACTIONS++ # The live slice is hard-coded `[:5]` in `web_goals.py`'s `to_query`.+ assert MAX_ACTIONS == 5diff --git a/products/web_analytics/backend/hogql_queries/web_goals.py b/products/web_analytics/backend/hogql_queries/web_goals.pyindex b4c566ef4d8f..39fa4e956564 100644--- a/products/web_analytics/backend/hogql_queries/web_goals.py+++ b/products/web_analytics/backend/hogql_queries/web_goals.py@@ -1,5 +1,5 @@from collections.abc import Iterator, Sequence-from typing import TypeVar+from typing import Optional, TypeVarfrom posthog.schema import CachedWebGoalsQueryResponse, WebAnalyticsOrderByFields, WebGoalsQuery, WebGoalsQueryResponse@@ -10,6 +10,10 @@ from posthog.hogql.query import execute_hogql_queryfrom products.actions.backend.models.action import Actionfrom products.web_analytics.backend.hogql_queries.web_analytics_query_runner import WebAnalyticsQueryRunner+from products.web_analytics.backend.hogql_queries.web_goals_lazy_precompute import (+ can_use_lazy_precompute,+ execute_lazy_precomputed_read,+)# Returns an array `seq` split into chunks of size `size`# Example:@@ -183,6 +187,10 @@ WHERE {periods_expression}return outer_selectdef _calculate(self):+ lazy_response = self._maybe_calculate_via_lazy_precompute()+ if lazy_response is not None:+ return lazy_response+try:query = self.to_query()except NoActionsError:@@ -232,7 +240,89 @@ WHERE {periods_expression}index = 3if index is not None:- results.sort(key=lambda x: x[index], reverse=self.query.orderBy[1] == "DESC")+ # Sort by the current-period scalar only — `x[index]` is a+ # `(current, previous)` tuple and `previous` is `None` when+ # `include_previous=False`. Python's stable sort falls+ # through to compare the second element on ties, and+ # `None < int` raises `TypeError`. Indexing `[0]` keeps the+ # comparison on the scalar current value only.+ results.sort(key=lambda x: x[index][0], reverse=self.query.orderBy[1] == "DESC")++ return WebGoalsQueryResponse(+ columns=[+ "context.columns.action_name",+ "context.columns.converting_users",+ "context.columns.total_conversions",+ "context.columns.conversion_rate",+ ],+ results=results,+ samplingRate=self._sample_rate,+ modifiers=self.modifiers,+ )++ def _maybe_calculate_via_lazy_precompute(self) -> Optional[WebGoalsQueryResponse]:+ """Short-circuit through the goals lazy precompute table when eligible.++ Returns None on ineligibility or any failure, in which case the caller+ falls through to the live HogQL path.++ The lazy precompute reads each top-5 action's `count` / `unique persons`+ plus the per-period denominator (`action_id = -1` carrying every+ qualifying session's person). We pivot those back into the runner's+ response shape — `[action_name, (cur_unique, prev_unique), (cur_total,+ prev_total), (cur_rate, prev_rate)]` per action — matching the live+ path's `_calculate` exactly so consumers can't tell the two apart.+ """+ if not can_use_lazy_precompute(self):+ return None+ result = execute_lazy_precomputed_read(self)+ if result is None:+ return None+ return self._build_response_from_lazy(result)++ def _build_response_from_lazy(self, result: dict) -> WebGoalsQueryResponse:+ include_previous = self.query_compare_to_date_range is not None+ actions = result["actions"]+ denominator = result["denominator"]+ per_action = result["per_action"]++ current_visitors = denominator["current"]+ previous_visitors = denominator["previous"]++ results: list = []+ for action in actions:+ metrics = per_action.get(int(action.id))+ current_total = metrics["current_total"] if metrics else 0+ previous_total = metrics["previous_total"] if metrics else 0+ current_unique = metrics["current_unique"] if metrics else 0+ previous_unique = metrics["previous_unique"] if metrics else 0++ action_total = (current_total, previous_total if include_previous else None)+ action_unique = (current_unique, previous_unique if include_previous else None)++ current_rate = current_unique / current_visitors if current_visitors > 0 else 0+ previous_rate = (+ (previous_unique / previous_visitors if previous_visitors > 0 else 0) if include_previous else None+ )++ results.append([action.name, action_unique, action_total, (current_rate, previous_rate)])++ if self.query.orderBy is not None:+ index = None+ if self.query.orderBy[0] == WebAnalyticsOrderByFields.CONVERTING_USERS:+ index = 1+ elif self.query.orderBy[0] == WebAnalyticsOrderByFields.TOTAL_CONVERSIONS:+ index = 2+ elif self.query.orderBy[0] == WebAnalyticsOrderByFields.CONVERSION_RATE:+ index = 3+ if index is not None:+ # Sort by the current-period scalar only — `x[index]` is a+ # `(current, previous)` tuple and `previous` is `None` when+ # `include_previous=False`. Python's stable sort falls+ # through to compare the second element on ties, and+ # `None < int` raises `TypeError`. Indexing `[0]` keeps the+ # comparison on the scalar current value only.+ results.sort(key=lambda x: x[index][0], reverse=self.query.orderBy[1] == "DESC")return WebGoalsQueryResponse(columns=[@@ -244,6 +334,8 @@ WHERE {periods_expression}results=results,samplingRate=self._sample_rate,modifiers=self.modifiers,+ usedPreAggregatedTables=True,+ usedLazyPrecompute=True,)def event_properties(self) -> ast.Expr:diff --git a/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.pynew file mode 100644index 000000000000..3300523d3ab8--- /dev/null+++ b/products/web_analytics/backend/hogql_queries/web_goals_lazy_precompute.py@@ -0,0 +1,547 @@+"""Lazy precompute path for the Web Analytics GOALS tile.++Mirrors `web_stats_paths_lazy_precompute.py` and shares its eligibility gate+via `web_lazy_precompute_common`. The precomputed table stores one row per+(team, job, UTC hour, action_id):++- `action_id = -1` carries the per-hour denominator: unique persons whose+ session had ANY qualifying event (pageview / screen / action match).+- `action_id = <real id>` carries the per-action conversion: sum of match+ counts plus unique converting persons.++The action set (the top-5 actions returned by+`Action.objects…order_by('pinned_at', '-last_calculated_at')[:5]`) is part+of the INSERT AST and therefore the lazy_computation cache key — a different+top-5 set yields a different job_id, so the runner's hard `[:5]` slice is+mirrored without further coordination.+"""++import time+from collections.abc import Sequence+from datetime import UTC, datetime+from typing import TYPE_CHECKING, Optional++import structlog+from prometheus_client import Counter, Histogram++from posthog.schema import HogQLQueryModifiers++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.property import action_to_expr+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tag_queries++from products.actions.backend.models.action import Action+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (+ LazyComputationResult,+ LazyComputationTable,+ ensure_precomputed,+)+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ LAZY_TTL_SECONDS,+ SESSION_FORWARD_PAD_MINUTES,+ LazyPrecomputeIneligible,+ ceil_utc_day,+ check_common_eligibility,+ floor_utc_day,+ host_filter_expr,+ log_eligibility_outcome,+ test_account_filter_expr,+)++if TYPE_CHECKING:+ from products.web_analytics.backend.hogql_queries.web_goals import WebGoalsQueryRunner++logger = structlog.get_logger(__name__)+++# Sentinel action_id used for the per-hour denominator row. Real Django+# `Action.id` values are positive auto-increment integers, so -1 is safe.+DENOMINATOR_ACTION_ID = -1++# Maximum number of actions the precompute will cover. Matches the runner's+# hard `Action.objects…[:5]` slice exactly — precomputing more would be+# wasted INSERT work the runner never reads. If the live UX ever expands+# beyond 5 actions, bump both this constant and the runner's slice together.+MAX_ACTIONS = 5+++_KNOWN_FAILED_ERROR_TYPES: set[str] = {+ "ServerException",+ "NetworkError",+ "OperationalError",+ "IntegrityError",+ "AssertionError",+ "AttributeError",+ "KeyError",+ "ValueError",+ "TypeError",+ "TimeoutError",+}+++def _bucket_error_label(exc: BaseException) -> str:+ name = type(exc).__name__+ return name if name in _KNOWN_FAILED_ERROR_TYPES else "other"+++WEB_GOALS_LAZY_FAILED = Counter(+ "web_goals_lazy_precompute_failed_total",+ "Lazy precompute path (goals tile) failures, by error class",+ ["error_type"],+)++WEB_GOALS_LAZY_EMPTY = Counter(+ "web_goals_lazy_precompute_empty_total",+ "Lazy precompute reads that returned zero rows (no qualifying sessions).",+)++WEB_GOALS_LAZY_ACTIONS = Histogram(+ "web_goals_lazy_precompute_actions",+ "Number of actions the precompute job covered (cap at MAX_ACTIONS).",+ buckets=(1, 2, 3, 4, 5),+)+++class NoActionsConfigured(LazyPrecomputeIneligible):+ pass+++def can_use_lazy_precompute(runner: "WebGoalsQueryRunner") -> bool:+ """Return True iff the GOALS tile can be served from precompute."""+ try:+ _check_eligible(runner)+ except LazyPrecomputeIneligible as exc:+ log_eligibility_outcome(log_prefix="web_goals_lazy_precompute", team_id=runner.team.pk, error=exc)+ return False+ log_eligibility_outcome(log_prefix="web_goals_lazy_precompute", team_id=runner.team.pk, error=None)+ return True+++def _check_eligible(runner: "WebGoalsQueryRunner") -> None:+ query = runner.query++ check_common_eligibility(+ team=runner.team,+ use_web_analytics_precompute=query.useWebAnalyticsPrecompute,+ conversion_goal=None,+ sampling=query.sampling,+ modifiers=query.modifiers,+ properties=query.properties or [],+ resolve_date_range=lambda: (runner.query_date_range.date_from(), runner.query_date_range.date_to()),+ )++ # We need at least one action — without any, the live runner raises+ # `NoActionsError` and returns an empty response; the lazy path has+ # nothing to precompute either.+ if _select_actions(runner) == []:+ raise NoActionsConfigured()+++# Attribute name used to memoize the action lookup on the per-request+# runner instance. Using a `_lazy_*` prefix avoids collision with anything+# the live `WebGoalsQueryRunner` already stores.+_RUNNER_ACTIONS_CACHE_ATTR = "_lazy_goals_actions"+++def _select_actions(runner: "WebGoalsQueryRunner") -> list:+ """Top-N actions, matching the live runner's hard `[:5]` slice exactly.++ Memoized on the runner instance: this function is called from both the+ eligibility check (`_check_eligible`) and the orchestrator+ (`execute_lazy_precomputed_read`). Without caching we issue two+ consecutive identical Postgres queries per opted-in request AND open a+ TOCTOU window where a concurrent action mutation between the two calls+ can flip eligibility from "pass with N actions" to "execute with 0+ actions", producing a confusing empty-then-fallback response. The+ runner is request-scoped, so a per-runner attribute cache is the right+ lifetime.++ Different top-5 sets across requests still produce different INSERT+ ASTs and therefore distinct lazy_computation cache keys — the cache+ here is purely an in-request memoization.+ """+ cached = getattr(runner, _RUNNER_ACTIONS_CACHE_ATTR, None)+ if cached is not None:+ return cached+ qs = Action.objects.filter(team__project_id=runner.team.project_id, deleted=False).order_by(+ "pinned_at", "-last_calculated_at"+ )[:MAX_ACTIONS]+ fetched = list(qs)+ setattr(runner, _RUNNER_ACTIONS_CACHE_ATTR, fetched)+ return fetched+++def _events_session_id_expr(runner: "WebGoalsQueryRunner") -> ast.Expr:+ return runner.events_session_property+++def _action_or_expr(actions: Sequence) -> ast.Expr:+ """Build `Or(action_to_expr(a) for a in actions)` — gates the events scan+ to events that can possibly contribute to any of the actions, plus+ `$pageview`/`$screen` which always anchor the session."""+ return ast.Or(exprs=[action_to_expr(a) for a in actions])+++def _build_insert_query(actions: Sequence) -> str:+ """Synthesize the HogQL INSERT template for the given action set.++ The shape is one row per (team, job, hour, action_id) emitted by:+ - inner session aggregation that produces per-session+ `count_<n>` columns (one per action) plus `session_person_id`+ - `arrayJoin` over `[(-1, 0), (action_0_id, count_0), ..., (action_N_id,+ count_N)]` that fans those columns out into rows+ - outer `GROUP BY toStartOfHour(start_timestamp), action_id` that emits+ `sumState(action_count)` and `uniqStateIf(session_person_id, ...)`++ `action_id = -1` aggregates the per-hour denominator (every session's+ person), giving the global "converting universe" the runner uses to+ compute conversion rate. The condition `action_id = -1 OR action_count+ > 0` keeps unique-person counts honest for both the per-action and+ denominator rows in one expression.+ """+ # Per-session COUNT columns + ORM-known action ids for the arrayJoin.+ # Every tuple element is wrapped in an explicit `toInt64(...)` so the+ # tuple types unify cleanly across the array. ClickHouse requires+ # uniform element types within an array of tuples; without the explicit+ # cast the denominator's literal `0` (Int32) and the per-action+ # `countIf(...)` (UInt64) would force ClickHouse into type-unification+ # rules that have historically produced runtime errors in similar+ # precompute paths, and the round-trip parity test is skipped pending+ # the read-after-write CI flake — so a type error would only surface in+ # production through the failure counter and silent fall-through to the+ # live path.+ # `countIf` is bounded by the per-job time window so events that occur+ # in the SESSION_FORWARD_PAD_MINUTES tail (past `time_window_max`) do+ # NOT contribute to this job's counts. The pad lets `min(start_timestamp)`+ # see late events for correct session-start anchoring, but counting them+ # here would overcount conversions for sessions starting near the end of+ # the user's selected range — the live runner counts goals with+ # `countIf(action_expr AND timestamp IN current_period)`, so the lazy+ # match it event-by-event rather than aggregating the whole session's+ # event tail into the start-hour bucket.+ count_aliases = ",\n ".join(+ f"countIf(and({{action_{n}_expr}}, timestamp >= {{time_window_min}}, timestamp < {{time_window_max}})) AS count_{n}"+ for n in range(len(actions))+ )+ array_join_pairs = ",\n ".join(+ f"tuple({{action_{n}_id}}, toInt64(count_{n}))" for n in range(len(actions))+ )+ # The literal `-1` anchors the per-hour denominator row; `0` is just a+ # placeholder because the denominator row's `count_state` is never read.+ array_join_literal = f"tuple(toInt64({DENOMINATOR_ACTION_ID}), toInt64(0)), {array_join_pairs}"++ return f"""+SELECT+ toStartOfHour(start_timestamp) AS time_window_start,+ action_id,+ sumState(assumeNotNull(toInt(action_count))) AS count_state,+ uniqStateIf(+ session_person_id,+ or(equals(action_id, {DENOMINATOR_ACTION_ID}), greater(action_count, 0))+ ) AS unique_persons_state+FROM (+ SELECT+ start_timestamp,+ session_person_id,+ arrayJoin([+ {array_join_literal}+ ]) AS pair,+ pair.1 AS action_id,+ pair.2 AS action_count+ FROM (+ SELECT+ any(events.person_id) AS session_person_id,+ min(session.$start_timestamp) AS start_timestamp,+ {{events_session_id}} AS session_id,+ {count_aliases}+ FROM events+ WHERE and(+ {{events_session_id}} IS NOT NULL,+ or(events.event = '$pageview', events.event = '$screen', {{action_or_expr}}),+ timestamp >= {{time_window_min}},+ timestamp < ({{time_window_max}} + toIntervalMinute({{pad_minutes}})),+ {{user_filter}},+ {{test_account_filter}}+ )+ GROUP BY session_id+ HAVING and(+ toStartOfHour(min(session.$start_timestamp)) >= {{time_window_min}},+ toStartOfHour(min(session.$start_timestamp)) < {{time_window_max}}+ )+ )+)+GROUP BY time_window_start, action_id+"""+++def ensure_web_goals_precomputed(+ runner: "WebGoalsQueryRunner",+ actions: Sequence,+ time_range_start: datetime,+ time_range_end: datetime,+) -> LazyComputationResult:+ placeholders: dict[str, ast.Expr] = {+ "events_session_id": _events_session_id_expr(runner),+ "action_or_expr": _action_or_expr(actions),+ "user_filter": host_filter_expr(runner.query.properties or []),+ "test_account_filter": test_account_filter_expr(+ test_account_filters=runner._test_account_filters, team=runner.team+ ),+ "pad_minutes": ast.Constant(value=SESSION_FORWARD_PAD_MINUTES),+ }+ for n, action in enumerate(actions):+ placeholders[f"action_{n}_expr"] = action_to_expr(action)+ placeholders[f"action_{n}_id"] = ast.Constant(value=int(action.id))++ return ensure_precomputed(+ team=runner.team,+ insert_query=_build_insert_query(actions),+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ ttl_seconds=LAZY_TTL_SECONDS,+ table=LazyComputationTable.WEB_GOALS_PREAGGREGATED,+ placeholders=placeholders,+ query_type="web_goals_lazy_insert",+ )+++# Soft budget for the cumulative `ensure_precomputed` time inside a single+# request. Same reasoning as the paths tile: a compare-period request makes+# two back-to-back ensure calls and the framework's default per-call wait is+# 180s — skip the second if the first already burned most of that.+ENSURE_BUDGET_MS = 120 * 1000+++# Read template. One row per `action_id` (including the `-1` denominator) for+# the requested current + previous periods. The HAVING is intentionally absent —+# the runner needs every requested `action_id` in the response (even if 0+# converted) so action_name lookups don't surface as missing rows.+_READ_SQL_TEMPLATE = """+SELECT+ action_id,+ sumMergeIf(count_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS current_total,+ sumMergeIf(count_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_total,+ uniqMergeIf(unique_persons_state, and(time_window_start >= {cur_start}, time_window_start < {cur_end})) AS current_unique,+ uniqMergeIf(unique_persons_state, and(time_window_start >= {prev_start}, time_window_start < {prev_end})) AS previous_unique+FROM posthog.web_goals_preaggregated+WHERE and(team_id = {team_id}, job_id IN {job_ids}, action_id IN {action_ids})+GROUP BY action_id+"""+++def execute_read_query(+ *,+ runner: "WebGoalsQueryRunner",+ job_ids: list[str],+ action_ids: list[int],+ current_start_utc: datetime,+ current_end_utc: datetime,+ previous_start_utc: Optional[datetime],+ previous_end_utc: Optional[datetime],+) -> list:+ """Run the precompute-read HogQL. Returns raw `response.results`."""+ prev_start = previous_start_utc if previous_start_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)+ prev_end = previous_end_utc if previous_end_utc is not None else datetime(1970, 1, 1, tzinfo=UTC)++ placeholders: dict[str, ast.Expr] = {+ "team_id": ast.Constant(value=runner.team.pk),+ "job_ids": ast.Constant(value=[str(jid) for jid in job_ids]),+ "action_ids": ast.Constant(value=action_ids),+ "cur_start": ast.Constant(value=current_start_utc),+ "cur_end": ast.Constant(value=current_end_utc),+ "prev_start": ast.Constant(value=prev_start),+ "prev_end": ast.Constant(value=prev_end),+ }++ parsed = parse_select(_READ_SQL_TEMPLATE, placeholders=placeholders)+ assert isinstance(parsed, ast.SelectQuery), "lazy goals read template must parse to a SelectQuery"++ modifiers = runner.modifiers.model_copy() if runner.modifiers else HogQLQueryModifiers()+ modifiers.convertToProjectTimezone = False++ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY, query_type="web_goals_lazy_query")+ response = execute_hogql_query(+ query_type="web_goals_lazy_query",+ query=parsed,+ team=runner.team,+ timings=runner.timings,+ modifiers=modifiers,+ limit_context=runner.limit_context,+ )+ return list(response.results or [])+++def execute_lazy_precomputed_read(runner: "WebGoalsQueryRunner") -> Optional[dict]:+ """Orchestrate the lazy precompute + read. Returns a dict with the action+ list and the per-action / denominator metrics, or None on any failure+ (caller falls through to the live HogQL path).++ Output shape:+ {+ "actions": [Action, ...], # top-N in order+ "denominator": {"current": int, "previous": int},+ "per_action": {+ action_id: {+ "current_total": int,+ "previous_total": int,+ "current_unique": int,+ "previous_unique": int,+ },+ ...+ },+ }+ """+ tag_queries(product=Product.WEB_ANALYTICS, feature=Feature.QUERY)+ team_id = runner.team.pk+ overall_started = time.perf_counter()+ try:+ actions = _select_actions(runner)+ if not actions:+ return None+ WEB_GOALS_LAZY_ACTIONS.observe(len(actions))++ 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++ current_start_utc = date_from.astimezone(UTC)+ current_end_utc = date_to.astimezone(UTC)+ time_range_start = floor_utc_day(current_start_utc)+ time_range_end = ceil_utc_day(current_end_utc)++ if time_range_start >= time_range_end:+ logger.info(+ "web_goals_lazy_precompute_empty_range",+ team_id=team_id,+ time_range_start=time_range_start.isoformat(),+ time_range_end=time_range_end.isoformat(),+ )+ return None++ logger.info(+ "web_goals_lazy_precompute_started",+ team_id=team_id,+ action_count=len(actions),+ time_range_start=time_range_start.isoformat(),+ time_range_end=time_range_end.isoformat(),+ time_range_days=(time_range_end - time_range_start).days,+ )++ ensure_started = time.perf_counter()+ result = ensure_web_goals_precomputed(+ runner=runner,+ actions=actions,+ time_range_start=time_range_start,+ time_range_end=time_range_end,+ )+ ensure_duration_ms = int((time.perf_counter() - ensure_started) * 1000)+ logger.info(+ "web_goals_lazy_precompute_ensure_done",+ team_id=team_id,+ job_count=len(result.job_ids),+ ensure_duration_ms=ensure_duration_ms,+ )++ if not result.job_ids or not result.ready:+ return None++ job_ids: list[str] = [str(jid) for jid in result.job_ids]++ previous_start_utc: Optional[datetime] = None+ previous_end_utc: Optional[datetime] = None+ if runner.query_compare_to_date_range is not None:+ prev_from = runner.query_compare_to_date_range.date_from()+ prev_to = runner.query_compare_to_date_range.date_to()+ if prev_from is not None and prev_to is not None:+ previous_start_utc = prev_from.astimezone(UTC)+ previous_end_utc = prev_to.astimezone(UTC)+ prev_range_start = floor_utc_day(previous_start_utc)+ prev_range_end = ceil_utc_day(previous_end_utc)+ if prev_range_start < prev_range_end:+ if ensure_duration_ms >= ENSURE_BUDGET_MS:+ logger.info(+ "web_goals_lazy_precompute_compare_budget_exceeded",+ team_id=team_id,+ elapsed_ms=ensure_duration_ms,+ budget_ms=ENSURE_BUDGET_MS,+ )+ return None+ prev_ensure_started = time.perf_counter()+ prev_result = ensure_web_goals_precomputed(+ runner=runner,+ actions=actions,+ time_range_start=prev_range_start,+ time_range_end=prev_range_end,+ )+ ensure_duration_ms += int((time.perf_counter() - prev_ensure_started) * 1000)+ if not prev_result.ready:+ logger.info(+ "web_goals_lazy_precompute_previous_not_ready",+ team_id=team_id,+ prev_job_count=len(prev_result.job_ids),+ )+ return None+ job_ids.extend(str(jid) for jid in prev_result.job_ids)++ action_ids = [DENOMINATOR_ACTION_ID, *[int(a.id) for a in actions]]+ read_started = time.perf_counter()+ rows = execute_read_query(+ runner=runner,+ job_ids=job_ids,+ action_ids=action_ids,+ current_start_utc=current_start_utc,+ current_end_utc=current_end_utc,+ previous_start_utc=previous_start_utc,+ previous_end_utc=previous_end_utc,+ )+ read_duration_ms = int((time.perf_counter() - read_started) * 1000)+ total_duration_ms = int((time.perf_counter() - overall_started) * 1000)++ if not rows:+ WEB_GOALS_LAZY_EMPTY.inc()+ logger.info(+ "web_goals_lazy_precompute_no_rows",+ team_id=team_id,+ job_count=len(result.job_ids),+ )+ return None++ denominator = {"current": 0, "previous": 0}+ per_action: dict[int, dict[str, int]] = {}+ for action_id, current_total, previous_total, current_unique, previous_unique in rows:+ if int(action_id) == DENOMINATOR_ACTION_ID:+ denominator = {"current": int(current_unique), "previous": int(previous_unique)}+ continue+ per_action[int(action_id)] = {+ "current_total": int(current_total),+ "previous_total": int(previous_total),+ "current_unique": int(current_unique),+ "previous_unique": int(previous_unique),+ }++ logger.info(+ "web_goals_lazy_precompute_completed",+ team_id=team_id,+ job_count=len(result.job_ids),+ rows_returned=len(rows),+ ensure_duration_ms=ensure_duration_ms,+ read_duration_ms=read_duration_ms,+ total_duration_ms=total_duration_ms,+ )+ return {+ "actions": actions,+ "denominator": denominator,+ "per_action": per_action,+ }+ except Exception as exc:+ WEB_GOALS_LAZY_FAILED.labels(error_type=_bucket_error_label(exc)).inc()+ logger.exception(+ "web_goals_lazy_precompute_failed",+ team_id=team_id,+ error_type=type(exc).__name__,+ total_duration_ms=int((time.perf_counter() - overall_started) * 1000),+ )+ return Nonediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4f2cdfda62e1..3796d833cda0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -9317,6 +9317,32 @@ export namespace Schemas {types?: unknown[] | null;}+ export interface Response7 {+ columns?: unknown[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ hasMore?: boolean | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ limit?: number | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ offset?: number | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: unknown[];+ samplingRate?: SamplingRate | null;+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ types?: unknown[] | null;+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null;+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null;+ }+export interface WebVitalsPathBreakdownResultItem {path: string;value: number;@@ -9899,7 +9925,7 @@ export namespace Schemas {types?: unknown[] | null;}- export type DataTableNodeResponse = { [key: string]: unknown } | Response | Response1 | Response2 | Response3 | Response4 | Response5 | Response6 | Response8 | Response9 | Response10 | Response11 | Response12 | Response13 | Response14 | Response15 | Response16 | Response18 | Response19 | Response20 | Response21 | Response22 | Response23 | Response24 | Response25 | Response26 | null;+ export type DataTableNodeResponse = { [key: string]: unknown } | Response | Response1 | Response2 | Response3 | Response4 | Response5 | Response6 | Response7 | Response8 | Response9 | Response10 | Response11 | Response12 | Response13 | Response14 | Response15 | Response16 | Response18 | Response19 | Response20 | Response21 | Response22 | Response23 | Response24 | Response25 | Response26 | null;export type DataTableNodeViewPropsContextType = typeof DataTableNodeViewPropsContextType[keyof typeof DataTableNodeViewPropsContextType];@@ -10212,6 +10238,10 @@ export namespace Schemas {/** Measured timings for different parts of the query generation process */timings?: QueryTiming[] | null;types?: unknown[] | null;+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null;+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null;}export interface WebGoalsQuery {@@ -10239,6 +10269,8 @@ export namespace Schemas {samplingFactor?: number | null;tags?: QueryLogTags | null;useSessionsTable?: boolean | null;+ /** Opt this specific query into the web_goals_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. * */+ useWebAnalyticsPrecompute?: boolean | null;/** version of the node, used for schema migrations */version?: number | null;}@@ -33772,6 +33804,32 @@ export namespace Schemas {types?: unknown[] | null;}+ export interface QueryResponseAlternative26 {+ columns?: unknown[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ hasMore?: boolean | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ limit?: number | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ offset?: number | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: unknown[];+ samplingRate?: SamplingRate | null;+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ types?: unknown[] | null;+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null;+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null;+ }+export interface QueryResponseAlternative27 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -34149,6 +34207,32 @@ export namespace Schemas {types?: unknown[] | null;}+ export interface QueryResponseAlternative46 {+ columns?: unknown[] | null;+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */+ error?: string | null;+ hasMore?: boolean | null;+ /** Generated HogQL query. */+ hogql?: string | null;+ limit?: number | null;+ /** Modifiers used when performing the query */+ modifiers?: HogQLQueryModifiers | null;+ offset?: number | null;+ /** Query status indicates whether next to the provided data, a query is still running. */+ query_status?: QueryStatus | null;+ /** The date range used for the query */+ resolved_date_range?: ResolvedDateRangeResponse | null;+ results: unknown[];+ samplingRate?: SamplingRate | null;+ /** Measured timings for different parts of the query generation process */+ timings?: QueryTiming[] | null;+ types?: unknown[] | null;+ /** Whether the response was served from the lazy precompute path. */+ usedLazyPrecompute?: boolean | null;+ /** Whether the response was served from a precomputed table. */+ usedPreAggregatedTables?: boolean | null;+ }+export interface QueryResponseAlternative47 {/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */error?: string | null;@@ -34920,7 +35004,7 @@ export namespace Schemas {timings?: QueryTiming[] | null;}- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93;+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | unknown | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative51 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative55 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative81 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93;export interface QueryStatusResponse {query_status: QueryStatus;