Repository navigation
fix: make ! invert a compound command and keep set -e from stopping on it - #265
Conversation
`! { ...; }`, `! ( ... )`, 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.
|
@strandly-the-agent please review |
strandly-the-agent
left a comment
There was a problem hiding this comment.
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 tripsset -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 fmtandclippyaren'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/executereset the cancellation test fails, and without theerrexit_ignored == 0check 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)
- Should
!match bash or POSIX/dash whenset -eis first turned on inside it? For! { set -e; false; echo x; }; echo $?with-eoff beforehand, bash and main exit 1, while the PR and dash printx 1. Bash only ignores errexit under!if it was already on when the!started. Gating the counter with*negated && proc.opt_errexitmatches bash on these rows. But it then breaks 4 rows this PR gets right, such as! { set -e; false; echo x; } || echo y, because&&/||/ifdon't propagate the ignored state inside. I'd keep the PR's behaviour and leave this as is. - If and while conditions still save, clear and restore
opt_errexit(src/exec.rs:1945,1978,2572,2597). That throws away aset ±erun inside a condition, and a cancelled call can leaveset -eoff. 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)
- ⚪
! ! falsereturns 0 (bash 1) on main too. The inline fix covers it. - ⚪
for i in 1 2; do ! { break; }; done; echo $?prints 0 (bash 1).! breakdoes 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 inrun_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 yexits (bash printsx),set -e; { false; echo in; } | catkeeps going pastfalse, and$(...)never appliesset -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.
|
Thanks. I took both fixes in 9b98a28.
Questions:
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
left a comment
There was a problem hiding this comment.
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_deadlineexits insideexecute_pipeline_checked, which interacts with this PR. The!arms decrementerrexit_ignoredbeforeresult?(src/exec.rs:2305,2320), so a deadline stop inside!doesn't leak the counter, andShell::runresets 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 | { … }underset -e,pipefail, the form inside functions, loops,$(...)andif, 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 fmtandclippycame 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.
Description
Putting
!in front of a compound command did nothing.! { false; },! ( false )and! if ...; fiall reported the compound's own status, soif ! (cmd) >/dev/null 2>&1; thentook the wrong branch. Claude Code's shell snapshot uses exactly that line. Separately,set -estopped 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 tripsset -e, and neither does anything that runs inside it. Aset -eorset +einside 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 -etests fail on main and pass with the change. I also added a guard so a call cancelled halfway through a!can't leaveset -eoff 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 -einside 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.
cargo test --workspace --all-targets,pytest tests/python,npm test)cargo fmtandcargo clippyChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.