: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): create a recalculation from daily timeseries results (#104152)
Rodrigo Iloro851a012d0808
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex c47c0adc8e84..064150bce1ec 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -79,6 +79,8 @@ import {SurveyQuestionType,} from '~/types'+import type { ExperimentMetricsRecalculationTriggerEnumApi } from 'products/experiments/frontend/generated/api.schemas'+import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'import type { FunnelCorrelationResultsType, Realm, UserType } from '../../types'@@ -1546,18 +1548,7 @@ export interface eventUsageLogicActions {recalculation_id: string | nullsucceeded?: numbertotal_metrics?: number- trigger?:- | 'agent_mcp'- | 'auto_refresh'- | 'cold_run'- | 'config_change'- | 'experiment_config_change'- | 'experiment_launch'- | 'experiment_stop'- | 'experiment_update'- | 'manual'- | 'metric_config_change'- | 'stale_refresh'+ trigger?: ExperimentMetricsRecalculationTriggerEnumApi}) => {properties: {@@ -1569,19 +1560,7 @@ export interface eventUsageLogicActions {recalculation_id: string | nullsucceeded?: number | undefinedtotal_metrics?: number | undefined- trigger?:- | 'agent_mcp'- | 'auto_refresh'- | 'cold_run'- | 'config_change'- | 'experiment_config_change'- | 'experiment_launch'- | 'experiment_stop'- | 'experiment_update'- | 'manual'- | 'metric_config_change'- | 'stale_refresh'- | undefined+ trigger?: ExperimentMetricsRecalculationTriggerEnumApi | undefined}status: 'completed' | 'failed' | 'triggered'}@@ -3101,18 +3080,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([properties: {experiment_id: numberrecalculation_id: string | null- trigger?:- | 'manual'- | 'cold_run'- | 'stale_refresh'- | 'auto_refresh'- | 'experiment_config_change'- | 'metric_config_change'- | 'config_change'- | 'experiment_launch'- | 'experiment_stop'- | 'experiment_update'- | 'agent_mcp'+ trigger?: ExperimentMetricsRecalculationTriggerEnumApiis_existing?: booleantotal_metrics?: numbersucceeded?: numberdiff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex 93ab2d007afb..c168e90d1bb8 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -115,6 +115,17 @@ const timeseriesFallbackRecalculation = {results: [{ metric_uuid: PRIMARY_METRIC_UUID, status: 'completed', result: primaryResult, error_message: null }],}+// Timeseries placeholder that covers every current metric: the backend returns this when the daily timeseries+// data is newer than the latest run, so nothing is missing and no run should start.+const completeTimeseriesFallbackRecalculation = {+ ...timeseriesFallbackRecalculation,+ completed_metrics: 2,+ results: [+ { metric_uuid: PRIMARY_METRIC_UUID, status: 'completed', result: primaryResult, error_message: null },+ { metric_uuid: SECONDARY_METRIC_UUID, status: 'completed', result: secondaryResult, error_message: null },+ ],+}+describe('experimentMetricsLogic', () => {let logic: ReturnType<typeof experimentMetricsLogic.build>@@ -498,7 +509,25 @@ describe('experimentMetricsLogic', () => {.toNotHaveDispatchedActions(['triggerRecalculation'])})- it('renders the timeseries fallback and triggers a cold_run to fill gaps and refresh', async () => {+ it('accepts a timeseries fallback that covers every metric without triggering a run', async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [+ 200,+ completeTimeseriesFallbackRecalculation,+ ],+ },+ })+ mountLogic()++ await expectLogic(logic)+ .toDispatchActions(['setCurrentRecalculation'])+ .toNotHaveDispatchedActions(['triggerRecalculation'])+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)+ expect(logic.values.secondaryMetricsResults[0]).toEqual(secondaryResult)+ })++ it('renders the timeseries fallback and triggers a cold_run to fill gaps', async () => {let capturedBody: anyuseMocks({get: {@@ -522,7 +551,7 @@ describe('experimentMetricsLogic', () => {.toFinishAllListeners()// The placeholder timeseries result is shown immediately for the metric it covered.expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)- // A real cold_run is fired to fill the gap (secondary) and refresh.+ // A real cold_run is fired to fill the gap (secondary).expect(capturedBody).toEqual({ trigger: 'cold_run' })})diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 6ea91a6170c1..a10f1b19ddb1 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -210,18 +210,7 @@ export interface experimentMetricsLogicActions {recalculation_id: string | nullsucceeded?: numbertotal_metrics?: number- trigger?:- | 'agent_mcp'- | 'auto_refresh'- | 'cold_run'- | 'config_change'- | 'experiment_config_change'- | 'experiment_launch'- | 'experiment_stop'- | 'experiment_update'- | 'manual'- | 'metric_config_change'- | 'stale_refresh'+ trigger?: ExperimentMetricsRecalculationTriggerEnumApi}) => {properties: {@@ -233,19 +222,7 @@ export interface experimentMetricsLogicActions {recalculation_id: string | nullsucceeded?: number | undefinedtotal_metrics?: number | undefined- trigger?:- | 'agent_mcp'- | 'auto_refresh'- | 'cold_run'- | 'config_change'- | 'experiment_config_change'- | 'experiment_launch'- | 'experiment_stop'- | 'experiment_update'- | 'manual'- | 'metric_config_change'- | 'stale_refresh'- | undefined+ trigger?: ExperimentMetricsRecalculationTriggerEnumApi | undefined}status: 'completed' | 'failed' | 'triggered'} // eventUsageLogic@@ -699,34 +676,38 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([}/**- * Timeseries fallback is a placeholder: it may cover only some metrics and is cumulative- * daily data, not a fresh point-in-time result. Always trigger a real cold_run to fill the- * gaps and refresh; the placeholder stays visible and cells update in place as it polls.+ * A run has a gap when its own resolved count fell short of its total (also after a reset and+ * relaunch), or when a metric was added after it finished so a current metric uuid is absent+ * from its results. The run's own counts look complete in the second case, so only a uuid+ * comparison catches it.+ */+ const coveredUuids = new Set(coveredMetricUuids(recalculation))+ const missingCurrentMetric = currentMetricUuids(props.experiment).some(+ (uuid) => !coveredUuids.has(uuid)+ )+ const hasGap =+ recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics ||+ missingCurrentMetric++ /**+ * The timeseries fallback is daily data the backend serves when no run exists yet. Accept it+ * as is: a cold_run only when a metric has no point (the daily workflow never computes+ * retention metrics, for one), so a page load does not recompute results the timeseries+ * already holds. The placeholder stays visible and cells update in place as the run polls.*/if (recalculation.result_source === 'timeseries_fallback') {- actions.triggerRecalculation('cold_run')+ if (hasGap) {+ actions.triggerRecalculation('cold_run')+ }return}/**- * Heal a completed run that does not cover every current metric. Two cases:- * 1. The run diverged: its own resolved count fell short of its total (also fires after a- * reset and relaunch).- * 2. A metric was added after this run finished, so a current metric uuid is absent from the- * run's results. The run's own counts look complete, so only a uuid comparison catches it.- * Otherwise the new metric shows a perpetual loading state, since nothing else re-runs on- * page load. Advance the window with experiment_config_change rather than reuse a cutoff that- * may predate the new start_date.+ * Heal a completed run with a gap; otherwise the new metric shows a perpetual loading state,+ * since nothing else re-runs on page load. Advance the window with experiment_config_change+ * rather than reuse a cutoff that may predate the new start_date.*/- const coveredUuids = new Set(coveredMetricUuids(recalculation))- const missingCurrentMetric = currentMetricUuids(props.experiment).some(- (uuid) => !coveredUuids.has(uuid)- )- if (- recalculation.status === RECALCULATION_STATUSES.completed &&- (recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics ||- missingCurrentMetric)- ) {+ if (recalculation.status === RECALCULATION_STATUSES.completed && hasGap) {actions.triggerRecalculation('experiment_config_change')return}diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.mdindex 005803d6b490..d7eca8db4fcb 100644--- a/posthog/temporal/experiments/README.md+++ b/posthog/temporal/experiments/README.md@@ -34,6 +34,19 @@ When a schedule triggers, it starts a workflow that:1. Discovers which experiment-metric pairs need calculation2. Calculates each metric in parallel3. Stores results in the database+4. Assembles one completed metrics recalculation per experiment from the points this run wrote (see below)++### Handing fresh points to the recalculation reader++The experiment page reads results through `GET /metrics_recalculation/latest`, which returns the newest completed `ExperimentMetricsRecalculation`. Timeseries rows alone never reach it, so after the metric activities finish, each workflow runs `create_recalculation_from_timeseries` once per experiment it touched (`products/experiments/backend/timeseries_sync.py`):++- 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. Metric types the daily run cannot compute (`DAILY_TIMESERIES_METRIC_TYPES` in `metric_resolution.py`, which excludes retention) 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.++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.```text┌────────────────────────────────────────────────────────────────────────────┐diff --git a/posthog/temporal/experiments/__init__.py b/posthog/temporal/experiments/__init__.pyindex 82746281f179..4919ad51f2b0 100644--- a/posthog/temporal/experiments/__init__.py+++ b/posthog/temporal/experiments/__init__.py@@ -2,6 +2,7 @@ from posthog.temporal.experiments.activities import (backfill_experiment_metric,calculate_experiment_regular_metric,calculate_experiment_saved_metric,+ create_recalculation_from_timeseries,get_experiment_regular_metrics_for_hour,get_experiment_saved_metrics_for_hour,)@@ -21,6 +22,7 @@ ACTIVITIES = [calculate_experiment_regular_metric,get_experiment_saved_metrics_for_hour,calculate_experiment_saved_metric,+ create_recalculation_from_timeseries,backfill_experiment_metric,]@@ -34,5 +36,6 @@ __all__ = ["calculate_experiment_regular_metric","get_experiment_saved_metrics_for_hour","calculate_experiment_saved_metric",+ "create_recalculation_from_timeseries","backfill_experiment_metric",]diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.pyindex 873005278b78..fdd32e7e7a62 100644--- a/posthog/temporal/experiments/activities.py+++ b/posthog/temporal/experiments/activities.py@@ -1,5 +1,5 @@from datetime import datetime, timedelta-from typing import Any, Union+from typing import Anyfrom zoneinfo import ZoneInfofrom django.db import close_old_connections@@ -8,7 +8,7 @@ from django.db.models import Qimport structlogimport temporalio.activity-from posthog.schema import ExperimentFunnelMetric, ExperimentMeanMetric, ExperimentQuery, ExperimentRatioMetric+from posthog.schema import ExperimentQueryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import tag_queries@@ -24,7 +24,12 @@ from posthog.temporal.experiments.models import ()from posthog.temporal.experiments.utils import DEFAULT_EXPERIMENT_RECALCULATION_HOUR, check_significance_transition-from products.experiments.backend.facade.timeseries import backfill_experiment_timeseries+from products.experiments.backend.facade.timeseries import (+ backfill_experiment_timeseries,+ build_metric,+ is_daily_timeseries_metric,+ sync_timeseries_recalculation,+)from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_endfrom products.experiments.backend.hogql_queries.error_handling import capture_experiment_metric_error_eventfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint@@ -94,6 +99,7 @@ def _get_experiment_regular_metrics_for_hour_sync(hour: int) -> list[ExperimentRexperiment_id=experiment.id,metric_uuid=metric_uuid,fingerprint=fingerprint,+ team_id=experiment.team_id,))@@ -156,14 +162,7 @@ def _calculate_experiment_regular_metric_sync()metric_type = metric_dict.get("metric_type")- metric_obj: Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric]- if metric_type == "mean":- metric_obj = ExperimentMeanMetric(**metric_dict)- elif metric_type == "funnel":- metric_obj = ExperimentFunnelMetric(**metric_dict)- elif metric_type == "ratio":- metric_obj = ExperimentRatioMetric(**metric_dict)- else:+ if not is_daily_timeseries_metric(metric_dict):return ExperimentRegularMetricResult(experiment_id=experiment_id,metric_uuid=metric_uuid,@@ -171,6 +170,7 @@ def _calculate_experiment_regular_metric_sync(success=False,error_message=f"Unknown metric type: {metric_type}",)+ metric_obj = build_metric(metric_dict)if not experiment.start_date:return ExperimentRegularMetricResult(@@ -386,6 +386,7 @@ def _get_experiment_saved_metrics_for_hour_sync(hour: int) -> list[ExperimentSavexperiment_id=experiment.id,metric_uuid=metric_uuid,fingerprint=fingerprint,+ team_id=experiment.team_id,))@@ -462,14 +463,7 @@ def _calculate_experiment_saved_metric_sync("fingerprint": fingerprint,}metric_type = query.get("metric_type")- metric_obj: Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric]- if metric_type == "mean":- metric_obj = ExperimentMeanMetric(**query)- elif metric_type == "funnel":- metric_obj = ExperimentFunnelMetric(**query)- elif metric_type == "ratio":- metric_obj = ExperimentRatioMetric(**query)- else:+ if not is_daily_timeseries_metric(query):return ExperimentSavedMetricResult(experiment_id=experiment_id,metric_uuid=metric_uuid,@@ -477,6 +471,7 @@ def _calculate_experiment_saved_metric_sync(success=False,error_message=f"Unknown metric type: {metric_type}",)+ metric_obj = build_metric(query)if not experiment.start_date:return ExperimentSavedMetricResult(@@ -643,6 +638,20 @@ async def calculate_experiment_saved_metric()+@database_sync_to_async+def _create_recalculation_from_timeseries_sync(experiment_id: int, team_id: int, run_started_at: str) -> str | None:+ close_old_connections()+ return sync_timeseries_recalculation(+ experiment_id, team_id=team_id, run_started_at=datetime.fromisoformat(run_started_at)+ )+++async def create_recalculation_from_timeseries(experiment_id: int, team_id: int, run_started_at: str) -> str | None:+ """Assemble a completed metrics recalculation from the timeseries points this run wrote for one experiment."""+ return await _create_recalculation_from_timeseries_sync(experiment_id, team_id, run_started_at)++@temporalio.activity.defndef backfill_experiment_metric(recalculation_id: str) -> dict[str, Any]:"""Backfill timeseries data for an experiment recalculation request."""diff --git a/posthog/temporal/experiments/models.py b/posthog/temporal/experiments/models.pyindex 26c19b97bc39..2d2ed4872b4d 100644--- a/posthog/temporal/experiments/models.py+++ b/posthog/temporal/experiments/models.py@@ -1,5 +1,7 @@import dataclasses+from posthog.dataclasses import frozen+# Temporal retry ceiling for the per-metric calc activities. Shared with the activity code, which emits the# terminal `experiment metric error` analytics event only on the final attempt — keep the RetryPolicy in# workflows.py and this constant in lockstep or terminal failures get emitted early / not at all.@@ -13,13 +15,15 @@ class ExperimentRegularMetricsWorkflowInputs:hour: int # 0-23, which hour's teams to process+@frozenclass ExperimentRegularMetricInput:"""Input to calculate a single experiment-metric."""experiment_id: intmetric_uuid: strfingerprint: str+ # Defaulted so histories recorded before the field existed still decode during replay.+ team_id: int | None = None@dataclasses.dataclass@@ -40,13 +44,14 @@ class ExperimentSavedMetricsWorkflowInputs:hour: int # 0-23, which hour's teams to process+@frozenclass ExperimentSavedMetricInput:"""Input to calculate a single experiment-saved metric."""experiment_id: intmetric_uuid: strfingerprint: str+ team_id: int | None = None@dataclasses.dataclassdiff --git a/posthog/temporal/experiments/workflows.py b/posthog/temporal/experiments/workflows.pyindex c7221dcfd243..d11a51d24bd8 100644--- a/posthog/temporal/experiments/workflows.py+++ b/posthog/temporal/experiments/workflows.py@@ -1,5 +1,5 @@import asyncio-from datetime import timedelta+from datetime import datetime, timedeltaimport temporalio.workflowfrom temporalio.common import RetryPolicy@@ -11,6 +11,7 @@ with temporalio.workflow.unsafe.imports_passed_through():backfill_experiment_metric,calculate_experiment_regular_metric,calculate_experiment_saved_metric,+ create_recalculation_from_timeseries,get_experiment_regular_metrics_for_hour,get_experiment_saved_metrics_for_hour,)@@ -24,6 +25,27 @@ with temporalio.workflow.unsafe.imports_passed_through():MAX_CONCURRENT_METRICS = 10+async def _create_recalculations_from_timeseries(+ experiments: set[tuple[int, int]], run_started_at: datetime, semaphore: asyncio.Semaphore+) -> int:+ """One activity per (experiment, team) this run touched; returns how many recalculation rows gained copies."""++ async def _sync_experiment(experiment_id: int, team_id: int) -> str | None:+ async with semaphore:+ return await temporalio.workflow.execute_activity(+ create_recalculation_from_timeseries,+ args=[experiment_id, team_id, run_started_at.isoformat()],+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ results = await asyncio.gather(+ *[_sync_experiment(experiment_id, team_id) for experiment_id, team_id in sorted(experiments)],+ return_exceptions=True,+ )+ return sum(1 for result in results if isinstance(result, str))++@temporalio.workflow.defn(name="experiment-regular-metrics-workflow")class ExperimentRegularMetricsWorkflow(PostHogWorkflow):"""@@ -32,7 +54,8 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):Runs daily per hour (24 schedules total). Each run:1. Discovers experiment-metrics for teams scheduled at this hour2. Calculates each metric in parallel (one activity per metric)- 3. Returns summary of successes/failures+ 3. Assembles a completed metrics recalculation per experiment from this run's points+ 4. Returns summary of successes/failures"""@staticmethod@@ -41,6 +64,8 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):@temporalio.workflow.runasync def run(self, inputs: ExperimentRegularMetricsWorkflowInputs) -> dict:+ run_started_at = temporalio.workflow.now()+# Step 1: Discover experiment-metrics for this hourexperiment_metrics = await temporalio.workflow.execute_activity(get_experiment_regular_metrics_for_hour,@@ -55,6 +80,7 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):"total": 0,"succeeded": 0,"failed": 0,+ "recalculations_synced": 0,}# Step 2: Calculate each metric with limited concurrency@@ -76,7 +102,18 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):tasks = [_run_metric(em) for em in experiment_metrics]results = await asyncio.gather(*tasks, return_exceptions=True)- # Step 3: Summarize+ # Step 3: Assemble a recalculation per experiment from the points this run wrote, so the latest read+ # serves them without a recompute. Points are matched against the run start, so the stamp is taken+ # before discovery. The patch gate keeps replay of histories recorded without this step deterministic.+ recalculations_synced = 0+ if temporalio.workflow.patched("experiment-timeseries-recalculation-sync-2026-09"):+ recalculations_synced = await _create_recalculations_from_timeseries(+ {(em.experiment_id, em.team_id) for em in experiment_metrics if em.team_id is not None},+ run_started_at,+ semaphore,+ )++ # Step 4: Summarizesucceeded = 0failed = 0@@ -93,6 +130,7 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):"total": len(experiment_metrics),"succeeded": succeeded,"failed": failed,+ "recalculations_synced": recalculations_synced,}@@ -104,7 +142,8 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):Runs daily per hour (24 schedules total). Each run:1. Discovers experiment-saved metrics for teams scheduled at this hour2. Calculates each metric in parallel (one activity per metric)- 3. Returns summary of successes/failures+ 3. Assembles a completed metrics recalculation per experiment from this run's points+ 4. Returns summary of successes/failures"""@staticmethod@@ -113,6 +152,8 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):@temporalio.workflow.runasync def run(self, inputs: ExperimentSavedMetricsWorkflowInputs) -> dict:+ run_started_at = temporalio.workflow.now()+# Step 1: Discover experiment-saved metrics for this hourexperiment_metrics = await temporalio.workflow.execute_activity(get_experiment_saved_metrics_for_hour,@@ -127,6 +168,7 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):"total": 0,"succeeded": 0,"failed": 0,+ "recalculations_synced": 0,}# Step 2: Calculate each metric with limited concurrency@@ -148,7 +190,18 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):tasks = [_run_metric(em) for em in experiment_metrics]results = await asyncio.gather(*tasks, return_exceptions=True)- # Step 3: Summarize+ # Step 3: Assemble a recalculation per experiment from the points this run wrote, so the latest read+ # serves them without a recompute. Points are matched against the run start, so the stamp is taken+ # before discovery. The patch gate keeps replay of histories recorded without this step deterministic.+ recalculations_synced = 0+ if temporalio.workflow.patched("experiment-timeseries-recalculation-sync-2026-09"):+ recalculations_synced = await _create_recalculations_from_timeseries(+ {(em.experiment_id, em.team_id) for em in experiment_metrics if em.team_id is not None},+ run_started_at,+ semaphore,+ )++ # Step 4: Summarizesucceeded = 0failed = 0@@ -165,6 +218,7 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):"total": len(experiment_metrics),"succeeded": succeeded,"failed": failed,+ "recalculations_synced": recalculations_synced,}diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.pyindex d343c5d1af66..fb26359f9101 100644--- a/products/experiments/backend/facade/timeseries.py+++ b/products/experiments/backend/facade/timeseries.py@@ -1,5 +1,12 @@-"""Timeseries backfill capability, re-exported for callers outside the experiments product."""+"""Timeseries capabilities, re-exported for callers outside the experiments product."""+from products.experiments.backend.temporal.metric_resolution import build_metric, is_daily_timeseries_metricfrom products.experiments.backend.timeseries_backfill import backfill_experiment_timeseries+from products.experiments.backend.timeseries_sync import sync_timeseries_recalculation-__all__ = ["backfill_experiment_timeseries"]+__all__ = [+ "backfill_experiment_timeseries",+ "build_metric",+ "is_daily_timeseries_metric",+ "sync_timeseries_recalculation",+]diff --git a/products/experiments/backend/migrations/0041_alter_experimentmetricsrecalculation_trigger.py b/products/experiments/backend/migrations/0041_alter_experimentmetricsrecalculation_trigger.pynew file mode 100644index 000000000000..ded3b1264cd3--- /dev/null+++ b/products/experiments/backend/migrations/0041_alter_experimentmetricsrecalculation_trigger.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.17 on 2026-09-21 21:35++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0040_experiment_feature_flag_rule_id_unique"),+ ]++ operations = [+ migrations.AlterField(+ model_name="experimentmetricsrecalculation",+ name="trigger",+ field=models.CharField(+ choices=[+ ("manual", "Manual"),+ ("agent_mcp", "Agent (MCP)"),+ ("cold_run", "Cold Run"),+ ("stale_refresh", "Stale Refresh"),+ ("auto_refresh", "Auto Refresh"),+ ("experiment_config_change", "Experiment Config Change"),+ ("metric_config_change", "Metric Config Change"),+ ("config_change", "Config Change"),+ ("experiment_launch", "Experiment Launch"),+ ("experiment_stop", "Experiment Stop"),+ ("experiment_update", "Experiment Update"),+ ("timeseries_sync", "Timeseries Sync"),+ ],+ default="manual",+ max_length=30,+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex b59fa4a53821..71f0b49b1fd7 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0040_experiment_feature_flag_rule_id_unique+0041_alter_experimentmetricsrecalculation_triggerdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 4015e4e99c78..7c41fe5c4522 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -546,6 +546,9 @@ class ExperimentMetricsRecalculation(TeamScopedRootMixin, UUIDModel):EXPERIMENT_LAUNCH = "experiment_launch", "Experiment Launch"EXPERIMENT_STOP = "experiment_stop", "Experiment Stop"EXPERIMENT_UPDATE = "experiment_update", "Experiment Update"+ # Written by the daily timeseries workflow, not by a user: a completed run assembled from the+ # timeseries points of one daily run, so the latest read serves fresh data without a recompute.+ TIMESERIES_SYNC = "timeseries_sync", "Timeseries Sync"team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")experiment = models.ForeignKey("Experiment", on_delete=models.CASCADE)diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex d1fd255588b4..aa37bfddf14b 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -50,6 +50,10 @@ from products.experiments.backend.temporal.recalculation_logic import discover_e# happy-path failure handling; this TTL is the defense-in-depth backstop if that rollback itself fails._STALE_RECALC_THRESHOLD = timedelta(minutes=30)+# A daily timeseries point older than this no longer stands in for a recalculation on the cold-start read. The+# daily run happens once per day, so a fresh experiment always has a point inside the bound.+TIMESERIES_FALLBACK_MAX_AGE = timedelta(hours=24)+# `is_existing=True` reuse path — counts how often the idempotency guard saves us a workflow start.# A sustained climb here without a matching climb in requests is the signal the frontend is double-posting._recalculation_reuse_counter = Counter(@@ -435,14 +439,16 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:metrics-recalculation run exists yet. Timeseries rows live in ExperimentMetricResult under the metric'sCONFIG fingerprint (not a per-run recalc fingerprint), so they're found without any recalc row.- Returns None when no metric has a completed timeseries point (caller then keeps the 404). query_to and- completed_at both pin to the freshest point's date so the frontend's >24h staleness path fires its own- recompute trigger (GET never triggers anything itself).+ Only points younger than TIMESERIES_FALLBACK_MAX_AGE count. The frontend accepts a fallback that covers every+ metric without starting a run, so an older point must read as a gap or the page would show weeks-old numbers+ as completed. Returns None when no metric has a fresh completed point (caller then keeps the 404). query_to+ and completed_at both pin to the freshest point's date. GET never triggers anything itself."""with team_scope(experiment.team_id, canonical=True):metrics = discover_experiment_metrics(experiment)stats_method = get_experiment_stats_method(experiment)+ now = timezone.now()results: list[dict] = []latest_query_to = Nonefor metric in metrics:@@ -463,6 +469,10 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:metric_uuid=metric.metric_uuid,fingerprint=config_fp,status=ExperimentMetricResult.Status.COMPLETED,+ # Bounded on both sides: the backfill writes end-of-day points, so today's point can carry+ # a future query_to that would surface here as a future completion time.+ query_to__gte=now - TIMESERIES_FALLBACK_MAX_AGE,+ query_to__lte=now,).order_by("-query_to").first()diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex f9616a164fcc..c21acdda5e08 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -112,7 +112,9 @@ The snapshot is immutable only while the experiment is running, where each run pA recalc row records what caused it, in `trigger` (`Trigger` on the model). The set is more than a manual click: `MANUAL`, `AGENT_MCP`, `COLD_RUN`, `STALE_REFRESH`, `AUTO_REFRESH`, config-change triggers (`EXPERIMENT_CONFIG_CHANGE`, `METRIC_CONFIG_CHANGE`), and experiment lifecycle triggers (`EXPERIMENT_LAUNCH`, `EXPERIMENT_STOP`, `EXPERIMENT_UPDATE`). This lets the analytics and the UI tell a user click apart from an automatic refresh.-`GET /metrics_recalculation/latest` returns a synthetic "completed" payload built from each metric's latest timeseries point (`build_timeseries_cold_start_payload`) when no real recalc run exists yet. This is the cold-start placeholder: the user sees the freshest cached timeseries values instead of a bare 404 on first open, with `query_to` pinned to the freshest point so the frontend's own staleness path can fire a real recompute. The GET path never triggers a recompute itself; it only reads.+`TIMESERIES_SYNC` is the one trigger no user or lifecycle event emits. The daily timeseries workflows write it after their metric activities finish: one completed row per experiment per daily run, with the run's timeseries points copied under the recalc fingerprint at a shared `query_to`, so the `latest` read serves fresh daily data without a recompute. The inline and saved metric workflows share that row: the first to finish creates it, the second adds the copies it lacks. See "Handing fresh points to the recalculation reader" in `posthog/temporal/experiments/README.md`.++`GET /metrics_recalculation/latest` returns a synthetic "completed" payload built from each metric's latest timeseries point (`build_timeseries_cold_start_payload`) when no real recalc run exists yet. This is the cold-start placeholder: the user sees the freshest cached timeseries values instead of a bare 404 on first open. Only points younger than `TIMESERIES_FALLBACK_MAX_AGE` (24 hours) count, so an older point reads as a gap and the frontend starts a `cold_run` for it; a fallback that covers every metric is accepted as is. The GET path never triggers a recompute itself; it only reads.### Live query progress on the GET pathdiff --git a/products/experiments/backend/temporal/metric_resolution.py b/products/experiments/backend/temporal/metric_resolution.pyindex c8c234a58e69..533ca3a21009 100644--- a/products/experiments/backend/temporal/metric_resolution.py+++ b/products/experiments/backend/temporal/metric_resolution.py@@ -26,6 +26,14 @@ METRIC_BUILDERS: dict[str, type[ExperimentMetric]] = {"retention": ExperimentRetentionMetric,}+# The daily timeseries activities build only these. The sync that turns their points into a recalculation reads+# the same set, so a metric the daily run never computes is not counted as a gap in the row it creates.+DAILY_TIMESERIES_METRIC_TYPES: frozenset[str] = frozenset({"mean", "funnel", "ratio"})+++def is_daily_timeseries_metric(metric: dict[str, Any] | None) -> bool:+ return bool(metric and metric.get("metric_type") in DAILY_TIMESERIES_METRIC_TYPES)+def _merge_saved_metric_breakdowns(saved_query: dict[str, Any], metadata: dict[str, Any] | None) -> dict[str, Any]:"""Merge per-experiment breakdowns from the M2M link metadata into the saved query, mirroring thediff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pyindex a6ddc86fcf04..f36a142fc29f 100644--- a/products/experiments/backend/test/test_metrics_recalculation_api.py+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -1,8 +1,11 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedelta+import time_machinefrom posthog.test.base import APIBaseTestfrom unittest import mock+from django.utils import timezone+from parameterized import parameterizedfrom rest_framework import status@@ -281,10 +284,11 @@ class TestMetricsRecalculationAPI(APIBaseTest):result={"ok": True},)+ @time_machine.travel("2026-09-01T12:00:00Z", tick=False)def test_get_latest_returns_timeseries_fallback_on_cold_start(self):# No real recalc row, but a completed timeseries point exists → 200 with source=timeseries_fallback.exp = self._launched_experiment(flag_key="ts-fallback")- self._store_timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC))+ self._store_timeseries_point(exp, "m1", timezone.now() - timedelta(hours=1))resp = self.client.get(self._latest_url(exp.id))assert resp.status_code == status.HTTP_200_OK, resp.content@@ -294,12 +298,13 @@ class TestMetricsRecalculationAPI(APIBaseTest):assert len(body["results"]) == 1assert body["results"][0]["result"] == {"ok": True}+ @time_machine.travel("2026-09-01T12:00:00Z", tick=False)def test_get_latest_prefers_timeseries_fallback_over_first_active_run(self):# Reload during the first-ever run: the pending run has no results yet, so returning it would blank# out the timeseries data on screen. The fallback keeps the results visible while active_run rides# along so the client still polls the executing run.exp = self._launched_experiment(flag_key="ts-fallback-active")- self._store_timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC))+ self._store_timeseries_point(exp, "m1", timezone.now() - timedelta(hours=1))active = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status="pending")resp = self.client.get(self._latest_url(exp.id))@@ -314,11 +319,12 @@ class TestMetricsRecalculationAPI(APIBaseTest):resp = self.client.get(self._latest_url(exp.id))assert resp.status_code == status.HTTP_404_NOT_FOUND+ @time_machine.travel("2026-09-01T12:00:00Z", tick=False)@mock.patch("products.experiments.backend.presentation.views.sync_connect")def test_get_latest_fallback_does_not_start_a_workflow(self, mock_connect):# GET stays a pure read: the fallback path must never connect to Temporal.exp = self._launched_experiment(flag_key="ts-pure-read")- self._store_timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC))+ self._store_timeseries_point(exp, "m1", timezone.now() - timedelta(hours=1))resp = self.client.get(self._latest_url(exp.id))assert resp.status_code == status.HTTP_200_OKdiff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex e2d279bca1fa..c355416e0c79 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -1,6 +1,7 @@from datetime import UTC, datetime, timedeltaimport pytest+import time_machinefrom posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import patch@@ -420,6 +421,7 @@ class TestRecalculationService(BaseTest):@pytest.mark.django_db(transaction=True)+@time_machine.travel("2026-09-01T12:00:00Z", tick=False)class TestTimeseriesColdStartPayload(BaseTest):def _flag(self, key: str) -> FeatureFlag:return FeatureFlag.objects.create(@@ -471,8 +473,8 @@ class TestTimeseriesColdStartPayload(BaseTest):def test_builds_completed_fallback_from_latest_point(self):exp = self._experiment("ts-one", ["m1"])- older = datetime(2026, 2, 1, tzinfo=UTC)- latest = datetime(2026, 2, 2, tzinfo=UTC)+ older = timezone.now() - timedelta(hours=3)+ latest = timezone.now() - timedelta(hours=1)self._timeseries_point(exp, "m1", older, {"stale": True})self._timeseries_point(exp, "m1", latest, {"ok": True})@@ -490,7 +492,7 @@ class TestTimeseriesColdStartPayload(BaseTest):def test_omits_metrics_without_a_timeseries_point(self):exp = self._experiment("ts-partial", ["m1", "m2"])- self._timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC), {"ok": True})+ self._timeseries_point(exp, "m1", timezone.now() - timedelta(hours=1), {"ok": True})# m2 has no point.payload = build_timeseries_cold_start_payload(exp)@@ -500,10 +502,25 @@ class TestTimeseriesColdStartPayload(BaseTest):uuids = {r["metric_uuid"] for r in payload["results"]}assert uuids == {"m1"}+ @parameterized.expand(+ [+ ("fresh_point", timedelta(hours=23), True),+ ("stale_point", timedelta(hours=25), False),+ # The backfill writes end-of-day points, so today's point can sit in the future.+ ("future_point", timedelta(hours=-10), False),+ ]+ )+ def test_only_points_inside_the_max_age_feed_the_fallback(self, _name: str, age: timedelta, included: bool):+ exp = self._experiment(f"ts-age-{_name}", ["m1"])+ self._timeseries_point(exp, "m1", timezone.now() - age, {"ok": True})++ payload = build_timeseries_cold_start_payload(exp)+ assert (payload is not None) == included+def test_config_fingerprint_mismatch_yields_no_point(self):exp = self._experiment("ts-drift", ["m1"])# Store a point under a stale fingerprint, then change config so the recomputed fp won't match.- self._timeseries_point(exp, "m1", datetime(2026, 2, 2, tzinfo=UTC), {"ok": True})+ self._timeseries_point(exp, "m1", timezone.now() - timedelta(hours=1), {"ok": True})exp.exposure_criteria = {"filterTestAccounts": True}exp.save()assert build_timeseries_cold_start_payload(exp) is Nonediff --git a/products/experiments/backend/test/test_timeseries_sync.py b/products/experiments/backend/test/test_timeseries_sync.pynew file mode 100644index 000000000000..dce99c1af2d1--- /dev/null+++ b/products/experiments/backend/test/test_timeseries_sync.py@@ -0,0 +1,226 @@+from datetime import UTC, datetime, timedelta++import pytest+import time_machine+from posthog.test.base import BaseTest++from django.utils import timezone++from parameterized import parameterized++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,+)+from products.experiments.backend.recalculation import get_run_results+from products.experiments.backend.temporal.metric_resolution import find_metric_dict+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.experiments.backend.timeseries_sync import sync_timeseries_recalculation+from products.feature_flags.backend.models.feature_flag import FeatureFlag++RUN_STARTED_AT = datetime(2026, 3, 1, 2, 0, tzinfo=UTC)+IN_RUN = datetime(2026, 3, 1, 2, 7, tzinfo=UTC)+LATER_IN_RUN = datetime(2026, 3, 1, 2, 9, tzinfo=UTC)+BEFORE_RUN = datetime(2026, 2, 28, 2, 5, tzinfo=UTC)+IN_FUTURE = datetime(2026, 3, 3, 0, 0, tzinfo=UTC)+++def _mean_metric(uuid: str) -> dict:+ return {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+++def _retention_metric(uuid: str) -> dict:+ return {+ "uuid": uuid,+ "kind": "ExperimentMetric",+ "metric_type": "retention",+ "start_event": {"kind": "EventsNode", "event": "signup"},+ "completion_event": {"kind": "EventsNode", "event": "purchase"},+ }++[email protected]_db(transaction=True)+@time_machine.travel("2026-03-01T02:10:00Z", tick=False)+class TestSyncTimeseriesRecalculation(BaseTest):+ def _experiment(self, flag_key: str, metrics: list[dict]) -> Experiment:+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=flag_key,+ name=f"Flag for {flag_key}",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ exp = Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=flag,+ name="exp",+ start_date=datetime(2026, 1, 1, tzinfo=UTC),+ )+ exp.metrics = metrics+ exp.save()+ return exp++ def _config_fp(self, exp: Experiment, metric_uuid: str) -> str:+ assert exp.start_date is not None+ metric_dict = find_metric_dict(exp, metric_uuid)+ assert metric_dict is not None+ return compute_metric_fingerprint(+ metric_dict,+ exp.start_date,+ get_experiment_stats_method(exp),+ exp.exposure_criteria,+ only_count_matured_users=exp.only_count_matured_users,+ )++ def _timeseries_point(self, exp: Experiment, metric_uuid: str, query_to: datetime, result: dict) -> None:+ assert exp.start_date is not None+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid=metric_uuid,+ fingerprint=self._config_fp(exp, metric_uuid),+ query_from=exp.start_date,+ query_to=query_to,+ status="completed",+ result=result,+ )++ def _sync(+ self,+ exp: Experiment,+ now: datetime = LATER_IN_RUN + timedelta(minutes=1),+ run_started_at: datetime = RUN_STARTED_AT,+ ) -> str | None:+ return sync_timeseries_recalculation(exp.id, team_id=self.team.id, run_started_at=run_started_at, now=now)++ def _link_saved_metric(self, exp: Experiment, metric_uuid: str) -> None:+ saved = ExperimentSavedMetric.objects.create(team=self.team, name=metric_uuid, query=_mean_metric(metric_uuid))+ ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": "primary"})++ def test_creates_a_completed_run_from_the_points_of_this_daily_run(self):+ exp = self._experiment("sync-full", [_mean_metric("m1"), _mean_metric("m2")])+ self._timeseries_point(exp, "m1", IN_RUN, {"m": 1})+ self._timeseries_point(exp, "m2", LATER_IN_RUN, {"m": 2})++ recalculation_id = self._sync(exp)++ assert recalculation_id is not None+ recalc = ExperimentMetricsRecalculation.objects.get(id=recalculation_id)+ assert recalc.status == ExperimentMetricsRecalculation.Status.COMPLETED+ assert recalc.trigger == ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC+ assert recalc.total_metrics == 2+ assert recalc.metric_uuids == ["m1", "m2"]+ assert recalc.completed_at is not None+ # One second past the newest point, so the copies never collide with a timeseries row on the+ # (experiment, metric_uuid, query_to) key.+ assert recalc.query_to == LATER_IN_RUN + timedelta(seconds=1)++ results = {r["metric_uuid"]: r["result"] for r in get_run_results(recalc)}+ assert results == {"m1": {"m": 1}, "m2": {"m": 2}}+ copies = ExperimentMetricResult.objects.filter(experiment=exp, query_to=recalc.query_to)+ assert {row.fingerprint for row in copies} == {+ compute_recalc_fingerprint(self._config_fp(exp, "m1")),+ compute_recalc_fingerprint(self._config_fp(exp, "m2")),+ }+ # The timeseries rows keep their config fingerprint.+ assert ExperimentMetricResult.objects.filter(experiment=exp, fingerprint=self._config_fp(exp, "m1")).exists()++ # A second pass over the same run finds the new row already covers these points.+ assert self._sync(exp) is None+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1++ def test_leaves_metric_types_the_daily_run_cannot_compute_out_of_the_row(self):+ exp = self._experiment("sync-retention", [_mean_metric("m1"), _retention_metric("r1")])+ self._timeseries_point(exp, "m1", IN_RUN, {"m": 1})++ recalculation_id = self._sync(exp)++ assert recalculation_id is not None+ recalc = ExperimentMetricsRecalculation.objects.get(id=recalculation_id)+ assert recalc.total_metrics == 1+ assert recalc.metric_uuids == ["m1"]+ assert {r["metric_uuid"] for r in get_run_results(recalc)} == {"m1"}++ def test_counts_a_supported_metric_without_a_point_as_a_gap(self):+ exp = self._experiment("sync-gap", [_mean_metric("m1"), _mean_metric("m2")])+ self._timeseries_point(exp, "m1", IN_RUN, {"m": 1})++ recalculation_id = self._sync(exp)++ assert recalculation_id is not None+ recalc = ExperimentMetricsRecalculation.objects.get(id=recalculation_id)+ assert recalc.total_metrics == 2+ assert recalc.metric_uuids == ["m1", "m2"]+ assert {r["metric_uuid"] for r in get_run_results(recalc)} == {"m1"}++ @parameterized.expand(+ [+ ("point_before_this_run", BEFORE_RUN, None),+ ("point_in_the_future", IN_FUTURE, None),+ ("recalculation_already_newer", IN_RUN, LATER_IN_RUN),+ ]+ )+ def test_skips_when_no_point_qualifies_or_a_newer_run_exists(+ self, _name: str, point_query_to: datetime, existing_recalc_query_to: datetime | None+ ):+ exp = self._experiment(f"sync-skip-{_name}", [_mean_metric("m1")])+ self._timeseries_point(exp, "m1", point_query_to, {"m": 1})+ if existing_recalc_query_to is not None:+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ query_to=existing_recalc_query_to,+ completed_at=existing_recalc_query_to,+ )+ before = ExperimentMetricsRecalculation.objects.filter(experiment=exp).count()++ assert self._sync(exp) is None+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == before++ @parameterized.expand([("inline_workflow_first", False), ("saved_workflow_first", True)])+ def test_two_workflow_passes_fill_one_row_for_the_day(self, _name: str, saved_first: bool):+ exp = self._experiment(f"sync-two-{_name}", [_mean_metric("m1")])+ self._link_saved_metric(exp, "s1")+ inline_started, inline_point, inline_done = RUN_STARTED_AT, IN_RUN, IN_RUN + timedelta(seconds=30)+ saved_started = IN_RUN + timedelta(minutes=1)+ saved_point, saved_done = saved_started + timedelta(minutes=2), saved_started + timedelta(minutes=3)+ self._timeseries_point(exp, "m1", inline_point, {"m": 1})+ self._timeseries_point(exp, "s1", saved_point, {"s": 1})+ passes = [(inline_started, inline_done), (saved_started, saved_done)]+ if saved_first:+ passes.reverse()++ for run_started_at, now in passes:+ self._sync(exp, now=now, run_started_at=run_started_at)++ rows = ExperimentMetricsRecalculation.objects.filter(experiment=exp)+ assert rows.count() == 1+ recalc = rows.get()+ assert recalc.total_metrics == 2+ results = {r["metric_uuid"]: r["result"] for r in get_run_results(recalc)}+ assert results == {"m1": {"m": 1}, "s1": {"s": 1}}++ @parameterized.expand([("pending",), ("in_progress",)])+ def test_skips_while_a_user_run_is_active_without_a_window(self, status: str):+ exp = self._experiment(f"sync-active-{status}", [_mean_metric("m1")])+ self._timeseries_point(exp, "m1", IN_RUN, {"m": 1})+ ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=status,+ started_at=timezone.now() if status == "in_progress" else None,+ )++ assert self._sync(exp) is None+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1diff --git a/products/experiments/backend/timeseries_sync.py b/products/experiments/backend/timeseries_sync.pynew file mode 100644index 000000000000..23a4730ac24f--- /dev/null+++ b/products/experiments/backend/timeseries_sync.py@@ -0,0 +1,182 @@+"""Assemble a completed metrics recalculation from the timeseries points of one daily 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+metric whose newest completed point falls inside the run qualifies, and the copies land under one shared query_to so+the 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.+"""++from datetime import datetime, timedelta++from django.db import transaction+from django.db.models import Q+from django.utils import timezone++import structlog++from posthog.models.scoping import team_scope++from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint+from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.experiments.backend.recalculation import get_active_recalculation+from products.experiments.backend.temporal.metric_resolution import find_metric_dict, is_daily_timeseries_metric+from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint+from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics++logger = structlog.get_logger(__name__)++# The copies land one second past the newest point. A copy at a point's own query_to would share its+# (experiment, metric_uuid, query_to) key with the timeseries row and rewrite that row's fingerprint.+_WINDOW_OFFSET = timedelta(seconds=1)++# The two hourly workflows start within the same cron minute; yesterday's sync row is a day older.+_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.++ 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+ oldest 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.+ """+ now = now or timezone.now()+ with team_scope(team_id, canonical=True), transaction.atomic():+ try:+ # Same lock as request_recalculation and the calc result write; the two hourly workflows serialize+ # here so they see each other's row and share it instead of creating two. Taken on the initial read+ # so the metric config inspected below cannot go stale while waiting for the lock.+ experiment = Experiment.objects.select_for_update(no_key=True).get(+ id=experiment_id, team_id=team_id, deleted=False+ )+ except Experiment.DoesNotExist:+ return None+ if experiment.start_date is None:+ return None++ stats_method = get_experiment_stats_method(experiment)+ metric_uuids: list[str] = []+ points: dict[str, tuple[str, ExperimentMetricResult]] = {}+ for metric in discover_experiment_metrics(experiment):+ metric_dict = find_metric_dict(experiment, metric.metric_uuid)+ if metric_dict is None or not is_daily_timeseries_metric(metric_dict):+ continue+ metric_uuids.append(metric.metric_uuid)+ config_fp = compute_metric_fingerprint(+ metric_dict,+ experiment.start_date,+ stats_method,+ experiment.exposure_criteria,+ only_count_matured_users=experiment.only_count_matured_users,+ excluded_variants=experiment.excluded_variants,+ )+ row = (+ ExperimentMetricResult.objects.filter(+ experiment=experiment,+ metric_uuid=metric.metric_uuid,+ fingerprint=config_fp,+ status=ExperimentMetricResult.Status.COMPLETED,+ query_to__gte=run_started_at,+ query_to__lte=now,+ )+ .order_by("-query_to")+ .first()+ )+ if row is not None:+ points[metric.metric_uuid] = (compute_recalc_fingerprint(config_fp), row)++ if not points:+ return None++ oldest_point = min(row.query_to for _, row in points.values())+ newest_point = max(row.query_to for _, row in points.values())++ recalculation = (+ ExperimentMetricsRecalculation.objects.filter(+ experiment=experiment,+ trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,+ query_to__gte=run_started_at - _SAME_RUN_LOOKBACK,+ )+ .order_by("-query_to")+ .first()+ )+ if recalculation is not None and recalculation.query_to is not None:+ already_copied = set(+ ExperimentMetricResult.objects.filter(+ experiment=experiment, query_to=recalculation.query_to, metric_uuid__in=points.keys()+ ).values_list("metric_uuid", flat=True)+ )+ missing = {uuid: point for uuid, point in points.items() if uuid not in already_copied}+ if not missing:+ return None+ _copy_points(experiment, recalculation.query_to, missing, now)+ copied = len(missing)+ else:+ # A run that already reaches the oldest point covers this data. Trigger-failure tombstones never got+ # a window and are ignored. An active run has no window until its start activity stamps one, and+ # it would finish behind a sync row created now, so it counts as coverage too.+ already_covered = (+ ExperimentMetricsRecalculation.objects.filter(experiment=experiment, query_to__gte=oldest_point)+ .exclude(Q(status=ExperimentMetricsRecalculation.Status.FAILED) & Q(completed_at__isnull=True))+ .exists()+ )+ if already_covered or get_active_recalculation(experiment) is not None:+ return None++ recalculation = ExperimentMetricsRecalculation.objects.create(+ team=experiment.team,+ experiment=experiment,+ status=ExperimentMetricsRecalculation.Status.COMPLETED,+ trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,+ query_to=newest_point + _WINDOW_OFFSET,+ started_at=now,+ completed_at=now,+ total_metrics=len(metric_uuids),+ metric_uuids=metric_uuids,+ )+ _copy_points(experiment, newest_point + _WINDOW_OFFSET, points, now)+ copied = len(points)++ logger.info(+ "Synced timeseries points into a metrics recalculation",+ experiment_id=experiment_id,+ recalculation_id=str(recalculation.id),+ copied_metrics=copied,+ total_metrics=len(metric_uuids),+ )+ return str(recalculation.id)+++def _copy_points(+ experiment: Experiment,+ window: datetime,+ points: dict[str, tuple[str, ExperimentMetricResult]],+ now: datetime,+) -> None:+ for metric_uuid, (recalc_fp, row) in points.items():+ ExperimentMetricResult.objects.update_or_create(+ experiment=experiment,+ metric_uuid=metric_uuid,+ query_to=window,+ defaults={+ "fingerprint": recalc_fp,+ "query_from": experiment.start_date,+ "status": ExperimentMetricResult.Status.COMPLETED,+ "result": row.result,+ "query_id": None,+ "completed_at": now,+ "error_message": None,+ },+ )diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 28ed8a29fcab..a310a2913493 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -2132,6 +2132,7 @@ export interface ExperimentInSessionExposureApi {* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop* * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync*/export type ExperimentMetricsRecalculationTriggerEnumApi =(typeof ExperimentMetricsRecalculationTriggerEnumApi)[keyof typeof ExperimentMetricsRecalculationTriggerEnumApi]@@ -2148,6 +2149,7 @@ export const ExperimentMetricsRecalculationTriggerEnumApi = {ExperimentLaunch: 'experiment_launch',ExperimentStop: 'experiment_stop',ExperimentUpdate: 'experiment_update',+ TimeseriesSync: 'timeseries_sync',} as const/**@@ -2166,7 +2168,8 @@ export interface RecalculateMetricsRequestApi {* * `config_change` - Config Change* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop- * * `experiment_update` - Experiment Update */+ * * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync */trigger?: ExperimentMetricsRecalculationTriggerEnumApi}@@ -2284,7 +2287,8 @@ export interface ExperimentMetricsRecalculationApi {* * `config_change` - Config Change* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop- * * `experiment_update` - Experiment Update */+ * * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync */readonly trigger: ExperimentMetricsRecalculationTriggerEnumApi/** When the job was created */readonly created_at: stringdiff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.tsindex ad37ac7d3049..0df8dfd7d7ba 100644--- a/products/experiments/frontend/generated/api.zod.ts+++ b/products/experiments/frontend/generated/api.zod.ts@@ -1094,13 +1094,14 @@ export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod'experiment_launch','experiment_stop','experiment_update',+ 'timeseries_sync',]).describe(- '\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'+ '\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update\n\* `timeseries_sync` - Timeseries Sync').default(experimentsMetricsRecalculationCreateBodyTriggerDefault).describe(- 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'+ 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update\n\* `timeseries_sync` - Timeseries Sync'),}).describe('Request body for triggering a metrics recalculation.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7fba7f56bffc..2177952ebd79 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38787,6 +38787,7 @@ export namespace Schemas {* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop* * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync*/export type ExperimentMetricsRecalculationTriggerEnum = typeof ExperimentMetricsRecalculationTriggerEnum[keyof typeof ExperimentMetricsRecalculationTriggerEnum];@@ -38803,6 +38804,7 @@ export namespace Schemas {ExperimentLaunch: 'experiment_launch',ExperimentStop: 'experiment_stop',ExperimentUpdate: 'experiment_update',+ TimeseriesSync: 'timeseries_sync',} as const;/**@@ -38889,7 +38891,8 @@ export namespace Schemas {* * `config_change` - Config Change* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop- * * `experiment_update` - Experiment Update */+ * * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync */readonly trigger: ExperimentMetricsRecalculationTriggerEnum;/** When the job was created */readonly created_at: string;@@ -82285,7 +82288,8 @@ export namespace Schemas {* * `config_change` - Config Change* * `experiment_launch` - Experiment Launch* * `experiment_stop` - Experiment Stop- * * `experiment_update` - Experiment Update */+ * * `experiment_update` - Experiment Update+ * * `timeseries_sync` - Timeseries Sync */trigger?: ExperimentMetricsRecalculationTriggerEnum;}