Skip to content

fix: make ! invert a compound command and keep set -e from stopping on it - #265

Merged
ferdingler merged 3 commits into
strands-agents:mainfrom
ferdingler:fix/compound-status
Nov 13, 2026
Merged

ferdingler merged 3 commits into
strands-agents:mainfrom
ferdingler:fix/compound-status

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Putting ! in front of a compound command did nothing. ! { false; }, ! ( false ) and ! if ...; fi all reported the compound's own status, so if ! (cmd) >/dev/null 2>&1; then took the wrong branch. Claude Code's shell snapshot uses exactly that line. Separately, set -e stopped the script at ! true, and at a failure inside an inverted compound, where bash keeps going.

Now ! inverts a compound the same way it inverts a simple command, including when the compound has a redirect or runs inside $(...). A command that ! inverts no longer trips set -e, and neither does anything that runs inside it. A set -e or set +e inside it still sticks afterwards. No public types or signatures change: the parser reuses the existing shape for a compound with !, and leaves the pipe part empty.

I checked every case against real bash. The new negation and set -e tests fail on main and pass with the change. I also added a guard so a call cancelled halfway through a ! can't leave set -e off for the next call. I broke it on purpose and the test caught it. I also added tests for the status of a redirected group like { false; } > f. Main already gets that right, but nothing tested it, and the snapshot line depends on it together with !. Two gaps I left alone because they're separate bugs: set -e inside a redirected group, and a group with a stdin redirect inside $(...), which always reports 0.

Related Issues

None.

Documentation PR

None.

Type of Change

Bug fix

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce new warnings.

  • I ran the relevant test suites for the bindings I touched (cargo test --workspace --all-targets, pytest tests/python, npm test)
  • If I touched Rust, I ran cargo fmt and cargo clippy

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

`! { ...; }`, `! ( ... )`, and `! if ...; fi` reported the compound's own
status, because the parser kept `!` only for a simple pipeline or a
compound piped into a pipeline. Under `set -e`, `! true` stopped the
script, and a failure inside an inverted compound did too. bash does
neither.

A compound that `!` inverts with no pipe after it now parses as a
compound pipeline with an empty tail, so the AST keeps its shape. It runs
in the current shell and its status is inverted. A command inverted by
`!` counts as tested for `set -e`, and the commands inside it do not stop
the script. `set -e` and `set +e` inside it still take effect after it.
Each call starts with no inverted context, so a call cancelled inside `!`
does not carry it to the next call.

The tests also pin the status of a redirected group, which main already
reports correctly.
@ferdingler
ferdingler requested a review from a team as a code owner November 13, 2026 02:43
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent please review

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TL;DR: approve, with two non-blocking 🟡s worth fixing here. ! on a compound and the set -e exemption match bash in every case the PR claims, and the counter doesn't leak through return, break, continue, exit or a cancelled call. Two ! gaps remain, and both are small parser fixes, verified below:

  • 🟡 New: ! ! { false; } now returns 0. Bash and main return 1. Inline comment below.
  • 🟡 Still broken: set -e; ! cmd | { …; } / ! cmd | while … stops the script. Bash keeps going. This is older than the PR, but it's the PR's own stated goal ("a command that ! inverts no longer trips set -e"). The fix is in the details.

With both fixes applied: lib 72/72 and integration 1950/1950 pass, 16 more adversarial cases match bash, and none get worse.

@ferdingler, this is the review you asked for. Repro scripts, outputs and the full patch are in the details.

🟡 ! cmd | compound under set -e: repro and fix
set -e; ! true | { cat; }; echo after $?
  bash: after 1    main: (exits 1)    PR: (exits 1)
set -e; ! printf 'a\n' | while read l; do [ "$l" = a ]; done; echo after $?
  bash: after 1    main: (exits 1)    PR: (exits 1)
set -e; ! true | { false; echo in; }; echo s=$?
  bash: in s=1     main: (exits 1)    PR: in (exits 1)

