Skip to content

fix(python): release the GIL while Shell runs a command - #125

Merged
ferdingler merged 6 commits into
strands-agents:mainfrom
schinchli:fix/python-release-gil
Nov 21, 2026
Merged

ferdingler merged 6 commits into
strands-agents:mainfrom
schinchli:fix/python-release-gil

Conversation

@schinchli

Copy link
Copy Markdown
Contributor

Description

The Python Shell methods drive the tokio runtime with self.runtime.block_on(...) while holding the GIL. So while a command runs, no other Python thread runs and an asyncio event loop stalls. The repro from #119 on 0.3.3: a background thread gets 1 tick during run("sleep 2"), against 1,588 during a plain time.sleep(2).

cli_main in the same file already releases the GIL with py.detach(...). The methods on Shell can't do the same directly, because py.detach requires an Ungil (Send) closure, and the closure captures two things that aren't Send:

  • shell::Shell, which holds Rc<Vec<NamedMcpClient>>. This is the same constraint the comment on Worker in js.rs describes.
  • the tokio::task::LocalSet.

This PR adds one private helper, block_on_detached, and routes run, read_file, write_file, remove_file and list_files through it:

  • The LocalSet is created inside the closure, so it never has to cross detach.
  • The future, which borrows &mut shell::Shell, crosses detach in a small SameThread wrapper with unsafe impl Send.

Why the unsafe impl is sound. Python::detach runs the closure on the calling thread, so the Rc never actually changes thread. Shell is #[pyclass(unsendable)], so PyO3 rejects a call from any other thread, and the &mut self borrow held across detach rules out re-entry on the same thread. I checked the cross-thread case on both builds: a second thread calling run on the same Shell while a command is running gets PyO3's unsendable PanicException, the same as on 0.3.3.

The alternative, if you'd rather have no unsafe: mirror the Node binding and run the shell on a dedicated worker thread. That's a larger change to Shell's structure, so I went with the smaller one first. Happy to switch.

Related Issues

Fixes #119

Documentation PR

None needed. No public API changes.

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

Details:

  • New test_run_releases_the_gil counts a background thread's ticks during run("sleep 0.5"). It fails on 0.3.3 (assert 1 > 50) and passes with this change; I ran it 5 times in a row with no failures.
  • pytest tests/python: 45 passed (maturin develop --release, Python 3.14, macOS arm64).
  • cargo test --workspace --all-targets: 1,749 passed, 0 failed.
  • cargo fmt --check is clean, and RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --features python builds. cargo clippy --features python --lib reports nothing in src/python.rs; the lints it does report are in other files and already exist on main.
  • Manual checks with the patched build: the [BUG] Shell.run() holds the GIL while a command runs #119 repro now gives 1,337 ticks, against 1,343 for time.sleep(2). An asyncio task keeps ticking during asyncio.to_thread(lambda: Shell().run("sleep 1")). Shell state (X=42, then echo $X) persists across calls. write_file, read_file, list_files and remove_file behave as before.
  • npm test not run: the Node binding is untouched.

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.

@schinchli
schinchli requested a review from a team as a code owner October 1, 2026 18:05
@JackYPCOnline

Copy link
Copy Markdown
Contributor

@strandly-the-agent can you review it? I dont know if it is designed?

@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 — the design is right and the unsafe impl Send is sound. Two should-fix comment/doc nits inline; nothing blocking, no public API change.

To JackYPCOnline's question — is this the intended design? Yes, in my view:

  • Sound, and the pattern PyO3 itself describes. Python::detach runs its closure inline on the calling thread (pyo3 0.29 marker.rs:562-573), so nothing in SameThread ever changes thread. PyO3's own docs say "there is no reason to prevent !Send types like Rc from crossing the closure… detach does not itself launch a new thread". The real invariant is no Python references inside the closure, and that holds: nothing outside src/python.rs uses pyo3 (grep -rn pyo3 src --include=*.rs | grep -v python.rs → 0 hits).
  • Smallest fix. It is the first unsafe in src/ (only test env-var code had one), confined to one private type. The SAFETY comment argues the wrong invariant, though — see inline.
  • Worker-thread alternative (mirroring js.rs) would be more code but would also lift the unsendable restriction: today a Shell can only be used from the thread that created it, so asyncio.to_thread(shell.run, …) or a thread-pool tool raises PanicException. That is pre-existing and orthogonal to #119 — I'd keep this PR as-is and track the cross-thread story as a follow-up issue if you want it.
✅ Verified (head 8a5637c, Python 3.13.15, aarch64)
  • maturin develop --release + pytest tests/python -v → 45 passed; test_run_releases_the_gil passed 5/5 reruns.
  • Issue #119 repro: 1890 ticks during Shell().run("sleep 2") vs 1884 during time.sleep(2).
  • Cross-thread call on a shared Shell → PanicException (same as main; the check is in PyO3's trampoline, untouched). 4 Shells on 4 threads × sleep 1 → wall 1.00s. Shell(timeout=0.3).run("sleep 5") returns at 0.30s through detach. Panic inside a command leaves the Shell, GIL and other threads usable. Drop on another thread → PyO3's unraisable + leak, pre-existing.
  • Test margin: during > 50 measured 471–476 ticks idle and with 2 external busy processes; drops to 9–44 only with CPU-bound Python threads in the same process, which the suite doesn't have.
  • cargo fmt --check clean; cargo clippy --features python --lib → 0 warnings in src/python.rs (6 pre-existing elsewhere).
  • All five block_on sites converted; no block_on left outside the helper. No .pyi stubs or CHANGELOG to update.
  • Repro scripts/outputs and the pytest log are uploaded as review artifacts.
Questions (non-blocking)
  1. ShellBuilder.build (src/python.rs:414-423) still holds the GIL, and that's where copy-mode binds do their host I/O (vfs::copy_from_host, src/vfs_config.rs:273-275); js.rs:389 treats build as async for that reason. Measured 140 ms / 1 tick for a 93 MB copy bind. Deliberately out of scope for #119?
  2. Want a follow-up issue for the unsendable / cross-thread limitation (worker-thread design)? I can file it.
Reading order

src/python.rs:426-450 (wrapper + helper) → one call site, e.g. :478-492 → tests/python/test_bindings.py:273-294.

Appendix — non-blocking (3)
  • ⚪ src/python.rs module doc has no threading-model note while src/js.rs:12-20 does; a 2–3 line "GIL released per I/O method, runtime runs inline, cross-thread use rejected by unsendable" would keep the mirror symmetric (AGENTS.md:26).
  • ⚪ python/strands_shell/__init__.py:276-286 class docstring never says a Shell must be used on its creating thread; the asyncio users this fixes will hit PanicException (a BaseException) from asyncio.to_thread. Pre-existing.
  • Pre-existing, not filed (contrived input): sleep 1e300 panics in src/commands/sleep.rs:21 and the command reports status=0, empty stderr. Say so if you'd like an issue.

Comment thread src/python.rs Resolved
Comment thread src/python.rs Resolved
schinchli added a commit to schinchli/shell that referenced this pull request Oct 3, 2026
Address review on strands-agents#125: the Send impl is sound because Python::detach runs
its closure on the calling thread and the future holds no Python references,
not because of unsendable/&mut self. Move SameThread inside
block_on_detached so it can't be misused elsewhere, narrow the asyncio claim,
and document the single-thread requirement on Shell.run.
schinchli added a commit to schinchli/shell that referenced this pull request Oct 3, 2026
Address review on strands-agents#125: the Send impl is sound because Python::detach runs
its closure on the calling thread and the future holds no Python references,
not because of unsendable/&mut self. Move SameThread inside
block_on_detached so it can't be misused elsewhere, narrow the asyncio claim,
and document the single-thread requirement on Shell.run.
@schinchli
schinchli force-pushed the fix/python-release-gil branch from 84f6fc0 to 97b3df5 Compare October 3, 2026 04:02
@schinchli

Copy link
Copy Markdown
Contributor Author

@JackYPCOnline both review points from @strandly-the-agent are addressed in 97b3df5 (one commit on top of the original fix, docs/comments plus a scoping move, no behavior change). Details are in the two threads above.

Checked locally against what ci.yml runs:

  • cargo test --workspace --all-targets: 1749 passed, 0 failed
  • cargo doc --workspace --no-deps: clean
  • maturin develop --release + pytest tests/python: 45 passed, including the GIL regression test
  • cargo fmt --check: clean

The CI and PR-title workflows show action_required because this comes from a fork. Could you approve the workflow run? It should be ready to merge after that.

@JackYPCOnline

Copy link
Copy Markdown
Contributor

@strandly-the-agent re-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 — both previous findings are resolved in 97b3df5; no behaviour change, ready to merge once a maintainer approves the fork CI run.

  • 🟡 SAFETY comment → fixed. Now states the real invariant (detach runs inline; T holds no Python refs) and SameThread + its unsafe impl Send are scoped inside block_on_detached (src/python.rs:435-440), so the impl can't be reused elsewhere.
  • 🟡 asyncio over-claim → fixed. Rust doc now says "an asyncio loop on another thread" (src/python.rs:427); Shell.run docstring documents blocking/GIL release and the one-thread rule (python/strands_shell/__init__.py:361-365). The added "and dropped" is correct — off-thread drop produces PyO3's unraisable RuntimeError and leaks the object (re-ran my repro on this build).

The delta is comments/docs plus moving a private type, so I reviewed it directly rather than re-running the full adversarial pass. CI on 97b3df5 shows action_required (fork) for both workflows — needs a maintainer click; nothing I can do there.

✅ Verified on 97b3df5 (Python 3.13.15, aarch64)
  • maturin develop --release + pytest tests/python -v → 45 passed; test_run_releases_the_gil 3/3 reruns.
  • #119 repro: 1882 ticks during Shell().run("sleep 2") vs 1886 during time.sleep(2).
  • cargo fmt --all -- --check clean; cargo clippy --features python --lib → 0 warnings in src/python.rs; RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --features python builds (the fn-local [Python::detach] link is fine).
  • git diff 8a5637c 97b3df5 touches only src/python.rs (comment/doc text + the scoping move, call sites unchanged) and the run docstring. No test or behaviour change.
  • Open, non-blocking from last round: ShellBuilder.build still holds the GIL during copy-mode bind I/O; and whether to file a follow-up for the unsendable cross-thread limitation. Both are out of scope for #119.

@JackYPCOnline

Copy link
Copy Markdown
Contributor

@strandly-the-agent re-review before i approve

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

Still approve — head is unchanged (97b3df5), and it stays green against current main, including the pyo3 0.29 → 0.30.1 bump.

Previous findings: both 🟡s (SAFETY comment, asyncio doc) were fixed in 97b3df5 and verified on 2026-10-07; nothing new to raise. Since then only main moved (19 commits: dependabot bumps incl. pyo3 0.30.1 in #164, test-only changes incl. the new tests/python/test_api.py API pin). So this is a merge-freshness check of an already-reviewed head, not a new review — I didn't re-run the specialist passes.

What I re-checked, because the soundness argument depends on pyo3 internals: in pyo3 0.30.1 Python::detach still calls the closure inline under a SuspendAttach guard (marker.rs:562-573), Ungil is still impl<T: Send> (marker.rs:188-192), and the unsendable thread check is still there (impl_/pyclass.rs:1118,1129). The SameThread reasoning holds unchanged.

mergeStateStatus: BLOCKED is only because both workflow runs on 97b3df5 are still action_required (fork PR) — a maintainer needs to approve the run; it isn't a code issue.

✅ Verified on `main@347993a` + 97b3df5 (clean merge; Python 3.13.15, aarch64)
  • git merge of pr-125 onto origin/main → no conflicts; diff vs main is exactly the PR's 3 files.
  • maturin develop --release (pyo3 0.30.1) exit=0.
  • pytest tests/python -v → 69 passed (45 previous + 24 new from main, incl. test_api.py's run: (self, command: 'str') -> 'Output' signature pin). test_run_releases_the_gil 3/3 reruns.
  • #119 repro: 1892 ticks during Shell().run("sleep 2") vs 1888 during time.sleep(2).
  • cargo fmt --all -- --check clean; cargo clippy --features python --lib → 0 warnings in src/python.rs.
  • Logs uploaded as review artifacts.

Address review on strands-agents#125: the Send impl is sound because Python::detach runs
its closure on the calling thread and the future holds no Python references,
not because of unsendable/&mut self. Move SameThread inside
block_on_detached so it can't be misused elsewhere, narrow the asyncio claim,
and document the single-thread requirement on Shell.run.
@schinchli
schinchli force-pushed the fix/python-release-gil branch from 97b3df5 to 7292937 Compare November 7, 2026 15:49
@schinchli
schinchli requested a review from a team as a code owner November 7, 2026 15:49
@schinchli

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (it was 59 commits behind; no conflicts). The change is identical to the head the bot approved (97b3df5); only the base moved, so this is a fresh head (7292937) and CI needs a new "Approve and run workflows".

Verified locally on the rebased branch:

  • maturin develop --features python builds, and pytest tests/python gives 69 passed
  • cargo test --workspace --all-targets, cargo fmt --all -- --check and cargo clippy --workspace --all-targets pass; clippy reports the same 16 warnings as main, none in the files this PR touches
  • test_run_releases_the_gil catches the bug: against main's src/python.rs it fails (assert 1 > 50, so the GIL is held), and it passes with the fix

I have not run the Node or WASM checks, since this change only touches the Python binding.

@JackYPCOnline, you asked for a re-review before approving. The bot approved the previous head, and this one only moves the base. Could you approve the workflow run and take a look when you have a moment?

ferdingler and others added 4 commits November 9, 2026 21:47
Before Python 3.11, time.sleep on Windows rounds up to the ~15.6 ms
system timer tick, so a 0.5 s command yields only ~30-45 ticks and
'during > 50' fails there. A held GIL yields ~1 tick, so 'during > 10'
still catches the regression.
@ferdingler

Copy link
Copy Markdown
Collaborator

@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 at ec1e2f2 — the fix is unchanged from the head I approved before, and the new threshold commit is correct. @ferdingler

Since my last review (97b3df5) the only change to the PR's own files is assert during > 50 → > 10 in test_run_releases_the_gil; the rest is merges of main. src/python.rs and the docstring are byte-identical to what I reviewed, and main hasn't touched src/python.rs in between, so I reviewed the delta myself rather than re-running the full passes.

On the threshold change:

  • The cause in the commit message checks out. The failed run on 8b96bdb was Python (windows-latest, 3.10) with assert 44 > 50 — the GIL was released, the tick thread was just slow.
  • > 10 still catches the bug. With main's src/python.rs and this test I get assert 1 > 10 (fails, as it should); with the fix, 476 ticks at a 1 ms tick and 32 at a simulated 15.6 ms tick.

CI is green on ec1e2f2, including Windows 3.10. No new findings; both earlier threads stay resolved.

✅ Verified at ec1e2f2 (Linux aarch64, Python 3.13.16, pyo3 0.30.1)
  • git diff 97b3df5 ec1e2f2 over the PR's three files → only the 3-line threshold change in tests/python/test_bindings.py.
  • maturin develop --release exit 0; pytest tests/python -v → 69 passed, 0 skipped; test_run_releases_the_gil 10/10 reruns.
  • #119 repro: 1901 ticks during Shell().run("sleep 2") vs 1900 during time.sleep(2).
  • Negative control (git checkout origin/main -- src/python.rs, rebuild): test fails with assert 1 > 10; repro gives 1 tick vs 1899.
  • Coarse-timer simulation (tick thread sleeping 15.6 ms instead of 1 ms, 5 runs each): 32 ticks every run, vs 476 at 1 ms. I did not run on Windows; the 44 comes from the CI log.
  • pyo3 0.30.1 Python::detach still runs the closure inline (marker.rs:562-573), and src/python.rs is still the only file using pyo3, so the SameThread reasoning holds.
  • cargo fmt --all -- --check clean. cargo clippy --features python --lib: 6 warnings in src/python.rs, all the pyo3 skip_from_py_object deprecation at lines 49–217, identical on main and outside this diff.
  • tests/python/test_api.py signature pin for run passes, so the public Python signature is unchanged.
Questions — non-blocking (carried over, not new)
  • ShellBuilder.build() still holds the GIL during copy-mode bind I/O. Fine to leave for a follow-up.
  • A Shell is still unsendable, so asyncio.to_thread users hit a panic rather than a clear error; the docstring now says so. Worth an issue if you want that lifted.

@ferdingler
ferdingler removed request for a team and JackYPCOnline November 21, 2026 03:26
@ferdingler
ferdingler merged commit fb32fe0 into strands-agents:main Nov 21, 2026
33 checks passed
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.

[BUG] Shell.run() holds the GIL while a command runs

4 participants