: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(aio): restore offline evaluation event reporting (#99431)
Radu Raicea1abc6a7dd06e
diff --git a/.agents/skills/writing-evals/SKILL.md b/.agents/skills/writing-evals/SKILL.mdindex ec92426e0894..460e046c815e 100644--- a/.agents/skills/writing-evals/SKILL.md+++ b/.agents/skills/writing-evals/SKILL.md@@ -48,7 +48,7 @@ async def eval_my_thing(ctx: EvalContext) -> None:- One suite = one Braintrust experiment. Bundle related cases into one suite; split only when the scorecard would be heterogeneous (self-skipping scorers stretch a shared scorer list across mildly different cases, but a scorecard where half the scorers skip half the cases is a sign to split).- `experiment_name` is the Braintrust history key — renaming it resets cross-run comparison. Existing sandboxed suites end in `-cli` because the MCP server serves the `cli` surface.-- `SandboxedPublicEval` sends logs to Braintrust (summary gets an experiment URL); `SandboxedPrivateEval` runs with `no_send_logs`, so the local log dir is the only record. Use private for cases whose prompts or seeds shouldn't leave the machine.+- `SandboxedPublicEval` sets `no_send_logs=False` and reports results to Braintrust and PostHog, including available input, output, and expected values. `SandboxedPrivateEval` sets `no_send_logs=True` and uploads results to neither service; local logs are still written. PostHog result uploads follow `no_send_logs` independently of `OPT_OUT_CAPTURE`, which still applies to ordinary SDK and trace clients. See [evaluation result reporting](../../../docs/internal/ai-offline-evaluation-reporting.md).## One-shot suitesdiff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.mdnew file mode 100644index 000000000000..487e59f9c311--- /dev/null+++ b/docs/internal/ai-offline-evaluation-reporting.md@@ -0,0 +1,22 @@+# Offline evaluation result reporting++The sandboxed evaluation harness in `products/posthog_ai/eval_harness/` reports scorer results as PostHog `$ai_evaluation` events.+With the Braintrust engine, each suite runs once and the harness sends the resulting scores to PostHog when uploads are enabled.+Reporting does not run the agent or scorers again.++## Capture settings++Evaluation result uploads to Braintrust and PostHog share the `no_send_logs` setting.+`SandboxedPublicEval` sets `no_send_logs=False` and uploads to both services.+`SandboxedPrivateEval` sets `no_send_logs=True` and uploads to neither service; local logs are still written.++The harness creates one dedicated result client at startup, shares it across all suites, and shuts it down after the invocation.+Each suite waits for queued PostHog uploads in worker threads so other suites can keep running.+This client permits `$ai_evaluation` reporting independently of `TEST` and `OPT_OUT_CAPTURE`, so those settings do not separate the two result destinations.+Ordinary PostHog SDK clients and trace clients retain their existing `TEST` and `OPT_OUT_CAPTURE` guards.++## Result contents and scope++Each event contains the existing experiment, case, and metric properties, including input, output, and expected values when available.+Result reporting uses the existing event schema.+The legacy SQL evaluation path in `ee/hogai/eval/offline/` has a separate reporter and is outside this behavior.diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex cef2def30286..7eeba45de8d8 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -274,4 +274,7 @@ Suite listing (`--list`) and argument errors do not create transcripts.Raw per-case agent logs land on local disk (`<case>.jsonl`, `<case>.artifacts.json`, `<case>.summary.txt`), which is usually the fastest way to see what the agent actually did.-`SandboxedPrivateEval` runs with `no_send_logs`, so its summary has no Braintrust URL; the local logs are the record.+`SandboxedPublicEval` sets `no_send_logs=False` and reports results to both Braintrust and PostHog.+`SandboxedPrivateEval` sets `no_send_logs=True` and uploads results to neither service; local logs are still written.+PostHog result uploads follow `no_send_logs` independently of `OPT_OUT_CAPTURE`, which still applies to ordinary SDK and trace clients.+See [evaluation result reporting](../../../docs/internal/ai-offline-evaluation-reporting.md) for capture settings and scope.diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex 7e9a381a3111..52dd89d6454c 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -266,17 +266,25 @@ class _BaseEvalRun:except Exception:logger.exception("Failed to append scores to local log summary for '%s'", case_name)- # Emit evaluation events and trace roots to PostHog (after scoring)- if self.posthog_client and result.results:+ evaluation_client = self.ctx.posthog_evaluation_client+ if not self.no_send_logs and evaluation_client is not None and result.results:try:emit_evaluation_events(- self.posthog_client,+ evaluation_client,self.experiment_id,self.experiment_name,result.results,namespace=self.trace_namespace,scorer_traces=self.scorer_traces,)+ await asyncio.to_thread(evaluation_client.flush)+ await self.ctx.reporter.record_posthog_evaluations_url(self.experiment_name, self.experiment_id)+ except Exception:+ logger.exception("Failed to emit evaluation events for '%s'", self.experiment_name)++ # Emit trace roots to PostHog (after scoring)+ if self.posthog_client and result.results:+ try:# Emit $ai_trace root events now that scores are availablefor eval_result in result.results:case_name = eval_result.input.get("name", "") if isinstance(eval_result.input, dict) else ""@@ -298,10 +306,9 @@ class _BaseEvalRun:scores=eval_result.scores,token_usage=meta.get("token_usage"),)- self.posthog_client.flush()- await self.ctx.reporter.record_posthog_evaluations_url(self.experiment_name, self.experiment_id)+ await asyncio.to_thread(self.posthog_client.flush)except Exception:- logger.exception("Failed to emit evaluation events for '%s'", self.experiment_name)+ logger.exception("Failed to emit trace roots for '%s'", self.experiment_name)# Hand the summary to the reporter: suites don't return their Braintrust# result up to the orchestrator, so this is the only place the final tablediff --git a/products/posthog_ai/eval_harness/harness/context.py b/products/posthog_ai/eval_harness/harness/context.pyindex 1afc521473a5..7020504ce35a 100644--- a/products/posthog_ai/eval_harness/harness/context.py+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -53,7 +53,10 @@ class EvalContext:when no selected suite requires demo data."""posthog_client: Posthog | None- """Analytics client for eval trace + evaluation event capture."""+ """Analytics client for eval traces, with the default capture guards."""++ posthog_evaluation_client: Posthog | None+ """Shared result client for suites that enable experiment uploads."""sandbox_slots: asyncio.Semaphore | None"""The one global limiter on concurrently live sandboxes, shared by everydiff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.pyindex 3ae30d9b52e0..08604a50f744 100644--- a/products/posthog_ai/eval_harness/harness/lifecycle.py+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -106,6 +106,7 @@ class SandboxedEvalHarness:self._database: EvalDatabase | None = Noneself._live_server: EvalLiveServer | None = Noneself._posthog_client: Posthog | None = None+ self._posthog_evaluation_client: Posthog | None = Noneself._demo_data: SandboxedDemoData | None = Nonedef run(self) -> int:@@ -279,6 +280,11 @@ class SandboxedEvalHarness:if self._posthog_client is not None:self._stack.callback(self._posthog_client.shutdown)+ # Each suite's no_send_logs setting controls result uploads to both services.+ self._posthog_evaluation_client = get_client("US", disabled=False)+ if self._posthog_evaluation_client is not None:+ self._stack.callback(self._posthog_evaluation_client.shutdown)+if Infra.DEMO_DATA in required:assert self._database is not Noneself._demo_data = ensure_demo_ready(@@ -389,6 +395,7 @@ class SandboxedEvalHarness:case_filter=self.options.case_filter,demo_data=self._demo_data,posthog_client=self._posthog_client,+ posthog_evaluation_client=self._posthog_evaluation_client,sandbox_slots=asyncio.Semaphore(self.options.max_sandboxes) if Infra.SANDBOX in required else None,team_setup_slots=asyncio.Semaphore(self.options.team_setup_concurrency),one_shot_slots=asyncio.Semaphore(DEFAULT_ONE_SHOT_CONCURRENCY),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.pyindex 3983b39aefb2..97b7e5c0e8e6 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,21 +1,31 @@from __future__ import annotationsimport asyncio+from functools import partialfrom pathlib import Path+from threading import Eventfrom typing import Any, ClassVarimport pytest+from unittest.mock import patch++from django.conf import settings++from posthoganalytics import Posthogfrom products.posthog_ai.eval_harness.config import BaseEvalCasefrom products.posthog_ai.eval_harness.engines.registry import resolve_enginefrom products.posthog_ai.eval_harness.engines.types import (+ CaseResult,EnvVarSpec,EvalSummary,ExperimentResult,ExperimentSpec,NullCaseHooks,)+from products.posthog_ai.eval_harness.harness.cli import parse_argsfrom products.posthog_ai.eval_harness.harness.context import EvalContext+from products.posthog_ai.eval_harness.harness.lifecycle import SandboxedEvalHarnessfrom products.posthog_ai.eval_harness.one_shot import _OneShotEvalRun@@ -24,6 +34,7 @@ class _StubReporter:self.done: list[tuple[str, str]] = []self.started: list[tuple[str, int]] = []self.summaries: list[tuple[str, Any, int]] = []+ self.posthog_urls: list[tuple[str, str]] = []async def case_done(self, experiment_name: str, case_name: str, duration_seconds: float, status: str) -> None:self.done.append((case_name, status))@@ -34,6 +45,9 @@ class _StubReporter:async def record_summary(self, experiment_name: str, summary: Any, error_count: int) -> None:self.summaries.append((experiment_name, summary, error_count))+ async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:+ self.posthog_urls.append((experiment_name, experiment_id))+class _StubEngine:name: ClassVar[str] = "stub"@@ -63,6 +77,7 @@ def _build_ctx(timeout_seconds: int = 30, one_shot_slots: int = 2, case_filter:case_filter=case_filter,demo_data=None,posthog_client=None,+ posthog_evaluation_client=None,sandbox_slots=None,team_setup_slots=asyncio.Semaphore(1),one_shot_slots=asyncio.Semaphore(one_shot_slots),@@ -156,27 +171,89 @@ def test_case_filter_narrows_eval_cases(tmp_path: Path, monkeypatch: pytest.Monkassert [case.input["name"] for case in run._build_eval_cases()] == ["c2"]-def test_run_routes_through_the_engine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:[email protected]("opt_out_capture", ["", "1"])[email protected]("no_send_logs", [False, True])+def test_run_routes_through_the_engine(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, opt_out_capture: str, no_send_logs: bool+) -> None:async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:raise AssertionError("the engine is stubbed, so the task must not run")+ async def run_suite(run: _OneShotEvalRun) -> None:+ loop = asyncio.get_running_loop()+ loop_progress_during_flush: list[bool] = []++ def blocking_flush() -> None:+ loop_progress = Event()+ loop.call_soon_threadsafe(loop_progress.set)+ loop_progress_during_flush.append(loop_progress.wait(timeout=5))++ with patch.object(Posthog, "flush", side_effect=blocking_flush):+ assert await run.run() is canned+ assert all(loop_progress_during_flush)+canned = ExperimentResult(summary=EvalSummary(engine_name="stub", experiment_name="one-shot-test", scores={}),- results=[],+ results=[+ CaseResult(+ input={"name": "c1", "prompt": "the prompt"},+ output={"last_message": "done"},+ scores={"correctness": 1.0},+ )+ ],)+ monkeypatch.setenv("OPT_OUT_CAPTURE", opt_out_capture)+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")engine = _StubEngine(canned)- ctx = _build_ctx()- run = _build_run(tmp_path, monkeypatch, ctx, task)- run.engine = engine-- returned = asyncio.run(run.run())-- assert returned is canned- assert len(engine.calls) == 1- call = engine.calls[0]- assert call.project_name == "one-shot-test"- assert [case.input["name"] for case in call.cases] == ["c1", "c2"]- assert call.metadata == {"agent_model": "claude-test"}- reporter = ctx.reporter- assert reporter.started == [("one-shot-test", 2)] # type: ignore[attr-defined]- assert reporter.summaries == [("one-shot-test", canned.summary, 0)] # type: ignore[attr-defined]+ harness = SandboxedEvalHarness(parse_args(["--agent-model", "claude-test"]))+ reporter = _StubReporter()++ with (+ patch(+ "posthoganalytics.Posthog", side_effect=partial(Posthog, sync_mode=True, enable_local_evaluation=False)+ ) as create_client,+ patch("posthoganalytics.client.batch_post") as batch_post,+ patch("products.posthog_ai.eval_harness.harness.lifecycle.atexit.register"),+ ):+ with harness._stack:+ harness._bootstrap(frozenset())+ ctx = harness._build_context(frozenset(), reporter) # type: ignore[arg-type]+ runs = [_build_run(tmp_path, monkeypatch, ctx, task) for _ in range(2)]+ for run in runs:+ run.engine = engine+ run.no_send_logs = no_send_logs+ run.is_public = not no_send_logs+ run.agent_trace_id_lookup["c1"] = "trace-1"+ run.case_trace_meta["c1"] = {"prompt": "the prompt", "duration": 1.0, "first_timestamp": ""}+ asyncio.run(run_suite(run))+ assert settings.TEST+ assert ctx.posthog_client is not None+ assert ctx.posthog_client.disabled+ ctx.posthog_client.capture(event="ordinary_test_event", distinct_id="test")++ assert create_client.call_count == 2+ assert ctx.posthog_evaluation_client is not None+ assert ctx.posthog_evaluation_client.capture(event="$ai_evaluation", distinct_id="after-shutdown") is None++ if no_send_logs:+ batch_post.assert_not_called()+ assert reporter.posthog_urls == []+ else:+ assert batch_post.call_count == 2+ for run, upload_call in zip(runs, batch_post.call_args_list):+ event = upload_call.kwargs["batch"][0]+ assert event["event"] == "$ai_evaluation"+ assert event["properties"]["$ai_metric_name"] == "correctness"+ assert event["properties"]["$ai_score"] == 1.0+ assert event["properties"]["$ai_experiment_id"] == run.experiment_id+ assert reporter.posthog_urls == [("one-shot-test", run.experiment_id) for run in runs]++ assert len(engine.calls) == 2+ for experiment in engine.calls:+ assert experiment.project_name == "one-shot-test"+ assert [case.input["name"] for case in experiment.cases] == ["c1", "c2"]+ assert experiment.metadata == {"agent_model": "claude-test"}+ assert experiment.no_send_logs == no_send_logs+ assert reporter.started == [("one-shot-test", 2)] * 2+ assert reporter.summaries == [("one-shot-test", canned.summary, 0)] * 2