parse_pipeline_into_compound puts the ! on the Pipeline inside the generated Item::Subshell (src/parser.rs:1504, (Item::Pipeline(stages, negated), None)). The new tested-context check at src/exec.rs:2265 only looks at the outer item, so it never sees the negation. Moving the ! to the outer item fixes it and reuses your new empty-tail CompoundPipeline path:

@@ src/parser.rs  fn parse_pipeline_into_compound
-    Ok(Item::Subshell(vec![
+    let item = Item::Subshell(vec![
         ( Item::Function { name: COMPOUND_STAGE.into(), body }, Some(Connector::Semi) ),
-        (Item::Pipeline(stages, negated), None),
-    ]))
+        (Item::Pipeline(stages, false), None),
+    ]);
+    if !negated {
+        return Ok(item);
+    }
+    Ok(Item::CompoundPipeline { compound: Box::new(item), tail: Vec::new(), negated })

The parser unit test a_piped_group_gives_its_body_to_the_stage_and_keeps_redirects_and_tail (src/parser.rs:2380) asserts the old shape. Match CompoundPipeline { compound, tail, negated: true }, unwrap compound as the Subshell, and flip the inner pipeline's flag to false. resolve_heredocs still reaches the stage through its CompoundPipeline arm, and ! cat <<E | { cat; } matches bash.

✅ What I verified
  • Head b79cc88. cargo test --lib: 72 passed. cargo test --test shell_integration: 1950 passed.
  • CI on the head is 30/30 green, including CI Gate. cargo fmt and clippy aren't installed in my sandbox, so they're covered by CI only.
  • My first local build ran out of disk space (ENOSPC). The tests above ran from a separate target dir.
  • Not run locally: the curl, lua and mcp suites, pytest, and npm. CI covers them.
  • Passes that ran:
    • correctness and scope review, about 70 bash-vs-PR-vs-main cases;
    • adversarial testing, 257 cases. The first attempt timed out because bash itself loops forever on set -e; until ! { true; }; do :; done; the retry completed;
    • my own spot-checks, including dash for the POSIX reading.
  • I broke the change on purpose: without the run/execute reset the cancellation test fails, and without the errexit_ignored == 0 check two errexit tests fail.
  • Test quality is good: the expect! cases assert behaviour, and the redirected-group status tests are honest coverage of what main already does.
Questions (non-blocking)
  1. Should ! match bash or POSIX/dash when set -e is first turned on inside it? For ! { set -e; false; echo x; }; echo $? with -e off beforehand, bash and main exit 1, while the PR and dash print x 1. Bash only ignores errexit under ! if it was already on when the ! started. Gating the counter with *negated && proc.opt_errexit matches bash on these rows. But it then breaks 4 rows this PR gets right, such as ! { set -e; false; echo x; } || echo y, because &&/||/if don't propagate the ignored state inside. I'd keep the PR's behaviour and leave this as is.
  2. If and while conditions still save, clear and restore opt_errexit (src/exec.rs:1945, 1978, 2572, 2597). That throws away a set ±e run inside a condition, and a cancelled call can leave set -e off. Should those move to the new counter in a follow-up, so there's one mechanism?
Reading order

src/parser.rs:1228 (empty-tail shape), then src/exec.rs:2294-2318 (execute_item negation plus the counter), src/exec.rs:2059 (the $(...) path), src/exec.rs:2261 (tested context), src/shell.rs:420 (reset), and finally the tests.

Appendix: non-blocking, mostly older than this PR (6)
  • ⚪ ! ! false returns 0 (bash 1) on main too. The inline fix covers it.
  • ⚪ for i in 1 2; do ! { break; }; done; echo $? prints 0 (bash 1). ! break does the same on main.
  • ⚪ ! { true; } > /nonexistent/f; echo $? gives 0 (bash 1: it skips the inversion when the redirect fails).
  • ⚪ ! { true; } & wait $! gives 1 (bash 0). This matches this shell's existing ! true &; bash doesn't invert background jobs.
  • ⚪ x=$(! { false; } </dev/null) gives 1 (bash 0). The cause is the stdin-redirect branch in run_capturing_status, which always reports 0 (src/exec.rs:2162), the gap the PR body already calls out.
  • ⚪ Older errexit gaps the PR doesn't touch: { set -e; false; echo x; } || echo y exits (bash prints x), set -e; { false; echo in; } | cat keeps going past false, and $(...) never applies set -e.

