Files
CyberGril/tools/verify_mem0_real_hel874.py
T
zonggongandmultica-agent e978e878df HEL-874 rework: bounded verbatim readback reaches the real provider input, real pinned Mem0 2.2.1 SDK contract verified live and the adapter's five wiring defects fixed, budget gates made provable (atomic reserve/settle embed ledger + independent llm_ops cap), definite-cap real-check execution table, 8360 isolated release package prepared (not deployed), 2026-10-26 user originals recorded source-only - semantic.context now quotes chain-verified archive rows (original words + role + when, <=200-char window with visible trim marker, summary demoted to a one-line pointer, same min(600,budget) cap) and episodic.context flips from gist-first-120-chars to verbatim-first (<=240) + role + date, both proven by tests/test_readback_hel874.py capturing the actual messages handed to the provider through the real API path: a detail absent from the gist yet quoted verbatim from a turn pushed outside the recent-20 window, the same for a semantic chain hit, and an unshared companion row never leaking through FTS, semantic or any anchor (AM-001); tools/verify_mem0_real_hel874.py runs the FIXED install itself (mem0ai 2.2.1 2c81af3, real embedded qdrant, real fastembed from the existing cache, deterministic 127.0.0.1 fake gateway, temp ledgers only): before=31970c4 dies at construction (second QdrantClient on the same path rejected by the SDK - recorded), and source-level findings confirmed live and fixed - unscoped search raises ValueError in 2.2.1 (add now carries user_id scope, search passes filters+top_k since limit is silently ignored), payload reads ride the SDK's own vector_store.client, the old outer search debit double-counted (wrapper is now the single accounting point), the SDK's internal extraction LLM was ungated (LlmLedgerGuard with its own llm_ops table, cap default 0) and check-then-debit could overshoot under concurrency (EmbedLedgerGuard now reserves atomically in BEGIN IMMEDIATE, releases on failure/cancel, purges stale holds); after fixes all 12 checks pass (construction/anchor payload/user scope/1 LLM + 2-3 embeds per add measured/extraction input set provably only prior gated batches incl. old memories and rolling history/unshared canary zero outbound/search single debit/concurrency never over cap/close-reopen intact/both zero caps refuse with ZERO outbound LLM requests), evidence in docs/rework/hel874/; mood sensitivity returns to the original repo's continuous rule 1.35-0.70*strength (bazi.sensitivity_from_strength, foundation commit 1012d8b) replacing HEL-870's invented 1.25/0.8 step and is labeled an engineering heuristic, never user-approved bazi science (external agent formulas remain not adopted); docs/budget-plan-hel874.md gives definite caps for the one-time team check (55 requests/0 embeds), first-week semantic activation (<=60 extract LLM / <=180 embeds) and user daily use with code-level hard-gate facts and authorization sources (old 20-30/100-200 were estimates, not approved quota; frozen 39/60 and 498/500 untouched and never挪用); deploy/hel874-release.md + cybergril-hel874-8360.service.example prepare the isolated fresh-empty-data-dir release with health capability matrix and data-preserving rollback (NOT executed, PR#11 not merged, no user-facing loop, no experience address); sources/comment-evidence-full-experience-20261026.json adds the two 2026-10-26 user originals (01a17806, 01a1780e full-experience-then-iterate) with authorship verified and manifest appended only - baseline/current/coverage/changes untouched; verification: 256 python tests pass on 3.11.16 venv + requirements.lock offline (3 new real-provider-input readback cases incl. AM-001 negative, mem0 fake rebuilt to mirror the real 2.2.1 surfaces, 9 cases), ruff clean, web tsc + 42 vitest + build pass, local 8360 stub smoke (loopback, isolated temp DB) health R4-assembly all green then stopped, real-SDK script re-run 12/12 after final edits, dual-target requirement checks 4/4 pass with handoff-HEL-874.json; zero real model calls, zero real embeddings, zero outbound (fake gateway on loopback + existing local model cache only), authoritative ledgers and freezes untouched, no existing services or profiles touched
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 22:13:45 +08:00

415 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""HEL-874 · 实际固定 Mem0 SDK 合同隔离验证(零真实出站、零权威账写入)。
在已安装的固定 mem0ai 2.2.1(2c81af3,HEL-857 hel857-venv)上,用真实
Qdrant 嵌入式向量库、真实 fastembed 本地嵌入(已有模型缓存)和 127.0.0.1
确定性假 OpenAI 网关,验证产品适配层 ``cybergril.memory.semantic.Mem0Backend``
的真实 SDK 合同:
C1 构造:真实 from_config + 嵌入式 qdrant 挂载(修复后不再开第二个同路径 client)。
C2 add:携带 user_id 作用域与锚点 metadata;payload 直读可回锚点。
C3 默认提取的输入集:第二批 add 的提取提示包含第一批的提取记忆(旧记忆)
与滚动 history——全部只来自此前过门批次;未分享 canary 永不出现。
C4 search:必须带 user_id 过滤(2.2.1 对无过滤 search 直接 ValueError);
每次恰好 1 条嵌入记账(旧实现外层+包装双记)。
C5 预算闸:embed_cap=0 / llm_cap=0 在任何真实工作前拒绝(LLM 服务器零请求)。
C6 并发:并行 search 预占不越过 cap。
C7 关闭恢复:aclose 后同一目录重建,数据与锚点仍在。
证据 JSON 写入 argv[1]。运行(在仓库根,用固定 venv):
/path/to/hel857-venv/bin/python tools/verify_mem0_real_hel874.py out.json
本脚本对修复前(31970c4)与修复后代码均可运行:修复前行为按异常如实记录,
供前后对照。
"""
from __future__ import annotations
import contextlib
import hashlib
import json
import os
import socket
import sqlite3
import sys
import tempfile
import threading
import time
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / "src"))
# 零出站:清代理、禁遥测;嵌入模型走已有本地缓存。
for key in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"):
os.environ.pop(key, None)
os.environ["NO_PROXY"] = "127.0.0.1,localhost"
os.environ["MEM0_TELEMETRY"] = "False"
CACHE = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir"
"/hel857-data/fastembed-cache")
if CACHE.exists():
os.environ["FASTEMBED_CACHE_PATH"] = str(CACHE)
REPORT: dict = {"started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
FAILURES: list[str] = []
def check(name: str, ok: bool, detail: str = "") -> bool:
REPORT.setdefault("checks", []).append({"name": name, "ok": bool(ok), "detail": detail})
if not ok:
FAILURES.append(f"{name}: {detail}")
return bool(ok)
# ---------------------------------------------------------------- 假 OpenAI 网关
class _Server(ThreadingHTTPServer):
daemon_threads = True
class FakeGateway(BaseHTTPRequestHandler):
requests: list[dict] = []
counter = {"n": 0}
lock = threading.Lock()
def log_message(self, *args): # silence
pass
def do_POST(self): # noqa: N802 — http.server contract
length = int(self.headers.get("content-length") or 0)
body = self.rfile.read(length).decode("utf-8", "replace")
with FakeGateway.lock:
FakeGateway.counter["n"] += 1
FakeGateway.requests.append({
"n": FakeGateway.counter["n"], "path": self.path, "body": body,
})
memory_text = f"合成提取记忆HEL874-{FakeGateway.counter['n']}"
completion = {
"id": f"chatcmpl-hel874-{FakeGateway.counter['n']}",
"object": "chat.completion",
"created": int(time.time()),
"model": "hel874-deterministic",
"choices": [{
"index": 0,
"message": {"role": "assistant",
"content": json.dumps({"memory": [{"text": memory_text, "event": "ADD"}]},
ensure_ascii=False)},
"finish_reason": "stop",
}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
}
payload = json.dumps(completion).encode()
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def start_gateway() -> _Server:
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
server = _Server(("127.0.0.1", port), FakeGateway)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def last_prompt() -> str:
req = FakeGateway.requests[-1]
try:
return json.loads(req["body"])["messages"][-1]["content"]
except Exception:
return req["body"]
def install_facts() -> None:
import importlib.metadata as md
facts = {"python": sys.version.split()[0]}
for pkg in ("mem0ai", "qdrant-client", "fastembed"):
try:
facts[pkg] = md.version(pkg)
except Exception as exc: # pragma: no cover
facts[pkg] = f"ERR {exc}"
import mem0
facts["mem0_path"] = str(Path(mem0.__file__).parent)
digests = {}
for rel in ("memory/main.py", "memory/storage.py", "embeddings/fastembed.py",
"llms/openai.py", "vector_stores/qdrant.py"):
path = Path(mem0.__file__).parent / rel
if path.exists():
digests[rel] = hashlib.sha256(path.read_bytes()).hexdigest()
facts["module_sha256"] = digests
tarball = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87"
"/workdir/hel857-data/mem0-2c81af3.tar.gz")
if tarball.exists():
facts["source_tarball_sha256"] = hashlib.sha256(tarball.read_bytes()).hexdigest()
REPORT["install"] = facts
def make_ledger(path: Path, cap: int, llm_cap: int) -> None:
conn = sqlite3.connect(str(path))
with conn:
conn.execute("CREATE TABLE IF NOT EXISTS embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT,"
" ts TEXT, pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
conn.execute("CREATE TABLE IF NOT EXISTS llm_ops (id INTEGER PRIMARY KEY AUTOINCREMENT,"
" ts TEXT, pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
conn.close()
path.with_name(path.name + ".meta").write_text(
json.dumps({"embed_cap": cap, "llm_cap": llm_cap}), encoding="utf-8")
def embed_used(path: Path) -> int:
conn = sqlite3.connect(str(path))
try:
row = conn.execute("SELECT coalesce(sum(items),0) FROM embed_ops").fetchone()
return int(row[0] or 0)
finally:
conn.close()
def embed_rows(path: Path) -> list[dict]:
conn = sqlite3.connect(str(path))
try:
return [{"kind": r[0], "items": r[1], "note": r[2]}
for r in conn.execute("SELECT kind,items,note FROM embed_ops ORDER BY id")]
finally:
conn.close()
def llm_used(path: Path) -> int:
conn = sqlite3.connect(str(path))
try:
row = conn.execute("SELECT coalesce(sum(items),0) FROM llm_ops").fetchone()
return int(row[0] or 0)
finally:
conn.close()
def config_for(tmp: Path, ledger: Path, *, port: int, cap: int, llm_cap: int) -> dict:
return {
"gateway_base_url": f"http://127.0.0.1:{port}/v1",
"gateway_model": "hel874-deterministic",
"gateway_key": "hel874-local-test",
"vector_root": str(tmp / "vec"),
"history_root": str(tmp / "hist"),
"collection": "cg_hel874",
"ledger_path": str(ledger),
"embed_cap": cap,
"llm_cap": llm_cap,
}
async def main_async() -> None:
from cybergril.memory.semantic import Mem0Backend, SemanticMemory
from cybergril.memory.store import Store
tmp = Path(tempfile.mkdtemp(prefix="hel874-real-sdk-"))
ledger = tmp / "ledger.sqlite3"
make_ledger(ledger, cap=64, llm_cap=32)
server = start_gateway()
port = server.server_address[1]
import cybergril.memory.semantic as sem_mod
REPORT["adapter_has_llm_guard"] = hasattr(sem_mod, "LlmLedgerGuard")
# ---- C1 construct --------------------------------------------------
backend = None
try:
backend = Mem0Backend(config_for(tmp, ledger, port=port, cap=64, llm_cap=32))
if hasattr(backend, "_memory") and hasattr(backend._memory, "vector_store") \
and getattr(backend, "_client", None) is backend._memory.vector_store.client:
single_client = "sdk-vector-store-client"
else:
single_client = "second-standalone-client"
check("C1_construct", True, f"client_path={single_client}")
except Exception as exc:
check("C1_construct", False, f"{type(exc).__name__}: {exc}")
REPORT["trace"] = traceback.format_exc()
finish(server)
return
store = Store(tmp / "product.db")
def public_turn(turn_id: str, user_text: str, ts: int) -> list[dict]:
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(?,'user',?,?,'sent')", (ts, user_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": user_text}]
anchor_for = sem_mod.anchor_fingerprint
# ---- C2 add with anchors + scope ------------------------------------
rows1 = public_turn("t1", "家里的备用钥匙藏在阳台第三个花盆下面", 1_763_000_000_000)
anchor1 = {"turn_ids": ["t1"], "turn_roles": [["t1", "user", rows1[0]["message_id"]]],
"input_sha256": anchor_for(rows1)}
llm_before = len(FakeGateway.requests)
try:
created1 = await backend.add_group(rows1, anchor1, "chat_public:t1:a1")
ok = bool(created1) and created1[0]["id"]
payload = backend.payload(created1[0]["id"]) or {}
ok = ok and payload.get("turn_roles") == anchor1["turn_roles"] \
and payload.get("input_sha256") == anchor1["input_sha256"] \
and payload.get("src_group") == "chat_public:t1:a1"
scoped = "user_id" in payload or "cybergril" in json.dumps(payload)
check("C2_add_anchor_payload", ok, f"created={bool(created1)} payload_keys={sorted(payload)[:8]}")
check("C2_add_user_scope", scoped, "user_id present in stored payload" if scoped
else "no user scope in payload (pre-fix behavior)")
except Exception as exc:
check("C2_add_anchor_payload", False, f"{type(exc).__name__}: {exc}")
# per-add real spend (verified live): phase-1 query embed + phase-3 batch
# embed of extracted texts + phase-7 entity-upsert embeds (0..N), 1 LLM call
embed_after_add = embed_used(ledger)
llm_after_add = len(FakeGateway.requests) - llm_before
REPORT["embed_rows_after_first_add"] = embed_rows(ledger)
check("C2_add_ledger_shape", 2 <= embed_after_add <= 4 and llm_after_add == 1,
f"embed_items={embed_after_add} llm_calls={llm_after_add}")
# ---- C3 default extraction input set --------------------------------
rows2 = public_turn("t2", "周末想一起去旧书店逛一圈", 1_763_000_100_000)
anchor2 = {"turn_ids": ["t2"], "turn_roles": [["t2", "user", rows2[0]["message_id"]]],
"input_sha256": anchor_for(rows2)}
try:
await backend.add_group(rows2, anchor2, "chat_public:t2:a2")
prompt = last_prompt()
old_memory_seen = "合成提取记忆HEL874-1" in prompt
new_row_seen = "旧书店" in prompt
history_seen = "花盆" in prompt # rolling history carries batch 1's raw message
check("C3_extraction_input_set", old_memory_seen and new_row_seen,
f"old_memory={old_memory_seen} new_row={new_row_seen} history_carry={history_seen}")
except Exception as exc:
check("C3_extraction_input_set", False, f"{type(exc).__name__}: {exc}")
# ---- C3b unshared canary never leaves --------------------------------
canary = "她私藏的紫铜风铃HEL874绝不外传"
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(?,'companion',?,?,'sent')", (1_763_000_200_000, canary, "t3"))
semantic = SemanticMemory(store, backend)
queued = semantic.enqueue_uncovered() # only public rows batch
gate_calls = len(FakeGateway.requests)
await semantic.tick()
prompts_since = [r["body"] for r in FakeGateway.requests[gate_calls:]]
leaked = any(canary in body for body in prompts_since)
batch = store.query_one("SELECT * FROM sem_batch WHERE batch_key LIKE '%t3%'")
companion_in_anchor = False
if batch:
companion_in_anchor = canary in batch["anchor_json"]
check("C3b_unshared_canary_never_outbound", (not leaked) and (not companion_in_anchor),
f"queued_public_batches={queued} leaked={leaked} anchor_taint={companion_in_anchor}")
# ---- C4 search: filters + single accounting --------------------------
embed_before_search = embed_used(ledger)
try:
hits = await backend.search("合成提取记忆", limit=4)
delta = embed_used(ledger) - embed_before_search
check("C4_search_filters", bool(hits), f"hits={len(hits)}")
check("C4_search_single_debit", delta == 1, f"embed_delta={delta} (pre-fix=2)")
except Exception as exc:
check("C4_search_filters", False, f"{type(exc).__name__}: {exc}")
check("C4_search_single_debit", False, "search raised")
# ---- C6 concurrency cannot overshoot ---------------------------------
# own vector roots: a second Memory on the SAME local path is rejected by
# qdrant's file lock (that is the C1 before-evidence, not this check)
cap_tmp = tmp / "conc-ledger.sqlite3"
make_ledger(cap_tmp, cap=3, llm_cap=3)
conc_cfg = config_for(tmp, cap_tmp, port=port, cap=3, llm_cap=3)
conc_cfg["vector_root"] = str(tmp / "vec-conc")
conc_cfg["history_root"] = str(tmp / "hist-conc")
conc_backend = Mem0Backend(conc_cfg)
import asyncio
async def one(i: int):
try:
await conc_backend.search(f"查询{i}")
return "ok"
except RuntimeError:
return "refused"
except Exception as exc: # pre-fix ValueError path
return f"err:{type(exc).__name__}"
outcomes = await asyncio.gather(*(one(i) for i in range(8)))
used_after = embed_used(cap_tmp)
check("C6_concurrency_cap", used_after <= 3,
f"outcomes={sorted(set(outcomes))} used={used_after} cap=3")
with contextlib.suppress(Exception):
await conc_backend.aclose()
# ---- C7 shutdown / reopen --------------------------------------------
await backend.aclose()
try:
reopened = Mem0Backend(config_for(tmp, ledger, port=port, cap=64, llm_cap=32))
hits2 = await reopened.search("合成提取记忆", limit=4)
check("C7_reopen_after_close", bool(hits2), f"hits_after_reopen={len(hits2)}")
await reopened.aclose()
except Exception as exc:
check("C7_reopen_after_close", False, f"{type(exc).__name__}: {exc}")
# ---- C5 zero budgets refuse BEFORE any real work ----------------------
cap0 = tmp / "cap0-ledger.sqlite3"
make_ledger(cap0, cap=0, llm_cap=0)
try:
zero = Mem0Backend(config_for(tmp, cap0, port=port, cap=0, llm_cap=0))
requests_before = len(FakeGateway.requests)
try:
await zero.add_group(rows1, anchor1, "cap0")
check("C5_embed_zero_refuses", False, "add succeeded with embed_cap=0")
except RuntimeError as exc:
llm_sent = len(FakeGateway.requests) - requests_before
check("C5_embed_zero_refuses", "embed" in str(exc) and llm_sent == 0,
f"err={exc} llm_sent={llm_sent}")
await zero.aclose()
except Exception as exc:
check("C5_embed_zero_refuses", False, f"{type(exc).__name__}: {exc}")
llm0 = tmp / "llm0-ledger.sqlite3"
make_ledger(llm0, cap=64, llm_cap=0)
try:
zero_llm = Mem0Backend(config_for(tmp, llm0, port=port, cap=64, llm_cap=0))
requests_before = len(FakeGateway.requests)
try:
await zero_llm.add_group(rows1, anchor1, "llm0")
check("C5_llm_zero_refuses", False, "add succeeded with llm_cap=0")
except RuntimeError as exc:
llm_sent = len(FakeGateway.requests) - requests_before
check("C5_llm_zero_refuses", "llm" in str(exc) and llm_sent == 0,
f"err={exc} llm_sent={llm_sent}")
await zero_llm.aclose()
except Exception as exc:
check("C5_llm_zero_refuses", False, f"{type(exc).__name__}: {exc}")
store.close()
finish(server)
def finish(server: _Server) -> None:
server.shutdown()
REPORT["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
REPORT["gateway_requests_total"] = len(FakeGateway.requests)
REPORT["failures"] = FAILURES
out = Path(sys.argv[1] if len(sys.argv) > 1 else "hel874-real-sdk-report.json")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"out": str(out), "failures": FAILURES,
"checks": {c["name"]: c["ok"] for c in REPORT.get("checks", [])}},
ensure_ascii=False, indent=2))
sys.exit(1 if FAILURES else 0)
def main() -> None:
install_facts()
import asyncio
asyncio.run(main_async())
if __name__ == "__main__":
main()