Skip to content

fix: exit the shell when exit runs inside a function - #222

Merged
ferdingler merged 4 commits into
strands-agents:mainfrom
ferdingler:fix/exit-inside-function
Nov 12, 2026
Merged

ferdingler merged 4 commits into
strands-agents:mainfrom
ferdingler:fix/exit-inside-function

Conversation

@ferdingler

@ferdingler ferdingler commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Description

exit inside a shell function only returned from the function, so the script kept going:

$ f(){ exit 6; }; f; echo no
no

with status 0. In bash that prints nothing and exits with 6.

Now exit in a function ends the shell, or only the subshell, command substitution or script it runs in, like bash. A function that exits as a pipeline stage or in a background job still ends only that stage or job, and return works as before. Other errors that end the shell when raised inside a function (${x?msg}, set -u unbound variables) now end the shell too, as in bash, instead of only returning from the function.

I compared about 30 cases against bash (loops, if, &&, !, groups, eval, nested functions, subshells, $( ), pipelines, background jobs, scripts, EXIT traps) and added tests for them. I also added tests so a function's exit can't carry over into the next Shell::run or MCP call. Assignment-only commands such as x=$(...) still set $? to 0; #232 covers that separately.

Related Issues

Part of #207

Documentation PR

N/A

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.

@ferdingler
ferdingler force-pushed the fix/exit-inside-function branch from 2b1d53d to 21002d6 Compare November 12, 2026 22:01
@ferdingler
ferdingler marked this pull request as ready for review November 12, 2026 22:01
@ferdingler
ferdingler requested a review from a team as a code owner November 12, 2026 22:01
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

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

Approve. exit inside a function now ends the shell, subshell, $( ) or script the same way bash does. I found no blocking issues. One 🟡 inline: keep the new pending_exit flag pub(crate) so it doesn't become public API (if it stays pub, this needs needs-api-review).

✅ What I verified
  • Tests: cargo test --workspace --all-targets at 21002d6 passed 2,226 tests with 0 failures (stable 1.100, debuginfo off).
  • Bash comparison: I ran 87 scripts under bash, a main binary and a PR binary. They cover if/while/until, &&/\|\|/!, groups, case, for, eval, nested functions, (…), $( ), pipelines in both directions, & with wait, redirects including failing ones, x=VAL f, command/builtin, EXIT traps, ${u?}, set -u, arrays, and a function exit followed by exit N.
  • No regressions: in every case that works on main, the PR either matches bash or behaves as main does. The headline case f(){ exit 6; }; f; echo no now gives no output and status 6, the same as bash (main printed no and returned 0).
  • Leftover state: a pending exit can't leak into the next call. execute and execute_with_reader reset both flags (src/exec.rs:194-195, :237-238). Every path through run_pipeline either goes through execute_pipeline_checked, which consumes the flag, or clears it itself (pipeline tails and the exec/command paths).
  • Removed early return: removing it in the function path (src/exec.rs:3469) also fixes $(f) output, which main threw away when the function exited (f(){ echo a; exit 3; }; X=$(f; echo after) now gives [a]).

Passes: the correctness and adversarial subagents both timed out at 900s without returning anything. Disk ran out during the first test build, which slowed them down. I read both role files and ran both passes inline instead, so this is a single-reviewer pass.

