Skip to content

fix(agent): a test summary that reports failures is a failed check - #4026

Closed
kovtcharov wants to merge 11 commits into
amd:mainfrom
kovtcharov:claude/verify-reads-pytest-summary
Closed

kovtcharov wants to merge 11 commits into
amd:mainfrom
kovtcharov:claude/verify-reads-pytest-summary

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

GAIA's verification line could certify a failing test run. When the agent runs pytest inside run_python and prints the result, the snippet exits 0 whatever pytest reported, and the line judged the run by that exit code alone. In an adversarial benchmark task the output said "1 failed, 3 passed" and the line said "verified — pytest ran and passed". A Python run whose own test summary reports failures now counts as a failed check.

Test plan

  • python -m pytest tests/unit/agents/test_verification_scope.py passes. On main, the 6 new cases fail (pytest N failed and N error summaries, and unittest FAILED (...), via both run_python and execute_python_file).
  • A passing summary from a snippet stays a pass (test_a_passing_summary_from_a_snippet_stays_passed).
🔍 Technical details

summary_reports_failure() reads the last pytest or unittest summary in a run_python / execute_python_file result, and _note_verification_signal ORs it into failed. The summary patterns are hoisted from verification_check_label so both functions use the same definition of a summary line. Shell runs are unchanged: their return_code is pytest's own.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This closes a real credibility hole: when the agent ran pytest from inside a Python snippet, the snippet exited 0 no matter what pytest reported, so a run that printed "1 failed, 3 passed" was still certified as "ran and passed". Now the run's own printed summary decides. The fix is small, errs on the cautious side, and is well covered by tests.

Two things worth a follow-up, neither of them a regression from this change:

  • The same masking still exists when tests are run through the shell. A command that swallows the exit code — pytest || true, pytest; echo done, or a make test wrapper that does the same — still reports a failing suite as verified. The same output-based check would close it, and it's the more common way an agent hides a failure.
  • A run can be flagged as failed and simultaneously described as "no test ran." When a snippet prints more than one pytest summary, the failure check reads the last one but the "is this a test run at all?" check reads the first. If the first summary is skips-only, the line says nothing was checked even though the run reported failures. Reading the same summary in both places fixes it.

Also, the test plan checkboxes are still unticked — worth confirming the run before merge.

Real-world evidence

No evidence-bundle.md in the tree, and the PR description carries no captured run. That's acceptable here: the change is confined to pure helper functions with no user-facing command or endpoint of its own, so there is no CLI/API/MCP surface for the lane to exercise. The user-visible effect — the wording of the verification line — would only show up in a live agent turn, which this lane can't produce.

I exercised the changed helpers directly instead (no pytest available in this environment, so not via the new tests):

1 failed                     fail=True  label=pytest
1 error                      fail=True  label=pytest
unittest FAILED              fail=True  label=unittest
4 passed                     fail=False label=pytest
two runs, fail-then-pass     fail=False label=pytest
two runs, pass-then-fail     fail=True  label=pytest
shell tool, same output      fail=False label=None
→ Verification: partially verified — pytest ran and did not pass. Nothing else was checked.

That matches the intended behaviour, including "latest run wins". The verdict rests on this plus static review; the wording as a user sees it in a live turn was not observed here.

🔍 Technical details

🟡 The shell path still certifies a failing suite (verification.py:124)

summary_reports_failure is gated to run_python / execute_python_file, and the PR description justifies that with "shell runs are unchanged: their return_code is pytest's own". That holds only when the command is pytest. run_shell_command with pytest -q || true, pytest; echo done, or make test over a recipe that swallows the status returns return_code == 0, _is_error_result says no error, and _CHECK_COMMAND_RE still labels it pytest — so the line reads verified — pytest ran and passed against a red suite. Confirmed locally: summary_reports_failure("execute_shell_command", {...,"stdout":"1 failed, 3 passed in 1.00s","return_code":0}) → False, label → pytest.

