:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(evals): summarize an offline eval run that skips a score (#106954)
Marcel Poelker6cedd9cd7c3b
diff --git a/ee/hogai/eval/base.py b/ee/hogai/eval/base.pyindex 3990dab1276c..84f12f616bc0 100644--- a/ee/hogai/eval/base.py+++ b/ee/hogai/eval/base.py@@ -10,6 +10,9 @@ from braintrust.framework import EvalData, EvalScorer, EvalTask, Input, Outputfrom posthog.models.utils import uuid7+# Imported for its side effect: braintrust's offline summary crashes on a skipped score.+from products.posthog_ai.eval_harness.engines import braintrust_patches # noqa: F401+from ee.hogai.eval.schema import DatasetInputdiff --git a/ee/hogai/test/test_eval_base.py b/ee/hogai/test/test_eval_base.pynew file mode 100644index 000000000000..54b41d8539d9--- /dev/null+++ b/ee/hogai/test/test_eval_base.py@@ -0,0 +1,41 @@+import asyncio+from typing import Any++from django.test import SimpleTestCase++from braintrust import EvalAsync, EvalCase, Score+from braintrust_core.score import Scorer++import ee.hogai.eval.base # noqa: F401 (imported for the braintrust patch it applies)+++class _SkipsOneCase(Scorer):+ def _name(self) -> str:+ return "skips"++ def _run_eval_sync(self, output: dict[str, Any] | None, expected: Any = None, **kwargs: Any) -> Score:+ if output and output.get("skip"):+ return Score(name="skips", score=None)+ return Score(name="skips", score=1.0)+++class TestOfflineEvalSummary(SimpleTestCase):+ def test_summarizes_an_offline_run_whose_scorer_skips_a_case(self) -> None:+ async def task(input: dict[str, Any]) -> dict[str, Any]:+ return input++ cases: list[EvalCase[dict[str, Any], dict[str, Any]]] = [+ EvalCase(input={"skip": False}),+ EvalCase(input={"skip": True}),+ ]+ summary = asyncio.run(+ EvalAsync(+ "offline-summary-guard",+ data=cases,+ task=task,+ scores=[_SkipsOneCase()],+ no_send_logs=True,+ )+ ).summary++ self.assertEqual(summary.scores["skips"].score, 1.0)diff --git a/products/posthog_ai/eval_harness/engines/braintrust.py b/products/posthog_ai/eval_harness/engines/braintrust.pyindex dfd6dd5986e1..efa687d7924c 100644--- a/products/posthog_ai/eval_harness/engines/braintrust.py+++ b/products/posthog_ai/eval_harness/engines/braintrust.py@@ -9,6 +9,8 @@ from typing import Any, ClassVarfrom braintrust import EvalAsync, EvalCase, EvalHooksfrom braintrust.framework import EvalResultWithSummary, Evaluator, ReporterDef+# Imported for its side effect: braintrust's offline summary crashes on a skipped score.+from . import braintrust_patches # noqa: F401from .types import AggregateScore, CaseResult, EnvVarSpec, EvalSummary, ExperimentResult, ExperimentSpec, SpanKind@@ -72,6 +74,8 @@ class BraintrustEngine:not be coroutines.- **``update=True``.** Experiment names stay runtime/model-agnostic so historylines up across runs; updating keeps that history rather than forking it.+ - **``braintrust_patches``.** Importing that module replaces braintrust's+ offline summary, which crashes on a skipped score. See its docstring."""name: ClassVar[str] = "braintrust"@@ -117,8 +121,9 @@ class BraintrustEngine:def _translate(self, result: EvalResultWithSummary) -> ExperimentResult:"""Map braintrust's ``EvalResultWithSummary`` onto the neutral model.- ``score=None`` is preserved per-case (braintrust drops it from the- aggregate); a task exception becomes ``CaseResult.error`` as a string so+ ``score=None`` is preserved per-case (the aggregate drops it, online+ through braintrust and offline through ``braintrust_patches``); a task+ exception becomes ``CaseResult.error`` as a string socallers never re-handle a live ``Exception``; ``summary.raw`` is thebraintrust summary's ``as_dict()`` so the jsonl export round-tripsbyte-for-byte through ``EvalSummary.as_json()``.diff --git a/products/posthog_ai/eval_harness/engines/braintrust_patches.py b/products/posthog_ai/eval_harness/engines/braintrust_patches.pynew file mode 100644index 000000000000..3c25e2b7d4b5--- /dev/null+++ b/products/posthog_ai/eval_harness/engines/braintrust_patches.py@@ -0,0 +1,69 @@+"""Braintrust behavior this repo replaces. Importing this module applies the replacement.++Both offline eval entry points import it: the harness engine in ``braintrust.py``+and ``ee/hogai/eval/base.py``. Patching once at import, rather than per run, keeps+concurrent suites from restoring the original under each other.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Sequence+from typing import Any++from braintrust import framework as bt_framework+from braintrust.framework import Evaluator, ExperimentSummary, ScoreSummary+++def none_safe_local_summary(evaluator: Evaluator[Any, Any], results: Sequence[Any]) -> ExperimentSummary:+ """Braintrust's offline summary, with ``score=None`` excluded from the means.++ The stock ``build_local_summary`` guards on the accumulator rather than the+ score, so it reaches ``0 + None`` and raises ``TypeError`` on the first skipped+ score. Every ``no_send_logs`` experiment takes that path, because+ ``no_send_logs`` is what leaves the braintrust experiment unset, so a private+ suite whose scorers skip a check cannot summarize without this.++ Braintrust ships the same guard from 0.4.2, and this repo pins 0.2.4 in+ ``pyproject.toml``. A bump past 0.4.2 deletes this module instead of keeping+ it, because later versions also change the ``ExperimentSummary`` shape that+ this function builds by hand.++ ``results`` is ``Sequence[Any]`` because braintrust annotates the parameter as+ ``list[EvalResultWithSummary]`` and then passes ``EvalResult`` objects, so no+ accurate shared type exists.+ """+ by_name: dict[str, tuple[float, int]] = defaultdict(lambda: (0.0, 0))+ for result in results:+ for name, score in result.scores.items():+ if score is None:+ continue+ total, count = by_name[name]+ by_name[name] = (total + score, count + 1)+ longest = max((len(name) for name in by_name), default=0)+ scores = {+ name: ScoreSummary(+ name=name,+ _longest_score_name=longest,+ score=(total / count if count else 0.0),+ improvements=0,+ regressions=0,+ )+ for name, (total, count) in by_name.items()+ }+ return ExperimentSummary(+ project_name=evaluator.project_name,+ project_id=None,+ experiment_id=None,+ experiment_name=evaluator.experiment_name or evaluator.project_name,+ project_url=None,+ experiment_url=None,+ comparison_experiment_name=None,+ scores=scores,+ metrics={},+ )+++# braintrust resolves this name as a module global inside ``EvalAsync``, so there is no per-call seam to wrap.+# The suppression is the parameter type described above: matching the declared one would misstate what arrives.+bt_framework.build_local_summary = none_safe_local_summary # ty: ignore[invalid-assignment]diff --git a/products/posthog_ai/eval_harness/test/test_engine_conformance.py b/products/posthog_ai/eval_harness/test/test_engine_conformance.pyindex 7ebcc1f3f906..fa2fb82cca5f 100644--- a/products/posthog_ai/eval_harness/test/test_engine_conformance.py+++ b/products/posthog_ai/eval_harness/test/test_engine_conformance.py@@ -1,16 +1,11 @@from __future__ import annotationsimport asyncio-from collections import defaultdict-from collections.abc import Sequencefrom typing import Anyimport pytest-import braintrust.framework as bt_frameworkfrom braintrust import Score-from braintrust.framework import EvalResult, Evaluator-from braintrust.logger import ExperimentSummary, ScoreSummaryfrom braintrust_core.score import Scorerfrom products.posthog_ai.eval_harness.engines.braintrust import BraintrustEngine@@ -21,53 +16,11 @@ from products.posthog_ai.eval_harness.engines.types import CaseHooks, CaseSpec,pytestmark = pytest.mark.parametrize("engine", ["braintrust"], indirect=True)-def _none_safe_local_summary(- evaluator: Evaluator[Any, Any], results: Sequence[EvalResult[Any, Any]]-) -> ExperimentSummary:- """A None-aware replacement for braintrust's offline ``build_local_summary``.-- The stock offline path sums ``None`` scores and crashes (a local-mode bug the- authenticated path doesn't have — the real harness always runs authenticated).- This shim excludes ``None`` from the mean, matching authenticated behavior, so- the offline fixture can exercise the None-exclusion the engine contract promises.- """- by_name: dict[str, tuple[float, int]] = defaultdict(lambda: (0.0, 0))- for result in results:- for name, score in result.scores.items():- if score is None:- continue- total, count = by_name[name]- by_name[name] = (total + score, count + 1)- longest = max((len(name) for name in by_name), default=0)- scores = {- name: ScoreSummary(- name=name,- _longest_score_name=longest,- score=(total / count if count else 0.0),- improvements=0,- regressions=0,- )- for name, (total, count) in by_name.items()- }- return ExperimentSummary(- project_name=evaluator.project_name,- project_id=None,- experiment_id=None,- experiment_name=evaluator.experiment_name or evaluator.project_name,- project_url=None,- experiment_url=None,- comparison_experiment_name=None,- scores=scores,- metrics={},- )--@pytest.fixturedef engine(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> BraintrustEngine:if request.param == "braintrust":# Keep the run fully offline: no API key means no login and no network.monkeypatch.delenv("BRAINTRUST_API_KEY", raising=False)- monkeypatch.setattr(bt_framework, "build_local_summary", _none_safe_local_summary)return BraintrustEngine()raise AssertionError(f"unknown engine fixture: {request.param}")