Files
CyberGril/tests/test_mem0_backend.py
T
zonggongandmultica-agent e291058754 HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 23:20:18 +08:00

323 lines
13 KiB
Python

"""Mem0 real-adapter wiring verified against a fake SDK mirroring pinned 2.2.1.
No network, no real embeddings, no real LLM. The fake mem0 module mirrors the
surfaces the pinned install actually exposes (verified live by
tools/verify_mem0_real_hel874.py): Memory.from_config, embedding_model.embed /
embed_batch(texts, memory_action), llm.generate_response, add(user_id=...),
search(query, filters=..., limit=...) — unscoped search REJECTED in 2.2.1 —
and vector_store.client payload reads. The fixed install itself stays untouched
on disk; adapter behavior against the real install is proven separately in
docs/rework/hel874/.
"""
import asyncio
import json
import sqlite3
import sys
import types
from dataclasses import dataclass
import pytest
from cybergril.memory.semantic import EmbedLedgerGuard, LlmLedgerGuard, Mem0Backend, SemanticMemory
from cybergril.memory.store import Store
# Shared fake vector store: Memory.add writes points, the SDK's own client reads
# them back — mirroring the single-client path the adapter now uses.
POINT_LOG: dict[str, dict] = {}
class _Point:
def __init__(self, point_id, payload):
self.id = point_id
self.payload = payload
class FakeQdrantClient:
def __init__(self):
self.closed = False
def retrieve(self, collection_name, ids, with_payload=True):
bucket = POINT_LOG.setdefault(collection_name, {})
return [_Point(i, bucket[i]) for i in ids if i in bucket]
def scroll(self, collection_name, scroll_filter=None, limit=10, offset=None,
with_payload=True):
"""Mirror qdrant scroll-by-payload-filter: must== match on src_group."""
bucket = POINT_LOG.setdefault(collection_name, {})
must = getattr(scroll_filter, "must", None) or []
wanted = None
for condition in must:
match = getattr(condition, "match", None)
if getattr(condition, "key", None) == "src_group" and match is not None:
wanted = getattr(match, "value", None)
points = [
_Point(point_id, payload) for point_id, payload in bucket.items()
if wanted is None or payload.get("src_group") == wanted
]
return points[:limit], None
def close(self):
self.closed = True
class _FakeVectorStore:
def __init__(self):
self.client = FakeQdrantClient()
class FakeEmbedder:
"""Pure like the real fastembed: no ledger knowledge lives in the SDK."""
def embed(self, text, memory_action=None):
return [0.0]
def embed_batch(self, texts, memory_action=None):
return [[0.0]] * len(texts)
class _FakeClientHandle:
"""Mirrors the OpenAI client handle the SDK exposes: retries default to 2."""
def __init__(self):
self.max_retries = 2
class FakeLlm:
"""Deterministic extraction: echoes the batch key as one ADD result."""
def __init__(self):
self.calls = []
self.client = _FakeClientHandle()
def generate_response(self, messages=None, **kwargs):
self.calls.append(messages)
user = messages[1]["content"] if messages and len(messages) > 1 else ""
marker = user.split("\n")[0][:20] if user else "记忆"
return json.dumps({"memory": [{"text": f"提取:{marker}", "event": "ADD"}]},
ensure_ascii=False)
class FakeMemory:
instances = []
def __init__(self, embedder, collection):
self.embedding_model = embedder
self.vector_store = _FakeVectorStore()
self.llm = FakeLlm()
self.collection = collection
self.seq = 0
@classmethod
def from_config(cls, config):
instance = cls(_sys_modules()["mem0"]._TEST_EMBEDDER,
config["vector_store"]["config"]["collection_name"])
cls.instances.append((instance, config))
return instance
def add(self, text, metadata=None, user_id=None):
if not user_id:
raise ValueError("filters must contain at least one of: user_id, agent_id, run_id")
self.embedding_model.embed(text, memory_action="search") # 2.2.1 phase 1: embed first
self.llm.generate_response(messages=[
{"role": "system", "content": "extract"},
{"role": "user", "content": text},
], response_format={"type": "json_object"})
self.embedding_model.embed_batch([f"提取:{text[:20]}"], memory_action="add")
self.seq += 1
entry_id = f"m{self.seq}"
bucket = POINT_LOG.setdefault(self.collection, {})
bucket[entry_id] = {"data": f"提取:{text[:20]}", "user_id": user_id, **(metadata or {})}
return {"results": [{"id": entry_id, "memory": f"提取:{text[:20]}", "event": "ADD"}]}
def search(self, query, top_k=20, filters=None, **kwargs):
if not filters or not any(k in filters for k in ("user_id", "agent_id", "run_id")):
raise ValueError("filters must contain at least one of: user_id, agent_id, run_id")
self.embedding_model.embed(query, memory_action="search") # and on search
bucket = POINT_LOG.setdefault(self.collection, {})
return {"results": [{"id": k, "memory": v["data"]}
for k, v in bucket.items()
if v.get("user_id") == filters["user_id"] and query[:2] in v["data"]][:top_k]}
def _sys_modules():
import sys as _sys
return _sys.modules
def _make_ledger(path):
conn = sqlite3.connect(str(path))
conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT, pid INTEGER,"
" kind TEXT, items INTEGER, note TEXT)")
conn.commit()
conn.close()
@pytest.fixture
def fake_mem0(monkeypatch, tmp_path):
ledger_path = tmp_path / "ledger.sqlite3"
_make_ledger(ledger_path)
POINT_LOG.clear()
FakeMemory.instances.clear()
monkeypatch.setitem(sys.modules, "mem0", types.ModuleType("mem0"))
qdrant = types.ModuleType("qdrant_client")
models = types.ModuleType("qdrant_client.models")
@dataclass
class MatchValue:
value: object = None
@dataclass
class FieldCondition:
key: str = ""
match: object = None
@dataclass
class Filter:
must: list | None = None
models.Filter, models.FieldCondition, models.MatchValue = Filter, FieldCondition, MatchValue
qdrant.models = models
monkeypatch.setitem(sys.modules, "qdrant_client", qdrant)
monkeypatch.setitem(sys.modules, "qdrant_client.models", models)
sys.modules["mem0"].Memory = FakeMemory
sys.modules["mem0"]._TEST_EMBEDDER = FakeEmbedder()
return ledger_path
def backend_for(tmp_path, fake_mem0, *, embedder=None, **overrides):
config = {
"gateway_base_url": "http://192.168.200.11:8731/v1",
"gateway_model": "halogen-qwen3.8-flash-next",
"vector_root": str(tmp_path / "vec"),
"history_root": str(tmp_path / "hist"),
"collection": "cg_public",
"ledger_path": str(fake_mem0),
"embed_cap": 10,
"llm_cap": 10,
}
config.update(overrides)
# each backend wraps a fresh embedder, exactly like real from_config instances
sys.modules["mem0"]._TEST_EMBEDDER = embedder or FakeEmbedder()
return Mem0Backend(config)
async def test_add_carries_anchor_and_search_roundtrips(tmp_path, fake_mem0):
backend = backend_for(tmp_path, fake_mem0)
store = Store(tmp_path / "mem0.db")
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1,'user','钥匙在抽屉','t9','sent')")
rows = [{"message_id": 1, "turn_id": "t9", "role": "user", "text": "钥匙在抽屉"}]
anchor = {"turn_ids": ["t9"], "turn_roles": [["t9", "user", 1]],
"input_sha256": "x"}
created = await backend.add_group(rows, anchor, "chat_public:t9:abc")
assert created and created[0]["id"].startswith("m")
payload = backend.payload(created[0]["id"])
assert payload["src_group"] == "chat_public:t9:abc"
assert payload["turn_roles"] == anchor["turn_roles"]
assert payload["user_id"] == "cybergril" # scoped records, searchable
hits = await backend.search("钥匙")
assert hits and hits[0]["memory"].startswith("提取:")
await backend.aclose()
assert backend._client.closed
store.close()
async def test_search_debits_exactly_one_embed_item(tmp_path, fake_mem0):
backend = backend_for(tmp_path, fake_mem0)
guard = EmbedLedgerGuard(fake_mem0, cap=10)
rows = [{"message_id": 1, "turn_id": "t", "role": "user", "text": "一句话"}]
await backend.add_group(rows, {"turn_ids": ["t"], "turn_roles": [["t", "user", 1]],
"input_sha256": "x"}, "g1")
spent = guard.used()
await backend.search("一句") # the old adapter double-debited this path
assert guard.used() == spent + 1
await backend.search("一句")
assert guard.used() == spent + 2
async def test_budget_guards_fail_closed_before_any_real_work(tmp_path, fake_mem0):
backend = backend_for(tmp_path, fake_mem0, embed_cap=0, llm_cap=0) # nothing approved
rows = [{"message_id": 1, "turn_id": "t", "role": "user", "text": "一句话"}]
anchor = {"turn_ids": ["t"], "turn_roles": [["t", "user", 1]], "input_sha256": "x"}
with pytest.raises(RuntimeError, match="semantic_embed_budget_not_approved"):
await backend.add_group(rows, anchor, "g0")
memory = FakeMemory.instances[-1][0]
assert not memory.llm.calls # refused BEFORE the extraction LLM was touched
with pytest.raises(RuntimeError):
await backend.search("任何查询")
# llm-only exhaustion: embed budget present, extraction budget empty
backend2 = backend_for(tmp_path, fake_mem0, embed_cap=10, llm_cap=0)
with pytest.raises(RuntimeError, match="semantic_llm_budget_not_approved"):
await backend2.add_group(rows, anchor, "g0b")
# and with caps, exhausting them refuses further work
backend3 = backend_for(tmp_path, fake_mem0, embed_cap=4, llm_cap=4)
await backend3.add_group(rows, anchor, "g1") # 1 search embed + 1 batch item + 1 llm
await backend3.add_group(rows, anchor, "g2")
with pytest.raises(RuntimeError):
await backend3.add_group(rows, anchor, "g3")
async def test_reservation_releases_on_failure_and_never_overspends(tmp_path, fake_mem0):
# a failing embedder must release its hold: the ledger counts nothing
ledger_path = tmp_path / "flaky-ledger.sqlite3"
_make_ledger(ledger_path)
guard = EmbedLedgerGuard(ledger_path, cap=3)
class FlakyEmbedder(FakeEmbedder):
def embed(self, text, memory_action=None):
if "炸" in text:
raise OSError("controlled embed failure")
return super().embed(text, memory_action)
sys.modules["mem0"]._TEST_EMBEDDER = FlakyEmbedder()
backend = backend_for(tmp_path, fake_mem0, embedder=sys.modules["mem0"]._TEST_EMBEDDER,
ledger_path=str(ledger_path), embed_cap=3, llm_cap=3)
rows = [{"message_id": 1, "turn_id": "t", "role": "user", "text": "炸掉"}]
with pytest.raises(OSError):
await backend.add_group(rows, {"turn_ids": ["t"], "turn_roles": [["t", "user", 1]],
"input_sha256": "x"}, "boom")
assert guard.used() == 0 # failure released every hold
# concurrent reserves cannot overshoot the cap
async def one_search(i: int):
try:
await backend.search(f"查询{i}")
return True
except RuntimeError:
return False
results = await asyncio.gather(*(one_search(i) for i in range(6)))
assert sum(results) >= 1 # some ran, and the ledger never overshot the cap
assert guard.used() <= 3 # hard cap held under concurrency
async def test_semantic_memory_end_to_end_with_fake_sdk(tmp_path, fake_mem0):
backend = backend_for(tmp_path, fake_mem0)
store = Store(tmp_path / "e2e.db")
semantic = SemanticMemory(store, backend)
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1760000000000,'user','阳台的牵牛花开了','t1','sent')")
semantic.enqueue_uncovered()
await semantic.tick()
assert store.query_one("SELECT state FROM sem_batch")["state"] == "done"
block = await semantic.context("牵牛花", [], 600)
assert "牵牛花" in block and block.startswith("她确实记得的更早的事")
# HEL-874 verbatim readback: the archive row's original words ride along
assert "阳台的牵牛花开了" in block
store.close()
async def test_llm_ledger_guard_counts_extraction_calls(tmp_path):
guard = LlmLedgerGuard(tmp_path / "llm-ledger.sqlite3", cap=2)
guard.settle(guard.reserve(1, "extract"), "extract")
guard.settle(guard.reserve(1, "extract"), "extract")
assert guard.used() == 2
with pytest.raises(RuntimeError):
guard.reserve(1, "extract") # cap reached → refuse
guard_zero = LlmLedgerGuard(tmp_path / "llm-zero.sqlite3", cap=0)
with pytest.raises(RuntimeError, match="semantic_llm_budget_not_approved"):
guard_zero.reserve(1, "extract") # default 0 = never approved