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.

refactor(experiments): move metric discovery out of temporal (#109389)

Anders6b9eb6543ac0
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 9e7dbcd64c57..923d35c25737 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -32,6 +32,7 @@ from posthog.temporal.common.client import sync_connect
from products.experiments.backend.metric_calculation.config import build_calculation_configs
from products.experiments.backend.metric_calculation.results import MetricResultStore
+from products.experiments.backend.metric_resolution import get_metrics_for_calculation
from products.experiments.backend.models.experiment import (
Experiment,
ExperimentMetricResult,
@@ -42,7 +43,6 @@ from products.experiments.backend.temporal.models import (
METRICS_RECALCULATION_WORKFLOW_NAME,
ExperimentMetricsRecalculationWorkflowInputs,
)
-from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics
# 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. An IN_PROGRESS row counts from started_at, so it must outlast the phase
@@ -403,7 +403,7 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
# 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_experiment_metrics(experiment)
+ metrics = get_metrics_for_calculation(experiment)
recalc = ExperimentMetricsRecalculation.objects.create(
team=experiment.team,
experiment=experiment,
@@ -411,7 +411,7 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
status=ExperimentMetricsRecalculation.Status.PENDING,
created_by=user,
total_metrics=len(metrics),
- metric_uuids=[m.metric_uuid for m in metrics],
+ metric_uuids=[m.uuid for m in metrics],
)
return build_job_payload(recalc, is_existing=False)
diff --git a/products/experiments/backend/temporal/enrollment_census_logic.py b/products/experiments/backend/temporal/enrollment_census_logic.py
index d9b7fc4ebbe5..3c665d7f4ab7 100644
--- a/products/experiments/backend/temporal/enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/enrollment_census_logic.py
@@ -181,7 +181,7 @@ def fetch_direct_scan_stats(window_days: int) -> list[TeamDirectScanStats]:
def running_experiment_load(team_ids: list[int]) -> dict[int, TeamRunningLoad]:
"""Per team: running experiment count and scheduled metric count across them.
- Mirrors discover_experiment_metrics (inline primary + secondary + saved-metric links, filtered by
+ Mirrors get_metrics_for_calculation (inline primary + secondary + saved-metric links, filtered by
the shared is_scheduled_metric predicate) so the projected build load matches what
nightly recalculation would actually schedule. Counts in two bulk queries instead of
resolving the metrics of each experiment, so a team running thousands of experiments
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 5fdd79df62c1..e3c70b213947 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -118,23 +118,6 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:
)
-def discover_experiment_metrics(experiment: Experiment) -> list[ExperimentMetricToRecalculate]:
- """All metrics to recalculate for an experiment, in (primary, secondary, saved) order.
-
- 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.
-
- 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.
- """
- return [
- ExperimentMetricToRecalculate(experiment_id=experiment.id, metric_uuid=metric.uuid, metric_type=metric.role)
- for metric in get_metrics_for_calculation(experiment)
- ]
-
-
@database_sync_to_async_pool
def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
close_old_connections()
@@ -144,7 +127,12 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentM
recalculation = ExperimentMetricsRecalculation.objects.select_related("experiment").get(id=recalculation_id)
experiment = recalculation.experiment
- metrics_to_recalculate = discover_experiment_metrics(experiment)
+ # request_recalculation sets total_metrics from the same resolver, so the run's progress count
+ # matches the metrics this activity schedules.
+ metrics_to_recalculate = [
+ ExperimentMetricToRecalculate(experiment_id=experiment.id, metric_uuid=metric.uuid, metric_type=metric.role)
+ for metric in get_metrics_for_calculation(experiment)
+ ]
recalculation.metric_uuids = [m.metric_uuid for m in metrics_to_recalculate]
recalculation.save(update_fields=["metric_uuids"])
@@ -357,7 +345,7 @@ def _capture_results_refresh_completed(update: RecalculationProgressUpdate) -> N
experiment_duration_hours = round(hours_since_launch) if hours_since_launch is not None else None
# Count from the discovery list that also sets total_metrics, so saved metrics count and legacy
# metrics that the run never calculates do not.
- roles = [metric.metric_type for metric in discover_experiment_metrics(experiment)]
+ roles = [metric.role for metric in get_metrics_for_calculation(experiment)]
primary_metrics_count = roles.count("primary")
secondary_metrics_count = roles.count("secondary")
# Global client, like most Temporal workflows: the worker is long-lived, so its background flush