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): schedule experiment recalculations hourly (#108101)

Rodrigo Iloroe0be0acc359e
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.md
index fa660a9fead5..0c58bb4024c5 100644
--- a/posthog/temporal/experiments/README.md
+++ b/posthog/temporal/experiments/README.md
@@ -88,6 +88,35 @@ The `ExperimentSavedMetricsWorkflow` follows the same structure but:
- Uses `calculate_experiment_saved_metric` to process each saved metric
- Does not filter on empty `metrics`/`metrics_secondary` arrays (saved metrics are separate)
+### Scheduled recalculations
+
+The timeseries sync row is assembled from that day's points, so its window is approximate and a
+metric the daily run could not compute has no row at all. A separate workflow therefore starts a
+real recalculation for each eligible experiment, on one hourly schedule
+(`products/experiments/backend/temporal/schedule.py`).
+
+That schedule fires at `:30`, after the timeseries runs earlier in the hour, and carries no input.
+Discovery reads the hour and selects the teams configured for it, so one schedule serves all 24
+hours. A team may configure up to two times, at least 6 hours apart, and gets a run at each.
+Both this discovery and the timeseries one call `recalculation_hour_filter`, so the two always
+agree on which teams belong to a given hour.
+
+The coordinator selects experiments with the same rules the daily discovery uses, plus a 12-hour
+minimum age, an organization feature flag, and a 50-exposure floor. It then starts an ordinary
+`ExperimentMetricsRecalculationWorkflow` per experiment, through the same function the API uses.
+
+The timeseries workflows keep one schedule per hour, because each runs its own metric queries and
+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: one is published 30 minutes before
+every scheduled run, so counting it would skip every experiment forever.
+
+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
+`experiment scheduled recalculation skipped` events carry the coordinator's own decisions.
+
## Key concepts
**Workflow**: A durable function that orchestrates the calculation. If it fails partway through, Temporal can resume it from where it left off.
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 884ac2f34933..5dfd887b83d0 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -112,6 +112,7 @@ from products.error_tracking.backend.facade.temporal import (
from products.experiments.backend.temporal.schedule import (
create_experiment_precompute_canary_schedule,
create_experiment_precompute_enrollment_census_schedule,
+ create_experiment_scheduled_recalculation_schedules,
)
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
from products.growth.backend.temporal.signup_enrichment.schedule import (
@@ -951,6 +952,7 @@ schedules = [
create_experiment_saved_metrics_schedules,
create_experiment_precompute_canary_schedule,
create_experiment_precompute_enrollment_census_schedule,
+ create_experiment_scheduled_recalculation_schedules,
cleanup_cohort_calculation_schedules,
cleanup_non_cloud_ai_observability_schedules,
create_ingestion_acceptance_test_schedule,
diff --git a/products/experiments/backend/temporal/schedule.py b/products/experiments/backend/temporal/schedule.py
index 81aff65a0c46..41430d3bec9f 100644
--- a/products/experiments/backend/temporal/schedule.py
+++ b/products/experiments/backend/temporal/schedule.py
@@ -11,11 +11,12 @@ from temporalio.client import (
ScheduleSpec,
)
-from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_schedule_exists, a_update_schedule
from products.experiments.backend.temporal.models import (
CANARY_WORKFLOW_NAME,
ENROLLMENT_CENSUS_WORKFLOW_NAME,
+ SCHEDULED_RECALCULATION_WORKFLOW_NAME,
ExperimentPrecomputeCanaryInputs,
ExperimentPrecomputeEnrollmentCensusInputs,
)
@@ -75,3 +76,40 @@ async def create_experiment_precompute_enrollment_census_schedule(client: Client
await a_update_schedule(client, ENROLLMENT_CENSUS_SCHEDULE_ID, schedule)
else:
await a_create_schedule(client, ENROLLMENT_CENSUS_SCHEDULE_ID, schedule, trigger_immediately=False)
+
+
+SCHEDULED_RECALCULATION_SCHEDULE_ID = "experiment-scheduled-recalculation"
+
+
+async def create_experiment_scheduled_recalculation_schedules(client: Client) -> None:
+ """Create or update the hourly schedule that starts a real metrics recalculation for every
+ experiment eligible in the hour it fires.
+
+ Fires at :30, after the daily timeseries schedule at :00, so the timeseries sync publish
+ usually lands before a real run supersedes it. The workflow takes no input: discovery reads
+ the hour and selects the teams configured for it, so one schedule serves all 24 hours.
+
+ SKIP overlap: a run that outlives its hour must not stack on the next one.
+ """
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ SCHEDULED_RECALCULATION_WORKFLOW_NAME,
+ id=f'{SCHEDULED_RECALCULATION_SCHEDULE_ID}-{{{{.ScheduledTime.Format "2006-01-02T15"}}}}',
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(cron_expressions=["30 * * * *"]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, SCHEDULED_RECALCULATION_SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULED_RECALCULATION_SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULED_RECALCULATION_SCHEDULE_ID, schedule, trigger_immediately=False)
+
+
+async def delete_experiment_scheduled_recalculation_schedules(client: Client) -> None:
+ """Delete the scheduled recalculation schedule."""
+ try:
+ await a_delete_schedule(client, SCHEDULED_RECALCULATION_SCHEDULE_ID)
+ except Exception:
+ pass # Schedule might not exist
diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_schedule.py b/products/experiments/backend/temporal/test_scheduled_recalculation_schedule.py
new file mode 100644
index 000000000000..4c92cf22ca66
--- /dev/null
+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_schedule.py
@@ -0,0 +1,50 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from django.conf import settings
+
+from products.experiments.backend.temporal.models import SCHEDULED_RECALCULATION_WORKFLOW_NAME
+from products.experiments.backend.temporal.schedule import (
+ SCHEDULED_RECALCULATION_SCHEDULE_ID,
+ create_experiment_scheduled_recalculation_schedules,
+)
+
+pytestmark = pytest.mark.asyncio
+
+MODULE = "products.experiments.backend.temporal.schedule"
+
+
+async def test_creates_one_hourly_schedule_offset_from_the_timeseries_run():
+ with (
+ patch(f"{MODULE}.a_schedule_exists", AsyncMock(return_value=False)),
+ patch(f"{MODULE}.a_create_schedule", AsyncMock()) as create,
+ patch(f"{MODULE}.a_update_schedule", AsyncMock()) as update,
+ ):
+ await create_experiment_scheduled_recalculation_schedules(AsyncMock())
+
+ assert create.await_count == 1
+ update.assert_not_awaited()
+
+ # Every field a typo could break: a wrong workflow name or task queue fails only in
+ # production, where nothing reports it.
+ call = create.await_args_list[0]
+ schedule_id, schedule = call.args[1], call.args[2]
+ assert schedule_id == SCHEDULED_RECALCULATION_SCHEDULE_ID
+ # :30, so the daily timeseries run at :00 publishes before a real run supersedes it.
+ assert schedule.spec.cron_expressions == ["30 * * * *"]
+ assert schedule.action.workflow == SCHEDULED_RECALCULATION_WORKFLOW_NAME
+ assert schedule.action.task_queue == settings.GENERAL_PURPOSE_TASK_QUEUE
+ # No input: discovery resolves the hour, so one schedule serves every hour.
+ assert schedule.action.args == []
+
+
+async def test_an_existing_schedule_is_updated_not_recreated():
+ with (
+ patch(f"{MODULE}.a_schedule_exists", AsyncMock(return_value=True)),
+ patch(f"{MODULE}.a_create_schedule", AsyncMock()) as create,
+ patch(f"{MODULE}.a_update_schedule", AsyncMock()) as update,
+ ):
+ await create_experiment_scheduled_recalculation_schedules(AsyncMock())
+
+ assert update.await_count == 1
+ create.assert_not_awaited()
diff --git a/tach.toml b/tach.toml
index 7f55b594ca47..c30aaed3a0e2 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1179,6 +1179,7 @@ expose = [
"backend\\.temporal\\.recalculation_metrics.*",
"backend\\.temporal\\.schedule\\.create_experiment_precompute_canary_schedule",
"backend\\.temporal\\.schedule\\.create_experiment_precompute_enrollment_census_schedule",
+ "backend\\.temporal\\.schedule\\.create_experiment_scheduled_recalculation_schedules",
]
from = [
"products.experiments",