: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(experiments): add CH progress indication to workflow pooling endpoint (#68067)
Rodrigo Ilorob08974647580
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 2c0d93a49127..07a46c0dcd9a 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1000,6 +1000,40 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):required=False,help_text="Per-metric results computed by this run, scoped by the run's recalc fingerprint",)+ # Live ClickHouse progress, present only on the GET poll path while the run is in_progress (read from+ # system.processes by query_id prefix; see get_live_query_progress). build_job_payload omits these keys+ # entirely for terminal or just-created runs, so they are genuinely optional in the response — NOT+ # read_only=True, which drf-spectacular would force into the schema's `required` list (making the generated+ # TypeScript `number | null` instead of the honest `number | null | undefined`). The serializer is+ # output-only (never .is_valid()), so omitting read_only costs no input-validation safety.+ running_metrics = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="Count of metric queries currently running in ClickHouse (bounded by worker-pool concurrency)",+ )+ rows_read = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="Rows read so far by the currently-running metric queries (monotonic; the live progress signal)",+ )+ estimated_rows_total = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text=(+ "ClickHouse's total_rows_approx across running queries. A soft ceiling ClickHouse revises upward "+ "mid-scan, so it can exceed or trail rows_read; treat rows_read as the reliable signal"+ ),+ )+ bytes_read = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="Bytes read so far by the currently-running metric queries",+ )+ active_cpu_time = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="Active CPU time (microseconds) consumed by the currently-running metric queries",+ )class RunningTimeBaselineStatsSerializer(serializers.Serializer):diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex b769ee774b2d..beaa6e4bf0b8 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -1125,6 +1125,6 @@ def _serialize_recalculation(recalc: ExperimentMetricsRecalculation) -> dict:`results` field — recomputing per-metric fingerprints once per request is enough."""results = get_run_results(recalc)- payload = build_job_payload(recalc, results=results)+ payload = build_job_payload(recalc, results=results, include_live_progress=True)payload["results"] = resultsreturn ExperimentMetricsRecalculationSerializer(payload).datadiff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex ac63770c5924..56974601b7bb 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -19,8 +19,13 @@ from django.utils import timezonefrom prometheus_client import Counterfrom rest_framework.exceptions import ValidationError-from posthog.models.scoping import team_scope+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.exceptions_capture import capture_exception+from posthog.models.scoping import get_current_team_id, team_scopefrom posthog.models.user import User+from posthog.settings import CLICKHOUSE_CLUSTERfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method@@ -79,17 +84,81 @@ def _derive_counters(recalc: ExperimentMetricsRecalculation, results: list[dict]return completed, failed_in_rows + discovery_only_failures+def get_live_query_progress(recalc: ExperimentMetricsRecalculation) -> dict | None:+ """Live ClickHouse progress for an in-flight run, read from system.processes by query_id prefix.++ Returns None unless the run is IN_PROGRESS. No storage needed: each metric query is tagged with the+ deterministic client_query_id `experiment_metric_recalc_{recalc_id}_{metric_uuid}`, which ClickHouse+ stamps into query_id as `{team_id}_{client_query_id}_{random}`. We match that prefix to find the run's+ currently-running queries and sum their progress.++ `running_metrics` is the count of distinct in-flight queries (bounded by the workflow's worker-pool+ concurrency). `estimated_rows_total` is ClickHouse's own total_rows_approx, which it revises upward+ mid-scan, so callers should treat rows_read as the monotonic signal and the estimate as a soft ceiling.+ """+ if recalc.status != ExperimentMetricsRecalculation.Status.IN_PROGRESS:+ return None++ # system.processes is a cluster-global table with no ClickHouse-side tenant scoping: the team boundary is+ # enforced only by the leading `{team_id}_` in the query_id prefix. Callers must pass a request-scoped row+ # (see get_recalculation_by_id); this is the defense-in-depth check that keeps a future unscoped caller from+ # summing another team's live queries.+ if recalc.team_id != get_current_team_id():+ return None++ prefix = f"{recalc.team_id}_experiment_metric_recalc_{recalc.id}_%"+ try:+ with tags_context(product=Product.EXPERIMENTS, feature=Feature.CACHE_WARMUP, team_id=recalc.team_id):+ rows = sync_execute(+ """+ SELECT+ sum(read_rows) AS rows_read,+ sum(total_rows_approx) AS estimated_rows_total,+ sum(read_bytes) AS bytes_read,+ sum(ProfileEvents['OSCPUVirtualTimeMicroseconds']) AS active_cpu_time,+ count(DISTINCT query_id) AS running_metrics+ FROM clusterAllReplicas(%(cluster)s, system.processes)+ WHERE query_id LIKE %(prefix)s+ SETTINGS skip_unavailable_shards=1, max_execution_time=2+ """,+ {"cluster": CLICKHOUSE_CLUSTER, "prefix": prefix},+ workload=Workload.OFFLINE,+ team_id=recalc.team_id,+ )+ except Exception:+ # Best-effort, decorative read on the poll's hot path: a cluster hiccup here must never sink the core+ # recalculation payload (status + derived counters). Swallow, and let the run's live progress read null.+ capture_exception()+ return None++ rows_read, estimated_rows_total, bytes_read, active_cpu_time, running_metrics = rows[0]+ # `running_metrics == 0` is a real, non-terminal state (the ~5s gaps between per-metric queries), distinct+ # from "run finished". Return the zeros so the poll can tell "in-flight, momentarily idle" from terminal null.+ return {+ "rows_read": int(rows_read or 0),+ "estimated_rows_total": int(estimated_rows_total or 0),+ "bytes_read": int(bytes_read or 0),+ "active_cpu_time": int(active_cpu_time or 0),+ "running_metrics": int(running_metrics or 0),+ }++def build_job_payload(recalc: ExperimentMetricsRecalculation,*,is_existing: bool | None = None,results: list[dict] | None = None,+ include_live_progress: bool = False,) -> dict:"""Shape a recalc row + derived counters as a dict the serializer can re-serialize.Returns model-native values (datetimes, ints, dicts) — DRF handles the wire format. The POST path passes`is_existing` to signal whether the workflow needs starting; the GET paths pass `results` so the same rowlist backs both the derived counters and the response's `results` field (no duplicate fingerprint work).++ `include_live_progress` opts the caller into one system.processes read per call (see get_live_query_progress);+ the poll (GET) path sets it so an in-flight run carries live ClickHouse progress, while the POST path does not+ (nothing is running yet)."""completed_metrics, failed_metrics = _derive_counters(recalc, results=results)payload: dict = {@@ -108,6 +177,10 @@ def build_job_payload(}if is_existing is not None:payload["is_existing"] = is_existing+ if include_live_progress:+ live_progress = get_live_query_progress(recalc)+ if live_progress is not None:+ payload.update(live_progress)return payloaddiff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex 0d5738d699a3..2e6bfd2d8e45 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -2,12 +2,15 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom posthog.test.base import BaseTest+from unittest.mock import patchfrom django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError+from posthog.models.scoping import team_scope+from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_methodfrom products.experiments.backend.models.experiment import (@@ -20,6 +23,7 @@ from products.experiments.backend.models.experiment import (from products.experiments.backend.recalculation import (build_timeseries_cold_start_payload,get_latest_recalculation,+ get_live_query_progress,get_recalculation_by_id,get_run_results,request_recalculation,@@ -416,3 +420,73 @@ class TestTimeseriesColdStartPayload(BaseTest):exp.exposure_criteria = {"filterTestAccounts": True}exp.save()assert build_timeseries_cold_start_payload(exp) is None++[email protected]_db(transaction=True)+class TestLiveQueryProgress(BaseTest):+ def _recalc(self, status: str) -> ExperimentMetricsRecalculation:+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key=f"live-{status}", name="live")+ exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag, name="live")+ return ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status=status)++ @parameterized.expand([("pending",), ("completed",), ("failed",)])+ def test_returns_none_without_querying_clickhouse_when_not_in_progress(self, status: str):+ recalc = self._recalc(status)+ with team_scope(self.team.id, canonical=True):+ with patch("products.experiments.backend.recalculation.sync_execute") as mock_execute:+ assert get_live_query_progress(recalc) is None+ mock_execute.assert_not_called()++ def test_returns_none_without_querying_clickhouse_when_team_context_mismatches(self):+ # system.processes is cluster-global; the team boundary is the query_id prefix. The team-context guard+ # is the fail-closed backstop against a caller passing a row from a different team than the request scope.+ recalc = self._recalc("in_progress")+ with team_scope(self.team.id + 1, canonical=True):+ with patch("products.experiments.backend.recalculation.sync_execute") as mock_execute:+ assert get_live_query_progress(recalc) is None+ mock_execute.assert_not_called()++ def test_maps_system_processes_aggregate_for_in_progress_run(self):+ recalc = self._recalc("in_progress")+ with team_scope(self.team.id, canonical=True):+ with patch(+ "products.experiments.backend.recalculation.sync_execute",+ return_value=[(1_284_512, 9_800_000, 41_000_000, 250_000, 3)],+ ):+ progress = get_live_query_progress(recalc)+ assert progress == {+ "rows_read": 1_284_512,+ "estimated_rows_total": 9_800_000,+ "bytes_read": 41_000_000,+ "active_cpu_time": 250_000,+ "running_metrics": 3,+ }++ def test_maps_all_zero_row_to_zeros_while_in_progress(self):+ # system.processes returns one all-zero row in the ~5s gaps between per-metric queries. That's a real,+ # non-terminal state: return zeros (not None) so the poll can tell "in-flight, idle" from "run finished".+ recalc = self._recalc("in_progress")+ with team_scope(self.team.id, canonical=True):+ with patch(+ "products.experiments.backend.recalculation.sync_execute",+ return_value=[(0, 0, 0, 0, 0)],+ ):+ progress = get_live_query_progress(recalc)+ assert progress == {+ "rows_read": 0,+ "estimated_rows_total": 0,+ "bytes_read": 0,+ "active_cpu_time": 0,+ "running_metrics": 0,+ }++ def test_returns_none_when_clickhouse_read_raises(self):+ # The live read is best-effort on the poll's hot path: a ClickHouse hiccup must degrade to None, never+ # bubble up and 500 the recalculation-detail endpoint (which also carries status + derived counters).+ recalc = self._recalc("in_progress")+ with team_scope(self.team.id, canonical=True):+ with patch(+ "products.experiments.backend.recalculation.sync_execute",+ side_effect=Exception("clusterAllReplicas unavailable"),+ ):+ assert get_live_query_progress(recalc) is Nonediff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 2805a86a1474..018533c6f992 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1681,6 +1681,31 @@ export interface ExperimentMetricsRecalculationApi {readonly result_source: ResultSourceEnumApi/** Per-metric results computed by this run, scoped by the run's recalc fingerprint */readonly results: readonly MetricRecalculationResultApi[]+ /**+ * Count of metric queries currently running in ClickHouse (bounded by worker-pool concurrency)+ * @nullable+ */+ running_metrics?: number | null+ /**+ * Rows read so far by the currently-running metric queries (monotonic; the live progress signal)+ * @nullable+ */+ rows_read?: number | null+ /**+ * ClickHouse's total_rows_approx across running queries. A soft ceiling ClickHouse revises upward mid-scan, so it can exceed or trail rows_read; treat rows_read as the reliable signal+ * @nullable+ */+ estimated_rows_total?: number | null+ /**+ * Bytes read so far by the currently-running metric queries+ * @nullable+ */+ bytes_read?: number | null+ /**+ * Active CPU time (microseconds) consumed by the currently-running metric queries+ * @nullable+ */+ active_cpu_time?: number | null}export interface ShipVariantApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3d4702c012c1..06cc78373057 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22584,6 +22584,31 @@ export namespace Schemas {readonly result_source: ResultSourceEnum;/** Per-metric results computed by this run, scoped by the run's recalc fingerprint */readonly results: readonly MetricRecalculationResult[];+ /**+ * Count of metric queries currently running in ClickHouse (bounded by worker-pool concurrency)+ * @nullable+ */+ running_metrics?: number | null;+ /**+ * Rows read so far by the currently-running metric queries (monotonic; the live progress signal)+ * @nullable+ */+ rows_read?: number | null;+ /**+ * ClickHouse's total_rows_approx across running queries. A soft ceiling ClickHouse revises upward mid-scan, so it can exceed or trail rows_read; treat rows_read as the reliable signal+ * @nullable+ */+ estimated_rows_total?: number | null;+ /**+ * Bytes read so far by the currently-running metric queries+ * @nullable+ */+ bytes_read?: number | null;+ /**+ * Active CPU time (microseconds) consumed by the currently-running metric queries+ * @nullable+ */+ active_cpu_time?: number | null;}export type ExperimentResultsWidgetCatalogEntryOpenApiWidgetType = typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType[keyof typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType];