: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
docs(analytics-platform): document concurrent first-reader INSERT race in lazy computation (#59300)
Lucas Ricoyc0ac75245419
diff --git a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.mdindex 1d4e3014dab5..80a00b6fc420 100644--- a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md+++ b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md@@ -311,3 +311,35 @@ Not applicable to PostHog (fully self-hosted), but for reference:| D: Write to sharded tables | Inherent | None | None | High (architectural change) || E: `in_order` load balancing | Practical (not formal) | None | None | Low (per-query settings) || E + quorum: `in_order` + `insert_quorum` | Practical (covers failover) | +20-100ms | None | Low (per-query settings, no serialization) |++## Concurrent first-readers: redundant INSERTs (by design)++The partial unique index `unique_pending_job_per_range` (migration `0004_unique_pending_job_index.py`) is `WHERE status='pending'`. Once a job transitions PENDING → READY the row is no longer in the index, so a second CREATE for the same `(team_id, query_hash, range)` no longer raises `IntegrityError`. This is intentional: a stale READY job past its TTL should be replaceable.++Combined with the executor's `for range in ttl_ranges` loop, this produces a wasted-INSERT pattern under concurrent first-readers on the **shortest-TTL** ranges (today / yesterday in `LAZY_TTL_SECONDS`):++```text+T=0.000 N threads enter executor. All call find_existing_jobs → []. All compute+ the same stale ttl_ranges = [today, yesterday, 7-day].++T=0.005 3 threads each WIN a different range (one PENDING per range via the+ partial unique index). The other (N-3) threads hit IntegrityError on+ all 3 ranges and loop back to wait on pubsub.++T~0.5 The 3 winners each finish their CH INSERT (~470ms) and mark READY+ within a few ms of each other.++T~0.5+ Each winner *continues its for-loop* to iter 2 and iter 3. Because+ the other winners just transitioned their rows out of the partial+ unique index (`status='pending'` → `status='ready'`), the CREATE for+ the other ranges no longer collides. Each winner runs a *second*+ INSERT for a range already covered by a fresh READY job.+```++Observed in a 10-concurrent-first-readers stress test of the `web_overview_query` lazy path: **6 jobs in PG for 3 unique ranges** (2-3 duplicate READY rows on the short-TTL today/yesterday ranges). The 7-day range, with its longer INSERT span and only one race participant per iter slot, produced exactly 1 job.++**Why this isn't a correctness bug:** the read path calls `filter_overlapping_jobs()` ([executor:383](lazy_computation_executor.py)) which deterministically keeps only the most-recently-created READY job per range. All concurrent callers therefore receive byte-identical results. The duplicate rows expire on their normal TTL or get compacted away by the ReplacingMergeTree.++**Cost:** ~2× redundant INSERTs on the shortest-TTL ranges under cold-cache load. At low concurrency this is invisible. At high concurrency (e.g. dashboard-load fan-out across multiple browser tabs) it doubles CH write load for those ranges only. Mitigated naturally once the cache is primed — a second wave against the same range produces zero new INSERTs.++**Possible fix (not applied):** `break` out of the for-loop after a successful CREATE+INSERT, returning control to the while-loop so `find_existing_jobs` re-runs and `ttl_ranges` gets recomputed against current state. Trade-off: each thread does at most one INSERT per round-trip (slower wall time when one thread legitimately owns multiple ranges), but eliminates the race. See `test_for_loop_creates_duplicate_after_peer_completes_mid_loop` in `tests/test_lazy_computation_executor.py` for the deterministic reproduction.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 80c65484f1a4..6bf368014ce3 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@@ -1393,6 +1393,92 @@ class TestRaceConditionHandling(BaseTest):assert result.ready is Trueassert existing_pending.id in result.job_ids+ def test_for_loop_creates_duplicate_after_peer_completes_mid_loop(self):+ """Wasted-INSERT pattern under concurrent first-readers — documented in CONSISTENCY.md.++ The executor's `for range in ttl_ranges` loop iterates over a snapshot of+ missing ranges computed once per while-loop tick. If a peer thread marks+ a job READY for a later range *while* this thread is mid-loop, the+ partial unique index `WHERE status='pending'` no longer blocks our+ CREATE — and we end up with a second READY job for a range already+ covered by the peer.++ `filter_overlapping_jobs` keeps reads consistent (it picks the most+ recently created READY per range), so this is a wasted-INSERT cost+ rather than a correctness bug.+ """+ query = self._make_computation_query()+ query_info = QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC")+ query_hash = compute_query_hash(query_info)++ range_a_start = datetime(2024, 1, 1, tzinfo=UTC)+ range_b_start = datetime(2024, 1, 2, tzinfo=UTC)+ range_b_end = datetime(2024, 1, 3, tzinfo=UTC)++ # Distinct TTLs so split_ranges_by_ttl keeps the two days as separate+ # for-loop iterations — matches the today/yesterday/7-day shape that+ # web_overview_lazy_precompute uses in prod.+ schedule = TtlSchedule(+ rules=[(range_b_start, 100)], # range_b: 100s+ default_ttl_seconds=200, # range_a: 200s+ )++ # Simulate the peer thread by injecting a fresh READY job for range_b+ # *during* this executor's insert for range_a — the moment the partial+ # unique index releases its hold on range_b would be when the peer+ # marks its own job READY.+ peer_ready: list[PreaggregationJob] = []++ def mock_insert_with_peer(team, job):+ if job.time_range_start == range_a_start:+ peer_job = PreaggregationJob.objects.create(+ team=self.team,+ query_hash=query_hash,+ time_range_start=range_b_start,+ time_range_end=range_b_end,+ status=PreaggregationJob.Status.READY,+ computed_at=django_timezone.now(),+ expires_at=django_timezone.now() + timedelta(days=7),+ )+ peer_ready.append(peer_job)++ executor = LazyComputationExecutor(+ wait_timeout_seconds=2.0,+ poll_interval_seconds=0.05,+ ttl_schedule=schedule,+ )+ result = executor.execute(+ team=self.team,+ query_info=query_info,+ start=range_a_start,+ end=range_b_end,+ run_insert=mock_insert_with_peer,+ )++ # Peer injection happened exactly once+ assert len(peer_ready) == 1++ # Two READY jobs exist for range_b — the peer's and ours from iter 2+ jobs_for_b = PreaggregationJob.objects.filter(+ team=self.team,+ query_hash=query_hash,+ time_range_start=range_b_start,+ time_range_end=range_b_end,+ status=PreaggregationJob.Status.READY,+ )+ assert jobs_for_b.count() == 2, (+ "Expected wasted duplicate READY job for range_b — see CONSISTENCY.md "+ "section 'Concurrent first-readers: redundant INSERTs (by design)'"+ )++ # filter_overlapping_jobs picks the most-recently-created READY per+ # range, so the duplicate is invisible to the read path.+ assert result.ready+ our_b_job = jobs_for_b.exclude(id=peer_ready[0].id).first()+ assert our_b_job is not None+ assert our_b_job.id in result.job_ids+ assert peer_ready[0].id not in result.job_ids, "filter_overlapping_jobs should drop the older peer READY job"+def test_unique_constraint_prevents_duplicate_pending_jobs(self):query = self._make_computation_query()query_info = QueryInfo(query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC")