headroom/tests/test_malloc_tuning.py
Tejas Chopra 96c25f5181
fix(cli): stop the macOS malloc re-exec replacing an embedder's process (#3064)
## Description

**`main` cannot currently run its own test suite on macOS.** `pytest
tests/` dies at roughly 2% with exit code 2 — no traceback, no summary,
no failing test named. The pytest process is simply gone.

Two independent defects, both landed today, both invisible to CI.

### 1. The macOS malloc re-exec replaces the calling process

`headroom proxy` re-execs itself once on Darwin to apply two libmalloc
knobs that libmalloc only reads before `main()` (#2820, PR #2879):

```python
os.execv(sys.executable, [sys.executable, "-m", "headroom.cli", *sys.argv[1:]])
```

That reconstruction is only faithful when the process really *is* the
Headroom CLI. Ten-plus test files invoke the `proxy` command in-process
through Click's `CliRunner`. There, `os.execv` replaces **pytest** with
a Headroom process holding pytest's argv. Run with `-s`, the mechanism
is visible:

```
tests/test_agent_savings.py Usage: python -m headroom.cli [OPTIONS] COMMAND [ARGS]...
Error: No such command 'tests/test_agent_savings.py::test_proxy_cli_reads_agent_90_profile_env'.
```

Everything after the first such test — roughly 98% of the suite — never
runs. The same hazard applies to any application embedding the CLI.

**The documented kill switch does not help.** `tests/conftest.py:41`
scrubs every `HEADROOM_*` variable for hermeticity, so
`HEADROOM_MALLOC_TUNING` is deleted before the guard reads it. Only the
private `_HEADROOM_MALLOC_TUNED` survives, because it starts with an
underscore.

**CI could not have caught this.** The tuning is Darwin-only, and while
the repo *does* have macOS jobs (`macos-native-wrapper`, `wrap-native
(macos-latest)`), neither runs the Python test suite — the `test` shards
are `ubuntu-latest` only. So `sys.platform != "darwin"` returns first
everywhere pytest actually runs. #2879 merged with 37 green checks.

### 2. A semantic merge conflict between two green PRs

#3051 added `bind_scope(tags, request.scope)` at `gemini.py:325` and
updated the three Gemini fakes it knew about. #3035 branched earlier and
added a fourth `_FakeRequest` without `.scope`. Each was green against
its own base; together they fail:

```
AttributeError: '_FakeRequest' object has no attribute 'scope'
```

Git merged both cleanly. Only running the suite on merged `main`
surfaces it.

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

## Changes Made

- Added `_process_is_headroom_cli_entrypoint()`: the re-exec now
verifies its own precondition — `argv[0]` must be the `headroom` console
script or `headroom/cli/__main__.py`.
- The embedded path returns **before** stamping
`_HEADROOM_MALLOC_TUNED`, so a genuine CLI child inheriting the
environment can still apply the tuning.
- Gave the Gemini `_FakeRequest` the `.scope` every real Starlette
`Request` carries.
- `test_reexec_skips_when_operator_already_set_vars` now sets a
realistic `argv[0]`, matching its sibling exec test.
- New `tests/test_cli_proxy_malloc_reexec_guard.py` asserting the
guard's logic on **every** platform, since no CI runner is macOS.

## Testing

- [x] Unit tests pass
- [x] Linting passes (ruff check + format)
- [ ] Type checking passes (`uv run mypy headroom`) — not run
- [x] New tests added for new functionality

### Test Output

Before, on `main`:

```text
$ .venv/bin/python -m pytest tests/ -q
collected 11622 items / 8 skipped
... tests/test_agent_savings.py ............................
$ echo $?
2
```

No summary line — the run does not end, it is replaced.

After, on this branch:

```text
$ .venv/bin/python -m pytest tests/ -q
3 failed, 11055 passed, 581 skipped, 6034 warnings in 303.69s (0:05:03)
```

All three remaining failures reproduce at `f9807fd6`, before today's
merges, and are unrelated:

| test | cause |
|---|---|
|
`test_graceful_shutdown::test_run_server_installs_cancelled_error_filter`
| full-suite ordering; passes in isolation (11 passed) |
|
`test_learn/test_integration::TestCodexIntegration::test_full_pipeline`
| pre-existing |
| `test_release_workflows::test_no_native_tls_in_wheel_build_tree` |
requires `cargo`, absent on this host |

## Real Behavior Proof

- Environment: macOS 15 (darwin 25.4.0), Python 3.12.13, arm64, real
checkout of `main` at `ef7e07e0`.
- Exact command / steps: bisected the crash to a single test, then to a
single commit — `be5b26d8` (parent) exits 0, `6d87825f` (#2879) exits 2.
Confirmed causation by temporarily replacing the `os.execv` line with
`return`, which makes the test pass. Recovered the mechanism by running
the crashing test with `-s`, which prints the Headroom CLI rejecting
pytest's own argv.
- Observed result: on `main` the suite cannot reach a summary; on this
branch it completes with 11,055 passing. The two-file reproduction
(`test_agent_savings.py` + `test_anthropic_beta_session_sticky.py`) goes
from exit 2 to 62 passed.
- Not tested: a real `headroom proxy` launch on macOS confirming
libmalloc still receives the knobs after re-exec. The guard is covered
by unit tests asserting `execv` is still called with `["-m",
"headroom.cli", "proxy", "--port", "8787"]` for a console-script
`argv[0]`, but I have not watched `vmmap` on a live proxy. **A macOS
maintainer should confirm #2820's RSS fix still works end to end before
this ships.**

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: no for a real CLI launch; the re-exec
no longer fires when the CLI is invoked in-process, which was never
intended to work.
- Kill switch / disable path: `HEADROOM_MALLOC_TUNING=0` still disables
the tuning outright.
- Unsafe override required: none.
- Qualification impact: none.
- Rollback path: revert this commit — but that restores a `main` whose
test suite cannot run on macOS.

## 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] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes

## Additional Notes

**This is my fault and worth recording.** I merged both #2879 and #3035
earlier today on the rule "approved + green CI". Both were genuinely
approved and genuinely green. Neither was rebased onto current `main`
first, and CI has no macOS runner, so green meant less than it appeared
to.

Two process gaps this exposes, neither of which this PR fixes:

1. **The Python test suite never runs on macOS.** The repo has macOS
jobs (`macos-native-wrapper`, `wrap-native (macos-latest)`), but the
`test` shards are `ubuntu-latest` only, so Darwin-only code paths — the
allocator tuning is one, `wrap` has others — are unreachable by pytest
in CI. Even a reduced macOS shard would have caught this.
2. **Nothing requires a PR to be current with `main` before merging.**
Both defects here are cross-PR interactions that no per-PR check can
see. Enabling "require branches to be up to date before merging" on
`main` would have forced a rebase and surfaced the Gemini fake.

I would suggest an issue for each rather than folding them in here.

Co-authored-by: Tejas Chopra <tejas@Tejass-MacBook-Pro.local>
2026-08-16 17:56:10 -07:00

292 lines
11 KiB
Python

"""macOS libmalloc tuning: pre-main re-exec gating + periodic allocator trim (#2820)."""
from __future__ import annotations
import asyncio
import pytest
import headroom.cli.proxy as proxy_cli
from headroom.proxy import malloc_trim
class _ExecCalled(Exception):
"""Sentinel so a fake execv can stop execution the way real execv would."""
def _fake_execv(recorder: dict):
def _execv(path, argv): # noqa: ANN001
recorder["path"] = path
recorder["argv"] = list(argv)
raise _ExecCalled
return _execv
@pytest.fixture(autouse=True)
def _clean_malloc_env(monkeypatch):
for var in (
"HEADROOM_MALLOC_TUNING",
"_HEADROOM_MALLOC_TUNED",
"MallocAggressiveMadvise",
"MallocLargeCache",
):
monkeypatch.delenv(var, raising=False)
# --------------------------------------------------------------------------- #
# _reexec_with_malloc_tuning
# --------------------------------------------------------------------------- #
def test_reexec_noop_off_darwin(monkeypatch):
monkeypatch.setattr(proxy_cli.sys, "platform", "linux")
rec: dict = {}
monkeypatch.setattr(proxy_cli.os, "execv", _fake_execv(rec))
proxy_cli._reexec_with_malloc_tuning() # must not raise / exec
assert rec == {}
def test_reexec_respects_opt_out(monkeypatch):
monkeypatch.setattr(proxy_cli.sys, "platform", "darwin")
monkeypatch.setenv("HEADROOM_MALLOC_TUNING", "0")
rec: dict = {}
monkeypatch.setattr(proxy_cli.os, "execv", _fake_execv(rec))
proxy_cli._reexec_with_malloc_tuning()
assert rec == {}
def test_reexec_guard_prevents_loop(monkeypatch):
monkeypatch.setattr(proxy_cli.sys, "platform", "darwin")
monkeypatch.setenv("_HEADROOM_MALLOC_TUNED", "1")
rec: dict = {}
monkeypatch.setattr(proxy_cli.os, "execv", _fake_execv(rec))
proxy_cli._reexec_with_malloc_tuning()
assert rec == {}
def test_reexec_skips_when_operator_already_set_vars(monkeypatch):
monkeypatch.setattr(proxy_cli.sys, "platform", "darwin")
# A real CLI launch, like the sibling exec test below: the tuning path is
# only reachable when this process is the Headroom CLI entrypoint, and
# under pytest argv[0] is pytest's own.
monkeypatch.setattr(proxy_cli.sys, "argv", ["headroom", "proxy"])
monkeypatch.setenv("MallocAggressiveMadvise", "1")
monkeypatch.setenv("MallocLargeCache", "0")
rec: dict = {}
monkeypatch.setattr(proxy_cli.os, "execv", _fake_execv(rec))
proxy_cli._reexec_with_malloc_tuning()
# No re-exec (vars present), but the guard is still stamped.
assert rec == {}
assert proxy_cli.os.environ.get("_HEADROOM_MALLOC_TUNED") == "1"
def test_reexec_sets_vars_and_execs_once(monkeypatch):
monkeypatch.setattr(proxy_cli.sys, "platform", "darwin")
monkeypatch.setattr(proxy_cli.sys, "executable", "/usr/bin/python3")
monkeypatch.setattr(proxy_cli.sys, "argv", ["headroom", "proxy", "--port", "8787"])
rec: dict = {}
monkeypatch.setattr(proxy_cli.os, "execv", _fake_execv(rec))
with pytest.raises(_ExecCalled):
proxy_cli._reexec_with_malloc_tuning()
# The tuning knobs and the loop guard are exported to the replacement process.
assert proxy_cli.os.environ["MallocAggressiveMadvise"] == "1"
assert proxy_cli.os.environ["MallocLargeCache"] == "0"
assert proxy_cli.os.environ["_HEADROOM_MALLOC_TUNED"] == "1"
# Re-exec normalizes to `python -m headroom.cli <args>`, preserving the PID.
assert rec["path"] == "/usr/bin/python3"
assert rec["argv"] == ["/usr/bin/python3", "-m", "headroom.cli", "proxy", "--port", "8787"]
# --------------------------------------------------------------------------- #
# malloc_trim.trim / trim_periodically
# --------------------------------------------------------------------------- #
def test_trim_calls_platform_fn(monkeypatch):
def fake_fn(ptr, size): # noqa: ANN001 (mac signature)
return 4096
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("darwin", fake_fn))
assert malloc_trim.trim() == 4096
def test_trim_never_runs_python_gc(monkeypatch):
# The periodic trim must NOT trigger a full cyclic collection: gc.collect()
# holds the GIL for a whole-heap traversal, which would stall the event loop
# even though the C purge itself is dispatched off-thread. Only the
# GIL-releasing allocator C call may run.
import gc
ran: list[str] = []
monkeypatch.setattr(gc, "collect", lambda *a, **k: ran.append("gc") or 0)
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("glibc", lambda _size: 0))
malloc_trim.trim()
assert ran == []
def test_trim_is_noop_on_unsupported_platform(monkeypatch):
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("unsupported", None))
assert malloc_trim.trim() == 0
def test_trim_periodically_trims_each_interval(monkeypatch):
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("glibc", object()))
trims: list[int] = []
monkeypatch.setattr(malloc_trim, "trim", lambda: trims.append(1) or 0)
async def fake_sleep(_seconds):
if len(trims) >= 2: # let two ticks run, then break the loop
raise asyncio.CancelledError
monkeypatch.setattr(malloc_trim.asyncio, "sleep", fake_sleep)
with pytest.raises(asyncio.CancelledError):
asyncio.run(malloc_trim.trim_periodically(interval_seconds=1))
assert len(trims) == 2
def test_trim_periodically_is_disabled_on_unsupported_platform(monkeypatch):
# No supported trim call: the task must return at once, never scheduling a
# wakeup (so it is a true no-op on Windows/musl, not a 60s spinner).
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("unsupported", None))
trims: list[int] = []
monkeypatch.setattr(malloc_trim, "trim", lambda: trims.append(1) or 0)
async def _no_sleep(_seconds):
raise AssertionError("unsupported platform must not schedule a trim wakeup")
monkeypatch.setattr(malloc_trim.asyncio, "sleep", _no_sleep)
asyncio.run(malloc_trim.trim_periodically(interval_seconds=60)) # returns, no raise
assert trims == []
@pytest.mark.parametrize("bad_interval", [0, -5])
def test_trim_periodically_rejects_non_positive_interval(monkeypatch, bad_interval):
# A non-positive interval would make asyncio.sleep return immediately and
# spin a continuous collect/trim loop; it must fall back to the default.
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("glibc", object()))
monkeypatch.setattr(malloc_trim, "trim", lambda: 0)
slept: list[float] = []
async def capture_sleep(seconds):
slept.append(seconds)
raise asyncio.CancelledError # stop after the first sleep
monkeypatch.setattr(malloc_trim.asyncio, "sleep", capture_sleep)
with pytest.raises(asyncio.CancelledError):
asyncio.run(malloc_trim.trim_periodically(interval_seconds=bad_interval))
assert slept == [malloc_trim._DEFAULT_TRIM_INTERVAL_SECONDS]
def test_trim_runs_off_the_event_loop_thread(monkeypatch):
# The blocking trim must run in a worker thread (via asyncio.to_thread), not
# on the event loop, so a slow trim cannot stall other async work.
import threading
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("glibc", object()))
seen: dict[str, int] = {}
def record():
seen["thread"] = threading.get_ident()
return 0
monkeypatch.setattr(malloc_trim, "trim", record)
calls = {"n": 0}
async def sleeper(_seconds):
calls["n"] += 1
if calls["n"] >= 2: # first sleep returns; after the trim, stop
raise asyncio.CancelledError
monkeypatch.setattr(malloc_trim.asyncio, "sleep", sleeper)
async def _run() -> int:
loop_thread = threading.get_ident()
with pytest.raises(asyncio.CancelledError):
await malloc_trim.trim_periodically(interval_seconds=60)
return loop_thread
loop_thread = asyncio.run(_run())
assert "thread" in seen # trim actually ran
assert seen["thread"] != loop_thread # ran off the event-loop thread
@pytest.mark.asyncio
async def test_slow_trim_does_not_stop_unrelated_async_work(monkeypatch):
# The periodic trim is dispatched off the event-loop thread via
# asyncio.to_thread and runs no Python gc.collect(), so even a slow purge
# must not freeze the loop. It is modeled here with a worker-thread park
# which, like the real GIL-releasing allocator C call, does not hold the
# GIL while it waits: unrelated coroutines keep making progress meanwhile.
import threading
monkeypatch.setattr(malloc_trim, "_resolve", lambda: ("glibc", object()))
started = threading.Event()
release = threading.Event()
def slow_trim() -> int:
started.set()
release.wait(5.0) # hold the worker thread until the test lets go
return 0
monkeypatch.setattr(malloc_trim, "trim", slow_trim)
# Fire the trim's interval immediately (the interval is >= 1s) while leaving
# the counter's sub-second sleeps to behave normally.
real_sleep = asyncio.sleep
async def smart_sleep(seconds):
if seconds >= 1:
return
await real_sleep(seconds)
monkeypatch.setattr(malloc_trim.asyncio, "sleep", smart_sleep)
ticks = 0
async def counter() -> None:
nonlocal ticks
while True:
await real_sleep(0.005)
ticks += 1
counter_task = asyncio.create_task(counter())
trim_task = asyncio.create_task(malloc_trim.trim_periodically(interval_seconds=60))
try:
# Wait for the trim to actually start blocking a worker thread.
for _ in range(400):
if started.is_set():
break
await real_sleep(0.005)
assert started.is_set(), "trim never started"
# The trim is now parked off-loop. The event loop must keep ticking.
ticks_before = ticks
await real_sleep(0.2)
ticks_during_trim = ticks - ticks_before
finally:
release.set()
counter_task.cancel()
trim_task.cancel()
# On-loop blocking would freeze the counter (~0 ticks); off-thread it keeps
# ticking (~40 in 0.2s). Generous floor for scheduler jitter.
assert ticks_during_trim >= 10
# --------------------------------------------------------------------------- #
# ProxyConfig wiring
# --------------------------------------------------------------------------- #
def test_proxy_config_malloc_trim_default_is_darwin_scoped(monkeypatch):
# Default-on only on macOS (the platform with the documented RSS ratchet);
# elsewhere it is opt-in, so glibc deployments do not silently take on a
# once-a-minute allocator purge.
from headroom.proxy import models
monkeypatch.setattr(models.sys, "platform", "darwin")
assert models.ProxyConfig().periodic_malloc_trim_enabled is True
monkeypatch.setattr(models.sys, "platform", "linux")
assert models.ProxyConfig().periodic_malloc_trim_enabled is False
# The interval knob is platform-independent.
assert models.ProxyConfig().malloc_trim_interval_seconds == 60