: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 observability to metric recalculation workflow (#63165)
Rodrigo Ilorob3c63909fc10
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex dfd3b1a355b3..559f20354e7b 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -54,6 +54,8 @@ from posthog.temporal.session_replay.delete_recordings.metrics import (from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptorfrom products.experiments.backend.temporal.recalculation_metrics import (+ EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_BUCKETS,+ EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_METRICS,EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS,EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,ExperimentsRecalculationMetricsInterceptor,@@ -276,6 +278,12 @@ async def create_worker(itertools.repeat(EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS),))+ | dict(+ zip(+ EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_METRICS,+ itertools.repeat(EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_BUCKETS),+ )+ )| {"batch_exports_activity_attempt": [1.0, 5.0, 10.0, 100.0]})if task_queue == settings.DATA_MODELING_TASK_QUEUE:diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex 55ce932022bd..0e9e7246e7f6 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -16,6 +16,7 @@ from django.db import transactionfrom django.db.models import Qfrom django.utils import timezone+from prometheus_client import Counterfrom rest_framework.exceptions import ValidationErrorfrom posthog.models.scoping import team_scope@@ -30,7 +31,7 @@ from products.experiments.backend.models.experiment import ()from products.experiments.backend.result_serialization import strip_step_sessionsfrom products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint-from products.experiments.backend.temporal.recalculation_logic import discover_metrics_for_experiment, find_metric_dict+from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics, find_metric_dict# How long an active (PENDING/IN_PROGRESS) row blocks new recalculations. Beyond this, the row is treated as# stale and a fresh recalc is allowed. Sized to be safely above the workflow's worst-case end-to-end runtime@@ -40,6 +41,20 @@ from products.experiments.backend.temporal.recalculation_logic import discover_m# happy-path failure handling; this TTL is the defense-in-depth backstop if that rollback itself fails._STALE_RECALC_THRESHOLD = timedelta(minutes=30)+# `is_existing=True` reuse path — counts how often the idempotency guard saves us a workflow start.+# A sustained climb here without a matching climb in requests is the signal the frontend is double-posting.+_recalculation_reuse_counter = Counter(+ "experiment_metrics_recalculation_existing_run_reused",+ "POST requests that returned an existing active run instead of creating a new one (idempotent reuse).",+)+# Fires whenever the 30-min staleness threshold marks a PENDING/IN_PROGRESS row FAILED so the experiment+# can recalculate again. A sustained climb is a leading indicator of Temporal connect failures or the+# rollback path in views.py itself failing.+_recalculation_stale_cleanup_counter = Counter(+ "experiment_metrics_recalculation_stale_rows_cleaned",+ "Stale recalc rows force-failed to release the per-experiment uniqueness constraint.",+)+def _derive_counters(recalc: ExperimentMetricsRecalculation, results: list[dict] | None = None) -> tuple[int, int]:"""Counters are not stored on the row (PR1 contract): they're derived on read from result rows + errors.@@ -128,22 +143,25 @@ def request_recalculation(experiment: Experiment, user: User, trigger: str = "ma.first())if existing:+ _recalculation_reuse_counter.inc()return build_job_payload(existing, is_existing=True)# No fresh active row, but stale tombstones might still hold the per-experiment uniqueness constraint# (unique_active_metrics_recalculation_per_experiment). Mark them FAILED so the constraint releases# and the new row can land. Status reflects reality — these workflows are not coming back.- ExperimentMetricsRecalculation.objects.filter(+ cleaned_count = ExperimentMetricsRecalculation.objects.filter(experiment=experiment,status__in=[ExperimentMetricsRecalculation.Status.PENDING,ExperimentMetricsRecalculation.Status.IN_PROGRESS,],).update(status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=timezone.now())+ if cleaned_count:+ _recalculation_stale_cleanup_counter.inc(cleaned_count)# Set total_metrics up front from the experiment definition so the client can show progress# ("N of M") immediately, before the workflow's discovery activity confirms the same count.- metrics = discover_metrics_for_experiment(experiment)+ metrics = discover_experiment_metrics(experiment)recalc = ExperimentMetricsRecalculation.objects.create(team=experiment.team,experiment=experiment,diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex 74eeb043e699..7e673bc8a9de 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -134,3 +134,7 @@ class RecalculationProgressUpdate:metric_uuids: list[str] | None = Nonemark_started: bool = Falsemark_completed: bool = False+ # Run-level outcome carried on the finish step so the activity can emit the+ # 'experiment results refresh completed' analytics event with real counts.+ succeeded_metrics: int | None = None+ failed_metrics: int | None = Nonediff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 8608c90f3c7f..19d6afec803a 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -36,11 +36,19 @@ async def update_recalculation_progress(update: RecalculationProgressUpdate) ->@temporalio.activity.defnasync def calculate_experiment_metric_for_recalculation(- experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",) -> MetricRecalculationResult:"""Calculate one metric, write its recalc-fingerprinted result to ExperimentMetricResult, and fold theprogress update (counter + error) into the same job atomically. query_to is the run's shared data-window end.++ metric_type is the primary/secondary classification carried from discovery; it's threaded into the per-metric+ PostHog event so the capture path doesn't have to re-query the saved-metric M2M to resolve it. Defaults to+ "primary" so existing call sites and tests that don't pass it remain valid."""return await _calculate_experiment_metric_for_recalculation_sync(- experiment_id, metric_uuid, recalculation_id, query_to+ experiment_id, metric_uuid, recalculation_id, query_to, metric_type)diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex eb7ae52e79e5..5f66073bdada 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -4,8 +4,10 @@ The thin ``@temporalio.activity.defn`` entrypoints live in ``recalculation_activmodule holds the DB-touching ``_*_sync`` implementations plus the pure helpers they compose from."""+import timeimport dataclassesfrom datetime import datetime+from typing import Anyfrom django.db import close_old_connections, transactionfrom django.utils import timezone@@ -16,10 +18,12 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.schema import ExperimentQueryfrom posthog.clickhouse.client.connection import Workload-from posthog.clickhouse.query_tagging import tag_queries+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.scoping import team_scope+from posthog.ph_client import ph_scoped_capturefrom posthog.sync import database_sync_to_asyncfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint@@ -88,17 +92,16 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:)-def discover_metrics_for_experiment(experiment: Experiment) -> list[ExperimentMetricToRecalculate]:- """Traverse the experiment definition and return the list of metrics a recalc should process.+def discover_experiment_metrics(experiment: Experiment) -> list[ExperimentMetricToRecalculate]:+ """All metrics to recalculate for an experiment, in (primary, secondary, saved) order.- Pure read of the experiment object — no database writes, no scoping concerns. The activity wrapper- (`_discover_experiment_metrics_sync`) loads + scopes + persists `metric_uuids`; the service layer can- call this directly when it already has the experiment in scope (e.g., to seed `total_metrics` at create- time so the client can show progress without waiting for the workflow's discovery activity to run).+ Single source of truth for "which metrics does this experiment have" — used both to set+ ``total_metrics`` at recalculation-create time and by the discovery activity. Touches the DB+ (saved-metric links), so call inside a team scope / sync context.- Named `discover_metrics_for_experiment` (not `discover_experiment_metrics`) to avoid colliding with the- Temporal activity of the same shape in `recalculation_activities.py`, which takes a `recalculation_id`- instead of an Experiment.+ Note: this sync helper takes an ``Experiment``. The async Temporal activity in+ ``recalculation_activities.py`` shares the name but takes a ``recalculation_id`` — disambiguate by+ import path and argument type at the call site."""metrics_to_recalculate: list[ExperimentMetricToRecalculate] = []@@ -135,7 +138,7 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMrecalculation = ExperimentMetricsRecalculation.objects.select_related("experiment").get(id=recalculation_id)experiment = recalculation.experiment- metrics_to_recalculate = discover_metrics_for_experiment(experiment)+ metrics_to_recalculate = discover_experiment_metrics(experiment)recalculation.metric_uuids = [m.metric_uuid for m in metrics_to_recalculate]recalculation.save(update_fields=["metric_uuids"])@@ -193,13 +196,69 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -># Finish: same first-write-wins guard so a retried mark_completed activity doesn't re-stamp the# completion timestamp (and, by symmetry with mark_started, doesn't reopen a closed run).- ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, completed_at__isnull=True).update(- completed_at=timezone.now(),- status=update.status or ExperimentMetricsRecalculation.Status.COMPLETED,+ won = (+ ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, completed_at__isnull=True).update(+ completed_at=timezone.now(),+ status=update.status or ExperimentMetricsRecalculation.Status.COMPLETED,+ )+ == 1)+ # Emit the run-level analytics event only on the winning (first) completion, so a retried+ # mark_completed doesn't double-count.+ if won:+ _capture_results_refresh_completed(update)return None+def _capture_results_refresh_completed(update: RecalculationProgressUpdate) -> None:+ """Run-level analytics: 'experiment results refresh completed' with the final counts. Mirrors the+ legacy client-side event. Telemetry must never fail the activity, so swallow any error."""+ try:+ recalc = (+ ExperimentMetricsRecalculation.objects.select_related("experiment", "experiment__team")+ .filter(id=update.recalculation_id)+ .first()+ )+ if recalc is None:+ return+ experiment = recalc.experiment+ team = experiment.team+ distinct_id = (+ experiment.created_by.distinct_id+ if experiment.created_by and experiment.created_by.distinct_id+ else f"team_{team.id}"+ )+ total_duration_ms = (+ round((recalc.completed_at - recalc.created_at).total_seconds() * 1000)+ if recalc.completed_at and recalc.created_at+ else None+ )+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=distinct_id,+ event="experiment results refresh completed",+ properties={+ "experiment_id": experiment.id,+ "team_id": team.id,+ "recalculation_id": str(recalc.id),+ "status": recalc.status,+ "total_metrics": recalc.total_metrics,+ "succeeded_metrics": update.succeeded_metrics,+ "failed_metrics": update.failed_metrics,+ "total_duration_ms": total_duration_ms,+ "trigger": recalc.trigger,+ "execution_mode": "recalculation",+ },+ groups=groups(organization=team.organization, team=team),+ )+ except Exception:+ logger.warning(+ "experiment_results_refresh_completed_capture_failed",+ recalculation_id=update.recalculation_id,+ exc_info=True,+ )++# ---------------------------------------------------------------------------# Calculation helpers# ---------------------------------------------------------------------------@@ -255,6 +314,62 @@ def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str) -> M)+# ---------------------------------------------------------------------------+# Product analytics (recalculation flow)+#+# These mirror the legacy client-side events ('experiment metric finished' / 'experiment metric error'),+# now that metrics are computed on the backend instead of in the browser. execution_mode='recalculation'+# distinguishes them from legacy events on the same dashboards.+# ---------------------------------------------------------------------------+++def _capture_experiment_metric_event(+ experiment: Experiment,+ metric_uuid: str,+ metric_type: str,+ metric_dict: dict | None,+ event: str,+ extra_properties: dict[str, Any],+) -> None:+ """Emit a per-metric product analytics event. Telemetry must never fail the activity, so any error+ is swallowed. Attributed to the experiment creator, falling back to a team-scoped distinct_id.++ `metric_type` is the primary/secondary classification carried from discovery+ (`ExperimentMetricToRecalculate.metric_type`), threaded through the workflow + activity args so the+ capture path doesn't have to re-query the M2M to resolve it.+ """+ try:+ team = experiment.team+ distinct_id = (+ experiment.created_by.distinct_id+ if experiment.created_by and experiment.created_by.distinct_id+ else f"team_{team.id}"+ )+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=distinct_id,+ event=event,+ properties={+ "experiment_id": experiment.id,+ "team_id": team.id,+ "metric_uuid": metric_uuid,+ "metric_kind": (metric_dict or {}).get("metric_type"),+ "is_primary": metric_type == "primary",+ "execution_mode": "recalculation",+ **extra_properties,+ },+ groups=groups(organization=team.organization, team=team),+ )+ except Exception:+ logger.warning(+ "experiment_metric_event_capture_failed",+ event=event,+ experiment_id=experiment.id,+ metric_uuid=metric_uuid,+ exc_info=True,+ )++# ---------------------------------------------------------------------------# Calculation# ---------------------------------------------------------------------------@@ -262,7 +377,11 @@ def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str) -> M@database_sync_to_asyncdef _calculate_experiment_metric_for_recalculation_sync(- experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",) -> MetricRecalculationResult:close_old_connections()@@ -326,6 +445,7 @@ def _calculate_experiment_metric_for_recalculation_sync()recalc_fp = compute_recalc_fingerprint(config_fp, recalculation_id)+ calc_started_at = time.perf_counter()try:# Metric build + query live inside the try so unexpected shapes surface as a calculation-step failure.# override_end_date forces the run's shared query_to into the ClickHouse query bounds. Without it@@ -337,7 +457,14 @@ def _calculate_experiment_metric_for_recalculation_sync(override_end_date=query_to_dt,workload=Workload.OFFLINE,)- tag_queries(trigger="warming/experiment_metrics_recalculation")+ # Attribute CH load back to this team + product so query_log analysis can tell whose recalc is+ # expensive without reverse-engineering the trigger string.+ tag_queries(+ trigger="warming/experiment_metrics_recalculation",+ team_id=state.team_id,+ product=Product.EXPERIMENTS,+ feature=Feature.CACHE_WARMUP,+ )result = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)result_dict = result.model_dump(mode="json")@@ -351,6 +478,14 @@ def _calculate_experiment_metric_for_recalculation_sync(result=result_dict,error_message=None,)+ _capture_experiment_metric_event(+ experiment,+ metric_uuid,+ metric_type,+ metric_dict,+ "experiment metric finished",+ {"duration_ms": round((time.perf_counter() - calc_started_at) * 1000)},+ )return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)except (StatisticError, ZeroDivisionError) as e:@@ -372,6 +507,18 @@ def _calculate_experiment_metric_for_recalculation_sync(metric_uuid=metric_uuid,error=message,)+ _capture_experiment_metric_event(+ experiment,+ metric_uuid,+ metric_type,+ metric_dict,+ "experiment metric error",+ {+ "duration_ms": round((time.perf_counter() - calc_started_at) * 1000),+ "error_type": "insufficient_data",+ "error_message": message,+ },+ )return _fail(recalculation_id, metric_uuid, "calculation", message)except Exception as e:@@ -404,4 +551,7 @@ def _calculate_experiment_metric_for_recalculation_sync(experiment_id=experiment_id,metric_uuid=metric_uuid,)+ # No 'experiment metric error' event here: this path re-raises and Temporal retries, so+ # emitting would double-count per attempt. The final failed count is reported once at the+ # run level ('experiment results refresh completed').raisediff --git a/products/experiments/backend/temporal/recalculation_metrics.py b/products/experiments/backend/temporal/recalculation_metrics.pyindex 5af4d8f23a5b..85dfb08bbe33 100644--- a/products/experiments/backend/temporal/recalculation_metrics.py+++ b/products/experiments/backend/temporal/recalculation_metrics.py@@ -48,6 +48,14 @@ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS = [300_000.0, # 5m]+# Bucket boundaries for `_activity_success_attempts` (counts the attempt number at which success was reached).+# With `RetryPolicy(maximum_attempts=2)` today, only buckets [1, 2] are populated, but the wider range survives+# a future policy change without needing a new histogram.+EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_METRICS = (+ "experiment_metrics_recalculation_activity_success_attempts",+)+EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_BUCKETS = [1.0, 2.0, 5.0, 10.0]+def increment_workflow_finished(status: str) -> None:"""Workflow-body callsite for the terminal lifecycle counter.@@ -56,8 +64,12 @@ def increment_workflow_finished(status: str) -> None:`status` attribute can be the run's business-level outcome (`"completed"` / `"failed"`, where `"failed"`means at least one metric failed). An interceptor-based version would only see exception-vs-no-exception,which conflates a 9-of-10-failed run with a healthy one.++ `workflow_type` is attached so dashboards stay scoped when other experiments workflows ship later."""- workflow.metric_meter().with_additional_attributes({"status": status}).create_counter(+ workflow.metric_meter().with_additional_attributes(+ {"status": status, "workflow_type": _RECALCULATION_WORKFLOW_TYPE}+ ).create_counter("experiment_metrics_recalculation_workflow_finished","Number of experiment metrics recalculation workflows that reached a terminal state.",).add(1)@@ -65,16 +77,30 @@ def increment_workflow_finished(status: str) -> None:class _ActivityInboundInterceptor(ActivityInboundInterceptor):async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:- activity_type = activity.info().activity_type+ info = activity.info()+ activity_type = info.activity_typeif activity_type not in _RECALCULATION_ACTIVITY_TYPES:return await super().execute_activity(input)- meter = activity.metric_meter().with_additional_attributes({"activity_type": activity_type})+ meter = activity.metric_meter().with_additional_attributes(+ {"activity_type": activity_type, "workflow_type": _RECALCULATION_WORKFLOW_TYPE}+ )+ # Fires on every attempt (first run + each retry). Comparing this to `_activity_successes` reveals+ # retry rate; without it a transient ClickHouse blip is indistinguishable from a healthy first-try+ # success. Pattern mirrors batch_exports' `batch_exports_activity_attempts`.+ meter.create_counter(+ "experiment_metrics_recalculation_activity_attempts",+ "Number of experiment metrics recalculation activity attempts (each retry is one attempt).",+ ).add(1)+try:with ExecutionTimeRecorder("experiment_metrics_recalculation_activity_execution_latency",description="Execution latency for experiment metrics recalculation activities.",- histogram_attributes={"activity_type": activity_type},+ histogram_attributes={+ "activity_type": activity_type,+ "workflow_type": _RECALCULATION_WORKFLOW_TYPE,+ },):result = await super().execute_activity(input)except Exception:@@ -87,6 +113,14 @@ class _ActivityInboundInterceptor(ActivityInboundInterceptor):"experiment_metrics_recalculation_activity_successes","Number of successful experiment metrics recalculation activity executions.",).add(1)+ # Records the attempt-count distribution for successful runs. info.attempt is 1 on a first-try success+ # and >1 when retries happened before success — `histogram_quantile(0.99, ...)` answers+ # "how often do we need to retry to succeed?". Matches batch_exports' success_attempts pattern.+ meter.create_histogram(+ name="experiment_metrics_recalculation_activity_success_attempts",+ description="Attempt number at which an activity execution succeeded (1 = first try).",+ unit="attempts",+ ).record(info.attempt)return result@@ -94,7 +128,9 @@ class _WorkflowInboundInterceptor(WorkflowInboundInterceptor):async def execute_workflow(self, input: ExecuteWorkflowInput) -> typing.Any:if workflow.info().workflow_type != _RECALCULATION_WORKFLOW_TYPE:return await super().execute_workflow(input)- workflow.metric_meter().create_counter(+ workflow.metric_meter().with_additional_attributes(+ {"workflow_type": _RECALCULATION_WORKFLOW_TYPE}+ ).create_counter("experiment_metrics_recalculation_workflow_started","Number of experiment metrics recalculation workflows started.",).add(1)@@ -102,6 +138,7 @@ class _WorkflowInboundInterceptor(WorkflowInboundInterceptor):with ExecutionTimeRecorder("experiment_metrics_recalculation_workflow_execution_latency",description="End-to-end execution latency for the experiment metrics recalculation workflow.",+ histogram_attributes={"workflow_type": _RECALCULATION_WORKFLOW_TYPE},):return await super().execute_workflow(input)except BaseException:diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex de49018d71ca..f02036691971 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -107,7 +107,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):async with semaphore:return await temporalio.workflow.execute_activity(calculate_experiment_metric_for_recalculation,- args=[metric.experiment_id, metric.metric_uuid, recalculation_id, query_to],+ args=[metric.experiment_id, metric.metric_uuid, recalculation_id, query_to, metric.metric_type],# No heartbeat: the activity's only long-running step is one blocking ClickHouse query# with no progress hooks, so start_to_close_timeout is the real per-attempt ceiling.start_to_close_timeout=timedelta(minutes=5),@@ -128,7 +128,13 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):final_status = "failed" if failed > 0 else "completed"await temporalio.workflow.execute_activity(update_recalculation_progress,- RecalculationProgressUpdate(recalculation_id=recalculation_id, status=final_status, mark_completed=True),+ RecalculationProgressUpdate(+ recalculation_id=recalculation_id,+ status=final_status,+ mark_completed=True,+ succeeded_metrics=succeeded,+ failed_metrics=failed,+ ),start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=3),)diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 5837306841e3..39ae9ac00a79 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -1,3 +1,4 @@+from contextlib import contextmanagerfrom datetime import datetimeimport pytest@@ -22,6 +23,7 @@ from products.experiments.backend.temporal.recalculation_logic import (_discover_experiment_metrics_sync,_update_recalculation_progress_sync,)+from products.experiments.stats.shared.statistics import StatisticErrorfrom products.feature_flags.backend.models.feature_flag import FeatureFlag_discover_raw = _discover_experiment_metrics_sync.func # type: ignore[attr-defined]@@ -39,9 +41,15 @@ def _update(update: RecalculationProgressUpdate):return _update_raw(update)-def _calculate(experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str):+def _calculate(+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",+):with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):- return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to)+ return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to, metric_type)@pytest.mark.django_db(transaction=True)@@ -565,3 +573,177 @@ class TestMissingRecalcRow:assert bogus_id in str(exc_info.value)assert "not found" in str(exc_info.value)assert exc_info.value.non_retryable is True+++@contextmanager+def _record_captures():+ """Patch ph_scoped_capture so the analytics tests can assert the exact event name + properties+ without standing up a real PostHog client. Yields the list of captured capture(...) kwargs."""+ captured: list[dict] = []++ def _fake_capture(*args, **kwargs) -> None:+ captured.append(kwargs)++ @contextmanager+ def _fake_scoped():+ yield _fake_capture++ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ph_scoped_capture",+ _fake_scoped,+ ):+ yield captured++[email protected]_db(transaction=True)+class TestRecalculationAnalytics(BaseTest):+ """Product analytics emitted by the recalculation activities. Names mirror the legacy client-side+ events; execution_mode='recalculation' distinguishes the backend-driven flow."""++ def _flag(self, key: str) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name=f"Flag for {key}",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ def _experiment(self, flag_key: str, *, metrics=None, secondary=None) -> Experiment:+ exp = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=self._flag(flag_key),+ name="exp",+ start_date=timezone.now(),+ )+ if metrics is not None:+ exp.metrics = metrics+ if secondary is not None:+ exp.metrics_secondary = secondary+ exp.save()+ return exp++ def _recalc(self, exp: Experiment, *, metric_uuids: list[str]) -> ExperimentMetricsRecalculation:+ return ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ metric_uuids=metric_uuids,+ total_metrics=len(metric_uuids),+ query_to=datetime.fromisoformat(_QUERY_TO),+ )++ def test_metric_finished_event_on_success(self):+ exp = self._experiment(flag_key="an-success", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with _record_captures() as captured:+ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"+ ) as mock_runner:+ mock_runner.return_value.run.return_value.model_dump.return_value = {}+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert len(captured) == 1+ props = captured[0]["properties"]+ assert captured[0]["event"] == "experiment metric finished"+ assert captured[0]["distinct_id"] == self.user.distinct_id+ assert props["experiment_id"] == exp.id+ assert props["team_id"] == self.team.id+ assert props["metric_uuid"] == "m1"+ assert props["metric_kind"] == "mean"+ assert props["is_primary"] is True+ assert props["execution_mode"] == "recalculation"+ assert "duration_ms" in props++ def test_metric_error_event_on_insufficient_data(self):+ exp = self._experiment(flag_key="an-error", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with _record_captures() as captured:+ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"+ ) as mock_runner:+ mock_runner.return_value.run.side_effect = StatisticError("not enough data")+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert len(captured) == 1+ props = captured[0]["properties"]+ assert captured[0]["event"] == "experiment metric error"+ assert props["error_type"] == "insufficient_data"+ assert props["error_message"] == "not enough data"+ assert props["execution_mode"] == "recalculation"++ def test_secondary_metric_is_not_marked_primary(self):+ # metric_type is now threaded through from the workflow's discovery output rather than re-derived+ # from a fresh DB lookup. The activity's caller (workflow) reads the value from+ # ExperimentMetricToRecalculate; tests pass it explicitly to exercise the same path.+ exp = self._experiment(flag_key="an-secondary", secondary=[_mean_metric("s1")])+ recalc = self._recalc(exp, metric_uuids=["s1"])++ with _record_captures() as captured:+ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"+ ) as mock_runner:+ mock_runner.return_value.run.return_value.model_dump.return_value = {}+ _calculate(exp.id, "s1", str(recalc.id), _QUERY_TO, metric_type="secondary")++ assert captured[0]["properties"]["is_primary"] is False++ def test_transient_failure_emits_no_per_metric_event(self):+ # The transient except-Exception path re-raises for Temporal to retry; emitting there would+ # double-count per attempt. The failure is reflected in the run-level event instead.+ exp = self._experiment(flag_key="an-transient", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with _record_captures() as captured:+ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"+ ) as mock_runner:+ mock_runner.return_value.run.side_effect = RuntimeError("kaboom")+ with pytest.raises(RuntimeError, match="kaboom"):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert captured == []++ def test_results_refresh_completed_event_on_finish(self):+ exp = self._experiment(flag_key="an-finish", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with _record_captures() as captured:+ _update(+ RecalculationProgressUpdate(+ recalculation_id=str(recalc.id),+ status="completed",+ mark_completed=True,+ succeeded_metrics=3,+ failed_metrics=1,+ )+ )++ assert len(captured) == 1+ props = captured[0]["properties"]+ assert captured[0]["event"] == "experiment results refresh completed"+ assert captured[0]["distinct_id"] == self.user.distinct_id+ assert props["experiment_id"] == exp.id+ assert props["team_id"] == self.team.id+ assert props["recalculation_id"] == str(recalc.id)+ assert props["status"] == "completed"+ assert props["succeeded_metrics"] == 3+ assert props["failed_metrics"] == 1+ assert props["execution_mode"] == "recalculation"+ assert "total_duration_ms" in props++ def test_results_refresh_completed_not_re_emitted_on_retry(self):+ # mark_completed is first-write-wins; a retried finish activity must not re-fire the run-level event.+ exp = self._experiment(flag_key="an-finish-retry", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ update = RecalculationProgressUpdate(+ recalculation_id=str(recalc.id), status="completed", mark_completed=True, succeeded_metrics=1+ )+ with _record_captures() as captured:+ _update(update)+ _update(update) # simulated Temporal retry++ assert len(captured) == 1diff --git a/products/experiments/backend/temporal/test_recalculation_metrics.py b/products/experiments/backend/temporal/test_recalculation_metrics.pyindex 509e37562f3b..03d9bdfe1d2c 100644--- a/products/experiments/backend/temporal/test_recalculation_metrics.py+++ b/products/experiments/backend/temporal/test_recalculation_metrics.py@@ -99,7 +99,9 @@ def test_increment_workflow_finished_emits_status_attribute(name: str, status: s):increment_workflow_finished(status)- mock_meter.with_additional_attributes.assert_called_once_with({"status": status})+ mock_meter.with_additional_attributes.assert_called_once_with(+ {"status": status, "workflow_type": "experiment-metrics-recalculation-workflow"}+ )mock_meter_with_attrs.create_counter.assert_called_once()assert (mock_meter_with_attrs.create_counter.call_args.args[0] == "experiment_metrics_recalculation_workflow_finished"diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex 636770d919d9..503c6505fa69 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -47,9 +47,13 @@ def _make_mock_activities(@activity.defn(name="calculate_experiment_metric_for_recalculation")async def mock_calculate(- experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",) -> MetricRecalculationResult:- calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to))+ calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to, metric_type))return metric_results.get(metric_uuid, MetricRecalculationResult(metric_uuid=metric_uuid, success=True))activities = [mock_discover, mock_update_progress, mock_calculate]@@ -148,7 +152,11 @@ class TestExperimentMetricsRecalculationWorkflow:@activity.defn(name="calculate_experiment_metric_for_recalculation")async def mock_calculate(- experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)@@ -196,7 +204,11 @@ class TestExperimentMetricsRecalculationWorkflow:@activity.defn(name="calculate_experiment_metric_for_recalculation")async def mock_calculate(- experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex c29fd9aba967..d5ff0155a7e2 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -14,6 +14,8 @@ from products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,ExperimentMetricsRecalculation,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,)from products.experiments.backend.recalculation import (get_latest_recalculation,@@ -72,6 +74,25 @@ class TestRecalculationService(BaseTest):assert result["is_existing"] is Falseassert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1+ def test_request_recalculation_sets_total_metrics_from_experiment(self):+ # inline primary + inline secondary + one saved (shared) metric → total of 3+ exp = self._launched_experiment(flag_key="total-metrics")+ exp.metrics = [_mean_metric("p1")]+ exp.metrics_secondary = [_mean_metric("s1")]+ exp.save()+ saved = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="saved-shared1",+ query={"uuid": "shared1", "kind": "ExperimentMetric", "metric_type": "mean"},+ )+ ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": "primary"})++ result = request_recalculation(exp, self.user, "manual")++ row = ExperimentMetricsRecalculation.objects.get(id=result["id"])+ assert row.total_metrics == 3+ assert set(row.metric_uuids) == {"p1", "s1", "shared1"}+def test_request_recalculation_is_idempotent(self):exp = self._launched_experiment()first = request_recalculation(exp, self.user, "manual")