Files
CyberGril/tools/verify_semantic_recovery_hel885.py
T
zonggongandmultica-agent 78b6267d3a HEL-885 rework: per-row progress matches what was really sent, cross-day and unknown-outcome accounting stay conservative, positive caps require the ledger authority, and the release dependency-fill command actually exists - every Memory.add now carries an anchor for exactly its own row (the HEL-882 whole-batch anchor let the first stored vector mark unsent rows complete; the manager's real-SDK partial reproduction showed the user's original words never leaving the process), a row finishing with a legitimately EMPTY extraction gets a durable sem_row_done record (r4.sql additive table) written inside the worker thread the moment its add completes, resume skips = vector-store anchors ∪ sem_row_done so no row is lost, none falsely complete, and finished work is never re-sent across budget-refusal/crash/restart/lease/concurrency, entry_ids merge across partial attempts, and the swallowed-failure detection is per-row; PersistentBudget.settle/release book on hold.day (the old write to state.day manufactured -80 used on the new day and re-opened headroom the reservation day had already spent; token_usage/request_usage refund the paying day, budget_total stays global) and the empty-budget_total TypeError crash in total_requests_used/total_tokens_used is fixed - the old one-shot-total test passed only because that crash surfaced as chat.error, it now books the total honestly; _atomic_reserve no longer purges aged reserve: rows (a crashed worker's hold is an UNKNOWN outcome - an hour-old timeout is not proof the call never happened; unknown consumption stays billed across restarts, only a provably-unsent release() ever removes a hold, embed_ops and llm_ops share the fix); Mem0Backend refuses construction before importing mem0 when any cap>0 lacks a (non-empty dict) authority block - ledger_authority_required - or when the prefix check fails, closing the fresh-empty-ledger bypass the manager reproduced live, config/semantic.example.yaml ships the authority block as REQUIRED with the explicit cumulative formula (embed_cap=500+approved-increment e.g. 680, embed_reserve=2 frozen untouched, min_used=498; never write 180 as the cumulative cap of a 498-used account) mirrored into docs/budget-plan-hel874.md §2 with the HEL-885 accounting rules; deploy/hel874-release.md §4 replaces the nonexistent uv pip download (rc=2, re-verified) with python3 -m pip download --only-binary :all: --platform manylinux2014_x86_64 --python-version 3.11 --implementation cp --abi cp311 + sha256 manifest + uv pip install --no-index --find-links offline merge + same-process co-import verdict, honest missing-materials list unchanged (no 3.11 wheels cached, zero downloads this card, no version swaps), and tools/check_release_offline_hel882.py gains R7 probing both command surfaces offline; verification: 281 python tests pass on 3.11.16 venv + requirements.lock offline (9 new tests/test_rework_hel885.py cases: partial batch claims only the sent row / empty-extraction row completes and is never resent / process restart sends only the missing row / concurrent ticks never double-send / cross-day settle and release book on the reservation day / aged unknown llm+embed reservations never refunded / missing-empty-malformed-wrong authority all fail closed; test_resume_never_loses_or_duplicates_rows rewritten to drive the REAL product path instead of hand-planting single-row anchors the product never wrote), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned mem0 2.2.1 install on the deterministic boundary: contract re-run 12/12 (harness now hands a synthetic authority prefix - production defaults not relaxed), new tools/verify_semantic_recovery_hel885.py 7/7 (S0 authority fail-closed, S1 per-row partial with exactly 1 HTTP, S2 restart sends only the missing row proven by HTTP count since mem0 prompts legitimately carry old rows in rolling history, S3 lease recovery + concurrent ticks single-send, S4a/S4b unknown reservations kept), both manager review scripts re-run VERBATIM against this head (partial: completed=[2] only, resume done with 2 entries, HTTP=2, user words actually sent; extra: new-day used=0, over-cap request refused, aged reservation second_allowed=false, uv probe still rc=2), release offline check R1-R7 green, dual-target requirement checks 4/4 with handoff-HEL-885.json; zero real LLM, 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-27 00:01:44 +08:00

267 lines
12 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-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())