mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(memory): bound DeerMem's in-process document cache (#8480)
FileMemoryStorage kept one deep-copied document per (user, agent) scope it had ever read, with no cap. A scope that is only read is never evicted, and GET /api/memory accepts any well-formed agent_name, so one user could grow the cache by a document per request for the life of the process. The cache is now least recently used with a cap of 256 scopes. A hit or a write refreshes its scope, and an evicted scope is read from its files again.
This commit is contained in:
parent
aa78349751
commit
a9b5dd80f8
@ -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.
|
||||
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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"):
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user