mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-04 02:45:54 +08:00
feat/https-compose-caddy
2
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
62b3bedaba |
fix(cache): keep prefix-tracker state across a graceful proxy restart (#4299)
## Description Every proxy restart rewrites the prompt cache of every warm conversation. After a restart the proxy has no `PrefixCacheTracker` for the conversation, so it compresses the whole history afresh, the early messages come out as different bytes than the prefix it forwarded before the restart, and the provider re-writes the cache from the first changed message. Measured on 2026-10-19 on one Mac running Claude Code through the proxy: after each graceful restart (app relaunches for updates: proxy SIGTERM'd and respawned), the next request of every active session read only ~25k cached tokens (tools + system) and re-wrote the rest, up to 247k, 310k, 361k and 432k tokens at a time. The restart-aligned rewrites came to about 4.6M tokens of 1h cache writes that day (2x the input price), about a quarter of all cache writes. A client-side integrity probe reported `kind=tracker_reset, stable_messages=861, first_changed_message=3`. This adds an opt-in `HEADROOM_PREFIX_STATE_FILE=<path>`. When set, the proxy saves the `SessionTrackerStore` on graceful shutdown and restores it at startup, before serving, so the first request after a restart replays byte-identical frozen-prefix bytes. Unset, nothing changes. The file holds conversation content, so it is never a default. Related but different: #4156 (away recap replaces the lineage), #4287 (CCR proactive expansion rewrites), #4204 (deferred tool loads in the lineage key), #4284 (mid-history divergence starts a cold lineage). No existing issue; found while auditing one machine's token usage. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) ## Changes Made - `SessionTrackerStore.save_state` / `load_state` (`headroom/cache/prefix_tracker.py`). Per tracker: turn number, cached token and message counts, last original and last forwarded messages, the per-turn states that lineage resolution resumes, provider, last activity and observed cache TTL; per lineage: session id, cache affinity and the recent snapshot history. So `resolve_tracker` matches the next request to the restored tracker, forks included. Each distinct message is stored once per tracker (successive turns, snapshots and the original/forwarded pairs mostly repeat), and new lineage keys and turn ids continue past the restored ones. - CCR entries ride along (review: retrieval integrity). Per tracker, `save_state` collects every CCR reference in its saved messages and read-maturation state (`hash=<hex>` markers and SmartCrusher's `<<ccr:<hex>`) and writes the live `CompressionStore` entries behind them (new `CompressionStore.export_entries`, which reads without counting a retrieval). A tracker and its entries count against the size cap together, so a tracker is never saved without them. `load_state` re-stores them (`import_entries`) with their original expiry, before any tracker is installed, so a replayed marker resolves from the first request even with `HEADROOM_CCR_BACKEND=memory`. An entry a persistent backend still holds is left as it is; a malformed one rejects the file. - Restore keeps only trackers still inside the store's own retention (last activity plus the observed or configured cache TTL and its cleanup margin, at least the session TTL), the same rule the live store uses. NaN or future timestamps are dropped. - Versioned schema (`version: 1`). Any read, parse or validation error logs one warning and leaves the store empty; the whole file is validated before anything is installed. The file is written atomically (`headroom.fsutil.write_text`: temp file, fsync, rename) at mode 0600: an existing file is tightened to 0600 in place, never unlinked first, so a failed write (ENOSPC) keeps the previous snapshot. Deleted after a successful load. Stateless mode (`persistence_allowed`) neither writes nor reads it (a stateless start used to load, and so delete, a snapshot). Ignored with multiple workers (one file cannot hold N per-process stores). - Size cap: the 256 most recently active trackers and at most 64 MB, newest first; whatever does not fit starts cold, as everything did before. - `HeadroomProxy.startup()` loads, `HeadroomProxy.shutdown()` saves as its first step, before any await, so the shutdown step timeout cannot cut it short. No periodic writes. - Token-mode `CompressionCache` seed: a restored tracker has no `CompressionCache` behind it in the new process, so the freeze computed from that cache froze nothing: the pipeline recompressed messages the provider cached, read maturation rewrote Reads inside the cached prefix, and beyond the provider-confirmed floor the overlay declined a larger previous form. One shared `seed_restored_compression_cache` seeds the session's cache from the restored original/forwarded pair (`update_from_result`) on the first request, on all three token-mode paths: Anthropic `/v1/messages`, OpenAI `/v1/chat/completions`, and the session-aware `/v1/compress` (sidecar). It gives the same freeze count as before the restart. - `ReadMaturationManager.export_state` / `validate_state` / `restore_state`: matured markers, booked ids and replay token deltas ride along with the tracker, so a matured Read's removal is not booked as savings again on every request after a restart. The saved state is validated at load with the rest of the file, so a bad entry rejects the file instead of failing a request. - `tests/test_anthropic_fork_lineage_cache.py`: `_drive` accepts a shared provider-cache model and config overrides, so a second call is a proxy restart in front of a warm provider cache. - Documented the variable in `docs/content/docs/configuration.mdx`. - `pyproject.toml` / `uv.lock` (review: Dependency audit): the `aiohttp` constraint floor is now `>=3.14.4` (CVE-2026-111063, CVE-2026-111064 and GHSA-2g87-pp6c-29x5, all fixed in 3.14.4), relocked with `uv lock --upgrade-package aiohttp==3.14.4`. Only aiohttp (3.14.3 -> 3.14.4) and yarl (1.22.0 -> 1.25.1, which 3.14.4 requires) move. Main still resolves 3.14.3, so the same commit is on #4299, #4286, #4285 and #4269. Remaining gaps (unchanged by this PR, none of them changes forwarded message bytes): - Session-sticky `anthropic-beta` union (`HEADROOM_BETA_HEADER_STICKY`): in memory, so after a restart a session's sticky set starts from the client's own header again. Headers only. - Output shaper: stateless per request (byte-stable steering text, effort from the current request's structure), so nothing to persist. - Gemini and Bedrock paths resume the restored tracker and its overlay replay; they keep no token-mode `CompressionCache`, so there is nothing to seed. A crash or SIGKILL still loses everything, by design (no periodic writes). ## 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 # New regression tests for the review findings, run against the |
||
|
|
1cf4d053d2 |
fix(cache): stop Claude Code forks from cold-starting the conversation's lineage (#4043)
### Maintainer qualification refresh (2026-10-09) Current head: `a91a1ec24ab20b6dcea0f6e7f8d41feb7d0beea0`. The newly supplied live Claude Code/Anthropic before-after evidence resolves the previous runtime-proof hold. Clean synchronization with current main `01d9194` preserves contributor logic. Independently reran all 88 fork-lineage/prefix tests with the existing native extension; current-head hosted checks are green. Approved for human merge review. The live capture below remains correctly attributed to the preceding implementation head, not represented as a new capture of this synchronization commit. No merge performed. ## Description Claude Code sends side requests alongside an agent's turns. The subagent progress summary and the parent session's side query both re-send the history plus one prompt, with the breakpoint one message earlier, so they read the prompt cache without writing it. resolve_tracker matched such a fork as a continuation and replaced the lineage snapshot with it. The next real turn extends the history before the fork, not the fork, so it matched no lineage. It started a cold tracker (frozen=0), and the token-mode pipeline rewrote history the provider had already cached. Production, 2026-10-08: a review subagent busted Anthropic's cache on 35 of 81 turns. cache_read_input_tokens fell to the 6,065-token system prompt while 100-150k tokens were re-written. Its 600k-token parent did the same after its own side queries. In the proxy log, every bust is the first main request after a fork and shows no frozen prefix. Fork-free sessions on the same proxy were 96/96 and 130/130 full hits. A lineage now keeps its last three request snapshots. A request that extends an earlier one resumes that turn instead of starting cold. Each response is also recorded against the turn that sent it, through a request-scoped ContextVar (the same pattern as the tenant key and CCR store). A fork's response can no longer replace the main line's frozen prefix or overlay source, whether it lands before or after the in-flight main turn's response. Templated fan-out siblings that extend a shared earlier snapshot now stay on one tracker and each resumes its own turn's state. Splitting them would mint a new lineage per fork and exhaust the per-session cap. The fan-out test asserts the per-line state instead of object identity. ## 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/cache/prefix_tracker.py`: each lineage keeps a `deque(maxlen=_LINEAGE_HISTORY)` (3) of request snapshots instead of one. `resolve_tracker` resumes the turn a request extends, and the turn it resolved is held in a request-scoped `ContextVar` (`_resolved_turn`) so the response is recorded against that turn. - `tests/test_anthropic_fork_lineage_cache.py` (new): handler-level regression. A main turn after a fork (progress summary or side query) must replay its cached prefix byte for byte, and a fork must not replace the lineage it branched from, whichever response lands first. - `tests/test_cache/test_prefix_tracker.py`: the fan-out test asserts per-line state instead of tracker object identity. ## Testing - [x] Unit tests pass (`pytest tests/test_anthropic_fork_lineage_cache.py tests/test_cache/ tests/test_proxy_anthropic_cache_stability.py`: 272 passed, with `test_cache/test_dynamic_detector.py` run on its own: 57 passed, 2 skipped) - [x] Linting passes (`ruff check` on the changed files) - [x] Type checking passes for the changed module (`mypy headroom/cache/prefix_tracker.py`: no issues) - [x] New tests added for new functionality - [ ] Manual testing performed ### Test Output ```text # new test file, without the fix (parent commit) FAILED tests/test_anthropic_fork_lineage_cache.py::test_main_turn_after_a_fork_replays_its_cached_prefix[summary] FAILED tests/test_anthropic_fork_lineage_cache.py::test_main_turn_after_a_fork_replays_its_cached_prefix[side-query] FAILED tests/test_anthropic_fork_lineage_cache.py::test_fork_does_not_replace_the_lineage_it_branched_from[fork-first] FAILED tests/test_anthropic_fork_lineage_cache.py::test_fork_does_not_replace_the_lineage_it_branched_from[main-first] AssertionError: main turn 2 re-sent turn 1's history with different bytes ============================== 4 failed ============================== # with the fix ============================== 4 passed ============================== ``` ## Real Behavior Proof - Environment: Windows 11, Python 3.13.16, real Claude Code 2.1.295 sessions against the Anthropic API through `headroom proxy --mode token` (details below). - Exact command / steps: the scripted Claude Code session described below, run once on `17abee27` (before) and once on `9b27664a` (after). - Observed result: main turns right after a fork arrived with a cold tracker 5/5 before, 0/5 after; cached tokens lost 3,363 before, 0 after. - Not tested: the full collapse to the system prompt seen in production fork-heavy sessions (did not reproduce in this short session); a deployed proxy running this fix. Live before/after capture on 2026-10-09. Real Claude Code 2.1.295 sessions against the Anthropic API (subscription login, `claude-sonnet-5-5`), through `headroom proxy --mode token` on Windows 11 / Python 3.13.16, with the native extension built in each tree. - **Before:** `17abee27` (merge base with `main`) - **After:** `9b27664a` (this PR) Both ran the same scripted session: a stream-json SDK client with `agentProgressSummaries` and `promptSuggestions` on, one general-purpose subagent that `cat`s ten ~40 KB JSON files one tool call at a time, then three parent follow-up turns. Each request's kind comes from Claude Code's own debug log (`[API REQUEST] source=…`). `sdk` and `agent:*` are main turns; `agent_summary` and `prompt_suggestion` are forks. Token counts are the upstream `usage` values from the proxy's PERF lines. | Main turns right after a fork | Before | After | |---|---|---| | Count | 5 | 5 | | Arrived with a cold tracker (no `Pipeline: freezing` line) | **5/5** | **0/5** | | Read the full prior prefix | 4/5 | **5/5** | | Cached tokens lost | 3,363 | 0 | - **Before**, subagent turn #15 (after its 23-message `agent_summary` fork): cold, `cache_read` 22,137 against the 25,500 cached by the previous turn, `cache_creation` 4,902. - **After**, the matching subagent turn #17 (after a 21-message `agent_summary` fork): frozen 20/23, `cache_read` 25,311 = 24,192 + 1,119, exactly the previous turn's read + write. This short session did not reproduce the full collapse to the system prompt (~6k read) seen in production fork-heavy sessions. In most cold turns the pipeline happened to regenerate identical bytes. The capture does show the mechanism deterministically: before, every fork leaves the next main turn of that conversation starting cold, and one of those cold turns rewrote 3.4k cached tokens. After, none start cold and every post-fork turn reads its whole prior prefix. <details><summary>Per-request tables (before / after)</summary> **Before (`17abee27`)** | # | kind | msgs | frozen | cache_read_input_tokens | cache_creation_input_tokens | |---|---|---|---|---|---| | 1 | main (parent) | 2 | - | 0 | 15,072 | | 2 | main (subagent) | 2 | - | 5,406 | 7,859 | | 3 | main (subagent) | 5 | 3 | 13,265 | 660 | | 4 | main (subagent) | 7 | 3 | 13,925 | 1,176 | | 5 | main (subagent) | 9 | 3 | 15,101 | 1,319 | | 6 | main (subagent) | 11 | 3 | 16,420 | 1,138 | | 7 | fork (agent_summary) | 11 | 3 | 16,476 | 0 | | 8 | main (subagent) <- after fork | 13 | - | 17,558 | 1,127 | | 9 | main (subagent) | 15 | 3 | 18,685 | 1,134 | | 10 | main (subagent) | 17 | 3 | 19,819 | 1,126 | | 11 | main (subagent) | 19 | 3 | 20,945 | 1,136 | | 12 | main (subagent) | 21 | 3 | 22,081 | 1,133 | | 13 | main (subagent) | 23 | 3 | 23,214 | 2,286 | | 14 | fork (agent_summary) | 23 | 22 | 23,321 | 0 | | 15 | main (subagent) <- after fork | 25 | - | 22,137 | 4,902 | | 16 | main (subagent) | 27 | 24 | 27,039 | 1,260 | | 17 | main (subagent) | 29 | 24 | 28,299 | 7,523 | | 18 | main (parent) | 4 | 3 | 15,072 | 2,204 | | 19 | fork (prompt_suggestion) | 6 | 5 | 17,276 | 335 | | 20 | main (parent) <- after fork | 6 | - | 17,611 | 31 | | 21 | fork (prompt_suggestion) | 8 | 7 | 17,642 | 362 | | 22 | main (parent) <- after fork | 8 | - | 18,004 | 29 | | 23 | main (parent) | 10 | 9 | 18,033 | 242 | | 24 | fork (prompt_suggestion) | 12 | 9 | 18,275 | 128 | | 25 | main (parent) <- after fork | 12 | - | 18,403 | 18 | | 26 | fork (prompt_suggestion) | 14 | 9 | 18,421 | 142 | **After (`9b27664a`)** | # | kind | msgs | frozen | cache_read_input_tokens | cache_creation_input_tokens | |---|---|---|---|---|---| | 1 | main (parent) | 2 | - | 5,406 | 9,666 | | 2 | main (subagent) | 2 | - | 10,523 | 2,742 | | 3 | main (parent) | 4 | 3 | 15,072 | 692 | | 4 | main (subagent) | 5 | 3 | 13,265 | 1,681 | | 5 | fork (prompt_suggestion) | 6 | 3 | 15,764 | 25 | | 6 | main (subagent) | 7 | 3 | 14,946 | 1,246 | | 7 | main (subagent) | 9 | 3 | 16,192 | 1,138 | | 8 | main (subagent) | 11 | 3 | 17,330 | 2,303 | | 9 | main (subagent) | 13 | 3 | 19,633 | 1,167 | | 10 | main (subagent) | 15 | 3 | 20,800 | 1,137 | | 11 | main (subagent) | 17 | 3 | 21,937 | 1,129 | | 12 | main (subagent) | 19 | 3 | 23,066 | 1,126 | | 13 | main (subagent) | 21 | 20 | 24,192 | 1,119 | | 14 | main (parent) <- after fork | 6 | 3 | 15,789 | 31 | | 15 | fork (prompt_suggestion) | 8 | 3 | 15,820 | 108 | | 16 | fork (agent_summary) | 21 | 20 | 24,248 | 0 | | 17 | main (subagent) <- after fork | 23 | 20 | 25,311 | 710 | | 18 | main (parent) <- after fork | 8 | 3 | 15,928 | 851 | | 19 | fork (prompt_suggestion) | 10 | 3 | 16,779 | 688 | | 20 | main (parent) <- after fork | 10 | 3 | 17,467 | 29 | | 21 | main (parent) | 12 | 3 | 17,496 | 130 | | 22 | main (parent) | 14 | 3 | 17,626 | 249 | | 23 | fork (prompt_suggestion) | 16 | 3 | 17,875 | 131 | | 24 | main (parent) <- after fork | 16 | 3 | 18,006 | 18 | | 25 | fork (prompt_suggestion) | 18 | 3 | 18,024 | 136 | </details> ## Runtime Rollout Safety - Rollout-managed feature(s): none - Minimum rollout channel: n/a - Stable/default behavior changed: yes, prefix-tracker lineage matching for requests that extend an earlier snapshot of the same lineage - Kill switch / disable path: none - Unsafe override required: no - Qualification impact: none expected - Rollback path: revert this commit ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] 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) ## Additional Notes Not covered here: a few small partial misses in production that forks don't explain, and a synthetic-only risk that an older tool result gets recompressed once it falls past a lagging frozen boundary. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4043" 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: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: JerrettDavis <mxjerrett@gmail.com> |