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.

chore(experiments): add a coverage probe for the setup context (#104684)

Marcel Poelker64b523dc9373
diff --git a/products/experiments/backend/management/commands/probe_experiment_setup_context.py b/products/experiments/backend/management/commands/probe_experiment_setup_context.py
new file mode 100644
index 000000000000..3586970b71b7
--- /dev/null
+++ b/products/experiments/backend/management/commands/probe_experiment_setup_context.py
@@ -0,0 +1,140 @@
+"""Read every section of `experiment-setup-context` back for a project, from a shell.
+
+A local tool with two jobs. It confirms that a seeded project reports the shape it was seeded with,
+and it checks that every section still answers after `setup_context.py` changes.
+
+ CLICKHOUSE_DATABASE=posthog python manage.py probe_experiment_setup_context \\
+ --team-id 1 --target-event '$pageview' --metric-event '<event>' --cold
+
+`CLICKHOUSE_DATABASE=posthog` is not optional. The setting defaults to `default`, and the real
+value lives in `.env.services`, which a plain shell does not load.
+
+It answers a narrow question: did the section answer, and was the fact there to read. It does not
+measure whether the setup context helps an agent configure an experiment correctly, which needs an
+eval that scores the created experiment across two arms. A coverage number over a whole region is
+cheaper to get from one cross-team query than from this per-team loop, so this is not the way to
+measure a fleet.
+
+Calls the providers in process, so neither the feature flag nor authentication applies. It also
+skips the access-control filtering the endpoint applies to the experiment and saved-metric
+querysets, so the two list counts are upper bounds rather than what a scoped agent sees.
+
+Latency is only meaningful on a cold read. Three sections cache for an hour or more, keyed by team
+and inputs, so a second run over the same project measures the cache. `--cold` drops those keys,
+which is the only write this command makes.
+
+Without `--team-id`, `--limit` picks the projects that ran an experiment most recently, across the
+whole instance and with no organization scoping.
+
+The output carries ids, counts and booleans only, so a scorecard is safe to paste into an internal
+discussion. `--per-team` adds one row per project, which is how a single slow project is found.
+"""
+
+import json
+import dataclasses
+from argparse import ArgumentParser
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError
+
+from products.experiments.backend.setup_context_probe import (
+ SECTION_NAMES,
+ DecisiveFacts,
+ SetupContextProbe,
+ SetupContextScorecard,
+ teams_by_id,
+ teams_with_recent_experiments,
+)
+
+
+class Command(BaseCommand):
+ help = "Score the experiment setup context across projects"
+
+ def add_arguments(self, parser: ArgumentParser) -> None:
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ action="append",
+ dest="team_ids",
+ help="Probe this team only; repeatable. Without it, --limit picks teams by recent experiment.",
+ )
+ parser.add_argument(
+ "--limit", type=int, default=10, help="How many teams with recent experiments to probe (default 10)"
+ )
+ parser.add_argument(
+ "--target-event", help="Target event, so target_surface and the metric baseline run instead of skipping"
+ )
+ parser.add_argument("--metric-event", help="Metric event, so candidate_metric and the event match run")
+ parser.add_argument(
+ "--cold",
+ action="store_true",
+ help="Drop the cached sections before each team, so the latency is a real read",
+ )
+ parser.add_argument("--per-team", action="store_true", help="Also print one row per team")
+ parser.add_argument("--json", action="store_true", dest="as_json", help="Print JSON instead of TSV")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["limit"] < 1:
+ raise CommandError("--limit must be at least 1")
+ teams = (
+ teams_by_id(options["team_ids"]) if options["team_ids"] else teams_with_recent_experiments(options["limit"])
+ )
+ if not teams:
+ raise CommandError("No teams to probe")
+
+ probe = SetupContextProbe(
+ target_event=options["target_event"],
+ metric_event=options["metric_event"],
+ cold=options["cold"],
+ )
+ scorecard = probe.run(teams)
+
+ if options["as_json"]:
+ self.print_json(scorecard, per_team=options["per_team"])
+ else:
+ self.print_tsv(scorecard, per_team=options["per_team"])
+
+ def print_json(self, scorecard: SetupContextScorecard, *, per_team: bool) -> None:
+ payload = dataclasses.asdict(scorecard)
+ if not per_team:
+ payload.pop("readings")
+ self.stdout.write(json.dumps(payload, default=str))
+
+ def print_tsv(self, scorecard: SetupContextScorecard, *, per_team: bool) -> None:
+ self.stdout.write(
+ f"teams\t{scorecard.teams}\tunreadable\t{scorecard.failed_teams}"
+ f"\tlatency\t{'cold' if scorecard.cold else 'cached, not comparable'}"
+ )
+
+ self.stdout.write("\nsection\tok\tteams\tp50_ms\tp95_ms")
+ for section in scorecard.sections:
+ self.stdout.write(
+ f"{section.name}\t{section.ok}\t{section.teams}"
+ f"\t{self.milliseconds(section.p50_ms)}\t{self.milliseconds(section.p95_ms)}"
+ )
+
+ self.stdout.write("\nfact\tpresent\tmeasured")
+ for fact in scorecard.facts:
+ self.stdout.write(f"{fact.name}\t{fact.present}\t{fact.measured}")
+
+ if not per_team:
+ return
+ self.stdout.write("\nteam_id\t" + "\t".join([*SECTION_NAMES, *self.fact_names()]))
+ for reading in scorecard.readings:
+ statuses = [
+ reading.sections[name].status if name in reading.sections else "unread" for name in SECTION_NAMES
+ ]
+ facts = (
+ [getattr(reading.facts, name) for name in self.fact_names()]
+ if reading.facts is not None
+ else ["unread"] * len(self.fact_names())
+ )
+ self.stdout.write(f"{reading.team_id}\t" + "\t".join(str(value) for value in [*statuses, *facts]))
+
+ @staticmethod
+ def fact_names() -> list[str]:
+ return [field.name for field in dataclasses.fields(DecisiveFacts)]
+
+ @staticmethod
+ def milliseconds(value: float | None) -> str:
+ return "-" if value is None else f"{value:.0f}"
diff --git a/products/experiments/backend/setup_context.py b/products/experiments/backend/setup_context.py
index 73b250ef8b3c..343865d7126f 100644
--- a/products/experiments/backend/setup_context.py
+++ b/products/experiments/backend/setup_context.py
@@ -9,6 +9,7 @@ recommendations, because every consumer applies its own policy to the same facts
"""
import json
+import time
import hashlib
import logging
import dataclasses
@@ -39,7 +40,7 @@ from posthog.exceptions import (
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.production_event_activation import MOBILE_SIDE_LIBS, SERVER_SIDE_LIBS
from posthog.models.team.team import Team
-from posthog.utils import get_safe_cache, safe_cache_set
+from posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_set
from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
@@ -415,12 +416,17 @@ class ExperimentSetupContext:
shared_metrics: SetupContextSection[SharedMetrics]
+# A skipped section never runs a provider, so the observer never hears about it.
+SectionObserver = Callable[[str, SetupContextSectionStatus, float], None]
+
+
def build_setup_context(
*,
team: Team,
inputs: SetupContextInputs,
experiments: QuerySet[Experiment],
saved_metrics: QuerySet[ExperimentSavedMetric],
+ on_section: SectionObserver | None = None,
) -> ExperimentSetupContext:
"""Assemble every section of the setup context.
@@ -432,15 +438,15 @@ def build_setup_context(
# on a first call for a team writes) team extension rows outside ClickHouse.
skipped: SetupContextSection[Any] = SetupContextSection(status=SetupContextSectionStatus.SKIPPED)
return ExperimentSetupContext(
- team_defaults=_run_section("team_defaults", team, lambda: get_team_defaults(team)),
- sdk_profile=_run_section("sdk_profile", team, lambda: get_sdk_profile(team)),
+ team_defaults=_run_section("team_defaults", team, lambda: get_team_defaults(team), on_section),
+ sdk_profile=_run_section("sdk_profile", team, lambda: get_sdk_profile(team), on_section),
target_surface=(
- _run_section("target_surface", team, lambda: get_target_surface(team, inputs))
+ _run_section("target_surface", team, lambda: get_target_surface(team, inputs), on_section)
if inputs.target_event
else skipped
),
candidate_metric=(
- _run_section("candidate_metric", team, lambda: get_candidate_metric(team, inputs))
+ _run_section("candidate_metric", team, lambda: get_candidate_metric(team, inputs), on_section)
if inputs.metric_event
else skipped
),
@@ -448,6 +454,7 @@ def build_setup_context(
"previous_experiments",
team,
lambda: get_previous_experiments(experiments, limit=inputs.previous_experiments_limit),
+ on_section,
),
shared_metrics=_run_section(
"shared_metrics",
@@ -459,11 +466,22 @@ def build_setup_context(
limit=inputs.shared_metrics_limit,
metric_event=inputs.metric_event,
),
+ on_section,
),
)
-def _run_section(name: str, team: Team, provider: Callable[[], T]) -> SetupContextSection[T]:
+def _run_section(
+ name: str, team: Team, provider: Callable[[], T], on_section: SectionObserver | None = None
+) -> SetupContextSection[T]:
+ started = time.monotonic()
+ section = _read_section(name, team, provider)
+ if on_section is not None:
+ on_section(name, section.status, (time.monotonic() - started) * 1000)
+ return section
+
+
+def _read_section(name: str, team: Team, provider: Callable[[], T]) -> SetupContextSection[T]:
try:
return SetupContextSection(status=SetupContextSectionStatus.OK, data=provider())
except _CLICKHOUSE_TOO_EXPENSIVE:
@@ -771,6 +789,21 @@ def _target_cache_inputs(team: Team, inputs: SetupContextInputs) -> dict[str, An
}
+def clear_cached_sections(team: Team, inputs: SetupContextInputs) -> None:
+ """Drop the cached ClickHouse sections for this team and these inputs.
+
+ A caller that measures how long a section takes needs a cold read. The three cached sections
+ answer from the cache for hours, so a second measurement of the same team reports the cache.
+ """
+ target_inputs = _target_cache_inputs(team, inputs)
+ for section, key_inputs in (
+ ("sdk_profile", {}),
+ ("target_surface", target_inputs),
+ ("candidate_metric", target_inputs),
+ ):
+ safe_cache_delete(_cache_key(team, section, key_inputs))
+
+
def get_target_surface(team: Team, inputs: SetupContextInputs) -> TargetSurface:
if not inputs.target_event:
raise ValueError("target_event is required for the target surface")
diff --git a/products/experiments/backend/setup_context_probe.py b/products/experiments/backend/setup_context_probe.py
new file mode 100644
index 000000000000..3a46049c2df5
--- /dev/null
+++ b/products/experiments/backend/setup_context_probe.py
@@ -0,0 +1,268 @@
+"""Measure what `experiment-setup-context` can actually tell an agent, across many projects.
+
+Two numbers decide whether a section earns its tokens: how often it comes back `ok`, and how often
+it carries a fact a rule branches on. A section that answers for every project but decides nothing
+costs as much as one that times out.
+
+Every fact reports a denominator as well as a count, because a fact whose section did not run is
+unmeasured rather than absent. "0 of 25 projects cross identification" and "0 of 0" are different
+answers, and only the second one means nothing was read.
+"""
+
+import logging
+import dataclasses
+from collections.abc import Iterable, Sequence
+from math import ceil
+from statistics import median
+from typing import Final
+
+from django.db.models import Max
+
+from posthog.dataclasses import frozen
+from posthog.models.team.team import Team
+
+from products.experiments.backend.models.experiment import Experiment, ExperimentSavedMetric
+from products.experiments.backend.setup_context import (
+ ExperimentSetupContext,
+ PreviousExperiments,
+ SdkLibCategory,
+ SdkProfile,
+ SetupContextInputs,
+ SetupContextSectionStatus,
+ SharedMetrics,
+ TargetSurface,
+ build_setup_context,
+ clear_cached_sections,
+)
+
+logger = logging.getLogger(__name__)
+
+SECTION_NAMES: Final[tuple[str, ...]] = (
+ "team_defaults",
+ "sdk_profile",
+ "target_surface",
+ "candidate_metric",
+ "previous_experiments",
+ "shared_metrics",
+)
+
+# The band where a surface crosses identification, which is the one place the bucketing rules ask
+# for more than the user id. Kept in step with "Bucketing and persistence" in
+# products/experiments/skills/creating-experiments/references/setup-decisions.md.
+IDENTITY_BAND: Final[tuple[float, float]] = (0.1, 0.9)
+# "Near 1" in the device-id bucketing step.
+DEVICE_ID_SHARE_FLOOR: Final = 0.95
+
+
+@frozen
+class SectionReading:
+ status: SetupContextSectionStatus
+ # None for a section that never ran, which is every skipped section.
+ duration_ms: float | None
+
+
+@frozen
+class DecisiveFacts:
+ """Whether each fact a bucketing or precedent rule branches on was there to read."""
+
+ sdk_libs_empty: bool
+ libs_on_any_event_used: bool
+ anonymous_share_null: bool
+ anonymous_share_crosses_identification: bool
+ device_id_bucketing_plausible: bool
+ server_lib_reports_local_evaluation: bool
+ previous_experiments_listed: int
+ shared_metrics_listed: int
+
+
+FACT_SECTIONS: Final[dict[str, tuple[str, ...]]] = {
+ "sdk_libs_empty": ("sdk_profile",),
+ "libs_on_any_event_used": ("sdk_profile",),
+ "anonymous_share_null": ("target_surface",),
+ "anonymous_share_crosses_identification": ("target_surface",),
+ "device_id_bucketing_plausible": ("sdk_profile", "target_surface"),
+ "server_lib_reports_local_evaluation": ("sdk_profile",),
+ "previous_experiments_listed": ("previous_experiments",),
+ "shared_metrics_listed": ("shared_metrics",),
+}
+
+
+@frozen
+class TeamReading:
+ team_id: int
+ sections: dict[str, SectionReading]
+ facts: DecisiveFacts | None
+ failed: bool
+
+
+@frozen
+class SectionScore:
+ name: str
+ teams: int
+ ok: int
+ p50_ms: float | None
+ p95_ms: float | None
+
+
+@frozen
+class FactCoverage:
+ name: str
+ present: int
+ measured: int
+
+
+@frozen
+class SetupContextScorecard:
+ teams: int
+ failed_teams: int
+ cold: bool
+ sections: list[SectionScore]
+ facts: list[FactCoverage]
+ readings: list[TeamReading]
+
+
+class SetupContextProbe:
+ """Build the setup context for many projects and score what came back."""
+
+ def __init__(
+ self,
+ *,
+ target_event: str | None = None,
+ metric_event: str | None = None,
+ cold: bool = False,
+ ) -> None:
+ self.inputs = SetupContextInputs(target_event=target_event, metric_event=metric_event)
+ self.cold = cold
+
+ def run(self, teams: Sequence[Team]) -> SetupContextScorecard:
+ return self.score([self.read_team(team) for team in teams])
+
+ def read_team(self, team: Team) -> TeamReading:
+ sections: dict[str, SectionReading] = {}
+
+ def observe(name: str, status: SetupContextSectionStatus, duration_ms: float) -> None:
+ sections[name] = SectionReading(status=status, duration_ms=duration_ms)
+
+ try:
+ if self.cold:
+ clear_cached_sections(team, self.inputs)
+ context = build_setup_context(
+ team=team,
+ inputs=self.inputs,
+ experiments=Experiment.objects.filter(team_id=team.pk),
+ saved_metrics=ExperimentSavedMetric.objects.filter(team_id=team.pk),
+ on_section=observe,
+ )
+ except Exception:
+ # One project that cannot be read must not end a sweep over hundreds.
+ logger.exception("experiment_setup_context_probe_failed", extra={"team_id": team.pk})
+ return TeamReading(team_id=team.pk, sections={}, facts=None, failed=True)
+
+ for name in SECTION_NAMES:
+ if name not in sections:
+ sections[name] = SectionReading(status=getattr(context, name).status, duration_ms=None)
+ return TeamReading(team_id=team.pk, sections=sections, facts=self.decisive_facts(context), failed=False)
+
+ def decisive_facts(self, context: ExperimentSetupContext) -> DecisiveFacts:
+ sdk_profile: SdkProfile | None = context.sdk_profile.data
+ target_surface: TargetSurface | None = context.target_surface.data
+ previous: PreviousExperiments | None = context.previous_experiments.data
+ shared: SharedMetrics | None = context.shared_metrics.data
+
+ anonymous_share = target_surface.anonymous_share if target_surface else None
+ return DecisiveFacts(
+ sdk_libs_empty=sdk_profile is not None and not sdk_profile.libs,
+ libs_on_any_event_used=bool(sdk_profile and sdk_profile.libs_on_any_event),
+ anonymous_share_null=target_surface is not None and anonymous_share is None,
+ anonymous_share_crosses_identification=(
+ anonymous_share is not None and IDENTITY_BAND[0] <= anonymous_share <= IDENTITY_BAND[1]
+ ),
+ device_id_bucketing_plausible=self.device_id_bucketing_plausible(sdk_profile, target_surface),
+ server_lib_reports_local_evaluation=bool(
+ sdk_profile
+ and any(
+ lib.category == SdkLibCategory.SERVER and lib.locally_evaluated_share is not None
+ for lib in sdk_profile.libs
+ )
+ ),
+ previous_experiments_listed=len(previous.experiments) if previous else 0,
+ shared_metrics_listed=len(shared.metrics) if shared else 0,
+ )
+
+ @staticmethod
+ def device_id_bucketing_plausible(sdk_profile: SdkProfile | None, target_surface: TargetSurface | None) -> bool:
+ """Step 1 of the bucketing rules, read exactly as that step reads it.
+
+ The surface's own share has to be near 1, at least one profiled SDK has to be one that
+ reached the surface, and every such SDK has to be near 1 on its flag calls. An `any()` over
+ the two lists merged would pass on one high row from an SDK the surface never sees.
+ """
+ if sdk_profile is None or target_surface is None:
+ return False
+ if target_surface.device_id_share is None or target_surface.device_id_share <= DEVICE_ID_SHARE_FLOOR:
+ return False
+ surface_libs = {lib.lib for lib in target_surface.libs}
+ matching = [lib for lib in sdk_profile.libs if lib.lib in surface_libs]
+ return bool(matching) and all(lib.device_id_share > DEVICE_ID_SHARE_FLOOR for lib in matching)
+
+ def score(self, readings: Sequence[TeamReading]) -> SetupContextScorecard:
+ read = [reading for reading in readings if not reading.failed]
+ return SetupContextScorecard(
+ teams=len(readings),
+ failed_teams=len(readings) - len(read),
+ cold=self.cold,
+ sections=[self.score_section(name, read) for name in SECTION_NAMES],
+ facts=[self.score_fact(field.name, read) for field in dataclasses.fields(DecisiveFacts)],
+ readings=list(readings),
+ )
+
+ def score_section(self, name: str, readings: Sequence[TeamReading]) -> SectionScore:
+ present = [reading.sections[name] for reading in readings if name in reading.sections]
+ durations = sorted(section.duration_ms for section in present if section.duration_ms is not None)
+ return SectionScore(
+ name=name,
+ teams=len(present),
+ ok=sum(1 for section in present if section.status == SetupContextSectionStatus.OK),
+ p50_ms=median(durations) if durations else None,
+ p95_ms=self.percentile(durations, 0.95),
+ )
+
+ def score_fact(self, name: str, readings: Sequence[TeamReading]) -> FactCoverage:
+ measured = [reading for reading in readings if reading.facts is not None and self.fact_measured(reading, name)]
+ return FactCoverage(
+ name=name,
+ present=sum(1 for reading in measured if bool(getattr(reading.facts, name))),
+ measured=len(measured),
+ )
+
+ @staticmethod
+ def fact_measured(reading: TeamReading, name: str) -> bool:
+ return all(
+ section in reading.sections and reading.sections[section].status == SetupContextSectionStatus.OK
+ for section in FACT_SECTIONS[name]
+ )
+
+ @staticmethod
+ def percentile(sorted_values: Sequence[float], share: float) -> float | None:
+ if not sorted_values:
+ return None
+ # Nearest-rank, so a handful of projects still gives an honest tail rather than an average.
+ index = min(len(sorted_values) - 1, max(0, ceil(share * len(sorted_values)) - 1))
+ return sorted_values[index]
+
+
+def teams_with_recent_experiments(limit: int) -> list[Team]:
+ """Projects that ran an experiment most recently, which are the ones a rule change reaches."""
+ team_ids = list(
+ Experiment.objects.exclude(deleted=True)
+ .values("team_id")
+ .annotate(last_experiment_at=Max("created_at"))
+ .order_by("-last_experiment_at")
+ .values_list("team_id", flat=True)[:limit]
+ )
+ by_id = {team.pk: team for team in Team.objects.filter(pk__in=team_ids)}
+ return [by_id[team_id] for team_id in team_ids if team_id in by_id]
+
+
+def teams_by_id(team_ids: Iterable[int]) -> list[Team]:
+ return list(Team.objects.filter(pk__in=list(team_ids)))
diff --git a/products/experiments/backend/test/test_setup_context_probe.py b/products/experiments/backend/test/test_setup_context_probe.py
new file mode 100644
index 000000000000..75973d7ccd47
--- /dev/null
+++ b/products/experiments/backend/test/test_setup_context_probe.py
@@ -0,0 +1,119 @@
+import dataclasses
+from datetime import timedelta
+from io import StringIO
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.core.management import call_command
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.experiments.backend.hogql_queries.exposure_query_logic import DEFAULT_EXPOSURE_EVENT
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.setup_context_probe import (
+ SECTION_NAMES,
+ DecisiveFacts,
+ SetupContextProbe,
+ teams_with_recent_experiments,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestSetupContextProbe(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="probe-flag",
+ created_by=self.user,
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ )
+ Experiment.objects.create(team=self.team, name="Probe experiment", feature_flag=flag, created_by=self.user)
+ _create_person(team=self.team, distinct_ids=["visitor"])
+ _create_event(
+ team=self.team,
+ event=DEFAULT_EXPOSURE_EVENT,
+ distinct_id="visitor",
+ timestamp=timezone.now() - timedelta(hours=1),
+ properties={
+ "$feature_flag": "probe-flag",
+ "$feature_flag_response": "test",
+ "$lib": "web",
+ "$device_id": "device-1",
+ "$is_identified": "false",
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="visitor",
+ timestamp=timezone.now() - timedelta(hours=1),
+ properties={"$lib": "web", "$device_id": "device-1", "$is_identified": "false"},
+ )
+ flush_persons_and_events()
+
+ def test_scorecard_reports_every_section_and_every_decisive_fact(self) -> None:
+ scorecard = SetupContextProbe(target_event="$pageview").run([self.team])
+
+ assert scorecard.teams == 1
+ assert scorecard.failed_teams == 0
+ assert [section.name for section in scorecard.sections] == list(SECTION_NAMES)
+ # candidate_metric is skipped without a metric event, so it reports a status but no timing.
+ assert {section.name: section.p50_ms is None for section in scorecard.sections}["candidate_metric"]
+ assert {fact.name for fact in scorecard.facts} == {field.name for field in dataclasses.fields(DecisiveFacts)}
+ assert scorecard.readings[0].facts is not None
+ assert scorecard.readings[0].facts.previous_experiments_listed == 1
+
+ def test_a_fact_whose_section_was_skipped_is_unmeasured_rather_than_absent(self) -> None:
+ scorecard = SetupContextProbe().run([self.team])
+
+ coverage = {fact.name: fact for fact in scorecard.facts}
+ assert coverage["anonymous_share_crosses_identification"].measured == 0
+ assert coverage["device_id_bucketing_plausible"].measured == 0
+ assert coverage["previous_experiments_listed"].measured == 1
+
+ def test_one_unreadable_project_does_not_end_the_sweep(self) -> None:
+ with patch(
+ "products.experiments.backend.setup_context_probe.build_setup_context",
+ side_effect=RuntimeError("boom"),
+ ):
+ scorecard = SetupContextProbe().run([self.team])
+
+ assert scorecard.teams == 1
+ assert scorecard.failed_teams == 1
+ assert scorecard.readings[0].facts is None
+ assert all(fact.measured == 0 for fact in scorecard.facts)
+
+ def test_teams_with_recent_experiments_finds_the_seeded_project(self) -> None:
+ assert self.team in teams_with_recent_experiments(limit=5)
+
+ def test_command_prints_a_scorecard_without_user_authored_strings(self) -> None:
+ out = StringIO()
+ call_command(
+ "probe_experiment_setup_context",
+ f"--team-id={self.team.pk}",
+ "--target-event=$pageview",
+ "--per-team",
+ stdout=out,
+ )
+ printed = out.getvalue()
+
+ for name in SECTION_NAMES:
+ assert name in printed
+ assert str(self.team.pk) in printed
+ assert "Probe experiment" not in printed
+ assert "probe-flag" not in printed
+
+
+class TestPercentile(SimpleTestCase):
+ @parameterized.expand([(1, 0.0), (12, 11.0), (20, 18.0)])
+ def test_p95_takes_the_nearest_rank(self, count: int, expected: float) -> None:
+ assert SetupContextProbe.percentile([float(rank) for rank in range(count)], 0.95) == expected
+
+ def test_no_timing_has_no_percentile(self) -> None:
+ assert SetupContextProbe.percentile([], 0.95) is None