: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(analytics-platform): emit cache-hit metric for lazy computation executions (#59247)
Lucas Ricoy429ca30f2f02
diff --git a/products/analytics_platform/backend/lazy_computation/README.md b/products/analytics_platform/backend/lazy_computation/README.mdindex d63c728e1b9b..b8ae0f269146 100644--- a/products/analytics_platform/backend/lazy_computation/README.md+++ b/products/analytics_platform/backend/lazy_computation/README.md@@ -168,6 +168,54 @@ If an executor crashes while a job is PENDING, other waiters detect this via RedStale jobs are marked FAILED and the normal replacement flow kicks in. This means we can recover from crashes of the process we were waiting for.+## Observability++Each invocation of the executor emits both a structured log and a Prometheus counter, sharing the same labels so the two views agree.++### Prometheus++`lazy_computation_executions_total` is incremented once per `executor.execute()` call, with labels:++| label | values |+| ------------- | ------------------------------------------------------------------- |+| `outcome` | `success`, `timeout`, `non_retryable_error`, `max_retries_exceeded` |+| `cache_state` | `hit`, `partial_hit`, `miss` — see below |+| `table` | the lazy table being populated (e.g. `preaggregation_results`) |++`cache_state` values:++- `hit` — the request did no new work (no jobs created, no waits).+- `partial_hit` — the request had to do work but found pre-existing READY data.+- `miss` — the request had to do work and found no pre-existing data.++Full hit ratio across a window:++```promql+sum(rate(lazy_computation_executions_total{cache_state="hit"}[5m]))+ /+sum(rate(lazy_computation_executions_total[5m]))+```++Any-coverage ratio (`hit` or `partial_hit`):++```promql+sum(rate(lazy_computation_executions_total{cache_state=~"hit|partial_hit"}[5m]))+ /+sum(rate(lazy_computation_executions_total[5m]))+```++Per-table breakdown of failures:++```promql+sum by (table, outcome) (+ rate(lazy_computation_executions_total{outcome!="success"}[5m])+)+```++### Structured log++The `lazy_computation.executed` log line carries the same `outcome`, `cache_state`, and `table` fields plus per-call detail (`query_hash`, `jobs_created`, `jobs_waited_for`, `total_duration_ms`, `time_range_days`). Useful when you need to follow a specific request rather than aggregate.+## Limitations- Automatic transformation only supports very specific query patternsdiff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.pyindex a6c120edb1db..d8891b4dda8d 100644--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py@@ -16,6 +16,7 @@ from django.utils import timezone as django_timezoneimport redis as redis_libimport structlogfrom clickhouse_driver.errors import ServerException+from prometheus_client import Counterfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLQuerySettings, get_default_hogql_global_settings@@ -73,6 +74,23 @@ DEFAULT_CH_START_GRACE_PERIOD_SECONDS = 60 # 1 minutePREAGGREGATION_INSERT_QUORUM: str | int = 0 if TEST or DEBUG else "auto"+# Mirrors the `lazy_computation.executed` structured log so the same outcomes+# (`success` / `timeout` / `non_retryable_error` / `max_retries_exceeded`) are+# countable in Prometheus without log-based aggregation.+#+# `cache_state` values:+# - `hit` → the request did no new work (no jobs created, no waits).+# - `partial_hit` → the request had to do work but found pre-existing READY data.+# - `miss` → the request had to do work and found no pre-existing data.+#+# See README.md § Observability for example PromQL queries.+LAZY_COMPUTATION_EXECUTIONS_TOTAL = Counter(+ "lazy_computation_executions_total",+ "Lazy computation executor invocations, labeled by outcome / cache_state / table.",+ ["outcome", "cache_state", "table"],+)++def _get_insert_settings(team_id: int) -> dict:"""Build ClickHouse settings for preaggregation INSERT queries.@@ -670,12 +688,26 @@ class LazyComputationExecutor:jobs_created = 0waited_job_ids: set[uuid.UUID] = set()+ had_ready_at_start: bool | None = None+def _log_execution(outcome: str, result: LazyComputationResult) -> None:+ if jobs_created == 0 and not waited_job_ids:+ cache_state = "hit"+ elif had_ready_at_start:+ cache_state = "partial_hit"+ else:+ cache_state = "miss"+ LAZY_COMPUTATION_EXECUTIONS_TOTAL.labels(+ outcome=outcome,+ cache_state=cache_state,+ table=str(query_info.table),+ ).inc()logger.info("lazy_computation.executed",query_hash=query_hash,table=str(query_info.table),outcome=outcome,+ cache_state=cache_state,total_duration_ms=round((time.monotonic() - start_time) * 1000),jobs_created=jobs_created,jobs_waited_for=len(waited_job_ids),@@ -701,6 +733,9 @@ class LazyComputationExecutor:missing_ranges = find_missing_contiguous_windows(fresh_jobs, start, end)ttl_ranges = split_ranges_by_ttl(missing_ranges, self.ttl_schedule)+ if had_ready_at_start is None:+ had_ready_at_start = any(j.status == PreaggregationJob.Status.READY for j in fresh_jobs)+# Step 3: Insert missing rangesdid_work = Falseif ttl_ranges and failures <= self.max_retries: