Repository navigation
feat(lint): ban stdlib subprocess in favor of RunningProcess; hard-fail the deadlock shape - #3792
Conversation
…d-fail the deadlock shape
RunningProcess drains stdout and stderr concurrently through an atomic queue.
The stdlib API does not, and one shape of it hangs outright:
subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE) # only stdout read
Once the un-drained pipe fills its OS buffer (~64 KB Linux, ~8 KB Windows) the
child blocks and the parent waits for a child that can never finish.
Measured here rather than assumed:
- child writing 20k stderr lines, parent reading only stdout
-> never returned; killed at 60s
- identical child under RunningProcess
-> rc=0 in 0.3s, stdout intact
RunningProcess itself was audited first, since 42 call sites depend on it --
it drains both streams correctly, so no cross-repo fix was needed.
Rules
-----
- SRC001 now fires on EVERY `subprocess.run`, not only capturing ones. The
capture condition was hiding the majority of call sites from the ratchet:
scanning went from ~9 findings to 102 on the same tree.
- SRC003 additionally covers `subprocess.call`.
- SRC006 (new) covers `os.system` / `os.popen`, which previously escaped
entirely -- including the regex pre-filter, which only looked for
`subprocess.`.
- SRC005 (new) is the acute case: both pipes piped, no `communicate()`.
Unlike the others it is held at ZERO -- the baseline deliberately contains
no SRC005 entries, so a new one fails the build immediately. `communicate()`
anywhere in the enclosing function clears it, as does
`stderr=subprocess.STDOUT` or `DEVNULL`.
Three real SRC005 sites existed, all in ci/tests/test_stale_lock_real_scenario.py:
`Popen(stdout=PIPE, stderr=PIPE)` where stderr was never read on any path.
Fixed to `stderr=subprocess.DEVNULL`, which is behaviour-preserving -- the
output was already going nowhere -- and cannot pollute the stdout line parsing
the way STDOUT merging would. SRC005 is now 0.
Scope and wiring
----------------
The checker previously scanned only `ci` and `test.py`, so `tests/`,
`build.py` and `mcp_server.py` could accumulate deadlocks unseen. Now scanned;
they contribute no SRC005 and their pre-existing findings are baselined.
Baseline regenerated over the wider scope and wider rules: 346 findings across
164 entries. Counts may shrink freely and any increase fails, so the ban works
as a ratchet -- existing sites migrate to RunningProcess over time, no new ones
can appear.
Registered SRC001-006 in ruff's `external` list so `# noqa: SRC00x` is
understood rather than reported as an unused suppression.
CI: bound the board-build job
-----------------------------
`build_template.yml`'s `build` job had no `timeout-minutes`, so a hang ran to
GitHub's 360-minute default and was killed with no diagnostic. That is exactly
how every esp32s3 run stalled (#3791). Set to 45 minutes: board builds finish
well under 20, so this leaves headroom for a cold toolchain download while
turning a hang into a bounded, reportable failure.
Note this does NOT explain #3791 by itself -- no pipe deadlock was found in the
esp32s3 path, and the bloat gate's only spawn passes no pipes at all. The
timeout makes the next occurrence diagnosable instead of silent.
Verified: 14 new rule tests, 696 ci/tests passing, C++ suite green, lint clean.
Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe pull request expands subprocess lint rules for process spawning and undrained pipes, adds coverage and baseline entries, extends lint scan paths, updates spawned-process tests, and sets a 45-minute build timeout. ChangesSubprocess rule enforcement
Build timeout configuration
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
ci/lint_python/subprocess_capture_checker.py (1)
172-255: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAnnotate
selfin all new methods.The new methods omit annotations for
self. Apply the required explicit parameter annotation consistently.
ci/lint_python/subprocess_capture_checker.py#L172-L255: annotateselfin_is_os_spawn,_is_undrained_dual_pipe, and_function_calls_communicate.ci/tests/test_subprocess_deadlock_rules.py#L27-L133: annotateselfin each new test method.As per coding guidelines, “All function parameters MUST have explicit type annotations.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ci/lint_python/subprocess_capture_checker.py` around lines 172 - 255, Annotate the self parameter explicitly in _is_os_spawn, _is_undrained_dual_pipe, and _function_calls_communicate in ci/lint_python/subprocess_capture_checker.py:172-255, using the enclosing class type. Apply the same explicit self annotation to every new test method in ci/tests/test_subprocess_deadlock_rules.py:27-133.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ci/lint_python/subprocess_baseline.txt`:
- Around line 12-33: Update the documented baseline regeneration command in the
surrounding configuration so it scans the same roots as run_ruff(), including
tests and mcp_server.py, while preserving the existing exclusion. Apply the
equivalent command update to all repeated baseline-regeneration instructions
referenced by the comment.
In `@ci/lint_python/subprocess_capture_checker.py`:
- Around line 172-179: Update _is_os_spawn and the surrounding AST analysis to
resolve imported os aliases and direct imports before reporting SRC006. Track
import os aliases such as operating_system and from os import system/popen
bindings, recognize calls through those bindings alongside the existing
os.system/os.popen forms, and add coverage for both alias and direct-import
cases.
- Around line 221-255: The _function_calls_communicate method currently accepts
any .communicate() call in the enclosing function; track the variable assigned
from the relevant Popen call and only recognize communicate() invoked on that
result, excluding unrelated processes and nested functions. Add a regression
case covering two process variables where only the other process is communicated
with, ensuring SRC005 remains reported for the undrained Popen.
- Line 83: Update the `_SUBPROCESS_RE` pattern to use the regex word-boundary
escape `\b` before `os`, rather than the embedded literal backspace character,
while preserving matching for `os.system(` and `os.popen(`.
In `@pyproject.toml`:
- Around line 300-305: Add "SRC006" to the lint.external list in pyproject.toml,
alongside the existing SRC001–SRC005 entries, so Ruff recognizes the emitted
rule and noqa suppressions.
---
Nitpick comments:
In `@ci/lint_python/subprocess_capture_checker.py`:
- Around line 172-255: Annotate the self parameter explicitly in _is_os_spawn,
_is_undrained_dual_pipe, and _function_calls_communicate in
ci/lint_python/subprocess_capture_checker.py:172-255, using the enclosing class
type. Apply the same explicit self annotation to every new test method in
ci/tests/test_subprocess_deadlock_rules.py:27-133.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 507916d2-c868-4daa-a9c4-2b9046ccfb31
📒 Files selected for processing (7)
.github/workflows/build_template.ymlci/lint/stage_impls.pyci/lint_python/subprocess_baseline.txtci/lint_python/subprocess_capture_checker.pyci/tests/test_stale_lock_real_scenario.pyci/tests/test_subprocess_deadlock_rules.pypyproject.toml
| def _is_os_spawn(self, node: ast.Call) -> bool: | ||
| """True for `os.system(...)` / `os.popen(...)`.""" | ||
| func = node.func | ||
| if not isinstance(func, ast.Attribute): | ||
| return False | ||
| if not (isinstance(func.value, ast.Name) and func.value.id == "os"): | ||
| return False | ||
| return func.attr in ("system", "popen") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Resolve imported os bindings before reporting SRC006.
_is_os_spawn only recognizes the literal receiver name os. Both import os as operating_system; operating_system.system(...) and from os import system; system(...) bypass SRC006. Track import aliases and direct imports, then add coverage for both forms.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ci/lint_python/subprocess_capture_checker.py` around lines 172 - 179, Update
_is_os_spawn and the surrounding AST analysis to resolve imported os aliases and
direct imports before reporting SRC006. Track import os aliases such as
operating_system and from os import system/popen bindings, recognize calls
through those bindings alongside the existing os.system/os.popen forms, and add
coverage for both alias and direct-import cases.
There was a problem hiding this comment.
Fixed in fd42f9f — import os as osx and from os import system both bypassed the rule. Now resolved via visit_Import/visit_ImportFrom, with tests for aliased module, bare imported name, aliased bare name, and a negative case (from mymodule import system must stay clean).
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
git show --stat --oneline fd42f9f605
git show --format=fuller --find-renames --find-copies fd42f9f605 -- \
ci/lint_python/subprocess_capture_checker.py \
ci/tests/test_subprocess_deadlock_rules.py
printf '\n--- Checker symbols ---\n'
ast-grep outline ci/lint_python/subprocess_capture_checker.py \
--items all --type class,method --match 'SubprocessVisitor|visit_Import|visit_ImportFrom|_is_os_spawn' || true
printf '\n--- Relevant checker source ---\n'
rg -n -C 8 \
'def visit_Import|def visit_ImportFrom|def _is_os_spawn|os_module|os_spawn|system|popen' \
ci/lint_python/subprocess_capture_checker.py
printf '\n--- Relevant test source ---\n'
rg -n -C 8 \
'os as|from os import|mymodule import system|SRC006|os\.system|os\.popen' \
ci/tests/test_subprocess_deadlock_rules.pyLength of output: 1325
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Current checkout ---'
git status --short --branch
git log -n 12 --oneline -- \
ci/lint_python/subprocess_capture_checker.py \
ci/tests/test_subprocess_deadlock_rules.py
printf '%s\n' '--- Checker structure ---'
ast-grep outline ci/lint_python/subprocess_capture_checker.py \
--items all --type class,method \
--match 'SubprocessVisitor|visit_Import|visit_ImportFrom|_is_os_spawn' || true
printf '%s\n' '--- Import resolution and SRC006 logic ---'
rg -n -C 10 \
'def visit_Import|def visit_ImportFrom|def _is_os_spawn|os_module|os_spawn|os_bind|system|popen' \
ci/lint_python/subprocess_capture_checker.py
printf '%s\n' '--- SRC006 tests ---'
rg -n -C 10 \
'import os as|from os import|mymodule import system|SRC006|os\.system|os\.popen' \
ci/tests/test_subprocess_deadlock_rules.pyLength of output: 8201
@zackees, verification is inconclusive.
The sandbox checkout is still at 1a8b827a. It does not contain visit_Import, visit_ImportFrom, or the stated SRC006 test cases. Please retry after the sandbox updates to include fd42f9f605.
You are interacting with an AI system.
…3806) `bash lint` failed on a root `tmp.sh` -- a local debugging scratch script containing `pio run -v`: tmp.sh: Line 14: [pio_run] Forbidden: `pio run` as build invocation. ❌ PlatformIO-internal-usage: 1 violation(s) (gating). That file is matched by `.gitignore:87` (`tmp.*`). It cannot be committed and CI never sees it, so gating on it fails the lint for something no reviewer will ever look at, with no way to fix it other than deleting a file that belongs to whoever is debugging. `_collect_files()` walked the tree pruning only `_SKIP_DIRS`, with no notion of gitignore. It now asks `git check-ignore --stdin` once for the whole candidate list and drops what git ignores. Details worth keeping: - Repo-relative POSIX paths are fed in, because check-ignore echoes back exactly the spelling it was given; feeding the walk's absolute Windows paths made the results unmappable and the first cut silently filtered nothing. - Fails open. No git, not a checkout, or check-ignore erroring just means a few extra files get scanned -- never a missed violation. - Uses `RunningProcess` rather than stdlib subprocess, per the ban added in #3792. Verified both directions: the ignored `tmp.sh` is now skipped, and a tracked `ci/tmp_probe_tracked.sh` containing `pio run -v` is still caught and still exits 1. `bash lint` fully green. Co-authored-by: Claude <[email protected]>
Bans the stdlib
subprocessAPI in favour ofRunningProcess, and hard-fails the one shape that actually deadlocks.Measured, not assumed
RunningProcessdrains stdout and stderr concurrently through an atomic queue. The stdlib API does not, and this shape hangs outright:Once the un-drained pipe fills its OS buffer (~64 KB Linux, ~8 KB Windows) the child blocks, and the parent waits for a child that can never finish.
RunningProcessI audited
RunningProcessitself first, since 42 call sites depend on it — it drains both streams correctly, so no cross-repo fix was needed.Rules
subprocess.run, not only capturing ones. That capture condition was hiding most call sites from the ratchet: the same tree went from ~9 findings to 102.subprocess.call.os.system/os.popen, which escaped entirely — including the regex pre-filter, which only looked forsubprocess..communicate(). Unlike the others it is held at zero — the baseline deliberately has no SRC005 entries, so a new one fails the build immediately. Cleared bycommunicate()in the enclosing function, or bystderr=subprocess.STDOUT/DEVNULL.Precision check: SRC005 fires on exactly the 3 genuinely-risky sites and none of the ~13 provably-safe
communicate()sites.The three real sites
All in
ci/tests/test_stale_lock_real_scenario.py—Popen(stdout=PIPE, stderr=PIPE)where stderr is never read on any path. Fixed tostderr=subprocess.DEVNULL, which is behaviour-preserving (the output was already going nowhere) and, unlike merging into STDOUT, cannot pollute thePID:/READYline parsing those tests depend on. SRC005 is now 0.Scope and ratchet
The checker previously scanned only
ciandtest.py, sotests/,build.pyandmcp_server.pycould accumulate deadlocks unseen. Now scanned; they contribute no SRC005 and their pre-existing findings are baselined.Baseline regenerated over the wider scope and wider rules: 346 findings across 164 entries. Counts may shrink freely; any increase fails. So the ban is a ratchet — existing sites migrate to
RunningProcessover time, and no new ones can appear.Also registered
SRC001–SRC006in ruff'sexternallist, so# noqa: SRC00xis understood rather than reported as an unused suppression (none of the SRC codes were listed before).CI: bound the board-build job
build_template.yml'sbuildjob had notimeout-minutes, so a hang ran to GitHub's 360-minute default and was killed with no diagnostic — exactly how everyesp32s3run stalled (#3791). Set to 45 minutes; board builds finish well under 20, leaving headroom for a cold toolchain download.To be clear about what this does not do: it does not explain #3791. No pipe deadlock was found in the esp32s3 path, and the bloat gate's only spawn passes no pipes at all. The timeout makes the next occurrence diagnosable instead of silent.
Verification
14 new rule tests; 696
ci/testspassing; C++ suite green;bash lintclean.Pre-existing, not touched
ci/tests/test_stale_lock_real_scenario.pyfails all 3 tests under--runslow— identically on unmodified master. They're skipped by default, so this has gone unnoticed.bash lintgates on a gitignored local file (tmp.sh,.gitignore:87). Same on master; CI never sees it.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests
Chores