#!/usr/bin/env python3 """HEL-886 · 实际固定 SDK 处理中生命周期验证(零真实出站、零真实嵌入、零权威账写入)。 在固定 mem0ai 2.2.1(hel857-venv)+ 真实嵌入式 Qdrant + 真实 OpenAI 客户端上复现 总管独立复审(review_hel885_inflight.py)的两个缺口并证明修复。边界口径与 tools/verify_mem0_real_hel874.py 相同:确定性 512 维替身(TextEmbedding 构造前 安装)、127.0.0.1 假网关、临时账/库。回环网关会阻塞第一份 HTTP 应答,模拟 「第一请求已被服务端接受但尚未返回」,全部场景在同一进程内推进。 L1 处理中取消:取消只取消等待协程;worker 线程完成并发送终态。第二/第三次 tick 不重发;最终 1 HTTP、1 向量、1 条 sem_row_done、批次 done 且 entry_ids 完整(修复前:2 HTTP、2 向量、只记 1 条)。 L2 跨租约仍活跃:注入时钟前进 41 秒,worker 仍在第一请求里;recover 不回收 活跃批次,并发 tick 不重发(修复前:同样双发)。 L3 关闭排空:aclose 先排空仍在运行的 worker(其后才关 vector client), worker 的持久写在排空等待期间落盘。 L4a 全行已完成的重启收尾:llm_cap=1 全部用完且单行已真实完成,落「行完成已 持久、批状态未写」的崩溃窗口后重启——零新 HTTP、cap 不变即 done, entry_ids 完整(修复前:queued/semantic_llm_budget_exhausted)。 L4b 部分未完成仍走硬闸:还有缺行且额度耗尽时,重启后依旧拒绝,不为收尾放行。 L5 真死 owner 的租约回收仍有效:无活跃 worker 的过期 pending 照常 failed/ lease_expired 并重试(未因修复而停用恢复)。 证据 JSON 写 argv[1]。运行(仓库根,固定 venv): /path/to/hel857-venv/bin/python tools/verify_inflight_lifecycle_hel886.py out.json """ from __future__ import annotations import asyncio import contextlib import importlib.util import json import sys import tempfile import threading import time from pathlib import Path @contextlib.contextmanager def _suppress_cancel(): with contextlib.suppress(asyncio.CancelledError, Exception): yield 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 Mem0Backend, SemanticMemory # noqa: E402 — after boundary from cybergril.memory.store import Store # noqa: E402 REPORT: dict = {"head": "HEL-886 inflight lifecycle", "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_turn(store: Store, turn_id: str, user_text: str, companion_text: str | None = None): with store.conn: store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES" "(1,'user',?,?,'sent')", (user_text, turn_id)) ids = [store.query_one("SELECT id FROM chat_message WHERE text=?", (user_text,))["id"]] if companion_text is not None: 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,)) ids.append(store.query_one( "SELECT id FROM chat_message WHERE text=?", (companion_text,))["id"]) return ids async def blocked_first_http(kind: str, tmp: Path): """L1/L2/L3 share the shape: one real add accepted by the loopback gateway, answer withheld; the manager's exact repro.""" first_arrived, release = threading.Event(), threading.Event() class Gateway(contract.FakeGateway): def do_POST(self): # noqa: N802 — http.server contract if len(getattr(self.server, "accepted", [])) == 0: self.server.accepted.append(1) first_arrived.set() if not release.wait(15): raise RuntimeError("test barrier timed out") super().do_POST() server = contract._Server(('127.0.0.1', 0), Gateway) server.accepted = [] thread = threading.Thread(target=server.serve_forever) thread.start() try: ledger = tmp / f"{kind}.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 / f"{kind}-vec") cfg["history_root"] = str(tmp / f"{kind}-hist") backend = Mem0Backend(cfg) store = Store(tmp / f"{kind}.db") clock = [1000.0] live = SemanticMemory(store, backend, clock=lambda: clock[0]) seed_turn(store, f"turn-{kind}", f"处理中原话{kind}") live.enqueue_uncovered() mark = len(contract.FakeGateway.requests) task = asyncio.create_task(live.tick()) assert await asyncio.to_thread(first_arrived.wait, 5) # "arrived" = accepted by the loopback server, answer still withheld # (FakeGateway.requests only logs on completion, after the barrier). http_arrived = len(server.accepted) batch_live = dict(store.query_one("SELECT state,owner FROM sem_batch")) if kind == "cancel": task.cancel() with contextlib.suppress(asyncio.CancelledError): await task elif kind == "lease": clock[0] += 41 live.recover() # concurrent scheduler ticks while the first HTTP is unanswered await asyncio.wait_for(live.tick(), 8) await asyncio.wait_for(live.tick(), 8) http_concurrent = len(server.accepted) batch_concurrent = dict(store.query_one("SELECT state FROM sem_batch")) if kind == "drain": def _answer(): # the wire answer arrives while shutdown is waiting clock[0] = 2000 release.set() timer = threading.Timer(0.2, _answer) timer.start() started = time.monotonic() await live.aclose(drain_timeout=10) waited = time.monotonic() - started row = store.query_one("SELECT * FROM sem_row_done") batch = dict(store.query_one("SELECT state,finished_at FROM sem_batch")) check("L3_shutdown_drains_live_worker_before_close", http_concurrent == 1 and waited >= 0.15 and row is not None and row["done_at"] >= 2000 and batch["state"] == "done" and batch["finished_at"] >= 2000, f"arrived={http_concurrent} waited={waited:.2f}s row_done_at=" f"{row and row['done_at']} batch={batch}") with _suppress_cancel(): await task timer.join() store.close() return {} release.set() if not task.cancelled(): await task for _ in range(300): # the WORKER thread writes the terminal state if store.query_one("SELECT state FROM sem_batch")["state"] != "pending": break await asyncio.sleep(0.02) # the drain path waits for the worker's durable writes, then closes points, _ = backend._client.scroll(collection_name=backend.collection, with_payload=True, limit=100) await live.aclose(drain_timeout=10) await asyncio.sleep(0.05) http_total = len(contract.FakeGateway.requests) - mark rows = store.query("SELECT * FROM sem_row_done") batch = dict(store.query_one("SELECT state,reason,entry_ids FROM sem_batch")) store.close() check(f"L{'1' if kind == 'cancel' else '2'}_{kind}_single_send_and_full_record", http_arrived == 1 and http_concurrent == 1 and http_total == 1 and len(points) == 1 and batch_live["state"] == "pending" and batch_live["owner"] and batch_concurrent["state"] == "pending" and batch["state"] == "done" and batch["reason"] is None and len(rows) == 1 and json.loads(batch["entry_ids"] or "[]") == json.loads(rows[0]["entry_ids"]), f"arrived={http_arrived} concurrent={http_concurrent} http_total={http_total} " f"points={len(points)} batch_live={batch_live} " f"batch_concurrent={batch_concurrent['state']} final={batch} row_done={len(rows)}") return {} finally: release.set() server.shutdown() server.server_close() thread.join() async def scenario_all_done_restart(tmp: Path): """L4a: the manager's third example — fully-completed batch finalizes after restart with zero new budget. L4b: a missing row keeps the hard gate.""" ledger = tmp / "alldone.sqlite3" contract.make_ledger(ledger, cap=100, llm_cap=1) cfg = contract.config_for(tmp, ledger, port=_gateway_port, cap=100, llm_cap=1) cfg["vector_root"] = str(tmp / "alldone-vec") cfg["history_root"] = str(tmp / "alldone-hist") backend = Mem0Backend(cfg) db = tmp / "alldone.db" store = Store(db) seed_turn(store, "turn-done", "完整处理的合成原话") live = SemanticMemory(store, backend) live.enqueue_uncovered() mark = len(contract.FakeGateway.requests) await live.tick() original = dict(store.query_one("SELECT state,entry_ids FROM sem_batch")) with store.conn: # crash window: row persisted, final status did not store.execute("UPDATE sem_batch SET state='pending',owner='crashed',lease_until=1") store.close() await backend.aclose() backend2 = Mem0Backend(cfg) # same caps — nothing new approved store2 = Store(db) live2 = SemanticMemory(store2, backend2) await live2.tick() after = dict(store2.query_one("SELECT state,reason,entry_ids FROM sem_batch")) http = len(contract.FakeGateway.requests) - mark used = backend2.llm_guard.used() check("L4a_all_done_finalizes_without_new_budget", original["state"] == "done" and after["state"] == "done" and after["reason"] is None and http == 1 and used == 1 and json.loads(after["entry_ids"] or "[]") == json.loads(original["entry_ids"]), f"before={original} after={after} http={http} llm_used={used}") store2.close() await backend2.aclose() async def scenario_partial_keeps_gate(tmp: Path): """L4b: one row still missing + budget exhausted → restart keeps refusing.""" ledger = tmp / "partial.sqlite3" contract.make_ledger(ledger, cap=100, llm_cap=1) cfg = contract.config_for(tmp, ledger, port=_gateway_port, cap=100, llm_cap=1) cfg["vector_root"] = str(tmp / "partial-vec") cfg["history_root"] = str(tmp / "partial-hist") backend = Mem0Backend(cfg) db = tmp / "partial.db" store = Store(db) seed_turn(store, "turn-partial", "部分完成用户原话", "部分完成伴侣原话") live = SemanticMemory(store, backend) live.enqueue_uncovered() await live.tick() # one row sent, the other budget-refused with store.conn: store.execute("UPDATE sem_batch SET state='pending',owner='crashed',lease_until=1") store.close() await backend.aclose() backend2 = Mem0Backend(cfg) store2 = Store(db) live2 = SemanticMemory(store2, backend2) mark = len(contract.FakeGateway.requests) await live2.tick() after = dict(store2.query_one("SELECT state,reason FROM sem_batch")) http = len(contract.FakeGateway.requests) - mark check("L4b_partial_keeps_the_hard_gate", after["state"] == "queued" and "budget" in (after["reason"] or "") and http == 0, f"after={after} http={http}") store2.close() await backend2.aclose() async def scenario_dead_lease(tmp: Path): """L5: recovery of a genuinely dead owner is NOT disabled by the fix.""" ledger = tmp / "deadlease.sqlite3" contract.make_ledger(ledger, cap=100, llm_cap=10) cfg = contract.config_for(tmp, ledger, port=_gateway_port, cap=100, llm_cap=10) cfg["vector_root"] = str(tmp / "dead-vec") cfg["history_root"] = str(tmp / "dead-hist") backend = Mem0Backend(cfg) store = Store(tmp / "dead.db") seed_turn(store, "turn-dead", "真正死亡第一行", "真正死亡第二行") live = SemanticMemory(store, backend) live.enqueue_uncovered() 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() await live.aclose(drain_timeout=5) after = dict(store.query_one("SELECT state FROM sem_batch")) http = len(contract.FakeGateway.requests) - mark check("L5_dead_owner_lease_still_recovers", job["state"] == "failed" and job["reason"] == "lease_expired" and after["state"] == "done" and http == 2, f"recovered={job} after={after} http={http}") store.close() _gateway_port: int = 0 async def main() -> None: global _gateway_port server = contract.start_gateway() _gateway_port = server.server_address[1] with tempfile.TemporaryDirectory(dir=ROOT / "tools") as raw_tmp: tmp = Path(raw_tmp) try: await blocked_first_http("cancel", tmp) await blocked_first_http("lease", tmp) await blocked_first_http("drain", tmp) await scenario_all_done_restart(tmp) await scenario_partial_keeps_gate(tmp) await scenario_dead_lease(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 "hel886-inflight-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())