Commit Graph
2 Commits
Author SHA1 Message Date
Raúl 3d3c629a9f fix(proxy): write per-port proxy logs so concurrent instances stop truncating each other (#3204)
## Description

Every proxy instance wrote the same two fixed files:
`~/.headroom/logs/proxy.log` (runtime log, via the `RotatingFileHandler`
in `_setup_file_logging`) and `~/.headroom/logs/proxy-stdio.log`
(subprocess stdout/stderr from `_start_proxy`). The name is a constant
(`paths.py` `_PROXY_LOG_FILE = "proxy.log"`), so N concurrent proxies on
different ports (wrapped copilot, droid, claude; plus any persistent
`install agent` deployment) run N independent rotating handlers over the
*same* file and truncate/rename each other's history.

This fix keys both files by port (`proxy-<port>.log`,
`proxy-stdio-<port>.log`) so each proxy rotates only its own file.
`headroom perf` aggregates every per-port file and still reads a lone
legacy `proxy.log` when that is all that exists (backward compat); the
`proxy-stdio-*` captures (raw stdout/stderr, not PERF records) are
excluded from the parser.

This matters more now that wrap-spawned proxies self-exit after an idle
grace (orphan-proxy watchdog, #3202): the process is gone, so its
per-port log is the only forensic evidence and must survive an unrelated
proxy's rotation.

Closes #3203

## Type of Change

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

## Changes Made

- `headroom/paths.py`: `proxy_log_path(port=None)` and new
`proxy_stdio_log_path(port=None)` are the single source of truth for the
filenames (`proxy-<port>.log` / `proxy-stdio-<port>.log` with a port,
legacy names without). The `_PROXY_LOG_FILE` constant stays only as the
readers' fallback name.
- `headroom/proxy/helpers.py`: `_setup_file_logging(port=None)` targets
`proxy_log_path(port)`. The duplicate-handler guard runs BEFORE the
`RotatingFileHandler` is constructed (construction opens the file), so a
second `create_app` on a different port in one process cannot leave an
empty stray `proxy-<port>.log` or leak an fd; a handler pointing at a
different port is replaced and closed so per-port keying holds.
- `headroom/proxy/server.py`: `create_app` resolves `config` first, then
calls `_setup_file_logging(config.port)` (the proxy always knows its own
port).
- `headroom/cli/wrap.py`: `_get_log_path(port=None)` /
`_get_proxy_stdio_log_path(port=None)` are per-port; `_start_proxy`
passes its `port`. The stdio filename comes from
`paths.proxy_stdio_log_path` (single source) and its directory from
`_get_log_path`.
- `headroom/perf/analyzer.py`: `parse_log_files` selects PERF logs by a
positive filename match (`_PERF_LOG_FILE_RE` =
`proxy(-<digits>)?.log(.N)?`) rather than a `proxy-stdio` blacklist, so
`proxy-stdio-*.log` and any other `proxy-<word>.log` are never ingested;
ordering is deterministic (mtime, then path).
- `headroom/cli/perf.py`, `wiki/cli.md`: doc/help text updated for
per-port + legacy.
- `tests/test_perf_per_port_logs.py` (new): per-port path helpers; a
second `_setup_file_logging` on a new port reroutes cleanly with no
cross-file leakage (regression for the guard-ordering bug); and
`parse_log_files` aggregates per-port + legacy while excluding stdio and
other non-PERF `proxy-*.log`.
- `tests/test_cli_proxy_env.py`, `tests/test_agent_savings.py`,
`tests/test_cli/test_wrap_{codex,claude_vertex_proxy_env,proxy_detach}.py`:
the `_get_log_path` monkeypatches take the new optional `port`, and the
two stdio-filename assertions/fixtures in `test_cli_proxy_env.py` use
the per-port name.

## Testing

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

### Test Output

```text
$ .venv/bin/python -m pytest tests/test_perf_per_port_logs.py tests/test_cli_proxy_env.py tests/test_agent_savings.py -q -p no:randomly
115 passed, 1 skipped in 4.44s

$ .venv/bin/python -m pytest tests/test_cli_perf_format.py tests/test_learn/test_analyzer.py -q
107 passed in 4.16s

$ .venv/bin/python -m pytest tests/test_cli/test_wrap_proxy_detach.py tests/test_cli/test_wrap_codex.py tests/test_cli/test_wrap_claude_vertex_proxy_env.py -q
120 passed in 171.19s

$ .venv/bin/ruff check <touched> && .venv/bin/ruff format --check <touched>
All checks passed!

$ .venv/bin/mypy headroom/paths.py headroom/cli/wrap.py headroom/proxy/helpers.py headroom/proxy/server.py headroom/perf/analyzer.py
Success: no issues found in 5 source files
```

Rust gate (`cargo clippy/test/fmt`) not run: Python-only change, no
crate touched.

## Real Behavior Proof

- Environment: macOS 26.5 arm64, Python 3.13, local editable source
build.
- Exact command / steps: `headroom proxy --port 8890` and `headroom
proxy --port 8891` started concurrently; inspected `~/.headroom/logs/`;
then `headroom perf --hours 1 --format json`.
- Observed result: each proxy wrote its own file (`proxy-8890.log`,
`proxy-8891.log`, independent), the pre-existing shared `proxy.log` was
not touched, and `headroom perf` reported `log_files_read: 4`,
aggregating per-port + legacy with no error.
`test_setup_file_logging_reroutes_on_port_change` additionally drives
the production helper twice in one process and asserts each port's
records land only in its own file.
- Not tested: Windows path semantics (filename construction is
platform-independent `pathlib`); a legacy `proxy.log` written by an OLD
binary running beside a new per-port one end to end (readers handle it,
but not exercised live).

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: N/A (no flag; readers accept both layouts).
- Stable/default behavior changed: log filenames change from `proxy.log`
to `proxy-<port>.log`; `headroom perf` reads both, so history is not
orphaned.
- Kill switch / disable path: N/A (no flag).
- Unsafe override required: no.
- Qualification impact: none — readers stay backward compatible with a
lone legacy `proxy.log`.
- Rollback path: revert; a downgraded binary writes legacy `proxy.log`
again and readers still aggregate any per-port files left behind.

Disk growth: each per-port family keeps the prior bound (`maxBytes=10 MB
× backupCount=5` = 60 MB), but there is now one family per distinct port
used instead of one global family. Ports are usually stable (default
8787; wrap auto-selects a nearby free port), so in practice a handful of
families; the theoretical worst case is bounded by the port scan
(`_find_available_port`, ≤100) → ≤ ~6 GB. No automatic pruning; stale
`proxy-<port>.log*` families can be deleted safely (perf reads whatever
remains). A retention policy is intentionally out of scope.

## 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
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] 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 — log-filename change; no UI.

## Additional Notes

Follow-up (separate SDK PR, not here): the TypeScript SDK helper
`sdk/typescript/src/paths.ts::proxyLogPath()` still returns legacy
`proxy.log` with no port argument and is pinned by `paths.test.ts`. It
mirrors `paths.py`, so it should gain an optional port argument in an
SDK PR (kept separate to stay one-surface, and because that package's
vitest suite is the right gate for it).
2026-09-09 15:54:34 -05:00
quentinmaisonneuve 6cba4419d0 fix(wrap): detach the shared proxy on Windows so it survives an ungraceful agent close (#1464)
## Description

Closing one `headroom wrap <agent>` instance on Windows could kill the
**shared proxy** out from under every other running instance, so their
requests started failing.

`_start_proxy` launched the proxy as a child of whichever agent started
it first, without detaching it from that agent's console and Job object.
The wrapper already reference-counts clients via per-PID markers and
`_make_cleanup` leaves the proxy running while other clients exist — but
that only runs on a *graceful* exit. On an *ungraceful* close (closing
the terminal window, `taskkill`, a crash) Windows tree-kills the whole
process group/Job and the proxy dies directly, bypassing the reference
counting. Every other instance's `ANTHROPIC_BASE_URL` then points at a
dead `127.0.0.1:8787`, so all of its API traffic fails.

## 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

- `_start_proxy` creates the proxy with `DETACHED_PROCESS |
CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB` on Windows, so an
ungraceful close of the launching agent can no longer reach it; only the
ref-counted `_make_cleanup` ends the proxy.
- Falls back without `CREATE_BREAKAWAY_FROM_JOB` (catching `OSError`)
when the launcher's Job forbids breakaway; `DETACHED_PROCESS` still
spares the proxy from console-close events.
- Platform guard is `sys.platform == "win32"` (not `os.name == "nt"`) so
mypy narrows the platform and resolves the Windows-only `subprocess`
constants.
- POSIX path unchanged: `creationflags=0`, detachment still via
`start_new_session` (`setsid`).
- Added `tests/test_cli/test_wrap_proxy_detach.py` and a CHANGELOG Bug
Fixes entry.

## 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
$ pytest tests/test_cli/test_wrap_proxy_detach.py -q
..                                                                       [100%]
2 passed, 2 warnings in 1.50s

$ ruff check headroom/cli/wrap.py tests/test_cli/test_wrap_proxy_detach.py
All checks passed!

$ mypy --follow-imports=silent headroom/cli/wrap.py tests/test_cli/test_wrap_proxy_detach.py
Success: no issues found
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.11.9, headroom-ai (pipx). Two
concurrent `headroom wrap claude` instances sharing proxy
`127.0.0.1:8787`. `_start_proxy` was also exercised directly on this
host with `subprocess.Popen` stubbed.
- Exact command / steps: (1) start two `headroom wrap claude` instances;
(2) close the terminal window of the one that started the proxy
(ungraceful — not `/exit`); (3) issue a request from the surviving
instance. Separately: call `_start_proxy(8787)` with `subprocess.Popen`
stubbed and read back the creation flags.
- Observed result: before the fix the proxy died with the closed window
and the surviving instance failed (`ANTHROPIC_BASE_URL` → dead `:8787`),
because the OS tree-killed the child before the ref-count path could
spare it. After the fix the detached proxy survives the close and the
surviving instance keeps working; the stub harness reports
`creationflags=0x1000208` (`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
| CREATE_BREAKAWAY_FROM_JOB`) on win32 and `0` when forced off-Windows.
- Not tested: real breakaway behavior under an actual restrictive Job
object on this host (the OS-level effect). The `OSError` fallback path
itself now has a dedicated unit test
(`test_start_proxy_retries_without_breakaway_when_job_forbids_it`).

## 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
- [x] 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 have updated the CHANGELOG.md if applicable

## Screenshots (if applicable)

N/A — no UI changes.

## Additional Notes

- Documentation checklist item is N/A: this is a behavioral bug fix with
no user-facing doc surface.
- Scope is the single `subprocess.Popen` call in `_start_proxy`; the
marker-based reference counting in `_make_cleanup` is unchanged and
remains the only thing that intentionally stops the proxy.
2026-06-30 13:49:28 -05:00