Skip to content

: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.

feat(experiments): add precompute result-consistency canary (#63040)

Juraj Majerik5b185375c885
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index c15cb68d1bb0..9446e83fdd11 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -131,3 +131,6 @@ SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS: int = get_from_env(
SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS: int = get_from_env(
"SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS", 30, type_cast=int
)
+
+# Incoming webhook for experiment precompute canary divergence alerts. Unset: Slack alerting is skipped.
+EXPERIMENT_CANARY_SLACK_WEBHOOK_URL: str = os.getenv("EXPERIMENT_CANARY_SLACK_WEBHOOK_URL", "")
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index c99873e442fa..de2c7d9c41d8 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -85,6 +85,7 @@ from products.error_tracking.backend.temporal.spike_event_cleanup.schedule impor
from products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import (
create_error_tracking_symbol_set_cleanup_schedule,
)
+from products.experiments.backend.temporal.schedule import create_experiment_precompute_canary_schedule
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
from products.replay_vision.backend.temporal.estimates import create_replay_vision_estimates_schedule
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
@@ -648,6 +649,7 @@ schedules = [
create_purge_deleted_recording_metadata_schedule,
create_experiment_regular_metrics_schedules,
create_experiment_saved_metrics_schedules,
+ create_experiment_precompute_canary_schedule,
create_all_realtime_cohort_calculation_schedules,
create_ingestion_acceptance_test_schedule,
create_warehouse_sources_queue_partition_management_schedule,
diff --git a/products/experiments/backend/management/commands/run_experiment_canary.py b/products/experiments/backend/management/commands/run_experiment_canary.py
new file mode 100644
index 000000000000..73c29a150277
--- /dev/null
+++ b/products/experiments/backend/management/commands/run_experiment_canary.py
@@ -0,0 +1,71 @@
+"""Trigger an on-demand run of the experiment precompute canary.
+
+With ``--experiment-id`` the canary runs in forensics mode against that one experiment (all of its
+funnel/mean/ratio metrics, optionally narrowed with ``--metric-uuid``), regardless of team precompute
+config or experiment runtime. Without it, a regular quota-sampled run is started.
+
+Manual runs post divergences to Slack (marked manual) but skip the Prometheus push, so they don't
+distort the scheduled canary's health signal. Results are visible in the Temporal UI on the started
+workflow, and divergences land in the structured error log.
+"""
+
+import asyncio
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand
+
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+from posthog.temporal.common.client import sync_connect
+
+from products.experiments.backend.temporal.models import CANARY_WORKFLOW_NAME, ExperimentPrecomputeCanaryInputs
+
+
+class Command(BaseCommand):
+ help = "Trigger an on-demand experiment precompute canary run"
+
+ def add_arguments(self, parser) -> None:
+ parser.add_argument("--experiment-id", type=int, help="Canary this experiment only (forensics mode)")
+ parser.add_argument(
+ "--metric-uuid",
+ action="append",
+ dest="metric_uuids",
+ help="Restrict to specific metric uuid(s); repeatable. Requires --experiment-id.",
+ )
+ parser.add_argument(
+ "--time-budget-seconds", type=int, default=3600, help="Stop starting new metrics after this long"
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["metric_uuids"] and not options["experiment_id"]:
+ self.stderr.write("--metric-uuid requires --experiment-id")
+ return
+
+ inputs = ExperimentPrecomputeCanaryInputs(
+ experiment_id=options["experiment_id"],
+ metric_uuids=options["metric_uuids"],
+ time_budget_seconds=options["time_budget_seconds"],
+ triggered_manually=True,
+ )
+
+ workflow_id = (
+ f"experiment-precompute-canary-manual-{inputs.experiment_id}"
+ if inputs.experiment_id is not None
+ else "experiment-precompute-canary-manual"
+ )
+
+ temporal = sync_connect()
+ try:
+ handle = asyncio.run(
+ temporal.start_workflow(
+ CANARY_WORKFLOW_NAME,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ )
+ )
+ except WorkflowAlreadyStartedError:
+ self.stderr.write(f"A canary run with id {workflow_id} is already in progress")
+ return
+ self.stdout.write(f"Started workflow {handle.id} (run {handle.result_run_id}) on {settings.TEMPORAL_HOST}")
diff --git a/products/experiments/backend/temporal/__init__.py b/products/experiments/backend/temporal/__init__.py
index fbd093eff500..45fe939a4fb4 100644
--- a/products/experiments/backend/temporal/__init__.py
+++ b/products/experiments/backend/temporal/__init__.py
@@ -1,3 +1,9 @@
+from products.experiments.backend.temporal.canary_activities import (
+ report_experiment_canary_results,
+ run_experiment_metric_canary,
+ sample_experiment_canary_targets,
+)
+from products.experiments.backend.temporal.canary_workflow import ExperimentPrecomputeCanaryWorkflow
from products.experiments.backend.temporal.recalculation_activities import (
calculate_experiment_metric_for_recalculation,
discover_experiment_metrics,
@@ -7,18 +13,26 @@ from products.experiments.backend.temporal.recalculation_workflow import Experim
WORKFLOWS = [
ExperimentMetricsRecalculationWorkflow,
+ ExperimentPrecomputeCanaryWorkflow,
]
ACTIVITIES = [
discover_experiment_metrics,
calculate_experiment_metric_for_recalculation,
update_recalculation_progress,
+ sample_experiment_canary_targets,
+ run_experiment_metric_canary,
+ report_experiment_canary_results,
]
__all__ = [
"ACTIVITIES",
"WORKFLOWS",
"ExperimentMetricsRecalculationWorkflow",
+ "ExperimentPrecomputeCanaryWorkflow",
"calculate_experiment_metric_for_recalculation",
"discover_experiment_metrics",
+ "report_experiment_canary_results",
+ "run_experiment_metric_canary",
+ "sample_experiment_canary_targets",
"update_recalculation_progress",
]
diff --git a/products/experiments/backend/temporal/canary_activities.py b/products/experiments/backend/temporal/canary_activities.py
new file mode 100644
index 000000000000..ca280dd689cb
--- /dev/null
+++ b/products/experiments/backend/temporal/canary_activities.py
@@ -0,0 +1,38 @@
+"""Temporal activity entrypoints for the experiment precompute canary.
+
+Thin ``@temporalio.activity.defn`` wrappers; the implementations live in ``canary_logic``.
+"""
+
+import temporalio.activity
+
+from posthog.sync import database_sync_to_async
+
+from products.experiments.backend.temporal.canary_logic import (
+ report_canary_results_sync,
+ run_metric_canary_sync,
+ sample_canary_targets_sync,
+)
+from products.experiments.backend.temporal.models import (
+ CanaryMetricResult,
+ CanaryMetricTarget,
+ CanaryReportInputs,
+ ExperimentPrecomputeCanaryInputs,
+)
+
+
+async def sample_experiment_canary_targets(inputs: ExperimentPrecomputeCanaryInputs) -> list[CanaryMetricTarget]:
+ """Pick the (experiment, metric) pairs for this canary run; uuids only, definitions resolve later."""
+ return await database_sync_to_async(sample_canary_targets_sync)(inputs)
+
+
+async def run_experiment_metric_canary(target: CanaryMetricTarget) -> CanaryMetricResult:
+ """Run one metric through both execution paths (precomputed twice, direct once) and compare."""
+ return await database_sync_to_async(run_metric_canary_sync)(target)
+
+
+async def report_experiment_canary_results(report: CanaryReportInputs) -> None:
+ """Push Prometheus gauges and post the Slack alert when any metric diverged."""
+ return await database_sync_to_async(report_canary_results_sync)(report)
diff --git a/products/experiments/backend/temporal/canary_logic.py b/products/experiments/backend/temporal/canary_logic.py
new file mode 100644
index 000000000000..2b53fad4ebb4
--- /dev/null
+++ b/products/experiments/backend/temporal/canary_logic.py
@@ -0,0 +1,501 @@
+"""Experiment precompute canary: detects broken or unstable precomputed experiment results in production.
+
+Samples (experiment, metric) pairs across precompute-enabled teams and runs each metric three times:
+runs A and B force the precomputed path (``PrecomputationMode.PRECOMPUTED``), run C forces a direct events
+scan (``PrecomputationMode.DIRECT``). Two checks per metric:
+
+- stability (A vs B): two precomputed reads seconds apart must agree. Funnel reads are fully frozen, so the
+ tolerance is strict; mean/ratio metrics join live event values onto frozen exposures, so only the exposure
+ counts are held to the strict tolerance.
+- correctness (B vs C): the precomputed read must agree with the events table within a loose tolerance that
+ covers live ingestion between the cache writes and the direct scan.
+
+The bug class this guards (multi-node ClickHouse read-your-writes, see
+``products/analytics_platform/backend/lazy_computation/CONSISTENCY.md``) cannot be reproduced in dev/CI
+(single-node, synchronous inserts) — production observation is the point of the canary.
+
+Runbook:
+
+- 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_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
+ wrong) and ``last_run_timestamp`` stale for >48h (the canary itself is broken).
+- A divergence also posts to Slack (``settings.EXPERIMENT_CANARY_SLACK_WEBHOOK_URL``; unset → skipped) and
+ emits a structured ``experiment_precompute_canary_divergence`` error log with each run's per-variant
+ numbers and the ``experiment-canary-*`` client_query_ids to look up in ``system.query_log``.
+- On-demand forensics run against one experiment:
+ ``python manage.py run_experiment_canary --experiment-id <id>``.
+"""
+
+import time
+import uuid
+import random
+import dataclasses
+from datetime import timedelta
+from typing import Any
+
+from django.conf import settings
+from django.db import close_old_connections
+from django.utils import timezone
+
+import requests
+import structlog
+from prometheus_client import Gauge
+
+from posthog.schema import ExperimentQuery, PrecomputationMode
+
+from posthog.clickhouse.query_tagging import tags_context
+from posthog.metrics import pushed_metrics_registry
+from posthog.models.scoping import team_scope
+
+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+from products.experiments.backend.temporal.metric_resolution import (
+ ExperimentMetric,
+ build_metric,
+ find_metric_dict,
+ iter_metric_dicts,
+)
+from products.experiments.backend.temporal.models import (
+ ALL_OUTCOMES,
+ MAX_CANARY_DETAIL_LENGTH,
+ OUTCOME_DIVERGENCE,
+ OUTCOME_ERROR,
+ OUTCOME_PASS,
+ OUTCOME_PATH_FLIP,
+ OUTCOME_SKIPPED,
+ CanaryMetricResult,
+ CanaryMetricTarget,
+ CanaryReportInputs,
+ CanaryRunSnapshot,
+ CanaryVariantStats,
+ ExperimentPrecomputeCanaryInputs,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Frozen-vs-frozen reads should be identical; the only legitimate noise is ReplacingMergeTree background
+# merges collapsing a handful of duplicate-key rows (measured ~1 in 40K). The incident signature was 15-40%.
+STRICT_TOLERANCE = 0.001
+# Precomputed-vs-direct (and mean-metric sums, which join live values) legitimately drift by the few minutes
+# of ingestion between the cache writes and the comparison read.
+LOOSE_TOLERANCE = 0.02
+
+# Below this, a single user moves a variant by more than the strict tolerance and comparison is meaningless.
+MIN_EXPOSURES_PER_VARIANT = 100
+
+# Only metric types that use the precompute path. Retention metrics don't, so a paired run tests nothing.
+ELIGIBLE_METRIC_TYPES = ("funnel", "mean", "ratio")
+
+# Experiments must have been running this long to be sampled — comfortably past the runner's 12h
+# precomputation gate, with enough accumulated exposures for the comparison to be meaningful.
+MIN_EXPERIMENT_RUNTIME = timedelta(days=2)
+
+_CANARY_RUNS: tuple[tuple[str, PrecomputationMode], ...] = (
+ ("a", PrecomputationMode.PRECOMPUTED),
+ ("b", PrecomputationMode.PRECOMPUTED),
+ ("c", PrecomputationMode.DIRECT),
+)
+
+
+# ---------------------------------------------------------------------------
+# Sampling
+# ---------------------------------------------------------------------------
+
+
+def _eligible_experiments() -> list[Experiment]:
+ """Running experiments on precompute-enabled teams, past the minimum runtime."""
+ team_ids = list(
+ TeamExperimentsConfig.objects.filter(experiment_precomputation_enabled=True).values_list("team_id", flat=True)
+ )
+ if not team_ids:
+ return []
+ return list(
+ Experiment.objects.filter(
+ team_id__in=team_ids,
+ start_date__lte=timezone.now() - MIN_EXPERIMENT_RUNTIME,
+ end_date__isnull=True,
+ )
+ .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")
+ )
+
+
+def _experiment_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:
+ with team_scope(experiment.team_id, canonical=True):
+ return [m for m in iter_metric_dicts(experiment) if m.get("metric_type") in ELIGIBLE_METRIC_TYPES]
+
+
+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 = (
+ Experiment.objects.filter(id=experiment_id, start_date__isnull=False)
+ .exclude(deleted=True)
+ .select_related("team")
+ .first()
+ )
+ if experiment is None:
+ logger.warning("experiment_precompute_canary_forensics_target_not_found", experiment_id=experiment_id)
+ return []
+
+ targets: list[CanaryMetricTarget] = []
+ seen_uuids: set[str] = set()
+ for metric_dict in _experiment_metric_dicts(experiment):
+ metric_uuid = metric_dict["uuid"]
+ if metric_uuid in seen_uuids or (metric_uuids and metric_uuid not in metric_uuids):
+ continue
+ seen_uuids.add(metric_uuid)
+ targets.append(
+ CanaryMetricTarget(
+ team_id=experiment.team_id,
+ experiment_id=experiment.id,
+ metric_uuid=metric_uuid,
+ metric_type=metric_dict["metric_type"],
+ )
+ )
+ return targets
+
+
+def sample_canary_targets_sync(inputs: ExperimentPrecomputeCanaryInputs) -> list[CanaryMetricTarget]:
+ """Pick a sample of metrics across eligible experiments: shuffle experiments, take up to
+ per_experiment_cap metrics from each into the remaining per-type quotas, stop when quotas are full.
+ Under-filled when the eligible population is small — run what we have. Output stays grouped by
+ experiment so metrics sharing an exposures cache run adjacently."""
+ close_old_connections()
+
+ if inputs.experiment_id is not None:
+ return _forensics_targets(inputs.experiment_id, inputs.metric_uuids)
+
+ quotas = {"funnel": inputs.funnel_quota, "mean": inputs.mean_quota, "ratio": inputs.ratio_quota}
+ experiments = _eligible_experiments()
+ random.shuffle(experiments)
+
+ targets: list[CanaryMetricTarget] = []
+ for experiment in experiments:
+ if not any(quotas.values()):
+ break
+ metric_dicts = _experiment_metric_dicts(experiment)
+ random.shuffle(metric_dicts)
+ taken = 0
+ seen_uuids: set[str] = set()
+ for metric_dict in metric_dicts:
+ if taken == inputs.per_experiment_cap:
+ break
+ metric_type = metric_dict["metric_type"]
+ metric_uuid = metric_dict["uuid"]
+ if quotas.get(metric_type, 0) <= 0 or metric_uuid in seen_uuids:
+ continue
+ seen_uuids.add(metric_uuid)
+ targets.append(
+ CanaryMetricTarget(
+ team_id=experiment.team_id,
+ experiment_id=experiment.id,
+ metric_uuid=metric_uuid,
+ metric_type=metric_type,
+ )
+ )
+ quotas[metric_type] -= 1
+ taken += 1
+
+ logger.info(
+ "experiment_precompute_canary_sampled",
+ target_count=len(targets),
+ experiment_count=len({t.experiment_id for t in targets}),
+ unfilled_quotas={k: v for k, v in quotas.items() if v > 0},
+ )
+ return targets
+
+
+# ---------------------------------------------------------------------------
+# Verdict
+# ---------------------------------------------------------------------------
+
+
+class CanaryVerdict:
+ outcome: str
+ stability_deviation: float | None = None
+ correctness_deviation: float | None = None
+ detail: str | None = None
+
+
+def relative_deviation(a: float, b: float) -> float:
+ return abs(a - b) / max(abs(a), abs(b), 1.0)
+
+
+def _max_deviation(run_x: CanaryRunSnapshot, run_y: CanaryRunSnapshot) -> float:
+ deviations = [0.0]
+ for key, stats_x in run_x.variants.items():
+ stats_y = run_y.variants[key]
+ deviations.append(relative_deviation(stats_x.sum, stats_y.sum))
+ deviations.append(relative_deviation(stats_x.number_of_samples, stats_y.number_of_samples))
+ return max(deviations)
+
+
+def _stability_violated(metric_type: str, run_a: CanaryRunSnapshot, run_b: CanaryRunSnapshot) -> bool:
+ for key, stats_a in run_a.variants.items():
+ stats_b = run_b.variants[key]
+ if relative_deviation(stats_a.number_of_samples, stats_b.number_of_samples) > STRICT_TOLERANCE:
+ return True
+ # Funnel sums are reads of frozen caches; mean/ratio sums join live event values and drift.
+ sum_tolerance = STRICT_TOLERANCE if metric_type == "funnel" else LOOSE_TOLERANCE
+ if relative_deviation(stats_a.sum, stats_b.sum) > sum_tolerance:
+ return True
+ return False
+
+
+def evaluate_canary_runs(
+ metric_type: str, run_a: CanaryRunSnapshot, run_b: CanaryRunSnapshot, run_c: CanaryRunSnapshot
+) -> 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)
+ if any(not run.variants for run in runs):
+ return CanaryVerdict(outcome=OUTCOME_SKIPPED, detail="empty results (no exposures yet)")
+
+ # Checked before the variant-set comparison: a flipped run compares live vs frozen data, so it can
+ # also explain a variant showing up in one run but not another.
+ flipped = [run.label for run in (run_a, run_b) if not run.is_precomputed]
+ 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")
+
+ variant_keys = {frozenset(run.variants) for run in runs}
+ if len(variant_keys) > 1:
+ return CanaryVerdict(outcome=OUTCOME_ERROR, detail="variant set mismatch between runs")
+
+ # Gated on every run: a thin variant in the direct scan would make the correctness comparison just as
+ # meaningless as one in the precomputed reads.
+ if min(stats.number_of_samples for run in runs for stats in run.variants.values()) < MIN_EXPOSURES_PER_VARIANT:
+ return CanaryVerdict(
+ outcome=OUTCOME_SKIPPED, detail=f"fewer than {MIN_EXPOSURES_PER_VARIANT} exposures in a variant"
+ )
+
+ stability_deviation = _max_deviation(run_a, run_b)
+ correctness_deviation = _max_deviation(run_b, run_c)
+ diverged = _stability_violated(metric_type, run_a, run_b) or correctness_deviation > LOOSE_TOLERANCE
+
+ return CanaryVerdict(
+ outcome=OUTCOME_DIVERGENCE if diverged else OUTCOME_PASS,
+ stability_deviation=stability_deviation,
+ correctness_deviation=correctness_deviation,
+ detail="deviation beyond tolerance" if diverged else None,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Execution
+# ---------------------------------------------------------------------------
+
+
+def _execute_canary_run(
+ experiment: Experiment, metric: ExperimentMetric, mode: PrecomputationMode, label: str, query_id: str
+) -> CanaryRunSnapshot:
+ # Fresh runner per run: the runner caches precomputation state from its first execution. The workload
+ # is deliberately left at its default (online cluster) — the bug class this canary hunts is only
+ # observable on the path users actually read from. user_facing=False keeps original exceptions intact
+ # for Temporal's retry classification instead of converting them to friendly ValidationErrors.
+ runner = ExperimentQueryRunner(
+ query=ExperimentQuery(experiment_id=experiment.id, metric=metric, precomputation_mode=mode),
+ team=experiment.team,
+ user_facing=False,
+ )
+ with tags_context(client_query_id=query_id, trigger="experiment_precompute_canary"):
+ response = runner.calculate()
+
+ stats_entries = [*([response.baseline] if response.baseline else []), *(response.variant_results or [])]
+ return CanaryRunSnapshot(
+ label=label,
+ query_id=query_id,
+ is_precomputed=bool(response.is_precomputed),
+ variants={
+ entry.key: CanaryVariantStats(sum=entry.sum, number_of_samples=entry.number_of_samples)
+ for entry in stats_entries
+ },
+ )
+
+
+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.
+ """
+ close_old_connections()
+
+ def _skipped(detail: str) -> CanaryMetricResult:
+ return CanaryMetricResult(target=target, outcome=OUTCOME_SKIPPED, detail=detail)
+
+ with team_scope(target.team_id, canonical=True):
+ experiment = (
+ Experiment.objects.filter(id=target.experiment_id, team_id=target.team_id, start_date__isnull=False)
+ .exclude(deleted=True)
+ .select_related("team")
+ .first()
+ )
+ if experiment is None:
+ return _skipped("experiment not found, deleted, or missing start_date")
+
+ metric_dict = find_metric_dict(experiment, target.metric_uuid)
+ if metric_dict is None:
+ return _skipped("metric no longer present on experiment")
+ # Re-resolved, so the type can differ from what was sampled (metric edited in between). The verdict
+ # rules depend on it, so use the current type — and bail if it changed to an ineligible one.
+ metric_type = metric_dict.get("metric_type")
+ if metric_type not in ELIGIBLE_METRIC_TYPES:
+ return _skipped(f"metric type changed to ineligible {metric_type!r}")
+ try:
+ metric = build_metric(metric_dict)
+ except Exception as e:
+ return _skipped(f"metric definition not parseable: {str(e)[:MAX_CANARY_DETAIL_LENGTH]}")
+
+ canary_id = uuid.uuid4().hex[:12]
+ runs: list[CanaryRunSnapshot] = []
+ for 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",
+ 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,
+ )
+ raise
+
+ verdict = evaluate_canary_runs(metric_type, *runs)
+ result = CanaryMetricResult(
+ target=target,
+ outcome=verdict.outcome,
+ stability_deviation=verdict.stability_deviation,
+ correctness_deviation=verdict.correctness_deviation,
+ runs=runs,
+ detail=verdict.detail,
+ )
+
+ if result.outcome == OUTCOME_DIVERGENCE:
+ # Full forensics in one log line: enough to investigate without re-running the canary.
+ logger.error(
+ "experiment_precompute_canary_divergence",
+ team_id=target.team_id,
+ experiment_id=target.experiment_id,
+ metric_uuid=target.metric_uuid,
+ metric_type=target.metric_type,
+ stability_deviation=result.stability_deviation,
+ correctness_deviation=result.correctness_deviation,
+ runs=[dataclasses.asdict(run) for run in runs],
+ )
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Reporting
+# ---------------------------------------------------------------------------
+
+
+def _format_run_line(run: CanaryRunSnapshot) -> str:
+ path = "precomputed" if run.is_precomputed else "direct"
+ variants = ", ".join(
+ f"{key} {stats.sum:g}/{stats.number_of_samples}" for key, stats in sorted(run.variants.items())
+ )
+ return f"{run.label} [{path}] `{run.query_id}`: {variants}"
+
+
+def _build_slack_blocks(divergent: list[CanaryMetricResult], counts: dict[str, int], manual: bool) -> list[dict]:
+ header = ":rotating_light: *Experiment precompute canary: divergence detected*"
+ if manual:
+ header += " (manual run)"
+ blocks: list[dict[str, Any]] = [
+ {"type": "section", "text": {"type": "mrkdwn", "text": header}},
+ {
+ "type": "context",
+ "elements": [
+ {
+ "type": "mrkdwn",
+ "text": " | ".join(f"{outcome}: {counts.get(outcome, 0)}" for outcome in ALL_OUTCOMES),
+ }
+ ],
+ },
+ {"type": "divider"},
+ ]
+ for result in divergent:
+ target = result.target
+ lines = [
+ f":red_circle: *team {target.team_id} / experiment {target.experiment_id} / metric `{target.metric_uuid}` ({target.metric_type})*",
+ f"stability deviation {100 * (result.stability_deviation or 0):.4f}% | correctness deviation {100 * (result.correctness_deviation or 0):.4f}%",
+ *(_format_run_line(run) for run in result.runs),
+ ]
+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": "\n".join(lines)}})
+ return blocks
+
+
+def _send_slack_alert(divergent: list[CanaryMetricResult], counts: dict[str, int], manual: bool) -> None:
+ webhook_url = settings.EXPERIMENT_CANARY_SLACK_WEBHOOK_URL
+ if not webhook_url:
+ logger.info("experiment_precompute_canary_slack_not_configured")
+ return
+ try:
+ response = requests.post(
+ webhook_url, json={"blocks": _build_slack_blocks(divergent, counts, manual)}, timeout=10
+ )
+ response.raise_for_status()
+ except requests.RequestException as e:
+ # Not re-raised: the divergence is already in the error log and the Prometheus gauges.
+ # str(e) would include the request URL, i.e. the webhook secret — log only safe fields.
+ logger.warning(
+ "experiment_precompute_canary_slack_failed",
+ error_type=type(e).__name__,
+ status_code=getattr(e.response, "status_code", None),
+ )
+
+
+def report_canary_results_sync(report: CanaryReportInputs) -> None:
+ counts = dict.fromkeys(ALL_OUTCOMES, 0)
+ for result in report.results:
+ counts[result.outcome] = counts.get(result.outcome, 0) + 1
+
+ logger.info("experiment_precompute_canary_run_finished", triggered_manually=report.triggered_manually, **counts)
+
+ if not report.triggered_manually:
+ with pushed_metrics_registry("experiment_precompute_canary") as registry:
+ outcome_gauge = Gauge(
+ "experiment_precompute_canary_outcomes",
+ "Number of metrics per outcome in the last canary run",
+ labelnames=["outcome"],
+ registry=registry,
+ )
+ for outcome, count in counts.items():
+ outcome_gauge.labels(outcome=outcome).set(count)
+ deviation_gauge = Gauge(
+ "experiment_precompute_canary_max_deviation",
+ "Max relative deviation observed across metrics in the last canary run",
+ labelnames=["check"],
+ registry=registry,
+ )
+ deviation_gauge.labels(check="stability").set(
+ max((r.stability_deviation or 0.0 for r in report.results), default=0.0)
+ )
+ deviation_gauge.labels(check="correctness").set(
+ max((r.correctness_deviation or 0.0 for r in report.results), default=0.0)
+ )
+ Gauge(
+ "experiment_precompute_canary_last_run_timestamp",
+ "Unix timestamp of the last canary run; staleness means the canary itself is broken",
+ registry=registry,
+ ).set(time.time())
+
+ divergent = [result for result in report.results if result.outcome == OUTCOME_DIVERGENCE]
+ if divergent:
+ _send_slack_alert(divergent, counts, report.triggered_manually)
diff --git a/products/experiments/backend/temporal/canary_workflow.py b/products/experiments/backend/temporal/canary_workflow.py
new file mode 100644
index 000000000000..54f3409b71ff
--- /dev/null
+++ b/products/experiments/backend/temporal/canary_workflow.py
@@ -0,0 +1,94 @@
+import json
+from datetime import timedelta
+
+import temporalio.workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with temporalio.workflow.unsafe.imports_passed_through():
+ from products.experiments.backend.temporal.canary_activities import (
+ report_experiment_canary_results,
+ run_experiment_metric_canary,
+ sample_experiment_canary_targets,
+ )
+ from products.experiments.backend.temporal.models import (
+ CANARY_WORKFLOW_NAME,
+ MAX_CANARY_DETAIL_LENGTH,
+ OUTCOME_ERROR,
+ OUTCOME_SKIPPED,
+ CanaryMetricResult,
+ CanaryReportInputs,
+ ExperimentPrecomputeCanaryInputs,
+ )
+
+# Three sequential queries at the runner's 600s ceiling each, plus headroom.
+METRIC_ACTIVITY_TIMEOUT = timedelta(minutes=35)
+
+
[email protected](name=CANARY_WORKFLOW_NAME)
+class ExperimentPrecomputeCanaryWorkflow(PostHogWorkflow):
+ """Verify precomputed experiment results against paired reads and a direct events scan.
+
+ Samples metrics across precompute-enabled teams, runs them sequentially (metrics of one experiment
+ share its exposures cache, so only the first recomputes it; sequential execution also avoids concurrent
+ writes to the lazy-computation job table), and reports outcomes to Prometheus and Slack. See
+ ``canary_logic`` for the comparison rules and the runbook.
+ """
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ExperimentPrecomputeCanaryInputs:
+ loaded = json.loads(inputs[0]) if inputs else {}
+ return ExperimentPrecomputeCanaryInputs(**loaded)
+
+ @temporalio.workflow.run
+ async def run(self, inputs: ExperimentPrecomputeCanaryInputs) -> dict:
+ start = temporalio.workflow.now()
+
+ targets = await temporalio.workflow.execute_activity(
+ sample_experiment_canary_targets,
+ inputs,
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ results: list[CanaryMetricResult] = []
+ budget = timedelta(seconds=inputs.time_budget_seconds)
+ for target in targets:
+ if temporalio.workflow.now() - start > budget:
+ results.append(
+ CanaryMetricResult(target=target, outcome=OUTCOME_SKIPPED, detail="time budget exhausted")
+ )
+ continue
+ try:
+ result = await temporalio.workflow.execute_activity(
+ run_experiment_metric_canary,
+ target,
+ # No heartbeat: each of the three runs is one blocking ClickHouse query with no
+ # progress hooks, so start_to_close_timeout is the real per-attempt ceiling.
+ start_to_close_timeout=METRIC_ACTIVITY_TIMEOUT,
+ retry_policy=RetryPolicy(
+ maximum_attempts=2,
+ initial_interval=timedelta(seconds=5),
+ maximum_interval=timedelta(minutes=1),
+ ),
+ )
+ except Exception as e:
+ # Query failures are monitoring signal, not a reason to abandon the remaining metrics.
+ result = CanaryMetricResult(
+ target=target, outcome=OUTCOME_ERROR, detail=str(e)[:MAX_CANARY_DETAIL_LENGTH]
+ )
+ results.append(result)
+
+ await temporalio.workflow.execute_activity(
+ report_experiment_canary_results,
+ CanaryReportInputs(results=results, triggered_manually=inputs.triggered_manually),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+ counts: dict[str, int] = {}
+ for result in results:
+ counts[result.outcome] = counts.get(result.outcome, 0) + 1
+ temporalio.workflow.logger.info(f"experiment precompute canary finished: {counts or 'no targets'}")
+ return {"total": len(results), **counts}
diff --git a/products/experiments/backend/temporal/metric_resolution.py b/products/experiments/backend/temporal/metric_resolution.py
new file mode 100644
index 000000000000..6c1651739723
--- /dev/null
+++ b/products/experiments/backend/temporal/metric_resolution.py
@@ -0,0 +1,67 @@
+"""Shared helpers for resolving experiment metric definitions across inline and saved/shared metrics.
+
+Used by the recalculation workflow and the precompute canary workflow, which both pass metric uuids between
+activities and re-resolve the definition at the point of use.
+"""
+
+from typing import Any
+
+from posthog.schema import (
+ ExperimentFunnelMetric,
+ ExperimentMeanMetric,
+ ExperimentRatioMetric,
+ ExperimentRetentionMetric,
+)
+
+from products.experiments.backend.models.experiment import Experiment
+
+ExperimentMetric = ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
+
+# Modern ExperimentMetric types (kind="ExperimentMetric"). Legacy Trends/Funnels metrics never enter these
+# workflows, so there is no fallback — an unexpected metric_type surfaces as an error at the call site.
+METRIC_BUILDERS: dict[str, type[ExperimentMetric]] = {
+ "mean": ExperimentMeanMetric,
+ "funnel": ExperimentFunnelMetric,
+ "ratio": ExperimentRatioMetric,
+ "retention": ExperimentRetentionMetric,
+}
+
+
+def _merge_saved_metric_breakdowns(saved_query: dict[str, Any], metadata: dict[str, Any] | None) -> dict[str, Any]:
+ """Merge per-experiment breakdowns from the M2M link metadata into the saved query, mirroring the
+ daily-warming activity. Without this, callers would compute the unbroken-down version of a saved
+ metric the experiment has configured with breakdowns."""
+ metadata = metadata or {}
+ return {
+ **saved_query,
+ "breakdownFilter": {
+ **(saved_query.get("breakdownFilter") or {}),
+ "breakdowns": metadata.get("breakdowns") or [],
+ },
+ }
+
+
+def iter_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:
+ """All metric definition dicts for an experiment: inline primary + secondary, then saved/shared metrics.
+
+ Inline metrics are dicts in experiment.metrics / metrics_secondary. Saved metrics live on the M2M
+ through-model and carry their definition (with uuid) in saved_metric.query; per-experiment breakdown
+ overrides from the link metadata are merged in.
+ """
+ dicts: list[dict[str, Any]] = [
+ metric for metric in (experiment.metrics or []) + (experiment.metrics_secondary or []) if metric.get("uuid")
+ ]
+ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
+ saved_query = link.saved_metric.query
+ if saved_query and saved_query.get("uuid"):
+ dicts.append(_merge_saved_metric_breakdowns(saved_query, link.metadata))
+ return dicts
+
+
+def find_metric_dict(experiment: Experiment, metric_uuid: str) -> dict[str, Any] | None:
+ """Resolve a metric_uuid to its definition dict, across inline AND saved/shared metrics."""
+ return next((metric for metric in iter_metric_dicts(experiment) if metric.get("uuid") == metric_uuid), None)
+
+
+def build_metric(metric_dict: dict[str, Any]) -> ExperimentMetric:
+ return METRIC_BUILDERS[metric_dict["metric_type"]](**metric_dict)
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index c5f13d00c9bf..74eeb043e699 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -1,5 +1,18 @@
import dataclasses
+# Shared by the workflow definition, the schedule, and the management command.
+CANARY_WORKFLOW_NAME = "experiment-precompute-canary"
+
+OUTCOME_PASS = "pass"
+OUTCOME_DIVERGENCE = "divergence"
+OUTCOME_PATH_FLIP = "path_flip"
+OUTCOME_ERROR = "error"
+OUTCOME_SKIPPED = "skipped"
+ALL_OUTCOMES = (OUTCOME_PASS, OUTCOME_DIVERGENCE, OUTCOME_PATH_FLIP, OUTCOME_ERROR, OUTCOME_SKIPPED)
+
+# Cap CanaryMetricResult.detail so a pathological error message can't bloat the Temporal payload.
+MAX_CANARY_DETAIL_LENGTH = 1000
+
@dataclasses.dataclass
class ExperimentMetricsRecalculationWorkflowInputs:
@@ -36,6 +49,71 @@ class MetricRecalculationResult:
error_message: str | None = None
+class ExperimentPrecomputeCanaryInputs:
+ """Input to the precompute canary workflow.
+
+ Scheduled runs use the defaults (quota sampling across eligible experiments). On-demand forensics runs
+ set experiment_id to canary one specific experiment — all of its eligible metrics, quotas ignored —
+ optionally narrowed via metric_uuids. triggered_manually skips the Prometheus push (manual runs would
+ distort the scheduled-canary health signal) but still posts to Slack.
+ """
+
+ experiment_id: int | None = None
+ metric_uuids: list[str] | None = None
+ funnel_quota: int = 6
+ mean_quota: int = 3
+ ratio_quota: int = 2
+ per_experiment_cap: int = 3
+ time_budget_seconds: int = 3600
+ triggered_manually: bool = False
+
+
+class CanaryMetricTarget:
+ """One sampled (experiment, metric) pair. Carries only the uuid — the definition is re-resolved inside
+ the run activity so a metric edited/deleted between sampling and execution is seen as it currently is."""
+
+ team_id: int
+ experiment_id: int
+ metric_uuid: str
+ metric_type: str # "funnel" | "mean" | "ratio"
+
+
+class CanaryVariantStats:
+ sum: float
+ number_of_samples: int
+
+
+class CanaryRunSnapshot:
+ """Per-variant aggregates from one execution of the metric query."""
+
+ label: str # "a" | "b" (forced precomputed) | "c" (forced direct scan)
+ query_id: str # client_query_id, for system.query_log forensics
+ is_precomputed: bool
+ variants: dict[str, CanaryVariantStats]
+
+
+class CanaryMetricResult:
+ """Verdict for one metric: outcome plus everything needed to investigate without re-running."""
+
+ target: CanaryMetricTarget
+ outcome: str # "pass" | "divergence" | "path_flip" | "error" | "skipped"
+ stability_deviation: float | None = None # max relative deviation, run a vs b
+ correctness_deviation: float | None = None # max relative deviation, run b vs c
+ runs: list[CanaryRunSnapshot] = dataclasses.field(default_factory=list)
+ detail: str | None = None
+
+
+class CanaryReportInputs:
+ results: list[CanaryMetricResult]
+ triggered_manually: bool = False
+
+
@dataclasses.dataclass
class RecalculationProgressUpdate:
"""Input for the start and finish lifecycle steps.
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 0908b0815b93..8fabd2cb8e46 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -13,13 +13,7 @@ from django.utils import timezone
import structlog
from temporalio.exceptions import ApplicationError
-from posthog.schema import (
- ExperimentFunnelMetric,
- ExperimentMeanMetric,
- ExperimentQuery,
- ExperimentRatioMetric,
- ExperimentRetentionMetric,
-)
+from posthog.schema import ExperimentQuery
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import tag_queries
@@ -36,6 +30,7 @@ from products.experiments.backend.models.experiment import (
ExperimentMetricResult,
ExperimentMetricsRecalculation,
)
+from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict
from products.experiments.backend.temporal.models import (
ExperimentMetricToRecalculate,
MetricRecalculationResult,
@@ -193,50 +188,6 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) ->
# ---------------------------------------------------------------------------
-def _find_metric_dict(experiment: Experiment, metric_uuid: str) -> dict | None:
- """Resolve a metric_uuid to its definition dict, across inline AND saved/shared metrics.
-
- Inline metrics are dicts in experiment.metrics / metrics_secondary. Saved metrics live on the M2M
- through-model and carry their definition (with uuid) in saved_metric.query.
- """
- for metric in (experiment.metrics or []) + (experiment.metrics_secondary or []):
- if metric.get("uuid") == metric_uuid:
- return metric
-
- for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
- saved_query = link.saved_metric.query
- if saved_query and saved_query.get("uuid") == metric_uuid:
- # Merge per-experiment breakdowns from link.metadata into the saved query, mirroring the
- # daily-warming activity. Without this, recalc would compute the unbroken-down version of a
- # saved metric the experiment has configured with breakdowns.
- metadata = link.metadata or {}
- return {
- **saved_query,
- "breakdownFilter": {
- **(saved_query.get("breakdownFilter") or {}),
- "breakdowns": metadata.get("breakdowns") or [],
- },
- }
-
- return None
-
-
-# Modern ExperimentMetric types (kind="ExperimentMetric"). Legacy Trends/Funnels metrics never enter this
-# workflow, so there is no fallback — an unexpected metric_type surfaces as a calculation-step error.
-_METRIC_BUILDERS = {
- "mean": ExperimentMeanMetric,
- "funnel": ExperimentFunnelMetric,
- "ratio": ExperimentRatioMetric,
- "retention": ExperimentRetentionMetric,
-}
-
-
-def _build_metric(
- metric_dict: dict,
-) -> ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric:
- return _METRIC_BUILDERS[metric_dict["metric_type"]](**metric_dict)
-
-
def _record_failure(recalculation_id: str, metric_uuid: str, step: str, message: str) -> None:
"""Merge the error entry into metric_errors under a row lock (no lost updates between concurrent failures).
@@ -337,7 +288,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
except Experiment.DoesNotExist:
return _fail(recalculation_id, metric_uuid, "discovery", f"Experiment {experiment_id} not found or deleted")
- metric_dict = _find_metric_dict(experiment, metric_uuid)
+ metric_dict = find_metric_dict(experiment, metric_uuid)
if metric_dict is None:
return _fail(
recalculation_id,
@@ -364,7 +315,7 @@ def _calculate_experiment_metric_for_recalculation_sync(
# the runner falls back to its default ("now-ish"), so every metric in the run would query a
# slightly different time window — defeating the "one query_to for the whole run" guarantee.
runner = ExperimentQueryRunner(
- query=ExperimentQuery(experiment_id=experiment_id, metric=_build_metric(metric_dict)),
+ query=ExperimentQuery(experiment_id=experiment_id, metric=build_metric(metric_dict)),
team=experiment.team,
override_end_date=query_to_dt,
workload=Workload.OFFLINE,
diff --git a/products/experiments/backend/temporal/schedule.py b/products/experiments/backend/temporal/schedule.py
new file mode 100644
index 000000000000..96ce939b4c4b
--- /dev/null
+++ b/products/experiments/backend/temporal/schedule.py
@@ -0,0 +1,45 @@
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleCalendarSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleRange,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.experiments.backend.temporal.models import CANARY_WORKFLOW_NAME, ExperimentPrecomputeCanaryInputs
+
+CANARY_SCHEDULE_ID = "experiment-precompute-canary-schedule"
+
+
+async def create_experiment_precompute_canary_schedule(client: Client) -> None:
+ """Daily off-peak run of the experiment precompute canary. SKIP overlap: a slow run (the per-run time
+ budget allows up to an hour of queries) must not stack on the next day's."""
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ CANARY_WORKFLOW_NAME,
+ ExperimentPrecomputeCanaryInputs(),
+ id=f'{CANARY_SCHEDULE_ID}-{{{{.ScheduledTime.Format "2006-01-02"}}}}',
+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Daily at 3 AM UTC",
+ hour=[ScheduleRange(start=3, end=3)],
+ )
+ ]
+ ),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+
+ if await a_schedule_exists(client, CANARY_SCHEDULE_ID):
+ await a_update_schedule(client, CANARY_SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, CANARY_SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/experiments/backend/temporal/test_canary_logic.py b/products/experiments/backend/temporal/test_canary_logic.py
new file mode 100644
index 000000000000..3ae7b51877c0
--- /dev/null
+++ b/products/experiments/backend/temporal/test_canary_logic.py
@@ -0,0 +1,430 @@
+import uuid
+from datetime import timedelta
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+from django.utils import timezone
+
+import requests
+from parameterized import parameterized
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+from products.experiments.backend.temporal.canary_logic import (
+ evaluate_canary_runs,
+ relative_deviation,
+ report_canary_results_sync,
+ run_metric_canary_sync,
+ sample_canary_targets_sync,
+)
+from products.experiments.backend.temporal.models import (
+ OUTCOME_DIVERGENCE,
+ OUTCOME_ERROR,
+ OUTCOME_PASS,
+ OUTCOME_PATH_FLIP,
+ OUTCOME_SKIPPED,
+ CanaryMetricResult,
+ CanaryMetricTarget,
+ CanaryReportInputs,
+ CanaryRunSnapshot,
+ CanaryVariantStats,
+ ExperimentPrecomputeCanaryInputs,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+def _snapshot(label: str, variants: dict[str, tuple[float, int]], is_precomputed: bool = True) -> CanaryRunSnapshot:
+ return CanaryRunSnapshot(
+ label=label,
+ query_id=f"experiment-canary-test-{label}",
+ is_precomputed=is_precomputed,
+ variants={
+ key: CanaryVariantStats(sum=sum_, number_of_samples=samples) for key, (sum_, samples) in variants.items()
+ },
+ )
+
+
+_BASE = {"control": (1000.0, 10000), "test": (1100.0, 10000)}
+
+
+class TestRelativeDeviation:
+ @parameterized.expand(
+ [
+ # name, a, b, expected
+ ("both_zero", 0.0, 0.0, 0.0),
+ ("denominator_is_larger_value", 1000.0, 1005.0, 5.0 / 1005.0),
+ ("one_zero_below_floor", 0.0, 0.5, 0.5), # denominator floored at 1.0
+ ("negative_values", -10.0, 10.0, 2.0),
+ ]
+ )
+ def test_relative_deviation(self, _name, a, b, expected):
+ assert relative_deviation(a, b) == pytest.approx(expected)
+ assert relative_deviation(b, a) == pytest.approx(expected)
+
+
+class TestEvaluateCanaryRuns:
+ @parameterized.expand(
+ [
+ # name, metric_type, run_a variants, run_b variants, run_c variants, expected outcome
+ ("identical_funnel_passes", "funnel", _BASE, _BASE, _BASE, OUTCOME_PASS),
+ (
+ "funnel_within_strict_tolerance_passes",
+ "funnel",
+ _BASE,
+ {"control": (1000.4, 10000), "test": (1100.0, 10000)}, # 0.04% < 0.1%
+ _BASE,
+ OUTCOME_PASS,
+ ),
+ (
+ "funnel_sum_drift_between_precomputed_reads_diverges",
+ "funnel",
+ _BASE,
+ {"control": (1005.0, 10000), "test": (1100.0, 10000)}, # 0.5% > 0.1%
+ {"control": (1005.0, 10000), "test": (1100.0, 10000)},
+ OUTCOME_DIVERGENCE,
+ ),
+ (
+ "funnel_samples_drift_between_precomputed_reads_diverges",
+ "funnel",
+ _BASE,
+ {"control": (1000.0, 10050), "test": (1100.0, 10000)}, # 0.5% > 0.1%
+ {"control": (1000.0, 10050), "test": (1100.0, 10000)},
+ OUTCOME_DIVERGENCE,
+ ),
+ (
+ "mean_sum_drift_between_precomputed_reads_passes",
+ "mean",
+ _BASE,
+ {"control": (1010.0, 10000), "test": (1100.0, 10000)}, # 1% < 2% loose, sums join live values
+ {"control": (1010.0, 10000), "test": (1100.0, 10000)},
+ OUTCOME_PASS,
+ ),
+ (
+ "mean_samples_drift_between_precomputed_reads_diverges",
+ "mean",
+ _BASE,
+ {"control": (1000.0, 10050), "test": (1100.0, 10000)}, # exposures are frozen: strict
+ {"control": (1000.0, 10050), "test": (1100.0, 10000)},
+ OUTCOME_DIVERGENCE,
+ ),
+ (
+ "direct_scan_within_loose_tolerance_passes",
+ "funnel",
+ _BASE,
+ _BASE,
+ {"control": (1010.0, 10080), "test": (1108.0, 10000)}, # ~1% < 2%
+ OUTCOME_PASS,
+ ),
+ (
+ "direct_scan_beyond_loose_tolerance_diverges",
+ "funnel",
+ _BASE,
+ _BASE,
+ {"control": (1300.0, 10000), "test": (1100.0, 10000)}, # 23% — the incident signature
+ OUTCOME_DIVERGENCE,
+ ),
+ ]
+ )
+ def test_outcomes(self, _name, metric_type, a, b, c, expected):
+ verdict = evaluate_canary_runs(metric_type, _snapshot("a", a), _snapshot("b", b), _snapshot("c", c))
+ assert verdict.outcome == expected
+
+ def test_path_flip_is_not_divergence(self):
+ diverged = {"control": (1300.0, 12000), "test": (1100.0, 10000)}
+ verdict = evaluate_canary_runs(
+ "funnel", _snapshot("a", _BASE, is_precomputed=False), _snapshot("b", diverged), _snapshot("c", diverged)
+ )
+ assert verdict.outcome == OUTCOME_PATH_FLIP
+ assert "a" in (verdict.detail or "")
+
+ def test_direct_run_not_precomputed_is_expected(self):
+ verdict = evaluate_canary_runs(
+ "funnel", _snapshot("a", _BASE), _snapshot("b", _BASE), _snapshot("c", _BASE, is_precomputed=False)
+ )
+ assert verdict.outcome == OUTCOME_PASS
+
+ def test_path_flip_takes_precedence_over_variant_mismatch(self):
+ verdict = evaluate_canary_runs(
+ "funnel",
+ _snapshot("a", {"control": (1000.0, 10000)}, is_precomputed=False),
+ _snapshot("b", _BASE),
+ _snapshot("c", _BASE),
+ )
+ assert verdict.outcome == OUTCOME_PATH_FLIP
+
+ def test_low_volume_in_direct_scan_is_skipped(self):
+ thin_c = {"control": (1000.0, 10000), "test": (5.0, 50)}
+ verdict = evaluate_canary_runs("funnel", _snapshot("a", _BASE), _snapshot("b", _BASE), _snapshot("c", thin_c))
+ assert verdict.outcome == OUTCOME_SKIPPED
+
+ def test_variant_set_mismatch_is_error(self):
+ verdict = evaluate_canary_runs(
+ "funnel", _snapshot("a", _BASE), _snapshot("b", _BASE), _snapshot("c", {"control": (1000.0, 10000)})
+ )
+ assert verdict.outcome == OUTCOME_ERROR
+
+ def test_empty_results_are_skipped(self):
+ verdict = evaluate_canary_runs("funnel", _snapshot("a", _BASE), _snapshot("b", {}), _snapshot("c", _BASE))
+ assert verdict.outcome == OUTCOME_SKIPPED
+
+ def test_low_volume_is_skipped(self):
+ low = {"control": (10.0, 50), "test": (12.0, 60)}
+ verdict = evaluate_canary_runs("funnel", _snapshot("a", low), _snapshot("b", low), _snapshot("c", low))
+ assert verdict.outcome == OUTCOME_SKIPPED
+
+ def test_deviations_are_reported_on_pass(self):
+ c = {"control": (1010.0, 10000), "test": (1100.0, 10000)}
+ verdict = evaluate_canary_runs("funnel", _snapshot("a", _BASE), _snapshot("b", _BASE), _snapshot("c", c))
+ assert verdict.stability_deviation == 0.0
+ assert verdict.correctness_deviation == pytest.approx(0.01, rel=0.05)
+
+
+def _inline_metric(metric_type: str) -> dict:
+ return {"uuid": str(uuid.uuid4()), "kind": "ExperimentMetric", "metric_type": metric_type}
+
+
+def _funnel_metric() -> dict:
+ return {**_inline_metric("funnel"), "series": [{"kind": "EventsNode", "event": "purchase"}]}
+
+
[email protected](autouse=True)
+def _keep_test_connection(request):
+ # close_old_connections() would sever the test transaction's connection.
+ if request.node.get_closest_marker("django_db") is None:
+ yield
+ return
+ with patch("products.experiments.backend.temporal.canary_logic.close_old_connections"):
+ yield
+
+
[email protected]_db(transaction=True)
+class TestCanarySampling(BaseTest):
+ def _flag(self, key: str) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key=key,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+
+ def _experiment(self, metrics: list[dict], days_running: int = 3, **kwargs) -> Experiment:
+ return Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ feature_flag=self._flag(f"flag-{uuid.uuid4().hex[:8]}"),
+ name="exp",
+ metrics=metrics,
+ start_date=timezone.now() - timedelta(days=days_running),
+ **kwargs,
+ )
+
+ def _enable_precompute(self) -> None:
+ TeamExperimentsConfig.objects.update_or_create(
+ team=self.team, defaults={"experiment_precomputation_enabled": True}
+ )
+
+ def test_teams_without_precompute_enabled_are_never_sampled(self):
+ self._experiment([_inline_metric("funnel")])
+ assert sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs()) == []
+
+ @parameterized.expand(
+ [
+ # name, experiment kwargs
+ ("not_launched", {"start_date": None}),
+ ("stopped", {"end_date": timezone.now}),
+ ("too_young", {"start_date": timezone.now}),
+ ("deleted", {"deleted": True}),
+ ("archived", {"archived": True}),
+ ]
+ )
+ def test_ineligible_experiments_are_not_sampled(self, _name, overrides):
+ self._enable_precompute()
+ resolved = {key: value() if callable(value) else value for key, value in overrides.items()}
+ experiment = self._experiment([_inline_metric("funnel")])
+ Experiment.objects.filter(id=experiment.id).update(**resolved)
+ assert sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs()) == []
+
+ def test_retention_and_legacy_metrics_are_dropped(self):
+ self._enable_precompute()
+ legacy = {"uuid": str(uuid.uuid4()), "kind": "ExperimentTrendsQuery"} # no metric_type
+ self._experiment([_inline_metric("retention"), legacy])
+ assert sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs()) == []
+
+ def test_quotas_and_per_experiment_cap(self):
+ self._enable_precompute()
+ experiment = self._experiment([_inline_metric("funnel") for _ in range(10)])
+ targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs(funnel_quota=5, per_experiment_cap=3))
+ assert len(targets) == 3
+ assert all(t.experiment_id == experiment.id and t.metric_type == "funnel" for t in targets)
+ assert len({t.metric_uuid for t in targets}) == 3
+
+ targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs(funnel_quota=2, per_experiment_cap=10))
+ assert len(targets) == 2
+
+ def test_includes_secondary_and_saved_metrics(self):
+ self._enable_precompute()
+ secondary = _inline_metric("mean")
+ experiment = self._experiment([])
+ Experiment.objects.filter(id=experiment.id).update(metrics_secondary=[secondary])
+ saved_uuid = str(uuid.uuid4())
+ saved = ExperimentSavedMetric.objects.create(
+ team=self.team,
+ name="saved",
+ query={"uuid": saved_uuid, "kind": "ExperimentMetric", "metric_type": "funnel"},
+ )
+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved, metadata={"type": "primary"})
+
+ targets = sample_canary_targets_sync(ExperimentPrecomputeCanaryInputs(per_experiment_cap=10))
+ assert {t.metric_uuid for t in targets} == {secondary["uuid"], saved_uuid}
+
+ 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
+ targets = sample_canary_targets_sync(
+ ExperimentPrecomputeCanaryInputs(experiment_id=experiment.id, funnel_quota=1, per_experiment_cap=1)
+ )
+ assert len(targets) == 5
+
+ def test_forensics_mode_metric_uuid_filter(self):
+ metrics = [_inline_metric("funnel"), _inline_metric("mean")]
+ experiment = self._experiment(metrics)
+ targets = sample_canary_targets_sync(
+ ExperimentPrecomputeCanaryInputs(experiment_id=experiment.id, metric_uuids=[metrics[1]["uuid"]])
+ )
+ assert [t.metric_uuid for t in targets] == [metrics[1]["uuid"]]
+
+
[email protected]_db(transaction=True)
+class TestRunMetricCanary(BaseTest):
+ def _experiment(self, metrics: list[dict]) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key=f"flag-{uuid.uuid4().hex[:8]}",
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "name": "Control", "rollout_percentage": 50},
+ {"key": "test", "name": "Test", "rollout_percentage": 50},
+ ]
+ },
+ },
+ )
+ return Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ feature_flag=flag,
+ name="exp",
+ metrics=metrics,
+ start_date=timezone.now() - timedelta(days=3),
+ )
+
+ def _target(self, experiment: Experiment, metric_uuid: str) -> CanaryMetricTarget:
+ return CanaryMetricTarget(
+ team_id=self.team.id, experiment_id=experiment.id, metric_uuid=metric_uuid, metric_type="funnel"
+ )
+
+ def test_missing_experiment_is_skipped(self):
+ result = run_metric_canary_sync(
+ CanaryMetricTarget(team_id=self.team.id, experiment_id=999999, metric_uuid="x", metric_type="funnel")
+ )
+ assert result.outcome == OUTCOME_SKIPPED
+
+ def test_missing_metric_is_skipped(self):
+ experiment = self._experiment([])
+ result = run_metric_canary_sync(self._target(experiment, str(uuid.uuid4())))
+ assert result.outcome == OUTCOME_SKIPPED
+
+ def test_metric_type_changed_to_ineligible_is_skipped(self):
+ metric = _inline_metric("retention")
+ experiment = self._experiment([metric])
+ result = run_metric_canary_sync(self._target(experiment, metric["uuid"])) # target still says funnel
+ assert result.outcome == OUTCOME_SKIPPED
+
+ def test_unparseable_metric_is_skipped(self):
+ metric = {"uuid": str(uuid.uuid4()), "metric_type": "funnel"} # missing required series
+ experiment = self._experiment([metric])
+ result = run_metric_canary_sync(self._target(experiment, metric["uuid"]))
+ assert result.outcome == OUTCOME_SKIPPED
+
+ def test_runs_three_times_and_evaluates(self):
+ metric = _funnel_metric()
+ experiment = self._experiment([metric])
+ snapshots = [_snapshot("a", _BASE), _snapshot("b", _BASE), _snapshot("c", _BASE)]
+ with patch(
+ "products.experiments.backend.temporal.canary_logic._execute_canary_run", side_effect=snapshots
+ ) as mock_run:
+ result = run_metric_canary_sync(self._target(experiment, metric["uuid"]))
+
+ assert result.outcome == OUTCOME_PASS
+ assert [call.args[3] for call in mock_run.call_args_list] == ["a", "b", "c"]
+ modes = [call.args[2].value for call in mock_run.call_args_list]
+ assert modes == ["precomputed", "precomputed", "direct"]
+ assert len(result.runs) == 3
+
+ def test_query_failure_raises_for_temporal_retry(self):
+ metric = _funnel_metric()
+ experiment = self._experiment([metric])
+ with patch(
+ "products.experiments.backend.temporal.canary_logic._execute_canary_run",
+ side_effect=RuntimeError("clickhouse timeout"),
+ ):
+ with pytest.raises(RuntimeError):
+ run_metric_canary_sync(self._target(experiment, metric["uuid"]))
+
+
+def _result(outcome: str, **kwargs) -> CanaryMetricResult:
+ target = CanaryMetricTarget(team_id=1, experiment_id=2, metric_uuid="m-uuid", metric_type="funnel")
+ return CanaryMetricResult(target=target, outcome=outcome, runs=[_snapshot("a", _BASE)], **kwargs)
+
+
+class TestCanaryReporting:
+ @override_settings(EXPERIMENT_CANARY_SLACK_WEBHOOK_URL="")
+ def test_no_slack_when_webhook_unset(self):
+ with patch("products.experiments.backend.temporal.canary_logic.requests.post") as post:
+ report_canary_results_sync(CanaryReportInputs(results=[_result(OUTCOME_DIVERGENCE)]))
+ post.assert_not_called()
+
+ @override_settings(EXPERIMENT_CANARY_SLACK_WEBHOOK_URL="https://hooks.example.com/secret")
+ def test_no_slack_when_nothing_diverged(self):
+ with patch("products.experiments.backend.temporal.canary_logic.requests.post") as post:
+ report_canary_results_sync(
+ CanaryReportInputs(results=[_result(OUTCOME_PASS), _result(OUTCOME_ERROR), _result(OUTCOME_SKIPPED)])
+ )
+ post.assert_not_called()
+
+ @override_settings(EXPERIMENT_CANARY_SLACK_WEBHOOK_URL="https://hooks.example.com/secret")
+ def test_slack_posted_on_divergence(self):
+ with patch(
+ "products.experiments.backend.temporal.canary_logic.requests.post", return_value=MagicMock()
+ ) as post:
+ report_canary_results_sync(
+ CanaryReportInputs(results=[_result(OUTCOME_DIVERGENCE, stability_deviation=0.3)])
+ )
+ post.assert_called_once()
+ args, kwargs = post.call_args
+ assert args[0] == "https://hooks.example.com/secret"
+ assert kwargs["timeout"] == 10
+ body = str(kwargs["json"])
+ assert "experiment 2" in body
+ assert "m-uuid" in body
+
+ @override_settings(EXPERIMENT_CANARY_SLACK_WEBHOOK_URL="https://hooks.example.com/secret")
+ def test_slack_failure_is_swallowed_and_does_not_log_the_url(self):
+ error = requests.RequestException("404 for url: https://hooks.example.com/secret")
+ with patch("products.experiments.backend.temporal.canary_logic.requests.post", side_effect=error):
+ with patch("products.experiments.backend.temporal.canary_logic.logger.warning") as warning:
+ report_canary_results_sync(CanaryReportInputs(results=[_result(OUTCOME_DIVERGENCE)]))
+ assert "secret" not in str(warning.call_args)
diff --git a/products/experiments/backend/temporal/test_canary_workflow.py b/products/experiments/backend/temporal/test_canary_workflow.py
new file mode 100644
index 000000000000..f7abbd45ed9b
--- /dev/null
+++ b/products/experiments/backend/temporal/test_canary_workflow.py
@@ -0,0 +1,112 @@
+import uuid
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from products.experiments.backend.temporal.canary_workflow import ExperimentPrecomputeCanaryWorkflow
+from products.experiments.backend.temporal.models import (
+ OUTCOME_ERROR,
+ OUTCOME_PASS,
+ OUTCOME_SKIPPED,
+ CanaryMetricResult,
+ CanaryMetricTarget,
+ CanaryReportInputs,
+ ExperimentPrecomputeCanaryInputs,
+)
+
+
+def _target(metric_uuid: str, experiment_id: int = 1) -> CanaryMetricTarget:
+ return CanaryMetricTarget(team_id=1, experiment_id=experiment_id, metric_uuid=metric_uuid, metric_type="funnel")
+
+
+def _make_mock_activities(targets: list[CanaryMetricTarget], failing_uuids: set[str] | None = None):
+ failing_uuids = failing_uuids or set()
+ run_calls: list[CanaryMetricTarget] = []
+ reports: list[CanaryReportInputs] = []
+
+ @activity.defn(name="sample_experiment_canary_targets")
+ async def mock_sample(inputs: ExperimentPrecomputeCanaryInputs) -> list[CanaryMetricTarget]:
+ return targets
+
+ @activity.defn(name="run_experiment_metric_canary")
+ async def mock_run(target: CanaryMetricTarget) -> CanaryMetricResult:
+ run_calls.append(target)
+ if target.metric_uuid in failing_uuids:
+ raise ApplicationError("clickhouse timeout", non_retryable=True)
+ return CanaryMetricResult(target=target, outcome=OUTCOME_PASS)
+
+ @activity.defn(name="report_experiment_canary_results")
+ async def mock_report(report: CanaryReportInputs) -> None:
+ reports.append(report)
+
+ return [mock_sample, mock_run, mock_report], run_calls, reports
+
+
+async def _run_workflow(activities, inputs: ExperimentPrecomputeCanaryInputs) -> dict:
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ExperimentPrecomputeCanaryWorkflow],
+ activities=activities,
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ ExperimentPrecomputeCanaryWorkflow.run,
+ inputs,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+
+class TestExperimentPrecomputeCanaryWorkflow:
+ async def test_runs_each_target_and_reports(self):
+ targets = [_target("m1"), _target("m2"), _target("m3", experiment_id=2)]
+ activities, run_calls, reports = _make_mock_activities(targets)
+
+ result = await _run_workflow(activities, ExperimentPrecomputeCanaryInputs())
+
+ assert result == {"total": 3, OUTCOME_PASS: 3}
+ assert [t.metric_uuid for t in run_calls] == ["m1", "m2", "m3"]
+ assert len(reports) == 1
+ assert [r.outcome for r in reports[0].results] == [OUTCOME_PASS] * 3
+ assert reports[0].triggered_manually is False
+
+ async def test_failed_activity_becomes_error_outcome_and_loop_continues(self):
+ targets = [_target("m1"), _target("m2"), _target("m3")]
+ activities, run_calls, reports = _make_mock_activities(targets, failing_uuids={"m2"})
+
+ result = await _run_workflow(activities, ExperimentPrecomputeCanaryInputs())
+
+ assert result == {"total": 3, OUTCOME_PASS: 2, OUTCOME_ERROR: 1}
+ assert [t.metric_uuid for t in run_calls] == ["m1", "m2", "m3"]
+ outcomes = {r.target.metric_uuid: r.outcome for r in reports[0].results}
+ assert outcomes == {"m1": OUTCOME_PASS, "m2": OUTCOME_ERROR, "m3": OUTCOME_PASS}
+
+ async def test_exhausted_time_budget_skips_remaining_metrics(self):
+ targets = [_target("m1"), _target("m2")]
+ activities, run_calls, reports = _make_mock_activities(targets)
+
+ result = await _run_workflow(activities, ExperimentPrecomputeCanaryInputs(time_budget_seconds=-1))
+
+ assert result == {"total": 2, OUTCOME_SKIPPED: 2}
+ assert run_calls == []
+ assert all(r.detail == "time budget exhausted" for r in reports[0].results)
+
+ async def test_no_targets_still_reports(self):
+ activities, run_calls, reports = _make_mock_activities([])
+
+ result = await _run_workflow(activities, ExperimentPrecomputeCanaryInputs(triggered_manually=True))
+
+ assert result == {"total": 0}
+ assert run_calls == []
+ assert len(reports) == 1
+ assert reports[0].results == []
+ assert reports[0].triggered_manually is True
diff --git a/products/experiments/backend/temporal/test_metric_resolution.py b/products/experiments/backend/temporal/test_metric_resolution.py
new file mode 100644
index 000000000000..874acdfc6763
--- /dev/null
+++ b/products/experiments/backend/temporal/test_metric_resolution.py
@@ -0,0 +1,81 @@
+import uuid
+
+import pytest
+from posthog.test.base import BaseTest
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric, ExperimentToSavedMetric
+from products.experiments.backend.temporal.metric_resolution import find_metric_dict, iter_metric_dicts
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
[email protected]_db(transaction=True)
+class TestMetricResolution(BaseTest):
+ def _experiment(self, metrics: list[dict] | None = None, metrics_secondary: list[dict] | None = None) -> Experiment:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key=f"flag-{uuid.uuid4().hex[:8]}",
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ return Experiment.objects.create(
+ team=self.team,
+ created_by=self.user,
+ feature_flag=flag,
+ name="exp",
+ metrics=metrics or [],
+ metrics_secondary=metrics_secondary or [],
+ )
+
+ def _attach_saved(self, experiment: Experiment, query: dict, metadata: dict | None = None) -> None:
+ saved = ExperimentSavedMetric.objects.create(team=self.team, name="saved", query=query)
+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved, metadata=metadata or {})
+
+ def test_inline_metric_takes_precedence_over_saved_with_same_uuid(self):
+ shared_uuid = str(uuid.uuid4())
+ inline = {"uuid": shared_uuid, "metric_type": "funnel", "source": "inline"}
+ experiment = self._experiment(metrics=[inline])
+ self._attach_saved(experiment, {"uuid": shared_uuid, "metric_type": "funnel", "source": "saved"})
+
+ resolved = find_metric_dict(experiment, shared_uuid)
+ assert resolved is not None
+ assert resolved["source"] == "inline"
+
+ def test_resolution_order_is_primary_secondary_saved(self):
+ primary, secondary = {"uuid": str(uuid.uuid4())}, {"uuid": str(uuid.uuid4())}
+ experiment = self._experiment(metrics=[primary], metrics_secondary=[secondary])
+ saved_uuid = str(uuid.uuid4())
+ self._attach_saved(experiment, {"uuid": saved_uuid, "metric_type": "mean"})
+
+ assert [m["uuid"] for m in iter_metric_dicts(experiment)] == [
+ primary["uuid"],
+ secondary["uuid"],
+ saved_uuid,
+ ]
+
+ def test_saved_metric_breakdowns_merged_from_link_metadata(self):
+ experiment = self._experiment()
+ saved_uuid = str(uuid.uuid4())
+ breakdowns = [{"property": "$browser", "type": "event"}]
+ self._attach_saved(
+ experiment,
+ {"uuid": saved_uuid, "metric_type": "funnel", "breakdownFilter": {"breakdown_limit": 5}},
+ metadata={"breakdowns": breakdowns},
+ )
+
+ resolved = find_metric_dict(experiment, saved_uuid)
+ assert resolved is not None
+ assert resolved["breakdownFilter"] == {"breakdown_limit": 5, "breakdowns": breakdowns}
+
+ def test_saved_metric_without_metadata_gets_empty_breakdowns(self):
+ experiment = self._experiment()
+ saved_uuid = str(uuid.uuid4())
+ self._attach_saved(experiment, {"uuid": saved_uuid, "metric_type": "funnel"})
+
+ resolved = find_metric_dict(experiment, saved_uuid)
+ assert resolved is not None
+ assert resolved["breakdownFilter"] == {"breakdowns": []}
+
+ def test_metrics_without_uuid_are_excluded(self):
+ experiment = self._experiment(metrics=[{"metric_type": "funnel"}])
+ self._attach_saved(experiment, {"metric_type": "funnel"})
+ assert iter_metric_dicts(experiment) == []
diff --git a/products/experiments/backend/temporal/test_registration.py b/products/experiments/backend/temporal/test_registration.py
index 9db6609157ce..b74f73829c8b 100644
--- a/products/experiments/backend/temporal/test_registration.py
+++ b/products/experiments/backend/temporal/test_registration.py
@@ -1,4 +1,5 @@
from products.experiments.backend.temporal import ACTIVITIES, WORKFLOWS
+from products.experiments.backend.temporal.canary_workflow import ExperimentPrecomputeCanaryWorkflow
from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow
@@ -8,8 +9,11 @@ def test_activities_registered():
"discover_experiment_metrics",
"calculate_experiment_metric_for_recalculation",
"update_recalculation_progress",
+ "sample_experiment_canary_targets",
+ "run_experiment_metric_canary",
+ "report_experiment_canary_results",
}
def test_workflow_registered():
- assert WORKFLOWS == [ExperimentMetricsRecalculationWorkflow]
+ assert WORKFLOWS == [ExperimentMetricsRecalculationWorkflow, ExperimentPrecomputeCanaryWorkflow]
diff --git a/tach.toml b/tach.toml
index 0602c7cee59b..9c47bf5f68f0 100644
--- a/tach.toml
+++ b/tach.toml
@@ -674,15 +674,17 @@ from = [
]
# Temporal worker registration lives in posthog/management/commands/start_temporal_worker.py, which imports
-# ACTIVITIES and WORKFLOWS from each product's backend.temporal package. Eight peer products do the same
-# thing, but experiments is the first isolated product to register a workflow, so the canonical interface
-# doesn't cover it yet. Narrowly expose just the registration symbols rather than widening every isolated
-# product's surface.
+# ACTIVITIES and WORKFLOWS from each product's backend.temporal package, and schedule registration lives in
+# posthog/temporal/schedule.py, which imports each product's schedule-creation functions. Eight peer products
+# do the same thing, but experiments is the first isolated product to register a workflow, so the canonical
+# interface doesn't cover it yet. Narrowly expose just the registration symbols rather than widening every
+# isolated product's surface.
[[interfaces]]
expose = [
"backend\\.temporal\\.ACTIVITIES",
"backend\\.temporal\\.WORKFLOWS",
+ "backend\\.temporal\\.schedule\\.create_experiment_precompute_canary_schedule",
]
from = [
"products.experiments",