Skip to content

fix(shell): run piped commands as a pipeline on macOS and Linux - #4019

Closed
kovtcharov wants to merge 1 commit into
amd:mainfrom
kovtcharov:claude/fix-posix-shell-pipes
Closed

kovtcharov wants to merge 1 commit into
amd:mainfrom
kovtcharov:claude/fix-posix-shell-pipes

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

On macOS and Linux every piped shell command returned wrong output with status "success". grep a x.txt | wc -l returned x.txt, and cat x.txt | sort came back unsorted. Pipes now run as real pipelines, still without a shell, so the model gets the output it asked for. A failing stage is never hidden behind a later one, so pytest | tail can't turn a failing suite into a verified pass.

Fixes #4018.

Test plan

  • python -m pytest tests/unit/test_shell_pipelines.py tests/unit/test_skill_binary_grants.py passes. On main, 4 of the 7 new pipeline tests fail.
  • cat notes.txt | grep apple | wc -l in the shell tool returns a count on macOS/Linux.
  • Windows CI unchanged: pipelines there still go through cmd.exe.
🔍 Technical details
  • Validated segments are chained with Popen. Each stage's stderr goes to a temp file, so a chatty upstream can't deadlock the pipeline.
  • The exit code is the rightmost non-zero stage (pipefail). An upstream stage killed by SIGPIPE counts as success, because that is how | head ends a pipeline.
  • A timeout kills every stage.
  • test_a_pipeline_is_not_run_as_argv only asserted the shell flag, which is why it passed while the bug was live. It now asserts the stages are chained.

@github-actions

Copy link
Copy Markdown
Contributor

Approve with suggestions

This fixes a genuinely bad bug: on macOS and Linux every piped command was being run as one concatenated command, so the model got wrong output labelled success. Pipes now run as a real pipeline, still with no shell involved, and a failing stage can no longer be hidden behind a later one. I could not find a correctness or security hole in the new path.

Three small things worth folding in before merge, none blocking:

  • A timed-out pipeline throws away output it already collected. If the last stage finishes but an earlier one keeps running past the timeout, the tool reports the timeout with an empty output, even though the answer was already in hand. A single (non-piped) command in the same situation keeps its partial output — worth matching.
  • A pipeline whose second command doesn't exist is reported as "nothing ran", even though the first command did run. That label is read by the verification footer, so it should say what actually happened.
  • Line endings are no longer normalised for piped output, so a tool that emits Windows-style line breaks will look different through a pipe than it does on its own.

Worth calling out that the test that should have caught the original bug only checked a flag, not the behaviour — this PR fixes that too, which is the more valuable half of the change.

Real-world evidence

No evidence-bundle.md was produced for this PR, and pytest isn't installed in this review lane, so I couldn't run the new suite. Instead I exercised the new pipeline function's source directly on this Linux runner:

sort            : rc=0 out='apple\napple pie\nfig\npear\n'
3-stage         : rc=0 out='2\n'                       (cat | grep | wc -l)
failing stage   : rc=1 err='cat: missing.txt: No such file or directory'
| head on 200k  : rc=0 out='line\n' in 0.00s           (SIGPIPE not treated as failure)
hung stage      : TimeoutExpired after 2.0s, all processes reaped

That confirms the core claims of the PR — chaining, pipefail, SIGPIPE, and timeout cleanup all behave as described. It does not cover the tool wrapper end to end, the Windows cmd.exe path, or the skill-grant gating, so the verdict on those rests on static review alone. The PR's own test plan boxes are still unchecked.

🔍 Technical details

🟢 Minor

1. Partial stdout is dropped on timeout (src/gaia/agents/tools/shell_tools.py:448)

communicate() binds out before the upstream wait() loop, but if that loop times out the re-raised TimeoutExpired carries exc.output (None from wait()) instead. Reproduced on this runner:

$ _run_pipeline([["sh","-c","echo early; sleep 30"],["head","-1"]], cwd, timeout=3)
TIMEOUT after 3.0s, stdout=None      # 'early\n' was already read and discarded

subprocess.run in the else branch does return partial output here, so the two paths disagree.

        out = None
        try:
            out, _ = procs[-1].communicate(timeout=max(deadline - time.monotonic(), 0))
            for proc in procs[:-1]:
                proc.wait(timeout=max(deadline - time.monotonic(), 0))
        except subprocess.TimeoutExpired as exc:
            for proc in procs:
                proc.kill()
            for proc in procs:
                proc.wait()
            raise subprocess.TimeoutExpired(
                exc.cmd, timeout, output=out or exc.output, stderr=_read_all(errs)
            ) from exc

2. NOT_EXECUTED is claimed when an upstream stage did run (shell_tools.py:1411)

A missing binary in stage 2+ raises FileNotFoundError out of _run_pipeline after stage 1 has already been spawned, and the handler returns {**NOT_EXECUTED, ...} with the comment "so nothing started". Confirmed locally: cat notes.txt | definitely-not-a-binary → FileNotFoundError: [Errno 2] ... 'definitely-not-a-binary'. Since NOT_EXECUTED is load-bearing for the verification footer, consider distinguishing "the pipeline produced no result" from "nothing ran" — or at least mention the pipeline in the error text.

3. No universal-newline translation in the pipeline path (shell_tools.py:483)

subprocess.run(..., encoding="utf-8") wraps the pipe in a TextIOWrapper with newline=None, so CRLF is translated; the raw .decode() here isn't:

pipeline : 'a\r\nb\r\n'
single   : 'a\nb\n'

Same command, different output depending on whether it was piped. io.TextIOWrapper(io.BytesIO(out), encoding="utf-8", errors="replace").read() (or str.replace("\r\n", "\n")) would keep the two paths consistent. Applies to _read_all too.

Verified, not flagged

  • No privilege expansion. Every segment still goes through _validate_command (shell_tools.py:1221), the path-traversal scan still exempts per-segment rather than per-line (:1159), and skill_grant_covers_call still returns False for any multi-segment command — so gh issue list | head -5 under a grant prompts, exactly as before. The new path only reaches _run_pipeline when not use_shell, which on Windows is impossible for a pipeline, so cmd.exe behaviour is genuinely untouched.
  • No fd or deadlock hazard. Each intermediate read end is closed in the parent right after the next stage is spawned (:443), stderr goes to per-stage temp files so a chatty upstream can't fill a pipe buffer, and the except BaseException handler closes every still-open proc.stdout — including the dangling upstream when a mid-loop Popen fails.
  • pipefail is the real thing. failed[-1] is the rightmost non-zero stage, matching bash's set -o pipefail; the i < len(codes) - 1 guard correctly exempts only upstream SIGPIPE deaths.

Strengths

  • The SIGPIPE-is-not-a-failure rule plus rightmost-non-zero exit code is exactly the semantics an agent needs — without it, pytest | tail reporting a passing suite would have been a worse bug than the one being fixed.
  • Per-stage stderr to temp files (rather than pipes) sidesteps the classic multi-process capture deadlock, and the timeout path kills and reaps every stage rather than just the tail.
  • test_a_pipeline_is_not_run_as_argv previously asserted only the shell flag, which is why it stayed green while the bug was live; tightening it to assert the chained segments is the fix that keeps this from regressing.

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.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Rebased onto current main. First in the shell stack, nothing to merge before it; #4020 builds on this.

@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.

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: empty. The merge produces a tree identical to main.

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

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Piped shell commands return wrong output on macOS and Linux

2 participants