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.

fix(evals): let a sandboxed eval run locally, and say so when it cannot (#84068)

Georgiy Tarasovfb8f38d0d8ae
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index eebf82de608c..4a6a84e0d163 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -15,7 +15,7 @@ from .engines.base import EvalEngine
from .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKind
from .harness.kernel_sandboxes import reclaim_kernels
from .log_sink import append_case_scores, build_case_dir, write_case_logs
-from .runner import EvalCaseResult, run_eval_case
+from .runner import AgentNeverRanError, EvalCaseResult, agent_never_ran, run_eval_case
from .scorers import ExitCodeZero, wrap_scorers
from .trace_events import emit_evaluation_events, emit_trace_events, emit_trace_root
@@ -454,6 +454,12 @@ class _SandboxedEvalRun(_BaseEvalRun):
except Exception:
logger.exception("Failed to write local eval logs for '%s'", eval_case.name)
+ # After the logs are on disk, so a failed run is still there to read.
+ if agent_never_ran(result.artifacts):
+ raise AgentNeverRanError(
+ f"Eval case '{eval_case.name}' failed before doing any work: {result.artifacts.stderr}"
+ )
+
return result.artifacts.model_dump() | {
"last_message": last_message,
"messages": messages,
diff --git a/products/posthog_ai/eval_harness/config.py b/products/posthog_ai/eval_harness/config.py
index fb105706015d..781382266ab0 100644
--- a/products/posthog_ai/eval_harness/config.py
+++ b/products/posthog_ai/eval_harness/config.py
@@ -92,6 +92,10 @@ class AgentArtifacts(BaseModel):
lint_output: str = ""
"""Lint output extracted from agent tool calls."""
+ tool_call_count: int = 0
+ """Tool calls the agent made. Zero alongside a non-zero ``exit_code`` means the run failed before
+ it did any work, which the harness treats as an infrastructure error rather than a score."""
+
duration_seconds: float = 0.0
"""Wall-clock time for the agent run in seconds."""
diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.py
index ba5d052973e7..87f453c71a12 100644
--- a/products/posthog_ai/eval_harness/harness/cli.py
+++ b/products/posthog_ai/eval_harness/harness/cli.py
@@ -7,10 +7,12 @@ from typing import cast, get_args
from .providers import DockerProviderStrategy, ModalProviderStrategy, SandboxProvider
-# Bare model ids, no "anthropic/"/"openai/" prefix: the LLM gateway checks the model
-# against a bare-id allowlist with startswith, so the prefixed form is rejected with a
-# 403 and the agent finishes without doing anything — while still scoring exit_code_zero=1.
-DEFAULT_AGENT_MODEL = "claude-opus-4-8"
+# Bare model ids, no "anthropic/"/"openai/" prefix: the LLM gateway checks the model against a
+# bare-id allowlist with startswith, so the prefixed form is rejected with a 403 and the agent
+# finishes without doing anything. `start_llm_gateway` declares this exact id free-tier on the
+# harness's own gateway, and a run that dies at the gate anyway now fails as an error rather than
+# scoring zero on every outcome scorer.
+DEFAULT_AGENT_MODEL = "claude-opus-5"
DEFAULT_CODEX_AGENT_MODEL = "gpt-5.5"
# Literal mirror of products.tasks' RuntimeAdapter values: this module must stay
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index 12aa951c12a2..f19d4c9ac665 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -195,7 +195,7 @@ class SandboxedEvalHarness:
if Infra.LLM_GATEWAY in required:
assert self._live_server is not None
- self._stack.callback(start_llm_gateway(self._live_server.url))
+ self._stack.callback(start_llm_gateway(self._live_server.url, self.options.agent_model))
if Infra.MCP_SERVER in required:
assert self._live_server is not None
self._stack.callback(start_mcp_server(self._live_server.url))
diff --git a/products/posthog_ai/eval_harness/harness/services.py b/products/posthog_ai/eval_harness/harness/services.py
index bb740a1f9c9d..d01f81c47f53 100644
--- a/products/posthog_ai/eval_harness/harness/services.py
+++ b/products/posthog_ai/eval_harness/harness/services.py
@@ -22,11 +22,16 @@ logger = logging.getLogger(__name__)
LONG_LIVED_SUBPROCESSES = LongLivedSubprocessManager()
-def start_llm_gateway(live_server_url: str) -> Callable[[], None]:
+def start_llm_gateway(live_server_url: str, agent_model: str) -> Callable[[], None]:
"""Start the LLM gateway as a subprocess.
Mirrors ``bin/start-llm-gateway``: runs uvicorn on a non-default port.
The sandbox's agent-server uses this to proxy LLM calls to Anthropic.
+
+ ``agent_model`` is declared free-tier on this gateway, because the gate it would otherwise hit
+ cannot mean anything here: every case runs as a freshly minted team that has never been billed,
+ so ``check_free_tier_model_access`` sees ``code_usage_billed=False`` and rejects the run's model
+ with a 403 before the agent sends its first message.
"""
gateway_dir = Path(settings.BASE_DIR) / "services" / "llm-gateway"
venv_dir = gateway_dir / ".venv"
@@ -60,6 +65,9 @@ def start_llm_gateway(live_server_url: str) -> Callable[[], None]:
"LLM_GATEWAY_DATABASE_URL": test_db_url,
"LLM_GATEWAY_DEBUG": "true",
"LLM_GATEWAY_POSTHOG_HOST": live_server_url,
+ # Only the model this run uses, so the gate still rejects a typo rather than waving through
+ # anything the agent-server happens to ask for.
+ "LLM_GATEWAY_POSTHOG_CODE_FREE_TIER_MODELS": json.dumps([agent_model]),
}
logger.info("Starting LLM gateway on port %d", LLM_GATEWAY_PORT)
diff --git a/products/posthog_ai/eval_harness/runner.py b/products/posthog_ai/eval_harness/runner.py
index 8b4658e7b32d..0b646d693b92 100644
--- a/products/posthog_ai/eval_harness/runner.py
+++ b/products/posthog_ai/eval_harness/runner.py
@@ -36,10 +36,34 @@ WORKFLOW_COMPLETION_GRACE_SECONDS = 60
WORKFLOW_CANCELLATION_GRACE_SECONDS = 30
+class AgentNeverRanError(RuntimeError):
+ """The agent failed before it did any work, so the case has no outcome to score.
+
+ Raised so the engine records the case as an error and drops it from the aggregates. Scoring it
+ instead would put a zero on every outcome scorer while ``exit_code_zero`` stayed at one, which
+ reads as a model regression rather than the infrastructure failure it is.
+ """
+
+
class WorkflowCleanupError(RuntimeError):
pass
+def agent_never_ran(artifacts: AgentArtifacts) -> bool:
+ """Did the run fail before the agent did anything at all?
+
+ An agent that errored after making tool calls has a partial outcome worth scoring. One that
+ errored with no tool call behind it produced nothing, so its zeros describe the infrastructure
+ rather than the model.
+
+ Keyed off ``exit_code`` rather than ``stderr`` because both terminal failure channels set a
+ non-zero exit code, but only a ``session/update`` error also fills ``stderr``. A terminal
+ ``_posthog/error`` (the channel a provider 403 lands on) leaves ``stderr`` empty, so a
+ ``stderr`` check would score it instead of excluding it.
+ """
+ return artifacts.exit_code != 0 and artifacts.tool_call_count == 0
+
+
async def _wait_for_workflow_terminal(handle: WorkflowHandle, timeout_seconds: int) -> bool:
try:
await asyncio.wait_for(handle.result(), timeout=timeout_seconds)
@@ -159,6 +183,7 @@ async def run_eval_case(
def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_finished: bool) -> AgentArtifacts:
"""Extract scoring artifacts from JSONL agent logs."""
tool_outputs: list[dict] = []
+ agent_errors: list[str] = []
has_error = False
for line in log_content.strip().split("\n"):
@@ -189,6 +214,12 @@ def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_f
session_update = update.get("sessionUpdate")
if session_update in {"tool_call", "tool_call_update"}:
tool_outputs.append(update)
+ # The agent-server reports its own failures here, and every `errorType` it emits means the
+ # run failed rather than the model answering badly. Without this the case looks clean:
+ # the workflow still finishes, so `exit_code` stays 0 and only the outcome scorers move.
+ if session_update == "error":
+ has_error = True
+ agent_errors.append(str(update.get("message") or update.get("errorType") or "agent error"))
# Extract git diff, file changes, test results from tool outputs
git_diff = ""
@@ -240,12 +271,13 @@ def _parse_artifacts_from_log(log_content: str, duration_seconds: float, agent_f
return AgentArtifacts(
exit_code=0 if agent_finished and not has_error else 1,
stdout=agent_output[:10000],
- stderr="",
+ stderr="\n".join(agent_errors)[:5000],
git_diff=git_diff,
files_changed=files_changed,
test_exit_code=test_exit_code,
test_output=test_output[:5000],
lint_exit_code=lint_exit_code,
lint_output=lint_output[:5000],
+ tool_call_count=len(tool_outputs),
duration_seconds=duration_seconds,
)
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
index 6b22b81bbdb8..23199c52d321 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
@@ -14,7 +14,7 @@ import requests
from parameterized import parameterized
from products.posthog_ai.eval_harness import runner
-from products.posthog_ai.eval_harness.config import SandboxedEvalCase
+from products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCase
from products.posthog_ai.eval_harness.harness.cli import parse_args
from products.posthog_ai.eval_harness.harness.live_server import EvalLiveServer
from products.posthog_ai.eval_harness.harness.providers import ModalProviderStrategy, SandboxProviderStrategy
@@ -263,3 +263,43 @@ def test_modal_cleanup_case_terminates_only_the_task_sandboxes(monkeypatch: pyte
sandbox_list.assert_called_once_with(app_id="app-id", tags={"task_id": "task-id"})
sandbox.terminate.assert_called_once_with()
+
+
+class TestAgentRunFailureDetection:
+ # An agent-server failure reaches the log as a session error, and the workflow still finishes
+ # cleanly afterwards. Miss it and a run where no agent ever spoke reports exit_code_zero=1 with
+ # zeros on every outcome scorer, which reads as a model regression.
+ def test_a_session_error_makes_the_run_a_failure(self) -> None:
+ log = "\n".join(
+ [
+ '{"notification": {"method": "session/update", "params": {"update": '
+ '{"sessionUpdate": "error", "errorType": "agent_error", "message": "403 model_gate"}}}}',
+ ]
+ )
+ artifacts = runner._parse_artifacts_from_log(log, duration_seconds=1.0, agent_finished=True)
+ assert artifacts.exit_code == 1
+ assert "403 model_gate" in artifacts.stderr
+
+ # A provider 403 lands on the terminal `_posthog/error` channel, which sets the non-zero exit
+ # code but leaves `stderr` empty. Reading `stderr` to spot the infra failure would score this
+ # run at zero on every outcome scorer instead of dropping it from the aggregates.
+ def test_a_terminal_posthog_error_with_no_tool_call_is_infrastructure(self) -> None:
+ log = '{"notification": {"method": "_posthog/error", "params": {"message": "403 model_gate"}}}'
+ artifacts = runner._parse_artifacts_from_log(log, duration_seconds=1.0, agent_finished=True)
+ assert artifacts.exit_code == 1
+ assert artifacts.tool_call_count == 0
+ assert runner.agent_never_ran(artifacts) is True
+
+ @parameterized.expand(
+ [
+ ("no work behind the error", "403 model_gate", 0, True),
+ ("errored after doing work", "stream terminated", 3, False),
+ ("clean run", "", 2, False),
+ ("clean run with no tool calls", "", 0, False),
+ ]
+ )
+ def test_only_a_run_that_did_nothing_counts_as_infrastructure(
+ self, _name: str, stderr: str, tool_call_count: int, expected: bool
+ ) -> None:
+ artifacts = AgentArtifacts(exit_code=1 if stderr else 0, stderr=stderr, tool_call_count=tool_call_count)
+ assert runner.agent_never_ran(artifacts) is expected
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
index 04a899abfbbd..2f55c184aa25 100755
--- a/products/posthog_ai/scripts/build_skills.py
+++ b/products/posthog_ai/scripts/build_skills.py
@@ -814,6 +814,11 @@ def _setup_django() -> None:
— it only needs the Django ORM metadata and model imports to work.
"""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
+ # A build must not depend on reaching the flags endpoint. Rendering a HogQL example walks
+ # `Database.create_for`, which asks posthoganalytics whether a flag is on; that call has no
+ # timeout, so on a machine without egress the build sits in connect() forever with no output
+ # and no error. Opting out makes `feature_enabled` answer locally instead.
+ os.environ.setdefault("OPT_OUT_CAPTURE", "1")
try:
import django