Files
CyberGril/tools/verify_shutdown_queued_hel889.py
T
zonggongandmultica-agent 440d95cad8 HEL-889 rework: shutdown never closes under a live worker, and a queued-cancelled worker is released by the authoritative future state — SemanticMemory now runs batch workers on its OWN dedicated ThreadPoolExecutor and keeps each work item's concurrent.futures.Future: cancelling the awaiting tick propagates to that future, and its post-cancel state is the deterministic queued/started oracle (the manager's review_hel886_edges.py reproduced the old false-liveness on the shared default executor: register _live, await to_thread, executor busy -> cancel tick cancels the QUEUED item, _run and its finally never run, _live=1 forever with the batch pending and recovery permanently skipping a worker that does not exist, restart the only way out; now a CANCELLED future proves nothing ever ran: _release_never_started removes the registry entry idempotently and returns the batch to queued with its attempt restored and zero sends, while a running/finished future keeps HEL-886 semantics — the worker thread owns the batch fate, single send, no reclaim, no resend), and aclose becomes a real ownership protocol instead of a bounded promise it could break: a closing flag makes tick refuse new claims and makes both backends' _add_group_sync check should_stop BEFORE each row's wire work (a _ShutdownAbort at a boundary keeps finished rows' sem_row_done proofs and requeues only the unsent remainder — never a mid-row cut, and a single-row batch still completes done); never-started workers are cancelled out of the executor queue under the same authoritative CANCELLED proof; started workers finish their current row and flush, and aclose WAITS for every live worker to actually exit before backend/executor close — drain_timeout only bounds the polite phase (after expiry: honest warning, keep waiting; a live worker is never treated as dead), bounded in practice because Mem0Backend now sets the gateway OpenAI client's timeout (gateway_timeout config, default 60s) instead of the 600s default that made the drain effectively open-ended; a cancelled aclose closes NOTHING (shielded finish, closing signal reset, layer stays usable), concurrent aclose calls serialize on an asyncio.Lock and are idempotent, and the app lifespan comment now states the ownership contract — the manager's fixed-SDK reproduction of the OLD timeout branch (loopback gateway accepts the first HTTP then withholds the answer, aclose(drain_timeout=0.05) returns with the worker alive, app closes the store, late worker dies on 'QdrantLocal instance is closed'/'Cannot operate on a closed database', reopen shows pending/row_done=0/llm_used=1) is closed: aclose does not return while the worker is alive, the worker's writes land BEFORE the app-order store.close(), and the reopened store shows done + row_done=1 + full entry_ids with llm_used=1 and zero late errors; crash semantics unchanged and still honest (unknown wire outcomes billed, proof-gated retries, strict-once not claimed); verification: 294 python tests pass on 3.11.16 venv + requirements.lock offline (7 new tests/test_rework_hel889.py cases, all barrier-driven real product paths: queued-cancel release + in-process recovery via injected single-worker executor / shutdown-timeout never closes under the live worker and flushes before app-order store close / between-rows abort requeues and the next process sends ONLY the missing row / shutdown-before-start zero sends then resumes / cancelled aclose leaves everything open / concurrent aclose serializes / closed layer refuses new claims), ruff clean (src/tests/tools), no frontend changes (frontend checks not re-run, stated honestly); pinned mem0 2.2.1 on the deterministic boundary (512-dim stand-in before TextEmbedding construction, loopback-only): new tools/verify_shutdown_queued_hel889.py 12/12 (Q1 queued-cancel phantom released and recovered in-process with the manager's 41s lease probe, S1 fixed-SDK shutdown-timeout branch, S2 between-rows abort + missing-row-only resume proven by gateway POST counts, S3 cancelled aclose, S4 concurrent aclose), the manager's review_hel886_edges.py re-run VERBATIM on the pristine f1b50ad first reproduced both defects exactly (docs/rework/hel889/edges-verbatim-before-fix-f1b50ad.json matches the manager's independent JSON), the same-shape rerun review_hel886_edges_rerun_hel889.py now passes both scenarios with every original result key (queued: done/attempts=1/registered 0/entries 1/row_done 1; timeout: aclose_returned_while_worker_alive=false, late_worker_error null, persisted done+entry_ids+row_done=1, llm_used=1) while the verbatim original stops at its own premise assert executor._work_queue.qsize()==1 — batch workers no longer ride the loop default executor, the encoded defect is structurally gone (original negative and baseline kept); regressions all green: verify_inflight_lifecycle_hel886.py 6/6 (single-send preserved), 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, review_hel885_inflight.py still fails at its 2-add barrier exactly as documented in HEL-886; runbook §4 gains the HEL-889 ownership/queued-cancel semantics, config/semantic.example.yaml documents gateway_timeout, docs/requirements/handoff-HEL-889.json written, dual-target requirement checks 4/4 (origin/main and origin/agent/agent/de8874a3803b, with and without handoff); 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 01:24:11 +08:00

414 lines
19 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-889 · 关闭所有权与排队取消验证(零真实出站、零真实嵌入、零权威账写入)。
在固定 mem0ai 2.2.1(hel857-venv)+ 真实嵌入式 Qdrant + 真实 OpenAI 客户端上
复现总管独立复审(review_hel886_edges.py)的两个缺口并证明修复。边界口径与
tools/verify_mem0_real_hel874.py 相同:确定性 512 维替身(TextEmbedding 构造前
安装)、127.0.0.1 假网关、临时账/库。全部场景在同一进程内推进。
Q1 排队未开始取消(总管原负例同形,阻塞改在本产品专用批执行器上):单
worker 执行器被无关任务占住,批次 worker 只入队未启动即取消 tick——
concurrent.futures 的 CANCELLED 是权威「从未运行」证明:假活跃注册项立即
释放、批次回 queued 且 attempts 复原(修复前:pending/_live=1 永久卡死,
只能重启);释放执行器、推进 41 秒后 recover+tick 进程内完成:1 条目、
1 sem_row_done、注册表清零。
S1 关闭超时(固定 SDK 实跑,总管原负例同形):回环网关先接受第一 HTTP 但
阻塞应答,aclose(drain_timeout=0.05)(默认 120 秒的同一超时分支)在
worker 仍活时绝不返回(修复前:返回后 app 关 store,晚到 worker 报
Cannot operate on a closed database,重开仍 pending/row_done=0);应答放
行后 worker 完成并落盘,aclose 才返回、才关 client;按 app 顺序关库重开:
批 done、row_done=1、entry_ids 完整、llm_used=1、无任何晚到错误。
S2 行间中止:两行批次第一 HTTP 阻塞中 aclose;放行后第 1 行保留完成证明,
批次回 queued/shutdown_between_rows;下一进程只发缺行(网关 POST 仅 +1),
done 且两行 entry_ids 完整——不重发已证明行,也不把中止行伪装完成。
S3 关闭被取消:排空等待中的 aclose 任务被取消——什么都没关(client 仍可用、
批次仍 pending),closing 信号复位;worker 正常完成 done;随后再次 aclose
干净收尾。
S4 并发关闭:两个 aclose 同时进入——串行化、排空一次、资源只关一次、批次
done;第三次调用立即返回(幂等)。
证据 JSON 写 argv[1]。运行(仓库根,固定 venv):
/path/to/hel857-venv/bin/python tools/verify_shutdown_queued_hel889.py out.json
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import importlib.util
import json
import sys
import tempfile
import threading
import time
from contextlib import suppress
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 Mem0Backend, SemanticMemory, StubBackend # noqa: E402 — after boundary
from cybergril.memory.store import Store # noqa: E402
REPORT: dict = {"head": "HEL-889 shutdown ownership & queued-cancel",
"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)
async def wait_until(predicate, timeout=5.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
await asyncio.sleep(0.01)
return False
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))
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,))
class BlockingGateway(contract.FakeGateway):
"""First POST on this server is accepted but the answer is withheld —
the manager's exact repro shape."""
def do_POST(self): # noqa: N802 — http.server contract
if not getattr(self.server, "accepted", None):
self.server.accepted = [1]
self.server.arrived.set()
if not self.server.release.wait(20):
raise RuntimeError("test barrier timed out")
super().do_POST()
def start_blocking_gateway():
server = contract._Server(('127.0.0.1', 0), BlockingGateway)
server.accepted = []
server.arrived, server.release = threading.Event(), threading.Event()
thread = threading.Thread(target=server.serve_forever)
thread.start()
return server, thread
def backend_for(tmp: Path, name: str, port: int):
tmp.mkdir(parents=True, exist_ok=True)
ledger = tmp / f"{name}.sqlite3"
contract.make_ledger(ledger, cap=100, llm_cap=10)
cfg = contract.config_for(tmp / f"{name}-ledgers", ledger, port=port, cap=100, llm_cap=10)
cfg["vector_root"] = str(tmp / f"{name}-vec")
cfg["history_root"] = str(tmp / f"{name}-hist")
return Mem0Backend(cfg), cfg
def batch_row(store: Store, turn_id: str | None = None) -> dict:
sql = "SELECT state,reason,owner,attempts,entry_ids FROM sem_batch"
row = (store.query_one(sql + " WHERE turn_id=?", (turn_id,)) if turn_id
else store.query_one(sql))
return dict(row) if row else {}
def client_usable(backend: Mem0Backend) -> bool:
try:
backend._client.get_collections()
return True
except Exception:
return False
# ------------------------------------------------------------------ Q1 (stub)
async def q1_queued_cancel(tmp: Path) -> dict:
"""总管原负例同形:单 worker 执行器占住、worker 仅入队即取消。"""
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(20)))
assert entered.wait(5)
store = Store(tmp / "q1.db")
seed_turn(store, "edge", "排队取消边界合成原话")
clock = [1000.0]
backend = StubBackend()
live = SemanticMemory(store, backend, clock=lambda: clock[0], executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await wait_until(lambda: live._live
and all(not h.started.is_set() for h in live._live.values()))
queued_snapshot = {"registered_workers": len(live._live),
"product_executor_queue": live._executor._work_queue.qsize()}
task.cancel()
with suppress(asyncio.CancelledError):
await task
released = {"registered_workers": len(live._live),
"batch": batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done")),
"stored_entries": len(backend._entries)}
release.set()
blocker.result(timeout=5)
clock[0] += 41 # 总管的租约到期探针
live.recover()
await live.tick()
final = {"batch": batch_row(store),
"registered_workers": len(live._live),
"stored_entries": len(backend._entries),
"row_done": len(store.query("SELECT * FROM sem_row_done"))}
await live.aclose(drain_timeout=0)
store.close()
executor.shutdown(wait=True)
return {"queued": queued_snapshot, "after_cancel": released, "after_recovery": final}
# ------------------------------------------------------------- S1..S4 (real)
async def s1_shutdown_timeout(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s1", server.server_address[1])
store = Store(tmp / "s1.db")
seed_turn(store, "turn-s1", "独立关闭边界合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.4) # 超时分支已过,worker 仍活
deadline_state = {"aclose_returned_while_worker_alive": closing.done(),
"batch_before_any_close": batch_row(store),
"client_usable": client_usable(backend)}
server.release.set()
await closing
before_store_close = batch_row(store)
late_error = None
with suppress(asyncio.CancelledError, Exception):
try:
await task
except Exception as exc: # noqa: BLE001 — record, never hide
late_error = f"{type(exc).__name__}: {exc}"
store.close() # 与 app lifespan 完全相同的顺序,此刻安全
check_store = Store(tmp / "s1.db")
persisted = {**batch_row(check_store),
"row_done": len(check_store.query("SELECT * FROM sem_row_done")),
"llm_used": backend.llm_guard.used(),
"gateway_posts": len(contract.FakeGateway.requests)}
check_store.close()
return {"deadline": deadline_state, "before_store_close": before_store_close,
"late_worker_error": late_error, "persisted": persisted}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s2_between_rows(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, cfg = backend_for(tmp, "s2", server.server_address[1])
db = tmp / "s2.db"
store = Store(db)
seed_turn(store, "turn-s2", "行间关闭第一行原话", "行间关闭第二行原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
posts_before = len(contract.FakeGateway.requests)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.2)
server.release.set()
await closing
after_shutdown = {**batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done")),
"gateway_posts_during_shutdown":
len(contract.FakeGateway.requests) - posts_before}
with suppress(asyncio.CancelledError, Exception):
await task
store.close()
backend2 = Mem0Backend(cfg) # 下一进程:同账同库,无新批准
store2 = Store(db)
live2 = SemanticMemory(store2, backend2)
await live2.tick()
resumed = {**batch_row(store2),
"row_done": len(store2.query("SELECT * FROM sem_row_done")),
"gateway_posts_resume":
len(contract.FakeGateway.requests) - posts_before}
await live2.aclose()
store2.close()
return {"after_shutdown": after_shutdown, "after_resume": resumed}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s3_cancelled_aclose(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s3", server.server_address[1])
store = Store(tmp / "s3.db")
seed_turn(store, "turn-s3", "关闭被取消的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.2)
closing.cancel()
with suppress(asyncio.CancelledError):
await closing
after_cancel = {"client_usable": client_usable(backend),
"batch": batch_row(store),
"closing_cleared": not live._closing.is_set()}
server.release.set()
with suppress(asyncio.CancelledError, Exception):
await task
after_worker = batch_row(store)
await live.aclose()
return {"after_cancel": after_cancel, "after_worker": after_worker,
"client_usable_after_real_close": client_usable(backend)}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s4_concurrent_aclose(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s4", server.server_address[1])
store = Store(tmp / "s4.db")
seed_turn(store, "turn-s4", "并发关闭的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
first = asyncio.create_task(live.aclose(drain_timeout=0.05))
second = asyncio.create_task(live.aclose(drain_timeout=30))
await asyncio.sleep(0.2)
server.release.set()
await asyncio.gather(first, second)
done_state = {**batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done"))}
await live.aclose() # 幂等
with suppress(asyncio.CancelledError, Exception):
await task
return {"batch": done_state, "client_usable_after_close": client_usable(backend)}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
def evaluate(q1: dict, s1: dict, s2: dict, s3: dict, s4: dict) -> None:
# Q1: 排队取消立即恢复(总管负例:pending/_live=1 永久卡死)
check("Q1 queued snapshot shows phantom-liveness", q1["queued"]["registered_workers"] == 1
and q1["queued"]["product_executor_queue"] == 1)
check("Q1 cancel releases registry and requeues",
q1["after_cancel"]["registered_workers"] == 0
and q1["after_cancel"]["batch"]["state"] == "queued"
and q1["after_cancel"]["batch"]["attempts"] == 0
and q1["after_cancel"]["stored_entries"] == 0,
json.dumps(q1["after_cancel"], ensure_ascii=False))
check("Q1 in-process recovery completes without restart",
q1["after_recovery"]["batch"]["state"] == "done"
and q1["after_recovery"]["registered_workers"] == 0
and q1["after_recovery"]["stored_entries"] == 1
and q1["after_recovery"]["row_done"] == 1,
json.dumps(q1["after_recovery"], ensure_ascii=False))
# S1: 关闭超时不再把活 worker 当死(总管负例:aclose 返回→关库→丢落盘)
check("S1 aclose does NOT return while the worker is alive",
s1["deadline"]["aclose_returned_while_worker_alive"] is False
and s1["deadline"]["client_usable"] is True)
check("S1 worker completes and flushes before store close",
s1["before_store_close"]["state"] == "done"
and json.loads(s1["before_store_close"]["entry_ids"] or "[]"),
json.dumps(s1["before_store_close"], ensure_ascii=False))
check("S1 no late-worker error after honest drain", s1["late_worker_error"] is None)
check("S1 durable reopen: done + row_done=1 + llm_used=1",
s1["persisted"]["state"] == "done" and s1["persisted"]["row_done"] == 1
and s1["persisted"]["llm_used"] == 1,
json.dumps(s1["persisted"], ensure_ascii=False))
# S2: 行间中止保留证明、下一进程只发缺行
check("S2 shutdown between rows requeues with first row proven",
s2["after_shutdown"]["state"] == "queued"
and "shutdown" in (s2["after_shutdown"]["reason"] or "")
and s2["after_shutdown"]["row_done"] == 1
and s2["after_shutdown"]["gateway_posts_during_shutdown"] == 1,
json.dumps(s2["after_shutdown"], ensure_ascii=False))
check("S2 resume sends ONLY the missing row and completes",
s2["after_resume"]["state"] == "done"
and s2["after_resume"]["row_done"] == 2
and s2["after_resume"]["gateway_posts_resume"] == 2
and len(json.loads(s2["after_resume"]["entry_ids"] or "[]")) == 2,
json.dumps(s2["after_resume"], ensure_ascii=False))
# S3: 被取消的关闭什么都不关
check("S3 cancelled aclose closes nothing and re-arms",
s3["after_cancel"]["client_usable"] is True
and s3["after_cancel"]["batch"]["state"] == "pending"
and s3["after_cancel"]["closing_cleared"] is True)
check("S3 worker finishes done and a later aclose closes for real",
s3["after_worker"]["state"] == "done"
and s3["client_usable_after_real_close"] is False)
# S4: 并发关闭串行化、只关一次
check("S4 concurrent aclose drains once and closes once",
s4["batch"]["state"] == "done" and s4["batch"]["row_done"] == 1
and s4["client_usable_after_close"] is False,
json.dumps(s4, ensure_ascii=False))
async def main_async() -> None:
with tempfile.TemporaryDirectory(prefix="hel889-edges-") as td:
tmp = Path(td)
q1 = await q1_queued_cancel(tmp / "q1")
s1 = await s1_shutdown_timeout(tmp / "s1")
s2 = await s2_between_rows(tmp / "s2")
s3 = await s3_cancelled_aclose(tmp / "s3")
s4 = await s4_concurrent_aclose(tmp / "s4")
evaluate(q1, s1, s2, s3, s4)
REPORT["queued_cancel"] = q1
REPORT["shutdown_timeout"] = s1
REPORT["between_rows"] = s2
REPORT["cancelled_aclose"] = s3
REPORT["concurrent_aclose"] = s4
def main() -> int:
asyncio.run(main_async())
REPORT["failures"] = FAILURES
out = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "hel889-edges.json"
out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"ok": not FAILURES, "checks": len(REPORT.get("checks", [])),
"failures": FAILURES, "out": str(out)}, ensure_ascii=False))
return 1 if FAILURES else 0
if __name__ == "__main__":
raise SystemExit(main())