The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): context-length cache updates are serialized across agents
Maciej Lisiewskif14db1b4fe42
diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex 78c94e4852d..e898159a693 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -18,8 +18,9 @@ from urllib.parse import urlparseimport hermes_yaml as yamlfrom agent import model_metadata_http+from agent.model_metadata_cache import _write_context_cache, locked_context_cache-from utils import atomic_json_write, atomic_yaml_write, base_url_host_matches, base_url_hostname+from utils import atomic_json_write, base_url_host_matches, base_url_hostnamefrom hermes_constants import OPENROUTER_MODELS_URL, openrouter_variant_basefrom agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, UNPRICED_REPLAY_FIELDS, without_persistence_fields@@ -1126,20 +1127,12 @@ def _load_context_cache() -> dict[str, int]:return _load_context_cache_document().get("context_lengths") or {}-def _write_context_cache(cache: dict[str, int], bedrock_confirmed: dict | None = None) -> None:- """Atomic write (a truncating write killed mid-dump leaves a partial file that- _load_context_cache() swallows as {}, wiping EVERY cached length). Raises on failure."""- document = {"context_lengths": cache}- if bedrock_confirmed:- document["bedrock_confirmed_v1"] = bedrock_confirmed- atomic_yaml_write(_get_context_cache_path(), document)--def _context_cache_key(model: str, base_url: str) -> str:"""Canonical ``model@base_url`` key; trailing slashes stripped so ``/v1`` and ``/v1/`` share one entry."""return f"{model}@{(base_url or '').rstrip('/')}"+@locked_context_cachedef save_context_length(model: str, base_url: str, length: int, *, source: str = "") -> None:"""Persist a discovered context length under ``model@base_url`` (same model, different providers, different limits)."""# 0/negative is always a bug and would make get_model_context_length() return 0 (`0 is not None`).@@ -1196,6 +1189,7 @@ def get_cached_context_length(model: str, base_url: str, *, bedrock_confirmed: breturn length+@locked_context_cachedef _invalidate_cached_context_length(model: str, base_url: str) -> None:"""Drop a stale entry and its probe cooldown using the persisted cache URL.diff --git a/agent/model_metadata_cache.py b/agent/model_metadata_cache.pynew file mode 100644index 00000000000..c3aa390960c--- /dev/null+++ b/agent/model_metadata_cache.py@@ -0,0 +1,51 @@+"""``context_length_cache.yaml`` writes and their cross-process serialization.++Every agent (CLI, gateway sessions, cron jobs, subagents) persists probed context windows with a+load -> mutate -> write cycle; unserialized, one writer rewrites a stale snapshot and drops the+other's entry (or resurrects an invalidated, too-large length).+"""++import contextlib+import functools+import logging+import threading++from utils import atomic_yaml_write++logger = logging.getLogger(__name__)++_CONTEXT_CACHE_LOCK_HOLDER = threading.local()+_CONTEXT_CACHE_LOCK_TIMEOUT_SECONDS = 5.0+++def _write_context_cache(cache: dict[str, int], bedrock_confirmed: dict | None = None) -> None:+ """Atomic write (a truncating write killed mid-dump leaves a partial file that+ _load_context_cache() swallows as {}, wiping EVERY cached length). Raises on failure."""+ from agent.model_metadata import _get_context_cache_path # facade seam: tests patch the path there+ document = {"context_lengths": cache}+ if bedrock_confirmed:+ document["bedrock_confirmed_v1"] = bedrock_confirmed+ atomic_yaml_write(_get_context_cache_path(), document)+++def locked_context_cache(fn):+ """Run ``fn``'s load -> mutate -> write cycle under the cache file's cross-process lock.++ The cache is best-effort: when the lock cannot be taken in time the update is skipped, never raised.+ """+ @functools.wraps(fn)+ def wrapper(*args, **kwargs):+ from agent.model_metadata import _get_context_cache_path # facade seam: tests patch the path there+ from hermes_cli.auth import _file_lock+ path = _get_context_cache_path()+ lock_path = path.with_name(path.name + ".lock")+ with contextlib.ExitStack() as stack:+ try:+ stack.enter_context(_file_lock(+ lock_path, _CONTEXT_CACHE_LOCK_HOLDER, _CONTEXT_CACHE_LOCK_TIMEOUT_SECONDS,+ f"Timed out waiting for the context length cache lock ({lock_path})"))+ except (OSError, TimeoutError):+ logger.debug("Skipping context length cache update", exc_info=True)+ return None+ return fn(*args, **kwargs)+ return wrapperdiff --git a/tests/agent/test_model_metadata_cache.py b/tests/agent/test_model_metadata_cache.pynew file mode 100644index 00000000000..1ba8f55d716--- /dev/null+++ b/tests/agent/test_model_metadata_cache.py@@ -0,0 +1,51 @@+"""Concurrent writers of ``context_length_cache.yaml`` (race audit lostupdate-7).++Every agent (CLI, gateway sessions, cron jobs, subagents) persists probed context windows with a+load -> mutate -> write cycle; an unserialized pair rewrites a stale snapshot and drops the other+writer's entry, so the next session re-probes or overflows its context on the first call.+"""++import threading++import pytest++import agent.model_metadata as mm+from tests.lock_contention import watch_file_lock_contention+from tests.waiting import wait_until++[email protected]("first_writer", ["save", "invalidate"])+def test_concurrent_cache_writers_keep_each_others_entries(monkeypatch, first_writer):+ contended = watch_file_lock_contention(monkeypatch)+ mm.save_context_length("model-a", "https://a.example/v1", 200_000)+ real_load = mm._load_context_cache_document+ loaded = threading.Event()+ other_saved = threading.Event()++ def parked_load():+ document = real_load()+ if threading.current_thread().name == "first-writer":+ loaded.set()+ # Unserialized writers let the other agent save here; serialized ones are seen+ # blocking on the cache lock instead.+ wait_until(lambda: other_saved.is_set() or contended.is_set(),+ what="the other agent saved or blocked on the cache lock")+ return document++ monkeypatch.setattr(mm, "_load_context_cache_document", parked_load)+ if first_writer == "save":+ action = lambda: mm.save_context_length("model-a", "https://a.example/v1", 128_000)+ expected_a = 128_000+ else:+ action = lambda: mm._invalidate_cached_context_length("model-a", "https://a.example/v1")+ expected_a = None+ worker = threading.Thread(target=action, name="first-writer")+ worker.start()+ assert loaded.wait(timeout=5)+ mm.save_context_length("model-b", "https://b.example/v1", 64_000)+ other_saved.set()+ worker.join(timeout=10)+ assert not worker.is_alive()++ assert mm.get_cached_context_length("model-b", "https://b.example/v1") == 64_000+ assert mm.get_cached_context_length("model-a", "https://a.example/v1") == expected_a