headroom/tests/test_cli/test_subprocess_utf8_encoding.py
Parideboy d633e8172c
fix(windows): pin UTF-8 encoding on text-mode subprocess calls (#1311)
Fixes #1310.

## Description

On Windows, `headroom` startup crashes a subprocess reader thread:

```
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 7894: character maps to <undefined>
  ... subprocess.py _readerthread -> buffer.append(fh.read())
  ... encodings/cp1252.py
```

Text-mode `subprocess` calls omit `encoding=`, so Python decodes child
output with the locale codec (**cp1252** on Windows). Children that emit
UTF-8 ??? `cbm index_repository` (indexing sources with chars like
`???`/`???`), `claude mcp get/add`, the memory-sync process ??? produce
bytes invalid in cp1252 and kill the reader thread. Linux/macOS default
to UTF-8, so it's invisible there.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- Add `encoding="utf-8", errors="replace"` to every text-mode
(`text=True` / `universal_newlines=True`) subprocess call in the
`headroom/` package (~50 call sites; several already had it).
- `errors="replace"` (not `ignore`) so corrupt bytes surface as `???`
rather than vanishing from parsed output.
- Add `tests/test_cli/test_subprocess_utf8_encoding.py`: an AST guard
asserting every text-mode subprocess call pins `encoding=`. The runtime
crash can't reproduce on UTF-8 CI, so the invariant is enforced at the
source level instead.

## Testing

- [x] Unit tests pass (`pytest`)
- New guard test passes (validates 51 call sites).
- `tests/test_install`, `tests/test_cli/test_mcp.py`,
`tests/test_mcp_registry` pass.
(`test_runtime_start_lock_blocks_another_process` fails on this Windows
box, but it fails identically on unmodified `main` ??? a pre-existing
`msvcrt` lock flake, unrelated.)

### Test Output

```text
> python -m pytest tests/test_cli/test_subprocess_utf8_encoding.py -q
1 passed in 0.12s

> python -m pytest tests/test_install/ tests/test_cli/test_mcp.py tests/test_mcp_registry/ -q
133 passed, 2 skipped in 15.34s
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13.13.
- Exact command / steps: Started `headroom` without `PYTHONUTF8=1` on a
repo with UTF-8 chars in indexable files. Observed the
`UnicodeDecodeError` crash. Applied the fix (pinning `encoding="utf-8"`
on all text-mode subprocess calls). Re-ran. No crash. The AST guard
enforces the invariant on CI (which runs UTF-8 locales and cannot
reproduce the cp1252 crash natively).
- Observed result: Subprocess reader threads no longer crash on UTF-8
output under cp1252 locale.
- Not tested: All third-party tools that `headroom` shells out to; each
was given `errors="replace"` as a safety net.

## Workaround for affected users (before fix is deployed)

`PYTHONUTF8=1` (PowerShell: `$env:PYTHONUTF8=1; headroom ...`).

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 12:52:49 -05:00

68 lines
2.5 KiB
Python

"""Guard: every text-mode subprocess call uses the shared wrapper.
On Windows, text-mode ``subprocess`` defaults to the locale codec (cp1252) when
``encoding=`` is omitted. Child output that is UTF-8 (e.g. a repo index printing
symbol names with ``↔``/``—``) then raises ``UnicodeDecodeError: 'charmap'`` in the
reader thread and aborts startup.
The fix is a shared wrapper at ``headroom._subprocess`` that automatically sets
``encoding="utf-8", errors="replace"`` when ``text=True`` or
``universal_newlines=True``. This test asserts that no raw ``subprocess.run`` /
``subprocess.Popen`` (or similar) call with ``text=True`` exists in the shipped
package — they must all go through the wrapper.
"""
from __future__ import annotations
import ast
from pathlib import Path
_PACKAGE = Path(__file__).resolve().parents[2] / "headroom"
_SKIP = {"_subprocess.py"}
_SUBPROCESS_FUNCS = {"run", "Popen", "check_output", "check_call", "call"}
def _kwarg(call: ast.Call, name: str) -> ast.keyword | None:
return next((k for k in call.keywords if k.arg == name), None)
def _is_true(node: ast.AST | None) -> bool:
return isinstance(node, ast.Constant) and node.value is True
def _is_raw_subprocess_call(call: ast.Call) -> bool:
func = call.func
return isinstance(func, ast.Attribute) and func.attr in _SUBPROCESS_FUNCS
def _offenders() -> list[str]:
bad: list[str] = []
for path in _PACKAGE.rglob("*.py"):
if path.name in _SKIP:
continue
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not _is_raw_subprocess_call(node):
continue
text_kw = _kwarg(node, "text")
un_kw = _kwarg(node, "universal_newlines")
text_mode = (text_kw is not None and _is_true(text_kw.value)) or (
un_kw is not None and _is_true(un_kw.value)
)
if text_mode:
rel = path.relative_to(_PACKAGE.parent)
bad.append(f"{rel}:{node.lineno}")
return bad
def test_text_mode_subprocess_calls_use_wrapper() -> None:
offenders = _offenders()
assert not offenders, (
"raw subprocess calls with text=True found (use headroom._subprocess wrapper):\n"
+ "\n".join(offenders)
)
if __name__ == "__main__": # pragma: no cover - manual run
test_text_mode_subprocess_calls_use_wrapper()
print("ok: all text-mode subprocess calls use the shared wrapper")