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(evals): report confidence intervals and pass^k across trials (#114092)

Lucas Fariaa78210e03acb
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index 7e3af9d0e964..abda86f174ef 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -258,6 +258,7 @@ python -m products.posthog_ai.eval_harness.harness --list | grep my_thing
Progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.
Only the overall run uses `PASS` or `FAIL`, so a suite with a low behavioral score still reads as completed rather than passed.
The final summary gives labeled suite and case totals, the score gate, total duration, and one block per experiment with scorer averages, PostHog and Braintrust URLs, and the agent-log directory.
+Each scorer line shows its score with a 95% confidence interval clustered by case. With `--trials N` a second line adds pass^N (every trial passed), pass@N (any trial passed) and the number of flaky cases, counting only cases scored on all N trials, so a noisy suite is distinguishable from a real score change.
A crashed suite is labeled `CRASH`, includes its traceback in the summary, and makes the run exit nonzero without taking down the other suites.
Every real eval invocation mirrors its complete stdout and stderr to:
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index 56d2d15e7442..2f33053c73a8 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -20,6 +20,7 @@ from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCase
from .engines.base import EvalEngine
from .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKind
from .harness.kernel_sandboxes import reclaim_kernels
+from .harness.trial_stats import trial_stats
from .log_parser import describe_tool_use
from .log_sink import append_case_scores, build_case_dir, write_case_logs
from .runner import AgentNeverRanError, EvalCaseResult, agent_never_ran, run_eval_case
@@ -325,7 +326,12 @@ class _BaseEvalRun:
# Errored cases (infra failures) are surfaced separately so they read as noise,
# not as agent 0s dragging the averages.
error_count = sum(1 for r in result.results if r.error is not None)
- await self.ctx.reporter.record_summary(self.experiment_name, result.summary, error_count=error_count)
+ await self.ctx.reporter.record_summary(
+ self.experiment_name,
+ result.summary,
+ error_count=error_count,
+ trial_stats=trial_stats(result.results, trials=self.ctx.trials),
+ )
if os.getenv("EXPORT_EVAL_RESULTS"):
self._export_case_results(result)
diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.py
index f094d7d59923..9d3d5bb61f09 100644
--- a/products/posthog_ai/eval_harness/harness/reporting.py
+++ b/products/posthog_ai/eval_harness/harness/reporting.py
@@ -10,6 +10,7 @@ from pathlib import Path
from typing import Literal
from ..engines.types import EvalSummary
+from .trial_stats import ScorerTrialStats
EVAL_RESULTS_JSONL = "eval_results.jsonl"
"""Machine-readable per-experiment summary export, opt-in via ``EXPORT_EVAL_RESULTS``."""
@@ -47,6 +48,7 @@ class ProgressReporter:
self._case_durations: dict[str, float] = defaultdict(float)
self._case_statuses: dict[str, Counter[str]] = defaultdict(Counter)
self._summary_error_counts: dict[str, int] = defaultdict(int)
+ self._trial_stats: dict[str, Sequence[ScorerTrialStats]] = {}
self._experiment_totals: dict[str, int] = {}
self._posthog_urls: dict[str, str] = {}
self._log_dirs: dict[str, Path] = {}
@@ -112,9 +114,17 @@ class ProgressReporter:
f"{_format_duration(result.duration_seconds)}"
)
- async def record_summary(self, experiment_name: str, summary: EvalSummary, *, error_count: int = 0) -> None:
+ async def record_summary(
+ self,
+ experiment_name: str,
+ summary: EvalSummary,
+ *,
+ error_count: int = 0,
+ trial_stats: Sequence[ScorerTrialStats] = (),
+ ) -> None:
async with self._lock:
self._summaries[experiment_name] = summary
+ self._trial_stats[experiment_name] = trial_stats
self._summary_error_counts[experiment_name] = error_count
if os.getenv("EXPORT_EVAL_RESULTS"):
with open(EVAL_RESULTS_JSONL, "a", encoding="utf-8") as f:
@@ -206,10 +216,12 @@ class ProgressReporter:
(f" Cases: {statuses['ok']} done, {statuses['timeout']} timed out, {error_count} errors"),
f" Case time: {_format_duration(self._case_durations[experiment_name])}",
]
+ stats_by_scorer = {stats.name: stats for stats in self._trial_stats.get(experiment_name, ())}
scores = [(score.name, score.score) for score in summary.scores.values() if score.score is not None]
if scores:
lines.append(" Scores:")
- lines.extend(f" {name}: {score * 100:.1f}%" for name, score in scores)
+ for name, score in scores:
+ lines.extend(_score_lines(name, score, stats_by_scorer.get(name)))
else:
lines.append(" Scores: none")
@@ -251,6 +263,27 @@ class ProgressReporter:
return lines
+def _score_lines(name: str, score: float, stats: ScorerTrialStats | None) -> list[str]:
+ if stats is None:
+ return [f" {name}: {score * 100:.1f}%"]
+ interval = ""
+ if stats.ci_low is not None and stats.ci_high is not None:
+ interval = f" (95% CI {stats.ci_low * 100:.1f}-{stats.ci_high * 100:.1f}%)"
+ lines = [f" {name}: {score * 100:.1f}%{interval}"]
+ if stats.trials > 1:
+ k = stats.trials
+ shortfall = f" | {stats.short_cases} cases short of {k} trials" if stats.short_cases else ""
+ lines.append(
+ f" pass^{k} {_percent(stats.pass_all)} | pass@{k} {_percent(stats.pass_any)} "
+ f"| {stats.flaky_cases}/{stats.complete_cases} cases flaky{shortfall}"
+ )
+ return lines
+
+
+def _percent(value: float | None) -> str:
+ return "n/a" if value is None else f"{value * 100:.1f}%"
+
+
def _format_duration(seconds: float) -> str:
if seconds < 60:
return f"{seconds:.1f}s"
diff --git a/products/posthog_ai/eval_harness/harness/trial_stats.py b/products/posthog_ai/eval_harness/harness/trial_stats.py
new file mode 100644
index 000000000000..4cc1efb5e3b5
--- /dev/null
+++ b/products/posthog_ai/eval_harness/harness/trial_stats.py
@@ -0,0 +1,116 @@
+"""Per-scorer statistics across the cases and trials of an experiment.
+
+Stdlib-only, so the reporting path never pulls in Django or Braintrust to render it.
+"""
+
+from __future__ import annotations
+
+import math
+from collections import defaultdict
+from collections.abc import Sequence
+from dataclasses import dataclass
+
+from ..engines.types import CaseResult
+
+# Two-sided 95% Student's t quantiles for 1-30 degrees of freedom; past that the normal 1.96 is close enough.
+_T_95 = (
+ 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228,
+ 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086,
+ 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042,
+) # fmt: skip
+
+
+@dataclass(frozen=True)
+class ScorerTrialStats:
+ """How stable one scorer's result is across the cases and trials of an experiment.
+
+ pass^k, pass@k and flakiness treat a score of 1.0 as a pass, which fits the binary
+ scorers the harness ships; a partial-credit scorer only ever passes at 1.0.
+ """
+
+ name: str
+ cases: int
+ """Cases with at least one scored trial."""
+ trials: int
+ """Trials each case was run for, the ``k`` in pass^k."""
+ mean: float
+ """Mean over every scored trial, the same aggregate the engine reports."""
+ ci_low: float | None
+ ci_high: float | None
+ """95% interval of ``mean`` with case-clustered errors, clamped to [0, 1]. ``None`` below two cases."""
+ complete_cases: int
+ """Cases scored on every one of the ``trials`` trials; pass^k, pass@k and flakiness count only these."""
+ pass_all: float | None
+ """pass^k: share of complete cases where every trial passed. ``None`` for single-trial runs."""
+ pass_any: float | None
+ """pass@k: share of complete cases where at least one trial passed. ``None`` for single-trial runs."""
+ flaky_cases: int
+ """Complete cases where some trials passed and others did not."""
+ short_cases: int
+ """Cases with fewer than ``trials`` scored trials, including cases whose every trial errored.
+ A case the scorer skipped (returned ``None``) does not apply to it and is not short."""
+
+
+def trial_stats(results: Sequence[CaseResult], *, trials: int) -> list[ScorerTrialStats]:
+ """Aggregate scored trials per scorer for an experiment run with ``trials`` trials per case.
+
+ Errored results (infra failures) and ``None`` scores (skipped scorers) are ignored.
+ """
+ case_names = {result.input["name"] for result in results}
+ scores_by_scorer: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
+ skipped_by_scorer: dict[str, set[str]] = defaultdict(set)
+ for result in results:
+ if result.error is not None:
+ continue
+ case_name = result.input["name"]
+ for scorer, score in result.scores.items():
+ if score is None:
+ skipped_by_scorer[scorer].add(case_name)
+ else:
+ scores_by_scorer[scorer][case_name].append(score)
+ return [
+ _scorer_stats(
+ name,
+ list(by_case.values()),
+ trials,
+ short_cases=sum(
+ len(by_case.get(case, [])) < trials and not (case not in by_case and case in skipped_by_scorer[name])
+ for case in case_names
+ ),
+ )
+ for name, by_case in scores_by_scorer.items()
+ ]
+
+
+def _scorer_stats(name: str, scores_by_case: list[list[float]], trials: int, *, short_cases: int) -> ScorerTrialStats:
+ total = sum(len(scores) for scores in scores_by_case)
+ mean = sum(sum(scores) for scores in scores_by_case) / total
+ margin = _clustered_margin(scores_by_case, mean, total)
+
+ complete = [scores for scores in scores_by_case if len(scores) >= trials]
+ passes = [sum(score >= 1.0 for score in scores) for scores in complete]
+ multi_trial = trials > 1 and bool(complete)
+ return ScorerTrialStats(
+ name=name,
+ cases=len(scores_by_case),
+ trials=trials,
+ mean=mean,
+ ci_low=None if margin is None else max(0.0, mean - margin),
+ ci_high=None if margin is None else min(1.0, mean + margin),
+ complete_cases=len(complete),
+ pass_all=sum(n == len(s) for n, s in zip(passes, complete)) / len(complete) if multi_trial else None,
+ pass_any=sum(n > 0 for n in passes) / len(complete) if multi_trial else None,
+ flaky_cases=sum(0 < n < len(s) for n, s in zip(passes, complete)),
+ short_cases=short_cases,
+ )
+
+
+def _clustered_margin(scores_by_case: list[list[float]], mean: float, total: int) -> float | None:
+ """Half-width of the 95% interval around the pooled ``mean``; ``None`` below two cases."""
+ cases = len(scores_by_case)
+ if cases < 2:
+ return None
+ # Cluster-robust variance of the pooled mean: trials of one case are not independent draws.
+ residuals = sum(sum(score - mean for score in scores) ** 2 for scores in scores_by_case)
+ standard_error = math.sqrt(cases / (cases - 1) * residuals) / total
+ return (_T_95[cases - 2] if cases - 1 <= len(_T_95) else 1.96) * standard_error
diff --git a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
index a4cde07e09fa..46e2b415225b 100644
--- a/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
+++ b/products/posthog_ai/eval_harness/test/test_one_shot_runner.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+from collections.abc import Sequence
from functools import partial
from pathlib import Path
from threading import Event
@@ -26,6 +27,7 @@ from products.posthog_ai.eval_harness.engines.types import (
from products.posthog_ai.eval_harness.harness.cli import parse_args
from products.posthog_ai.eval_harness.harness.context import EvalContext
from products.posthog_ai.eval_harness.harness.lifecycle import SandboxedEvalHarness
+from products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats
from products.posthog_ai.eval_harness.one_shot import _OneShotEvalRun
@@ -42,7 +44,9 @@ class _StubReporter:
async def experiment_started(self, experiment_name: str, planned_cases: int, log_dir: Path) -> None:
self.started.append((experiment_name, planned_cases))
- async def record_summary(self, experiment_name: str, summary: Any, error_count: int) -> None:
+ async def record_summary(
+ self, experiment_name: str, summary: Any, error_count: int, trial_stats: Sequence[ScorerTrialStats] = ()
+ ) -> None:
self.summaries.append((experiment_name, summary, error_count))
async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
index e18797b933ee..c613f34cfed1 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
@@ -18,6 +18,7 @@ from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalS
from products.posthog_ai.eval_harness.harness.cli import SkillDelivery
from products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResult
from products.posthog_ai.eval_harness.harness.transcript import RunTranscript
+from products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats
from products.posthog_ai.eval_harness.scorers import ExitCodeZero
from products.tasks.backend.facade.agents import CustomPromptSandboxContext
@@ -123,6 +124,79 @@ async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(
assert output.count("PASS") == 1
+ "stats, expected",
+ [
+ pytest.param(
+ ScorerTrialStats(
+ name="s",
+ cases=10,
+ trials=3,
+ mean=0.7,
+ ci_low=0.61,
+ ci_high=0.83,
+ complete_cases=9,
+ short_cases=1,
+ pass_all=0.4,
+ pass_any=0.85,
+ flaky_cases=4,
+ ),
+ " s: 72.0% (95% CI 61.0-83.0%)\n"
+ " pass^3 40.0% | pass@3 85.0% | 4/9 cases flaky | 1 cases short of 3 trials\n",
+ id="multiple_trials",
+ ),
+ pytest.param(
+ ScorerTrialStats(
+ name="s",
+ cases=10,
+ trials=1,
+ mean=0.7,
+ ci_low=0.61,
+ ci_high=0.83,
+ complete_cases=10,
+ short_cases=0,
+ pass_all=None,
+ pass_any=None,
+ flaky_cases=0,
+ ),
+ " s: 72.0% (95% CI 61.0-83.0%)\n PostHog",
+ id="single_trial",
+ ),
+ pytest.param(
+ ScorerTrialStats(
+ name="s",
+ cases=10,
+ trials=3,
+ mean=0.7,
+ ci_low=0.61,
+ ci_high=0.83,
+ complete_cases=0,
+ short_cases=10,
+ pass_all=None,
+ pass_any=None,
+ flaky_cases=0,
+ ),
+ " pass^3 n/a | pass@3 n/a | 0/0 cases flaky | 10 cases short of 3 trials\n",
+ id="no_case_completed_every_trial",
+ ),
+ ],
+)
+async def test_reporter_shows_the_engine_score_with_trial_stats(
+ stats: ScorerTrialStats, expected: str, capsys: pytest.CaptureFixture[str]
+) -> None:
+ reporter = ProgressReporter(total_suites=1)
+ await reporter.record_summary(
+ "exp",
+ EvalSummary(engine_name="Braintrust", experiment_name="exp", scores={"s": AggregateScore("s", 0.72)}),
+ trial_stats=[stats],
+ )
+ await reporter.record_posthog_evaluations_url("exp", "bd8b7f0d-7cc3-4ea3-a3a6-53be0d9e6eb4")
+ reporter.print_final_summary([], exit_code=0, fail_under=None, duration_seconds=1.0)
+
+ assert expected in capsys.readouterr().out
+
+
def test_tool_call_spans_carry_the_resolved_tool_and_its_arguments() -> None:
trends_query = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}
parsed = ParsedLog(
diff --git a/products/posthog_ai/eval_harness/test/test_trial_stats.py b/products/posthog_ai/eval_harness/test/test_trial_stats.py
new file mode 100644
index 000000000000..119adaf1ed89
--- /dev/null
+++ b/products/posthog_ai/eval_harness/test/test_trial_stats.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+from dataclasses import replace
+
+import pytest
+
+from products.posthog_ai.eval_harness.engines.types import CaseResult
+from products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats, trial_stats
+
+
+def _result(case: str, score: float | None) -> CaseResult:
+ return CaseResult(input={"name": case}, output=None, scores={"s": score})
+
+
+def _errored(case: str) -> CaseResult:
+ return CaseResult(input={"name": case}, output=None, scores={}, error="sandbox died")
+
+
+def _trials(scores_by_case: dict[str, list[float]]) -> list[CaseResult]:
+ return [_result(case, score) for case, scores in scores_by_case.items() for score in scores]
+
+
+def _round(value: float | None) -> float | None:
+ return None if value is None else round(value, 4)
+
+
+def _rounded(stats: ScorerTrialStats) -> ScorerTrialStats:
+ return replace(
+ stats,
+ mean=round(stats.mean, 4),
+ ci_low=_round(stats.ci_low),
+ ci_high=_round(stats.ci_high),
+ pass_all=_round(stats.pass_all),
+ pass_any=_round(stats.pass_any),
+ )
+
+
+EXPECTED = ScorerTrialStats(
+ name="s",
+ cases=2,
+ trials=3,
+ mean=0.8333,
+ ci_low=0.0,
+ ci_high=1.0,
+ complete_cases=2,
+ pass_all=0.5,
+ pass_any=1.0,
+ flaky_cases=1,
+ short_cases=0,
+)
+
+
+ "results, trials, expected",
+ [
+ pytest.param(
+ _trials({"stable": [1, 1, 1], "flaky": [1, 0, 1]}),
+ 3,
+ EXPECTED,
+ id="stable_and_flaky_case_over_three_trials",
+ ),
+ pytest.param(
+ [*_trials({"full": [1, 1, 1], "short": [0]}), _errored("short"), _result("short", None)],
+ 3,
+ replace(EXPECTED, mean=0.75, complete_cases=1, pass_all=1.0, pass_any=1.0, flaky_cases=0, short_cases=1),
+ id="mean_pools_trials_like_the_engine_and_pass_k_skips_short_cases",
+ ),
+ pytest.param(
+ [
+ *_trials({"full": [1, 1, 1], "other": [0, 0, 0]}),
+ *[_errored("crashed") for _ in range(3)],
+ *[_result("not_applicable", None) for _ in range(3)],
+ ],
+ 3,
+ replace(EXPECTED, mean=0.5, pass_all=0.5, pass_any=0.5, flaky_cases=0, short_cases=1),
+ id="an_all_errored_case_is_short_but_a_skipped_case_is_not",
+ ),
+ pytest.param(
+ _trials({f"case{i}": [1.0 if i < 7 else 0.0] for i in range(10)}),
+ 1,
+ replace(
+ EXPECTED,
+ cases=10,
+ trials=1,
+ mean=0.7,
+ ci_low=0.3545,
+ complete_cases=10,
+ pass_all=None,
+ pass_any=None,
+ flaky_cases=0,
+ ),
+ id="single_trial_run_has_an_interval_but_no_pass_k",
+ ),
+ pytest.param(
+ _trials({"only": [1, 0]}),
+ 2,
+ replace(EXPECTED, cases=1, trials=2, mean=0.5, ci_low=None, ci_high=None, complete_cases=1, pass_all=0.0),
+ id="single_case_has_no_interval",
+ ),
+ ],
+)
+def test_trial_stats(results: list[CaseResult], trials: int, expected: ScorerTrialStats) -> None:
+ assert [_rounded(stats) for stats in trial_stats(results, trials=trials)] == [expected]