Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(proxy): share cold-start warmup across pipelines + lock memory init
Adryan Eka Vandra7e2b078b7657
diff --git a/headroom/proxy/memory_handler.py b/headroom/proxy/memory_handler.pyindex 5ad45c3c4..f42e038d5 100644--- a/headroom/proxy/memory_handler.py+++ b/headroom/proxy/memory_handler.py@@ -49,6 +49,12 @@ NATIVE_MEMORY_BETA_HEADER = "context-management-2025-06-27"# Native memory tool typeNATIVE_MEMORY_TOOL_TYPE = "memory_20250818"+# Maximum time to wait for a single backend initialization (one-shot).+# Applies to MemoryHandler._ensure_initialized. On timeout, _initialized+# stays False so that subsequent requests retry instead of deadlocking.+# See wiki/plans/2026-04-17-fix-codex-proxy-resilience-plan.md "Risks" row 7.+STARTUP_INIT_TIMEOUT_SECONDS = 30.0+@dataclassclass MemoryConfig:@@ -101,6 +107,11 @@ class MemoryHandler:self.agent_type = agent_typeself._backend: LocalBackend | Any = Noneself._initialized = False+ # Async singleflight guard for backend init. Ensures concurrent first+ # callers land on one init (double-checked pattern inside+ # _ensure_initialized). Not used by the legacy sync _initialized flag+ # on its own because that flag isn't atomic across await points.+ self._init_lock: asyncio.Lock | None = Noneself._memory_tools: list[dict[str, Any]] | None = None# Native memory tool directoryself._native_memory_dir: Path | None = None@@ -109,6 +120,16 @@ class MemoryHandler:# Memory Bridgeself._bridge: Any = None # MemoryBridge, lazy imported+ def _get_init_lock(self) -> asyncio.Lock:+ """Lazily create the init lock bound to the running event loop.++ Avoids ``DeprecationWarning: There is no current event loop`` when+ ``MemoryHandler`` is constructed before the loop is set up.+ """+ if self._init_lock is None:+ self._init_lock = asyncio.Lock()+ return self._init_lock+def _init_native_memory_dir(self) -> None:"""Initialize native memory directory."""if self.config.native_memory_dir:@@ -134,13 +155,46 @@ class MemoryHandler:return {}async def _ensure_initialized(self) -> None:- """Lazy initialization of memory backend."""+ """Lazy initialization of memory backend.++ Singleflight via ``self._init_lock`` with double-checked pattern:+ concurrent first callers await the same load rather than triggering+ N parallel backend inits. Wrapped in ``asyncio.wait_for`` with a+ configurable timeout (``STARTUP_INIT_TIMEOUT_SECONDS``); on timeout+ ``self._initialized`` stays ``False`` so a later request can retry+ (fail-open contract — no exception propagates to request handlers).+ """+ # Fast path: already initialized, no lock contention.if self._initialized:returnif not self.config.enabled:return+ lock = self._get_init_lock()++ async def _do_init() -> None:+ async with lock:+ # Double-check after acquiring the lock — another task may+ # have completed the init while we were waiting.+ if self._initialized:+ return+ await self._init_backend_locked()++ try:+ await asyncio.wait_for(_do_init(), timeout=STARTUP_INIT_TIMEOUT_SECONDS)+ except asyncio.TimeoutError:+ # Fail-open: leave _initialized=False so subsequent calls retry.+ logger.error(+ "Memory: backend initialization timed out after "+ f"{STARTUP_INIT_TIMEOUT_SECONDS}s "+ f"(backend={self.config.backend}). "+ "Subsequent requests will retry."+ )+ return++ async def _init_backend_locked(self) -> None:+ """Actual backend-init body. Must be called with ``_init_lock`` held."""if self.config.backend == "local":from headroom.memory.backends.local import LocalBackend, LocalBackendConfig@@ -1600,6 +1654,37 @@ To SAVE: create /memories/<topic>.txt "content""""Initialize the configured backend so readiness checks can be accurate."""await self._ensure_initialized()+ async def warmup_embedder(self) -> bool:+ """Force one warm-up embed call so the ONNX graph is compiled now.++ Returns ``True`` if the embedder was exercised successfully,+ ``False`` otherwise. Best-effort — all errors are swallowed and+ logged, never raised, so startup cannot be blocked by embedder+ cold-start failures.++ Only meaningful for the ``local`` backend (the ONNX/sentence+ embedder warm-up is what we want to preempt). Qdrant/Neo4j is a+ no-op because Mem0 handles its own embedder lifecycle upstream.+ """+ if not self._initialized or self._backend is None:+ return False++ try:+ hm = getattr(self._backend, "_hierarchical_memory", None)+ if hm is None:+ return False+ embedder = getattr(hm, "_embedder", None) or getattr(hm, "embedder", None)+ if embedder is None:+ return False+ if not hasattr(embedder, "embed"):+ return False+ await embedder.embed("warmup")+ logger.info("Memory: embedder warm-up encode complete")+ return True+ except Exception as exc: # pragma: no cover - defensive+ logger.warning(f"Memory: embedder warm-up failed (non-fatal): {exc}")+ return False+def health_status(self) -> dict[str, Any]:"""Return a lightweight health snapshot for readiness endpoints."""return {diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 757364e16..9f2d4f956 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -128,6 +128,7 @@ from headroom.proxy.prometheus_metrics import PrometheusMetrics # noqa: F401from headroom.proxy.rate_limiter import TokenBucketRateLimiter # noqa: F401from headroom.proxy.request_logger import RequestLogger # noqa: F401from headroom.proxy.semantic_cache import SemanticCache # noqa: F401+from headroom.proxy.warmup import WarmupRegistryfrom headroom.subscription.base import get_quota_registry, reset_quota_registryfrom headroom.subscription.codex_rate_limits import get_codex_rate_limit_statefrom headroom.subscription.copilot_quota import get_copilot_quota_tracker@@ -367,6 +368,12 @@ class HeadroomProxy(# HTTP clientself.http_client: httpx.AsyncClient | None = None+ # Shared cold-start warmup registry (populated by startup()).+ # Holds typed slots with loaded / loading / null / error status for+ # each preloaded heavy asset. Exposed as ``proxy.warmup`` and+ # serialized by the /debug/warmup route (Unit 5).+ self.warmup: WarmupRegistry = WarmupRegistry()+# Backend for Anthropic API (direct, LiteLLM, or any-llm)# Supports: "anthropic" (direct), "bedrock", "vertex", "litellm-<provider>", or "anyllm"self.anthropic_backend: Backend | None = None@@ -626,16 +633,42 @@ class HeadroomProxy(logger.info("Smart Routing: DISABLED (legacy sequential mode)")# Eagerly load ALL compressors, parsers, and detectors at startup- # This eliminates cold-start latency spikes on first requests+ # This eliminates cold-start latency spikes on first requests.+ # Iterate BOTH pipelines (Anthropic + OpenAI) and dedupe transforms+ # by id() so shared-transform instances never load twice. The+ # resulting status dict is merged into ``self.warmup`` so /debug/warmup+ # (Unit 5) and /readyz have a single source of truth.self._kompress_status = "not installed"eager_status: dict[str, str] = {}if self.config.optimize:logger.info("Pre-loading compressors and parsers...")- for transform in self.anthropic_pipeline.transforms:- if hasattr(transform, "eager_load_compressors"):- eager_status = transform.eager_load_compressors()- break+ seen_transform_ids: set[int] = set()+ pipelines = (self.anthropic_pipeline, self.openai_pipeline)+ for pipeline in pipelines:+ for transform in pipeline.transforms:+ if id(transform) in seen_transform_ids:+ continue+ seen_transform_ids.add(id(transform))+ if not hasattr(transform, "eager_load_compressors"):+ continue+ try:+ transform_status = transform.eager_load_compressors()+ except Exception as exc:+ logger.warning(+ "Eager preload failed for %s: %s",+ type(transform).__name__,+ exc,+ )+ continue+ if not isinstance(transform_status, dict):+ continue+ # Merge: later writers win only if the key wasn't set.+ # Preload a transform ONCE — if another pipeline also has+ # ``eager_load_compressors`` it contributes only new keys.+ for key, value in transform_status.items():+ eager_status.setdefault(key, value)+ self.warmup.merge_transform_status(transform_status)# Update internal status from eager loading resultsif eager_status.get("kompress") == "enabled":@@ -666,8 +699,35 @@ class HeadroomProxy(logger.info("Magika: ENABLED (ML content detection)")if self.memory_handler:- await self.memory_handler.ensure_initialized()+ self.warmup.memory_backend.mark_loading()+ try:+ await self.memory_handler.ensure_initialized()+ except Exception as exc: # pragma: no cover - defensive+ self.warmup.memory_backend.mark_error(str(exc))+ logger.warning(+ "Memory: backend initialization failed (startup continues): %s", exc+ )memory_status = self.memory_handler.health_status()+ if memory_status.get("initialized"):+ self.warmup.memory_backend.mark_loaded(+ handle=self.memory_handler,+ backend=memory_status.get("backend"),+ )+ # Force one embed call so the ONNX graph is compiled now,+ # not lazily during the first request. Best-effort — any+ # failure is swallowed inside warmup_embedder.+ self.warmup.memory_embedder.mark_loading()+ warmed = await self.memory_handler.warmup_embedder()+ if warmed:+ self.warmup.memory_embedder.mark_loaded()+ else:+ # Not an error — e.g. qdrant-neo4j has no embedder slot+ # we can reach, or the backend simply exposes no handle.+ self.warmup.memory_embedder.mark_null()+ else:+ if self.warmup.memory_backend.status != "error":+ self.warmup.memory_backend.mark_null()+ self.warmup.memory_embedder.mark_null()logger.info("Memory: ENABLED "f"(backend={memory_status['backend']}, initialized={memory_status['initialized']})"diff --git a/headroom/proxy/warmup.py b/headroom/proxy/warmup.pynew file mode 100644index 000000000..9c66ab36a--- /dev/null+++ b/headroom/proxy/warmup.py@@ -0,0 +1,147 @@+"""Warmup registry for proxy cold-start state.++Holds references to preloaded heavy assets (ML compressors, content detectors,+memory backends, embedders) that are eagerly initialized during+``HeadroomProxy.startup`` so that request-time use shares one in-process+singleton and concurrent first-use callers do not trigger N parallel loads.++The registry is populated by ``HeadroomProxy.startup`` and exposed as+``proxy.warmup``. Unit 5's ``/debug/warmup`` endpoint serializes this state.++Slot status semantics+---------------------+Each slot exposes a :class:`WarmupSlot` with a ``status`` that must be one of:++``loaded``+ The asset was loaded successfully and its handle is stored on the slot.+``loading``+ Load is in progress (used when the warmup is async; currently only+ applies to memory embedder warm-up, everything else is synchronous).+``null``+ Preload did not run for this slot. Either preload was disabled+ (``optimize=False``) or the component is not configured / unavailable.+ This is *not* an error — the request-time lazy path should still work.+``error``+ Preload was attempted but failed. An ``error`` string is populated.+ The request-time lazy path is still the fallback and may succeed.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass, field+from typing import Any, Literal++logger = logging.getLogger(__name__)++WarmupStatus = Literal["loaded", "loading", "null", "error"]+++@dataclass+class WarmupSlot:+ """Status record for one warmed-up component.++ ``handle`` is the concrete asset (compressor instance, backend instance,+ etc.) when ``status == "loaded"``. Otherwise it is ``None``.+ """++ status: WarmupStatus = "null"+ handle: Any | None = None+ error: str | None = None+ # Free-form extra info surfaced by /debug/warmup (e.g. tree-sitter language+ # list, model id, embedder backend name). Kept small and JSON-serializable.+ info: dict[str, Any] = field(default_factory=dict)++ def mark_loaded(self, handle: Any = None, **info: Any) -> None:+ self.status = "loaded"+ self.handle = handle+ self.error = None+ if info:+ self.info.update(info)++ def mark_loading(self) -> None:+ self.status = "loading"+ self.handle = None+ self.error = None++ def mark_null(self) -> None:+ self.status = "null"+ self.handle = None+ self.error = None++ def mark_error(self, error: str) -> None:+ self.status = "error"+ self.handle = None+ self.error = error++ def to_dict(self) -> dict[str, Any]:+ """Serialize for /debug/warmup. Never includes the raw handle."""+ payload: dict[str, Any] = {"status": self.status}+ if self.error:+ payload["error"] = self.error+ if self.info:+ payload["info"] = dict(self.info)+ return payload+++@dataclass+class WarmupRegistry:+ """Shared preloaded asset registry populated by ``HeadroomProxy.startup``.++ One instance per ``HeadroomProxy``. All writes happen on the startup+ task; reads may come from request handlers or ``/debug/warmup``. Python+ dict/dataclass attribute access is thread-safe enough for our read+ patterns (single-writer on startup, readers never mutate).+ """++ kompress: WarmupSlot = field(default_factory=WarmupSlot)+ magika: WarmupSlot = field(default_factory=WarmupSlot)+ code_aware: WarmupSlot = field(default_factory=WarmupSlot)+ tree_sitter: WarmupSlot = field(default_factory=WarmupSlot)+ smart_crusher: WarmupSlot = field(default_factory=WarmupSlot)+ memory_backend: WarmupSlot = field(default_factory=WarmupSlot)+ memory_embedder: WarmupSlot = field(default_factory=WarmupSlot)++ def merge_transform_status(self, status: dict[str, str]) -> None:+ """Merge a ``eager_load_compressors`` status dict into slots.++ Only promotes a slot to ``loaded`` if the status string is+ ``enabled`` / ``ready`` / starts with ``loaded``. Any other value+ is treated as ``null`` with the string surfaced via ``info``.+ ``error`` statuses must be set explicitly by the caller.+ """++ def _apply(slot: WarmupSlot, value: str | None) -> None:+ if value is None:+ return+ v = value.strip().lower()+ if v in {"enabled", "ready"} or v.startswith("loaded"):+ # Preserve whatever handle/info was set already.+ if slot.status != "loaded":+ slot.mark_loaded(handle=slot.handle, source_status=value)+ else:+ slot.info.setdefault("source_status", value)+ else:+ if slot.status != "loaded":+ slot.info["source_status"] = value++ _apply(self.kompress, status.get("kompress"))+ _apply(self.magika, status.get("magika"))+ _apply(self.code_aware, status.get("code_aware"))+ _apply(self.tree_sitter, status.get("tree_sitter"))+ _apply(self.smart_crusher, status.get("smart_crusher"))++ def to_dict(self) -> dict[str, dict[str, Any]]:+ """Serialize the whole registry (for ``/debug/warmup``)."""+ return {+ "kompress": self.kompress.to_dict(),+ "magika": self.magika.to_dict(),+ "code_aware": self.code_aware.to_dict(),+ "tree_sitter": self.tree_sitter.to_dict(),+ "smart_crusher": self.smart_crusher.to_dict(),+ "memory_backend": self.memory_backend.to_dict(),+ "memory_embedder": self.memory_embedder.to_dict(),+ }+++__all__ = ["WarmupRegistry", "WarmupSlot", "WarmupStatus"]diff --git a/tests/test_memory_handler_concurrent_init.py b/tests/test_memory_handler_concurrent_init.pynew file mode 100644index 000000000..3c22124de--- /dev/null+++ b/tests/test_memory_handler_concurrent_init.py@@ -0,0 +1,217 @@+"""Concurrency + timeout tests for MemoryHandler._ensure_initialized (Unit 1).++Covers:+- 10 concurrent first-callers trigger exactly one backend init+ (singleflight via asyncio.Lock + double-check).+- Initialization timeout is surfaced via log + leaves _initialized=False so+ a subsequent call can retry (fail-open contract).+- End-to-end real-backend sanity test (no monkeypatching of internals)+ that exercises LocalBackend so the system-wide check is satisfied.+"""++from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import patch++import pytest++from headroom.proxy.memory_handler import (+ STARTUP_INIT_TIMEOUT_SECONDS,+ MemoryConfig,+ MemoryHandler,+)++# -------------------------------------------------------------------+# Singleflight under concurrent callers+# -------------------------------------------------------------------+++async def test_concurrent_ensure_initialized_runs_init_once(tmp_path, monkeypatch):+ hits = {"n": 0}+ start_event = asyncio.Event()+ release_event = asyncio.Event()++ class FakeLocalBackend:+ def __init__(self, config): # noqa: D401+ self.config = config++ async def _ensure_initialized(self) -> None:+ hits["n"] += 1+ start_event.set()+ # Simulate a slow cold-start so concurrent callers pile up on+ # the lock. Without singleflight, hits would exceed 1.+ await release_event.wait()++ async def close(self) -> None:+ pass++ import headroom.memory.backends.local as local_mod++ monkeypatch.setattr(local_mod, "LocalBackend", FakeLocalBackend)++ handler = MemoryHandler(+ MemoryConfig(+ enabled=True, backend="local", db_path=str(tmp_path / "mem.db")+ )+ )++ async def caller() -> None:+ await handler._ensure_initialized()++ # Fire 10 concurrent first-callers.+ tasks = [asyncio.create_task(caller()) for _ in range(10)]+ # Let one task enter the critical section, then release it.+ await start_event.wait()+ release_event.set()+ await asyncio.gather(*tasks)++ assert hits["n"] == 1, f"expected 1 backend init under concurrency, got {hits['n']}"+ assert handler._initialized is True+++async def test_ensure_initialized_noop_when_disabled(tmp_path):+ handler = MemoryHandler(+ MemoryConfig(enabled=False, backend="local", db_path=str(tmp_path / "mem.db"))+ )+ await handler._ensure_initialized()+ assert handler._initialized is False+ assert handler._backend is None+++# -------------------------------------------------------------------+# Timeout fail-open+# -------------------------------------------------------------------+++async def test_ensure_initialized_timeout_leaves_handler_unready(+ tmp_path, monkeypatch+):+ class HangingBackend:+ def __init__(self, config):+ self.config = config++ async def _ensure_initialized(self) -> None:+ # Hang forever — timeout must cancel this.+ await asyncio.Event().wait()++ async def close(self) -> None:+ pass++ import headroom.memory.backends.local as local_mod++ monkeypatch.setattr(local_mod, "LocalBackend", HangingBackend)++ handler = MemoryHandler(+ MemoryConfig(+ enabled=True, backend="local", db_path=str(tmp_path / "mem.db")+ )+ )++ # Attach a handler directly to the module logger — caplog has trouble+ # when third-party conftest monkeys with propagation settings.+ import logging as _logging++ mem_logger = _logging.getLogger("headroom.proxy.memory_handler")+ captured: list[_logging.LogRecord] = []++ class _ListHandler(_logging.Handler):+ def emit(self, record: _logging.LogRecord) -> None:+ captured.append(record)++ handler_log = _ListHandler(level=_logging.ERROR)+ mem_logger.addHandler(handler_log)+ prev_level = mem_logger.level+ mem_logger.setLevel(_logging.DEBUG)+ try:+ # Shrink the module-level timeout to keep the test fast.+ with patch(+ "headroom.proxy.memory_handler.STARTUP_INIT_TIMEOUT_SECONDS", 0.1+ ):+ await handler._ensure_initialized()+ finally:+ mem_logger.removeHandler(handler_log)+ mem_logger.setLevel(prev_level)++ # Fail-open: no exception, _initialized=False, error logged.+ assert handler._initialized is False+ found_timeout_log = any("timed out" in rec.getMessage().lower() for rec in captured)+ assert found_timeout_log, (+ "expected 'timed out' log record; "+ f"got: {[(r.levelname, r.getMessage()) for r in captured]}"+ )++ # Confirm the default constant is unchanged (sanity).+ assert STARTUP_INIT_TIMEOUT_SECONDS == 30.0+++# -------------------------------------------------------------------+# Real backend init (no monkeypatching) — integration smoke test+# -------------------------------------------------------------------+++async def test_real_localbackend_initializes_via_public_entrypoint(tmp_path):+ """End-to-end sanity check: the public ``ensure_initialized`` path works+ against a real LocalBackend. This catches regressions where the new+ asyncio.Lock layering (Unit 1) breaks the actual init chain."""+ pytest.importorskip("sqlite3") # bundled with Python but be explicit+ # Skip on environments without an embedder backend available.+ try:+ import onnxruntime # noqa: F401+ except Exception:+ try:+ import sentence_transformers # noqa: F401+ except Exception: # pragma: no cover - env-dependent+ pytest.skip("No embedder backend available in this environment")++ handler = MemoryHandler(+ MemoryConfig(+ enabled=True,+ backend="local",+ db_path=str(tmp_path / "mem.db"),+ )+ )++ # Concurrent callers should still produce one initialized backend.+ await asyncio.gather(*[handler.ensure_initialized() for _ in range(5)])+ assert handler._initialized is True+ assert handler._backend is not None++ # warmup_embedder is best-effort; on a real backend it should succeed.+ warmed = await handler.warmup_embedder()+ assert warmed is True+ await handler.close()+++async def test_warmup_embedder_returns_false_without_backend():+ handler = MemoryHandler(MemoryConfig(enabled=True, backend="local"))+ # _initialized=False, _backend=None → no-op, no crash.+ result = await handler.warmup_embedder()+ assert result is False+++async def test_warmup_embedder_swallows_exceptions():+ handler = MemoryHandler(MemoryConfig(enabled=True, backend="local"))+ handler._initialized = True++ class HM:+ class _E:+ async def embed(self, _text: Any) -> Any:+ raise RuntimeError("synthetic embedder failure")++ _embedder = _E()++ class Backend:+ _hierarchical_memory = HM()++ handler._backend = Backend()+ # Must not raise; returns False.+ result = await handler.warmup_embedder()+ assert result is Falsediff --git a/tests/test_proxy_warmup.py b/tests/test_proxy_warmup.pynew file mode 100644index 000000000..a5db602db--- /dev/null+++ b/tests/test_proxy_warmup.py@@ -0,0 +1,282 @@+"""Tests for the shared cold-start warmup registry (Unit 1).++Covers:+- WarmupRegistry slot state transitions.+- Preload iterates both Anthropic + OpenAI pipelines and dedupes+ shared transforms by ``id(transform)``.+- Embedder warm-up encode runs once during startup (happy path).+- optimize=False leaves slots null.+- Memory backend init failure yields registry status=error, startup+ still completes, health reports degraded memory.+"""++from __future__ import annotations++from unittest.mock import AsyncMock++import pytest++pytest.importorskip("fastapi")++from headroom.proxy.warmup import WarmupRegistry, WarmupSlot++# -------------------------------------------------------------------+# WarmupSlot / WarmupRegistry unit tests+# -------------------------------------------------------------------+++def test_warmup_slot_defaults_to_null():+ slot = WarmupSlot()+ assert slot.status == "null"+ assert slot.handle is None+ assert slot.error is None+ assert slot.to_dict() == {"status": "null"}+++def test_warmup_slot_transitions():+ slot = WarmupSlot()+ slot.mark_loading()+ assert slot.status == "loading"++ slot.mark_loaded(handle="h", model="x")+ assert slot.status == "loaded"+ assert slot.handle == "h"+ assert slot.info == {"model": "x"}+ assert slot.to_dict() == {"status": "loaded", "info": {"model": "x"}}++ slot.mark_error("boom")+ assert slot.status == "error"+ assert slot.handle is None+ assert slot.error == "boom"+ assert slot.to_dict()["status"] == "error"+ assert slot.to_dict()["error"] == "boom"++ slot.mark_null()+ assert slot.status == "null"+ assert slot.handle is None+ assert slot.error is None+++def test_warmup_registry_merges_enabled_status_into_loaded():+ reg = WarmupRegistry()+ reg.merge_transform_status(+ {+ "kompress": "enabled",+ "magika": "enabled",+ "code_aware": "enabled",+ "tree_sitter": "loaded (3 languages)",+ "smart_crusher": "ready",+ }+ )+ out = reg.to_dict()+ assert out["kompress"]["status"] == "loaded"+ assert out["magika"]["status"] == "loaded"+ assert out["code_aware"]["status"] == "loaded"+ assert out["tree_sitter"]["status"] == "loaded"+ assert out["smart_crusher"]["status"] == "loaded"+++def test_warmup_registry_preserves_null_for_unavailable():+ reg = WarmupRegistry()+ reg.merge_transform_status({"kompress": "unavailable", "magika": "not installed"})+ assert reg.kompress.status == "null"+ assert reg.magika.status == "null"+ assert reg.kompress.info.get("source_status") == "unavailable"+++def test_warmup_registry_to_dict_has_expected_keys():+ reg = WarmupRegistry()+ out = reg.to_dict()+ assert set(out.keys()) == {+ "kompress",+ "magika",+ "code_aware",+ "tree_sitter",+ "smart_crusher",+ "memory_backend",+ "memory_embedder",+ }+++# -------------------------------------------------------------------+# Startup orchestration tests — use HeadroomProxy + stubbed transforms+# -------------------------------------------------------------------+++def _stub_pipelines(monkeypatch):+ """Build a minimal proxy whose pipelines share a single spy transform.++ The transform's ``eager_load_compressors`` increments a hit counter;+ assertion that dedup prevents double-loading relies on that counter.+ """+ pytest.importorskip("httpx")+ from headroom.proxy.server import HeadroomProxy, ProxyConfig++ class SpyTransform:+ def __init__(self) -> None:+ self.hits = 0++ def eager_load_compressors(self) -> dict[str, str]:+ self.hits += 1+ return {+ "kompress": "enabled",+ "magika": "enabled",+ "code_aware": "enabled",+ "smart_crusher": "ready",+ }++ config = ProxyConfig(+ optimize=True,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ smart_routing=False,+ code_aware_enabled=False,+ )+ proxy = HeadroomProxy(config)++ spy = SpyTransform()+ # Replace both pipeline transform lists with the SAME instance so the+ # dedupe-by-id() logic is what we actually assert against.+ proxy.anthropic_pipeline.transforms = [spy]+ proxy.openai_pipeline.transforms = [spy]+ return proxy, spy+++async def test_startup_runs_shared_transform_once(_stub_pipelines):+ proxy, spy = _stub_pipelines+ await proxy.startup()+ try:+ assert spy.hits == 1, "shared transform must be eager-loaded exactly once"+ assert proxy.warmup.kompress.status == "loaded"+ assert proxy.warmup.magika.status == "loaded"+ assert proxy.warmup.code_aware.status == "loaded"+ assert proxy.warmup.smart_crusher.status == "loaded"+ finally:+ await proxy.shutdown()+++async def test_startup_optimize_false_leaves_slots_null():+ pytest.importorskip("httpx")+ from headroom.proxy.server import HeadroomProxy, ProxyConfig++ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ smart_routing=False,+ )+ proxy = HeadroomProxy(config)++ called = {"n": 0}++ class SpyTransform:+ def eager_load_compressors(self) -> dict[str, str]:+ called["n"] += 1+ return {"kompress": "enabled"}++ proxy.anthropic_pipeline.transforms = [SpyTransform()]+ proxy.openai_pipeline.transforms = [SpyTransform()]++ await proxy.startup()+ try:+ assert called["n"] == 0, "preload must not run when optimize=False"+ assert proxy.warmup.kompress.status == "null"+ assert proxy.warmup.memory_backend.status == "null"+ assert proxy.warmup.memory_embedder.status == "null"+ finally:+ await proxy.shutdown()+++async def test_startup_memory_embedder_warmup_encodes_once(tmp_path, monkeypatch):+ pytest.importorskip("httpx")+ from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler+ from headroom.proxy.server import HeadroomProxy, ProxyConfig++ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ )+ proxy = HeadroomProxy(config)++ # Swap in a hand-rolled MemoryHandler whose backend exposes a mock+ # embedder. We don't want real ONNX here — just a spy.+ handler = MemoryHandler(+ MemoryConfig(+ enabled=True, backend="local", db_path=str(tmp_path / "mem.db")+ )+ )+ handler._initialized = True++ embed = AsyncMock(return_value=[0.0])++ class FakeHM:+ def __init__(self):+ self._embedder = type("_E", (), {"embed": embed})()++ class FakeBackend:+ def __init__(self):+ self._hierarchical_memory = FakeHM()++ async def close(self):+ pass++ handler._backend = FakeBackend()+ handler.ensure_initialized = AsyncMock()+ proxy.memory_handler = handler++ await proxy.startup()+ try:+ assert embed.await_count == 1+ assert embed.await_args[0][0] == "warmup"+ assert proxy.warmup.memory_backend.status == "loaded"+ assert proxy.warmup.memory_embedder.status == "loaded"+ finally:+ await proxy.shutdown()+++async def test_startup_memory_backend_error_surfaced_and_health_degraded(tmp_path):+ pytest.importorskip("httpx")+ from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler+ from headroom.proxy.server import HeadroomProxy, ProxyConfig++ config = ProxyConfig(+ optimize=False,+ cache_enabled=False,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ )+ proxy = HeadroomProxy(config)++ handler = MemoryHandler(+ MemoryConfig(+ enabled=True, backend="local", db_path=str(tmp_path / "mem.db")+ )+ )++ async def _boom() -> None:+ raise RuntimeError("synthetic backend init failure")++ handler.ensure_initialized = _boom # type: ignore[assignment]+ proxy.memory_handler = handler++ # Startup must NOT raise — the memory slot must report error and the+ # rest of the startup pipeline keeps going (quota registry etc.).+ await proxy.startup()+ try:+ assert proxy.warmup.memory_backend.status == "error"+ assert "synthetic" in (proxy.warmup.memory_backend.error or "")+ # Memory embedder stays null because the backend never initialized.+ assert proxy.warmup.memory_embedder.status == "null"+ health = handler.health_status()+ assert health["initialized"] is False+ finally:+ await proxy.shutdown()