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): run cheap scheduled recalculation checks in discovery (#118046)

Rodrigo Iloro40bc9e52652c
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.md
index ad6928c412fc..e6c43ed88732 100644
--- a/posthog/temporal/experiments/README.md
+++ b/posthog/temporal/experiments/README.md
@@ -104,9 +104,17 @@ The timeseries workflows keep one schedule per hour, because each runs its own m
can outlive its hour. This one starts other workflows and returns, so a single schedule with a
`SKIP` overlap policy covers it.
-It skips an experiment whose recalculation is already running, or whose last one finished within
-the hour. That freshness check ignores `timeseries_sync` rows, which carry a timeseries run's
-window rather than a full recalculation.
+Discovery skips an experiment before its exposure query when:
+
+- its recalculation is already running,
+- its last one finished within the hour on a recent window,
+- no release condition of its flag has a rollout above 0%,
+- it has no metric that the recalculation computes, inline or saved.
+
+The freshness check ignores `timeseries_sync` rows, which carry a timeseries run's window rather
+than a full recalculation. Discovery reads these with a fixed number of queries for the whole hour,
+and sends the skipped event for each experiment it drops. The start step checks the running and
+recent rules again, to catch a run that started after discovery.
The coordinator never waits for the runs it starts. Each run's outcome lands on its own
`ExperimentMetricsRecalculation` row, and the `experiment scheduled recalculation started` and
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 7d1dcfc029f9..d3b46d5d9dc3 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -415,15 +415,23 @@ def request_recalculation(experiment: Experiment, user: User | None, trigger: st
return build_job_payload(recalc, is_existing=False)
+def active_recalculation_filter() -> Q:
+ """The rows that block a new recalculation: PENDING or IN_PROGRESS, inside the staleness bound.
+
+ The scheduled discovery applies the same filter to many experiments in one query, so the two
+ readers cannot disagree on which run is active.
+ """
+ threshold = timezone.now() - _STALE_RECALC_THRESHOLD
+ return Q(status=ExperimentMetricsRecalculation.Status.PENDING, created_at__gte=threshold) | Q(
+ status=ExperimentMetricsRecalculation.Status.IN_PROGRESS, started_at__gte=threshold
+ )
+
+
def get_active_recalculation(experiment: Experiment) -> ExperimentMetricsRecalculation | None:
with team_scope(experiment.team_id, canonical=True):
- threshold = timezone.now() - _STALE_RECALC_THRESHOLD
return (
ExperimentMetricsRecalculation.objects.filter(team=experiment.team, experiment=experiment)
- .filter(
- Q(status=ExperimentMetricsRecalculation.Status.PENDING, created_at__gte=threshold)
- | Q(status=ExperimentMetricsRecalculation.Status.IN_PROGRESS, started_at__gte=threshold)
- )
+ .filter(active_recalculation_filter())
.order_by("-created_at")
.first()
)
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_activities.py b/products/experiments/backend/temporal/scheduled_recalculation_activities.py
index bede01a0d969..f0e987b27c0a 100644
--- a/products/experiments/backend/temporal/scheduled_recalculation_activities.py
+++ b/products/experiments/backend/temporal/scheduled_recalculation_activities.py
@@ -67,7 +67,11 @@ def capture_started(experiment: Experiment, hour: int, recalculation_id: str) ->
@database_sync_to_async_pool
def _discover_scheduled_recalculation_candidates_sync() -> ScheduledRecalculationDiscovery:
close_old_connections()
- return find_scheduled_recalculation_candidates()
+ selection = find_scheduled_recalculation_candidates()
+ hour = selection.discovery.hour
+ for skip in selection.skips:
+ capture_skip(skip.experiment, hour, reason=skip.decision.reason, detail=dict(skip.decision.detail))
+ return selection.discovery
@temporalio.activity.defn
@@ -75,7 +79,8 @@ async def discover_scheduled_recalculation_candidates() -> ScheduledRecalculatio
"""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.
+ report the window without the workflow reading a clock of its own. Sends the skipped event
+ for each experiment that discovery rejects, so a skip costs the workflow no activity.
"""
return await _discover_scheduled_recalculation_candidates_sync()
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
index b0145abe7307..0c79b50f117f 100644
--- a/products/experiments/backend/temporal/scheduled_recalculation_logic.py
+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py
@@ -4,10 +4,10 @@ Pure synchronous functions, no Temporal imports, so every rule is testable on it
workflow's activities in `scheduled_recalculation_activities` are thin wrappers over these.
"""
-from datetime import timedelta
-from typing import Final
+from datetime import datetime, timedelta
+from typing import TYPE_CHECKING, Final
-from django.db.models import Q
+from django.db.models import Prefetch, Q, QuerySet
from django.utils import timezone
import structlog
@@ -16,7 +16,17 @@ 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.metric_resolution import get_metrics_for_calculation
+from products.experiments.backend.models.experiment import (
+ Experiment,
+ ExperimentMetricsRecalculation,
+ ExperimentToSavedMetric,
+)
+from products.feature_flags.backend.facade.config import ConfigFormatError
+from products.feature_flags.backend.facade.filters import condition_rollout_percentage
+
+if TYPE_CHECKING:
+ from products.feature_flags.backend.models.feature_flag import FeatureFlag
logger = structlog.get_logger(__name__)
@@ -38,6 +48,8 @@ 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"
+SKIP_ZERO_ROLLOUT: Final = "zero_rollout"
+SKIP_NO_METRICS: Final = "no_metrics"
@frozen
@@ -61,6 +73,24 @@ class SkipDecision:
detail: dict[str, str | int | float | None]
+@frozen
+class DiscoverySkip:
+ experiment: Experiment
+ decision: SkipDecision
+
+
+@frozen
+class ScheduledRecalculationSelection:
+ """The discovery result, plus the experiments that discovery skipped.
+
+ Only `discovery` leaves the activity. The skips hold model instances, so the activity reports
+ them itself and never returns them to the workflow.
+ """
+
+ discovery: ScheduledRecalculationDiscovery
+ skips: list[DiscoverySkip]
+
+
def team_has_scheduled_recalculation_enabled(team_id: int, organization_id: str) -> bool:
return feature_enabled_or_false(
SCHEDULED_RECALCULATION_FEATURE_FLAG,
@@ -72,14 +102,15 @@ def team_has_scheduled_recalculation_enabled(team_id: int, organization_id: str)
)
-def find_scheduled_recalculation_candidates() -> ScheduledRecalculationDiscovery:
+def find_scheduled_recalculation_candidates() -> ScheduledRecalculationSelection:
"""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.
+ Skips, before any exposure query, every experiment that `_discovery_skip` rejects: a flag that
+ can serve nobody, no metric that the recalculation would compute, an active run, or a recent
+ run. The query count does not grow with the number of candidates.
An exposure-frozen experiment stays eligible, because its metric events keep arriving.
"""
@@ -110,28 +141,156 @@ def find_scheduled_recalculation_candidates() -> ScheduledRecalculationDiscovery
# 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] = []
+ enabled_ids: list[int] = []
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]:
+ if enabled_teams[team_id]:
+ enabled_ids.append(experiment_id)
+
+ # Loaded only for enabled teams, so the metric definitions of every other team stay unread.
+ experiments = list(
+ Experiment.objects.filter(id__in=enabled_ids)
+ .select_related("feature_flag", "team__organization", "created_by")
+ .prefetch_related(
+ Prefetch(
+ "experimenttosavedmetric_set",
+ queryset=ExperimentToSavedMetric.objects.select_related("saved_metric"),
+ )
+ )
+ .order_by("id")
+ )
+ active_runs = _active_run_skips(enabled_ids)
+ recent_runs = _recent_run_skips(enabled_ids)
+
+ candidates: list[ScheduledRecalculationCandidate] = []
+ skips: list[DiscoverySkip] = []
+ for experiment in experiments:
+ try:
+ decision = _discovery_skip(experiment, active_runs=active_runs, recent_runs=recent_runs)
+ except Exception:
+ # One malformed flag or metric must not stop discovery for every team in this hour. The
+ # experiment stays a candidate, and the exposure gate decides.
+ logger.warning("scheduled_recalculation_skip_check_failed", experiment_id=experiment.id, exc_info=True)
+ decision = None
+ if decision is not None:
+ skips.append(DiscoverySkip(experiment=experiment, decision=decision))
continue
candidates.append(
ScheduledRecalculationCandidate(
- experiment_id=experiment_id, team_id=team_id, organization_id=str(organization_id)
+ experiment_id=experiment.id,
+ team_id=experiment.team_id,
+ organization_id=str(experiment.team.organization_id),
)
)
- logger.info("scheduled_recalculation_candidates", hour=hour, count=len(candidates))
- return ScheduledRecalculationDiscovery(hour=hour, candidates=candidates)
+ logger.info("scheduled_recalculation_candidates", hour=hour, count=len(candidates), skipped=len(skips))
+ return ScheduledRecalculationSelection(
+ discovery=ScheduledRecalculationDiscovery(hour=hour, candidates=candidates), skips=skips
+ )
-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 on a
- window of data that is itself recent.
+def _discovery_skip(
+ experiment: Experiment,
+ *,
+ active_runs: dict[int, SkipDecision],
+ recent_runs: dict[int, SkipDecision],
+) -> SkipDecision | None:
+ if not _flag_can_serve_anyone(experiment.feature_flag):
+ return SkipDecision(reason=SKIP_ZERO_ROLLOUT, detail={})
+ # The same rule the recalculation discovery applies, so a run started here never completes empty.
+ if not get_metrics_for_calculation(experiment):
+ return SkipDecision(reason=SKIP_NO_METRICS, detail={})
+ return active_runs.get(experiment.id) or recent_runs.get(experiment.id)
+
+
+def _flag_can_serve_anyone(flag: "FeatureFlag") -> bool:
+ """Whether a release condition has a rollout above 0%. A flag without one never exposes a user.
+
+ A flag in a config format other than version 1 stays eligible, and the exposure gate decides.
+ """
+ try:
+ conditions = flag.conditions
+ except ConfigFormatError:
+ return True
+ return any(condition_rollout_percentage(condition) > 0 for condition in conditions)
+
+
+def _active_run_skip(recalculation_id: str) -> SkipDecision:
+ return SkipDecision(reason=SKIP_ACTIVE_RUN, detail={"existing_recalculation_id": recalculation_id})
+
+
+def _recent_run_skip(recalculation_id: str, completed_at: datetime) -> SkipDecision:
+ minutes = int((timezone.now() - completed_at).total_seconds() // 60)
+ return SkipDecision(
+ reason=SKIP_RECENT_RUN,
+ detail={"latest_recalculation_id": recalculation_id, "minutes_since_completion": minutes},
+ )
+
+
+def _recent_recalculations(
+ queryset: QuerySet[ExperimentMetricsRecalculation],
+) -> QuerySet[ExperimentMetricsRecalculation]:
+ """Runs that finished inside the freshness window on a window of data that is itself recent.
`timeseries_sync` rows never count toward freshness: they carry a timeseries run's window, not a
full recalculation, and counting one would skip the experiment that needs the real run.
+ """
+ freshness_cutoff = timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATION
+ return (
+ queryset.filter(completed_at__isnull=False, completed_at__gte=freshness_cutoff)
+ # A reused window makes a run recent without making its data recent: `_resolve_query_to`
+ # keeps the previous `query_to` for metric_config_change, manual_retry and heal_latest_run,
+ # and the page heals itself on load, so this is a routine shape rather than a rare one. A
+ # null `query_to` still counts, because such a run resolved no window to judge.
+ .filter(Q(query_to__isnull=True) | Q(query_to__gte=freshness_cutoff))
+ .exclude(trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC)
+ )
+
+
+def _active_run_skips(experiment_ids: list[int]) -> dict[int, SkipDecision]:
+ """The newest active run of each experiment, in one query across teams."""
+ # 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 active_recalculation_filter # noqa: PLC0415
+
+ rows = (
+ # Unscoped because the experiments belong to many teams. The filter on the discovered ids
+ # keeps the read to those experiments' rows.
+ ExperimentMetricsRecalculation.objects.unscoped()
+ .filter(experiment_id__in=experiment_ids)
+ .filter(active_recalculation_filter())
+ .order_by("experiment_id", "-created_at")
+ .values_list("experiment_id", "id")
+ )
+ skips: dict[int, SkipDecision] = {}
+ for experiment_id, recalculation_id in rows:
+ skips.setdefault(experiment_id, _active_run_skip(str(recalculation_id)))
+ return skips
+
+
+def _recent_run_skips(experiment_ids: list[int]) -> dict[int, SkipDecision]:
+ """The latest recent run of each experiment, in one query across teams."""
+ rows = (
+ _recent_recalculations(
+ ExperimentMetricsRecalculation.objects.unscoped().filter(experiment_id__in=experiment_ids)
+ )
+ .order_by("experiment_id", "-completed_at")
+ .values_list("experiment_id", "id", "completed_at")
+ )
+ skips: dict[int, SkipDecision] = {}
+ for experiment_id, recalculation_id, completed_at in rows:
+ if completed_at is not None:
+ skips.setdefault(experiment_id, _recent_run_skip(str(recalculation_id), completed_at))
+ return skips
+
+
+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 on a
+ window of data that is itself recent (`_recent_recalculations`).
+
+ Discovery applies the same rules to the whole batch. This check catches a run that started
+ between discovery and the start of this experiment.
Scopes explicitly with `for_team`: the model is fail-closed and an activity carries no request
context, so an unscoped read would raise `TeamScopeError`.
@@ -148,30 +307,11 @@ def recent_recalculation_skip(experiment: Experiment, team_id: int) -> SkipDecis
active = get_active_recalculation(experiment)
if active is not None:
- return SkipDecision(reason=SKIP_ACTIVE_RUN, detail={"existing_recalculation_id": str(active.id)})
+ return _active_run_skip(str(active.id))
- freshness_cutoff = timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATION
- latest = (
- scoped.filter(
- experiment=experiment,
- completed_at__isnull=False,
- completed_at__gte=freshness_cutoff,
- )
- # A reused window makes a run recent without making its data recent: `_resolve_query_to`
- # keeps the previous `query_to` for metric_config_change, manual_retry and heal_latest_run,
- # and the page heals itself on load, so this is a routine shape rather than a rare one. A
- # null `query_to` still counts, because such a run resolved no window to judge.
- .filter(Q(query_to__isnull=True) | Q(query_to__gte=freshness_cutoff))
- .exclude(trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC)
- .order_by("-completed_at")
- .first()
- )
+ latest = _recent_recalculations(scoped.filter(experiment=experiment)).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 _recent_run_skip(str(latest.id), latest.completed_at)
return None
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py
index 643750a00e82..d47807c427d6 100644
--- a/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import timedelta
from uuid import uuid4
@@ -5,20 +6,36 @@ import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.models.scoping import team_scope
-from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation
+from products.experiments.backend.models.experiment import (
+ Experiment,
+ ExperimentMetricsRecalculation,
+ ExperimentSavedMetric,
+ ExperimentToSavedMetric,
+)
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.temporal.models import ScheduledRecalculationStartResult
from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ SKIPPED_EVENT,
_check_experiment_exposures_sync,
+ _discover_scheduled_recalculation_candidates_sync,
_start_scheduled_recalculation_sync,
)
from products.experiments.backend.temporal.scheduled_recalculation_logic import (
SKIP_ACTIVE_RUN,
SKIP_EXPOSURE_QUERY_FAILED,
SKIP_INSUFFICIENT_EXPOSURES,
+ SKIP_NO_METRICS,
+ SKIP_RECENT_RUN,
+ SKIP_ZERO_ROLLOUT,
+ ScheduledRecalculationDiscovery,
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -30,6 +47,7 @@ RECALCULATION = "products.experiments.backend.recalculation"
# 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]
+_discover_raw = _discover_scheduled_recalculation_candidates_sync.func # type: ignore[attr-defined]
def _check_exposures(experiment_id: int, hour: int) -> bool:
@@ -43,21 +61,108 @@ def _start_recalculation(experiment_id: int, hour: int) -> ScheduledRecalculatio
return _start_recalculation_raw(experiment_id, hour)
+def _discover() -> ScheduledRecalculationDiscovery:
+ with (
+ patch(f"{MODULE}.close_old_connections"),
+ patch(
+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",
+ return_value=True,
+ ),
+ ):
+ return _discover_raw()
+
+
+def _metric() -> dict:
+ return {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}
+
+
@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": []}
+ # Discovery selects the teams configured for the current hour, and the class clock is at 12:00.
+ TeamExperimentsConfig.objects.update_or_create(
+ team=self.team, defaults={"experiment_recalculation_times": ["12:00:00"]}
)
- self.experiment = Experiment.objects.create(
+ self.experiment = self._experiment()
+
+ def _experiment(self, **overrides: object) -> Experiment:
+ flag = FeatureFlag.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())}],
+ key=f"flag-{uuid4()}",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ defaults: dict = {
+ "team": self.team,
+ "name": "exp",
+ "feature_flag": flag,
+ "created_by": self.user,
+ "start_date": timezone.now() - timedelta(days=2),
+ "metrics": [_metric()],
+ }
+ return Experiment.objects.create(**{**defaults, **overrides})
+
+ def _add_run(self, experiment: Experiment, **fields: object) -> None:
+ with team_scope(self.team.id, canonical=True):
+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=experiment, **fields)
+
+ def _zero_rollout(self) -> Experiment:
+ experiment = self._experiment()
+ experiment.feature_flag.filters = {"groups": [{"properties": [], "rollout_percentage": 0}]}
+ experiment.feature_flag.save()
+ return experiment
+
+ def _active_run(self) -> Experiment:
+ experiment = self._experiment()
+ self._add_run(experiment, status=ExperimentMetricsRecalculation.Status.IN_PROGRESS, started_at=timezone.now())
+ return experiment
+
+ def _recent_run(self) -> Experiment:
+ experiment = self._experiment()
+ saved = ExperimentSavedMetric.objects.create(team=self.team, name="saved", query=_metric())
+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved)
+ self._add_run(
+ experiment,
+ status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ completed_at=timezone.now() - timedelta(minutes=5),
)
+ return experiment
+
+ @parameterized.expand(
+ [
+ ("zero_rollout", lambda test: test._zero_rollout(), SKIP_ZERO_ROLLOUT),
+ ("no_metrics", lambda test: test._experiment(metrics=[]), SKIP_NO_METRICS),
+ ("active_run", lambda test: test._active_run(), SKIP_ACTIVE_RUN),
+ ("recent_run", lambda test: test._recent_run(), SKIP_RECENT_RUN),
+ ]
+ )
+ def test_discovery_sends_a_skipped_event_instead_of_returning_the_experiment(
+ self, _name: str, arrange: Callable[["TestScheduledRecalculationActivities"], Experiment], reason: str
+ ):
+ skipped = arrange(self)
+ with patch(f"{MODULE}.posthoganalytics.capture") as capture:
+ discovery = _discover()
+ assert [c.experiment_id for c in discovery.candidates] == [self.experiment.id]
+ capture.assert_called_once()
+ assert capture.call_args.kwargs["event"] == SKIPPED_EVENT
+ assert capture.call_args.kwargs["properties"]["experiment_id"] == skipped.id
+ assert capture.call_args.kwargs["properties"]["reason"] == reason
+ assert capture.call_args.kwargs["properties"]["hour"] == 12
+
+ def test_discovery_query_count_does_not_grow_with_skips(self):
+ # Covers the skipped events too: each one reads the team, organization and creator.
+ def discovery_queries() -> int:
+ with patch(f"{MODULE}.posthoganalytics.capture"), CaptureQueriesContext(connection) as queries:
+ _discover()
+ return len(queries.captured_queries)
+
+ self._recent_run()
+ baseline = discovery_queries()
+ for _ in range(5):
+ self._recent_run()
+ self._zero_rollout()
+ assert discovery_queries() == baseline
def test_exposure_gate_passes_above_threshold(self):
with patch(f"{MODULE}.count_total_exposures", return_value=120):
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py
index 77564a952175..f1c57a1862d4 100644
--- a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py
@@ -21,6 +21,8 @@ from products.experiments.backend.models.experiment import (
Experiment,
ExperimentHoldout,
ExperimentMetricsRecalculation,
+ ExperimentSavedMetric,
+ ExperimentToSavedMetric,
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.temporal.scheduled_recalculation_logic import (
@@ -28,7 +30,9 @@ from products.experiments.backend.temporal.scheduled_recalculation_logic import
MIN_EXPERIMENT_AGE,
MIN_TIME_SINCE_LAST_RECALCULATION,
SKIP_ACTIVE_RUN,
+ SKIP_NO_METRICS,
SKIP_RECENT_RUN,
+ SKIP_ZERO_ROLLOUT,
count_total_exposures,
find_scheduled_recalculation_candidates,
recent_recalculation_skip,
@@ -41,14 +45,28 @@ def _metric() -> dict[str, Any]:
return {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}
+FULL_ROLLOUT_FILTERS: dict[str, Any] = {"groups": [{"properties": [], "rollout_percentage": 100}]}
+FLAG_PATH = "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false"
+
+
# 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:
+ def _experiment(
+ self,
+ *,
+ team: Team | None = None,
+ started_hours_ago: float = 48,
+ flag_filters: dict[str, Any] | None = None,
+ **overrides: Any,
+ ) -> Experiment:
team = team or self.team
flag = FeatureFlag.objects.create(
- team=team, key=f"flag-{uuid4()}", created_by=self.user, filters={"groups": []}
+ team=team,
+ key=f"flag-{uuid4()}",
+ created_by=self.user,
+ filters=FULL_ROLLOUT_FILTERS if flag_filters is None else flag_filters,
)
# No status here: save() always recomputes it from start_date and end_date.
defaults: dict[str, Any] = {
@@ -72,12 +90,22 @@ class TestScheduledRecalculationLogic(BaseTest):
)
with (
clock,
- patch(
- "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",
- return_value=True,
- ),
+ patch(FLAG_PATH, return_value=True),
):
- return {c.experiment_id for c in find_scheduled_recalculation_candidates().candidates}
+ return {c.experiment_id for c in find_scheduled_recalculation_candidates().discovery.candidates}
+
+ def _discovery_skip_reason(self, experiment: Experiment) -> str | None:
+ with patch(FLAG_PATH, return_value=True):
+ selection = find_scheduled_recalculation_candidates()
+ reasons = {skip.experiment.id: skip.decision.reason for skip in selection.skips}
+ candidate_ids = {c.experiment_id for c in selection.discovery.candidates}
+ assert (experiment.id in candidate_ids) is (experiment.id not in reasons)
+ return reasons.get(experiment.id)
+
+ def _assert_discovery_and_start_skip(self, experiment: Experiment, reason: str | None) -> None:
+ decision = recent_recalculation_skip(experiment, self.team.id)
+ assert (decision.reason if decision else None) == reason
+ assert self._discovery_skip_reason(experiment) == reason
def test_default_hour_picks_up_team_without_config(self):
experiment = self._experiment()
@@ -171,17 +199,52 @@ class TestScheduledRecalculationLogic(BaseTest):
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)
+ @parameterized.expand(
+ [
+ ("inline_metric", [_metric()], False, None),
+ ("no_metrics", [], False, SKIP_NO_METRICS),
+ # Legacy metrics carry no metric_type, so the recalculation computes none of them.
+ ("legacy_metric_only", [{"kind": "ExperimentTrendsQuery", "uuid": str(uuid4())}], False, SKIP_NO_METRICS),
+ ("saved_metric_only", [], True, None),
+ ]
+ )
+ def test_discovery_skips_an_experiment_with_no_computable_metric(
+ self, _name: str, metrics: list[dict[str, Any]], with_saved_metric: bool, expected_reason: str | None
+ ):
+ experiment = self._experiment(metrics=metrics)
+ if with_saved_metric:
+ saved = ExperimentSavedMetric.objects.create(team=self.team, name="saved", query=_metric())
+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved)
+ assert self._discovery_skip_reason(experiment) == expected_reason
+
+ @parameterized.expand(
+ [
+ ("zero_rollout", {"groups": [{"properties": [], "rollout_percentage": 0}]}, SKIP_ZERO_ROLLOUT),
+ # The flags service matches nobody when a v1 flag has no release condition.
+ ("no_conditions", {"groups": []}, SKIP_ZERO_ROLLOUT),
+ # An absent rollout means 100% to the flags service.
+ ("missing_rollout", {"groups": [{"properties": []}]}, None),
+ (
+ "one_condition_above_zero",
+ {"groups": [{"properties": [], "rollout_percentage": 0}, {"properties": [], "rollout_percentage": 5}]},
+ None,
+ ),
+ # The rule reads v1 keys only, so another format is left to the exposure gate.
+ ("config_v2", {"version": 2, "rules": []}, None),
+ # A malformed value fails open, so one flag cannot stop discovery for the whole hour.
+ ("string_rollout", {"groups": [{"properties": [], "rollout_percentage": "50"}]}, None),
+ ]
+ )
+ def test_discovery_skips_a_flag_that_serves_nobody(
+ self, _name: str, flag_filters: dict[str, Any], expected_reason: str | None
+ ):
+ experiment = self._experiment(flag_filters=flag_filters)
+ assert self._discovery_skip_reason(experiment) == expected_reason
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 == []
+ with patch(FLAG_PATH, return_value=False):
+ assert find_scheduled_recalculation_candidates().discovery.candidates == []
def test_flag_is_evaluated_once_per_team(self):
for _ in range(3):
@@ -219,9 +282,7 @@ class TestScheduledRecalculationLogic(BaseTest):
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
+ self._assert_discovery_and_start_skip(experiment, SKIP_ACTIVE_RUN)
@parameterized.expand(
[
@@ -238,7 +299,7 @@ class TestScheduledRecalculationLogic(BaseTest):
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
+ self._assert_discovery_and_start_skip(experiment, None)
@parameterized.expand(
[
@@ -269,6 +330,7 @@ class TestScheduledRecalculationLogic(BaseTest):
if decision is not None:
assert decision.reason == SKIP_RECENT_RUN
assert decision.detail["minutes_since_completion"] == 10
+ assert self._discovery_skip_reason(experiment) == (SKIP_RECENT_RUN if expected_skip else None)
def test_old_completed_run_does_not_skip(self):
experiment = self._experiment()
@@ -279,7 +341,7 @@ class TestScheduledRecalculationLogic(BaseTest):
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
+ self._assert_discovery_and_start_skip(experiment, 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
@@ -293,7 +355,7 @@ class TestScheduledRecalculationLogic(BaseTest):
trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,
completed_at=timezone.now() - timedelta(minutes=5),
)
- assert recent_recalculation_skip(experiment, self.team.id) is None
+ self._assert_discovery_and_start_skip(experiment, None)
def test_unfinished_failed_run_is_ignored(self):
experiment = self._experiment()
@@ -304,7 +366,7 @@ class TestScheduledRecalculationLogic(BaseTest):
status=ExperimentMetricsRecalculation.Status.FAILED,
completed_at=None,
)
- assert recent_recalculation_skip(experiment, self.team.id) is None
+ self._assert_discovery_and_start_skip(experiment, None)
def test_flag_helper_passes_group_properties(self):
with patch(
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py b/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py
index 0c89661be8f3..5b4fe6cc310d 100644
--- a/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_workflow.py
@@ -1,13 +1,24 @@
import uuid
+from datetime import timedelta
import pytest
+import time_machine
+from posthog.test.base import NonAtomicBaseTest
+from unittest.mock import patch
+from django.utils import timezone
+
+from asgiref.sync import async_to_sync
from temporalio import activity
from temporalio.client import WorkflowFailureError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.temporal.models import ScheduledRecalculationStartResult
+from products.experiments.backend.temporal.scheduled_recalculation_activities import (
+ discover_scheduled_recalculation_candidates,
+)
from products.experiments.backend.temporal.scheduled_recalculation_logic import (
ScheduledRecalculationCandidate,
ScheduledRecalculationDiscovery,
@@ -15,8 +26,7 @@ from products.experiments.backend.temporal.scheduled_recalculation_logic import
from products.experiments.backend.temporal.scheduled_recalculation_workflow import (
ScheduledExperimentRecalculationWorkflow,
)
-
-pytestmark = pytest.mark.asyncio
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
def _candidates(*experiment_ids: int) -> list[ScheduledRecalculationCandidate]:
@@ -30,6 +40,10 @@ async def _run(discover, exposures, start, hour: int = 2) -> dict:
async def discover_activity() -> ScheduledRecalculationDiscovery:
return ScheduledRecalculationDiscovery(hour=hour, candidates=discover(hour))
+ return await _execute(discover_activity, exposures, start)
+
+
+async def _execute(discover_activity, exposures, start) -> dict:
@activity.defn(name="check_experiment_exposures")
async def exposures_activity(experiment_id: int, hour: int) -> bool:
return exposures(experiment_id)
@@ -54,11 +68,13 @@ async def _run(discover, exposures, start, hour: int = 2) -> dict:
)
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] = []
@@ -75,6 +91,7 @@ async def test_every_candidate_starts():
assert sorted(started) == [1, 2, 3]
async def test_exposure_gate_stops_the_start_activity():
started: list[int] = []
@@ -88,6 +105,7 @@ async def test_exposure_gate_stops_the_start_activity():
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:
@@ -103,9 +121,50 @@ async def test_one_failing_candidate_does_not_stop_the_others():
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)
+
+
+# Non-atomic, because the real discovery activity reads from a worker thread that cannot see
+# an uncommitted test transaction.
+@time_machine.travel("2026-09-15T02:30:00Z", tick=True)
+class TestScheduledRecalculationWorkflowDiscovery(NonAtomicBaseTest):
+ def _experiment(self, rollout_percentage: int) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key=f"flag-{uuid.uuid4()}",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": rollout_percentage}]},
+ )
+ return Experiment.objects.create(
+ team=self.team,
+ name="exp",
+ feature_flag=flag,
+ start_date=timezone.now() - timedelta(days=2),
+ metrics=[{"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid.uuid4())}],
+ )
+
+ def test_a_skipped_experiment_never_reaches_the_exposure_check(self):
+ candidate = self._experiment(rollout_percentage=100)
+ self._experiment(rollout_percentage=0)
+ checked: list[int] = []
+
+ def exposures(experiment_id: int) -> bool:
+ checked.append(experiment_id)
+ return False
+
+ with (
+ patch(
+ "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false",
+ return_value=True,
+ ),
+ patch("products.experiments.backend.temporal.scheduled_recalculation_activities.posthoganalytics"),
+ ):
+ result = async_to_sync(_execute)(discover_scheduled_recalculation_candidates, exposures, lambda eid: None)
+ assert checked == [candidate.id]
+ assert result["candidates"] == 1