: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): count finished queries in recalculation live progress (#69155)
Rodrigo Iloro8cc50ae66892
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex c5d9da526c23..2d9ce9b0467d 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -1001,12 +1001,13 @@ 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.+ # Live ClickHouse progress, present only on the GET poll path while the run is in_progress (in-flight+ # queries from system.processes plus queries finished during the run from system.query_log, matched 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,@@ -1015,25 +1016,32 @@ class ExperimentMetricsRecalculationSerializer(serializers.Serializer):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)",+ help_text=(+ "Rows read by the run's metric queries so far, both finished and currently running. Cumulative "+ "and roughly monotonic across the run; the primary 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"+ "ClickHouse's total_rows_approx across running queries plus the final read_rows of finished ones. "+ "A soft ceiling revised 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",+ help_text="Bytes read by the run's metric queries so far, both finished and currently running",)active_cpu_time = serializers.IntegerField(required=False,allow_null=True,- help_text="Active CPU time (microseconds) consumed by the currently-running metric queries",+ help_text=(+ "Active CPU time (microseconds) consumed by the run's metric queries so far, both finished and "+ "currently running"+ ),)diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex 56974601b7bb..8d5132284ea2 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -85,43 +85,73 @@ def _derive_counters(recalc: ExperimentMetricsRecalculation, results: list[dict]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.+ """Cumulative ClickHouse progress for an in-flight run: in-flight queries from system.processes plus+ queries already finished during the run from system.query_log, matched by query_id prefix.Returns None unless the run is IN_PROGRESS. No storage needed: each metric query is tagged with thedeterministic 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.+ stamps into query_id as `{team_id}_{client_query_id}_{random}`. system.processes only holds a query+ while it executes, and the metric queries are usually shorter than the poll interval, so processes+ alone reads zero for most of the run; the query_log branch keeps finished queries counted, making+ rows_read cumulative and roughly monotonic across the run (modulo query_log flush lag).++ `running_metrics` counts only the currently in-flight queries (bounded by the workflow's worker-pool+ concurrency). `estimated_rows_total` is ClickHouse's own total_rows_approx for in-flight queries (revised+ upward mid-scan) plus the final read_rows of finished ones, so it can trail rows_read; treat rows_read as+ the primary signal. Temporal retries of a metric produce one query_log row per attempt and each attempt's+ rows are summed; that overcount is accepted for a decorative counter."""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.+ # system.processes and system.query_log are cluster-global tables 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 queries.if recalc.team_id != get_current_team_id():return Noneprefix = f"{recalc.team_id}_experiment_metric_recalc_{recalc.id}_%"+ # The prefix alone scopes rows to this run; the time bound exists so the query_log scan prunes to the+ # run's window instead of walking the whole table on every poll. The 60s pad absorbs clock skew between+ # the Django clock that stamped started_at and the ClickHouse clock behind event_time.+ since = (recalc.started_at or recalc.created_at) - timedelta(seconds=60)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+ sum(rows_read) AS rows_read,+ sum(estimated_rows_total) AS estimated_rows_total,+ sum(bytes_read) AS bytes_read,+ sum(active_cpu_time) AS active_cpu_time,+ countIf(is_running = 1) AS running_metrics+ FROM+ (+ SELECT+ read_rows AS rows_read,+ total_rows_approx AS estimated_rows_total,+ read_bytes AS bytes_read,+ ProfileEvents['OSCPUVirtualTimeMicroseconds'] AS active_cpu_time,+ 1 AS is_running+ FROM clusterAllReplicas(%(cluster)s, system.processes)+ WHERE query_id LIKE %(prefix)s+ UNION ALL+ SELECT+ read_rows AS rows_read,+ read_rows AS estimated_rows_total,+ read_bytes AS bytes_read,+ ProfileEvents['OSCPUVirtualTimeMicroseconds'] AS active_cpu_time,+ 0 AS is_running+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE query_id LIKE %(prefix)s+ AND type = 'QueryFinish'+ AND event_date >= toDate(toDateTime(%(since)s))+ AND event_time >= toDateTime(%(since)s)+ )SETTINGS skip_unavailable_shards=1, max_execution_time=2""",- {"cluster": CLICKHOUSE_CLUSTER, "prefix": prefix},+ {"cluster": CLICKHOUSE_CLUSTER, "prefix": prefix, "since": int(since.timestamp())},workload=Workload.OFFLINE,team_id=recalc.team_id,)@@ -132,8 +162,9 @@ def get_live_query_progress(recalc: ExperimentMetricsRecalculation) -> dict | Noreturn Nonerows_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.+ # All-zeros is a real, non-terminal state (queries not started yet, or finished but not flushed to+ # query_log), distinct from "run finished". Return the zeros so the poll can tell "in-flight, nothing+ # visible yet" from terminal null.return {"rows_read": int(rows_read or 0),"estimated_rows_total": int(estimated_rows_total or 0),diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex 2e6bfd2d8e45..574feb53b5f6 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -1,7 +1,7 @@from datetime import UTC, datetime, timedeltaimport pytest-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import patchfrom django.utils import timezone@@ -9,6 +9,8 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationError+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.scoping import team_scopefrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint@@ -490,3 +492,32 @@ class TestLiveQueryProgress(BaseTest):side_effect=Exception("clusterAllReplicas unavailable"),):assert get_live_query_progress(recalc) is None++[email protected]_db(transaction=True)+class TestLiveQueryProgressFinishedQueries(BaseTest, ClickhouseTestMixin):+ def test_counts_rows_from_queries_finished_during_the_run(self):+ # The per-metric queries usually outlive no single 2s poll: a query that finishes between polls must+ # still be visible via system.query_log, otherwise the run's progress reads zero for its whole life.+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="live-ql", name="live-ql")+ exp = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag, name="live-ql")+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=exp, status="in_progress", started_at=timezone.now()+ )++ with tags_context(+ team_id=self.team.id,+ client_query_id=f"experiment_metric_recalc_{recalc.id}_metric-1",+ product=Product.EXPERIMENTS,+ feature=Feature.CACHE_WARMUP,+ ):+ sync_execute("SELECT sum(number) FROM numbers(1000)", team_id=self.team.id)+ sync_execute("SYSTEM FLUSH LOGS")++ with team_scope(self.team.id, canonical=True):+ progress = get_live_query_progress(recalc)++ assert progress is not None+ assert progress["rows_read"] == 1000+ assert progress["estimated_rows_total"] == 1000+ assert progress["running_metrics"] == 0diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 83992135be11..7714642972ef 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1687,22 +1687,22 @@ export interface ExperimentMetricsRecalculationApi {*/running_metrics?: number | null/**- * Rows read so far by the currently-running metric queries (monotonic; the live progress signal)+ * Rows read by the run's metric queries so far, both finished and currently running. Cumulative and roughly monotonic across the run; the primary 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+ * ClickHouse's total_rows_approx across running queries plus the final read_rows of finished ones. A soft ceiling revised 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+ * Bytes read by the run's metric queries so far, both finished and currently running* @nullable*/bytes_read?: number | null/**- * Active CPU time (microseconds) consumed by the currently-running metric queries+ * Active CPU time (microseconds) consumed by the run's metric queries so far, both finished and currently running* @nullable*/active_cpu_time?: number | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 308a4af07e94..a09aa10b5592 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -22830,22 +22830,22 @@ export namespace Schemas {*/running_metrics?: number | null;/**- * Rows read so far by the currently-running metric queries (monotonic; the live progress signal)+ * Rows read by the run's metric queries so far, both finished and currently running. Cumulative and roughly monotonic across the run; the primary 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+ * ClickHouse's total_rows_approx across running queries plus the final read_rows of finished ones. A soft ceiling revised 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+ * Bytes read by the run's metric queries so far, both finished and currently running* @nullable*/bytes_read?: number | null;/**- * Active CPU time (microseconds) consumed by the currently-running metric queries+ * Active CPU time (microseconds) consumed by the run's metric queries so far, both finished and currently running* @nullable*/active_cpu_time?: number | null;