159 lines
6.7 KiB
Python
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))
|