Repository navigation
fix(python): release the GIL while Shell runs a command - #125
Conversation
|
@strandly-the-agent can you review it? I dont know if it is designed? |
strandly-the-agent
left a comment
There was a problem hiding this comment.
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::detachruns its closure inline on the calling thread (pyo3 0.29marker.rs:562-573), so nothing inSameThreadever changes thread. PyO3's own docs say "there is no reason to prevent!Sendtypes likeRcfrom crossing the closure…detachdoes not itself launch a new thread". The real invariant is no Python references inside the closure, and that holds: nothing outsidesrc/python.rsuses pyo3 (grep -rn pyo3 src --include=*.rs | grep -v python.rs→ 0 hits). - Smallest fix. It is the first
unsafeinsrc/(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 theunsendablerestriction: today aShellcan only be used from the thread that created it, soasyncio.to_thread(shell.run, …)or a thread-pool tool raisesPanicException. 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_gilpassed 5/5 reruns.- Issue #119 repro: 1890 ticks during
Shell().run("sleep 2")vs 1884 duringtime.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 throughdetach. 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 > 50measured 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 --checkclean;cargo clippy --features python --lib→ 0 warnings insrc/python.rs(6 pre-existing elsewhere).- All five
block_onsites converted; noblock_onleft outside the helper. No.pyistubs or CHANGELOG to update. - Repro scripts/outputs and the pytest log are uploaded as review artifacts.
Questions (non-blocking)
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:389treats build as async for that reason. Measured 140 ms / 1 tick for a 93 MB copy bind. Deliberately out of scope for #119?- 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.rsmodule doc has no threading-model note whilesrc/js.rs:12-20does; a 2–3 line "GIL released per I/O method, runtime runs inline, cross-thread use rejected byunsendable" would keep the mirror symmetric (AGENTS.md:26). - ⚪
python/strands_shell/__init__.py:276-286class docstring never says a Shell must be used on its creating thread; the asyncio users this fixes will hitPanicException(aBaseException) fromasyncio.to_thread. Pre-existing. - Pre-existing, not filed (contrived input):
sleep 1e300panics insrc/commands/sleep.rs:21and the command reportsstatus=0, empty stderr. Say so if you'd like an issue.
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.
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.
84f6fc0 to
97b3df5
Compare
|
@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
The CI and PR-title workflows show |
|
@strandly-the-agent re-review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
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 (
detachruns inline;Tholds no Python refs) andSameThread+ itsunsafe impl Sendare scoped insideblock_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.rundocstring 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 unraisableRuntimeErrorand 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_gil3/3 reruns.- #119 repro: 1882 ticks during
Shell().run("sleep 2")vs 1886 duringtime.sleep(2). cargo fmt --all -- --checkclean;cargo clippy --features python --lib→ 0 warnings insrc/python.rs;RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --features pythonbuilds (the fn-local[Python::detach]link is fine).git diff 8a5637c 97b3df5touches onlysrc/python.rs(comment/doc text + the scoping move, call sites unchanged) and therundocstring. No test or behaviour change.- Open, non-blocking from last round:
ShellBuilder.buildstill holds the GIL during copy-mode bind I/O; and whether to file a follow-up for theunsendablecross-thread limitation. Both are out of scope for #119.
|
@strandly-the-agent re-review before i approve |
strandly-the-agent
left a comment
There was a problem hiding this comment.
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 mergeof pr-125 ontoorigin/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'srun: (self, command: 'str') -> 'Output'signature pin).test_run_releases_the_gil3/3 reruns.- #119 repro: 1892 ticks during
Shell().run("sleep 2")vs 1888 duringtime.sleep(2). cargo fmt --all -- --checkclean;cargo clippy --features python --lib→ 0 warnings insrc/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.
97b3df5 to
7292937
Compare
|
Rebased onto current Verified locally on the rebased branch:
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? |
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.
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
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)withassert 44 > 50— the GIL was released, the tick thread was just slow. > 10still catches the bug. Withmain'ssrc/python.rsand this test I getassert 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 ec1e2f2over the PR's three files → only the 3-line threshold change intests/python/test_bindings.py.maturin develop --releaseexit 0;pytest tests/python -v→ 69 passed, 0 skipped;test_run_releases_the_gil10/10 reruns.- #119 repro: 1901 ticks during
Shell().run("sleep 2")vs 1900 duringtime.sleep(2). - Negative control (
git checkout origin/main -- src/python.rs, rebuild): test fails withassert 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::detachstill runs the closure inline (marker.rs:562-573), andsrc/python.rsis still the only file using pyo3, so theSameThreadreasoning holds. cargo fmt --all -- --checkclean.cargo clippy --features python --lib: 6 warnings insrc/python.rs, all the pyo3skip_from_py_objectdeprecation at lines 49–217, identical onmainand outside this diff.tests/python/test_api.pysignature pin forrunpasses, 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
Shellis stillunsendable, soasyncio.to_threadusers hit a panic rather than a clear error; the docstring now says so. Worth an issue if you want that lifted.
Description
The Python
Shellmethods drive the tokio runtime withself.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 duringrun("sleep 2"), against 1,588 during a plaintime.sleep(2).cli_mainin the same file already releases the GIL withpy.detach(...). The methods onShellcan't do the same directly, becausepy.detachrequires anUngil(Send) closure, and the closure captures two things that aren'tSend:shell::Shell, which holdsRc<Vec<NamedMcpClient>>. This is the same constraint the comment onWorkerinjs.rsdescribes.tokio::task::LocalSet.This PR adds one private helper,
block_on_detached, and routesrun,read_file,write_file,remove_fileandlist_filesthrough it:LocalSetis created inside the closure, so it never has to crossdetach.&mut shell::Shell, crossesdetachin a smallSameThreadwrapper withunsafe impl Send.Why the
unsafe implis sound.Python::detachruns the closure on the calling thread, so theRcnever actually changes thread.Shellis#[pyclass(unsendable)], so PyO3 rejects a call from any other thread, and the&mut selfborrow held acrossdetachrules out re-entry on the same thread. I checked the cross-thread case on both builds: a second thread callingrunon the sameShellwhile a command is running gets PyO3'sunsendablePanicException, 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 toShell'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.
cargo test --workspace --all-targets,pytest tests/python,npm test)cargo fmtandcargo clippyDetails:
test_run_releases_the_gilcounts a background thread's ticks duringrun("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 --checkis clean, andRUSTDOCFLAGS="-D warnings" cargo doc --no-deps --features pythonbuilds.cargo clippy --features python --libreports nothing insrc/python.rs; the lints it does report are in other files and already exist onmain.time.sleep(2). An asyncio task keeps ticking duringasyncio.to_thread(lambda: Shell().run("sleep 1")). Shell state (X=42, thenecho $X) persists across calls.write_file,read_file,list_filesandremove_filebehave as before.npm testnot run: the Node binding is untouched.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.