: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): Stop canary queries that cannot test the cache (#100496)
Juraj Majerik79c5f5ac6db2
diff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.pyindex 519badde3ecc..12347ecc4670 100644--- a/products/experiments/backend/temporal/canary_logic.py+++ b/products/experiments/backend/temporal/canary_logic.py@@ -130,7 +130,7 @@ def _eligible_experiments() -> list[Experiment]:)if not team_ids:return []- return list(+ experiments = (Experiment.objects.filter(team_id__in=team_ids,start_date__lte=timezone.now() - MIN_EXPERIMENT_RUNTIME,@@ -138,10 +138,14 @@ def _eligible_experiments() -> list[Experiment]:).exclude(deleted=True).exclude(archived=True)- .select_related("team")- # Metric discovery walks saved metrics per experiment; prefetch to avoid an N+1 over the sample.- .prefetch_related("experimenttosavedmetric_set__saved_metric")+ .select_related("team", "feature_flag"))+ # Metric discovery walks saved metrics per experiment; prefetch to avoid an N+1 over the sample.+ experiments = experiments.prefetch_related("experimenttosavedmetric_set__saved_metric")+ # Group-aggregated experiments never precompute (the exposures build can't resolve $group_N), so+ # sampling one buys a guaranteed path flip. The index is a property over the flag's filters JSON,+ # hence the Python-side filter.+ return [e for e in experiments if e.feature_flag.aggregation_group_type_index is None]def _experiment_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:@@ -149,6 +153,21 @@ def _experiment_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:return [m for m in iter_metric_dicts(experiment) if m.get("metric_type") in ELIGIBLE_METRIC_TYPES]+def _uses_data_warehouse(metric_dict: dict[str, Any]) -> bool:+ """True when any side of the metric reads a data warehouse table. These metrics never precompute+ (the precomputed table lacks the join keys), so sampling one buys a guaranteed path flip. The+ fields cover every metric shape; a field absent on a shape is simply None."""+ nodes = [+ metric_dict.get("source"),+ *(metric_dict.get("series") or []),+ metric_dict.get("numerator"),+ metric_dict.get("denominator"),+ metric_dict.get("start_event"),+ metric_dict.get("completion_event"),+ ]+ return any(isinstance(node, dict) and node.get("kind") == "ExperimentDataWarehouseNode" for node in nodes)++def _forensics_targets(experiment_id: int, metric_uuids: list[str] | None) -> list[CanaryMetricTarget]:"""On-demand mode: all eligible metrics of one experiment, quotas and runtime gates ignored."""experiment = (@@ -211,7 +230,7 @@ def sample_canary_targets_sync(inputs: ExperimentPrecomputeCanaryInputs) -> listbreakmetric_type = metric_dict["metric_type"]metric_uuid = metric_dict["uuid"]- if quotas.get(metric_type, 0) <= 0 or metric_uuid in seen_uuids:+ if quotas.get(metric_type, 0) <= 0 or metric_uuid in seen_uuids or _uses_data_warehouse(metric_dict):continueseen_uuids.add(metric_uuid)targets.append(@@ -277,6 +296,23 @@ def _stability_violated(metric_type: str, run_a: CanaryRunSnapshot, run_b: Canarreturn False+def _flipped_sides(run: CanaryRunSnapshot) -> list[str]:+ """Cache sides a forced-precomputed run fell back on. Non-empty means the run is a path flip:+ it read live data, so comparing it against another run tests nothing about the cache."""+ sides = []+ if not run.is_precomputed:+ sides.append(f"{run.label} (exposures)")+ if run.metric_events_path == "direct_scan":+ sides.append(f"{run.label} (metric events)")+ return sides+++def _path_flip_verdict(flipped: list[str]) -> CanaryVerdict:+ # A forced-precomputed run fell back to the direct scan (e.g. the lazy computation executor timed+ # out). Deviation is expected — not a divergence.+ return CanaryVerdict(outcome=OUTCOME_PATH_FLIP, detail=f"run(s) {', '.join(flipped)} fell back to direct scan")++def evaluate_canary_runs(metric_type: str, run_a: CanaryRunSnapshot, run_b: CanaryRunSnapshot, run_c: CanaryRunSnapshot | None) -> CanaryVerdict:@@ -294,16 +330,9 @@ def evaluate_canary_runs(# also explain a variant showing up in one run but not another. Both cache sides count: a run whose# metric-events build fell back to scanning events would compare that scan against run c's scan,# which passes trivially without testing the cache.- flipped = []- for run in (run_a, run_b):- if not run.is_precomputed:- flipped.append(f"{run.label} (exposures)")- if run.metric_events_path == "direct_scan":- flipped.append(f"{run.label} (metric events)")+ flipped = [side for run in (run_a, run_b) for side in _flipped_sides(run)]if flipped:- # A forced-precomputed run fell back to the direct scan (e.g. the lazy computation executor timed- # out). Deviation is expected — not a divergence.- return CanaryVerdict(outcome=OUTCOME_PATH_FLIP, detail=f"run(s) {', '.join(flipped)} fell back to direct scan")+ return _path_flip_verdict(flipped)variant_keys = {frozenset(run.variants) for run in runs}if len(variant_keys) > 1:@@ -433,6 +462,7 @@ def run_metric_canary_sync(target: CanaryMetricTarget) -> CanaryMetricResult:canary_id = uuid.uuid4().hex[:12]runs: list[CanaryRunSnapshot] = []direct_scan_uncheckable = False+ flipped: list[str] = []for label, mode in _CANARY_RUNS:query_id = f"experiment-canary-{canary_id}-{label}"try:@@ -451,12 +481,22 @@ def run_metric_canary_sync(target: CanaryMetricTarget) -> CanaryMetricResult:metric_uuid=target.metric_uuid,query_id=query_id,)+ continueexcept Exception:_log_canary_run_failed(target, label, query_id)raise-- run_c = None if direct_scan_uncheckable else runs[2]- verdict = evaluate_canary_runs(metric_type, runs[0], runs[1], run_c)+ # A flipped run already decides the verdict; the remaining runs would only burn ClickHouse+ # on a comparison that cannot happen.+ if mode == PrecomputationMode.PRECOMPUTED:+ flipped = _flipped_sides(runs[-1])+ if flipped:+ break++ if flipped:+ verdict = _path_flip_verdict(flipped)+ else:+ run_c = None if direct_scan_uncheckable else runs[2]+ verdict = evaluate_canary_runs(metric_type, runs[0], runs[1], run_c)result = CanaryMetricResult(target=target,outcome=verdict.outcome,diff --git a/products/experiments/backend/temporal/metric_resolution.py b/products/experiments/backend/temporal/metric_resolution.pyindex fc282208efc6..c8c234a58e69 100644--- a/products/experiments/backend/temporal/metric_resolution.py+++ b/products/experiments/backend/temporal/metric_resolution.py@@ -61,7 +61,12 @@ def iter_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:for metric in (experiment.metrics or []) + (experiment.metrics_secondary or [])if is_scheduled_metric(metric)]- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ # Calling select_related on the manager would clone the queryset and discard a caller's+ # prefetch cache, re-querying per experiment. Join saved_metric only when nothing is prefetched.+ links = experiment.experimenttosavedmetric_set.all()+ if "experimenttosavedmetric_set" not in getattr(experiment, "_prefetched_objects_cache", {}):+ links = links.select_related("saved_metric")+ for link in links:saved_query = link.saved_metric.queryif is_scheduled_metric(saved_query):dicts.append(_merge_saved_metric_breakdowns(saved_query, link.metadata))diff --git a/products/experiments/backend/temporal/test_canary_logic.py b/products/experiments/backend/temporal/test_canary_logic.pyindex 3d165529797c..7a66f7a712bb 100644--- a/products/experiments/backend/temporal/test_canary_logic.py+++ b/products/experiments/backend/temporal/test_canary_logic.py@@ -5,7 +5,9 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.db import connectionfrom django.test import override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport requests@@ -348,6 +350,23 @@ class TestCanarySampling(BaseTest):targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs())assert [t.metric_type for t in targets] == ["retention"]+ def test_group_aggregated_experiments_are_not_sampled(self):+ self._enable_precompute()+ experiment = self._experiment([_inline_metric("funnel")])+ experiment.feature_flag.filters = {**experiment.feature_flag.filters, "aggregation_group_type_index": 0}+ experiment.feature_flag.save()+ assert sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs()) == []++ def test_data_warehouse_metrics_are_not_sampled(self):+ self._enable_precompute()+ dw_mean = {+ **_inline_metric("mean"),+ "source": {"kind": "ExperimentDataWarehouseNode", "table_name": "stripe_charge"},+ }+ self._experiment([dw_mean, _inline_metric("funnel")])+ targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs())+ assert [t.metric_type for t in targets] == ["funnel"]+def test_quotas_and_per_experiment_cap(self):self._enable_precompute()experiment = self._experiment([_inline_metric("funnel") for _ in range(10)])@@ -375,6 +394,27 @@ class TestCanarySampling(BaseTest):targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs(per_experiment_cap=10))assert {t.metric_uuid for t in targets} == {secondary["uuid"], saved_uuid}+ def test_sampling_reads_saved_metrics_in_one_query(self):+ self._enable_precompute()+ for _ in range(3):+ experiment = self._experiment([])+ saved = ExperimentSavedMetric.objects.create(+ team=self.team,+ name="saved",+ query={"uuid": str(uuid.uuid4()), "kind": "ExperimentMetric", "metric_type": "funnel"},+ )+ ExperimentToSavedMetric.objects.create(+ experiment=experiment, saved_metric=saved, metadata={"type": "primary"}+ )++ with CaptureQueriesContext(connection) as ctx:+ targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs(per_experiment_cap=10))++ assert len(targets) == 3+ # One prefetch on the through table; a query per experiment means the cache was bypassed.+ link_queries = [q for q in ctx.captured_queries if "experimenttosavedmetric" in q["sql"]]+ assert len(link_queries) == 1+def test_forensics_mode_ignores_team_config_and_quotas(self):metrics = [_inline_metric("funnel") for _ in range(5)]experiment = self._experiment(metrics) # precompute NOT enabled for the team@@ -461,6 +501,20 @@ class TestRunMetricCanary(BaseTest):assert modes == ["precomputed", "precomputed", "direct"]assert len(result.runs) == 3+ def test_flipped_first_run_short_circuits(self):+ metric = _funnel_metric()+ experiment = self._experiment([metric])+ # side_effect has one snapshot: a second query would raise StopIteration and fail the test.+ with patch(+ "products.experiments.backend.temporal.canary_logic._execute_canary_run",+ side_effect=[_snapshot("a", _BASE, is_precomputed=False)],+ ) as mock_run:+ result = run_metric_canary_sync(self._target(experiment, metric["uuid"]))++ assert result.outcome == OUTCOME_PATH_FLIP+ assert mock_run.call_count == 1+ assert len(result.runs) == 1+def test_run_tags_team_id_alongside_client_query_id(self):metric = _funnel_metric()experiment = self._experiment([metric])