Skip to content

: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.

feat(experiments): metrics recalculation workflow registration (#60602)

Rodrigo Iloro467a7490c1eb
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 9ef287641d00..bfaa043c5ff0 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -361,7 +361,7 @@ jobs:
- name: Check for changes that affect general purpose temporal worker
id: check_changes_general_purpose_temporal_worker
run: |
- if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then
echo "changed=true" >> $GITHUB_OUTPUT
else
echo "changed=false" >> $GITHUB_OUTPUT
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index c75bea1c357b..125849ad4ab8 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -175,6 +175,10 @@ from products.error_tracking.backend.temporal import (
ACTIVITIES as ERROR_TRACKING_ACTIVITIES,
WORKFLOWS as ERROR_TRACKING_WORKFLOWS,
)
+from products.experiments.backend.temporal import (
+ ACTIVITIES as EXPERIMENTS_RECALCULATION_ACTIVITIES,
+ WORKFLOWS as EXPERIMENTS_RECALCULATION_WORKFLOWS,
+)
from products.exports.backend.temporal.subscriptions import (
ACTIVITIES as SUBSCRIPTION_ACTIVITIES,
WORKFLOWS as SUBSCRIPTION_WORKFLOWS,
@@ -238,6 +242,7 @@ _task_queue_specs = [
+ DLQ_REPLAY_WORKFLOWS
+ SYNC_PERSON_DISTINCT_IDS_WORKFLOWS
+ EXPERIMENTS_WORKFLOWS
+ + EXPERIMENTS_RECALCULATION_WORKFLOWS
+ CLEANUP_PROPDEFS_WORKFLOWS
+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS
+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,
@@ -250,6 +255,7 @@ _task_queue_specs = [
+ DLQ_REPLAY_ACTIVITIES
+ SYNC_PERSON_DISTINCT_IDS_ACTIVITIES
+ EXPERIMENTS_ACTIVITIES
+ + EXPERIMENTS_RECALCULATION_ACTIVITIES
+ CLEANUP_PROPDEFS_ACTIVITIES
+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES
+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES,
diff --git a/products/experiments/backend/temporal/__init__.py b/products/experiments/backend/temporal/__init__.py
index 2fce1928e501..fbd093eff500 100644
--- a/products/experiments/backend/temporal/__init__.py
+++ b/products/experiments/backend/temporal/__init__.py
@@ -3,9 +3,11 @@ from products.experiments.backend.temporal.recalculation_activities import (
discover_experiment_metrics,
update_recalculation_progress,
)
+from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
-# The workflow is registered in a later PR; until then the package exposes no workflows.
-WORKFLOWS: list[type] = []
+WORKFLOWS = [
+ ExperimentMetricsRecalculationWorkflow,
+]
ACTIVITIES = [
discover_experiment_metrics,
calculate_experiment_metric_for_recalculation,
@@ -15,6 +17,7 @@ ACTIVITIES = [
__all__ = [
"ACTIVITIES",
"WORKFLOWS",
+ "ExperimentMetricsRecalculationWorkflow",
"calculate_experiment_metric_for_recalculation",
"discover_experiment_metrics",
"update_recalculation_progress",
diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.py
new file mode 100644
index 000000000000..ef0b6181ce4a
--- /dev/null
+++ b/products/experiments/backend/temporal/recalculation_workflow.py
@@ -0,0 +1,137 @@
+import asyncio
+from datetime import timedelta
+
+import temporalio.workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with temporalio.workflow.unsafe.imports_passed_through():
+ from products.experiments.backend.temporal.models import (
+ ExperimentMetricsRecalculationWorkflowInputs,
+ RecalculationProgressUpdate,
+ )
+ from products.experiments.backend.temporal.recalculation_activities import (
+ calculate_experiment_metric_for_recalculation,
+ discover_experiment_metrics,
+ update_recalculation_progress,
+ )
+
+MAX_CONCURRENT_METRICS = 10
+
+
[email protected](name="experiment-metrics-recalculation-workflow")
+class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
+ """Recalculate all metrics for an experiment on demand.
+
+ Each run discovers all metrics, marks the job in_progress (which also pins the single data-window end), fans
+ out one calc activity per metric with bounded concurrency, then finalizes the job status. Per-metric progress
+ counters and errors are folded into the calc activity itself, so the workflow only writes progress at start
+ and finish.
+ """
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ExperimentMetricsRecalculationWorkflowInputs:
+ return ExperimentMetricsRecalculationWorkflowInputs(recalculation_id=inputs[0])
+
+ @temporalio.workflow.run
+ async def run(self, inputs: ExperimentMetricsRecalculationWorkflowInputs) -> dict:
+ recalculation_id = inputs.recalculation_id
+
+ metrics = await temporalio.workflow.execute_activity(
+ discover_experiment_metrics,
+ recalculation_id,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ if not metrics:
+ # mark_started and mark_completed are mutually exclusive per the activity's XOR contract;
+ # for a zero-metric run, start and finish are two sequential calls.
+ await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status="in_progress",
+ total_metrics=0,
+ metric_uuids=[],
+ mark_started=True,
+ ),
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status="completed",
+ mark_completed=True,
+ ),
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ temporalio.workflow.logger.info(f"recalc {recalculation_id} had no metrics; completing immediately")
+ 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
+ # activity returns that query_to so every calc activity below uses the exact same window.
+ query_to = await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status="in_progress",
+ total_metrics=len(metrics),
+ metric_uuids=[m.metric_uuid for m in metrics],
+ mark_started=True,
+ ),
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ # The activity returns Optional[str] in general, but with mark_started=True it always returns the ISO
+ # query_to string. Narrow with a real check (not assert, which is stripped under python -O) so calc
+ # activities receive a typed str.
+ if not isinstance(query_to, str):
+ raise ApplicationError(
+ f"start activity for recalc {recalculation_id} returned {type(query_to).__name__}, expected str",
+ non_retryable=True,
+ )
+
+ temporalio.workflow.logger.info(f"running recalc {recalculation_id} with {len(metrics)} metrics")
+
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_METRICS)
+
+ async def _run_metric(metric):
+ 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],
+ # 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),
+ retry_policy=RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=5),
+ maximum_interval=timedelta(seconds=30),
+ ),
+ )
+
+ results = await asyncio.gather(*[_run_metric(m) for m in metrics], return_exceptions=True)
+ succeeded = sum(1 for r in results if not isinstance(r, BaseException) and r.success)
+ failed = len(metrics) - succeeded
+
+ # Any failure marks the run as "failed"; the succeeded/failed counts carry the partial-vs-total nuance
+ # for consumers that need it (the UI shows "N succeeded, M failed" alongside the status). A status-only
+ # check then can't mistake a 9-of-10-failed run for a healthy one.
+ 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),
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ temporalio.workflow.logger.info(
+ f"recalc {recalculation_id} finished: {succeeded} succeeded, {failed} failed (status={final_status})"
+ )
+ return {"total": len(metrics), "succeeded": succeeded, "failed": failed}
diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.py
new file mode 100644
index 000000000000..728fe34b03f3
--- /dev/null
+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py
@@ -0,0 +1,182 @@
+import uuid
+
+import pytest
+
+import temporalio.worker
+from parameterized import parameterized
+from temporalio import activity
+from temporalio.client import WorkflowFailureError
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from products.experiments.backend.temporal.models import (
+ ExperimentMetricsRecalculationWorkflowInputs,
+ ExperimentMetricToRecalculate,
+ MetricRecalculationResult,
+ RecalculationProgressUpdate,
+)
+from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
+
+_START_QUERY_TO = "2026-05-29T12:00:00+00:00"
+
+
+def _metric(metric_uuid: str) -> ExperimentMetricToRecalculate:
+ return ExperimentMetricToRecalculate(experiment_id=1, metric_uuid=metric_uuid, metric_type="primary")
+
+
+def _make_mock_activities(
+ metrics: list[ExperimentMetricToRecalculate] | None = None,
+ metric_results: dict[str, MetricRecalculationResult] | None = None,
+):
+ metrics = metrics or []
+ metric_results = metric_results or {}
+ progress_updates: list[RecalculationProgressUpdate] = []
+ calculate_calls: list[tuple] = []
+
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return metrics
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ progress_updates.append(update)
+ # Mirror the real activity (option A): return the run's shared query_to on the start step.
+ return _START_QUERY_TO if update.mark_started else None
+
+ @activity.defn(name="calculate_experiment_metric_for_recalculation")
+ async def mock_calculate(
+ experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str
+ ) -> MetricRecalculationResult:
+ calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to))
+ return metric_results.get(metric_uuid, MetricRecalculationResult(metric_uuid=metric_uuid, success=True))
+
+ activities = [mock_discover, mock_update_progress, mock_calculate]
+ return activities, progress_updates, calculate_calls
+
+
+async def _run_workflow(activities) -> dict:
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ExperimentMetricsRecalculationWorkflow],
+ activities=activities,
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ ExperimentMetricsRecalculationWorkflow.run,
+ ExperimentMetricsRecalculationWorkflowInputs(recalculation_id=str(uuid.uuid4())),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+
+class TestExperimentMetricsRecalculationWorkflow:
+ async def test_no_metrics_completes_immediately(self):
+ activities, progress_updates, calculate_calls = _make_mock_activities(metrics=[])
+
+ result = await _run_workflow(activities)
+
+ assert result == {"total": 0, "succeeded": 0, "failed": 0}
+ assert calculate_calls == []
+ # Two progress calls: start (mark_started) then finish (mark_completed). The XOR contract on the
+ # progress activity forbids combining both into one call.
+ assert len(progress_updates) == 2
+ assert progress_updates[0].mark_started is True and progress_updates[0].mark_completed is False
+ assert progress_updates[0].status == "in_progress"
+ assert progress_updates[0].total_metrics == 0
+ assert progress_updates[1].mark_completed is True and progress_updates[1].mark_started is False
+ assert progress_updates[1].status == "completed"
+
+ @parameterized.expand(
+ [
+ # name, failed_uuids, expected_result, expected_final_status
+ # Any failure -> "failed" status; counts carry the partial-vs-total nuance.
+ ("all_succeed", set(), {"total": 2, "succeeded": 2, "failed": 0}, "completed"),
+ ("all_fail", {"m1", "m2"}, {"total": 2, "succeeded": 0, "failed": 2}, "failed"),
+ ("partial_failure", {"m2"}, {"total": 2, "succeeded": 1, "failed": 1}, "failed"),
+ ]
+ )
+ async def test_outcomes(self, name: str, failed_uuids: set, expected_result: dict, expected_final_status: str):
+ metrics = [_metric("m1"), _metric("m2")]
+ metric_results = {
+ uuid_: MetricRecalculationResult(metric_uuid=uuid_, success=False, error_step="calculation")
+ for uuid_ in failed_uuids
+ }
+ activities, progress_updates, calculate_calls = _make_mock_activities(
+ metrics=metrics, metric_results=metric_results
+ )
+
+ result = await _run_workflow(activities)
+
+ assert result == expected_result
+ assert {c[1] for c in calculate_calls} == {"m1", "m2"}
+ # The shared query_to from the start step is threaded into every calc activity.
+ assert {c[3] for c in calculate_calls} == {_START_QUERY_TO}
+ assert progress_updates[-1].status == expected_final_status
+ assert progress_updates[-1].mark_completed is True
+
+ @parameterized.expand(
+ [
+ # name, metrics — exercise both the empty-metrics path and the fan-out path.
+ ("no_metrics", []),
+ ("one_metric", [_metric("m1")]),
+ ]
+ )
+ async def test_workflow_respects_progress_xor_contract(
+ self, name: str, metrics: list[ExperimentMetricToRecalculate]
+ ):
+ # The production progress activity raises non-retryable ApplicationError when mark_started == mark_completed.
+ # If the workflow ever combines both flags in one call (or sends neither), this test fails the run instead
+ # of silently passing as the stub-mock path would.
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return metrics
+
+ @activity.defn(name="update_recalculation_progress")
+ async def progress_with_xor_guard(update: RecalculationProgressUpdate) -> str | None:
+ if update.mark_started == update.mark_completed:
+ raise ApplicationError(
+ "RecalculationProgressUpdate must set exactly one of mark_started or mark_completed",
+ non_retryable=True,
+ )
+ return _START_QUERY_TO if update.mark_started else None
+
+ @activity.defn(name="calculate_experiment_metric_for_recalculation")
+ async def mock_calculate(
+ experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str
+ ) -> MetricRecalculationResult:
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ # Workflow must complete without the validating activity raising — i.e., every progress call has exactly
+ # one of mark_started / mark_completed set.
+ await _run_workflow([mock_discover, progress_with_xor_guard, mock_calculate])
+
+ 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,
+ # the workflow must fail non-retryably rather than silently pass None into calc activities.
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return [_metric("m1")]
+
+ @activity.defn(name="update_recalculation_progress")
+ async def progress_returning_none(update: RecalculationProgressUpdate) -> str | None:
+ return None # contract violation on the start step
+
+ @activity.defn(name="calculate_experiment_metric_for_recalculation")
+ async def mock_calculate(
+ experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str
+ ) -> MetricRecalculationResult:
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ with pytest.raises(WorkflowFailureError) as exc_info:
+ await _run_workflow([mock_discover, progress_returning_none, mock_calculate])
+
+ cause = exc_info.value.cause
+ assert isinstance(cause, ApplicationError)
+ assert cause.non_retryable is True
+ assert "expected str" in str(cause)
diff --git a/products/experiments/backend/temporal/test_registration.py b/products/experiments/backend/temporal/test_registration.py
index a81d587e23d9..9db6609157ce 100644
--- a/products/experiments/backend/temporal/test_registration.py
+++ b/products/experiments/backend/temporal/test_registration.py
@@ -1,4 +1,5 @@
from products.experiments.backend.temporal import ACTIVITIES, WORKFLOWS
+from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
def test_activities_registered():
@@ -10,6 +11,5 @@ def test_activities_registered():
}
-def test_workflows_empty_until_workflow_added():
- # The workflow is added in the next PR; until then the package exposes no workflows.
- assert WORKFLOWS == []
+def test_workflow_registered():
+ assert WORKFLOWS == [ExperimentMetricsRecalculationWorkflow]
diff --git a/tach.toml b/tach.toml
index fe537218ece4..e230b9200739 100644
--- a/tach.toml
+++ b/tach.toml
@@ -672,6 +672,21 @@ 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. 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.
+
+[[interfaces]]
+expose = [
+ "backend\\.temporal\\.ACTIVITIES",
+ "backend\\.temporal\\.WORKFLOWS",
+]
+from = [
+ "products.experiments",
+]
+
# user_interviews exposes Vapi webhook handlers that are routed directly from posthog/urls.py.
[[interfaces]]