From d834188dcd4e470357d5835c9d22b3de37a97a23 Mon Sep 17 00:00:00 2001 From: Hyeonsang Cho Date: Sat, 21 Nov 2026 20:01:55 +0900 Subject: [PATCH] fix(memory): rebuild the DeerMem index from the memory buckets only (#8463) The full retrieval-index rebuild at Gateway startup globbed `**/facts/**/*.md` under the storage root. The host's default root is the runtime home, which also holds every thread's sandbox-writable workspace (users/{id}/threads/{thread}/user-data/workspace). A fact-shaped file a sandbox wrote at .../workspace/agents/{agent}/facts/ passed validation and was indexed into that user's scope: memory_search served it, it never appeared in the canonical memory, delete_fact left the row, and every restart indexed it again. Any other workspace file below a facts/ directory logged a parse traceback and counted as a failed fact. Walk only the fact directories the scoped readers use: the legacy root bucket (agents/*/facts) and each user bucket (users/*/agents/*/facts). --- .../harness/deerflow/agents/memory/AGENTS.md | 3 ++ .../backends/deermem/deermem/core/storage.py | 8 +++- backend/tests/test_memory_storage_markdown.py | 48 +++++++++++++++++++ docs/guide/memory.md | 2 +- 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/backend/packages/harness/deerflow/agents/memory/AGENTS.md b/backend/packages/harness/deerflow/agents/memory/AGENTS.md index 3b1b85dbe0..36e418a005 100644 --- a/backend/packages/harness/deerflow/agents/memory/AGENTS.md +++ b/backend/packages/harness/deerflow/agents/memory/AGENTS.md @@ -69,6 +69,9 @@ client or the real storage, because the payload shape is the contract. files at any time. Storage updates it after the durable locks are released, and search falls back to substring matching until a rebuild succeeds. Recreate index files only for SQLite corruption codes; an operational error is not corruption. +- **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. - **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 e1eb861b86..7a3cceb539 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 @@ -14,6 +14,7 @@ import abc import copy import hashlib import importlib +import itertools import json import logging import math @@ -2137,7 +2138,12 @@ class FileMemoryStorage(MemoryStorage): synced_signatures: dict[tuple[str | None, str | None], tuple[Any, ...]] = {} if scopes is None: root = Path(self._config.storage_path) if self._config.storage_path else memory_file_path(self._config).parent - candidates = root.glob("**/facts/**/*.md") + # Only the fact directories the scoped readers use: the legacy root + # bucket and each user's bucket. The host's default root is the + # runtime home, which also holds every thread's sandbox-writable + # workspace (users/{id}/threads/...), so a wider walk would index + # files a sandbox wrote as that user's memory. + candidates = itertools.chain(root.glob("agents/*/facts/**/*.md"), root.glob("users/*/agents/*/facts/**/*.md")) # One signature per manifest: every agent bucket of a user shares its # memory.json, and _scope_signature reads only that file. manifest_signatures: dict[Path, tuple[Any, ...]] = {} diff --git a/backend/tests/test_memory_storage_markdown.py b/backend/tests/test_memory_storage_markdown.py index 7295a7314d..e13a0a8e81 100644 --- a/backend/tests/test_memory_storage_markdown.py +++ b/backend/tests/test_memory_storage_markdown.py @@ -1129,6 +1129,54 @@ def test_full_rebuild_index_accepts_original_email_user_scope(tmp_path: Path) -> assert retrieval.fact_ids == ["fact_01HZZZZZZZZZZZZZZZZZZZZZZZ"] +def test_full_rebuild_index_reads_only_the_memory_buckets(tmp_path: Path) -> None: + """The host's storage root is the runtime home, which also holds every thread's workspace. + + A sandbox can write a valid fact file into its workspace; the full rebuild + must not index it as the user's memory, and a stray ``facts/`` file there + is not a failed fact. + """ + + class RecordingRetrieval: + def __init__(self) -> None: + self.indexed: list[tuple[str, dict]] = [] + + def upsert(self, fact, *, scope, path): + self.indexed.append((fact["id"], scope)) + + def remove(self, fact_id, *, scope): + pass + + def search(self, query, *, scopes, top_k, mode, filters): + return [] + + retrieval = RecordingRetrieval() + scoped = FileMemoryStorage(DeerMemConfig(storage_path=str(tmp_path)), retrieval=retrieval) + scoped.upsert_fact({"id": "fact_user", "content": "user fact", "category": "context", "confidence": 0.9}, user_id="alice", agent_name="agent-a") + scoped.upsert_fact({"id": "fact_legacy", "content": "legacy fact", "category": "context", "confidence": 0.9}, user_id=None, agent_name="agent-a") + user_fact = next(tmp_path.glob("users/alice/agents/agent-a/facts/*/fact_user.md")) + legacy_fact = next(tmp_path.glob("agents/agent-a/facts/*/fact_legacy.md")) + for workspace, source, planted_id in [ + (tmp_path / "users" / "alice" / "threads" / "t1" / "user-data" / "workspace", user_fact, "fact_planted_user"), + (tmp_path / "threads" / "t1" / "user-data" / "workspace", legacy_fact, "fact_planted_legacy"), + ]: + planted = workspace / "agents" / "agent-a" / "facts" / "00" / f"{planted_id}.md" + planted.parent.mkdir(parents=True) + planted.write_text(source.read_text(encoding="utf-8").replace(source.stem, planted_id), encoding="utf-8") + stray = workspace / "docs" / "facts" / "notes.md" + stray.parent.mkdir(parents=True) + stray.write_text("# Project facts\n", encoding="utf-8") + retrieval.indexed.clear() + + result = scoped.rebuild_index() + + assert result == {"supported": True, "indexed": 2, "failed": 0} + assert sorted(retrieval.indexed, key=lambda item: item[0]) == [ + ("fact_legacy", {"userId": None, "agentName": "agent-a"}), + ("fact_user", {"userId": "alice", "agentName": "agent-a"}), + ] + + def test_full_rebuild_index_skips_fact_deleted_after_directory_listing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: class RecordingRetrieval: def __init__(self) -> None: diff --git a/docs/guide/memory.md b/docs/guide/memory.md index 25901f7176..ee55e06275 100644 --- a/docs/guide/memory.md +++ b/docs/guide/memory.md @@ -130,7 +130,7 @@ When `eviction_reserved_categories` includes `correction`, corrections take prio When `lastConfirmedAt` is absent, hybrid confirmation freshness and staleness review use `createdAt`. Repeated mentions in conversation do not refresh either timestamp. -File-backed memory now separates global user context from agent facts. Each user has one `memory.json` containing only the project-independent `user` and `history` summaries; every fact is a canonical Markdown file below `agents/{agent_name}/facts/`. Existing lead-agent middleware, API, Settings, import/export, and embedded-client calls that omit `agent_name` resolve inside DeerMem to the reserved `__default__` bucket. That bucket is outside the valid custom-agent name grammar, so a real custom agent named `lead-agent` has a separate fact repository and deleting a custom agent cannot delete a memory-only directory without `config.yaml`. Public agent identifiers are case-insensitive and canonicalized to lowercase. Runtime/API readers still receive a compatibility `facts` array for the selected/default agent, so the frontend does not read agent facts from `memory.json`; structured Markdown `source` metadata is projected to the historical string field at the MemoryManager boundary. An unscoped Clear All first migrates facts from unread legacy per-agent JSON without adopting its soon-to-be-cleared summaries, then removes shared summaries and facts from every agent bucket while preserving agent configuration files, so a later read cannot resurrect skipped legacy facts; an explicitly agent-scoped clear removes only that agent's facts. On first normal read, old facts embedded in the user JSON are migrated automatically to `__default__`; facts written to the earlier implicit `lead-agent` bucket are also moved when that directory is not a real custom agent. Migration and normal writes notify the configured retrieval adapter only after durable storage locks are released. DeerMem uses a scope-aware SQLite FTS5/BM25 adapter by default, stores only rebuildable derived index data under `.retrieval/` (or under `memory.backend_config.retrieval_index_path` when set; a relative value resolves against `storage_path`), and rebuilds it in the background during Gateway startup or lazily on the first scoped search. A corrupt derived index is recreated automatically. When several Gateway instances share one `storage_path`, point `retrieval_index_path` at instance-local disk: SQLite's WAL mode is unsupported on network filesystems, each instance re-syncs a user's index on its next search after a peer writes, and a declared multi-instance deployment (`deployment.multi_instance: true` / `DEER_FLOW_MULTI_INSTANCE=1`) that leaves the index under the memory root logs a warning at startup. The Helm chart mounts a Pod-local `emptyDir` for it. Set `memory.backend_config.retrieval_adapter` to an empty string to disable it and use the local substring fallback. Chinese tokenization is optional; install the backend `memory-zh` extra (`uv sync --extra memory-zh`) for jieba-assisted sub-phrase search. Journaled writes, a shared user lock, and optimistic user-memory revisions prevent silent lost updates. +File-backed memory now separates global user context from agent facts. Each user has one `memory.json` containing only the project-independent `user` and `history` summaries; every fact is a canonical Markdown file below `agents/{agent_name}/facts/`. Existing lead-agent middleware, API, Settings, import/export, and embedded-client calls that omit `agent_name` resolve inside DeerMem to the reserved `__default__` bucket. That bucket is outside the valid custom-agent name grammar, so a real custom agent named `lead-agent` has a separate fact repository and deleting a custom agent cannot delete a memory-only directory without `config.yaml`. Public agent identifiers are case-insensitive and canonicalized to lowercase. Runtime/API readers still receive a compatibility `facts` array for the selected/default agent, so the frontend does not read agent facts from `memory.json`; structured Markdown `source` metadata is projected to the historical string field at the MemoryManager boundary. An unscoped Clear All first migrates facts from unread legacy per-agent JSON without adopting its soon-to-be-cleared summaries, then removes shared summaries and facts from every agent bucket while preserving agent configuration files, so a later read cannot resurrect skipped legacy facts; an explicitly agent-scoped clear removes only that agent's facts. On first normal read, old facts embedded in the user JSON are migrated automatically to `__default__`; facts written to the earlier implicit `lead-agent` bucket are also moved when that directory is not a real custom agent. Migration and normal writes notify the configured retrieval adapter only after durable storage locks are released. DeerMem uses a scope-aware SQLite FTS5/BM25 adapter by default, stores only rebuildable derived index data under `.retrieval/` (or under `memory.backend_config.retrieval_index_path` when set; a relative value resolves against `storage_path`), and rebuilds it in the background during Gateway startup or lazily on the first scoped search. A rebuild reads only the fact directories of the memory buckets, never files below a thread's directory, so a fact-shaped file in a sandbox workspace is not indexed. A corrupt derived index is recreated automatically. When several Gateway instances share one `storage_path`, point `retrieval_index_path` at instance-local disk: SQLite's WAL mode is unsupported on network filesystems, each instance re-syncs a user's index on its next search after a peer writes, and a declared multi-instance deployment (`deployment.multi_instance: true` / `DEER_FLOW_MULTI_INSTANCE=1`) that leaves the index under the memory root logs a warning at startup. The Helm chart mounts a Pod-local `emptyDir` for it. Set `memory.backend_config.retrieval_adapter` to an empty string to disable it and use the local substring fallback. Chinese tokenization is optional; install the backend `memory-zh` extra (`uv sync --extra memory-zh`) for jieba-assisted sub-phrase search. Journaled writes, a shared user lock, and optimistic user-memory revisions prevent silent lost updates. FTS5 search selects the highest combined BM25, time-decay, and confidence scores across all matching facts before applying the requested result count. Requesting fewer results preserves the same ranking.