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.

feat(analytics-platform): export lazy_computation job lifecycle counters (#60464)

Lucas Ricoybc7129a70f2f
diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.md
index b8ae0f269146..cd9aea9a47a9 100644
--- a/products/analytics_platform/backend/lazy_computation/README.md
+++ b/products/analytics_platform/backend/lazy_computation/README.md
@@ -170,10 +170,12 @@ Stale jobs are marked FAILED and the normal replacement flow kicks in. This mean
## Observability
-Each invocation of the executor emits both a structured log and a Prometheus counter, sharing the same labels so the two views agree.
+Each invocation of the executor emits both a structured log and Prometheus counters. The executor-level counter answers "is the caller getting served"; the job-level counters answer "are PG jobs flowing as fast as we're creating them".
### Prometheus
+#### Executor-level
+
`lazy_computation_executions_total` is incremented once per `executor.execute()` call, with labels:
| label | values |
@@ -182,6 +184,51 @@ Each invocation of the executor emits both a structured log and a Prometheus cou
| `cache_state` | `hit`, `partial_hit`, `miss` — see below |
| `table` | the lazy table being populated (e.g. `preaggregation_results`) |
+#### Job-level
+
+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_finished_total{outcome, table}` — one increment every time a job reaches a terminal status.
+
+`outcome` values:
+
+- `ready` — INSERT succeeded, PENDING → READY.
+- `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.
+
+Net job throughput (positive = backlog growing, expected ~0 in steady state):
+
+```promql
+sum(rate(lazy_computation_jobs_created_total[5m]))
+ -
+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[5m]))
+```
+
+Average miss size (jobs per full-miss execution — answers "when we miss, how much do we end up computing?"):
+
+```promql
+sum(rate(lazy_computation_jobs_created_total{cache_state="miss"}[5m]))
+ /
+sum(rate(lazy_computation_executions_total{cache_state="miss"}[5m]))
+```
+
+Average partial-hit top-up size (jobs per partial-hit execution):
+
+```promql
+sum(rate(lazy_computation_jobs_created_total{cache_state="partial_hit"}[5m]))
+ /
+sum(rate(lazy_computation_executions_total{cache_state="partial_hit"}[5m]))
+```
+
`cache_state` values:
- `hit` — the request did no new work (no jobs created, no waits).
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 b94733254388..3b34693079ea 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -91,6 +91,41 @@ LAZY_COMPUTATION_EXECUTIONS_TOTAL = Counter(
)
+# Per-job lifecycle counters. The executor framework processes jobs synchronously
+# inside `execute()` — there is no background queue and PENDING is just "an INSERT
+# is currently running in some pod". A point-in-time sample of PENDING rows can't
+# answer "are we keeping up?" because finished jobs vanish from the live set as
+# fast as new ones arrive. These counters are the queue-throughput primitive
+# instead: subtract the rates to get net backlog growth, slice by `outcome` to
+# see whether failures or staleness are climbing.
+#
+# `created.cache_state` mirrors the executor-level `lazy_computation_executions_total`
+# label so a per-job rate can be attributed to the kind of execute() call that
+# spawned it. Hits don't create anything, so only `miss` and `partial_hit` appear:
+# - `miss` → execute() found no pre-existing READY data; every job in
+# this counter slice is part of a fresh population.
+# - `partial_hit` → execute() found some pre-existing READY data; jobs here are
+# top-ups filling the gaps.
+# Use `rate(created{cache_state="miss"}) / rate(executions_total{cache_state="miss"})`
+# to get average jobs per miss execution (i.e. average miss window size).
+#
+# `finished` outcomes:
+# - `ready` → INSERT succeeded, row moved PENDING → READY.
+# - `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`.
+LAZY_COMPUTATION_JOBS_CREATED_TOTAL = Counter(
+ "lazy_computation_jobs_created_total",
+ "PreaggregationJob rows inserted in PENDING status (one per missing range, per executor).",
+ ["cache_state", "table"],
+)
+LAZY_COMPUTATION_JOBS_FINISHED_TOTAL = Counter(
+ "lazy_computation_jobs_finished_total",
+ "PreaggregationJob rows that reached a terminal status, labeled by outcome and table.",
+ ["outcome", "table"],
+)
+
+
def _get_insert_settings(team_id: int) -> dict:
"""Build ClickHouse settings for preaggregation INSERT queries.
@@ -756,6 +791,15 @@ class LazyComputationExecutor:
did_work = True
continue
+ # `had_ready_at_start` is set above before the create loop runs and
+ # is the same signal `_log_execution` uses to compute the executor's
+ # final cache_state. Reusing it here keeps job-level and
+ # execution-level series aligned. Hits never enter this branch.
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(
+ cache_state="partial_hit" if had_ready_at_start else "miss",
+ table=str(query_info.table),
+ ).inc()
+
try:
insert_start = time.monotonic()
insert_fn(team, new_job)
@@ -764,6 +808,9 @@ class LazyComputationExecutor:
new_job.computed_at = django_timezone.now()
new_job.save()
publish_job_completion(new_job.id, "ready")
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
+ outcome="ready", table=str(query_info.table)
+ ).inc()
jobs_created += 1
logger.info(
"lazy_computation.job_completed",
@@ -781,6 +828,9 @@ class LazyComputationExecutor:
new_job.error = str(e)
new_job.save()
publish_job_completion(new_job.id, "failed")
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
+ outcome="failed", table=str(query_info.table)
+ ).inc()
jobs_created += 1
logger.warning(
"lazy_computation.job_failed",
@@ -836,6 +886,9 @@ class LazyComputationExecutor:
if self._is_job_stale(job):
marked = self._try_mark_stale_job_as_failed(job)
if marked:
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
+ outcome="stale", table=str(query_info.table)
+ ).inc()
logger.warning(
"lazy_computation.job_marked_stale",
job_id=str(job.id),
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 6bf368014ce3..c01b97ece685 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
@@ -2379,6 +2379,251 @@ class TestPubsubAndStaleDetection(BaseTest):
assert mock_publish.call_args[0][1] == "failed"
+class TestJobLifecycleCounters(BaseTest):
+ """Counters that answer "how many jobs were we creating vs finishing" — the
+ framework runs jobs synchronously, so PENDING is just "INSERT in flight" and
+ a periodic gauge sample misses everything that started and finished between
+ scrapes. These counters fire at the exact PG transitions so
+ `rate(created) - rate(finished)` reflects real throughput."""
+
+ TABLE = LazyComputationTable.PREAGGREGATION_RESULTS
+
+ def _query_info(self) -> QueryInfo:
+ query = parse_select(
+ "SELECT toStartOfDay(timestamp) as a, [] as b, uniqExactState(person_id) as c FROM events GROUP BY a"
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return QueryInfo(query=query, table=self.TABLE, timezone="UTC")
+
+ @staticmethod
+ def _delta(metric, labels: dict[str, str], before: float) -> float:
+ sample = metric.labels(**labels)._value.get()
+ return sample - before
+
+ def test_full_miss_increments_created_miss_and_finished_ready(self):
+ """A fresh range with no pre-existing READY data is a full miss — the
+ single job created here must land on the `cache_state="miss"` series so
+ miss-execution / miss-job rates can be cross-divided downstream."""
+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ )
+
+ miss_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(cache_state="miss", table=str(self.TABLE))._value.get()
+ ready_before = LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(outcome="ready", table=str(self.TABLE))._value.get()
+
+ executor = LazyComputationExecutor()
+ result = executor.execute(
+ team=self.team,
+ query_info=self._query_info(),
+ start=datetime(2024, 4, 1, tzinfo=UTC),
+ end=datetime(2024, 4, 2, tzinfo=UTC),
+ run_insert=lambda t, j: None,
+ )
+
+ assert result.ready is True
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ {"cache_state": "miss", "table": str(self.TABLE)},
+ miss_before,
+ )
+ == 1.0
+ )
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ {"outcome": "ready", "table": str(self.TABLE)},
+ ready_before,
+ )
+ == 1.0
+ )
+
+ def test_partial_hit_increments_created_partial_hit(self):
+ """When the requested range partially overlaps a pre-existing READY job,
+ the executor only creates the missing-window job — and that job belongs
+ to the `partial_hit` series, not `miss`. This is how downstream tells
+ "we are recomputing 1 day on top of 6 cached" apart from "fresh 7-day
+ miss"."""
+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ )
+
+ query_info = self._query_info()
+ query_hash = compute_query_hash(query_info)
+
+ # Seed a READY job covering Jan 1 only; request Jan 1–3, forcing the
+ # executor to create exactly one new job (Jan 2–3) with prior coverage
+ # already present.
+ PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=query_hash,
+ time_range_start=datetime(2024, 8, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 8, 2, tzinfo=UTC),
+ status=PreaggregationJob.Status.READY,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ computed_at=django_timezone.now(),
+ )
+
+ miss_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(cache_state="miss", table=str(self.TABLE))._value.get()
+ partial_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(
+ cache_state="partial_hit", table=str(self.TABLE)
+ )._value.get()
+
+ executor = LazyComputationExecutor()
+ result = executor.execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 8, 1, tzinfo=UTC),
+ end=datetime(2024, 8, 3, tzinfo=UTC),
+ run_insert=lambda t, j: None,
+ )
+
+ assert result.ready is True
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ {"cache_state": "partial_hit", "table": str(self.TABLE)},
+ partial_before,
+ )
+ == 1.0
+ )
+ # And critically: the miss series did NOT move — a partial hit must not
+ # contaminate the miss-execution / miss-job ratio.
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ {"cache_state": "miss", "table": str(self.TABLE)},
+ miss_before,
+ )
+ == 0.0
+ )
+
+ def test_failed_insert_increments_created_and_finished_failed(self):
+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ )
+
+ miss_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(cache_state="miss", table=str(self.TABLE))._value.get()
+ failed_before = LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(
+ outcome="failed", table=str(self.TABLE)
+ )._value.get()
+
+ executor = LazyComputationExecutor(max_retries=0)
+ result = executor.execute(
+ team=self.team,
+ query_info=self._query_info(),
+ start=datetime(2024, 5, 1, tzinfo=UTC),
+ end=datetime(2024, 5, 2, tzinfo=UTC),
+ run_insert=lambda t, j: (_ for _ in ()).throw(Exception("boom")),
+ )
+
+ assert result.ready is False
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ {"cache_state": "miss", "table": str(self.TABLE)},
+ miss_before,
+ )
+ == 1.0
+ )
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ {"outcome": "failed", "table": str(self.TABLE)},
+ failed_before,
+ )
+ == 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."""
+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ )
+
+ miss_before = LAZY_COMPUTATION_JOBS_CREATED_TOTAL.labels(cache_state="miss", 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"),
+ ):
+ executor = LazyComputationExecutor(wait_timeout_seconds=0.2, poll_interval_seconds=0.05)
+ result = executor.execute(
+ team=self.team,
+ query_info=self._query_info(),
+ start=datetime(2024, 6, 1, tzinfo=UTC),
+ end=datetime(2024, 6, 2, tzinfo=UTC),
+ run_insert=lambda t, j: None,
+ )
+ assert result.ready is False # Timed out: every create attempt lost the race.
+
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_CREATED_TOTAL,
+ {"cache_state": "miss", "table": str(self.TABLE)},
+ miss_before,
+ )
+ == 0.0
+ )
+
+ def test_stale_mark_increments_finished_stale(self):
+ """When execute() finds a PENDING job whose owner has crashed, the
+ winning waiter both flips the row to FAILED and bumps
+ `finished{stale}`. Losing waiters take the same branch and see
+ `marked=False`, so no double-count is possible."""
+ from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ )
+
+ # Seed a PENDING job older than the executor's CH-start grace period,
+ # with no Redis heartbeat: _is_job_stale returns True on the first pass.
+ query_info = self._query_info()
+ query_hash = compute_query_hash(query_info)
+ pending_job = PreaggregationJob.objects.create(
+ team=self.team,
+ query_hash=query_hash,
+ time_range_start=datetime(2024, 7, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 7, 2, tzinfo=UTC),
+ status=PreaggregationJob.Status.PENDING,
+ expires_at=django_timezone.now() + timedelta(days=7),
+ )
+ PreaggregationJob.objects.filter(id=pending_job.id).update(
+ created_at=django_timezone.now() - timedelta(seconds=10),
+ )
+
+ stale_before = LAZY_COMPUTATION_JOBS_FINISHED_TOTAL.labels(outcome="stale", table=str(self.TABLE))._value.get()
+
+ executor = LazyComputationExecutor(
+ wait_timeout_seconds=0.5,
+ poll_interval_seconds=0.05,
+ ch_start_grace_period_seconds=1,
+ max_retries=0,
+ )
+ executor.execute(
+ team=self.team,
+ query_info=query_info,
+ start=datetime(2024, 7, 1, tzinfo=UTC),
+ end=datetime(2024, 7, 2, tzinfo=UTC),
+ run_insert=lambda t, j: None,
+ )
+
+ assert (
+ self._delta(
+ LAZY_COMPUTATION_JOBS_FINISHED_TOTAL,
+ {"outcome": "stale", "table": str(self.TABLE)},
+ stale_before,
+ )
+ == 1.0
+ )
+
+
class TestIsNonRetryableError(BaseTest):
@parameterized.expand(
[