The check is output-based and only ever flips toward "did not pass", so widening the gate is low-risk — drop the tool-name allowlist and let any result carrying stdout/stderr be examined, or add the shell tool names. Pre-existing, so not blocking this PR, but it's the same bug in the path an agent reaches more often.

🟢 Label reads the first summary, failure reads the last (verification.py:162)

summary_reports_failure deliberately uses summaries[-1]; verification_check_label still uses .search, i.e. the first match. With stdout = "3 skipped in 0.10s\n\n1 failed, 3 passed in 1.00s" the label comes back None (skips-only summary fails the inner passed|failed|error|… test) while failed is True — the entry is flagged failed but dropped from the check list, and build_verification_scope emits unverified — 1 tool call ran, none of them a test, lint, or build. One basis for both:

        summaries = list(_PYTEST_SUMMARY_RE.finditer(output))
        summary = summaries[-1] if summaries else None

🟢 Mixed-runner output resolves by runner, not by recency (verification.py:136-142)

If a snippet's last pytest summary passes but a unittest FAILED (...) appears anywhere in the output, the unittest branch wins. That's the cautious direction so it's fine as shipped — just note the docstring's "the last summary printed wins" is true within a runner, not across the two.

Strengths

  • Hoisting _PYTEST_SUMMARY_RE / _UNITTEST_SUMMARY_RE to module constants means the label and the pass/fail verdict can't drift apart on what counts as a summary line — the right refactor to pair with this fix.
  • Every ambiguous case resolves toward "did not pass" rather than a false certification, matching the module's stated conservatism.
  • Tests are parametrized across both tools and all three summary shapes, and the docstring records the benchmark run that motivated the fix — the negative case (test_a_passing_summary_from_a_snippet_stays_passed) guards the obvious over-correction.
  • [1-9]\d* correctly keeps 0 failed from tripping the check.

Kalin Ovtcharov and others added 11 commits September 21, 2026 04:14
On macOS and Linux every piped shell command returned wrong output with
status "success". The validator drops the `|` tokens and the executor then
ran the segments as one argv, so `cat notes.txt | sort` ran as
`cat notes.txt sort` and `grep a x.txt | wc -l` returned "x.txt" instead of
a count. Windows was unaffected because it goes through cmd.exe.

Validated segments are now chained as separate processes, still without a
shell. The exit code is the rightmost failing stage, so `pytest | tail`
cannot turn a failing suite into a verified pass; an upstream stage killed
by SIGPIPE (`| head`) is not a failure. Every stage's stderr is kept, and a
timeout kills the whole pipeline.

test_a_pipeline_is_not_run_as_argv only pinned the shell flag, so it passed
while the bug was live; it now checks that the stages are chained.
Agents reach for `python -m pytest` first, and the shell refused it with
"only read-only commands are allowed" - no hint that pytest exists behind
the coding skill. In a 14-task benchmark run on main that dead end was hit
5 times; the agent gave up on the tests and twice reported them as passing.

`python -m pytest` is now judged as `pytest`: same grant, same flag and path
policy, no extra prompt. Without the grant it gets pytest's "load that skill
first" refusal. The typed spelling is what runs, because `-m` puts the
working directory on the import path, so a checkout that was never
installed imports without a pytest.ini workaround. Only the exact
`python|python3|py -m pytest` shape maps; `-c`, a script, another module or
an interpreter flag stays refused.

An inline `PYTHONPATH=. pytest` was refused as an unknown command named
"pythonpath=."; it now says inline environment assignments are unsupported.
A shell command over the rate limit (3 per 10 s, 10 per minute) was refused
with "wait N seconds", so the model spent a whole step sending the same
command again after the same wait. In a benchmark run the refused command was
the recovery itself - `python -m pytest` right after bare `pytest` failed to
import the project - in 2 of 14 tasks.

