: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): emit publish-outcome counter from hourly timeseries runs (#108324)
Juraj Majerik8807dcb83009
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.mdindex d0d69033aa8a..2e0bcf2382e1 100644--- a/posthog/temporal/experiments/README.md+++ b/posthog/temporal/experiments/README.md@@ -48,6 +48,8 @@ The experiment page reads results through `GET /metrics_recalculation/latest`, wEach 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.+Each run ends by emitting the `experiment_timeseries_publish_runs` Prometheus counter (labels: `workflow_type`, `status`), skipped when the run computed nothing. `status="missing"` means the run computed metrics but published zero recalculation rows - the silent-failure mode where results exist yet never reach users. One `missing` run can be legitimate (every row already covered by another run or a manual recalculation), so the Grafana alert thresholds over a window instead of firing per run.+```text┌────────────────────────────────────────────────────────────────────────────┐│ ExperimentRegularMetricsWorkflow │diff --git a/posthog/temporal/experiments/test_per_experiment_publish.py b/posthog/temporal/experiments/test_per_experiment_publish.pyindex f3346ebbaa04..9929c6461ecd 100644--- a/posthog/temporal/experiments/test_per_experiment_publish.py+++ b/posthog/temporal/experiments/test_per_experiment_publish.py@@ -2,6 +2,7 @@ import uuidimport asyncioimport pytest+from unittest.mock import patchimport temporalio.workerfrom temporalio import activity@@ -14,7 +15,7 @@ from posthog.temporal.experiments.models import (ExperimentSavedMetricResult,ExperimentSavedMetricsWorkflowInputs,)-from posthog.temporal.experiments.workflows import ExperimentSavedMetricsWorkflow+from posthog.temporal.experiments.workflows import ExperimentSavedMetricsWorkflow, _record_publish_outcomeFAST_EXPERIMENT = 101SLOW_EXPERIMENT = 102@@ -75,10 +76,16 @@ async def test_an_experiment_publishes_before_the_whole_batch_finishes():fast_published.set()return f"recalc-{experiment_id}"- result = await _run_workflow([mock_discover, mock_calculate, mock_publish])+ with patch("temporalio.workflow.metric_meter") as mock_meter:+ 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}+ # Asserted through the harness so the test fails if the workflow body stops calling the helper,+ # which would silently kill the missing-publish alert.+ mock_meter.return_value.with_additional_attributes.assert_called_once_with(+ {"workflow_type": "experiment-saved-metrics-workflow", "status": "published"}+ )@pytest.mark.asyncio@@ -157,3 +164,29 @@ async def test_a_failed_publish_skips_only_its_own_experiment():result = await _run_workflow([mock_discover, mock_calculate, mock_publish])assert result == {"hour": 2, "total": 2, "succeeded": 2, "failed": 0, "recalculations_synced": 1}+++ "succeeded,recalculations_synced,expected_status",+ [(2, 2, "published"), (2, 0, "missing"), (0, 0, None)],+)+def test_publish_outcome_counter_feeds_the_missing_publish_alert(+ succeeded: int, recalculations_synced: int, expected_status: str | None+) -> None:+ """The "missing" emission is the alert signal for runs that compute results users never see. A flipped+ condition kills the alert; emitting on runs that computed nothing floods it with false positives."""+ with (+ patch("temporalio.workflow.metric_meter") as mock_meter,+ patch("temporalio.workflow.info") as mock_info,+ ):+ mock_info.return_value.workflow_type = "experiment-saved-metrics-workflow"+ _record_publish_outcome(succeeded, recalculations_synced)++ if expected_status is None:+ mock_meter.assert_not_called()+ return+ with_attributes = mock_meter.return_value.with_additional_attributes+ with_attributes.assert_called_once_with(+ {"workflow_type": "experiment-saved-metrics-workflow", "status": expected_status}+ )+ with_attributes.return_value.create_counter.return_value.add.assert_called_once_with(1)diff --git a/posthog/temporal/experiments/workflows.py b/posthog/temporal/experiments/workflows.pyindex 656bcd63599a..a12b82081157 100644--- a/posthog/temporal/experiments/workflows.py+++ b/posthog/temporal/experiments/workflows.py@@ -26,6 +26,28 @@ with temporalio.workflow.unsafe.imports_passed_through():MAX_CONCURRENT_METRICS = 10+def _record_publish_outcome(succeeded: int, recalculations_synced: int) -> None:+ """Per-run counter behind the missing-publish alert: a run that computed metrics but published zero+ recalculation rows is the silent-failure mode where results exist yet never reach users.++ A single "missing" run can be legitimate (every row already covered by another run or a manual+ recalculation), so the threshold lives in the Grafana alert rule, not here. `workflow.metric_meter()`+ skips emission during replay, so no patch gate is needed."""+ if succeeded == 0:+ return+ status = "published" if recalculations_synced > 0 else "missing"+ try:+ temporalio.workflow.metric_meter().with_additional_attributes(+ {"workflow_type": temporalio.workflow.info().workflow_type, "status": status}+ ).create_counter(+ "experiment_timeseries_publish_runs",+ "Hourly experiment timeseries runs that computed metrics, by whether they published recalculation rows.",+ ).add(1)+ except Exception:+ # A meter failure must not fail a run whose calculations and publishes already finished.+ temporalio.workflow.logger.warning("Failed to record the publish outcome counter", exc_info=True)++async def _create_recalculations_from_timeseries(experiments: set[tuple[int, int]], run_started_at: datetime, semaphore: asyncio.Semaphore) -> int:@@ -195,6 +217,8 @@ class ExperimentRegularMetricsWorkflow(PostHogWorkflow):else:failed += 1+ _record_publish_outcome(succeeded, recalculations_synced)+return {"hour": inputs.hour,"total": len(experiment_metrics),@@ -288,6 +312,8 @@ class ExperimentSavedMetricsWorkflow(PostHogWorkflow):else:failed += 1+ _record_publish_outcome(succeeded, recalculations_synced)+return {"hour": inputs.hour,"total": len(experiment_metrics),