: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): ignore empty breakdowns in metric fingerprints (#105021)
Juraj Majerik18a44013806b
diff --git a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.pyindex 02941cae8cd9..700f43bbe1bb 100644--- a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py+++ b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py@@ -22,6 +22,28 @@ METRIC_FIELDS_TO_IGNORE: set[str] = {}+def _strip_empty_breakdowns(clean_metric: dict) -> None:+ """Remove a breakdownFilter that carries no breakdowns before hashing.++ An empty breakdown list is the same metric config as no breakdowns, but the two dict shapes hash to+ different values. Saved-metric resolution (`_merge_saved_metric_breakdowns`) injects+ `breakdownFilter.breakdowns = []` when the experiment link has none, while the daily timeseries discovery+ and the experiment serializer hash the raw saved query. Without this normalization the same config gets+ two fingerprints, so readers on one convention (timeseries sync, cold-start fallback) never find rows+ written under the other.+ """+ breakdown_filter = clean_metric.get("breakdownFilter")+ if breakdown_filter is None:+ clean_metric.pop("breakdownFilter", None)+ return+ if isinstance(breakdown_filter, dict) and not breakdown_filter.get("breakdowns"):+ remaining = {key: value for key, value in breakdown_filter.items() if key != "breakdowns"}+ if remaining:+ clean_metric["breakdownFilter"] = remaining+ else:+ clean_metric.pop("breakdownFilter")++def compute_metric_fingerprint(metric: dict,start_date: Any,@@ -48,6 +70,7 @@ def compute_metric_fingerprint(clean_metric = deepcopy(metric)for field in METRIC_FIELDS_TO_IGNORE:clean_metric.pop(field, None)+ _strip_empty_breakdowns(clean_metric)# Convert datetime to ISO string for JSON serialization# Always use UTC to ensure consistent fingerprints regardless of user timezonediff --git a/products/experiments/backend/temporal/test_discovery_fingerprints.py b/products/experiments/backend/temporal/test_discovery_fingerprints.pyindex 0f7111f2124f..6721330b291c 100644--- a/products/experiments/backend/temporal/test_discovery_fingerprints.py+++ b/products/experiments/backend/temporal/test_discovery_fingerprints.py@@ -13,9 +13,11 @@ from posthog.temporal.experiments.activities import (from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_methodfrom products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric+from products.experiments.backend.temporal.metric_resolution import find_metric_dictfrom products.feature_flags.backend.models.feature_flag import FeatureFlag-METRIC = {"metric_type": "mean", "uuid": "metric-uuid-1", "source": {"kind": "EventsNode", "event": "test"}}+METRIC_UUID = "metric-uuid-1"+METRIC = {"metric_type": "mean", "uuid": METRIC_UUID, "source": {"kind": "EventsNode", "event": "test"}}# Access the underlying sync functions, patching out close_old_connections which kills the test DB connection_raw_regular_sync = _get_experiment_regular_metrics_for_hour_sync.func # type: ignore[attr-defined]@@ -74,3 +76,42 @@ class TestDiscoveryFingerprints:fingerprints = [r.fingerprint for r in results if r.experiment_id == experiment.id]assert fingerprints == [self._expected_fingerprint(experiment, saved_metric.query)]++ def test_saved_metric_discovery_fingerprint_matches_recalculation_resolution(self) -> None:+ """Discovery hashes the raw saved query; the recalculation side (timeseries sync, cold-start+ fallback) hashes the merged dict from find_metric_dict, which injects an empty breakdown list.+ If the two diverge, the sync never finds the daily points and daily results are never published."""+ experiment, user = self._create_experiment(metrics=[])+ saved_metric = ExperimentSavedMetric.objects.create(+ team=experiment.team,+ name="Saved metric",+ query=METRIC,+ created_by=user,+ )+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved_metric, metadata={})++ with patch("posthog.temporal.experiments.activities.close_old_connections"):+ results = _raw_saved_sync(hour=2)++ discovery_fingerprints = [r.fingerprint for r in results if r.experiment_id == experiment.id]+ merged_dict = find_metric_dict(experiment, METRIC_UUID)+ assert merged_dict is not None+ assert discovery_fingerprints == [self._expected_fingerprint(experiment, merged_dict)]+++ "variant,expected_equal",+ [+ ({**METRIC, "breakdownFilter": {"breakdowns": []}}, True),+ ({**METRIC, "breakdownFilter": {"breakdowns": None}}, True),+ ({**METRIC, "breakdownFilter": None}, True),+ ({**METRIC, "breakdownFilter": {"breakdowns": [{"type": "event", "property": "$os_name"}]}}, False),+ ],+)+def test_only_real_breakdowns_change_the_fingerprint(variant: dict, expected_equal: bool) -> None:+ """Empty breakdown shapes are the same config as no breakdowns and must hash identically, while an+ actual breakdown is a config change that must invalidate cached results."""+ start = datetime.datetime(2026, 1, 1, tzinfo=ZoneInfo("UTC"))+ base_fp = compute_metric_fingerprint(METRIC, start, "bayesian", None)+ variant_fp = compute_metric_fingerprint(variant, start, "bayesian", None)+ assert (variant_fp == base_fp) is expected_equaldiff --git a/products/experiments/backend/test/test_timeseries_sync.py b/products/experiments/backend/test/test_timeseries_sync.pyindex dce99c1af2d1..3e85faa71698 100644--- a/products/experiments/backend/test/test_timeseries_sync.py+++ b/products/experiments/backend/test/test_timeseries_sync.py@@ -139,6 +139,40 @@ class TestSyncTimeseriesRecalculation(BaseTest):assert self._sync(exp) is Noneassert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 1+ def test_finds_points_written_under_the_daily_saved_metric_fingerprint(self):+ """The daily saved-metrics discovery hashes the raw saved query, while the sync resolves the metric+ through find_metric_dict, which injects an empty breakdown list. The two must land on the same+ fingerprint, or every saved metric computes fresh points each morning that are never published."""+ exp = self._experiment("sync-saved", [])+ self._link_saved_metric(exp, "sm1")+ assert exp.start_date is not None++ saved_query = ExperimentSavedMetric.objects.get(team=self.team, name="sm1").query+ daily_fp = compute_metric_fingerprint(+ saved_query,+ exp.start_date,+ get_experiment_stats_method(exp),+ exp.exposure_criteria,+ only_count_matured_users=exp.only_count_matured_users,+ excluded_variants=exp.excluded_variants,+ )+ ExperimentMetricResult.objects.create(+ experiment=exp,+ metric_uuid="sm1",+ fingerprint=daily_fp,+ query_from=exp.start_date,+ query_to=IN_RUN,+ status="completed",+ result={"m": 1},+ )++ recalculation_id = self._sync(exp)++ assert recalculation_id is not None+ recalc = ExperimentMetricsRecalculation.objects.get(id=recalculation_id)+ assert recalc.metric_uuids == ["sm1"]+ assert [r["metric_uuid"] for r in get_run_results(recalc)] == ["sm1"]+def test_leaves_metric_types_the_daily_run_cannot_compute_out_of_the_row(self):exp = self._experiment("sync-retention", [_mean_metric("m1"), _retention_metric("r1")])self._timeseries_point(exp, "m1", IN_RUN, {"m": 1})