: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): preserve logs and trace links for each trial (#116887)
Daniel Parkerc1e719d8d63b
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.mdindex 118cbe5e1846..fd5fef805aab 100644--- a/docs/internal/ai-offline-evaluation-reporting.md+++ b/docs/internal/ai-offline-evaluation-reporting.md@@ -21,6 +21,11 @@ Ordinary PostHog SDK clients and trace clients retain their existing `TEST` andEach event contains the existing experiment, case, and metric properties, including input, output, and expected values when available.Each event also carries the run's configuration: `agent_model`, `trials`, `git_sha`, `git_dirty`, and for sandboxed runs `agent_runtime`, `skill_delivery`, and `reasoning_effort`.+Each trial has a unique ID in engine metadata. Local logs and summaries use that ID, so repeated trials retain separate output and scores.+The harness shortens long case names in filenames to stay within 255 bytes. It keeps the complete trial ID and file extension.+Scorer traces and agent trace roots use the same ID to match each result to its own execution.+Case names stay the same across trials.+## Postgres experiment ingestionThe project API accepts offline experiment results behind the `ai-observability-offline-evaluations` feature flag.diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex 7b3bb2684b1e..89c60d354bb8 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -290,7 +290,10 @@ The final terminal line is the unlabeled absolute path, with no output after it,The transcript itself ends with the same path, and `logs/harness/latest.log` points to the newest transcript.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.+Each trial writes separate local files: `<case>.trial-<id>.jsonl`, `<case>.trial-<id>.artifacts.json`, and `<case>.trial-<id>.summary.txt`.+The harness shortens long case names in filenames to stay within 255 bytes. It keeps the complete trial ID and file extension.+The summary includes the trial ID, the agent trace ID when available, and the scores for that trial.+Case names and `--eval` filters stay the same.`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.diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex e6d13b784eb0..27eba006e9dd 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -180,6 +180,7 @@ class _BaseEvalRun:self.agent_trace_id_lookup: dict[str, str] = {}# Per-case metadata for emitting $ai_trace root events after scoring.self.case_trace_meta: dict[str, dict[str, Any]] = {}+ self._trial_counts: dict[str, int] = {}# Local disk sink for raw agent logs — lets an agent iterating on the# harness read back what happened without round-tripping through Braintrust.@@ -247,6 +248,9 @@ class _BaseEvalRun:async def _task(self, input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any] | None:case_started = time.monotonic()case_name = input.get("name", "?")+ hooks.metadata["trial_id"] = str(uuid.uuid4())+ hooks.metadata["trial_index"] = self._trial_counts.get(case_name, 0)+ self._trial_counts[case_name] = hooks.metadata["trial_index"] + 1status: Literal["ok", "timeout", "error"] = "ok"try:return await self._execute_case(input, hooks)@@ -282,7 +286,12 @@ class _BaseEvalRun:if not case_name:continuetry:- append_case_scores(self.run_log_dir, case_name, dict(eval_result.scores or {}))+ append_case_scores(+ self.run_log_dir,+ case_name,+ dict(eval_result.scores or {}),+ trial_id=eval_result.metadata.get("trial_id"),+ )except Exception:logger.exception("Failed to append scores to local log summary for '%s'", case_name)@@ -309,8 +318,9 @@ class _BaseEvalRun:# 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 ""- trace_id = self.agent_trace_id_lookup.get(case_name)- meta = self.case_trace_meta.get(case_name)+ trial_id = str(eval_result.metadata.get("trial_id") or case_name)+ trace_id = self.agent_trace_id_lookup.get(trial_id)+ meta = self.case_trace_meta.get(trial_id)if trace_id and meta:emit_trace_root(self.posthog_client,@@ -352,8 +362,7 @@ class _BaseEvalRun:"""Write one JSONL row per case x trial to the run's local log dir.The reporter's ``eval_results.jsonl`` carries only per-experiment- aggregates, and ``eval_harness/logs/`` case logs overwrite each other- across trials — neither supports a paired case-level analysis. The data+ aggregates. The per-case records support paired case-level analysis. The dataalready lives in ``ExperimentResult.results``; persist it here.``trial_index`` groups the trials of one case: scores from the sametrial index are comparable across runs of the same case set, but a@@ -372,7 +381,8 @@ class _BaseEvalRun:"run_id": self.experiment_id,"experiment": self.experiment_name,"case_name": case_name,- "trial_index": trial_index,+ "trial_index": case_result.metadata.get("trial_index", trial_index),+ "trial_id": case_result.metadata.get("trial_id"),"scores": case_result.scores,"error": case_result.error,}@@ -624,9 +634,10 @@ class _SandboxedEvalRun(_BaseEvalRun):"""Build Braintrust spans, write local logs, emit trace events, and shapethe scorer input dict — all off the sandbox slot."""# Store trace_id in metadata so evaluation events can link to the trace+ trial_id = hooks.metadata.get("trial_id", eval_case.name)if result.trace_id:hooks.metadata["trace_id"] = result.trace_id- self.agent_trace_id_lookup[eval_case.name] = result.trace_id+ self.agent_trace_id_lookup[trial_id] = result.trace_idhooks.metadata["artifacts"] = result.artifacts.model_dump()# Parse the log once, use for both Braintrust spans and PostHog trace capture@@ -651,7 +662,7 @@ class _SandboxedEvalRun(_BaseEvalRun):run_metadata=self._experiment_metadata(),)# Store metadata for emit_trace_root (called after scoring)- self.case_trace_meta[eval_case.name] = {+ self.case_trace_meta[trial_id] = {"prompt": eval_case.prompt,"duration": result.artifacts.duration_seconds,"first_timestamp": parsed.first_timestamp,@@ -671,7 +682,9 @@ class _SandboxedEvalRun(_BaseEvalRun):prompt=eval_case.prompt,duration=result.artifacts.duration_seconds,last_message=last_message,- token_usage=self.case_trace_meta.get(eval_case.name, {}).get("token_usage"),+ token_usage=self.case_trace_meta.get(trial_id, {}).get("token_usage"),+ trial_id=hooks.metadata.get("trial_id"),+ trace_id=result.trace_id,)except Exception:logger.exception("Failed to write local eval logs for '%s'", eval_case.name)diff --git a/products/posthog_ai/eval_harness/log_sink.py b/products/posthog_ai/eval_harness/log_sink.pyindex 57f63306704c..7dbd043eb0cc 100644--- a/products/posthog_ai/eval_harness/log_sink.py+++ b/products/posthog_ai/eval_harness/log_sink.py@@ -18,6 +18,12 @@ def _slugify(name: str) -> str:return slug or "unnamed"+def _case_log_slug(case_name: str, trial_id: str | None) -> str:+ trial_suffix = f".trial-{_slugify(trial_id)}" if trial_id else ""+ case_name_limit = 255 - len(trial_suffix) - len(".artifacts.json")+ return _slugify(case_name)[:case_name_limit] + trial_suffix++@dataclass(frozen=True)class CaseLogPaths:case_dir: Path@@ -111,8 +117,11 @@ def write_case_logs(duration: float,last_message: str,token_usage: dict[str, Any] | None = None,+ *,+ trial_id: str | None = None,+ trace_id: str | None = None,) -> CaseLogPaths:- slug = _slugify(case_name)+ slug = _case_log_slug(case_name, trial_id)paths = CaseLogPaths(case_dir=case_dir,raw_log=case_dir / f"{slug}.jsonl",@@ -122,12 +131,17 @@ def write_case_logs(paths.raw_log.write_text(raw_log or "")paths.artifacts.write_text(json.dumps(artifacts, indent=2, default=str))- paths.summary.write_text(_format_summary(case_name, prompt, duration, last_message, token_usage))+ summary = _format_summary(case_name, prompt, duration, last_message, token_usage)+ if trial_id:+ summary = f"trial_id: {trial_id}\n" + summary+ if trace_id:+ summary = f"trace_id: {trace_id}\n" + summary+ paths.summary.write_text(summary)return paths-def append_case_scores(case_dir: Path, case_name: str, scores: dict[str, Any]) -> None:- slug = _slugify(case_name)+def append_case_scores(case_dir: Path, case_name: str, scores: dict[str, Any], *, trial_id: str | None = None) -> None:+ slug = _case_log_slug(case_name, trial_id)summary_path = case_dir / f"{slug}.summary.txt"if not summary_path.exists():returndiff --git a/products/posthog_ai/eval_harness/one_shot.py b/products/posthog_ai/eval_harness/one_shot.pyindex 78a43bd161c3..8f3fd48fe628 100644--- a/products/posthog_ai/eval_harness/one_shot.py+++ b/products/posthog_ai/eval_harness/one_shot.py@@ -74,10 +74,14 @@ class _OneShotEvalRun(_BaseEvalRun):timeout=self.ctx.per_case_timeout_seconds,)output.setdefault("prompt", case.prompt)- await self._write_local_logs(case, output, duration=time.monotonic() - started)+ await self._write_local_logs(+ case, output, duration=time.monotonic() - started, trial_id=hooks.metadata.get("trial_id")+ )return output- async def _write_local_logs(self, case: BaseEvalCase, output: dict[str, Any], duration: float) -> None:+ async def _write_local_logs(+ self, case: BaseEvalCase, output: dict[str, Any], duration: float, trial_id: str | None = None+ ) -> None:try:write_case_logs(case_dir=self.run_log_dir,@@ -87,6 +91,7 @@ class _OneShotEvalRun(_BaseEvalRun):prompt=case.prompt,duration=duration,last_message=str(output.get("last_message", "")),+ trial_id=trial_id,)except Exception:logger.exception("Failed to write local eval logs for '%s'", case.name)diff --git a/products/posthog_ai/eval_harness/scorers/tracing.py b/products/posthog_ai/eval_harness/scorers/tracing.pyindex 3d150380a010..4c922a55a29f 100644--- a/products/posthog_ai/eval_harness/scorers/tracing.py+++ b/products/posthog_ai/eval_harness/scorers/tracing.py@@ -178,7 +178,7 @@ class TracedScorer(AsyncOnlyScorerMixin, Scorer):self._inner.anthropic_client = original_anthropic # ty: ignore[invalid-assignment]async def _run_eval_async(self, output, expected=None, **kwargs):- case_name = _case_name_from_kwargs(kwargs)+ case_name = kwargs.get("metadata", {}).get("trial_id") or _case_name_from_kwargs(kwargs)with self._invocation_context(case_name) as is_llm_scorer:# eval_async, not _run_eval_async: sync-only inner scorers rely on# the base class's async-to-sync delegation.@@ -231,7 +231,7 @@ def wrap_scorers(Returns (wrapped_scorers, scorer_traces dict).- ``agent_trace_id_lookup`` maps case_name → agent trace_id. It's populated+ ``agent_trace_id_lookup`` maps trial_id → agent trace_id. It's populatedby the ``task()`` function and read by deterministic scorers to attachtheir spans to the agent trace. ``trace_namespace`` prefixes the experimentname in trace metadata so eval kinds stay distinguishable in PostHog.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 46e2b415225b..12601bf59f24 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,5 +1,6 @@from __future__ import annotations+import jsonimport asynciofrom collections.abc import Sequencefrom functools import partial@@ -94,11 +95,13 @@ def _build_ctx(timeout_seconds: int = 30, one_shot_slots: int = 2, case_filter:)-def _build_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ctx: EvalContext, task_fn: Any) -> _OneShotEvalRun:+def _build_run(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ctx: EvalContext, task_fn: Any, case_name: str = "c1"+) -> _OneShotEvalRun:monkeypatch.setattr("products.posthog_ai.eval_harness.base.build_case_dir", lambda *_: tmp_path)return _OneShotEvalRun(experiment_name="one-shot-test",- cases=[BaseEvalCase(name="c1", prompt="the prompt"), BaseEvalCase(name="c2", prompt="other")],+ cases=[BaseEvalCase(name=case_name, prompt="the prompt"), BaseEvalCase(name="c2", prompt="other")],scorers=[],ctx=ctx,is_public=False,@@ -272,3 +275,60 @@ def test_run_routes_through_the_engine(assert experiment.no_send_logs == no_send_logsassert reporter.started == [("one-shot-test", 2)] * 2assert reporter.summaries == [("one-shot-test", canned.summary, 0)] * 2++[email protected]("case_name", ["c1", "c1" * 110, "c1" * 200])+def test_concurrent_trials_keep_their_own_logs_and_scores(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, case_name: str+) -> None:+ monkeypatch.delenv("BRAINTRUST_API_KEY", raising=False)+ monkeypatch.setenv("EXPORT_EVAL_RESULTS", "1")+ monkeypatch.chdir(tmp_path)+ started = 0+ all_started = asyncio.Event()+ finished = [asyncio.Event() for _ in range(3)]+ completion_order: list[int] = []++ async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:+ nonlocal started+ index = started+ value = index / 2+ started += 1+ if started == 3:+ all_started.set()+ await all_started.wait()+ if index < 2:+ await finished[index + 1].wait()+ completion_order.append(index)+ finished[index].set()+ return {"answer": value, "last_message": str(value)}++ def score(output: dict[str, Any], **kwargs: Any) -> float:+ return output["answer"]++ ctx = _build_ctx(one_shot_slots=3, case_filter=case_name)+ ctx.trials = 3+ run = _build_run(tmp_path, monkeypatch, ctx, task, case_name=case_name)+ run.active_scorers = [score]+ result = asyncio.run(run.run())++ assert len(result.results) == 3+ assert completion_order == [2, 1, 0]+ assert {row.metadata["trial_index"] for row in result.results} == {0, 1, 2}+ assert len(list(tmp_path.glob("*.summary.txt"))) == 3+ assert len({row.metadata["trial_id"] for row in result.results}) == 3+ assert {row.input["name"] for row in result.results} == {case_name}+ exports = [json.loads(line) for line in (tmp_path / "case_results.jsonl").read_text().splitlines()]+ for row in result.results:+ trial_id = row.metadata["trial_id"]+ summary_path = next(tmp_path.glob(f"*.trial-{trial_id}.summary.txt"))+ prefix = summary_path.with_name(summary_path.name.removesuffix(".summary.txt"))+ assert json.loads(prefix.with_name(prefix.name + ".jsonl").read_text()) == row.output+ assert prefix.with_name(prefix.name + ".artifacts.json").exists()+ summary = summary_path.read_text()+ assert f"case: {case_name}\n" in summary+ assert f"trial_id: {trial_id}" in summary+ assert json.loads(summary.split("=== scores ===\n")[1]) == row.scores+ exported = next(item for item in exports if item["trial_id"] == trial_id)+ assert exported["trial_index"] == row.metadata["trial_index"] == row.output["answer"] * 2+ assert exported["scores"] == row.scoresdiff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.pyindex 7e9d160489a3..6efb4d20cfc9 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@@ -25,7 +25,13 @@ from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitEfrom products.posthog_ai.eval_harness import basefrom products.posthog_ai.eval_harness.acp_log import GenerationDescriptor, ParsedLogfrom products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCase-from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary, NullCaseHooks+from products.posthog_ai.eval_harness.engines.types import (+ AggregateScore,+ CaseResult,+ EvalSummary,+ ExperimentResult,+ NullCaseHooks,+)from products.posthog_ai.eval_harness.harness.cli import SkillDeliveryfrom products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResultfrom products.posthog_ai.eval_harness.harness.transcript import RunTranscript@@ -578,3 +584,59 @@ async def test_case_setup_retries_use_fresh_data_and_report_one_outcome(assert reporter.has_case_errors() is (not recovers)assert ctx.sandbox_slots._value == ctx.team_setup_slots._value == 1assert not broken_workers+++async def test_sandboxed_trials_keep_separate_logs_and_trace_roots(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.delenv("EXPORT_EVAL_RESULTS", raising=False)+ monkeypatch.setattr(base, "build_case_dir", lambda *_: tmp_path)+ ctx = MagicMock(posthog_client=None, reporter=ProgressReporter(total_suites=1))+ ctx.posthog_evaluation_client = None+ ctx.trials = 3+ run = base._SandboxedEvalRun("trials", [], [], ctx, is_public=False, no_send_logs=True)+ run.posthog_client = MagicMock()+ results = []+ for index in range(3):+ trial_id = f"trial-{index}"+ hooks = NullCaseHooks()+ hooks.metadata["trial_id"] = trial_id+ raw_log = json.dumps(+ {+ "notification": {+ "method": "session/update",+ "params": {+ "update": {+ "sessionUpdate": "agent_message_chunk",+ "content": {"type": "text", "text": str(index)},+ }+ },+ }+ }+ )+ output = await run._post_process(+ SandboxedEvalCase(name="same-case", prompt="Run the task"),+ hooks,+ base.EvalCaseResult(artifacts=AgentArtifacts(exit_code=0), raw_log=raw_log, trace_id=f"trace-{index}"),+ {},+ )+ results.append(+ CaseResult(input={"name": "same-case"}, output=output, scores={"score": index / 2}, metadata=hooks.metadata)+ )+ await run._finalize(+ ExperimentResult(+ summary=EvalSummary(engine_name="stub", experiment_name="trials", scores={}),+ results=list(reversed(results)),+ )+ )+ for index in range(3):+ summary = (tmp_path / f"same-case.trial-trial-{index}.summary.txt").read_text()+ assert f"trace_id: trace-{index}" in summary+ assert json.loads(summary.split("=== scores ===\n")[1]) == {"score": index / 2}+ roots = [+ call.kwargs["properties"]+ for call in run.posthog_client.capture.call_args_list+ if call.kwargs.get("event") == "$ai_trace"+ ]+ assert [root["$ai_trace_id"] for root in roots] == ["trace-2", "trace-1", "trace-0"]diff --git a/products/posthog_ai/eval_harness/test/test_trace_events.py b/products/posthog_ai/eval_harness/test/test_trace_events.pyindex 2879d0c5a499..ddff25fa334e 100644--- a/products/posthog_ai/eval_harness/test/test_trace_events.py+++ b/products/posthog_ai/eval_harness/test/test_trace_events.py@@ -1,5 +1,6 @@from __future__ import annotations+import asynciofrom collections.abc import Callablefrom typing import Any, cast@@ -173,3 +174,54 @@ def test_every_event_carries_the_run_metadata(def test_the_two_run_kinds_label_themselves_differently() -> None:assert _SandboxedEvalRun.trace_namespace != _OneShotEvalRun.trace_namespace+++def test_repeated_case_scores_link_to_their_own_trial_traces() -> None:+ class _TrialScorer(Scorer):+ def _name(self) -> str:+ return "stub"++ def _run_eval_sync(self, output: Any, expected: Any = None, **kwargs: Any) -> Score:+ return Score(name="stub", score=1.0)++ client = _CapturingClient()+ scorer_traces: dict[tuple[str, str], str] = {}+ scorer = TracedScorer(+ _TrialScorer(),+ cast(TracedClients, None),+ {"experiment_id": "exp-1", "experiment_name": "ns/my-suite", "run_metadata": RUN_METADATA},+ scorer_traces,+ posthog_client=cast(Posthog, client),+ agent_trace_id_lookup={"trial-1": "agent-1", "trial-2": "agent-2"},+ )+ results = []+ for index in (1, 2):+ trial_id = f"trial-{index}"+ metadata = {"trial_id": trial_id, "trace_id": f"agent-{index}"}+ asyncio.run(scorer.eval_async({}, input={"name": "same-case"}, metadata=metadata))+ scorer_traces[(trial_id, "judge")] = f"judge-{index}"+ results.append(+ CaseResult(+ input={"name": "same-case"},+ output={},+ scores={"stub": 1.0, "judge": 0.5},+ metadata=metadata,+ )+ )+ emit_evaluation_events(+ cast(Posthog, client),+ "exp-1",+ "my-suite",+ list(reversed(results)),+ namespace="ns",+ run_metadata=RUN_METADATA,+ scorer_traces=scorer_traces,+ )+ assert [call["properties"]["$ai_trace_id"] for call in client.calls] == [+ "agent-1",+ "agent-2",+ "agent-2",+ "judge-2",+ "agent-1",+ "judge-1",+ ]diff --git a/products/posthog_ai/eval_harness/trace_events.py b/products/posthog_ai/eval_harness/trace_events.pyindex cda59292d878..a586afca503b 100644--- a/products/posthog_ai/eval_harness/trace_events.py+++ b/products/posthog_ai/eval_harness/trace_events.py@@ -302,7 +302,7 @@ def emit_evaluation_events() -> None:"""Emit ``$ai_evaluation`` events for each scorer result in each eval case.- ``scorer_traces`` maps ``(case_name, scorer_name)`` to the trace_id of+ ``scorer_traces`` maps ``(trial_id, scorer_name)`` to the trace_id ofthe scorer's LLM call. If available, ``$ai_trace_id`` on the eventpoints to the scorer trace (for inspecting the scorer's reasoning)."""@@ -311,6 +311,7 @@ def emit_evaluation_events(for result in eval_results:case_name = result.input.get("name", "unknown") if isinstance(result.input, dict) else "unknown"metadata = result.metadata or {}+ trial_id = str(metadata.get("trial_id") or case_name)agent_trace_id = metadata.get("trace_id")item_id = str(uuid.uuid4())@@ -322,7 +323,7 @@ def emit_evaluation_events(for scorer_name, score_value in (result.scores or {}).items():# Prefer scorer trace_id (links to scorer's LLM reasoning);# fall back to agent trace_id- scorer_trace_id = scorer_traces.get((case_name, scorer_name)) if scorer_traces else None+ scorer_trace_id = scorer_traces.get((trial_id, scorer_name)) if scorer_traces else Nonetrace_id = scorer_trace_id or agent_trace_idproperties: dict[str, Any] = {