Repository navigation
fix(proxy): bound the model-keyed tokenizer, beacon and litellm caches - #4497
JerrettDavis merged 8 commits into
Conversation
TokenizerRegistry._cache, the beacon's _public_model cache and resolve_litellm_model's cache are keyed by the request's model string and never evicted, so a client sending a new name per request grew each one without limit. Cap each at a fixed entry count (64 tokenizers, 256 for the two name caches) with least-recently-used eviction through a small shared helper, headroom.utils.remember_bounded. A model in steady use is never evicted; an evicted one is recomputed on its next use. Keys are not clipped, so two distinct model names can never share an entry. Fixes headroomlabs-ai#4479
PR governanceThis PR follows the template and is marked ready for human review. |
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
JerrettDavis
left a comment
There was a problem hiding this comment.
Reviewed 8dbc133 after cleanly syncing main f10725e. The bounded cache helper and the three cache call sites preserve model keys and results, and the tests exercise eviction, recency, cached None, and the estimation fallback. 107 focused tests passed with the existing native extension; 14 optional tests skipped. I found no additional code-level blocker.
Approval remains held by shared dependency failures verified on this exact head: pip-audit job 122580840258 reports litellm 1.101.0 / CVE-2026-114612 (fixed in 1.101.3 among other release lines), and npm audit job 122580839798 reports unexcepted bundled undici 6.29.0 advisories GHSA-2m5v-pch6-74hx, GHSA-qrxm-fqhp-jwvm, and GHSA-9fm3-97px-rjf6 in e2e/wrap/tools. Maintainers need to land and carry the shared dependency remediation before green qualification. These are inherited gates outside the cache change; no contributor CI action is requested.
|
Thanks for the thorough review, @JerrettDavis. Understood that the remaining hold is the shared pip-audit (litellm CVE-2026-114612) and npm audit (bundled undici in e2e/wrap/tools) gates on main. This PR does not touch any dependency manifests, so I will leave those to the maintainer remediation and rebase onto main once it lands so the audit jobs can re-run on a green base. |
JerrettDavis
left a comment
There was a problem hiding this comment.
Re-reviewed 8ad6d56 with main 31dcaf4 included. The shared recency helper bounds the tokenizer cache at 64 entries and beacon/pricing caches at 256 without truncating model keys, changing cached None behavior, or preventing recomputation after eviction. The combined focused suites passed 116 tests with 14 optional skips; lint, formatting and whitespace checks passed. I reviewed the real rotating-2,000-model-name evidence and refreshed the discussion. Required CI and the full current rollup are green; the former inherited dependency gate is cleared. No remaining blocker found.
|
@JerrettDavis thanks for re-reviewing 8ad6d56 and for checking the rotating-model-name evidence and the cleared dependency gate. Much appreciated. |
a29cc2d to
bf0037d
Compare
JerrettDavis
left a comment
There was a problem hiding this comment.
Re-reviewed the combined tree against upstream/main e4a60ed, including the tokenizer-registry overlap. Model-specific factory dispatch and main's failed-factory fallback-cache rule are preserved alongside the bounded recency writes. Full model keys, cached None and recomputation after eviction remain intact. 111 focused cache/tokenizer/encoding tests passed with 14 optional skips, plus adjacent load-timeout, telemetry and pricing suites and ten shared Gemini cases; Ruff lint/format and whitespace are clean. Existing in-process rotating-model runtime evidence remains scoped. Exact-head hosted CI and applicable checks are green; current main is included and no remaining blocker was found.
|
Thanks for the approval, @JerrettDavis, and for re-checking the combined tree against current main, including the tokenizer-registry overlap. |
🤖 I have created a release *beep* *boop* --- ## [0.43.1](v0.43.0...v0.43.1) (2026-11-05) ### Bug Fixes * **ccr:** keep the in-memory order queue from evicting re-stored entries ([#4545](#4545)) ([c6f5bf9](c6f5bf9)) * **memory:** read the relation key the memory_save schema advertises ([#4647](#4647)) ([7592e68](7592e68)) * **memory:** replace the HNSW vector when a memory is re-indexed ([#4649](#4649)) ([ee638f9](ee638f9)) * **openclaw:** accept 12-character hashes in headroom_retrieve ([#4640](#4640)) ([8d3e9e5](8d3e9e5)) * **ort:** avoid implicit runtime discovery from the workspace ([#4570](#4570)) ([69fbd23](69fbd23)) * **proxy:** bound the model-keyed tokenizer, beacon and litellm caches ([#4497](#4497)) ([e51b806](e51b806)) * **proxy:** use HTTP/1.1 client for ChatGPT streaming and model metadata ([#4006](#4006)) ([e1becdf](e1becdf)) * **release:** normalize damaged release PR envelopes before detection ([#4664](#4664)) ([917edc6](917edc6)) * **router:** keep tagged blocks out of the lossy size-gate fallback ([#4543](#4543)) ([f333edf](f333edf)) * **router:** log the ONNX fallbacks at info instead of warning ([#4535](#4535)) ([db30d82](db30d82)) ### Dependencies * bump the npm-minor-patch group across 3 directories with 6 updates ([#4662](#4662)) ([8f104f8](8f104f8)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --------- Co-authored-by: headroom-release[bot] <352661243+headroom-release[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
- fix(deps): patch OpenClaw Undici and narrow E2E audit exceptions (headroomlabs-ai#4453) - feat(ccr): Redis backend, one CCR store for every replica (headroomlabs-ai#4368) - fix(cache): bound the router's compression cache, keep the rest in SQLite (headroomlabs-ai#4357) - feat(compress): share /v1/compress sessions across replicas via Redis (headroomlabs-ai#4369) - fix(proxy): keep in-period costs in the budget ledger when the entry cap is reached (headroomlabs-ai#4448) - fix(proxy): import Response at runtime in the Bedrock handler (headroomlabs-ai#4397) - fix(tabular): pass tables with repeated header names through verbatim (headroomlabs-ai#4278) - fix(smart-crusher): match audit-safe protected_patterns against unescaped text (headroomlabs-ai#4294) - fix(copilot): detect COPILOT_API_URL in cli-main.js for Copilot CLI >= 1.0.93 (headroomlabs-ai#4450) - fix(proxy): do not rebuild a failed turn-hook re-drive as HTTP 200 (headroomlabs-ai#4398) - fix(transforms): keep the fences of a code block passed through for a protected tag (headroomlabs-ai#4292) - fix(cache): keep indented lines intact in OpenAI whitespace normalization (headroomlabs-ai#4343) - fix(gemini): keep snake_case inline_data and function parts when compressing (headroomlabs-ai#4290) - fix(proxy): record outcome when a passthrough stream ends mid-character (headroomlabs-ai#4429) - fix(image): flatten transparent images onto white before re-encoding as JPEG (headroomlabs-ai#4296) - fix(proxy): honor bypass header and license gate in Anthropic batch create (headroomlabs-ai#4411) - fix(install): keep the HuggingFace cache on a writable mount in Docker presets (headroomlabs-ai#4207) (headroomlabs-ai#4209) - fix(opencode): do not rewrite an OpenCode config that fails to parse (headroomlabs-ai#4424) - fix(openai): recompress cached Responses units whose CCR entries expired (headroomlabs-ai#4146) - fix(kompress): never drop words the model did not see (headroomlabs-ai#4175) - fix(proxy): bound per-model state keyed by the client model string (headroomlabs-ai#4407) - fix(copilot): preserve native inline OAuth identity (headroomlabs-ai#4144) - fix(proxy): drop web_search_call history from a Responses request with no web_search tool (headroomlabs-ai#4202) - fix(security): restrict the Windows runtime log via NTFS ACL, not just warn (headroomlabs-ai#4135) - fix(sdk): preserve Vercel AI SDK file and image parts through compression (headroomlabs-ai#4048) - fix(ci): pin checkout in release notification smoke workflow (headroomlabs-ai#4399) - docs(troubleshooting): explain the frozen ghcr.io/chopratejas/headroom image (headroomlabs-ai#4069) - fix(proxy): count output tokens from CRLF-framed SSE streams too (headroomlabs-ai#4298) - fix(telemetry): give empty-item compressions a stable tool signature (headroomlabs-ai#4396) - fix(proxy): keep tool deferral for GitHub Copilot upstream (headroomlabs-ai#4356) - fix(savings): key a Responses conversation on its thread, not the shared session (headroomlabs-ai#4440) - fix(storage): normalize timezone-aware JSONL time filters (headroomlabs-ai#4063) - fix(gateway): keep input_includes_cache when re-drive usage is merged (headroomlabs-ai#4423) - fix(proxy): copy cached tool compaction results (hardening) (headroomlabs-ai#4410) - fix(image): clear last_result before each compress() call (headroomlabs-ai#4341) - fix(memory): resolve partial IDs beyond the first 1000 records (headroomlabs-ai#4389) - fix(memory): ignore incidental cwd prose (headroomlabs-ai#4166) - fix(mcp): accept the JSONC opencode config that wrap and install already accept (headroomlabs-ai#4297) - fix(proxy): accept HEADROOM_MEMORY_INJECTION_MODE=tool (headroomlabs-ai#4395) - fix(memory): treat a cwd with no UTF-8 form as unresolved instead of raising (headroomlabs-ai#4167) - fix(opencode): restore process env keys on transport dispose (headroomlabs-ai#4430) - docs: drop effort-routing text that headroomlabs-ai#3377 removed (headroomlabs-ai#4449) - fix(transforms): pass HeadroomConfig.smart_crusher to the default pipeline's router (headroomlabs-ai#4243) - fix(proxy): skip memory tool injection on streamed OpenAI requests (headroomlabs-ai#4451) - fix(learn): anchor the managed block on its last start marker, append when no end marker (headroomlabs-ai#4342) - fix(proxy): keep negative compression savings across restart (headroomlabs-ai#4406) - fix(ccr): recognize client-owned MCP retrieval aliases (headroomlabs-ai#4165) - fix(logs): count omitted levels from dropped lines (headroomlabs-ai#4141) - fix(zcode): skip providers that point at the Headroom proxy itself (headroomlabs-ai#4413) - fix(memory): bound retrieval queries before embedding (headroomlabs-ai#4244) - fix(offline): keep litellm's pricing table local under HEADROOM_OFFLINE (headroomlabs-ai#4242) - feat(proxy): report the same tool savings on gateway /v1/compress as the proxy path (headroomlabs-ai#4467) - chore: release 0.42.0 (headroomlabs-ai#4228) - deps: Bump the npm-minor-patch group across 3 directories with 9 updates (headroomlabs-ai#4495) - deps: Bump the npm-minor-patch group across 2 directories with 14 updates (headroomlabs-ai#4455) - deps: require Python 3.11; clear Dependabot alerts in the 3.10 lock fork (headroomlabs-ai#4517) - docs(teams): replace the 3-months-free perk with a talk-to-us pitch (headroomlabs-ai#4524) - fix(docker): install the redis extra in every image (headroomlabs-ai#4514) - fix(packaging): rename the sandbox extra to lean and correct SECURITY.md claims (headroomlabs-ai#3727) - fix(openclaw/release): ship responsive npm integrations (headroomlabs-ai#1458) - fix(memory): fail close unresolved project operations (headroomlabs-ai#2637) - fix(proxy): install SOCKS support for websocket proxies (headroomlabs-ai#3357) - fix(pricing): add Claude Haiku 5.5 rates, 1M context and its 100K long-prompt card (headroomlabs-ai#4037) - fix(proxy): keep deferred tool loads out of the prefix-tracker lineage key (headroomlabs-ai#4204) - fix(transforms): stop an embedded markdown table from dropping the rest of a tool result (headroomlabs-ai#4216) - fix(client): store metrics at HeadroomConfig.store_url (headroomlabs-ai#4270) - fix(install): write persistent shell env values verbatim (headroomlabs-ai#4289) - fix: do not report a seeded stored setting as an env override (headroomlabs-ai#4326) - fix(cache): invalidate configured registry instances on replacement (headroomlabs-ai#4363) - fix(cache): validate malformed learned TTL values (headroomlabs-ai#4364) - fix(memory): bound history traversal on cyclic supersession links (headroomlabs-ai#4366) - fix(memory): skip the edit-distance retry check on long commands (headroomlabs-ai#4371) - fix(memory): match compound and null SQLite metadata filters (headroomlabs-ai#4373) - fix(proxy): log unknown model ids as one bounded token; skip unparseable PERF lines (headroomlabs-ai#4374) - fix(memory): preserve relationships when updating graph entities (headroomlabs-ai#4379) - chore(sdk-typescript): npm metadata and the proxy requirement up front (headroomlabs-ai#4536) - fix(proxy): recognise every local spelling of the proxy in the cc-switch loop guard (headroomlabs-ai#4405) - fix(proxy): do not book Gemini countTokens as a request outcome (headroomlabs-ai#4412) - fix(router): keep small shell results verbatim (headroomlabs-ai#3590) (headroomlabs-ai#4426) - fix(codex): accept multi-line inline tables in Codex config.toml (headroomlabs-ai#4436) - fix(proxy): preserve response cache keys across in-place hooks (headroomlabs-ai#4457) - fix(transforms): tolerate malformed assistant tool calls in ContentRouter.apply (headroomlabs-ai#4459) - fix(read-lifecycle): keep Reads fresh after a failed Edit or Write (headroomlabs-ai#4461) - fix(mixed-content): do not carve ISO-timestamped log rows as search results (headroomlabs-ai#4463) - fix(install): tolerate absent Windows tasks in stop_supervisor (headroomlabs-ai#4465) (headroomlabs-ai#4468) - fix(tokenizers): don't cache token-count inputs larger than max_chars (headroomlabs-ai#4469) - fix(compaction): reject negative dictionary indices and non-array legends in expand_compacted (headroomlabs-ai#4470) - fix(tokenizers): coerce structured text values in message token counters (headroomlabs-ai#4472) - docs: clarify Target savings metric is % of new input tokens (headroomlabs-ai#4485) - fix(toin): skip a malformed pattern instead of aborting the store load (headroomlabs-ai#4484) - fix(client): close upstream responses when wrapped streams are closed (headroomlabs-ai#4482) - fix(cache): namespace SemanticCacheLayer by provider, model and metadata (headroomlabs-ai#4473) - fix(router): validate lossless provider output on the excluded-tool path (headroomlabs-ai#4486) - fix(dedup): bound line-number digit run and never fold into a longer pointer (headroomlabs-ai#4488) - fix(sdk): send Anthropic messages to /v1/compress natively so thinking blocks survive (headroomlabs-ai#4489) - fix(doctor): detect root openai_base_url Codex routing and agent-configured proxy ports (headroomlabs-ai#4490) - fix(proxy): cap cache_control breakpoints on OpenAI chat path (headroomlabs-ai#4471) (headroomlabs-ai#4491) - fix(cache): count a tool_result with no text as replayable in the frozen prefix (headroomlabs-ai#4523) - fix(proxy): keep read maturation out of the provider-confirmed prefix (headroomlabs-ai#4522) - fix(relevance): cap embedding batch size so ORT's arena stays small (headroomlabs-ai#4507) - fix(transforms): honour Subscription toin_read_only when the router calls SmartCrusher (headroomlabs-ai#4493) - fix(transforms): enforce role, mutable, and cache zone guards in batch compression (headroomlabs-ai#4480) (headroomlabs-ai#4494) - fix(transforms): preserve YAML block scalar data during comment elision (headroomlabs-ai#4498) - fix(memory): compare SQLite timestamps as UTC instants (headroomlabs-ai#4499) - fix(client): preserve Anthropic create stream flags (headroomlabs-ai#4500) - fix(client): honor configured cache optimizer enablement (headroomlabs-ai#4501) - fix(proxy): don't fail startup when libc_ver() can't read the interpreter (headroomlabs-ai#4519) - fix(security): lstat before narrowing sqlite files (headroomlabs-ai#4527) - docs(site): Python-first quickstart and a FastAPI page built on compress() (headroomlabs-ai#4529) - fix(cache): preserve OpenAI tool block metadata on cached replay (headroomlabs-ai#4334) - fix(evals): reject changed numeric probe values (headroomlabs-ai#4502) - fix(tokenizers): price Anthropic document blocks by page count, not as base64 text (headroomlabs-ai#4441) - fix(deps): clear the glob and minimatch npm audit findings (headroomlabs-ai#4599) - test(proxy): make compression timeout regression deterministic (headroomlabs-ai#4587) - deps: bump ruff from 0.17.0 to 0.17.2 in the pip-minor-patch group across 1 directory (headroomlabs-ai#4380) - ci: Bump actions/setup-python from 6 to 7 (headroomlabs-ai#4558) - fix(mcp): confine headroom_read to the workspace (GHSA-8g49-pg6g-xgrf) (headroomlabs-ai#4525) - ci: Bump the actions-minor-patch group with 2 updates (headroomlabs-ai#4557) - deps: Bump the npm-minor-patch group across 1 directory with 6 updates (headroomlabs-ai#4621) - chore(deps): bump the uv group across 1 directory with 2 updates (headroomlabs-ai#4537) - deps: Bump @anthropic-ai/sdk from 0.133.0 to 1.3.0 in /sdk/typescript (headroomlabs-ai#4554) - fix(proxy): keep tool deferral on Copilot Business/Enterprise/Individual hosts (headroomlabs-ai#4608) - fix(deps): bump mem0ai, langgraph and langgraph-sdk past open advisories (headroomlabs-ai#4614) - deps: Bump the cargo-minor-patch group across 1 directory with 12 updates (headroomlabs-ai#4553) - deps: Bump tsup from 8.5.1 to 9.0.0 in /sdk/typescript (headroomlabs-ai#4386) - deps: Bump tsup from 8.5.1 to 9.0.0 in /plugins/opencode (headroomlabs-ai#4385) - deps: Bump lru from 0.18.5 to 0.19.0 (headroomlabs-ai#4382) - fix(cli): document that code-aware compression is enabled by default (headroomlabs-ai#4616) - fix(proxy): keep health probes and the Codex attestation out of the proxy log (headroomlabs-ai#4611) - fix(privacy): turn off ONNX Runtime's Microsoft telemetry by default (headroomlabs-ai#4602) - test(deps): fail when a composite extra's uv.lock list drops a nested extra's package (headroomlabs-ai#4598) - deps: qualify latest Anthropic SDK 1.4.0 in docs (headroomlabs-ai#4556) - fix(router): preserve read protection for quiet sed options (headroomlabs-ai#4521) - fix(wrap): overwrite drifted selfheal hook command instead of skipping it (headroomlabs-ai#2723) - fix(langgraph): replace the compressed ToolMessage in graph state (headroomlabs-ai#4620) - test(wrap): isolate two auth-precedence tests from the caller's ANTHROPIC_* env (headroomlabs-ai#4601) - fix(privacy): turn off Mem0's PostHog telemetry by default (headroomlabs-ai#4619) - fix(relevance): hand the embedding arena back after each run on macOS (headroomlabs-ai#4567) - fix(codec): reject densified blocks with mismatched row counts (headroomlabs-ai#4271) - fix(proxy): skip the memory-context search in cache mode (headroomlabs-ai#4606) - fix(pipeline): store the pipeline input in CCR behind offload markers (headroomlabs-ai#4576) - fix(backends/litellm): keep cache_control on text blocks for Bedrock prompt caching (headroomlabs-ai#4565) - fix(relevance): load the Rust default embedder from Python's pinned snapshot (headroomlabs-ai#4190) - fix(smart-crusher): preserve unchanged JSON bytes (headroomlabs-ai#4044) - fix(scripts): resolve hooks dir via git so install-git-hooks works in linked worktrees (headroomlabs-ai#4176) - fix(proxy/memory): harden _extract_tool_calls against malformed choices and blocks (headroomlabs-ai#2483) - fix: Add info about apply to README.md (headroomlabs-ai#1592) - Fix(proxy) vertex model override propagation (headroomlabs-ai#2367) - fix(backends): forward the standard service_tier param (litellm + anyllm) (headroomlabs-ai#2468) - fix(wrap): route OMP OpenAI providers through Headroom (headroomlabs-ai#2755) - fix(proxy): warm deferred kompress model so /health stops reporting backend=null (headroomlabs-ai#2799) - ci: run eval smoke test on Rust compressor changes (headroomlabs-ai#2948) - fix(proxy): handle ClientDisconnect in anthropic_messages (headroomlabs-ai#3532) - fix(output-savings): rewrite a pre-rule ledger once instead of warning on every /stats poll (headroomlabs-ai#4196) - fix(openclaw): record turn advancements as one marker file per key (headroomlabs-ai#4212) - fix(ccr): keep proactive expansion out of the cached prefix (headroomlabs-ai#4300) - fix(proxy): route /v1/models to the x-headroom-base-url upstream (headroomlabs-ai#4308) - fix(docker): pass RUNTIME_HOME=/root for root bake targets (headroomlabs-ai#4445) - docs: fix generate_report example arguments (headroomlabs-ai#4435) - fix(proxy): forward Copilot accounting headers on streaming path (headroomlabs-ai#4431) - fix(memory): bound verb-pattern word runs to stop quadratic backtracking in bridge import (headroomlabs-ai#4370) (headroomlabs-ai#4376) - fix(cache): fail closed on SQLite corruption instead of deleting the store online (headroomlabs-ai#4361) - fix(proxy): reconcile Chat content-block cache markers after prefix replay (headroomlabs-ai#4333) - fix(diff): keep combined-diff changes made against a later parent (headroomlabs-ai#4318) - fix(opencode): only route POST requests to LLM endpoint paths (headroomlabs-ai#4464) - fix: [BUG] A timeout in one image compression call resets the shared worker pool and affects concurrent requests (headroomlabs-ai#4528) - docs(readme): lead with two front doors and one measured savings claim (headroomlabs-ai#4530) - docs(llms): add a by-task section and state the measured savings claim once (headroomlabs-ai#4531) - docs: add AGENTS.md for agents using Headroom and agents changing the repo (headroomlabs-ai#4532) - docs(pypi): job-word summary and keywords, and a PyPI-specific README (headroomlabs-ai#4534) - deps: qualify latest compatible docs and E2E tools (headroomlabs-ai#4580) - fix(proxy): preserve retrieval outputs across Codex WS deltas (headroomlabs-ai#4574) - fix(sdk): carry Vercel AI SDK reasoning parts and provider options through compression (headroomlabs-ai#4564) - feat(savings): show the proxy's model-routing savings in headroom savings (headroomlabs-ai#4304) - feat(plugins): headroom skill for Claude Code, Codex, Copilot and skills.sh (headroomlabs-ai#4533) - fix(providers): isolate resolved Anthropic context limits (headroomlabs-ai#4593) - fix(proxy): honor x-headroom-base-url on provider passthrough routes (headroomlabs-ai#4596) - fix(packaging): use direct CLI module entry point (headroomlabs-ai#2665) - test(onnx): fix magika idle-thread test on macOS with ORT 1.31 (headroomlabs-ai#4194) - fix(memory): dispatch core text search to the async FTS5 adapter (headroomlabs-ai#4365) - fix: [BUG] DirectMem0Adapter.search_memories calls removed mem0 search API (headroomlabs-ai#4518) - fix(toin): retain pending changes after filesystem save failures (headroomlabs-ai#4568) - fix(thinking): isolate compaction memo by compressor instance (headroomlabs-ai#4569) - fix(cache): build semantic entry before evicting so a failed embedding keeps live entries (headroomlabs-ai#4581) - fix(tabular): keep empty records and separator-like Markdown body rows (headroomlabs-ai#4582) - fix(code): preserve syntax in CCR retrieval comments (headroomlabs-ai#4583) - fix: [BUG] Saved request metrics lose their cache optimization fields (headroomlabs-ai#4584) - fix(proxy): preserve Cline headroom__headroom_retrieve results from recompression (headroomlabs-ai#4586) - fix(cache): scope router results to request compression policy (headroomlabs-ai#4590) - fix(proxy): keep mid-conversation system sections for third-party models (headroomlabs-ai#4591) - feat(mcp)!: port MCP servers to SDK 2.x (headroomlabs-ai#4603) - fix(proxy): strip upstream transport framing headers from Gemini response replays (headroomlabs-ai#4605) - fix(code): keep multi-line class headers' opening brace (headroomlabs-ai#4623) - fix(code): keep Rust attributes attached to their items (headroomlabs-ai#4624) - docs: add Kong AI Gateway integration page (headroomlabs-ai#4625) - fix: use all user text blocks for relevance scoring (headroomlabs-ai#4628) - fix: [BUG] Volatile SQLite metrics stores lose their schema before the first save (headroomlabs-ai#4633) - fix(kompress): read the pinned snapshot from Python's one HF cache in the native proxy (headroomlabs-ai#4438) - test(tokenizer): hold the env lock in the invalid-repo Hub error test (headroomlabs-ai#4151) - fix(proxy): skip memory-context search in cache mode on OpenAI routes (headroomlabs-ai#4632) - fix(proxy): skip memory-context search on OpenAI paths in cache mode (headroomlabs-ai#4634) - feat(ccr): answer headroom_retrieve on streaming chat completions (headroomlabs-ai#4631) - fix(openclaw): read the retrieve hash from params, not the tool-call id (headroomlabs-ai#4641) - fix(proxy): bypass compression for large admitted histories (headroomlabs-ai#4142) - fix(tokenizers): resolve tiktoken encoding for gateway-prefixed model ids (headroomlabs-ai#4637) - fix(proxy): answer /api/hello probes behind the token gate, log rejection context (headroomlabs-ai#4150) - fix(memory): keep learned evidence until persistence succeeds (headroomlabs-ai#4229) - fix(proxy): allow loopback-published container hosts to access /debug/memory (headroomlabs-ai#4259) - fix(code): keep semicolon-separated statements valid (headroomlabs-ai#4630) - fix(config): use the longest matching model_context_limits prefix (headroomlabs-ai#4288) - fix(transforms): recognise code fences whose info string is not a bare word (headroomlabs-ai#4291) - fix(transforms): stop the dense-line elider cutting Chinese, Japanese and Thai prose (headroomlabs-ai#4295) - fix(cache): reject nonpositive semantic cache capacities (headroomlabs-ai#4301) - fix(proxy): strip only one leading space from SSE field values (headroomlabs-ai#4306) - fix(tokenizers): honor registered model factories (headroomlabs-ai#4437) - fix(memory): preserve parent scopes when clearing memories (headroomlabs-ai#4305) - deps: Bump tsup from 8.5.1 to 9.0.0 in /plugins/openclaw (headroomlabs-ai#4384) - fix(diff): renumber hunk headers after trimming context (headroomlabs-ai#4319) - fix(kompress): keep words past the tokenizer's truncation point (headroomlabs-ai#4328) - fix(tabular): keep tables whose columns share a name (headroomlabs-ai#4329) - fix(proxy): let model discovery honor the custom base URL (headroomlabs-ai#4330) - fix(offline): guard the learn and memory-eval LLM calls under HEADROOM_OFFLINE (headroomlabs-ai#4344) - fix(proxy): keep Gemini memory context on entries with non-text parts (headroomlabs-ai#4506) - docs(security): sync security model with egress pollers, counts and beacon payload (headroomlabs-ai#4539) - fix(proxy): say a forwarded streaming error came from the provider (headroomlabs-ai#4629) - fix(install): stabilize Windows task lifecycle and eliminate console window popup (headroomlabs-ai#4627) - fix(ccr): buffer a stream only for a marker new this turn (headroomlabs-ai#4607) - fix(toin): preserve stores that exceed the byte limit (headroomlabs-ai#4589) - fix(opencode): route Copilot Claude models through the proxy (headroomlabs-ai#4594) - fix(thinking): leave a thinking block with a null or non-string value unchanged (headroomlabs-ai#4562) - fix(tabular): keep interior blank CSV rows instead of dropping them (headroomlabs-ai#4563) - fix(update-check): skip releases with no files and do not fall back to an uninstallable version (headroomlabs-ai#4560) - fix(core): case-insensitive Bearer scheme, clamp SQLite CCR TTLs, redact the Redis URL in logs (headroomlabs-ai#4561) - fix(kompress): run the CPU and ONNX Runtime loader guards before building a session (headroomlabs-ai#4559) - fix(router): gate block-form tool output against cached lossy results (headroomlabs-ai#4504) - ci: bump astral-sh/setup-uv from 10.3.2 to 10.3.3 in the actions-minor-patch group (headroomlabs-ai#4659) - deps: update tomlkit requirement from <1.0,>=0.15.0 to >=0.15.2,<1.0 (headroomlabs-ai#4653) - deps: bump ruff from 0.17.2 to 0.17.3 in the pip-minor-patch group (headroomlabs-ai#4652) - docs(security): describe the per-route outcome of an unsafe base-URL override (headroomlabs-ai#4660) - chore: release 0.43.0 (headroomlabs-ai#4643) - fix(router): log the ONNX fallbacks at info instead of warning (headroomlabs-ai#4535) - fix: keep parent predicates when clearing a narrower memory scope (headroomlabs-ai#4327) - fix(proxy): preserve Unicode separators in SSE JSON (headroomlabs-ai#4337) - fix(proxy): bound the model-keyed tokenizer, beacon and litellm caches (headroomlabs-ai#4497) - fix(router): keep tagged blocks out of the lossy size-gate fallback (headroomlabs-ai#4543) - fix(ccr): keep the in-memory order queue from evicting re-stored entries (headroomlabs-ai#4545) - fix(ort): avoid implicit runtime discovery from the workspace (headroomlabs-ai#4570) - fix(ccr): only refuse a bare marker, not originals that start and end with markers (headroomlabs-ai#4626) - fix(proxy): use HTTP/1.1 client for ChatGPT streaming and model metadata (headroomlabs-ai#4006) - test(gemini): serve the memory-tail tests' body through request.stream() (headroomlabs-ai#4645) - fix(kompress): load ONNX Runtime through the dynamic loader guard before building a session (headroomlabs-ai#4644) - fix(openclaw): accept 12-character hashes in headroom_retrieve (headroomlabs-ai#4640) - deps: bump the npm-minor-patch group across 3 directories with 6 updates (headroomlabs-ai#4662) - fix(release): normalize damaged release PR envelopes before detection (headroomlabs-ai#4664) - fix(memory): replace the HNSW vector when a memory is re-indexed (headroomlabs-ai#4649) - fix(memory): read the relation key the memory_save schema advertises (headroomlabs-ai#4647) - chore: release 0.43.1 (headroomlabs-ai#4661) - fix(proxy): keep cold-turn reasoning drops sticky so the next warm turn reuses the cached prefix (headroomlabs-ai#4592) - fix(tabular): split fixed-width rows on column boundaries, not on double spaces (headroomlabs-ai#4541) - fix(learn): support opencode v2 session schema in learn scanner (headroomlabs-ai#4199) - fix(proxy): rename leaked_threads metric to timed_out_workers_total (headroomlabs-ai#3908) - fix(content-router): trust confident HTML detection over mixed-content heuristics (headroomlabs-ai#3627) - deps: bump the npm-minor-patch group across 1 directory with 2 updates (headroomlabs-ai#4650) - deps: update tree-sitter requirement from <0.27,>=0.25.2 to >=0.26.0,<0.27 (headroomlabs-ai#4656) - fix(proxy): add --no-ccr-response-handling flag to bypass response buffering (headroomlabs-ai#3082) (headroomlabs-ai#3100) - fix(install): make install status agree with doctor when the proxy is reachable (headroomlabs-ai#3072) (headroomlabs-ai#3141) - fix(cli): resolve active proxy port for read commands (headroomlabs-ai#3522) - feat(providers): add Hermes agent wrap support (headroomlabs-ai#934) - deps: update click requirement from >=8.3.3 to >=8.5.0 (headroomlabs-ai#4655) - deps: update sqlite-vec requirement from >=0.1.6 to >=0.1.9 (headroomlabs-ai#4654) - deps: bump rusqlite from 0.40.2 to 0.41.1 (headroomlabs-ai#4658) - deps: bump the cargo-minor-patch group with 3 updates (headroomlabs-ai#4657) - fix(kompress): prevent loading model when enable_kompress is False (headroomlabs-ai#4667) - fix(kompress): let the next window decide the words past the token cut (headroomlabs-ai#4669) - fix(sdk): keep Vercel AI SDK tool-result output kinds through compression (headroomlabs-ai#4670) - ci: pin every GitHub Action to a commit SHA (headroomlabs-ai#4671) - fix(memory): keep multimodal user content intact when injecting memories (headroomlabs-ai#4648) - fix(router): ignore shell operators inside quoted arguments in read detection (headroomlabs-ai#4646) - fix(packaging)!: keep PyTorch extras out of all (headroomlabs-ai#4067) - fix(langchain): check optional integration availability (headroomlabs-ai#4042) - fix(memory): gracefully degrade on context lookup and initialization errors (headroomlabs-ai#3251) (headroomlabs-ai#4049) - fix(install): decode Windows Task Scheduler XML output before parsing (headroomlabs-ai#3969) (headroomlabs-ai#4064) - fix(search_compressor): keep kept rows byte-for-byte and in input order (headroomlabs-ai#3982) - fix(telemetry): keep install ID stateless (headroomlabs-ai#3542) - fix(providers): count Anthropic tool_result/tool_use content blocks in OpenAI token counter (headroomlabs-ai#2681) - fix(binaries): fail closed on HEADROOM_BINARIES_ALLOW_UNVERIFIED=0/false (headroomlabs-ai#3218) - fix(doctor): recognize IPv6 loopback and case-insensitive proxy routing URLs (headroomlabs-ai#3255) - fix(vertex): explain Vertex failures in-band, correct the model/region matrix (headroomlabs-ai#2640)
Description
Three process-wide caches are keyed by the
modelfield of the request body and never evict, so a client that sends a new model name on every request grows each of them without limit (#4479):TokenizerRegistry._cacheinheadroom/tokenizers/registry.py. Each entry is a tokenizer that owns its ownTokenCountCache._model_cachebehind the beacon's_public_modelinheadroom/telemetry/session.py._resolved_model_cachebehindresolve_litellm_modelinheadroom/pricing/litellm_pricing.py.#4407 bounded the per-model maps in the cost and savings trackers. This PR bounds these three caches the way
savings_tracker._resolve_litellm_modelwas bounded in #2860: a fixed entry count with least-recently-used eviction. The caps are 64 tokenizers and 256 entries for each of the two name caches. A model in steady use is never evicted. An evicted model is recomputed the next time it is used, so the cap never changes a result.Keys are not clipped. A cache key decides which tokenizer, pricing key or beacon model a request gets, so clipping would let two different model names share an entry and get the wrong answer. With the count capped, the size of each entry is already limited by the request body cap.
Fixes #4479
Type of Change
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/utils.py: addsremember_bounded(cache, key, value, maxsize). It storeskeyas the newest entry of a plain dict and evicts from the front, since dict order is recency order. It is safe without a lock: if two threads race, a key may be evicted early or the cache may sit one entry over the cap for a moment, but it never raises. The dicts stay plain dicts so the existing tests that clear, seed orlen()_resolved_model_cachekeep working.headroom/tokenizers/registry.py: addsTokenizerRegistry._CACHE_MAXSIZE = 64. A cache hit refreshes the entry's recency, and both the created-tokenizer path and the estimation-fallback path insert throughremember_bounded.register()andclear_cache()are unchanged.headroom/telemetry/session.py: adds_MODEL_CACHE_MAXSIZE = 256and the same hit/insert handling. CachedNoneresults ("not a public model") still count as hits. The "ponytail: unbounded dict" comment is replaced.headroom/pricing/litellm_pricing.py: adds_RESOLVED_MODEL_CACHE_MAXSIZE = 256and the same treatment inresolve_litellm_model.tests/test_bounded_model_caches.py: covers eviction order for the helper and, for each cache, that it stays bounded, that a model in steady use survives (LRU, not FIFO), and that an evicted name is recomputed. It also covers the registry's estimation-fallback path and a dict resized by another thread mid-eviction, so every changed line is exercised.Testing
Unit tests pass (
pytest)Linting passes (
ruff check .)Type checking passes (
mypy headroom): no new errors in the touched modules. The only error reported is inheadroom/memory/adapters/embedders.py:389, which is the same onmain.New tests added for new functionality
Manual testing performed
Test Output
None of the 8 full-suite failures comes from this change:
test_mcp_reconcile::test_ordinary_install_does_not_adopt_serena,test_wrap_sighup_proxy_leak::test_sighup_on_launch_tool_releases_the_proxy, bothtest_cc_switch_reconcilertests andtest_proxy_uds::test_prepare_only_chmods_directories_it_createsfail the same way on an unmodifiedmaincheckout in this environment (no installedheadroomconsole script, sandbox permissions).test_direct_chat_ccr_resolution.pyhangs atTestClient(app)startup until the timeout, and a different case fails on each run. On unmodifiedmainit failed in 2 of 3 isolated runs.test_offline_egress_chokepoint.pyandtest_stateless_no_disk.pypass when run on their own on this branch.Real Behavior Proof
Environment: Linux x86_64 (Amazon Linux 2023), Python 3.12.14, this branch on top of
mainat17d38e56(0.42.0), with the published 0.42.0headroom._corewheel binary. No Rust toolchain was available here, so_corewas not rebuilt; this PR does not touch Rust.Exact command / steps: the reproduction from [BUG] Three process-wide caches keyed by the request's
modelstring never evict (tokenizer registry, beacon_public_model, litellm model resolver) #4479, run against the real modules with no stubs. After one warm-up call per cache, callget_tokenizer(f"gpt-4o-x{i}-" + "m" * 10_000).count_text(...),session._public_model(f"custom-{i}-" + "m" * 10_000)andlitellm_pricing.resolve_litellm_model(f"custom-{i}-" + "m" * 10_000)for 2,000 distinct names each. Measurelen(cache)and thetracemallocgrowth across each loop. Then check thatgpt-4ostill resolves through both name caches.Observed result: on
main, all three caches grow to 2,001 entries (40.7 MB, 20.2 MB and 20.2 MB traced). On this branch they stop at 64, 256 and 256 entries (1.3 MB, 2.6 MB and 2.6 MB), andgpt-4ostill resolves through both name caches:mypy headroomfor the whole package (only the four touched modules were checked).Runtime Rollout Safety
Rollout-managed feature(s): None.
Minimum rollout channel: Stable.
Stable/default behavior changed: No change for normal traffic (far fewer distinct models than the caps). Past the caps, the least recently used entry is dropped and recomputed if that model comes back.
Kill switch / disable path: Not applicable.
Unsafe override required: No.
Qualification impact: None.
Rollback path: Revert this commit.
Review Readiness
I have performed a self-review
This PR is ready for human review
Checklist
My code follows the project's style guidelines
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
I have added tests that prove my fix is effective or that my feature works
New and existing unit tests pass locally with my changes
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
No user documentation needed: these caches are internal.
Cap sizes: 256 matches
savings_tracker._MODEL_RESOLUTION_CACHE_MAXSIZE. The tokenizer registry uses 64 because each entry owns aTokenCountCacheof up to 8,000,000 characters.Open PR fix(tokenizers): honor registered model factories #4437 ([BUG] register_tokenizer("my-model", factory=...) is never consulted; get_tokenizer returns EstimatingTokenCounter #4434) edits
TokenizerRegistry.register(). This PR only touchesget()and the class attributes, so the two should not conflict.🤖 Opened with Superhuman, an open-source contribution agent.
Maintainer current-main requalification
Exact head
a29cc2d40f5c8111cd079949201d8660c8a50130, upstream maine4a60ed72f6ef5b28569f8bfbe2163cfda32c948.Updated against upstream/main e4a60ed, resolving the tokenizer-registry overlap by retaining main's registered-model factories and dispatch, including its rule not to cache estimation after a failed model-specific factory. Applied the contributor's bounded recency insertion at the successful cache writes and ordinary fallback writes. No contributor policy or correctness logic was replaced. Re-reviewed cache helper/call sites and existing discussion; cached None, full model keys and recomputation after eviction remain intact.
The combined tree passes 111 bounded-cache/tokenizer/encoding tests with 14 optional skips, plus the adjacent tokenizer load-timeout, telemetry selfcheck and pricing-resolution suites. Ruff lint/format and whitespace checks pass. Existing rotating-2,000-name runtime evidence remains scoped to in-process module calls; an existing development native extension was used locally, not rebuilt. The shared test-only Gemini fixture repair was applied for independently established main failures; all ten cases pass. Formal approval awaits exact-head hosted qualification.
Exact-head hosted checks are being handled by maintainers. No new finding in the reviewed scope; formal approval awaits exact-head hosted qualification; nothing merged.
Maintainer commit-message qualification repair: current head bf0037d. Corrected only the maintainer main-sync commit message to Conventional Commit format. The complete file tree is byte-identical to the previously tested head; exact-head hosted checks are being refreshed. Nothing merged.