: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): retry temporary infrastructure setup failures (#116093)
Daniel Parker073abf05871b
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex 2760de62e759..f3d64e67bad2 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -105,6 +105,16 @@ Do not trim endpoint serializers or generated tool schemas to meet the budget; tThe eval runner's `--skill-delivery exec` mode removes bundled skills and defaults cases without an explicit interaction origin to the `eval` MCP consumer, which supports skill `learn`. Explicit case origins take precedence in both delivery modes. Bundled mode leaves unspecified origins unchanged.The runner applies the selected delivery mode to both Python's sandbox-provisioning flag override and MCP's flag override. Bundled mode preserves native skills unless a case explicitly disables them; exec mode removes them. Compare the `expected_skill_loaded` and `skill_loaded_before_tool` scores: a completed eval run can report `PASS` despite zero scores unless `--fail-under` sets a score threshold.+The runner reports `FAIL` and exits with status 1 if a suite crashes or a case has an infrastructure error.+This rule applies even without a score threshold.+Infrastructure errors do not contribute to score averages.+Case timeouts and low scores affect the exit status only through `--fail-under`.+Temporary case setup failures and support-service readiness timeouts receive two retries by default, with delays of 1 second and 2 seconds.+Use `--infra-retries 0` to disable these retries.+Each case setup retry creates fresh test data before the agent starts.+The runner stops the previous service process before a readiness retry.+Retry messages show the next attempt and delay; only the final case result affects the error count.+Authentication errors, setup code errors, agent work, and low scores do not trigger these retries.Bundled-mode evals explicitly disable `mcp-exec-skills` through the dev/test process override, which skips skill-catalog warmup and polling. Exec-mode evals allow 120 seconds for MCP startup, covering the 60-second warmup budget plus an in-flight download and development build; bundled mode keeps the 30-second startup limit. Production feature-flag evaluation does not control this process lifecycle.## Rolling out MCP skill discoverydiff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.mdindex abda86f174ef..7b3bb2684b1e 100644--- a/products/posthog_ai/eval_harness/README.md+++ b/products/posthog_ai/eval_harness/README.md@@ -63,25 +63,43 @@ python -m products.posthog_ai.eval_harness.harness --provider modalpython -m products.posthog_ai.eval_harness.harness --list```-| Flag | Meaning |-| --------------------------------- | -------------------------------------------------------------------------------- |-| `--eval <substr>` | Only run cases whose name contains the substring. |-| `--provider {docker,modal}` | Where sandboxes run. Default `docker`. |-| `--max-sandboxes N` | Cap concurrently live sandboxes across all suites. |-| `--agent-model <model>` | Model the sandboxed agent runs against, pinned for stable cross-run comparison. |-| `--agent-runtime {claude,codex}` | Agent runtime serving the model. Default `claude`. |-| `--skill-delivery {bundled,exec}` | Skill delivery path. Default `bundled`; `exec` removes native sandbox skills. |-| `--reasoning-effort <effort>` | Agent reasoning effort; valid values depend on runtime+model. |-| `--keep-sandbox-containers` | Skip the end-of-run Docker sweep, to inspect a leftover container. Docker only. |-| `--rebuild-sandbox-image` | Force a rebuild of the `posthog-sandbox-base` image before the run. Docker only. |-| `--create-db` | Rebuild the eval test database instead of reusing it. |-| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |-| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |-| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |-| `--list` | Print the discovered suite ids (with their kinds) and exit. |+| Flag | Meaning |+| --------------------------------- | -------------------------------------------------------------------------------------------------------- |+| `--eval <substr>` | Only run cases whose name contains the substring. |+| `--provider {docker,modal}` | Where sandboxes run. Default `docker`. |+| `--max-sandboxes N` | Cap concurrently live sandboxes across all suites. |+| `--agent-model <model>` | Model the sandboxed agent runs against, pinned for stable cross-run comparison. |+| `--agent-runtime {claude,codex}` | Agent runtime serving the model. Default `claude`. |+| `--skill-delivery {bundled,exec}` | Skill delivery path. Default `bundled`; `exec` removes native sandbox skills. |+| `--reasoning-effort <effort>` | Agent reasoning effort; valid values depend on runtime+model. |+| `--keep-sandbox-containers` | Skip the end-of-run Docker sweep, to inspect a leftover container. Docker only. |+| `--rebuild-sandbox-image` | Force a rebuild of the `posthog-sandbox-base` image before the run. Docker only. |+| `--create-db` | Rebuild the eval test database instead of reusing it. |+| `--case-timeout <seconds>` | Agent-run budget (minimum 1 second), started after the case's team setup. |+| `--trials N` | Run every case N times (Braintrust trials), for variance on stochastic agents. |+| `--infra-retries N` | Retry temporary case setup failures and service readiness timeouts N times. Default 2; use 0 to disable. |+| `--fail-under <fraction>` | Exit nonzero when the mean score across all experiments falls below this (0-1). |+| `--list` | Print the discovered suite ids (with their kinds) and exit. |Sandbox-only flags (`--provider`, `--max-sandboxes`, `--agent-runtime`, `--skill-delivery`, `--reasoning-effort`, `--keep-sandbox-containers`, `--rebuild-sandbox-image`) are rejected in preflight when no selected suite is sandboxed, instead of being silently ignored.+The run exits with status 1 if a suite crashes or a case has an infrastructure error, even without `--fail-under`.+Infrastructure errors remain separate from score averages.+Case timeouts and low scores affect the exit status only through `--fail-under`.++Temporary case setup failures and support-service readiness timeouts receive two retries by default.+The default delays are 1 second and 2 seconds.+Setup retries cover connection failures, temporary PostgreSQL failures, ClickHouse overload, query timeouts or memory limits, and object-storage server errors.+Known PostgreSQL transport failures can retry without a SQLSTATE.+Failed setup steps close unusable Django connections in the same worker thread before a retry.+Each case setup retry creates fresh test data before the agent starts.+The runner releases the team setup permit during the delay and stops the previous service process before a readiness retry.+`CASE RETRY` and `STARTUP RETRY` messages show the next attempt and delay.+The final summary counts case setup retries separately from case errors.+Case metadata records `setup_attempts` and `setup_retry_errors`.+The runner retries neither agent work nor low scores, case timeouts, authentication errors, setup code errors, or services that exit during startup.+Existing sandbox-creation and storage-read retries still apply.+`EXPORT_EVAL_RESULTS=1` additionally appends one structured JSON summary per experiment to `eval_results.jsonl`.The full plain-text run transcript is always written without this setting.diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex 2f33053c73a8..e6d13b784eb0 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -5,21 +5,33 @@ import timeimport uuidimport asyncioimport logging-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom dataclasses import replacefrom functools import partialfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literal+from django.db import (+ OperationalError as DjangoOperationalError,+ close_old_connections,+)+import orjson+from botocore.exceptions import ClientError, ConnectionClosedError, EndpointConnectionError, ReadTimeoutError+from clickhouse_driver.errors import ErrorCodes, NetworkError, ServerException, SocketTimeoutError+from psycopg import OperationalError as PsycopgOperationalError++from posthog.dataclasses import frozen+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut-from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN, CustomPromptSandboxContextfrom .acp_log import ParsedLog, parse_logfrom .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCasefrom .engines.base import EvalEnginefrom .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKindfrom .harness.kernel_sandboxes import reclaim_kernels+from .harness.retries import infrastructure_retry_delayfrom .harness.trial_stats import trial_statsfrom .log_parser import describe_tool_usefrom .log_sink import append_case_scores, build_case_dir, write_case_logs@@ -400,6 +412,75 @@ class _BaseEvalRun:return result+def _retryable_setup_error(error: Exception) -> bool:+ if isinstance(+ error,+ (+ ConnectionError,+ NetworkError,+ SocketTimeoutError,+ EndpointConnectionError,+ ConnectionClosedError,+ ReadTimeoutError,+ ClickHouseAtCapacity,+ ClickHouseQueryTimeOut,+ ClickHouseQueryMemoryLimitExceeded,+ ),+ ):+ return True+ if isinstance(error, ServerException):+ return error.code in {+ ErrorCodes.TIMEOUT_EXCEEDED,+ ErrorCodes.TOO_MANY_SIMULTANEOUS_QUERIES,+ ErrorCodes.MEMORY_LIMIT_EXCEEDED,+ }+ if isinstance(error, ClientError):+ return error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") in {500, 502, 503, 504}+ cause = error.__cause__ if isinstance(error, DjangoOperationalError) else error+ if isinstance(cause, PsycopgOperationalError):+ code = cause.sqlstate+ if code is not None:+ return code.startswith("08") or code in {"40001", "40P01", "53300", "57P01", "57P02", "57P03"}+ message = str(cause).lower()+ if "fatal:" in message:+ return False+ return any(+ transport_error in message+ for transport_error in (+ "connection refused",+ "connection reset by peer",+ "connection timed out",+ "timeout expired",+ "server closed the connection unexpectedly",+ "ssl syscall error: eof detected",+ "ssl connection has been closed unexpectedly",+ "could not receive data from server",+ "could not send data to server",+ "network is unreachable",+ "no route to host",+ "temporary failure in name resolution",+ )+ )+ return False+++async def _run_setup_step[Result](step: Callable[[], Result]) -> Result:+ def run_in_worker() -> Result:+ try:+ return step()+ except Exception:+ close_old_connections()+ raise++ return await asyncio.to_thread(run_in_worker)+++@frozen+class _SandboxedCaseSetup:+ context: CustomPromptSandboxContext+ seed: dict[str, Any]++class _SandboxedEvalRun(_BaseEvalRun):"""The sandbox-agent incarnation of ``_BaseEvalRun``: per-case teamprovisioning, the sandbox-owning window, and ACP log post-processing.@@ -441,8 +522,69 @@ class _SandboxedEvalRun(_BaseEvalRun):assert isinstance(case, SandboxedEvalCase)return super()._case_input(case) | {"repo_fixture": case.repo_fixture}+ async def _prepare_case(+ self,+ eval_case: SandboxedEvalCase,+ original_case: SandboxedEvalCase | None,+ hooks: CaseHooks | None,+ ) -> _SandboxedCaseSetup:+ for attempt in range(self.ctx.infrastructure_retries + 1):+ if hooks is not None:+ hooks.metadata["setup_attempts"] = attempt + 1+ sandbox_context: CustomPromptSandboxContext | None = None+ try:+ # Team cloning and some case seeders both write to ClickHouse. Bound+ # the full setup phase separately even when Modal makes sandbox+ # capacity effectively unbounded.+ async with self.ctx.team_setup_slots:+ # The factory does Django ORM work. Django's async-safety+ # guard rejects sync ORM calls from async contexts, so run it+ # in a worker thread.+ sandbox_context = await _run_setup_step(+ partial(+ self._demo_data.make_context,+ eval_case.name,+ disable_bundled_skills=(+ self.ctx.skill_delivery == "exec"+ or bool(original_case and original_case.disable_bundled_skills)+ ),+ ),+ )+ if original_case is not None and original_case.interaction_origin:+ sandbox_context = replace(sandbox_context, interaction_origin=original_case.interaction_origin)+ elif self.ctx.skill_delivery == "exec":+ sandbox_context = replace(sandbox_context, interaction_origin=EVAL_INTERACTION_ORIGIN)+ seed = (+ await _run_setup_step(partial(original_case.setup, sandbox_context))+ if original_case is not None and original_case.setup is not None+ else {}+ )+ return _SandboxedCaseSetup(context=sandbox_context, seed=seed)+ except Exception as error:+ if sandbox_context is not None:+ await reclaim_kernels(+ sandbox_context.team_id,+ keep=self._provider_strategy.keeps_sandboxes(),+ )+ if not _retryable_setup_error(error) or attempt == self.ctx.infrastructure_retries:+ raise+ delay = infrastructure_retry_delay(attempt)+ error_type = type(error).__name__+ if hooks is not None:+ hooks.metadata.setdefault("setup_retry_errors", []).append(error_type)+ await self.ctx.reporter.case_setup_retry(+ self.experiment_name,+ eval_case.name,+ next_attempt=attempt + 2,+ total_attempts=self.ctx.infrastructure_retries + 1,+ delay_seconds=delay,+ error_type=error_type,+ )+ await asyncio.sleep(delay)+ raise AssertionError("unreachable")+async def _run_sandbox_window(- self, eval_case: SandboxedEvalCase, original_case: SandboxedEvalCase | None+ self, eval_case: SandboxedEvalCase, original_case: SandboxedEvalCase | None, hooks: CaseHooks | None = None) -> tuple[EvalCaseResult, dict[str, Any]]:"""Run the sandbox-owning window and return its result plus the seed data.@@ -452,37 +594,13 @@ class _SandboxedEvalRun(_BaseEvalRun):never waits on post-processing."""ctx = self.ctx- seed_result: dict[str, Any] = {}async with self._sandbox_slots:- # Team cloning and some case seeders both write to ClickHouse. Bound- # the full setup phase separately even when Modal makes sandbox- # capacity effectively unbounded.- async with ctx.team_setup_slots:- # The factory does Django ORM work. Django's async-safety- # guard rejects sync ORM calls from async contexts, so run it- # in a worker thread.- sandbox_context = await asyncio.to_thread(- self._demo_data.make_context,- eval_case.name,- disable_bundled_skills=(- ctx.skill_delivery == "exec" or bool(original_case and original_case.disable_bundled_skills)- ),- )- if original_case is not None and original_case.interaction_origin:- sandbox_context = replace(sandbox_context, interaction_origin=original_case.interaction_origin)- elif ctx.skill_delivery == "exec":- sandbox_context = replace(sandbox_context, interaction_origin=EVAL_INTERACTION_ORIGIN)- if original_case is not None and original_case.setup is not None:- try:- seed_result = await asyncio.to_thread(original_case.setup, sandbox_context)- except Exception:- logger.exception("Setup hook failed for '%s'", eval_case.name)- raise+ prepared = await self._prepare_case(eval_case, original_case, hooks)# Start the agent budget after team setup, so neither semaphore wait# nor the ClickHouse copy can consume it.try:result = await asyncio.wait_for(- run_eval_case(eval_case, sandbox_context, provider=self._provider_strategy),+ run_eval_case(eval_case, prepared.context, provider=self._provider_strategy),timeout=ctx.per_case_timeout_seconds,)finally:@@ -491,10 +609,10 @@ class _SandboxedEvalRun(_BaseEvalRun):# case is exactly the one most likely to have left one running. One# indexed query for every case that never touched a notebook.await reclaim_kernels(- sandbox_context.team_id,+ prepared.context.team_id,keep=self._provider_strategy is not None and self._provider_strategy.keeps_sandboxes(),)- return result, seed_result+ return result, prepared.seedasync def _post_process(self,@@ -583,7 +701,7 @@ class _SandboxedEvalRun(_BaseEvalRun):)original_case = self.cases_by_name.get(input["name"])sandbox_case = original_case if isinstance(original_case, SandboxedEvalCase) else None- result, seed_result = await self._run_sandbox_window(eval_case, sandbox_case)+ result, seed_result = await self._run_sandbox_window(eval_case, sandbox_case, hooks)return await self._post_process(eval_case, hooks, result, seed_result)def _timeout_output(self) -> dict[str, Any]:diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.pyindex 57dc21920048..68acf98d0db7 100644--- a/products/posthog_ai/eval_harness/harness/cli.py+++ b/products/posthog_ai/eval_harness/harness/cli.py@@ -6,6 +6,7 @@ from dataclasses import dataclassfrom typing import Literal, cast, get_argsfrom .providers import DockerProviderStrategy, ModalProviderStrategy, SandboxProvider+from .retries import DEFAULT_INFRA_RETRIES# 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@@ -61,6 +62,8 @@ class HarnessOptions:"""Sandbox-only flags the user passed explicitly, so a run without sandboxedsuites can reject them instead of silently ignoring them."""+ infrastructure_retries: int = DEFAULT_INFRA_RETRIES+def _default_case_timeout() -> int:if os.getenv("EVAL_MODE") == "offline":@@ -167,6 +170,12 @@ def build_parser() -> argparse.ArgumentParser:default=1,help="Run every case this many times (Braintrust trials), to measure variance on stochastic agents.",)+ parser.add_argument(+ "--infra-retries",+ type=int,+ default=DEFAULT_INFRA_RETRIES,+ help="Retries for temporary case setup failures and support-service readiness timeouts. Use 0 to disable.",+ )parser.add_argument("--fail-under",type=float,@@ -220,6 +229,8 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:parser.error(f"--agent-model {agent_model} is an OpenAI model; pass --agent-runtime codex to serve it")if args.fail_under is not None and not (0 < args.fail_under <= 1):parser.error("--fail-under must be greater than 0 and at most 1")+ if args.infra_retries < 0:+ parser.error("--infra-retries must be at least 0")default_slots = (DockerProviderStrategy.default_max_sandboxes@@ -246,4 +257,5 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:trials=args.trials,fail_under=args.fail_under,sandbox_flags_set=sandbox_flags_set,+ infrastructure_retries=args.infra_retries,)diff --git a/products/posthog_ai/eval_harness/harness/context.py b/products/posthog_ai/eval_harness/harness/context.pyindex 53b72d45e26e..73451bd43fe4 100644--- a/products/posthog_ai/eval_harness/harness/context.py+++ b/products/posthog_ai/eval_harness/harness/context.py@@ -10,6 +10,7 @@ from .cli import SkillDeliveryfrom .demo_data import SandboxedDemoDatafrom .providers import SandboxProvider, SandboxProviderStrategyfrom .reporting import ProgressReporter+from .retries import DEFAULT_INFRA_RETRIES@dataclass(frozen=False)@@ -87,3 +88,5 @@ class EvalContext:git_dirty: bool | None"""Whether tracked files differed from ``git_sha``; ``None`` when unknown."""++ infrastructure_retries: int = DEFAULT_INFRA_RETRIESdiff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.pyindex 24277422d01a..3b1e090802d5 100644--- a/products/posthog_ai/eval_harness/harness/lifecycle.py+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py@@ -49,6 +49,7 @@ from .providers import PreflightError, SandboxProviderStrategy, build_providerfrom .reporting import ProgressReporter, SuiteRunResultfrom .requirements import Infra, infra_unionfrom .services import (+ LONG_LIVED_SUBPROCESSES,build_local_skills,ensure_personhog_binaries,package_local_skills_archive,@@ -223,7 +224,7 @@ class SandboxedEvalHarness:return exit_codedef _exit_code(self, results: Sequence[SuiteRunResult], reporter: ProgressReporter) -> int:- if any(result.status == "crashed" for result in results):+ if any(result.status == "crashed" for result in results) or reporter.has_case_errors():return 1if self.options.fail_under is None:return 0@@ -247,6 +248,7 @@ class SandboxedEvalHarness:def _bootstrap(self, required: frozenset[Infra]) -> None:"""Stand up everything the selected suites share. Teardown is registered inreverse on the stack, so what wasn't started is never torn down."""+ LONG_LIVED_SUBPROCESSES.startup_retries = self.options.infrastructure_retries# Belt and braces for the SIGINT / SIGTERM paths, where the ExitStack never unwinds.atexit.register(stop_all_subprocesses)if self.provider is not None:@@ -429,6 +431,7 @@ class SandboxedEvalHarness:trials=self.options.trials,git_sha=self._git_sha,git_dirty=self._git_dirty,+ infrastructure_retries=self.options.infrastructure_retries,)async def _run_suite(self, suite: EvalSuite, ctx: EvalContext) -> SuiteRunResult:diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.pyindex 9d3d5bb61f09..859d169bd6d2 100644--- a/products/posthog_ai/eval_harness/harness/reporting.py+++ b/products/posthog_ai/eval_harness/harness/reporting.py@@ -45,6 +45,7 @@ class ProgressReporter:self._finished_suites = 0self._summaries: dict[str, EvalSummary] = {}self._case_counts: dict[str, int] = defaultdict(int)+ self._setup_retry_count = 0self._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)@@ -104,6 +105,23 @@ class ProgressReporter:f"CASE {marker:<7} {experiment_name} :: {case_name} {progress} {_format_duration(duration_seconds)}")+ async def case_setup_retry(+ self,+ experiment_name: str,+ case_name: str,+ *,+ next_attempt: int,+ total_attempts: int,+ delay_seconds: float,+ error_type: str,+ ) -> None:+ async with self._lock:+ self._setup_retry_count += 1+ _emit(+ f"CASE RETRY {experiment_name} :: {case_name} setup attempt {next_attempt}/{total_attempts} "+ f"in {delay_seconds:.1f}s ({error_type}). No action required."+ )+async def suite_finished(self, result: SuiteRunResult) -> None:async with self._lock:self._finished_suites += 1@@ -161,6 +179,7 @@ class ProgressReporter:),f"Mean score: {self._mean_score_text()}",f"Score gate: {self._score_gate_text(fail_under)}",+ f"Case setup retries: {self._setup_retry_count}",f"Duration: {_format_duration(duration_seconds)}",]@@ -186,6 +205,9 @@ class ProgressReporter:))+ def has_case_errors(self) -> bool:+ return self._combined_case_statuses()["error"] > 0+def mean_score(self) -> float | None:scores = [score.scorediff --git a/products/posthog_ai/eval_harness/harness/retries.py b/products/posthog_ai/eval_harness/harness/retries.pynew file mode 100644index 000000000000..2bf67b422b6f--- /dev/null+++ b/products/posthog_ai/eval_harness/harness/retries.py@@ -0,0 +1,5 @@+DEFAULT_INFRA_RETRIES = 2+++def infrastructure_retry_delay(retry_index: int) -> float:+ return float(min(2**retry_index, 10))diff --git a/products/posthog_ai/eval_harness/long_lived_subprocess.py b/products/posthog_ai/eval_harness/long_lived_subprocess.pyindex bd03fd3c8de2..11baaecf3edc 100644--- a/products/posthog_ai/eval_harness/long_lived_subprocess.py+++ b/products/posthog_ai/eval_harness/long_lived_subprocess.py@@ -15,6 +15,8 @@ from pathlib import Pathfrom types import FrameTypefrom typing import TypedDict, cast+from .harness.retries import DEFAULT_INFRA_RETRIES, infrastructure_retry_delay+logger = logging.getLogger(__name__)StopCallback = Callable[[], None]@@ -24,6 +26,10 @@ class SubprocessStartupError(RuntimeError):"""A managed support subprocess failed to come up (crashed, timed out, or port already bound)."""+class SubprocessReadinessTimeout(SubprocessStartupError):+ pass++class ProcessMetadata(TypedDict):name: strport: int@@ -37,6 +43,7 @@ class LongLivedSubprocessManager:"""Own support subprocess lifecycle for sandboxed eval sessions."""def __init__(self) -> None:+ self.startup_retries = DEFAULT_INFRA_RETRIESself._stops: list[StopCallback] = []self._stops_lock = threading.Lock()self._previous_signal_handlers: dict[int, object] = {}@@ -53,6 +60,42 @@ class LongLivedSubprocessManager:env: dict[str, str],log_prefix: str,readiness_timeout: float = 30.0,+ ) -> tuple[subprocess.Popen, StopCallback]:+ for attempt in range(self.startup_retries + 1):+ try:+ return self._start_once(+ name=name,+ port=port,+ cmd=cmd,+ cwd=cwd,+ env=env,+ log_prefix=log_prefix,+ readiness_timeout=readiness_timeout,+ )+ except SubprocessReadinessTimeout:+ if attempt == self.startup_retries:+ raise+ delay = infrastructure_retry_delay(attempt)+ logger.warning(+ "STARTUP RETRY %s: readiness timed out; previous process stopped. Attempt %d/%d in %.1fs. No action required.",+ name,+ attempt + 2,+ self.startup_retries + 1,+ delay,+ )+ time.sleep(delay)+ raise AssertionError("unreachable")++ def _start_once(+ self,+ *,+ name: str,+ port: int,+ cmd: list[str],+ cwd: Path,+ env: dict[str, str],+ log_prefix: str,+ readiness_timeout: float = 30.0,) -> tuple[subprocess.Popen, StopCallback]:"""Spawn a long-lived support service for the eval session.@@ -86,6 +129,7 @@ class LongLivedSubprocessManager:finally:self._remove_pid_file(port)self._unregister(stop)+ atexit.unregister(stop)self._register(stop)atexit.register(stop)@@ -107,7 +151,7 @@ class LongLivedSubprocessManager:time.sleep(0.5)stop()- raise SubprocessStartupError(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")+ raise SubprocessReadinessTimeout(f"{name} failed to start on port {port} within {readiness_timeout:.0f}s.")def stop_all(self) -> None:with self._stops_lock:diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.pyindex e1d38b8d5e96..5570724175a5 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py@@ -6,6 +6,7 @@ import asyncioimport subprocessfrom pathlib import Pathfrom types import SimpleNamespace+from typing import Literalfrom uuid import UUIDimport pytest@@ -16,6 +17,8 @@ from parameterized import parameterizedfrom products.posthog_ai.eval_harness import runnerfrom products.posthog_ai.eval_harness.config import AgentArtifacts, SandboxedEvalCase+from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary+from products.posthog_ai.eval_harness.harness import lifecyclefrom products.posthog_ai.eval_harness.harness.cli import SkillDelivery, parse_argsfrom products.posthog_ai.eval_harness.harness.context import EvalContextfrom products.posthog_ai.eval_harness.harness.discovery import EvalSuite@@ -166,6 +169,68 @@ def test_eval_feature_enabled_leaves_dispatcher_flags_off(_name: str, flag: str,assert eval_feature_enabled(flag, distinct_id="distinct-1") is expected+ "outcome, fail_under, score, expected_exit_code",+ [+ pytest.param("case_error", None, 1.0, 1, id="case_error_without_gate"),+ pytest.param("engine_error", None, 1.0, 1, id="engine_error_without_gate"),+ pytest.param("both_errors", 0.5, 1.0, 1, id="errors_with_passing_gate"),+ pytest.param("case_error", 1.0, 1.0, 1, id="case_error_with_perfect_score"),+ pytest.param("crash", None, 1.0, 1, id="suite_crash"),+ pytest.param("ok", None, 0.0, 0, id="low_score_without_gate"),+ pytest.param("ok", 0.5, 0.5, 0, id="score_meets_gate"),+ pytest.param("ok", 0.5, 0.0, 1, id="score_below_gate"),+ pytest.param("ok", 0.5, None, 1, id="no_scores_with_gate"),+ pytest.param("timeout", None, 0.0, 0, id="timeout_without_gate"),+ pytest.param("timeout", 0.5, 0.0, 1, id="timeout_below_gate"),+ ],+)+def test_eval_run_exit_status(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ outcome: Literal["ok", "case_error", "engine_error", "both_errors", "timeout", "crash"],+ fail_under: float | None,+ score: float | None,+ expected_exit_code: int,+) -> None:+ monkeypatch.delenv("EXPORT_EVAL_RESULTS", raising=False)++ async def suite(ctx: EvalContext) -> None:+ if outcome == "crash":+ raise RuntimeError("Synthetic suite failure")+ await ctx.reporter.case_done("experiment", "completed-case", duration_seconds=1.0)+ if outcome in {"case_error", "both_errors", "timeout"}:+ await ctx.reporter.case_done(+ "experiment",+ "failed-case",+ duration_seconds=1.0,+ status="timeout" if outcome == "timeout" else "error",+ )+ await ctx.reporter.record_summary(+ "experiment",+ EvalSummary(+ engine_name="Braintrust",+ experiment_name="experiment",+ scores={"score": AggregateScore("score", score)} if score is not None else {},+ ),+ error_count=1 if outcome in {"engine_error", "both_errors"} else 0,+ )++ monkeypatch.setattr(+ lifecycle,+ "discover_suites",+ lambda _selectors: [EvalSuite(domain="test", module_name="exit_status", fn_name="suite", fn=suite)],+ )+ monkeypatch.setattr(lifecycle, "infra_union", lambda _kinds: frozenset())+ monkeypatch.setattr(lifecycle, "validate_eval_env", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(SandboxedEvalHarness, "_bootstrap", lambda *_args: None)+ args = [] if fail_under is None else ["--fail-under", str(fail_under)]++ assert SandboxedEvalHarness(parse_args(args)).run() == expected_exit_code+ output = capsys.readouterr().out+ assert f"Status: {'PASS' if expected_exit_code == 0 else 'FAIL'}" in output++@pytest.mark.asyncio@pytest.mark.parametrize("delivery", ["bundled", "exec"])@pytest.mark.parametrize("origin", ["eval", "slack", None])diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.pyindex a5edfc1be4b8..d3d1a3c92546 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_cli.py@@ -14,3 +14,16 @@ from products.posthog_ai.eval_harness.harness.cli import SkillDelivery, parse_ar)def test_skill_delivery_defaults_to_bundled_and_allows_exec(argv: list[str], expected_delivery: SkillDelivery) -> None:assert parse_args(argv).skill_delivery == expected_delivery+++ "argv,expected",+ [([], 2), (["--infra-retries", "0"], 0), (["--infra-retries", "3"], 3), (["--infra-retries", "-1"], None)],+)+def test_infrastructure_retry_budget(argv: list[str], expected: int | None) -> None:+ if expected is None:+ with pytest.raises(SystemExit) as error:+ parse_args(argv)+ assert error.value.code == 2+ else:+ assert parse_args(argv).infrastructure_retries == expecteddiff --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 c613f34cfed1..7e9d160489a3 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@@ -5,12 +5,23 @@ import jsonimport asynciofrom collections.abc import Iteratorfrom contextlib import contextmanager+from functools import partialfrom pathlib import Path-from typing import Any+from threading import get_ident+from typing import Any, Literalimport pytestfrom unittest.mock import AsyncMock, MagicMock+from django.db import OperationalError++from botocore.exceptions import ClientError+from clickhouse_driver.errors import ErrorCodes, NetworkError, ServerException+from psycopg import OperationalError as PsycopgOperationalError+from psycopg.errors import AdminShutdown, InvalidPassword++from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from 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@@ -367,3 +378,203 @@ async def test_sandboxed_eval_skill_delivery_sets_the_agent_origin(assert seed == {"seeded": True}else:assert seed == {}+++ "stage,error,failures,retries,recovers",+ [+ pytest.param("clone", NetworkError("Temporary connection failure"), 1, 2, True, id="clone_recovers"),+ pytest.param("seed", NetworkError("Temporary connection failure"), 2, 2, True, id="seed_recovers"),+ pytest.param("seed", AdminShutdown("Database restart"), 1, 2, True, id="postgres_restart"),+ pytest.param("clone", AdminShutdown("Database restart"), 1, 2, True, id="postgres_clone_restart"),+ pytest.param(+ "clone", PsycopgOperationalError("connection failed: Connection refused"), 1, 2, True, id="postgres_refused"+ ),+ pytest.param(+ "seed",+ PsycopgOperationalError("server closed the connection unexpectedly"),+ 1,+ 2,+ True,+ id="postgres_socket_closed",+ ),+ pytest.param("seed", PsycopgOperationalError("timeout expired"), 1, 2, True, id="postgres_timeout"),+ pytest.param(+ "seed",+ PsycopgOperationalError('FATAL: password authentication failed for user "example"'),+ 1,+ 2,+ False,+ id="postgres_authentication_without_sqlstate",+ ),+ pytest.param(+ "seed",+ PsycopgOperationalError('invalid sslmode value: "example"'),+ 1,+ 2,+ False,+ id="postgres_configuration_without_sqlstate",+ ),+ pytest.param(+ "seed",+ PsycopgOperationalError('Connection refused\nFATAL: database "example" does not exist'),+ 1,+ 2,+ False,+ id="postgres_mixed_permanent_failure",+ ),+ pytest.param("seed", InvalidPassword("Invalid test credentials"), 1, 2, False, id="postgres_authentication"),+ pytest.param(+ "seed", ServerException("Busy", code=ErrorCodes.MEMORY_LIMIT_EXCEEDED), 1, 2, True, id="clickhouse_busy"+ ),+ pytest.param("clone", ClickHouseAtCapacity(), 1, 2, True, id="clickhouse_wrapped_capacity"),+ pytest.param("seed", ClickHouseQueryTimeOut(), 1, 2, True, id="clickhouse_wrapped_timeout"),+ pytest.param("seed", ClickHouseQueryMemoryLimitExceeded(), 1, 2, True, id="clickhouse_wrapped_memory"),+ pytest.param(+ "seed",+ ClientError(+ {+ "ResponseMetadata": {+ "HTTPStatusCode": 503,+ "RequestId": "test-request",+ "HostId": "test-host",+ "HTTPHeaders": {},+ "RetryAttempts": 0,+ }+ },+ "GetObject",+ ),+ 1,+ 2,+ True,+ id="storage_outage",+ ),+ pytest.param(+ "seed",+ ClientError(+ {+ "ResponseMetadata": {+ "HTTPStatusCode": 403,+ "RequestId": "test-request",+ "HostId": "test-host",+ "HTTPHeaders": {},+ "RetryAttempts": 0,+ }+ },+ "GetObject",+ ),+ 1,+ 2,+ False,+ id="storage_authentication",+ ),+ pytest.param("seed", NetworkError("Temporary connection failure"), 3, 2, False, id="retry_limit"),+ pytest.param("seed", NetworkError("Temporary connection failure"), 1, 0, False, id="retries_disabled"),+ pytest.param("seed", ValueError("Invalid setup"), 1, 2, False, id="setup_bug"),+ pytest.param(+ "seed",+ PsycopgOperationalError("Unclassified connection failure"),+ 1,+ 2,+ False,+ id="unknown_postgres_failure",+ ),+ pytest.param("agent", NetworkError("Agent connection failure"), 1, 2, False, id="agent_does_not_retry"),+ ],+)+async def test_case_setup_retries_use_fresh_data_and_report_one_outcome(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ stage: Literal["clone", "seed", "agent"],+ error: Exception,+ failures: int,+ retries: int,+ recovers: bool,+) -> None:+ monkeypatch.setattr(base, "build_case_dir", MagicMock(return_value=tmp_path))+ reporter = ProgressReporter(total_suites=1)+ ctx = MagicMock(+ posthog_client=None,+ case_filter=None,+ skill_delivery="bundled",+ sandbox_slots=asyncio.Semaphore(1),+ team_setup_slots=asyncio.Semaphore(1),+ per_case_timeout_seconds=30,+ infrastructure_retries=retries,+ reporter=reporter,+ )+ ctx.provider_strategy.keeps_sandboxes.return_value = False+ contexts = [CustomPromptSandboxContext(team_id=team, user_id=1) for team in range(1, retries + 2)]+ failure = error+ if isinstance(error, PsycopgOperationalError) and stage == "seed":+ failure = OperationalError("Synthetic database failure")+ failure.__cause__ = error+ broken_workers: set[int] = set()++ def setup_step[Result](results: Iterator[Result | Exception], *_args: object, **_kwargs: object) -> Result:+ if get_ident() in broken_workers:+ raise PsycopgOperationalError("the connection is closed")+ result = next(results)+ if isinstance(result, Exception):+ if isinstance(error, PsycopgOperationalError):+ broken_workers.add(get_ident())+ raise result+ return result++ def close_worker_connections() -> None:+ broken_workers.discard(get_ident())++ monkeypatch.setattr(base, "close_old_connections", close_worker_connections)+ clone_results: list[CustomPromptSandboxContext | Exception] = [+ *([failure] * failures if stage == "clone" else []),+ *contexts,+ ]+ ctx.demo_data.make_context.side_effect = partial(setup_step, iter(clone_results))+ seed = MagicMock(side_effect=partial(setup_step, iter(([failure] * failures if stage == "seed" else []) + [{}])))+ case = SandboxedEvalCase(name="case", prompt="Run the task", setup=seed)+ run = base._SandboxedEvalRun(+ experiment_name="setup-retries",+ cases=[case],+ scorers=[],+ ctx=ctx,+ is_public=False,+ no_send_logs=True,+ )+ launch = AsyncMock(+ side_effect=failure if stage == "agent" else None,+ return_value=base.EvalCaseResult(artifacts=AgentArtifacts(exit_code=0)),+ )+ monkeypatch.setattr(base, "run_eval_case", launch)+ cleanup = AsyncMock()+ monkeypatch.setattr(base, "reclaim_kernels", cleanup)+ monkeypatch.setattr(run, "_post_process", AsyncMock(return_value={"score": 0.0}))++ async def backoff(_delay: float) -> None:+ assert ctx.team_setup_slots._value == 1+ assert launch.call_count == 0+ if stage == "seed":+ assert cleanup.await_count == seed.call_count++ monkeypatch.setattr(base.asyncio, "sleep", backoff)+ hooks = NullCaseHooks()+ if recovers:+ assert await run._task({"name": "case", "prompt": case.prompt}, hooks) == {"score": 0.0}+ assert launch.call_count == 1+ assert hooks.metadata["setup_attempts"] == failures + 1+ assert hooks.metadata["setup_retry_errors"] == [type(failure).__name__] * failures+ else:+ with pytest.raises(type(failure)):+ await run._task({"name": "case", "prompt": case.prompt}, hooks)+ assert launch.call_count == (1 if stage == "agent" else 0)+ if stage == "seed":+ seeded_teams = [call.args[0].team_id for call in seed.call_args_list]+ assert len(seeded_teams) == len(set(seeded_teams))+ output = capsys.readouterr().out+ retry_count = failures if recovers else (retries if stage == "seed" and isinstance(error, NetworkError) else 0)+ assert output.count("CASE RETRY") == retry_count+ assert output.count("CASE DONE" if recovers else "CASE ERROR") == 1+ assert reporter.has_case_errors() is (not recovers)+ assert ctx.sandbox_slots._value == ctx.team_setup_slots._value == 1+ assert not broken_workersdiff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.pyindex 73300a085eed..7a1fa6db923c 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_services.py@@ -3,12 +3,20 @@ from __future__ import annotationsimport osimport jsonimport zipfile+import itertools+from functools import partialfrom pathlib import Pathimport pytestfrom unittest.mock import MagicMock, patch+from products.posthog_ai.eval_harness import long_lived_subprocessfrom products.posthog_ai.eval_harness.harness.services import package_local_skills_archive, start_mcp_server+from products.posthog_ai.eval_harness.long_lived_subprocess import (+ LongLivedSubprocessManager,+ SubprocessReadinessTimeout,+ SubprocessStartupError,+)def test_package_local_skills_archive_is_deterministic_and_excludes_cache_markers(tmp_path: Path) -> None:@@ -71,3 +79,77 @@ def test_start_mcp_server_isolates_the_selected_skill_delivery(else:assert env["POSTHOG_MCP_SKILLS_URL"] == skill_archive_urlassert result is stop++[email protected]("failures,retries,recovers", [(1, 2, True), (3, 2, False), (1, 0, False)])+def test_service_readiness_retries_stop_each_failed_process(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ failures: int,+ retries: int,+ recovers: bool,+) -> None:+ manager = LongLivedSubprocessManager()+ manager.startup_retries = retries+ processes: list[MagicMock] = []+ stopped: list[MagicMock] = []++ def spawn(*_args: object, **_kwargs: object) -> MagicMock:+ assert stopped == processes+ process = MagicMock(pid=len(processes) + 1)+ process.poll.return_value = None+ processes.append(process)+ return process++ monkeypatch.setattr(long_lived_subprocess.subprocess, "Popen", spawn)+ clock = itertools.count()+ monkeypatch.setattr(long_lived_subprocess.time, "monotonic", lambda: next(clock))+ monkeypatch.setattr(long_lived_subprocess.time, "sleep", lambda _delay: None)+ monkeypatch.setattr(manager, "_stop_stale_managed_process", lambda **_kwargs: None)+ monkeypatch.setattr(manager, "_fail_if_port_bound", lambda *_args: None)+ monkeypatch.setattr(manager, "_pipe_output", lambda *_args: None)+ monkeypatch.setattr(manager, "_write_pid_file", lambda **_kwargs: None)+ monkeypatch.setattr(manager, "_remove_pid_file", lambda _port: None)+ monkeypatch.setattr(manager, "_stop_process_group", stopped.append)+ socket = MagicMock()+ monkeypatch.setattr(+ long_lived_subprocess.socket,+ "create_connection",+ MagicMock(side_effect=[OSError("Not ready")] * failures + [socket]),+ )+ start = partial(+ manager.start,+ name="test service",+ port=12345,+ cmd=["fake-service"],+ cwd=tmp_path,+ env={},+ log_prefix="test",+ readiness_timeout=2,+ )+ if recovers:+ process, stop = start()+ assert process is processes[-1]+ assert len(processes) == failures + 1+ stop()+ socket.close.assert_called_once()+ else:+ with pytest.raises(SubprocessReadinessTimeout):+ start()+ assert len(processes) == retries + 1+ assert stopped == processes+ assert manager._stops == []+++ "error", [SubprocessStartupError("Port in use"), FileNotFoundError("Missing executable"), KeyboardInterrupt()]+)+def test_service_startup_does_not_retry_permanent_errors_or_interrupts(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, error: BaseException+) -> None:+ manager = LongLivedSubprocessManager()+ start = MagicMock(side_effect=error)+ monkeypatch.setattr(manager, "_start_once", start)+ with pytest.raises(type(error)):+ manager.start(name="test service", port=12345, cmd=["fake-service"], cwd=tmp_path, env={}, log_prefix="test")+ assert start.call_count == 1