The tool now waits for the window and then runs the command, reporting
waited_seconds. The rate stays exactly as capped; a wait longer than
max_rate_limit_wait_seconds (60 s) is still refused.
The shell tool refused `&&`, `||` and `;` outright, so work that is one call
elsewhere — `cd src && ls`, `pytest -q | tail -5; grep -rn parse_` — cost GAIA
three or four. Two benchmark runs of 14 tasks hit 4 operator refusals and about
7 recovery steps, and used 100 steps where Claude Code used 82; every extra step
re-sends a ~12K-token prompt, and fresh input is 53% of the cost.

A line is now split into its pipelines, and every segment of every pipeline goes
through the same tiered validation as before, before any of it runs: one refused
command refuses the whole line, one confirm-tier command raises a single prompt
showing the whole line, and a skill grant covers the line only when it covers
every segment. The steps then run sequentially in-process with sh's semantics —
`&&` on success, `||` on failure, `;` regardless — through the existing pipeline
runner, so no line reaches a shell on POSIX and Windows gets one pipeline per
cmd.exe call instead of the line. `cd <dir>` is allowed as a bare one-argument
command, path-validated like `working_directory`, and moves only the rest of its
own line.

Redirection, command substitution, a background `&` and inline `VAR=value` are
still refused; newlines now are too, which they were not before, and cmd.exe
reads one as a command separator. The line costs the rate limiter one command
because it is one model step, and a failure no `||` handled still sets
`has_errors`, so `pytest -q; ls` cannot report a failing suite as a passing
check.
Across seven benchmark runs of 14 tasks on four models, 19 of the 21 shell
operator refusals were `2>/dev/null` or `2>&1` — neither of which creates a
file. They are how every model asks for a test run (`pytest -q 2>&1 | tail -20`,
`ls tests/ 2>/dev/null`), each refusal cost the call plus a median of one more
to recover (43 wasted tool calls, ~5% of all of them), and the refusal's own
hint said to use `write_file`, which is not advice for a stderr redirect. One
measured case became a false claim: the agent could not test a patch in a
scratch copy, and reported a later run against unpatched code as if it had
covered the patch.

Both forms are now lifted out of the line before the operator scan and recorded
as a flag on the segment that wrote them — exact standalone tokens only, and
never inside double quotes. `2>&1` points that segment's stderr at its own
stdout pipe, so a later stage's `grep` sees it; `2>/dev/null` points it at the
null device. Neither names a file, and on POSIX neither reaches a shell: they
are destinations for a stream this process already captures. On Windows the
step is a cmd.exe string, so the redirection travels in it, spelled `2>nul`.

Everything else stays refused: `2>` to any other path, `1>`, `>`, `>>`, `<`,
`&>`, `>&`, backticks, `$()`, `&`, and newlines. Return codes are untouched, so
discarding stderr cannot turn a failing command into a passing one.
Every inline assignment the shell tool refused across four models' benchmark
runs was a PYTHONPATH the agent needed to import the project under test —
`PYTHONPATH=. pytest -q tests/` and two variants, three of the 28 measured shell
refusals. The refusal's hint said to run the command without the assignment,
which fails with ImportError, so the agent was left with no way to verify its
own work and wrote a throwaway runner script or gave up.

Leading `NAME=value` tokens are now split off each segment of a line and applied
as that subprocess's environment. The value never reaches a shell — it is an
entry in the env dict handed to the process — and what is left after the
assignments is what the allowlist sees, so `PYTHONPATH=. rm -rf /` is refused
exactly as `rm -rf /` is. The variable reaches that one process: not a later
segment, not a later step, and never this process's own environment. On Windows
a step carrying one runs as argv rather than through cmd.exe, which would apply
it to the whole string.

The names that change WHICH binary runs, or what code one loads, stay refused by
family, so the list does not go stale the next time one of these tools adds a
hook:

- the dynamic linkers (LD_*, DYLD_*, GCONV_*), the shells (BASH_*, SHELL, ENV,
  IFS) and PATH itself
- the hook and option variables of the binaries this tool can actually run:
  GIT_* (GIT_SSH_COMMAND, GIT_EXTERNAL_DIFF, GIT_CONFIG_* inject commands), GH_*
  (GH_PAGER runs one), PYTEST_* (PYTEST_ADDOPTS re-injects the flags the pytest
  grant denies), LESS* (LESSOPEN is an input filter), NODE_*, PERL*, RUBY*,
  JAVA*, PS*
