Skip to content

Build and run agents you can see, understand and trust.

fix(state): skip oversized read-cache entries (#2534)

WuWenbodf4269fae3af
diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.py
index 0c44922d1..7b806effc 100644
--- a/src/agentscope/state/_state.py
+++ b/src/agentscope/state/_state.py
@@ -124,6 +124,11 @@ class ToolContext(BaseModel):
if entry.file_path != file_path
]
+ # An entry that cannot fit even in an empty cache must not evict
+ # unrelated entries or make the configured byte limit ineffective.
+ if new_entry_bytes > self.max_cache_bytes:
+ return
+
# Evict the oldest entries if exceeding max_cache_files
while len(self.read_file_cache) >= self.max_cache_files:
self.read_file_cache.pop(0)
diff --git a/tests/builtin_file_cache_test.py b/tests/builtin_file_cache_test.py
index 519c74bfd..6aedb28f1 100644
--- a/tests/builtin_file_cache_test.py
+++ b/tests/builtin_file_cache_test.py
@@ -248,6 +248,31 @@ class FileCacheTest(IsolatedAsyncioTestCase):
self.assertIn(files[2], cached_paths)
self.assertIn(files[3], cached_paths)
+ async def test_oversized_file_is_not_cached(self) -> None:
+ """An oversized entry must not exceed the cache byte limit."""
+ context = ToolContext()
+ context.max_cache_bytes = 1.0
+
+ await context.cache_file(
+ file_path="small.txt",
+ lines=["a" * 512],
+ mtime=1.0,
+ )
+ await context.cache_file(
+ file_path="oversized.txt",
+ lines=["b" * 2048],
+ mtime=1.0,
+ )
+
+ self.assertEqual(
+ [entry.file_path for entry in context.read_file_cache],
+ ["small.txt"],
+ )
+ self.assertLessEqual(
+ sum(entry.bytes for entry in context.read_file_cache),
+ context.max_cache_bytes,
+ )
+
async def test_cache_hit_refreshes_lru_recency(self) -> None:
"""Test cache hits keep recently used files from being evicted."""
self.state.tool_context.max_cache_files = 3