Repository navigation
fix(ci): fix three subprocess pipe deadlocks, ratchet raw subprocess use - #3748
Conversation
The SRC001 checker (ci/lint_python/subprocess_capture_checker.py) was never wired into the lint pipeline -- its four sibling checkers are registered in stage_impls.py and it is not. It has therefore never run, which is how ~246 unguarded stdlib subprocess usages accumulated. It also guarded the wrong API. `subprocess.run` internally calls `Popen.communicate()`, which drains both pipes concurrently and cannot deadlock on a full buffer. The dangerous API is bare `Popen` with pipes that nobody drains -- which the checker did not look at. Live deadlocks fixed: * ci/profile_runner.py -- the deadlock detector could deadlock itself. Both stdout and stderr were piped and neither was read until after the child exited. A test emitting past the ~64 KB pipe buffer blocked in write(), poll() never returned, and the harness reported a bogus TIMEOUT and attached a debugger to a process that was blocked on us not reading. Replaced the poll loop with communicate(timeout=...), which drains concurrently and leaves the child alive on timeout so the debugger still gets a live PID. * ci/tools/gh/workflow_scanner.py -- piped stderr and never read it. `gh api --paginate` writes progress and rate-limit text there; once full, gh blocked, stdout never hit EOF, and the reader hung before wait(timeout=60) was reached. Ran in a worker thread, so the scanner stalled silently. * ci/run-clang-format.py -- drained stdout to EOF before touching stderr, with the comment "hopefully the stderr pipe won't get full and block the process". It can. Also dropped an unreachable Python 2 branch. Checker changes: SRC001 (run+capture) reframed as a convention rule, SRC002 (Popen) for the real hazard, SRC003 (check_output/check_call), and SRC004 for capturing text-mode calls with no explicit encoding= -- the locale-codec trap that mojibakes or crashes on non-ASCII output under Windows cp1252. 52 files currently hit SRC004. Baselined per file+code so counts may shrink freely but never grow, and wired into stage_impls.py so it actually runs. Validated: 400 KB through run-clang-format's pipe without hanging (6x the buffer); 804 KB through profile_runner across both pipes; timeout path still fires at the right moment with a live PID. 551 passed / 39 skipped in ci/tests, lint green. test_fbuild_qemu.py fails identically before and after this change (pre-existing, docker/qemu environment). Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe PR expands subprocess linting with four rules and baseline ratcheting, integrates it into Ruff, and replaces several manual subprocess output-handling paths with concurrent capture, explicit decoding, and structured timeout cleanup. ChangesSubprocess lint ratchet
CI process output capture
Estimated code review effort: 4 (Complex) | ~45 minutes 🚥 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: 6
🧹 Nitpick comments (2)
ci/lint_python/subprocess_capture_checker.py (1)
180-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReturn a dataclass instead of a bare tuple for violations.
check_filereturnslist[tuple[int, str, str]], andvisitor.violations(Line 95) is the same shape. As per coding guidelines, "Return dataclass structs instead of tuples or dicts for functions with multiple return values", and "Use@typecheckeddecorator with@dataclassfor runtime type validation." A smallViolationdataclass (lineno,code,message) would self-document the fields consumed inmain()'s unpacking loop (Line 293) instead of relying on positional order.🤖 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 180 - 189, Introduce a typechecked dataclass named Violation with lineno, code, and message fields, then update check_file and SubprocessVisitor.violations to use list[Violation] instead of tuple types. Replace positional tuple construction and main()’s unpacking loop with Violation attribute access while preserving the existing values and behavior.Source: Coding guidelines
ci/profile_runner.py (1)
222-253: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
_run_with_timeoutno longer raisesTimeoutExpired— outer handler is now dead code.Since
proc.communicate(timeout=...)timeouts are now caught here and converted intoRunWithTimeoutResult(success=False, output="TIMEOUT", pid_if_timeout=pid), this method never re-raisessubprocess.TimeoutExpiredto its caller anymore. Theexcept subprocess.TimeoutExpired: ... return Falseblock inrun_benchmark(Line 317) can no longer trigger — the actual timeout path is already handled via thepid_if_timeoutcheck at Lines 283-285.♻️ Suggested cleanup (outside this range, in `run_benchmark`)
except subprocess.CalledProcessError as e: print(f"ERROR: {e}") return False(remove the preceding
except subprocess.TimeoutExpired: ... return Falseblock)🤖 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/profile_runner.py` around lines 222 - 253, Remove the now-unreachable subprocess.TimeoutExpired handler from run_benchmark, leaving the existing CalledProcessError handling intact; timeouts are already converted to RunWithTimeoutResult by _run_with_timeout and handled through pid_if_timeout.
🤖 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_capture_checker.py`:
- Around line 256-259: Update _is_excluded to compare exclude patterns against
path components or normalized path prefixes rather than using raw substring
containment, so an exclude such as “ci/tmp” matches its intended directory and
descendants but not paths like “ci/tmpfoo”. Preserve the existing boolean
behavior for genuinely excluded paths.
- Around line 98-126: Make noqa suppression code-specific in visit_Call instead
of skipping the entire call when _has_noqa returns true. Determine each
applicable SRC001–SRC004 violation independently, and suppress only the code
explicitly covered by the line’s noqa comment so co-occurring findings such as
SRC002 and SRC004 remain independently reportable.
In `@ci/lint/stage_impls.py`:
- Around line 552-564: Update the subprocess_capture_checker invocation in
run_ruff() to also exclude ci/wasm and .pio, matching the exclude set used by
the sibling lint checkers while retaining ci/tmp.
In `@ci/profile_runner.py`:
- Around line 204-218: Add or correct the SRC002 baseline entry for the
intentional subprocess.Popen call in the profile runner, using the repository’s
expected `ci/profile_runner.py|SRC002|...` format so the custom checker
recognizes the existing inline noqa suppression.
In `@ci/run-clang-format.py`:
- Around line 199-204: Update the DiffError raise in the OSError handler to
explicitly chain the original exception with “from exc”, preserving the causal
traceback while keeping the existing error message unchanged.
In `@ci/tools/gh/workflow_scanner.py`:
- Around line 240-243: Update the gh api result handling in the
workflow-scanning method around RunningProcess.run to validate result.returncode
before checking stdout. On failure, fail fast with a descriptive error that
includes the command failure details from result.stderr (and returncode as
appropriate), rather than returning error_blocks; preserve the existing
empty-stdout behavior only for successful requests.
---
Nitpick comments:
In `@ci/lint_python/subprocess_capture_checker.py`:
- Around line 180-189: Introduce a typechecked dataclass named Violation with
lineno, code, and message fields, then update check_file and
SubprocessVisitor.violations to use list[Violation] instead of tuple types.
Replace positional tuple construction and main()’s unpacking loop with Violation
attribute access while preserving the existing values and behavior.
In `@ci/profile_runner.py`:
- Around line 222-253: Remove the now-unreachable subprocess.TimeoutExpired
handler from run_benchmark, leaving the existing CalledProcessError handling
intact; timeouts are already converted to RunWithTimeoutResult by
_run_with_timeout and handled through pid_if_timeout.
🪄 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: f7ae94da-6129-4ee4-97b9-77262a8038e6
📒 Files selected for processing (6)
ci/lint/stage_impls.pyci/lint_python/subprocess_baseline.txtci/lint_python/subprocess_capture_checker.pyci/profile_runner.pyci/run-clang-format.pyci/tools/gh/workflow_scanner.py
| def visit_Call(self, node: ast.Call) -> None: # noqa: N802 | ||
| if not self._is_subprocess_run(node): | ||
| self.generic_visit(node) | ||
| return | ||
|
|
||
| # Skip if this call uses input= (stdin piping is not a deadlock risk) | ||
| if any(kw.arg == "input" for kw in node.keywords): | ||
| attr = self._subprocess_attr(node) | ||
| if attr is None: | ||
| self.generic_visit(node) | ||
| return | ||
|
|
||
| # Skip if this line has a noqa comment | ||
| if self._has_noqa(node.lineno): | ||
| self.generic_visit(node) | ||
| return | ||
|
|
||
| # Check keyword arguments for capture patterns | ||
| captures = self._captures_output(node) | ||
|
|
||
| if attr == "run" and captures: | ||
| self._add(node.lineno, "SRC001") | ||
| elif attr == "Popen": | ||
| self._add(node.lineno, "SRC002") | ||
| elif attr in ("check_output", "check_call"): | ||
| self._add(node.lineno, "SRC003") | ||
|
|
||
| # The decode hazard only exists when the parent actually reads and | ||
| # decodes the stream. Byte-mode capture is unaffected. | ||
| if ( | ||
| captures | ||
| and self._is_text_mode(node) | ||
| and not self._has_kwarg(node, "encoding") | ||
| ): | ||
| self._add(node.lineno, "SRC004") | ||
|
|
||
| self.generic_visit(node) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
_has_noqa suppresses ALL codes on a line, not just the one named in the comment.
visit_Call calls self._has_noqa(node.lineno) once and skips the whole call if truthy (Line 104-107), before any code-specific determination happens. Since SRC001-SRC004 can legitimately co-occur on the same call (e.g. a Popen(..., text=True) without encoding= triggers both SRC002 and SRC004), a targeted # noqa: SRC002 comment will also silently suppress the unrelated SRC004 encoding hazard on that line — defeating the per-code ratchet this PR is trying to introduce.
🐛 Proposed fix: make noqa suppression code-aware
def visit_Call(self, node: ast.Call) -> None: # noqa: N802
attr = self._subprocess_attr(node)
if attr is None:
self.generic_visit(node)
return
- if self._has_noqa(node.lineno):
- self.generic_visit(node)
- return
-
captures = self._captures_output(node)
if attr == "run" and captures:
self._add(node.lineno, "SRC001")
elif attr == "Popen":
self._add(node.lineno, "SRC002")
elif attr in ("check_output", "check_call"):
self._add(node.lineno, "SRC003")
if (
captures
and self._is_text_mode(node)
and not self._has_kwarg(node, "encoding")
):
self._add(node.lineno, "SRC004")
self.generic_visit(node)
def _add(self, lineno: int, code: str) -> None:
- self.violations.append((lineno, code, _MESSAGES[code]))
+ if not self._has_noqa(lineno, code):
+ self.violations.append((lineno, code, _MESSAGES[code]))- def _has_noqa(self, lineno: int) -> bool:
+ def _has_noqa(self, lineno: int, code: str) -> bool:
"""Check if a line has a noqa comment."""
if not self.source_lines or lineno < 1 or lineno > len(self.source_lines):
return False
line = self.source_lines[lineno - 1]
- return "noqa" in line and ("SRC0" in line or "noqa:" not in line)
+ if "noqa" not in line:
+ return False
+ match = re.search(r"noqa:\s*([A-Z0-9,\s]+)", line)
+ if not match:
+ return True # bare `# noqa` suppresses everything
+ return code in {c.strip() for c in match.group(1).split(",")}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def visit_Call(self, node: ast.Call) -> None: # noqa: N802 | |
| if not self._is_subprocess_run(node): | |
| self.generic_visit(node) | |
| return | |
| # Skip if this call uses input= (stdin piping is not a deadlock risk) | |
| if any(kw.arg == "input" for kw in node.keywords): | |
| attr = self._subprocess_attr(node) | |
| if attr is None: | |
| self.generic_visit(node) | |
| return | |
| # Skip if this line has a noqa comment | |
| if self._has_noqa(node.lineno): | |
| self.generic_visit(node) | |
| return | |
| # Check keyword arguments for capture patterns | |
| captures = self._captures_output(node) | |
| if attr == "run" and captures: | |
| self._add(node.lineno, "SRC001") | |
| elif attr == "Popen": | |
| self._add(node.lineno, "SRC002") | |
| elif attr in ("check_output", "check_call"): | |
| self._add(node.lineno, "SRC003") | |
| # The decode hazard only exists when the parent actually reads and | |
| # decodes the stream. Byte-mode capture is unaffected. | |
| if ( | |
| captures | |
| and self._is_text_mode(node) | |
| and not self._has_kwarg(node, "encoding") | |
| ): | |
| self._add(node.lineno, "SRC004") | |
| self.generic_visit(node) | |
| def visit_Call(self, node: ast.Call) -> None: # noqa: N802 | |
| attr = self._subprocess_attr(node) | |
| if attr is None: | |
| self.generic_visit(node) | |
| return | |
| captures = self._captures_output(node) | |
| if attr == "run" and captures: | |
| self._add(node.lineno, "SRC001") | |
| elif attr == "Popen": | |
| self._add(node.lineno, "SRC002") | |
| elif attr in ("check_output", "check_call"): | |
| self._add(node.lineno, "SRC003") | |
| # The decode hazard only exists when the parent actually reads and | |
| # decodes the stream. Byte-mode capture is unaffected. | |
| if ( | |
| captures | |
| and self._is_text_mode(node) | |
| and not self._has_kwarg(node, "encoding") | |
| ): | |
| self._add(node.lineno, "SRC004") | |
| self.generic_visit(node) |
🤖 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 98 - 126, Make
noqa suppression code-specific in visit_Call instead of skipping the entire call
when _has_noqa returns true. Determine each applicable SRC001–SRC004 violation
independently, and suppress only the code explicitly covered by the line’s noqa
comment so co-occurring findings such as SRC002 and SRC004 remain independently
reportable.
| def _is_excluded(path: Path, exclude_parts: list[str]) -> bool: | ||
| """Return True if any component of path matches an exclude pattern.""" | ||
| path_str = path.as_posix() | ||
| for exc in exclude_parts: | ||
| if exc in path_str: | ||
| return True | ||
| return False | ||
| return any(exc in path_str for exc in exclude_parts) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Substring-based exclude matching can over-match.
_is_excluded now does raw substring containment (exc in path_str) instead of component-aware matching. An exclude of "ci/tmp" would also match an unrelated path like ci/tmpfoo/bar.py, silently pulling files out of lint scope that were never meant to be excluded.
🔧 Suggested fix: match path components/prefixes, not arbitrary substrings
def _is_excluded(path: Path, exclude_parts: list[str]) -> bool:
"""Return True if any component of path matches an exclude pattern."""
path_str = path.as_posix()
- return any(exc in path_str for exc in exclude_parts)
+ return any(
+ path_str == exc or path_str.startswith(f"{exc}/") or f"/{exc}/" in path_str
+ for exc in exclude_parts
+ )📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def _is_excluded(path: Path, exclude_parts: list[str]) -> bool: | |
| """Return True if any component of path matches an exclude pattern.""" | |
| path_str = path.as_posix() | |
| for exc in exclude_parts: | |
| if exc in path_str: | |
| return True | |
| return False | |
| return any(exc in path_str for exc in exclude_parts) | |
| def _is_excluded(path: Path, exclude_parts: list[str]) -> bool: | |
| """Return True if any component of path matches an exclude pattern.""" | |
| path_str = path.as_posix() | |
| return any( | |
| path_str == exc or path_str.startswith(f"{exc}/") or f"/{exc}/" in path_str | |
| for exc in exclude_parts | |
| ) |
🤖 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 256 - 259, Update
_is_excluded to compare exclude patterns against path components or normalized
path prefixes rather than using raw substring containment, so an exclude such as
“ci/tmp” matches its intended directory and descendants but not paths like
“ci/tmpfoo”. Preserve the existing boolean behavior for genuinely excluded
paths.
| result = subprocess.run( | ||
| [ | ||
| "uv", | ||
| "run", | ||
| "python", | ||
| "ci/lint_python/subprocess_capture_checker.py", | ||
| "ci", | ||
| "test.py", | ||
| "--exclude", | ||
| "ci/tmp", | ||
| ], | ||
| capture_output=False, | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
New checker invocation is missing ci/wasm and .pio excludes used by every sibling checker.
Every other lint step in run_ruff() (ruff check/format, KBI checker, sys_path checker, dict_type checker) excludes ci/tmp, ci/wasm, and .pio. This new subprocess-ratchet call only excludes ci/tmp. The checked-in ci/lint_python/subprocess_baseline.txt has no entries under those trees, confirming they were never scanned when the baseline was generated — so any raw-subprocess usage there will surface as an unbaselined "regression" and fail this lint stage unexpectedly.
🔧 Proposed fix
result = subprocess.run(
[
"uv",
"run",
"python",
"ci/lint_python/subprocess_capture_checker.py",
"ci",
"test.py",
"--exclude",
"ci/tmp",
+ "ci/wasm",
+ ".pio",
],
capture_output=False,
)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| result = subprocess.run( | |
| [ | |
| "uv", | |
| "run", | |
| "python", | |
| "ci/lint_python/subprocess_capture_checker.py", | |
| "ci", | |
| "test.py", | |
| "--exclude", | |
| "ci/tmp", | |
| ], | |
| capture_output=False, | |
| ) | |
| result = subprocess.run( | |
| [ | |
| "uv", | |
| "run", | |
| "python", | |
| "ci/lint_python/subprocess_capture_checker.py", | |
| "ci", | |
| "test.py", | |
| "--exclude", | |
| "ci/tmp", | |
| "ci/wasm", | |
| ".pio", | |
| ], | |
| capture_output=False, | |
| ) |
🧰 Tools
🪛 Ruff (0.15.21)
[error] 553-562: Starting a process with a partial executable path
(S607)
🤖 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/stage_impls.py` around lines 552 - 564, Update the
subprocess_capture_checker invocation in run_ruff() to also exclude ci/wasm and
.pio, matching the exclude set used by the sibling lint checkers while retaining
ci/tmp.
| # Raw Popen is deliberate here: the timeout path has to attach a | ||
| # debugger to a *live* PID before killing it, which neither | ||
| # subprocess.run nor RunningProcess.run expose. See the drain note | ||
| # below for why communicate() rather than a poll loop. | ||
| proc = subprocess.Popen( # noqa: SRC002 - needs live PID on timeout | ||
| cmd, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| text=True, | ||
| # Test binaries print non-ASCII (arrows, box drawing) and this | ||
| # runs on Windows, where the locale codec is cp1252. | ||
| encoding="utf-8", | ||
| errors="replace", | ||
| env=env, | ||
| ) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
fd subprocess_capture_checker.py --exec cat -n {}Repository: FastLED/FastLED
Length of output: 15145
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate profile_runner.py =="
fd profile_runner.py
echo "== subprocess_baseline entries for ci/profile_runner.py =="
if [ -f ci/lint_python/subprocess_baseline.txt ]; then
rg -n "ci/profile_runner\.py\|subprocess_profile_runner\.py|profile_runner\.py" ci/lint_python/subprocess_baseline.txt || true
else
echo "baseline missing"
fi
echo "== relevant lines in ci/profile_runner.py =="
sed -n '190,225p' ci/profile_runner.py
echo "== Ruff config references =="
fd -a 'ruff.toml|\.ruff.toml|pyproject.toml|setup.cfg' . | sed 's#^\./##' | while read -r f; do
echo "--- $f ---"
rg -n "exclude|lint|extend-select|ignore|RUF102|SRC|external|per-file-ignores" "$f" || true
done
echo "== parse and probe inline noqa behavior from source =="
python3 - <<'PY'
from pathlib import Path
source = Path("ci/lint_python/subprocess_capture_checker.py").read_text()
print("Has noqa handler:", "_has_noqa" in source)
for needle in ['noqa: SRC002', 'SRC002']:
print(f"{needle!r}: {needle in source}")
PYRepository: FastLED/FastLED
Length of output: 2444
Address the baseline gap for this intentional subprocess.Popen call.
ci/profile_runner.py is not in ci/lint_python/subprocess_baseline.txt, so the custom checker still reports this as a new SRC002 regression despite the inline # noqa: SRC002 comment. Add the ci/profile_runner.py|SRC002|... baseline entry, or update that entry if this call was already baselined under a different path.
🧰 Tools
🪛 ast-grep (0.44.1)
[error] 207-217: Command coming from incoming request
Context: subprocess.Popen( # noqa: SRC002 - needs live PID on timeout
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
# Test binaries print non-ASCII (arrows, box drawing) and this
# runs on Windows, where the locale codec is cp1252.
encoding="utf-8",
errors="replace",
env=env,
)
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(subprocess-from-request)
🪛 Ruff (0.15.21)
[error] 208-208: subprocess call: check for execution of untrusted input
(S603)
[warning] 208-208: Invalid rule code in # noqa: SRC002
Add non-Ruff rule codes to the lint.external configuration option
(RUF102)
🤖 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/profile_runner.py` around lines 204 - 218, Add or correct the SRC002
baseline entry for the intentional subprocess.Popen call in the profile runner,
using the repository’s expected `ci/profile_runner.py|SRC002|...` format so the
custom checker recognizes the existing inline noqa suppression.
Source: Linters/SAST tools
| except OSError as exc: | ||
| raise DiffError( | ||
| "Command '{}' failed to start: {}".format( | ||
| subprocess.list2cmdline(invocation), exc | ||
| ) | ||
| ) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Chain the original exception with raise ... from exc.
Preserves the causal traceback for easier debugging when clang-format fails to start.
🐛 Proposed fix
except OSError as exc:
raise DiffError(
"Command '{}' failed to start: {}".format(
subprocess.list2cmdline(invocation), exc
)
- )
+ ) from exc📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| except OSError as exc: | |
| raise DiffError( | |
| "Command '{}' failed to start: {}".format( | |
| subprocess.list2cmdline(invocation), exc | |
| ) | |
| ) | |
| except OSError as exc: | |
| raise DiffError( | |
| "Command '{}' failed to start: {}".format( | |
| subprocess.list2cmdline(invocation), exc | |
| ) | |
| ) from exc |
🧰 Tools
🪛 Ruff (0.15.21)
[warning] 200-204: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
🤖 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/run-clang-format.py` around lines 199 - 204, Update the DiffError raise in
the OSError handler to explicitly chain the original exception with “from exc”,
preserving the causal traceback while keeping the existing error message
unchanged.
Source: Linters/SAST tools
| if not result.stdout: | ||
| return error_blocks | ||
|
|
||
| # Read all lines into memory (we need to do context lookback) | ||
| all_lines = [line.rstrip() for line in process.stdout] | ||
| process.wait(timeout=60) | ||
| all_lines = [line.rstrip() for line in result.stdout.splitlines()] |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Silent fallback on gh api failure — no returncode check.
RunningProcess.run is called without check=True, and only result.stdout truthiness is checked. If gh api ... --paginate fails (auth error, rate limit, 404) and stdout is empty, this silently returns error_blocks=[]; scan() then reports "No errors found!" even though log retrieval itself failed, with the failure reason (result.stderr/result.returncode) never surfaced.
🛡️ Suggested fix
if not result.stdout:
return error_blocks
+ if result.returncode != 0:
+ print(
+ f"gh api failed for {job.job_name} (exit {result.returncode}): {result.stderr}",
+ file=sys.stderr,
+ )
+ return error_blocks
+
all_lines = [line.rstrip() for line in result.stdout.splitlines()]As per coding guidelines, "Never use silent fallbacks for missing critical resources - always fail fast with descriptive errors."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if not result.stdout: | |
| return error_blocks | |
| # Read all lines into memory (we need to do context lookback) | |
| all_lines = [line.rstrip() for line in process.stdout] | |
| process.wait(timeout=60) | |
| all_lines = [line.rstrip() for line in result.stdout.splitlines()] | |
| if not result.stdout: | |
| return error_blocks | |
| if result.returncode != 0: | |
| print( | |
| f"gh api failed for {job.job_name} (exit {result.returncode}): {result.stderr}", | |
| file=sys.stderr, | |
| ) | |
| return error_blocks | |
| all_lines = [line.rstrip() for line in result.stdout.splitlines()] |
🤖 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/tools/gh/workflow_scanner.py` around lines 240 - 243, Update the gh api
result handling in the workflow-scanning method around RunningProcess.run to
validate result.returncode before checking stdout. On failure, fail fast with a
descriptive error that includes the command failure details from result.stderr
(and returncode as appropriate), rather than returning error_blocks; preserve
the existing empty-stdout behavior only for successful requests.
Source: Coding guidelines
The checker was never running
ci/lint_python/subprocess_capture_checker.py(SRC001) is not registered inci/lint/stage_impls.py, unlike its four sibling checkers (keyboard_interrupt,sys_path,dict_type,pyserial). It has never executed. That is how 246 unguarded stdlibsubprocessusages accumulated.It also guarded the wrong API
subprocess.runinternally callsPopen.communicate(), which drains both pipes concurrently (threads on Windows, selectors on POSIX). It cannot deadlock on a full buffer — the exact hazard SRC001 was written to prevent.The API that does deadlock is bare
Popenwith pipes nobody drains. The checker did not look atPopenat all.Three live deadlocks fixed
ci/profile_runner.py— the deadlock detector could deadlock itself. Both pipes were opened, neither read until after the child exited:A test emitting past the ~64 KB buffer blocks in
write(), sopoll()never returns, the loop runs to the full 120 s, and the harness reports a bogusTIMEOUTand attaches a debugger to a process that was blocked on us. Replaced withcommunicate(timeout=...), which drains concurrently and does not kill on timeout — so the debugger still gets a live PID.ci/tools/gh/workflow_scanner.py— piped stderr and never read it.gh api --paginatewrites progress and rate-limit text there; once that buffer filled,ghblocked, stdout never reached EOF, and the reader hung beforewait(timeout=60)was reached. It runs in a worker thread, so the scanner stalled with no diagnostic.ci/run-clang-format.py— drained stdout to EOF before touching stderr, with a comment conceding the risk:# hopefully the stderr pipe won't get full and block the processIt can. Also dropped an unreachable Python 2 branch (guarded by
sys.version_info[0] >= 3).Checker changes
subprocess.runwith capture — convention: preferRunningProcesssubprocess.Popen— the real deadlock hazardcheck_output/check_callencoding=SRC004 is worth calling out: 52 files hit it. Text mode without
encoding=decodes with the locale codec — cp1252 on Windows — so non-ASCII child output either mojibakes or raisesUnicodeDecodeErrorin the reader thread, surfacing asstdout is Noneand a confusing downstreamTypeError. This is the same class of bug as #3747.Note that
RunningProcessdoes not fix this by itself — I tested it. Without an explicitencoding, it produces mojibake rather than crashing, which is arguably worse for a tool that regex-matches its own output.Baseline + wiring
Baselined per file+code in
ci/lint_python/subprocess_baseline.txt. Counts may shrink freely; any increase fails. This gives ban semantics immediately without a 246-site diff, and lets the remaining sites be migrated incrementally.Registered in
stage_impls.pyso it actually runs.Validation
run-clang-format's pipe (6× the buffer) — completes, no hang. Previously the deadlock case.profile_runneracross both pipes — completes.handle_hung_test.splitlines(keepends=True)matches the oldreadlines()).551 passed, 39 skippedinci/tests;bash lintgreen.test_fbuild_qemu.pyfails identically before and after this change on a clean tree (pre-existing docker/qemu environment issue, not caused here).Deliberately not migrated
Left baselined with rationale — these need care rather than a mechanical swap:
ci/hooks/check-on-stop.py— the handle escapes to another thread that kills it mid-communicate().ci/util/pio_process_killer.py— a genericPopenfacade whose handle is registered in a global PID registry.ci/util/pio_package_daemon.py—shell=True+ a deliberately Git-Bash-free Windows env; ESP-IDF installs break if quoting changes.ci/tests/test_stale_lock_real_scenario.py— tests process-death semantics, so a wrapper adds risk without benefit.🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Quality Improvements