: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): recalculation workflow metrics interceptor. (#60603)
Rodrigo Ilorobbc669ef318c
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex 36cec8777078..dfd3b1a355b3 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -53,6 +53,11 @@ from posthog.temporal.session_replay.delete_recordings.metrics import ()from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptor+from products.experiments.backend.temporal.recalculation_metrics import (+ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS,+ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,+ ExperimentsRecalculationMetricsInterceptor,+)from products.logs.backend.temporal.metrics import (LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS,LOGS_ALERTING_COUNT_HISTOGRAM_METRICS,@@ -134,6 +139,7 @@ ALL_INTERCEPTOR_CLASSES = [SentimentMetricsInterceptor,EvalReportsMetricsInterceptor,LogsAlertingMetricsInterceptor,+ ExperimentsRecalculationMetricsInterceptor,]@@ -264,6 +270,12 @@ async def create_worker()| dict(zip(LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(LOGS_ALERTING_COUNT_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS)))+ | dict(+ zip(+ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,+ itertools.repeat(EXPERIMENT_METRICS_RECALCULATION_LATENCY_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/temporal/recalculation_metrics.py b/products/experiments/backend/temporal/recalculation_metrics.pynew file mode 100644index 000000000000..5af4d8f23a5b--- /dev/null+++ b/products/experiments/backend/temporal/recalculation_metrics.py@@ -0,0 +1,131 @@+"""Prometheus metrics for the experiment metrics recalculation workflow.++Follows the established Temporal interceptor pattern (see posthog/temporal/ai_observability/metrics.py).+Emits two latency histograms via ``ExecutionTimeRecorder`` (activity-level, labeled by activity_type;+workflow-level, end-to-end) plus counters for activity success/failure and workflow starts. The histogram+names match ``EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS`` so the bucket boundaries+registered in ``posthog/temporal/common/worker.py`` actually apply.+"""++import typing++from django.conf import settings++from temporalio import activity, workflow+from temporalio.worker import (+ ActivityInboundInterceptor,+ ExecuteActivityInput,+ ExecuteWorkflowInput,+ Interceptor,+ WorkflowInboundInterceptor,+ WorkflowInterceptorClassInput,+)++from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder++# The workflow type name (matches @workflow.defn(name=...) in recalculation_workflow).+_RECALCULATION_WORKFLOW_TYPE = "experiment-metrics-recalculation-workflow"+# Activity type names (the registered activity function names).+_RECALCULATION_ACTIVITY_TYPES = {+ "discover_experiment_metrics",+ "calculate_experiment_metric_for_recalculation",+ "update_recalculation_progress",+}++EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS = (+ "experiment_metrics_recalculation_activity_execution_latency",+ "experiment_metrics_recalculation_workflow_execution_latency",+)+EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS = [+ 100.0, # 100ms+ 500.0, # 500ms+ 1_000.0, # 1s+ 5_000.0, # 5s+ 10_000.0, # 10s+ 30_000.0, # 30s+ 60_000.0, # 1m+ 120_000.0, # 2m+ 300_000.0, # 5m+]+++def increment_workflow_finished(status: str) -> None:+ """Workflow-body callsite for the terminal lifecycle counter.++ Emitted from inside `ExperimentMetricsRecalculationWorkflow.run` rather than the interceptor so the+ `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.metric_meter().with_additional_attributes({"status": status}).create_counter(+ "experiment_metrics_recalculation_workflow_finished",+ "Number of experiment metrics recalculation workflows that reached a terminal state.",+ ).add(1)+++class _ActivityInboundInterceptor(ActivityInboundInterceptor):+ async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:+ activity_type = activity.info().activity_type+ if activity_type not in _RECALCULATION_ACTIVITY_TYPES:+ return await super().execute_activity(input)++ meter = activity.metric_meter().with_additional_attributes({"activity_type": activity_type})+ try:+ with ExecutionTimeRecorder(+ "experiment_metrics_recalculation_activity_execution_latency",+ description="Execution latency for experiment metrics recalculation activities.",+ histogram_attributes={"activity_type": activity_type},+ ):+ result = await super().execute_activity(input)+ except Exception:+ meter.create_counter(+ "experiment_metrics_recalculation_activity_failures",+ "Number of failed experiment metrics recalculation activity executions.",+ ).add(1)+ raise+ meter.create_counter(+ "experiment_metrics_recalculation_activity_successes",+ "Number of successful experiment metrics recalculation activity executions.",+ ).add(1)+ return result+++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(+ "experiment_metrics_recalculation_workflow_started",+ "Number of experiment metrics recalculation workflows started.",+ ).add(1)+ try:+ with ExecutionTimeRecorder(+ "experiment_metrics_recalculation_workflow_execution_latency",+ description="End-to-end execution latency for the experiment metrics recalculation workflow.",+ ):+ return await super().execute_workflow(input)+ except BaseException:+ # The workflow body emits `increment_workflow_finished` immediately before its return statements,+ # so any exception escaping past here means the body's call never ran — no risk of double-count.+ # Without this, hard failures (activity retries exhausted, non-retryable ApplicationError, etc.)+ # increment `_workflow_started` but not `_workflow_finished`, silently under-counting in any+ # `finished / started` success-rate dashboard.+ increment_workflow_finished("failed")+ raise+++class ExperimentsRecalculationMetricsInterceptor(Interceptor):+ """Interceptor emitting Prometheus metrics for the experiment metrics recalculation workflow."""++ # Required by `is_task_queue_supported` in `posthog/temporal/common/interceptor.py` — without this attribute+ # the interceptor is filtered out of every worker and the metrics never emit. The recalc workflow + activities+ # are registered on this queue in `posthog/management/commands/start_temporal_worker.py`.+ task_queue = settings.GENERAL_PURPOSE_TASK_QUEUE++ def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:+ return _ActivityInboundInterceptor(super().intercept_activity(next))++ def workflow_interceptor_class(+ self, input: WorkflowInterceptorClassInput+ ) -> type[WorkflowInboundInterceptor] | None:+ return _WorkflowInboundInterceptordiff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex ef0b6181ce4a..de49018d71ca 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -17,6 +17,7 @@ with temporalio.workflow.unsafe.imports_passed_through():discover_experiment_metrics,update_recalculation_progress,)+ from products.experiments.backend.temporal.recalculation_metrics import increment_workflow_finishedMAX_CONCURRENT_METRICS = 10@@ -72,6 +73,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)temporalio.workflow.logger.info(f"recalc {recalculation_id} had no metrics; completing immediately")+ increment_workflow_finished("completed")return {"total": 0, "succeeded": 0, "failed": 0}# Start the run: mark in_progress, persist the metric list, and pin the shared data-window end. The start@@ -134,4 +136,5 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):temporalio.workflow.logger.info(f"recalc {recalculation_id} finished: {succeeded} succeeded, {failed} failed (status={final_status})")+ increment_workflow_finished(final_status)return {"total": len(metrics), "succeeded": succeeded, "failed": failed}diff --git a/products/experiments/backend/temporal/test_recalculation_metrics.py b/products/experiments/backend/temporal/test_recalculation_metrics.pynew file mode 100644index 000000000000..509e37562f3b--- /dev/null+++ b/products/experiments/backend/temporal/test_recalculation_metrics.py@@ -0,0 +1,143 @@+import pytest+from unittest.mock import MagicMock, patch++from django.conf import settings++from parameterized import parameterized+from temporalio.worker import ActivityInboundInterceptor++from posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder+from posthog.temporal.common.interceptor import is_task_queue_supported++from products.experiments.backend.temporal import recalculation_metrics+from products.experiments.backend.temporal.recalculation_metrics import (+ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS,+ EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,+ ExperimentsRecalculationMetricsInterceptor,+ increment_workflow_finished,+)+++def test_registered_on_general_purpose_queue():+ # Pins the interceptor's `task_queue` ClassVar — without it, `is_task_queue_supported` filters the+ # interceptor out of every worker and the metrics emit nothing.+ assert is_task_queue_supported(settings.GENERAL_PURPOSE_TASK_QUEUE, ExperimentsRecalculationMetricsInterceptor)+++def test_metric_names_defined():+ assert (+ "experiment_metrics_recalculation_activity_execution_latency"+ in EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS+ )+ assert (+ "experiment_metrics_recalculation_workflow_execution_latency"+ in EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS+ )+++def test_buckets_sorted_ascending_and_floats():+ buckets = EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS+ assert buckets == sorted(buckets)+ assert all(isinstance(b, float) for b in buckets)+++def test_interceptor_wraps_activity():+ class _Sentinel(ActivityInboundInterceptor):+ pass++ interceptor = ExperimentsRecalculationMetricsInterceptor()+ wrapped = interceptor.intercept_activity(_Sentinel(None)) # type: ignore[arg-type]+ assert isinstance(wrapped, ActivityInboundInterceptor)+++ [+ # Pins the contract that the histogram name passed to ExecutionTimeRecorder matches the constant we+ # registered for bucket overrides in posthog/temporal/common/worker.py. If a future refactor renames+ # either side without renaming the other, the worker's bucket override silently becomes dead config+ # (no histogram with that name ever fires, so the override key never resolves).+ ("activity_histogram", "experiment_metrics_recalculation_activity_execution_latency"),+ ("workflow_histogram", "experiment_metrics_recalculation_workflow_execution_latency"),+ ]+)+def test_registered_histogram_names_are_emitted(name: str, histogram_name: str):+ assert histogram_name in EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS++ mock_meter = MagicMock()+ mock_hist = MagicMock()+ mock_meter.create_histogram_timedelta.return_value = mock_hist++ # ExecutionTimeRecorder.__exit__ calls bare get_metric_meter() inside posthog.temporal.common.metrics,+ # so the patch target is the original definition (the ai_observability module just re-exports it).+ with patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter):+ with ExecutionTimeRecorder(histogram_name):+ pass++ mock_meter.create_histogram_timedelta.assert_called_once()+ assert mock_meter.create_histogram_timedelta.call_args.kwargs["name"] == histogram_name+ mock_hist.record.assert_called_once()+++ [+ ("completed_status", "completed"),+ ("failed_status", "failed"),+ ]+)+def test_increment_workflow_finished_emits_status_attribute(name: str, status: str):+ # Counter is the only workflow-level lifecycle signal that distinguishes business outcomes (all-succeeded+ # vs at-least-one-failed). The status attribute is what `recalc-success-rate` dashboards key off.+ mock_meter = MagicMock()+ mock_meter_with_attrs = MagicMock()+ mock_counter = MagicMock()+ mock_meter.with_additional_attributes.return_value = mock_meter_with_attrs+ mock_meter_with_attrs.create_counter.return_value = mock_counter++ with patch(+ "products.experiments.backend.temporal.recalculation_metrics.workflow.metric_meter",+ return_value=mock_meter,+ ):+ increment_workflow_finished(status)++ mock_meter.with_additional_attributes.assert_called_once_with({"status": status})+ 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"+ )+ mock_counter.add.assert_called_once_with(1)+++async def test_workflow_interceptor_emits_finished_failed_on_hard_failure():+ # If the inner execute_workflow raises (activity retries exhausted, non-retryable ApplicationError, etc.),+ # the workflow body's `increment_workflow_finished` call never runs. Without the interceptor's except path,+ # `_workflow_started` increments but `_workflow_finished` does not, and any `finished / started` dashboard+ # silently under-counts hard failures. The interceptor closes that gap before re-raising.+ from unittest.mock import AsyncMock++ boom = RuntimeError("activity retries exhausted")+ next_interceptor = MagicMock()+ next_interceptor.execute_workflow = AsyncMock(side_effect=boom)++ interceptor = recalculation_metrics._WorkflowInboundInterceptor(next_interceptor)++ mock_info = MagicMock()+ mock_info.workflow_type = "experiment-metrics-recalculation-workflow"++ with (+ patch("products.experiments.backend.temporal.recalculation_metrics.workflow.info", return_value=mock_info),+ patch(+ "products.experiments.backend.temporal.recalculation_metrics.workflow.metric_meter",+ return_value=MagicMock(),+ ),+ # ExecutionTimeRecorder reaches into Temporal's workflow context on exit; stub it for the unit test.+ # Patch target is posthog.temporal.common.metrics — that's where ExecutionTimeRecorder's bare+ # get_metric_meter() call resolves. Patching the ai_observability re-export leaves the real call live.+ patch("posthog.temporal.common.metrics.get_metric_meter", return_value=MagicMock()),+ patch(+ "products.experiments.backend.temporal.recalculation_metrics.increment_workflow_finished"+ ) as mock_finished,+ ):+ with pytest.raises(RuntimeError, match="activity retries exhausted"):+ await interceptor.execute_workflow(MagicMock())++ mock_finished.assert_called_once_with("failed")diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex 728fe34b03f3..636770d919d9 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -1,6 +1,7 @@import uuidimport pytest+from unittest.mock import patchimport temporalio.workerfrom parameterized import parameterized@@ -155,6 +156,32 @@ class TestExperimentMetricsRecalculationWorkflow:# one of mark_started / mark_completed set.await _run_workflow([mock_discover, progress_with_xor_guard, mock_calculate])+ @parameterized.expand(+ [+ # name, failed_uuids, metrics, expected_status — covers both return sites (empty and fan-out) and+ # both terminal status values. Without this, either return site could silently lose the counter+ # call without any test failure.+ ("empty_completes", set(), [], "completed"),+ ("all_succeed_completes", set(), [_metric("m1"), _metric("m2")], "completed"),+ ("any_failure_fails", {"m1"}, [_metric("m1"), _metric("m2")], "failed"),+ ]+ )+ async def test_workflow_finished_counter_fires_with_terminal_status(+ self, name: str, failed_uuids: set, metrics: list[ExperimentMetricToRecalculate], expected_status: str+ ):+ metric_results = {+ uuid_: MetricRecalculationResult(metric_uuid=uuid_, success=False, error_step="calculation")+ for uuid_ in failed_uuids+ }+ activities, _progress, _calls = _make_mock_activities(metrics=metrics, metric_results=metric_results)++ with patch(+ "products.experiments.backend.temporal.recalculation_workflow.increment_workflow_finished"+ ) as mock_finished:+ await _run_workflow(activities)++ mock_finished.assert_called_once_with(expected_status)+async def test_workflow_fails_non_retryable_if_start_activity_returns_none(self):# The workflow narrows the start activity's Optional[str] return into a real str via an if/raise# (not assert, which python -O strips). If the activity ever violates its contract and returns None,diff --git a/tach.toml b/tach.tomlindex 8bf1baf8126f..9d4219244e79 100644--- a/tach.toml+++ b/tach.toml@@ -665,17 +665,15 @@ from = ["products.experiments",]-# Temporal worker registration lives in posthog/management/commands/start_temporal_worker.py, which imports-# ACTIVITIES and WORKFLOWS from each product's backend.temporal package, and schedule registration lives in-# posthog/temporal/schedule.py, which imports each product's schedule-creation functions. Eight peer products-# do the same thing, but experiments is the first isolated product to register a workflow, so the canonical-# interface doesn't cover it yet. Narrowly expose just the registration symbols rather than widening every-# isolated product's surface.+# Experiments is the first isolated product to register a Temporal workflow, so the canonical interface+# doesn't cover the registration surface yet. Narrowly expose the symbols core imports (worker registration,+# schedule registration, and the worker interceptor) rather than widening every isolated product's surface.[[interfaces]]expose = ["backend\\.temporal\\.ACTIVITIES","backend\\.temporal\\.WORKFLOWS",+ "backend\\.temporal\\.recalculation_metrics.*","backend\\.temporal\\.schedule\\.create_experiment_precompute_canary_schedule",]from = [