274 lines
14 KiB
Python
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())
|