: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
refactor(experiments): write metric results through one store (#109451)
Anders281aa5f8aaae
diff --git a/posthog/temporal/experiments/README.md b/posthog/temporal/experiments/README.mdindex 7ce1f53fe64e..ad6928c412fc 100644--- a/posthog/temporal/experiments/README.md+++ b/posthog/temporal/experiments/README.md@@ -35,6 +35,11 @@ When a schedule triggers, it starts a workflow that:2. Calculates each experiment's metrics in parallel, under one hour-wide concurrency limit3. Stores results in the database+Each metric activity stores its result through the experiments facade (`record_daily_metric_result`, `record_daily_metric_failure`).+The write looks the row up on `(experiment, metric_uuid, query_to)` and stores the calculation key as the row's fingerprint.+A row that already holds that window under another fingerprint, such as a recalculation result at the same window, is updated in place instead of failing on the unique constraint.+A failed write is the exception: it leaves a completed row under another fingerprint in place, so a transient failure cannot replace a recalculation result.+These workflows used to publish a `timeseries_sync` recalculation row per experiment as well.The scheduled recalculation workflow owns that job now, so the publish pass is gated out behind`experiment-drop-timeseries-publish-2026-10`.diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.pyindex 02611e99b39c..196d45bc6ec2 100644--- a/posthog/temporal/experiments/activities.py+++ b/posthog/temporal/experiments/activities.py@@ -39,6 +39,8 @@ from products.experiments.backend.facade.timeseries import (daily_inline_metric_calculations,daily_saved_metric_calculations,is_daily_timeseries_metric,+ record_daily_metric_failure,+ record_daily_metric_result,sync_timeseries_recalculation,)from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end@@ -48,11 +50,7 @@ from products.experiments.backend.hogql_queries.error_handling import ()from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import sanitize_non_finite-from products.experiments.backend.models.experiment import (- Experiment,- ExperimentMetricResult as ExperimentMetricResultModel,- ExperimentToSavedMetric,-)+from products.experiments.backend.models.experiment import Experiment, ExperimentToSavedMetricfrom products.experiments.stats.shared.statistics import StatisticErrorlogger = structlog.get_logger(__name__)@@ -208,21 +206,13 @@ def _calculate_experiment_regular_metric_sync(result = query_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)result_dict = sanitize_non_finite(result.model_dump(mode="json"))- completed_at = datetime.now(ZoneInfo("UTC"))-- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_result(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.COMPLETED,- "result": result_dict,- "query_id": None,- "completed_at": completed_at,- "error_message": None,- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ result=result_dict,)check_significance_transition(experiment, metric_uuid, fingerprint, result_dict, query_to_utc)@@ -241,19 +231,13 @@ def _calculate_experiment_regular_metric_sync()except (StatisticError, ZeroDivisionError) as e:- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_failure(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.FAILED,- "result": None,- "query_id": None,- "completed_at": None,- "error_message": str(e),- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ error_message=str(e),)logger.warning(@@ -288,19 +272,13 @@ def _calculate_experiment_regular_metric_sync(# doesn't retry and the worker interceptor doesn't report it to error tracking.is_permanent = classify_experiment_query_error(e) == "validation_error"- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_failure(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.FAILED,- "result": None,- "query_id": None,- "completed_at": None,- "error_message": str(e),- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ error_message=str(e),)if is_permanent:@@ -498,21 +476,13 @@ def _calculate_experiment_saved_metric_sync(result = query_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)result_dict = sanitize_non_finite(result.model_dump(mode="json"))- completed_at = datetime.now(ZoneInfo("UTC"))-- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_result(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.COMPLETED,- "result": result_dict,- "query_id": None,- "completed_at": completed_at,- "error_message": None,- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ result=result_dict,)check_significance_transition(experiment, metric_uuid, fingerprint, result_dict, query_to_utc)@@ -531,19 +501,13 @@ def _calculate_experiment_saved_metric_sync()except (StatisticError, ZeroDivisionError) as e:- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_failure(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.FAILED,- "result": None,- "query_id": None,- "completed_at": None,- "error_message": str(e),- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ error_message=str(e),)logger.warning(@@ -578,19 +542,13 @@ def _calculate_experiment_saved_metric_sync(# doesn't retry and the worker interceptor doesn't report it to error tracking.is_permanent = classify_experiment_query_error(e) == "validation_error"- ExperimentMetricResultModel.objects.update_or_create(- experiment_id=experiment_id,+ record_daily_metric_failure(+ experiment_id,metric_uuid=metric_uuid,- fingerprint=fingerprint,- query_to=query_to_utc,- defaults={- "query_from": query_from_utc,- "status": ExperimentMetricResultModel.Status.FAILED,- "result": None,- "query_id": None,- "completed_at": None,- "error_message": str(e),- },+ calculation_key=fingerprint,+ window=query_to_utc,+ query_from=query_from_utc,+ error_message=str(e),)if is_permanent:diff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.pyindex 5b72c3a5bb59..a79f3dfaa499 100644--- a/posthog/temporal/experiments/test_cache_warming.py+++ b/posthog/temporal/experiments/test_cache_warming.py@@ -34,11 +34,28 @@ from products.experiments.backend.models.experiment import (ExperimentToSavedMetric,)+# A recalculation of the experiment can hold the daily window under its own fingerprint. The daily write must take+# that row over instead of failing on the (experiment, metric_uuid, query_to) unique constraint.+_WINDOW_HOLDERS = [("free_window", None), ("window_held_by_another_fingerprint", "recalculation-fingerprint")]+@override_settings(IN_UNIT_TESTING=True)class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):+ def _hold_window(self, experiment_id: int, metric_uuid: str, query_to: datetime, fingerprint: str | None) -> None:+ if fingerprint is not None:+ ExperimentMetricResult.objects.create(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ fingerprint=fingerprint,+ query_from=datetime.fromisoformat("2020-01-01T00:00:00+00:00"),+ query_to=query_to,+ status=ExperimentMetricResult.Status.COMPLETED,+ result={"stale": True},+ )++ @parameterized.expand(_WINDOW_HOLDERS)@time_machine.travel("2020-01-10T12:00:00Z", tick=False)- def test_regular_metric_activity_pins_runner_to_stored_query_to(self):+ def test_regular_metric_activity_pins_runner_to_stored_query_to(self, _name: str, holder: str | None):feature_flag = self.create_feature_flag()experiment = self.create_experiment(feature_flag=feature_flag,@@ -50,6 +67,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):experiment.metrics = [metric_dict]experiment.save()expected_query_to = datetime.fromisoformat("2020-01-05T00:00:00+00:00")+ self._hold_window(experiment.id, metric_dict["uuid"], expected_query_to, holder)with (patch("posthog.temporal.experiments.activities.close_old_connections"),@@ -66,9 +84,11 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):assert mock_runner_class.call_args.kwargs["as_of"] == expected_query_toresult_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])assert result_row.query_to == expected_query_to+ assert (result_row.fingerprint, result_row.result) == ("fingerprint", {"variant_results": []})+ @parameterized.expand(_WINDOW_HOLDERS)@time_machine.travel("2020-01-10T12:00:00Z", tick=False)- def test_saved_metric_activity_pins_runner_to_stored_query_to(self):+ def test_saved_metric_activity_pins_runner_to_stored_query_to(self, _name: str, holder: str | None):feature_flag = self.create_feature_flag()experiment = self.create_experiment(feature_flag=feature_flag,@@ -90,6 +110,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):saved_metric=saved_metric,metadata={"type": "primary"},)+ self._hold_window(experiment.id, metric_dict["uuid"], expected_query_to, holder)with (patch("posthog.temporal.experiments.activities.close_old_connections"),@@ -106,6 +127,7 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):assert mock_runner_class.call_args.kwargs["as_of"] == expected_query_toresult_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])assert result_row.query_to == expected_query_to+ assert (result_row.fingerprint, result_row.result) == ("fingerprint", {"variant_results": []})@parameterized.expand([("creator_is_member", True), ("creator_left_organization", False)])@time_machine.travel("2020-01-10T12:00:00Z", tick=False)diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex b715a8845306..396dce8f51b1 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -87,7 +87,6 @@ from products.experiments.backend.models.experiment import (EXPOSURE_FROZEN_GROUP_MARKER,Experiment,ExperimentHoldout,- ExperimentMetricResult,ExperimentSavedMetric,ExperimentTimeseriesRecalculation,ExperimentToSavedMetric,@@ -4552,11 +4551,7 @@ class ExperimentService:metric_uuid = metric.get("uuid")if metric_uuid:- ExperimentMetricResult.objects.filter(- experiment_id=experiment.id,- metric_uuid=metric_uuid,- fingerprint=fingerprint,- ).delete()+ MetricResultStore(experiment_id=experiment.id).delete_daily_points(metric_uuid, fingerprint)recalculation_request = ExperimentTimeseriesRecalculation.objects.create(team=experiment.team,diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.pyindex eb4baa3c0510..d1fda80fb66d 100644--- a/products/experiments/backend/facade/timeseries.py+++ b/products/experiments/backend/facade/timeseries.py@@ -5,7 +5,11 @@ from products.experiments.backend.metric_calculation.keys import (daily_saved_metric_calculations,metric_calculation_keys,)-from products.experiments.backend.metric_calculation.results import previous_completed_metric_result+from products.experiments.backend.metric_calculation.results import (+ previous_completed_metric_result,+ record_daily_metric_failure,+ record_daily_metric_result,+)from products.experiments.backend.metric_resolution import (METRIC_BUILDERS,apply_saved_metric_overrides,@@ -26,6 +30,8 @@ __all__ = ["is_scheduled_metric","metric_calculation_keys","previous_completed_metric_result",+ "record_daily_metric_failure",+ "record_daily_metric_result","apply_saved_metric_overrides","sync_timeseries_recalculation",]diff --git a/products/experiments/backend/metric_calculation/results.py b/products/experiments/backend/metric_calculation/results.pyindex cb103b371e8c..b0e6fcae1c5e 100644--- a/products/experiments/backend/metric_calculation/results.py+++ b/products/experiments/backend/metric_calculation/results.py@@ -1,9 +1,9 @@-"""Reads of stored metric results.+"""Reads and writes of stored metric results.-`MetricResultStore` is the only reader of `ExperimentMetricResult`. Its named queries hide three storage-conventions from the callers:+`MetricResultStore` is the only module that reads or writes `ExperimentMetricResult`. Its named queries and writes+hide three storage conventions from the callers:-- A recalculation run files its rows under a salted calculation key (`compute_recalc_fingerprint`), and the daily+- A recalculation run files its rows under a salted calculation key (`_recalc_fingerprint`), and the dailytimeseries workflows file theirs under the bare key. So the two families never find each other's rows.- The timeseries sync copies daily points into a run one second past the newest point (`sync_copy_window`).- Every writer stores the experiment's start date in `query_from`. After a relaunch moves the start date forward,@@ -13,6 +13,11 @@ Several rows can share `(experiment, metric_uuid, query_to)` once the unique conquery that can meet such rows returns the one with the newest `completed_at`, then the highest id. It never looks arow up with `.get()` on that key. While the constraint holds, no two rows tie, so this order changes no result.+Every write looks the row up on `(experiment, metric_uuid, query_to)` and stores the fingerprint as an updated+field. A row that holds the window under another fingerprint is therefore updated in place, and no write can+violate the unique constraint or create a second row for a window. A daily failure is the exception: it leaves a+completed row under another fingerprint in place, because it has no result to replace that row with.+Every query filters on the experiment first, so the `(experiment, metric_uuid, query_to)` indexes serve it."""@@ -22,8 +27,12 @@ from datetime import date, datetime, timedeltafrom typing import Anyfrom zoneinfo import ZoneInfo+from django.db import transactionfrom django.db.models import F, QuerySetfrom django.db.models.fields.json import KT, KeyTransform+from django.utils import timezone as django_timezone++import structlogfrom posthog.dataclasses import frozen@@ -43,9 +52,16 @@ _RECALCULATION_SALT = "recalculation"_SYNC_COPY_OFFSET = timedelta(seconds=1)_COMPLETED = ExperimentMetricResult.Status.COMPLETED+_FAILED = ExperimentMetricResult.Status.FAILED++_TERMINAL_RECALC_STATUSES = frozenset(+ {ExperimentMetricsRecalculation.Status.COMPLETED, ExperimentMetricsRecalculation.Status.FAILED}+)+logger = structlog.get_logger(__name__)-def compute_recalc_fingerprint(config_fingerprint: str) -> str:++def _recalc_fingerprint(config_fingerprint: str) -> str:"""Fingerprint stamped onto ExperimentMetricResult rows written by the recalculation workflow.Returns a 64-char SHA256 hex digest derived solely from the config fingerprint plus a fixed salt, so it is@@ -103,7 +119,7 @@ class MetricResultStore:for calculation_config in build_calculation_configs(run.experiment)}fingerprints = [- compute_recalc_fingerprint(calculation_configs[metric_uuid].calculation_key())+ _recalc_fingerprint(calculation_configs[metric_uuid].calculation_key())for metric_uuid in run.metric_uuids or []if metric_uuid in calculation_configs]@@ -122,7 +138,7 @@ class MetricResultStore:experiment_id=self.experiment_id,metric_uuid=calculation_config.metric_id,query_to=window,- fingerprint=compute_recalc_fingerprint(calculation_config.calculation_key()),+ fingerprint=_recalc_fingerprint(calculation_config.calculation_key()),status=_COMPLETED,).exists()@@ -195,6 +211,205 @@ class MetricResultStore:).values_list("metric_uuid", flat=True))+ def record_run_result(+ self,+ recalculation_id: str,+ calculation_config: MetricCalculationConfig,+ *,+ window: datetime,+ query_from: datetime,+ result: dict[str, Any],+ query_id: str | None,+ ) -> None:+ """Store the completed result of one metric of a recalculation run, unless the run is terminal or missing."""+ self._record_for_run(+ recalculation_id,+ calculation_config,+ window=window,+ query_from=query_from,+ status=_COMPLETED,+ result=result,+ error_message=None,+ query_id=query_id,+ )++ def record_run_failure(+ self,+ recalculation_id: str,+ calculation_config: MetricCalculationConfig,+ *,+ window: datetime,+ query_from: datetime,+ error_message: str,+ query_id: str | None,+ ) -> None:+ """Store the failure of one metric of a recalculation run, unless the run is terminal or missing."""+ self._record_for_run(+ recalculation_id,+ calculation_config,+ window=window,+ query_from=query_from,+ status=_FAILED,+ result=None,+ error_message=error_message,+ query_id=query_id,+ )++ def record_daily_point(+ self, metric_uuid: str, calculation_key: str, *, window: datetime, query_from: datetime, result: dict[str, Any]+ ) -> None:+ """Store a completed daily point under the bare calculation key. The backfill stores its past days here too."""+ self._upsert(+ metric_uuid,+ window,+ fingerprint=calculation_key,+ query_from=query_from,+ status=_COMPLETED,+ result=result,+ error_message=None,+ query_id=None,+ completed_at=django_timezone.now(),+ )++ def record_daily_failure(+ self, metric_uuid: str, calculation_key: str, *, window: datetime, query_from: datetime, error_message: str+ ) -> None:+ """Store a failed daily point under the bare calculation key, unless a completed row under another+ fingerprint holds the window.++ That row is usually a recalculation of a stopped experiment, because a late daily run and the recalculation+ both use `end_date`. The run finds its row only by the salted key, and a failure has no result to put in its+ place, so the store keeps the row and drops the failure. A completed point under the same key gets the+ failure, so the timeseries shows the latest attempt at that window.+ """+ self._upsert(+ metric_uuid,+ window,+ fingerprint=calculation_key,+ query_from=query_from,+ status=_FAILED,+ result=None,+ error_message=error_message,+ query_id=None,+ completed_at=None,+ keep_completed_row_of_other_fingerprint=True,+ )++ def copy_into_sync_run(+ self,+ window: datetime,+ points: Iterable[tuple[MetricCalculationConfig, ExperimentMetricResult]],+ *,+ query_from: datetime,+ completed_at: datetime,+ ) -> None:+ """Copy daily points into a timeseries sync run at its window, under the salted keys a run read looks for."""+ for calculation_config, point in points:+ self._upsert(+ calculation_config.metric_id,+ window,+ fingerprint=_recalc_fingerprint(calculation_config.calculation_key()),+ query_from=query_from,+ status=_COMPLETED,+ result=point.result,+ error_message=None,+ query_id=None,+ completed_at=completed_at,+ )++ def delete_daily_points(self, metric_uuid: str, calculation_key: str) -> None:+ """Delete every row of a metric under the bare calculation key, which holds its daily and backfilled points."""+ ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id, metric_uuid=metric_uuid, fingerprint=calculation_key+ ).delete()++ def _record_for_run(+ self,+ recalculation_id: str,+ calculation_config: MetricCalculationConfig,+ *,+ window: datetime,+ query_from: datetime,+ status: str,+ result: dict[str, Any] | None,+ error_message: str | None,+ query_id: str | None,+ ) -> None:+ team_id = calculation_config.settings.team_id+ with transaction.atomic():+ # Match request_recalculation's lock order; result inserts also take an experiment FK lock.+ Experiment.objects.select_for_update(no_key=True).filter(id=self.experiment_id, team_id=team_id).exists()+ current_status = (+ ExperimentMetricsRecalculation.objects.select_for_update()+ .filter(id=recalculation_id, experiment_id=self.experiment_id, team_id=team_id)+ .values_list("status", flat=True)+ .first()+ )+ if current_status is None or current_status in _TERMINAL_RECALC_STATUSES:+ logger.warning(+ "Skipping experiment metric result write for a terminal or missing recalculation",+ recalculation_id=recalculation_id,+ metric_uuid=calculation_config.metric_id,+ recalculation_status=current_status,+ )+ return++ self._upsert(+ calculation_config.metric_id,+ window,+ fingerprint=_recalc_fingerprint(calculation_config.calculation_key()),+ query_from=query_from,+ status=status,+ result=result,+ error_message=error_message,+ query_id=query_id,+ completed_at=django_timezone.now() if status == _COMPLETED else None,+ )++ def _upsert(+ self,+ metric_uuid: str,+ window: datetime,+ *,+ fingerprint: str,+ query_from: datetime,+ status: str,+ result: dict[str, Any] | None,+ error_message: str | None,+ query_id: str | None,+ completed_at: datetime | None,+ keep_completed_row_of_other_fingerprint: bool = False,+ ) -> None:+ fields: dict[str, Any] = {+ "fingerprint": fingerprint,+ "query_from": query_from,+ "status": status,+ "result": result,+ "query_id": query_id,+ "completed_at": completed_at,+ "error_message": error_message,+ }+ with transaction.atomic():+ # Upsert on the true unique key (experiment, metric_uuid, query_to); fingerprint goes in the updated fields+ # so a row already occupying that key under a different fingerprint is updated in place, not inserted as a+ # colliding duplicate. When a concurrent write inserts the row first, get_or_create locks that row instead.+ row, created = ExperimentMetricResult.objects.select_for_update().get_or_create(+ experiment_id=self.experiment_id, metric_uuid=metric_uuid, query_to=window, defaults=fields+ )+ if created:+ return+ if keep_completed_row_of_other_fingerprint and row.status == _COMPLETED and row.fingerprint != fingerprint:+ logger.info(+ "Keeping a completed experiment metric result that another fingerprint holds",+ experiment_id=self.experiment_id,+ metric_uuid=metric_uuid,+ query_to=window,+ )+ return+ for name, value in fields.items():+ setattr(row, name, value)+ row.save(update_fields=[*fields, "updated_at"])+@staticmethoddef sync_copy_window(newest_point: datetime) -> datetime:"""The query_to of a timeseries sync run and of the copies it holds, for daily points up to `newest_point`."""@@ -256,3 +471,33 @@ def previous_completed_metric_result(return Nonerow = MetricResultStore(experiment_id=experiment_id).previous_completed(metric_uuid, calculation_key, before=before)return row.result if row is not None else None+++def record_daily_metric_result(+ experiment_id: int,+ *,+ metric_uuid: str,+ calculation_key: str,+ window: datetime,+ query_from: datetime,+ result: dict[str, Any],+) -> None:+ """Store a completed daily point, for the scheduled workflows outside the product."""+ MetricResultStore(experiment_id=experiment_id).record_daily_point(+ metric_uuid, calculation_key, window=window, query_from=query_from, result=result+ )+++def record_daily_metric_failure(+ experiment_id: int,+ *,+ metric_uuid: str,+ calculation_key: str,+ window: datetime,+ query_from: datetime,+ error_message: str,+) -> None:+ """Store a failed daily point, for the scheduled workflows outside the product."""+ MetricResultStore(experiment_id=experiment_id).record_daily_failure(+ metric_uuid, calculation_key, window=window, query_from=query_from, error_message=error_message+ )diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 32bdc1779fa8..2fe13f534df1 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -70,7 +70,7 @@ Every metric in a single recalc shares one `query_to` timestamp, stamped by the### Recalc fingerprint, not config fingerprint-Every result row is keyed by a `recalc_fp = sha256(config_fp + "recalculation")` (`compute_recalc_fingerprint` in `metric_calculation/results.py`). The config part is the calculation key that the daily timeseries workflows use too: `MetricCalculationConfig.calculation_key()` in `metric_calculation/config.py`. The calculation config holds everything the calculation reads, but key version 1 hashes only the effective metric definition, the start date, the stats method, the stored exposure criteria, maturity and the excluded variants. The salt is a fixed string, so the recalc fingerprint is deterministic per config, not per run.+Every result row is keyed by a `recalc_fp = sha256(config_fp + "recalculation")` (`_recalc_fingerprint` in `metric_calculation/results.py`). The config part is the calculation key that the daily timeseries workflows use too: `MetricCalculationConfig.calculation_key()` in `metric_calculation/config.py`. The calculation config holds everything the calculation reads, but key version 1 hashes only the effective metric definition, the start date, the stats method, the stored exposure criteria, maturity and the excluded variants. The salt is a fixed string, so the recalc fingerprint is deterministic per config, not per run.This matters because the recalc workflow shares the `ExperimentMetricResult` table with the timeseries workflows. If we used the config fingerprint, every recalc would overwrite the cached daily timeseries row, wrecking the timeseries reads. The constant salt keeps the recalc family distinct from the timeseries family on the same table, so they never collide.@@ -100,9 +100,15 @@ The snapshot for such an experiment is the one row at `end_date` for the currentThe trade-off: reads have to recompute the fingerprint set to find a run's results (`MetricResultStore.for_run` walks each metric, recomputes its `config_fp`, applies the recalc salt, then `WHERE fingerprint IN (...) AND query_to = recalc.query_to`). If the experiment's `start_date` / `exposure_criteria` / stats config changes between the write and the read, the recomputed fingerprints don't match the on-disk ones, and results "disappear." Documented inline as the fingerprint-divergence hazard.-Every read of `ExperimentMetricResult` goes through the named queries of `MetricResultStore` (`metric_calculation/results.py`), so the salt, the sync's copy window and the relaunch rule on `query_from` stay in one module.+Every read and write of `ExperimentMetricResult` goes through `MetricResultStore` (`metric_calculation/results.py`), so the salt, the sync's copy window and the relaunch rule on `query_from` stay in one module.When several rows share `(experiment, metric_uuid, query_to)`, each query returns the row with the newest `completed_at`, then the highest id.The unique constraint on that key allows only one row, so this order decides nothing until the constraint goes.+Every writer (the calc activity, the daily activities, the backfill and the timeseries sync) looks the row up on `(experiment, metric_uuid, query_to)` and stores its fingerprint as an updated field.+A row that holds the window under another fingerprint is therefore updated in place, so no write can fail on the unique constraint or create a second row for a window.+A daily write and a recalculation share a window only when an experiment stops while its daily run is in flight, so both use `end_date`.+A successful daily write then takes over the recalculation's row, and the next reload recomputes that metric.+A failed daily write leaves a completed row under another fingerprint in place, because it has no result to replace it with.+The calc activity's write keeps its lock order and its terminal-run guard (see [cancellation and result-write protection](../../../../docs/internal/experiment-metric-recalculation.md)).### Counters are derived, not storeddiff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 319d89430533..aea0802daa73 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -40,13 +40,9 @@ from products.experiments.backend.hogql_queries.error_handling import (from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import sanitize_non_finitefrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import MetricResultStore, compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.metric_resolution import build_metric, get_metrics_for_calculation-from products.experiments.backend.models.experiment import (- Experiment,- ExperimentMetricResult,- ExperimentMetricsRecalculation,-)+from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculationfrom products.experiments.backend.temporal.models import (CAPACITY_MAX_METRIC_ATTEMPTS,CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS,@@ -69,11 +65,6 @@ logger = structlog.get_logger(__name__)# Cap stored/returned error messages so a pathological traceback can't bloat the Temporal payload (~2 MiB cap)._MAX_ERROR_MESSAGE_LENGTH = 2000-_TERMINAL_RECALC_STATUSES = frozenset(- {ExperimentMetricsRecalculation.Status.COMPLETED, ExperimentMetricsRecalculation.Status.FAILED}-)--# ---------------------------------------------------------------------------# Discovery# ---------------------------------------------------------------------------@@ -497,56 +488,6 @@ def _clear_retry(recalculation_id: str, metric_uuid: str) -> None:recalc.save(update_fields=["metric_retries"])-def _store_result(- *,- recalculation_id: str,- experiment_id: int,- metric_uuid: str,- recalc_fp: str,- query_from: datetime,- query_to: datetime,- status: str,- result: dict | None,- error_message: str | None,- query_id: str | None = None,-) -> None:- with transaction.atomic():- # Match request_recalculation's lock order; result inserts also take an experiment FK lock.- Experiment.objects.select_for_update(no_key=True).filter(id=experiment_id).exists()- current_status = (- ExperimentMetricsRecalculation.objects.select_for_update()- .filter(id=recalculation_id, experiment_id=experiment_id)- .values_list("status", flat=True)- .first()- )- if current_status is None or current_status in _TERMINAL_RECALC_STATUSES:- logger.warning(- "Skipping experiment metric result write for a terminal or missing recalculation",- recalculation_id=recalculation_id,- metric_uuid=metric_uuid,- recalculation_status=current_status,- )- return-- # Upsert on the true unique key (experiment, metric_uuid, query_to); fingerprint goes in defaults so a row- # already occupying that key under a different fingerprint is updated in place, not inserted as a colliding- # duplicate. This heals rows written under the old per-run fingerprint scheme.- ExperimentMetricResult.objects.update_or_create(- experiment_id=experiment_id,- metric_uuid=metric_uuid,- query_to=query_to,- defaults={- "fingerprint": recalc_fp,- "query_from": query_from,- "status": status,- "result": result,- "query_id": query_id,- "completed_at": timezone.now() if status == ExperimentMetricResult.Status.COMPLETED else None,- "error_message": error_message,- },- )--def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str, *, error_type: str) -> MetricRecalculationResult:@@ -739,11 +680,11 @@ def _calculate_experiment_metric_for_recalculation_sync(error_type="validation_error",)- recalc_fp = compute_recalc_fingerprint(calculation_config.calculation_key())+ results = MetricResultStore(experiment_id=experiment_id)# Skip the query if this metric is already computed for this exact config and window; a config change# changes the fingerprint, so a stale result won't match and recomputes.- if MetricResultStore(experiment_id=experiment_id).has_completed(calculation_config, window=query_to_dt):+ if results.has_completed(calculation_config, window=query_to_dt):# A crash between the result write and the retry cleanup on a prior attempt lands here on the# next one; clear so a completed metric can't keep reporting as retrying._clear_retry(recalculation_id, metric_uuid)@@ -755,15 +696,11 @@ def _calculate_experiment_metric_for_recalculation_sync(query_from = experiment.start_datedef record_terminal_error(message: str, error_type: str, *, retriable: bool) -> None:- _store_result(- recalculation_id=recalculation_id,- experiment_id=experiment_id,- metric_uuid=metric_uuid,- recalc_fp=recalc_fp,+ results.record_run_failure(+ recalculation_id,+ calculation_config,+ window=query_to_dt,query_from=query_from,- query_to=query_to_dt,- status=ExperimentMetricResult.Status.FAILED,- result=None,error_message=message,query_id=client_query_id,)@@ -814,16 +751,12 @@ def _calculate_experiment_metric_for_recalculation_sync(result = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)result_dict = sanitize_non_finite(result.model_dump(mode="json"))- _store_result(- recalculation_id=recalculation_id,- experiment_id=experiment_id,- metric_uuid=metric_uuid,- recalc_fp=recalc_fp,- query_from=experiment.start_date,- query_to=query_to_dt,- status=ExperimentMetricResult.Status.COMPLETED,+ results.record_run_result(+ recalculation_id,+ calculation_config,+ window=query_to_dt,+ query_from=query_from,result=result_dict,- error_message=None,query_id=client_query_id,)_capture_experiment_metric_event(@@ -841,15 +774,11 @@ def _calculate_experiment_metric_for_recalculation_sync(except (StatisticError, ZeroDivisionError) as e:# Expected "not enough data" style failures — warn, no exception capture.message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]- _store_result(- recalculation_id=recalculation_id,- experiment_id=experiment_id,- metric_uuid=metric_uuid,- recalc_fp=recalc_fp,- query_from=experiment.start_date,- query_to=query_to_dt,- status=ExperimentMetricResult.Status.FAILED,- result=None,+ results.record_run_failure(+ recalculation_id,+ calculation_config,+ window=query_to_dt,+ query_from=query_from,error_message=message,query_id=client_query_id,)diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex babd907cc690..a86bda426054 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -21,7 +21,7 @@ from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitEfrom posthog.temporal.common.errors import NonReportableErrorfrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -41,7 +41,6 @@ from products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,_cancel_metric_query_sync,_discover_experiment_metrics_sync,- _store_result,_update_recalculation_progress_sync,)from products.experiments.stats.shared.statistics import StatisticError@@ -998,7 +997,7 @@ class TestCalculateActivity(BaseTest):def test_query_from_matches_experiment_start_date_on_result_row(self):# Companion to test_query_to_is_passed_as_as_of_to_runner: the lower bound of the run's# time window is experiment.start_date, threaded into the runner via the experiment object it- # constructs and stored on the result row via _store_result(query_from=experiment.start_date).+ # constructs and stored on the result row by the result store's run write (query_from=experiment.start_date).# This test pins the stored-row side. If the runner ever changes how it derives query_from, or if a# future refactor decouples the stored value from what the runner actually queries, the same class# of silent-miscalculation bug we just fixed for query_to could reappear here.@@ -1051,7 +1050,7 @@ class TestCalculateActivity(BaseTest):metric = _mean_metric("m1")exp = self._experiment(flag_key="calc-skip-existing", metrics=[metric])query_to = datetime.fromisoformat(_QUERY_TO)- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))existing = ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m1",@@ -1110,7 +1109,7 @@ class TestCalculateActivity(BaseTest):metric = _mean_metric("m1")exp = self._experiment(flag_key="calc-excluded", metrics=[metric])query_to = datetime.fromisoformat(_QUERY_TO)- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m1",@@ -1130,84 +1129,6 @@ class TestCalculateActivity(BaseTest):mock_runner.assert_called_once()- def test_store_result_updates_existing_row_with_different_fingerprint_in_place(self):- # The unique constraint is (experiment, metric_uuid, query_to); fingerprint is not part of it. A row may- # already occupy that key under a different fingerprint (an earlier run written under the old per-run- # scheme, or the timeseries workflow). _store_result must update that row in place, not insert a second- # one and crash with IntegrityError. This is what unsticks experiments already collided in production.- exp = self._experiment(flag_key="store-upsert-key", metrics=[_mean_metric("m1")])- recalc = self._recalc(exp, metric_uuids=["m1"])- query_to = datetime.fromisoformat(_QUERY_TO)- ExperimentMetricResult.objects.create(- experiment=exp,- metric_uuid="m1",- fingerprint="legacy-fingerprint-from-a-prior-run",- query_from=query_to,- query_to=query_to,- status=ExperimentMetricResult.Status.COMPLETED,- result={"stale": True},- )-- _store_result(- recalculation_id=str(recalc.id),- experiment_id=exp.id,- metric_uuid="m1",- recalc_fp="new-deterministic-fingerprint",- query_from=query_to,- query_to=query_to,- status=ExperimentMetricResult.Status.COMPLETED,- result={"fresh": True},- error_message=None,- )-- rows = ExperimentMetricResult.objects.filter(experiment=exp, metric_uuid="m1", query_to=query_to)- assert rows.count() == 1- row = rows.get()- assert row.fingerprint == "new-deterministic-fingerprint"- assert row.result == {"fresh": True}-- @parameterized.expand(- [- (ExperimentMetricsRecalculation.Status.FAILED,),- (ExperimentMetricsRecalculation.Status.COMPLETED,),- (None,),- ]- )- def test_store_result_skips_a_terminal_or_missing_recalculation(self, status: str | None) -> None:- exp = self._experiment(flag_key="store-superseded", metrics=[_mean_metric("m1")])- recalc = self._recalc(exp, metric_uuids=["m1"])- if status is None:- ExperimentMetricsRecalculation.objects.filter(id=recalc.id).delete()- else:- ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(status=status)- query_to = datetime.fromisoformat(_QUERY_TO)- ExperimentMetricResult.objects.create(- experiment=exp,- metric_uuid="m1",- fingerprint="fingerprint-from-the-superseding-run",- query_from=query_to,- query_to=query_to,- status=ExperimentMetricResult.Status.COMPLETED,- result={"fresh": True},- )-- _store_result(- recalculation_id=str(recalc.id),- experiment_id=exp.id,- metric_uuid="m1",- recalc_fp="fingerprint-from-the-orphaned-run",- query_from=query_to,- query_to=query_to,- status=ExperimentMetricResult.Status.FAILED,- result=None,- error_message="the orphan's late failure",- )-- row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1", query_to=query_to)- assert row.status == ExperimentMetricResult.Status.COMPLETED- assert row.result == {"fresh": True}- assert row.error_message is None-@parameterized.expand([# (name, metric_uuid, metrics_on_experiment, run_with_mocked_failure, expected_result_rows)@@ -1222,9 +1143,9 @@ class TestCalculateActivity(BaseTest):def test_retry_does_not_double_count(self, name: str, metric_uuid: str, metrics: list, mock_runner_failure: bool, expected_result_rows: int):- # Temporal retries the whole activity on transient failure. _store_result is idempotent (update_or_create- # keyed on fingerprint + query_to) and metric_errors is keyed by metric_uuid, so a second run must leave- # state identical to the first — no inflated counts, no duplicate result rows.+ # Temporal retries the whole activity on transient failure. The run write is idempotent (update_or_create+ # keyed on experiment, metric_uuid and query_to) and metric_errors is keyed by metric_uuid, so a second run+ # must leave state identical to the first — no inflated counts, no duplicate result rows.exp = self._experiment(flag_key=f"retry-{name}", metrics=metrics)recalc = self._recalc(exp, metric_uuids=[metric_uuid])@@ -1247,7 +1168,7 @@ class TestCalculateActivity(BaseTest):recalc.refresh_from_db()assert len(recalc.metric_errors) == 1assert metric_uuid in recalc.metric_errors- # Exact count per case: 0 for discovery failures (no _store_result call), 1 for calc failures+ # Exact count per case: 0 for discovery failures (no result write), 1 for calc failures# (one FAILED row, overwritten on retry rather than duplicated).assert (ExperimentMetricResult.objects.filter(experiment=exp, metric_uuid=metric_uuid).count()diff --git a/products/experiments/backend/temporal/test_recalculation_concurrency.py b/products/experiments/backend/temporal/test_recalculation_concurrency.pyindex f39e5f3b3e79..db21aad48e1b 100644--- a/products/experiments/backend/temporal/test_recalculation_concurrency.py+++ b/products/experiments/backend/temporal/test_recalculation_concurrency.py@@ -13,13 +13,14 @@ from django.utils import timezonefrom posthog.models import Team, Userfrom posthog.models.scoping import team_scope+from products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,ExperimentMetricsRecalculation,)from products.experiments.backend.recalculation import request_recalculation-from products.experiments.backend.temporal.recalculation_logic import _store_resultfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -37,7 +38,17 @@ def test_superseded_result_cannot_overwrite_a_replacement_during_commit(feature_flag=FeatureFlag.objects.create(team=team, key="concurrent-recalculation"),start_date=query_from,end_date=query_to,+ metrics=[+ {+ "uuid": "m1",+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ ],)+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not Nonestale = ExperimentMetricsRecalculation.objects.for_team(team.id).create(team=team,experiment=experiment,@@ -58,16 +69,13 @@ def test_superseded_result_cannot_overwrite_a_replacement_during_commit(with team_scope(team.id, canonical=True), connection.cursor() as cursor:cursor.execute("SELECT pg_backend_pid()")worker_pid.put(cursor.fetchone()[0])- _store_result(- recalculation_id=str(stale.id),- experiment_id=experiment.id,- metric_uuid="m1",- query_to=query_to,- recalc_fp="stale",+ MetricResultStore(experiment_id=experiment.id).record_run_failure(+ str(stale.id),+ calculation_config,+ window=query_to,query_from=query_from,- status=ExperimentMetricResult.Status.FAILED,- result=None,error_message="abandoned calculation failed",+ query_id=None,)finally:connections.close_all()diff --git a/products/experiments/backend/test/test_metric_result_store.py b/products/experiments/backend/test/test_metric_result_store.pyindex 96588194950c..9d9648dbb563 100644--- a/products/experiments/backend/test/test_metric_result_store.py+++ b/products/experiments/backend/test/test_metric_result_store.py@@ -14,7 +14,7 @@ from products.experiments.backend.metric_calculation.config import ()from products.experiments.backend.metric_calculation.results import (MetricResultStore,- compute_recalc_fingerprint,+ _recalc_fingerprint,previous_completed_metric_result,)from products.experiments.backend.models.experiment import (@@ -35,22 +35,22 @@ def test_recalc_fingerprint_is_deterministic_for_a_given_config():# pins the same query_to, so a run-dependent fingerprint produced a new value each run and collided on the# (experiment, metric_uuid, query_to) unique constraint. Same config in, same fingerprint out, every run.config_fp = "a" * 64- assert compute_recalc_fingerprint(config_fp) == compute_recalc_fingerprint(config_fp)+ assert _recalc_fingerprint(config_fp) == _recalc_fingerprint(config_fp)def test_recalc_fingerprint_differs_from_the_bare_config_fingerprint():# It must stay distinct from the config fingerprint the timeseries workflow stores, so recalc rows never# leak into the timeseries read (which filters by the bare config fingerprint).config_fp = "b" * 64- assert compute_recalc_fingerprint(config_fp) != config_fp+ assert _recalc_fingerprint(config_fp) != config_fpdef test_recalc_fingerprint_differs_per_config():- assert compute_recalc_fingerprint("c" * 64) != compute_recalc_fingerprint("d" * 64)+ assert _recalc_fingerprint("c" * 64) != _recalc_fingerprint("d" * 64)def test_recalc_fingerprint_is_sha256_hex_length():- assert len(compute_recalc_fingerprint("e" * 64)) == 64+ assert len(_recalc_fingerprint("e" * 64)) == 64def _stored_result(samples: int) -> dict[str, Any]:@@ -138,7 +138,7 @@ class TestMetricResultStore(BaseTest):calculation_config = get_metric_calculation_config(experiment, "m1")assert calculation_config is not Nonefingerprint = (- compute_recalc_fingerprint(calculation_config.calculation_key())+ _recalc_fingerprint(calculation_config.calculation_key())if reader == "for_run"else calculation_config.calculation_key())@@ -191,3 +191,134 @@ class TestMetricResultStore(BaseTest):)assert result == (_stored_result(7) if own_team else None)++ def _run(self, experiment: Experiment, status: str) -> ExperimentMetricsRecalculation:+ return ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=experiment, metric_uuids=["m1"], status=status, query_to=_WINDOW+ )++ def _write(self, writer: str, experiment: Experiment, calculation_config: MetricCalculationConfig) -> None:+ store = MetricResultStore(experiment_id=experiment.id)+ key = calculation_config.calculation_key()+ match writer:+ case "run_result":+ run = self._run(experiment, ExperimentMetricsRecalculation.Status.IN_PROGRESS)+ store.record_run_result(+ str(run.id),+ calculation_config,+ window=_WINDOW,+ query_from=_START,+ result=_stored_result(9),+ query_id="q",+ )+ case "run_failure":+ run = self._run(experiment, ExperimentMetricsRecalculation.Status.IN_PROGRESS)+ store.record_run_failure(+ str(run.id),+ calculation_config,+ window=_WINDOW,+ query_from=_START,+ error_message="boom",+ query_id="q",+ )+ case "daily_point":+ store.record_daily_point("m1", key, window=_WINDOW, query_from=_START, result=_stored_result(9))+ case "daily_failure":+ store.record_daily_failure("m1", key, window=_WINDOW, query_from=_START, error_message="boom")+ case "sync_copy":+ point = ExperimentMetricResult(result=_stored_result(9))+ store.copy_into_sync_run(+ _WINDOW, [(calculation_config, point)], query_from=_START, completed_at=_WINDOW+ )+ case _:+ raise AssertionError(f"unknown writer {writer}")++ @parameterized.expand(+ [+ ("run_result", True, ExperimentMetricResult.Status.COMPLETED),+ ("run_failure", True, ExperimentMetricResult.Status.FAILED),+ ("daily_point", False, ExperimentMetricResult.Status.COMPLETED),+ ("sync_copy", True, ExperimentMetricResult.Status.COMPLETED),+ ]+ )+ def test_a_write_takes_over_the_row_that_holds_its_window_under_another_fingerprint(+ self, writer: str, salted: bool, status: str+ ) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ self._row(experiment, "another-fingerprint", query_to=_WINDOW, completed_at=_WINDOW, samples=1)++ self._write(writer, experiment, calculation_config)++ row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid="m1", query_to=_WINDOW)+ key = calculation_config.calculation_key()+ assert row.fingerprint == (_recalc_fingerprint(key) if salted else key)+ assert row.status == status+ if status == ExperimentMetricResult.Status.COMPLETED:+ assert (row.result, row.error_message) == (_stored_result(9), None)+ else:+ assert (row.result, row.error_message, row.completed_at) == (None, "boom", None)++ @parameterized.expand([("held_by_a_recalculation", True), ("held_by_the_same_daily_key", False)])+ def test_a_daily_failure_replaces_a_completed_row_only_under_its_own_key(+ self, _name: str, held_by_recalculation: bool+ ) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ key = calculation_config.calculation_key()+ held_fingerprint = _recalc_fingerprint(key) if held_by_recalculation else key+ self._row(experiment, held_fingerprint, query_to=_WINDOW, completed_at=_WINDOW, samples=1)++ self._write("daily_failure", experiment, calculation_config)++ row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid="m1", query_to=_WINDOW)+ if held_by_recalculation:+ assert (row.fingerprint, row.status, _samples(row)) == (+ held_fingerprint,+ ExperimentMetricResult.Status.COMPLETED,+ [1],+ )+ assert self._read("for_run", experiment, calculation_config) == [1]+ else:+ assert (row.fingerprint, row.status, row.result, row.error_message) == (+ key,+ ExperimentMetricResult.Status.FAILED,+ None,+ "boom",+ )++ @parameterized.expand(+ [+ (ExperimentMetricsRecalculation.Status.FAILED,),+ (ExperimentMetricsRecalculation.Status.COMPLETED,),+ (None,),+ ]+ )+ def test_a_run_write_skips_a_terminal_or_missing_recalculation(self, status: str | None) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ run = self._run(experiment, ExperimentMetricsRecalculation.Status.IN_PROGRESS)+ if status is None:+ ExperimentMetricsRecalculation.objects.filter(id=run.id).delete()+ else:+ ExperimentMetricsRecalculation.objects.filter(id=run.id).update(status=status)+ self._row(experiment, "fingerprint-from-the-superseding-run", query_to=_WINDOW, completed_at=_WINDOW, samples=1)++ MetricResultStore(experiment_id=experiment.id).record_run_failure(+ str(run.id),+ calculation_config,+ window=_WINDOW,+ query_from=_START,+ error_message="the orphan's late failure",+ query_id=None,+ )++ row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid="m1", query_to=_WINDOW)+ assert (row.fingerprint, row.status, row.error_message) == (+ "fingerprint-from-the-superseding-run",+ ExperimentMetricResult.Status.COMPLETED,+ None,+ )diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pyindex 02bbac49e8df..fb1103c6ebef 100644--- a/products/experiments/backend/test/test_metrics_recalculation_api.py+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -11,7 +11,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -259,7 +259,7 @@ class TestMetricsRecalculationAPI(APIBaseTest):# and we just set query_to on the recalc above.assert exp.metrics and exp.start_date is not Noneassert recalc.query_to is not None- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m1",diff --git a/products/experiments/backend/test/test_recalculation_admin.py b/products/experiments/backend/test/test_recalculation_admin.pyindex 3b8f83fc6339..54793b55b8bb 100644--- a/products/experiments/backend/test/test_recalculation_admin.py+++ b/products/experiments/backend/test/test_recalculation_admin.py@@ -15,7 +15,7 @@ from parameterized import parameterizedfrom products.experiments.backend.admin.recalculation_admin import ExperimentMetricsRecalculationAdminfrom products.experiments.backend.admin.recalculation_panel import build_recalculation_panel, format_durationfrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -130,7 +130,7 @@ class TestRecalculationAdminPanel(BaseTest):ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m-named",- fingerprint=compute_recalc_fingerprint(calculation_config.calculation_key()),+ fingerprint=_recalc_fingerprint(calculation_config.calculation_key()),query_from=datetime(2026, 1, 1, tzinfo=UTC),query_to=query_to,status=ExperimentMetricResult.Status.FAILED,diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.pyindex 85fdbb8c5c7e..53c05e659b98 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -16,7 +16,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.scoping import team_scopefrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -378,7 +378,7 @@ class TestRecalculationService(BaseTest):# and we just set query_to on the recalc above.assert exp.metrics and exp.start_date is not Noneassert recalc.query_to is not None- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))# The row from THIS run (recalc-fingerprinted) — must be returned.ExperimentMetricResult.objects.create(@@ -412,7 +412,7 @@ class TestRecalculationService(BaseTest):exp = self._launched_experiment(flag_key="reuse-excluded")assert exp.start_date is not None # _launched_experiment always sets it; narrow for the create belowquery_to = datetime(2026, 1, 10, tzinfo=UTC)- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m1",@@ -447,7 +447,7 @@ class TestRecalculationService(BaseTest):)assert exp.metrics and exp.start_date is not Noneassert recalc.query_to is not None- recalc_fp = compute_recalc_fingerprint(_calculation_key(exp, "m1"))+ recalc_fp = _recalc_fingerprint(_calculation_key(exp, "m1"))ExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m1",diff --git a/products/experiments/backend/test/test_timeseries_sync.py b/products/experiments/backend/test/test_timeseries_sync.pyindex f70f6df17bcc..db3992f370a1 100644--- a/products/experiments/backend/test/test_timeseries_sync.py+++ b/products/experiments/backend/test/test_timeseries_sync.py@@ -10,7 +10,7 @@ from parameterized import parameterizedfrom products.experiments.backend.facade.timeseries import metric_calculation_keysfrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config-from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -121,8 +121,8 @@ class TestSyncTimeseriesRecalculation(BaseTest):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")),+ _recalc_fingerprint(self._config_fp(exp, "m1")),+ _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()diff --git a/products/experiments/backend/timeseries_backfill.py b/products/experiments/backend/timeseries_backfill.pyindex aa9989af4c4b..4ff2f97f128c 100644--- a/products/experiments/backend/timeseries_backfill.py+++ b/products/experiments/backend/timeseries_backfill.py@@ -18,8 +18,9 @@ from posthog.clickhouse.client.connection import Workloadfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import sanitize_non_finite+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.metric_resolution import build_metric-from products.experiments.backend.models.experiment import ExperimentMetricResult, ExperimentTimeseriesRecalculation+from products.experiments.backend.models.experiment import ExperimentTimeseriesRecalculationlogger = structlog.get_logger(__name__)@@ -71,6 +72,7 @@ def backfill_experiment_timeseries(recalculation_id: str, *, backfill_until: datmetric_obj = build_metric(recalculation_request.metric)experiment_query = ExperimentQuery(experiment_id=experiment.id, metric=metric_obj)fingerprint = recalculation_request.fingerprint+ results = MetricResultStore(experiment_id=experiment.id)days_processed = 0@@ -94,19 +96,12 @@ def backfill_experiment_timeseries(recalculation_id: str, *, backfill_until: dat)result = query_runner._calculate()- ExperimentMetricResult.objects.update_or_create(- experiment_id=experiment.id,- metric_uuid=recalculation_request.metric["uuid"],- query_to=query_to_utc,- defaults={- "fingerprint": fingerprint,- "query_from": experiment.start_date,- "status": ExperimentMetricResult.Status.COMPLETED,- "result": sanitize_non_finite(result.model_dump()),- "query_id": None,- "completed_at": datetime.now(ZoneInfo("UTC")),- "error_message": None,- },+ results.record_daily_point(+ recalculation_request.metric["uuid"],+ fingerprint,+ window=query_to_utc,+ query_from=experiment.start_date,+ result=sanitize_non_finite(result.model_dump()),)recalculation_request.last_successful_date = current_datediff --git a/products/experiments/backend/timeseries_sync.py b/products/experiments/backend/timeseries_sync.pyindex e013cd676526..2e63806d0723 100644--- a/products/experiments/backend/timeseries_sync.py+++ b/products/experiments/backend/timeseries_sync.py@@ -21,8 +21,8 @@ import structlogfrom posthog.models.scoping import team_scope-from products.experiments.backend.metric_calculation.config import build_calculation_configs-from products.experiments.backend.metric_calculation.results import MetricResultStore, compute_recalc_fingerprint+from products.experiments.backend.metric_calculation.config import MetricCalculationConfig, build_calculation_configs+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.metric_resolution import is_daily_timeseries_metricfrom products.experiments.backend.models.experiment import (Experiment,@@ -63,17 +63,14 @@ def sync_timeseries_recalculation(store = MetricResultStore(experiment_id=experiment.id)metric_uuids: list[str] = []- points: dict[str, tuple[str, ExperimentMetricResult]] = {}+ points: dict[str, tuple[MetricCalculationConfig, ExperimentMetricResult]] = {}for calculation_config in build_calculation_configs(experiment):if not is_daily_timeseries_metric(calculation_config.definition):continuemetric_uuids.append(calculation_config.metric_id)row = store.latest_daily_point(calculation_config, since=run_started_at, until=now)if row is not None:- points[calculation_config.metric_id] = (- compute_recalc_fingerprint(calculation_config.calculation_key()),- row,- )+ points[calculation_config.metric_id] = (calculation_config, row)if not points:return None@@ -95,7 +92,9 @@ def sync_timeseries_recalculation(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)+ store.copy_into_sync_run(+ recalculation.query_to, missing.values(), query_from=experiment.start_date, completed_at=now+ )copied = len(missing)else:# A run that already reaches the oldest point covers this data. Trigger-failure tombstones never got@@ -121,7 +120,7 @@ def sync_timeseries_recalculation(total_metrics=len(metric_uuids),metric_uuids=metric_uuids,)- _copy_points(experiment, window, points, now)+ store.copy_into_sync_run(window, points.values(), query_from=experiment.start_date, completed_at=now)copied = len(points)logger.info(@@ -132,26 +131,3 @@ def sync_timeseries_recalculation(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,- },- )