: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): read recalculation hours from the times list (#107570)
Juraj Majerikee3b04153d8a
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.mdindex e16c53ceae8c..d0d69033aa8a 100644--- a/posthog/temporal/experiments/README.md+++ b/posthog/temporal/experiments/README.md@@ -1,10 +1,10 @@# Experiment metrics calculation-This module calculates experiment metrics in the background using Temporal, a workflow orchestration system. It runs daily for each active experiment, computing statistical results and storing them for timeseries retrieval.+This module calculates experiment metrics in the background using Temporal, a workflow orchestration system. It runs on each team's schedule (once or twice per day) for each active experiment, computing statistical results and storing them for timeseries retrieval.## How it works-Each team can configure when their experiments should be recalculated (default: 2 AM UTC). The system runs 24 schedules - one for each hour of the day. When a schedule fires, it finds all experiments belonging to teams configured for that hour and calculates their metrics.+Each team can configure one or two times of day when their experiments are recalculated, at least six hours apart (default: once at 02:00 UTC), via `TeamExperimentsConfig.experiment_recalculation_times`. The system runs 24 schedules - one for each hour of the day. When a schedule fires, it finds all experiments belonging to teams configured for that hour and calculates their metrics. A team with two configured times matches two schedules, so its experiments get two independent runs a day, each publishing its own recalculation.```text┌─────────────────────────────────────────────────────────────────────────┐@@ -42,9 +42,9 @@ The experiment page reads results through `GET /metrics_recalculation/latest`, w- A metric qualifies when its newest completed row under the config fingerprint has a `query_to` between the workflow start and now. Yesterday's row for a metric that failed today does not qualify, and neither does a future-dated day-end row from the backfill workflow.- The activity creates a completed recalculation with trigger `timeseries_sync` and copies each qualifying row under the recalc fingerprint at one shared `query_to`, one second past the newest point. Copies at a point's own `query_to` would share the `(experiment, metric_uuid, query_to)` key with the timeseries row and rewrite its fingerprint.-- A supported metric without a qualifying point is counted in `total_metrics` but gets no copy, so the frontend sees the gap and heals it with a real run. Every buildable metric type (`DAILY_TIMESERIES_METRIC_TYPES` in `metric_resolution.py`) is computed daily; legacy metrics without a `metric_type` are left out of `total_metrics` and `metric_uuids` entirely.-- The row belongs to the experiment's daily run, not to one workflow. The inline and saved metric workflows both run the activity for the same experiment in the same hour, each with its own run start. The first pass creates the row; a later pass finds the day's `timeseries_sync` row and adds the copies it still lacks, so the row covers every metric the daily run computed whichever workflow finishes last.-- When no sync row exists for the day, the activity skips if any other recalculation, finished or executing, already has a `query_to` at or past the oldest qualifying point.+- A supported metric without a qualifying point is counted in `total_metrics` but gets no copy, so the frontend sees the gap and heals it with a real run. Every buildable metric type (`DAILY_TIMESERIES_METRIC_TYPES` in `metric_resolution.py`) is computed on every scheduled run; legacy metrics without a `metric_type` are left out of `total_metrics` and `metric_uuids` entirely.+- The row belongs to one scheduled run of the experiment, not to one workflow. The inline and saved metric workflows both run the activity for the same experiment in the same hour, each with its own run start. The first pass creates the row; a later pass in the same hour finds that run's `timeseries_sync` row and adds the copies it still lacks, so the row covers every metric the run computed whichever workflow finishes last. The lookup is scoped to the run's start, so a team's second run of the day creates its own row instead of touching the earlier one.+- When no sync row exists for the run, the activity skips if any other recalculation, finished or executing, already has a `query_to` at or past the oldest qualifying point.Each metric stamps its own `query_to` at the moment its activity runs, so the points of one run are seconds to minutes apart. The copies present them as one window; that approximation is deliberate.diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.pyindex f1c8f077096a..1d16fdcf414f 100644--- a/posthog/temporal/experiments/activities.py+++ b/posthog/temporal/experiments/activities.py@@ -30,7 +30,7 @@ from posthog.temporal.experiments.models import (ExperimentSavedMetricInput,ExperimentSavedMetricResult,)-from posthog.temporal.experiments.utils import DEFAULT_EXPERIMENT_RECALCULATION_HOUR, check_significance_transition+from posthog.temporal.experiments.utils import check_significance_transition, recalculation_hour_filterfrom products.experiments.backend.facade.timeseries import (backfill_experiment_timeseries,@@ -75,19 +75,8 @@ def _get_experiment_regular_metrics_for_hour_sync(hour: int) -> list[ExperimentRexperiment_metrics: list[ExperimentRegularMetricInput] = []- # Build time filter - teams with NULL recalculation_time default to hour 2 (02:00 UTC)- # The filter traverses Experiment -> Team -> TeamExperimentsConfig via Django's reverse relation- if hour == DEFAULT_EXPERIMENT_RECALCULATION_HOUR:- time_filter = (- Q(team__teamexperimentsconfig__experiment_recalculation_time__hour=hour)- | Q(team__teamexperimentsconfig__experiment_recalculation_time__isnull=True)- | Q(team__teamexperimentsconfig__isnull=True)- )- else:- time_filter = Q(team__teamexperimentsconfig__experiment_recalculation_time__hour=hour)-experiments = Experiment.objects.filter(- time_filter,+ recalculation_hour_filter(hour),deleted=False,status=Experiment.Status.RUNNING,start_date__gte=datetime.now(ZoneInfo("UTC")) - timedelta(days=EXPERIMENT_RECALCULATION_MAX_AGE_DAYS),@@ -389,17 +378,8 @@ def _get_experiment_saved_metrics_for_hour_sync(hour: int) -> list[ExperimentSavexperiment_metrics: list[ExperimentSavedMetricInput] = []- if hour == DEFAULT_EXPERIMENT_RECALCULATION_HOUR:- time_filter = (- Q(team__teamexperimentsconfig__experiment_recalculation_time__hour=hour)- | Q(team__teamexperimentsconfig__experiment_recalculation_time__isnull=True)- | Q(team__teamexperimentsconfig__isnull=True)- )- else:- time_filter = Q(team__teamexperimentsconfig__experiment_recalculation_time__hour=hour)-experiments = Experiment.objects.filter(- time_filter,+ recalculation_hour_filter(hour),deleted=False,status=Experiment.Status.RUNNING,start_date__gte=datetime.now(ZoneInfo("UTC")) - timedelta(days=EXPERIMENT_RECALCULATION_MAX_AGE_DAYS),diff --git a/posthog/temporal/experiments/test_recalculation_time_filter.py b/posthog/temporal/experiments/test_recalculation_time_filter.pyindex 9e6a6f72a304..fb464417239b 100644--- a/posthog/temporal/experiments/test_recalculation_time_filter.py+++ b/posthog/temporal/experiments/test_recalculation_time_filter.py@@ -7,9 +7,12 @@ from unittest.mock import patchfrom posthog.models import Organization, Team, Userfrom posthog.models.team.extensions import get_or_create_team_extension-from posthog.temporal.experiments.activities import _get_experiment_regular_metrics_for_hour_sync+from posthog.temporal.experiments.activities import (+ _get_experiment_regular_metrics_for_hour_sync,+ _get_experiment_saved_metrics_for_hour_sync,+)-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -27,8 +30,9 @@ def _create_running_experiment(team, user, flag_key, metrics=None):)-# Access the underlying sync function, patching out close_old_connections which kills the test DB connection+# Access the underlying sync functions, patching out close_old_connections which kills the test DB connection_raw_sync = _get_experiment_regular_metrics_for_hour_sync.func # type: ignore[attr-defined]+_raw_saved_sync = _get_experiment_saved_metrics_for_hour_sync.func # type: ignore[attr-defined]def _get_metrics_sync(hour):@@ -36,6 +40,11 @@ def _get_metrics_sync(hour):return _raw_sync(hour)+def _get_saved_metrics_sync(hour):+ with patch("posthog.temporal.experiments.activities.close_old_connections"):+ return _raw_saved_sync(hour)++@pytest.mark.django_dbclass TestRecalculationTimeFilter:def test_team_with_custom_hour_matched_at_that_hour(self):@@ -45,6 +54,7 @@ class TestRecalculationTimeFilter:config = get_or_create_team_extension(team, TeamExperimentsConfig)config.experiment_recalculation_time = time(5, 0, 0)+ config.experiment_recalculation_times = ["05:00:00"]config.save()_create_running_experiment(team, user, "custom-hour")@@ -58,6 +68,47 @@ class TestRecalculationTimeFilter:assert team.experiment_set.first().id in experiment_ids_hour_5assert team.experiment_set.first().id not in experiment_ids_hour_2+ def test_team_with_two_recalculation_times_matched_at_both_hours(self):+ org = Organization.objects.create(name="Test Org Two Times")+ team = Team.objects.create(organization=org, name="Team Two Times")+ user = User.objects.create(email="[email protected]")++ config = get_or_create_team_extension(team, TeamExperimentsConfig)+ config.experiment_recalculation_time = time(8, 0, 0)+ config.experiment_recalculation_times = ["08:00:00", "20:00:00"]+ config.save()++ _create_running_experiment(team, user, "two-times")++ experiment_id = team.experiment_set.first().id+ assert experiment_id in {r.experiment_id for r in _get_metrics_sync(hour=8)}+ assert experiment_id in {r.experiment_id for r in _get_metrics_sync(hour=20)}+ assert experiment_id not in {r.experiment_id for r in _get_metrics_sync(hour=2)}+ assert experiment_id not in {r.experiment_id for r in _get_metrics_sync(hour=14)}++ def test_saved_metrics_follow_two_recalculation_times(self):+ org = Organization.objects.create(name="Test Org Saved")+ team = Team.objects.create(organization=org, name="Team Saved Two Times")+ user = User.objects.create(email="[email protected]")++ config = get_or_create_team_extension(team, TeamExperimentsConfig)+ config.experiment_recalculation_time = time(8, 0, 0)+ config.experiment_recalculation_times = ["08:00:00", "20:00:00"]+ config.save()++ experiment = _create_running_experiment(team, user, "saved-two-times")+ saved_metric = ExperimentSavedMetric.objects.create(+ team=team,+ name="Saved metric",+ query={"metric_type": "mean", "uuid": "saved-uuid-1", "source": {"kind": "EventsNode", "event": "test"}},+ created_by=user,+ )+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved_metric)++ assert experiment.id in {r.experiment_id for r in _get_saved_metrics_sync(hour=8)}+ assert experiment.id in {r.experiment_id for r in _get_saved_metrics_sync(hour=20)}+ assert experiment.id not in {r.experiment_id for r in _get_saved_metrics_sync(hour=2)}+def test_team_with_no_config_row_defaults_to_hour_2(self):org = Organization.objects.create(name="Test Org 2")team = Team.objects.create(organization=org, name="Team No Config")diff --git a/posthog/temporal/experiments/utils.py b/posthog/temporal/experiments/utils.pyindex ec379421a8d6..7564b30ae710 100644--- a/posthog/temporal/experiments/utils.py+++ b/posthog/temporal/experiments/utils.py@@ -1,6 +1,8 @@from datetime import datetimefrom typing import Union+from django.db.models import Q+import structlogfrom posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentRatioMetric@@ -18,6 +20,25 @@ logger = structlog.get_logger(__name__)DEFAULT_EXPERIMENT_RECALCULATION_HOUR = 2 # 02:00 UTC+def recalculation_hour_filter(hour: int) -> Q:+ """Experiments whose team recalculates at this UTC hour.++ The filter traverses Experiment -> Team -> TeamExperimentsConfig via Django's reverse+ relation. experiment_recalculation_times holds "HH:00:00" strings, so hour membership+ is a jsonb containment check. A null list or a missing config row means the default+ hour; the deprecated experiment_recalculation_time column is not consulted, because+ the API keeps the list in sync with it on every write.+ """+ match = Q(team__teamexperimentsconfig__experiment_recalculation_times__contains=[f"{hour:02d}:00:00"])+ if hour == DEFAULT_EXPERIMENT_RECALCULATION_HOUR:+ return (+ match+ | Q(team__teamexperimentsconfig__experiment_recalculation_times__isnull=True)+ | Q(team__teamexperimentsconfig__isnull=True)+ )+ return match++def get_metric(metric_data: dict) -> Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric]:metric_type = metric_data.get("metric_type")if metric_type == "mean":diff --git a/products/experiments/backend/timeseries_sync.py b/products/experiments/backend/timeseries_sync.pyindex 23a4730ac24f..c3b9ea85ec2b 100644--- a/products/experiments/backend/timeseries_sync.py+++ b/products/experiments/backend/timeseries_sync.py@@ -1,13 +1,14 @@-"""Assemble a completed metrics recalculation from the timeseries points of one daily run.+"""Assemble a completed metrics recalculation from the timeseries points of one scheduled run.-The daily timeseries workflows stamp each metric's query_to at the moment its own activity runs, so the points of one-run land seconds to minutes apart and never share an exact window. This module accepts that approximation: every+The scheduled timeseries workflows stamp each metric's query_to at the moment its own activity runs, so the points of+one run land seconds to minutes apart and never share an exact window. This module accepts that approximation: everymetric whose newest completed point falls inside the run qualifies, and the copies land under one shared query_to sothe recalculation reads (`get_run_results`, derived counters, the metric-config-change window reuse) work unchanged.Two workflows (inline metrics, saved metrics) run per hour and each calls this for the same experiment with its own-run start. The row belongs to the experiment's daily run, not to one workflow: the first pass creates it, and a later-pass adds the copies the row still lacks.+run start. The row belongs to one scheduled run of the experiment, not to one workflow: the first pass creates it,+and a later pass in the same hour adds the copies the row still lacks. The lookup is scoped to the run's start, so a+team with a second recalculation time later in the day gets a fresh row for that run."""from datetime import datetime, timedelta@@ -45,12 +46,12 @@ _SAME_RUN_LOOKBACK = timedelta(hours=1)def sync_timeseries_recalculation(experiment_id: int, *, team_id: int, run_started_at: datetime, now: datetime | None = None) -> str | None:- """Copy the timeseries points written between run_started_at and now into this daily run's recalculation.+ """Copy the timeseries points written between run_started_at and now into this run's recalculation.Returns the recalculation id when a row was created or gained copies, else None: no metric has a point- inside the run, the day's sync row already holds every point, or another run's window already reaches the+ inside the run, the run's sync row already holds every point, or another run's window already reaches theoldest qualifying point. A supported metric without a point is counted in total_metrics but gets no copy, so- the frontend sees the gap and heals it. Metric types the daily run cannot compute are left out of the row.+ the frontend sees the gap and heals it. Metric types the scheduled run cannot compute are left out of the row."""now = now or timezone.now()with team_scope(team_id, canonical=True), transaction.atomic():