: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): read metric results through one store (#109403)
Andersae944e2fce09
diff --git a/posthog/temporal/experiments/utils.py b/posthog/temporal/experiments/utils.pyindex 249b7d7b738d..f20421fa1b7e 100644--- a/posthog/temporal/experiments/utils.py+++ b/posthog/temporal/experiments/utils.py@@ -5,11 +5,11 @@ from django.db.models import Qimport structlogfrom products.cdp.backend.internal_events import InternalEventEvent, produce_internal_event-from products.experiments.backend.facade.timeseries import apply_saved_metric_overrides-from products.experiments.backend.models.experiment import (- Experiment,- ExperimentMetricResult as ExperimentMetricResultModel,+from products.experiments.backend.facade.timeseries import (+ apply_saved_metric_overrides,+ previous_completed_metric_result,)+from products.experiments.backend.models.experiment import Experimentlogger = structlog.get_logger(__name__)@@ -118,21 +118,15 @@ def check_significance_transition(if not new_significant_keys:return- previous = (- ExperimentMetricResultModel.objects.filter(- experiment=experiment,- metric_uuid=metric_uuid,- fingerprint=fingerprint,- status=ExperimentMetricResultModel.Status.COMPLETED,- query_to__lt=query_to_utc,- )- .order_by("-query_to")- .first()+ previous_result = previous_completed_metric_result(+ experiment.id,+ team_id=experiment.team_id,+ metric_uuid=metric_uuid,+ calculation_key=fingerprint,+ before=query_to_utc,)- prev_significant_keys = (- _get_significant_variant_keys(previous.result) if previous and previous.result else set()- )+ prev_significant_keys = _get_significant_variant_keys(previous_result) if previous_result else set()newly_significant = new_significant_keys - prev_significant_keysif not newly_significant:diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 1b968593c78f..b715a8845306 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -72,6 +72,7 @@ from products.experiments.backend.metric_calculation.config import (saved_metric_calculation_keys,stamp_calculation_keys,)+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.metric_resolution import MetricRolefrom products.experiments.backend.metric_utils import filter_metric_group_ids_by_eventfrom products.experiments.backend.metric_validation import (@@ -2758,15 +2759,7 @@ class ExperimentService:try:first_metric = experiment.metrics[0] if experiment.metrics else Noneif first_metric and first_metric.get("uuid"):- metric_result = (- ExperimentMetricResult.objects.filter(- experiment=experiment,- metric_uuid=first_metric["uuid"],- status=ExperimentMetricResult.Status.COMPLETED,- )- .order_by("-completed_at")- .first()- )+ metric_result = MetricResultStore(experiment_id=experiment.id).last_completed(first_metric["uuid"])if metric_result and metric_result.result:# Significance lives on each variant. The top-level `significant` is a legacy# field that stored results leave null. A variant's value is null when@@ -4451,9 +4444,9 @@ class ExperimentService:for experiment_date in experiment_dates:timeseries[experiment_date.isoformat()] = None- metric_results = ExperimentMetricResult.objects.filter(- experiment_id=experiment.id, metric_uuid=metric_uuid, fingerprint=fingerprint- ).order_by("query_to")+ stored = MetricResultStore(experiment_id=experiment.id).timeseries(+ metric_uuid, fingerprint, timezone=project_tz+ )completed_count = 0failed_count = 0@@ -4461,18 +4454,11 @@ class ExperimentService:no_record_count = 0latest_completed_at = None- results_by_date: dict[date, ExperimentMetricResult] = {}- for result in metric_results:- query_to_adjusted = result.query_to - timedelta(microseconds=1)- query_to_in_project_tz = query_to_adjusted.astimezone(project_tz)- day_in_project_tz = query_to_in_project_tz.date()- results_by_date[day_in_project_tz] = result-for experiment_date in experiment_dates:date_key = experiment_date.isoformat()- if experiment_date in results_by_date:- metric_result = results_by_date[experiment_date]+ if experiment_date in stored.by_day:+ metric_result = stored.by_day[experiment_date]if metric_result.status == "completed":timeseries[date_key] = strip_step_sessions(metric_result.result)@@ -4511,8 +4497,6 @@ class ExperimentService:],).first()- first_result = metric_results.first()- last_result = metric_results.last()response = {"experiment_id": experiment.id,"metric_uuid": metric_uuid,@@ -4520,8 +4504,10 @@ class ExperimentService:"timeseries": timeseries,"errors": errors if errors else None,"computed_at": latest_completed_at.isoformat() if latest_completed_at else None,- "created_at": first_result.created_at.isoformat() if first_result else experiment.created_at.isoformat(),- "updated_at": last_result.updated_at.isoformat() if last_result else experiment.updated_at.isoformat(),+ "created_at": stored.earliest.created_at.isoformat()+ if stored.earliest+ else experiment.created_at.isoformat(),+ "updated_at": stored.latest.updated_at.isoformat() if stored.latest else experiment.updated_at.isoformat(),"recalculation_status": active_recalculation.status if active_recalculation else None,"recalculation_created_at": active_recalculation.created_at.isoformat() if active_recalculation else None,}diff --git a/products/experiments/backend/facade/timeseries.py b/products/experiments/backend/facade/timeseries.pyindex b858767a41bf..eb4baa3c0510 100644--- a/products/experiments/backend/facade/timeseries.py+++ b/products/experiments/backend/facade/timeseries.py@@ -5,6 +5,7 @@ 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_resultfrom products.experiments.backend.metric_resolution import (METRIC_BUILDERS,apply_saved_metric_overrides,@@ -24,6 +25,7 @@ __all__ = ["is_daily_timeseries_metric","is_scheduled_metric","metric_calculation_keys",+ "previous_completed_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.pynew file mode 100644index 000000000000..cb103b371e8c--- /dev/null+++ b/products/experiments/backend/metric_calculation/results.py@@ -0,0 +1,258 @@+"""Reads of stored metric results.++`MetricResultStore` is the only reader of `ExperimentMetricResult`. Its named queries hide three storage+conventions from the callers:++- A recalculation run files its rows under a salted calculation key (`compute_recalc_fingerprint`), and the daily+ timeseries 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,+ the rows of the earlier run have a `query_from` before it.++Several rows can share `(experiment, metric_uuid, query_to)` once the unique constraint on that key goes. Every+query that can meet such rows returns the one with the newest `completed_at`, then the highest id. It never looks a+row up with `.get()` on that key. While the constraint holds, no two rows tie, so this order changes no result.++Every query filters on the experiment first, so the `(experiment, metric_uuid, query_to)` indexes serve it.+"""++import hashlib+from collections.abc import Iterable, Mapping+from datetime import date, datetime, timedelta+from typing import Any+from zoneinfo import ZoneInfo++from django.db.models import F, QuerySet+from django.db.models.fields.json import KT, KeyTransform++from posthog.dataclasses import frozen++from products.experiments.backend.metric_calculation.config import MetricCalculationConfig, build_calculation_configs+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)++# Constant salt: keeps recalc rows distinct from the timeseries workflow's bare config fingerprint, while+# staying deterministic per config so a re-run updates the existing row instead of colliding on the unique key.+_RECALCULATION_SALT = "recalculation"++# The copies land one second past the newest point. A copy at a point's own query_to would share its+# (experiment, metric_uuid, query_to) key with the timeseries row and rewrite that row's fingerprint.+_SYNC_COPY_OFFSET = timedelta(seconds=1)++_COMPLETED = ExperimentMetricResult.Status.COMPLETED+++def compute_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+ deterministic for a given config and deliberately distinct from the timeseries workflow's bare config+ fingerprint.+ """+ return hashlib.sha256(f"{config_fingerprint}{_RECALCULATION_SALT}".encode()).hexdigest()+++def _newest_write_first(rows: QuerySet[ExperimentMetricResult], *window_order: str) -> QuerySet[ExperimentMetricResult]:+ """Order `rows` by `window_order`, then put the newest write first among rows that tie on it."""+ return rows.order_by(*window_order, F("completed_at").desc(nulls_last=True), F("id").desc())+++@frozen+class DailyTimeseries:+ """The stored results of one metric under one calculation key, one row per day."""++ by_day: dict[date, ExperimentMetricResult]+ earliest: ExperimentMetricResult | None+ latest: ExperimentMetricResult | None+++@frozen+class ResultSummary:+ """The fields of a stored result that describe an experiment's outcome. The rest of the result stays in+ Postgres."""++ completed_at: datetime | None+ query_to: datetime+ # The stored JSON values as text, None when the result does not store them.+ baseline_samples: str | None+ baseline_sum: str | None+ variant_results: tuple[dict[str, Any], ...]+++@frozen+class MetricResultStore:+ """The stored metric results of one experiment."""++ experiment_id: int++ def for_run(self, run: ExperimentMetricsRecalculation) -> list[ExperimentMetricResult]:+ """The rows of a recalculation run, one per metric uuid, ordered by metric uuid.++ A run has no link to its rows. The rows are found by the salted keys of the run's metrics under the+ current configuration of the experiment, at the run's query_to. A metric that no longer resolves on the+ experiment has no key, so its row is not found. A configuration change after the run changes the keys, so+ the run's rows are not found until the configuration changes back.+ """+ if run.query_to is None:+ return []+ calculation_configs = {+ calculation_config.metric_id: calculation_config+ for calculation_config in build_calculation_configs(run.experiment)+ }+ fingerprints = [+ compute_recalc_fingerprint(calculation_configs[metric_uuid].calculation_key())+ for metric_uuid in run.metric_uuids or []+ if metric_uuid in calculation_configs+ ]+ if not fingerprints:+ return []+ # The recalc fingerprint is per config, not per run, so each window of a running experiment holds a row under+ # the same fingerprint. Without the query_to filter a later run would return every earlier window's row.+ rows = ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id, fingerprint__in=fingerprints, query_to=run.query_to+ )+ return list(_newest_write_first(rows, "metric_uuid").distinct("metric_uuid"))++ def has_completed(self, calculation_config: MetricCalculationConfig, *, window: datetime) -> bool:+ """Whether a recalculation already stored a completed result for this calculation config at this window."""+ return ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id,+ metric_uuid=calculation_config.metric_id,+ query_to=window,+ fingerprint=compute_recalc_fingerprint(calculation_config.calculation_key()),+ status=_COMPLETED,+ ).exists()++ def latest_daily_point(+ self, calculation_config: MetricCalculationConfig, *, since: datetime, until: datetime+ ) -> ExperimentMetricResult | None:+ """The completed daily point of this calculation config with the latest query_to inside [since, until]."""+ rows = ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id,+ metric_uuid=calculation_config.metric_id,+ fingerprint=calculation_config.calculation_key(),+ status=_COMPLETED,+ query_to__gte=since,+ query_to__lte=until,+ )+ return _newest_write_first(rows, "-query_to").first()++ def timeseries(self, metric_uuid: str, calculation_key: str, *, timezone: ZoneInfo) -> DailyTimeseries:+ """The rows of one metric under a calculation key, whatever their status, one per day of `timezone`.++ Only daily rows carry the bare key, because a recalculation salts it. The latest query_to inside a day+ stands for that day.+ """+ rows = list(+ _newest_write_first(+ ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id, metric_uuid=metric_uuid, fingerprint=calculation_key+ ),+ "-query_to",+ )+ )+ by_day: dict[date, ExperimentMetricResult] = {}+ for row in rows:+ # A daily row's query_to is the exclusive end of its day, so the microsecond before it falls inside+ # the day the row covers.+ day = (row.query_to - timedelta(microseconds=1)).astimezone(timezone).date()+ by_day.setdefault(day, row)+ return DailyTimeseries(by_day=by_day, earliest=rows[-1] if rows else None, latest=rows[0] if rows else None)++ def last_completed(self, metric_uuid: str) -> ExperimentMetricResult | None:+ """The completed row of a metric that was written last, whatever its configuration and window."""+ return (+ ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id, metric_uuid=metric_uuid, status=_COMPLETED+ )+ # NULLS FIRST keeps the stop-experiment check's rule. Every writer sets completed_at on a completed row,+ # so NULLS LAST would differ only for rows that no writer creates.+ .order_by(F("completed_at").desc(nulls_first=True), "-id")+ .first()+ )++ def previous_completed(+ self, metric_uuid: str, calculation_key: str, *, before: datetime+ ) -> ExperimentMetricResult | None:+ """The completed daily point under this key with the latest query_to before `before`."""+ rows = ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id,+ metric_uuid=metric_uuid,+ fingerprint=calculation_key,+ status=_COMPLETED,+ query_to__lt=before,+ )+ return _newest_write_first(rows, "-query_to").first()++ def metric_uuids_stored_at(self, window: datetime, metric_uuids: Iterable[str]) -> set[str]:+ """The metric uuids among `metric_uuids` that have a row at exactly this window, in any status."""+ return set(+ ExperimentMetricResult.objects.filter(+ experiment_id=self.experiment_id, query_to=window, metric_uuid__in=list(metric_uuids)+ ).values_list("metric_uuid", flat=True)+ )++ @staticmethod+ def 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`."""+ return newest_point + _SYNC_COPY_OFFSET++ @staticmethod+ def current_outcomes(metric_uuid_by_experiment: Mapping[int, str]) -> dict[int, ResultSummary]:+ """For each experiment, the completed result of the given metric that describes the current run, in one+ query.++ The current run is the one since the experiment's start date, so rows from before a relaunch do not count.+ Within the run, the row with the latest query_to counts, because a backfill stores a historical query_to+ with completed_at set to the time of the backfill.+ """+ if not metric_uuid_by_experiment:+ return {}+ rows = (+ ExperimentMetricResult.objects.filter(+ experiment_id__in=metric_uuid_by_experiment.keys(),+ metric_uuid__in=set(metric_uuid_by_experiment.values()),+ status=_COMPLETED,+ # `gte` rather than an exact match, so a start date edited to an earlier moment keeps its results.+ # A draft has no start date, so nothing matches.+ query_from__gte=F("experiment__start_date"),+ )+ .order_by("experiment_id", "metric_uuid", "-query_to", F("completed_at").desc(nulls_last=True), "-id")+ .distinct("experiment_id", "metric_uuid")+ .values(+ "experiment_id",+ "metric_uuid",+ "completed_at",+ "query_to",+ baseline_samples=KT("result__baseline__number_of_samples"),+ baseline_sum=KT("result__baseline__sum"),+ variant_results=KeyTransform("variant_results", "result"),+ )+ )+ summaries: dict[int, ResultSummary] = {}+ for row in rows:+ if metric_uuid_by_experiment.get(row["experiment_id"]) != row["metric_uuid"]:+ continue+ variant_results = row["variant_results"] if isinstance(row["variant_results"], list) else []+ summaries[row["experiment_id"]] = ResultSummary(+ completed_at=row["completed_at"],+ query_to=row["query_to"],+ baseline_samples=row["baseline_samples"],+ baseline_sum=row["baseline_sum"],+ variant_results=tuple(variant for variant in variant_results if isinstance(variant, dict)),+ )+ return summaries+++def previous_completed_metric_result(+ experiment_id: int, *, team_id: int, metric_uuid: str, calculation_key: str, before: datetime+) -> dict[str, Any] | None:+ """The stored result of the completed daily point under this key with the latest query_to before `before`,+ for callers outside the product. None when there is no such point or the experiment is not in the team."""+ if not Experiment.objects.filter(id=experiment_id, team_id=team_id).exists():+ return None+ row = MetricResultStore(experiment_id=experiment_id).previous_completed(metric_uuid, calculation_key, before=before)+ return row.result if row is not None else Nonediff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex c55e0ae9bf89..7d1dcfc029f9 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -4,9 +4,8 @@ Module-level free functions (not methods on ExperimentService) so the API view c- ``request_recalculation`` — idempotent create: returns the active run if one exists, else creates a pending job.- ``get_latest_recalculation`` — most recent recalc row for an experiment, or ``None``.-- ``get_run_results`` — read-back of per-metric results for a specific run, scoped by recomputing each metric's- per-run recalc fingerprint (no FK on ExperimentMetricResult; the scoping key lives entirely on the job row +- the run id).+- ``get_run_results`` — read-back of per-metric results for a specific run, through ``MetricResultStore.for_run``+ (no FK on ExperimentMetricResult; the store finds a run's rows from the job row and the current metric config)."""import asyncio@@ -32,6 +31,7 @@ from posthog.settings import CLICKHOUSE_CLUSTERfrom posthog.temporal.common.client import sync_connectfrom products.experiments.backend.metric_calculation.config import build_calculation_configs+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -42,7 +42,6 @@ from products.experiments.backend.temporal.models import (METRICS_RECALCULATION_WORKFLOW_NAME,ExperimentMetricsRecalculationWorkflowInputs,)-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics# How long an active (PENDING/IN_PROGRESS) row blocks new recalculations. Beyond this, the row is treated as@@ -464,50 +463,19 @@ def get_recalculation_by_id(experiment: Experiment, recalculation_id: str) -> Ex).first()-def _recalc_fingerprints_for_run(experiment: Experiment, recalc: ExperimentMetricsRecalculation) -> dict[str, str]:- """Recompute each metric's per-run recalc fingerprint (strategy 'a': no extra storage).-- Returns ``{metric_uuid: recalc_fp}`` for metrics still resolvable on the experiment. A uuid present on the job- but no longer on the experiment is skipped (metric removed mid-run).-- Divergence hazard: the fingerprint is derived from mutable experiment fields (start_date, exposure_criteria,- stats method, only_count_matured_users). If any of these change between the workflow's writes and a later- read, the recomputed fingerprints will not match the on-disk ones and the corresponding result rows become- unreachable (until the experiment fields revert). This is the explicit trade-off of "no FK on- ExperimentMetricResult" — the snapshot lives in the fingerprint, not in a stored column.- """- calculation_configs = {- calculation_config.metric_id: calculation_config for calculation_config in build_calculation_configs(experiment)- }- fingerprints: dict[str, str] = {}- for metric_uuid in recalc.metric_uuids or []:- calculation_config = calculation_configs.get(metric_uuid)- if calculation_config is None:- continue- fingerprints[metric_uuid] = compute_recalc_fingerprint(calculation_config.calculation_key())- return fingerprints--def get_run_results(recalc: ExperimentMetricsRecalculation) -> list[dict]:"""Return the ExperimentMetricResult rows that belong to THIS run.- Scopes by recomputing each metric's recalc fingerprint and filtering ``fingerprint__in`` — never returns- rows from a previous run or from the timeseries workflow (which uses config fingerprints).+ Never returns rows from a previous run or from the timeseries workflow (which uses config fingerprints).- See `_recalc_fingerprints_for_run` for the fingerprint-divergence hazard: if experiment fields that feed- the fingerprint change after the run wrote its rows, this can return [] for what is on-disk a successful- run. Symptom: "results disappeared after editing exposure_criteria / start_date / stats config."+ Divergence hazard: the store finds a run's rows by recomputing each metric's fingerprint from mutable+ experiment fields (start_date, exposure_criteria, stats method, only_count_matured_users). If any of these+ change after the run wrote its rows, this can return [] for what is on-disk a successful run, until the+ experiment fields revert. Symptom: "results disappeared after editing exposure_criteria / start_date / stats+ config." This is the explicit trade-off of "no FK on ExperimentMetricResult": the snapshot lives in the+ fingerprint, not in a stored column."""- fingerprints = _recalc_fingerprints_for_run(recalc.experiment, recalc)- if not fingerprints or recalc.query_to is None:- return []-- # Scope to this run's window. The recalc fingerprint is now deterministic per config (not per run), so a- # running experiment accumulates one row per query_to under the same fingerprint; without this filter a- # later run would return every prior window's row and overcount. recalc.query_to pins the run's window.- rows = ExperimentMetricResult.objects.filter(- experiment=recalc.experiment, fingerprint__in=list(fingerprints.values()), query_to=recalc.query_to- )+ rows = MetricResultStore(experiment_id=recalc.experiment_id).for_run(recalc)return [{"metric_uuid": row.metric_uuid,@@ -533,24 +501,14 @@ def build_timeseries_cold_start_payload(experiment: Experiment) -> dict | None:"""with team_scope(experiment.team_id, canonical=True):calculation_configs = build_calculation_configs(experiment)+ store = MetricResultStore(experiment_id=experiment.id)now = timezone.now()results: list[dict] = []latest_query_to = Nonefor calculation_config in calculation_configs:- row = (- ExperimentMetricResult.objects.filter(- experiment=experiment,- metric_uuid=calculation_config.metric_id,- fingerprint=calculation_config.calculation_key(),- status=ExperimentMetricResult.Status.COMPLETED,- # Bounded on both sides: the backfill writes end-of-day points, so today's point can carry- # a future query_to that would surface here as a future completion time.- query_to__gte=now - TIMESERIES_FALLBACK_MAX_AGE,- query_to__lte=now,- )- .order_by("-query_to")- .first()- )+ # Bounded on both sides: the backfill writes end-of-day points, so today's point can carry a future+ # query_to that would surface here as a future completion time.+ row = store.latest_daily_point(calculation_config, since=now - TIMESERIES_FALLBACK_MAX_AGE, until=now)if row is None:continueresults.append(diff --git a/products/experiments/backend/setup_context.py b/products/experiments/backend/setup_context.pyindex 0bb5fec3cd65..f66e5d36efed 100644--- a/products/experiments/backend/setup_context.py+++ b/products/experiments/backend/setup_context.py@@ -19,7 +19,6 @@ from typing import Any, Final, Generic, TypeVarfrom django.db import modelsfrom django.db.models import BooleanField, Case, Count, F, Max, Prefetch, Q, QuerySet, Value, When-from django.db.models.fields.json import KT, KeyTransformfrom django.utils import timezonefrom posthog.schema import ActionsNode, ExperimentEventExposureConfig@@ -55,6 +54,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (resolve_default_exposure_event,resolve_flag_call_source_event,)+from products.experiments.backend.metric_calculation.results import MetricResultStorefrom products.experiments.backend.metric_resolution import is_scheduled_metricfrom products.experiments.backend.metric_utils import (collect_metric_events_and_action_ids,@@ -63,7 +63,6 @@ from products.experiments.backend.metric_utils import ()from products.experiments.backend.models.experiment import (Experiment,- ExperimentMetricResult,ExperimentSavedMetric,ExperimentToSavedMetric,metric_display_rank,@@ -1170,60 +1169,35 @@ def _outcomes(outcome_metrics: dict[int, OutcomeMetric]) -> dict[int, Experimentboth writers of `ExperimentMetricResult` build the metric from its `metric_type`. Itsexperiment correctly gets no outcome."""- if not outcome_metrics:- return {}- rows = (- ExperimentMetricResult.objects.filter(- experiment_id__in=outcome_metrics.keys(),- metric_uuid__in={metric.uuid for metric in outcome_metrics.values()},- status=ExperimentMetricResult.Status.COMPLETED,- # Both writers store the experiment's start date, so a relaunch moves that date- # forward and leaves the earlier run's rows behind it. A draft has no start date, so- # nothing matches. `gte` rather than an exact match, so a start date edited to an- # earlier moment keeps its results instead of hiding them until every row is recomputed.- query_from__gte=F("experiment__start_date"),- )- # A backfill stores a historical `query_to` with `completed_at` set to now, so ordering by- # the write time can pick an older day. The (experiment, metric_uuid, query_to) index covers this.- .order_by("experiment_id", "metric_uuid", "-query_to", F("completed_at").desc(nulls_last=True))- .distinct("experiment_id", "metric_uuid")- # The stored query text in each result stays in Postgres.- .values(- "experiment_id",- "metric_uuid",- "completed_at",- "query_to",- baseline_samples=KT("result__baseline__number_of_samples"),- baseline_sum=KT("result__baseline__sum"),- variant_results=KeyTransform("variant_results", "result"),- )+ summaries = MetricResultStore.current_outcomes(+ {experiment_id: metric.uuid for experiment_id, metric in outcome_metrics.items()})outcomes: dict[int, ExperimentOutcome] = {}- for row in rows:- metric = outcome_metrics.get(row["experiment_id"])- if metric is None or metric.uuid != row["metric_uuid"]:- continue- variants = [variant for variant in row["variant_results"] or [] if isinstance(variant, dict)]+ for experiment_id, summary in summaries.items():+ metric = outcome_metrics[experiment_id]# Samples exclude users seen in several variants under the default handling, so this is# the analyzed population rather than every exposure. A result that stores no sample count# anywhere is unknown, not zero.stored_samples = [samples- for samples in [row["baseline_samples"], *(variant.get("number_of_samples") for variant in variants)]+ for samples in [+ summary.baseline_samples,+ *(variant.get("number_of_samples") for variant in summary.variant_results),+ ]if samples is not None]metric_samples = sum(int(float(samples)) for samples in stored_samples) if stored_samples else Noneexposure_shaped = metric.metric_type in EXPOSURE_SHAPED_METRIC_TYPES- outcomes[row["experiment_id"]] = ExperimentOutcome(+ outcomes[experiment_id] = ExperimentOutcome(metric_type=metric.metric_type,metric_samples=metric_samples,analyzed_exposures=metric_samples if exposure_shaped else None,control_baseline_value=_control_baseline_value(- row["baseline_sum"], row["baseline_samples"], exposure_shaped+ summary.baseline_sum, summary.baseline_samples, exposure_shaped),- any_variant_significant=any(v.get("significant") is True for v in variants),- result_completed_at=row["completed_at"],- result_data_through=row["query_to"],+ any_variant_significant=any(v.get("significant") is True for v in summary.variant_results),+ result_completed_at=summary.completed_at,+ result_data_through=summary.query_to,)return outcomesdiff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 80c6b373438c..32bdc1779fa8 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -70,11 +70,11 @@ 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")` (`recalc_fingerprint.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")` (`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.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.-Runs of a **running** experiment are told apart by `query_to`, not by the fingerprint. Each run advances `query_to` toward "now", so it accumulates one row per run under the same fingerprint, one per window end. `get_run_results` filters `fingerprint__in=(...) AND query_to=recalc.query_to`, so a read returns exactly the rows for that run's window.+Runs of a **running** experiment are told apart by `query_to`, not by the fingerprint. Each run advances `query_to` toward "now", so it accumulates one row per run under the same fingerprint, one per window end. `MetricResultStore.for_run`, behind `get_run_results`, filters `fingerprint__in=(...) AND query_to=recalc.query_to`, so a read returns exactly the rows for that run's window.A run never recomputes a completed result for the same config and window.Before it queries, the calc activity looks for a `COMPLETED` row with the same recalc fingerprint and `query_to`.@@ -98,7 +98,11 @@ The snapshot for such an experiment is the one row at `end_date` for the current`ExperimentMetricResult` has no foreign key pointing back to `ExperimentMetricsRecalculation`. The scoping key lives entirely in the fingerprint plus `query_to`. This avoided a migration on a shared table to add a nullable column, and makes the two workflow families uniform in how they write results.-The trade-off: reads have to recompute the fingerprint set to find a run's results (`get_run_results` 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.+The 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.+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.### Counters are derived, not storeddiff --git a/products/experiments/backend/temporal/recalc_fingerprint.py b/products/experiments/backend/temporal/recalc_fingerprint.pydeleted file mode 100644index 950522ec12af..000000000000--- a/products/experiments/backend/temporal/recalc_fingerprint.py+++ /dev/null@@ -1,15 +0,0 @@-import hashlib--# Constant salt: keeps recalc rows distinct from the timeseries workflow's bare config fingerprint, while-# staying deterministic per config so a re-run updates the existing row instead of colliding on the unique key.-_RECALCULATION_SALT = "recalculation"---def compute_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- deterministic for a given config and deliberately distinct from the timeseries workflow's bare config- fingerprint.- """- return hashlib.sha256(f"{config_fingerprint}{_RECALCULATION_SALT}".encode()).hexdigest()diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex c84262c6be25..319d89430533 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -40,6 +40,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_finitefrom products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import MetricResultStore, compute_recalc_fingerprintfrom products.experiments.backend.metric_resolution import build_metric, get_metrics_for_calculationfrom products.experiments.backend.models.experiment import (Experiment,@@ -61,7 +62,6 @@ from products.experiments.backend.temporal.models import (MetricRecalculationResult,RecalculationProgressUpdate,)-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.experiments.stats.shared.statistics import StatisticErrorlogger = structlog.get_logger(__name__)@@ -743,14 +743,7 @@ def _calculate_experiment_metric_for_recalculation_sync(# 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.- already_computed = ExperimentMetricResult.objects.filter(- experiment_id=experiment_id,- metric_uuid=metric_uuid,- query_to=query_to_dt,- fingerprint=recalc_fp,- status=ExperimentMetricResult.Status.COMPLETED,- ).exists()- if already_computed:+ if MetricResultStore(experiment_id=experiment_id).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)diff --git a/products/experiments/backend/temporal/test_recalc_fingerprint.py b/products/experiments/backend/temporal/test_recalc_fingerprint.pydeleted file mode 100644index 6e1986745cc7..000000000000--- a/products/experiments/backend/temporal/test_recalc_fingerprint.py+++ /dev/null@@ -1,24 +0,0 @@-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint---def test_recalc_fingerprint_is_deterministic_for_a_given_config():- # The recalc fingerprint must NOT depend on the recalculation run: a stopped experiment re-recalculated- # 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)---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---def test_recalc_fingerprint_differs_per_config():- assert compute_recalc_fingerprint("c" * 64) != compute_recalc_fingerprint("d" * 64)---def test_recalc_fingerprint_is_sha256_hex_length():- assert len(compute_recalc_fingerprint("e" * 64)) == 64diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex fc6038142582..babd907cc690 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -21,6 +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_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -35,7 +36,6 @@ from products.experiments.backend.temporal.models import (MetricRecalculationResult,RecalculationProgressUpdate,)-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.experiments.backend.temporal.recalculation_activities import calculate_experiment_metric_for_recalculationfrom products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,diff --git a/products/experiments/backend/test/test_metric_result_store.py b/products/experiments/backend/test/test_metric_result_store.pynew file mode 100644index 000000000000..96588194950c--- /dev/null+++ b/products/experiments/backend/test/test_metric_result_store.py@@ -0,0 +1,193 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any+from zoneinfo import ZoneInfo++from posthog.test.base import BaseTest++from django.db import connection++from parameterized import parameterized++from products.experiments.backend.metric_calculation.config import (+ MetricCalculationConfig,+ get_metric_calculation_config,+)+from products.experiments.backend.metric_calculation.results import (+ MetricResultStore,+ compute_recalc_fingerprint,+ previous_completed_metric_result,+)+from products.experiments.backend.models.experiment import (+ Experiment,+ ExperimentMetricResult,+ ExperimentMetricsRecalculation,+)+from products.feature_flags.backend.models.feature_flag import FeatureFlag++_START = datetime(2026, 1, 1, tzinfo=UTC)+# Midnight, so a daily row with this query_to covers 9 January.+_WINDOW = datetime(2026, 1, 10, tzinfo=UTC)+_WINDOW_DAY = date(2026, 1, 9)+++def test_recalc_fingerprint_is_deterministic_for_a_given_config():+ # The recalc fingerprint must NOT depend on the recalculation run: a stopped experiment re-recalculated+ # 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)+++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+++def test_recalc_fingerprint_differs_per_config():+ assert compute_recalc_fingerprint("c" * 64) != compute_recalc_fingerprint("d" * 64)+++def test_recalc_fingerprint_is_sha256_hex_length():+ assert len(compute_recalc_fingerprint("e" * 64)) == 64+++def _stored_result(samples: int) -> dict[str, Any]:+ return {"baseline": {"key": "control", "number_of_samples": samples}, "variant_results": []}+++def _samples(row: ExperimentMetricResult | None) -> list[int]:+ return [row.result["baseline"]["number_of_samples"]] if row is not None and row.result else []+++class TestMetricResultStore(BaseTest):+ def _experiment(self) -> Experiment:+ flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="store-flag", name="store")+ return Experiment.objects.create(+ team=self.team,+ created_by=self.user,+ feature_flag=flag,+ name="store",+ start_date=_START,+ metrics=[+ {+ "uuid": "m1",+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "purchase"},+ }+ ],+ )++ def _row(+ self, experiment: Experiment, fingerprint: str, *, query_to: datetime, completed_at: datetime, samples: int+ ) -> None:+ ExperimentMetricResult.objects.create(+ experiment=experiment,+ metric_uuid="m1",+ fingerprint=fingerprint,+ query_from=_START,+ query_to=query_to,+ status=ExperimentMetricResult.Status.COMPLETED,+ result=_stored_result(samples),+ completed_at=completed_at,+ )++ def _read(self, reader: str, experiment: Experiment, calculation_config: MetricCalculationConfig) -> list[int]:+ store = MetricResultStore(experiment_id=experiment.id)+ key = calculation_config.calculation_key()+ match reader:+ case "for_run":+ run = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=experiment, metric_uuids=["m1"], query_to=_WINDOW+ )+ return [sample for row in store.for_run(run) for sample in _samples(row)]+ case "latest_daily_point":+ return _samples(+ store.latest_daily_point(calculation_config, since=_WINDOW - timedelta(days=1), until=_WINDOW)+ )+ case "timeseries":+ return _samples(store.timeseries("m1", key, timezone=ZoneInfo("UTC")).by_day.get(_WINDOW_DAY))+ case "last_completed":+ return _samples(store.last_completed("m1"))+ case "previous_completed":+ return _samples(store.previous_completed("m1", key, before=_WINDOW + timedelta(days=1)))+ case "current_outcomes":+ summary = MetricResultStore.current_outcomes({experiment.id: "m1"})[experiment.id]+ assert summary.baseline_samples is not None+ return [int(summary.baseline_samples)]+ raise AssertionError(f"unknown reader {reader}")++ @parameterized.expand(+ [+ (f"{reader}_{tie}", reader, tie)+ for reader in (+ "for_run",+ "latest_daily_point",+ "timeseries",+ "last_completed",+ "previous_completed",+ "current_outcomes",+ )+ for tie in ("newer_write_wins", "higher_id_wins_between_equal_writes")+ ]+ )+ def test_rows_sharing_a_window_resolve_to_the_newest_write(self, _name: str, reader: str, tie: str) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ fingerprint = (+ compute_recalc_fingerprint(calculation_config.calculation_key())+ if reader == "for_run"+ else calculation_config.calculation_key()+ )+ # The unique constraint allows one row per (experiment, metric_uuid, query_to). Dropping it inside the+ # test transaction lets two rows share a window, and the rollback at the end of the test restores it.+ assert connection.in_atomic_block+ with connection.schema_editor() as editor:+ editor.alter_unique_together(ExperimentMetricResult, [("experiment", "metric_uuid", "query_to")], [])+ if tie == "newer_write_wins":+ # The newer write gets the lower id, so an order on id alone picks the wrong row.+ self._row(experiment, fingerprint, query_to=_WINDOW, completed_at=_WINDOW + timedelta(hours=2), samples=2)+ self._row(experiment, fingerprint, query_to=_WINDOW, completed_at=_WINDOW + timedelta(hours=1), samples=1)+ else:+ self._row(experiment, fingerprint, query_to=_WINDOW, completed_at=_WINDOW + timedelta(hours=1), samples=1)+ self._row(experiment, fingerprint, query_to=_WINDOW, completed_at=_WINDOW + timedelta(hours=1), samples=2)++ assert self._read(reader, experiment, calculation_config) == [2]++ def test_the_latest_window_inside_a_day_stands_for_that_day(self) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ key = calculation_config.calculation_key()+ # Both windows fall on 9 January. The later window was written first, so the write time alone picks the+ # other row.+ self._row(experiment, key, query_to=_WINDOW, completed_at=_WINDOW + timedelta(hours=1), samples=2)+ self._row(+ experiment, key, query_to=_WINDOW - timedelta(hours=6), completed_at=_WINDOW + timedelta(hours=2), samples=1+ )++ timeseries = MetricResultStore(experiment_id=experiment.id).timeseries("m1", key, timezone=ZoneInfo("UTC"))++ assert list(timeseries.by_day) == [_WINDOW_DAY]+ assert _samples(timeseries.by_day[_WINDOW_DAY]) == [2]++ @parameterized.expand([("own_team", True), ("other_team", False)])+ def test_previous_completed_metric_result_reads_only_the_callers_team(self, _name: str, own_team: bool) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ key = calculation_config.calculation_key()+ self._row(experiment, key, query_to=_WINDOW, completed_at=_WINDOW, samples=7)++ result = previous_completed_metric_result(+ experiment.id,+ team_id=self.team.id if own_team else self.team.id + 1,+ metric_uuid="m1",+ calculation_key=key,+ before=_WINDOW + timedelta(days=1),+ )++ assert result == (_stored_result(7) if own_team else None)diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pyindex c153678bcd73..02bbac49e8df 100644--- a/products/experiments/backend/test/test_metrics_recalculation_api.py+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -11,13 +11,13 @@ 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_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,ExperimentMetricsRecalculation,)from products.experiments.backend.temporal.models import ExperimentMetricsRecalculationWorkflowInputs-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/products/experiments/backend/test/test_recalculation_admin.py b/products/experiments/backend/test/test_recalculation_admin.pyindex de99abcea549..3b8f83fc6339 100644--- a/products/experiments/backend/test/test_recalculation_admin.py+++ b/products/experiments/backend/test/test_recalculation_admin.py@@ -14,12 +14,13 @@ from parameterized import parameterizedfrom products.experiments.backend.admin.recalculation_admin import ExperimentMetricsRecalculationAdminfrom products.experiments.backend.admin.recalculation_panel import build_recalculation_panel, format_duration+from products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import compute_recalc_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,ExperimentMetricsRecalculation,)-from products.experiments.backend.recalculation import _recalc_fingerprints_for_runfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -124,11 +125,12 @@ class TestRecalculationAdminPanel(BaseTest):completed_at=datetime(2026, 1, 2, 10, 0, 30, tzinfo=UTC),)# No metric_errors entry, so the failure text comes from the FAILED result row's error_message.- fingerprints = _recalc_fingerprints_for_run(exp, recalc)+ calculation_config = get_metric_calculation_config(exp, "m-named")+ assert calculation_config is not NoneExperimentMetricResult.objects.create(experiment=exp,metric_uuid="m-named",- fingerprint=fingerprints["m-named"],+ fingerprint=compute_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 1887d3ab8645..85fdbb8c5c7e 100644--- a/products/experiments/backend/test/test_recalculation_service.py+++ b/products/experiments/backend/test/test_recalculation_service.py@@ -16,6 +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_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -33,7 +34,6 @@ from products.experiments.backend.recalculation import (get_run_results,request_recalculation,)-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/products/experiments/backend/test/test_timeseries_sync.py b/products/experiments/backend/test/test_timeseries_sync.pyindex b828fe6b5b89..f70f6df17bcc 100644--- a/products/experiments/backend/test/test_timeseries_sync.py+++ b/products/experiments/backend/test/test_timeseries_sync.py@@ -10,6 +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_fingerprintfrom products.experiments.backend.models.experiment import (Experiment,ExperimentMetricResult,@@ -18,7 +19,6 @@ from products.experiments.backend.models.experiment import (ExperimentToSavedMetric,)from products.experiments.backend.recalculation import get_run_results-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintfrom products.experiments.backend.timeseries_sync import sync_timeseries_recalculationfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdiff --git a/products/experiments/backend/timeseries_sync.py b/products/experiments/backend/timeseries_sync.pyindex f10bec5c1a00..e013cd676526 100644--- a/products/experiments/backend/timeseries_sync.py+++ b/products/experiments/backend/timeseries_sync.py@@ -22,6 +22,7 @@ import structlogfrom posthog.models.scoping import team_scopefrom products.experiments.backend.metric_calculation.config import build_calculation_configs+from products.experiments.backend.metric_calculation.results import MetricResultStore, compute_recalc_fingerprintfrom products.experiments.backend.metric_resolution import is_daily_timeseries_metricfrom products.experiments.backend.models.experiment import (Experiment,@@ -29,14 +30,9 @@ from products.experiments.backend.models.experiment import (ExperimentMetricsRecalculation,)from products.experiments.backend.recalculation import get_active_recalculation-from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprintlogger = structlog.get_logger(__name__)-# The copies land one second past the newest point. A copy at a point's own query_to would share its-# (experiment, metric_uuid, query_to) key with the timeseries row and rewrite that row's fingerprint.-_WINDOW_OFFSET = timedelta(seconds=1)-# The two hourly workflows start within the same cron minute; yesterday's sync row is a day older._SAME_RUN_LOOKBACK = timedelta(hours=1)@@ -65,27 +61,19 @@ def sync_timeseries_recalculation(if experiment.start_date is None:return None+ store = MetricResultStore(experiment_id=experiment.id)metric_uuids: list[str] = []points: dict[str, tuple[str, 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)- config_fp = calculation_config.calculation_key()- row = (- ExperimentMetricResult.objects.filter(- experiment=experiment,- metric_uuid=calculation_config.metric_id,- fingerprint=config_fp,- status=ExperimentMetricResult.Status.COMPLETED,- query_to__gte=run_started_at,- query_to__lte=now,- )- .order_by("-query_to")- .first()- )+ 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(config_fp), row)+ points[calculation_config.metric_id] = (+ compute_recalc_fingerprint(calculation_config.calculation_key()),+ row,+ )if not points:return None@@ -103,11 +91,7 @@ def sync_timeseries_recalculation(.first())if recalculation is not None and recalculation.query_to is not None:- already_copied = set(- ExperimentMetricResult.objects.filter(- experiment=experiment, query_to=recalculation.query_to, metric_uuid__in=points.keys()- ).values_list("metric_uuid", flat=True)- )+ already_copied = store.metric_uuids_stored_at(recalculation.query_to, points.keys())missing = {uuid: point for uuid, point in points.items() if uuid not in already_copied}if not missing:return None@@ -125,18 +109,19 @@ def sync_timeseries_recalculation(if already_covered or get_active_recalculation(experiment) is not None:return None+ window = MetricResultStore.sync_copy_window(newest_point)recalculation = ExperimentMetricsRecalculation.objects.create(team=experiment.team,experiment=experiment,status=ExperimentMetricsRecalculation.Status.COMPLETED,trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC,- query_to=newest_point + _WINDOW_OFFSET,+ query_to=window,started_at=now,completed_at=now,total_metrics=len(metric_uuids),metric_uuids=metric_uuids,)- _copy_points(experiment, newest_point + _WINDOW_OFFSET, points, now)+ _copy_points(experiment, window, points, now)copied = len(points)logger.info(