Evidence (S3, strands-agents/shell/pr/265/): test-integ.log, test-lib.log, bash-compare.txt, adv-results.txt, adv-results-with-fix.txt, orchestrator-spotcheck.txt, suggested-fix.diff.

Comment thread src/parser.rs Resolved
@ferdingler

Copy link
Copy Markdown
Collaborator Author

Thanks. I took both fixes in 9b98a28.

  • ! ! compound: ! now toggles. See the inline reply.
  • set -e; ! cmd | compound: I moved the ! to the outer item as you suggested, so it reuses the empty-tail path and counts as tested. I updated the parser unit test for the new shape. A new test covers ! true | { false; echo in; } and ! printf | while ... under set -e. It fails on the previous head. The here-document case ! cat <<E | { cat; } still matches bash.

Questions:

  1. I agree. I keep the current behaviour. Gating on opt_errexit breaks the || rows, and it is closer to POSIX.
  2. Yes, but in a follow-up. Moving the if/while conditions to the counter changes behaviour outside !, so it should not be in this PR.

The appendix items are older than this PR or are the gaps I listed in the description. I leave them out of scope.

@strandly-the-agent please review

@strandly-the-agent strandly-the-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TL;DR: approve. Both findings are fixed in 9b98a28, and the main merge in b56ac5c leaves the PR's own diff unchanged. I couldn't break either fix, and CI is green at b56ac5c, CI Gate included.

  • ✅ ! ! compound: fixed. ! now toggles, so ! ! cancels on compounds and simple pipelines, and ! ! ! still inverts. The new test covers all four forms.
  • ✅ set -e; ! cmd | { …; } / ! cmd | while …: fixed. The ! now sits on the outer item, so it counts as tested. The here-document and $(...) forms match bash.
  • Questions 1 and 2: I agree with keeping the POSIX/dash behaviour and doing the if/while counter move as a follow-up.

@ferdingler, thanks for taking both fixes.

✅ What I verified at b56ac5c
  • The PR's src/ diff against its merge base is byte-identical to 9b98a28's. The merge only brings in #257 and #264 from main.
  • #257 adds stop_at_deadline exits inside execute_pipeline_checked, which interacts with this PR. The ! arms decrement errexit_ignored before result? (src/exec.rs:2305, 2320), so a deadline stop inside ! doesn't leak the counter, and Shell::run resets it anyway.
  • cargo test --lib: 72 passed. cargo test --test shell_integration: 1955 passed, 4 of 4 full runs clean. cargo test --test lua_integration: 231 passed.
  • Before the merge, compound_pipe_stderr_timeout_reported_once (a 500 ms timeout) flaked in about a quarter of full runs on both 9b98a28 and b79cc88. It never failed at b56ac5c. It doesn't involve !, so I'm only mentioning it.
  • I ran 19 cases aimed at the fixes: ! ! true | { … } under set -e, pipefail, the form inside functions, loops, $(...) and if, the here-document case, and triple negation. All 19 match bash on the merged binary.
  • I reran the 257-case adversarial set against b79cc88: 16 rows now match bash, 0 got worse. The output is identical to the run with my suggested patch.
  • cargo fmt and clippy came from CI only; they aren't in my sandbox.

Evidence (S3, strands-agents/shell/pr/265/): test-integ-9b98a28.log, flake-rates.txt, followup-attack.txt, adv-results-9b98a28.txt.

@ferdingler
ferdingler merged commit 5d16d3f into strands-agents:main Nov 13, 2026
30 checks passed
@ferdingler
ferdingler deleted the fix/compound-status branch November 13, 2026 03:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants