: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
feat(experiments): classify byte-capped canary direct scans as uncheckable (#98284)
Juraj Majerikf9544285da74
diff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.pyindex ef2fc63ec973..440d4c7ec028 100644--- a/products/experiments/backend/temporal/canary_logic.py+++ b/products/experiments/backend/temporal/canary_logic.py@@ -21,7 +21,7 @@ The bug class this guards (multi-node ClickHouse read-your-writes, seeRunbook:- Outcomes land in Prometheus via the pushgateway (job ``experiment_precompute_canary``):- ``experiment_precompute_canary_outcomes{outcome=pass|divergence|path_flip|error|skipped}``,+ ``experiment_precompute_canary_outcomes{outcome=pass|divergence|path_flip|uncheckable|error|skipped}``,``experiment_precompute_canary_max_deviation{check=stability|correctness}``, and``experiment_precompute_canary_last_run_timestamp``. Suggested alerts:``outcomes{outcome="divergence"} > 0`` (experiment results unstable between refreshes or cache content@@ -51,6 +51,7 @@ from prometheus_client import Gaugefrom posthog.schema import ExperimentQuery, PrecomputationModefrom posthog.clickhouse.query_tagging import tags_context+from posthog.errors import CHQueryErrorTooManyBytesfrom posthog.metrics import pushed_metrics_registryfrom posthog.models.scoping import team_scope@@ -71,6 +72,7 @@ from products.experiments.backend.temporal.models import (OUTCOME_PASS,OUTCOME_PATH_FLIP,OUTCOME_SKIPPED,+ OUTCOME_UNCHECKABLE,CanaryMetricResult,CanaryMetricTarget,CanaryOutcome,@@ -276,11 +278,13 @@ def _stability_violated(metric_type: str, run_a: CanaryRunSnapshot, run_b: Canardef evaluate_canary_runs(- metric_type: str, run_a: CanaryRunSnapshot, run_b: CanaryRunSnapshot, run_c: CanaryRunSnapshot+ metric_type: str, run_a: CanaryRunSnapshot, run_b: CanaryRunSnapshot, run_c: CanaryRunSnapshot | None) -> CanaryVerdict:- """Compare the three runs: A↔B is the stability check, B↔C the correctness check (B is adjacent in- time to C, minimizing live-ingestion drift)."""- runs = (run_a, run_b, run_c)+ """Compare the runs: A↔B is the stability check, B↔C the correctness check (B is adjacent in+ time to C, minimizing live-ingestion drift). run_c is None when the direct scan cannot execute+ under the per-query byte cap: stability is still checked, and a clean pair verdicts as+ uncheckable rather than pass because correctness stays unverified."""+ runs = tuple(run for run in (run_a, run_b, run_c) if run is not None)if any(not run.variants for run in runs):return CanaryVerdict(outcome=OUTCOME_SKIPPED, detail="empty results (no exposures yet)")@@ -311,8 +315,21 @@ def evaluate_canary_runs()stability_deviation = _max_deviation(run_a, run_b)+ stability_broken = _stability_violated(metric_type, run_a, run_b)++ if run_c is None:+ return CanaryVerdict(+ outcome=OUTCOME_DIVERGENCE if stability_broken else OUTCOME_UNCHECKABLE,+ stability_deviation=stability_deviation,+ detail=(+ "deviation beyond tolerance"+ if stability_broken+ else "direct scan exceeds the byte cap; correctness not checked"+ ),+ )+correctness_deviation = _max_deviation(run_b, run_c, min_sum_delta=MIN_CORRECTNESS_SUM_DELTA)- diverged = _stability_violated(metric_type, run_a, run_b) or correctness_deviation > LOOSE_TOLERANCE+ diverged = stability_broken or correctness_deviation > LOOSE_TOLERANCEreturn CanaryVerdict(outcome=OUTCOME_DIVERGENCE if diverged else OUTCOME_PASS,@@ -362,12 +379,26 @@ def _execute_canary_run()+def _log_canary_run_failed(target: CanaryMetricTarget, label: str, query_id: str) -> None:+ logger.warning(+ "experiment_precompute_canary_run_failed",+ team_id=target.team_id,+ experiment_id=target.experiment_id,+ metric_uuid=target.metric_uuid,+ run_label=label,+ query_id=query_id,+ exc_info=True,+ )++def run_metric_canary_sync(target: CanaryMetricTarget) -> CanaryMetricResult:"""Run one metric three times (precomputed, precomputed, direct) and compare.Deterministic dead ends (experiment/metric gone, unparseable definition) return a skipped result.Query failures raise so Temporal retries the whole triple — the comparisons require runs adjacent in- time, so retrying a single run against stale siblings would skew the pair.+ time, so retrying a single run against stale siblings would skew the pair. One exception: the direct+ scan hitting the per-query byte cap is deterministic for the data window, so it yields an uncheckable+ verdict instead of burning another full scan per retry."""close_old_connections()@@ -399,23 +430,31 @@ def run_metric_canary_sync(target: CanaryMetricTarget) -> CanaryMetricResult:canary_id = uuid.uuid4().hex[:12]runs: list[CanaryRunSnapshot] = []+ direct_scan_uncheckable = Falsefor label, mode in _CANARY_RUNS:query_id = f"experiment-canary-{canary_id}-{label}"try:runs.append(_execute_canary_run(experiment, metric, mode, label, query_id))- except Exception:- logger.warning(- "experiment_precompute_canary_run_failed",+ except CHQueryErrorTooManyBytes:+ if label != "c":+ # A forced-precomputed run that falls back to the direct scan can hit the cap too;+ # that failure is what a user's read would see, so it stays an error.+ _log_canary_run_failed(target, label, query_id)+ raise+ direct_scan_uncheckable = True+ logger.info(+ "experiment_precompute_canary_direct_scan_uncheckable",team_id=target.team_id,experiment_id=target.experiment_id,metric_uuid=target.metric_uuid,- run_label=label,query_id=query_id,- exc_info=True,)+ except Exception:+ _log_canary_run_failed(target, label, query_id)raise- verdict = evaluate_canary_runs(metric_type, *runs)+ 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/models.py b/products/experiments/backend/temporal/models.pyindex f687ff79008f..00bec875e738 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -6,17 +6,22 @@ from posthog.dataclasses import frozen# Shared by the workflow definition, the schedule, and the management command.CANARY_WORKFLOW_NAME = "experiment-precompute-canary"-CanaryOutcome = Literal["pass", "divergence", "path_flip", "error", "skipped"]+CanaryOutcome = Literal["pass", "divergence", "path_flip", "uncheckable", "error", "skipped"]OUTCOME_PASS: Final = "pass"OUTCOME_DIVERGENCE: Final = "divergence"OUTCOME_PATH_FLIP: Final = "path_flip"+# The direct-scan ground truth cannot execute under the per-query byte cap, so correctness is+# unverifiable for this metric. Stability was still checked. Kept separate from "error" so the+# error gauge only counts unexpected failures.+OUTCOME_UNCHECKABLE: Final = "uncheckable"OUTCOME_ERROR: Final = "error"OUTCOME_SKIPPED: Final = "skipped"ALL_OUTCOMES: tuple[CanaryOutcome, ...] = (OUTCOME_PASS,OUTCOME_DIVERGENCE,OUTCOME_PATH_FLIP,+ OUTCOME_UNCHECKABLE,OUTCOME_ERROR,OUTCOME_SKIPPED,)diff --git a/products/experiments/backend/temporal/test_canary_logic.py b/products/experiments/backend/temporal/test_canary_logic.pyindex b83738fcf655..ab8b528ba6de 100644--- a/products/experiments/backend/temporal/test_canary_logic.py+++ b/products/experiments/backend/temporal/test_canary_logic.py@@ -12,6 +12,7 @@ import requestsfrom parameterized import parameterizedfrom posthog.clickhouse.query_tagging import get_query_tags+from posthog.errors import CHQueryErrorTooManyBytesfrom products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetricfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig@@ -28,6 +29,7 @@ from products.experiments.backend.temporal.models import (OUTCOME_PASS,OUTCOME_PATH_FLIP,OUTCOME_SKIPPED,+ OUTCOME_UNCHECKABLE,CanaryMetricResult,CanaryMetricTarget,CanaryOutcome,@@ -178,6 +180,17 @@ class TestEvaluateCanaryRuns:verdict = evaluate_canary_runs(metric_type, _snapshot("a", a), _snapshot("b", b), _snapshot("c", c))assert verdict.outcome == expected+ @parameterized.expand(+ [+ ("stable_pair_is_uncheckable", _BASE, OUTCOME_UNCHECKABLE),+ ("unstable_pair_still_diverges", {"control": (1005.0, 10000), "test": (1100.0, 10000)}, OUTCOME_DIVERGENCE),+ ]+ )+ def test_missing_direct_run(self, _name, b_variants, expected):+ verdict = evaluate_canary_runs("funnel", _snapshot("a", _BASE), _snapshot("b", b_variants), None)+ assert verdict.outcome == expected+ assert verdict.correctness_deviation is None+def test_path_flip_is_not_divergence(self):diverged = {"control": (1300.0, 12000), "test": (1100.0, 10000)}verdict = evaluate_canary_runs(@@ -471,6 +484,30 @@ class TestRunMetricCanary(BaseTest):with pytest.raises(RuntimeError):run_metric_canary_sync(self._target(experiment, metric["uuid"]))+ def test_direct_scan_byte_cap_is_uncheckable_not_error(self):+ metric = _funnel_metric()+ experiment = self._experiment([metric])+ side_effects = [+ _snapshot("a", _BASE),+ _snapshot("b", _BASE),+ CHQueryErrorTooManyBytes("byte cap", code=307),+ ]+ with patch("products.experiments.backend.temporal.canary_logic._execute_canary_run", side_effect=side_effects):+ result = run_metric_canary_sync(self._target(experiment, metric["uuid"]))++ assert result.outcome == OUTCOME_UNCHECKABLE+ assert len(result.runs) == 2++ def test_precomputed_run_byte_cap_still_raises(self):+ metric = _funnel_metric()+ experiment = self._experiment([metric])+ with patch(+ "products.experiments.backend.temporal.canary_logic._execute_canary_run",+ side_effect=CHQueryErrorTooManyBytes("byte cap", code=307),+ ):+ with pytest.raises(CHQueryErrorTooManyBytes):+ run_metric_canary_sync(self._target(experiment, metric["uuid"]))+def _result(outcome: CanaryOutcome, **kwargs) -> CanaryMetricResult:target = CanaryMetricTarget(team_id=1, experiment_id=2, metric_uuid="m-uuid", metric_type="funnel")