fix(mcp): bound version-detection git subprocess (#3038)

## Description

`headroom_compress` hangs (60s `-32001` MCP timeout) in stdio MCP
servers. Root cause: the compression pipeline init → OpenTelemetry
tracer → `get_version()` → `_source_tree_version()` →
`list_release_tags()` runs `git tag -l v*` via `subprocess.run` with no
timeout and inherited stdin. In a stdio MCP server, `git` inherits the
stdio pipe and hangs, so `await run_in_executor(...)` blocks until the
client's 60s timeout.

Fix: pass `stdin=DEVNULL` (stop inheriting the stdio pipe) +
`timeout=10` (fail gracefully through the existing `try/except` and
continue through the packaged, distribution-metadata, or `"unknown"`
fallback chain) on the three version-detection git calls.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/release_version.py`: add `stdin=subprocess.DEVNULL` +
`timeout=10` to `list_release_tags`, `list_release_commits`, and
`commit_height_since` git subprocess calls.
- `tests/test_release_version.py`: add
`test_version_detection_git_calls_are_hang_safe` asserting the three git
calls are bounded and do not inherit the caller's stdin.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ uv run --no-sync python -m pytest tests/test_release_version.py tests/test_observability_metrics.py -q
collected 29 items
tests\test_release_version.py ................                           [ 55%]
tests\test_observability_metrics.py .............                        [100%]
============================= 29 passed in 6.34s ==============================

$ uv run --no-sync ruff check .
All checks passed!

$ uv run --no-sync ruff format . --check
1415 files already formatted

$ uv run --no-sync mypy headroom/release_version.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: Windows 10, Python 3.13.13, headroom `0.36.0-dev`
(editable install), `headroom mcp serve` (stdio transport), no proxy.
- Exact command / steps: spawned `headroom mcp serve` and sent a raw MCP
`tools/call` for `headroom_compress` with
`{"content":"{"name":"test","items":[1,2,3,4,5]}"}`. Also verified
through the dsh web UI at http://127.0.0.1:3080 (same tool, routed
through a running proxy).
- Observed result: before the fix, `tools/call` hung 70s and returned
`Error: MCP error -32001: Request timed out`. After the fix,
`tools/call` returned in 2.38s:

```json
{"hash":"a76e1fa6b2611dc18b031c6d","original_tokens":24,"compressed_tokens":24,"tokens_saved":0,"transforms":["router:noop"]}
```

The dsh web UI returned the same hash `a76e1fa6b2611dc18b031c6d`.

- Not tested: `headroom_retrieve` / `headroom_stats` against a live
proxy; Linux/macOS stdio MCP clients; the git-hang path with a *running*
proxy (the proxy is not in the tool-call path — the hang reproduces with
no proxy).

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: version detection now fails
gracefully through the packaged, distribution-metadata, or `"unknown"`
fallback chain instead of hanging when a git subprocess exceeds 10s.
Compression behavior is unchanged.
- Kill switch / disable path: none — the timeout is a bounded safety
net; version detection is already best-effort behind `try/except`.
- Unsafe override required: no.
- Qualification impact: none (version detection is best-effort; failure
already continues through that fallback chain).
- Rollback path: revert this commit.

## Review Readiness

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

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

-
`tests/test_release_workflows.py::test_no_native_tls_in_wheel_build_tree`
fails locally with `FileNotFoundError` (missing Windows build tool) —
pre-existing and unrelated to this change.
- The commented-code and documentation checklist items are left
unchecked: the change is a small, self-documenting bug fix
(`stdin=DEVNULL` + `timeout=10` are self-explanatory), the rationale is
captured in the commit message and test docstring, and no API/behavior
surface changed to document.
- Not dsh-specific: this affects `headroom mcp serve` for any stdio
client (claude/codex/etc.).

Co-authored-by: Zenjibad <316719033+Zenjibad@users.noreply.github.com>
Co-authored-by: Jerrett Davis <mxjerrett@gmail.com>
This commit is contained in:
Zenjibad
2026-10-01 16:09:44 -05:00
committed by GitHub
co-authored by Zenjibad Jerrett Davis
parent 4257ed4df3
commit 0712e048b0
2 changed files with 30 additions and 0 deletions
+7
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import os
import re
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass, replace
from pathlib import Path
@@ -248,6 +249,8 @@ def list_release_tags(root: Path) -> list[str]:
check=True,
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=10,
)
return [tag.strip() for tag in result.stdout.splitlines() if tag.strip()]
@@ -267,6 +270,8 @@ def list_release_commits(root: Path, previous_tag: str) -> list[CommitInfo]:
check=True,
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=10,
)
commits: list[CommitInfo] = []
@@ -290,6 +295,8 @@ def commit_height_since(root: Path, previous_tag: str) -> str:
check=True,
capture_output=True,
text=True,
stdin=subprocess.DEVNULL,
timeout=10,
)
return result.stdout.strip() or "0"
+23
View File
@@ -11,11 +11,13 @@ import pytest
from headroom.release_version import (
CommitInfo,
classify_commit_bump,
commit_height_since,
compute_release_version,
determine_bump_level,
find_latest_release_tag,
get_canonical_version,
list_release_commits,
list_release_tags,
normalize_release_tag,
parse_release_tag,
)
@@ -156,6 +158,27 @@ def test_list_release_commits_parses_empty_body_entries(
]
def test_version_detection_git_calls_are_hang_safe(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Version-detection git subprocesses must not inherit the caller's stdin
and must be bounded — otherwise they hang ``headroom_compress``: the
compression pipeline initializes the OTel tracer, which calls
``get_version()`` → ``_source_tree_version()`` → these git calls."""
run = Mock()
run.return_value = Mock(stdout="")
monkeypatch.setattr("headroom.release_version.run", run)
list_release_tags(ROOT)
list_release_commits(ROOT, "")
commit_height_since(ROOT, "v0.1.0")
assert len(run.call_args_list) == 3
for call in run.call_args_list:
assert call.kwargs["stdin"] == subprocess.DEVNULL
assert call.kwargs["timeout"] == 10
def test_release_version_script_runs_directly_without_importing_headroom_package(
tmp_path: Path,
) -> None: