267 lines
12 KiB
Python
267 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""HEL-885 · 实际固定 SDK 恢复语义验证(零真实出站、零真实嵌入、零权威账写入)。
|
||
|
||
在固定 mem0ai 2.2.1(hel857-venv)+ 真实嵌入式 Qdrant + 真实 OpenAI 客户端上,
|
||
复现总管独立复审的四类失败并证明修复:确定性 512 维替身(TextEmbedding 构造前
|
||
安装)、127.0.0.1 假网关、临时账/库,全部同 tools/verify_mem0_real_hel874.py
|
||
的 HEL-882 边界口径。
|
||
|
||
S0 正 cap 缺 authority 拒绝构造(HEL-882 版曾成功构造并发送)。
|
||
S1 逐行锚点:llm_cap=1 双公开行 → 首个向量只证明自己那行;补预算后续跑,
|
||
用户原话真的发出且每行恰一次(总管 partial 复现的修复形态)。
|
||
S2 进程重启续跑:行1完成后重启(新 Store/新 Backend 同目录),只补缺行。
|
||
S3 租约回收与并发 tick:过期租约回收后处理;两个并发 tick 不双发。
|
||
S4 未知预占不超时退款(llm_ops 与 embed_ops 同路径):一小时前的未结算
|
||
预占重启后仍占额度;唯一删除路径是显式可证明未发送的 release。
|
||
|
||
证据 JSON 写 argv[1]。运行(仓库根,固定 venv):
|
||
|
||
/path/to/hel857-venv/bin/python tools/verify_semantic_recovery_hel885.py out.json
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import importlib.util
|
||
import json
|
||
import sqlite3
|
||
import sys
|
||
import tempfile
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
REPO = ROOT
|
||
sys.path.insert(0, str(REPO / "src"))
|
||
spec = importlib.util.spec_from_file_location('contract', REPO / 'tools/verify_mem0_real_hel874.py')
|
||
contract = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(contract)
|
||
contract.install_deterministic_boundary()
|
||
from cybergril.memory.semantic import ( # noqa: E402 — after boundary install
|
||
EmbedLedgerGuard,
|
||
LlmLedgerGuard,
|
||
Mem0Backend,
|
||
SemanticBudgetError,
|
||
SemanticMemory,
|
||
)
|
||
from cybergril.memory.store import Store # noqa: E402
|
||
|
||
REPORT: dict = {"head": "HEL-885 rework", "real_llm_requests": 0, "real_embeddings": 0,
|
||
"boundary": "deterministic 512 vectors, non-loopback forbidden"}
|
||
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)
|
||
|
||
|
||
def seed_two_row_turn(store: Store, turn_id: str, user_text: str, companion_text: str):
|
||
with store.conn:
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
|
||
"(1,'user',?,?,'sent')", (user_text, turn_id))
|
||
inserted = store.execute(
|
||
"INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
|
||
"(2,'companion',?,?,'sent')", (companion_text, turn_id))
|
||
store.execute(
|
||
"INSERT INTO sharing_attempt(message_id,turn_id,epoch,token,text_hash,expires_at,"
|
||
"ack_at,candidates,state) VALUES(?,'"+turn_id+"',1,'synthetic','synthetic',"
|
||
"999999,3,'[]','judged')", (inserted.lastrowid,))
|
||
return (store.query_one("SELECT id FROM chat_message WHERE text=?", (user_text,))["id"],
|
||
store.query_one("SELECT id FROM chat_message WHERE text=?", (companion_text,))["id"])
|
||
|
||
|
||
def bodies_since(mark: int) -> list[str]:
|
||
return [r["body"] for r in contract.FakeGateway.requests[mark:]]
|
||
|
||
|
||
async def scenario_partial_and_resume(tmp: Path, server, tag: str) -> dict:
|
||
"""S1 (+S2 restart inside): budget-fail split, resume, restart-safety."""
|
||
ledger = tmp / f"{tag}.sqlite3"
|
||
contract.make_ledger(ledger, cap=100, llm_cap=1)
|
||
cfg = contract.config_for(tmp, ledger, port=server.server_address[1],
|
||
cap=100, llm_cap=1)
|
||
cfg["vector_root"] = str(tmp / f"{tag}-vec")
|
||
cfg["history_root"] = str(tmp / f"{tag}-hist")
|
||
backend = Mem0Backend(cfg)
|
||
db = tmp / f"{tag}.db"
|
||
store = Store(db)
|
||
user_id, companion_id = seed_two_row_turn(
|
||
store, f"turn-{tag}", f"用户原话{tag}", f"伴侣公开原话{tag}")
|
||
live = SemanticMemory(store, backend)
|
||
live.enqueue_uncovered()
|
||
mark = len(contract.FakeGateway.requests)
|
||
await live.tick()
|
||
first_bodies = len(contract.FakeGateway.requests) - mark
|
||
first = dict(store.query_one("SELECT state,reason FROM sem_batch"))
|
||
batch_key = store.query_one("SELECT batch_key FROM sem_batch")["batch_key"]
|
||
completed = sorted(backend.completed_message_ids(batch_key))
|
||
points, _ = backend._client.scroll(collection_name=backend.collection,
|
||
with_payload=True, limit=100)
|
||
per_row = all(len((p.payload or {}).get("turn_roles") or []) == 1 for p in points)
|
||
check(f"S1_{tag}_first_tick_partial",
|
||
first["state"] == "queued" and "budget" in (first["reason"] or "")
|
||
and first_bodies == 1 and completed == [companion_id] and per_row,
|
||
f"state={first['state']} reason={first['reason']} http={first_bodies} "
|
||
f"completed={completed} points={len(points)} per_row_anchor={per_row}")
|
||
|
||
# S2 restart: close everything, reopen NEW instances on the same paths.
|
||
# Precise no-resend proof = HTTP count: only the user row still needs an
|
||
# add (one extraction request each). Raw text presence alone cannot count
|
||
# sends — mem0 legitimately carries earlier rows in the rolling history
|
||
# of every later extraction prompt.
|
||
store.close()
|
||
await backend.aclose()
|
||
cfg2 = dict(cfg)
|
||
backend2 = Mem0Backend(cfg2)
|
||
backend2.llm_guard.cap = 5 # the manager raises the temporary cap
|
||
store2 = Store(db)
|
||
live2 = SemanticMemory(store2, backend2)
|
||
mark2 = len(contract.FakeGateway.requests)
|
||
await live2.tick()
|
||
after = dict(store2.query_one("SELECT state,reason,entry_ids FROM sem_batch"))
|
||
bodies = bodies_since(mark2)
|
||
user_sent = any(f"用户原话{tag}" in b for b in bodies)
|
||
completed2 = sorted(backend2.completed_message_ids(batch_key))
|
||
check(f"S2_{tag}_restart_sends_only_missing_row",
|
||
after["state"] == "done" and len(bodies) == 1 and user_sent
|
||
and completed2 == sorted([user_id, companion_id])
|
||
and json.loads(after["entry_ids"] or "[]"),
|
||
f"state={after['state']} http={len(bodies)} user_sent={user_sent} "
|
||
f"completed={completed2} entry_ids={after['entry_ids']}")
|
||
store2.close()
|
||
await backend2.aclose()
|
||
return {"first_state": first["state"], "first_reason": first["reason"],
|
||
"completed_after_first": completed}
|
||
|
||
|
||
async def scenario_lease_and_concurrency(tmp: Path, server) -> None:
|
||
ledger = tmp / "lease.sqlite3"
|
||
contract.make_ledger(ledger, cap=100, llm_cap=10)
|
||
cfg = contract.config_for(tmp, ledger, port=server.server_address[1],
|
||
cap=100, llm_cap=10)
|
||
cfg["vector_root"] = str(tmp / "lease-vec")
|
||
cfg["history_root"] = str(tmp / "lease-hist")
|
||
backend = Mem0Backend(cfg)
|
||
db = tmp / "lease.db"
|
||
store = Store(db)
|
||
seed_two_row_turn(store, "turn-lease", "租约恢复第一行", "租约恢复第二行")
|
||
live = SemanticMemory(store, backend)
|
||
live.enqueue_uncovered()
|
||
# a worker died holding the lease: expired pending batch is recovered
|
||
with store.conn:
|
||
store.execute("UPDATE sem_batch SET state='pending',owner='dead',lease_until=1")
|
||
live.recover()
|
||
job = dict(store.query_one("SELECT state,reason FROM sem_batch"))
|
||
mark = len(contract.FakeGateway.requests)
|
||
await live.tick()
|
||
after_lease = dict(store.query_one("SELECT state FROM sem_batch"))
|
||
bodies = bodies_since(mark)
|
||
check("S3a_lease_expired_batch_recovers",
|
||
job["state"] == "failed" and job["reason"] == "lease_expired"
|
||
and after_lease["state"] == "done" and len(bodies) == 2
|
||
and all(any(t in b for b in bodies) for t in ("租约恢复第一行", "租约恢复第二行")),
|
||
f"recovered={job} state_after={after_lease['state']} http={len(bodies)}")
|
||
|
||
# concurrency: two ticks racing on one fresh batch never double-send
|
||
seed_two_row_turn(store, "turn-race", "并发第一行", "并发第二行")
|
||
live.enqueue_uncovered()
|
||
mark2 = len(contract.FakeGateway.requests)
|
||
await asyncio.gather(live.tick(), live.tick())
|
||
bodies2 = bodies_since(mark2)
|
||
races = store.query("SELECT state FROM sem_batch WHERE turn_id='turn-race'")
|
||
check("S3b_concurrent_ticks_single_send",
|
||
all(r["state"] == "done" for r in races) and len(bodies2) == 2
|
||
and all(any(t in b for b in bodies2) for t in ("并发第一行", "并发第二行")),
|
||
f"http={len(bodies2)} states={[r['state'] for r in races]}")
|
||
store.close()
|
||
await backend.aclose()
|
||
|
||
|
||
def scenario_aged_reservations(tmp: Path) -> None:
|
||
llm_path = tmp / "aged-llm.sqlite3"
|
||
llm = LlmLedgerGuard(llm_path, cap=1)
|
||
pending = llm.reserve(1, "sent_but_crashed_before_settlement")
|
||
with sqlite3.connect(str(llm_path)) as conn:
|
||
conn.execute("UPDATE llm_ops SET ts='2000-01-01T00:00:00Z' WHERE id=?", (pending,))
|
||
second_allowed = True
|
||
try:
|
||
LlmLedgerGuard(llm_path, cap=1).reserve(1, "second_after_restart")
|
||
except RuntimeError:
|
||
second_allowed = False
|
||
llm_used = LlmLedgerGuard(llm_path, cap=1).used()
|
||
check("S4a_aged_unknown_llm_reservation_kept",
|
||
(not second_allowed) and llm_used == 1,
|
||
f"second_allowed={second_allowed} used_after_restart={llm_used}")
|
||
|
||
embed_path = tmp / "aged-embed.sqlite3"
|
||
contract.make_ledger(embed_path, cap=1, llm_cap=0)
|
||
guard = EmbedLedgerGuard(embed_path, cap=1)
|
||
hold = guard.reserve(1, "embed_sent_then_crashed")
|
||
with sqlite3.connect(str(embed_path)) as conn:
|
||
conn.execute("UPDATE embed_ops SET ts='2000-01-01T00:00:00Z' WHERE id=?", (hold,))
|
||
embed_second = True
|
||
try:
|
||
EmbedLedgerGuard(embed_path, cap=1).reserve(1, "again")
|
||
except RuntimeError:
|
||
embed_second = False
|
||
embed_used = EmbedLedgerGuard(embed_path, cap=1).used()
|
||
EmbedLedgerGuard(embed_path, cap=1).release(hold) # explicit unsent release path
|
||
embed_after_release = EmbedLedgerGuard(embed_path, cap=1).used()
|
||
check("S4b_aged_unknown_embed_reservation_kept",
|
||
(not embed_second) and embed_used == 1 and embed_after_release == 0,
|
||
f"second_allowed={embed_second} used={embed_used} after_release={embed_after_release}")
|
||
|
||
|
||
def scenario_authority(tmp: Path) -> None:
|
||
fresh = tmp / "authority-fresh.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()
|
||
base = {"gateway_base_url": "http://127.0.0.1:9/v1", "gateway_model": "x",
|
||
"vector_root": str(tmp / "a-vec"), "history_root": str(tmp / "a-hist"),
|
||
"collection": "cg_a", "ledger_path": str(fresh),
|
||
"embed_cap": 100, "llm_cap": 1}
|
||
refused = ""
|
||
try:
|
||
Mem0Backend(dict(base))
|
||
except SemanticBudgetError as exc:
|
||
refused = str(exc)
|
||
empty_block = ""
|
||
try:
|
||
Mem0Backend({**base, "authority": {}})
|
||
except SemanticBudgetError as exc:
|
||
empty_block = str(exc)
|
||
check("S0_positive_caps_without_authority_fail_closed",
|
||
refused == "ledger_authority_required" and empty_block == "ledger_authority_required",
|
||
f"missing={refused} empty={empty_block}")
|
||
|
||
|
||
async def main() -> None:
|
||
server = contract.start_gateway()
|
||
with tempfile.TemporaryDirectory(dir=ROOT / "tools" if (ROOT / "tools").is_dir()
|
||
else None) as raw_tmp:
|
||
tmp = Path(raw_tmp)
|
||
try:
|
||
scenario_authority(tmp)
|
||
await scenario_partial_and_resume(tmp, server, "p1")
|
||
await scenario_lease_and_concurrency(tmp, server)
|
||
scenario_aged_reservations(tmp)
|
||
finally:
|
||
server.shutdown()
|
||
server.server_close()
|
||
REPORT["gateway_requests_total"] = len(contract.FakeGateway.requests)
|
||
REPORT["failures"] = FAILURES
|
||
out = Path(sys.argv[1] if len(sys.argv) > 1 else "hel885-recovery-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)
|
||
|
||
|
||
asyncio.run(main())
|