Skip to content

Commit 96c25f5

Browse files
chopratejasTejas Chopra
andauthored
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>
1 parent ef7e07e commit 96c25f5

4 files changed

Lines changed: 132 additions & 0 deletions

File tree

headroom/cli/proxy.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import sys
66
import warnings
77
from importlib import import_module
8+
from pathlib import Path
89
from typing import Any, Literal, cast
910

1011
import click
@@ -125,13 +126,33 @@ def _get_env_bool_optional(name: str) -> bool | None:
125126
}
126127

127128

129+
def _process_is_headroom_cli_entrypoint() -> bool:
130+
"""Is this process the Headroom CLI itself, rather than an embedder?
131+
132+
``_reexec_with_malloc_tuning`` rebuilds the command line as
133+
``python -m headroom.cli <argv[1:]>``. That is only a faithful
134+
reconstruction when the process really was started as the Headroom CLI. If
135+
something else invoked the ``proxy`` command in-process — pytest's
136+
``CliRunner``, an embedding application, ``runpy`` — then ``argv[1:]``
137+
belongs to *that* program, and ``os.execv`` would replace it with a Headroom
138+
process parsing arguments that were never meant for us.
139+
"""
140+
argv0 = Path(sys.argv[0] or "")
141+
if argv0.name in {"headroom", "headroom.exe"}:
142+
return True
143+
# `python -m headroom.cli` sets argv[0] to .../headroom/cli/__main__.py.
144+
return argv0.parts[-3:] == ("headroom", "cli", "__main__.py")
145+
146+
128147
def _reexec_with_malloc_tuning() -> None:
129148
if sys.platform != "darwin":
130149
return
131150
if not _get_env_bool("HEADROOM_MALLOC_TUNING", True):
132151
return
133152
if os.environ.get("_HEADROOM_MALLOC_TUNED") == "1":
134153
return
154+
if not _process_is_headroom_cli_entrypoint():
155+
return
135156
missing = {k: v for k, v in _MALLOC_TUNING.items() if k not in os.environ}
136157
# Set the loop guard before the re-exec so the replacement process (which
137158
# inherits this environment) skips this path instead of re-execing forever.
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""The macOS malloc re-exec must never replace an embedder's process.
2+
3+
``headroom proxy`` re-execs itself once on Darwin to apply two libmalloc knobs
4+
that libmalloc only reads before ``main()`` (#2820). The re-exec rebuilds the
5+
command as ``python -m headroom.cli <argv[1:]>``, which is only a faithful
6+
reconstruction when this process really is the Headroom CLI.
7+
8+
When the ``proxy`` command is invoked *in-process* — pytest's ``CliRunner``, an
9+
embedding application — ``os.execv`` replaces that process instead. The whole
10+
pytest run is destroyed mid-suite with no traceback, and the replacement
11+
Headroom process is handed pytest's own argv.
12+
13+
CI cannot catch this: the tuning is Darwin-only and no CI runner is macOS, so
14+
these tests assert the guard's *logic* on every platform rather than relying on
15+
the re-exec being reachable.
16+
"""
17+
18+
from __future__ import annotations
19+
20+
import sys
21+
22+
import pytest
23+
24+
from headroom.cli import proxy as proxy_cli
25+
26+
27+
@pytest.mark.parametrize(
28+
"argv0",
29+
[
30+
"/usr/local/bin/headroom",
31+
"/opt/homebrew/bin/headroom",
32+
],
33+
)
34+
def test_console_script_is_recognised_as_the_entrypoint(
35+
argv0: str, monkeypatch: pytest.MonkeyPatch
36+
) -> None:
37+
monkeypatch.setattr(sys, "argv", [argv0, "proxy"])
38+
assert proxy_cli._process_is_headroom_cli_entrypoint() is True
39+
40+
41+
def test_module_invocation_is_recognised_as_the_entrypoint(
42+
monkeypatch: pytest.MonkeyPatch,
43+
) -> None:
44+
monkeypatch.setattr(
45+
sys, "argv", ["/venv/lib/python3.12/site-packages/headroom/cli/__main__.py", "proxy"]
46+
)
47+
assert proxy_cli._process_is_headroom_cli_entrypoint() is True
48+
49+
50+
@pytest.mark.parametrize(
51+
"argv0",
52+
[
53+
"/venv/bin/pytest",
54+
# `python -m pytest` — same basename as a module run, different package.
55+
"/venv/lib/python3.12/site-packages/pytest/__main__.py",
56+
"/usr/bin/uvicorn",
57+
"",
58+
],
59+
)
60+
def test_embedders_are_not_mistaken_for_the_entrypoint(
61+
argv0: str, monkeypatch: pytest.MonkeyPatch
62+
) -> None:
63+
monkeypatch.setattr(sys, "argv", [argv0, "proxy"])
64+
assert proxy_cli._process_is_headroom_cli_entrypoint() is False
65+
66+
67+
def test_reexec_does_not_exec_when_embedded(monkeypatch: pytest.MonkeyPatch) -> None:
68+
"""The end-to-end guard: no execv when another program owns the process."""
69+
monkeypatch.setattr(sys, "platform", "darwin")
70+
monkeypatch.setattr(sys, "argv", ["/venv/bin/pytest", "tests/"])
71+
monkeypatch.delenv("_HEADROOM_MALLOC_TUNED", raising=False)
72+
for key in proxy_cli._MALLOC_TUNING:
73+
monkeypatch.delenv(key, raising=False)
74+
75+
calls: list[object] = []
76+
monkeypatch.setattr(proxy_cli.os, "execv", lambda *a, **k: calls.append(a))
77+
78+
proxy_cli._reexec_with_malloc_tuning()
79+
80+
assert calls == []
81+
# The loop guard must not be set either: this process never applied the
82+
# tuning, so a genuine CLI child inheriting the env must still be free to.
83+
assert "_HEADROOM_MALLOC_TUNED" not in proxy_cli.os.environ
84+
85+
86+
def test_reexec_still_execs_for_a_real_cli_launch(monkeypatch: pytest.MonkeyPatch) -> None:
87+
"""The fix must not disable the feature it is guarding."""
88+
monkeypatch.setattr(sys, "platform", "darwin")
89+
monkeypatch.setattr(sys, "argv", ["/usr/local/bin/headroom", "proxy", "--port", "8787"])
90+
monkeypatch.delenv("_HEADROOM_MALLOC_TUNED", raising=False)
91+
for key in proxy_cli._MALLOC_TUNING:
92+
monkeypatch.delenv(key, raising=False)
93+
94+
calls: list[tuple] = []
95+
monkeypatch.setattr(proxy_cli.os, "execv", lambda *a, **k: calls.append(a))
96+
97+
proxy_cli._reexec_with_malloc_tuning()
98+
99+
assert len(calls) == 1
100+
_executable, argv = calls[0]
101+
assert argv[1:] == ["-m", "headroom.cli", "proxy", "--port", "8787"]
102+
for key, value in proxy_cli._MALLOC_TUNING.items():
103+
assert proxy_cli.os.environ[key] == value

tests/test_gemini_ccr_continuation_usage.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ def __init__(self) -> None:
2525
self.headers: dict[str, str] = {}
2626
self.query_params: dict[str, str] = {}
2727
self.url = SimpleNamespace(path="/v1beta/models/gemini-pro:generateContent", query="")
28+
# Every real Starlette Request carries a scope, and the Gemini handler
29+
# binds the savings-attribution ledger to it (#3051). Without this the
30+
# double is a shape that cannot occur in production.
31+
self.scope: dict = {"type": "http", "method": "POST"}
2832

2933

3034
class _CcrToolCallResponse:

tests/test_malloc_tuning.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ def test_reexec_guard_prevents_loop(monkeypatch):
6565

6666
def test_reexec_skips_when_operator_already_set_vars(monkeypatch):
6767
monkeypatch.setattr(proxy_cli.sys, "platform", "darwin")
68+
# A real CLI launch, like the sibling exec test below: the tuning path is
69+
# only reachable when this process is the Headroom CLI entrypoint, and
70+
# under pytest argv[0] is pytest's own.
71+
monkeypatch.setattr(proxy_cli.sys, "argv", ["headroom", "proxy"])
6872
monkeypatch.setenv("MallocAggressiveMadvise", "1")
6973
monkeypatch.setenv("MallocLargeCache", "0")
7074
rec: dict = {}

0 commit comments

Comments
 (0)