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): publish each experiment's daily results as soon as its metrics finish (#106496)

Juraj Majerike45c12b3b577
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.md
index d7eca8db4fcb..fbe5b2c803a9 100644
--- a/posthog/temporal/experiments/README.md
+++ b/posthog/temporal/experiments/README.md
@@ -32,13 +32,13 @@ There are two parallel workflow systems:
When a schedule triggers, it starts a workflow that:
1. Discovers which experiment-metric pairs need calculation
-2. Calculates each metric in parallel
+2. Calculates each experiment's metrics in parallel, under one hour-wide concurrency limit
3. Stores results in the database
-4. Assembles one completed metrics recalculation per experiment from the points this run wrote (see below)
+4. Assembles one completed metrics recalculation per experiment as soon as that experiment's own metrics finish (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`):
+The experiment page reads results through `GET /metrics_recalculation/latest`, which returns the newest completed `ExperimentMetricsRecalculation`. Timeseries rows alone never reach it, so each workflow runs `create_recalculation_from_timeseries` once per experiment it touched (`products/experiments/backend/timeseries_sync.py`). The publish runs right after the experiment's own metric activities complete, not behind a whole-hour barrier, so one slow experiment or a mid-batch worker restart delays only its own publish:
- 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.
diff --git a/posthog/temporal/experiments/test_per_experiment_publish.py b/posthog/temporal/experiments/test_per_experiment_publish.py
new file mode 100644
index 000000000000..f3346ebbaa04
--- /dev/null
+++ b/posthog/temporal/experiments/test_per_experiment_publish.py
@@ -0,0 +1,159 @@
+import uuid
+import asyncio
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from posthog.temporal.experiments.models import (
+ ExperimentSavedMetricInput,
+ ExperimentSavedMetricResult,
+ ExperimentSavedMetricsWorkflowInputs,
+)
+from posthog.temporal.experiments.workflows import ExperimentSavedMetricsWorkflow
+
+FAST_EXPERIMENT = 101
+SLOW_EXPERIMENT = 102
+
+
+async def _run_workflow(activities: list) -> dict:
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ExperimentSavedMetricsWorkflow],
+ activities=activities,
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ ExperimentSavedMetricsWorkflow.run,
+ ExperimentSavedMetricsWorkflowInputs(hour=2),
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+
+async def test_an_experiment_publishes_before_the_whole_batch_finishes():
+ """A slow experiment must not delay another experiment's publish. The slow experiment's metric only
+ completes after the fast experiment's publish activity ran, so a workflow that publishes behind a
+ whole-batch barrier fails this test (the fast publish then cannot run until the slow metric ends)."""
+ fast_published = asyncio.Event()
+ publish_calls: list[int] = []
+
+ @activity.defn(name="get_experiment_saved_metrics_for_hour")
+ async def mock_discover(hour: int) -> list[ExperimentSavedMetricInput]:
+ return [
+ ExperimentSavedMetricInput(
+ experiment_id=FAST_EXPERIMENT, metric_uuid="m-fast", fingerprint="f1", team_id=1
+ ),
+ ExperimentSavedMetricInput(
+ experiment_id=SLOW_EXPERIMENT, metric_uuid="m-slow", fingerprint="f2", team_id=1
+ ),
+ ]
+
+ @activity.defn(name="calculate_experiment_saved_metric")
+ async def mock_calculate(experiment_id: int, metric_uuid: str, fingerprint: str) -> ExperimentSavedMetricResult:
+ if experiment_id == SLOW_EXPERIMENT:
+ try:
+ await asyncio.wait_for(fast_published.wait(), timeout=15)
+ except TimeoutError:
+ raise ApplicationError("the fast experiment never published", non_retryable=True)
+ return ExperimentSavedMetricResult(
+ experiment_id=experiment_id, metric_uuid=metric_uuid, fingerprint=fingerprint, success=True
+ )
+
+ @activity.defn(name="create_recalculation_from_timeseries")
+ async def mock_publish(experiment_id: int, team_id: int, run_started_at: str) -> str | None:
+ publish_calls.append(experiment_id)
+ if experiment_id == FAST_EXPERIMENT:
+ fast_published.set()
+ return f"recalc-{experiment_id}"
+
+ result = await _run_workflow([mock_discover, mock_calculate, mock_publish])
+
+ assert publish_calls == [FAST_EXPERIMENT, SLOW_EXPERIMENT]
+ assert result == {"hour": 2, "total": 2, "succeeded": 2, "failed": 0, "recalculations_synced": 2}
+
+
+async def test_publish_does_not_wait_in_the_metric_semaphore_queue():
+ """Every metric task in the hour enqueues on the shared metric semaphore up front, and waiters are
+ served in order. A publish that waited in that queue would sit behind the whole remaining batch. Here
+ the batch saturates the ten metric slots and every slow metric only completes after the fast
+ experiment's publish, so a queued-behind-metrics publish deadlocks and fails via the timeout guard."""
+ fast_published = asyncio.Event()
+
+ @activity.defn(name="get_experiment_saved_metrics_for_hour")
+ async def mock_discover(hour: int) -> list[ExperimentSavedMetricInput]:
+ slow = [
+ ExperimentSavedMetricInput(
+ experiment_id=SLOW_EXPERIMENT, metric_uuid=f"m-slow-{i}", fingerprint=f"s{i}", team_id=1
+ )
+ for i in range(14)
+ ]
+ return [
+ ExperimentSavedMetricInput(
+ experiment_id=FAST_EXPERIMENT, metric_uuid="m-fast", fingerprint="f1", team_id=1
+ ),
+ *slow,
+ ]
+
+ @activity.defn(name="calculate_experiment_saved_metric")
+ async def mock_calculate(experiment_id: int, metric_uuid: str, fingerprint: str) -> ExperimentSavedMetricResult:
+ if experiment_id == SLOW_EXPERIMENT:
+ try:
+ await asyncio.wait_for(fast_published.wait(), timeout=15)
+ except TimeoutError:
+ raise ApplicationError("the fast experiment never published", non_retryable=True)
+ return ExperimentSavedMetricResult(
+ experiment_id=experiment_id, metric_uuid=metric_uuid, fingerprint=fingerprint, success=True
+ )
+
+ @activity.defn(name="create_recalculation_from_timeseries")
+ async def mock_publish(experiment_id: int, team_id: int, run_started_at: str) -> str | None:
+ if experiment_id == FAST_EXPERIMENT:
+ fast_published.set()
+ return f"recalc-{experiment_id}"
+
+ result = await _run_workflow([mock_discover, mock_calculate, mock_publish])
+
+ assert result == {"hour": 2, "total": 15, "succeeded": 15, "failed": 0, "recalculations_synced": 2}
+
+
+async def test_a_failed_publish_skips_only_its_own_experiment():
+ """One experiment's publish failing after its retries must not fail the workflow or block the other
+ experiments' publishes, or a single bad row would lose the whole hour's freshness."""
+
+ @activity.defn(name="get_experiment_saved_metrics_for_hour")
+ async def mock_discover(hour: int) -> list[ExperimentSavedMetricInput]:
+ return [
+ ExperimentSavedMetricInput(
+ experiment_id=FAST_EXPERIMENT, metric_uuid="m-fast", fingerprint="f1", team_id=1
+ ),
+ ExperimentSavedMetricInput(
+ experiment_id=SLOW_EXPERIMENT, metric_uuid="m-slow", fingerprint="f2", team_id=1
+ ),
+ ]
+
+ @activity.defn(name="calculate_experiment_saved_metric")
+ async def mock_calculate(experiment_id: int, metric_uuid: str, fingerprint: str) -> ExperimentSavedMetricResult:
+ return ExperimentSavedMetricResult(
+ experiment_id=experiment_id, metric_uuid=metric_uuid, fingerprint=fingerprint, success=True
+ )
+
+ @activity.defn(name="create_recalculation_from_timeseries")
+ async def mock_publish(experiment_id: int, team_id: int, run_started_at: str) -> str | None:
+ if experiment_id == FAST_EXPERIMENT:
+ raise ApplicationError("publish rejected", non_retryable=True)
+ return f"recalc-{experiment_id}"
+
+ result = await _run_workflow([mock_discover, mock_calculate, mock_publish])
+
+ assert result == {"hour": 2, "total": 2, "succeeded": 2, "failed": 0, "recalculations_synced": 1}
diff --git a/posthog/temporal/experiments/workflows.py b/posthog/temporal/experiments/workflows.py
index d11a51d24bd8..656bcd63599a 100644
--- a/posthog/temporal/experiments/workflows.py
+++ b/posthog/temporal/experiments/workflows.py
@@ -3,6 +3,7 @@ from datetime import datetime, timedelta
import temporalio.workflow
from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError
from posthog.temporal.common.base import PostHogWorkflow
@@ -28,7 +29,10 @@ 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."""
+ """One activity per (experiment, team) this run touched; returns how many recalculation rows gained copies.
+
+ Pre-patch publish pass, kept only so executions recorded before the per-experiment publish replay
+ deterministically."""
async def _sync_experiment(experiment_id: int, team_id: int) -> str | None:
async with semaphore:
@@ -46,6 +50,67 @@ async def _create_recalculations_from_timeseries(
return sum(1 for result in results if isinstance(result, str))
+async def _calculate_and_publish_per_experiment(
+ calculate_activity,
+ experiment_metrics,
+ run_started_at: datetime,
+ semaphore: asyncio.Semaphore,
+) -> tuple[list, int]:
+ """Calculate each experiment's metrics and publish its recalculation as soon as its own metrics finish.
+
+ Grouped per experiment so a slow experiment, or a worker restart mid-hour, delays only its own publish
+ instead of every experiment in the batch. Metric activities share the caller's semaphore, so query
+ concurrency is the same as one flat fan-out. Returns the per-metric results and the publish count.
+ """
+
+ async def _run_metric(em):
+ async with semaphore:
+ return await temporalio.workflow.execute_activity(
+ calculate_activity,
+ args=[em.experiment_id, em.metric_uuid, em.fingerprint],
+ start_to_close_timeout=timedelta(minutes=15),
+ retry_policy=RetryPolicy(
+ maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
+ initial_interval=timedelta(seconds=10),
+ maximum_interval=timedelta(seconds=60),
+ ),
+ )
+
+ groups: dict[tuple[int, int | None], list] = {}
+ for em in experiment_metrics:
+ groups.setdefault((em.experiment_id, em.team_id), []).append(em)
+
+ # Publishes get their own limit. Every metric task in the hour enqueues on the shared semaphore up
+ # front and waiters are served in order, so a publish waiting in that queue would sit behind the whole
+ # remaining batch, which recreates the end-of-hour barrier this function exists to remove.
+ publish_semaphore = asyncio.Semaphore(MAX_CONCURRENT_METRICS)
+
+ async def _run_experiment(experiment_id: int, team_id: int | None, metrics: list) -> tuple[list, bool]:
+ metric_results = await asyncio.gather(*[_run_metric(em) for em in metrics], return_exceptions=True)
+ if team_id is None:
+ return metric_results, False
+ try:
+ async with publish_semaphore:
+ synced = 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),
+ )
+ except ActivityError:
+ # A failed publish loses one experiment's freshness until the next run; it must not fail
+ # the rest of the hour's calculations.
+ return metric_results, False
+ return metric_results, isinstance(synced, str)
+
+ group_results = await asyncio.gather(
+ *[_run_experiment(experiment_id, team_id, metrics) for (experiment_id, team_id), metrics in groups.items()]
+ )
+ results = [result for metric_results, _ in group_results for result in metric_results]
+ published = sum(1 for _, synced in group_results if synced)
+ return results, published
+
+
@temporalio.workflow.defn(name="experiment-regular-metrics-workflow")
class ExperimentRegularMetricsWorkflow(PostHogWorkflow):
"""
@@ -53,9 +118,9 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):
Runs daily per hour (24 schedules total). Each run:
1. Discovers experiment-metrics for teams scheduled at this hour
- 2. Calculates each metric in parallel (one activity per metric)
- 3. Assembles a completed metrics recalculation per experiment from this run's points
- 4. Returns summary of successes/failures
+ 2. Per experiment: calculates its metrics in parallel (one activity per metric, shared concurrency
+ limit), then assembles its completed metrics recalculation from this run's points
+ 3. Returns summary of successes/failures
"""
@staticmethod
@@ -83,37 +148,42 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):
"recalculations_synced": 0,
}
- # Step 2: Calculate each metric with limited concurrency
+ # Step 2: Per experiment, calculate its metrics and publish its recalculation as soon as they
+ # finish, so a team's results land minutes after its own experiments compute instead of hours
+ # after the whole batch. The patch gates keep replay of older histories deterministic.
semaphore = asyncio.Semaphore(MAX_CONCURRENT_METRICS)
- async def _run_metric(em):
- async with semaphore:
- return await temporalio.workflow.execute_activity(
- calculate_experiment_regular_metric,
- args=[em.experiment_id, em.metric_uuid, em.fingerprint],
- start_to_close_timeout=timedelta(minutes=15),
- retry_policy=RetryPolicy(
- maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
- initial_interval=timedelta(seconds=10),
- maximum_interval=timedelta(seconds=60),
- ),
- )
-
- tasks = [_run_metric(em) for em in experiment_metrics]
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # 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,
+ if temporalio.workflow.patched("experiment-per-experiment-publish-2026-09"):
+ results, recalculations_synced = await _calculate_and_publish_per_experiment(
+ calculate_experiment_regular_metric, experiment_metrics, run_started_at, semaphore
)
+ else:
+
+ async def _run_metric(em):
+ async with semaphore:
+ return await temporalio.workflow.execute_activity(
+ calculate_experiment_regular_metric,
+ args=[em.experiment_id, em.metric_uuid, em.fingerprint],
+ start_to_close_timeout=timedelta(minutes=15),
+ retry_policy=RetryPolicy(
+ maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
+ initial_interval=timedelta(seconds=10),
+ maximum_interval=timedelta(seconds=60),
+ ),
+ )
+
+ tasks = [_run_metric(em) for em in experiment_metrics]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ 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: Summarize
+ # Step 3: Summarize
succeeded = 0
failed = 0
@@ -141,9 +211,9 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):
Runs daily per hour (24 schedules total). Each run:
1. Discovers experiment-saved metrics for teams scheduled at this hour
- 2. Calculates each metric in parallel (one activity per metric)
- 3. Assembles a completed metrics recalculation per experiment from this run's points
- 4. Returns summary of successes/failures
+ 2. Per experiment: calculates its metrics in parallel (one activity per metric, shared concurrency
+ limit), then assembles its completed metrics recalculation from this run's points
+ 3. Returns summary of successes/failures
"""
@staticmethod
@@ -171,37 +241,42 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):
"recalculations_synced": 0,
}
- # Step 2: Calculate each metric with limited concurrency
+ # Step 2: Per experiment, calculate its metrics and publish its recalculation as soon as they
+ # finish, so a team's results land minutes after its own experiments compute instead of hours
+ # after the whole batch. The patch gates keep replay of older histories deterministic.
semaphore = asyncio.Semaphore(MAX_CONCURRENT_METRICS)
- async def _run_metric(em):
- async with semaphore:
- return await temporalio.workflow.execute_activity(
- calculate_experiment_saved_metric,
- args=[em.experiment_id, em.metric_uuid, em.fingerprint],
- start_to_close_timeout=timedelta(minutes=15),
- retry_policy=RetryPolicy(
- maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
- initial_interval=timedelta(seconds=10),
- maximum_interval=timedelta(seconds=60),
- ),
- )
-
- tasks = [_run_metric(em) for em in experiment_metrics]
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # 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,
+ if temporalio.workflow.patched("experiment-per-experiment-publish-2026-09"):
+ results, recalculations_synced = await _calculate_and_publish_per_experiment(
+ calculate_experiment_saved_metric, experiment_metrics, run_started_at, semaphore
)
+ else:
+
+ async def _run_metric(em):
+ async with semaphore:
+ return await temporalio.workflow.execute_activity(
+ calculate_experiment_saved_metric,
+ args=[em.experiment_id, em.metric_uuid, em.fingerprint],
+ start_to_close_timeout=timedelta(minutes=15),
+ retry_policy=RetryPolicy(
+ maximum_attempts=TIMESERIES_METRIC_MAX_ATTEMPTS,
+ initial_interval=timedelta(seconds=10),
+ maximum_interval=timedelta(seconds=60),
+ ),
+ )
+
+ tasks = [_run_metric(em) for em in experiment_metrics]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ 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: Summarize
+ # Step 3: Summarize
succeeded = 0
failed = 0
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.md
index c21acdda5e08..3a5350794880 100644
--- a/products/experiments/backend/temporal/ARCHITECTURE.md
+++ b/products/experiments/backend/temporal/ARCHITECTURE.md
@@ -112,7 +112,7 @@ The snapshot is immutable only while the experiment is running, where each run p
A 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.
-`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`.
+`TIMESERIES_SYNC` is the one trigger no user or lifecycle event emits. The daily timeseries workflows write it as soon as each experiment's own 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.