: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
fix(web-analytics): remove pathkey mirror dual-write from paths read path (#69783)
Lucas Ricoyda6720628472
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 4dcb217e7775..74c8f08a184e 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1090,16 +1090,3 @@ WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS: list[int] = [get_from_env("WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS))]--# Teams whose PATHS precompute reads also dual-write into the colocated-# `web_stats_paths_preaggregated_pathkey` table so its read layout can be-# A/B-compared (PR #64948). Deliberately narrow — only the named teams pay the-# extra mirror write — and defaults to the Cloud dogfooding team (project 2)-# only, same as the precompute lists above. Temporary; removed once the-# comparison concludes.-WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS: list[int] = [- int(team_id)- for team_id in get_list(- get_from_env("WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS", _LAZY_PRECOMPUTE_DEFAULT_TEAM_IDS)- )-]diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.pyindex 99393f0d4132..7b2a0d81ce4e 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_stats_paths_lazy_precompute.py@@ -765,64 +765,3 @@ class TestWebStatsPathsLazyPrecompute(ClickhouseTestMixin, APIBaseTest):with override_settings(WEB_ANALYTICS_LAZY_PRECOMPUTE_UNRESTRICTED_TEAM_IDS=[self.team.pk]):self._run(self._build_query(opt_in_precompute=False))assert PreaggregationJob.objects.filter(team_id=self.team.pk).count() == 0-- @parameterized.expand([("allowlisted", True), ("not_allowlisted", False)])- @freeze_time("2024-01-15T12:00:00Z")- def test_pathkey_mirror_runs_only_for_allowlisted_teams(self, _name: str, allowlisted: bool) -> None:- import products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute as mod-- job_id = uuid.uuid4()- mirror_team_ids = [self.team.pk] if allowlisted else []- with (- self._enable_lazy(),- override_settings(WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS=mirror_team_ids),- patch.object(- mod,- "ensure_web_stats_paths_precomputed",- return_value=LazyComputationResult(ready=True, job_ids=[job_id]),- ),- patch.object(mod, "execute_read_query", return_value=[]),- patch.object(mod, "mirror_jobs_to_pathkey") as mock_mirror,- ):- runner = WebStatsTableQueryRunner(team=self.team, query=self._build_query())- mod.execute_lazy_precomputed_read(runner, sort_column="visitors", sort_direction="DESC", limit=11, offset=0)-- if allowlisted:- mock_mirror.assert_called_once_with(team_id=self.team.pk, job_ids=[str(job_id)])- else:- mock_mirror.assert_not_called()-- def test_mirror_jobs_to_pathkey_copies_rows_between_tables(self) -> None:- from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey-- job_id = uuid.uuid4()- with patch(- "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute"- ) as mock_exec:- mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[str(job_id)])-- mock_exec.assert_called_once()- sql, params = mock_exec.call_args.args- assert "INSERT INTO web_stats_paths_preaggregated_pathkey" in sql- assert "FROM web_stats_paths_preaggregated" in sql- assert params["team_id"] == self.team.pk- assert params["job_ids"] == [job_id] # coerced from str back to UUID-- def test_mirror_jobs_to_pathkey_swallows_errors(self) -> None:- from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey-- with patch(- "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute",- side_effect=ValueError("boom"),- ):- # Must not raise — a failed mirror cannot affect the primary read.- mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[str(uuid.uuid4())])-- def test_mirror_jobs_to_pathkey_noop_on_empty(self) -> None:- from products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute import mirror_jobs_to_pathkey-- with patch(- "products.web_analytics.backend.hogql_queries.web_stats_paths_lazy_precompute.sync_execute"- ) as mock_exec:- mirror_jobs_to_pathkey(team_id=self.team.pk, job_ids=[])- mock_exec.assert_not_called()diff --git a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.pyindex cf908b9bcfe0..bd1babe026da 100644--- a/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_stats_paths_lazy_precompute.py@@ -11,12 +11,9 @@ attributing bounce to sessions that entered on the path."""import time-import uuidfrom datetime import UTC, datetimefrom typing import TYPE_CHECKING, Optional-from django.conf import settings-import structlogfrom prometheus_client import Counter, Histogram@@ -31,13 +28,7 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.clickhouse.client import sync_execute-from posthog.clickhouse.preaggregation.web_stats_paths_preaggregated_sql import (- DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE,- DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_TABLE,-)-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries, tags_context-from posthog.settings import DEBUG, TEST+from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (LazyComputationResult,@@ -101,15 +92,6 @@ WEB_STATS_PATHS_LAZY_ROWS = Histogram(buckets=(1, 10, 100, 500, 1000, 2500, 5000, 7500, 10000, float("inf")),)-# Best-effort mirror of the precomputed rows into the colocated `_pathkey` table-# variant (PR #64948) so its read layout can be A/B-compared. Failures here never-# affect the primary read, so we only count them.-WEB_STATS_PATHS_PATHKEY_MIRROR_FAILED = Counter(- "web_stats_paths_pathkey_mirror_failed_total",- "Best-effort copies into web_stats_paths_preaggregated_pathkey that failed, by error class.",- ["error_type"],-)-class WrongBreakdown(LazyPrecomputeIneligible):pass@@ -457,59 +439,6 @@ def ensure_web_stats_paths_precomputed()-# Columns shared by both tables, in declaration order. The pathkey table mirrors-# the original schema exactly, so the copy is a straight column-for-column INSERT.-_PATHKEY_MIRROR_COLUMNS = (- "team_id, job_id, time_window_start, breakdown_value, "- "uniq_users_state, sum_pageviews_state, avg_bounce_state, computed_at, expires_at"-)--# Mirror the primary insert's durability settings (quorum + synchronous-# distribution), disabled on single-node TEST/DEBUG like the executor does.-_PATHKEY_MIRROR_SETTINGS: dict = {- "insert_distributed_sync": 1,- "insert_quorum": 0 if TEST or DEBUG else "auto",- "load_balancing": "in_order",-}---def mirror_jobs_to_pathkey(*, team_id: int, job_ids: list[str]) -> None:- """Best-effort copy of precomputed PATHS rows for `job_ids` into the colocated- pathkey table (PR #64948). Idempotent (ReplacingMergeTree) and never raises —- a failed mirror must not affect the primary read."""- if not job_ids:- return-- primary = DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_TABLE()- pathkey = DISTRIBUTED_WEB_STATS_PATHS_PREAGGREGATED_PATHKEY_TABLE()- sql = f"""- INSERT INTO {pathkey} ({_PATHKEY_MIRROR_COLUMNS})- SELECT {_PATHKEY_MIRROR_COLUMNS}- FROM {primary}- WHERE team_id = %(team_id)s AND job_id IN %(job_ids)s- """- try:- with tags_context(- team_id=team_id,- product=Product.WEB_ANALYTICS,- feature=Feature.QUERY,- query_type="web_stats_paths_pathkey_mirror_insert",- ):- sync_execute(- sql,- {"team_id": team_id, "job_ids": [uuid.UUID(jid) for jid in job_ids]},- settings=_PATHKEY_MIRROR_SETTINGS,- )- except Exception as exc:- WEB_STATS_PATHS_PATHKEY_MIRROR_FAILED.labels(error_type=_bucket_error_label(exc)).inc()- logger.warning(- "web_stats_paths_pathkey_mirror_failed",- team_id=team_id,- job_count=len(job_ids),- error_type=type(exc).__name__,- )--# Returns one row per breakdown_value with (current, previous) period pairs# plus a fill-fraction column for the bar visualisation:# breakdown_value, visitors, prev_visitors, views, prev_views, bounce_rate,@@ -830,13 +759,6 @@ def execute_lazy_precomputed_read()read_duration_ms = int((time.perf_counter() - read_started) * 1000)- # Best-effort dual-write: mirror these jobs' rows into the colocated pathkey- # table for A/B read comparison. Narrowly scoped to the allowlisted teams- # (default: Cloud project 2) so only they pay the extra mirror write. After- # the read so it never adds latency to the user's response; swallows errors.- if team_id in settings.WEB_STATS_PATHS_PREAGG_MIRROR_PATHKEY_TEAM_IDS:- mirror_jobs_to_pathkey(team_id=team_id, job_ids=job_ids)-total_duration_ms = int((time.perf_counter() - overall_started) * 1000)rows_returned = len(rows) if rows else 0