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.

feat(evals): improve sandbox run progress and timeout recovery (#116892)

Daniel Parkerad25524bb181
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.md
index fd5fef805aab..1c16b0fd8222 100644
--- a/docs/internal/ai-offline-evaluation-reporting.md
+++ b/docs/internal/ai-offline-evaluation-reporting.md
@@ -25,6 +25,13 @@ Each trial has a unique ID in engine metadata. Local logs and summaries use that
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.
+For a repeatable smoke comparison, use the [Claude and Codex command pair](../../products/posthog_ai/eval_harness/README.md#claude-and-codex-smoke-comparison).
+Both commands select the same MCP case and record the model, runtime, delivery mode, and checkout.
+Compare completed coverage and infrastructure errors alongside named scores and duration.
+Trial metadata and local summaries also record phase durations in seconds.
+The scoring phase includes time waiting for the experiment results, rather than scorer execution alone.
+A failed final metadata upload produces a warning and keeps the completed results available locally.
+A scorer failure marks the case as an error. Statistics still include scores from other successful scorers.
## Postgres experiment ingestion
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index 89c60d354bb8..739ec100f3f4 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -76,6 +76,7 @@ python -m products.posthog_ai.eval_harness.harness --list
| `--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. |
+| `--verbose` | Show detailed logs and tracebacks in the console. The transcript always keeps the detailed logs. |
| `--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). |
@@ -100,8 +101,18 @@ 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.
+The case budget starts after team setup. Polling uses one monotonic deadline across all turns.
+The harness reserves up to 120 seconds, capped at one quarter of the case budget, for log recovery and cleanup.
+The outer case timeout remains the final guard. Slow setup or storage reads cannot give a follow-up a fresh case budget.
+Poll timeouts keep their diagnostic stage and log counts in case metadata and the local artifacts file. They remain scored timeouts.
+A timeout summary contains the failure reason. Its raw log file can be empty; the full run transcript retains streamed agent output.
+
`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.
+Normal console output shows runner progress, summaries, and short error messages.
+Dependency warnings, SDK progress bars, and direct setup prints stay in the transcript.
+`--verbose` also shows Python warnings, SDK output, and detailed logs in the console.
+Native subprocess output always goes to the transcript.
### Comparing skill delivery
@@ -113,14 +124,43 @@ hogli evals eval_skill_distribution --skill-delivery bundled --agent-runtime cla
hogli evals eval_skill_distribution --skill-delivery exec --agent-runtime claude --agent-model claude-opus-4-8 --trials 3
```
-Both runs use the same six prompts and Braintrust history key.
+Both runs use the same prompts and Braintrust history key.
The experiment metadata records `skill_delivery`; compare the shared `expected_skill_loaded` and `skill_loaded_before_tool` scores rather than the aggregate mean, because the exec arm also reports search and discovery diagnostics.
### Codex runtime
`--agent-runtime codex` runs the same agent-server with OpenAI's Codex harness instead of Claude, defaulting the model to `gpt-5.5`.
It requires `LLM_GATEWAY_OPENAI_API_KEY` in the environment (checked by preflight), which the harness's LLM gateway uses to proxy the agent's OpenAI calls.
-Experiment names don't change with the runtime or skill delivery. Each Braintrust experiment and every PostHog event records `agent_model`, `trials`, `git_sha` and `git_dirty`. Sandboxed runs add `agent_runtime`, `skill_delivery` and `reasoning_effort`, so compare cross-run scores within one runtime and delivery mode.
+Experiment names don't change with the runtime or skill delivery. Each Braintrust experiment and every PostHog event records `agent_model`, `trials`, `git_sha` and `git_dirty`. Sandboxed runs add `agent_runtime`, `skill_delivery` and `reasoning_effort`. Use these fields to separate runs. A comparison across runtimes measures the model and runtime together.
+
+### Claude and Codex smoke comparison
+
+Start with one fixed MCP case. It checks skill discovery and tool use for a historical traffic query.
+Both commands below use the same case, provider, skill delivery, concurrency, and scorers.
+Run them in order from the same checkout. Separate harness processes share service ports, so do not run them together.
+
+Prepare the normal [provider prerequisites](#providers) and both model credentials before starting.
+Claude requires `LLM_GATEWAY_ANTHROPIC_API_KEY`; Codex also requires `LLM_GATEWAY_OPENAI_API_KEY`.
+
+```bash
+eval_comparison_args=(
+ cli_mcp/eval_skill_distribution::eval_skill_distribution
+ --eval historical_traffic_share_by_type
+ --provider modal
+ --max-sandboxes 1
+ --skill-delivery exec
+ --trials 1
+)
+EXPORT_EVAL_RESULTS=1 hogli evals "${eval_comparison_args[@]}" --agent-runtime claude --agent-model claude-opus-5
+EXPORT_EVAL_RESULTS=1 hogli evals "${eval_comparison_args[@]}" --agent-runtime codex --agent-model gpt-5.5
+```
+
+Compare the named scorer results, completed cases, timeouts, infrastructure errors, and total duration in both final summaries.
+Keep both transcript paths and both agent-log directories. Each directory contains `case_results.jsonl` with scores and trial IDs.
+Check the recorded `git_sha` and `git_dirty` values before comparing runs.
+Treat missing or errored trials as incomplete coverage, rather than a model score.
+This is a smoke comparison, not a broad model ranking. Set `--trials 3` in the shared arguments to check repeatability after the first pair completes.
+Remove `--eval historical_traffic_share_by_type` to compare the full skill-distribution suite.
## Providers
@@ -273,11 +313,20 @@ python -m products.posthog_ai.eval_harness.harness --list | grep my_thing
## Output
-Progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.
+Progress lines use stable labels as cases and suites start or finish: `SUITE START`, `EXPERIMENT START`, `CASE START`, `CASE PHASE`, `CASE READY`, `CASE DONE`, `EXPERIMENT DONE`, and `SUITE DONE`.
Only the overall run uses `PASS` or `FAIL`, so a suite with a low behavioral score still reads as completed rather than passed.
+The console shows case starts and phase changes for each trial.
+A status line every 30 seconds shows execution totals, phase counts, elapsed time, and the oldest active trial.
+`CASE READY` means execution completed; scoring and result collection are still pending.
+`CASE DONE` and `EXPERIMENT DONE` mean the scores are ready.
+The `scoring` phase includes time waiting for all results in that experiment, so it is not an isolated scorer duration.
+Use `--verbose` to show detailed service and agent logs in the console. The transcript retains these logs in both modes.
+Warnings and errors use short console messages. Open the transcript for full tracebacks.
+
The final summary gives labeled suite and case totals, the score gate, total duration, and one block per experiment with scorer averages, PostHog and Braintrust URLs, and the agent-log directory.
Each scorer line shows its score with a 95% confidence interval clustered by case. With `--trials N` a second line adds pass^N (every trial passed), pass@N (any trial passed) and the number of flaky cases, counting only cases scored on all N trials, so a noisy suite is distinguishable from a real score change.
-A crashed suite is labeled `CRASH`, includes its traceback in the summary, and makes the run exit nonzero without taking down the other suites.
+A crashed suite is labeled `CRASH` and makes the run exit nonzero without taking down the other suites.
+Its full traceback stays in the transcript. `--verbose` also shows the traceback in the final summary.
Every real eval invocation mirrors its complete stdout and stderr to:
@@ -292,7 +341,7 @@ Suite listing (`--list`) and argument errors do not create transcripts.
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.
+The summary includes the trial ID, the agent trace ID when available, phase durations in seconds, 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.
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.py
index 27eba006e9dd..4be9e0c995d2 100644
--- a/products/posthog_ai/eval_harness/base.py
+++ b/products/posthog_ai/eval_harness/base.py
@@ -6,6 +6,7 @@ import uuid
import asyncio
import logging
from collections.abc import Callable, Sequence
+from contextlib import suppress
from dataclasses import replace
from functools import partial
from pathlib import Path
@@ -24,13 +25,14 @@ 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, CustomPromptSandboxContext
+from products.tasks.backend.facade.agents import EVAL_INTERACTION_ORIGIN, CustomPromptSandboxContext, TurnPollTimeout
from .acp_log import ParsedLog, parse_log
from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCase
from .engines.base import EvalEngine
from .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKind
from .harness.kernel_sandboxes import reclaim_kernels
+from .harness.reporting import CasePhase
from .harness.retries import infrastructure_retry_delay
from .harness.trial_stats import trial_stats
from .log_parser import describe_tool_use
@@ -251,16 +253,44 @@ class _BaseEvalRun:
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"] + 1
+ hooks.metadata["phase_durations"] = await self.ctx.reporter.case_started(
+ self.experiment_name, case_name, hooks.metadata["trial_id"], hooks.metadata["trial_index"]
+ )
status: Literal["ok", "timeout", "error"] = "ok"
+ error_type: str | None = None
+ cancelled = False
try:
return await self._execute_case(input, hooks)
- except TimeoutError:
+ except (TimeoutError, TurnPollTimeout) as error:
# A case that outran its budget is a task result (too slow), not an
# infra error: score it 0 rather than letting Braintrust mark it errored.
status = "timeout"
- logger.warning("Eval case '%s' timed out after %ds", case_name, self.ctx.per_case_timeout_seconds)
- return self._timeout_output()
- except Exception:
+ output = self._timeout_output()
+ if isinstance(error, TurnPollTimeout):
+ hooks.metadata["poll_timeout"] = error.diagnostics()
+ output["stderr"] = str(error)
+ if poll_timeout := hooks.metadata.get("poll_timeout"):
+ output["poll_timeout"] = poll_timeout
+ logger.warning("Eval case '%s' timed out: %s", case_name, output.get("stderr") or output.get("error"))
+ try:
+ write_case_logs(
+ case_dir=self.run_log_dir,
+ case_name=case_name,
+ raw_log="",
+ artifacts=output,
+ prompt=input.get("prompt", ""),
+ duration=time.monotonic() - case_started,
+ last_message=str(output.get("stderr") or output.get("error") or "Case timed out"),
+ trial_id=hooks.metadata["trial_id"],
+ )
+ except Exception:
+ logger.exception("Failed to write timeout logs for '%s'", case_name)
+ return output
+ except asyncio.CancelledError:
+ cancelled = True
+ raise
+ except Exception as error:
+ error_type = type(error).__name__
# Infra failure (provisioning, demo copy, setup hook, poll). Re-raise so
# Braintrust records the case as errored and excludes it from score
# averages, instead of scoring the task 0 for the harness's fault.
@@ -269,12 +299,21 @@ class _BaseEvalRun:
raise
finally:
# Report on every path so the reporter's live case counter never stalls.
- await self.ctx.reporter.case_done(
- self.experiment_name,
- case_name,
- duration_seconds=time.monotonic() - case_started,
- status=status,
- )
+ if cancelled:
+ await self.ctx.reporter.finish_cases([hooks.metadata["trial_id"]])
+ else:
+ await self.ctx.reporter.case_done(
+ self.experiment_name,
+ case_name,
+ duration_seconds=time.monotonic() - case_started,
+ status=status,
+ trial_id=hooks.metadata["trial_id"],
+ error_type=error_type,
+ )
+
+ async def _set_case_phase(self, hooks: CaseHooks | None, phase: CasePhase) -> None:
+ if hooks is not None and (trial_id := hooks.metadata.get("trial_id")):
+ await self.ctx.reporter.case_phase(trial_id, phase)
async def _finalize(self, result: ExperimentResult) -> None:
"""Append scores to local summaries, emit PostHog evaluation/trace-root
@@ -291,6 +330,7 @@ class _BaseEvalRun:
case_name,
dict(eval_result.scores or {}),
trial_id=eval_result.metadata.get("trial_id"),
+ phase_durations=eval_result.metadata.get("phase_durations"),
)
except Exception:
logger.exception("Failed to append scores to local log summary for '%s'", case_name)
@@ -385,6 +425,7 @@ class _BaseEvalRun:
"trial_id": case_result.metadata.get("trial_id"),
"scores": case_result.scores,
"error": case_result.error,
+ "phase_durations": case_result.metadata.get("phase_durations"),
}
)
path = Path(self.run_log_dir) / "case_results.jsonl"
@@ -395,6 +436,11 @@ class _BaseEvalRun:
except OSError:
logger.exception("Failed to export per-case results for '%s'", self.experiment_name)
+ async def _report_results(self, result: ExperimentResult) -> None:
+ for case_result in result.results:
+ if trial_id := case_result.metadata.get("trial_id"):
+ await self.ctx.reporter.case_scored(trial_id, error=case_result.error)
+
async def run(self) -> ExperimentResult:
eval_cases = self._build_eval_cases()
@@ -403,20 +449,25 @@ class _BaseEvalRun:
planned_cases = len(eval_cases) * self.ctx.trials
await self.ctx.reporter.experiment_started(self.experiment_name, planned_cases, self.run_log_dir)
- result = await self.engine.run_experiment(
- ExperimentSpec(
- project_name=self._project_name(),
- cases=eval_cases,
- task=self._task,
- scorers=self.active_scorers,
- trial_count=self.ctx.trials,
- is_public=self.is_public,
- no_send_logs=self.no_send_logs,
- # Experiment names stay runtime/model-agnostic so history lines up across
- # runs; the metadata is what lets an engine filter or compare by them.
- metadata=self._experiment_metadata(),
+ try:
+ result = await self.engine.run_experiment(
+ ExperimentSpec(
+ project_name=self._project_name(),
+ cases=eval_cases,
+ task=self._task,
+ scorers=self.active_scorers,
+ trial_count=self.ctx.trials,
+ is_public=self.is_public,
+ no_send_logs=self.no_send_logs,
+ # Experiment names stay runtime/model-agnostic so history lines up across
+ # runs; the metadata is what lets an engine filter or compare by them.
+ metadata=self._experiment_metadata(),
+ on_results=self._report_results,
+ )
)
- )
+ await self._report_results(result)
+ finally:
+ await self.ctx.reporter.finish_experiment(self.experiment_name)
await self._finalize(result)
return result
@@ -546,7 +597,9 @@ class _SandboxedEvalRun(_BaseEvalRun):
# Team cloning and some case seeders both write to ClickHouse. Bound
# the full setup phase separately even when Modal makes sandbox
# capacity effectively unbounded.
+ await self._set_case_phase(hooks, "queued")
async with self.ctx.team_setup_slots:
+ await self._set_case_phase(hooks, "setup")
# 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.
@@ -609,8 +662,23 @@ class _SandboxedEvalRun(_BaseEvalRun):
# Start the agent budget after team setup, so neither semaphore wait
# nor the ClickHouse copy can consume it.
try:
+ with suppress(Exception):
+ await self._set_case_phase(hooks, "agent")
result = await asyncio.wait_for(
- run_eval_case(eval_case, prepared.context, provider=self._provider_strategy),
+ run_eval_case(
+ eval_case,
+ prepared.context,
+ provider=self._provider_strategy,
+ on_cleanup=partial(self._set_case_phase, hooks, "cleanup"),
+ timeout_seconds=ctx.per_case_timeout_seconds,
+ on_poll_timeout=(
+ lambda error: (
+ hooks.metadata.update({"poll_timeout": error.diagnostics()})
+ if hooks is not None
+ else None
+ )
+ ),
+ ),
timeout=ctx.per_case_timeout_seconds,
)
finally:
@@ -715,6 +783,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, hooks)
+ await self._set_case_phase(hooks, "logs")
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/engines/braintrust.py b/products/posthog_ai/eval_harness/engines/braintrust.py
index efa687d7924c..7cd091e63cc8 100644
--- a/products/posthog_ai/eval_harness/engines/braintrust.py
+++ b/products/posthog_ai/eval_harness/engines/braintrust.py
@@ -2,17 +2,22 @@
from __future__ import annotations
+import asyncio
+import logging
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Any, ClassVar
from braintrust import EvalAsync, EvalCase, EvalHooks
from braintrust.framework import EvalResultWithSummary, Evaluator, ReporterDef
+from braintrust.logger import Span, SpanImpl
# Imported for its side effect: braintrust's offline summary crashes on a skipped score.
from . import braintrust_patches # noqa: F401
from .types import AggregateScore, CaseResult, EnvVarSpec, EvalSummary, ExperimentResult, ExperimentSpec, SpanKind
+logger = logging.getLogger(__name__)
+
def _quiet_report_eval(evaluator: Evaluator, result: EvalResultWithSummary, verbose: bool, jsonl: bool) -> bool:
return True
@@ -85,10 +90,26 @@ class BraintrustEngine:
def required_env(cls) -> tuple[EnvVarSpec, ...]:
return (EnvVarSpec("BRAINTRUST_API_KEY", "records experiments and scores to Braintrust"),)
+ @staticmethod
+ def _persist_trial_metadata(result: ExperimentResult, trial_spans: dict[str, Span]) -> None:
+ for case in result.results:
+ if span := trial_spans.get(case.metadata.get("trial_id", "")):
+ span.log(metadata=case.metadata)
+ next(iter(trial_spans.values())).flush()
+
async def run_experiment(self, spec: ExperimentSpec) -> ExperimentResult:
+ trial_spans: dict[str, Span] = {}
+
async def bridged_task(input: dict[str, Any], hooks: EvalHooks) -> dict[str, Any] | None:
# Wrap braintrust's hooks so the suite task only ever sees neutral CaseHooks.
- return await spec.task(input, _BraintrustCaseHooks(hooks))
+ try:
+ return await spec.task(input, _BraintrustCaseHooks(hooks))
+ finally:
+ if not spec.no_send_logs and isinstance(hooks.span, SpanImpl):
+ # The pinned SDK exposes only the task span. Its context token retains the trial root span.
+ parent = hooks.span._context_token.old_value
+ if isinstance(parent, Span) and (trial_id := hooks.metadata.get("trial_id")):
+ trial_spans[trial_id] = parent
cases = [EvalCase(input=case.input, expected=case.expected, metadata=case.metadata) for case in spec.cases]
result = await EvalAsync(
@@ -116,7 +137,17 @@ class BraintrustEngine:
# across runs; the metadata is what lets Braintrust filter or compare.
metadata=spec.metadata,
)
- return self._translate(result)
+ translated = self._translate(result)
+ if spec.on_results is not None:
+ await spec.on_results(translated)
+ if trial_spans:
+ try:
+ await asyncio.to_thread(self._persist_trial_metadata, translated, trial_spans)
+ except Exception:
+ logger.warning(
+ "Could not upload final trial metadata; completed eval results remain available", exc_info=True
+ )
+ return translated
def _translate(self, result: EvalResultWithSummary) -> ExperimentResult:
"""Map braintrust's ``EvalResultWithSummary`` onto the neutral model.
@@ -144,7 +175,14 @@ class BraintrustEngine:
scores=dict(case.scores or {}),
expected=case.expected,
metadata=dict(case.metadata or {}),
- error=None if case.error is None else str(case.error),
+ error_kind="task" if case.error is not None else "scorer",
+ error=(
+ str(case.error)
+ if case.error is not None
+ else f"Scorer errors: {', '.join(case.metadata['scorer_errors'])}"
+ if case.metadata and case.metadata.get("scorer_errors")
+ else None
+ ),
)
for case in result.results
],
diff --git a/products/posthog_ai/eval_harness/engines/types.py b/products/posthog_ai/eval_harness/engines/types.py
index 552e2e767120..d245af8a87c3 100644
--- a/products/posthog_ai/eval_harness/engines/types.py
+++ b/products/posthog_ai/eval_harness/engines/types.py
@@ -93,16 +93,17 @@ class ExperimentSpec:
is_public: bool
no_send_logs: bool
metadata: dict[str, Any]
+ on_results: Callable[[ExperimentResult], Awaitable[None]] | None = None
-@dataclass
+@dataclass(frozen=False)
class CaseResult:
"""One scored case (or case × trial): the engine-neutral ``EvalResult``.
``scores`` maps scorer name to its per-case score; ``None`` means the scorer
skipped this case (excluded from aggregates). ``error`` is non-``None`` when
- the task itself raised — an infra failure the engine excludes from score
- averages rather than scoring 0.
+ the task or a scorer raised. ``error_kind`` distinguishes task failures,
+ excluded from all score averages, from partial scorer failures.
"""
input: dict[str, Any]
@@ -111,6 +112,7 @@ class CaseResult:
expected: Any = None
metadata: dict[str, Any] = field(default_factory=dict)
error: str | None = None
+ error_kind: Literal["task", "scorer"] = "task"
@dataclass(frozen=True)
diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.md
index c807f2348979..a7f7b9b8973f 100644
--- a/products/posthog_ai/eval_harness/harness/README.md
+++ b/products/posthog_ai/eval_harness/harness/README.md
@@ -69,6 +69,18 @@ The final summary renders after teardown, logging is flushed, and the transcript
The reporter emits plain-text records with stable labels so terminals and agents can scan the same output.
`START` marks work entering flight, `DONE` marks successful completion, and `TIMEOUT`, `ERROR`, or `CRASH` name exceptional outcomes.
Only the final overall run status uses `PASS` or `FAIL`.
+`CASE START` and `CASE PHASE` identify each trial. `CASE READY` marks completed execution with scoring still pending.
+The reporter prints phase counts and the oldest active trial every 30 seconds while suites run.
+The `scoring` duration includes waiting for the experiment results. It does not measure scorer execution alone.
+Public runs update Braintrust trial metadata after scoring so it contains the final phase durations.
+Scorer exceptions produce case errors in the console and final summary.
+The reporter writes output in worker threads so slow output does not stop the event loop.
+Terminal writes do not hold the transcript file lock, so progress output cannot block logging through that lock.
+The runner starts workflow cleanup before progress reporting.
+Cancellation during progress reporting does not stop workflow cleanup.
+The sandbox window always reclaims notebook kernels after the agent run, without another progress report.
+The console defaults to concise output. `--verbose` shows detailed logging and tracebacks.
+Both modes retain detailed logs in the transcript, including routine service stderr without a warning label.
Every invocation that attempts an eval writes the combined stdout/stderr stream to `logs/harness/<timestamp>_<id>.log`.
An explanatory line identifies the full run transcript, followed by the log's unlabeled absolute path as the final line in both the transcript and terminal.
@@ -85,6 +97,8 @@ Two consequences worth internalizing:
- The per-case timeout is an `asyncio.wait_for` **inside** the slot. Braintrust's own `timeout` would have wrapped the whole task invocation, including time queued on the semaphore, killing cases that never got a sandbox.
- A second `team_setup_slots` semaphore covers the full demo-data clone plus optional case seeder. It has one permit on ordinary local machines and four when `CODER` or `CI` is set, so managed environments prepare cases faster without making setup concurrency follow Modal's unbounded sandbox capacity.
- The agent timeout begins after team setup. Waiting for either semaphore never consumes it.
+- All turns share a monotonic poll deadline. The harness reserves up to 120 seconds, capped at one quarter of the case budget, for diagnostic recovery and cleanup before outer cancellation.
+- Poll timeouts retain their stage and log counts in case metadata and local artifacts. They follow the existing scored-timeout path.
- One-shot suites never touch the sandbox semaphore; a separate global `one_shot_slots` semaphore bounds their concurrently running cases under the same acquire-once, budget-inside rules.
There are two event loops. The main loop owns the Temporal dev server, the suites, and the reporter.
diff --git a/products/posthog_ai/eval_harness/harness/__main__.py b/products/posthog_ai/eval_harness/harness/__main__.py
index 06f9d73cbbd8..ebb93775aede 100644
--- a/products/posthog_ai/eval_harness/harness/__main__.py
+++ b/products/posthog_ai/eval_harness/harness/__main__.py
@@ -9,12 +9,14 @@ from .django_env import setup_django
from .env_preflight import load_env_file
from .ports import PERSONHOG_ROUTER_PORT
from .providers import SANDBOX_PROVIDER_SETTING, PreflightError
-from .transcript import RunTranscript
+from .transcript import RunTranscript, write_console
+
+logger = logging.getLogger("products.posthog_ai.eval_harness")
USAGE_ERROR_EXIT_CODE = 2
-def _run(options: HarnessOptions) -> int:
+def _run(options: HarnessOptions, *, transcript: RunTranscript | None = None) -> int:
# Load the repo-root .env before Django reads the environment, so the harness
# works without a manual `set -a; source .env`. Shell values win, and the
# explicit overrides below still trump anything an env file provided.
@@ -37,7 +39,9 @@ def _run(options: HarnessOptions) -> int:
# would otherwise silently point eval reads at the dev persons DB.
os.environ["PERSONHOG_ADDR"] = f"127.0.0.1:{PERSONHOG_ROUTER_PORT}"
- setup_django()
+ setup_django(keep_logging=transcript is not None)
+ if transcript is not None:
+ _configure_logging(transcript, verbose=options.verbose)
# Deferred so Django is configured first: everything below reaches settings,
# the ORM, or the products.tasks facade at import time.
@@ -49,15 +53,16 @@ def _run(options: HarnessOptions) -> int:
except (PreflightError, SuiteDiscoveryError) as e:
# A missing prerequisite or a typo'd selector is user error, not a harness
# bug: say what's wrong without a traceback.
- print(f"error: {e}", file=sys.stderr) # noqa: T201
+ write_console(f"error: {e}\n", stream=sys.stderr)
return USAGE_ERROR_EXIT_CODE
-def _configure_logging() -> None:
+def _configure_logging(transcript: RunTranscript | None = None, *, verbose: bool = False) -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
force=True,
+ handlers=[transcript.logging_handler(verbose=verbose)] if transcript is not None else None,
)
@@ -70,15 +75,15 @@ def main(argv: list[str] | None = None) -> int:
transcript = RunTranscript.create()
exit_code = 1
try:
- with transcript.capture():
- _configure_logging()
+ with transcript.capture(verbose=options.verbose):
+ _configure_logging(transcript, verbose=options.verbose)
try:
- exit_code = _run(options)
+ exit_code = _run(options, transcript=transcript)
except KeyboardInterrupt:
- logging.getLogger(__name__).warning("Interrupted")
+ logger.warning("Interrupted")
exit_code = 130
except Exception:
- logging.getLogger(__name__).exception("Sandboxed eval harness failed")
+ logger.exception("Sandboxed eval harness failed")
exit_code = 1
finally:
logging.shutdown()
diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.py
index 68acf98d0db7..c58a1ab56738 100644
--- a/products/posthog_ai/eval_harness/harness/cli.py
+++ b/products/posthog_ai/eval_harness/harness/cli.py
@@ -62,6 +62,7 @@ class HarnessOptions:
"""Sandbox-only flags the user passed explicitly, so a run without sandboxed
suites can reject them instead of silently ignoring them."""
+ verbose: bool = False
infrastructure_retries: int = DEFAULT_INFRA_RETRIES
@@ -176,6 +177,9 @@ def build_parser() -> argparse.ArgumentParser:
default=DEFAULT_INFRA_RETRIES,
help="Retries for temporary case setup failures and support-service readiness timeouts. Use 0 to disable.",
)
+ parser.add_argument(
+ "--verbose", action="store_true", help="Show detailed logs in the console as well as the transcript."
+ )
parser.add_argument(
"--fail-under",
type=float,
@@ -258,4 +262,5 @@ def parse_args(argv: list[str] | None = None) -> HarnessOptions:
fail_under=args.fail_under,
sandbox_flags_set=sandbox_flags_set,
infrastructure_retries=args.infra_retries,
+ verbose=args.verbose,
)
diff --git a/products/posthog_ai/eval_harness/harness/django_env.py b/products/posthog_ai/eval_harness/harness/django_env.py
index 0fb124ec318c..6c098ba5742c 100644
--- a/products/posthog_ai/eval_harness/harness/django_env.py
+++ b/products/posthog_ai/eval_harness/harness/django_env.py
@@ -7,13 +7,14 @@ from collections.abc import Generator, Iterator
from typing import Any
import django
+from django.conf import settings
logger = logging.getLogger(__name__)
_DJANGO_INITIALIZED = False
-def setup_django(*, debug: bool = True) -> None:
+def setup_django(*, debug: bool = True, keep_logging: bool = False) -> None:
"""Configure the environment and initialize Django for a harness run.
Sets the eval env flags (``DEBUG``/``TEST``/``IN_EVAL_TESTING``) and disables
@@ -32,6 +33,8 @@ def setup_django(*, debug: bool = True) -> None:
# Eval traces use an explicit regional client; local self-capture would poll flags with the development API key.
os.environ["SELF_CAPTURE"] = "0"
+ if keep_logging:
+ settings.LOGGING_CONFIG = None
django.setup()
from django.test.utils import setup_test_environment # noqa: PLC0415 — must import only after django.setup()
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index 3b1e090802d5..c8dcb31d2152 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -169,7 +169,7 @@ class SandboxedEvalHarness:
flags = ", ".join(self.options.sandbox_flags_set)
raise PreflightError(f"{flags}: no selected suite is sandboxed, so sandbox flags have no effect")
- reporter = ProgressReporter(total_suites=len(suites))
+ reporter = ProgressReporter(total_suites=len(suites), verbose=self.options.verbose)
reporter.print_run_header(
provider=self.options.provider,
agent_runtime=self.options.agent_runtime,
@@ -183,6 +183,7 @@ class SandboxedEvalHarness:
results: list[SuiteRunResult] | None = None
interrupted = False
try:
+ reporter.setup_started("check configuration")
validate_eval_env(self.options.agent_runtime, kinds=kinds, engine_env=self._engine.required_env())
if Infra.SANDBOX in required:
self.provider = build_provider(
@@ -193,7 +194,9 @@ class SandboxedEvalHarness:
self._validate_agent_options()
self.provider.preflight()
if Infra.PERSONHOG in required:
+ reporter.setup_started("build personhog")
ensure_personhog_binaries()
+ reporter.setup_started("start shared services and prepare demo data")
self._bootstrap(required)
results = asyncio.run(self._run_suites(suites, required, reporter))
except KeyboardInterrupt:
@@ -394,7 +397,8 @@ class SandboxedEvalHarness:
)
else:
logger.info("Running %d suite(s) without sandbox infrastructure", len(suites))
- results = await asyncio.gather(*(self._run_suite(suite, ctx) for suite in suites))
+ async with reporter.live_updates():
+ results = await asyncio.gather(*(self._run_suite(suite, ctx) for suite in suites))
return results
async def _sweep_notebook_kernels(self) -> None:
diff --git a/products/posthog_ai/eval_harness/harness/reporting.py b/products/posthog_ai/eval_harness/harness/reporting.py
index 859d169bd6d2..cc384d53447c 100644
--- a/products/posthog_ai/eval_harness/harness/reporting.py
+++ b/products/posthog_ai/eval_harness/harness/reporting.py
@@ -1,15 +1,20 @@
from __future__ import annotations
import os
+import time
import asyncio
import traceback
from collections import Counter, defaultdict
-from collections.abc import Sequence
-from dataclasses import dataclass
+from collections.abc import AsyncIterator, Sequence
+from contextlib import asynccontextmanager, suppress
+from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal
+from posthog.dataclasses import frozen
+
from ..engines.types import EvalSummary
+from .transcript import write_console
from .trial_stats import ScorerTrialStats
EVAL_RESULTS_JSONL = "eval_results.jsonl"
@@ -23,7 +28,7 @@ CaseStatus = Literal["ok", "timeout", "error"]
def _emit(text: str) -> None:
- print(text) # noqa: T201 — this module is the single owner of harness terminal output
+ write_console(text + "\n")
@dataclass
@@ -36,11 +41,36 @@ class SuiteRunResult:
duration_seconds: float = 0.0
+CasePhase = Literal["queued", "setup", "agent", "cleanup", "logs", "scoring"]
+
+
+@frozen(frozen=False)
+class _CaseProgress:
+ experiment: str
+ name: str
+ trial_index: int
+ started: float
+ phase_started: float
+ phase: CasePhase = "queued"
+ status: CaseStatus = "ok"
+ durations: dict[str, float] = field(default_factory=dict)
+
+ def transition(self, phase: CasePhase) -> None:
+ now = time.monotonic()
+ self.durations[self.phase] = self.durations.get(self.phase, 0.0) + now - self.phase_started
+ self.phase = phase
+ self.phase_started = now
+
+ def label(self) -> str:
+ return f"{self.experiment} :: {self.name} [trial {self.trial_index + 1}]"
+
+
class ProgressReporter:
"""Serializes harness output and renders the stable final summary."""
- def __init__(self, total_suites: int) -> None:
+ def __init__(self, total_suites: int, *, verbose: bool = False) -> None:
self._total_suites = total_suites
+ self._verbose = verbose
self._lock = asyncio.Lock()
self._finished_suites = 0
self._summaries: dict[str, EvalSummary] = {}
@@ -53,6 +83,89 @@ class ProgressReporter:
self._experiment_totals: dict[str, int] = {}
self._posthog_urls: dict[str, str] = {}
self._log_dirs: dict[str, Path] = {}
+ self._active_cases: dict[str, _CaseProgress] = {}
+ self._started = time.monotonic()
+
+ @asynccontextmanager
+ async def live_updates(self) -> AsyncIterator[None]:
+ async def update() -> None:
+ while True:
+ await asyncio.sleep(30)
+ await self.report_progress()
+
+ task = asyncio.create_task(update())
+ try:
+ yield
+ finally:
+ task.cancel()
+ with suppress(asyncio.CancelledError):
+ await task
+
+ async def report_progress(self) -> None:
+ async with self._lock:
+ counts: Counter[str] = Counter(case.phase for case in self._active_cases.values())
+ total = sum(self._experiment_totals.values())
+ finished = sum(self._case_counts.values())
+ states = ", ".join(
+ f"{phase}={counts[phase]}" for phase in ("queued", "setup", "agent", "cleanup", "logs", "scoring")
+ )
+ lines = [
+ f"PROGRESS executions {finished}/{total}; elapsed {_format_duration(time.monotonic() - self._started)}",
+ f" {states}",
+ ]
+ if self._active_cases:
+ oldest = min(self._active_cases.values(), key=lambda case: case.started)
+ lines.append(
+ f" oldest: {oldest.label()} ({oldest.phase}, {_format_duration(time.monotonic() - oldest.phase_started)})"
+ )
+ await asyncio.to_thread(_emit, "\n".join(lines))
+
+ async def case_started(self, experiment: str, name: str, trial_id: str, trial_index: int) -> dict[str, float]:
+ async with self._lock:
+ now = time.monotonic()
+ case = _CaseProgress(
+ experiment=experiment, name=name, trial_index=trial_index, started=now, phase_started=now
+ )
+ self._active_cases[trial_id] = case
+ await asyncio.to_thread(_emit, f"CASE START {case.label()} queued; id={trial_id}")
+ return case.durations
+
+ async def case_phase(self, trial_id: str, phase: CasePhase) -> None:
+ async with self._lock:
+ case = self._active_cases.get(trial_id)
+ if case is None or case.phase == phase:
+ return
+ case.transition(phase)
+ await asyncio.to_thread(_emit, f"CASE PHASE {case.label()} {phase}")
+
+ async def case_scored(self, trial_id: str, *, error: str | None = None) -> None:
+ async with self._lock:
+ case = self._active_cases.pop(trial_id, None)
+ if case is None:
+ return
+ case.transition(case.phase)
+ if error is not None:
+ self._case_statuses[case.experiment][case.status] -= 1
+ self._case_statuses[case.experiment]["error"] += 1
+ marker = (
+ "ERROR" if error is not None else {"ok": "DONE", "timeout": "TIMEOUT", "error": "ERROR"}[case.status]
+ )
+ await asyncio.to_thread(_emit, f"CASE {marker:<7} {case.label()} results ready")
+
+ async def finish_cases(self, trial_ids: Sequence[str]) -> None:
+ async with self._lock:
+ for trial_id in trial_ids:
+ case = self._active_cases.pop(trial_id, None)
+ if case is not None:
+ case.transition(case.phase)
+
+ async def finish_experiment(self, experiment: str) -> None:
+ await self.finish_cases(
+ [trial_id for trial_id, case in self._active_cases.items() if case.experiment == experiment]
+ )
+
+ def setup_started(self, phase: str) -> None:
+ _emit(f"SETUP START {phase}")
def print_run_header(
self,
@@ -72,19 +185,21 @@ class ProgressReporter:
f"Sandbox concurrency: {max_sandboxes}",
f"Trials per case: {trials}",
f"Case timeout: {case_timeout_seconds}s",
+ "Execution completion does not include scoring. The experiment ends when results are ready.",
+ "Use --verbose for detailed console logs. The transcript always keeps detailed logs.",
"",
]
_emit("\n".join(lines))
async def suite_started(self, suite_id: str) -> None:
async with self._lock:
- _emit(f"SUITE START {suite_id}")
+ await asyncio.to_thread(_emit, f"SUITE START {suite_id}")
async def experiment_started(self, experiment_name: str, planned_cases: int, log_dir: Path) -> None:
async with self._lock:
self._experiment_totals[experiment_name] = planned_cases
self._log_dirs[experiment_name] = log_dir
- _emit(f"EXPERIMENT START {experiment_name} [{planned_cases} cases]")
+ await asyncio.to_thread(_emit, f"EXPERIMENT START {experiment_name} [{planned_cases} cases]")
async def case_done(
self,
@@ -93,16 +208,32 @@ class ProgressReporter:
*,
duration_seconds: float,
status: CaseStatus = "ok",
+ trial_id: str | None = None,
+ error_type: str | None = None,
) -> None:
async with self._lock:
self._case_counts[experiment_name] += 1
self._case_durations[experiment_name] += duration_seconds
self._case_statuses[experiment_name][status] += 1
marker = {"ok": "DONE", "timeout": "TIMEOUT", "error": "ERROR"}[status]
+ detail = ""
+ case = self._active_cases.get(trial_id) if trial_id else None
+ if case is not None and trial_id is not None:
+ case_name = f"{case_name} [trial {case.trial_index + 1}]"
+ case.status = status
+ if status == "error":
+ detail = f"; {error_type or 'infrastructure error'}; last phase={case.phase}; id={trial_id}. Inspect the full run transcript and {self._log_dirs.get(experiment_name, 'agent logs')}."
+ case.transition(case.phase)
+ self._active_cases.pop(trial_id, None)
+ else:
+ marker = "READY" if status == "ok" else "TIMEOUT"
+ detail = "; execution complete; scoring pending"
+ case.transition("scoring")
total = self._experiment_totals.get(experiment_name)
progress = f"[{self._case_counts[experiment_name]}/{total}]" if total is not None else ""
- _emit(
- f"CASE {marker:<7} {experiment_name} :: {case_name} {progress} {_format_duration(duration_seconds)}"
+ await asyncio.to_thread(
+ _emit,
+ f"CASE {marker:<7} {experiment_name} :: {case_name} {progress} {_format_duration(duration_seconds)}{detail}",
)
async def case_setup_retry(
@@ -117,21 +248,28 @@ class ProgressReporter:
) -> None:
async with self._lock:
self._setup_retry_count += 1
- _emit(
+ await asyncio.to_thread(
+ _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."
+ 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
marker = "DONE" if result.status == "passed" else "CRASH"
- _emit(
+ await asyncio.to_thread(
+ _emit,
f"SUITE {marker:<5} {result.suite_id} "
f"[{self._finished_suites}/{self._total_suites} suites] "
- f"{_format_duration(result.duration_seconds)}"
+ f"{_format_duration(result.duration_seconds)}",
)
+ @staticmethod
+ def _append_summary(summary: EvalSummary) -> None:
+ with open(EVAL_RESULTS_JSONL, "a", encoding="utf-8") as f:
+ f.write(summary.as_json() + "\n")
+
async def record_summary(
self,
experiment_name: str,
@@ -145,11 +283,10 @@ class ProgressReporter:
self._trial_stats[experiment_name] = trial_stats
self._summary_error_counts[experiment_name] = error_count
if os.getenv("EXPORT_EVAL_RESULTS"):
- with open(EVAL_RESULTS_JSONL, "a", encoding="utf-8") as f:
- f.write(summary.as_json() + "\n")
+ await asyncio.to_thread(self._append_summary, summary)
total = self._experiment_totals.get(experiment_name)
progress = f"[{self._case_counts[experiment_name]}/{total} cases]" if total is not None else ""
- _emit(f"EXPERIMENT DONE {experiment_name} {progress}")
+ await asyncio.to_thread(_emit, f"EXPERIMENT DONE {experiment_name} {progress}")
async def record_posthog_evaluations_url(self, experiment_name: str, experiment_id: str) -> None:
async with self._lock:
@@ -279,7 +416,13 @@ class ProgressReporter:
lines.append(f"Suite: {result.suite_id}")
lines.append(f"Duration: {_format_duration(result.duration_seconds)}")
if result.error is not None:
- lines.append("".join(traceback.format_exception(result.error)).rstrip())
+ if self._verbose:
+ lines.append("".join(traceback.format_exception(result.error)).rstrip())
+ else:
+ lines.append(
+ f"{type(result.error).__name__}: {str(result.error).splitlines()[0] if str(result.error) else '(no message)'}"
+ )
+ lines.append("Inspect the full run transcript for the traceback.")
else:
lines.append("(no traceback captured)")
return lines
diff --git a/products/posthog_ai/eval_harness/harness/transcript.py b/products/posthog_ai/eval_harness/harness/transcript.py
index 4a61627e4dac..a60f7f0b756c 100644
--- a/products/posthog_ai/eval_harness/harness/transcript.py
+++ b/products/posthog_ai/eval_harness/harness/transcript.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import os
import sys
import uuid
+import logging
import threading
from collections.abc import Iterator
-from contextlib import contextmanager, redirect_stderr, redirect_stdout
+from contextlib import ExitStack, contextmanager, redirect_stderr, redirect_stdout
from datetime import UTC, datetime
from pathlib import Path
from typing import IO, TextIO
@@ -18,21 +20,23 @@ class _TranscriptSink:
def __init__(self, path: Path, stdout: TextIO) -> None:
self.path = path
self.stdout = stdout
- self.file: IO[str] = path.open("w", encoding="utf-8", buffering=1)
+ self.file: IO[str] = path.open("a", encoding="utf-8", buffering=1)
self.lock = threading.Lock()
self.finished = False
self.ends_with_newline = True
- def write(self, terminal: TextIO, text: str) -> int:
+ def write(self, terminal: TextIO, text: str, *, terminal_text: str | None = None) -> int:
with self.lock:
if self.finished:
return len(text)
self.file.write(text)
self.file.flush()
- terminal.write(text)
- terminal.flush()
if text:
self.ends_with_newline = text.endswith("\n")
+ console_text = text if terminal_text is None else terminal_text
+ if console_text:
+ terminal.write(console_text)
+ terminal.flush()
return len(text)
def flush(self, terminal: TextIO) -> None:
@@ -40,20 +44,48 @@ class _TranscriptSink:
if self.finished:
return
self.file.flush()
- terminal.flush()
+ terminal.flush()
def finish(self) -> None:
with self.lock:
if self.finished:
return
+ self.file.flush()
+ with self.path.open("rb") as saved:
+ if saved.seek(0, os.SEEK_END):
+ saved.seek(-1, os.SEEK_END)
+ self.ends_with_newline = saved.read(1) == b"\n"
prefix = "" if self.ends_with_newline else "\n"
line = f"{prefix}Full run transcript (stdout and stderr):\n{self.path}\n"
self.file.write(line)
self.file.flush()
- self.stdout.write(line)
- self.stdout.flush()
self.finished = True
self.file.close()
+ self.stdout.write(line)
+ self.stdout.flush()
+
+
+class _TranscriptLogHandler(logging.Handler):
+ def __init__(self, sink: _TranscriptSink, terminal: TextIO, verbose: bool) -> None:
+ super().__init__()
+ self._sink = sink
+ self._terminal = terminal
+ self._verbose = verbose
+
+ def emit(self, record: logging.LogRecord) -> None:
+ try:
+ detail = self.format(record) + "\n"
+ terminal_text = ""
+ if self._verbose:
+ terminal_text = detail
+ elif record.levelno >= logging.WARNING and record.name.startswith("products.posthog_ai.eval_harness"):
+ message = str(
+ record.msg.get("event", record.msg) if isinstance(record.msg, dict) else record.getMessage()
+ ).splitlines()
+ terminal_text = f"{record.levelname}: {record.name}: {message[0][:240] if message else ''}\n"
+ self._sink.write(self._terminal, detail, terminal_text=terminal_text)
+ except Exception:
+ self.handleError(record)
class _TeeStream:
@@ -62,6 +94,7 @@ class _TeeStream:
def __init__(self, terminal: TextIO, sink: _TranscriptSink) -> None:
self._terminal = terminal
self._sink = sink
+ self._verbose = True
@property
def encoding(self) -> str:
@@ -72,13 +105,16 @@ class _TeeStream:
return self._terminal.errors
def write(self, text: str) -> int:
+ return self._sink.write(self._terminal, text, terminal_text=None if self._verbose else "")
+
+ def write_console(self, text: str) -> int:
return self._sink.write(self._terminal, text)
def flush(self) -> None:
self._sink.flush(self._terminal)
def fileno(self) -> int:
- return self._terminal.fileno()
+ return self._sink.file.fileno()
def isatty(self) -> bool:
# Static output is readable in terminals, redirected logs, and agent tools.
@@ -88,6 +124,15 @@ class _TeeStream:
return True
+def write_console(text: str, *, stream: TextIO | None = None) -> None:
+ target = sys.stdout if stream is None else stream
+ if isinstance(target, _TeeStream):
+ target.write_console(text)
+ else:
+ target.write(text)
+ target.flush()
+
+
class RunTranscript:
"""Tee one harness invocation to disk and publish its path last."""
@@ -97,6 +142,9 @@ class RunTranscript:
self._stdout = _TeeStream(stdout, self._sink)
self._stderr = _TeeStream(stderr, self._sink)
+ def logging_handler(self, *, verbose: bool = False) -> logging.Handler:
+ return _TranscriptLogHandler(self._sink, self._stderr._terminal, verbose)
+
@classmethod
def create(cls, root: Path = HARNESS_LOGS_ROOT) -> RunTranscript:
root = root.resolve()
@@ -108,8 +156,39 @@ class RunTranscript:
return transcript
@contextmanager
- def capture(self) -> Iterator[None]:
- with redirect_stdout(self._stdout), redirect_stderr(self._stderr):
+ def _capture_file_descriptor(self, stream: _TeeStream, descriptor: int) -> Iterator[None]:
+ terminal = stream._terminal
+ try:
+ terminal_descriptor = terminal.fileno()
+ except (AttributeError, OSError, ValueError):
+ yield
+ return
+ terminal.flush()
+ with os.fdopen(os.dup(terminal_descriptor), "w", encoding=stream.encoding, buffering=1) as console:
+ saved_descriptor = os.dup(descriptor)
+ stream._terminal = console
+ if stream is self._stdout:
+ self._sink.stdout = console
+ try:
+ # Native child processes inherit file descriptors and bypass Python stream redirection.
+ os.dup2(self._sink.file.fileno(), descriptor)
+ yield
+ finally:
+ os.dup2(saved_descriptor, descriptor)
+ os.close(saved_descriptor)
+ stream._terminal = terminal
+ if stream is self._stdout:
+ self._sink.stdout = terminal
+
+ @contextmanager
+ def capture(self, *, verbose: bool = True) -> Iterator[None]:
+ self._stdout._verbose = verbose
+ self._stderr._verbose = verbose
+ with ExitStack() as stack:
+ stack.enter_context(self._capture_file_descriptor(self._stdout, 1))
+ stack.enter_context(self._capture_file_descriptor(self._stderr, 2))
+ stack.enter_context(redirect_stdout(self._stdout))
+ stack.enter_context(redirect_stderr(self._stderr))
yield
def finish(self) -> None:
diff --git a/products/posthog_ai/eval_harness/harness/trial_stats.py b/products/posthog_ai/eval_harness/harness/trial_stats.py
index 4cc1efb5e3b5..f35e3cda0b1e 100644
--- a/products/posthog_ai/eval_harness/harness/trial_stats.py
+++ b/products/posthog_ai/eval_harness/harness/trial_stats.py
@@ -54,13 +54,13 @@ class ScorerTrialStats:
def trial_stats(results: Sequence[CaseResult], *, trials: int) -> list[ScorerTrialStats]:
"""Aggregate scored trials per scorer for an experiment run with ``trials`` trials per case.
- Errored results (infra failures) and ``None`` scores (skipped scorers) are ignored.
+ Task failures and ``None`` scores are ignored. Successful scores survive other scorer failures.
"""
case_names = {result.input["name"] for result in results}
scores_by_scorer: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
skipped_by_scorer: dict[str, set[str]] = defaultdict(set)
for result in results:
- if result.error is not None:
+ if result.error is not None and result.error_kind == "task":
continue
case_name = result.input["name"]
for scorer, score in result.scores.items():
diff --git a/products/posthog_ai/eval_harness/log_sink.py b/products/posthog_ai/eval_harness/log_sink.py
index 7dbd043eb0cc..de8855e4bebb 100644
--- a/products/posthog_ai/eval_harness/log_sink.py
+++ b/products/posthog_ai/eval_harness/log_sink.py
@@ -140,7 +140,14 @@ def write_case_logs(
return paths
-def append_case_scores(case_dir: Path, case_name: str, scores: dict[str, Any], *, trial_id: str | None = None) -> None:
+def append_case_scores(
+ case_dir: Path,
+ case_name: str,
+ scores: dict[str, Any],
+ *,
+ trial_id: str | None = None,
+ phase_durations: dict[str, float] | None = None,
+) -> None:
slug = _case_log_slug(case_name, trial_id)
summary_path = case_dir / f"{slug}.summary.txt"
if not summary_path.exists():
@@ -148,6 +155,9 @@ def append_case_scores(case_dir: Path, case_name: str, scores: dict[str, Any], *
rendered = json.dumps(scores, indent=2, default=str)
with summary_path.open("a") as f:
+ if phase_durations:
+ f.write("=== phase_seconds ===\n")
+ f.write(json.dumps(phase_durations, indent=2) + "\n")
f.write("=== scores ===\n")
f.write(rendered)
f.write("\n")
diff --git a/products/posthog_ai/eval_harness/long_lived_subprocess.py b/products/posthog_ai/eval_harness/long_lived_subprocess.py
index 11baaecf3edc..5af9e7b8d322 100644
--- a/products/posthog_ai/eval_harness/long_lived_subprocess.py
+++ b/products/posthog_ai/eval_harness/long_lived_subprocess.py
@@ -202,7 +202,7 @@ class LongLivedSubprocessManager:
self._remove_pid_file(port)
return
- logger.warning("Stopping stale sandboxed eval %s process group %s on port %s", name, pgid, port)
+ logger.info("Stopping stale sandboxed eval %s process group %s on port %s", name, pgid, port)
self._terminate_process_group(pgid, port)
self._remove_pid_file(port)
@@ -354,7 +354,7 @@ class LongLivedSubprocessManager:
if proc.stdout is not None:
threading.Thread(target=pipe_to_logger, args=(proc.stdout, logging.INFO), daemon=True).start()
if proc.stderr is not None:
- threading.Thread(target=pipe_to_logger, args=(proc.stderr, logging.WARNING), daemon=True).start()
+ threading.Thread(target=pipe_to_logger, args=(proc.stderr, logging.INFO), daemon=True).start()
def _register(self, stop: StopCallback) -> None:
self._install_signal_handlers()
diff --git a/products/posthog_ai/eval_harness/one_shot.py b/products/posthog_ai/eval_harness/one_shot.py
index 8f3fd48fe628..900d1e60bbe1 100644
--- a/products/posthog_ai/eval_harness/one_shot.py
+++ b/products/posthog_ai/eval_harness/one_shot.py
@@ -67,12 +67,14 @@ class _OneShotEvalRun(_BaseEvalRun):
case = self.cases_by_name.get(input["name"]) or BaseEvalCase(name=input["name"], prompt=input.get("prompt", ""))
started = time.monotonic()
async with self.ctx.one_shot_slots:
+ await self._set_case_phase(hooks, "agent")
# Budget the task from slot acquisition, so time spent queued on the
# semaphore can never eat into a case's timeout.
output = await asyncio.wait_for(
self._task_fn(case, self.ctx),
timeout=self.ctx.per_case_timeout_seconds,
)
+ await self._set_case_phase(hooks, "logs")
output.setdefault("prompt", case.prompt)
await self._write_local_logs(
case, output, duration=time.monotonic() - started, trial_id=hooks.metadata.get("trial_id")
diff --git a/products/posthog_ai/eval_harness/runner.py b/products/posthog_ai/eval_harness/runner.py
index 72c0f1609302..a7563b8c41df 100644
--- a/products/posthog_ai/eval_harness/runner.py
+++ b/products/posthog_ai/eval_harness/runner.py
@@ -6,6 +6,7 @@ import time
import uuid
import asyncio
import logging
+from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING
from temporalio.client import WorkflowFailureError
@@ -16,6 +17,7 @@ from posthog.temporal.common.client import async_connect
from products.tasks.backend.facade.agents import (
CustomPromptSandboxContext,
MultiTurnSession,
+ TurnPollTimeout,
create_task_and_trigger,
poll_for_turn,
)
@@ -27,6 +29,8 @@ from .harness.providers import SandboxProviderStrategy
if TYPE_CHECKING:
from temporalio.client import WorkflowHandle
+ from products.tasks.backend.models import TaskRun
+
logger = logging.getLogger(__name__)
__all__ = ["run_eval_case"]
@@ -39,6 +43,7 @@ LINT_TITLE_RE = re.compile(r"\b(ruff|lint)\b")
WORKFLOW_COMPLETION_GRACE_SECONDS = 60
WORKFLOW_CANCELLATION_GRACE_SECONDS = 30
+CASE_FINALIZATION_RESERVE_SECONDS = 120
class AgentNeverRanError(RuntimeError):
@@ -117,11 +122,22 @@ class EvalCaseResult:
lines could not be split (malformed lines); scorers self-skip on it."""
+async def _report_cleanup(on_cleanup: Callable[[], Awaitable[None]] | None) -> None:
+ if on_cleanup is not None:
+ try:
+ await on_cleanup()
+ except Exception:
+ logger.warning("Could not report eval cleanup progress", exc_info=True)
+
+
async def run_eval_case(
case: SandboxedEvalCase,
context: CustomPromptSandboxContext,
*,
provider: SandboxProviderStrategy,
+ on_cleanup: Callable[[], Awaitable[None]] | None = None,
+ timeout_seconds: float | None = None,
+ on_poll_timeout: Callable[[TurnPollTimeout], None] | None = None,
) -> EvalCaseResult:
"""Run an eval case using the full Task -> temporal workflow -> log polling pipeline.
@@ -133,6 +149,11 @@ async def run_eval_case(
trace_id = str(uuid.uuid4())
logger.info("Starting eval case '%s' (trace=%s) with prompt: %.100s...", case.name, trace_id, case.prompt)
start = time.monotonic()
+ poll_deadline = (
+ start + timeout_seconds - min(CASE_FINALIZATION_RESERVE_SECONDS, timeout_seconds / 4)
+ if timeout_seconds is not None
+ else None
+ )
# The helpers mutate this in place as they provision, so the except/finally
# blocks can finish the workflow and clean up the task even when a turn
# raises before the helpers return.
@@ -142,19 +163,22 @@ async def run_eval_case(
# Eval is a test harness — direct use of internals (instead of MTS) is intentional:
# the agent isn't asked for structured JSON, and we need full_log for artifact parsing.
if case.followups:
- full_log, turn_logs = await _run_multi_turn_case(case, context, state)
+ full_log, turn_logs = await _run_multi_turn_case(
+ case, context, state, provider=provider, poll_deadline=poll_deadline
+ )
else:
- full_log, turn_logs = await _run_single_turn_case(case, context, state)
+ full_log, turn_logs = await _run_single_turn_case(
+ case, context, state, provider=provider, poll_deadline=poll_deadline
+ )
# Both helpers set task_id and handle before their first poll, so a clean
# return guarantees they are populated.
assert state.task_id is not None and state.handle is not None
- # Register the task so the end-of-run sweep stays scoped to this run's sandboxes.
- provider.register_task(str(state.task_id))
duration = time.monotonic() - start
logger.info("Eval case '%s' completed in %.1fs, log size=%d", case.name, duration, len(full_log))
artifacts = _parse_artifacts_from_log(full_log, duration, agent_finished=True)
completion_task = asyncio.create_task(_finish_workflow(state.handle, status="completed", reason=None))
+ await _report_cleanup(on_cleanup)
cleanup_confirmed = await asyncio.shield(completion_task)
if not cleanup_confirmed:
raise WorkflowCleanupError(
@@ -166,18 +190,24 @@ async def run_eval_case(
# coroutine; catch it explicitly so we can stop the workflow, then re-raise.
duration = time.monotonic() - start
logger.exception("Eval case '%s' failed after %.1fs: %s", case.name, duration, e)
+ if isinstance(e, TurnPollTimeout) and on_poll_timeout is not None:
+ on_poll_timeout(e)
cleanup_confirmed = False
- if completion_task is not None:
- # A case timeout can arrive while successful workflow cleanup is
- # already running. Let that bounded task settle instead of sending a
- # conflicting failed completion signal.
- cleanup_confirmed = await asyncio.shield(completion_task)
- elif state.handle is not None and not isinstance(e, WorkflowCleanupError):
- cleanup_confirmed = await asyncio.shield(
+ # A case timeout can arrive while successful workflow cleanup is
+ # already running. Let that bounded task settle instead of sending a
+ # conflicting failed completion signal.
+ if completion_task is None and state.handle is not None and not isinstance(e, WorkflowCleanupError):
+ completion_task = asyncio.create_task(
_finish_workflow(state.handle, status="failed", reason=f"eval case '{case.name}' failed: {e}")
)
- if state.handle is not None and not cleanup_confirmed:
- logger.warning("Eval workflow cleanup could not be confirmed for case '%s'", case.name)
+ try:
+ if not isinstance(e, asyncio.CancelledError):
+ await _report_cleanup(on_cleanup)
+ finally:
+ if completion_task is not None:
+ cleanup_confirmed = await asyncio.shield(completion_task)
+ if state.handle is not None and not cleanup_confirmed:
+ logger.warning("Eval workflow cleanup could not be confirmed for case '%s'", case.name)
raise
finally:
if state.task_id is not None:
@@ -201,33 +231,59 @@ class _CaseRunState:
async def _run_single_turn_case(
- case: SandboxedEvalCase, context: CustomPromptSandboxContext, state: _CaseRunState
+ case: SandboxedEvalCase,
+ context: CustomPromptSandboxContext,
+ state: _CaseRunState,
+ *,
+ provider: SandboxProviderStrategy,
+ poll_deadline: float | None = None,
) -> tuple[str, list[str] | None]:
"""The historical one-prompt path: create, poll once, return the full log."""
task_run = await create_task_and_trigger(case.prompt, context, step_name=case.name)
state.task_id = task_run.task_id
+ provider.register_task(str(task_run.task_id))
# Handle to the case's workflow so a timeout/error can shut the agent down.
client = await async_connect()
state.handle = client.get_workflow_handle(task_run.workflow_id)
- turn = await poll_for_turn(task_run, verbose=True, output_fn=lambda msg: logger.info("agent: %s", msg))
+ turn = await poll_for_turn(
+ task_run,
+ verbose=True,
+ output_fn=lambda msg: logger.info("agent: %s", msg),
+ workflow_handle=state.handle,
+ poll_deadline=poll_deadline,
+ )
logger.info("Eval case '%s' turn 1/1: last_message=%.200s", case.name, turn.last_message or "(none)")
return turn.full_log or "", None
async def _run_multi_turn_case(
- case: SandboxedEvalCase, context: CustomPromptSandboxContext, state: _CaseRunState
+ case: SandboxedEvalCase,
+ context: CustomPromptSandboxContext,
+ state: _CaseRunState,
+ *,
+ provider: SandboxProviderStrategy,
+ poll_deadline: float | None = None,
) -> tuple[str, list[str] | None]:
"""Run ``case.prompt`` plus every follow-up in one agent session.
``session.end()`` only signals completion, so the caller still finishes the
workflow through ``_finish_workflow`` like any other case.
"""
+
+ async def task_created(task_run: TaskRun) -> None:
+ state.task_id = task_run.task_id
+ provider.register_task(str(task_run.task_id))
+ client = await async_connect()
+ state.handle = client.get_workflow_handle(task_run.get_workflow_id(task_run.task_id, task_run.id))
+
session, _ = await MultiTurnSession.start_raw(
prompt=case.prompt,
context=context,
step_name=case.name,
verbose=True,
output_fn=lambda msg: logger.info("agent: %s", msg),
+ poll_deadline=poll_deadline,
+ on_task_run_created=task_created,
)
state.task_id = session.task.id
state.handle = session.workflow_handle
diff --git a/products/posthog_ai/eval_harness/test/test_braintrust_engine.py b/products/posthog_ai/eval_harness/test/test_braintrust_engine.py
index d33abc170a5f..219ef04cee40 100644
--- a/products/posthog_ai/eval_harness/test/test_braintrust_engine.py
+++ b/products/posthog_ai/eval_harness/test/test_braintrust_engine.py
@@ -2,10 +2,22 @@ from __future__ import annotations
from typing import Any
+import pytest
+from unittest.mock import MagicMock
+
+from braintrust import (
+ framework as bt_framework,
+ logger as bt_logger,
+)
from braintrust.framework import EvalResult, EvalResultWithSummary
-from braintrust.logger import ExperimentSummary, ScoreSummary
+from braintrust.logger import ExperimentSummary, ScoreSummary, SpanImpl
+from braintrust.span_identifier_v3 import SpanObjectTypeV3
+from braintrust.util import LazyValue
+from products.posthog_ai.eval_harness.engines import braintrust as engine_module
from products.posthog_ai.eval_harness.engines.braintrust import BraintrustEngine, _BraintrustCaseHooks
+from products.posthog_ai.eval_harness.engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec
+from products.posthog_ai.eval_harness.harness.trial_stats import trial_stats
def _summary(**overrides: Any) -> ExperimentSummary:
@@ -31,14 +43,23 @@ def test_translate_preserves_none_scores_and_stringifies_errors() -> None:
EvalResult(input={"name": "a"}, output={"v": 1}, scores={"acc": 1.0}, expected={"e": 1}, metadata={"m": 1}),
EvalResult(input={"name": "skip"}, output={}, scores={"acc": None}, metadata={}),
EvalResult(input={"name": "boom"}, output=None, scores={}, error=ValueError("infra boom")),
+ EvalResult(
+ input={"name": "scorer-error"},
+ output={},
+ scores={"other": 1.0},
+ metadata={"scorer_errors": {"acc": "Traceback: scorer failed"}},
+ ),
],
)
translated = BraintrustEngine()._translate(result)
- assert [r.scores for r in translated.results] == [{"acc": 1.0}, {"acc": None}, {}]
+ assert [r.scores for r in translated.results] == [{"acc": 1.0}, {"acc": None}, {}, {"other": 1.0}]
assert translated.results[2].error == "infra boom"
assert translated.results[0].error is None
+ assert translated.results[3].error == "Scorer errors: acc"
+ assert translated.results[3].error_kind == "scorer"
+ assert {stats.name: stats.mean for stats in trial_stats(translated.results, trials=1)} == {"acc": 1.0, "other": 1.0}
assert translated.results[0].input == {"name": "a"}
assert translated.results[0].expected == {"e": 1}
assert translated.results[0].metadata == {"m": 1}
@@ -47,6 +68,96 @@ def test_translate_preserves_none_scores_and_stringifies_errors() -> None:
assert translated.summary.scores["acc"].score == 0.5
[email protected]("scorer_fails", [False, True])
[email protected]("metadata_fails", [False, True])
+async def test_public_trial_metadata_keeps_final_scoring_durations(
+ monkeypatch: pytest.MonkeyPatch, scorer_fails: bool, metadata_fails: bool
+) -> None:
+ logger = MagicMock()
+ monkeypatch.setattr(engine_module, "logger", logger)
+ events: list[dict[str, Any]] = []
+ flushed: list[list[dict[str, Any]]] = []
+ background = MagicMock()
+ background.log.side_effect = lambda event: events.append(event.get())
+ updating_metadata = False
+
+ def flush() -> None:
+ if updating_metadata and metadata_fails:
+ raise ConnectionError("metadata upload failed")
+ flushed.append(list(events))
+
+ background.flush.side_effect = flush
+ monkeypatch.setattr(bt_logger._state, "global_bg_logger", lambda: background)
+
+ def start_span(name: str, **kwargs: Any) -> SpanImpl:
+ return SpanImpl(
+ parent_object_type=SpanObjectTypeV3.EXPERIMENT,
+ parent_object_id=LazyValue(lambda: "example-experiment", use_mutex=False),
+ parent_compute_object_metadata_args=None,
+ parent_span_ids=None,
+ name=name,
+ event=kwargs,
+ )
+
+ experiment = MagicMock(dataset=None)
+ experiment.start_span.side_effect = start_span
+ experiment.summarize.return_value = _summary()
+ experiment.flush.side_effect = background.flush
+ monkeypatch.setattr(bt_framework, "init_experiment", lambda **_: experiment)
+ trials = 0
+
+ async def task(input: dict[str, Any], hooks: CaseHooks) -> dict[str, Any]:
+ nonlocal trials
+ hooks.metadata["trial_id"] = f"trial-{trials}"
+ trials += 1
+ hooks.metadata["phase_durations"] = {"agent": 2.0}
+ return {}
+
+ async def score(output: Any) -> float:
+ if scorer_fails:
+ raise ValueError("scorer failed")
+ return 1.0
+
+ async def on_results(result: ExperimentResult) -> None:
+ nonlocal updating_metadata
+ assert flushed
+ updating_metadata = True
+ for case in result.results:
+ assert (case.error is not None) is scorer_fails
+ case.metadata["phase_durations"]["scoring"] = 3.0
+
+ result = await BraintrustEngine().run_experiment(
+ ExperimentSpec(
+ project_name="example",
+ cases=[CaseSpec(input={"name": "case"})],
+ task=task,
+ scorers=[score],
+ trial_count=2,
+ is_public=True,
+ no_send_logs=False,
+ metadata={},
+ on_results=on_results,
+ )
+ )
+
+ rows: dict[str, dict[str, Any]] = {}
+ for event in flushed[-1]:
+ if event.get("span_attributes", {}).get("name") == "eval":
+ rows[event["id"]] = event
+ elif event["id"] in rows:
+ rows[event["id"]].update(event)
+ assert len(rows) == 2
+ assert {row["metadata"]["trial_id"] for row in rows.values()} == {"trial-0", "trial-1"}
+ if metadata_fails:
+ logger.warning.assert_called_once_with(
+ "Could not upload final trial metadata; completed eval results remain available", exc_info=True
+ )
+ else:
+ assert all(row["metadata"]["phase_durations"] == {"agent": 2.0, "scoring": 3.0} for row in rows.values())
+ assert all(case.metadata["phase_durations"]["scoring"] == 3.0 for case in result.results)
+
+
def test_translate_summary_raw_round_trips_as_json() -> None:
summary = _summary()
translated = BraintrustEngine()._translate(EvalResultWithSummary(summary=summary, results=[]))
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.py
index 12601bf59f24..cee656be28b3 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
@@ -30,6 +30,7 @@ from products.posthog_ai.eval_harness.harness.context import EvalContext
from products.posthog_ai.eval_harness.harness.lifecycle import SandboxedEvalHarness
from products.posthog_ai.eval_harness.harness.trial_stats import ScorerTrialStats
from products.posthog_ai.eval_harness.one_shot import _OneShotEvalRun
+from products.tasks.backend.facade.agents import TurnPollTimeout
class _StubReporter:
@@ -39,7 +40,30 @@ class _StubReporter:
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:
+ async def case_started(self, experiment: str, name: str, trial_id: str, trial_index: int) -> dict[str, float]:
+ return {}
+
+ async def case_phase(self, trial_id: str, phase: str) -> None:
+ pass
+
+ async def case_scored(self, trial_id: str, *, error: str | None = None) -> None:
+ pass
+
+ async def finish_cases(self, trial_ids: Sequence[str]) -> None:
+ pass
+
+ async def finish_experiment(self, experiment: str) -> None:
+ pass
+
+ async def case_done(
+ self,
+ experiment_name: str,
+ case_name: str,
+ duration_seconds: float,
+ status: str,
+ trial_id: str | None = None,
+ error_type: str | None = None,
+ ) -> None:
self.done.append((case_name, status))
async def experiment_started(self, experiment_name: str, planned_cases: int, log_dir: Path) -> None:
@@ -123,28 +147,56 @@ def test_execute_case_backfills_prompt_and_writes_logs(tmp_path: Path, monkeypat
assert (tmp_path / "c1.summary.txt").exists()
-def test_task_scores_timeout_as_output_not_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("poll_timeout", [False, True, "cleanup_cancelled"])
+def test_task_scores_timeout_as_output_not_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, poll_timeout: bool | str
+) -> None:
async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:
- await asyncio.sleep(30)
+ if poll_timeout:
+ error = TurnPollTimeout(
+ "Poll budget expired",
+ stage="no_turn_output",
+ elapsed=5,
+ stale_seconds=5,
+ total_lines=0,
+ turn_relevant_lines=0,
+ )
+ if poll_timeout == "cleanup_cancelled":
+ hooks.metadata["poll_timeout"] = error.diagnostics()
+ raise TimeoutError
+ raise error
+ await asyncio.Event().wait()
return {}
ctx = _build_ctx(timeout_seconds=1)
run = _build_run(tmp_path, monkeypatch, ctx, task)
- output = asyncio.run(run._task({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()))
-
- assert output == {"timeout": True, "error": "case timeout after 1s"}
+ hooks = NullCaseHooks()
+ output = asyncio.run(run._task({"name": "c1", "prompt": "the prompt"}, hooks=hooks))
+
+ assert output is not None and output["timeout"] is True
+ assert output["error"] == "case timeout after 1s"
+ saved = json.loads((tmp_path / f"c1.trial-{hooks.metadata['trial_id']}.artifacts.json").read_text())
+ assert saved == output
+ if poll_timeout:
+ assert hooks.metadata["poll_timeout"]["poll_timeout_stage"] == "no_turn_output"
+ assert output["poll_timeout"] == hooks.metadata["poll_timeout"]
+ if poll_timeout is True:
+ assert output["stderr"] == "Poll budget expired"
assert ctx.reporter.done == [("c1", "timeout")] # type: ignore[attr-defined]
-def test_task_reraises_infra_errors(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("error_type", [ValueError, asyncio.CancelledError])
+def test_task_reraises_infra_errors(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, error_type: type[BaseException]
+) -> None:
async def task(case: BaseEvalCase, ctx: EvalContext) -> dict[str, Any]:
- raise ValueError("boom")
+ raise error_type("boom")
ctx = _build_ctx()
run = _build_run(tmp_path, monkeypatch, ctx, task)
- with pytest.raises(ValueError):
+ with pytest.raises(error_type):
asyncio.run(run._task({"name": "c1", "prompt": "the prompt"}, hooks=NullCaseHooks()))
- assert ctx.reporter.done == [("c1", "error")] # type: ignore[attr-defined]
+ assert ctx.reporter.done == ([] if error_type is asyncio.CancelledError else [("c1", "error")]) # type: ignore[attr-defined]
def test_one_shot_slots_bound_concurrency(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
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 5570724175a5..ac78a0b000b4 100644
--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness.py
@@ -4,9 +4,10 @@ import os
import sys
import asyncio
import subprocess
+from collections.abc import Awaitable, Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import Literal
+from typing import Literal, cast
from uuid import UUID
import pytest
@@ -30,7 +31,7 @@ from products.tasks.backend.constants import (
WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,
WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,
)
-from products.tasks.backend.facade.agents import TurnPollResult
+from products.tasks.backend.facade.agents import MultiTurnSession, TurnPollResult, TurnPollTimeout
from products.tasks.backend.facade.contracts import AgentTaskRunDTO
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.utils import mcp_exec_skills_env_vars
@@ -266,27 +267,39 @@ async def test_eval_run_preserves_bundled_skills_unless_exec_is_selected(
@pytest.mark.asyncio
-async def test_success_waits_for_workflow_cleanup_before_returning(monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("reporting_error", [None, BrokenPipeError("closed output")])
[email protected]("budget", [None, 900, 20])
+async def test_success_waits_for_workflow_cleanup_before_returning(
+ monkeypatch: pytest.MonkeyPatch, budget: int | None, reporting_error: Exception | None
+) -> None:
+ monkeypatch.setattr(runner, "time", SimpleNamespace(monotonic=lambda: 1000.0))
handle = _FakeWorkflowHandle(complete_on_signal=False)
provider = _Provider()
- _patch_runner_boundaries(
- monkeypatch,
- handle,
- AsyncMock(
- return_value=TurnPollResult(
- last_message="done", full_log='{"notification": {}}', total_lines=0, printed_lines=0
- )
- ),
+ poll = AsyncMock(
+ return_value=TurnPollResult(
+ last_message="done", full_log='{"notification": {}}', total_lines=0, printed_lines=0
+ )
)
+ _patch_runner_boundaries(monkeypatch, handle, poll)
+
+ cleanup_started = asyncio.Event()
+
+ async def on_cleanup() -> None:
+ cleanup_started.set()
+ if reporting_error is not None:
+ raise reporting_error
case_task = asyncio.create_task(
runner.run_eval_case(
SandboxedEvalCase(name="case", prompt="prompt"),
MagicMock(),
provider=provider,
+ on_cleanup=on_cleanup,
+ timeout_seconds=budget,
)
)
await asyncio.wait_for(handle.signal_received.wait(), timeout=1)
+ assert cleanup_started.is_set()
assert not case_task.done()
handle.terminal.set()
@@ -296,9 +309,17 @@ async def test_success_waits_for_workflow_cleanup_before_returning(monkeypatch:
assert handle.signals == [["completed", None]]
assert provider.cleaned_task_ids == [str(_TASK_ID)]
+ expected = 1000 + budget - min(120, budget / 4) if budget is not None else None
+ assert poll.await_args is not None
+ assert poll.await_args.kwargs["poll_deadline"] == expected
+ assert poll.await_args.kwargs["workflow_handle"] is handle
+
@pytest.mark.asyncio
-async def test_poll_failure_is_preserved_after_workflow_cleanup(monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("reporting_error", [None, BrokenPipeError("closed output")])
+async def test_poll_failure_is_preserved_after_workflow_cleanup(
+ monkeypatch: pytest.MonkeyPatch, reporting_error: Exception | None
+) -> None:
handle = _FakeWorkflowHandle(complete_on_signal=True)
provider = _Provider()
_patch_runner_boundaries(monkeypatch, handle, AsyncMock(side_effect=RuntimeError("poll failed")))
@@ -308,6 +329,7 @@ async def test_poll_failure_is_preserved_after_workflow_cleanup(monkeypatch: pyt
SandboxedEvalCase(name="case", prompt="prompt"),
MagicMock(),
provider=provider,
+ on_cleanup=AsyncMock(side_effect=reporting_error),
)
assert handle.signals[0][0] == "failed"
@@ -315,7 +337,55 @@ async def test_poll_failure_is_preserved_after_workflow_cleanup(monkeypatch: pyt
@pytest.mark.asyncio
-async def test_cancellation_finishes_workflow_before_propagating(monkeypatch: pytest.MonkeyPatch) -> None:
[email protected]("poll_failed", [False, True])
+async def test_cancellation_during_progress_waits_for_workflow_cleanup(
+ monkeypatch: pytest.MonkeyPatch, poll_failed: bool
+) -> None:
+ handle = _FakeWorkflowHandle(complete_on_signal=False)
+ provider = _Provider()
+ _patch_runner_boundaries(
+ monkeypatch,
+ handle,
+ AsyncMock(
+ side_effect=RuntimeError("poll failed") if poll_failed else None,
+ return_value=TurnPollResult(last_message="done", full_log="", total_lines=0, printed_lines=0),
+ ),
+ )
+ progress_started = asyncio.Event()
+ progress_release = asyncio.Event()
+
+ async def on_cleanup() -> None:
+ progress_started.set()
+ await progress_release.wait()
+
+ case_task = asyncio.create_task(
+ runner.run_eval_case(
+ SandboxedEvalCase(name="case", prompt="prompt"),
+ MagicMock(),
+ provider=provider,
+ on_cleanup=on_cleanup,
+ )
+ )
+ try:
+ await asyncio.wait_for(progress_started.wait(), timeout=1)
+ case_task.cancel()
+ await asyncio.wait_for(handle.signal_received.wait(), timeout=1)
+ assert not case_task.done()
+ handle.terminal.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(case_task, timeout=1)
+ finally:
+ progress_release.set()
+ handle.terminal.set()
+ assert handle.signals[0][0] == ("failed" if poll_failed else "completed")
+ assert provider.cleaned_task_ids == [str(_TASK_ID)]
+
+
[email protected]("reporting_error", [None, BrokenPipeError("closed output")])
+async def test_cancellation_finishes_workflow_before_propagating(
+ monkeypatch: pytest.MonkeyPatch, reporting_error: Exception | None
+) -> None:
poll_started = asyncio.Event()
never_finishes = asyncio.Event()
@@ -331,6 +401,7 @@ async def test_cancellation_finishes_workflow_before_propagating(monkeypatch: py
SandboxedEvalCase(name="case", prompt="prompt"),
MagicMock(),
provider=provider,
+ on_cleanup=AsyncMock(side_effect=reporting_error),
)
)
await asyncio.wait_for(poll_started.wait(), timeout=1)
@@ -445,3 +516,57 @@ class TestSliceTurnLogs:
def test_a_malformed_line_disables_slicing(self) -> None:
assert runner._slice_turn_logs('{"line": 0}\nnot json\n{"line": 1}', [1, 3]) is None
+
+
[email protected]("initial_failure", [False, True])
[email protected]("cleanup_cancelled", [False, True])
+async def test_multi_turn_timeout_retains_cleanup_state(
+ monkeypatch: pytest.MonkeyPatch, initial_failure: bool, cleanup_cancelled: bool
+) -> None:
+ handle = _FakeWorkflowHandle(complete_on_signal=not cleanup_cancelled)
+ provider = _Provider()
+ error = TurnPollTimeout(
+ "Poll budget expired",
+ stage="no_turn_output",
+ elapsed=10,
+ stale_seconds=10,
+ total_lines=0,
+ turn_relevant_lines=0,
+ )
+ monkeypatch.setattr(runner, "time", SimpleNamespace(monotonic=lambda: 1000.0))
+ monkeypatch.setattr(
+ runner, "async_connect", AsyncMock(return_value=SimpleNamespace(get_workflow_handle=lambda _: handle))
+ )
+ task_run = MagicMock(task_id=_TASK_ID)
+ session = MagicMock(task=SimpleNamespace(id=_TASK_ID), workflow_handle=handle, log_lines_seen=0)
+ session.send_followup_raw = AsyncMock(side_effect=error)
+
+ async def start(**kwargs: object) -> tuple[MultiTurnSession, str]:
+ assert kwargs["poll_deadline"] == 1780.0
+ callback = cast(Callable[[object], Awaitable[None]], kwargs["on_task_run_created"])
+ await callback(task_run)
+ if initial_failure:
+ raise error
+ return session, "done"
+
+ monkeypatch.setattr(runner.MultiTurnSession, "start_raw", start)
+ diagnostics: dict[str, object] = {}
+ case_task = asyncio.create_task(
+ runner.run_eval_case(
+ SandboxedEvalCase(name="case", prompt="prompt", followups=["followup"]),
+ MagicMock(),
+ provider=provider,
+ timeout_seconds=900,
+ on_poll_timeout=lambda error: diagnostics.update(error.diagnostics()),
+ )
+ )
+ await asyncio.wait_for(handle.signal_received.wait(), timeout=1)
+ assert diagnostics == error.diagnostics()
+ if cleanup_cancelled:
+ case_task.cancel()
+ handle.terminal.set()
+ with pytest.raises(asyncio.CancelledError if cleanup_cancelled else TurnPollTimeout):
+ await case_task
+ assert handle.signals[0][0] == "failed"
+ assert provider.cleaned_task_ids == [str(_TASK_ID)]
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.py
index d3d1a3c92546..a670c5267606 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
@@ -27,3 +27,8 @@ def test_infrastructure_retry_budget(argv: list[str], expected: int | None) -> N
assert error.value.code == 2
else:
assert parse_args(argv).infrastructure_retries == expected
+
+
[email protected]("argv,verbose", [([], False), (["--verbose"], True)])
+def test_console_output_detail(argv: list[str], verbose: bool) -> None:
+ assert parse_args(argv).verbose is verbose
diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py
index 6efb4d20cfc9..2871ab102be9 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
@@ -1,13 +1,18 @@
from __future__ import annotations
+import io
+import os
import sys
import json
import asyncio
+import logging
+import warnings
+import subprocess
from collections.abc import Iterator
from contextlib import contextmanager
from functools import partial
from pathlib import Path
-from threading import get_ident
+from threading import Event, Thread, get_ident
from typing import Any, Literal
import pytest
@@ -32,6 +37,7 @@ from products.posthog_ai.eval_harness.engines.types import (
ExperimentResult,
NullCaseHooks,
)
+from products.posthog_ai.eval_harness.harness import reporting
from products.posthog_ai.eval_harness.harness.cli import SkillDelivery
from products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResult
from products.posthog_ai.eval_harness.harness.transcript import RunTranscript
@@ -68,6 +74,45 @@ def test_run_transcript_captures_both_streams_and_prints_its_path_last(
assert (tmp_path / "latest.log").resolve() == transcript.path
[email protected]("verbose", [False, True])
[email protected]("blocked_operation", ["write", "flush"])
+def test_logging_continues_while_progress_output_is_blocked(
+ tmp_path: Path, verbose: bool, blocked_operation: str
+) -> None:
+ blocked = Event()
+ release = Event()
+ logged = Event()
+ stdout = MagicMock(wraps=io.StringIO())
+
+ def wait_for_release(*_args: object) -> None:
+ blocked.set()
+ release.wait()
+
+ getattr(stdout, blocked_operation).side_effect = wait_for_release
+ transcript = RunTranscript(tmp_path / "run.log", stdout, io.StringIO())
+ handler = transcript.logging_handler(verbose=verbose)
+
+ def log() -> None:
+ handler.handle(logging.LogRecord("eval", logging.INFO, "", 0, "poll continues", (), None))
+ logged.set()
+
+ progress = Thread(target=transcript._stdout.write_console, args=("CASE PHASE agent\n",))
+ logging_worker = Thread(target=log)
+ progress.start()
+ try:
+ assert blocked.wait(timeout=5)
+ logging_worker.start()
+ assert logged.wait(timeout=5)
+ assert "poll continues" in transcript.path.read_text()
+ finally:
+ release.set()
+ progress.join(timeout=5)
+ if logging_worker.ident is not None:
+ logging_worker.join(timeout=5)
+ handler.close()
+ transcript.finish()
+
+
@pytest.mark.asyncio
async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
@@ -580,12 +625,53 @@ async def test_case_setup_retries_use_fresh_data_and_report_one_outcome(
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 output.count("CASE READY" 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_workers
[email protected]("agent_error", [None, RuntimeError("agent failed"), asyncio.CancelledError()])
[email protected]("reporting_phase", ["agent", "cleanup"])
+async def test_kernel_cleanup_preserves_case_outcome_when_progress_fails(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, agent_error: BaseException | None, reporting_phase: str
+) -> None:
+ monkeypatch.setattr(base, "build_case_dir", MagicMock(return_value=tmp_path))
+ ctx = MagicMock(posthog_client=None, case_filter=None, sandbox_slots=asyncio.Semaphore(1))
+ ctx.per_case_timeout_seconds = 30
+ ctx.provider_strategy.keeps_sandboxes.return_value = False
+ case = SandboxedEvalCase(name="case", prompt="Run the task")
+ run = base._SandboxedEvalRun("cleanup", [case], [], ctx, is_public=False, no_send_logs=True)
+ context = CustomPromptSandboxContext(team_id=1, user_id=2)
+ monkeypatch.setattr(
+ run, "_prepare_case", AsyncMock(return_value=base._SandboxedCaseSetup(context=context, seed={}))
+ )
+
+ async def report_phase(_trial_id: str, phase: str) -> None:
+ if phase == reporting_phase:
+ raise BrokenPipeError("closed output")
+
+ ctx.reporter.case_phase = AsyncMock(side_effect=report_phase)
+ hooks = NullCaseHooks()
+ hooks.metadata["trial_id"] = "trial"
+ result = base.EvalCaseResult(artifacts=AgentArtifacts(exit_code=0))
+ monkeypatch.setattr(base, "run_eval_case", AsyncMock(return_value=result, side_effect=agent_error))
+ cleanup = AsyncMock()
+ monkeypatch.setattr(base, "reclaim_kernels", cleanup)
+
+ if agent_error is None:
+ actual, _ = await run._run_sandbox_window(case, case, hooks)
+ assert actual is result
+ else:
+ with pytest.raises(type(agent_error)) as raised:
+ await run._run_sandbox_window(case, case, hooks)
+ assert raised.value is agent_error
+
+ cleanup.assert_awaited_once_with(1, keep=False)
+ assert ctx.sandbox_slots._value == 1
+
+
@pytest.mark.asyncio
async def test_sandboxed_trials_keep_separate_logs_and_trace_roots(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
@@ -640,3 +726,172 @@ async def test_sandboxed_trials_keep_separate_logs_and_trace_roots(
if call.kwargs.get("event") == "$ai_trace"
]
assert [root["$ai_trace_id"] for root in roots] == ["trace-2", "trace-1", "trace-0"]
+
+
[email protected]("verbose", [False, True])
[email protected]("structured", [False, True])
+def test_console_detail_does_not_remove_transcript_logs(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str], verbose: bool, structured: bool
+) -> None:
+ transcript = RunTranscript.create(tmp_path)
+ handler = transcript.logging_handler(verbose=verbose)
+ handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
+ info = logging.LogRecord(
+ "products.posthog_ai.eval_harness.example",
+ logging.INFO,
+ "",
+ 0,
+ {"event": "agent detail"} if structured else "agent detail",
+ (),
+ None,
+ )
+ try:
+ raise ValueError("service unavailable")
+ except ValueError:
+ error = logging.LogRecord(
+ "products.posthog_ai.eval_harness.example",
+ logging.ERROR,
+ "",
+ 0,
+ {"event": "case error"} if structured else "case error",
+ (),
+ sys.exc_info(),
+ )
+ dependency_warning = logging.LogRecord("dependency", logging.WARNING, "", 0, "optional dependency detail", (), None)
+ dependency_error = logging.LogRecord("dependency", logging.ERROR, "", 0, "optional service detail", (), None)
+ runner_warning = logging.LogRecord(
+ "products.posthog_ai.eval_harness.example", logging.WARNING, "", 0, "Setup will retry", (), None
+ )
+ with transcript.capture(verbose=verbose), warnings.catch_warnings():
+ warnings.simplefilter("always")
+ warnings.warn("optional Python dependency detail", UserWarning, stacklevel=1)
+ sys.stdout.write("SDK progress detail\n")
+ reporting._emit("CASE PHASE example :: case [trial 1] agent")
+ handler.handle(dependency_warning)
+ handler.handle(dependency_error)
+ handler.handle(runner_warning)
+ handler.handle(info)
+ handler.handle(error)
+ handler.close()
+ transcript.finish()
+ output = capsys.readouterr()
+ saved = transcript.path.read_text()
+ assert "CASE PHASE example :: case [trial 1] agent" in output.out
+ assert "Setup will retry" in output.err
+ assert "optional service detail" in saved
+ assert ("optional service detail" in output.err) is verbose
+ assert "optional dependency detail" in saved
+ assert "optional Python dependency detail" in saved
+ assert "SDK progress detail" in saved
+ assert ("SDK progress detail" in output.out) is verbose
+ assert ("optional Python dependency detail" in output.err) is verbose
+ assert ("optional dependency detail" in output.err) is verbose
+ assert "agent detail" in saved
+ assert "ValueError: service unavailable" in saved
+ assert "case error" in output.err
+ assert ("agent detail" in output.err) is verbose
+ assert ("Traceback" in output.err) is verbose
+ assert output.out.splitlines()[-1] == saved.splitlines()[-1] == str(transcript.path)
+
+
[email protected]("verbose", [False, True])
+def test_native_child_output_stays_in_transcript_and_file_descriptors_restore(
+ tmp_path: Path, capfd: pytest.CaptureFixture[str], verbose: bool
+) -> None:
+ transcript = RunTranscript.create(tmp_path)
+ with transcript.capture(verbose=verbose):
+ subprocess.run(
+ [sys.executable, "-c", "import os; os.write(1, b'native stdout\\n'); os.write(2, b'native stderr')"],
+ check=True,
+ )
+ reporting._emit("SETUP START example service")
+ os.write(1, b"descriptors restored\n")
+ transcript.finish()
+ output = capfd.readouterr()
+ saved = transcript.path.read_text()
+ assert "native stdout" not in output.out
+ assert "native stderr" not in output.err
+ assert "SETUP START example service" in output.out
+ assert "descriptors restored" in output.out
+ assert "native stdout\nnative stderr" in saved
+ assert saved.count("SETUP START example service") == 1
+ assert output.out.splitlines()[-1] == saved.splitlines()[-1] == str(transcript.path)
+
+
[email protected]("scoring_error", [None, "scorer failed"])
+async def test_progress_tracks_trials_and_keeps_scoring_distinct(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str], scoring_error: str | None
+) -> None:
+ loop_thread = get_ident()
+ emit = reporting._emit
+
+ def worker_emit(text: str) -> None:
+ assert get_ident() != loop_thread
+ emit(text)
+
+ monkeypatch.setattr(reporting, "_emit", worker_emit)
+ now = [10.0]
+ monkeypatch.setattr(reporting.time, "monotonic", lambda: now[0])
+ reporter = ProgressReporter(total_suites=1)
+ await reporter.experiment_started("suite", 3, tmp_path)
+ phases = await reporter.case_started("suite", "same-case", "trial-1", 0)
+ await reporter.case_started("suite", "same-case", "trial-2", 1)
+ now[0] = 15.0
+ await reporter.case_phase("trial-1", "setup")
+ now[0] = 25.0
+ await reporter.case_phase("trial-1", "agent")
+ now[0] = 45.0
+ await reporter.case_done("suite", "same-case", duration_seconds=35, trial_id="trial-1")
+ await reporter.report_progress()
+ output = capsys.readouterr().out
+ assert "CASE READY" in output
+ assert "scoring pending" in output
+ assert "executions 1/3" in output
+ assert "queued=1" in output and "scoring=1" in output
+ assert "oldest: suite :: same-case [trial 1] (scoring" in output
+ assert phases == {"queued": 5.0, "setup": 10.0, "agent": 20.0}
+ now[0] = 50.0
+ await reporter.case_scored("trial-1", error=scoring_error)
+ assert ("CASE ERROR" if scoring_error else "CASE DONE") in capsys.readouterr().out
+ assert reporter.has_case_errors() is (scoring_error is not None)
+ await reporter.finish_experiment("suite")
+ await reporter.report_progress()
+ assert "scoring=0" in capsys.readouterr().out
+ assert phases["scoring"] == 5.0
+
+
+async def test_periodic_progress_stops_with_its_context(monkeypatch: pytest.MonkeyPatch) -> None:
+ loop = asyncio.get_running_loop()
+ reporter = ProgressReporter(total_suites=1)
+ sleeping = asyncio.Event()
+ release = asyncio.Event()
+ emitted = asyncio.Event()
+ cancelled = asyncio.Event()
+ lines: list[str] = []
+
+ async def pause(delay: float) -> None:
+ assert delay == 30
+ sleeping.set()
+ try:
+ await release.wait()
+ release.clear()
+ except asyncio.CancelledError:
+ cancelled.set()
+ raise
+
+ def capture(text: str) -> None:
+ lines.append(text)
+ loop.call_soon_threadsafe(emitted.set)
+
+ monkeypatch.setattr(reporting.asyncio, "sleep", pause)
+ monkeypatch.setattr(reporting, "_emit", capture)
+ async with reporter.live_updates():
+ await sleeping.wait()
+ sleeping.clear()
+ release.set()
+ await emitted.wait()
+ await sleeping.wait()
+ assert len(lines) == 1 and lines[0].startswith("PROGRESS")
+ assert cancelled.is_set()
diff --git a/products/posthog_ai/eval_harness/test/test_trial_stats.py b/products/posthog_ai/eval_harness/test/test_trial_stats.py
index 119adaf1ed89..6fc12ce9ea11 100644
--- a/products/posthog_ai/eval_harness/test/test_trial_stats.py
+++ b/products/posthog_ai/eval_harness/test/test_trial_stats.py
@@ -53,6 +53,24 @@ EXPECTED = ScorerTrialStats(
@pytest.mark.parametrize(
"results, trials, expected",
[
+ pytest.param(
+ [
+ replace(result, error="Scorer errors: other", error_kind="scorer")
+ for result in _trials({"stable": [1, 1, 1], "flaky": [1, 0, 1]})
+ ],
+ 3,
+ EXPECTED,
+ id="successful_scores_survive_other_scorer_failures",
+ ),
+ pytest.param(
+ [
+ *_trials({"stable": [1, 1, 1], "flaky": [1, 0, 1]}),
+ replace(_result("stable", 0), error="task failed"),
+ ],
+ 3,
+ EXPECTED,
+ id="task_errors_remain_excluded_even_with_partial_scores",
+ ),
pytest.param(
_trials({"stable": [1, 1, 1], "flaky": [1, 0, 1]}),
3,
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index d20b8783f04f..71806c3a1cc9 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import re
import json
+import time
import asyncio
import logging
from collections.abc import Callable, Collection, Sequence
@@ -39,6 +40,7 @@ OutputFn = Callable[[str], object] | None
POLL_INTERVAL_SECONDS = 10
MAX_POLL_SECONDS = 30 * 60 # default per-turn budget; callers with longer turns pass max_poll_seconds
MAX_CONSECUTIVE_STORAGE_ERRORS = 3
+FINAL_POLL_READ_SECONDS = 5
# Turn-relevant log silence required before salvaging a dropped-finalization turn, sized to one SSE
# read window (SSE_READ_TIMEOUT_SECONDS): if the turn produced no real output for a whole read window,
# a live stream would have. The poll loop measures this silence over turn-relevant lines only, because
@@ -483,6 +485,7 @@ async def poll_for_turn(
output_fn: OutputFn = None,
workflow_handle: WorkflowHandle | None = None,
max_poll_seconds: int | None = None,
+ poll_deadline: float | None = None,
) -> TurnPollResult:
"""Poll S3 logs until the agent finishes a turn.
@@ -491,8 +494,11 @@ async def poll_for_turn(
runs once this budget is exhausted, so a caller must keep it below its own activity
`start_to_close_timeout` or the salvage never gets a chance to fire (the Signals
scout passes its 15-minute per-run budget for exactly this reason).
+ `poll_deadline` uses the monotonic clock so setup, I/O, and earlier turns cannot
+ extend the caller's shared time budget. Leave recovery time after this deadline.
"""
poll_budget = MAX_POLL_SECONDS if max_poll_seconds is None else max_poll_seconds
+ started_at = time.monotonic()
# Track the timing/errors
elapsed = 0
consecutive_storage_errors = 0
@@ -509,22 +515,42 @@ async def poll_for_turn(
# boundary (which would return a stale previous-turn response in multi-turn sessions).
original_skip_lines = skip_lines
while elapsed < poll_budget:
- await asyncio.sleep(POLL_INTERVAL_SECONDS)
- elapsed += POLL_INTERVAL_SECONDS
+ if poll_deadline is not None:
+ remaining = poll_deadline - time.monotonic()
+ if remaining > 0:
+ await asyncio.sleep(min(POLL_INTERVAL_SECONDS, remaining))
+ elapsed = int(time.monotonic() - started_at)
+ else:
+ await asyncio.sleep(POLL_INTERVAL_SECONDS)
+ elapsed += POLL_INTERVAL_SECONDS
# Send heartbeat signals to the ProcessTaskWorkflow on each poll cycle to prevent
# the workflow's inactivity timeout from firing while the agent is still working
- if workflow_handle is not None:
+ if workflow_handle is not None and (poll_deadline is None or time.monotonic() < poll_deadline):
try:
- await workflow_handle.signal("heartbeat")
+ heartbeat = workflow_handle.signal("heartbeat")
+ if poll_deadline is None:
+ await heartbeat
+ else:
+ await asyncio.wait_for(heartbeat, timeout=max(0, poll_deadline - time.monotonic()))
except Exception:
logger.warning("custom_prompt - poll_for_turn: failed to send workflow heartbeat", exc_info=True)
try:
# Poll the logs.
- log_state = await sync_to_async(
+ read_logs = sync_to_async(
# thread_sensitive=False because of pure I/O (object_storage.read + JSON parsing) and doesn't touch the ORM
_check_logs,
thread_sensitive=False,
)(task_run, skip_lines)
+ if poll_deadline is None:
+ log_state = await read_logs
+ else:
+ remaining = poll_deadline - time.monotonic()
+ log_state = await asyncio.wait_for(
+ read_logs, timeout=remaining if remaining > 0 else FINAL_POLL_READ_SECONDS
+ )
+ elapsed = int(time.monotonic() - started_at)
+ except TimeoutError:
+ break
except ObjectStorageError:
consecutive_storage_errors += 1
logger.warning(
@@ -610,6 +636,8 @@ async def poll_for_turn(
# prior poll; without the clamp we'd re-parse old lines. Doubles as the line-count high-water
# mark handed to salvage: every line up to here was seen (and watched go quiet) during polling.
skip_lines = max(skip_lines, log_state.total_lines)
+ if poll_deadline is not None and time.monotonic() >= poll_deadline:
+ break
refreshed = await _refresh_task_run(task_run.id)
if refreshed.status in {
TaskRun.Status.COMPLETED,
@@ -638,6 +666,8 @@ async def poll_for_turn(
# Poll budget exhausted. A run already terminal here was marked by something else (cancel,
# relay-detected crash) — drain it; otherwise try to salvage below.
refreshed = await _refresh_task_run(task_run.id)
+ if poll_deadline is not None:
+ elapsed = int(time.monotonic() - started_at)
if refreshed.status in {
TaskRun.Status.COMPLETED,
TaskRun.Status.FAILED,
@@ -705,6 +735,7 @@ async def poll_for_agent_task(
output_fn: OutputFn = None,
workflow_handle: WorkflowHandle | None = None,
max_poll_seconds: int | None = None,
+ poll_deadline: float | None = None,
) -> TurnPollResult:
run = await sync_to_async(TaskRun.objects.get)(
id=task_run.run_id, task_id=task_run.task_id, team_id=task_run.team_id
@@ -717,6 +748,7 @@ async def poll_for_agent_task(
output_fn=output_fn,
workflow_handle=workflow_handle,
max_poll_seconds=max_poll_seconds,
+ poll_deadline=poll_deadline,
)
diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index 954e25d853a0..cd6a34f94aa7 100644
--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -74,6 +74,7 @@ class MultiTurnSession:
# Set this below the caller's Temporal activity `start_to_close_timeout` so the
# dropped-finalization salvage can fire before the activity is cancelled.
max_poll_seconds: int | None = None
+ poll_deadline: float | None = None
_workflow_handle: WorkflowHandle | None = field(default=None, repr=False)
@classmethod
@@ -223,6 +224,7 @@ class MultiTurnSession:
before_task_dispatch: Callable[[UUID], dict[str, JsonValue] | None] | None = None,
origin_key: str | None = None,
max_poll_seconds: int | None = None,
+ poll_deadline: float | None = None,
workflow_id_prefix: str | None = None,
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
mcp_credential_owner_id: int | None = None,
@@ -250,6 +252,8 @@ class MultiTurnSession:
their paths. Use them for text too long for the agent to pass on itself, such as
the task of a sub-agent.
"""
+ if poll_deadline is not None and time.monotonic() >= poll_deadline:
+ raise TimeoutError("The case time budget expired before the initial turn")
task, task_run = await create_task_and_trigger(
prompt,
context,
@@ -283,6 +287,7 @@ class MultiTurnSession:
verbose=verbose,
output_fn=output_fn,
max_poll_seconds=max_poll_seconds,
+ poll_deadline=poll_deadline,
_workflow_handle=workflow_handle,
)
if on_task_run_created is not None:
@@ -305,6 +310,7 @@ class MultiTurnSession:
output_fn=output_fn,
workflow_handle=workflow_handle,
max_poll_seconds=max_poll_seconds,
+ poll_deadline=poll_deadline,
)
session.log_lines_seen = turn.total_lines
session.printed_lines = turn.printed_lines
@@ -372,6 +378,8 @@ class MultiTurnSession:
async def _send_and_poll(self, message: str, *, label: str, attempt: int) -> str | None:
"""Signal the followup and poll for the next turn. Returns None on empty end_turn."""
assert self._workflow_handle is not None
+ if self.poll_deadline is not None and time.monotonic() >= self.poll_deadline:
+ raise TimeoutError("The case time budget expired before the next turn")
await self._workflow_handle.signal(ProcessTaskWorkflow.send_followup_message, message)
logger.info(
"multi_turn: sent followup run=%s label=%s attempt=%d",
@@ -388,6 +396,7 @@ class MultiTurnSession:
output_fn=self.output_fn,
workflow_handle=self._workflow_handle,
max_poll_seconds=self.max_poll_seconds,
+ poll_deadline=self.poll_deadline,
)
self.log_lines_seen = turn.total_lines
self.printed_lines = turn.printed_lines
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index a6bf02b99f9b..671ea159475c 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -1,6 +1,8 @@
import json
import asyncio
from pathlib import Path
+from types import SimpleNamespace
+from typing import cast
from uuid import UUID, uuid4
import pytest
@@ -180,23 +182,121 @@ class TestPollForTurnStaleSalvage:
turn still emitting near the deadline isn't cut off. Tests patch the budget and floor small."""
@pytest.mark.asyncio
- async def test_salvages_last_message_when_end_turn_never_arrives(self):
+ @pytest.mark.parametrize("deadline", [None, 30.0])
+ async def test_salvages_last_message_when_end_turn_never_arrives(self, deadline: float | None) -> None:
# Final message + null-cost usage_update, no end_turn — the prod failure shape.
log = "\n".join([_agent_message_line("close-out summary"), _usage_update_line(165000)])
fake = FakeTaskRun()
+ now = [0.0]
+
+ async def sleep(delay: float) -> None:
+ now[0] += delay
+
with (
patch("posthog.storage.object_storage.read", return_value=log),
- patch("asyncio.sleep", new=AsyncMock()),
+ patch("asyncio.sleep", side_effect=sleep),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.time.monotonic",
+ side_effect=lambda: now[0],
+ ),
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 30),
patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- turn = await poll_for_turn(fake, skip_lines=0)
+ turn = await poll_for_turn(fake, skip_lines=0, poll_deadline=deadline)
assert turn.last_message == "close-out summary"
assert turn.total_lines == 2
+ @pytest.mark.asyncio
+ async def test_reads_completed_turn_on_the_final_poll_interval(self) -> None:
+ now = [0.0]
+ fake = FakeTaskRun()
+ partial = _agent_message_line("working")
+ complete = "\n".join([partial, _agent_message_line("done"), _end_turn_line()])
+
+ async def sleep(delay: float) -> None:
+ now[0] += delay
+
+ def read(*args: object, **kwargs: object) -> str:
+ return complete if now[0] >= 25 else partial
+
+ with (
+ patch("posthog.storage.object_storage.read", side_effect=read),
+ patch("asyncio.sleep", side_effect=sleep),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.time.monotonic",
+ side_effect=lambda: now[0],
+ ),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ turn = await poll_for_turn(fake, poll_deadline=25.0)
+ assert turn.last_message == "done"
+ assert turn.total_lines == 3
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("slow_io", ["storage", "heartbeat"])
+ async def test_recovers_after_io_exhausts_the_deadline(self, slow_io: str) -> None:
+ now = [0.0]
+ fake = FakeTaskRun()
+ log = "\n".join([_agent_message_line("done"), _usage_update_line(165000)])
+ reads = 0
+ heartbeats = 0
+
+ async def sleep(delay: float) -> None:
+ now[0] += delay
+
+ def read(*args: object, **kwargs: object) -> str:
+ nonlocal reads
+ reads += 1
+ if slow_io == "storage" and reads == 2:
+ now[0] += 60
+ return log
+
+ async def heartbeat(*args: object) -> None:
+ nonlocal heartbeats
+ heartbeats += 1
+ if slow_io == "heartbeat" and heartbeats == 2:
+ now[0] += 60
+
+ handle = MagicMock(signal=AsyncMock(side_effect=heartbeat))
+ with (
+ patch("posthog.storage.object_storage.read", side_effect=read),
+ patch("asyncio.sleep", side_effect=sleep),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.time.monotonic",
+ side_effect=lambda: now[0],
+ ),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ turn = await poll_for_turn(fake, poll_deadline=30.0, workflow_handle=handle)
+ assert turn.last_message == "done"
+ assert turn.total_lines == 2
+
+ @pytest.mark.asyncio
+ async def test_final_poll_read_has_a_timeout(self) -> None:
+ async def blocked_read(*args: object) -> None:
+ await asyncio.Event().wait()
+
+ with (
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.sync_to_async", return_value=blocked_read
+ ),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals._refresh_task_run",
+ new=AsyncMock(return_value=FakeTaskRun()),
+ ),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.time",
+ SimpleNamespace(monotonic=lambda: 0.0),
+ ),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.FINAL_POLL_READ_SECONDS", 0.01),
+ ):
+ with pytest.raises(TurnPollTimeout):
+ await asyncio.wait_for(poll_for_turn(FakeTaskRun(), poll_deadline=0.0), timeout=1)
+
@pytest.mark.asyncio
async def test_salvages_dropped_finalization_after_active_work(self):
# Real work across several polls, then end_turn dropped — must still be salvaged. Uses the
@@ -307,20 +407,33 @@ class TestPollForTurnStaleSalvage:
await poll_for_turn(fake, skip_lines=0)
@pytest.mark.asyncio
- async def test_max_poll_seconds_overrides_module_budget(self):
- # A caller-supplied max_poll_seconds bounds the loop instead of the module MAX_POLL_SECONDS:
- # the module value is left larger, so the elapsed in the timeout error proves the override won.
- log = _agent_message_line("intermediate") # no fingerprint — always times out
+ @pytest.mark.parametrize("deadline", [None, 25.0, 0.0])
+ async def test_max_poll_seconds_overrides_module_budget(self, deadline: float | None) -> None:
+ log = _agent_message_line("intermediate")
fake = FakeTaskRun()
+ now = [0.0]
+
+ async def sleep(delay: float) -> None:
+ now[0] += delay
+
+ def read(*args: object, **kwargs: object) -> str:
+ now[0] += 7
+ return log
+
with (
- patch("posthog.storage.object_storage.read", return_value=log),
- patch("asyncio.sleep", new=AsyncMock()),
+ patch("posthog.storage.object_storage.read", side_effect=read),
+ patch("asyncio.sleep", side_effect=sleep),
+ patch(
+ "products.tasks.backend.logic.services.custom_prompt_internals.time.monotonic",
+ side_effect=lambda: now[0],
+ ),
patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 100),
patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
):
- with pytest.raises(RuntimeError, match="after 30s"):
- await poll_for_turn(fake, skip_lines=0, max_poll_seconds=30)
+ with pytest.raises(TurnPollTimeout) as error:
+ await poll_for_turn(fake, skip_lines=0, max_poll_seconds=30, poll_deadline=deadline)
+ assert error.value.elapsed == (30 if deadline is None else int(now[0]))
@pytest.mark.asyncio
async def test_salvage_reassembles_chunked_message(self):
@@ -1183,8 +1296,10 @@ class TestMultiTurnSessionRetry:
return session
@pytest.mark.asyncio
- async def test_happy_path_no_retry(self):
+ @pytest.mark.parametrize("deadline,turns", [(None, 1), (float("inf"), 2), (0.0, 1)])
+ async def test_happy_path_no_retry(self, deadline: float | None, turns: int) -> None:
session = self._make_session()
+ session.poll_deadline = deadline
agent_response = json.dumps({"value": "ok"})
with patch(
@@ -1192,12 +1307,19 @@ class TestMultiTurnSessionRetry:
new=AsyncMock(
return_value=TurnPollResult(last_message=agent_response, full_log=None, total_lines=10, printed_lines=5)
),
- ):
- result = await session.send_followup("hello", _Resp, label="unit")
-
- assert result == _Resp(value="ok")
- # Signal sent exactly once on happy path
- assert session._workflow_handle.signal.await_count == 1 # type: ignore[union-attr]
+ ) as poll:
+ if deadline == 0.0:
+ with pytest.raises(TimeoutError):
+ await session.send_followup("hello", _Resp, label="unit")
+ cast(AsyncMock, session._workflow_handle).signal.assert_not_awaited()
+ poll.assert_not_awaited()
+ return
+ for _ in range(turns):
+ result = await session.send_followup("hello", _Resp, label="unit")
+ assert result == _Resp(value="ok")
+
+ assert all(call.kwargs["poll_deadline"] == deadline for call in poll.await_args_list)
+ assert session._workflow_handle.signal.await_count == turns # type: ignore[union-attr]
@pytest.mark.asyncio
async def test_retries_once_on_empty_end_turn(self):