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>
This commit is contained in:
zonggong
2026-10-27 01:24:11 +08:00
co-authored by multica-agent
parent f1b50ad91a
commit 440d95cad8
28 changed files with 2178 additions and 48 deletions
+4 -2
View File
@@ -262,8 +262,10 @@ def create_app(
app.state.active["cancel"].set()
await app.state.active["finished"].wait()
if app.state.semantic:
# HEL-886: drain live batch workers BEFORE the vector-store
# client / SQLite store close under their durable writes.
# HEL-889 shutdown ownership: aclose returns only after every
# live batch worker has actually exited (drain_timeout bounds
# the polite phase, never a licence to close under a worker),
# so the provider clients and the store below close safely.
await app.state.semantic.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
+251 -46
View File
@@ -61,11 +61,27 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
row and the terminal ``sem_batch`` state itself. A lease that expires while
its worker is still registered LIVE is never reclaimed (a blocked HTTP call
is not a dead owner) and no concurrent tick resends rows of an active
batch; shutdown drains live workers before closing the vector-store client
and the SQLite store under them. For genuinely dead processes the recovery
stays honest: the crashed attempt's wire outcome is UNKNOWN (its ledger
holds stay billed), the retry sends only rows without a completion proof,
and strict-once delivery is NOT claimed for arbitrary crashes.
batch. For genuinely dead processes the recovery stays honest: the crashed
attempt's wire outcome is UNKNOWN (its ledger holds stay billed), the retry
sends only rows without a completion proof, and strict-once delivery is NOT
claimed for arbitrary crashes.
- Shutdown ownership & queued-worker truth (HEL-889): ``aclose`` NEVER closes
the vector-store client (or lets the SQLite store close) under a worker
that may still write — the manager reproduced the old drain-timeout branch
returning with a live worker, the app closing the store, and the late
worker dying on ``Cannot operate on a closed database`` with its durable
writes lost. The protocol: a closing flag stops new claims and stops
workers between rows (before a row's wire work begins, never mid-row);
never-started workers are cancelled out of the executor queue where
``concurrent.futures`` CANCELLED state is AUTHORITATIVE (provably nothing
sent → safe reschedule, attempt restored); started workers finish their
current row (every wire call is bounded by the gateway client timeout set
at construction) and flush before any resource closes — ``drain_timeout``
bounds only the polite phase, it is never a licence to close under a live
worker. A cancelled ``aclose`` leaves everything open (nothing
half-closed); a queued worker whose waiter was cancelled is released by the
deterministic CANCELLED check, so the old false-registry "phantom worker
that only a restart could clear" can no longer pin a batch pending forever.
- Completed-work finalization needs no new budget (HEL-886): a batch whose
every row already carries a completion proof finalizes to ``done`` with
zero new HTTP/embed/LLM — recovery of the "row persisted, final status did
@@ -77,6 +93,9 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
from __future__ import annotations
import asyncio
import concurrent.futures
import contextlib
import contextvars
import hashlib
import json
import logging
@@ -107,6 +126,16 @@ class SemanticBudgetError(RuntimeError):
"""
class _ShutdownAbort(Exception):
"""aclose() asked a worker to stop BEFORE a row's wire work began.
Raised at a row boundary only (never mid-row): rows that already
finished keep their durable ``sem_row_done`` proofs, the unsent remainder
returns to the queue for the next process, and no wire outcome is left
ambiguous — nothing was in flight when the abort fired.
"""
def _request_definitely_unsent(exc: BaseException) -> bool:
"""True only when the failure provably happened before anything hit the wire.
@@ -177,17 +206,20 @@ class StubBackend:
def _add_group_sync(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""Per-row mirror of the mem0 contract: one entry per row, each with
that row's own anchor (HEL-885) — orchestration progress parity. The
sync core runs inside the HEL-886 batch worker thread like the real
backend's."""
backend's; ``should_stop`` (HEL-889) is checked before each row so a
shutdown aborts only at a boundary, never mid-row."""
def _add() -> list[dict]:
done = self.completed_message_ids(batch_key) | set(skip)
send = [r for r in rows if r["message_id"] not in done]
created = []
for row in send:
if should_stop is not None and should_stop():
raise _ShutdownAbort()
row_anchor = {
"turn_ids": [row["turn_id"]],
"turn_roles": [[row["turn_id"], row["role"], row["message_id"]]],
@@ -209,9 +241,10 @@ class StubBackend:
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
self._add_group_sync, rows, anchor, batch_key, skip=skip,
on_row_done=on_row_done, should_stop=should_stop)
async def search(self, query: str, limit: int = 5) -> list[dict]:
def _search() -> list[dict]:
@@ -645,6 +678,10 @@ class Mem0Backend:
self.request_guard = request_guard
self.extract_scene = config.get("extract_scene", "mem0_extract")
self._failures = threading.local()
# HEL-889: every wire call is bounded so the shutdown drain phase has
# a real upper bound — an accepted-but-never-answered gateway call can
# never pin a worker (and aclose) open-endedly.
self.gateway_timeout = float(config.get("gateway_timeout", 60.0))
self.collection = config.get("collection", "cg_public")
self.user_scope = config.get("user_scope", "cybergril")
vector_root = Path(config["vector_root"])
@@ -696,6 +733,11 @@ class Mem0Backend:
client = getattr(llm, "client", None)
if client is not None and hasattr(client, "max_retries"):
client.max_retries = 0
if client is not None:
# HEL-889 bounded-wire guarantee (see __init__): the default 600s
# client timeout would make aclose's drain effectively unbounded.
with contextlib.suppress(Exception):
client.timeout = self.gateway_timeout
def _record_failure(reason: str) -> None:
failures = getattr(self._failures, "list", None)
@@ -823,9 +865,11 @@ class Mem0Backend:
def _add_group_sync(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""Synchronous core of ``add_group`` — callable from an already-running
worker thread (the HEL-886 batch worker owns the whole execution)."""
worker thread (the HEL-886 batch worker owns the whole execution).
``should_stop`` (HEL-889) is checked before each row's wire work: a
shutdown aborts at a boundary with nothing in flight, never mid-row."""
# HEL-886: prove the remaining work BEFORE any budget gate. A batch
# whose every row already carries a completion proof (vector anchor or
# sem_row_done) finalizes with ZERO new HTTP/embed/LLM — recovery of a
@@ -842,6 +886,11 @@ class Mem0Backend:
self.llm_guard.check(1)
created = []
for row in send:
if should_stop is not None and should_stop():
# aclose() arrived: do not START this row's wire work. Rows
# already finished keep their durable proofs; the remainder
# returns to the queue — nothing was left in flight.
raise _ShutdownAbort()
# Per-row anchor: this add's input set is exactly this row.
row_anchor = {
"turn_ids": [row["turn_id"]],
@@ -878,7 +927,7 @@ class Mem0Backend:
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""One entry per row, each carrying that row's own anchor (HEL-885).
``skip`` holds message_ids already proven complete (vector-store
@@ -886,10 +935,12 @@ class Mem0Backend:
re-sent. ``on_row_done(row, entries)`` fires in the worker thread as
soon as one row's add fully finished (empty extraction included), so
the caller can durably record per-row progress even if the process
dies mid-batch.
dies mid-batch. ``should_stop`` (HEL-889) aborts BEFORE a row's wire
work when shutdown asks for it — a boundary, never a mid-row cut.
"""
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
self._add_group_sync, rows, anchor, batch_key, skip=skip,
on_row_done=on_row_done, should_stop=should_stop)
async def search(self, query: str, limit: int = 5) -> list[dict]:
self.ledger.check(1) # the query embed is accounted inside the wrapper
@@ -951,7 +1002,8 @@ EmbedLedgerGuard.debit = _ledger_debit
class _LiveWorker:
"""In-process handle on a batch worker thread that is REALLY running.
"""In-process handle on a batch worker thread — queued, started or
running to completion.
HEL-886: the batch's durable fate belongs to its worker thread, never to
the coroutine that happened to start it. A task cancellation cancels only
@@ -961,19 +1013,28 @@ class _LiveWorker:
as this handle is registered, the batch is actively owned — lease expiry
must NOT reclaim it (a slow/blocked call is not a dead owner) and no
concurrent tick may resend its rows.
HEL-889: ``started`` separates QUEUED from STARTED — the registry is
written before submission, but a handle whose work item never left the
executor queue is NOT a live thread, and the cancelling waiter (or
aclose) releases it via the authoritative ``concurrent.futures``
CANCELLED state instead of waiting for a ``finally`` that will never run.
"""
__slots__ = ("batch_id", "owner", "done")
__slots__ = ("batch_id", "owner", "done", "started", "future")
def __init__(self, batch_id: int, owner: str) -> None:
self.batch_id, self.owner = batch_id, owner
self.done = threading.Event()
self.started = threading.Event()
self.future: concurrent.futures.Future | None = None
class SemanticMemory:
"""Owns the batch queue, the anchors and the fail-closed read gate."""
def __init__(self, store, backend, *, clock=time.time) -> None:
def __init__(self, store, backend, *, clock=time.time,
executor: concurrent.futures.Executor | None = None) -> None:
self.store, self.backend, self.clock = store, backend, clock
self.public = PublicView(store)
# HEL-886 live-worker registry: batch_id → handle. Guarded by its own
@@ -981,6 +1042,20 @@ class SemanticMemory:
# threads while the SQLite paths keep their own transactions.
self._live: dict[int, _LiveWorker] = {}
self._live_lock = threading.Lock()
# HEL-889 shutdown ownership: batch workers run on a DEDICATED
# executor so this layer holds the ``concurrent.futures.Future`` for
# each work item — the authoritative queued/started oracle — and a
# blocked batch call can never starve the loop's shared default
# executor (search/close paths). ``_closing`` is the cooperative stop
# signal; ``_aclose_lock``/``_closed`` make aclose idempotent and
# concurrency-safe. A caller-injected executor (verification barrier
# setups) stays caller-owned — never shut down here.
self._owns_executor = executor is None
self._executor = executor or concurrent.futures.ThreadPoolExecutor(
max_workers=4, thread_name_prefix="cg-semantic-batch")
self._closing = threading.Event()
self._aclose_lock = asyncio.Lock()
self._closed = False
# ------------------------------------------------------------ enqueue
def public_rows_for_turn(self, turn_id: str) -> list[dict]:
@@ -1084,7 +1159,46 @@ class SemanticMemory:
(now, now, *dead),
)
# ------------------------------------------------------------ worker truth
def _requeue_owned(self, batch_id: int, owner: str, reason: str) -> None:
"""Return a batch THIS process still owns to the queue.
HEL-889: used only where the stop provably left nothing unresolved on
the wire (never started, or aborted at a row boundary before the next
row's send) — the attempt is restored so a later tick re-claims it.
Unknown wire outcomes never pass through here; those stay
conservative (HEL-885/886: billed holds, proof-gated retries).
"""
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state='queued',reason=?,owner=NULL,lease_until=NULL,"
"attempts=MAX(0,attempts-1) WHERE id=? AND owner=? AND state='pending'",
(reason, batch_id, owner),
)
def _release_never_started(self, handle: _LiveWorker, reason: str) -> None:
"""Release a worker whose work item provably NEVER ran.
Idempotent and race-safe: only the caller that actually removes the
handle from the registry performs the batch requeue, so the waiter
cancel path and aclose's queue-cancel path can both fire without
double-restoring the attempt. ``future.cancelled()`` (checked by the
callers) is the authoritative guarantee that no thread will ever
execute ``_run`` — there is no queue/started race to lose.
"""
with self._live_lock:
released = self._live.get(handle.batch_id) is handle
if released:
del self._live[handle.batch_id]
handle.done.set()
if released:
self._requeue_owned(handle.batch_id, handle.owner, reason)
async def tick(self) -> None:
if self._closing.is_set():
# Shutdown owns the process from here: no new claims may start
# real work aclose would then have to drain (HEL-889).
return
self.recover()
owner, now = secrets.token_hex(16), int(self.clock() * 1000)
with self.store.conn:
@@ -1138,10 +1252,25 @@ class SemanticMemory:
failed/abandoned — that was the double-send defect: the cancelled
waiter wrote ``failed``, a second tick reclaimed the batch and
re-sent rows whose first HTTP was still in flight.
HEL-889: ``started`` is set as the FIRST statement, so the
registry always distinguishes a queued item (releasable via the
authoritative future CANCELLED state) from a real thread; a
closing signal aborts BEFORE any outbound work (nothing sent,
attempt restored) or at a row boundary (``_ShutdownAbort`` from
the backend's ``should_stop``), never mid-row.
"""
handle.started.set()
state, reason, entry_ids = "failed", "extraction_failed", None
row_entries: list[str] = []
try:
if self._closing.is_set():
# Shutdown won the race before this worker began: nothing
# was sent, so handing the batch straight back to the
# queue is provably safe.
self._requeue_owned(job["id"], owner, "shutdown_before_start")
state = "queued"
return
anchor = json.loads(job["anchor_json"])
rows = []
for turn_id, role, message_id in anchor["turn_roles"]:
@@ -1160,11 +1289,18 @@ class SemanticMemory:
done_ids |= {r["message_id"] for r in self.store.query(
"SELECT message_id FROM sem_row_done WHERE batch_id=?", (job["id"],))}
created = self.backend._add_group_sync(
rows, anchor, job["batch_key"], skip=done_ids, on_row_done=_row_done)
rows, anchor, job["batch_key"], skip=done_ids, on_row_done=_row_done,
should_stop=lambda: self._closing.is_set())
row_entries.extend(e["id"] for e in created if e["id"] not in row_entries)
entry_ids = json.dumps(
list(dict.fromkeys(row_entries)), ensure_ascii=False)
state, reason = "done", None
except _ShutdownAbort:
# aclose() stopped this batch at a row boundary: finished rows
# keep their durable proofs, the unsent remainder returns to
# the queue for the next process — nothing was in flight.
self._requeue_owned(job["id"], owner, "shutdown_between_rows")
state = "queued"
except Exception as exc: # noqa: BLE001 — job isolation, reason recorded
reason = str(exc) or exc.__class__.__name__
if "budget" in reason:
@@ -1204,41 +1340,110 @@ class SemanticMemory:
with self._live_lock:
self._live.pop(job["id"], None)
# HEL-889: submit through OUR executor and keep the underlying
# ``concurrent.futures.Future`` — cancelling the awaiting task
# propagates to it, and its post-cancel state is the authoritative
# queued/started oracle (no queue-to-thread race to guess at).
ctx = contextvars.copy_context()
future = self._executor.submit(ctx.run, _run)
handle.future = future
try:
await asyncio.to_thread(_run)
await asyncio.wrap_future(future)
except asyncio.CancelledError:
# Only the WAITER was cancelled. The worker thread keeps running
# and writes the batch's durable fate itself; abandoning it as
# "failed" here would let the next tick double-send rows whose
# first HTTP is still in flight (the HEL-886 defect). Nothing to
# clean up — _run owns the registry entry.
# Two provably different cancel windows (HEL-889 P2):
# - CANCELLED: the work item never left the executor queue, no
# thread will EVER run _run (its finally can never clean up).
# Release the false registry entry and hand the batch back to
# the queue — nothing was sent, the attempt is restored.
# - already started/finished: the worker thread owns the batch
# fate (HEL-886) — it writes its durable state and unregisters
# itself; abandoning it here would re-open the double-send.
if future.cancelled():
self._release_never_started(handle, "queued_worker_cancelled")
raise
async def aclose(self, *, drain_timeout: float = 120.0) -> None:
"""Shutdown order (HEL-886): drain OUR still-running workers first.
"""Shutdown ownership protocol (HEL-889): resources NEVER close under
a worker that may still write.
A live worker holds an open HTTP call and will write ``sem_row_done``
and the terminal batch state when it returns; closing the vector-store
client or the SQLite store under it would orphan exactly those durable
writes. Waits up to ``drain_timeout`` seconds, then closes the backend
anyway with an honest warning — the workers' registry entries stay
conservative (their rows resend only without a completion proof).
The manager reproduced the old timeout branch: ``aclose`` gave up
after ``drain_timeout``, the backend closed, the app closed the
store, and the still-running worker died on ``Cannot operate on a
closed database`` with its durable writes lost. Now:
1. the closing flag stops new claims (``tick`` returns) and stops
workers at the NEXT row boundary — before a row's wire work
begins, never mid-row;
2. never-started workers are cancelled out of the executor queue
outright: a ``concurrent.futures`` CANCELLED item provably never
ran, so releasing it and rescheduling its batch is safe;
3. aclose WAITS until every live worker has actually exited.
``drain_timeout`` bounds only the polite phase — after it expires
we log honestly and KEEP WAITING: a live worker may be holding an
accepted-but-unanswered HTTP whose durable write must land, and
treating it as dead is exactly the lost-write window this closes.
Every worker operation is bounded (the gateway client timeout
bounds the wire, set at construction; everything else is local),
so the wait terminates in practice;
4. only then the backend and this layer's executor close.
Idempotent and concurrency-safe: concurrent callers serialize on one
lock; a caller cancelled mid-drain leaves everything OPEN (nothing
half-closed, the closing signal reset) for a later aclose to finish.
For genuinely dead processes the crash semantics stay conservative
(HEL-885/886): unknown wire outcomes stay billed, retries send only
rows without a completion proof, strict-once is not claimed.
"""
deadline = time.monotonic() + drain_timeout
while True:
with self._live_lock:
handles = list(self._live.values())
if not handles:
break
left = deadline - time.monotonic()
if left <= 0:
log.warning("semantic shutdown drain: %d live batch worker(s) still running "
"after %.0fs — closing anyway, their outcome stays unknown",
len(handles), drain_timeout)
break
await asyncio.to_thread(
lambda hs=handles, lv=left: [h.done.wait(min(lv, 1.0)) for h in hs])
await self.backend.aclose()
if self._closed:
return
try:
async with self._aclose_lock:
if self._closed:
return
self._closing.set()
deadline = time.monotonic() + drain_timeout
warned = False
while True:
with self._live_lock:
handles = list(self._live.values())
if not handles:
break
for handle in handles:
future = handle.future
if (not handle.started.is_set() and future is not None
and future.cancel()):
# Provably never started — release and reschedule
# right here; the queue-to-thread race cannot
# exist once cancel() itself succeeded.
self._release_never_started(handle, "shutdown_queued_cancelled")
with self._live_lock:
remaining = len(self._live)
if not remaining:
break
if not warned and time.monotonic() >= deadline:
warned = True
log.warning(
"semantic shutdown drain: %d live batch worker(s) still "
"running after %.0fs — close signal set, waiting for their "
"bounded exit before any resource closes (a live worker is "
"never treated as dead)", remaining, drain_timeout)
await asyncio.sleep(0.05)
async def _finish() -> None:
await self.backend.aclose()
if self._owns_executor:
self._executor.shutdown(wait=True)
self._closed = True
# Shielded: once draining is complete the closes themselves
# run to completion even if this caller is cancelled.
await asyncio.shield(_finish())
except asyncio.CancelledError:
if not self._closed:
# A cancelled close leaves NOTHING half-closed and re-arms the
# layer: ticks may continue, a later aclose drains again.
self._closing.clear()
raise
# ------------------------------------------------------------ read gate
def chain_resolve(self, hit: dict) -> dict: