Files
CyberGril/tools/verify_close_ownership_hel894.py
T
zonggongandmultica-agent 152479b350 HEL-894 rework: a cancelled close owns nothing it did not start — aclose cancellation is now a two-phase ownership protocol - the manager's independent pinned-SDK review of ceb0f35 reproduced two combo holes in the HEL-889 close path: (1) cancelling aclose AFTER backend.aclose began made the shielded finish keep running unowned in the background while the outer except already released the lock and cleared closing — the layer was reported reusable (closing=false/closed=false/client usable), a new tick claimed a batch onto real HTTP, then the orphaned finish closed Qdrant under it (SDK-only branch: batch failed on 'QdrantLocal instance is closed' with row_done=0/llm_used=1; with the caller closing the store afterwards the late worker died on ProgrammingError 'Cannot operate on a closed database' and the reopened batch sat pending), and (2) cancelling a SECOND aclose that was still WAITING for the close lock ran the same except and cleared the FIRST closer's flag (first close still pending but signal=false, a new batch ran to done while the original worker was still on the wire). SemanticMemory.aclose now states the revocation boundary explicitly: the DRAIN phase (nothing closed yet) stays revocable — a cancelled caller leaves everything open, resets the closing signal and the layer remains usable (HEL-889 semantics preserved); the FINISH phase (backend.aclose begun) is irreversible — a cancelled caller keeps the closing markers (a half-closed layer is never reported usable, ticks keep refusing), keeps the lock, and waits — repeated cancels only re-shield — for the layer-owned close task it started (self._close_task, created exactly once with asyncio.create_task and stored on the layer, never dropped to the background) to land before propagating CancelledError, so resources close exactly once; _finish_close also joins this layer's OWN executor via asyncio.to_thread so a cancelled caller can never block the event loop on a synchronous shutdown wait (caller-injected executors stay caller-owned), and signal reset is ownership-gated by owns_close: only the call that actually acquired the lock and set the signal may clear it, and only while no close task exists — a lock waiter cancelled on acquisition touches nothing; module docstring, aclose docstring and the app lifespan comment state the same contract; verification: 299 python tests pass on 3.11.16 venv + requirements.lock offline (5 new tests/test_rework_hel894.py cases, all barrier-driven real product paths: finish-phase cancel keeps ownership and refuses new work with zero sends and zero budget / repeated cancels during finish land the close exactly once / a same-phase second aclose waits then returns idempotently while a third cancelled lock-waiter touches nothing / waiter-cancel + owner draining + refused new tick + original worker completing combo / drain-phase cancel still re-arms for reuse), 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_close_ownership_hel894.py 16/16 reruns the manager's two negatives in the same shape with assertions restated for the new protocol (F1 SDK-only: after the cancel closing=true/closed=false/client usable and the cancelled caller does not return before its close lands; the new tick is refused with zero gateway arrivals, batch queued/owner NULL/attempts 0 and llm_used=0; after the gate the close lands exactly once with live_workers=0 and the reopened batch is intact queued/row_done=0/llm_used=0 — before the fix the same run gave closing=false, a claimed batch, QdrantLocal instance is closed, failed/pending with row_done=0/llm_used=1; F2 + store-close branch: same shape and no late error — before: ProgrammingError; W waiter cancel: closing stays set, the new batch stays queued, the original worker completes done/row_done=1 after release and the owner's close then lands once); the manager's review_hel889_cancel.py re-run VERBATIM on the pristine ceb0f35 first reproduced both defects exactly (docs/rework/hel894/before-ceb0f35.json matches the manager's independent JSON), and on the fixed tree stops honestly at its own premise assert server.arrived — 'a finish-phase-cancelled layer still starts new real HTTP' is structurally gone because tick refuses while closing is held (verbatim-after-fix.log; original negative and baseline kept); regressions all green: verify_shutdown_queued_hel889.py 12/12 (queued cancel, timeout drain, between-rows resume, drain-cancel re-arm, concurrent close all preserved), verify_inflight_lifecycle_hel886.py 6/6, 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 (extra's uv rc=2 is its own expected negative), HEL-889 same-shape rerun review_hel886_edges_rerun_hel889.py passes; crash semantics unchanged and still honest (unknown wire outcomes billed, proof-gated retries, strict-once not claimed); runbook §4 gains the HEL-894 cancellation-ownership paragraph, docs/requirements/handoff-HEL-894.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:43:54 +08:00

274 lines
14 KiB
Python

#!/usr/bin/env python3
"""HEL-894 · 关闭所有权取消语义验证(零真实出站、零真实嵌入、零权威账写入)。
总管独立复审 review_hel889_cancel.py(固定 mem0 2.2.1 + 真实 Qdrant/OpenAI
client + 实际产品 tick/aclose)两个负例的修复后同形重跑。原脚本原件保留、
修复前基线见 docs/rework/hel894/before-ceb0f35.json;本轮断言按 HEL-894 新
安全协议改写(不再期待「取消后可续用」——提交阶段已不可撤销,tick 必须拒新,
关闭由层持有任务一次落成)。边界与 tools/verify_shutdown_queued_hel889.py 相
同:确定性 512 维替身(TextEmbedding 构造前安装)、127.0.0.1 假网关、临时
账/库;屏障只加在 client.close 之前,底层真实 close 照常执行;单线程执行器
由调用方注入持有,避免同步 shutdown 阻断观测。
F1 提交阶段取消(SDK-only,负例一同形):取消返回后 closing 保持置位、
closed 尚未落成、client 仍可用;新批 tick 被拒(网关零到达、批次仍
queued/owner NULL/attempts 0、llm_used=0);被取消的调用方等自己启动
的层持有关闭任务落成后才传播取消(closed=true、client 不可用、
live_workers=0、close 恰一次);重开:批次仍 queued、row_done=0、
llm_used=0。修复前:closing=false/closed=false/可用 → 新批被领 → 后台
旧 _finish 关 Qdrant → QdrantLocal instance is closed → failed/
row_done=0/llm_used=1。
F2 提交阶段取消 + 调用方随后关 Store(负例一加强分支,单独记录):同上,
且无任何晚到错误(修复前:ProgrammingError: Cannot operate on a closed
database,重开 pending/row_done=0/llm_used=1)。
W 等锁者取消(负例二同形):第一关闭排空中、第二关闭等锁即取消——
closing 保持置位(修复前被清掉);新批 tick 被拒仍 queued;原 worker
放行后完成 done/row_done=1;第一关闭随后一次收尾关库;新批保持 queued。
证据 JSON 写 argv[1]。运行(相邻目录 CyberGril 为被测 checkout,固定 venv):
/path/to/hel857-venv/bin/python tools/verify_close_ownership_hel894.py out.json
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import importlib.util
import json
import sys
import tempfile
import threading
from contextlib import suppress
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
spec = importlib.util.spec_from_file_location(
'edges', ROOT / 'tools/verify_shutdown_queued_hel889.py')
edges = importlib.util.module_from_spec(spec)
spec.loader.exec_module(edges) # installs the deterministic boundary on import
REPORT: dict = {"head": "HEL-894 close ownership under cancellation",
"real_llm_requests": 0, "real_embeddings": 0,
"boundary": "deterministic 512 vectors, non-loopback forbidden",
"protocol": "drain-phase cancel re-arms; finish-phase cancel keeps "
"markers, refuses ticks, lands the layer-owned close "
"exactly once; lock waiters never touch the owner's state"}
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 finish_cancel(tmp, close_store: bool) -> dict:
"""总管负例一同形:取消发生在真实 client.close 已进入之后。"""
server, thread = edges.start_blocking_gateway()
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
backend, _ = edges.backend_for(tmp, 'finish', server.server_address[1])
store = edges.Store(tmp / 'store.db')
live = edges.SemanticMemory(store, backend, executor=executor)
close_entered, close_release = threading.Event(), threading.Event()
close_calls = {"count": 0}
real_close = backend._client.close
def gated_close(*args, **kwargs):
close_calls["count"] += 1
close_entered.set()
assert close_release.wait(10)
return real_close(*args, **kwargs)
backend._client.close = gated_close
posts_before = len(edges.contract.FakeGateway.requests)
task = None
try:
closing = asyncio.create_task(live.aclose())
assert await asyncio.to_thread(close_entered.wait, 5) # backend.aclose BEGAN
closing.cancel()
await asyncio.sleep(0.05) # cancel lands in the owned-close tail
report = {'caller_done_after_cancel': closing.done(),
'after_cancellation': {'closing': live._closing.is_set(),
'closed': live._closed,
'client_usable': edges.client_usable(backend)}}
edges.seed_turn(store, 'new-turn', '关闭取消后继续相处的合成原话')
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
await asyncio.sleep(0.3) # a refused tick would have reached the wire by now
report['tick_during_closing'] = {
'gateway_arrived': server.arrived.is_set(),
'gateway_posts': len(edges.contract.FakeGateway.requests) - posts_before,
'llm_used': backend.llm_guard.used(),
'batch': edges.batch_row(store, 'new-turn')}
close_release.set()
with suppress(asyncio.CancelledError):
await closing # the layer-owned close lands, then the cancel propagates
assert await edges.wait_until(lambda: live._closed)
report['finish_landed'] = {'closed': live._closed,
'client_usable': edges.client_usable(backend),
'live_workers': len(live._live),
'close_calls': close_calls['count'],
'closing_still_set': live._closing.is_set(),
'batch': edges.batch_row(store, 'new-turn')}
if close_store:
store.close() # additional caller closure, recorded separately
server.release.set()
try:
await task
report['late_worker_error'] = None
except Exception as exc: # noqa: BLE001 — record, never hide
report['late_worker_error'] = f'{type(exc).__name__}: {exc}'
reopened = edges.Store(tmp / 'store.db')
report['persisted'] = {**edges.batch_row(reopened, 'new-turn'),
'row_done': len(reopened.query('SELECT * FROM sem_row_done')),
'llm_used': backend.llm_guard.used()}
reopened.close()
return report
finally:
close_release.set()
server.release.set()
if task is not None:
with suppress(BaseException):
await task
with suppress(BaseException):
await live.aclose()
store.close()
executor.shutdown(wait=True)
server.shutdown()
server.server_close()
thread.join()
async def waiter_cancel(tmp) -> dict:
"""总管负例二同形:等锁的第二个关闭被取消,不得动第一关闭者的信号。"""
server, thread = edges.start_blocking_gateway()
backend, _ = edges.backend_for(tmp, 'waiter', server.server_address[1])
store = edges.Store(tmp / 'store.db')
live = edges.SemanticMemory(store, backend)
edges.seed_turn(store, 'old', '已有活跃任务的合成原话')
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
close_one = close_two = None
try:
assert await asyncio.to_thread(server.arrived.wait, 5)
close_one = asyncio.create_task(live.aclose(drain_timeout=0.05))
assert await edges.wait_until(lambda: live._closing.is_set())
close_two = asyncio.create_task(live.aclose()) # still WAITING for the lock
await asyncio.sleep(0.05)
close_two.cancel()
with suppress(asyncio.CancelledError):
await close_two
report = {'active_close_pending': not close_one.done(),
'signal_after_waiter_cancel': live._closing.is_set()}
edges.seed_turn(store, 'new', '关闭期间不应新领任务的合成原话')
live.enqueue_uncovered()
await live.tick() # refused while the owner's close holds the layer
report['new_batch_during_closing'] = edges.batch_row(store, 'new')
report['original_batch_while_blocked'] = edges.batch_row(store, 'old')
posts_before_release = len(edges.contract.FakeGateway.requests)
server.release.set()
with suppress(BaseException):
await task
await close_one # drain completes, then the close lands once
report['after_release'] = {
'original_batch': edges.batch_row(store, 'old'),
'new_batch_still': edges.batch_row(store, 'new'),
'row_done': len(store.query('SELECT * FROM sem_row_done')),
# BlockingGateway records a POST only when its answer is allowed
# through, so the ONE post after release is the original worker's
# in-flight request landing — the refused new batch adds none.
'gateway_posts_after_release':
len(edges.contract.FakeGateway.requests) - posts_before_release,
'client_closed': not edges.client_usable(backend)}
return report
finally:
server.release.set()
with suppress(BaseException):
await task
if close_one is not None:
with suppress(BaseException):
await close_one
with suppress(BaseException):
await live.aclose()
store.close()
server.shutdown()
server.server_close()
thread.join()
def evaluate(f1: dict, f2: dict, w: dict) -> None:
for tag, f in (("F1", f1), ("F2", f2)):
check(f"{tag} cancelled caller does not return before its close lands",
f["caller_done_after_cancel"] is False)
check(f"{tag} markers stay: closing set, not yet closed, client untouched",
f["after_cancellation"]["closing"] is True
and f["after_cancellation"]["closed"] is False
and f["after_cancellation"]["client_usable"] is True,
json.dumps(f["after_cancellation"], ensure_ascii=False))
check(f"{tag} tick during closing claims nothing and sends nothing",
f["tick_during_closing"]["gateway_arrived"] is False
and f["tick_during_closing"]["gateway_posts"] == 0
and f["tick_during_closing"]["llm_used"] == 0
and f["tick_during_closing"]["batch"]["state"] == "queued"
and f["tick_during_closing"]["batch"]["owner"] is None
and f["tick_during_closing"]["batch"]["attempts"] == 0,
json.dumps(f["tick_during_closing"], ensure_ascii=False))
check(f"{tag} layer-owned close lands exactly once, no live workers",
f["finish_landed"]["closed"] is True
and f["finish_landed"]["client_usable"] is False
and f["finish_landed"]["live_workers"] == 0
and f["finish_landed"]["close_calls"] == 1
and f["finish_landed"]["closing_still_set"] is True,
json.dumps(f["finish_landed"], ensure_ascii=False))
check(f"{tag} no late error", f["late_worker_error"] is None, str(f["late_worker_error"]))
check(f"{tag} reopened batch intact and unbilled",
f["persisted"]["state"] == "queued" and f["persisted"]["owner"] is None
and f["persisted"]["row_done"] == 0 and f["persisted"]["llm_used"] == 0,
json.dumps(f["persisted"], ensure_ascii=False))
check("W owner close still pending, waiter cancel keeps the signal",
w["active_close_pending"] is True and w["signal_after_waiter_cancel"] is True,
json.dumps({k: w[k] for k in ("active_close_pending",
"signal_after_waiter_cancel")}, ensure_ascii=False))
check("W new batch refused during the owner's close",
w["new_batch_during_closing"]["state"] == "queued"
and w["new_batch_during_closing"]["owner"] is None,
json.dumps(w["new_batch_during_closing"], ensure_ascii=False))
check("W original batch still actively owned while blocked",
w["original_batch_while_blocked"]["state"] == "pending"
and bool(w["original_batch_while_blocked"]["owner"]),
json.dumps(w["original_batch_while_blocked"], ensure_ascii=False))
check("W original worker completes, one close, new batch untouched",
w["after_release"]["original_batch"]["state"] == "done"
and w["after_release"]["row_done"] == 1
and w["after_release"]["new_batch_still"]["state"] == "queued"
and w["after_release"]["gateway_posts_after_release"] == 1
and w["after_release"]["client_closed"] is True,
json.dumps(w["after_release"], ensure_ascii=False))
async def main_async() -> dict:
with tempfile.TemporaryDirectory(prefix='hel894-close-') as directory:
root = Path(directory)
f1 = await finish_cancel(root / 'sdk-only', False)
f2 = await finish_cancel(root / 'finish', True)
w = await waiter_cancel(root / 'waiter')
evaluate(f1, f2, w)
REPORT['finish_cancel_sdk_only'] = f1
REPORT['finish_cancel_then_store_close'] = f2
REPORT['waiter_cancel'] = w
def main() -> int:
asyncio.run(main_async())
REPORT["failures"] = FAILURES
out = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'hel894-close.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())