Files
CyberGril/tools/verify_inflight_lifecycle_hel886.py
T
zonggongandmultica-agent f1b50ad91a HEL-886 rework: a live worker is never treated as dead, and a fully-completed batch finalizes without new budget - SemanticMemory gains an in-process live-worker registry (batch_id -> _LiveWorker, registered BEFORE the thread starts, so the batch is provably active from the moment the claim commits) and the batch's whole execution (row building, anchor verify, resume set, real adds, terminal sem_batch write) moves INTO the worker thread function, because asyncio.to_thread cannot interrupt a running call: cancelling the tick cancels only the waiter, and the old finally that marked the still-running batch failed and cleared its owner was the exact double-send the manager reproduced live with the pinned SDK (first HTTP accepted but unanswered -> cancel tick -> failed written while the add was on the wire -> second tick re-claimed and sent the same sentence again: 2 HTTP, 2 vectors, 1 row_done entry, the late worker's result dropped); recover() now fails only expired pending batches WITHOUT a live worker, so a lease past 40s with the thread still inside its add is never reclaimed and concurrent ticks cannot re-send an active row (same 1-HTTP/1-vector/1-record outcome on the manager's clock-injection lease variant), while a genuinely dead owner (crash/restart, no registered worker) keeps the honest conservative recovery: unknown wire outcome, ledger holds stay billed (HEL-885), the retry sends only rows without a completion proof, and strict-once is NOT claimed for arbitrary crashes without remote idempotency (module docstring + runbook say so in words); new SemanticMemory.aclose() drains live workers (bounded wait, honest warning on timeout) BEFORE backend/store close so shutdown never orphans durable writes, and the app lifespan now drains through it; Mem0Backend/StubBackend extract the sync core _add_group_sync (async add_group contract unchanged) where the completion set (vector-store anchors + sem_row_done + skip) is proven BEFORE any budget gate: a batch whose every row is already complete returns done with ZERO new HTTP/embed/LLM after restart (the manager's third example: llm_cap=1 fully spent, row really completed, 'row persisted, final status did not' crash window -> was queued/semantic_llm_budget_exhausted, now done with entry_ids intact, cap unchanged, nothing refunded), while any missing row keeps the hard fail-closed gate - finalization never buys headroom; verification: 287 python tests pass on 3.11.16 venv + requirements.lock offline (6 new tests/test_rework_hel886.py cases: in-flight cancel never double-sends / expired lease with live worker never reclaims + concurrent ticks single-send / dead-owner lease still recovers / shutdown drains the live worker before close proven by post-aclose durable writes / all-rows-done restart finalizes with zero new HTTP / partially-done keeps refusing), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned mem0 2.2.1 on the deterministic boundary (512-dim stand-in installed before TextEmbedding construction, loopback-only): the manager's review_hel885_inflight.py re-run VERBATIM now fails exactly at its worker_done 2-add barrier (the assertion that a second send must happen; before the fix the same script passed with 2 HTTP/2 vectors - baseline JSON kept), the same-shape rerun with the barrier at ONE completed add passes both scenarios with 1 HTTP/1 vector/1 sem_row_done, batch pending while in flight, done with full entry_ids, and the all-done restart finalizes done with zero new HTTP and llm_used still 1; new tools/verify_inflight_lifecycle_hel886.py 6/6 (L1 cancel single-send full record, L2 lease-expired-live no reclaim, L3 shutdown drain before close, L4a all-done finalize without budget, L4b partial keeps the hard gate, L5 dead-owner recovery still works); regressions all green: verify_semantic_recovery_hel885.py 7/7, verify_mem0_real_hel874.py 12/12, check_release_offline_hel882.py R1-R7 15/15, both manager review_hel882_{partial,extra}.py scripts re-run verbatim pass; dual-target requirement checks 4/4 with handoff-HEL-886.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:30:47 +08:00

327 lines
15 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-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())