Skip to content

Commit f6d9f10

Browse files
authored
Merge pull request #37 from OpenWAM-Official/fix/prompt-embed-cache-eviction
fix: prevent prompt embed cache eviction KeyError
2 parents 90e94ae + 779682e commit f6d9f10

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

‎openwam/deploy/engine.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,12 @@ def __setitem__(self, key: Any, value: Any) -> None:
7878
self.move_to_end(key)
7979
super().__setitem__(key, value)
8080
while len(self) > self._maxsize:
81-
evicted_key, _ = self.popitem(last=False)
81+
# ``OrderedDict.popitem`` retrieves the value through ``self[key]``.
82+
# Since ``__getitem__`` updates recency, that lookup runs after the
83+
# key has been removed from the ordering map and raises ``KeyError``.
84+
# Delete through the base implementation to bypass the override.
85+
evicted_key = next(iter(self))
86+
super().__delitem__(evicted_key)
8287
if not self._evict_warned:
8388
self._evict_warned = True
8489
logger.warning("prompt_embed_cache exceeded maxsize=%d; evicted %r", self._maxsize, evicted_key)

‎tests/test_deployment_changes.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,26 @@ def test_prompt_embed_cache_default_is_bounded_default(self):
580580
assert isinstance(engine._prompt_embed_cache, _BoundedPromptEmbedCache)
581581
assert engine._prompt_embed_cache._maxsize == DEFAULT_PROMPT_EMBED_CACHE_MAXSIZE
582582

583+
def test_prompt_embed_cache_eviction_preserves_lru_order(self, caplog):
584+
from openwam.deploy.engine import _BoundedPromptEmbedCache
585+
586+
caplog.set_level("WARNING", logger="openwam.deploy.engine")
587+
cache = _BoundedPromptEmbedCache(maxsize=3)
588+
for key in ("probe", "a", "b", "c"):
589+
cache[key] = key
590+
591+
assert list(cache) == ["a", "b", "c"]
592+
593+
# Reads refresh recency, so "a" survives the next eviction.
594+
assert cache["a"] == "a"
595+
cache["d"] = "d"
596+
assert list(cache) == ["c", "a", "d"]
597+
598+
cache["e"] = "e"
599+
assert list(cache) == ["a", "d", "e"]
600+
warnings = [record for record in caplog.records if "prompt_embed_cache exceeded maxsize" in record.getMessage()]
601+
assert len(warnings) == 1
602+
583603
def test_prompt_embed_cache_maxsize_from_config(self):
584604
engine, _ = self._make_engine(prompt_cache_cfg={"enabled": True, "maxsize": 8})
585605
assert engine._prompt_embed_cache._maxsize == 8

0 commit comments

Comments
 (0)