deer-flow/backend/tests/test_deermem_self_contained.py
qin-chenghan ad45f59d66
feat(memory): pluggable memory abstraction with self-contained DeerMem backend (#4122)
* feat(memory): pluggable + self-contained memory system (MemoryManager plan phases 1 & 2)

Phase 1 — Pluggable (steps 0-10):
- ABC MemoryManager (9 methods) + singleton factory + drop-in backend discovery
- DeerMem default backend with core/ (storage/queue/updater/prompt/message_processing)
- NoopMemoryManager backend (proves pluggability)
- All call sites (middleware/hook/prompt/gateway/client/app) routed through manager
- hasattr capability probing for DeerMem-internal methods (no hard imports)
- MemoryConfig gains manager_class field; shared vs DeerMem-private annotated

Phase 2 — Self-contained DeerMem (steps 11-18):
- backend_config passthrough + DeerMemConfig (all DeerMem-private fields moved off MemoryConfig)
- DI: DeerMem owns storage/queue/updater/llm as instance attributes (no global singletons)
- Storage independence: core/paths.py with own root (~/.deermem or ),
  factory auto-injects deer-flow's runtime_home() as absolute base_dir (zero-config)
- LLM independence: core/llm.py via langchain init_chat_model (no create_chat_model)
- Trace independence: optional tracing_callback replaces inject_langfuse_metadata/request_trace_context
- Message processing independence: hide_from_ui default-skip + optional should_keep_hidden_message hook
- Internal imports → relative (only deer_mem.py ABC import is host-relative)
- Carrier (deer_mem.py adapter) / portable (deermem/ config+core) split
- New tests: test_deermem_self_contained + test_memory_manager_pluggable; all memory tests migrated
- Other-agent demo: samples/other_agent_demo/ + automated portability test
- config.example.yaml memory section updated to phase-2 schema

* feat(memory): port consolidation + staleness fix into self-contained DeerMem; phase-2 host hooks

Port upstream #3996 (memory consolidation) and #3993 (staleness KeyError fix)
from origin/MemoryManager into the pluggable, self-contained DeerMem structure
(backends/deermem/deermem/), adapted to the DI MemoryUpdater (config injected,
not get_memory_config globals):

- DeerMemConfig: add consolidation_enabled (opt-in, default false) /
  consolidation_min_facts / consolidation_max_groups_per_cycle /
  consolidation_max_sources
- prompt.py: factsToConsolidate JSON field + {consolidation_section} placeholder
  + CONSOLIDATION_PROMPT constant
- updater.py: _coerce_source_confidence / _select_consolidation_candidates /
  _build_consolidation_section module helpers (matching the existing
  _select_stale_candidates style); consolidation normalization in
  _normalize_memory_update_data; consolidation apply in _apply_updates (after
  max_facts trim, with apply-time guardrails mirroring staleness); staleness
  KeyError fix (f["id"] -> f.get("id") is not None) applied to both the
  staleness guardrail and the consolidation allowed_source_ids comprehension
- config.example.yaml: consolidation section under memory.backend_config
- tests/test_memory_consolidation.py: 40 DI-adapted tests (running, not skipped)
  incl. the staleness KeyError regression

Also includes in-flight phase-2 host-integration work: storage_path semantics
(any absolute/relative value = root dir) and host-default tracing_callback /
should_keep_hidden_message hooks injected into backend_config by the factory.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(memory): add noop backend template and backends guide

- backends/noop/: complete drop-in template (config.py with zero deer-flow
  imports, noop_manager.py with a 6-step new-backend walkthrough in its
  docstring, commented optional fact-CRUD capabilities).
- backends/README.md: which files to touch when adding/swapping a backend,
  the 5-item backend contract, and common pitfalls.
- manager.py: generalize backend examples in comments (drop mem0-specific
  references).

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(frontend): guard formatTimeAgo against invalid timestamps

Return a neutral placeholder when the input date is invalid (e.g. an empty lastUpdated from a backend with no memories) instead of throwing 'Invalid time value' from date-fns.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(memory): wire tool-driven memory mode through the MemoryManager ABC

tools.py (memory_search/add/update/delete) now calls get_memory_manager()
instead of the removed host memory module, so tool mode (memory.mode: tool)
works for any backend. DeerMem.search is implemented (case-insensitive
substring match, ranked by confidence) as a stand-in for the planned
semantic retrieval; noop.search returns [] (unchanged). Fact-CRUD tools
use getattr+callable probing -- backends lacking those ops (noop) get a
clear JSON error instead of crashing.

Tests: test_memory_tools rewired to mock the manager (handler tests) +
TestModeGating retained; test_memory_search now covers DeerMem.search;
pluggable stubs test updated (search no longer a stub).

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: resolve lint errors (import sorting, type annotation quotes, E402 in skipped tests)

* docs: restore explanatory comments in config.example.yaml memory section

* fix(security): port html-escape memory facts fix (#4097) to vendored DeerMem prompt.py

* fix(memory): address review + port dropped upstream memory fixes

Review blockers (vendored DeerMem):
- #4044 restore _escape_memory_for_prompt (current_memory blob in
  MEMORY_UPDATE_PROMPT) - prevents </current_memory> breakout
- #4028 html.escape staleness-section cat/content in _build_staleness_section
- #4119 add _escape_summary for injection-path summaries (Work/Personal/
  Current Focus/Recent/Earlier/Background)
- default-model silent no-op: factory injects host default chat model via a
  new host_llm slot (create_chat_model(name=None)); DeerMem prefers host_llm
  over build_llm(model). Zero-config extraction works out of the box again
- MemoryConfigResponse: fix stale docstring (backend-agnostic shape; DeerMem
  knobs live under backend_config, not top-level - restoring flat would
  re-couple the API to DeerMem). Frontend audited: does not read /memory/config
- _host_default_tracing_callback: restore langfuse assistant_id/environment
- search: push category onto the ABC signature; DeerMem filters BEFORE the
  top_k slice (was filtered client-side after slicing -> starved results)
- _do_update_memory_sync: split into wrapper+impl; bind trace_id into the
  request-trace ContextVar on the Timer/executor worker via a new
  trace_context_manager host hook (None trace_id left unbound - no fabrication)
- client.py fact-CRUD now passes user_id (was writing to the global bucket
  while get_memory reads per-user)
- _resolve_manager_class: fail-fast (raise ValueError) on an unresolved
  explicit manager_class instead of silently falling back to DeerMem (memory is
  persistent state - a wrong store is a silent data-integrity footgun)

Upstream memory fixes dropped by the host->vendored rename conflict, re-ported
to backends/deermem/deermem/core/ (+ deer_mem.py):
- #4073 queue busy-timer-spin -> _reprocess_pending flag (core/queue.py)
- #4074 null source.confidence in staleness -> _coerce_source_confidence
  (core/updater.py: _build_staleness_section + _apply_updates stale sort)
- #4075 factsToRemove is optional (drop from _REQUIRED_MEMORY_UPDATE_TOP_LEVEL_KEYS)
- #4076 null confidence in search ranking -> _coerce_source_confidence
  (deer_mem.py DeerMem.search)

host_llm + trace_context_manager are host-injected via backend_config (factory
in manager.py), keeping backends/deermem/ at exactly one `from deerflow` line
(the ABC contract) - portability test preserved.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: resolve lint errors (F541 f-string without placeholders, E501 line too long)

* fix(memory): restore hide_from_ui clarification preservation, expose mode

Two memory-system fixes (F541/E501 lint was already fixed on this branch):

- filter_messages_for_memory: restore default preservation of well-formed
  human_input_response clarification answers (v2 regression). The
  self-containment refactor made the bare function skip ALL hide_from_ui when
  no hook was passed, but upstream preserves well-formed clarification
  responses by default (test_hide_from_ui_human_input_response_is_preserved).
  Inline a host-agnostic _is_human_clarification_response mirror of
  read_human_input_response as the default keep-decision; the host-injected
  should_keep_hidden_message hook still overrides (production path unchanged).
  Portable package stays zero `from deerflow`.

- /memory/config: expose `mode` (middleware|tool) in MemoryConfigResponse +
  the config/status endpoints + client.get_memory_config. mode is a host-
  shared, behavior-determining field missing from the response projection.
  Sync tests (mock .mode; e2e assert mode present).

- Align manager_class field docstring with fail-fast behavior.

Tests: filter/self-contained/portability (35) + memory-config (4) pass;
ruff clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): resolve ruff format failures in memory module + tests

`make lint` runs `ruff format --check` in addition to `ruff check`; 8 memory
files had pending format changes -- 7 pre-existing (deer_mem, updater, tools,
test_memory_queue/router/search/tools) + message_processing from the
hide_from_ui fix. Apply `ruff format`: whitespace/wrapping only, no logic
change. 109 memory tests pass; ruff check + format --check both clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address PR review - legacy field migration, fact_id contract, path/docs

Address willem-bd's review on PR head bc8bf0d4 (risk:high, persistent state):

- config: auto-migrate pre-abstraction top-level memory.* DeerMem fields
  (storage_path, max_facts, debounce_seconds, model_name, token_counting,
  staleness_*, consolidation_*) into backend_config on load + warn, so an
  upgrade does NOT silently revert customized settings (was: silent
  extra='ignore' drop). model_name -> backend_config.model.model. Unknown
  top-level keys warned.
- factory: resolve a relative backend_config.storage_path against runtime_home()
  (base_dir-relative, CWD-independent) to preserve pre-abstraction semantics;
  paths.py stays portable (no runtime_home import).
- tools: memory_add uses the fact_id returned directly by create_fact instead of
  re-deriving it via content-key matching (coupled the tool to the backend's
  content normalization; could misreport a storage cap). create_fact now returns
  (memory_data, fact_id); gateway/client/tool updated. Fix terse
  {"error":"content"} -> {"error":"empty content"}.
- app.py: update stale token_counting=="char" warm-up comment to point at
  manager.warm (DeerMem.warm re-checks char and returns early).
- router: comment explaining reload_memory silent fallback vs fact 501 asymmetry
  (read-only degrade vs write fail-loud).
- CHANGELOG: document breaking changes (/memory/config + client.get_memory_config
  shape flat->backend_config; custom storage_class path moved + __init__ must
  accept config) and the legacy-field auto-migration.
- tests: add regression test pinning the per-user memory path
  ({storage_path}/users/{safe_user_id}/memory.json == host make_safe_user_id)
  across the abstraction; update create_fact mocks for (memory_data, fact_id).

Tests: 273 passed (memory suite); ruff check + format clean.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address PR review - storage_path, max_facts, tracing, parsing

Six review findings (willem-bd), each verified against upstream:

- storage_path semantics (file -> root dir): migration drops file-style
  (.json) legacy values with a warning; factory raises if storage_path
  resolves to an existing file (avoid silent NotADirectoryError write
  failure). CHANGELOG + config.example.yaml comment updated.
- create_memory_fact enforces max_facts again (via _trim_facts_to_max) and
  returns (memory, None) when the cap evicts the new fact; memory_add tool
  reports "not stored", client raises ValueError, POST /memory/facts -> 409.
- max_facts trim uses _coerce_source_confidence (was raw f.get("confidence",
  0) -> TypeError on non-float imported/legacy confidence, swallowed as
  silent update failure).
- memory-tracing assistant_id restored to "memory_agent" (was "lead-agent"
  copy-paste; matches upstream + DeerMem run_name).
- _is_human_clarification_response cross-checked against
  read_human_input_response (drift guard test).
- empty-string legacy values skipped silently in migration (narrow fix, not
  broad "if not value" which would skip explicit bool False).

8 new regression tests. make lint + 406 memory tests pass.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(memory): address internal review - storage fail-fast, build_llm degrade, config warn, noop template

Addresses 4 findings from the PR #4122 internal supplemental review
(parallel to willem-bd's review, no overlap):

- create_storage fail-fast: a misspelled/unimportable storage_class now
  raises ValueError instead of silently falling back to FileMemoryStorage.
  Memory is persistent state, so a wrong store is a data-integrity footgun;
  mirrors the existing manager_class resolution policy. (storage.py)

- noop template create_fact signature: the commented template used
  keyword-only `content` and returned a bare dict, while DeerMem's actual
  create_fact takes positional `content` and returns tuple[dict, str|None]
  (the memory_add tool passes content positionally; gateway/client/tools all
  tuple-unpack). A backend copied from the template would 500 on fact-CRUD.
  Template fixed; delete_fact/update_fact templates left (callers compatible).
  (noop_manager.py)

- build_llm graceful degrade: wrap init_chat_model in try/except, degrade to
  None + WARNING on failure (mirroring _host_default_llm) so a misconfigured
  explicit model does not crash app startup -- non-LLM memory ops still work
  and an update raises at runtime with the error logged. (llm.py)

- from_backend_config unknown-key warning: log a WARNING for unknown
  backend_config keys (mirrors the host layer's load_memory_config_from_dict)
  so a typo like `storage_pat` does not silently fall back to the default and
  write memory to an unintended location. (config.py)

Tests: rewrote 3 create_storage fallback tests to expect ValueError; added 4
tests (build_llm zero-config/degrade, from_backend_config warn/silent).
make lint green; full memory suite passes.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: lllyfff <2281215061@qq.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: lllyfff <122260771+lllyfff@users.noreply.github.com>
2026-07-15 11:21:04 +08:00

399 lines
18 KiB
Python

"""Phase-2 (self-contained DeerMem) tests.
Covers: DI construction (owns storage/updater/queue/llm), zero-config defaults,
``trace_id`` threading to the optional ``tracing_callback``, langfuse being
optional, ``hide_from_ui`` default-skip + hook-keep, empty ``storage_class``
(portable default), and portability -- ``backends/deermem/`` has exactly one
``from deerflow`` line (the ABC contract) and can be vendored into another agent
by copying the folder and repointing that one line.
Storage is isolated via ``$DEERMEM_DATA_DIR`` -> ``tmp_path``; the LLM is a fake
injected onto the updater so no network is needed.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
from langchain_core.messages import AIMessage, HumanMessage
from deerflow.agents.memory.backends.deermem.deer_mem import DeerMem
from deerflow.agents.memory.backends.deermem.deermem.core.message_processing import (
filter_messages_for_memory,
)
from deerflow.agents.memory.backends.deermem.deermem.core.storage import FileMemoryStorage
from deerflow.agents.memory.backends.deermem.deermem.core.updater import _trim_facts_to_max
@pytest.fixture
def deermem_data_dir(tmp_path, monkeypatch):
"""Isolate DeerMem storage under tmp_path via $DEERMEM_DATA_DIR."""
d = tmp_path / "deermem_data"
d.mkdir()
monkeypatch.setenv("DEERMEM_DATA_DIR", str(d))
yield d
class _FakeLLM:
"""Returns a fixed memory-update JSON so no real LLM/network is needed."""
def __init__(self, payload: str | None = None) -> None:
self._payload = payload or '{"user":{},"history":{},"newFacts":[],"factsToRemove":[]}'
def invoke(self, prompt, config=None):
return type("R", (), {"content": self._payload})()
def _deermem_with_fake_llm(backend_config=None, payload=None) -> DeerMem:
dm = DeerMem(backend_config=backend_config)
fake = _FakeLLM(payload)
dm._llm = fake
dm._updater._llm = fake
return dm
def test_di_construction_owns_dependencies():
dm = DeerMem(backend_config={"max_facts": 50, "storage_path": "/tmp/x"})
assert dm._config.max_facts == 50
assert dm._storage is not None and dm._updater is not None and dm._queue is not None
# dependencies are wired (DI), not globals:
assert dm._updater._storage is dm._storage
assert dm._queue._updater is dm._updater
def test_zero_config_defaults_run_non_llm_ops(deermem_data_dir):
dm = DeerMem(backend_config=None) # zero config
assert dm._llm is None # no model -> no LLM
dm.import_memory(
{"version": "1.0", "lastUpdated": "", "user": {}, "history": {}, "facts": [{"id": "f", "content": "x", "category": "c", "confidence": 0.5, "createdAt": "", "source": "m"}]},
user_id="u",
)
assert "x" in dm.get_context(user_id="u")
assert dm.get_memory(user_id="u")["facts"][0]["content"] == "x"
def test_trace_id_threads_through_to_tracing_callback(deermem_data_dir):
calls = []
def tracer(cfg, *, thread_id, user_id, trace_id, model_name):
calls.append((thread_id, trace_id, model_name))
dm = _deermem_with_fake_llm({"tracing_callback": tracer, "model": {"provider": "openai", "model": "gpt-x", "api_key": "k", "base_url": "u"}})
dm.add(
thread_id="t1",
messages=[HumanMessage(content="hi"), AIMessage(content="hello")],
agent_name=None,
user_id="u1",
trace_id="trace-42",
)
dm._queue.flush()
assert calls and calls[0] == ("t1", "trace-42", "gpt-x")
def test_tracing_callback_optional_no_langfuse(deermem_data_dir):
dm = _deermem_with_fake_llm({"model": {"provider": "openai", "model": "gpt-x", "api_key": "k", "base_url": "u"}})
assert dm._config.tracing_callback is None # langfuse not hard-required
dm.add(
thread_id="t2",
messages=[HumanMessage(content="hi"), AIMessage(content="hello")],
agent_name=None,
user_id="u2",
trace_id="t-99",
)
dm._queue.flush() # no callback, no error, update completes
def test_hide_from_ui_default_skip_hook_keeps():
hidden = HumanMessage(content="secret", additional_kwargs={"hide_from_ui": True})
normal = HumanMessage(content="hi")
ai = AIMessage(content="hello")
# default (no hook) -> hide_from_ui skipped
assert hidden not in filter_messages_for_memory([hidden, normal, ai])
# hook returns True -> hidden kept
assert hidden in filter_messages_for_memory([hidden, normal, ai], should_keep_hidden_message=lambda ak: True)
def test_storage_class_empty_uses_filememorystorage():
# empty storage_class (default) -> FileMemoryStorage directly, no importlib (portable, zero noise)
dm = DeerMem(backend_config=None)
assert dm._config.storage_class == ""
assert isinstance(dm._storage, FileMemoryStorage)
def test_portability_only_abc_contract_imports_deerflow():
"""backends/deermem/ has exactly ONE `from deerflow` line: the ABC contract in deer_mem.py."""
import deerflow.agents.memory.backends.deermem as pkg
root = Path(pkg.__file__).parent
deerflow_imports = []
for p in root.rglob("*.py"):
for line in p.read_text(encoding="utf-8").splitlines():
s = line.strip()
if s.startswith("from deerflow") or s.startswith("import deerflow"):
deerflow_imports.append((p.relative_to(root).as_posix(), s))
assert len(deerflow_imports) == 1, deerflow_imports
assert deerflow_imports[0][0] == "deer_mem.py"
assert "memory.manager import MemoryManager" in deerflow_imports[0][1]
# Minimal vendored host contract (what another agent would ship). DeerMem only
# needs this ABC -- nothing else from a host.
_VENDORED_MANAGER_PY = '''
"""Vendored host contract (minimal ABC) for the portability demo."""
from abc import ABC, abstractmethod
from typing import Any
class MemoryManager(ABC):
def __init__(self, backend_config: dict | None = None) -> None:
self._backend_config = backend_config
@abstractmethod
def add(self, thread_id, messages, *, agent_name=None, user_id=None, trace_id=None) -> None: ...
@abstractmethod
def add_nowait(self, thread_id, messages, *, agent_name=None, user_id=None) -> None: ...
@abstractmethod
def get_context(self, user_id, *, agent_name=None, thread_id=None) -> str: ...
@abstractmethod
def search(self, query, top_k=5, *, user_id=None, agent_name=None) -> list: ...
@abstractmethod
def get_memory(self, *, user_id=None, agent_name=None) -> dict: ...
@abstractmethod
def delete_memory(self, *, user_id=None, agent_name=None) -> None: ...
@abstractmethod
def clear_memory(self, *, user_id=None, agent_name=None) -> dict: ...
@abstractmethod
def import_memory(self, memory_data, *, user_id=None, agent_name=None) -> dict: ...
@abstractmethod
def export_memory(self, *, user_id=None, agent_name=None) -> dict: ...
'''
def test_portability_vendor_to_other_agent(tmp_path, monkeypatch):
"""Copy backends/deermem/ into a temp package, repoint the ONE ABC import to
a vendored manager, import, and run a round-trip -- proves copy + 1-line +
run portability (zero deerflow dependency at runtime)."""
import importlib
import shutil
import deerflow.agents.memory.backends.deermem as pkg
src = Path(pkg.__file__).parent
# Vendored host package with a minimal manager.py (the contract).
host_pkg = tmp_path / "otheragent"
host_pkg.mkdir()
(host_pkg / "__init__.py").write_text("", encoding="utf-8")
(host_pkg / "manager.py").write_text(_VENDORED_MANAGER_PY, encoding="utf-8")
# Copy the DeerMem backend folder.
dst_pkg = tmp_path / "otheragent_deermem"
shutil.copytree(src, dst_pkg)
# Repoint the single ABC-contract import line to the vendored manager.
deer_mem_file = dst_pkg / "deer_mem.py"
text = deer_mem_file.read_text(encoding="utf-8")
assert "from deerflow.agents.memory.manager import MemoryManager" in text
text = text.replace(
"from deerflow.agents.memory.manager import MemoryManager",
"from otheragent.manager import MemoryManager",
)
deer_mem_file.write_text(text, encoding="utf-8")
monkeypatch.setenv("DEERMEM_DATA_DIR", str(tmp_path / "data"))
monkeypatch.syspath_prepend(str(tmp_path))
try:
mod = importlib.import_module("otheragent_deermem.deer_mem")
assert hasattr(mod, "DeerMem")
dm = mod.DeerMem(backend_config=None) # zero config, self._llm=None
dm.import_memory(
{"version": "1.0", "lastUpdated": "", "user": {}, "history": {}, "facts": [{"id": "f", "content": "y", "category": "c", "confidence": 0.5, "createdAt": "", "source": "m"}]},
user_id="ua",
)
assert "y" in dm.get_context(user_id="ua")
finally:
for k in [k for k in list(sys.modules) if k.startswith("otheragent_deermem") or k == "otheragent"]:
sys.modules.pop(k, None)
def test_per_user_memory_path_matches_host_safe_user_id(deermem_data_dir):
"""Pin the per-user memory path across the abstraction.
DeerMem writes memory to ``{storage_path}/users/{safe_user_id}/memory.json``
where ``safe_user_id`` is byte-identical to the host's ``make_safe_user_id``.
The factory injects ``runtime_home()`` (= base_dir) as ``storage_path``, so
the on-disk path is ``{base_dir}/users/{uid}/memory.json`` -- identical to
pre-abstraction. This locks that equivalence so a future change to DeerMem's
path / safe_user_id logic can't silently orphan existing per-user memory
(risk:high, persistent state).
"""
from deerflow.config.paths import make_safe_user_id
user_id = "test-user-123@example.com"
# storage_path mirrors what the host factory injects (runtime_home / base_dir)
dm = DeerMem(backend_config={"storage_path": str(deermem_data_dir)})
dm.create_fact("User prefers concise answers", category="preference", user_id=user_id)
expected_safe = make_safe_user_id(user_id)
expected_file = deermem_data_dir / "users" / expected_safe / "memory.json"
assert expected_file.is_file(), f"memory not at expected per-user path: {expected_file}"
# DeerMem used the host-identical safe_user_id (not some other encoding).
user_dirs = [p.name for p in (deermem_data_dir / "users").iterdir() if p.is_dir()]
assert user_dirs == [expected_safe], f"safe_user_id diverged from host: {user_dirs}"
def test_trim_facts_to_max_coerces_non_float_confidence():
"""Non-float stored confidence must not crash the max_facts trim sort.
Regression: the vendored copy used ``key=lambda f: f.get("confidence", 0)``
which raised TypeError comparing None/str against float once ``len > max_facts``
(legacy / imported facts with abnormal confidence). This is the #4034 intent
that the module-skipped test files never exercised against the vendored
updater; pinning it here so the rename can't silently drop the coercion again.
"""
facts = [
{"id": "a", "confidence": None},
{"id": "b", "confidence": "0.9"}, # numeric string
{"id": "c", "confidence": 0.8},
{"id": "d", "confidence": "high"}, # non-numeric
]
# No TypeError; coerced ranking: b("0.9"->0.9) > c(0.8) > a(None->0.5)=d("high"->0.5).
kept = _trim_facts_to_max(facts, max_facts=2)
assert [f["id"] for f in kept] == ["b", "c"]
# Below the cap -> returned unchanged (no sort, no crash).
assert _trim_facts_to_max(facts, max_facts=10) == facts
def test_create_fact_trims_to_max_and_signals_eviction(deermem_data_dir):
"""create_fact enforces max_facts and signals eviction via None fact_id.
Regression: the vendored ``create_memory_fact`` only appended (no trim), so
manual / tool adds could grow memory past max_facts. Now it trims (highest
confidence wins) and returns ``None`` when the cap evicts the new fact, so
the tool reports "not stored" instead of a dangling id + false "added".
"""
# DeerMemConfig enforces max_facts >= 10, so fill the cap with 10 high-conf facts.
dm = DeerMem(backend_config={"max_facts": 10, "storage_path": str(deermem_data_dir)})
for i in range(10):
_, fid = dm.create_fact(f"high{i}", category="context", confidence=0.9, user_id="u1")
assert fid is not None
# Cap is full (10 facts); a lower-confidence 11th is evicted, not stored.
memory_data, evicted_id = dm.create_fact("low_evicted", category="context", confidence=0.1, user_id="u1")
assert evicted_id is None
assert "low_evicted" not in {f["content"] for f in memory_data["facts"]}
assert len(memory_data["facts"]) == 10
def test_search_survives_non_float_confidence(deermem_data_dir):
"""DeerMem.search ranks by _coerce_source_confidence, so non-float stored
confidence (null / string / non-numeric, reachable via import / legacy) must
not crash the sort. Re-adds the regression guard deleted with the monolithic
test_search_memory_facts_sort_survives_non_float_stored_confidence."""
dm = DeerMem(backend_config={"storage_path": str(deermem_data_dir)})
# create_fact validates confidence to float, so seed non-float via import
# (simulating imported / legacy data that bypasses _validate_confidence).
dm.import_memory(
{
"user": {},
"history": {},
"facts": [
{"id": "a", "content": "alpha matching query", "confidence": None},
{"id": "b", "content": "bravo matching query", "confidence": "0.9"},
{"id": "c", "content": "charlie matching query", "confidence": "high"},
],
},
user_id="u1",
)
results = dm.search("query", top_k=10, user_id="u1")
# No TypeError; all three match "query"; ranked by coerced confidence desc:
# b("0.9"->0.9) > a(None->0.5)=c("high"->0.5), stable so a before c.
assert [r["id"] for r in results] == ["b", "a", "c"]
def test_is_human_clarification_response_matches_host_read():
"""The standalone mirror must agree with the host's read_human_input_response
so hidden-message filtering doesn't diverge between production (host hook) and
standalone / test (mirror default). Pins drift (#5)."""
from deerflow.agents.human_input import read_human_input_response
from deerflow.agents.memory.backends.deermem.deermem.core.message_processing import _is_human_clarification_response
def payload(**overrides):
base = {"version": 1, "kind": "human_input_response", "source": "s", "request_id": "r", "value": "v", "response_kind": "text"}
base.update(overrides)
return {"human_input_response": base}
cases = [
{},
{"human_input_response": {}},
payload(), # valid text response
payload(response_kind="option", option_id="o1"), # valid option response
payload(response_kind="option"), # option without option_id -> not valid
payload(value=""), # empty value -> not valid
payload(source=""), # empty source -> not valid
payload(version=2), # wrong version -> not valid
payload(kind="other"), # wrong kind -> not valid
{"human_input_response": "not a mapping"},
{"other_key": 1}, # no human_input_response key
]
for ak in cases:
host_keeps = read_human_input_response(ak) is not None
mirror_keeps = _is_human_clarification_response(ak)
assert host_keeps == mirror_keeps, f"divergence on {ak!r}: host={host_keeps} mirror={mirror_keeps}"
def test_build_llm_returns_none_when_no_model_configured():
"""Zero-config (no model_config, or model_config with no model) -> None.
Non-LLM ops still work; an update raises at runtime."""
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemModelConfig
from deerflow.agents.memory.backends.deermem.deermem.core.llm import build_llm
assert build_llm(None) is None
assert build_llm(DeerMemModelConfig()) is None # model=None default
def test_build_llm_degrades_to_none_on_init_failure(caplog):
"""build_llm degrades to None (with a WARNING) when init_chat_model fails,
mirroring _host_default_llm -- so a misconfigured explicit ``model`` does
NOT crash app startup. Memory CRUD/read/search still work; extraction is
disabled; an update raises at runtime with the underlying error logged."""
from unittest.mock import patch
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemModelConfig
from deerflow.agents.memory.backends.deermem.deermem.core.llm import build_llm
model_config = DeerMemModelConfig(provider="openai", model="bogus-model", api_key="k")
llm_logger = "deerflow.agents.memory.backends.deermem.deermem.core.llm"
with patch("langchain.chat_models.init_chat_model", side_effect=RuntimeError("boom")):
with caplog.at_level("WARNING", logger=llm_logger):
result = build_llm(model_config)
assert result is None
assert any("build_llm failed" in r.message for r in caplog.records)
def test_from_backend_config_warns_on_unknown_keys(caplog):
"""Unknown backend_config keys log a WARNING so a typo (e.g. ``storage_pat``
missing the ``h``) does not silently fall back to the default and write
memory to an unintended location. Mirrors the host layer's
load_memory_config_from_dict warning."""
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig
cfg_logger = "deerflow.agents.memory.backends.deermem.deermem.config"
with caplog.at_level("WARNING", logger=cfg_logger):
cfg = DeerMemConfig.from_backend_config({"storage_path": "/tmp/x", "storage_pat": "/tmp/y"})
# known key parsed; unknown key ignored but warned about
assert cfg.storage_path == "/tmp/x"
assert any("Unknown backend_config keys" in r.message for r in caplog.records)
assert any("storage_pat" in r.message for r in caplog.records)
def test_from_backend_config_silent_on_known_keys(caplog):
"""No warning when every key is known (regression guard for the typo warning)."""
from deerflow.agents.memory.backends.deermem.deermem.config import DeerMemConfig
cfg_logger = "deerflow.agents.memory.backends.deermem.deermem.config"
with caplog.at_level("WARNING", logger=cfg_logger):
DeerMemConfig.from_backend_config({"storage_path": "/tmp/x", "max_facts": 20})
assert not any("Unknown backend_config keys" in r.message for r in caplog.records)