- Fixed mem0 source commit 2c81af3 (2.2.1) in isolated venv, qdrant embedded + fastembed local zh embeddings (95.3MB, within 500MB cap) - Gate0 transport-level persistent debit ledger: 61st call blocked pre-send, failures count, cross-process persistence, retries disabled+counted (fake transport, zero network) - Gate1 qdrant embedded checks: keyword_search functional (Chinese segmentation gap recorded honestly), restart subprocess, clean-copy restore, no telemetry collections - Gate2 privacy with stub LLM: P1-P5 zero leak, first-share timing F1-F6 (failed/cancel/unconfirmed no migration, ack+judged migrates told content with anchors, duplicate receipt idempotent), full backup incl. unshared internal memories restores clean - A/B same-material same-criteria: Mem0 paraphrase recall strictly better than current lexical path (S3, model answers in Chinese), S1-S9 all pass, no regression - Headline findings: Chinese input extracted as English memories (default upstream prompt), BM25 lexical channel inert for Chinese, ADD-only infer confirmed with our update orchestration, custom metadata needs direct payload read - 26/60 real outbound via persistent ledger (incl. one parse-failure retry), usage/latency per row; embeddings 28/500; HEL-835 quota untouched - Experiment branch only: no merge to main/product, no deploy, no real-profile access; handoff JSON + dual-base requirement checks pass Co-authored-by: multica-agent <github@multica.ai>
178 lines
8.1 KiB
Python
178 lines
8.1 KiB
Python
#!/usr/bin/env python3
|
||
"""门禁 1(第 0 步三查):qdrant 嵌入式本地模式,零真实模型。
|
||
|
||
Q0a keyword_search/BM25 存在性(源级 + 中文运行时);
|
||
Q0b 本地读写 + scope 过滤(user_id 合取);
|
||
Q0c 进程重启挂载(子进程真实重启,非同进程重开);
|
||
Q0d 清洁关闭后目录复制 → 新路径恢复(实际支持的后端方式,不依赖远程 snapshot API);
|
||
Q0e collection 清单:恰为主 collection + 派生实体 collection,无遥测 collection。
|
||
|
||
本门禁首次触发模型资源下载(BAAI/bge-small-zh-v1.5 与 Qdrant/bm25);
|
||
下载前已核对远端清单(见 results/resource_manifest.json),下载后实测字节数与 SHA256。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
from .common import (DATA_DIR, MODEL_CACHE, close_memory, install_counters,
|
||
mem_config, write_result)
|
||
|
||
TMP = DATA_DIR / "gate1"
|
||
ROLE = "test"
|
||
|
||
|
||
def make_memory(vec_root: Path, hist_root: Path):
|
||
import mem0 # 确认遥测关闭由 common 的环境变量承担
|
||
from mem0 import Memory
|
||
m = Memory.from_config(mem_config(ROLE, vec_root=vec_root, hist_root=hist_root))
|
||
install_counters(m)
|
||
return m
|
||
|
||
|
||
def model_resource_snapshot() -> dict:
|
||
"""实际占用/下载字节。HF-hub 缓存以硬链接组织 blobs+snapshots,按 inode 去重。"""
|
||
files = []
|
||
total = 0
|
||
seen_inodes: set[tuple] = set()
|
||
if MODEL_CACHE.exists():
|
||
for p in sorted(MODEL_CACHE.rglob("*")):
|
||
if p.is_file() and not p.is_symlink():
|
||
st = p.stat()
|
||
key = (st.st_dev, st.st_ino)
|
||
if key in seen_inodes:
|
||
continue
|
||
seen_inodes.add(key)
|
||
b = p.read_bytes()
|
||
files.append({"path": str(p.relative_to(MODEL_CACHE)), "bytes": len(b),
|
||
"sha256": hashlib.sha256(b).hexdigest()})
|
||
total += len(b)
|
||
return {"cache_dir": str(MODEL_CACHE), "files": files, "total_bytes": total,
|
||
"cap_bytes": 500_000_000, "within_cap": total <= 500_000_000}
|
||
|
||
|
||
def run() -> dict:
|
||
if TMP.exists():
|
||
shutil.rmtree(TMP)
|
||
TMP.mkdir(parents=True)
|
||
results: dict = {}
|
||
sample = [
|
||
{"role": "user", "content": "今天在旧书店淘到一本蓝色封面的诗集,纸页有点受潮的味道,可是我特别喜欢"},
|
||
{"role": "assistant", "content": "旧书店的潮味配蓝色封面,像把那个下午整个带回来了。"},
|
||
]
|
||
|
||
m = make_memory(TMP, TMP)
|
||
before_res = model_resource_snapshot()
|
||
|
||
# Q0b 本地读写 + 过滤(infer=False 零 LLM)
|
||
r_u1 = m.add(sample, user_id="u1", infer=False)
|
||
r_u2 = m.add([{"role": "user", "content": "海雾诗集放在床头第二层"}], user_id="u2", infer=False)
|
||
r_u1e = m.add([{"role": "user", "content": "周三是 book club 的日子,我喜欢那本 blue notebook"}],
|
||
user_id="u1", infer=False)
|
||
all_u1 = m.get_all(filters={"user_id": "u1"})
|
||
all_u2 = m.get_all(filters={"user_id": "u2"})
|
||
results["Q0b_local_rw_filter"] = {
|
||
"u1_items": len(all_u1.get("results") or []),
|
||
"u2_items": len(all_u2.get("results") or []),
|
||
"expect": "本地路径可写入;user_id 过滤为合取隔离,u1 看不到 u2 的记忆",
|
||
"pass": bool((all_u1.get("results") or []) and (all_u2.get("results") or []))
|
||
and not any("海雾诗集放在床头" in it["memory"] for it in (all_u1.get("results") or [])),
|
||
}
|
||
|
||
# Q0a keyword_search:存在性 + 运行时词面命中 + 中文分词局限如实记录
|
||
kw_en = m.vector_store.keyword_search(query="book club", top_k=5, filters={"user_id": "u1"})
|
||
kw_zh_subword = m.vector_store.keyword_search(query="诗集", top_k=5, filters={"user_id": "u1"})
|
||
results["Q0a_keyword_search"] = {
|
||
"has_method": hasattr(m.vector_store, "keyword_search"),
|
||
"en_phrase_hits": [(str(x.id), round(float(x.score or 0), 3)) for x in (kw_en or [])],
|
||
"zh_subword_hits": len(kw_zh_subword or []),
|
||
"finding_zh": ("Qdrant/bm25 对中文按整段(空格/标点切分)哈希成单 token;"
|
||
"spaCy 缺席时 lemmatize_for_bm25 原样返回,无中文分词 → "
|
||
"中文子词查询在词面通道不命中(换说法召回只能依赖密集语义通道)"),
|
||
"expect": "keyword_search 机制可用(英文 token BM25 打分命中、带过滤);中文分词局限如实记录",
|
||
"pass": hasattr(m.vector_store, "keyword_search") and (kw_en is not None) and len(kw_en) >= 1,
|
||
}
|
||
|
||
# 语义检索(本地嵌入,零 API)
|
||
sem = m.search("诗集", filters={"user_id": "u1"})
|
||
sem_ids = [r["id"] for r in (sem.get("results") or [])] if isinstance(sem, dict) else [r["id"] for r in sem]
|
||
results["Q0b_semantic_search"] = {
|
||
"hits": sem_ids,
|
||
"expect": "本地 bge-small-zh-v1.5 语义检索可用(零外部嵌入 API)",
|
||
"pass": len(sem_ids) >= 1,
|
||
}
|
||
|
||
# Q0e collection 清单(主 collection 必在;实体 collection 仅实体路径激活时派生创建)
|
||
cols = [c.name for c in m.vector_store.client.get_collections().collections]
|
||
results["Q0e_collections"] = {
|
||
"collections": sorted(cols),
|
||
"expect": "本地实例仅主 collection(实体 collection 由实体路径懒创建;spaCy 缺席时为空集),无遥测 collection",
|
||
"pass": sorted(cols) in ([f"cg_{ROLE}"], [f"cg_{ROLE}", f"cg_{ROLE}_entities"]),
|
||
}
|
||
close_memory(m)
|
||
after_res = model_resource_snapshot()
|
||
|
||
# Q0c 子进程真实重启:同一路径重新挂载,数据仍在
|
||
child = subprocess.run(
|
||
[sys.executable, "-m", "spike.hel857.step0_child", str(TMP)],
|
||
capture_output=True, text=True, cwd=str(Path(__file__).resolve().parents[2]),
|
||
)
|
||
try:
|
||
child_out = json.loads(child.stdout)
|
||
except Exception:
|
||
child_out = {"stdout": child.stdout[-2000:], "stderr": child.stderr[-2000:],
|
||
"returncode": child.returncode}
|
||
results["Q0c_restart_subprocess"] = {
|
||
"child": child_out,
|
||
"expect": "进程退出后子进程重新挂载同一路径:记忆仍在、可检索",
|
||
"pass": bool(child_out.get("restarted_ok")),
|
||
}
|
||
|
||
# Q0d 清洁关闭后复制 → 新路径恢复
|
||
restore_root = TMP / "restore"
|
||
restore_root.mkdir()
|
||
shutil.copytree(TMP / f"vec_{ROLE}", restore_root / f"vec_{ROLE}")
|
||
shutil.copy2(TMP / f"mem0_{ROLE}_history.db", restore_root / f"mem0_{ROLE}_history.db")
|
||
m2 = make_memory(restore_root, restore_root)
|
||
restored = m2.get_all(filters={"user_id": "u1"})
|
||
restored_texts = [it["memory"] for it in (restored.get("results") or [])]
|
||
hist_rows = 0
|
||
import sqlite3
|
||
with sqlite3.connect(str(restore_root / f"mem0_{ROLE}_history.db")) as conn:
|
||
hist_rows = conn.execute("SELECT COUNT(*) FROM history").fetchone()[0]
|
||
close_memory(m2)
|
||
results["Q0d_copy_restore"] = {
|
||
"restored_items": len(restored_texts),
|
||
"restored_first": restored_texts[:1],
|
||
"history_rows": hist_rows,
|
||
"expect": "清洁关闭 + 目录复制到新路径:向量数据与 history 均恢复(u1 应有 3 条)",
|
||
"pass": len(restored_texts) == 3 and hist_rows >= 3,
|
||
}
|
||
|
||
resource = {
|
||
"before_first_load": before_res,
|
||
"after": after_res,
|
||
"downloaded_bytes_this_gate": after_res["total_bytes"] - before_res["total_bytes"],
|
||
}
|
||
ok = all(v.get("pass") for v in results.values()) and after_res["within_cap"]
|
||
return {"ok": ok, "network_outbound": 0, "results": results,
|
||
"model_resources": resource,
|
||
"notes": {
|
||
"entity_extraction": "spaCy 未安装 → mem0 实体路径返回空(上游设计为优雅降级);实体嵌入计数为 0,如实记录,不伪装已启用",
|
||
"restart": "Q0c 为真实子进程重启(非同进程重开连接)",
|
||
}}
|
||
|
||
|
||
def main(argv: list[str]) -> dict:
|
||
out = run()
|
||
write_result("gate1_backend.json", out)
|
||
return out
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(0 if main([])["ok"] else 1)
|