: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
fix(experiments): use one rule for the current metric result (#109498)
Anders86d43ce44fd0
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 396dce8f51b1..c0cef57f7cd4 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -69,6 +69,7 @@ from products.experiments.backend.logic.result_stats import MetricTimeseriesfrom products.experiments.backend.logic.timeseries_text import ExperimentTimeseriesFormatterfrom products.experiments.backend.metric_calculation.config import (ExperimentCalculationSettings,+ build_primary_calculation_configs,saved_metric_calculation_keys,stamp_calculation_keys,)@@ -2751,26 +2752,28 @@ class ExperimentService:completed_metadata["duration"] = int((experiment.end_date - experiment.start_date).total_seconds())# Look up whether the primary metric reached significance from the- # latest cached result in Postgres (ExperimentMetricResult). This is+ # current stored result in Postgres (ExperimentMetricResult). This is# safe to call here because it's a simple indexed lookup — it reads# previously cached results, never triggers a ClickHouse query or# result computation. Returns None immediately if no results exist yet.try:- first_metric = experiment.metrics[0] if experiment.metrics else None- if first_metric and first_metric.get("uuid"):- 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- # validation stopped the analysis, so only computed values decide.- variant_results = metric_result.result.get("variant_results") or []- computed = [- variant["significant"]- for variant in variant_results- if isinstance(variant, dict) and isinstance(variant.get("significant"), bool)- ]- if computed:- completed_metadata["significant"] = any(computed)+ primary_metric = next(iter(build_primary_calculation_configs(experiment)), None)+ outcome = (+ MetricResultStore(experiment_id=experiment.id).current_outcome(primary_metric)+ if primary_metric is not None+ else None+ )+ if outcome is not None:+ # 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+ # validation stopped the analysis, so only computed values decide.+ computed = [+ variant["significant"]+ for variant in outcome.variant_results+ if isinstance(variant.get("significant"), bool)+ ]+ if computed:+ completed_metadata["significant"] = any(computed)except Exception:logger.exception("Failed to look up metric significance",diff --git a/products/experiments/backend/metric_calculation/config.py b/products/experiments/backend/metric_calculation/config.pyindex 640849875830..1b9ee46eae3f 100644--- a/products/experiments/backend/metric_calculation/config.py+++ b/products/experiments/backend/metric_calculation/config.py@@ -48,7 +48,7 @@ from products.experiments.backend.metric_resolution import (saved_metric_link_role,saved_metric_links,)-from products.experiments.backend.models.experiment import Experiment+from products.experiments.backend.models.experiment import Experiment, metric_display_rankfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigif TYPE_CHECKING:@@ -212,7 +212,8 @@ class ExperimentCalculationSettings:def from_experiment(cls, experiment: Experiment, *, team_config: TeamExperimentsConfig | None = None) -> "ExperimentCalculationSettings":- """Settings from the current fields of the experiment, which does not need to be saved."""+ """Settings from the current fields of the experiment, which does not need to be saved. A caller that+ builds the configs of several experiments of one team passes the team's config to read it once."""return cls.from_configuration(team=experiment.team,feature_flag=experiment.feature_flag,@@ -284,18 +285,36 @@ class MetricCalculationConfig:return hashlib.sha256(encoded.encode("utf-8")).hexdigest()-def build_calculation_configs(experiment: Experiment) -> list[MetricCalculationConfig]:+def build_calculation_configs(+ experiment: Experiment, *, team_config: TeamExperimentsConfig | None = None+) -> list[MetricCalculationConfig]:"""One calculation config per metric that `get_metrics_for_calculation` returns, in that order."""metrics = get_metrics_for_calculation(experiment)if not metrics:return []- settings = ExperimentCalculationSettings.from_experiment(experiment)+ settings = ExperimentCalculationSettings.from_experiment(experiment, team_config=team_config)return [settings.build_metric_config(metric_id=metric.uuid, role=metric.role, definition=metric.definition)for metric in metrics]+def build_primary_calculation_configs(+ experiment: Experiment, *, team_config: TeamExperimentsConfig | None = None+) -> list[MetricCalculationConfig]:+ """The configs of the primary metrics that the experiment calculates, inline and saved, in the order the+ results page lists them. The first one is the metric the product calls the experiment's primary metric."""+ rank = metric_display_rank(experiment.primary_metrics_ordered_uuids)+ primary = [+ calculation_config+ for calculation_config in build_calculation_configs(experiment, team_config=team_config)+ if calculation_config.role == "primary"+ ]+ # Stable, so metrics missing from the ordering keep the order of `get_metrics_for_calculation` behind the+ # ordered ones.+ return sorted(primary, key=lambda calculation_config: rank(calculation_config.metric_id))++def get_metric_calculation_config(experiment: Experiment, metric_uuid: str) -> MetricCalculationConfig | None:"""The config that `build_calculation_configs` builds for one metric, or None when the experimentcalculates no metric with this uuid."""diff --git a/products/experiments/backend/metric_calculation/results.py b/products/experiments/backend/metric_calculation/results.pyindex b0e6fcae1c5e..4d35d6bf428f 100644--- a/products/experiments/backend/metric_calculation/results.py+++ b/products/experiments/backend/metric_calculation/results.py@@ -1,13 +1,14 @@"""Reads and writes of stored metric results.`MetricResultStore` is the only module that reads or writes `ExperimentMetricResult`. Its named queries and writes-hide three storage conventions from the callers:+hide two storage conventions from the callers:- A recalculation run files its rows under a salted calculation key (`_recalc_fingerprint`), and the daily- timeseries workflows file theirs under the bare key. So the two families never find each other's rows.+ timeseries workflows file theirs under the bare key. So the run reads, the reuse check and the chart never find+ the other family's rows. Only the current outcome reads both, because both hold results of the same calculation.- 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.++The calculation key includes the start date, so no reader needs `query_from` to tell a relaunch apart.Several rows can share `(experiment, metric_uuid, query_to)` once the unique constraint on that key goes. Everyquery that can meet such rows returns the one with the newest `completed_at`, then the highest id. It never looks a@@ -28,8 +29,9 @@ from typing import Anyfrom zoneinfo import ZoneInfofrom django.db import transaction-from django.db.models import F, QuerySet+from django.db.models import F, Q, QuerySetfrom django.db.models.fields.json import KT, KeyTransform+from django.db.models.functions import Leastfrom django.utils import timezone as django_timezoneimport structlog@@ -178,17 +180,9 @@ class MetricResultStore: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 current_outcome(self, calculation_config: MetricCalculationConfig) -> ResultSummary | None:+ """The current result of the metric that `calculation_config` describes. `current_outcomes` defines the rule."""+ return self.current_outcomes({self.experiment_id: calculation_config}).get(self.experiment_id)def previous_completed(self, metric_uuid: str, calculation_key: str, *, before: datetime@@ -416,27 +410,33 @@ class MetricResultStore: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.+ def current_outcomes(config_by_experiment: Mapping[int, MetricCalculationConfig]) -> dict[int, ResultSummary]:+ """For each experiment, the current result of the metric that its calculation config describes, in one query.++ The current result is the completed row whose data ends last among the rows filed under the config's+ calculation key, by a recalculation run or by the daily workflows. A row's data ends at its query_to, or at+ its completed_at when that comes first. A backfill stamps the current day with the end of that day, but the+ row holds data only up to the moment the backfill ran, so a later run of the same day must win over it. A row+ under another key was computed from another configuration, for example from the start date before a+ relaunch, so it does not count. The end of the data counts, not the newest write, because a backfill writes+ past windows after the newer ones."""- if not metric_uuid_by_experiment:+ if not config_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"),+ filed_under_config = Q()+ for experiment_id, calculation_config in config_by_experiment.items():+ key = calculation_config.calculation_key()+ filed_under_config |= Q(+ experiment_id=experiment_id,+ metric_uuid=calculation_config.metric_id,+ fingerprint__in=[key, _recalc_fingerprint(key)],)- .order_by("experiment_id", "metric_uuid", "-query_to", F("completed_at").desc(nulls_last=True), "-id")- .distinct("experiment_id", "metric_uuid")+ rows = (+ ExperimentMetricResult.objects.filter(filed_under_config, status=_COMPLETED)+ # Postgres LEAST skips a NULL, so a row without completed_at ranks by its query_to.+ .alias(data_until=Least("query_to", "completed_at"))+ .order_by("experiment_id", F("data_until").desc(), F("completed_at").desc(nulls_last=True), "-id")+ .distinct("experiment_id").values("experiment_id","metric_uuid",@@ -449,8 +449,6 @@ class MetricResultStore:)summaries: dict[int, ResultSummary] = {}for row in rows:- if metric_uuid_by_experiment.get(row["experiment_id"]) != row["metric_uuid"]:- continuevariant_results = row["variant_results"] if isinstance(row["variant_results"], list) else []summaries[row["experiment_id"]] = ResultSummary(completed_at=row["completed_at"],diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 96a77435c6e9..f9ac11e8afe9 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -2956,10 +2956,11 @@ class ExperimentSetupPreviousExperimentSerializer(serializers.Serializer):outcome = ExperimentSetupOutcomeSerializer(allow_null=True,help_text=(- "From the completed result that covers the latest data in the experiment's current run. A funnel or "- "a mean primary metric is chosen over a retention or a ratio one, because only its samples are the "- "analyzed population. Null when no result exists for that run, which is also the case for older "- "metric definitions that results are never stored for."+ "From the completed result that covers the latest data under the experiment's current configuration. "+ "A funnel or a mean primary metric is chosen over a retention or a ratio one, because only its samples "+ "are the analyzed population. Null when no result exists for that configuration, for example after a "+ "relaunch or a settings edit until the results are recalculated, and for older metric definitions that "+ "results are never stored for."),)diff --git a/products/experiments/backend/setup_context.py b/products/experiments/backend/setup_context.pyindex f66e5d36efed..c13a1b4d488c 100644--- a/products/experiments/backend/setup_context.py+++ b/products/experiments/backend/setup_context.py@@ -54,19 +54,18 @@ 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.config import (+ MetricCalculationConfig,+ build_primary_calculation_configs,+ team_experiments_configs,+)from products.experiments.backend.metric_calculation.results import MetricResultStore-from products.experiments.backend.metric_resolution import is_scheduled_metricfrom products.experiments.backend.metric_utils import (collect_metric_events_and_action_ids,filter_metric_group_ids_by_event,resolve_action_events,)-from products.experiments.backend.models.experiment import (- Experiment,- ExperimentSavedMetric,- ExperimentToSavedMetric,- metric_display_rank,-)+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfigfrom products.experiments.backend.variant_distribution import is_evenly_distributed@@ -1038,11 +1037,11 @@ def _link_type(link: ExperimentToSavedMetric) -> str:@frozenclass OutcomeMetric:- uuid: str+ calculation_config: MetricCalculationConfigmetric_type: str-def _outcome_metric(experiment: Experiment) -> OutcomeMetric | None:+def _outcome_metric(experiment: Experiment, team_config: TeamExperimentsConfig) -> OutcomeMetric | None:"""The primary metric whose stored result this section reports.Only metrics that can have a stored result count, so a legacy metric listed first never hides@@ -1051,24 +1050,15 @@ def _outcome_metric(experiment: Experiment) -> OutcomeMetric | None:analyzed population, which is the fact the outcome exists to carry."""candidates = [- OutcomeMetric(uuid=str(metric["uuid"]), metric_type=str(metric["metric_type"]))- for metric in [- *(metric for metric in experiment.metrics or [] if isinstance(metric, dict)),- *(- link.saved_metric.query- for link in _saved_metric_links(experiment)- if _link_type(link) == "primary" and isinstance(link.saved_metric.query, dict)- ),- ]- if is_scheduled_metric(metric)+ OutcomeMetric(+ calculation_config=calculation_config, metric_type=str(calculation_config.definition["metric_type"])+ )+ for calculation_config in build_primary_calculation_configs(experiment, team_config=team_config)]- rank = metric_display_rank(experiment.primary_metrics_ordered_uuids)- # Stable, so a metric the experiment does not order keeps its declared place behind the ordered ones.- ordered = sorted(candidates, key=lambda candidate: rank(candidate.uuid))- for candidate in ordered:+ for candidate in candidates:if candidate.metric_type in EXPOSURE_SHAPED_METRIC_TYPES:return candidate- return ordered[0] if ordered else None+ return candidates[0] if candidates else None@frozen@@ -1163,14 +1153,14 @@ def _multiple_variant_handling(exposure_criteria: dict[str, Any]) -> str:def _outcomes(outcome_metrics: dict[int, OutcomeMetric]) -> dict[int, ExperimentOutcome]:- """Stored result that describes each experiment's current run, in one query.+ """The current stored result of each experiment's outcome metric, in one query.A legacy Trends or Funnels metric never has a stored result, with or without a uuid, becauseboth writers of `ExperimentMetricResult` build the metric from its `metric_type`. Itsexperiment correctly gets no outcome."""summaries = MetricResultStore.current_outcomes(- {experiment_id: metric.uuid for experiment_id, metric in outcome_metrics.items()}+ {experiment_id: metric.calculation_config for experiment_id, metric in outcome_metrics.items()})outcomes: dict[int, ExperimentOutcome] = {}for experiment_id, summary in summaries.items():@@ -1219,7 +1209,7 @@ def _control_baseline_value(def get_previous_experiments(experiments: QuerySet[Experiment], *, limit: int) -> PreviousExperiments:rows = list(experiments.exclude(deleted=True)- .select_related("feature_flag")+ .select_related("feature_flag", "team").prefetch_related(Prefetch("experimenttosavedmetric_set",@@ -1230,9 +1220,15 @@ def get_previous_experiments(experiments: QuerySet[Experiment], *, limit: int) -.order_by(F("start_date").desc(nulls_last=True), "-created_at", "-id")[:limit])- outcome_metrics = {- experiment.id: metric for experiment in rows if (metric := _outcome_metric(experiment)) is not None- }+ # A draft has no current result: rows from before a reset carry the earlier start date in their key.+ launched_rows = [experiment for experiment in rows if experiment.start_date is not None]+ # A calculation key resolves the team's experiment defaults, so read them once per team, not once per experiment.+ team_configs = team_experiments_configs({experiment.team_id for experiment in launched_rows})+ outcome_metrics: dict[int, OutcomeMetric] = {}+ for experiment in launched_rows:+ metric = _outcome_metric(experiment, team_configs[experiment.team_id])+ if metric is not None:+ outcome_metrics[experiment.id] = metricoutcomes = _outcomes(outcome_metrics)previous: list[PreviousExperiment] = []diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 2fe13f534df1..8500be435cea 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -100,7 +100,11 @@ 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 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.+Every read and write of `ExperimentMetricResult` goes through `MetricResultStore` (`metric_calculation/results.py`), so the salt and the sync's copy window stay in one module.+The current result of a metric (`current_outcome`) is the completed row whose data ends last under the metric's current calculation key, salted or bare.+A row's data ends at the earlier of its `query_to` and its `completed_at`, because the backfill stamps the current day with the end of that day but holds data only up to the moment it ran.+The experiment-completed event reads it for the first primary metric in display order, inline or saved, and the setup context reads it for its outcomes.+A backfilled past window does not win over a newer window, a backfilled current day does not win over a later run of that day, and a row under an earlier configuration, for example from before a relaunch, does not count.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.diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex df3a92615a38..9331aea5c5b3 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -50,6 +50,7 @@ from products.experiments.backend.experiment_service import (_resolve_scalar_updates,)from products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.metric_resolution import METRIC_BUILDERSfrom products.experiments.backend.metric_validation import (extract_entity_nodes,@@ -73,6 +74,12 @@ from products.surveys.backend.models import Surveyfrom products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable+def _calculation_key(experiment: Experiment, metric_uuid: str) -> str:+ calculation_config = get_metric_calculation_config(Experiment.objects.get(pk=experiment.pk), metric_uuid)+ assert calculation_config is not None+ return calculation_config.calculation_key()++def _stored_metric_result(*significant: bool | None) -> dict[str, Any]:# The shape recalculation stores: significance lives on each variant, and the legacy# top-level field stays null. A variant's significance is null when validation stopped the@@ -3509,6 +3516,7 @@ class TestExperimentService(APIBaseTest):ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid=metric_uuid,+ fingerprint=_calculation_key(experiment, metric_uuid),query_from=experiment.start_date,query_to=timezone.now(),status=ExperimentMetricResult.Status.COMPLETED,@@ -3525,6 +3533,71 @@ class TestExperimentService(APIBaseTest):metadata = completed_call.args[2]assert metadata["significant"] is True+ @parameterized.expand(+ [+ # A backfill stores a past window after the newest window was written.+ ("newest_window_not_newest_write", "backfill", False),+ ("result_of_an_earlier_configuration", "stale_configuration", False),+ ("saved_primary_metric", "saved_metric", True),+ ("metric_listed_first_on_the_results_page", "display_order", False),+ ]+ )+ @patch("products.experiments.backend.experiment_service.report_user_action")+ def test_end_experiment_reads_the_current_result_of_the_primary_metric(+ self, _name: str, case: str, expected_significant: bool, mock_report_user_action: MagicMock+ ) -> None:+ now = timezone.now()+ rows: list[tuple[str, str, datetime, datetime, bool]] = []+ if case == "saved_metric":+ saved_metric = ExperimentSavedMetric.objects.create(+ team=self.team, name="Saved", query={**self._DEFAULT_METRIC, "uuid": "saved-m"}+ )+ experiment = self._create_running_experiment(+ name=f"Current {case}",+ feature_flag_key=f"current-{case}",+ metrics=[],+ primary_metrics_ordered_uuids=None,+ saved_metrics_ids=[{"id": saved_metric.id, "metadata": {"type": "primary"}}],+ )+ rows.append(("saved-m", _calculation_key(experiment, "saved-m"), now, now, True))+ elif case == "display_order":+ experiment = self._create_running_experiment(+ name=f"Current {case}",+ feature_flag_key=f"current-{case}",+ metrics=[self._DEFAULT_METRIC, {**self._DEFAULT_METRIC, "uuid": "m2"}],+ primary_metrics_ordered_uuids=["m2", "m1"],+ )+ rows.append(("m1", _calculation_key(experiment, "m1"), now, now, True))+ rows.append(("m2", _calculation_key(experiment, "m2"), now, now, False))+ else:+ experiment = self._create_running_experiment(name=f"Current {case}", feature_flag_key=f"current-{case}")+ key = _calculation_key(experiment, "m1")+ if case == "backfill":+ rows.append(("m1", _recalc_fingerprint(key), now - timedelta(hours=1), now - timedelta(hours=1), False))+ rows.append(("m1", key, now - timedelta(days=2), now, True))+ else:+ rows.append(("m1", key, now - timedelta(days=1), now - timedelta(days=1), False))+ rows.append(("m1", "key-of-the-configuration-before-an-edit", now, now, True))+ assert experiment.start_date is not None+ for metric_uuid, fingerprint, query_to, completed_at, significant in rows:+ ExperimentMetricResult.objects.create(+ experiment=experiment,+ metric_uuid=metric_uuid,+ fingerprint=fingerprint,+ query_from=experiment.start_date,+ query_to=query_to,+ status=ExperimentMetricResult.Status.COMPLETED,+ result=_stored_metric_result(significant),+ completed_at=completed_at,+ )++ self._service().end_experiment(experiment, request=MagicMock())++ completed_call = next(+ call for call in mock_report_user_action.call_args_list if call.args[1] == "experiment completed"+ )+ assert completed_call.args[2]["significant"] is expected_significant+@patch("products.experiments.backend.experiment_service.report_user_action")def test_end_experiment_completed_event_omits_significant_when_no_results(self, mock_report_user_action):experiment = self._create_running_experiment(name="End No Results", feature_flag_key="end-no-results-flag")@@ -3644,6 +3717,7 @@ class TestExperimentService(APIBaseTest):ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid=experiment.metrics[0]["uuid"],+ fingerprint=_calculation_key(experiment, experiment.metrics[0]["uuid"]),query_from=experiment.start_date,query_to=timezone.now(),status=ExperimentMetricResult.Status.COMPLETED,diff --git a/products/experiments/backend/test/test_metric_result_store.py b/products/experiments/backend/test/test_metric_result_store.pyindex 9d9648dbb563..9999e0a2d048 100644--- a/products/experiments/backend/test/test_metric_result_store.py+++ b/products/experiments/backend/test/test_metric_result_store.py@@ -109,13 +109,11 @@ class TestMetricResultStore(BaseTest):)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+ case "current_outcome":+ summary = store.current_outcome(calculation_config)+ assert summary is not None and summary.baseline_samples is not Nonereturn [int(summary.baseline_samples)]raise AssertionError(f"unknown reader {reader}")@@ -126,9 +124,8 @@ class TestMetricResultStore(BaseTest):"for_run","latest_daily_point","timeseries",- "last_completed","previous_completed",- "current_outcomes",+ "current_outcome",)for tie in ("newer_write_wins", "higher_id_wins_between_equal_writes")]@@ -174,6 +171,28 @@ class TestMetricResultStore(BaseTest):assert list(timeseries.by_day) == [_WINDOW_DAY]assert _samples(timeseries.by_day[_WINDOW_DAY]) == [2]+ def test_the_current_outcome_is_the_row_whose_data_ends_last(self) -> None:+ experiment = self._experiment()+ calculation_config = get_metric_calculation_config(experiment, "m1")+ assert calculation_config is not None+ key = calculation_config.calculation_key()+ # A backfill that ran at 10:00 on 9 January stamps that day with the end of the day.+ self._row(experiment, key, query_to=_WINDOW, completed_at=_WINDOW - timedelta(hours=14), samples=1)+ # A recalculation run at 14:00 on the same day holds newer data under an earlier query_to.+ self._row(+ experiment,+ _recalc_fingerprint(key),+ query_to=_WINDOW - timedelta(hours=10),+ completed_at=_WINDOW - timedelta(hours=9, minutes=55),+ samples=2,+ )+ # A backfill of 8 January written after both, so the write time alone picks it.+ self._row(+ experiment, key, query_to=_WINDOW - timedelta(days=1), completed_at=_WINDOW - timedelta(hours=9), samples=3+ )++ assert self._read("current_outcome", experiment, calculation_config) == [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()diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex cc573f2645a3..59e464a0cdef 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -8768,9 +8768,12 @@ class TestExperimentSetupContextEndpoint(ClickhouseTestMixin, APILicensedTest):start_date=started_at,metrics=[{"kind": "ExperimentMetric", "metric_type": "mean", "uuid": "populated-metric"}],)+ calculation_config = get_metric_calculation_config(experiment, "populated-metric")+ assert calculation_config is not NoneExperimentMetricResult.objects.create(experiment=experiment,metric_uuid="populated-metric",+ fingerprint=calculation_config.calculation_key(),query_from=started_at,query_to=timezone.now(),status=ExperimentMetricResult.Status.COMPLETED,diff --git a/products/experiments/backend/test/test_setup_context.py b/products/experiments/backend/test/test_setup_context.pyindex 060222b3db53..ba16c4347c84 100644--- a/products/experiments/backend/test/test_setup_context.py+++ b/products/experiments/backend/test/test_setup_context.py@@ -24,6 +24,8 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (DEFAULT_EXPOSURE_EVENT,EXPERIMENT_EXPOSURE_EVENT,)+from products.experiments.backend.metric_calculation.config import get_metric_calculation_config+from products.experiments.backend.metric_calculation.results import _recalc_fingerprintfrom products.experiments.backend.models.experiment import (EXPOSURE_FROZEN_GROUP_KEY,Experiment,@@ -78,6 +80,12 @@ def _retention_metric(uuid: str, start_event: str = "signup", completion_event:}+def _key(experiment: Experiment, metric_uuid: str) -> str:+ calculation_config = get_metric_calculation_config(experiment, metric_uuid)+ assert calculation_config is not None+ return calculation_config.calculation_key()++def _payload_of_each_section() -> dict[str, Any]:"""Section name to the dataclass its `data` carries."""return {@@ -727,6 +735,7 @@ class TestPostgresSections(APIBaseTest):ExperimentMetricResult.objects.create(experiment=saved_primary,metric_uuid="saved-primary-uuid",+ fingerprint=_key(saved_primary, "saved-primary-uuid"),query_from=now - timedelta(days=30),query_to=now - timedelta(days=completed_days_ago),status=status,@@ -736,6 +745,7 @@ class TestPostgresSections(APIBaseTest):ExperimentMetricResult.objects.create(experiment=three_way,metric_uuid="inline-primary",+ fingerprint=_key(three_way, "inline-primary"),query_from=now - timedelta(days=10),query_to=now,status=ExperimentMetricResult.Status.COMPLETED,@@ -743,7 +753,7 @@ class TestPostgresSections(APIBaseTest):completed_at=now,)- with self.assertNumQueries(3):+ with self.assertNumQueries(4):previous = get_previous_experiments(Experiment.objects.filter(team_id=self.team.pk), limit=10)by_name = {experiment.name: experiment for experiment in previous.experiments}@@ -829,22 +839,37 @@ class TestPostgresSections(APIBaseTest):def test_the_outcome_comes_from_the_current_run_and_the_latest_data(self) -> None:now = timezone.now()start = now - timedelta(days=10)- experiment = self._experiment("relaunched", start_date=start, metrics=[_mean_metric("inline-primary")])- for query_from, query_to, completed_at, result in [- # Reset and relaunch keeps the earlier run's rows, which carry the earlier start date.+ experiment = self._experiment(+ "relaunched", start_date=now - timedelta(days=60), metrics=[_mean_metric("inline-primary")]+ )+ earlier_run_key = _key(experiment, "inline-primary")+ # Reset and relaunch keeps the earlier run's rows, which carry the earlier start date in their key.+ Experiment.objects.filter(pk=experiment.pk).update(start_date=start)+ experiment.refresh_from_db()+ key = _key(experiment, "inline-primary")+ for fingerprint, query_from, query_to, completed_at, result in [(+ earlier_run_key,now - timedelta(days=60),now - timedelta(days=31),now - timedelta(days=31),_stored_result(900, [900], True),),# A backfilled older day, written after the newest day was written.- (start, now - timedelta(days=2), now, _stored_result(20, [20], False)),- (start, now - timedelta(days=1), now - timedelta(hours=2), _stored_result(30, [40], False)),+ (key, start, now - timedelta(days=2), now, _stored_result(20, [20], False)),+ # The newest window, stored by a recalculation run under the salted key.+ (+ _recalc_fingerprint(key),+ start,+ now - timedelta(days=1),+ now - timedelta(hours=2),+ _stored_result(30, [40], False),+ ),]:ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid="inline-primary",+ fingerprint=fingerprint,query_from=query_from,query_to=query_to,status=ExperimentMetricResult.Status.COMPLETED,@@ -859,7 +884,7 @@ class TestPostgresSections(APIBaseTest):assert outcome.analyzed_exposures == 70assert outcome.result_data_through == now - timedelta(days=1)- def test_a_start_date_moved_earlier_keeps_the_outcome(self) -> None:+ def test_a_result_of_an_earlier_configuration_is_not_the_outcome(self) -> None:now = timezone.now()experiment = self._experiment("edited-start", start_date=now - timedelta(days=10), metrics=[_mean_metric("inline-primary")]@@ -867,6 +892,7 @@ class TestPostgresSections(APIBaseTest):ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid="inline-primary",+ fingerprint=_key(experiment, "inline-primary"),query_from=now - timedelta(days=10),query_to=now,status=ExperimentMetricResult.Status.COMPLETED,@@ -877,8 +903,8 @@ class TestPostgresSections(APIBaseTest):previous = get_previous_experiments(Experiment.objects.filter(team_id=self.team.pk), limit=10)- outcome = previous.experiments[0].outcome- assert outcome is not None and outcome.analyzed_exposures == 80+ assert previous.experiments[0].outcome is None+ assert previous.summary.launched_without_results == 1def test_a_draft_does_not_crowd_out_a_launched_experiment(self) -> None:self._experiment("fresh-draft", days_ago=0)@@ -917,6 +943,7 @@ class TestPostgresSections(APIBaseTest):ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid="inline-primary",+ fingerprint=_key(experiment, "inline-primary"),query_from=now - timedelta(days=10),query_to=now,status=ExperimentMetricResult.Status.COMPLETED,@@ -1059,6 +1086,7 @@ class TestPostgresSections(APIBaseTest):ExperimentMetricResult.objects.create(experiment=experiment,metric_uuid=metric_uuid,+ fingerprint=_key(experiment, metric_uuid),query_from=now - timedelta(days=10),query_to=now,status=ExperimentMetricResult.Status.COMPLETED,diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 07a84a71bde0..183ddb320c6c 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -4485,7 +4485,7 @@ export interface ExperimentSetupPreviousExperimentApi {stats_method: string/** Whether the experiment uses a holdout group. */has_holdout: boolean- /** From the completed result that covers the latest data in the experiment's current run. A funnel or a mean primary metric is chosen over a retention or a ratio one, because only its samples are the analyzed population. Null when no result exists for that run, which is also the case for older metric definitions that results are never stored for. */+ /** From the completed result that covers the latest data under the experiment's current configuration. A funnel or a mean primary metric is chosen over a retention or a ratio one, because only its samples are the analyzed population. Null when no result exists for that configuration, for example after a relaunch or a settings edit until the results are recalculated, and for older metric definitions that results are never stored for. */outcome: ExperimentSetupOutcomeApi | null}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5e553352d0b9..71115565e0ff 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46274,7 +46274,7 @@ export namespace Schemas {stats_method: string;/** Whether the experiment uses a holdout group. */has_holdout: boolean;- /** From the completed result that covers the latest data in the experiment's current run. A funnel or a mean primary metric is chosen over a retention or a ratio one, because only its samples are the analyzed population. Null when no result exists for that run, which is also the case for older metric definitions that results are never stored for. */+ /** From the completed result that covers the latest data under the experiment's current configuration. A funnel or a mean primary metric is chosen over a retention or a ratio one, because only its samples are the analyzed population. Null when no result exists for that configuration, for example after a relaunch or a settings edit until the results are recalculated, and for older metric definitions that results are never stored for. */outcome: ExperimentSetupOutcome | null;}