Files
CyberGril/docs/rework/hel889/review_hel886_edges_rerun_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

159 lines
6.7 KiB
Python

"""HEL-889 rerun of the manager's review_hel886_edges.py — same scenarios,
adjusted to the FIXED contracts.
Adjustments vs the original (before/after documented, negative preserved):
1. queued_cancel: the congestion blocker now occupies the PRODUCT's dedicated
batch executor (``SemanticMemory(executor=...)`` — HEL-889 moved batch
workers off the loop's shared default executor onto a dedicated one this
layer owns, precisely so the queue/started truth is observable). The
original blocked the loop default executor because ``to_thread`` put the
worker there; that premise no longer holds, and re-run verbatim the
original stops at its own ``assert live._live and
executor._work_queue.qsize() == 1`` (original-verbatim-after-fix.log — the
queued defect it encoded is gone). This rerun keeps every step of the
manager's sequence: cancel the tick while queued, release, clock +41s,
recover + tick, and the same result fields.
2. shutdown_timeout: identical gateway, identical ``aclose(drain_timeout=0.05)``
(the default-120s branch). The original released the wire barrier only
AFTER ``store.close()`` — an ordering the fixed ownership protocol forbids
(aclose returns only once the live worker exited, so store.close() can
never precede the worker's flush). The barrier is therefore released by a
timer thread 0.3s into the drain; every result key of the original is kept.
Everything else — real pinned SDK, real Qdrant, real OpenAI client,
deterministic 512-dim stand-in installed before TextEmbedding construction,
loopback-only gateway, temp ledgers — is unchanged.
"""
import asyncio
import concurrent.futures
import importlib.util
import json
import sys
import tempfile
import threading
from pathlib import Path
ROOT = Path(__file__).resolve().parent
REPO = ROOT / 'CyberGril'
sys.path.insert(0, str(REPO / 'src'))
spec = importlib.util.spec_from_file_location('contract', REPO / 'tools/verify_mem0_real_hel874.py')
c = importlib.util.module_from_spec(spec)
spec.loader.exec_module(c)
c.install_deterministic_boundary()
from cybergril.memory.semantic import SemanticMemory, StubBackend, Mem0Backend
from cybergril.memory.store import Store
def seed(store):
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1,'user','独立关闭边界合成原话','edge','sent')")
async def queued_cancel(tmp):
store = Store(tmp / 'queued.db')
seed(store)
clock = [1000.0]
backend = StubBackend()
# HEL-889: batch workers run on the layer's OWN executor — the manager's
# congestion now blocks exactly that one.
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(8)))
assert entered.wait(2)
live = SemanticMemory(store, backend, clock=lambda: clock[0], executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
for _ in range(500):
if live._live and all(not h.started.is_set() for h in live._live.values()):
break
await asyncio.sleep(0.01)
assert live._live and executor._work_queue.qsize() == 1
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
release.set()
blocker.result(timeout=2)
await asyncio.sleep(0.05)
clock[0] += 41
live.recover()
await live.tick()
result = {'batch': dict(store.query_one('SELECT state,owner,attempts FROM sem_batch')),
'registered_workers': len(live._live), 'stored_entries': len(backend._entries),
'row_done': len(store.query('SELECT * FROM sem_row_done')),
'executor_queue_size': executor._work_queue.qsize()}
# There is no worker remaining: only a false registry handle prevents recovery.
await live.aclose(drain_timeout=0)
store.close()
executor.shutdown(wait=True)
return result
async def shutdown_timeout(tmp):
arrived, release = threading.Event(), threading.Event()
class Gateway(c.FakeGateway):
def do_POST(self):
arrived.set()
if not release.wait(8):
raise RuntimeError('barrier timed out')
super().do_POST()
server = c._Server(('127.0.0.1', 0), Gateway)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
c.make_ledger(tmp / 'ledger.db', cap=100, llm_cap=10)
cfg = c.config_for(tmp, tmp / 'ledger.db', port=server.server_address[1], cap=100, llm_cap=10)
backend = Mem0Backend(cfg)
store = Store(tmp / 'shutdown.db')
seed(store)
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
try:
assert await asyncio.to_thread(arrived.wait, 3)
# Same code branch as the default 120s deadline, shortened for a bounded test.
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.3) # deadline long past, worker still alive
result = {'aclose_returned_while_worker_alive': closing.done(),
'batch_before_store_close': dict(store.query_one(
'SELECT state,entry_ids FROM sem_batch'))}
# The fixed protocol never closes under a live worker: the wire answer
# must arrive (here via timer) BEFORE aclose can return and the app
# order store.close() runs.
threading.Timer(0.2, release.set).start()
await closing
result['batch_before_store_close'] = dict(store.query_one(
'SELECT state,entry_ids FROM sem_batch'))
store.close()
try:
await task
result['late_worker_error'] = None
except Exception as exc:
result['late_worker_error'] = f'{type(exc).__name__}: {exc}'
check = Store(tmp / 'shutdown.db')
result['persisted_batch'] = dict(check.query_one('SELECT state,entry_ids FROM sem_batch'))
result['persisted_row_done'] = len(check.query('SELECT * FROM sem_row_done'))
result['llm_used'] = backend.llm_guard.used()
check.close()
return result
finally:
release.set()
server.shutdown()
server.server_close()
server_thread.join()
with tempfile.TemporaryDirectory(dir=ROOT) as td:
tmp = Path(td)
report = {'head': 'HEL-889 same-shape rerun of review_hel886_edges.py (fixed tree)',
'real_llm': 0, 'real_embeddings': 0,
'queued_cancel': asyncio.run(queued_cancel(tmp)),
'shutdown_timeout': asyncio.run(shutdown_timeout(tmp))}
(ROOT / 'HEL-889-edges-rerun-fixed.json').write_text(
json.dumps(report, ensure_ascii=False, indent=2))
print(json.dumps(report, ensure_ascii=False, indent=2))