: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): skip replica quorum on background precompute inserts (#103220)
Lucas Ricoy876f5325ebfc
diff --git a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.mdindex adb33d7f1dc1..32043c9dafe7 100644--- a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md+++ b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md@@ -56,6 +56,8 @@ Only works with ReplicatedMergeTree family tables, not Distributed tables direct**Availability risk with `'auto'`**: quorum = `(num_replicas / 2) + 1`, so with 2 replicas quorum is 2 (all). If one replica goes down, no quorum INSERTs can succeed — they all fail with `TOO_FEW_LIVE_REPLICAS` after `insert_quorum_timeout` (default 60s). With 3 replicas quorum is 2, so one replica can be down and INSERTs still succeed. This means quorum trades write availability for consistency: in a 2-replica setup, a single replica failure blocks all computation writes (for up to 60 seconds before the timeout error). The computation executor's retry logic would handle the error, but no new precomputed data can be written until the replica recovers. Without quorum, the system degrades gracefully — writes go to the remaining replica and reads work, just without the read-your-own-writes guarantee.+Because of this trade, quorum is opt-out per caller: `ensure_precomputed(read_after_write=False)` drops it for builds whose readers arrive later (background warmers, revalidation tasks). Those callers get nothing from the read-your-own-writes guarantee, so for them quorum is pure availability risk: replicas count against quorum by ZooKeeper registration, not liveness, so a dead-but-registered replica (mid-upscale, unrevived node) fails every quorum INSERT until someone repairs the cluster metadata. `web_ensure_precomputed` defaults `read_after_write` to `False`, so every web analytics build skips quorum unless a caller overrides it. Callers that SELECT the rows in the same request (experiments) keep the framework default of `True`. The residual same-call race (build, then read before the part replicates) is handled with a settle wait: `LazyComputationResult.freshly_built` marks coverage that landed during the call, and `ensure_precomputed` sleeps `PREAGGREGATION_REPLICATION_SETTLE_SECONDS` (1s, above the observed sub-second replica lag) before returning it to a quorum-skipping caller, so the caller's immediate read-back cannot cache a partial result.+Sources:- [ClickHouse settings docs](https://clickhouse.com/docs/operations/settings/settings#insert_quorum)diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex 730b05323545..3197ef084d95 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -95,6 +95,11 @@ PREAGGREGATION_INSERT_QUORUM: str | int = 0 if TEST or DEBUG else "auto"# distinct from 159 TIMEOUT_EXCEEDED (max_execution_time), which stays non-retryable.PREAGGREGATION_INSERT_QUORUM_TIMEOUT_MS = 2 * 1000+# How long a quorum-skipping caller waits after building before its own read, so the+# parts can replicate (observed lag between colocated replicas is under a second).+# Zero in tests and local dev: the single-node ClickHouse there has no replica to lag.+PREAGGREGATION_REPLICATION_SETTLE_SECONDS: float = 0.0 if TEST or DEBUG else 1.0+# Mirrors the `lazy_computation.executed` structured log so the same outcomes# (`success` / `timeout` / `non_retryable_error` / `max_retries_exceeded`) are@@ -166,7 +171,7 @@ LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL = Counter()-def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False) -> dict:+def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False, read_after_write: bool = True) -> dict:"""Build ClickHouse settings for preaggregation INSERT queries.Starts from the same HogQLGlobalSettings defaults that execute_hogql_query@@ -176,13 +181,20 @@ def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False) -> dict:GROUP BY hash table can grow large (high-cardinality breakdowns), and mostkinds never approach the threshold, so callers enable it deliberately ratherthan paying for it everywhere.++ `read_after_write=False` drops the replica-quorum wait. Quorum's only job is+ the read-your-own-writes edge case: a SELECT issued right after this INSERT+ landing on a replica the part hasn't reached yet. A caller whose reads come+ minutes later (background builders) gets no consistency from it — only the+ failure mode where a downed or stale-registered replica turns every build+ into TOO_FEW_LIVE_REPLICAS until the cluster is repaired."""settings = get_default_hogql_global_settings(team_id=team_id).model_dump(exclude_none=True)settings.pop("readonly", None) # INSERTs need write accesssettings.update({"max_execution_time": HOGQL_INCREASED_MAX_EXECUTION_TIME,- "insert_quorum": PREAGGREGATION_INSERT_QUORUM,+ "insert_quorum": PREAGGREGATION_INSERT_QUORUM if read_after_write else 0,"insert_quorum_timeout": PREAGGREGATION_INSERT_QUORUM_TIMEOUT_MS,# The executor marks a job READY as soon as the INSERT returns, so rows must be on the# shards by then — not sitting in the initiator's async distribution queue, where they@@ -574,7 +586,7 @@ class LazyComputationQuery:cache_key_context: dict[str, str] | None = None-@dataclass+@dataclass(frozen=True)class LazyComputationResult:"""Result of executing lazy computation jobs."""@@ -588,6 +600,13 @@ class LazyComputationResult:# executor's serve-stale grace instead of recomputing inline. The data is complete# but up to (TTL + grace) old; the caller decides whether to surface that.stale: bool = False+ # True when part of the coverage landed during this call (built inline, or waited on+ # another executor's build). Callers that skipped the replica quorum+ # (read_after_write=False) must not read these jobs in the same request: the parts+ # may not have replicated to the read replica yet, and a wrong result read now would+ # be cached. Serving live once and letting the next request use the jobs is the+ # intended reaction.+ freshly_built: bool = Falsedef compute_query_hash(query_info: LazyComputationQuery) -> str:@@ -1424,7 +1443,11 @@ class LazyComputationExecutor:final_jobs = find_existing_jobs(team, query_hash, start, end)final_fresh = self._filter_by_freshness(final_jobs)final_ready = filter_overlapping_jobs([j for j in final_fresh if j.status == PreaggregationJob.Status.READY])- result = LazyComputationResult(ready=True, job_ids=[j.id for j in final_ready])+ result = LazyComputationResult(+ ready=True,+ job_ids=[j.id for j in final_ready],+ freshly_built=jobs_created > 0 or bool(waited_job_ids),+ )_log_execution("success", result)return result@@ -1562,6 +1585,7 @@ def ensure_precomputed(empty_result_max_age_seconds: int | None = None,end_is_data_horizon: bool = False,cache_key_context: dict[str, str] | None = None,+ read_after_write: bool = True,) -> LazyComputationResult:"""Ensure lazy-computed data exists for the given query and time range.@@ -1633,6 +1657,14 @@ def ensure_precomputed(into its own filters, so it stores no rows past it. Job claimsthen clamp to a historical end instead of claiming the fullfinal day. See LazyComputationExecutor.execute.+ read_after_write: Set False when no caller SELECTs the inserted rows in the+ same request that ran this ensure (background builders whose+ readers arrive minutes later). Skips the replica-quorum wait on+ the INSERT, so builds keep succeeding while a replica is down+ or stale-registered; the cost is that a reader can miss the+ newest parts until replication catches up — usually fast, but+ with no guaranteed bound. The post-build settle wait covers the+ builder's own read-back; later readers accept the residual risk.Returns:ComputationResult with job_ids that can be used to query the data@@ -1717,7 +1749,7 @@ def ensure_precomputed(sync_execute(insert_sql,values,- settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk),+ settings=_get_insert_settings(t.id, spill_to_disk=spill_to_disk, read_after_write=read_after_write),))@@ -1739,7 +1771,7 @@ def ensure_precomputed(stale_while_revalidate_seconds=stale_while_revalidate_seconds,run_inserts=run_inserts,)- return executor.execute(+ result = executor.execute(team,query_info,time_range_start,@@ -1747,6 +1779,13 @@ def ensure_precomputed(run_insert=_run_manual_insert,end_is_data_horizon=end_is_data_horizon,)+ if not read_after_write and result.ready and result.freshly_built and PREAGGREGATION_REPLICATION_SETTLE_SECONDS:+ # The coverage landed during this call and quorum was skipped, so the parts may+ # not have reached the caller's read replica yet. Waiting out the replication+ # lag here is what keeps the caller's immediate read-back (the warmer warming+ # the query cache) from caching a partial result for the full TTL.+ time.sleep(PREAGGREGATION_REPLICATION_SETTLE_SECONDS)+ return resultdef _resolve_insert_query(insert_query: str | ast.SelectQuery, placeholders: dict[str, ast.Expr]) -> ast.SelectQuery:diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.pyindex 63db051ca624..447e2410252f 100644--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py@@ -2350,6 +2350,8 @@ class TestComputationExecutorExecute(BaseTest):assert result.ready is Trueassert fresh_job.id in result.job_ids+ # Coverage pre-existed, so a quorum-skipping caller may read it in-request.+ assert result.freshly_built is Falsedef test_returned_jobs_cover_range_when_overlap_filter_evicts_broad_job(self):query_info, query_hash = self._make_query_info()@@ -3469,6 +3471,18 @@ class TestInsertSettings(BaseTest):assert settings["max_execution_time"] == HOGQL_INCREASED_MAX_EXECUTION_TIMEassert "readonly" not in settings+ def test_background_builder_skips_replica_quorum(self):+ # TEST/DEBUG already force the quorum constant to 0, so pin the production+ # value to make the branch observable: without it a downed or+ # stale-registered replica fails every background build with+ # TOO_FEW_LIVE_REPLICAS until the cluster is repaired.+ with patch(+ f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.PREAGGREGATION_INSERT_QUORUM",+ "auto",+ ):+ assert _get_insert_settings(self.team.pk)["insert_quorum"] == "auto"+ assert _get_insert_settings(self.team.pk, read_after_write=False)["insert_quorum"] == 0+class TestInsertSettingsAppliedToInserts(BaseTest):INSERT_QUERY = """@@ -3483,23 +3497,76 @@ class TestInsertSettingsAppliedToInserts(BaseTest):GROUP BY time_window_start"""- def test_manual_insert_path_passes_insert_settings_to_clickhouse(self):- with patch(- "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute"- ) as mock_execute:+ @parameterized.expand(+ [+ ("default_read_after_write", {}, "auto"),+ ("background_no_quorum", {"read_after_write": False}, 0),+ ]+ )+ def test_manual_insert_path_passes_insert_settings_to_clickhouse(self, _name, extra_kwargs, expected_quorum):+ # The quorum constant is patched to its production value because TEST forces+ # it to 0, which would make both parameter rows assert the same settings.+ with (+ patch(+ f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.PREAGGREGATION_INSERT_QUORUM",+ "auto",+ ),+ patch(+ f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute"+ ) as mock_execute,+ ):result = ensure_precomputed(team=self.team,insert_query=self.INSERT_QUERY,time_range_start=datetime(2024, 1, 1, tzinfo=UTC),time_range_end=datetime(2024, 1, 2, tzinfo=UTC),+ **extra_kwargs,)+ expected_settings = _get_insert_settings(self.team.pk, **extra_kwargs)assert result.ready is True# Bind the assertion to the INSERT specifically, so the test doesn't break (or silently# check the wrong call) if the executor flow ever issues other queries around the insert.insert_calls = [c for c in mock_execute.call_args_list if c.args[0].lstrip().startswith("INSERT")]assert len(insert_calls) == 1 # one missing range -> one INSERT- assert insert_calls[0].kwargs["settings"] == _get_insert_settings(self.team.pk)+ assert insert_calls[0].kwargs["settings"] == expected_settings+ assert insert_calls[0].kwargs["settings"]["insert_quorum"] == expected_quorum+ # The coverage landed in this call, so quorum-skipping callers must not read it yet.+ assert result.freshly_built is True++ @parameterized.expand(+ [+ ("quorum_skipped_waits_for_replication", {"read_after_write": False}, True),+ ("quorum_insert_needs_no_wait", {}, False),+ ]+ )+ def test_settle_wait_after_quorumless_build(self, _name, extra_kwargs, expect_sleep):+ # Without the wait, the builder's immediate read-back can land on a replica the+ # quorum-less parts have not reached and cache a partial result for the TTL.+ with (+ patch(+ f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.PREAGGREGATION_REPLICATION_SETTLE_SECONDS",+ 1.0,+ ),+ patch(+ f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.time.sleep"+ ) as mock_sleep,+ patch(f"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute"),+ ):+ result = ensure_precomputed(+ team=self.team,+ insert_query=self.INSERT_QUERY,+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),+ **extra_kwargs,+ )++ assert result.ready is True+ assert result.freshly_built is True+ if expect_sleep:+ mock_sleep.assert_called_once_with(1.0)+ else:+ mock_sleep.assert_not_called()def test_ast_insert_path_passes_insert_settings_to_clickhouse(self):job = PreaggregationJob.objects.create(diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.pyindex c7d2201d9149..a54b92f15318 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py@@ -742,6 +742,22 @@ class TestWebEnsurePrecomputed(BaseTest):web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None)assert is_team_oom_pinned(self.team.pk) is False+ @parameterized.expand(+ [+ ("defaults_to_no_quorum", {}, False),+ ("explicit_override_survives", {"read_after_write": True}, True),+ ]+ )+ @mock.patch(f"{_COMMON}.ensure_precomputed")+ def test_builds_never_require_replica_quorum(self, _name, extra_kwargs, expected, mock_ensure):+ # No web analytics build is read back in-request, so the wrapper must opt out of+ # the framework's quorum wait: with it, one downed aux replica fails every build+ # (TOO_FEW_LIVE_REPLICAS) and precompute serving collapses region-wide. An+ # explicit caller override must survive — the default is a setdefault, not a stamp.+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[], memory_exceeded=False)+ web_ensure_precomputed(team=self.team, ttl_seconds={"default": 3600}, table=None, **extra_kwargs)+ assert mock_ensure.call_args.kwargs["read_after_write"] is expected+@mock.patch(f"{_COMMON}.ensure_precomputed")def test_pinned_team_restamps_prebuilt_schedule(self, mock_ensure):# A caller may pass an already-built TtlSchedule (ensure_precomputed accepts one);diff --git a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.pyindex b21eeab54567..74b0a3edda77 100644--- a/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py+++ b/products/web_analytics/backend/hogql_queries/web_dimensional_precompute.py@@ -316,6 +316,7 @@ def ensure_web_stats_dimensional_precomputed(table=LazyComputationTable.WEB_STATS_DIMENSIONAL_PREAGGREGATED,placeholders=_base_placeholders(),query_type="web_stats_dimensional_insert",+ read_after_write=False,)@@ -333,4 +334,5 @@ def ensure_web_bounces_dimensional_precomputed(table=LazyComputationTable.WEB_BOUNCES_DIMENSIONAL_PREAGGREGATED,placeholders=_base_placeholders(),query_type="web_bounces_dimensional_insert",+ read_after_write=False,)diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.pyindex 8227c90068d7..a6485e1eb863 100644--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py@@ -650,6 +650,11 @@ def web_ensure_precomputed(# must not pay for its own backfill.if "run_inserts" not in kwargs:kwargs["run_inserts"] = background+ # No web analytics build is read back in the same request: user reads either hit+ # covering READY jobs or fall back to the live query, and builders (warmer,+ # revalidation) run ahead of demand. Replica quorum therefore buys no consistency+ # here — it only turns a downed aux replica into a total build outage.+ kwargs.setdefault("read_after_write", False)# Per-team distinct-shape backstop. Only build paths can mint a new namespace, so this# only bites there (a user read is already run_inserts=False). At the ceiling, a *new*# shape drops back to a check-only pass — not ready → the caller serves live — instead