- PAGER/EDITOR/VISUAL/BROWSER, and the PYTHON* variables that run code
  (PYTHONSTARTUP, PYTHONHOME, PYTHONEXECUTABLE, PYTHONBREAKPOINT)

Matching is case-insensitive, because Windows matches environment names that
way. PYTHONPATH is deliberately not on that list: its containment is that every
assignment's value is path-checked against the agent's allowed paths — on every
segment, granted binaries included, because a value is never a remote id.
Asking the agent to run `for f in a b; do ...; done` told it
`[Errno 2] No such file or directory: 'for'`, which reads as a PATH problem
and sends it hunting for an install. Commands run directly rather than
through a shell, so `for` is not a binary that happens to be absent — it can
never run, and the refusal now says so and names run_python as the thing that
can.

Seen in a benchmark run, where two agents each burned steps on it.
The verification line read "partially verified - pytest passed, pytest did
not." when two differently spelled test runs shared a label: a shell pytest
that failed at collection, then a pytest run through run_python that passed.
A reader, and the benchmark's judge, took that as the harness contradicting
itself; it appeared in 3 of 14 tasks in one benchmark run.

The verdict is unchanged - a narrower passing rerun still does not hide a run
that failed - but a label on both sides is now counted: "1 of 2 pytest runs
did not pass".
… one

The agent could change source, check it with a couple of prints, and report
the fix as done without running the project's tests. In an adversarial
benchmark task that meant a test that was already failing went unreported:
GAIA fixed the bug, never ran the suite, and never saw it; Claude Code ran the
suite and reported the old failure.

The check reads the turn's tool record, not the answer's wording. It fires when
a write/edit tool changed a code file in the project, no check ran after that
change (a labelled check, or a run_python / execute_python_file /
run_shell_command whose output holds a pytest or unittest summary line), the
project has a test suite, and steps remain. It asks once; the corrective
message starts with [check:verify-after-change] and stays in the returned
conversation so transcripts can count it. Only the tail of Python and shell
outputs is kept for the check, so reading a large file doesn't copy it.
GAIA's verification line said "verified - pytest ran and passed" for a run
whose own output was "1 failed, 3 passed". The agent had run pytest inside
run_python and printed the result; the snippet itself exited 0, and the
check was judged by that exit code alone. In an adversarial benchmark task
(a hanging test) the harness therefore certified a suite that had failed.

A run_python or execute_python_file result whose last pytest or unittest
summary reports failures or errors is now a failed check, whatever the
snippet's exit code. The last summary printed wins, since a snippet may run
the suite more than once.
@kovtcharov
kovtcharov force-pushed the claude/verify-reads-pytest-summary branch from 1894efa to 517001e Compare September 21, 2026 11:59
@github-actions github-actions Bot added the documentation Documentation changes label Sep 21, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Restacked on #4025 (verify-after-change). Merge after #4025.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Everything in this PR is already on main, so there is nothing left to merge.

It landed as part of #4049, which squash-merged the tip of the stack this branch sits in and carried every commit below it along. GitHub does not auto-close the lower PRs in a stack when the tip is squashed, which is why this stayed open — and why it has been showing a conflict against a main that already contains its work.

Merging it now would actively hurt: the only thing it still adds is a second copy of two methods main already defines.

Closing as superseded. No work is lost; reopen if you disagree.

🔍 Technical details

Verified rather than assumed — merged origin/main into this branch taking main's side, then diffed the result against main:

git checkout -B probe <branch> && git merge origin/main --no-edit -X theirs
git diff --stat origin/main HEAD

Residual: 23 lines in src/gaia/agents/base/agent.py — duplicate definitions of _verification_project_root and _verify_after_change_prompt. Both already exist in main (git grep -c reports 2 occurrences after the merge, 1 before).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants