Skip to content

: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.

fix(analytics-platform): quiet and count lazy job create races (#83927)

Lucas Ricoyd47c635de71d
diff --git a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
index 4301eeba2357..adb33d7f1dc1 100644
--- a/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
+++ b/products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
@@ -336,7 +336,7 @@ Not applicable to PostHog (fully self-hosted), but for reference:
## 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.
+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 collides. 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`):
@@ -345,8 +345,8 @@ T=0.000 N threads enter executor. All call find_existing_jobs → []. All compu
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.
+ partial unique index). The other (N-3) threads lose the create race on
+ all 3 ranges (ON CONFLICT DO NOTHING) 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.
@@ -365,3 +365,13 @@ Observed in a 10-concurrent-first-readers stress test of the `web_overview_query
**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.
+
+## Expired-but-PENDING rows: blocked windows (known limitation)
+
+`find_existing_jobs` filters on `expires_at >= now`, but the `unique_pending_job_per_range` index only keys on `status='pending'`. A PENDING row whose `expires_at` has passed is therefore invisible to readers while still holding the create slot for its window. Rows land in that state when the owning executor dies without a terminal update and the TTL then lapses, or when an INSERT outlives the TTL stamped at creation (short today-bands are most exposed).
+
+**Consequences:** the window looks uncovered, every create for it loses the race, and the step-4 stale reaper never sees the row (it only reaps jobs `find_existing_jobs` returned). Writers retry immediately once (the healthy-race case, where the rescan finds the winner's row), then back off exponentially like the wait branch, giving up at `wait_timeout_seconds`; check-only reads are unaffected and fall back to the live query.
+
+**Detection:** a sustained `lazy_computation_job_create_conflicts_total` rate for a table with no matching `lazy_computation_jobs_created_total` / `lazy_computation_jobs_finished_total` progress. The steady background conflict rate from warmers and SWR revalidation racing on shared windows does not show this signature.
+
+**Possible fixes (not applied):** on a lost race, fetch the blocking PENDING row and fail it when expired; or a periodic sweeper that fails PENDING rows past `expires_at`. Both stay compatible with the index as deployed.
diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.md
index 17ddc18f6371..b47e5e774a7f 100644
--- a/products/analytics_platform/backend/lazy_computation/README.md
+++ b/products/analytics_platform/backend/lazy_computation/README.md
@@ -147,7 +147,7 @@ When a job fails, multiple waiters may all try to create a replacement job simul
1. Job A fails
2. Waiters B and C both try to create a replacement
-3. One succeeds (gets the new job), the other gets an IntegrityError
+3. One succeeds (gets the new job); the other's `INSERT .. ON CONFLICT DO NOTHING` is a silent no-op (`create_lazy_computation_job` returns `None`)
4. The loser finds the winner's job and waits for it
### Replacement jobs use the same range
@@ -188,7 +188,8 @@ Each invocation of the executor emits both a structured log and Prometheus count
Jobs run synchronously inside `execute()` — there is no background queue, so PENDING just means "an INSERT is in flight in some pod". A periodic gauge of `status='pending'` rows misses jobs that started and finished between scrapes and tells you nothing about throughput. These two counters fire at the exact PG status transitions instead:
-- `lazy_computation_jobs_created_total{cache_state, table}` — one increment every time a PENDING row is inserted (one per missing range per executor). The loser of a partial-unique-index race (`IntegrityError`) does **not** increment, so the count matches PG row inserts. `cache_state` mirrors the executor-level label so a job created during a fresh execute() call lands on `miss` and a top-up job filling a hole in pre-existing READY data lands on `partial_hit`. `hit` never appears because hits don't create anything.
+- `lazy_computation_jobs_created_total{cache_state, table}` — one increment every time a PENDING row is inserted (one per missing range per executor). The loser of a partial-unique-index race does **not** increment, so the count matches PG row inserts. `cache_state` mirrors the executor-level label so a job created during a fresh execute() call lands on `miss` and a top-up job filling a hole in pre-existing READY data lands on `partial_hit`. `hit` never appears because hits don't create anything.
+- `lazy_computation_job_create_conflicts_total{table}` — one increment every time a create is skipped because a PENDING row already holds the `unique_pending_job_per_range` slot. A steady background rate is expected (the warmers and SWR revalidation race on the same windows by design); a sustained elevated rate means writers piling onto the same windows, or a PENDING row past its own `expires_at` blocking a window it no longer serves. Each conflict also emits a `lazy_computation.job_create_conflict` structured log with `team_id`, `query_hash`, and the window, which is the only place the colliding values appear now that the insert no longer raises a Postgres error.
- `lazy_computation_jobs_finished_total{outcome, table}` — one increment every time a job reaches a terminal status.
`outcome` values:
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index a9b5d5a6d220..bf1e7ca246fb 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -9,7 +9,7 @@ from datetime import UTC, datetime, timedelta
from enum import StrEnum
from zoneinfo import ZoneInfo
-from django.db import IntegrityError, transaction
+from django.db import DEFAULT_DB_ALIAS
from django.db.models import Q
from django.utils import timezone as django_timezone
@@ -151,6 +151,17 @@ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL = Counter(
["outcome", "table"],
)
+# Lost create races are otherwise invisible outside Postgres logs. A steady
+# background rate is expected (the baseline warmer, the dimensional DAG, and SWR
+# revalidation race on the same windows by design); a sustained elevated rate
+# means either writers piling onto the same windows or a PENDING row past its
+# own expires_at blocking a window it no longer serves.
+LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL = Counter(
+ "lazy_computation_job_create_conflicts_total",
+ "PENDING job inserts skipped because a PENDING row already covers that (team, query_hash, range).",
+ ["table"],
+)
+
def _get_insert_settings(team_id: int, *, spill_to_disk: bool = False) -> dict:
"""Build ClickHouse settings for preaggregation INSERT queries.
@@ -723,17 +734,36 @@ def create_lazy_computation_job(
time_range_start: datetime,
time_range_end: datetime,
ttl_seconds: int = DEFAULT_TTL_SECONDS,
-) -> PreaggregationJob:
- """Create a new computation job in PENDING status with expiry time."""
- expires_at = django_timezone.now() + timedelta(seconds=ttl_seconds)
- return PreaggregationJob.objects.create(
+) -> PreaggregationJob | None:
+ """Create a new PENDING job with expiry time, or return None when another
+ PENDING row already holds the `unique_pending_job_per_range` slot.
+
+ Uses INSERT .. ON CONFLICT DO NOTHING (`ignore_conflicts`) so losing the
+ race is a silent no-op rather than a logged Postgres error with a rolled-back
+ transaction; executors race on these windows by design. Only unique
+ conflicts are suppressed: FK and check-constraint violations still raise
+ IntegrityError to the caller.
+ """
+ job = PreaggregationJob(
team=team,
query_hash=query_hash,
time_range_start=time_range_start,
time_range_end=time_range_end,
status=PreaggregationJob.Status.PENDING,
- expires_at=expires_at,
+ expires_at=django_timezone.now() + timedelta(seconds=ttl_seconds),
)
+ # ignore_conflicts emits a bare ON CONFLICT DO NOTHING, which relies on the
+ # partial unique index being the only realistic unique conflict on this
+ # table; a future unique constraint would have its violations misreported
+ # as lost races.
+ PreaggregationJob.objects.bulk_create([job], ignore_conflicts=True)
+ # ignore_conflicts suppresses RETURNING and the UUID pk is generated
+ # client-side, so probe by pk to learn whether the row actually landed.
+ # Pinned to the writer: a replica-routed read here would misclassify the
+ # winner as a loser and orphan its own PENDING row.
+ if not PreaggregationJob.objects.using(DEFAULT_DB_ALIAS).filter(id=job.id).exists():
+ return None
+ return job
def build_lazy_computation_insert_sql(
@@ -956,6 +986,7 @@ class LazyComputationExecutor:
pubsub: redis_lib.client.PubSub | None = None
jobs_created = 0
waited_job_ids: set[uuid.UUID] = set()
+ conflict_passes = 0
had_ready_at_start: bool | None = None
@@ -1050,6 +1081,7 @@ class LazyComputationExecutor:
# Step 3: Insert missing ranges
did_work = False
+ lost_create_race = False
if ttl_ranges and failures <= self.max_retries:
for range_start, range_end, ttl in ttl_ranges:
# Each insert runs inline and is bounded only by the ClickHouse
@@ -1065,12 +1097,22 @@ class LazyComputationExecutor:
_log_execution("timeout", result)
return result
- try:
- with transaction.atomic():
- new_job = create_lazy_computation_job(team, query_hash, range_start, range_end, ttl)
- except IntegrityError:
- # Another executor created a PENDING job for this range — loop will pick it up
- did_work = True
+ new_job = create_lazy_computation_job(team, query_hash, range_start, range_end, ttl)
+ if new_job is None:
+ # Another executor created a PENDING job for this range; the
+ # rescan at the top of the loop will pick it up. The log keeps
+ # the per-window trace that Postgres logs no longer carry, so
+ # investigations can still identify which windows are colliding.
+ LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL.labels(table=str(query_info.table)).inc()
+ logger.info(
+ "lazy_computation.job_create_conflict",
+ team_id=team.id,
+ query_hash=query_hash,
+ table=str(query_info.table),
+ time_range_start=str(range_start),
+ time_range_end=str(range_end),
+ )
+ lost_create_race = True
continue
# `had_ready_at_start` is set above before the create loop runs and
@@ -1170,12 +1212,31 @@ class LazyComputationExecutor:
_log_execution("max_retries_exceeded", result)
return result
- if did_work:
- interval = self.poll_interval_seconds
+ if did_work or lost_create_race:
+ if lost_create_race and not did_work:
+ # In the healthy race the loser's next rescan sees the winner's
+ # committed PENDING row and moves to the wait branch, so the
+ # first conflict pass retries immediately. A conflict that
+ # repeats with the window still missing means the blocking row
+ # is PENDING but past its expires_at: invisible to
+ # find_existing_jobs yet still holding the unique-index slot,
+ # which would otherwise hot-spin no-op inserts until the wait
+ # budget runs out. Pace those retries with the same backoff the
+ # wait branch uses.
+ conflict_passes += 1
+ if conflict_passes > 1:
+ remaining = self.wait_timeout_seconds - (time.monotonic() - start_time)
+ if remaining > 0:
+ time.sleep(min(interval, remaining))
+ interval = min(interval * 2, self.max_poll_interval_seconds)
+ else:
+ conflict_passes = 0
+ interval = self.poll_interval_seconds
continue
# Step 4: Wait for pending jobs
if pending_jobs:
+ conflict_passes = 0
waited_job_ids.update(j.id for j in pending_jobs)
if pubsub is None:
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.py
index 80e9ef370d4a..c605d9e6a627 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
@@ -78,6 +78,35 @@ class TestComputationJob(BaseTest):
assert retrieved.id == job.id
assert retrieved.query_hash == query_hash
+ @parameterized.expand(
+ [
+ ("pending_blocks", PreaggregationJob.Status.PENDING, False),
+ ("ready_does_not_block", PreaggregationJob.Status.READY, True),
+ ]
+ )
+ def test_create_job_conflicts_only_with_pending_rows(self, _name, seeded_status, expect_created):
+ query_hash = "abc123def456"
+ start = datetime(2024, 1, 1, tzinfo=UTC)
+ end = datetime(2024, 1, 2, tzinfo=UTC)
+ PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=query_hash,
+ time_range_start=start,
+ time_range_end=end,
+ status=seeded_status,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+
+ job = create_lazy_computation_job(self.team, query_hash, start, end)
+
+ row_count = PreaggregationJob.objects.filter(team=self.team, query_hash=query_hash).count()
+ if expect_created:
+ assert job is not None
+ assert row_count == 2
+ else:
+ assert job is None
+ assert row_count == 1
+
class TestComputeQueryHash(BaseTest):
@parameterized.expand(
@@ -1436,7 +1465,7 @@ class TestRaceConditionHandling(BaseTest):
assert isinstance(s, ast.SelectQuery)
return s
- def test_integrity_error_on_create_loops_back_and_picks_up_pending_job(self):
+ def test_lost_create_race_loops_back_and_picks_up_pending_job(self):
query = self._make_computation_query()
query_info = LazyComputationQuery(
query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
@@ -1464,18 +1493,21 @@ class TestRaceConditionHandling(BaseTest):
with (
patch(
"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.create_lazy_computation_job",
- side_effect=IntegrityError("duplicate key"),
+ return_value=None,
),
patch(
"products.analytics_platform.backend.lazy_computation.lazy_computation_executor.find_existing_jobs",
side_effect=[
[], # First call: miss the job (race window)
- [existing_pending], # Second call: find it as PENDING after IntegrityError loops back
+ [existing_pending], # Second call: find it as PENDING after losing the create race
[existing_pending], # Third call (in loop): find it as READY, no pending → break
[existing_pending], # Fourth call: final collection after loop
],
),
patch.object(executor, "_wait_for_notification", side_effect=mock_wait),
+ patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.time.sleep"
+ ) as mock_sleep,
):
result = executor.execute(
team=self.team,
@@ -1487,6 +1519,9 @@ class TestRaceConditionHandling(BaseTest):
assert result.ready is True
assert existing_pending.id in result.job_ids
+ # A single lost race must not pace: the rescan finds the winner's row,
+ # so any sleep here is pure added latency on the fan-out path.
+ mock_sleep.assert_not_called()
def test_for_loop_creates_duplicate_after_peer_completes_mid_loop(self):
"""Wasted-INSERT pattern under concurrent first-readers — documented in CONSISTENCY.md.
@@ -2129,7 +2164,7 @@ class TestComputationExecutorExecute(BaseTest):
poll_interval_seconds=0.05,
)
- # Simulate: our create hits IntegrityError (another executor got there first),
+ # Simulate: our create loses the race (another executor got there first),
# then on the next loop we find their PENDING job, then it completes.
other_pending = PreaggregationJob.objects.create(
team=self.team,
@@ -2900,22 +2935,29 @@ class TestJobLifecycleCounters(BaseTest):
== 1.0
)
- def test_integrity_error_on_create_does_not_increment_created(self):
- """Two executors racing on the same range produce one row in PG, not two —
- the loser's IntegrityError path must not double-count creates."""
+ def test_lost_create_race_increments_conflicts_not_created(self):
+ """Two executors racing on the same range produce one row in PG, not two:
+ the loser must count a conflict, never a create."""
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL,
LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
)
miss_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(cache_state="miss", table=str(self.TABLE))._value.get()
+ conflicts_before = LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL.labels(table=str(self.TABLE))._value.get()
# Range has no existing coverage, so the executor enters the create path
# on every loop iteration. Patching `create_lazy_computation_job` to
- # always raise IntegrityError simulates losing the partial-unique-index
- # race on every attempt; the executor times out shortly after.
- with patch(
- "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.create_lazy_computation_job",
- side_effect=IntegrityError("partial unique index race"),
+ # always return None simulates losing the partial-unique-index race on
+ # every attempt; the executor times out shortly after.
+ with (
+ patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.create_lazy_computation_job",
+ return_value=None,
+ ),
+ patch(
+ "products.analytics_platform.backend.lazy_computation.lazy_computation_executor.time.sleep"
+ ) as mock_sleep,
):
executor = LazyComputationExecutor(wait_timeout_seconds=0.2, poll_interval_seconds=0.05)
result = executor.execute(
@@ -2926,6 +2968,9 @@ class TestJobLifecycleCounters(BaseTest):
run_insert=lambda t, j: None,
)
assert result.ready is False # Timed out: every create attempt lost the race.
+ # Repeated conflicts on a still-missing window must pace instead of
+ # hot-spinning no-op inserts for the whole wait budget.
+ assert mock_sleep.call_count >= 1
assert (
self._delta(
@@ -2935,6 +2980,14 @@ class TestJobLifecycleCounters(BaseTest):
)
== 0.0
)
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOB_CREATE_CONFLICTS_TOTAL,
+ {"table": str(self.TABLE)},
+ conflicts_before,
+ )
+ > 0
+ )
def test_stale_mark_increments_finished_stale(self):
"""When execute() finds a PENDING job whose owner has crashed, the