mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 10:27:23 +08:00
feat/https-compose-caddy
38
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
00d4f441d3 |
fix(memory): gracefully degrade on context lookup and initialization errors (#3251) (#4049)
## Description When `--memory` is enabled, memory backend initialization or database access failures (such as `sqlite3.OperationalError: unable to open database file` on bind mounts or invalid SQLite stores) caused request handlers to raise unhandled exceptions and abort client requests with HTTP 500. This change ensures that memory lookup and backend initialization failures degrade gracefully by logging a warning and continuing request processing without memory context (`memory_context = None`). Closes #3251 ## 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 - In `headroom/proxy/memory_handler.py:search_and_format_context`: wrapped `_ensure_initialized()` and `_resolve_for_request()` in a `try...except Exception` block, logging a warning and returning `None` on failure. - In `headroom/proxy/handlers/anthropic.py:handle_anthropic_messages`: added an `except Exception as e:` handler for memory context lookup to prevent lookup errors from raising unhandled exceptions out of the request handler. - In `headroom/proxy/handlers/openai.py`: added `except Exception as e:` handlers in Responses API (`handle_openai_responses`) and WebSocket (`handle_realtime_websocket`) context search blocks. - Added regression tests in `tests/test_anthropic_pre_upstream_backpressure.py` and `tests/test_memory_handler_native_ops.py`. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text tests/test_anthropic_pre_upstream_backpressure.py .. [100%] 2 passed in 1.56s tests/test_memory_handler_native_ops.py .................................. [100%] 34 passed in 1.57s ``` ## Real Behavior Proof - Environment: Linux x86_64, Python 3.14 - Exact command / steps: `pytest -q tests/test_anthropic_pre_upstream_backpressure.py -k test_memory_context && pytest -q tests/test_memory_handler_native_ops.py` - Observed result: Verified `test_memory_context_exception_fails_open_and_releases_semaphore` and `test_search_and_format_context_degrades_gracefully_on_backend_error` pass cleanly. - Not tested: None ## Runtime Rollout Safety - Rollout-managed feature(s): None - Minimum rollout channel: stable - Stable/default behavior changed: No (gracefully falls back when memory store is unavailable rather than returning 500) - Kill switch / disable path: Disable memory with `--memory false` or omitting `--memory` - Unsafe override required: None - Qualification impact: None - Rollback path: git revert ## 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` (release-please handles this) ## Additional Notes Ensures optional memory subsystem failure does not take down core proxy traffic. ## Current maintainer verification (October 9 UTC) Exact synchronized head: `b222647f31e0fbdfd8e33279f4c3c21e3cd4e40f`, containing main `01d9194854233ef6ed04005cf0a5b8c32bf65d6d` through a clean merge. The updated WebSocket regression gates each response pair on its matching upstream request and keeps the client open through both completions; the handler call is bounded by a five-second timeout. No contributor logic was changed during synchronization. Both affected routing/WebSocket files pass: 96 tests on Windows/Python 3.12 with the compatible existing native extension. Additional reviewer probes pass with deliberately yielding upstream sends at 0, 1, and 10 ms, addressing the reported scheduling race. These are local mocked-socket tests; no live external-provider or client session is claimed. GitHub fork-workflow approval was provided for this reviewed head; Current-head hosted snapshot completed with 30 successful checks, 12 skips, and one failed test shard. The failed per-frame memory recovery test is a PR regression: this file has 1 failure/10 passes locally on the PR, versus all 11 passes on main. Failed lookup currently adds memory instructions instead of preserving the original WebSocket frame; the new maintainer review requests that correction. The 96 routing/lifecycle tests and three scheduling probes above remain passing evidence with this explicit limit. ### Maintainer current-main requalification Exact head `3ca4324e69bd46a1c07288fb1b17c12b6fbcc9a7`, upstream main `2d3ee51846435ef5b320eea4806af14e602b0d8c`. Synchronized with upstream main |
||
|
|
365f6fe523 |
fix(proxy): skip memory-context search in cache mode on OpenAI routes (#4632)
## Description Follow-up to #4600 / #4606 as requested in #4622. PR #4606 implemented this optimization for Anthropic `/v1/messages`. This PR brings the three OpenAI routes (`handle_openai_chat`, `handle_openai_responses`, and `handle_openai_responses_ws`) into alignment. In `--mode cache`, memory context injection is disabled so prompt prefix bytes remain byte-stable across turns. Previously, all three OpenAI paths still executed the memory-context search (`search_and_format_context`: embedding query, vector index lookups, graph searches) and appended the result to the latest user turn in cache mode, introducing latency (~1–37ms+ per turn) and altering the forwarded user turn. With this PR: 1. `handle_openai_chat`: checks `is_cache_mode(self.config.mode)` before executing `search_and_format_context`, emits `decision="skipped_cache_mode"`, and keeps the user turn intact. 2. `handle_openai_responses`: checks `is_cache_mode(self.config.mode)` before searching, emits `decision="skipped_cache_mode"`, and keeps `body["input"]` intact. 3. `handle_openai_responses_ws`: checks `is_cache_mode(self.config.mode)` before measuring `memory_context`, emits `decision="skipped_cache_mode"`, and leaves `ws_response_body["input"]` untouched. 4. Memory tool injection remains completely unchanged across all routes. Closes #4622 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [x] Performance improvement ## Changes Made - `headroom/proxy/handlers/openai.py`: Check `is_cache_mode(self.config.mode)` when `inject_context` is enabled across `handle_openai_chat`, `handle_openai_responses`, and `handle_openai_responses_ws`. Emit `decision="skipped_cache_mode"` with `bytes_injected=0` and bypass `search_and_format_context`. - `tests/test_proxy_system_prompt_immutable.py`: Added `test_cache_mode_skips_memory_context_search_openai_chat` and `test_cache_mode_skips_memory_context_search_openai_responses` to verify that `search_and_format_context` is never awaited in cache mode and user message / input fields remain byte-equal to client values. ## Testing - [x] Unit tests pass (`pytest tests/test_proxy_system_prompt_immutable.py`) - [x] Linting passes (`ruff check headroom/proxy/handlers/openai.py tests/test_proxy_system_prompt_immutable.py`) - [x] Formatting passes (`ruff format --check headroom/proxy/handlers/openai.py tests/test_proxy_system_prompt_immutable.py`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ pytest tests/test_proxy_system_prompt_immutable.py -q 10 passed, 1 warning in 31.92s $ ruff check headroom/proxy/handlers/openai.py tests/test_proxy_system_prompt_immutable.py All checks passed! $ ruff format --check headroom/proxy/handlers/openai.py tests/test_proxy_system_prompt_immutable.py 2 files already formatted ``` ## Real Behavior Proof - Environment: Linux / WSL2 Ubuntu, Python 3.13, local proxy test harness (`create_app` + `TestClient`). - Exact command / steps: Executed requests against `/v1/chat/completions` and `/v1/responses` with proxy configured in `--mode cache` and memory context enabled. Verified upstream payload captures and mock call history. - Observed result: In cache mode, the memory search is bypassed on all OpenAI requests; search_and_format_context was never awaited (0 calls), user message content and input fields remain byte-equal without injected memory context, and proxy emitted decision=skipped_cache_mode with bytes_injected=0. - Not tested: Live WebSocket connection to OpenAI upstream with streaming audio/realtime endpoints. ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: n/a - Stable/default behavior changed: no. Cache mode requires byte stability across turns; memory search is skipped in cache mode. Token mode is untouched. - Kill switch / disable path: n/a - Unsafe override required: no - Qualification impact: none - Rollback path: git 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 - [x] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation: n/a - [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` ## Additional Notes - Aligns OpenAI Chat, Responses, and WebSocket routes with Anthropic behavior established in #4606. - Preserves memory tool injection without modification. Co-authored-by: shaiknaziya20 <naziyashaik5512@gmail.com> ### Maintainer combined-head validation Reviewed head `66a09054548423e33af47121ac7e87134d023fe4` includes a clean main sync through `12dca26aa` plus test-only maintainer follow-ups: the existing WebSocket dummy config now explicitly uses token mode, and a two-frame cache-mode regression covers skipped searches, unchanged input, retained memory tools, passthrough cancellation frames, and skip telemetry. No contributor runtime logic was changed. Windows / Python 3.12.13, with the existing local Rust extension: `.venv/Scripts/python.exe -m pytest tests/test_proxy_system_prompt_immutable.py tests/test_codex_ws_per_frame_memory.py tests/test_openai_codex_ws_lifecycle.py -q --tb=short --disable-warnings` => **89 passed**. The new WebSocket regression fails on current main because both frames still execute memory searches. Ruff check/format and main-relative whitespace checks pass. Additional runtime proof used a real Uvicorn proxy and a separate local HTTP upstream, both bound to ephemeral loopback ports, with production HTTP forwarding intact (no `_retry_request` patch). A deterministic recording memory backend returned `LOOPBACK_MEMORY` when searched, so the probe can distinguish an actual skip from an unconfigured/disabled memory path. The probe sent the same authenticated Chat and Responses requests in token mode, then cache mode, using user text `latest user prompt` and fixed Responses instructions. Exact invocation from the isolated worktree: `PYTHONPATH=G:/git/headroom-review4632 HEADROOM_OFFLINE=1 G:/git/headroom/.venv/Scripts/python.exe G:/git/headroom/.codex/review4632-loopback.py` (environment variables set with PowerShell `$env:` assignments). Results: **four HTTP 200 responses**; token mode performed one memory search per route and forwarded the returned memory text; cache mode performed zero searches per route, forwarded the original user text unchanged, and recorded `memory_skip_reason=cache_mode`. The proxy and upstream were shut down after the run. Limits: the loopback provider and recording memory backend are deterministic local fixtures; no external provider, embedding model, production memory service, load test, or real upstream WebSocket was exercised. WebSocket multi-frame/input/tool/telemetry behavior is covered by the focused regression above. Updated-head hosted qualification is inspected by maintainers; no contributor CI action is needed. Nothing merged. --------- Co-authored-by: shaiknaziya20 <naziyashaik5512@gmail.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
682bf73f48 |
fix(proxy): preserve retrieval outputs across Codex WS deltas (#4574)
## Description
Codex Responses WebSocket continuations may send only
`custom_tool_call_output` plus `previous_response_id`. A
`headroom_retrieve` result wrapped by Code Mode `exec` then loses the
originating call's tool identity and can be compressed into another
retrieval pointer.
## Why / Rationale
The retrieval exemption currently depends on calls present in the
current request. Delta requests omit those calls, so a successful
retrieval can become unreadable to the model. The exemption must follow
the retrieval call ID for the lifetime of that WebSocket connection.
## Change Explanation
Record only effective retrieval tool names from completed upstream
output items in a bounded connection-local map, using the existing
wrapped-call resolver. Pass that classification privately to compression
while forwarding the original request unchanged. Current-input calls
take precedence; ordinary and unknown outputs remain compressible. At
512 retained identities, preserve subsequent output bytes without
compression and warn once instead of evicting a protected identity.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- Preserve retrieval classification across delta, repeated, and rejected
tool outputs until connection teardown.
- Keep classifications isolated by connection; never retain arguments or
results.
- Fail open for unsupported compressor overrides and classification-cap
saturation.
- Add focused regressions for the delta lifecycle and ordinary-output
controls.
## Testing
- [x] Native pre-commit checks, including configured isolated mypy.
- [x] Whole-tree `ruff check .` and `ruff format --check .`.
- [x] Affected Python regression suite.
- [x] Native `make ci-precheck` (Rust formatting, Clippy, workspace
tests, extension build/import, Python contracts, commitlint).
- [x] Actual native Codex manual canary.
### Test Output
```text
Before fix with real Rust core: 2 failed, 1 control passed
Focused WS delta regressions: 4 passed
Affected WS/Responses suites: 148 passed in 11.32s
Native workspace Rust tests: 1671 passed, 3 ignored
Native Python contracts: 178 passed, 5 skipped
Native pre-commit/commit-msg hooks: passed
make ci-precheck: PASSED
```
Native gates used source-pinned Rust 1.95.0, the existing lockfile's
ONNX Runtime 1.26.0, an explicit owned dylib path, and serial Rust
tests. To fit local disk, Cargo dev/test profiles used size
optimization, symbol stripping, no debug symbols, and no incremental
artifacts; debug assertions and overflow checks stayed enabled. Checks
and tests were not excluded. All Headroom state/config/CCR paths were
disposable.
## Real Behavior Proof
- Environment: macOS arm64, Python 3.13.15, native Codex 0.165.0,
`gpt-6.1-sol`, OpenAI Responses WebSocket through Headroom. Existing
native authentication was reused.
- Candidate: isolated official Headroom 0.42.0 wheel with only this
reviewed production patch applied. Main-branch source is covered by the
local tests above. No shared installation was changed by the canary.
- Steps: seed the compression store with synthetic JSON containing 240
rows and one random nonce unknown to the model; pass only the generated
retrieval hash. Start the proxy on an isolated port with disposable
workspace/config/CCR paths. Run native Codex in ephemeral, read-only
Code Mode with only `headroom_retrieve` enabled and retries disabled.
Execute exactly one Code Mode call using the program below, print the
complete result, and ask the model to return only the decoded nonce.
- Observed: exactly one completed MCP retrieval; the full original was
52,043 bytes with SHA256
`ba25ccb718db06ba176a038f989eff40f8fa03e974391fd1c94a06091e2720c1`;
decoding succeeded and the model returned the expected unknown nonce.
The Code Mode output had no replacement CCR marker. The unpatched
official runtime reproduced the retrieval failure. Debug wire snapshots
are bounded views; their hashes are not claimed as full transport
hashes.
- Not tested: live shared installation adoption or the full Python test
suite. The isolated canary was stopped after qualification.
```js
// @exec: {"max_output_tokens": 22000}
const result = await tools.mcp__headroom__headroom_retrieve({hash: "SEEDED_HASH"});
text(result);
const payload = JSON.parse(result.content[0].text);
const original = JSON.parse(payload.original_content);
const matches = original.rows.filter(row =>
typeof row.needle === "string" && row.needle.startsWith("CCR_NATIVE_"));
if (matches.length !== 1) throw new Error("Expected exactly one synthetic needle");
text({recovered_needle: matches[0].needle,
original_length: payload.original_content.length});
```
## Runtime Rollout Safety
- Rollout-managed feature(s): existing Codex WebSocket transport; no new
configuration or feature flag.
- Minimum rollout channel: existing default route.
- Stable/default behavior changed: retrieval exemption survives delta
requests.
- Kill switch / disable path: existing proxy bypass.
- Unsafe override required: none.
- Qualification impact: actual native retrieval/decode canary plus
lifecycle regressions.
- Rollback path: restore the previous package/version.
## Review Readiness
- [x] I have performed a self-review.
- [x] This PR is ready for human review.
## Checklist
- [x] Code follows the project's style guidelines.
- [x] Self-review and an independent source review completed.
- [x] Comments explain the connection lifetime and fail-open boundary.
- [x] Added regressions fail before the fix and pass after it.
- [x] New and existing affected tests pass locally.
- [x] No `CHANGELOG.md` edits.
## Additional Notes
No dependency, public API, configuration, or documentation surface is
added. Private canary payloads and wire logs are excluded from the
patch. Hosted checks and the required upstream maintainer review remain
separate from local validation.
Co-authored-by: JD Davis <mxjerrett@gmail.com>
|
||
|
|
957ab1830d |
fix(memory): fail close unresolved project operations (#2637)
## Description An unresolved project scope still carried the global database path. Custom-tool, native-memory, and learner paths could therefore initialize or reuse global state after context injection had already skipped. This PR makes unresolved project scopes backend-less and checks request scope before any memory or learning operation. Optional memory failures still allow the main model request to continue. This supersedes #502 at reviewed commit `9d45c11233959815da651393c3b3737359497882` and preserves attribution to @chopratejas in the commit trailer. ## 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 - Remove the database path and backend from unresolved project scopes. - Gate injection, custom tools, native operations, and learning before backend acquisition. - Pass request context through OpenAI and Anthropic memory-tool paths. - Preserve explicit global/user modes and fail-open model traffic. ## Testing ### October 27 combined-tree refresh Merged upstream `17d38e5699b7d7c69ac6addcd762f39e42dd7f00` into `5f625dba9bccee6b38ec2e9de6c04023c29358e7`. No manual source repairs were needed. - Focused memory, routing, WebSocket, Anthropic, and gateway tests: **308 passed, 2 skipped**. - The two skips cover the macOS non-UTF8 symlink fixture and optional native tool-search extension. - The Python pre-push test list, invoked directly against the built extension: **177 passed, 4 skipped**. - The real-file proof below passed again on this combined tree. - Independent static review found no integration blocker. - Ruff, whitespace, and commit hooks passed, including mypy and the new commit's commitlint check. - Full `make ci-precheck` is not green: Rust 1.99.1 reports `clippy::question_mark` in `crates/headroom-core/src/ccr/backends/in_memory.rs:163`. The same command fails on clean upstream `17d38e56`. - The Python wrapper requires `pip`, absent from this uv environment. Its test list was run directly after `uv sync` built the extension. - The history-wide commitlint target rejects an older commit footer. The new merge commit passed its commit hook. - The push hook was bypassed for these documented limitations. Hosted qualification for the new head remains required. The focused command below was extended with `tests/gateway/test_hook_tool_growth.py tests/gateway/test_native_deferral.py tests/gateway/test_tool_compaction_accounting.py`. ### October 25 validation Current-main refresh: `ba3320e49f202c5880e4ef8e28efe810b78eeb07`, with `3fef15d376d9899f77a28464e2e91f8b99514930` merged as the second parent. - [x] Focused regression tests pass - [x] Ruff lint and format checks pass for all ten PR files - [x] PR diff whitespace check passes - [ ] Type checking rerun for this refresh - [x] Real-file behavior proof completed - [x] Independent review found no remaining integration issue The merge required no manual code repairs. No dependency or API changes were added to the PR. ### Exact commands ```bash uv sync --frozen --extra dev --extra proxy uv run --frozen --extra dev --extra proxy python -m pytest tests/test_memory_storage_router.py tests/test_memory_handler_project_isolation.py tests/test_memory_handler_native_ops.py tests/test_memory_decision.py tests/test_memory_decision_policy.py tests/test_openai_codex_routing.py tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_per_frame_memory.py tests/test_openai_responses_traffic_learner.py tests/test_anthropic_buffered_memory_continuation.py tests/test_memory_handler_concurrent_init.py -q uv run --frozen --extra dev --extra proxy ruff check $(git diff --name-only 3fef15d3...HEAD) uv run --frozen --extra dev --extra proxy ruff format --check $(git diff --name-only 3fef15d3...HEAD) git diff --check 3fef15d3...HEAD ``` ### Test Output ```text 259 passed, 1 skipped, 1 warning in 27.35s All checks passed! 10 files already formatted ``` The skip is the non-UTF8 symlink fixture, which this macOS filesystem cannot create. The warning is an existing Starlette/httpx deprecation. The native extension was built from the combined source. These results replace the earlier PR-only test counts for this refresh. ## Real Behavior Proof I ran this on macOS 27.0.1 with Python 3.14.5 at `ba3320e49f202c5880e4ef8e28efe810b78eeb07`. The script uses the actual router and memory handler, with no mocked backend. It creates a temporary SQLite canary table and native-memory file. A request without project identity returns no backend or database path. Context lookup, five custom tools, six native commands, and Anthropic tool dispatch skip memory access. The script checks that the backend remains uninitialized, no project backend is cached, and file paths and byte hashes remain unchanged. It also reads the SQLite canary afterward. This proves rejection before backend access. The canary database is not a populated Headroom memory schema, so this does not demonstrate resolved-project retrieval. No provider request, model-request forwarding, live proxy, service restart, or native Windows/Linux execution was tested by this script. Temporary canary files are removed automatically. ### Reproduce Save the script below as `memory-behavior-proof.py` in the repository root after running the environment setup above. ```bash HEADROOM_WORKSPACE_DIR="$PWD/proof-workspace" HEADROOM_CONFIG_DIR="$PWD/proof-config" HEADROOM_SETTINGS_PATH="$PWD/proof-settings.json" .venv/bin/python -u memory-behavior-proof.py ``` <details> <summary>Executable script</summary> ```python """Check unresolved memory scope using real files and production handlers.""" import asyncio import hashlib import json import os from pathlib import Path import sqlite3 import tempfile os.environ["HEADROOM_BEACON"] = "off" os.environ["HEADROOM_TELEMETRY"] = "off" os.environ["HEADROOM_OFFLINE"] = "1" from headroom.memory.storage_router import MemoryStorageMode, RequestContext from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler, MemoryMode def snapshot(root): return { str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() for path in root.rglob("*") if path.is_file() } async def exercise(root): database = root / "memory.db" with sqlite3.connect(database) as connection: connection.execute("CREATE TABLE canary (content TEXT)") connection.execute("INSERT INTO canary VALUES ('private-existing-memory')") native_dir = root / "native" native_dir.mkdir() (native_dir / "canary.txt").write_text("private-existing-memory\n", encoding="utf-8", newline="\n") handler = MemoryHandler(MemoryConfig( enabled=True, backend="local", db_path=str(database), storage_root=str(root / "projects"), storage_mode=MemoryStorageMode.PROJECT, inject_context=True, mode=MemoryMode.AUTO_TAIL, use_native_tool=True, native_memory_dir=str(native_dir), )) before = snapshot(root) ctx = RequestContext(headers={}, system_prompt="You are helpful.", base_user_id="alice") backend, scope = handler._router.backend_for(ctx) assert backend is None and scope.db_path is None and scope.project_key is None print(f"scope: project_key={scope.project_key}, db_path={scope.db_path}, backend={backend}") context = await handler.search_and_format_context( "alice", [{"role": "user", "content": "Find my private memory"}], ctx, ) assert context is None print(f"context lookup: {context}") expected = {"status": "skipped", "reason": "project_unresolved"} tools = { "memory_save": {"content": "must not persist"}, "memory_search": {"query": "private-existing-memory"}, "memory_update": {"memory_id": "m1", "new_content": "must not update"}, "memory_delete": {"memory_id": "m1"}, "memory_list": {}, } for name, arguments in tools.items(): result = json.loads(await handler._execute_memory_tool(name, arguments, "alice", request_context=ctx)) assert result == expected print(f"{name}: {json.dumps(result, sort_keys=True)}") for command in ("view", "create", "str_replace", "insert", "delete", "rename"): arguments = {"command": command, "path": "/memories/canary.txt", "file_text": "must not persist", "old_str": "private", "new_str": "public", "insert_line": 0, "insert_text": "must not persist", "old_path": "/memories/canary.txt", "new_path": "/memories/renamed.txt"} result = json.loads(await handler._execute_native_memory_tool(arguments, "alice", request_context=ctx)) assert result == expected print(f"native {command}: {json.dumps(result, sort_keys=True)}") results = await handler.handle_memory_tool_calls({"content": [ {"type": "tool_use", "id": "native-create", "name": "memory", "input": {"command": "create", "path": "/memories/canary.txt", "file_text": "must not persist"}}, {"type": "tool_use", "id": "custom-save", "name": "memory_save", "input": {"content": "must not persist"}}, ]}, "alice", "anthropic", request_context=ctx) assert len(results) == 2 and all(json.loads(item["content"]) == expected for item in results) print("Anthropic tool dispatch: both calls skipped") assert not handler.initialized and handler._backend is None and not handler._router._backends assert snapshot(root) == before with sqlite3.connect(database) as connection: assert connection.execute("SELECT content FROM canary").fetchall() == [("private-existing-memory",)] print("backend initialization: false; cached project backends: 0") print("SQLite and native files: byte hashes unchanged; no files added or removed") print("Provider traffic and model-request forwarding: not exercised by this proof") with tempfile.TemporaryDirectory(prefix="headroom-pr2637-proof-") as directory: asyncio.run(exercise(Path(directory))) print("Cleanup: temporary canary files removed") ``` </details> <details> <summary>Captured output</summary> ```text event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' scope: project_key=None, db_path=None, backend=None event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' context lookup: None event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' memory_save: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' memory_search: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' memory_update: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' memory_delete: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' memory_list: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native view: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native create: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native str_replace: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native insert: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native delete: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' native rename: {"reason": "project_unresolved", "status": "skipped"} event=memory_project_unresolved behavior=empty user_id=alice hint='set x-headroom-project-id, x-headroom-cwd, or provide a cwd in the system prompt, or set memory.unresolved_project_fallback=global to opt-in to legacy cross-project GLOBAL pooling (cross-project leak risk).' Anthropic tool dispatch: both calls skipped backend initialization: false; cached project backends: 0 SQLite and native files: byte hashes unchanged; no files added or removed Provider traffic and model-request forwarding: not exercised by this proof Cleanup: temporary canary files removed ``` </details> ## Runtime Rollout Safety - Rollout-managed feature(s): Project-scoped memory injection, tools, native operations, and traffic learning. - Minimum rollout channel: Stable/default. - Stable/default behavior changed: Unresolved project requests skip memory and learning instead of acquiring the global backend. - Kill switch / disable path: Run without `--memory`; use `--no-learn` to disable traffic learning. - Unsafe override required: No. - Qualification impact: Project memory isolation, explicit global/user modes, and fail-open model traffic. - Rollback path: Revert this PR. No schema or data migration is required. ## 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] Documentation changes are not required for this internal safety fix - [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) Not applicable. ## Additional Notes Waiting follow-up: [project-scoped TrafficLearner](https://github.com/krzkraw/headroom/tree/krz/project-scoped-traffic-learner). It depends on the request-scoped APIs completed here. No schema or data migration is required. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2637" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: chopratejas <chopratejas@gmail.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
1d112cd36c |
fix(proxy): show turn-hook savings in /stats extension_savings, incl. Codex WS (#4233)
## Description
### The test we ran
A Daytona sandbox running Headroom Enterprise 0.4.3 (core 0.39.1), with
Codex CLI 0.162.1 and Claude Code connected to real GitHub, Context7 and
Fetch MCP servers, working through the workshop tasks.
### What we found
- The tool-search plugin's turn hook rewrote the Codex `/v1/responses`
input and saved about **8K tokens per request**. `run_request_hooks`
booked that saving through `ctx.record_savings(hook.savings_source,
tokens=...)`.
- After many such requests, `GET /stats` still showed
**`extension_savings: {}`**.
There were two causes:
1. **`extension_savings` has no writer in core.** The only thing that
fills it is `PrometheusMetrics.record_extension_savings`, and core never
calls it. Attribution rows from `ctx.record_savings` /
`record_scope_savings` go to `savings_by_source`, which `/stats` shows
as `savings.by_source`.
2. **The Codex WebSocket path drops attribution entirely.** Both WS
compression calls (first frame and later frames) called
`_compress_openai_responses_payload_in_executor` without `savings_tags`.
So `TurnContext.tags` was a throwaway `{}`, and the hook's row (along
with the built-in tool-search deferral row) never reached
`savings.by_source` either. Codex uses the WS transport by default. The
HTTP `/v1/responses` path already passed `savings_tags`.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- **`/stats.extension_savings`** now reports measured savings per
source: the **realized** attribution rows, plus
`record_extension_savings` totals. If a source also calls
`record_extension_savings` (`headroom-hdr` reports through both APIs on
every request), it shows the larger of its two totals rather than their
sum, so hdr is not double-counted. Nothing ties an attribution row to a
`record_extension_savings` call, so a plugin that used the two APIs on
different turns would be under-reported, never over-reported.
Unrealized/estimated rows (tool-search deferral, `realized=False`) stay
out and remain visible in `savings.by_source`.
- **Codex WS:** each frame compresses into its own `savings_tags` dict.
Its rows are merged into the session's pending list on the event loop,
and only when that frame was actually rewritten and sent. Each per-turn
`RequestOutcome` carries the pending rows and then clears them. A turn
whose `response.completed` has no input usage leaves its rows pending,
the same gate as its headline `saved_delta`
(`_deferrable_savings_delta`). Rows no turn claimed go out with the
session-end residual outcome, and only if the residual has input usage.
A fresh dict per frame matters because a timed-out compression thread
keeps running (`_run_compression_in_executor` can't cancel it), and it
must not book rows for a frame that went out uncompressed.
**Realized vs estimated:** `savings.by_source` already keeps one row per
`(source, realized)`, so realized and unrealized savings are shown
separately. `extension_savings` now carries only the realized ones.
**Review fix (@JerrettDavis, bounded WS pending list):** the
session-wide pending list grew one row per rewritten frame, while
`savings_attribution.from_tags` read only the first `MAX_SOURCES` (32)
rows. After 33 frames that each booked a 100-token `tool_search` row,
the handoff cleared all 33 rows but booked only 3,200 of the 3,300
tokens. `savings_attribution.accumulate(rows, items)` replaces the
`extend` at both WS frame paths.
**Bounded rows, nothing dropped (follow-up to @JerrettDavis's two
reviews):** the 32-row cap that silently dropped rows is gone from
`record_savings`, `from_tags` and `accumulate`. Storage is bounded by
coalescing plus one overflow row:
- every writer goes through the one `accumulate` helper: the per-request
ledger (`record_savings`, so every handler) and the WS pending list.
Rows with the same `(source, realized, estimated)` key are summed into
one row (`tokens`, `usd`, `events`). `details` are kept only while every
summed row has the same `details`.
- **cardinality bound:** a ledger keeps at most `MAX_NAMED_ROWS` (256)
named rows. A new source past that bound is summed into an `other` row
with the same `(realized, estimated)`, and its `details` are dropped.
Tokens, dollars and events are conserved: nothing is dropped, only the
source name. `tool_search` never folds, because
`tool_schema_savings_policy` finds the deferral's row by name to lower
it when hooks un-defer tools.
- **finite sums:** a row's `usd` saturates at ±`MAX_ROW_USD` (1e15) and
its `tokens` stay within 0..`MAX_ROW_TOKENS` (10^15). A row that was
clipped, or summed from one that was, carries `saturated: true`. Every
total stays finite, so the Prometheus exposition and
`json.dumps(allow_nan=False)` never see `inf`/`nan`.
- each row carries `events`: how many recordings it stands for (1 on a
fresh row, summed on merge). `PrometheusMetrics.record_request`
(`headroom_savings_attribution_events_total`), the OTel
`headroom.savings.attribution.events` counter and the perf analyzer's
"Savings by Source" add that count instead of 1 per row, so 33 coalesced
frames are 33 events, not 1 (Devin's finding). A row without `events`
(older PERF logs, rows built by hand) counts as 1.
- a row that a reader edited in place (`reconcile_deferred_tokens`, the
tool-search plugin) is summed defensively, so a junk value counts as 0
instead of raising inside the handler. The core deferral and the native
deferral hook both book `tool_search` as estimated, so they now share
one row, and the reconcile debits that row; totals are unchanged.
- `MAX_SOURCES` is no longer used. No importer was found outside this
repo's own test, but `savings_attribution` is imported by plugins, so
the name is kept behind a module `__getattr__` that raises a
`DeprecationWarning`.
- **Scope of the bound:** it is per ledger (one request, or one WS
session's pending list). The process-wide
`PrometheusMetrics.savings_by_source` table has no source cap yet; that
is a separate PR.
### Before / after
| | origin/main | this PR |
|---|---|---|
| A turn hook books 8,000 tokens on 2 requests →
`/stats.extension_savings` | `{}` | `{"tool_search": 16000}` |
| An hdr-style plugin calls both APIs (300 tokens × 2) | `{"hdr": 600}`
| `{"hdr": 600}` (not 1200) |
| A Codex WS turn with a folding hook → attribution rows on the turn
outcome | `[]` | `[("ws_fold", realized=True)]` |
| 33 WS frames, each booking `tool_search` 100 tokens, then one billed
turn → booked `tool_search` tokens (helper-level, the reviewer's
scenario) | 3,200 of 3,300, 33 rows stored | 3,300, 1 row stored |
| Real WS handler, 33 frames each with a folding hook (`ws_fold` row)
plus a 100-token hook row → non-`ws_fold` tokens booked | 1,600 of 3,300
(66 rows stored) | 3,300 |
| Same, repeated source → rows stored / hook events in
`headroom_savings_attribution_events_total` |
|
||
|
|
46306024e7 |
fix(openai): read Responses cache_write_tokens instead of inferring writes (#4237)
## Type of Change - [x] Bug fix (Responses usage accounting) ## Description OpenAI's Responses usage now reports billed cache writes as `input_tokens_details.cache_write_tokens`. They are billed at the write rate: $5/M on `gpt-5.6-sol`, against $4/M input. Every Headroom Responses path ignored that field and inferred writes as `input − cached` instead. As a result: - On HTTP, writes were flagged as inferred and dropped from pricing, so the written tokens were priced as uncached input at list. - On the Codex WebSocket path the inferred write was never flagged, so the uncached slice was billed twice: once as uncached and once as a write. Part of the savings redesign (step 2). The counterfactual record (#4236) needs the true write share `w = W/(U+W)`. ### The test that found it We ran Headroom Enterprise 0.4.3 in a Daytona sandbox with Codex CLI 0.162.1 on `gpt-5.6-sol` and the real GitHub MCP server, doing workshop task 1. We audited 13 calls against the provider's billing. - Every call reported `cache_write_tokens`. For call 2, usage was input 12,497, cached 9,568, write 2,926 (3 uncached). - PERF printed `cache_write=0` on every line. - Of the true $0.0850 saved, $0.0497 came from avoided cache **writes**, which core could not see. - /stats `total_cost_usd` undercounted the real bill by 8–10%. ## Changes Made - `_openai_responses_cache_split(input, cached, reported_write)` returns `(read, write, uncached, inferred)`. A reported write is used as-is; the write is inferred only when the field is absent. - Callers updated: - `_extract_responses_usage` (WS) returns a 6th `inferred` element. - The WS per-turn and session-end outcomes now pass `cache_inferred`. Before this they never set it. - The WS→HTTP fallback returns the flag. - HTTP `/v1/responses` keeps the turn-hook re-drive reads and adds the re-drives' reported writes (`TurnHookUsage.cache_write_tokens`). - The passthrough normalizer, the streaming usage parser (mapped onto the existing real-write branch) and `gateway_turn.normalize_usage` (Kong relays) also read the field. - Not changed: Chat Completions, which reports no write counter, and the `/v1/usage` relay, which doesn't map Responses-shaped details at all. That was already a gap for reads and is left as a follow-up. ## Before / after (audit replay, 13 Codex calls, current pricers) | | inferred (main) | reported (this PR) | provider truth | |---|---|---|---| | cost-tracker input cost | $0.2329 | $0.2649 | — (audit total $0.305 includes output) | | SavingsTracker compression $ (novel tokens) | $0.0434 | $0.0542 | $0.0850 total saved | The rest of the gap is re-sent history and the per-request record, which come in the follow-up PRs of the redesign. ## Testing - [x] New regression tests: - `test_ws_session_metrics_use_reported_cache_writes` (WS) - `test_fallback_returns_reported_cache_writes_as_real` - `test_responses_reported_cache_writes_include_the_redrive` (HTTP + turn hook) - `test_normalize_openai_responses_reported_cache_writes` (gateway) - [x] The existing WS test now pins `cache_inferred is True` when no write is reported. - [x] Passed (275, 14 skipped): `test_ws_http_fallback`, `test_openai_codex_ws_lifecycle`, `test_gateway_turn_unit`, `test_proxy_budget`, `test_turn_hook_usage`, `test_proxy_handler_helpers`, `test_proxy_openai_responses_integration`, `test_proxy_cache_telemetry`, `test_direct_chat_ccr_resolution`, `test_request_outcome`. - `test_turn_hook_usage` needs `LITELLM_LOCAL_MODEL_COST_MAP=True` locally: respx blocks litellm's remote price-map fetch. It fails the same way on main without it. - [x] `ruff check` / `ruff format --check` (0.16.8) and `mypy headroom` are clean. ### Test Output ```text Maintainer mixed-WebSocket-session probe: turn 1: input=100 read=75 write=25 uncached=25 cache_inferred=true turn 2: input=100 read=75 write=20 uncached=5 cache_inferred=false ``` The probe exercised the actual WebSocket handler using the existing lifecycle test harness. It verifies separate per-turn records for this mixed session; it does not establish behavior for every suppressed memory-tool re-drive. The prior qualified head completed hosted CI with 30 successful and 12 skipped checks. The current main-synced head is being qualified again. ## Real Behavior Proof - Environment: macOS, this branch; the audit's recorded provider usage for the 13 Codex calls. - Exact command / steps: replayed each call's usage through `CostTracker.record_tokens` and `estimate_request_savings_usd`, first with the inferred split (main) and then with the reported split (this PR). Script: `replay_c.py` in the audit scratchpad. - Observed result: input cost $0.2329 → $0.2649 and compression dollars $0.0434 → $0.0542, as in the table above. Call 2 now records read 9,568 / write 2,926 / uncached 3 instead of write 2,929 inferred. - Not tested: a live Codex session against this branch. The live re-run comes with the audit-eval PR of the redesign. ## Runtime Rollout Safety - Rollout-managed feature(s): no new rollout-managed feature switch. - Minimum rollout channel: existing Responses transport policy applies. - Unsafe override required: no. - Qualification impact: reported cache writes affect recorded cost and savings; hosted checks and human review remain required. - Stable/default behavior changed: Responses accounting prices explicitly reported writes as billed writes; inferred writes remain marked as estimates. - Yes for OpenAI Responses cost and savings dollars. The newly reported writes are now priced at the write rate. - WS turns without a reported write are now flagged inferred. That removes the double-billed uncached slice, so WS cost totals go down for older responses. - WS turns now count toward `cache_inferred_turns`. - Kill switch / disable path: none needed; this follows the provider's own usage. - Rollback path: revert. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4237" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> ## Review Readiness - [ ] I have performed a self-review - [ ] This PR is ready for human review The maintainer has recorded independent qualification above. Author readiness attestations have not been filled on the author's behalf. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
a493f559a1 |
fix(proxy): classify Pi Codex Responses alias (#2583)
## Description Pi-compatible clients such as Gajae-Code open the Codex Responses WebSocket at `/v1/codex/responses`, an alias added in #196. The unidentified-client stamp added in #1036 only recognizes `/v1/responses`, while Gajae-Code currently identifies itself as `pi/<version>`. The alias therefore remains unclassified and takes the generic proxy compression-timeout path instead of the Codex fail-open path. This change applies the existing narrow `X-Client: codex` stamp to the Pi-compatible alias and its subpaths. Explicit `X-Client` values and already-recognized user agents remain untouched. Refs #196 and #1036. ## 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 causes existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Treat `/v1/codex/responses` and its subpaths as Codex Responses paths for unidentified-client stamping. - Add regression coverage for the exact Pi-compatible alias and its compact subpath. - Add a WebSocket lifecycle test proving the alias forwards `X-Client: codex` upstream. ## Testing - [ ] 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 pytest tests/test_codex_client_stamp.py tests/test_auth_policy.py tests/test_auth_mode.py tests/test_proxy_codex_route_aliases.py tests/test_openai_codex_ws_lifecycle.py -q 81 passed, 1 pre-existing Starlette deprecation warning in 35.79s $ uv run ruff check . All checks passed! $ uv run ruff format --check headroom/proxy/auth_policy.py tests/test_codex_client_stamp.py tests/test_openai_codex_ws_lifecycle.py 3 files already formatted $ uv run mypy headroom Success: no issues found in 509 source files $ uv run pre-commit run --files headroom/proxy/auth_policy.py tests/test_codex_client_stamp.py tests/test_openai_codex_ws_lifecycle.py All configured hooks passed ``` The full suite completed with `9696 passed, 568 skipped, 15 failed`. The 15 failures are outside this diff: existing `unwrap claude` signature mismatches, environment-dependent Kompress health expectations, an overlong AF_UNIX test path, and a missing local Rust toolchain. The focused Codex routing suite above is green. ## Real Behavior Proof - Environment: macOS Darwin 25.5 arm64, Python 3.13.13, Gajae-Code 0.11.11, `openai-codex/gpt-5.6-sol`; patched Headroom source proxy on `127.0.0.1:8788` in cache mode with OpenAI Kompress disabled. The isolated GJC model config contained the proxy base URL and deliberately had no `X-Client` header override. - Exact command / steps: Exercised the patched source proxy through the live Pi-compatible alias as follows: 1. Start the patched source proxy with `uv run headroom proxy --host 127.0.0.1 --port 8788 --mode cache --disable-kompress-openai --stateless`. 2. Point an isolated GJC agent config at `http://127.0.0.1:8788/v1` without custom headers. 3. Run `gjc -p --no-session --no-tools --system-prompt "Reply exactly as requested." --model openai-codex/gpt-5.6-sol "Reply with exactly ALIAS_OK."`. - Observed result: GJC returned `ALIAS_OK`. The live proxy recorded `path=/v1/codex/responses` and the request outcome ended with `client=codex` (`tok_before=3120`, `tok_after=3081`, `tok_saved=39`). Before the patch, the same installed classifier returned `False` for this alias and live GJC outcomes had an empty client classification (reported as `proxy` by the savings ledger). - Not tested: Windows/Linux live providers, token mode, or the broader compression scheduler changes proposed in #963. The full repository suite is not locally green for the unrelated failures listed above. ## Runtime Rollout Safety - Rollout-managed feature(s): none — this is a fix to an existing unidentified-client stamping path, not behind a rollout channel. - Minimum rollout channel: n/a (ships to stable with the fix). - Stable/default behavior changed: yes. Unidentified clients calling `/v1/codex/responses` or its subpaths (e.g. the Pi-compatible `pi/<version>` user agent) are now stamped `X-Client: codex` and take the Codex fail-open path instead of the generic proxy compression-timeout path. Requests with an explicit `X-Client` header or an already-recognized user agent are unchanged. - Kill switch / disable path: no new switch; the existing explicit `X-Client` header and recognized-user-agent paths still bypass the stamp exactly as before. - Unsafe override required: no. - Qualification impact: none — no qualification-gated surface is touched. - Rollback path: revert the implementation 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 - [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 the 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) Not applicable. ## Additional Notes - Documentation is unchanged because this restores the already-documented Pi compatibility route's existing Codex classification behavior. - PR #963 addresses broader Responses compression scheduling/timeouts but does not add `/v1/codex/responses` to the path-based client stamp. - `make ci-precheck` was not available because this workstation has no Rust toolchain; the push used `--no-verify` after the Python, lint, formatting, typing, focused routing, and live proxy checks above. Co-authored-by: Jerrett Davis <mxjerrett@gmail.com> |
||
|
|
0396ea2fc2 |
fix(codex): resolve per-turn project context (#2636)
## Description Codex Desktop can send turns from multiple projects through one HTTP or WebSocket route, so a static `/p/<project>` route cannot reliably identify each turn. This PR resolves project context per turn from explicit overrides or Codex thread/turn metadata. Unsafe or inconsistent resolution skips project memory and learning while the model request continues. Related to #2355 and overlaps #2379. ## 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 - Resolve `thread_id` and `turn_id` to the matching rollout cwd. - Use the resolver for HTTP and per-frame WebSocket traffic. - Pin each WebSocket to its first resolved project and fail closed on mismatch. - Strip Codex-only metadata before forwarding upstream. ## 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 121 passed, 1 pre-existing deprecation warning All checks passed! Success: no issues found in 510 source files ``` ## Real Behavior Proof - Environment: macOS; isolated Codex state and project fixtures plus the combined local deployment. - Exact command / steps: Exercised two same-basename projects over HTTP and concurrent WebSockets, including resume/fork, missing, stale, locked, malformed, and mismatched contexts. - Observed result: Each turn resolved to the correct project; unsafe cases skipped project memory and learning without blocking the model request. The integrated patch also ran in the local deployment for more than 39 hours. - Not tested: Linux, Windows, VMs, or GitHub CI. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: N/A; this change uses stable/default behavior. - Stable/default behavior changed: Codex HTTP and WebSocket turns resolve project context per turn; unsafe resolution skips project memory and learning. - Kill switch / disable path: Run without `--memory`; use `--no-learn` to disable traffic learning. - Unsafe override required: No. - Qualification impact: Codex project-context isolation for HTTP and WebSocket traffic. - Rollback path: Revert this PR. No schema, data, or configuration migration is required. ## 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] Documentation changes are not required for this internal routing fix - [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) Not applicable. ## Additional Notes Waiting follow-up: [project-scoped TrafficLearner](https://github.com/krzkraw/headroom/tree/krz/project-scoped-traffic-learner). It depends on the per-turn project API introduced here. No database or configuration migration is required. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/2636" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
46755b5f72 |
fix(memory): avoid injecting tools into tool-free requests (#3677)
## Description Memory tool injection should be suppressed only for a client that is explicitly known not to support tools. An omitted or empty `tools` field is not enough to make that determination because Codex and other clients may advertise tool capability out of band. Closes #3676 ## Changes Made - Carry the client capability decision through the Anthropic and OpenAI Responses paths. - Preserve existing and sticky memory tools for Codex and unknown clients. - Suppress fresh and sticky memory-tool injection only for an explicitly tool-incapable client. - Add endpoint-level and helper regressions for that distinction. ## Testing - Targeted memory and routing tests passed locally. - `ruff check .` passed. - `ruff format --check .` passed. - `mypy` passed for the changed modules. - GitHub CI is running on the current head. ## Runtime Rollout Safety - No new feature flag, schema, or migration is introduced. - Existing memory injection configuration remains the available disable path. - Rollback is a normal revert of this change. ## Review Readiness - Self-review completed. - The PR is ready for human review. --------- Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
1390d89715 |
fix(shaper): measure output-token steering, and stop claiming savings we did not measure (#3377)
## What this does
Verbosity steering already shipped (BETA, L2). This branch measures it
properly, fixes two ways it was misbehaving, and changes what Headroom
is willing to *claim* about it.
Net effect for a user: steering saves more than it did, on more models,
and the dashboard stops showing a savings percentage that was never
measured on their traffic.
## Three changes worth reviewing separately
### 1. The L3 steering text had two defects, both measured
**"Reproduce code, error strings, numbers, units, and API or CLI names
exactly"** read as a licence to emit code. Against the same SWE-bench
turn it left gpt-5.2 unchanged but inflated gpt-5.1 by 58% (1631 → 2573
output tokens), cutting L3's saving on that model from 51% to 23%.
Replaced with a completeness floor that forbids dropping task-critical
content — negations included — without instructing the model to
reproduce anything. The whole OpenAI family went from *negative* to
+31.2%.
**"reference by path and line"** was too soft. Told to stop restating
code, models wrote "change the check in the mixin" and the reader had to
ask which file. Measured with a blind judge playing the engineer who
must apply the fix: of four blocker categories only "under-specified
location" moved between L0 and L3 (0 → 3 across 9 paired tasks). Notably
the *predicted* failure — "omit rationale" → "but why?" — scored zero at
both levels. Making the citation obligatory took that category to 0 and
turn inflation from +23.1% to 0.0%.
Suppressing content is safe. Suppressing the pointer to it is not: the
reader buys it back at the cost of a whole turn, which at agentic
context sizes is far more expensive than the tokens saved.
### 2. The savings table now ships empty
`MODELLED_REDUCTION` previously carried built-in factors. It now ships
`{}` plus a `register_modelled_factors()` seam.
A credible reduction factor is not a constant. It depends on the model
family, the shape of the turn, and the exact steering text — and
producing one means running a paired benchmark across models and paying
for both arms. A constant compiled into the source is a number measured
on somebody else's traffic.
So `estimate_from_model` returns `None` for every level and the
dashboard renders its "not measured" fallback. That is the correct
rendering of *not measured*; a number nobody measured is not. Both real
paths are unchanged and documented at the table: run a holdout (which
outranks this tier entirely), or register factors from a benchmark.
The old built-in figure is a good argument for this: it claimed `(0.336,
0.738)` from five synthetic prompts, measured against a version of the
L3 string that has since changed twice. It over-reported by roughly 2×
at the optimistic end — the direction that matters for a number on a
dashboard.
### 3. Everything else
Thinking tokens split from visible output (`thinking_tokens.py`), the
estimator that was wired but never ran now runs, and the
`OUTCOME_OBSERVED` pipeline stage.
An earlier commit in this range adds a `headroom-output` plugin and a
writable `PRE_SEND_PARAMS` body hook; a later one removes both. Live
measurement showed per-turn effort routing ~15× underwater on mechanical
turns, so the hypothesis it was built on did not survive. The net diff
has neither, and a test now pins the hook as deliberately absent — an
unused writable-body seam is a liability, not an extension point.
## How it was measured
SWE-bench Verified, 12 instances carrying the real source files each
gold patch touches (6k–48k chars), stratified by the dataset's
difficulty label, run at L0 and L3 across six models and paired on
instance. Truncated pairs excluded — a capped response's length is the
ceiling, not the model's choice.
| | pairs | reduction |
|---|---|---|
| Anthropic (opus, sonnet, haiku) | 33 | 18.2% |
| OpenAI (terra, luna, sol) | 28 | 31.2% |
61 usable pairs, median +31.8%, mean +23.0% (SE 5.3, t=4.4), all six
positive in sign, 13% of individual pairs negative.
**On power, since it is easy to over-read the per-model figures:** only
luna (t=6.0), terra (t=3.0) and sonnet (t=2.7) are individually
distinguishable from zero. sol, haiku and opus are not (t≈1.3, 1.3,
0.7). They are single samples per instance against a model whose
*unsteered* output varies by a median 33% run to run — measured
directly, by re-running the L0 arm on identical prompts. The aggregate
effect is solid; a single-model number from this run is not.
## Risk
- Steering is the one lever that mutates the provider prefix-cache key,
so the text is byte-stable and applied once per conversation;
`steering_allowed_for` suppresses it entirely in `mode="cache"`.
- The feature stays opt-in (`available_in=STABLE`, no
`default_enabled_in`). L3 is a visible change to every response and
should be a choice.
- `shaper_enabled_for` keeps byte-faithful forwarding intact: default-on
plus `optimize=False` means don't shape, because creating a `system`
field where the client sent none breaks the contract.
## Testing
612 targeted tests pass; full suite green apart from
`test_mcp_reconcile.py::test_ordinary_install_does_not_adopt_serena`,
which fails identically on `main`.
The final commit fixes a UP037 lint error that arrived with the
savings-rendering work on main. It is unrelated to this branch but fails
CI lint for anything opened on top of it.
|
||
|
|
a06a51eca6 |
fix(proxy): preserve Codex WebSocket model attribution (#3029)
## Description Codex can switch models during a multi-turn Responses WebSocket conversation. Headroom was not consistently attributing each completed turn to the model that handled it, which made per-model usage and savings reporting inaccurate. Closes #3027 ## 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 - Attribute each completed WebSocket response to its reported model. - Keep session-end metrics consistent with the response that completed. - Add a regression test covering two different models on one WebSocket session. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added new functionality - [x] Manual testing performed ### Test Output ```text uv run pytest -q tests/test_openai_codex_ws_lifecycle.py -k session_metrics_track_model_per_response_create 1 passed, 51 deselected in 2.09s Full Codex WebSocket lifecycle module: 52 passed Adjacent Codex WebSocket suites: 77 passed, 1 skipped uv run ruff check . All checks passed uv run ruff format --check . 1411 files already formatted uv run mypy headroom Success: no issues found in 520 source files ``` ## Real Behavior Proof - Environment: Windows, Python 3.13.3, OpenAI Codex Responses WebSocket. - Exact command / steps: From the repository root, run `uv sync --extra dev --extra proxy`, then run `uv run headroom wrap codex`; in one live Codex conversation complete one turn with model A, switch to model B, complete a second turn, and inspect the proxy dashboard or `http://localhost:8787/stats` recent requests. - Observed result: Both completed turns appeared under the models that handled them, in order. - Not tested: Production deployment and non-Codex transports. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: Stable/default. - Stable/default behavior changed: Corrects telemetry attribution only; no public API or routing changes. - Kill switch / disable path: Revert the change or use the previous release. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert commit `d5d8d7ca`. ## 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) ### Pre change In a single session, started with `5.6-sol` and then switched to `5.6-luna`. The dashboard did not reflect the model change. <img width="1274" height="207" alt="image" src="https://github.com/user-attachments/assets/697803e4-d33d-4660-b8dd-f1a8d6404517" /> ### After change Repeated the same steps: started with `5.6-sol` and switched to `5.6-luna`. The dashboard now correctly reflects the model change. <img width="1264" height="202" alt="image" src="https://github.com/user-attachments/assets/722e5fab-ad1b-4e62-9344-5f9dd312d614" /> ## Additional Notes |
||
|
|
8a1d38bc5d |
fix(proxy): complete stateless Responses and buffered CCR lifecycle (#2997)
## Description Consolidates the related OpenAI Responses ZDR/stateless continuation and buffered CCR response-lifecycle corrections on current main. It preserves client storage policy, makes Headroom-owned continuations stateless across HTTP and WebSocket, and prevents buffered streaming paths from committing a false HTTP 200 before the real upstream outcome is known. Closes #2675 ## 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 - Preserves explicit and omitted Responses `store` policy instead of forcing provider storage or disabling memory tools. - Replays normalized input, replayable outputs, encrypted reasoning content, and Headroom function outputs without `previous_response_id`. - Applies the same stateless continuation policy to HTTP and WebSocket. - Prevents transparent memory execution after client-visible WebSocket output. - Delays buffered CCR ASGI status/headers until the operation resolves for Anthropic Messages and OpenAI Responses. - Preserves real 429/5xx status and retry headers. - Converts malformed non-JSON/non-SSE upstream 200 replies to a sanitized 502 protocol error. - Preserves valid JSON-to-SSE synthesis and existing SSE adaptation. - Removes unreachable task cleanup left behind after replacing the old keepalive polling loop with a direct awaited operation. ## 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 118 passed across the changed HTTP/WS ZDR, lifecycle, and both-provider CCR suites 11526 tests collected with no collection errors ruff check .: All checks passed ruff format --check .: 1411 files already formatted mypy headroom/proxy/handlers/anthropic.py headroom/proxy/handlers/openai.py: Success: no issues found in 2 source files ``` Exact-head CI is entirely green on `cbc2739c0c633ea477727ec3eb2f8a3862fa08f3`. ## Real Behavior Proof - Environment: macOS arm64/Python 3.13 locally; GitHub-hosted Ubuntu matrix pending. - Exact command / steps: exercise `store=false` Responses memory calls over HTTP and WebSocket; exercise buffered Anthropic and Responses requests returning successful JSON/SSE, delayed 429 responses, exceptions, and malformed successful bodies; invoke returned ASGI responses and inspect emitted status, headers, and body order. - Observed result: stateless continuations omit provider response IDs and retain `store=false`; no ASGI start event is emitted before the buffered outcome; real failures preserve status/headers; malformed 200 responses become sanitized 502 errors. - Not tested: live ZDR tenant and live Anthropic/OpenAI upstream credentials are unavailable in repository CI; wire contracts are exercised through deterministic upstream doubles. ## Runtime Rollout Safety - Rollout-managed feature(s): Responses memory continuation and buffered CCR handling. - Minimum rollout channel: normal patch release after full CI qualification. - Stable/default behavior changed: memory continuation no longer requires provider storage; buffered CCR waits before committing response status. - Kill switch / disable path: disable memory/CCR using existing proxy configuration (`--no-ccr` for CCR); ordinary non-buffered paths are unchanged. - Unsafe override required: none. - Qualification impact: full Python matrix plus focused HTTP/WS lifecycle suites must pass; patch coverage must not rely on unreachable cleanup. - Rollback path: human revert of this PR restores prior continuation/buffering behavior; no persisted data migration is introduced. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review — exact-head CI is entirely green ## 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 — inline protocol/lifecycle documentation; no separate user guide required - [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) Not applicable; proxy protocol behavior. ## Additional Notes Human review only. No merge or auto-merge is configured. This supersedes narrower #2995 and incorporates the complete intent of #2705, #2959, and #2968 without falsely closing those PRs. It does not claim the broader event-level streaming-splice guarantees requested by #1877. Refreshed from main after #2996; the MCP cap `mcp>=1.28.1,<2.0.0` is preserved. |
||
|
|
039cd2431a |
fix(proxy): preserve merged session and quarantine contracts (#2943)
## Description Forward-fixes two integration contracts exposed while auditing the large August 12 merge batch on `main`. The Codex WebSocket request-ID hardening correctly gave every emitted dashboard/feed row a unique ID, but it also changed the human-readable `PERF` prefix from the stable WebSocket session ID to that per-emission ID. That broke operator correlation and the contract documented by the original merge. This PR separates storage identity from log correlation: rows remain unique, while `PERF` lines remain grouped under the session ID. The same audit found two tokenizer quarantine tests still modeling the pre-time-cap behavior. Timeout debt no longer activates quarantine after its deadline expires. The tests now establish a live deadline and therefore continue to exercise the intended fail-open branch without weakening the production guard. ## Changes - Add an optional `RequestOutcome.perf_request_id` correlation field, defaulting to the existing `request_id` behavior for all current callers. - Set that field to the stable session ID for both per-turn and residual Codex WebSocket emissions. - Strengthen the lifecycle regression test to prove the unique feed-row ID is not used as the `PERF` prefix. - Update tokenizer quarantine tests to model an active, time-capped quarantine. This is a forward fix; it does not revert the unique WebSocket request IDs or the time-capped quarantine behavior. ## Merge-batch audit context - Audited 48 squash merges from `12149f74466c08b69be8d5fe751425be63c2fda4` through `941c25d31e6c6e0b436c307cbe212771ff76b45f`. - Reviewed repeated-touch hotspots in the OpenAI/Anthropic handlers and proxy server. - Confirmed the batch has no deleted or renamed paths and no revert/supersession commits. - Reproduced the deterministic failures on the merged head and confirmed the corresponding pre-batch tokenizer tests passed; the new WebSocket assertion was introduced by the batch and exposed the dropped correlation contract. ## Validation - `ruff check` — passed - `ruff format --check` — passed - `mypy headroom` — passed (517 source files) - Focused proxy/outcome/tokenizer suite — 99 passed - CI-equivalent Python suite in four `pytest-split` shards — 10,797 passed, 603 skipped - `cargo fmt --all -- --check` — passed - `cargo clippy --workspace -- -D warnings` — passed - New beta-sticky integration suite — 9 passed - Simulator-backed proxy E2E — 7 passed - Real local Headroom process against a real local FastAPI upstream: - `/livez` healthy - `/readyz` ready (Kompress correctly optional/degraded in minimal passthrough mode) - OpenAI `/v1/chat/completions` round trip passed - Anthropic `/v1/messages` round trip passed - Local `act` exercised the push workflow's change-detection job and entered the real lint job. `act` required local no-op cache/setup shims because its runner action post-hooks/pip pairing are incompatible with this macOS Docker environment; the actual Ruff/mypy validations above were run natively and passed. ## Risk Low. The new field is optional and preserves existing behavior by default. Only Codex WebSocket outcome emitters opt into a separate log correlation ID; dashboard/feed row identity remains unchanged. --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
d02df10758 |
fix(proxy): give each Codex /v1/responses WS turn a unique request_id (#2164)
## Description
After any Codex traffic, the dashboard "Recent Requests" table goes
blank — including the unrelated Anthropic/Claude rows — even though the
proxy is actively handling and compressing Codex `/v1/responses`
WebSocket turns and aggregate counters keep moving. The feed isn't
stale; it is being wiped client-side.
Root cause: the Codex WebSocket handler
`OpenAIHandlerMixin.handle_openai_responses_ws`
(`headroom/proxy/handlers/openai.py`) mints a single `request_id` per
WebSocket **session** (`_next_request_id()` near the top of the handler)
and reuses it for every per-turn `RequestOutcome` in
`_record_ws_response_metrics`, the session-residual outcome, and the
session-summary `RequestLog`. Those all flow through
`emit_request_outcome` (`headroom/proxy/outcome.py`), which writes a
`RequestLog` per outcome into the request logger that backs
`/stats.recent_requests` and `/transformations/feed` — so one session
with N turns produces N+ feed rows sharing one `request_id`. The
dashboard renders that feed with `<template x-for="req in
(stats.recent_requests || [])" :key="req.request_id">`
(`headroom/dashboard/templates/dashboard.html:1298`); Alpine requires
unique `:key`s, so duplicate ids abort the entire `x-for` render and
blank the whole table. Anthropic/HTTP requests each get a unique
incrementing id from `_next_request_id()` and are unaffected — which is
why only Codex traffic triggers the blanking.
This PR gives each Codex WS feed emission a fresh unique id from the
same authoritative `_next_request_id()` counter (per-turn, residual, and
summary sites), restoring the "one unique id per feed row" invariant
that Anthropic already satisfies. With unique ids the Alpine `:key`s no
longer collide and the table renders Codex turns like any other request.
Feed-row counts, per-turn token and savings values, ordering, and
per-session metrics/cost bookkeeping are unchanged; the `[{session
request_id}]` log prefixes still use the session id so a session's log
lines stay greppable together.
Scope: this is the backend root-cause fix. Hardening the dashboard
`:key` against duplicate/`null` keys is a separate render-robustness
change and is deliberately left to a follow-up (`Refs #310`); once the
backend guarantees unique ids, the collision that blanks the table is
gone. The comment's secondary `savings_percent.toFixed(0)` concern is
already resolved on `main` (the row uses `formatOptionalPercent`).
Closes #310. The concrete duplicate-`request_id` diagnosis and the live
`/stats?cached=1` capture came from @sphynxttl's comment on the issue.
## 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/proxy/handlers/openai.py`: in `handle_openai_responses_ws`,
mint a fresh `request_id` from `_next_request_id()` at each request-feed
emission — the per-turn `RequestOutcome` in
`_record_ws_response_metrics`, the session-residual `RequestOutcome`,
and the session-summary `RequestLog` — instead of reusing the one
session id. The per-turn id is minted after the existing all-deltas-≤0
early-return, so no-op turns still emit nothing. The `[{request_id}]`
PERF/log prefixes keep the session id for operator correlation.
- `tests/test_openai_codex_ws_lifecycle.py`: new tests driving a
two-turn Codex WS session through the `_FakeWebSocket`/`_FakeUpstream`
harness with a capturing request logger and an incrementing
`_next_request_id`, asserting distinct per-row `request_id`s without
relying on local repro artifacts, unchanged per-turn token/savings
values, no phantom row for a no-op turn, and session-prefixed logs.
- `CHANGELOG.md`: `Unreleased → Fixed` entry.
## Testing
- [x] Unit tests pass (`uv run pytest
tests/test_openai_codex_ws_lifecycle.py`)
- [x] Linting passes (`uv run ruff check .`)
- [ ] Type checking passes (`uv run mypy headroom`)
- [x] New tests added for new functionality when applicable
- [x] Manual testing performed
### Test Output
```text
$ uv run pytest tests/test_openai_codex_ws_lifecycle.py -q
............................. [100%]
29 passed in 1.69s
$ uv run ruff check .
All checks passed!
```
## Real Behavior Proof
- Environment: Windows 11, Python 3.12 via `uv`, no live provider — the
WS handler is exercised through the in-process
`_FakeWebSocket`/`_FakeUpstream` harness that mirrors the production
wire shape.
- Exact command / steps: ran `uv run pytest
tests/test_openai_codex_ws_lifecycle.py::test_ws_multi_turn_request_ids_are_unique
-q` on this branch and `uv run pytest
tests/test_openai_codex_ws_lifecycle.py -q` for the focused file; on
`origin/main`, the new regression node is absent and the WS emit sites
still use `request_id=request_id` in
`headroom/proxy/handlers/openai.py`.
- Observed result: a two-turn Codex WS session now yields
`recent_requests` rows with unique `request_id`s, so the dashboard's
Alpine `:key` no longer collides; token/savings values and row counts
are unchanged; a no-op turn still emits no row. On `origin/main`, the
handler still reuses the session `request_id` at the WS feed emit sites.
- Not tested: live dashboard browser render of the fixed feed.
## 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 have updated the CHANGELOG.md if applicable
## Additional Notes
- Type checking (`mypy`) left unchecked: not run in this pass; the
change only swaps the source of an existing `request_id` string field.
- Non-goal (out of scope): hardening the dashboard `x-for` `:key`
against duplicate/`null` keys is a separate render-robustness fix for a
follow-up (`Refs #310`); this PR removes the source of the duplicates.
The comment's `savings_percent.toFixed(0)` concern is already fixed on
`main` (`formatOptionalPercent`).
- Prior art: an earlier change (issue #399 era) added the per-turn Codex
WS `RequestLog`/PERF emission but reused the session id; this PR makes
those ids unique.
|
||
|
|
4ec416df88 |
fix(proxy): stop discarding compressed Codex WS later-frame payloads (#2823)
## Description `headroom perf` reports 0 tokens saved for Codex CLI sessions despite real traffic being processed (confirmed via the reporter's live proxy stats in the issue). Root cause: a misplaced `return` statement in the Codex WS later-frame compression path silently discards every compressed payload and skips all token/savings bookkeeping for it. Closes #2819 ## 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/proxy/handlers/openai.py` (`_maybe_compress_response_create_frame`): PR #1579 (2026-07-16) moved a `return (raw_after_store, ...)` statement to the same indentation as the enclosing `except Exception:` block instead of inside it. That made the `return` fire **unconditionally** after every later (2nd+) `response.create` frame in a Codex WS session — success or failure — always forwarding the original pre-compression frame upstream and skipping the entire success-path code below it (correct rewritten-payload return, `tokens_saved`, `attempted_input_tokens_total`, `ws_frames_compressed`). Fixed by moving the `return` back inside the `except` block, restoring the success path. - `tests/test_openai_codex_ws_lifecycle.py`: new regression test `test_ws_later_frame_compression_is_actually_forwarded` — mocks the compressor to report `modified=True` with a distinct rewritten payload on a later frame, asserts the rewritten payload (not the original) is what's actually sent upstream. ## Testing - [x] Unit tests pass (`pytest`) - [ ] Linting passes (`ruff check .`) — not run locally, will confirm via CI - [ ] Type checking passes (`mypy headroom`) — not run locally, will confirm via CI - [x] New tests added for new functionality - [x] Manual testing performed (see Real Behavior Proof) ### Test Output ```text $ .venv/Scripts/python -m pytest tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_per_frame_memory.py tests/test_codex_ws_savings_deferral.py tests/test_openai_codex_ws_timings.py -q ............................................... 48 passed in 5.34s $ .venv/Scripts/python -m pytest tests/ -k "openai or codex" -q (wider sweep, unrelated dirs excluded) 968 passed, 3 failed, 77 skipped, 2 errors in 483.21s ``` The 3 failures (`test_client_integration.py::test_auto_detect_openai_optimizer`, `test_compress_route_tokenizer_by_model.py::...[deepseek/deepseek-v4]`, `test_learn/test_integration.py::TestCodexIntegration::test_full_pipeline`) reproduce identically on a clean, unmodified `main` — confirmed by stashing this PR's changes and re-running. They're local-environment issues (a live litellm 503, and this dev box's tool registry missing a `Bash` entry), not caused by this change. ## Real Behavior Proof - Environment: Windows 11, Python 3.14.5, local venv, `headroom._core` rebuilt via `maturin develop --release` against current `main` to rule out stale-build noise - Exact command / steps: (1) `git blame` on the buggy block traced the misplaced `return` to commit `1c50eca8` (PR #1579); (2) wrote a regression test that scripts two `response.create` frames over a fake Codex WS session, with the compressor mock returning `modified=False` for frame 1 and `modified=True` (with a distinct payload) for frame 2; (3) ran the test against the pre-fix code (`git stash` isolating just the source fix, keeping the test) — **failed**, `upstream.sent[-1]` was the untouched original frame; (4) ran the test against the fix — **passed**, `upstream.sent[-1]` is the compressed payload; (5) added a further regression test for the later-frame non-timeout-exception path Codecov flagged as uncovered, confirmed `pytest tests/test_openai_codex_ws_lifecycle.py -q` passes 32/32 - Observed result: confirmed the bug exists and the fix resolves it, at the unit level - Not tested: have not reproduced the full `headroom wrap codex` → `headroom perf` end-to-end flow against a live Codex CLI session (no access to Codex CLI / real OpenAI credentials in this environment) — root cause and fix are verified at the code-path level via the regression test above, not via the reporter's exact repro steps ## 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 (N/A — internal bugfix, no user-facing behavior/docs change beyond "compression now works as originally intended") - [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 - [ ] I have updated the CHANGELOG.md if applicable (release-please generates this automatically from commit messages) ## Additional Notes **Bonus finding, not just a metrics bug**: because the compressed payload was discarded and the original was always sent, this also means Codex WS sessions with multiple turns were silently getting **zero compression benefit** past the first `response.create` frame — not just wrong dashboards. The fix restores actual compression for those turns, not only correct accounting of it. |
||
|
|
1c50eca8b3 |
fix(proxy): skip Responses memory tools for ChatGPT auth (#1579)
## Description Fix ChatGPT/Codex session-auth Responses proxy handling so the ChatGPT backend always receives an explicit `store=false`, while keeping Responses memory tools limited to the regular API-key path where stored responses are supported. ## 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 - Detect ChatGPT auth before Responses memory-tool injection and force `store=false` for ChatGPT-auth Responses payloads. - Skip Responses memory tools and transparent memory-tool continuation handling for ChatGPT auth across HTTP, WebSocket first frames, WebSocket follow-up `response.create` frames, and WS-to-HTTP fallback. - Preserve API-key behavior after the current main merge: API-key requests that explicitly set `store=false` skip Responses memory tools, while API-key requests that receive injected memory tools are forced to `store=true` for continuation support. - Address Copilot formatter comments by making `_allow_responses_memory_tools` call sites formatter-stable. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ uv run --extra dev ruff format --check headroom/proxy/handlers/openai.py 1 file already formatted $ uv run --extra dev ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_routing.py tests/test_openai_codex_ws_timings.py tests/test_ws_http_fallback.py All checks passed! $ uv run --extra dev python -m pytest -q tests/test_openai_codex_routing.py tests/test_openai_codex_ws_timings.py tests/test_ws_http_fallback.py 37 passed in 0.34s ``` ## Real Behavior Proof - Environment: Local checkout of `fix/codex-store-false-memory-tools` using `uv run --extra dev`. - Exact command / steps: Ran the focused formatter, lint, and pytest commands listed in `Testing`. - Observed result: Formatting is stable, lint passes, and the focused OpenAI/Codex routing and fallback tests pass. - Not tested: Full test suite, `mypy headroom`, and a fresh live ChatGPT backend probe after the formatter-only follow-up. The original PR validation recorded that valid ChatGPT subscription backend requests return `200` with `store=false`, while identical `store=true` or omitted `store` requests return `400 Store must be set to false`. ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A. ## Additional Notes - Post-deploy monitoring terms: `Responses: forced store=false for ChatGPT auth`, `WS Responses: forced store=false for ChatGPT auth`, `chatgpt_store_false`, `Memory: forced store=true for Responses memory tool continuation`, and upstream 400s containing `Store must be set to false`. - Expected healthy signals: ChatGPT-auth Responses requests keep `store=false` and no longer fail with `Store must be set to false`; API-key memory-tool flows still inject memory tools and can continue via `previous_response_id`. - Rollback trigger: any increase in ChatGPT-auth 400s, API-key memory-tool continuation failures, or missing memory tool injection on API-key Responses requests. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
ac7ee4e0bf |
fix(proxy): support Codex WS compatible gateways (#1281)
Adds opt-in compatibility for OpenAI-compatible WebSocket gateways used behind Codex /v1/responses. - HEADROOM_OPENAI_WS_FLATTEN_RESPONSE_CREATE=1 flattens Codex response.create frames before upstream send. - HEADROOM_OPENAI_WS_PROPAGATE_UPSTREAM_CLOSE=1 propagates upstream close code/reason back to the client. - Default behavior is unchanged. Tested: python -m pytest tests/test_openai_codex_ws_lifecycle.py -q 18 passed Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
e5b3a634df |
fix(proxy): dedupe Codex WS request logging for accurate mixed-provider dashboards (#2189)
## Description Running Claude Code (Anthropic) and Codex (OpenAI) against the **same** Headroom proxy instance on one port produced incorrect, unstable dashboard data. The proxy core is provider-isolated and multi-provider-safe by design; the defect was in the observability layer. The Codex `/v1/responses` **WebSocket** handler was the only path in the proxy that wrote to the request logger by hand instead of through the unified `emit_request_outcome` funnel, and it did so twice per session close: the per-turn funnel record plus an unconditional cumulative session-summary `RequestLog`. This PR removes the duplicate summary log so Codex WS emits exactly one request log per turn, matching the HTTP provider paths. ## 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 - Dropped the duplicate cumulative session-summary `RequestLog` in the Codex WS handler while preserving the per-turn `emit_request_outcome` path. - Preserved gated `request_messages` and `turn_id` on residual outcomes so dashboard telemetry keeps the useful attribution without double-counting tokens. - Ensured explicit `--anyllm-provider` wins over a leaked `HEADROOM_ANYLLM_PROVIDER` environment variable. - Registered retry delay settings that had drifted out of the settings registry. - Hardened tests against developer-shell `HEADROOM_*` / `ANTHROPIC_CUSTOM_HEADERS` leakage and stabilized several focused proxy/wrap test fixtures. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ .venv/bin/pytest tests/ -q -p no:cacheprovider 8529 passed, 537 skipped, 5831 warnings in 276.25s (0:04:36) $ .venv/bin/ruff check <touched files> All checks passed! ``` ## Real Behavior Proof - Environment: macOS (Darwin 25.4.0), Python 3.13.14, pytest 9.0.3, ruff via project venv, branch `fix/multi-provider-runtime`. - Exact command / steps: Ran the full test suite without pytest cache provider and Ruff on all touched files; used `git stash` to confirm the stale fake-config failures pre-existed this change. - Observed result: Full suite passed with no failures; Ruff passed; Codex WS now routes end-of-session logging through `emit_request_outcome`, emitting one request log per turn with the same accounting model as Anthropic HTTP turns. - Not tested: Live simultaneous Claude + Codex dashboard run. `mypy headroom` was not run to completion; a scoped run reported one pre-existing `settings_store.py:470` coercion error outside this diff. ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A - server-side observability fix; no UI markup changed. ## Additional Notes - The proxy's multi-provider routing, header/auth isolation, and per-model cache keying are already correct and unchanged here; only the WS observability write path was double-counting. - Architectural assessment: `plans/reports/research-260714-0004-multi-provider-upstream-compression-report.md`; root-cause + resolution trail: `plans/reports/debug-assessment-260714-0011-dashboard-instability-mixed-claude-codex-report.md`. - No live simultaneous Claude + Codex dashboard run was performed; validation is from test coverage and code review of the WS logging path. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
551f473e04 |
fix(proxy): accept Codex websocket before upstream retries (#2203)
## Description Codex Desktop could abandon Headroom's local `/v1/responses` WebSocket handshake before Headroom's upstream retry strategy had a chance to recover. The ChatGPT-auth path waited for an upstream opening handshake with a minimum 30-second timeout before sending the local 101, while the reported Codex Desktop handshake expired after about 34 seconds. This change accepts validated ChatGPT-auth Codex WebSockets before opening the upstream connection, then keeps the existing upstream retries and HTTP fallback behind the established local session. API-key sessions retain connect-before-accept behavior so upstream `x-codex-*` headers can still be attached to their client-facing 101. The change is scoped to the pre-101 timing failure and does not address the separate large-context streaming investigation in #1944. Closes #2184 ## 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 - Accept ChatGPT-auth Codex WebSocket clients before the upstream connect and retry loop. - Preserve API-key connect-before-accept ordering and upstream `x-codex-*` handshake-header forwarding. - Keep upstream retry, relay, usage-state refresh, and WebSocket-to-HTTP fallback behavior after the local 101. - Add a deterministic regression that blocks the first upstream opening handshake and proves the local acceptance deadline is independent of it. ## Testing - [x] Unit tests pass (`uv run pytest tests/test_openai_codex_ws_lifecycle.py -q`) - [x] Linting passes (`uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py`) - [ ] Type checking passes (`uv run mypy headroom`) - [x] New tests added for new functionality when applicable - [ ] Manual testing performed ### Test Output ```text uv run pytest tests/test_openai_codex_ws_lifecycle.py -q 28 passed in 2.02s uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py All checks passed! uv run ruff format headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py --check 2 files already formatted ``` ## Real Behavior Proof - Environment: Python 3.12, synced development worktree, local fake Codex client and upstream WebSocket, no live provider - Exact command / steps: Run `uv run pytest tests/test_openai_codex_ws_lifecycle.py::test_chatgpt_ws_accepts_before_stalled_upstream_connect -q`; the fake upstream blocks its first opening handshake while the client enforces a bounded local-accept deadline. - Observed result: `1 passed in 0.46s`; the ChatGPT-auth client receives its local 101 before the blocked upstream connect is released, and the handler continues into its existing upstream recovery path. - Not tested: live Codex Desktop pre-turn compaction against ChatGPT subscription infrastructure ## 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 ## Additional Notes `CHANGELOG.md` is unchanged because the release pipeline generates it from conventional commits. No user documentation changes are required; the handler comments and ordered-flow docstring are updated with the auth-mode-specific behavior. The broader #1944 large-context disconnect surface remains out of scope. --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
5cece7bf58 |
fix(proxy): Strip Codex responses-lite marker from response.create frame body (#1820)
## Description Codex CLI mirrors the `X-OpenAI-Internal-Codex-Responses-Lite` request header into the `response.create` WS frame body under `client_metadata.ws_request_header_x_openai_internal_codex_responses_lite`. The existing fix strips the header itself (both the HTTP fallback path and the WS handshake path) but never touched this frame-body copy, so Headroom still forwarded it to `wss://chatgpt.com/backend-api/codex/responses` unmodified. Upstream rejects `gpt-5.x` models whenever that field is truthy, so every Codex-through-Headroom turn on gpt-5.5/5.4 failed with a 400, even on builds that already contain the header-strip fix. Closes #1523 ## 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/proxy/handlers/openai.py`: add `_strip_codex_lite_metadata()`, which removes `client_metadata.ws_request_header_x_openai_internal_codex_responses_lite` from a `response.create` frame body (checks both the flat-body shape and the `{"response": {...}}` envelope shape Codex uses depending on call path). Fail-safe no-op on non-JSON payloads or when the key is absent. - Wired the helper into both WS-forwarder send sites in the same file: the initial `first_msg_raw` send and the steady-state `_client_to_upstream` relay send. - `tests/test_openai_codex_ws_lifecycle.py`: added `test_ws_first_frame_strips_codex_lite_metadata_mirror`, which sends a `response.create` frame carrying the mirror key through the handler and asserts the frame actually forwarded to the fake upstream has the key removed while sibling `client_metadata` fields (e.g. `thread_id`) survive. ## 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 $ ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py All checks passed! $ mypy headroom/proxy/handlers/openai.py Success: no issues found (pre-existing unrelated notes in headroom/proxy/server.py only) $ pytest tests/test_openai_codex_ws_lifecycle.py tests/test_openai_codex_routing.py tests/test_codex_openai_contract_parity.py -q 52 passed, 23 warnings in 1.66s # Proof the new test actually catches the bug (checked out the parent commit's # openai.py, i.e. pre-fix, with the new test present): $ pytest tests/test_openai_codex_ws_lifecycle.py -q -k strips_codex_lite_metadata FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_first_frame_strips_codex_lite_metadata_mirror AssertionError: assert 'ws_request_header_x_openai_internal_codex_responses_lite' not in {'thread_id': 't_1', 'ws_request_header_x_openai_internal_codex_responses_lite': True} 1 failed, 26 deselected in 0.63s # Restored the fix -> same test passes (see "52 passed" run above). ``` ## Real Behavior Proof - Environment: macOS, Python 3.13, headroom-ai 0.30.0 (pip-installed copy patched identically to this diff), Codex CLI 0.142.5, ChatGPT Plus subscription auth, model `gpt-5.5`. - Exact command / steps: `headroom wrap codex` (proxy on 127.0.0.1:8787) → `codex exec "..."` with `model_provider = "headroom"` in `~/.codex/config.toml`. Also reproduced deterministically via a throwaway debug proxy instance with `HEADROOM_CODEX_WIRE_DEBUG=1` wire capture, isolated from the live account/session. - Observed result: pre-patch, deterministic `400 unsupported_value` / "This model is not supported when using X-OpenAI-Internal-Codex-Responses-Lite" on every single turn (reproduced repeatedly, across a header-only-stripped build). Post-patch (installed copy with this exact diff): clean full completions streamed to `response.completed` with zero error frames via wire capture, and — after restarting the live production proxy to load the patched module — the user confirmed `codex` working normally end-to-end through Headroom on `gpt-5.5` in real day-to-day use, not just the isolated repro. - Not tested: the HTTP (non-WS) fallback path for Codex — that path doesn't carry a `response.create` frame body in the same way, and the existing header-strip logic already covers it; no upstream 400s observed there in this investigation. ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A — backend WS proxy fix, no UI surface. ## Additional Notes - CHANGELOG.md / docs left untouched: this is a narrowly-scoped bugfix to existing (undocumented-at-user-level) WS forwarding internals; happy to add a CHANGELOG entry if maintainers want one. - Full root-cause writeup with wire-capture details is on the issue: https://github.com/headroomlabs-ai/headroom/issues/1523#issuecomment-4887989873 - Did not run the full repo-wide `pytest`/`mypy headroom` (whole package) — scoped to the modified file and the three most relevant existing test modules (`test_openai_codex_ws_lifecycle.py`, `test_openai_codex_routing.py`, `test_codex_openai_contract_parity.py`), all passing. Glad to run the full suite if a maintainer wants that in CI instead. Co-authored-by: JerrettDavis <mxjerrett@gmail.com> Co-authored-by: Tejas Chopra <chopratejas@gmail.com> |
||
|
|
4bd3ddfaa5 |
fix(opencode): use local MCP config (#1383)
## Description Fixes OpenCode Headroom MCP configuration across wrap, MCP install/status/uninstall, and persistent install docs/CLI. OpenCode was being configured to use a remote HTTP MCP endpoint at `/mcp`, but the Headroom proxy does not expose MCP there. The correct OpenCode configuration is a local stdio MCP server that runs `headroom mcp serve`. Closes #1380 ## Type of Change - [x] Bug fix - [ ] New feature - [ ] Breaking change - [x] Documentation update - [x] Tests ## Changes Made - Changed OpenCode MCP registration to emit `type: "local"` with `command: ["headroom", "mcp", "serve"]`. - Changed OpenCode MCP environment serialization from `env` to OpenCode's `environment` key, while still reading legacy `env` entries. - Removed generated remote `/mcp` entries from OpenCode wrap/runtime config. - Made `wrap opencode --no-mcp` skip persistent `mcp.headroom` injection. - Kept provider-only OpenCode config injection from writing MCP; MCP persistence is owned by the registrar path. - Made `headroom mcp status` and `headroom mcp uninstall` use the registrar lifecycle so OpenCode is covered. - Added `opencode` to persistent install `--target` choices. - Clarified OpenCode persistent install docs to use `--scope provider` for direct `opencode.json` edits. - Added regression coverage for registrar serialization, wrap behavior, runtime config, provider-scope install, MCP CLI lifecycle, and install target parsing. ## Testing - [x] `rtk .venv/bin/python -m pytest tests/test_mcp_registry tests/test_cli/test_mcp.py tests/test_cli/test_wrap_opencode.py tests/test_providers_opencode_config.py tests/test_providers_opencode_install.py tests/test_install -q` - [x] Result after absorbing #1381 overlap: `263 passed, 1 skipped` - [x] Targeted Ruff check passed for the changed Python/test files. - [x] Targeted Ruff format check passed for the changed Python/test files. - [x] Isolated HOME smoke tests with real `opencode mcp list --pure`. ## Real Behavior Proof - `headroom mcp install --agent opencode --proxy-url http://127.0.0.1:9000 --force` against an isolated HOME wrote a valid local OpenCode MCP entry with `environment.HEADROOM_PROXY_URL`. - `opencode mcp list --pure` against that isolated HOME connected to `headroom mcp serve`. - `headroom wrap opencode --prepare-only --no-rtk --no-serena --port 9001` wrote local MCP plus provider config. - `headroom wrap opencode --prepare-only --no-rtk --no-serena --no-mcp --port 9002` wrote provider config without `mcp.headroom`. - Generated runtime `OPENCODE_CONFIG_CONTENT` was accepted by `opencode mcp list --pure`; `include_mcp=False` reported no MCP servers. - `headroom mcp status` detected the isolated OpenCode config and read the custom proxy URL. - `headroom mcp uninstall` removed `mcp.headroom` from the isolated OpenCode config while leaving provider config intact. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review |
||
|
|
d24a3f8425 |
fix(proxy): bound Codex WS compression fallback latency (#1802)
## Description Codex `/v1/responses` WebSocket frames could spend the full global compression timeout before falling through unchanged, then report only a generic `compression_exception` reason. That made a recoverable timeout look like an opaque compression failure and left Codex users waiting around 30 seconds for frames that did not produce useful compression. This keeps the existing compression executor, adds a Codex WS-specific compression timeout bound, and records timeout fallback distinctly from other compression exceptions. Closes #922. ## 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 - Bound Codex Responses WebSocket frame compression with a WS-specific timeout. - Pass that timeout through the existing compression executor instead of adding a parallel executor path. - Record timeout passthrough with `compression_timeout` instead of the generic compression exception reason. - Preserve generic `compression_exception` for non-timeout failures. - Add coverage for first-frame timeout bounds, timeout reason logging, generic exception preservation, and later-frame failed metrics. ## Testing - [x] Unit tests pass (`uv run pytest tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_compression_scheduler.py tests/test_compression_observability.py -q`) - [x] Linting passes (`uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_compression_scheduler.py tests/test_compression_observability.py`) - [ ] Type checking passes (`uv run mypy headroom`) - [x] New tests added for new functionality when applicable - [x] Manual testing performed ### Test Output ```text uv run pytest tests/test_openai_codex_ws_lifecycle.py -q 22 passed in 1.38s uv run pytest tests/test_codex_ws_compression_scheduler.py tests/test_compression_observability.py -q 14 passed, 1 skipped in 3.63s uv run pytest tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_compression_scheduler.py tests/test_compression_observability.py -q 36 passed, 1 skipped in 2.09s uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py tests/test_codex_ws_compression_scheduler.py tests/test_compression_observability.py All checks passed! uv run ruff format headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py --check 2 files already formatted ``` ## Real Behavior Proof - Environment: Windows, Python through the project `uv` environment. - Exact command / steps: run the focused Codex WS timeout regressions with small monkeypatched timeout values. - Observed result: base uses the global timeout path or reports only generic `compression_exception`; head passes with Codex WS timeout bounded to the smaller WS cap, logs `compression_timeout` for timeout fallback, preserves `compression_exception` for non-timeout failures, and records failed metrics for later-frame timeout fallback. - Not tested: live Codex Desktop traffic against paid OpenAI credentials. ## 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 have updated the CHANGELOG.md if applicable ## Additional Notes No changelog entry is needed for this request-path bug fix. Type checking was not part of the focused local validation for this Python-only change. Live Codex Desktop validation is not included because the regression is covered at the handler boundary. |
||
|
|
0b0133b7fd |
Wire OpenAI Responses output shaping (#1438)
## Description Wire output shaping for OpenAI Responses traffic across HTTP `/v1/responses` and Codex WebSocket `response.create` frames. The change adds provider-specific shaping for `instructions`, `reasoning.effort`, and `text.verbosity` while keeping Anthropic request mutation separate. Review follow-up: merged byte-faithful `/v1/responses` forwarding from #1557 and marks shaped HTTP Responses payloads as `body_mutated=True`, so retry forwarding sends the shaped body instead of the original raw bytes. ## Type of Change - [ ] Bug fix (non-breaking change fixes an issue) - [x] New feature (non-breaking change adds functionality) - [ ] Breaking change (fix or feature would cause existing functionality change) - [x] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Added OpenAI Responses output shaping for `instructions`, `reasoning.effort`, and `text.verbosity`. - Wired shaping into `/v1/responses` HTTP and Codex WebSocket `response.create` paths. - Preserved `x-headroom-bypass` and `HEADROOM_OUTPUT_HOLDOUT` behavior. - Added output-shaper transform labels for verbosity, text verbosity, reasoning effort, holdout control, and strata. - Updated output-savings conversation keys for Responses payloads and WS `response.create` envelopes. - Counted WS frame payload tokens when assigning output-savings strata. - Merged byte-faithful `/v1/responses` forwarding from #1557 and kept shaped HTTP bodies on the mutated-forwarding path. - Added tests for classification, shaping, holdout, bypass, labels, WS strata, and byte-faithful forwarding compatibility. - Updated `CHANGELOG.md` for OpenAI Responses output-shaping support. ## 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 --extra dev python -m pytest tests/test_openai_codex_ws_lifecycle.py tests/test_openai_responses_output_shaper.py tests/test_codex_responses_passthrough_bytes.py tests/test_output_shaper.py tests/test_output_savings.py -q 110 passed, 1 warning in 1.49s $ uv run --extra dev ruff check headroom/proxy/handlers/openai.py tests/test_openai_responses_output_shaper.py tests/test_codex_responses_passthrough_bytes.py tests/test_openai_codex_ws_lifecycle.py tests/test_output_shaper.py tests/test_output_savings.py All checks passed! $ git diff --check No whitespace errors. ``` ## Real Behavior Proof - Environment: local macOS checkout, branch `output-shaper-openai-responses`. - Exact command / steps: ran targeted pytest, ruff, and diff checks listed above. - Observed result: targeted tests passed with an existing FastAPI TestClient deprecation warning; ruff passed; diff check passed. - Not tested: full repository test suite, live OpenAI traffic, browser dashboard rendering, full `mypy headroom`. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows project's style guidelines - [x] I performed self-review of my code - [x] I commented my code, particularly in hard-to-understand areas - [x] I made corresponding changes to documentation - [x] My changes generate no new warnings - [x] I 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 updated `CHANGELOG.md` if applicable ## Screenshots N/A ## Additional Notes - Non-applicable Type Change items are left unchecked. - The pytest warning comes from `fastapi.testclient` importing Starlette TestClient and was not introduced by this change. - `CHANGELOG.md` includes entries for OpenAI Responses output-shaping support and byte-faithful `/v1/responses` forwarding compatibility. --------- Co-authored-by: obchain <riteshnikhoriya94@gmail.com> |
||
|
|
5d3803a21c |
fix(proxy): strip Codex lite header from OpenAI WebSockets (#1543)
## Description Codex WebSocket traffic through Headroom can forward `X-OpenAI-Internal-Codex-Responses-Lite` upstream. OpenAI tightened enforcement of that header on 2026-06-26 for `gpt-5.5`, `gpt-5.4`, and `gpt-5.4-mini`, so the same Codex setup can fail through Headroom with `unsupported_value` while succeeding when Headroom is bypassed. The OpenAI Responses WS handler strips only `x-headroom-*` internal headers today, so this Codex client header survives into both the direct upstream WebSocket connect and the WS HTTP fallback path. This change strips `X-OpenAI-Internal-Codex-Responses-Lite` from the upstream header copy inside `handle_openai_responses_ws` after routing resolution and before the upstream request is sent. `_ws_http_fallback(...)` reuses that same header dict, so the fallback path inherits the fix without a second guard. `headroom/proxy/helpers.py` stays unchanged; the shared helper contract remains `x-headroom-*` only. Closes #1525 ## 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 - Add a narrow case-insensitive strip for `X-OpenAI-Internal-Codex-Responses-Lite` in `headroom/proxy/handlers/openai.py` after `_resolve_codex_routing_headers(...)` and before `websockets.connect(...)`. - Keep `_strip_internal_headers(...)` in `headroom/proxy/helpers.py` unchanged so the documented `x-headroom-*` stripping scope does not widen. - Extend `tests/test_openai_codex_ws_lifecycle.py` to capture `additional_headers`, prove the direct WS leak on base, prove the fix on head, prove `_ws_http_fallback(...)` inherits sanitized headers, and prove adjacent non-lite headers still survive. ## Testing - [x] Unit tests pass (`uv run pytest tests/test_openai_codex_ws_lifecycle.py -k "codex_responses_lite or without_codex_lite" -v`) - [x] Linting passes (`uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py`) - [ ] Type checking passes (`uv run mypy headroom`) - [x] New tests added for new functionality when applicable - [ ] Manual testing performed ### Test Output ```text Base proof before the fix: uv run pytest tests/test_openai_codex_ws_lifecycle.py -k "test_ws_codex_responses_lite_header_is_not_forwarded_upstream" -v FAILED tests/test_openai_codex_ws_lifecycle.py::test_ws_codex_responses_lite_header_is_not_forwarded_upstream AssertionError: assert 'X-OpenAI-Internal-Codex-Responses-Lite' not in { 'authorization': 'Bearer test', 'X-OpenAI-Internal-Codex-Responses-Lite': 'true', 'X-OpenAI-Debug': 'keep-me', 'ChatGPT-Account-ID': 'acct-123', 'x-client': 'codex', 'OpenAI-Beta': 'responses_websockets=2026-02-06' } Focused regression proof after the fix: uv run pytest tests/test_openai_codex_ws_lifecycle.py -k "codex_responses_lite or without_codex_lite" -v tests/test_openai_codex_ws_lifecycle.py::test_ws_codex_responses_lite_header_is_not_forwarded_upstream PASSED [ 33%] tests/test_openai_codex_ws_lifecycle.py::test_ws_codex_responses_lite_header_is_not_forwarded_to_fallback PASSED [ 66%] tests/test_openai_codex_ws_lifecycle.py::test_ws_without_codex_lite_preserves_adjacent_headers_and_api_key_route PASSED [100%] ====================== 3 passed, 16 deselected in 0.62s ======================= uv run ruff check headroom/proxy/handlers/openai.py tests/test_openai_codex_ws_lifecycle.py All checks passed! ``` ## Real Behavior Proof - Environment: local pytest async lifecycle harness in `tests/test_openai_codex_ws_lifecycle.py`, no live provider required. - Exact command / steps: `uv run pytest tests/test_openai_codex_ws_lifecycle.py -k "codex_responses_lite or without_codex_lite" -v` - Observed result: before the fix, the new direct-leak test failed because `websockets.connect(..., additional_headers=...)` still contained `X-OpenAI-Internal-Codex-Responses-Lite`. After the fix, the focused rerun passed and proved that both direct WS connect and forced `_ws_http_fallback(...)` receive sanitized headers while adjacent non-lite headers still survive. - Not tested: live Codex traffic against OpenAI with real credentials, unless that is added during implementation. ## 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 have updated the CHANGELOG.md if applicable ## Additional Notes `uv run mypy headroom` is outside the focused proof for this small WS-path fix and may remain unchecked if the coding pass keeps the validation surface to targeted pytest plus ruff. `CHANGELOG.md` remains unchanged because the resolved repo config says Headroom's release pipeline generates changelog entries from conventional commits. |
||
|
|
b0cd0329c7 |
fix(proxy): stamp X-Client: codex on Responses endpoint for unidentified callers (#1036)
## Description Codex Desktop (OpenAI's Codex GUI/IDE app) sends a `User-Agent` of the form `Codex Desktop/<ver> (...)`, which is not in `CLIENT_UA_MAP`, so `classify_client` returns `None`. On a compression timeout the backend only takes the codex fail-open path when the client classifies as `codex`; for an unidentified client it refuses with HTTP 413 (`compression_refused`), which Codex treats as a hard connection failure. This stamps `X-Client: codex` on requests to the Responses endpoint (`/v1/responses`) only when the caller does not otherwise classify. The stamp is scoped to the Responses endpoint and skipped for any caller that already classifies through a recognized user-agent or explicit `X-Client`, so non-Codex traffic is not relabeled. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [x] Tests only ## Changes Made - Added `should_stamp_codex_client(path, headers)` in `headroom.proxy.auth_mode` for narrow Responses-endpoint client stamping. - Applied the stamp in HTTP middleware before downstream request classification. - Applied the same stamp in the Responses WebSocket handler, which bypasses HTTP middleware. - Added unit coverage for the stamp/skip matrix, including Codex Desktop, explicit clients, recognized user-agents, and WebSocket behavior. - Merged current `main` and kept both the new stamp coverage and the existing Codex WebSocket image-generation regression coverage. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check`) - [x] Formatting passes (`ruff format --check`) - [x] New tests added for new functionality ### Test Output ```text python -m pytest tests/test_codex_client_stamp.py tests/test_auth_mode.py tests/test_openai_codex_ws_lifecycle.py -q 48 passed in 1.13s ruff check headroom/proxy/auth_mode.py headroom/proxy/server.py headroom/proxy/handlers/openai.py tests/test_codex_client_stamp.py tests/test_auth_mode.py tests/test_openai_codex_ws_lifecycle.py All checks passed! ruff format --check headroom/proxy/auth_mode.py headroom/proxy/server.py headroom/proxy/handlers/openai.py tests/test_codex_client_stamp.py tests/test_auth_mode.py tests/test_openai_codex_ws_lifecycle.py 6 files already formatted ``` ## Real Behavior Proof - Environment: local Windows 11 development checkout, Python 3.13.13, branch updated from `upstream/main`. - Exact command / steps: Ran the focused unit suite for the new client-stamp behavior and the overlapping Codex WebSocket lifecycle tests, then ran `ruff check` and `ruff format --check` on the changed modules and tests. - Observed result: The focused suite passed with 48 tests, lint passed, and formatting passed. The tests assert that unidentified `/v1/responses` callers classify as Codex after stamping while explicit or already-recognized clients are preserved. - Not tested: a live end-to-end Codex Desktop session through a running `headroom wrap codex` instance; verification is at the unit/integration boundary for classification and request routing. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |
||
|
|
7dbbb4077e |
fix(proxy): keep codex image-generation WS turns alive through the relay (#1000)
## Description Image generation through the proxy fails. Driving Codex (`/v1/responses` over WebSocket) through Headroom, an image-generation turn never returns an image — the client retries (`Reconnecting… n/5`) and gives up, while the same prompt works when Codex talks to ChatGPT directly. Root cause: two independent defects on the upstream `websockets.connect()`, both specific to how image generation behaves on the wire: 1. **Pong deadline kills the silent render.** An image turn emits a single `response.image_generation_call.generating` event and then goes silent for 20–60s while the model renders (no data frames). The hard-coded `ping_timeout=20` treats that healthy-but-quiet connection as dead and tears it down as `upstream_error` mid-render, before the image is ready. 2. **1 MiB frame cap drops the image.** The finished image comes back inline as a single base64 frame that exceeds the `websockets` default `max_size=2**20` (1 MiB), raising `PayloadTooBig` exactly as the image lands. They compound: with only ping fixed, the session survives the silent phase (observed ~20s → ~54s) but then dies on the oversized image frame. Normal text/tool turns stream tokens continuously and stay well under 1 MiB, so neither defect affects them — which is why this only ever bit image generation. Closes: N/A (no tracking issue) ## 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/proxy/handlers/openai.py`: on the upstream `/v1/responses` connect, set `ping_timeout=None` (keep `ping_interval=20` for NAT keepalive) so a long silent render is not torn down on a missing pong, and `max_size=None` so the inline base64 image frame is accepted instead of raising `PayloadTooBig`. - `tests/test_openai_codex_ws_lifecycle.py`: add `test_ws_upstream_connect_allows_large_frames_and_no_pong_deadline`, which captures the upstream connect kwargs and pins `ping_timeout is None` / `max_size is None`. ## Testing <!-- Check what you actually ran, then paste the real command output below. --> - [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 $ ruff check . All checks passed! $ mypy headroom --ignore-missing-imports Success: no issues found in 358 source files $ pytest tests/test_openai_codex_ws_lifecycle.py -q collected 15 items tests/test_openai_codex_ws_lifecycle.py .............. [100%] ============================== 15 passed in 0.72s ============================== $ pytest tests/test_openai_codex_ws_lifecycle.py -k large_frames_and_no_pong -q collected 15 items / 14 deselected / 1 selected tests/test_openai_codex_ws_lifecycle.py . [100%] ======================= 1 passed, 14 deselected in 0.35s ======================= ``` End-to-end (managed Codex image generation through the running proxy): ```text # BEFORE fix: fails at ~20s (unpatched) / ~54s (ping-only) # WS /v1/responses completed (cause=upstream_error, # last_upstream_type=response.image_generation_call.generating) # -> client "Reconnecting… n/5", no image produced # AFTER fix: [codex] Image ready; stopping the turn. Saved image: /tmp/headroom-imagegen-test.png $ file /tmp/headroom-imagegen-test.png PNG image data, 1254 x 1254, 8-bit/color RGB, non-interlaced (908 KB) # proxy session count +1 -> the turn DID traverse the proxy and completed. ``` ## Real Behavior Proof - Environment: macOS, headroom 0.23.0 running as the Codex `model_provider` (proxy on `127.0.0.1:8787`), Codex CLI 0.139.0 driving a managed `/v1/responses` image-generation turn through the proxy. - Exact command / steps: trigger a Codex image-generation turn (gpt-image-2) with the proxy in front; observe the upstream `/v1/responses` WS session in `proxy.log` and whether a PNG is returned. - Observed result: before the change the session dies with `upstream_error` while `last_upstream_type=response.image_generation_call.generating` and no image is produced; after the change a valid 1254×1254 PNG is returned and the session traverses the proxy normally. - Not tested: the full `pytest` suite was not run locally — this machine has no Rust toolchain to rebuild the matching `_core` extension, so the complete suite (incl. the pyo3 tests) is left to CI. The affected `test_openai_codex_ws_lifecycle.py` module was run against the installed extension and passes 15/15; `ruff check .` and `mypy headroom` were run in full and pass. ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Screenshots (if applicable) N/A. ## Additional Notes - `ruff check .` (whole repo) and `mypy headroom --ignore-missing-imports` (358 source files) were run locally and pass. The only `pytest` not run locally is the full suite, because the Rust `_core` cannot be rebuilt here without a toolchain; the directly affected lifecycle module passes 15/15 and CI runs the rest. - Documentation / CHANGELOG left unchecked — this is a focused two-line behavioral fix on the upstream WS connect; happy to add a CHANGELOG entry if preferred. - `ping_timeout=None` keeps `ping_interval` for NAT keepalive; if you'd rather bound it, a generous finite value (e.g. 300s) would also fix the render case — happy to switch. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
0ce68dedd7 |
fix(proxy): restore Codex usage headers on WS and streaming SSE transports (#577) (#794)
## Description Codex's subscription/rate-limit window (the `x-codex-*` headers) was being **stripped on every transport Codex actually uses**, so session/weekly usage never reached the Codex CLI's own `/status` display, Headroom `/stats`/dashboard, or any consumer that sniffs the client-facing handshake. This PR restores it on **both** the WebSocket and streaming-SSE paths — the two halves of #577 — in one place. Fixes #577 **Supersedes #582 and #590.** This PR incorporates #582's SSE fix (carried verbatim with a `Co-authored-by` trailer) and additionally forwards the window onto the client `101` on the WS path, which #582/#590's capture-only WS code cannot do. Both can be closed as superseded once this merges — GitHub closing keywords only auto-close issues (hence `Fixes #577` above), not PRs, so #582/#590 need a manual close. ### WebSocket (`gpt-5.4+`) OpenAI delivers `x-codex-*` **only** on the upstream WS handshake response, never in data frames. `handle_openai_responses_ws` accepted the client WS *before* it connected upstream and never read `upstream.response.headers`, so the window was dropped. This reorders the handler to **connect upstream first**, extract the `x-codex-*` subset, then **accept the client WS with those headers attached** to the `101`, and refresh the Python state for `/stats` parity. ### Streaming SSE (incorporated from #582, @m16khb) Codex CLI almost always streams. `streaming.py` neither captured `x-codex-*` into `CodexRateLimitState` nor forwarded it — the forwarded-header filter matched only the substring `"ratelimit"`, which `x-codex-*` does not contain. This calls `update_from_headers()` **before** the `>=400` early-return (so a streaming 429/5xx still refreshes the window, matching the non-streaming handlers) and widens the forward filter to pass `x-codex-*`. > Credit: the SSE fix is @m16khb's work from #582, carried here verbatim with a > `Co-authored-by` trailer so the maintainer gets a single PR covering both > transports. This supersedes #582/#590's **WS** capture (which only writes > `/stats`); the connect-before-accept reorder additionally forwards the window to > the client `101`, which capture-only cannot do. #590's optional snapshot > persistence is intentionally left out (separable; hot-path sync write; doesn't > help the `101`-sniff consumers). ## 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 - `openai.py`: add `_extract_codex_handshake_headers()` (strictly `x-codex-*`, via `raw_items()` to avoid `MultipleValuesError`; never `set-cookie`/`authorization`). - `openai.py`: reorder `handle_openai_responses_ws` — connect-only retry loop runs before `accept()`; `accept(headers=...)` carries the forwarded window; first client frame read afterward. HTTP fallback preserved; it now also refreshes `/stats` from the HTTP response headers. - `streaming.py`: capture `x-codex-*` on all statuses + widen the forwarded-header filter (from #582). ### Diff-size note The bulk of the `openai.py` line count is **whitespace-only relocation**: the relay block dedents one level out of the old per-attempt `async with`. Logical change is ~290 lines. **Review with `?w=1`.** In API-key mode the handshake carries no `x-codex-*`, so the accept-header list is empty and the path behaves exactly as before — the fix only activates for ChatGPT-subscription auth. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed - WS: `test_ws_connect_happens_before_accept`, `test_ws_forwards_codex_headers_to_client_accept` (only `x-codex-*` forwarded; `set-cookie`/`authorization` excluded; `/stats` refreshed), `test_ws_connect_failure_falls_back_to_http`, `test_ws_first_frame_timeout_after_connect_closes_upstream`. - Fallback: `test_fallback_refreshes_codex_rate_limit_state`. - SSE: `test_codex_rate_limit_headers_captured_and_forwarded_in_streaming`, `test_codex_rate_limit_captured_on_streaming_429` (from #582). - Wire-level e2e: `tests/e2e_ws_codex_usage_headers.py` boots the real proxy + fake upstream + real `websockets` client and reads the client `101` — closes the gap the unit tests stub (that uvicorn/starlette actually write `accept(headers=...)`). ## Test Output ``` $ uv run pytest tests/test_proxy_streaming_ratelimit_headers.py \ tests/test_ws_http_fallback.py \ tests/test_openai_codex_ws_lifecycle.py \ tests/test_openai_codex_ws_timings.py \ tests/test_codex_rate_limits.py -q 63 passed in 0.83s $ .venv/bin/python tests/e2e_ws_codex_usage_headers.py [codex-hdr-e2e] client 101 headers: x-codex-primary-used-percent: 42 x-codex-primary-window-minutes: 300 x-codex-secondary-used-percent: 7 x-codex-secondary-window-minutes: 10080 [codex-hdr-e2e] /stats reflects codex window (primary-used=42) === CODEX-HDR E2E ALL GREEN === $ uv run ruff check . && uv run ruff format --check <touched files> All checks passed! ``` ## 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 - [ ] I have updated the CHANGELOG.md if applicable ## Additional Notes - **Why connect-before-accept (not capture-only).** Once `accept()` sends the `101`, headers can no longer be added; the `x-codex-*` window only exists after we connect upstream. Capturing into Python state (as #582/#590's WS code does) fixes `/stats` but not the Codex CLI's native display or any `101`-sniffing consumer — those need the headers *on the client handshake*, which requires the reorder. - **Security.** Forwarding is filtered strictly to `x-codex-*`; `set-cookie`, `authorization`, and all other upstream headers are never forwarded to the client (asserted by both the unit test and the e2e). 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Contract Schemas Per maintainer request: a JSON Schema (draft 2020-12) artifact enshrining the OpenAI interaction expectations this changeset relies on, so drift is detectable later. Committed following the repo's parity convention: - schema: `tests/parity/fixtures/codex_openai_contracts/codex-openai-interaction.schema.json` - test: `tests/test_codex_openai_contract_parity.py` binds the schema to the **live code** in both directions, so drift fails CI rather than living only in this description - every declared `x-codex-*` header must be consumed by `parse_codex_rate_limits`, and `_extract_codex_handshake_headers` must forward exactly the declared subset and never `set-cookie`/`authorization`. No new dependency (does not pull in `jsonschema`). It covers, as `$defs`: - `WSUpstreamHandshakeResponse` / `StreamingUpstreamResponseHeaders` - the upstream `x-codex-*` header family (full superset, with per-header wire pattern + the parsed semantic type) the WS and SSE captures read. Source of truth: `parse_codex_rate_limits`. - `ClientForwardedHandshakeHeaders` - the WS-101 **allow/deny** contract: only `x-codex-*` may be forwarded; `set-cookie`/`authorization` are explicitly forbidden (`propertyNames` + `not`). - `ClientForwardedStreamingHeaders` - the wider SSE forward set (`*ratelimit*` OR `x-codex*`). - `WSClientRequestFrame` / `WSRelayEvent` / `HTTPFallbackRequestBody` - the WS frame envelopes and the unwrapped HTTP-fallback POST body. - `CodexRateLimitStatsOutput` - the headroom `/stats` shape the parity tests assert. Validated with `jsonschema` (Draft202012 `check_schema` passes; positive instances from the e2e validate; negative instances - a leaked `set-cookie`, a fallback body still carrying a top-level `type` - are correctly rejected). <details> <summary><code>codex-openai-interaction.schema.json</code> (draft 2020-12)</summary> ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/chopratejas/headroom/contracts/codex-openai-interaction.schema.json", "title": "Codex <-> OpenAI interaction contracts (PR #794)", "description": "Enshrines the OpenAI interaction expectations this changeset depends on, so drift is detectable. Header values are transported as strings on the wire; the `x-headroom-parsed-type` annotation on each records the semantic type the parser (headroom/subscription/codex_rate_limits.py) coerces them to. Sources: codex_rate_limits.parse_codex_rate_limits (header family + gating), openai._extract_codex_handshake_headers (WS-101 forward filter), streaming.py (SSE forward filter).", "$defs": { "OpenAICodexWindowHeaders": { "title": "x-codex-*-{primary,secondary} window headers", "description": "A rolling rate-limit/subscription window. A window is materialized iff its `*-used-percent` header is present and numeric; `*-window-minutes` and `*-reset-at` are optional. `primary` and `secondary` are independent and either may be absent.", "type": "object", "properties": { "x-codex-primary-used-percent": { "type": "string", "pattern": "^\\d+(?:\\.\\d+)?$", "x-headroom-parsed-type": "float (0-100, NaN-guarded)", "description": "Percent of the primary window consumed. Gates creation of the primary window." }, "x-codex-primary-window-minutes": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int", "description": "Primary window size in minutes." }, "x-codex-primary-reset-at": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int (Unix epoch seconds)", "description": "Absolute reset time of the primary window." }, "x-codex-secondary-used-percent": { "type": "string", "pattern": "^\\d+(?:\\.\\d+)?$", "x-headroom-parsed-type": "float (0-100, NaN-guarded)", "description": "Percent of the secondary window consumed. Gates creation of the secondary window." }, "x-codex-secondary-window-minutes": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int" }, "x-codex-secondary-reset-at": { "type": "string", "pattern": "^\\d+$", "x-headroom-parsed-type": "int (Unix epoch seconds)" } }, "additionalProperties": true }, "OpenAICodexCreditsHeaders": { "title": "x-codex-credits-* headers", "description": "OpenAI credits balance. A credits snapshot is materialized iff `x-codex-credits-has-credits` is present; `unlimited` defaults to false; `balance` is optional.", "type": "object", "properties": { "x-codex-credits-has-credits": { "type": "string", "pattern": "^(?:[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[01])$", "x-headroom-parsed-type": "bool (true|false|1|0, case-insensitive)", "description": "Gates creation of the credits snapshot." }, "x-codex-credits-unlimited": { "type": "string", "pattern": "^(?:[Tt][Rr][Uu][Ee]|[Ff][Aa][Ll][Ss][Ee]|[01])$", "x-headroom-parsed-type": "bool (defaults false when absent/unparseable)" }, "x-codex-credits-balance": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Free-form server string, e.g. \"$5.00\"." } }, "additionalProperties": true }, "OpenAICodexMetaHeaders": { "title": "x-codex meta headers", "type": "object", "properties": { "x-codex-limit-name": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Active limit/model label, e.g. \"gpt-5.2-codex-sonic\"." }, "x-codex-promo-message": { "type": "string", "x-headroom-parsed-type": "str (empty -> null)", "description": "Server announcement. Also gates snapshot creation when present." } }, "additionalProperties": true }, "OpenAICodexRateLimitHeaders": { "title": "Full x-codex-* header family OpenAI may emit", "description": "Superset of every x-codex-* header headroom reads. parse_codex_rate_limits returns a snapshot iff at least one of: a primary window, a secondary window, a credits snapshot, or a non-empty promo message is present; otherwise null (treated as a non-Codex response). All members are individually optional.", "type": "object", "allOf": [ { "$ref": "#/$defs/OpenAICodexWindowHeaders" }, { "$ref": "#/$defs/OpenAICodexCreditsHeaders" }, { "$ref": "#/$defs/OpenAICodexMetaHeaders" } ], "additionalProperties": true }, "WSUpstreamHandshakeResponse": { "title": "OpenAI WS handshake (101) response headers consumed by the WS fix", "description": "On the Codex WebSocket transport the x-codex-* window is delivered ONLY on the upstream handshake response (never in data frames). handle_openai_responses_ws reads upstream.response.headers here. This is the contract the connect-before-accept reorder depends on: if OpenAI ever moves these headers off the handshake (e.g. into a frame), the WS half of the fix goes stale.", "$ref": "#/$defs/OpenAICodexRateLimitHeaders" }, "StreamingUpstreamResponseHeaders": { "title": "OpenAI streaming/HTTP response headers consumed by the SSE fix", "description": "On the streaming SSE/HTTP transport the same x-codex-* headers ride the HTTP response. streaming.py captures them on ALL statuses (including >=400) via update_from_headers, and forwards a wider set to the client (see ClientForwardedStreamingHeaders).", "$ref": "#/$defs/OpenAICodexRateLimitHeaders" }, "ClientForwardedHandshakeHeaders": { "title": "Headers forwarded onto the CLIENT-facing WS 101 (allow/deny contract)", "description": "_extract_codex_handshake_headers forwards ONLY headers whose (lowercased) name starts with `x-codex-`. Every other upstream handshake header - notably set-cookie and authorization - MUST NOT appear on the client 101. Enforced by propertyNames below and asserted by the unit tests + tests/e2e_ws_codex_usage_headers.py.", "type": "object", "propertyNames": { "pattern": "^[Xx]-[Cc][Oo][Dd][Ee][Xx]-" }, "not": { "anyOf": [ { "required": ["set-cookie"] }, { "required": ["Set-Cookie"] }, { "required": ["authorization"] }, { "required": ["Authorization"] } ] }, "additionalProperties": { "type": "string" } }, "ClientForwardedStreamingHeaders": { "title": "Headers forwarded to the client on the streaming SSE path", "description": "streaming.py forwards a header iff `\"ratelimit\" in name.lower()` OR `name.lower().startswith(\"x-codex\")`. This is a SUPERSET of the WS allow-list: it additionally passes generic *ratelimit* headers (e.g. the Anthropic streaming path) which do not contain the x-codex prefix.", "type": "object", "propertyNames": { "pattern": "(?:[Rr][Aa][Tt][Ee][Ll][Ii][Mm][Ii][Tt])|^[Xx]-[Cc][Oo][Dd][Ee][Xx]" }, "additionalProperties": { "type": "string" } }, "WSClientRequestFrame": { "title": "Client -> proxy WS data frame (Responses API over WS)", "description": "Codex sends the request as a response.create envelope. The HTTP fallback unwraps `.response` for the POST body, forces stream=true, and strips any top-level `type`. A flattened variant (no envelope, fields at top level) is also tolerated by the fallback.", "type": "object", "properties": { "type": { "const": "response.create" }, "response": { "type": "object", "properties": { "model": { "type": "string", "description": "e.g. gpt-5.4" }, "input": { "description": "String prompt or Responses-API structured input array.", "type": ["string", "array"] }, "stream": { "type": "boolean" } }, "required": ["model"], "additionalProperties": true } }, "required": ["type", "response"], "additionalProperties": true }, "WSRelayEvent": { "title": "proxy -> client WS data frame (relayed Responses API event)", "description": "SSE `data:` payloads relayed verbatim as WS text frames. `[DONE]` sentinels are dropped (not relayed). Every relayed event is a JSON object carrying a `type`. response.completed additionally carries usage under `response.usage`. anyOf (not oneOf): an error event also satisfies the looser lifecycle shape, which is fine.", "anyOf": [ { "title": "lifecycle event", "type": "object", "properties": { "type": { "type": "string", "examples": [ "response.created", "response.output_item.added", "response.completed" ] }, "response": { "type": "object", "additionalProperties": true } }, "required": ["type"], "additionalProperties": true }, { "title": "error event", "type": "object", "properties": { "type": { "const": "error" }, "error": { "type": "object", "properties": { "message": { "type": "string" } }, "required": ["message"], "additionalProperties": true } }, "required": ["type", "error"], "additionalProperties": true } ] }, "HTTPFallbackRequestBody": { "title": "proxy -> OpenAI HTTP POST body on WS->HTTP fallback", "description": "Derived from WSClientRequestFrame: the inner `.response` object, with `stream` forced to true and any top-level `type` removed.", "type": "object", "properties": { "model": { "type": "string" }, "stream": { "const": true }, "input": { "type": ["string", "array"] } }, "required": ["model", "stream"], "not": { "required": ["type"] }, "additionalProperties": true }, "CodexRateLimitStatsOutput": { "title": "headroom /stats output for the codex tracker (CodexRateLimitSnapshot.to_dict)", "description": "Internal (headroom-emitted) shape produced from the headers above; the WS and SSE update_from_headers parity tests assert this is refreshed. Included so drift in our own surface is also caught.", "type": "object", "properties": { "limit_id": { "const": "codex" }, "limit_name": { "type": ["string", "null"] }, "primary": { "$ref": "#/$defs/CodexWindowDict" }, "secondary": { "$ref": "#/$defs/CodexWindowDict" }, "credits": { "oneOf": [ { "type": "null" }, { "type": "object", "properties": { "has_credits": { "type": "boolean" }, "unlimited": { "type": "boolean" }, "balance": { "type": ["string", "null"] } }, "required": ["has_credits", "unlimited", "balance"], "additionalProperties": false } ] }, "promo_message": { "type": ["string", "null"] }, "captured_at": { "type": "number", "description": "Unix epoch seconds (float)." } }, "required": ["limit_id", "limit_name", "primary", "secondary", "credits", "promo_message", "captured_at"], "additionalProperties": false }, "CodexWindowDict": { "oneOf": [ { "type": "null" }, { "type": "object", "properties": { "used_percent": { "type": "number" }, "window_minutes": { "type": ["integer", "null"] }, "window_label": { "type": "string", "description": "e.g. \"5h\", \"7d\"-style label; \"unknown\" when window_minutes is null." }, "resets_at": { "type": ["integer", "null"], "description": "Unix epoch seconds." }, "seconds_until_reset": { "type": ["integer", "null"] } }, "required": ["used_percent", "window_minutes", "window_label", "resets_at", "seconds_until_reset"], "additionalProperties": false } ] } } } ``` </details> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: m16khb <m16khb@gmail.com> |
||
|
|
993c9076f9 |
refactor(proxy): migrate Codex WS + OpenAI HTTP + batch handlers; delete Databricks
Completes the migration of every ``metrics.record_request`` call site in ``headroom/proxy/handlers/`` onto the canonical funnel. After this commit, **zero ad-hoc record_request calls remain** across the entire handler subtree. Every request — regardless of provider, harness, or transport — flows through ``emit_request_outcome``. Migrated sites (this commit): * **handle_openai_responses_ws** (Codex WS) — 2 sites: - per-turn record (per ``response.completed``) - session-end residual (leftover tokens not captured per-turn) Pre-refactor these sites emitted only metrics + cost_tracker — no RequestLog, no PERF — so Codex traffic was invisible to ``headroom perf`` and the recent-requests feed. Funnel restores all four effects uniformly per turn. (Closes the visibility half of what #471's sibling PR addressed for the scheduler half.) The explicit session-summary RequestLog at session-end stays as a separate explicit log entry — it's a session-cumulative summary, distinct from per-turn observations. * **handle_openai_chat** — 3 sites: - response-cache hit (uses ``from_response_cache=True``) - backend-routed (LiteLLM/AnyLLM) non-streaming success - direct OpenAI non-streaming success * **handle_openai_responses** HTTP (Codex HTTP transport) — 1 site * **handle_passthrough** (OpenAI passthrough endpoints) — 1 site * **batch.py** handlers — 5 sites: - handle_google_batch_create - handle_google_batch_passthrough (Files API forward) - handle_google_batch_passthrough (list/get/cancel) - handle_google_batch_results (CCR-processed) - handle_batch_create (OpenAI batches) All converge on the funnel. Several gain request_id allocation they didn't have before (passthrough sites previously emitted ``request_id=None`` in logs). **Deleted: handle_databricks_invocations + its route + test cases.** Databricks was a 57-line thin wrapper at openai.py that parsed JSON, injected the model from URL into body, and delegated to ``handle_openai_chat``. It enabled ``databricks serving-endpoints query <model> --profile HEADROOM`` direct CLI use. No evidence of active users (no docs, no issues, no mentions). Databricks-hosted models still work via the standard ``/v1/chat/completions`` surface; LiteLLM has its own Databricks support too. If a user complains, this PR is a 30-minute revert. Architectural note: also updated 2 more test dummies (``_DummyOpenAIHandler`` in routing + WS lifecycle tests) to bind ``_record_request_outcome`` via the free function ``emit_request_outcome`` — same pattern as ``_run_compression_in_executor``. Final migration tally (from P0 audit + extensions): * **18 audit sites** + **5 batch.py sites discovered during migration** = 23 sites migrated * **1 site deleted** (Databricks) * **0 sites remaining** anywhere under ``handlers/`` Surface impact (this commit): * openai.py: −168 LOC (315 deletions − 147 insertions) * batch.py: +35 LOC (124 ins − 89 del; mostly comments) * proxy_routes.py: −4 LOC (Databricks route gone) * tests: +11 LOC (dummy `_record_request_outcome` bindings, 2 sites) * Net: ~−126 LOC in production handler code Tests * All 157 existing streaming/cache/Codex/anthropic/openai/backpressure/ routes tests pass with zero regressions. * ruff + ruff-format + mypy clean. This brings the cumulative refactor delta (across all 3 commits on this branch) to: contract introduced (outcome.py + funnel): ~+200 LOC fixed cost handler migrations (streaming + anthropic + gemini + openai + batch + WS): ~−700 LOC Databricks deletion: −57 LOC ────────────────────────────────────────────── ───────── Net production code delta: ~−557 LOC Plus +474 LOC of test coverage (RequestOutcome unit tests + funnel contract assertions). And every handler now emits identical observable outputs per request: same metrics shape, same cost_tracker shape, same RequestLog shape, same PERF format. The wire is uniform. |
||
|
|
03d12fc140 | fix: format Codex compression changes | ||
|
|
e9cae0131b |
fix: expose compression latency bottlenecks
Add Codex WS unit-level timing and bounded parallel compression, clarify context-tool session savings, and avoid costly diff/log fallbacks to Kompress. |
||
|
|
28a0e19deb | Merge origin/main into fix/codex-ws-dashboard-performance | ||
|
|
4279a7f353 | fix: populate Codex WS dashboard performance metrics | ||
|
|
160989c43e | fix(proxy): bound Codex Responses compression work | ||
|
|
62a1f23b88 | fix: log Codex ws cancellations safely | ||
|
|
eaf5980b4a | fix: stabilize codex compression, stats, and proxy lifecycle | ||
|
|
2b331e297a | fix: add Codex wire debug and WS usage metrics | ||
|
|
b71b659e1b |
fix(ci): restore repro harness test in dev installs
Add websockets to the dev extra so the repro harness smoke test can import its websocket client dependency in the CI test matrix. Also apply ruff formatting to the files the formatter check was rejecting so the 3.12 lint job passes. |
||
|
|
a31d81a426 |
feat(proxy): track Codex WS sessions and cancel relay tasks deterministically
Unit 3 of the Codex proxy resilience plan. Eliminates the "aged process
has leaked relay tasks" hypothesis by making every WS session explicitly
tracked and both relay tasks deterministically cancelled when either
exits.
- New headroom/proxy/ws_session_registry.py: dict-backed
WebSocketSessionRegistry + WSSessionHandle with register /
deregister / attach_tasks / snapshot. Deregister is idempotent and
clears relay-task references so coroutine frames are not retained
past session end.
- HeadroomProxy exposes proxy.ws_sessions so /debug/ws-sessions
(Unit 5) can read the live snapshot.
- handle_openai_responses_ws now registers on websocket.accept()
success and deregisters in the outermost finally so no leak can
survive handshake-phase, mid-stream, or upstream-error paths. The
session_id / termination_cause is threaded through both relay
halves and both sides raise asyncio.CancelledError cleanly.
- Replaced asyncio.gather(_client_to_upstream(), _upstream_to_client(),
return_exceptions=True) with explicit asyncio.create_task(...)
(named codex-ws-c2u-<sid> / codex-ws-u2c-<sid>) +
asyncio.wait(FIRST_COMPLETED) + cancel-and-await on the survivor.
Termination cause is classified as client_disconnect /
client_error / upstream_disconnect / upstream_error /
response_completed from which task completed first plus inline
error captures from the halves.
- Prometheus metrics: new active_ws_sessions and active_relay_tasks
gauges plus ws_session_duration_ms_{sum,count,max} histogram
bucketed by termination cause. Mirrors the Unit 2 stage_timing_*
shape.
Preserved: upstream WS retry loop, WS→HTTP fallback, memory-context
timeout, compression pipeline, Unit 2 stage timings. Memory-tool
execution inside _upstream_to_client still runs when the client task
exits first; however, if the client disconnects *before* the upstream
emits response.completed, pending memory writes in `pending_fcs` are
dropped (unchanged from prior behavior — a crashing upstream has the
same effect). Note: handle_openai_responses (HTTP, line ~800) is a
single-shot HTTP request; lifecycle tracking isn't added there
(scope boundary).
Tests:
- tests/test_ws_session_registry.py: 8 registry unit tests
(register/deregister idempotency, snapshot shape, attach merging,
reference release).
- tests/test_openai_codex_ws_lifecycle.py: 6 integration tests
using real relay tasks (only upstream WS endpoint mocked):
happy-path, failing-test-first "client disconnect cancels upstream
relay within 100 ms", upstream-closes-first, upstream-error mid-
stream, handshake-failure deregister, 50 concurrent sessions.
- Regression: test_openai_codex_ws_timings, test_openai_codex_routing,
test_proxy_codex_route_aliases, test_ws_memory_relay all pass.
- Tests pass under python -W error::RuntimeWarning (no "coroutine
was never awaited").
|