: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): back off the scheduled exposure check after repeated low counts (#118175)
Rodrigo Ilorod4e01f27d61b
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.mdindex e6c43ed88732..59e12fc40357 100644--- a/posthog/temporal/experiments/README.md+++ b/posthog/temporal/experiments/README.md@@ -109,7 +109,13 @@ 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.+- it has no metric that the recalculation computes, inline or saved,+- its last 3 exposure checks in a row found fewer than 50 exposures, and the last one ran less than 7 days ago.++The exposure back-off keeps its state in Redis, one key per experiment (`experiments:exposure_backoff:v1:<experiment_id>`) with a 14-day TTL renewed on every write.+Each exposure check below 50 adds 1 to the count, a check at 50 or more deletes the key, and a failed exposure query leaves it unchanged.+Discovery reads every key in one `MGET`.+A Redis error or an unreadable key never skips an experiment: the exposure gate decides as it would without the back-off.The freshness check ignores `timeseries_sync` rows, which carry a timeseries run's window ratherthan a full recalculation. Discovery reads these with a fixed number of queries for the whole hour,diff --git a/products/experiments/backend/temporal/scheduled_recalculation_activities.py b/products/experiments/backend/temporal/scheduled_recalculation_activities.pyindex f0e987b27c0a..e45d7d6bc9b6 100644--- a/products/experiments/backend/temporal/scheduled_recalculation_activities.py+++ b/products/experiments/backend/temporal/scheduled_recalculation_activities.py@@ -27,6 +27,7 @@ from products.experiments.backend.temporal.scheduled_recalculation_logic importcount_total_exposures,find_scheduled_recalculation_candidates,recent_recalculation_skip,+ record_exposure_check,)logger = structlog.get_logger(__name__)@@ -97,6 +98,7 @@ def _check_experiment_exposures_sync(experiment_id: int, hour: int) -> bool: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+ record_exposure_check(experiment.id, total)if total < MIN_TOTAL_EXPOSURES:capture_skip(experiment, hour, reason=SKIP_INSUFFICIENT_EXPOSURES, detail={"total_exposures": total})return Falsediff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.pyindex 8fc07f51f66d..4533f81e2490 100644--- a/products/experiments/backend/temporal/scheduled_recalculation_logic.py+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py@@ -4,7 +4,8 @@ Pure synchronous functions, no Temporal imports, so every rule is testable on itworkflow's activities in `scheduled_recalculation_activities` are thin wrappers over these."""-from datetime import datetime, timedelta+import json+from datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Finalfrom django.db.models import Prefetch, Q, QuerySet@@ -14,6 +15,7 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.ph_client import feature_enabled_or_false+from posthog.redis import get_clientfrom products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEYfrom products.experiments.backend.metric_resolution import get_metrics_for_calculation@@ -41,6 +43,15 @@ MIN_EXPERIMENT_AGE = timedelta(hours=12)MIN_TOTAL_EXPOSURES = 50+# After this many consecutive checks below MIN_TOTAL_EXPOSURES, the exposure query runs only once+# per EXPOSURE_BACKOFF_INTERVAL. Without it, an experiment that stays below the floor costs one+# ClickHouse query at every scheduled hour of its team.+EXPOSURE_BACKOFF_MIN_CONSECUTIVE_CHECKS = 3+EXPOSURE_BACKOFF_INTERVAL = timedelta(days=7)+# Longer than the interval, so the count survives until the next check renews it.+EXPOSURE_BACKOFF_TTL = timedelta(days=14)+EXPOSURE_BACKOFF_KEY_PREFIX = "experiments:exposure_backoff:v1"+# A run finished inside this window already left fresh enough data on the page.MIN_TIME_SINCE_LAST_RECALCULATION = timedelta(hours=1)@@ -50,6 +61,7 @@ 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"+SKIP_EXPOSURE_BACKOFF: Final = "exposure_backoff"@frozen@@ -73,6 +85,12 @@ class SkipDecision:detail: dict[str, str | int | float | None]+@frozen+class ExposureBackoffState:+ consecutive_insufficient_checks: int+ checked_at: datetime++@frozenclass DiscoverySkip:experiment: Experiment@@ -109,8 +127,8 @@ def find_scheduled_recalculation_candidates() -> ScheduledRecalculationSelectionevery team. An activity may read a clock; a workflow body may not.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.+ can serve nobody, no metric that the recalculation would compute, an active run, a recent run,+ or an exposure back-off. The query count does not grow with the number of candidates.An exposure-frozen experiment stays eligible, because its metric events keep arriving."""@@ -162,12 +180,15 @@ def find_scheduled_recalculation_candidates() -> ScheduledRecalculationSelection)active_runs = _active_run_skips(enabled_ids)recent_runs = _recent_run_skips(enabled_ids)+ exposure_backoffs = _exposure_backoff_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)+ decision = _discovery_skip(+ experiment, active_runs=active_runs, recent_runs=recent_runs, exposure_backoffs=exposure_backoffs+ )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.@@ -195,13 +216,14 @@ def _discovery_skip(*,active_runs: dict[int, SkipDecision],recent_runs: dict[int, SkipDecision],+ exposure_backoffs: 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)+ return active_runs.get(experiment.id) or recent_runs.get(experiment.id) or exposure_backoffs.get(experiment.id)def _flag_can_serve_anyone(flag: "FeatureFlag") -> bool:@@ -285,6 +307,79 @@ def _recent_run_skips(experiment_ids: list[int]) -> dict[int, SkipDecision]:return skips+def _exposure_backoff_key(experiment_id: int) -> str:+ return f"{EXPOSURE_BACKOFF_KEY_PREFIX}:{experiment_id}"+++def _parse_exposure_backoff_state(raw: bytes | str | None) -> ExposureBackoffState | None:+ if raw is None:+ return None+ try:+ data = json.loads(raw)+ return ExposureBackoffState(+ consecutive_insufficient_checks=int(data["count"]),+ checked_at=datetime.fromtimestamp(float(data["checked_at"]), tz=UTC),+ )+ # OverflowError and OSError come from a timestamp outside the range that datetime accepts.+ except (ValueError, TypeError, KeyError, OverflowError, OSError):+ return None+++def _exposure_backoff_skips(experiment_ids: list[int]) -> dict[int, SkipDecision]:+ """The experiments in an exposure back-off, read in one MGET across teams.++ Fails open: a Redis error or an unreadable value leaves the experiment a candidate, so the+ exposure gate decides as it would without the back-off.+ """+ if not experiment_ids:+ return {}+ try:+ values = get_client().mget([_exposure_backoff_key(experiment_id) for experiment_id in experiment_ids])+ except Exception:+ logger.warning("scheduled_recalculation_exposure_backoff_read_failed", exc_info=True)+ return {}++ now = timezone.now()+ skips: dict[int, SkipDecision] = {}+ for experiment_id, raw in zip(experiment_ids, values, strict=True):+ state = _parse_exposure_backoff_state(raw)+ if state is None or state.consecutive_insufficient_checks < EXPOSURE_BACKOFF_MIN_CONSECUTIVE_CHECKS:+ continue+ since_last_check = now - state.checked_at+ if since_last_check >= EXPOSURE_BACKOFF_INTERVAL:+ continue+ skips[experiment_id] = SkipDecision(+ reason=SKIP_EXPOSURE_BACKOFF,+ detail={+ "consecutive_insufficient_checks": state.consecutive_insufficient_checks,+ "days_since_last_check": round(since_last_check / timedelta(days=1), 1),+ },+ )+ return skips+++def record_exposure_check(experiment_id: int, total_exposures: int) -> None:+ """Count one more consecutive check below MIN_TOTAL_EXPOSURES, or clear the count at or above it.++ Every write renews the TTL. A Redis error only logs: losing a count costs at most a few extra+ exposure queries, while a raised error would skip the experiment.+ """+ key = _exposure_backoff_key(experiment_id)+ try:+ client = get_client()+ if total_exposures >= MIN_TOTAL_EXPOSURES:+ client.delete(key)+ return+ previous = _parse_exposure_backoff_state(client.get(key))+ count = (previous.consecutive_insufficient_checks if previous else 0) + 1+ value = json.dumps({"count": count, "checked_at": timezone.now().timestamp()})+ client.set(key, value, ex=EXPOSURE_BACKOFF_TTL)+ except Exception:+ logger.warning(+ "scheduled_recalculation_exposure_backoff_write_failed", experiment_id=experiment_id, exc_info=True+ )++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 awindow of data that is itself recent (`_recent_recalculations`).diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.pyindex d47807c427d6..8755e6bcd7a6 100644--- a/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_activities.py@@ -30,6 +30,7 @@ from products.experiments.backend.temporal.scheduled_recalculation_activities im)from products.experiments.backend.temporal.scheduled_recalculation_logic import (SKIP_ACTIVE_RUN,+ SKIP_EXPOSURE_BACKOFF,SKIP_EXPOSURE_QUERY_FAILED,SKIP_INSUFFICIENT_EXPOSURES,SKIP_NO_METRICS,@@ -181,6 +182,49 @@ class TestScheduledRecalculationActivities(BaseTest):assert _check_exposures(self.experiment.id, 2) is Falseassert capture.call_args.kwargs["reason"] == SKIP_EXPOSURE_QUERY_FAILED+ @parameterized.expand(+ [+ ("three_insufficient", [0, 12, 49], 3),+ ("two_insufficient", [0, 0], None),+ ("reset_at_threshold", [0, 0, 50, 0], None),+ ("failed_query_keeps_the_count", [0, 0, RuntimeError("clickhouse is sad"), 0], 3),+ ("failed_query_adds_nothing", [0, 0, RuntimeError("clickhouse is sad")], None),+ ]+ )+ def test_consecutive_insufficient_checks_back_off_the_experiment(+ self, _name: str, outcomes: list[int | Exception], backed_off_count: int | None+ ):+ for outcome in outcomes:+ with (+ patch(f"{MODULE}.count_total_exposures", side_effect=[outcome]),+ patch(f"{MODULE}.posthoganalytics.capture"),+ ):+ _check_exposures(self.experiment.id, 12)+ with patch(f"{MODULE}.posthoganalytics.capture") as capture:+ discovery = _discover()+ if backed_off_count is None:+ assert [c.experiment_id for c in discovery.candidates] == [self.experiment.id]+ capture.assert_not_called()+ return+ assert discovery.candidates == []+ properties = capture.call_args.kwargs["properties"]+ assert capture.call_args.kwargs["event"] == SKIPPED_EVENT+ assert properties["reason"] == SKIP_EXPOSURE_BACKOFF+ assert properties["consecutive_insufficient_checks"] == backed_off_count+ assert properties["days_since_last_check"] == 0++ @parameterized.expand([("enough", 120, True), ("insufficient", 12, False)])+ def test_exposure_gate_ignores_a_redis_failure(self, _name: str, total: int, expected: bool):+ with (+ patch(f"{MODULE}.count_total_exposures", return_value=total),+ patch(f"{MODULE}.capture_skip"),+ patch(+ "products.experiments.backend.temporal.scheduled_recalculation_logic.get_client",+ side_effect=ConnectionError("redis down"),+ ),+ ):+ assert _check_exposures(self.experiment.id, 12) is expected+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)diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.pyindex f1c57a1862d4..b5f5997efd61 100644--- a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py@@ -1,4 +1,5 @@import contextlib+from collections.abc import Callablefrom datetime import timedeltafrom types import SimpleNamespacefrom typing import Any@@ -14,6 +15,7 @@ from parameterized import parameterizedfrom posthog.models.scoping import team_scopefrom posthog.models.team import Team+from posthog.redis import get_clientfrom products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEYfrom products.experiments.backend.models.experiment import (@@ -27,15 +29,20 @@ from products.experiments.backend.models.experiment import (from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.experiments.backend.temporal.scheduled_recalculation_logic import (EXPERIMENT_RECALCULATION_MAX_AGE_DAYS,+ EXPOSURE_BACKOFF_INTERVAL,+ EXPOSURE_BACKOFF_KEY_PREFIX,+ EXPOSURE_BACKOFF_MIN_CONSECUTIVE_CHECKS,MIN_EXPERIMENT_AGE,MIN_TIME_SINCE_LAST_RECALCULATION,SKIP_ACTIVE_RUN,+ SKIP_EXPOSURE_BACKOFF,SKIP_NO_METRICS,SKIP_RECENT_RUN,SKIP_ZERO_ROLLOUT,count_total_exposures,find_scheduled_recalculation_candidates,recent_recalculation_skip,+ record_exposure_check,team_has_scheduled_recalculation_enabled,)from products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -46,7 +53,27 @@ def _metric() -> dict[str, Any]:FULL_ROLLOUT_FILTERS: dict[str, Any] = {"groups": [{"properties": [], "rollout_percentage": 100}]}-FLAG_PATH = "products.experiments.backend.temporal.scheduled_recalculation_logic.feature_enabled_or_false"+LOGIC = "products.experiments.backend.temporal.scheduled_recalculation_logic"+FLAG_PATH = f"{LOGIC}.feature_enabled_or_false"+++def _redis_down(key: str) -> contextlib.AbstractContextManager[object]:+ return patch(f"{LOGIC}.get_client", side_effect=ConnectionError("redis down"))+++def _unreadable_value(key: str) -> contextlib.AbstractContextManager[object]:+ get_client().set(key, "not json")+ return contextlib.nullcontext()+++def _timestamp_out_of_range(key: str) -> contextlib.AbstractContextManager[object]:+ get_client().set(key, '{"count": 3, "checked_at": 1e300}')+ return contextlib.nullcontext()+++def _missing_key(key: str) -> contextlib.AbstractContextManager[object]:+ get_client().delete(key)+ return contextlib.nullcontext()# Pinned at the default recalculation hour: a team with no config falls to hour 2, so a@@ -413,3 +440,46 @@ class TestScheduledRecalculationLogic(BaseTest):) as runner_class:assert count_total_exposures(experiment) == 20assert runner_class.call_args.kwargs["query"].holdout.id == holdout.id++ def _back_off(self, experiment: Experiment) -> None:+ for _ in range(EXPOSURE_BACKOFF_MIN_CONSECUTIVE_CHECKS):+ record_exposure_check(experiment.id, 0)++ @parameterized.expand(+ [+ # Travel in whole days, so discovery still runs at the class hour.+ ("inside_the_interval", EXPOSURE_BACKOFF_INTERVAL - timedelta(days=1), SKIP_EXPOSURE_BACKOFF),+ ("after_the_interval", EXPOSURE_BACKOFF_INTERVAL, None),+ ]+ )+ def test_exposure_backoff_holds_for_the_interval(self, _name: str, elapsed: timedelta, reason: str | None):+ experiment = self._experiment()+ self._back_off(experiment)+ with time_machine.travel(timezone.now() + elapsed, tick=False):+ assert self._discovery_skip_reason(experiment) == reason++ @parameterized.expand(+ [+ ("redis_error", _redis_down),+ ("unreadable_value", _unreadable_value),+ ("timestamp_out_of_range", _timestamp_out_of_range),+ ("missing_key", _missing_key),+ ]+ )+ def test_exposure_backoff_fails_open(+ self, _name: str, arrange: Callable[[str], contextlib.AbstractContextManager[object]]+ ):+ experiment = self._experiment()+ self._back_off(experiment)+ with arrange(f"{EXPOSURE_BACKOFF_KEY_PREFIX}:{experiment.id}"):+ assert self._discovery_skip_reason(experiment) is None++ def test_exposure_backoff_reads_every_candidate_in_one_round_trip(self):+ experiments = [self._experiment() for _ in range(3)]+ self._back_off(experiments[0])+ client = get_client()+ with patch.object(client, "mget", wraps=client.mget) as mget, patch.object(client, "get") as get:+ assert self._discovery_skip_reason(experiments[0]) == SKIP_EXPOSURE_BACKOFF+ mget.assert_called_once()+ assert len(mget.call_args.args[0]) == len(experiments)+ get.assert_not_called()