: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): scheduled recalculation selection logic (#108099)
Rodrigo Ilorod9fbceacebd7
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.pynew file mode 100644index 000000000000..f7c7f4ed3703--- /dev/null+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py@@ -0,0 +1,203 @@+"""Selection rules for the scheduled experiment recalculation workflow.++Pure synchronous functions, no Temporal imports, so every rule is testable on its own. The+workflow's activities in `scheduled_recalculation_activities` are thin wrappers over these.+"""++from datetime import timedelta+from typing import Final++from django.utils import timezone++import structlog++from posthog.dataclasses import frozen+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__)++SCHEDULED_RECALCULATION_FEATURE_FLAG = "experiments-scheduled-recalculation"++# Matches the daily timeseries discovery in posthog/temporal/experiments/activities.py, so both+# systems agree on which experiments are worth computing.+EXPERIMENT_RECALCULATION_MAX_AGE_DAYS = 60++# An experiment younger than this has too little data for the queries to be worth their cost.+MIN_EXPERIMENT_AGE = timedelta(hours=12)++MIN_TOTAL_EXPOSURES = 50++# A run finished inside this window already left fresh enough data on the page.+MIN_TIME_SINCE_LAST_RECALCULATION = timedelta(hours=1)++SKIP_INSUFFICIENT_EXPOSURES: Final = "insufficient_exposures"+SKIP_EXPOSURE_QUERY_FAILED: Final = "exposure_query_failed"+SKIP_ACTIVE_RUN: Final = "active_run_exists"+SKIP_RECENT_RUN: Final = "recent_run_exists"+++@frozen+class ScheduledRecalculationCandidate:+ experiment_id: int+ team_id: int+ organization_id: str+++@frozen+class ScheduledRecalculationDiscovery:+ """One hour's candidates, with the hour the run resolved, so callers report what it selected for."""++ hour: int+ candidates: list[ScheduledRecalculationCandidate]+++@frozen+class SkipDecision:+ reason: str+ detail: dict[str, str | int | float | None]+++def team_has_scheduled_recalculation_enabled(team_id: int, organization_id: str) -> bool:+ return feature_enabled_or_false(+ SCHEDULED_RECALCULATION_FEATURE_FLAG,+ str(team_id),+ groups={"organization": organization_id, "project": str(team_id)},+ group_properties={"organization": {"id": organization_id}, "project": {"id": str(team_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+++def find_scheduled_recalculation_candidates() -> ScheduledRecalculationDiscovery:+ """Experiments eligible for a scheduled recalculation right now, before the exposure gate.++ Reads the hour itself rather than taking it as a parameter, so one hourly schedule serves+ every team. An activity may read a clock; a workflow body may not.++ Deliberately applies no metrics filter: an experiment with no metrics gets a run, and the+ recalculation workflow completes it immediately.+ """+ # Deferred: importing this module runs posthog/temporal/experiments/__init__.py, which pulls+ # activities.py, which imports back into products.experiments.backend.facade.timeseries.+ from posthog.temporal.experiments.utils import recalculation_hour_filter # noqa: PLC0415 — breaks that cycle++ now = timezone.now()+ hour = now.hour++ time_filter = recalculation_hour_filter(hour)++ rows = (+ Experiment.objects.filter(+ time_filter,+ deleted=False,+ status=Experiment.Status.RUNNING,+ start_date__gte=now - timedelta(days=EXPERIMENT_RECALCULATION_MAX_AGE_DAYS),+ start_date__lte=now - MIN_EXPERIMENT_AGE,+ )+ .values_list("id", "team_id", "team__organization_id")+ .order_by("id")+ )++ # Cache per team: the flag is evaluated locally, but a team with many experiments would+ # otherwise repeat the same lookup once per row.+ enabled_teams: dict[int, bool] = {}+ candidates: list[ScheduledRecalculationCandidate] = []+ for experiment_id, team_id, organization_id in rows:+ if team_id not in enabled_teams:+ enabled_teams[team_id] = team_has_scheduled_recalculation_enabled(team_id, str(organization_id))+ if not enabled_teams[team_id]:+ continue+ candidates.append(+ ScheduledRecalculationCandidate(+ experiment_id=experiment_id, team_id=team_id, organization_id=str(organization_id)+ )+ )++ logger.info("scheduled_recalculation_candidates", hour=hour, count=len(candidates))+ return ScheduledRecalculationDiscovery(hour=hour, candidates=candidates)+++def recent_recalculation_skip(experiment: Experiment, team_id: int) -> SkipDecision | None:+ """Skip when a run is already active, or when one finished inside the freshness window.++ `timeseries_sync` rows never count toward freshness. The timeseries workflow publishes one+ at :00 and this workflow runs at :30, so counting it would skip every experiment forever.++ Scopes explicitly with `for_team`: the model is fail-closed and an activity carries no request+ context, so an unscoped read would raise `TeamScopeError`.++ `get_active_recalculation` owns the definition of "active", staleness bound included: nothing+ reaps an abandoned row in the background, so an unbounded check would lock the experiment out+ of every later scheduled run.+ """+ scoped = ExperimentMetricsRecalculation.objects.for_team(team_id)++ active = get_active_recalculation(experiment)+ if active is not None:+ return SkipDecision(reason=SKIP_ACTIVE_RUN, detail={"existing_recalculation_id": str(active.id)})++ latest = (+ scoped.filter(+ experiment=experiment,+ completed_at__isnull=False,+ completed_at__gte=timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATION,+ )+ .exclude(trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC)+ .order_by("-completed_at")+ .first()+ )+ if latest is not None and latest.completed_at is not None:+ minutes = int((timezone.now() - latest.completed_at).total_seconds() // 60)+ return SkipDecision(+ reason=SKIP_RECENT_RUN,+ detail={"latest_recalculation_id": str(latest.id), "minutes_since_completion": minutes},+ )++ return None+++def count_total_exposures(experiment: Experiment) -> int:+ """Total exposed entities across variants, over the experiment's own window.++ The `$multiple` bucket holds entities that saw more than one variant, so it is not a+ variant's audience and does not count toward the threshold.+ """+ from posthog.schema import ExperimentExposureQuery # noqa: PLC0415 — keeps the schema import off the module path++ from posthog.clickhouse.query_tagging import Product, tags_context+ from posthog.hogql_queries.query_runner import ExecutionMode++ from products.experiments.backend.hogql_queries.experiment_exposures_query_runner import (+ ExperimentExposuresQueryRunner,+ )++ feature_flag = experiment.feature_flag+ # The FK gives a model instance, and the query field is a pydantic type with no+ # attribute-based validation, so it must be serialized first.+ experiment_holdout = experiment.holdout+ holdout = (+ {"id": experiment_holdout.id, "name": experiment_holdout.name, "filters": experiment_holdout.filters}+ if experiment_holdout is not None+ else None+ )+ query = ExperimentExposureQuery(+ experiment_id=experiment.id,+ experiment_name=experiment.name,+ feature_flag={"key": feature_flag.key, "filters": feature_flag.filters},+ start_date=experiment.start_date.isoformat() if experiment.start_date else None,+ end_date=experiment.end_date.isoformat() if experiment.end_date else None,+ exposure_criteria=experiment.exposure_criteria,+ holdout=holdout,+ )+ with tags_context(+ product=Product.EXPERIMENTS, team_id=experiment.team_id, org_id=str(experiment.team.organization_id)+ ):+ runner = ExperimentExposuresQueryRunner(query=query, team=experiment.team, error_event_context=None)+ response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)++ total_exposures = getattr(response, "total_exposures", None) or {}+ return sum(value for key, value in total_exposures.items() if key != MULTIPLE_VARIANT_KEY)diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.pynew file mode 100644index 000000000000..ceed71978aa5--- /dev/null+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py@@ -0,0 +1,306 @@+import contextlib+from datetime import timedelta+from types import SimpleNamespace+from typing import Any+from uuid import uuid4++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from parameterized import parameterized++from posthog.models.scoping import team_scope+from posthog.models.team import Team++from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY+from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentMetricsRecalculation+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.experiments.backend.temporal.scheduled_recalculation_logic import (+ EXPERIMENT_RECALCULATION_MAX_AGE_DAYS,+ MIN_EXPERIMENT_AGE,+ MIN_TIME_SINCE_LAST_RECALCULATION,+ SKIP_ACTIVE_RUN,+ SKIP_RECENT_RUN,+ count_total_exposures,+ find_scheduled_recalculation_candidates,+ recent_recalculation_skip,+ team_has_scheduled_recalculation_enabled,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _metric() -> dict[str, Any]:+ return {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}+++# Pinned at the default recalculation hour: a team with no config falls to hour 2, so a+# test that does not care about the hour still sees its experiments selected.+@time_machine.travel("2026-09-15T02:30:00Z", tick=False)+class TestScheduledRecalculationLogic(BaseTest):+ def _experiment(self, *, team: Team | None = None, started_hours_ago: float = 48, **overrides: Any) -> Experiment:+ team = team or self.team+ flag = FeatureFlag.objects.create(+ team=team, key=f"flag-{uuid4()}", created_by=self.user, filters={"groups": []}+ )+ # No status here: save() always recomputes it from start_date and end_date.+ defaults: dict[str, Any] = {+ "team": team,+ "name": "exp",+ "feature_flag": flag,+ "start_date": timezone.now() - timedelta(hours=started_hours_ago),+ "metrics": [_metric()],+ }+ defaults.update(overrides)+ return Experiment.objects.create(**defaults)++ def _candidate_ids(self, hour: int | None = None) -> set[int]:+ # Discovery reads the hour from the clock, so a case that cares about the hour selects it+ # by travelling there. The minute stays at :30 so an age measured from the class instant+ # does not move.+ clock = (+ time_machine.travel(f"2026-09-15T{hour:02d}:30:00Z", tick=False)+ if hour is not None+ else contextlib.nullcontext()+ )+ with (+ clock,+ patch(+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",+ return_value=True,+ ),+ ):+ return {c.experiment_id for c in find_scheduled_recalculation_candidates().candidates}++ def test_default_hour_picks_up_team_without_config(self):+ experiment = self._experiment()+ assert experiment.id in self._candidate_ids(2)+ assert experiment.id not in self._candidate_ids(5)++ def test_configured_hour_overrides_default(self):+ TeamExperimentsConfig.objects.update_or_create(+ team=self.team,+ defaults={"experiment_recalculation_times": ["05:00:00"]},+ )+ experiment = self._experiment()+ assert experiment.id in self._candidate_ids(5)+ assert experiment.id not in self._candidate_ids(2)++ def test_both_configured_times_select_the_experiment(self):+ # Matching only the first entry would drop the team's second daily run.+ TeamExperimentsConfig.objects.update_or_create(+ team=self.team,+ defaults={"experiment_recalculation_times": ["00:00:00", "12:00:00"]},+ )+ experiment = self._experiment()+ assert experiment.id in self._candidate_ids(0)+ assert experiment.id in self._candidate_ids(12)+ assert experiment.id not in self._candidate_ids(6)++ def test_a_team_with_no_configured_times_falls_to_the_default_hour(self):+ TeamExperimentsConfig.objects.update_or_create(+ team=self.team,+ defaults={"experiment_recalculation_times": None},+ )+ experiment = self._experiment()+ assert experiment.id in self._candidate_ids(2)+ assert experiment.id not in self._candidate_ids(5)++ def test_deleted_experiment_is_excluded(self):+ experiment = self._experiment(deleted=True)+ assert experiment.id not in self._candidate_ids(2)++ @parameterized.expand(+ [+ ("draft", {"start_date": None}, Experiment.Status.DRAFT),+ ("stopped", {"end_date": timezone.now() - timedelta(hours=1)}, Experiment.Status.STOPPED),+ ]+ )+ def test_non_running_experiments_are_excluded(self, _name: str, overrides: dict[str, Any], expected_status: str):+ # save() recomputes status from the dates, so a status override would be silently ignored.+ experiment = self._experiment(**overrides)+ assert experiment.status == expected_status+ assert experiment.id not in self._candidate_ids(2)++ @parameterized.expand(+ [+ ("too_new", 3, False),+ ("just_old_enough", 13, True),+ ("too_old", 24 * 61, False),+ ("min_age_boundary", MIN_EXPERIMENT_AGE.total_seconds() / 3600, True),+ ("max_age_boundary", EXPERIMENT_RECALCULATION_MAX_AGE_DAYS * 24, True),+ ]+ )+ def test_age_bounds(self, _name: str, started_hours_ago: float, expected: bool):+ # The boundary cases sit on the inclusive edge, so the fixture and the filter must+ # read the same instant or they fall a hair outside it. The class-level clock pin+ # guarantees that.+ experiment = self._experiment(started_hours_ago=started_hours_ago)+ assert (experiment.id in self._candidate_ids()) is expected++ def test_experiment_without_metrics_is_a_candidate(self):+ experiment = self._experiment(metrics=[])+ assert experiment.id in self._candidate_ids(2)++ def test_feature_flag_off_yields_no_candidates(self):+ self._experiment()+ with patch(+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",+ return_value=False,+ ):+ assert find_scheduled_recalculation_candidates().candidates == []++ def test_flag_is_evaluated_once_per_team(self):+ for _ in range(3):+ self._experiment()+ with patch(+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",+ return_value=True,+ ) as flag:+ find_scheduled_recalculation_candidates()+ assert flag.call_count == 1++ def test_no_recalculations_means_no_skip(self):+ experiment = self._experiment()+ assert recent_recalculation_skip(experiment, self.team.id) is None++ @parameterized.expand(+ [+ ("pending", ExperimentMetricsRecalculation.Status.PENDING, ExperimentMetricsRecalculation.Trigger.MANUAL),+ (+ "in_progress",+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ ExperimentMetricsRecalculation.Trigger.MANUAL,+ ),+ (+ # Excluded from the freshness check, but an in-flight sync run still blocks a start.+ "pending_timeseries_sync",+ ExperimentMetricsRecalculation.Status.PENDING,+ ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,+ ),+ ]+ )+ def test_active_run_skips(self, _name: str, status: str, trigger: str):+ experiment = self._experiment()+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=experiment, status=status, trigger=trigger, started_at=timezone.now()+ )+ decision = recent_recalculation_skip(experiment, self.team.id)+ assert decision is not None+ assert decision.reason == SKIP_ACTIVE_RUN++ @parameterized.expand(+ [+ ("pending", ExperimentMetricsRecalculation.Status.PENDING),+ ("in_progress", ExperimentMetricsRecalculation.Status.IN_PROGRESS),+ ]+ )+ def test_stale_active_run_does_not_skip(self, _name: str, status: str):+ # Nothing reaps an abandoned row, so an unbounded active check would lock the experiment out.+ experiment = self._experiment()+ stale = timezone.now() - timedelta(days=5)+ with team_scope(self.team.id, canonical=True):+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=experiment, status=status, started_at=stale+ )+ ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(created_at=stale)+ assert recent_recalculation_skip(experiment, self.team.id) is None++ def test_recent_completed_run_skips(self):+ experiment = self._experiment()+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ completed_at=timezone.now() - timedelta(minutes=10),+ )+ decision = recent_recalculation_skip(experiment, self.team.id)+ assert decision is not None+ assert decision.reason == SKIP_RECENT_RUN+ assert decision.detail["minutes_since_completion"] == 10++ def test_old_completed_run_does_not_skip(self):+ experiment = self._experiment()+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ completed_at=timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATION - timedelta(minutes=1),+ )+ assert recent_recalculation_skip(experiment, self.team.id) is None++ def test_recent_timeseries_sync_run_is_ignored(self):+ # A sync row published at :00 is always fresher than the limit, so counting it+ # would stop every :30 run.+ experiment = self._experiment()+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,+ completed_at=timezone.now() - timedelta(minutes=5),+ )+ assert recent_recalculation_skip(experiment, self.team.id) is None++ def test_unfinished_failed_run_is_ignored(self):+ experiment = self._experiment()+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.FAILED,+ completed_at=None,+ )+ assert recent_recalculation_skip(experiment, self.team.id) is None++ def test_flag_helper_passes_group_properties(self):+ with patch(+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",+ return_value=True,+ ) as flag:+ assert team_has_scheduled_recalculation_enabled(self.team.id, str(self.team.organization_id)) is True+ assert flag.call_args.kwargs["groups"]["organization"] == str(self.team.organization_id)+ assert flag.call_args.kwargs["only_evaluate_locally"] is True++ def test_exposure_count_sums_variants_and_drops_the_multiple_bucket(self):+ # $multiple holds entities that saw more than one variant, so it is not a variant's+ # audience and must not count toward the threshold.+ experiment = self._experiment()+ response = SimpleNamespace(total_exposures={"control": 40, "test": 35, MULTIPLE_VARIANT_KEY: 500})+ runner = MagicMock()+ runner.run.return_value = response+ with patch(+ "products.experiments.backend.hogql_queries.experiment_exposures_query_runner.ExperimentExposuresQueryRunner",+ return_value=runner,+ ):+ assert count_total_exposures(experiment) == 75++ def test_exposure_count_is_zero_when_the_runner_returns_nothing(self):+ experiment = self._experiment()+ runner = MagicMock()+ runner.run.return_value = SimpleNamespace(total_exposures=None)+ with patch(+ "products.experiments.backend.hogql_queries.experiment_exposures_query_runner.ExperimentExposuresQueryRunner",+ return_value=runner,+ ):+ assert count_total_exposures(experiment) == 0++ def test_exposure_count_serializes_a_holdout(self):+ # The FK gives a model instance and the query field is a pydantic type, so passing the+ # instance through raises inside the runner and the experiment reads as query-failed.+ holdout = ExperimentHoldout.objects.create(team=self.team, name="h", filters=[])+ experiment = self._experiment(holdout=holdout)+ runner = MagicMock()+ runner.run.return_value = SimpleNamespace(total_exposures={"control": 10, "test": 10})+ with patch(+ "products.experiments.backend.hogql_queries.experiment_exposures_query_runner.ExperimentExposuresQueryRunner",+ return_value=runner,+ ) as runner_class:+ assert count_total_exposures(experiment) == 20+ assert runner_class.call_args.kwargs["query"].holdout.id == holdout.id