diff --git a/backend/packages/harness/deerflow/agents/memory/AGENTS.md b/backend/packages/harness/deerflow/agents/memory/AGENTS.md index ac847bce90..2db85ccf60 100644 --- a/backend/packages/harness/deerflow/agents/memory/AGENTS.md +++ b/backend/packages/harness/deerflow/agents/memory/AGENTS.md @@ -72,6 +72,8 @@ client or the real storage, because the payload shape is the contract. - **A full rebuild reads only the memory buckets.** The host's storage root is the runtime home, which also holds sandbox-writable thread workspaces; walking the whole root would index files a sandbox wrote as the user's memory. +- **The parsed-document cache is bounded.** A request can name any valid agent, + so a per-scope cache without a cap grows for the process lifetime. - **Sidecars do not touch canonical files.** Usage, audit and watermark data must not change a fact's timestamps or revisions. User delete and clear remove them. diff --git a/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/storage.py b/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/storage.py index 7a3cceb539..3a3070aef3 100644 --- a/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/storage.py +++ b/backend/packages/harness/deerflow/agents/memory/backends/deermem/deermem/core/storage.py @@ -24,6 +24,7 @@ import threading import time import uuid import weakref +from collections import OrderedDict from collections.abc import Iterator from contextlib import contextmanager from datetime import UTC, datetime @@ -50,6 +51,11 @@ from .paths import ( logger = logging.getLogger(__name__) DOCUMENT_VERSION = "2.0" +# Parsed documents kept in process, least recently used first out. The cache +# only saves a re-read: an evicted scope is read from its files again. Without +# a cap every (user, agent) scope a process ever touched stayed in memory, +# including scopes named only by a request's agent_name. +MEMORY_CACHE_MAX_SCOPES = 256 CORE_CATEGORIES = frozenset({"preference", "correction", "context", "goal", "behavior", "cognitive", "identity", "constraint", "decision", "other"}) @@ -639,7 +645,7 @@ class FileMemoryStorage(MemoryStorage): def __init__(self, config: DeerMemConfig, retrieval: RetrievalPort | None = None): self._config = config self._retrieval = retrieval - self._memory_cache: dict[tuple[str | None, str | None], tuple[dict[str, Any], tuple[Any, ...]]] = {} + self._memory_cache: OrderedDict[tuple[str | None, str | None], tuple[dict[str, Any], tuple[Any, ...]]] = OrderedDict() self._cache_lock = threading.Lock() self._scope_locks: weakref.WeakValueDictionary[tuple[str | None, str | None], threading.RLock] = weakref.WeakValueDictionary() self._retrieval_dirty_scopes: set[tuple[str | None, str | None]] = set() @@ -983,6 +989,13 @@ class FileMemoryStorage(MemoryStorage): def _cache_key(agent_name: str | None = None, *, user_id: str | None = None) -> tuple[str | None, str | None]: return (user_id, agent_name) + def _cache_document_locked(self, key: tuple[str | None, str | None], document: dict[str, Any], signature: tuple[Any, ...]) -> None: + """Store a scope's document as the most recent entry; the caller holds ``_cache_lock``.""" + self._memory_cache[key] = (copy.deepcopy(document), signature) + self._memory_cache.move_to_end(key) + while len(self._memory_cache) > MEMORY_CACHE_MAX_SCOPES: + self._memory_cache.popitem(last=False) + def _scope_lock(self, key: tuple[str | None, str | None]) -> threading.RLock: with self._cache_lock: return self._scope_locks.setdefault(key, threading.RLock()) @@ -1632,10 +1645,11 @@ class FileMemoryStorage(MemoryStorage): with self._cache_lock: cached = self._memory_cache.get(key) if cached is not None and cached[1] == signature: + self._memory_cache.move_to_end(key) return copy.deepcopy(cached[0]) document = self._read_document(path, agent_name, user_id=user_id) with self._cache_lock: - self._memory_cache[key] = (copy.deepcopy(document), signature) + self._cache_document_locked(key, document, signature) return copy.deepcopy(document) def reload(self, agent_name: str | None = None, *, user_id: str | None = None, _rebuild_retrieval: bool = True) -> dict[str, Any]: @@ -1661,7 +1675,7 @@ class FileMemoryStorage(MemoryStorage): signature = self._scope_signature(path, agent_name) document = self._read_document(path, agent_name, user_id=user_id) with self._cache_lock: - self._memory_cache[key] = (copy.deepcopy(document), signature) + self._cache_document_locked(key, document, signature) if _rebuild_retrieval and agent_name is not None and self._retrieval is not None: self.rebuild_index([{"userId": user_id, "agentName": agent_name}]) return copy.deepcopy(document) @@ -1749,7 +1763,7 @@ class FileMemoryStorage(MemoryStorage): if int(memory_file.get("revision") or 0) != pre_revision: committed = (pre_revision, signature) with self._cache_lock: - self._memory_cache[key] = (copy.deepcopy(document), signature) + self._cache_document_locked(key, document, signature) except MemoryRevisionConflict: raise except (OSError, ValueError, MemoryStorageCorruption) as exc: diff --git a/backend/tests/test_memory_storage_markdown.py b/backend/tests/test_memory_storage_markdown.py index e13a0a8e81..5be77f4f6a 100644 --- a/backend/tests/test_memory_storage_markdown.py +++ b/backend/tests/test_memory_storage_markdown.py @@ -142,6 +142,46 @@ def test_cached_load_does_not_scan_all_fact_files(storage: FileMemoryStorage, mo assert storage.load("agent-a", user_id="alice")["facts"][0]["content"] == "Project uses Python 3.12" +def test_memory_cache_keeps_only_the_most_recently_used_scopes(storage: FileMemoryStorage, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(storage_module, "MEMORY_CACHE_MAX_SCOPES", 2) + # A commit drops the user's cached scopes, so each scope here is its own user. + assert storage.save(_memory_with_fact("A"), "agent-a", user_id="alice") + assert storage.save(_memory_with_fact("B"), "agent-a", user_id="bob") + assert list(storage._memory_cache) == [("alice", "agent-a"), ("bob", "agent-a")] + reads: list[str | None] = [] + read_document = storage._read_document + + def counting_read(path: Path, agent_name: str | None, *, user_id: str | None) -> dict: + reads.append(user_id) + return read_document(path, agent_name, user_id=user_id) + + monkeypatch.setattr(storage, "_read_document", counting_read) + + # A cache hit marks the scope as recently used without reading its files. + assert storage.load("agent-a", user_id="alice")["facts"][0]["content"] == "A" + assert reads == [] + # A scope a request only names (no files) still takes a cache slot, so it + # evicts the least recently used scope instead of growing the cache. + assert storage.load("agent-unknown", user_id="carol")["facts"] == [] + assert list(storage._memory_cache) == [("alice", "agent-a"), ("carol", "agent-unknown")] + + # An evicted scope is read from its files again, with the same document. + assert storage.load("agent-a", user_id="bob")["facts"][0]["content"] == "B" + assert reads == ["carol", "bob"] + assert list(storage._memory_cache) == [("carol", "agent-unknown"), ("bob", "agent-a")] + + # A save caches the document it committed as the most recent scope. + assert storage.save(_memory_with_fact("A2"), "agent-a", user_id="alice") + assert list(storage._memory_cache) == [("bob", "agent-a"), ("alice", "agent-a")] + assert reads == ["carol", "bob", "alice"] + assert storage.load("agent-a", user_id="alice")["facts"][0]["content"] == "A2" + assert reads == ["carol", "bob", "alice"] + + # A reload replaces a scope that is still cached and makes it the most recent. + assert storage.reload("agent-a", user_id="bob")["facts"][0]["content"] == "B" + assert list(storage._memory_cache) == [("alice", "agent-a"), ("bob", "agent-a")] + + @pytest.mark.parametrize("read", ["load", "reload"]) def test_unlocked_read_skips_fact_deleted_after_directory_listing(storage: FileMemoryStorage, monkeypatch: pytest.MonkeyPatch, read: str) -> None: for fact_id in ("fact_keep", "fact_drop"):