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): unblock windows held by expired pending jobs (#96127)

Juraj Majerik89aa90de5e9f
diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.md
index b47e5e774a7f..31b1a193d6c6 100644
--- a/products/analytics_platform/backend/lazy_computation/README.md
+++ b/products/analytics_platform/backend/lazy_computation/README.md
@@ -198,8 +198,9 @@ Jobs run synchronously inside `execute()` — there is no background queue, so P
- `ready_empty` — INSERT succeeded but wrote no rows, PENDING → READY. Still a success; split out because an empty window is only provisionally computed (see `TtlSchedule.empty_result_ttl_seconds`), so a climbing share here points at a lagging source rather than a broken query.
- `failed` — INSERT raised (retryable or non-retryable), PENDING → FAILED.
- `stale` — a waiter detected the owning executor crashed (`_try_mark_stale_job_as_failed`) and the atomic update flipped the row to FAILED.
+- `expired` — a create conflict found the blocking PENDING row past its own `expires_at` and flipped it to FAILED (`_try_fail_expired_pending_job`), unblocking the window. Like `stale`, each increment means an executor died earlier without cleanup.
-Sum `ready` and `ready_empty` for total successes, and prefer `outcome=~"failed|stale"` over `outcome!="ready"` when alerting — the latter counts empty-but-successful jobs as problems.
+Sum `ready` and `ready_empty` for total successes, and prefer `outcome=~"failed|stale|expired"` over `outcome!="ready"` when alerting — the latter counts empty-but-successful jobs as problems.
Net job throughput (positive = backlog growing, expected ~0 in steady state):
@@ -212,7 +213,7 @@ sum(rate(lazy_computation_jobs_finished_total[5m]))
Failure share per table:
```promql
-sum by (table) (rate(lazy_computation_jobs_finished_total{outcome=~"failed|stale"}[5m]))
+sum by (table) (rate(lazy_computation_jobs_finished_total{outcome=~"failed|stale|expired"}[5m]))
/
sum by (table) (rate(lazy_computation_jobs_finished_total[5m]))
```
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 bf1e7ca246fb..eb931e0033a2 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -140,6 +140,8 @@ LAZY_COMPUTATION_EXECUTIONS_TOTAL = Counter(
# - `failed` → INSERT raised (retryable or non-retryable), row moved PENDING → FAILED.
# - `stale` → another waiter detected the owning executor crashed and marked
# the row FAILED via `_try_mark_stale_job_as_failed`.
+# - `expired` → a create conflict found the blocking PENDING row past its own
+# expires_at and marked it FAILED via `_try_fail_expired_pending_job`.
LAZY_COMPUTATION_JOBS_CREATED_TOTAL = Counter(
"lazy_computation_jobs_created_total",
"PreaggregationJob rows inserted in PENDING status (one per missing range, per executor).",
@@ -1112,6 +1114,18 @@ class LazyComputationExecutor:
time_range_start=str(range_start),
time_range_end=str(range_end),
)
+ if self._try_fail_expired_pending_job(team, query_hash, range_start, range_end):
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
+ outcome="expired", table=str(query_info.table)
+ ).inc()
+ logger.warning(
+ "lazy_computation.expired_pending_job_failed",
+ 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
@@ -1216,13 +1230,12 @@ class LazyComputationExecutor:
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.
+ # first conflict pass retries immediately. An expired blocking
+ # row is failed by _try_fail_expired_pending_job above, so the
+ # next pass can recreate it. Conflicts that still repeat with
+ # the window missing would 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)
@@ -1288,6 +1301,46 @@ class LazyComputationExecutor:
_log_execution("success", result)
return result
+ def _try_fail_expired_pending_job(
+ self, team: Team, query_hash: str, range_start: datetime, range_end: datetime
+ ) -> bool:
+ """
+ Mark an expired PENDING row as FAILED so its window can be recomputed.
+
+ A PENDING row past its expires_at is excluded by find_existing_jobs but
+ still holds the unique_pending_job_per_range slot, so its window shows as
+ missing while every attempt to create a job for it hits a conflict. The
+ wait branch never stale-marks such a row because it only sees jobs
+ find_existing_jobs returns. Without this, the window stays blocked
+ forever and every reader burns its wait budget before falling back.
+
+ The expires_at < now() guard means only rows whose data would already be
+ past its ClickHouse TTL can be failed; a live INSERT finishing afterwards
+ overwrites FAILED with READY, so at worst a takeover costs one duplicate
+ build. The publish wakes waiters that subscribed to the row before it
+ expired, so they rescan now instead of at their next poll timeout.
+ """
+ blocker = PreaggregationJob.objects.filter(
+ team=team,
+ query_hash=query_hash,
+ time_range_start=range_start,
+ time_range_end=range_end,
+ status=PreaggregationJob.Status.PENDING,
+ expires_at__lt=django_timezone.now(),
+ ).first()
+ if blocker is None:
+ return False
+ updated = PreaggregationJob.objects.filter(
+ id=blocker.id,
+ status=PreaggregationJob.Status.PENDING,
+ ).update(
+ status=PreaggregationJob.Status.FAILED,
+ error="Expired while pending (owning executor never finished)",
+ )
+ if updated > 0:
+ publish_job_completion(blocker.id, "failed")
+ return updated > 0
+
def _try_mark_stale_job_as_failed(self, job: PreaggregationJob) -> bool:
"""
Try to mark a stale PENDING job as FAILED.
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 c605d9e6a627..9995e93a400e 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
@@ -653,6 +653,70 @@ class TestExecuteComputationJobs(ClickhouseTestMixin, BaseTest):
assert ch_results[1][4] == 1 # Jan 2: user2
assert ch_results[2][4] == 1 # Jan 3: user3
+ def test_takes_over_expired_pending_job(self):
+ self._create_pageview_events()
+
+ query = self._make_computation_query()
+ query_info = LazyComputationQuery(
+ query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
+ )
+
+ # A PENDING row whose executor died: past expires_at, so it is invisible
+ # to find_existing_jobs but still holds the unique-index slot.
+ blocker = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=compute_query_hash(query_info),
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 4, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() - timedelta(hours=1),
+ )
+
+ result = LazyComputationExecutor().execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 4, tzinfo=UTC),
+ )
+
+ assert result.ready is True
+ assert len(result.job_ids) == 1
+ assert result.job_ids[0] != blocker.id
+
+ blocker.refresh_from_db()
+ assert blocker.status == PreaggregationJob.Status.FAILED
+ assert blocker.error == "Expired while pending (owning executor never finished)"
+
+ ch_results = self._query_computation_results(result.job_ids)
+ assert len(ch_results) == 3
+
+ def test_does_not_fail_live_pending_job(self):
+ query = self._make_computation_query()
+ query_info = LazyComputationQuery(
+ query=query, table=LazyComputationTable.PREAGGREGATION_RESULTS, timezone="UTC"
+ )
+
+ # A healthy in-flight build: PENDING with a future expires_at.
+ live_job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=compute_query_hash(query_info),
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 4, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+
+ result = LazyComputationExecutor(wait_timeout_seconds=0.3).execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 1, 1, tzinfo=UTC),
+ end=datetime(2024, 1, 4, tzinfo=UTC),
+ )
+
+ assert result.ready is False
+ live_job.refresh_from_db()
+ assert live_job.status == PreaggregationJob.Status.PENDING
+
class TestHogQLQueryWithPrecomputation(ClickhouseTestMixin, BaseTest):
"""Test execute_hogql_query with usePreaggregatedIntermediateResults modifier (lazy computation)."""