Appendix: non-blocking (3)
  • ⚪ Stale refused_array after a background job in $( ). At src/exec.rs:1845 the new Background arm swallows the Exit without clearing refused_array. The next function's exit in the same substitution is then ignored. Repro: g(){ exit 4; }; x=$(a=(1) & g; echo in); echo "x=$x" gives x=in on the PR and x= in both bash and main. With true & in place of the array the PR is correct. This needs an array inside a backgrounded command inside $( ), so it's unlikely in practice. Possible fix: add proc.refused_array = false; in that arm.
  • ⚪ Pre-existing, not filed (outside this PR's scope): trap 'exit 6' EXIT ends with status 0 instead of 6, and exit $(exit 6) gives 1 instead of 6. The second is in the same family as #232.
  • ⚪ Differences that come from syntax the shell doesn't support yet (<<<, time, select, [[ ]], <( ), declare) were the same on main. #207 already tracks them.

Evidence: s3://strandly-prod-artifacts-319426459652/strands-agents/shell/pr/222/ contains cargo-test.log, bash-parity.txt, repro-refused-array.sh and repro-refused-array.out.

Comment thread src/os.rs Resolved
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

Both findings are fixed in b8e912d. pending_exit is crate-private. The captured background path now clears the array-refusal flag before continuing, so the next function’s exit, nounset error, or ${missing?stop} still ends that substitution. All three regression tests failed before the fix and pass now.

Full workspace tests, fmt, clippy, doc tests, and warning-denied docs pass. The original 23 Bash comparisons still pass, plus five stdout/status checks for the new edge cases and normal return/background behavior. The pre-existing EXIT-trap and substitution-status gaps remain separate.

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

Approve at b8e912d. Both earlier findings are fixed, and I found nothing new.

  • 🟡 pending_exit is now pub(crate) (src/os.rs:151). Fixed.
  • ⚪ The captured background arm now clears refused_array (src/exec.rs:1848). Fixed. My repro x=$(a=(1) & g; echo in) now gives x=, the same as bash.
✅ What I verified
  • Tests: cargo test --workspace --all-targets at b8e912d passed 2,229 tests with 0 failures.
  • New tests: I deleted the one-line fix and re-ran the 3 new background_array_refusal_* tests. All 3 fail without it and pass with it restored.
  • Bash comparison: my 87 scripts from the last review give exactly the same output on b8e912d as on 21002d6, so nothing regressed.
  • Probing the fix: I tried scripts that might lose an exit after the flag is cleared: x=$(a=(1) & true; g; echo in), the same pattern inside a function (f(){ a=(1) & g; echo in-f; }), and return after a background job inside $( ). All three match bash. The flag only matters until the function returns, and this arm is where the exit gets swallowed, so clearing it there is the right place.

Evidence: s3://strandly-prod-artifacts-319426459652/strands-agents/shell/pr/222/cargo-test-b8e912d.log

@ferdingler
ferdingler force-pushed the fix/exit-inside-function branch from b8e912d to 3585172 Compare November 12, 2026 23:08
@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

Rebased onto main through 7000b66 in 3585172. The conflict with merged #217 is resolved: the compound pipeline keeps its producer status for pipefail and clears the function-exit flag at the pipeline boundary. The earlier visibility and array-refusal fixes remain intact.

Full workspace tests, fmt, clippy, doc tests, and warning-denied docs pass. All 38 Bash stdout/status comparisons pass, including ten new combined pipefail/function-exit cases covering both compound pipeline directions, command substitution, return, and errexit; 33 also compare stderr presence. GitHub now reports this PR mergeable. The final fetch included only the unrelated #218/#219 merges, and the combined merge tree was clean.

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

Approve at 3585172. The rebase over #217 is correct. Both compound pipeline paths keep the producer's status for pipefail and clear pending_exit after the tail, and the earlier fixes are still in place (src/os.rs:153, src/exec.rs:1848). I compared 107 scripts against bash and none got worse than on main. 2,353 tests pass.

One non-blocking item, from the same cause as the background-job fix: refused_array also goes stale when a captured compound pipeline's first stage refuses an array. Details below.

⚪ Stale refused_array in a captured compound pipeline

At src/exec.rs:2010-2011, a $( ) compound pipeline runs its first stage on the caller's proc, and captured_status(result, proc.last_exit) swallows the refusal's Exit without clearing the flag. The next function's exit in the same substitution is then ignored:

  • g(){ exit 4; }; x=$({ a=(1); } | cat; g; echo in); echo "x=$x" gives x=in. bash gives x=.
  • With { true; } in place of the array, the PR gives x= correctly. The flag is the cause.

This needs an array inside a compound pipeline inside $( ), so it's unlikely in practice. Possible fix: add proc.refused_array = false; after the captured_status call at line 2011.

✅ What I verified
  • Tests: cargo test --workspace --all-targets at 3585172 passed 2,353 tests with 0 failures.
  • Rebase: git range-diff against b8e912d shows commit 3 unchanged. Commits 1 and 2 differ only where #217's pipefail and opt_pipefail changes land.
  • Conflict resolution: in both compound pipeline paths, pending_exit = false follows the tail (src/exec.rs:2024, :2282). The producer status comes from captured_status, so a function exit there becomes its status for pipefail.
  • Bash comparison: I ran 107 scripts and compared stdout and exit status across bash, main at 7000b66 and the PR. Zero scripts that matched bash on main stop matching on the PR. The 20 new ones cover pipefail with a function exit on either side of a compound pipeline, in $( ), with !, return, set -e/-eo pipefail, while producers and three-stage pipelines, and all match bash except the item above. { f; } | { f; } fails to parse on both main and the PR (#207).
  • Passes: the rebase delta is a small conflict resolution plus a re-check of my earlier findings, so I reviewed it myself rather than spawning subagents.

Evidence: s3://strandly-prod-artifacts-319426459652/strands-agents/shell/pr/222/ contains cargo-test-3585172.log and bash-parity-3585172.txt.

@ferdingler

Copy link
Copy Markdown
Collaborator Author

@strandly-the-agent Please review this PR

Fixed the captured compound-pipeline refusal in 9c24ef2. Once the producer's control flow becomes its stage status, I clear refused_array before running the tail. A later function's exit, nounset error, or fatal parameter expansion now stops the substitution; return still returns only from the function.

All four new regression tests failed before the fix and pass now, including pipefail. I also audited the other status/control-flow consumption sites: forked processes are discarded, while redirected groups, eval, and source propagate the result. A 72-case CLI matrix covering nine refusal boundaries, four subsequent function outcomes, and pipefail on/off matches Bash stdout and exit status. It reproduced 12 failures before this fix, all at this compound boundary. Array diagnostics remain specific to this shell's unsupported-array behavior.

The full Rust test suite, fmt, clippy, doc tests, warning-denied docs, and the existing 38 Bash comparison probes pass. Please re-review the current head.

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

Approve at 9c24ef2. The compound-pipeline refused_array item from my last review is fixed, and I found nothing new.

  • ⚪ $( ) compound pipeline first stage (src/exec.rs:2013): fixed. g(){ exit 4; }; x=$({ a=(1); } | cat; g; echo in) now gives x=, the same as bash. return still returns only from the function (x=in 4, as in bash).
✅ What I verified
  • Tests: cargo test --workspace --all-targets at 9c24ef2 passed 2,357 tests with 0 failures.
  • New tests: I deleted the fix line at src/exec.rs:2013 and ran the 4 compound_array_refusal_* tests. All 4 fail without it and pass again once it's restored.
  • Fix placement: proc.refused_array = false; comes right after captured_status(result, proc.last_exit) turns the stage's control flow into a status, and before the tail runs. So a refusal in the tail still reaches the tail's own boundary.
  • Bash comparison: I ran 120 scripts and compared stdout and exit status across bash, main at 7000b66 and the PR. These are the 107 from my last review plus 13 new ones at this boundary: the refusal in the tail, three-stage pipelines, nested compound pipelines, the substitution inside a function, a redirected group, eval, and return. Zero scripts that matched bash on main stop matching on the PR.
  • Remaining differences: all expected. They come from syntax the shell doesn't support yet or the separate trap/substitution-status gaps, and the two new ones exist only because arrays are refused (bash runs them).
  • Passes: this delta is a two-line fix plus tests for my own finding, so I reviewed it myself rather than spawning subagents.

Evidence: s3://strandly-prod-artifacts-319426459652/strands-agents/shell/pr/222/ contains cargo-test-9c24ef2.log and bash-parity-9c24ef2.txt.

@ferdingler
ferdingler merged commit f1d4c37 into strands-agents:main Nov 12, 2026
30 checks passed
@ferdingler
ferdingler deleted the fix/exit-inside-function branch November 12, 2026 23:45
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