Skip to content

fix(ci): fix three subprocess pipe deadlocks, ratchet raw subprocess use - #3748

Merged
zackees merged 1 commit into
masterfrom
fix/subprocess-popen-ratchet
Jul 28, 2026
Merged

zackees merged 1 commit into
masterfrom
fix/subprocess-popen-ratchet

Conversation

@zackees

@zackees zackees commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

The checker was never running

ci/lint_python/subprocess_capture_checker.py (SRC001) is not registered in ci/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 stdlib subprocess usages accumulated.

It also guarded the wrong API

subprocess.run internally calls Popen.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 Popen with pipes nobody drains. The checker did not look at Popen at 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:

proc = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, ...)
while True:
    if proc.poll() is not None:
        stdout, stderr = proc.communicate()   # first read, only AFTER exit
    time.sleep(0.1)

A test emitting past the ~64 KB buffer blocks in write(), so poll() never returns, the loop runs to the full 120 s, and the harness reports a bogus TIMEOUT and attaches a debugger to a process that was blocked on us. Replaced with communicate(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 --paginate writes progress and rate-limit text there; once that buffer filled, gh blocked, stdout never reached EOF, and the reader hung before wait(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 process

It can. Also dropped an unreachable Python 2 branch (guarded by sys.version_info[0] >= 3).

Checker changes

Code Rule
SRC001 subprocess.run with capture — convention: prefer RunningProcess
SRC002 subprocess.Popen — the real deadlock hazard
SRC003 check_output / check_call
SRC004 capturing text-mode call with no explicit encoding=

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 raises UnicodeDecodeError in the reader thread, surfacing as stdout is None and a confusing downstream TypeError. This is the same class of bug as #3747.

Note that RunningProcess does not fix this by itself — I tested it. Without an explicit encoding, 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.py so it actually runs.

Validation

  • 400 KB through run-clang-format's pipe (6× the buffer) — completes, no hang. Previously the deadlock case.
  • 804 KB through profile_runner across both pipes — completes.
  • Timeout path still fires at the correct moment and hands a live PID to handle_hung_test.
  • Diff output verified byte-compatible (splitlines(keepends=True) matches the old readlines()).
  • 551 passed, 39 skipped in ci/tests; bash lint green.
  • test_fbuild_qemu.py fails 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 generic Popen facade 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

    • Improved process execution reliability by preventing hangs when commands produce large amounts of output.
    • Improved timeout handling and diagnostics for stalled profile runs.
    • Improved workflow log retrieval reliability, including safer output decoding.
  • Quality Improvements

    • Expanded automated checks for discouraged subprocess usage.
    • Added baseline tracking to identify new violations without disrupting existing approved cases.
    • Modernized formatting checks and clarified related error reporting.

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]>
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Subprocess lint ratchet

Layer / File(s) Summary
Multi-rule checker and baseline comparison
ci/lint_python/subprocess_capture_checker.py
The AST checker detects SRC001–SRC004 patterns, tracks violations by file and rule, and compares findings against a deterministic baseline.
Lint-stage enforcement and baseline data
ci/lint/stage_impls.py, ci/lint_python/subprocess_baseline.txt
The Ruff stage runs the checker, while the baseline documents existing findings and their allowed counts.

CI process output capture

Layer / File(s) Summary
Profile runner timeout handling
ci/profile_runner.py
Profile execution uses communicate(timeout=...), decodes output as UTF-8, and kills and reaps timed-out processes.
Clang-format execution migration
ci/run-clang-format.py
Clang-format execution uses RunningProcess for concurrent output capture and structured process errors.
Workflow log retrieval migration
ci/tools/gh/workflow_scanner.py
Workflow log retrieval uses RunningProcess with timeout handling and derives lines from captured stdout.

Estimated code review effort: 4 (Complex) | ~45 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main CI fix and subprocess lint ratchet introduced by the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/subprocess-popen-ratchet

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (2)
ci/lint_python/subprocess_capture_checker.py (1)

180-189: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Return a dataclass instead of a bare tuple for violations.

check_file returns list[tuple[int, str, str]], and visitor.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 @typechecked decorator with @dataclass for runtime type validation." A small Violation dataclass (lineno, code, message) would self-document the fields consumed in main()'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_timeout no longer raises TimeoutExpired — outer handler is now dead code.

Since proc.communicate(timeout=...) timeouts are now caught here and converted into RunWithTimeoutResult(success=False, output="TIMEOUT", pid_if_timeout=pid), this method never re-raises subprocess.TimeoutExpired to its caller anymore. The except subprocess.TimeoutExpired: ... return False block in run_benchmark (Line 317) can no longer trigger — the actual timeout path is already handled via the pid_if_timeout check 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 False block)

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between fab494d and 3ca8b5b.

📒 Files selected for processing (6)
  • ci/lint/stage_impls.py
  • ci/lint_python/subprocess_baseline.txt
  • ci/lint_python/subprocess_capture_checker.py
  • ci/profile_runner.py
  • ci/run-clang-format.py
  • ci/tools/gh/workflow_scanner.py

Comment on lines 98 to +126
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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.

Comment on lines 256 to +259
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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.

Comment thread ci/lint/stage_impls.py
Comment on lines +552 to +564
result = subprocess.run(
[
"uv",
"run",
"python",
"ci/lint_python/subprocess_capture_checker.py",
"ci",
"test.py",
"--exclude",
"ci/tmp",
],
capture_output=False,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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.

Comment thread ci/profile_runner.py
Comment on lines +204 to 218
# 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,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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}")
PY

Repository: 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

Comment thread ci/run-clang-format.py
Comment on lines 199 to 204
except OSError as exc:
raise DiffError(
"Command '{}' failed to start: {}".format(
subprocess.list2cmdline(invocation), exc
)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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

Comment on lines +240 to +243
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()]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested change
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

@zackees
zackees merged commit 0331078 into master Jul 28, 2026
19 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 28, 2026
@zackees
zackees deleted the fix/subprocess-popen-ratchet branch August 21, 2026 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant