: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): metric recalculation temporal activities (#60601)
Rodrigo Iloroac000acf6dc2
diff --git a/products/experiments/backend/temporal/__init__.py b/products/experiments/backend/temporal/__init__.pynew file mode 100644index 000000000000..2fce1928e501--- /dev/null+++ b/products/experiments/backend/temporal/__init__.py@@ -0,0 +1,21 @@+from products.experiments.backend.temporal.recalculation_activities import (+ calculate_experiment_metric_for_recalculation,+ discover_experiment_metrics,+ update_recalculation_progress,+)++# The workflow is registered in a later PR; until then the package exposes no workflows.+WORKFLOWS: list[type] = []+ACTIVITIES = [+ discover_experiment_metrics,+ calculate_experiment_metric_for_recalculation,+ update_recalculation_progress,+]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "calculate_experiment_metric_for_recalculation",+ "discover_experiment_metrics",+ "update_recalculation_progress",+]diff --git a/products/experiments/backend/temporal/conftest.py b/products/experiments/backend/temporal/conftest.pynew file mode 100644index 000000000000..5b2f0a18eafd--- /dev/null+++ b/products/experiments/backend/temporal/conftest.py@@ -0,0 +1,22 @@+import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _enter_team_scope(request):+ """Open team_scope around every DB-touching test that exposes self.team (i.e. BaseTest subclasses).++ Tests without self.team (no BaseTest, or pure helper-level tests) get a no-op fixture; they explicitly+ don't need scope because they don't hit the fail-closed ORM manager on ExperimentMetricsRecalculation.+ """+ if request.node.get_closest_marker("django_db") is None:+ yield+ return+ instance = getattr(request.node, "instance", None)+ team = getattr(instance, "team", None) if instance is not None else None+ if team is None:+ yield+ return+ with team_scope(team.id, canonical=True):+ yielddiff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pynew file mode 100644index 000000000000..c5f13d00c9bf--- /dev/null+++ b/products/experiments/backend/temporal/models.py@@ -0,0 +1,58 @@+import dataclasses+++class ExperimentMetricsRecalculationWorkflowInputs:+ """Input to the batch metrics recalculation workflow."""++ recalculation_id: str # UUID as string+++class ExperimentMetricToRecalculate:+ """A single metric to recalculate.++ The recalc fingerprint is derived inside the calculate activity from the recalculation_id,+ so it is intentionally not carried here.+ """++ experiment_id: int+ metric_uuid: str+ metric_type: str # "primary" or "secondary"+++class MetricRecalculationResult:+ """Result from calculating a single metric.++ Lightweight by design: carries only success/error metadata, never the computed result blob. The blob is+ written to ExperimentMetricResult (Postgres) inside the activity and read back by the API, so it never+ crosses the Temporal payload boundary (~2 MiB cap). error_message is capped by the activity before being set.+ """++ metric_uuid: str+ success: bool+ error_step: str | None = None+ error_message: str | None = None+++class RecalculationProgressUpdate:+ """Input for the start and finish lifecycle steps.++ Start step: status=in_progress, total_metrics, metric_uuids, mark_started=True. The activity itself+ stamps query_to and started_at under a first-write-wins guard.++ Finish step: status=completed|failed, mark_completed=True. The activity stamps completed_at, also+ first-write-wins.++ Per-metric counters and error entries are not carried here — they're written by the calculate activity+ in the same transaction as the result row.+ """++ recalculation_id: str+ status: str | None = None+ total_metrics: int | None = None+ metric_uuids: list[str] | None = None+ mark_started: bool = False+ mark_completed: bool = Falsediff --git a/products/experiments/backend/temporal/recalc_fingerprint.py b/products/experiments/backend/temporal/recalc_fingerprint.pynew file mode 100644index 000000000000..72a9b19289dc--- /dev/null+++ b/products/experiments/backend/temporal/recalc_fingerprint.py@@ -0,0 +1,11 @@+import hashlib+++def compute_recalc_fingerprint(config_fingerprint: str, recalculation_id: str) -> str:+ """Per-run fingerprint stamped onto ExperimentMetricResult rows so a recalculation run's results can be+ scoped without modifying the shared results model.++ Returns a 64-char SHA256 hex digest, unique per (config, run) pair. It is deliberately distinct from the+ config fingerprint used by the timeseries workflow, which keys its own reads off the config hash.+ """+ return hashlib.sha256(f"{config_fingerprint}{recalculation_id}".encode()).hexdigest()diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pynew file mode 100644index 000000000000..8608c90f3c7f--- /dev/null+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -0,0 +1,46 @@+"""Temporal activity entrypoints for experiment metrics recalculation.++These are thin ``@temporalio.activity.defn`` wrappers; the DB-touching implementations and helpers live in+``recalculation_logic``. Keeping the decorated entrypoints isolated makes the worker-registered surface obvious+and lets the logic be unit-tested without the activity decorator.+"""++import temporalio.activity++from products.experiments.backend.temporal.models import (+ ExperimentMetricToRecalculate,+ MetricRecalculationResult,+ RecalculationProgressUpdate,+)+from products.experiments.backend.temporal.recalculation_logic import (+ _calculate_experiment_metric_for_recalculation_sync,+ _discover_experiment_metrics_sync,+ _update_recalculation_progress_sync,+)+++async def discover_experiment_metrics(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:+ """Discover all metrics (inline + saved/shared) for an experiment and persist their uuids onto the job."""+ return await _discover_experiment_metrics_sync(recalculation_id)+++async def update_recalculation_progress(update: RecalculationProgressUpdate) -> str | None:+ """Update job progress. Used only for the start (in_progress + total + query_to) and finish (final status) steps.++ Returns the run's shared query_to as an ISO string when starting (mark_started); otherwise None.+ """+ return await _update_recalculation_progress_sync(update)+++async def calculate_experiment_metric_for_recalculation(+ experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+) -> MetricRecalculationResult:+ """Calculate one metric, write its recalc-fingerprinted result to ExperimentMetricResult, and fold the+ progress update (counter + error) into the same job atomically. query_to is the run's shared data-window end.+ """+ return await _calculate_experiment_metric_for_recalculation_sync(+ experiment_id, metric_uuid, recalculation_id, query_to+ )diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pynew file mode 100644index 000000000000..0908b0815b93--- /dev/null+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -0,0 +1,439 @@+"""Synchronous implementation for the metrics recalculation activities.++The thin ``@temporalio.activity.defn`` entrypoints live in ``recalculation_activities`` and delegate here. This+module holds the DB-touching ``_*_sync`` implementations plus the pure helpers they compose from.+"""++import dataclasses+from datetime import datetime++from django.db import close_old_connections, transaction+from django.utils import timezone++import structlog+from temporalio.exceptions import ApplicationError++from posthog.schema import (+ ExperimentFunnelMetric,+ ExperimentMeanMetric,+ ExperimentQuery,+ ExperimentRatioMetric,+ ExperimentRetentionMetric,+)++from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.query_tagging import tag_queries+from posthog.exceptions_capture import capture_exception+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.scoping import team_scope+from posthog.sync import database_sync_to_async++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.temporal.models import (+ ExperimentMetricToRecalculate,+ MetricRecalculationResult,+ RecalculationProgressUpdate,+)+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.experiments.stats.shared.statistics import StatisticError++logger = structlog.get_logger(__name__)++# Cap stored/returned error messages so a pathological traceback can't bloat the Temporal payload (~2 MiB cap).+_MAX_ERROR_MESSAGE_LENGTH = 2000+++# ---------------------------------------------------------------------------+# Discovery+# ---------------------------------------------------------------------------++[email protected](frozen=True)+class _RecalcState:+ """The recalc row fields the activities cross-check their inputs against.++ Loaded once at the top of each activity via a single unscoped SELECT — same query count as just reading+ team_id, but the extra columns let the calculate activity assert its (experiment_id, metric_uuid, query_to)+ inputs match the row state instead of trusting whatever the workflow passed.+ """++ team_id: int+ experiment_id: int+ metric_uuids: list[str]+ query_to: datetime | None+++def _get_recalc_state(recalculation_id: str) -> _RecalcState:+ """Resolve the recalc row's identifying fields without entering scope yet (chicken-and-egg)."""+ row = (+ ExperimentMetricsRecalculation.objects.unscoped()+ .filter(id=recalculation_id)+ .values("team_id", "experiment_id", "metric_uuids", "query_to")+ .first()+ )+ if row is None:+ # Deterministic: the row's not coming back (bogus id, manual delete, cascade from team/experiment).+ # Non-retryable so Temporal terminates promptly instead of burning retries on each activity.+ raise ApplicationError(+ f"ExperimentMetricsRecalculation {recalculation_id} not found",+ non_retryable=True,+ )+ return _RecalcState(+ team_id=row["team_id"],+ experiment_id=row["experiment_id"],+ metric_uuids=row["metric_uuids"] or [],+ query_to=row["query_to"],+ )+++@database_sync_to_async+def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:+ close_old_connections()++ state = _get_recalc_state(recalculation_id)+ with team_scope(state.team_id, canonical=True):+ recalculation = ExperimentMetricsRecalculation.objects.select_related("experiment").get(id=recalculation_id)+ experiment = recalculation.experiment++ metrics_to_recalculate: list[ExperimentMetricToRecalculate] = []++ def _add(metric_uuid: str | None, metric_type: str) -> None:+ if metric_uuid:+ metrics_to_recalculate.append(+ ExperimentMetricToRecalculate(+ experiment_id=experiment.id, metric_uuid=metric_uuid, metric_type=metric_type+ )+ )++ # Inline metrics carry their uuid directly on the dict; the metric_type is the source list.+ for source, metric_type in [(experiment.metrics, "primary"), (experiment.metrics_secondary, "secondary")]:+ for metric in source or []:+ _add(metric.get("uuid"), metric_type)++ # Saved (shared) metrics live in the M2M through-model: uuid is on saved_metric.query["uuid"], and+ # primary/secondary is recorded on the link's metadata["type"] (default "primary").+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ saved_query = link.saved_metric.query+ metric_uuid = saved_query.get("uuid") if saved_query else None+ metric_type = link.metadata.get("type", "primary") if link.metadata else "primary"+ _add(metric_uuid, metric_type)++ recalculation.metric_uuids = [m.metric_uuid for m in metrics_to_recalculate]+ recalculation.save(update_fields=["metric_uuids"])++ logger.info(+ "Discovered experiment metrics for recalculation",+ recalculation_id=recalculation_id,+ count=len(metrics_to_recalculate),+ )+ return metrics_to_recalculate+++# ---------------------------------------------------------------------------+# Progress (start / finish only — per-metric progress is folded into the calc step)+# ---------------------------------------------------------------------------+++@database_sync_to_async+def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -> str | None:+ close_old_connections()++ if update.mark_started == update.mark_completed:+ # Contract: exactly one of mark_started / mark_completed per call. Both-true or neither-true is a+ # workflow bug — fail non-retryable so Temporal terminates promptly.+ raise ApplicationError(+ "RecalculationProgressUpdate must set exactly one of mark_started or mark_completed",+ non_retryable=True,+ )++ state = _get_recalc_state(update.recalculation_id)+ with team_scope(state.team_id, canonical=True):+ # Start: write the data-window end + started_at + initial state under a first-write-wins guard so a+ # Temporal retry of this activity can't move query_to forward (which would orphan any rows persisted by+ # calc activities still in flight from the prior attempt).+ if update.mark_started:+ proposed_query_to = timezone.now()+ won = (+ ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, query_to__isnull=True).update(+ query_to=proposed_query_to,+ started_at=timezone.now(),+ status=update.status or ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ total_metrics=update.total_metrics if update.total_metrics is not None else 0,+ metric_uuids=update.metric_uuids if update.metric_uuids is not None else [],+ )+ == 1+ )+ if won:+ return proposed_query_to.isoformat()+ existing_query_to = (+ ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id)+ .values_list("query_to", flat=True)+ .first()+ )+ return existing_query_to.isoformat() if existing_query_to is not None else None++ # 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,+ )+ return None+++# ---------------------------------------------------------------------------+# Calculation helpers+# ---------------------------------------------------------------------------+++def _find_metric_dict(experiment: Experiment, metric_uuid: str) -> dict | None:+ """Resolve a metric_uuid to its definition dict, across inline AND saved/shared metrics.++ Inline metrics are dicts in experiment.metrics / metrics_secondary. Saved metrics live on the M2M+ through-model and carry their definition (with uuid) in saved_metric.query.+ """+ for metric in (experiment.metrics or []) + (experiment.metrics_secondary or []):+ if metric.get("uuid") == metric_uuid:+ return metric++ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ saved_query = link.saved_metric.query+ if saved_query and saved_query.get("uuid") == metric_uuid:+ # Merge per-experiment breakdowns from link.metadata into the saved query, mirroring the+ # daily-warming activity. Without this, recalc would compute the unbroken-down version of a+ # saved metric the experiment has configured with breakdowns.+ metadata = link.metadata or {}+ return {+ **saved_query,+ "breakdownFilter": {+ **(saved_query.get("breakdownFilter") or {}),+ "breakdowns": metadata.get("breakdowns") or [],+ },+ }++ return None+++# Modern ExperimentMetric types (kind="ExperimentMetric"). Legacy Trends/Funnels metrics never enter this+# workflow, so there is no fallback — an unexpected metric_type surfaces as a calculation-step error.+_METRIC_BUILDERS = {+ "mean": ExperimentMeanMetric,+ "funnel": ExperimentFunnelMetric,+ "ratio": ExperimentRatioMetric,+ "retention": ExperimentRetentionMetric,+}+++def _build_metric(+ metric_dict: dict,+) -> ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric:+ return _METRIC_BUILDERS[metric_dict["metric_type"]](**metric_dict)+++def _record_failure(recalculation_id: str, metric_uuid: str, step: str, message: str) -> None:+ """Merge the error entry into metric_errors under a row lock (no lost updates between concurrent failures).++ Idempotent on Temporal retries: the dict is keyed by metric_uuid, so re-running this for the same metric+ just overwrites the existing entry with a fresh timestamp.+ """+ capped = message[:_MAX_ERROR_MESSAGE_LENGTH]+ with transaction.atomic():+ recalc = ExperimentMetricsRecalculation.objects.select_for_update().get(id=recalculation_id)+ metric_errors = recalc.metric_errors or {}+ metric_errors[metric_uuid] = {"step": step, "message": capped, "timestamp": timezone.now().isoformat()}+ recalc.metric_errors = metric_errors+ recalc.save(update_fields=["metric_errors"])+++def _store_result(+ *,+ experiment_id: int,+ metric_uuid: str,+ recalc_fp: str,+ query_from: datetime,+ query_to: datetime,+ status: str,+ result: dict | None,+ error_message: str | None,+) -> None:+ ExperimentMetricResult.objects.update_or_create(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ fingerprint=recalc_fp,+ query_to=query_to,+ defaults={+ "query_from": query_from,+ "status": status,+ "result": result,+ "query_id": None,+ "completed_at": timezone.now() if status == ExperimentMetricResult.Status.COMPLETED else None,+ "error_message": error_message,+ },+ )+++def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str) -> MetricRecalculationResult:+ """Record a failure on the job (lookup step: job-only; calculation step: also persists a result row upstream)."""+ _record_failure(recalculation_id, metric_uuid, step, message)+ return MetricRecalculationResult(+ metric_uuid=metric_uuid, success=False, error_step=step, error_message=message[:_MAX_ERROR_MESSAGE_LENGTH]+ )+++# ---------------------------------------------------------------------------+# Calculation+# ---------------------------------------------------------------------------+++@database_sync_to_async+def _calculate_experiment_metric_for_recalculation_sync(+ experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str+) -> MetricRecalculationResult:+ close_old_connections()++ try:+ query_to_dt = datetime.fromisoformat(query_to)+ except ValueError as e:+ raise ApplicationError(+ f"query_to {query_to!r} is not a valid ISO datetime string: {e}",+ non_retryable=True,+ )+ state = _get_recalc_state(recalculation_id)++ # Defense-in-depth at the activity boundary: the workflow constructs all four args from its own state,+ # so a mismatch here means a workflow bug, not a data issue. Fail non-retryable so Temporal terminates+ # the run promptly rather than burning retries on a deterministic failure.+ if experiment_id != state.experiment_id:+ raise ApplicationError(+ f"experiment_id {experiment_id} does not match recalc.experiment_id {state.experiment_id}",+ non_retryable=True,+ )+ if metric_uuid not in state.metric_uuids:+ raise ApplicationError(+ f"metric_uuid {metric_uuid} is not in recalc {recalculation_id}'s metric set",+ non_retryable=True,+ )+ if state.query_to is None:+ raise ApplicationError(+ f"recalc {recalculation_id} has no query_to set — calculate activity ran before start activity",+ non_retryable=True,+ )+ if query_to_dt != state.query_to:+ raise ApplicationError(+ f"query_to {query_to_dt.isoformat()} does not match recalc.query_to {state.query_to.isoformat()}",+ non_retryable=True,+ )++ with team_scope(state.team_id, canonical=True):+ try:+ experiment = Experiment.objects.get(id=experiment_id, deleted=False)+ except Experiment.DoesNotExist:+ return _fail(recalculation_id, metric_uuid, "discovery", f"Experiment {experiment_id} not found or deleted")++ metric_dict = _find_metric_dict(experiment, metric_uuid)+ if metric_dict is None:+ return _fail(+ recalculation_id,+ metric_uuid,+ "discovery",+ f"Metric {metric_uuid} not found in experiment {experiment_id}",+ )++ if not experiment.start_date:+ return _fail(recalculation_id, metric_uuid, "discovery", f"Experiment {experiment_id} has no start_date")++ config_fp = compute_metric_fingerprint(+ metric_dict,+ experiment.start_date,+ get_experiment_stats_method(experiment),+ experiment.exposure_criteria,+ only_count_matured_users=experiment.only_count_matured_users,+ )+ recalc_fp = compute_recalc_fingerprint(config_fp, recalculation_id)++ 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+ # the runner falls back to its default ("now-ish"), so every metric in the run would query a+ # slightly different time window — defeating the "one query_to for the whole run" guarantee.+ runner = ExperimentQueryRunner(+ query=ExperimentQuery(experiment_id=experiment_id, metric=_build_metric(metric_dict)),+ team=experiment.team,+ override_end_date=query_to_dt,+ workload=Workload.OFFLINE,+ )+ tag_queries(trigger="warming/experiment_metrics_recalculation")+ result = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)+ result_dict = result.model_dump(mode="json")++ _store_result(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ recalc_fp=recalc_fp,+ query_from=experiment.start_date,+ query_to=query_to_dt,+ status=ExperimentMetricResult.Status.COMPLETED,+ result=result_dict,+ error_message=None,+ )+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)++ except (StatisticError, ZeroDivisionError) as e:+ # Expected "not enough data" style failures — warn, no exception capture.+ message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]+ _store_result(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ recalc_fp=recalc_fp,+ query_from=experiment.start_date,+ query_to=query_to_dt,+ status=ExperimentMetricResult.Status.FAILED,+ result=None,+ error_message=message,+ )+ logger.warning(+ "Experiment metric recalculation failed due to insufficient data",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ error=message,+ )+ return _fail(recalculation_id, metric_uuid, "calculation", message)++ except Exception as e:+ # Could be transient (ClickHouse connection blip, network glitch, or other infrastructure issue).+ # Record the failure so the UI sees it, then re-raise so Temporal's retry policy gets a chance.+ # If all attempts fail, the workflow's gather(return_exceptions=True) counts this metric as failed.+ # StatisticError and ZeroDivisionError are handled above as permanent and return success=False.+ message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]+ capture_exception(+ e,+ additional_properties={+ "experiment_id": experiment_id,+ "metric_uuid": metric_uuid,+ "recalculation_id": recalculation_id,+ },+ )+ _store_result(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ recalc_fp=recalc_fp,+ query_from=experiment.start_date,+ query_to=query_to_dt,+ status=ExperimentMetricResult.Status.FAILED,+ result=None,+ error_message=message,+ )+ _record_failure(recalculation_id, metric_uuid, "calculation", message)+ logger.exception(+ "Experiment metric recalculation failed",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ )+ raisediff --git a/products/experiments/backend/temporal/test_fingerprint.py b/products/experiments/backend/temporal/test_fingerprint.pynew file mode 100644index 000000000000..dc29c36c78ec--- /dev/null+++ b/products/experiments/backend/temporal/test_fingerprint.py@@ -0,0 +1,17 @@+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+++def test_is_deterministic():+ assert compute_recalc_fingerprint("config-fp", "run-1") == compute_recalc_fingerprint("config-fp", "run-1")+++def test_differs_per_run():+ assert compute_recalc_fingerprint("config-fp", "run-1") != compute_recalc_fingerprint("config-fp", "run-2")+++def test_differs_per_config():+ assert compute_recalc_fingerprint("config-fp-1", "run-1") != compute_recalc_fingerprint("config-fp-2", "run-1")+++def test_is_sha256_hex_length():+ assert len(compute_recalc_fingerprint("config-fp", "run-1")) == 64diff --git a/products/experiments/backend/temporal/test_models.py b/products/experiments/backend/temporal/test_models.pynew file mode 100644index 000000000000..8540b5822d07--- /dev/null+++ b/products/experiments/backend/temporal/test_models.py@@ -0,0 +1,34 @@+from products.experiments.backend.temporal.models import (+ ExperimentMetricsRecalculationWorkflowInputs,+ ExperimentMetricToRecalculate,+ MetricRecalculationResult,+ RecalculationProgressUpdate,+)+++def test_workflow_inputs_holds_recalculation_id():+ inputs = ExperimentMetricsRecalculationWorkflowInputs(recalculation_id="abc")+ assert inputs.recalculation_id == "abc"+++def test_metric_to_recalculate_fields():+ metric = ExperimentMetricToRecalculate(experiment_id=1, metric_uuid="u", metric_type="primary")+ assert metric.experiment_id == 1+ assert metric.metric_uuid == "u"+ assert metric.metric_type == "primary"+++def test_result_defaults():+ result = MetricRecalculationResult(metric_uuid="u", success=True)+ assert result.success is True+ assert result.error_step is None+ assert result.error_message is None+++def test_progress_update_defaults():+ update = RecalculationProgressUpdate(recalculation_id="abc")+ assert update.status is None+ assert update.total_metrics is None+ assert update.metric_uuids is None+ assert update.mark_started is False+ assert update.mark_completed is Falsediff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pynew file mode 100644index 000000000000..5837306841e3--- /dev/null+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -0,0 +1,567 @@+from datetime import datetime++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized+from temporalio.exceptions import ApplicationError++from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,+)+from products.experiments.backend.temporal.models import RecalculationProgressUpdate+from products.experiments.backend.temporal.recalculation_logic import (+ _calculate_experiment_metric_for_recalculation_sync,+ _discover_experiment_metrics_sync,+ _update_recalculation_progress_sync,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag++_discover_raw = _discover_experiment_metrics_sync.func # type: ignore[attr-defined]+_update_raw = _update_recalculation_progress_sync.func # type: ignore[attr-defined]+_calculate_raw = _calculate_experiment_metric_for_recalculation_sync.func # type: ignore[attr-defined]+++def _discover(recalculation_id: str):+ with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):+ return _discover_raw(recalculation_id)+++def _update(update: RecalculationProgressUpdate):+ with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):+ return _update_raw(update)+++def _calculate(experiment_id: int, metric_uuid: str, recalculation_id: str, query_to: str):+ with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):+ return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to)++[email protected]_db(transaction=True)+class TestRecalculationActivities(BaseTest):+ 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}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )++ def _experiment(self, flag_key: str) -> Experiment:+ return Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=self._flag(flag_key), name="exp"+ )++ def _recalc(self, exp: Experiment) -> ExperimentMetricsRecalculation:+ return ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp)++ def _attach_saved_metric(self, exp: Experiment, uuid: str, metric_type: str) -> None:+ saved = ExperimentSavedMetric.objects.create(+ team=self.team,+ name=f"saved-{uuid}",+ query={"uuid": uuid, "kind": "ExperimentMetric", "metric_type": "mean"},+ )+ ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": metric_type})++ @parameterized.expand(+ [+ (+ "primary_and_secondary",+ [{"uuid": "m1", "metric_type": "mean", "kind": "ExperimentMetric"}],+ [{"uuid": "m2", "metric_type": "mean", "kind": "ExperimentMetric"}],+ [],+ {"m1", "m2"},+ {"primary", "secondary"},+ ),+ ("no_metrics", [], [], [], set(), set()),+ (+ "primary_only",+ [{"uuid": "m1", "metric_type": "mean", "kind": "ExperimentMetric"}],+ [],+ [],+ {"m1"},+ {"primary"},+ ),+ (+ "saved_metrics_only",+ [],+ [],+ [("s1", "primary"), ("s2", "secondary")],+ {"s1", "s2"},+ {"primary", "secondary"},+ ),+ (+ "inline_and_saved_mixed",+ [{"uuid": "m1", "metric_type": "mean", "kind": "ExperimentMetric"}],+ [],+ [("s1", "secondary")],+ {"m1", "s1"},+ {"primary", "secondary"},+ ),+ ]+ )+ def test_discover_persists_metric_uuids(self, name: str, primary, secondary, saved, expected_uuids, expected_types):+ exp = self._experiment(flag_key=f"discover-{name}")+ exp.metrics = primary+ exp.metrics_secondary = secondary+ exp.save()+ for uuid, metric_type in saved:+ self._attach_saved_metric(exp, uuid, metric_type)+ recalc = self._recalc(exp)++ metrics = _discover(str(recalc.id))++ recalc.refresh_from_db()+ assert set(recalc.metric_uuids) == expected_uuids+ assert {m.metric_uuid for m in metrics} == expected_uuids+ assert {m.metric_type for m in metrics} == expected_types++ @parameterized.expand(+ [+ (+ "start",+ {+ "status": "in_progress",+ "total_metrics": 3,+ "metric_uuids": ["m1", "m2", "m3"],+ "mark_started": True,+ },+ "in_progress",+ True, # expects query_to set + returned+ ),+ (+ "finish",+ {"status": "completed", "mark_completed": True},+ "completed",+ False, # finish does not set/return query_to+ ),+ ]+ )+ def test_update_progress(self, name: str, update_kwargs: dict, expected_status: str, expects_query_to: bool):+ recalc = self._recalc(self._experiment(flag_key=f"progress-{name}"))+ returned = _update(RecalculationProgressUpdate(recalculation_id=str(recalc.id), **update_kwargs))++ recalc.refresh_from_db()+ assert recalc.status == expected_status++ if expects_query_to:+ assert recalc.started_at is not None+ assert recalc.total_metrics == update_kwargs["total_metrics"]+ assert recalc.metric_uuids == update_kwargs["metric_uuids"]+ assert recalc.query_to is not None+ # Returns the query_to it set (ISO string) so the workflow can thread it into calc activities.+ assert returned == recalc.query_to.isoformat()+ else:+ assert recalc.completed_at is not None+ assert returned is None++ def test_mark_started_is_first_write_wins_on_retry(self):+ # Temporal retries the start activity (network blip, worker crash) — the second attempt must NOT move+ # query_to/started_at forward. If it did, any calc activity already in flight from the first attempt+ # would persist ExperimentMetricResult rows with the old query_to, while the recalc row points at the+ # new one — orphaning those rows from the API's perspective.+ recalc = self._recalc(self._experiment(flag_key="progress-retry-start"))++ def _start() -> str | None:+ return _update(+ RecalculationProgressUpdate(+ recalculation_id=str(recalc.id),+ status="in_progress",+ total_metrics=3,+ metric_uuids=["m1", "m2", "m3"],+ mark_started=True,+ )+ )++ first = _start()+ recalc.refresh_from_db()+ first_query_to = recalc.query_to+ first_started_at = recalc.started_at+ assert first_query_to is not None # mark_started=True populates it++ second = _start()+ recalc.refresh_from_db()++ # DB state unchanged after retry — the conditional UPDATE matched zero rows.+ assert recalc.query_to == first_query_to+ assert recalc.started_at == first_started_at+ # Both attempts return the same canonical query_to so the workflow threads the same value either way.+ assert first == second == first_query_to.isoformat()++ def test_mark_completed_is_first_write_wins_on_retry(self):+ # Symmetric to mark_started: a retried finish activity must not re-stamp completed_at.+ recalc = self._recalc(self._experiment(flag_key="progress-retry-finish"))++ def _finish() -> str | None:+ return _update(+ RecalculationProgressUpdate(+ recalculation_id=str(recalc.id),+ status="completed",+ mark_completed=True,+ )+ )++ _finish()+ recalc.refresh_from_db()+ first_completed_at = recalc.completed_at+ first_status = recalc.status++ _finish()+ recalc.refresh_from_db()++ assert recalc.completed_at == first_completed_at+ assert recalc.status == first_status++ @parameterized.expand(+ [+ # Contract: exactly one of mark_started / mark_completed must be true. Both-true or neither-true+ # is a workflow bug — fail non-retryable so Temporal terminates promptly.+ ("both_true", {"mark_started": True, "mark_completed": True}),+ ("neither", {}),+ ]+ )+ def test_progress_update_requires_exactly_one_lifecycle_flag(self, name: str, flags: dict):+ recalc = self._recalc(self._experiment(flag_key=f"progress-mutex-{name}"))++ with pytest.raises(ApplicationError) as exc_info:+ _update(RecalculationProgressUpdate(recalculation_id=str(recalc.id), **flags))++ assert "exactly one of mark_started or mark_completed" in str(exc_info.value)+ assert exc_info.value.non_retryable is True+++_QUERY_TO = "2026-05-29T12:00:00+00:00"+++def _mean_metric(uuid: str) -> dict:+ # ExperimentMeanMetric requires a `source`; a bare {uuid, metric_type} dict fails pydantic validation.+ return {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }++[email protected]_db(transaction=True)+class TestCalculateActivity(BaseTest):+ 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}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )++ def _experiment(self, flag_key: str, *, with_start_date: bool = True, metrics=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 with_start_date else None,+ )+ if metrics is not None:+ exp.metrics = metrics+ exp.save()+ return exp++ def _recalc(+ self, exp: Experiment, *, metric_uuids: list[str], total: int | None = None+ ) -> ExperimentMetricsRecalculation:+ """Create a recalc row in the post-discovery + post-start state, so the calculate activity's+ input-validation guards (metric_uuids membership, query_to set) are satisfied as the workflow+ would have set them."""+ return ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ metric_uuids=metric_uuids,+ total_metrics=total if total is not None else len(metric_uuids),+ query_to=datetime.fromisoformat(_QUERY_TO),+ )++ def test_metric_disappeared_between_discovery_and_calc(self):+ # Discovery included m1 in the recalc's metric set (so input validation passes), but the experiment+ # was edited and m1 is no longer present — the calc activity's inner lookup must surface this as a+ # discovery-step failure rather than crashing.+ exp = self._experiment(flag_key="calc-missing", metrics=[])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ result = _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert result.success is False+ assert result.error_step == "discovery"+ recalc.refresh_from_db()+ assert len(recalc.metric_errors) == 1+ assert "m1" in recalc.metric_errors++ def test_bad_metric_type_fails_at_calculation(self):+ # Legacy metrics never reach this workflow, so there's no discovery-time type guard; an unexpected+ # metric_type raises while building the metric. The activity records the failure to metric_errors+ # and re-raises so Temporal's retry policy can handle potentially transient errors.+ exp = self._experiment(+ flag_key="calc-badtype",+ metrics=[{"uuid": "m-bad", "metric_type": "nonsense", "kind": "ExperimentMetric"}],+ )+ recalc = self._recalc(exp, metric_uuids=["m-bad"])++ with pytest.raises(KeyError):+ _calculate(exp.id, "m-bad", str(recalc.id), _QUERY_TO)++ recalc.refresh_from_db()+ assert len(recalc.metric_errors) == 1+ assert "m-bad" in recalc.metric_errors++ def test_missing_start_date_fails(self):+ exp = self._experiment(flag_key="calc-no-start", with_start_date=False, metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ result = _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert result.success is False+ recalc.refresh_from_db()+ assert len(recalc.metric_errors) == 1++ def test_saved_metric_is_resolvable(self):+ # A saved/shared metric (uuid only on saved_metric.query) must be found by the calc lookup; otherwise it+ # would wrongly fail at the discovery step. We force a calculation error so the run reaches the metric via+ # the saved-metric branch but fails for a non-lookup reason. The runtime error is re-raised so Temporal+ # can retry; the failure is recorded to metric_errors first.+ exp = self._experiment(flag_key="calc-saved")+ saved = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="saved-s1",+ query=_mean_metric("s1"),+ )+ ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": "primary"})+ recalc = self._recalc(exp, metric_uuids=["s1"])++ 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, "s1", str(recalc.id), _QUERY_TO)++ # Found the saved metric (did not fail at discovery), failure was recorded before re-raise.+ recalc.refresh_from_db()+ assert "s1" in recalc.metric_errors++ def test_query_to_is_passed_as_override_end_date_to_runner(self):+ # The run's shared query_to MUST be threaded into the ClickHouse query bounds via+ # override_end_date, not just stored on the result row. Without override_end_date the runner falls back+ # to its default ("now-ish"), so every metric in the run queries a slightly different time window —+ # silently violating the "one query_to for the whole run" guarantee. Stored value would look correct;+ # actual query bounds would not. Reference: workflow #3's backfill activity does the same thing.+ exp = self._experiment(flag_key="calc-override-end-date", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ 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)++ mock_runner.assert_called_once()+ kwargs = mock_runner.call_args.kwargs+ assert kwargs["override_end_date"] == datetime.fromisoformat(_QUERY_TO)++ def test_query_from_matches_experiment_start_date_on_result_row(self):+ # Companion to test_query_to_is_passed_as_override_end_date_to_runner: the lower bound of the run's+ # time window is experiment.start_date, threaded into the runner via the experiment object it+ # constructs and stored on the result row via _store_result(query_from=experiment.start_date).+ # This test pins the stored-row side. If the runner ever changes how it derives query_from, or if a+ # future refactor decouples the stored value from what the runner actually queries, the same class+ # of silent-miscalculation bug we just fixed for query_to could reappear here.+ exp = self._experiment(flag_key="calc-query-from", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ 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)++ # Runner gets the experiment whose start_date is the source of truth for the lower bound.+ mock_runner.assert_called_once()+ assert mock_runner.call_args.kwargs["team"] == exp.team+ # And the persisted row's query_from matches that same start_date — so reader and writer agree.+ row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")+ assert row.query_from == exp.start_date++ def test_multiple_failures_accumulate_in_metric_errors(self):+ # Two metrics fail in sequence (not in parallel — that would need threads + a real Postgres). Pins the+ # merge-into-dict behavior: each failure writes its own entry keyed by metric_uuid, no overwriting.+ # The select_for_update guard against concurrent writers is exercised by the production code, not here.+ exp = self._experiment(flag_key="calc-accumulate", metrics=[])+ recalc = self._recalc(exp, metric_uuids=["missing-a", "missing-b"])++ _calculate(exp.id, "missing-a", str(recalc.id), _QUERY_TO)+ _calculate(exp.id, "missing-b", str(recalc.id), _QUERY_TO)++ recalc.refresh_from_db()+ assert len(recalc.metric_errors) == 2+ assert set(recalc.metric_errors.keys()) == {"missing-a", "missing-b"}++ @parameterized.expand(+ [+ # (name, metric_uuid, metrics_on_experiment, run_with_mocked_failure, expected_result_rows)+ # Discovery-step failure: m1 in the recalc's discovered set but absent from the experiment (deleted+ # between discovery and calc). No result row written, only metric_errors.+ ("discovery_failure", "m1", [], False, 0),+ # Calculation-step failure: m1 resolves, runner raises, writes both metric_errors and exactly one+ # FAILED result row (update_or_create overwrites on retry rather than inserting).+ ("calculation_failure", "m1", [_mean_metric("m1")], True, 1),+ ]+ )+ def test_retry_does_not_double_count(+ self, name: str, metric_uuid: str, metrics: list, mock_runner_failure: bool, expected_result_rows: int+ ):+ # Temporal retries the whole activity on transient failure. _store_result is idempotent (update_or_create+ # keyed on fingerprint + query_to) and metric_errors is keyed by metric_uuid, so a second run must leave+ # state identical to the first — no inflated counts, no duplicate result rows.+ exp = self._experiment(flag_key=f"retry-{name}", metrics=metrics)+ recalc = self._recalc(exp, metric_uuids=[metric_uuid])++ def _run() -> None:+ if mock_runner_failure:+ with patch(+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"+ ) as mock_runner:+ mock_runner.return_value.run.side_effect = RuntimeError("kaboom")+ # Calc-step failures now re-raise so Temporal can retry transient errors. The record is+ # written before the re-raise, so the assertions below still hold across attempts.+ with pytest.raises(RuntimeError, match="kaboom"):+ _calculate(exp.id, metric_uuid, str(recalc.id), _QUERY_TO)+ else:+ _calculate(exp.id, metric_uuid, str(recalc.id), _QUERY_TO)++ _run()+ _run() # simulated Temporal retry++ recalc.refresh_from_db()+ assert len(recalc.metric_errors) == 1+ assert metric_uuid in recalc.metric_errors+ # Exact count per case: 0 for discovery failures (no _store_result call), 1 for calc failures+ # (one FAILED row, overwritten on retry rather than duplicated).+ assert (+ ExperimentMetricResult.objects.filter(experiment=exp, metric_uuid=metric_uuid).count()+ == expected_result_rows+ )++ @parameterized.expand(+ [+ # (name, build_kwargs, expected_error_fragment)+ # The workflow constructs all four args from its own state, so any mismatch here means a workflow+ # bug. The activity must fail non-retryable (no point in retrying a deterministic failure).+ (+ "experiment_id_mismatch",+ {"experiment_id_offset": 9999},+ "does not match recalc.experiment_id",+ ),+ (+ "metric_uuid_not_in_set",+ {"metric_uuid_override": "not-in-recalc-set"},+ "is not in recalc",+ ),+ (+ "query_to_mismatch",+ {"query_to_override": "2030-01-01T00:00:00+00:00"},+ "does not match recalc.query_to",+ ),+ (+ "query_to_unset_on_recalc",+ {"clear_query_to": True},+ "has no query_to set",+ ),+ # Parse failure before the cross-checks even run — without explicit handling this would escape as a+ # bare ValueError, hit Temporal's broad retry policy, and burn slots on a deterministic parse error.+ (+ "query_to_unparseable",+ {"query_to_override": "not-an-iso-string"},+ "is not a valid ISO datetime string",+ ),+ ]+ )+ def test_input_validation_fails_non_retryable(self, name: str, build_kwargs: dict, expected_fragment: str):+ exp = self._experiment(flag_key=f"validation-{name}", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])+ if build_kwargs.get("clear_query_to"):+ recalc.query_to = None+ recalc.save(update_fields=["query_to"])++ call_experiment_id = exp.id + build_kwargs.get("experiment_id_offset", 0)+ call_metric_uuid = build_kwargs.get("metric_uuid_override", "m1")+ call_query_to = build_kwargs.get("query_to_override", _QUERY_TO)++ with pytest.raises(ApplicationError) as exc_info:+ _calculate(call_experiment_id, call_metric_uuid, str(recalc.id), call_query_to)++ assert expected_fragment in str(exc_info.value)+ assert exc_info.value.non_retryable is True++ def test_unexpected_error_calls_capture_exception_and_caps_message(self):+ # Unexpected exceptions get captured to Sentry and re-raised for Temporal retry. The stored result row+ # carries the capped error message so the UI sees what happened even though the activity re-raised.+ exp = self._experiment(flag_key="calc-capture", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with (+ patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner,+ patch("products.experiments.backend.temporal.recalculation_logic.capture_exception") as mock_capture,+ ):+ mock_runner.return_value.run.side_effect = RuntimeError("x" * 5000)+ with pytest.raises(RuntimeError):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)++ assert mock_capture.called+ row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")+ assert row.status == ExperimentMetricResult.Status.FAILED+ assert row.error_message is not None+ assert len(row.error_message) <= 2000++[email protected]_db(transaction=True)+class TestMissingRecalcRow:+ # All three activities go through _get_recalc_state at the top. A missing row is deterministic+ # (bogus id, manual delete, or cascade from team/experiment) — every activity must fail non-retryable+ # so Temporal terminates instead of burning retries.+ @parameterized.expand(+ [+ ("discover", lambda bogus_id: _discover(bogus_id)),+ # mark_started satisfies the XOR guard so the call reaches _get_recalc_state.+ (+ "update_progress",+ lambda bogus_id: _update(RecalculationProgressUpdate(recalculation_id=bogus_id, mark_started=True)),+ ),+ ("calculate", lambda bogus_id: _calculate(1, "m1", bogus_id, _QUERY_TO)),+ ]+ )+ def test_fails_non_retryable(self, name: str, call_activity):+ bogus_id = "019e9af0-0000-7000-8000-000000000000"++ with pytest.raises(ApplicationError) as exc_info:+ call_activity(bogus_id)++ assert bogus_id in str(exc_info.value)+ assert "not found" in str(exc_info.value)+ assert exc_info.value.non_retryable is Truediff --git a/products/experiments/backend/temporal/test_registration.py b/products/experiments/backend/temporal/test_registration.pynew file mode 100644index 000000000000..a81d587e23d9--- /dev/null+++ b/products/experiments/backend/temporal/test_registration.py@@ -0,0 +1,15 @@+from products.experiments.backend.temporal import ACTIVITIES, WORKFLOWS+++def test_activities_registered():+ names = {activity.__name__ for activity in ACTIVITIES}+ assert names == {+ "discover_experiment_metrics",+ "calculate_experiment_metric_for_recalculation",+ "update_recalculation_progress",+ }+++def test_workflows_empty_until_workflow_added():+ # The workflow is added in the next PR; until then the package exposes no workflows.+ assert WORKFLOWS == []