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): scheduled recalculation workflow and activities (#108100)

Rodrigo Iloro67731213c5c3
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 968e3409c834..605aa40f6234 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -221,6 +221,8 @@ from products.experiments.backend.temporal import (
EXPERIMENT_CANARY_WORKFLOWS,
EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES,
EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS,
+ EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES,
+ EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS,
WORKFLOWS as EXPERIMENTS_RECALCULATION_WORKFLOWS,
)
from products.exports.backend.temporal.subscriptions import (
@@ -372,6 +374,7 @@ _task_queue_specs = [
+ EXPERIMENTS_WORKFLOWS
+ EXPERIMENT_CANARY_WORKFLOWS
+ EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS
+ + EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS
+ CLEANUP_PROPDEFS_WORKFLOWS
+ [BackfillMaterializedPropertiesBatchWorkflow]
+ BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS
@@ -399,6 +402,7 @@ _task_queue_specs = [
+ EXPERIMENTS_ACTIVITIES
+ EXPERIMENT_CANARY_ACTIVITIES
+ EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES
+ + EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES
+ CLEANUP_PROPDEFS_ACTIVITIES
+ BACKFILL_MATERIALIZED_PROPERTY_ACTIVITIES
+ BACKFILL_GROUP_TYPE_CREATED_AT_ACTIVITIES
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 37843a3a6492..2428ac49f74e 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -282,7 +282,7 @@ def _cancel_superseded_workflows(recalculation_ids: list[str]) -> None:
pass
-def request_recalculation(experiment: Experiment, user: User, trigger: str = "manual") -> dict:
+def request_recalculation(experiment: Experiment, user: User | None, trigger: str = "manual") -> dict:
"""Create an idempotent batch recalculation request for all experiment metrics.
If an active (pending or in_progress) run already exists for this experiment, returns the existing run's
diff --git a/products/experiments/backend/temporal/__init__.py b/products/experiments/backend/temporal/__init__.py
index 4b7daced4363..70986e07e96b 100644
--- a/products/experiments/backend/temporal/__init__.py
+++ b/products/experiments/backend/temporal/__init__.py
@@ -14,6 +14,14 @@ from products.experiments.backend.temporal.recalculation_activities import (
update_recalculation_progress,
)
from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
+from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ check_experiment_exposures,
+ discover_scheduled_recalculation_candidates,
+ start_scheduled_recalculation,
+)
+from products.experiments.backend.temporal.scheduled_recalculation_workflow import (
+ ScheduledExperimentRecalculationWorkflow,
+)
EXPERIMENT_CANARY_WORKFLOWS = [
ExperimentPrecomputeCanaryWorkflow,
@@ -29,11 +37,20 @@ EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS = [
EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES = [
run_experiment_enrollment_census,
]
+EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS = [
+ ScheduledExperimentRecalculationWorkflow,
+]
+EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES = [
+ discover_scheduled_recalculation_candidates,
+ check_experiment_exposures,
+ start_scheduled_recalculation,
+]
WORKFLOWS = [
ExperimentMetricsRecalculationWorkflow,
*EXPERIMENT_CANARY_WORKFLOWS,
*EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS,
+ *EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS,
]
ACTIVITIES = [
discover_experiment_metrics,
@@ -41,6 +58,7 @@ ACTIVITIES = [
update_recalculation_progress,
*EXPERIMENT_CANARY_ACTIVITIES,
*EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES,
+ *EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES,
]
__all__ = [
@@ -49,15 +67,21 @@ __all__ = [
"EXPERIMENT_CANARY_WORKFLOWS",
"EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES",
"EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS",
+ "EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES",
+ "EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS",
"WORKFLOWS",
"ExperimentMetricsRecalculationWorkflow",
"ExperimentPrecomputeCanaryWorkflow",
"ExperimentPrecomputeEnrollmentCensusWorkflow",
+ "ScheduledExperimentRecalculationWorkflow",
"calculate_experiment_metric_for_recalculation",
+ "check_experiment_exposures",
"discover_experiment_metrics",
+ "discover_scheduled_recalculation_candidates",
"report_experiment_canary_results",
"run_experiment_enrollment_census",
"run_experiment_metric_canary",
"sample_experiment_canary_targets",
+ "start_scheduled_recalculation",
"update_recalculation_progress",
]
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index b480b178f724..ee15d87ae5b1 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -214,3 +214,16 @@ class ExperimentPrecomputeEnrollmentCensusInputs:
would qualify for precomputation enrollment; it never enrolls anyone."""
window_days: int = 14
+
+
+SCHEDULED_RECALCULATION_WORKFLOW_NAME = "experiment-scheduled-recalculation-workflow"
+
+
+@frozen
+class ScheduledRecalculationStartResult:
+ """Outcome of one experiment's start attempt, for the coordinator's summary counts."""
+
+ experiment_id: int
+ started: bool
+ recalculation_id: str | None = None
+ skip_reason: str | None = None
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_activities.py b/products/experiments/backend/temporal/scheduled_recalculation_activities.py
new file mode 100644
index 000000000000..bede01a0d969
--- /dev/null
+++ b/products/experiments/backend/temporal/scheduled_recalculation_activities.py
@@ -0,0 +1,178 @@
+"""Activities for the scheduled experiment recalculation workflow.
+
+Each one wraps `scheduled_recalculation_logic` and reports its outcome to product analytics.
+Every activity is fire and forget: a failure skips one experiment and never stops the batch,
+because the recalculation workflow it starts owns its own retries and error reporting.
+"""
+
+from typing import Any
+
+from django.db import close_old_connections
+
+import structlog
+import posthoganalytics
+import temporalio.activity
+
+from posthog.event_usage import groups
+from posthog.sync import database_sync_to_async_pool
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
+from products.experiments.backend.temporal.models import ScheduledRecalculationStartResult
+from products.experiments.backend.temporal.scheduled_recalculation_logic import (
+ MIN_TOTAL_EXPOSURES,
+ SKIP_ACTIVE_RUN,
+ SKIP_EXPOSURE_QUERY_FAILED,
+ SKIP_INSUFFICIENT_EXPOSURES,
+ ScheduledRecalculationDiscovery,
+ count_total_exposures,
+ find_scheduled_recalculation_candidates,
+ recent_recalculation_skip,
+)
+
+logger = structlog.get_logger(__name__)
+
+STARTED_EVENT = "experiment scheduled recalculation started"
+SKIPPED_EVENT = "experiment scheduled recalculation skipped"
+
+
+def _capture(experiment: Experiment, event: str, properties: dict[str, Any]) -> None:
+ """Global client, not ph_scoped_capture: the worker is long lived, so its background flush
+ runs, while a scoped client's synchronous shutdown stalls the activity for about twice the
+ flush interval. Telemetry must never fail an activity, so every error is swallowed."""
+ try:
+ team = experiment.team
+ distinct_id = (
+ experiment.created_by.distinct_id
+ if experiment.created_by and experiment.created_by.distinct_id
+ else f"team_{team.id}"
+ )
+ posthoganalytics.capture(
+ distinct_id=distinct_id,
+ event=event,
+ properties={"experiment_id": experiment.id, "team_id": team.id, **properties},
+ groups=groups(organization=team.organization, team=team),
+ )
+ except Exception:
+ logger.warning("scheduled_recalculation_capture_failed", event=event, experiment_id=experiment.id)
+
+
+def capture_skip(experiment: Experiment, hour: int, reason: str, detail: dict[str, Any]) -> None:
+ _capture(experiment, SKIPPED_EVENT, {"hour": hour, "reason": reason, **detail})
+
+
+def capture_started(experiment: Experiment, hour: int, recalculation_id: str) -> None:
+ _capture(experiment, STARTED_EVENT, {"hour": hour, "recalculation_id": recalculation_id})
+
+
+@database_sync_to_async_pool
+def _discover_scheduled_recalculation_candidates_sync() -> ScheduledRecalculationDiscovery:
+ close_old_connections()
+ return find_scheduled_recalculation_candidates()
+
+
+async def discover_scheduled_recalculation_candidates() -> ScheduledRecalculationDiscovery:
+ """Experiments eligible for a scheduled recalculation now, before the exposure gate.
+
+ Returns the hour it selected for alongside the candidates, so the workflow and the events
+ report the window without the workflow reading a clock of its own.
+ """
+ return await _discover_scheduled_recalculation_candidates_sync()
+
+
+@database_sync_to_async_pool
+def _check_experiment_exposures_sync(experiment_id: int, hour: int) -> bool:
+ close_old_connections()
+ experiment = Experiment.objects.filter(id=experiment_id, deleted=False).first()
+ if experiment is None:
+ return False
+ try:
+ total = count_total_exposures(experiment)
+ except Exception as error:
+ capture_skip(experiment, hour, reason=SKIP_EXPOSURE_QUERY_FAILED, detail={"error_message": str(error)[:500]})
+ logger.warning("scheduled_recalculation_exposure_query_failed", experiment_id=experiment_id)
+ return False
+ if total < MIN_TOTAL_EXPOSURES:
+ capture_skip(experiment, hour, reason=SKIP_INSUFFICIENT_EXPOSURES, detail={"total_exposures": total})
+ return False
+ return True
+
+
+async def check_experiment_exposures(experiment_id: int, hour: int) -> bool:
+ """Whether one experiment has enough exposures to be worth recalculating.
+
+ A query failure counts as a skip: an experiment whose exposure query fails would fail its
+ metric queries too, so starting a run would only burn the cluster.
+ """
+ return await _check_experiment_exposures_sync(experiment_id, hour)
+
+
+@database_sync_to_async_pool
+def _start_scheduled_recalculation_sync(experiment_id: int, hour: int) -> ScheduledRecalculationStartResult:
+ # Deferred: recalculation.py imports temporal.recalculation_logic at module level, and this
+ # module is loaded from the temporal package's __init__, so a module-level import here closes
+ # a cycle back into a partially initialized module.
+ from products.experiments.backend.recalculation import ( # noqa: PLC0415 — breaks that cycle
+ request_recalculation,
+ start_metrics_recalculation_workflow,
+ )
+
+ close_old_connections()
+ # Re-check RUNNING, not just deleted: discovery ran before the exposure query, and an
+ # experiment stopped in between should not get a scheduled run.
+ experiment = (
+ Experiment.objects.filter(id=experiment_id, deleted=False, status=Experiment.Status.RUNNING)
+ .select_related("team")
+ .first()
+ )
+ if experiment is None:
+ return ScheduledRecalculationStartResult(experiment_id=experiment_id, started=False)
+
+ skip = recent_recalculation_skip(experiment, experiment.team_id)
+ if skip is not None:
+ capture_skip(experiment, hour, reason=skip.reason, detail=dict(skip.detail))
+ return ScheduledRecalculationStartResult(experiment_id=experiment_id, started=False, skip_reason=skip.reason)
+
+ try:
+ payload = request_recalculation(experiment, None, ExperimentMetricsRecalculation.Trigger.SCHEDULED)
+ except Exception:
+ logger.warning("scheduled_recalculation_request_failed", experiment_id=experiment_id, exc_info=True)
+ return ScheduledRecalculationStartResult(experiment_id=experiment_id, started=False)
+
+ # The pre-check above and this create are separate, unsynchronized reads: a run can start
+ # between them. request_recalculation's own is_existing flag closes that window instead of
+ # relying on the two staying in step.
+ if payload.get("is_existing"):
+ return ScheduledRecalculationStartResult(
+ experiment_id=experiment_id, started=False, skip_reason=SKIP_ACTIVE_RUN
+ )
+
+ recalculation_id = str(payload["id"])
+ try:
+ start_metrics_recalculation_workflow(
+ recalculation_id,
+ team_id=experiment.team_id,
+ organization_id=str(experiment.team.organization_id),
+ )
+ except Exception:
+ # start_metrics_recalculation_workflow rolls the row back to FAILED itself, so an orphaned
+ # PENDING row cannot look active to every later scheduled run.
+ logger.warning(
+ "scheduled_recalculation_dispatch_failed",
+ experiment_id=experiment_id,
+ recalculation_id=recalculation_id,
+ exc_info=True,
+ )
+ return ScheduledRecalculationStartResult(experiment_id=experiment_id, started=False)
+
+ capture_started(experiment, hour, recalculation_id)
+ return ScheduledRecalculationStartResult(
+ experiment_id=experiment_id, started=True, recalculation_id=recalculation_id
+ )
+
+
+async def start_scheduled_recalculation(experiment_id: int, hour: int) -> ScheduledRecalculationStartResult:
+ """Create the recalculation row and dispatch its workflow, unless a recent or active run exists."""
+ return await _start_scheduled_recalculation_sync(experiment_id, hour)
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
index f7c7f4ed3703..3a38d45ee732 100644
--- a/products/experiments/backend/temporal/scheduled_recalculation_logic.py
+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
@@ -16,7 +16,6 @@ from posthog.ph_client import feature_enabled_or_false
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
-from products.experiments.backend.recalculation import get_active_recalculation
logger = structlog.get_logger(__name__)
@@ -134,6 +133,10 @@ def recent_recalculation_skip(experiment: Experiment, team_id: int) -> SkipDecis
reaps an abandoned row in the background, so an unbounded check would lock the experiment out
of every later scheduled run.
"""
+ # Deferred: recalculation.py imports temporal.recalculation_logic at module level, so a
+ # module-level import here closes a cycle back into a partially initialized module.
+ from products.experiments.backend.recalculation import get_active_recalculation # noqa: PLC0415 — breaks that cycle
+
scoped = ExperimentMetricsRecalculation.objects.for_team(team_id)
active = get_active_recalculation(experiment)
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_workflow.py b/products/experiments/backend/temporal/scheduled_recalculation_workflow.py
new file mode 100644
index 000000000000..d31ae1f576f9
--- /dev/null
+++ b/products/experiments/backend/temporal/scheduled_recalculation_workflow.py
@@ -0,0 +1,83 @@
+import asyncio
+from datetime import timedelta
+
+import temporalio.workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with temporalio.workflow.unsafe.imports_passed_through():
+ from products.experiments.backend.temporal.models import SCHEDULED_RECALCULATION_WORKFLOW_NAME
+ from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ check_experiment_exposures,
+ discover_scheduled_recalculation_candidates,
+ start_scheduled_recalculation,
+ )
+ from products.experiments.backend.temporal.scheduled_recalculation_logic import ScheduledRecalculationDiscovery
+
+# Matches the daily timeseries workflows. Each unit here is one cheap query plus one workflow
+# start, so this bounds the exposure queries rather than the recalculations themselves.
+MAX_CONCURRENT_EXPERIMENTS = 10
+
+
[email protected](name=SCHEDULED_RECALCULATION_WORKFLOW_NAME)
+class ScheduledExperimentRecalculationWorkflow(PostHogWorkflow):
+ """Start a real metrics recalculation for every experiment eligible this hour.
+
+ One hourly schedule drives it. Discovery resolves the hour from the clock and selects the
+ teams configured for it, so the workflow carries no input and no clock of its own.
+
+ Fire and forget. Each started run is an ordinary `ExperimentMetricsRecalculationWorkflow`,
+ dispatched the same way the API dispatches one, and this workflow never waits for it. The
+ counts it returns are for an operator reading the run, not a source of truth: each run's
+ real outcome lands on its own `ExperimentMetricsRecalculation` row.
+ """
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> None:
+ return None
+
+ @temporalio.workflow.run
+ async def run(self) -> dict[str, int]:
+ discovery: ScheduledRecalculationDiscovery = await temporalio.workflow.execute_activity(
+ discover_scheduled_recalculation_candidates,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ hour, candidates = discovery.hour, discovery.candidates
+
+ if not candidates:
+ return {"hour": hour, "candidates": 0, "started": 0, "skipped": 0}
+
+ semaphore = asyncio.Semaphore(MAX_CONCURRENT_EXPERIMENTS)
+
+ async def _process(experiment_id: int) -> bool:
+ async with semaphore:
+ has_exposures = await temporalio.workflow.execute_activity(
+ check_experiment_exposures,
+ args=[experiment_id, hour],
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ if not has_exposures:
+ return False
+ result = await temporalio.workflow.execute_activity(
+ start_scheduled_recalculation,
+ args=[experiment_id, hour],
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ return bool(result.started)
+
+ outcomes = await asyncio.gather(
+ *[_process(candidate.experiment_id) for candidate in candidates], return_exceptions=True
+ )
+ started = sum(1 for outcome in outcomes if outcome is True)
+
+ temporalio.workflow.logger.info(f"scheduled recalculation hour {hour}: {started} of {len(candidates)} started")
+ return {
+ "hour": hour,
+ "candidates": len(candidates),
+ "started": started,
+ "skipped": len(candidates) - started,
+ }
diff --git a/products/experiments/backend/temporal/test_registration.py b/products/experiments/backend/temporal/test_registration.py
index 71b0b9f5a289..cd8b741c763b 100644
--- a/products/experiments/backend/temporal/test_registration.py
+++ b/products/experiments/backend/temporal/test_registration.py
@@ -5,6 +5,14 @@ from products.experiments.backend.temporal.enrollment_census_workflow import (
ExperimentPrecomputeEnrollmentCensusWorkflow,
)
from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
+from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ check_experiment_exposures,
+ discover_scheduled_recalculation_candidates,
+ start_scheduled_recalculation,
+)
+from products.experiments.backend.temporal.scheduled_recalculation_workflow import (
+ ScheduledExperimentRecalculationWorkflow,
+)
def test_activities_registered():
@@ -17,6 +25,9 @@ def test_activities_registered():
"run_experiment_metric_canary",
"report_experiment_canary_results",
"run_experiment_enrollment_census",
+ "discover_scheduled_recalculation_candidates",
+ "check_experiment_exposures",
+ "start_scheduled_recalculation",
}
@@ -25,6 +36,7 @@ def test_workflow_registered():
ExperimentMetricsRecalculationWorkflow,
ExperimentPrecomputeCanaryWorkflow,
ExperimentPrecomputeEnrollmentCensusWorkflow,
+ ScheduledExperimentRecalculationWorkflow,
]
@@ -49,3 +61,7 @@ def test_scheduled_workflows_registered_on_general_purpose_queue():
assert ExperimentPrecomputeCanaryWorkflow in workflows
assert ExperimentPrecomputeEnrollmentCensusWorkflow in workflows
assert run_experiment_enrollment_census in activities
+ assert ScheduledExperimentRecalculationWorkflow in workflows
+ assert discover_scheduled_recalculation_candidates in activities
+ assert check_experiment_exposures in activities
+ assert start_scheduled_recalculation in activities
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py
new file mode 100644
index 000000000000..643750a00e82
--- /dev/null
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py
@@ -0,0 +1,142 @@
+from datetime import timedelta
+from uuid import uuid4
+
+import time_machine
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from posthog.models.scoping import team_scope
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
+from products.experiments.backend.temporal.models import ScheduledRecalculationStartResult
+from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ _check_experiment_exposures_sync,
+ _start_scheduled_recalculation_sync,
+)
+from products.experiments.backend.temporal.scheduled_recalculation_logic import (
+ SKIP_ACTIVE_RUN,
+ SKIP_EXPOSURE_QUERY_FAILED,
+ SKIP_INSUFFICIENT_EXPOSURES,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+MODULE = "products.experiments.backend.temporal.scheduled_recalculation_activities"
+# The activity resolves these at call time from their own module, to break an import cycle.
+RECALCULATION = "products.experiments.backend.recalculation"
+
+# Unwrap the database_sync_to_async_pool decorator so the bodies run synchronously in the test
+# transaction, matching test_recalculation_activities.py.
+_check_exposures_raw = _check_experiment_exposures_sync.func # type: ignore[attr-defined]
+_start_recalculation_raw = _start_scheduled_recalculation_sync.func # type: ignore[attr-defined]
+
+
+def _check_exposures(experiment_id: int, hour: int) -> bool:
+ # close_old_connections() would drop the connection this test's transaction runs on.
+ with patch(f"{MODULE}.close_old_connections"):
+ return _check_exposures_raw(experiment_id, hour)
+
+
+def _start_recalculation(experiment_id: int, hour: int) -> ScheduledRecalculationStartResult:
+ with patch(f"{MODULE}.close_old_connections"):
+ return _start_recalculation_raw(experiment_id, hour)
+
+
+@time_machine.travel("2026-09-15T12:00:00Z", tick=False)
+class TestScheduledRecalculationActivities(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag = FeatureFlag.objects.create(
+ team=self.team, key=f"flag-{uuid4()}", created_by=self.user, filters={"groups": []}
+ )
+ self.experiment = Experiment.objects.create(
+ team=self.team,
+ name="exp",
+ feature_flag=flag,
+ status=Experiment.Status.RUNNING,
+ start_date=timezone.now() - timedelta(days=2),
+ metrics=[{"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}],
+ )
+
+ def test_exposure_gate_passes_above_threshold(self):
+ with patch(f"{MODULE}.count_total_exposures", return_value=120):
+ assert _check_exposures(self.experiment.id, 2) is True
+
+ def test_exposure_gate_fails_below_threshold(self):
+ with patch(f"{MODULE}.count_total_exposures", return_value=12), patch(f"{MODULE}.capture_skip") as capture:
+ assert _check_exposures(self.experiment.id, 2) is False
+ assert capture.call_args.kwargs["reason"] == SKIP_INSUFFICIENT_EXPOSURES
+
+ def test_exposure_query_failure_skips(self):
+ with (
+ patch(f"{MODULE}.count_total_exposures", side_effect=RuntimeError("clickhouse is sad")),
+ patch(f"{MODULE}.capture_skip") as capture,
+ ):
+ assert _check_exposures(self.experiment.id, 2) is False
+ assert capture.call_args.kwargs["reason"] == SKIP_EXPOSURE_QUERY_FAILED
+
+ def test_start_creates_a_row_and_dispatches_the_workflow(self):
+ with patch(f"{RECALCULATION}.start_metrics_recalculation_workflow") as dispatch:
+ result = _start_recalculation(self.experiment.id, 2)
+ assert result.started is True
+ assert result.recalculation_id is not None
+ with team_scope(self.team.id, canonical=True):
+ recalc = ExperimentMetricsRecalculation.objects.get(id=result.recalculation_id)
+ assert recalc.trigger == ExperimentMetricsRecalculation.Trigger.SCHEDULED
+ assert recalc.created_by is None
+ dispatch.assert_called_once_with(
+ result.recalculation_id,
+ team_id=self.team.id,
+ organization_id=str(self.team.organization_id),
+ )
+
+ def test_start_skips_when_a_run_is_active(self):
+ with team_scope(self.team.id, canonical=True):
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=self.experiment,
+ status=ExperimentMetricsRecalculation.Status.IN_PROGRESS,
+ started_at=timezone.now(),
+ )
+ with patch(f"{RECALCULATION}.start_metrics_recalculation_workflow") as dispatch:
+ result = _start_recalculation(self.experiment.id, 2)
+ assert result.started is False
+ assert result.skip_reason == SKIP_ACTIVE_RUN
+ dispatch.assert_not_called()
+
+ def test_start_skips_when_request_recalculation_reports_an_existing_run(self):
+ with (
+ patch(f"{RECALCULATION}.request_recalculation", return_value={"id": uuid4(), "is_existing": True}),
+ patch(f"{RECALCULATION}.start_metrics_recalculation_workflow") as dispatch,
+ ):
+ result = _start_recalculation(self.experiment.id, 2)
+ assert result.started is False
+ assert result.skip_reason == SKIP_ACTIVE_RUN
+ dispatch.assert_not_called()
+
+ def test_start_reports_not_started_when_dispatch_fails(self):
+ # The row rollback belongs to start_metrics_recalculation_workflow. What this activity owes
+ # is an honest result: no started event for a workflow that never started.
+ with (
+ patch(f"{RECALCULATION}.start_metrics_recalculation_workflow", side_effect=RuntimeError("temporal down")),
+ patch(f"{MODULE}.capture_started") as started_event,
+ ):
+ result = _start_recalculation(self.experiment.id, 2)
+ assert result.started is False
+ started_event.assert_not_called()
+
+ def test_deleted_experiment_is_skipped_not_raised(self):
+ missing_id = self.experiment.id + 10_000
+ assert _check_exposures(missing_id, 2) is False
+ result = _start_recalculation(missing_id, 2)
+ assert result.started is False
+
+ def test_start_skips_an_experiment_stopped_since_discovery(self):
+ # Discovery runs before the exposure query, so the experiment can stop in between.
+ self.experiment.end_date = timezone.now()
+ self.experiment.save()
+ with patch(f"{RECALCULATION}.start_metrics_recalculation_workflow") as dispatch:
+ result = _start_recalculation(self.experiment.id, 2)
+ assert result.started is False
+ dispatch.assert_not_called()
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py b/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py
new file mode 100644
index 000000000000..0c89661be8f3
--- /dev/null
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py
@@ -0,0 +1,111 @@
+import uuid
+
+import pytest
+
+from temporalio import activity
+from temporalio.client import WorkflowFailureError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.experiments.backend.temporal.models import ScheduledRecalculationStartResult
+from products.experiments.backend.temporal.scheduled_recalculation_logic import (
+ ScheduledRecalculationCandidate,
+ ScheduledRecalculationDiscovery,
+)
+from products.experiments.backend.temporal.scheduled_recalculation_workflow import (
+ ScheduledExperimentRecalculationWorkflow,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+def _candidates(*experiment_ids: int) -> list[ScheduledRecalculationCandidate]:
+ return [
+ ScheduledRecalculationCandidate(experiment_id=eid, team_id=1, organization_id="org") for eid in experiment_ids
+ ]
+
+
+async def _run(discover, exposures, start, hour: int = 2) -> dict:
+ @activity.defn(name="discover_scheduled_recalculation_candidates")
+ async def discover_activity() -> ScheduledRecalculationDiscovery:
+ return ScheduledRecalculationDiscovery(hour=hour, candidates=discover(hour))
+
+ @activity.defn(name="check_experiment_exposures")
+ async def exposures_activity(experiment_id: int, hour: int) -> bool:
+ return exposures(experiment_id)
+
+ @activity.defn(name="start_scheduled_recalculation")
+ async def start_activity(experiment_id: int, hour: int) -> ScheduledRecalculationStartResult:
+ return start(experiment_id)
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ task_queue = f"test-{uuid.uuid4()}"
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ScheduledExperimentRecalculationWorkflow],
+ activities=[discover_activity, exposures_activity, start_activity],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ ScheduledExperimentRecalculationWorkflow.run,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+
+async def test_no_candidates_returns_zeroes():
+ result = await _run(lambda hour: [], lambda eid: True, lambda eid: None)
+ assert result == {"hour": 2, "candidates": 0, "started": 0, "skipped": 0}
+
+
+async def test_every_candidate_starts():
+ started: list[int] = []
+
+ def start(experiment_id: int) -> ScheduledRecalculationStartResult:
+ started.append(experiment_id)
+ return ScheduledRecalculationStartResult(
+ experiment_id=experiment_id, started=True, recalculation_id=str(uuid.uuid4())
+ )
+
+ result = await _run(lambda hour: _candidates(1, 2, 3), lambda eid: True, start)
+ assert result["candidates"] == 3
+ assert result["started"] == 3
+ assert result["skipped"] == 0
+ assert sorted(started) == [1, 2, 3]
+
+
+async def test_exposure_gate_stops_the_start_activity():
+ started: list[int] = []
+
+ def start(experiment_id: int) -> ScheduledRecalculationStartResult:
+ started.append(experiment_id)
+ return ScheduledRecalculationStartResult(experiment_id=experiment_id, started=True)
+
+ result = await _run(lambda hour: _candidates(1, 2), lambda eid: eid == 1, start)
+ assert started == [1]
+ assert result["started"] == 1
+ assert result["skipped"] == 1
+
+
+async def test_one_failing_candidate_does_not_stop_the_others():
+ def exposures(experiment_id: int) -> bool:
+ if experiment_id == 2:
+ raise RuntimeError("boom")
+ return True
+
+ result = await _run(
+ lambda hour: _candidates(1, 2, 3),
+ exposures,
+ lambda eid: ScheduledRecalculationStartResult(experiment_id=eid, started=True),
+ )
+ assert result["started"] == 2
+ assert result["skipped"] == 1
+
+
+async def test_discovery_failure_fails_the_workflow():
+ def discover(hour: int) -> list[ScheduledRecalculationCandidate]:
+ raise RuntimeError("postgres is down")
+
+ with pytest.raises(WorkflowFailureError):
+ await _run(discover, lambda eid: True, lambda eid: None)
diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.py
index c355416e0c79..a0f58252be3b 100644
--- a/products/experiments/backend/test/test_recalculation_service.py
+++ b/products/experiments/backend/test/test_recalculation_service.py
@@ -154,6 +154,14 @@ class TestRecalculationService(BaseTest):
assert result["is_existing"] is True
assert result["id"] == str(recent_row.id)
+ def test_request_recalculation_without_a_user(self):
+ exp = self._launched_experiment(flag_key="no-user")
+ result = request_recalculation(exp, None, "stale_refresh")
+ assert result["is_existing"] is False
+ recalc = ExperimentMetricsRecalculation.objects.get(id=result["id"])
+ assert recalc.created_by is None
+ assert recalc.trigger == "stale_refresh"
+
def test_request_recalculation_rejects_unlaunched(self):
exp = Experiment.objects.create(
team=self.team, created_by=self.user, feature_flag=self._flag("unlaunched"), name="draft"
diff --git a/tach.toml b/tach.toml
index 8cf2c8849215..7f55b594ca47 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1173,6 +1173,8 @@ expose = [
"backend\\.temporal\\.EXPERIMENT_CANARY_WORKFLOWS",
"backend\\.temporal\\.EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES",
"backend\\.temporal\\.EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS",
+ "backend\\.temporal\\.EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES",
+ "backend\\.temporal\\.EXPERIMENT_SCHEDULED_RECALCULATION_WORKFLOWS",
"backend\\.temporal\\.WORKFLOWS",
"backend\\.temporal\\.recalculation_metrics.*",
"backend\\.temporal\\.schedule\\.create_experiment_precompute_canary_schedule",