Files
headroom/tests/test_release_version.py
0712e048b0 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>
2026-10-01 16:09:44 -05:00

210 lines
6.0 KiB
Python

"""Tests for release version normalization and bumping."""
import os
import subprocess
import sys
from pathlib import Path
from unittest.mock import Mock
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,
)
ROOT = Path(__file__).resolve().parent.parent
def test_normalize_release_tag_preserves_three_part_tag() -> None:
assert str(normalize_release_tag("v0.5.20")) == "0.5.20"
def test_normalize_release_tag_collapses_four_part_tag() -> None:
assert str(normalize_release_tag("v0.5.25.2")) == "0.5.25"
def test_compute_patch_release_from_four_part_history() -> None:
info = compute_release_version(
canonical_version="0.5.25",
level="patch",
tags=["v0.5.20", "v0.5.25.1", "v0.5.25.2"],
)
assert info.version == "0.5.26"
assert info.npm_version == "0.5.26"
assert info.previous_tag == "v0.5.25.2"
assert info.bump == "patch"
def test_compute_minor_release_from_four_part_history() -> None:
info = compute_release_version(
canonical_version="0.5.25",
level="minor",
tags=["v0.5.20", "v0.5.25.1", "v0.5.25.2"],
)
assert info.version == "0.6.0"
assert info.npm_version == "0.6.0"
assert info.previous_tag == "v0.5.25.2"
assert info.bump == "minor"
def test_compute_patch_release_from_canonical_without_tags() -> None:
info = compute_release_version(
canonical_version="0.5.25",
level="patch",
tags=[],
)
assert info.version == "0.5.26"
assert info.npm_version == "0.5.26"
assert info.previous_tag == ""
def test_manual_version_override_uses_single_semver() -> None:
info = compute_release_version(
canonical_version="0.5.25",
level="patch",
tags=["v0.5.25.2"],
manual_version="0.6.0",
)
assert info.version == "0.6.0"
assert info.npm_version == "0.6.0"
assert info.previous_tag == ""
assert info.bump == "manual"
def test_manual_version_override_rejects_legacy_four_part_version() -> None:
with pytest.raises(ValueError, match="Invalid semantic version"):
compute_release_version(
canonical_version="0.5.25",
level="patch",
tags=["v0.5.25.2"],
manual_version="0.5.25.3",
)
def test_find_latest_release_tag_prefers_highest_normalized_version() -> None:
assert find_latest_release_tag(["v0.5.25.2", "v0.5.27", "not-a-tag"]) == "v0.5.27"
def test_find_latest_release_tag_prefers_higher_legacy_height_with_same_base() -> None:
assert find_latest_release_tag(["v0.5.25.2", "v0.5.25.3", "v0.5.25"]) == "v0.5.25.3"
def test_parse_release_tag_preserves_legacy_height_for_sorting() -> None:
tag = parse_release_tag("v0.5.25.3")
assert str(tag.version) == "0.5.25"
assert tag.legacy_height == 3
def test_classify_commit_bump_treats_breaking_change_as_major() -> None:
assert (
classify_commit_bump(
CommitInfo(subject="fix(api)!: change response shape", body=""),
)
== "major"
)
def test_determine_bump_level_uses_greatest_commit_level() -> None:
commits = [
CommitInfo(subject="fix: patch one", body=""),
CommitInfo(subject="feat: add capability", body=""),
CommitInfo(subject="chore: maintenance", body=""),
]
assert determine_bump_level(commits) == "minor"
def test_determine_bump_level_prefers_major_over_minor_and_patch() -> None:
commits = [
CommitInfo(subject="fix: patch one", body=""),
CommitInfo(subject="feat: add capability", body=""),
CommitInfo(
subject="docs: update migration guide",
body="BREAKING CHANGE: the API changed",
),
]
assert determine_bump_level(commits) == "major"
def test_list_release_commits_parses_empty_body_entries(
monkeypatch: pytest.MonkeyPatch,
) -> None:
run = Mock()
run.return_value = Mock(
stdout="feat: add capability\x1f\x1efix: patch bug\x1fbody text\x1e",
)
monkeypatch.setattr("headroom.release_version.run", run)
commits = list_release_commits(ROOT, "")
assert commits == [
CommitInfo(subject="feat: add capability", body=""),
CommitInfo(subject="fix: patch bug", body="body text"),
]
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:
output_path = tmp_path / "github-output.txt"
env = os.environ.copy()
env["GITHUB_OUTPUT"] = str(output_path)
env["LEVEL"] = "patch"
env["MANUAL_VER"] = "0.6.0"
result = subprocess.run(
[sys.executable, str(ROOT / "headroom" / "release_version.py")],
cwd=ROOT,
capture_output=True,
text=True,
env=env,
check=False,
)
assert result.returncode == 0, result.stderr
canonical_version = get_canonical_version(ROOT)
assert output_path.read_text(encoding="utf-8").splitlines() == [
"version=0.6.0",
"npm_version=0.6.0",
f"canonical={canonical_version}",
"height=0",
"bump=manual",
"previous_tag=",
]