"""HEL-882 SDK-boundary recovery: hidden retries, swallowed failures, resumes. Fake-SDK mirror of the manager's independent review reproductions (real pinned mem0ai 2.2.1 behavior mirrored from source): 1. llm_cap=1 against a 500-ing gateway fired 6 HTTP requests (OpenAI default max_retries=2) while llm_ops used stayed 0 → retries now disabled at the client and every wire-hit (even a 5xx) settles as used. 2. embed_cap exhausting mid-add: the SDK swallows the embed refusal and returns an empty list; the product used to write sem_batch done/[] and the rows were never organized again → the refusal now re-raises, the batch re-queues without burning an attempt, and raising the cap resumes it. 3. stub→mem0 on the same archive: stub coverage blocked the real rebuild → coverage is per-backend now; a real completed batch is never re-sent. """ import contextlib import json import sqlite3 import sys import types import pytest from conftest import engineering_budget from test_mem0_backend import POINT_LOG, FakeEmbedder, FakeMemory, _make_ledger, synthetic_authority from cybergril.memory.semantic import ( EmbedLedgerGuard, Mem0Backend, SemanticBudgetError, SemanticMemory, StubBackend, build_semantic, verify_ledger_authority, ) from cybergril.memory.store import Store from cybergril.think.budget import BudgetGuard class Wire500Error(Exception): """Mirror of openai.APIStatusError: the request WAS answered (500).""" class NeverConnectedError(Exception): """Mirror of an openai error whose cause is httpx.ConnectError: unsent.""" def _httpx_connect_error(): cls = type("ConnectError", (Exception,), {}) cls.__module__ = "httpx" return cls() class SwallowingMemory(FakeMemory): """Mirror of 2.2.1's phase-3/7 fallback: embed failures in add() are swallowed into an empty result — the exact review reproduction.""" def add(self, text, metadata=None, user_id=None): self.embedding_model.embed(text, memory_action="search") # phase 1 self.llm.generate_response(messages=[ {"role": "system", "content": "extract"}, {"role": "user", "content": text}, ], response_format={"type": "json_object"}) extracted = f"提取:{text[:20]}" try: # phase 3 self.embedding_model.embed_batch([extracted], memory_action="add") except Exception: embed_map = {} with contextlib.suppress(Exception): embed_map[self.embedding_model.embed( # noqa: F841 — fallback mirror extracted, memory_action="add")] = None if not embed_map: return [] # ← the swallow the review caught self.seq += 1 entry_id = f"m{self.seq}" bucket = POINT_LOG.setdefault(self.collection, {}) bucket[entry_id] = {"data": extracted, "user_id": user_id, **(metadata or {})} return {"results": [{"id": entry_id, "memory": extracted, "event": "ADD"}]} def install_fake(monkeypatch, memory_cls=FakeMemory): 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") class MatchValue: def __init__(self, value=None): self.value = value class FieldCondition: def __init__(self, key="", match=None): self.key, self.match = key, match class Filter: def __init__(self, must=None): self.must = must 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 = memory_cls sys.modules["mem0"]._TEST_EMBEDDER = FakeEmbedder() return sys.modules["mem0"] def config_for(tmp_path, ledger, *, embed_cap=10, llm_cap=10, **extra): config = { "gateway_base_url": "http://127.0.0.1:9/v1", "gateway_model": "fake", "vector_root": str(tmp_path / "vec"), "history_root": str(tmp_path / "hist"), "collection": "cg_public", "ledger_path": str(ledger), "embed_cap": embed_cap, "llm_cap": llm_cap, } config.update(extra) if config.get("embed_cap", 0) > 0 or config.get("llm_cap", 0) > 0: # HEL-885: positive caps REQUIRE an explicit synthetic authority; the # product default (no authority) refuses — see test_rework_hel885. config.setdefault("authority", synthetic_authority(ledger)) return config def seed_turn(store, turn_id, text): with store.conn: store.execute( "INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(1,'user',?,?,'sent')", (text, turn_id), ) row = store.query_one("SELECT id FROM chat_message WHERE turn_id=?", (turn_id,)) return [{"message_id": row["id"], "turn_id": turn_id, "role": "user", "text": text}] async def test_hidden_retries_disabled_and_wire_hits_counted(tmp_path, monkeypatch): """Review repro 1: llm_cap=1, gateway 500s → exactly ONE HTTP attempt, and it lands in llm_ops; the second add refuses before the wire.""" from test_mem0_backend import FakeLlm class Failing500Llm(FakeLlm): """The wire answer is a 500: raised inside generate_response like the real OpenAI client does (an answered request, definitively sent).""" def generate_response(self, messages=None, **kwargs): self.calls.append("wire") raise Wire500Error("HTTP 500 review controlled") class Failing500Memory(FakeMemory): def __init__(self, embedder, collection): super().__init__(embedder, collection) self.llm = Failing500Llm() install_fake(monkeypatch, Failing500Memory) ledger = tmp_path / "retry.sqlite3" _make_ledger(ledger) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=1)) assert backend._memory.llm.client.max_retries == 0 # hidden retries disabled rows = [{"message_id": 1, "turn_id": "t1", "role": "user", "text": "合成"}] anchor = {"turn_ids": ["t1"], "turn_roles": [["t1", "user", 1]], "input_sha256": "x"} with pytest.raises(Wire500Error): await backend.add_group(rows, anchor, "retry") assert len(backend._memory.llm.calls) == 1 # one actual send, no SDK retries assert backend.llm_guard.used() == 1 # the answered 5xx is COUNTED # second add: cap 1/1 used → refuses before any wire hit calls_before = len(backend._memory.llm.calls) with pytest.raises(RuntimeError, match="semantic_llm_budget_exhausted"): await backend.add_group(rows, anchor, "retry2") assert len(backend._memory.llm.calls) == calls_before async def test_pre_connection_failure_releases(tmp_path, monkeypatch): """Only a provably-unsent request (httpx.ConnectError cause) releases.""" mem0 = install_fake(monkeypatch) class UnsentMemory(FakeMemory): def add(self, text, metadata=None, user_id=None): self.embedding_model.embed(text, memory_action="search") exc = NeverConnectedError("connection refused") exc.__cause__ = _httpx_connect_error() raise exc mem0.Memory = UnsentMemory ledger = tmp_path / "unsent.sqlite3" _make_ledger(ledger) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=5)) rows = [{"message_id": 1, "turn_id": "t", "role": "user", "text": "x"}] with pytest.raises(NeverConnectedError): await backend.add_group(rows, {"turn_ids": ["t"], "turn_roles": [["t", "user", 1]], "input_sha256": "x"}, "unsent") assert backend.llm_guard.used() == 0 # nothing reached the wire → released async def test_mid_add_budget_swallow_requeues_then_resumes(tmp_path, monkeypatch): """Review repro 2: embed cap exhausts mid-add, the SDK swallows it — the batch must NOT complete empty; raising the cap resumes and organizes.""" install_fake(monkeypatch, SwallowingMemory) ledger = tmp_path / "exhaust.sqlite3" _make_ledger(ledger) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=1, llm_cap=5)) store = Store(tmp_path / "exhaust.db") seed_turn(store, "t1", "合成测试钥匙在第三个花盆下面") semantic = SemanticMemory(store, backend) semantic.enqueue_uncovered() await semantic.tick() after_first = dict(store.query_one("SELECT state,reason,entry_ids,attempts FROM sem_batch")) assert after_first["state"] == "queued" # NOT done: the swallow was caught assert "budget" in (after_first["reason"] or "") assert after_first["attempts"] == 0 # budget refusal burns no attempt assert json.loads(after_first["entry_ids"] or "[]") == [] backend.ledger.cap = 50 # the manager raises the approved cap await semantic.tick() after_raise = dict(store.query_one("SELECT state,reason,entry_ids,attempts FROM sem_batch")) assert after_raise["state"] == "done" # resumed and organized the same rows assert json.loads(after_raise["entry_ids"]) hits = await backend.search("合成测试钥匙") assert hits store.close() async def test_resume_never_loses_or_duplicates_rows(tmp_path, monkeypatch): """HEL-885 rewrite: the crash-split resume runs through the REAL product path (real tick, real batch state) — no hand-planted single-row anchors. The HEL-882 version planted exactly the anchor the product never wrote, which masked the whole-batch-anchor defect the manager reproduced live.""" install_fake(monkeypatch) ledger = tmp_path / "resume.sqlite3" _make_ledger(ledger) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=1)) store = Store(tmp_path / "resume.db") seed_turn(store, "t2", "第一条原话") with store.conn: # a shared companion row joins the turn store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES" "(2,'companion','第二条原话','t2','sent')") row2 = store.query_one("SELECT id FROM chat_message WHERE text='第二条原话'") store.execute( "INSERT INTO sharing_attempt(message_id,turn_id,epoch,token,text_hash,expires_at," "ack_at,candidates,state) VALUES(?,'t2',1,'t','h',9223372036854775806," "1700000001000,'[]','judged')", (row2["id"],)) semantic = SemanticMemory(store, backend) semantic.enqueue_uncovered() await semantic.tick() # llm_cap=1: companion row spends it, user row refuses first = dict(store.query_one("SELECT state,reason FROM sem_batch")) assert first["state"] == "queued" and "budget" in (first["reason"] or "") # per-row anchors: the ONE stored vector vouches for its own row ONLY assert backend.completed_message_ids("chat_public:mem0:t2:" + _batch_digest(store)) == { row2["id"]} row1_id = store.query_one("SELECT id FROM chat_message WHERE text='第一条原话'")["id"] done_rows = {r["message_id"] for r in store.query("SELECT message_id FROM sem_row_done")} assert done_rows == {row2["id"]} backend.llm_guard.cap = 50 # budget returns; the SAME batch resumes await semantic.tick() after = dict(store.query_one("SELECT state,reason,entry_ids FROM sem_batch")) assert after["state"] == "done" and json.loads(after["entry_ids"]) # both rows actually sent, each EXACTLY once — no lost row, no resend sent = [json.dumps(m, ensure_ascii=False) for m in backend._memory.llm.calls] assert sum("第一条原话" in body for body in sent) == 1 assert sum("第二条原话" in body for body in sent) == 1 completed = backend.completed_message_ids("chat_public:mem0:t2:" + _batch_digest(store)) assert completed == {row1_id, row2["id"]} # nothing left to send → idempotent no-op assert await backend.add_group( [{"message_id": row1_id, "turn_id": "t2", "role": "user", "text": "第一条原话"}, {"message_id": row2["id"], "turn_id": "t2", "role": "companion", "text": "第二条原话"}], {"turn_ids": ["t2", "t2"], "turn_roles": [], "input_sha256": "x"}, "chat_public:mem0:t2:" + _batch_digest(store)) == [] store.close() def _batch_digest(store): row = store.query_one("SELECT batch_key FROM sem_batch WHERE backend='mem0'") return row["batch_key"].rsplit(":", 1)[1] async def test_stub_batches_never_block_real_rebuild_and_real_never_resends(tmp_path, monkeypatch): """Review repro 3: stub→mem0 on the same archive reorganizes; a real done batch is never re-enqueued nor re-sent.""" install_fake(monkeypatch) store = Store(tmp_path / "switch.db") seed_turn(store, "t3", "另一条合成原话") stub = SemanticMemory(store, StubBackend()) stub.enqueue_uncovered() await stub.tick() prior = dict(store.query_one("SELECT backend,state,entry_ids FROM sem_batch")) assert prior["backend"] == "stub" and prior["state"] == "done" ledger = tmp_path / "switch.sqlite3" _make_ledger(ledger) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=50)) live = SemanticMemory(store, backend) assert live.enqueue_uncovered() == 1 # stub coverage does NOT block mem0 await live.tick() batches = store.query("SELECT backend,state FROM sem_batch ORDER BY id") assert [b["backend"] for b in batches] == ["stub", "mem0"] assert batches[1]["state"] == "done" hits = await backend.search("另一条合成原话") assert hits # the real backend actually holds the row now # a real completed batch is never re-sent assert live.enqueue_uncovered() == 0 assert await backend.add_group( [{"message_id": store.query_one("SELECT id FROM chat_message WHERE turn_id='t3'")["id"], "turn_id": "t3", "role": "user", "text": "另一条合成原话"}], {"turn_ids": ["t3"], "turn_roles": [], "input_sha256": "x"}, store.query_one("SELECT batch_key FROM sem_batch WHERE backend='mem0'")["batch_key"], ) == [] store.close() async def test_embed_daily_cap_enforced_in_same_reserve(tmp_path): """Execution-table C per-day embed top applies inside the atomic reserve.""" ledger = tmp_path / "daily.sqlite3" _make_ledger(ledger) guard = EmbedLedgerGuard(ledger, cap=50, daily_cap=1) guard.settle(guard.reserve(1, "search"), "search") assert guard.used() == 1 with pytest.raises(RuntimeError, match="semantic_embed_budget_daily_exhausted"): guard.reserve(1, "search") # lifetime cap 50 still has room — day top hit async def test_mem0_internal_llm_goes_through_the_unified_request_gate(tmp_path, monkeypatch): """The SDK's hidden extraction LLM reserves request count + tokens in the product guard (category 'semantic') before the wire.""" install_fake(monkeypatch) ledger = tmp_path / "unified.sqlite3" _make_ledger(ledger) request_guard = BudgetGuard(engineering_budget(daily_requests={"semantic": 1})) backend = Mem0Backend(config_for(tmp_path, ledger, embed_cap=50, llm_cap=50), request_guard=request_guard) store = Store(tmp_path / "unified.db") rows = seed_turn(store, "t4", "统一闸测试") await backend.add_group(rows, {"turn_ids": ["t4"], "turn_roles": [["t4", "user", 1]], "input_sha256": "x"}, "u1") assert request_guard.requests_used("semantic") == 1 assert request_guard.used > 0 # conservative tokens pre-allocated too with pytest.raises(Exception, match="budget_requests_exhausted:semantic"): seed_turn(store, "t5", "第二次") rows2 = [{"message_id": store.query_one( "SELECT id FROM chat_message WHERE turn_id='t5'")["id"], "turn_id": "t5", "role": "user", "text": "第二次"}] await backend.add_group(rows2, {"turn_ids": ["t5"], "turn_roles": [["t5", "user", 2]], "input_sha256": "x"}, "u2") store.close() def test_authority_block_refuses_a_fresh_file_bypassing_the_freeze(tmp_path): """A new empty ledger must not re-open the frozen 498/500 headroom.""" authority_ledger = tmp_path / "authoritative.sqlite3" conn = sqlite3.connect(str(authority_ledger)) with conn: conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT," " pid INTEGER, kind TEXT, items INTEGER, note TEXT)") conn.execute("INSERT INTO embed_ops(ts,pid,kind,items,note) VALUES" "('2026-10-20T01:00:00Z',1,'dense',498,'product:frozen')") conn.close() import hashlib rows = sqlite3.connect(str(authority_ledger)).execute( "SELECT ts,pid,kind,items,note FROM embed_ops ORDER BY id LIMIT 1").fetchall() digest = hashlib.sha256( "\n".join("|".join(str(c) for c in row) for row in rows).encode()).hexdigest() authority = {"prefix_rows": 1, "prefix_sha256": digest, "min_used": 498} # the authoritative file itself passes verify_ledger_authority(authority_ledger, authority) # a different (fresh) file with an approved cap is refused fresh = tmp_path / "fresh-bypass.sqlite3" conn = sqlite3.connect(str(fresh)) with conn: conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT," " pid INTEGER, kind TEXT, items INTEGER, note TEXT)") conn.close() with pytest.raises(SemanticBudgetError): verify_ledger_authority(fresh, authority) with pytest.raises(SemanticBudgetError, match="ledger_authority_missing_file"): verify_ledger_authority(tmp_path / "not-there.sqlite3", authority) async def test_build_semantic_mem0_fail_closed_on_authority_mismatch(tmp_path, monkeypatch): install_fake(monkeypatch) fresh = tmp_path / "fresh2.sqlite3" conn = sqlite3.connect(str(fresh)) with conn: conn.execute("CREATE TABLE embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT," " pid INTEGER, kind TEXT, items INTEGER, note TEXT)") conn.execute("CREATE TABLE llm_ops (id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT," " pid INTEGER, kind TEXT, items INTEGER, note TEXT)") conn.close() store = Store(tmp_path / "fc.db") assert build_semantic( store, mode="mem0", config=config_for(tmp_path, fresh, embed_cap=10, llm_cap=10, authority={"prefix_rows": 1, "prefix_sha256": "0" * 64, "min_used": 498}), ) is None # fail closed: semantic layer off, never a silent stub swap store.close()