HEL-886 rework: a live worker is never treated as dead, and a fully-completed batch finalizes without new budget - SemanticMemory gains an in-process live-worker registry (batch_id -> _LiveWorker, registered BEFORE the thread starts, so the batch is provably active from the moment the claim commits) and the batch's whole execution (row building, anchor verify, resume set, real adds, terminal sem_batch write) moves INTO the worker thread function, because asyncio.to_thread cannot interrupt a running call: cancelling the tick cancels only the waiter, and the old finally that marked the still-running batch failed and cleared its owner was the exact double-send the manager reproduced live with the pinned SDK (first HTTP accepted but unanswered -> cancel tick -> failed written while the add was on the wire -> second tick re-claimed and sent the same sentence again: 2 HTTP, 2 vectors, 1 row_done entry, the late worker's result dropped); recover() now fails only expired pending batches WITHOUT a live worker, so a lease past 40s with the thread still inside its add is never reclaimed and concurrent ticks cannot re-send an active row (same 1-HTTP/1-vector/1-record outcome on the manager's clock-injection lease variant), while a genuinely dead owner (crash/restart, no registered worker) keeps the honest conservative recovery: unknown wire outcome, ledger holds stay billed (HEL-885), the retry sends only rows without a completion proof, and strict-once is NOT claimed for arbitrary crashes without remote idempotency (module docstring + runbook say so in words); new SemanticMemory.aclose() drains live workers (bounded wait, honest warning on timeout) BEFORE backend/store close so shutdown never orphans durable writes, and the app lifespan now drains through it; Mem0Backend/StubBackend extract the sync core _add_group_sync (async add_group contract unchanged) where the completion set (vector-store anchors + sem_row_done + skip) is proven BEFORE any budget gate: a batch whose every row is already complete returns done with ZERO new HTTP/embed/LLM after restart (the manager's third example: llm_cap=1 fully spent, row really completed, 'row persisted, final status did not' crash window -> was queued/semantic_llm_budget_exhausted, now done with entry_ids intact, cap unchanged, nothing refunded), while any missing row keeps the hard fail-closed gate - finalization never buys headroom; verification: 287 python tests pass on 3.11.16 venv + requirements.lock offline (6 new tests/test_rework_hel886.py cases: in-flight cancel never double-sends / expired lease with live worker never reclaims + concurrent ticks single-send / dead-owner lease still recovers / shutdown drains the live worker before close proven by post-aclose durable writes / all-rows-done restart finalizes with zero new HTTP / partially-done keeps refusing), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned mem0 2.2.1 on the deterministic boundary (512-dim stand-in installed before TextEmbedding construction, loopback-only): the manager's review_hel885_inflight.py re-run VERBATIM now fails exactly at its worker_done 2-add barrier (the assertion that a second send must happen; before the fix the same script passed with 2 HTTP/2 vectors - baseline JSON kept), the same-shape rerun with the barrier at ONE completed add passes both scenarios with 1 HTTP/1 vector/1 sem_row_done, batch pending while in flight, done with full entry_ids, and the all-done restart finalizes done with zero new HTTP and llm_used still 1; new tools/verify_inflight_lifecycle_hel886.py 6/6 (L1 cancel single-send full record, L2 lease-expired-live no reclaim, L3 shutdown drain before close, L4a all-done finalize without budget, L4b partial keeps the hard gate, L5 dead-owner recovery still works); regressions all green: 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; dual-target requirement checks 4/4 with handoff-HEL-886.json; 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 00:30:47 +08:00
co-authored by multica-agent
parent 78b6267d3a
commit f1b50ad91a
17 changed files with 1809 additions and 118 deletions
+3 -1
View File
@@ -262,7 +262,9 @@ def create_app(
app.state.active["cancel"].set()
await app.state.active["finished"].wait()
if app.state.semantic:
await app.state.semantic.backend.aclose()
# HEL-886: drain live batch workers BEFORE the vector-store
# client / SQLite store close under their durable writes.
await app.state.semantic.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
store.close()
+266 -117
View File
@@ -55,6 +55,22 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
counted forever — a lease expiring is not proof the call never happened.
Only ``release()`` with provably-unsent evidence (nothing hit the wire)
ever removes a hold.
- Live-worker lifecycle (HEL-886): the batch's durable fate is written by its
worker THREAD, not by the coroutine that started it. Cancelling the waiter
cancels only the wait — the thread finishes, records ``sem_row_done`` per
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.
- 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
not" crash window no longer demands balance. Rows still missing keep the
hard fail-closed gate; finalization never raises a cap or refunds a hold.
- The stub backend is an orchestration double for engineering verification and
isolated tests only; it is not semantic and never claimed as such.
"""
@@ -65,6 +81,7 @@ import hashlib
import json
import logging
import secrets
import threading
import time
from datetime import datetime
from pathlib import Path
@@ -158,11 +175,13 @@ class StubBackend:
self._entries: dict[str, dict] = {}
self._seq = 0
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str, *,
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]:
"""Per-row mirror of the mem0 contract: one entry per row, each with
that row's own anchor (HEL-885) — orchestration progress parity."""
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."""
def _add() -> list[dict]:
done = self.completed_message_ids(batch_key) | set(skip)
@@ -186,7 +205,13 @@ class StubBackend:
on_row_done(row, [entry])
return created
return await asyncio.to_thread(_add)
return _add()
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]:
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
async def search(self, query: str, limit: int = 5) -> list[dict]:
def _search() -> list[dict]:
@@ -796,6 +821,61 @@ class Mem0Backend:
break
return done
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]:
"""Synchronous core of ``add_group`` — callable from an already-running
worker thread (the HEL-886 batch worker owns the whole execution)."""
# 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
# crash window where "row done persisted, final status did not" must
# not demand new balance. Rows still missing keep the hard gate below:
# finalization never buys headroom, refunds nothing, raises no cap.
done = self.completed_message_ids(batch_key) | set(skip)
send = [r for r in rows if r["message_id"] not in done]
if not send:
return []
# Fail closed before ANY real work while either budget is unapproved:
# a 2.2.1 add always spends ≥1 embed item and 1 extraction LLM call.
self.ledger.check(1)
self.llm_guard.check(1)
created = []
for row in send:
# Per-row anchor: this add's input set is exactly this row.
row_anchor = {
"turn_ids": [row["turn_id"]],
"turn_roles": [[row["turn_id"], row["role"], row["message_id"]]],
"input_sha256": anchor_fingerprint([row]),
}
failures_before = len(getattr(self._failures, "list", []) or [])
result = self._memory.add(
row["text"], metadata={"src_group": batch_key, **row_anchor},
user_id=self.user_scope,
)
# mem0 2.2.1 swallows per-text embed failures into empty
# results (phase-3/7 fallback loops). An empty extraction is
# legitimate only when no embed/refusal happened during THIS
# row's add: if our guards refused anything, that refusal is
# the truth, not the empty list.
failures = (getattr(self._failures, "list", []) or [])[failures_before:]
if failures:
raise SemanticBudgetError(f"semantic_add_swallowed_failure:{failures[0]}")
items = result.get("results") if isinstance(result, dict) else result
if isinstance(items, dict):
items = [items]
row_entries = []
for item in items or []:
if not isinstance(item, dict):
continue
entry = {"id": item.get("id"), "data": (item.get("memory") or "")}
if entry["id"]:
row_entries.append(entry)
created.extend(row_entries)
if on_row_done is not None:
on_row_done(row, row_entries)
return created
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]:
@@ -808,56 +888,8 @@ class Mem0Backend:
the caller can durably record per-row progress even if the process
dies mid-batch.
"""
# Fail closed before ANY real work while either budget is unapproved:
# a 2.2.1 add always spends ≥1 embed item and 1 extraction LLM call.
self.ledger.check(1)
self.llm_guard.check(1)
def _add() -> list[dict]:
# Vector-store anchors are ALWAYS consulted (direct callers get the
# same no-resend guarantee); ``skip`` adds the caller's durable
# row records for rows that legitimately stored no vector.
done = self.completed_message_ids(batch_key) | set(skip)
send = [r for r in rows if r["message_id"] not in done]
if not send:
return []
created = []
for row in send:
# Per-row anchor: this add's input set is exactly this row.
row_anchor = {
"turn_ids": [row["turn_id"]],
"turn_roles": [[row["turn_id"], row["role"], row["message_id"]]],
"input_sha256": anchor_fingerprint([row]),
}
failures_before = len(getattr(self._failures, "list", []) or [])
result = self._memory.add(
row["text"], metadata={"src_group": batch_key, **row_anchor},
user_id=self.user_scope,
)
# mem0 2.2.1 swallows per-text embed failures into empty
# results (phase-3/7 fallback loops). An empty extraction is
# legitimate only when no embed/refusal happened during THIS
# row's add: if our guards refused anything, that refusal is
# the truth, not the empty list.
failures = (getattr(self._failures, "list", []) or [])[failures_before:]
if failures:
raise SemanticBudgetError(f"semantic_add_swallowed_failure:{failures[0]}")
items = result.get("results") if isinstance(result, dict) else result
if isinstance(items, dict):
items = [items]
row_entries = []
for item in items or []:
if not isinstance(item, dict):
continue
entry = {"id": item.get("id"), "data": (item.get("memory") or "")}
if entry["id"]:
row_entries.append(entry)
created.extend(row_entries)
if on_row_done is not None:
on_row_done(row, row_entries)
return created
return await asyncio.to_thread(_add)
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
async def search(self, query: str, limit: int = 5) -> list[dict]:
self.ledger.check(1) # the query embed is accounted inside the wrapper
@@ -918,12 +950,37 @@ def _ledger_debit(self, items: int, note: str) -> None: # pragma: no cover —
EmbedLedgerGuard.debit = _ledger_debit
class _LiveWorker:
"""In-process handle on a batch worker thread that is REALLY running.
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
the waiter (``asyncio.to_thread`` cannot interrupt the running thread);
the thread finishes its rows, writes ``sem_row_done`` and the terminal
``sem_batch`` state itself, then signals ``done`` and unregisters. As long
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.
"""
__slots__ = ("batch_id", "owner", "done")
def __init__(self, batch_id: int, owner: str) -> None:
self.batch_id, self.owner = batch_id, owner
self.done = threading.Event()
class SemanticMemory:
"""Owns the batch queue, the anchors and the fail-closed read gate."""
def __init__(self, store, backend, *, clock=time.time) -> 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
# lock — the registry is read/written from event loop AND worker
# threads while the SQLite paths keep their own transactions.
self._live: dict[int, _LiveWorker] = {}
self._live_lock = threading.Lock()
# ------------------------------------------------------------ enqueue
def public_rows_for_turn(self, turn_id: str) -> list[dict]:
@@ -997,10 +1054,34 @@ class SemanticMemory:
# ------------------------------------------------------------ job loop
def recover(self) -> None:
"""Fail expired pending batches whose owner is GENUINELY gone.
HEL-886: a lease expiring while THIS process still runs the batch's
worker thread proves nothing about death — the worker may be blocked
mid-HTTP and will write its durable fate when it returns. Batches with
a registered live worker are never touched here. For the truly dead
case (process crash / restart) the semantics stay honest and
conservative: the old attempt's wire outcome is UNKNOWN — its ledger
reservations stay billed (HEL-885), the retry sends only rows without
a completion proof (vector anchor ∪ ``sem_row_done``), and no
strict-once delivery is claimed for arbitrary crashes.
"""
now = int(self.clock() * 1000)
expired = [r["id"] for r in self.store.query(
"SELECT id FROM sem_batch WHERE state='pending' AND lease_until IS NOT NULL "
"AND lease_until<?", (now,))]
if not expired:
return
with self._live_lock:
dead = [batch_id for batch_id in expired if batch_id not in self._live]
if not dead:
return
marks = ",".join("?" * len(dead))
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state='failed',reason='lease_expired',owner=NULL,finished_at=? "
"WHERE state='pending' AND lease_until<?", (int(self.clock() * 1000), int(self.clock() * 1000)),
f"UPDATE sem_batch SET state='failed',reason='lease_expired',owner=NULL,"
f"finished_at=? WHERE state='pending' AND lease_until<? AND id IN ({marks})",
(now, now, *dead),
)
async def tick(self) -> None:
@@ -1008,17 +1089,31 @@ class SemanticMemory:
owner, now = secrets.token_hex(16), int(self.clock() * 1000)
with self.store.conn:
self.store.execute("BEGIN IMMEDIATE")
job = self.store.query_one(
"SELECT * FROM sem_batch WHERE state IN ('queued','failed') AND attempts<3 ORDER BY id LIMIT 1"
)
if not job:
return
job, offset = None, 0
while job is None:
candidate = self.store.query_one(
"SELECT * FROM sem_batch WHERE state IN ('queued','failed') AND attempts<3 "
"ORDER BY id LIMIT 1 OFFSET ?", (offset,),
)
if not candidate:
return
with self._live_lock:
# Defensive: a live worker's batch is unclaimable whatever
# its row state says — active ownership beats the table.
if candidate["id"] not in self._live:
job = candidate
else:
offset += 1
self.store.execute(
"UPDATE sem_batch SET state='pending',attempts=attempts+1,owner=?,lease_until=?,reason=NULL "
"WHERE id=?", (owner, now + 40000, job["id"]),
)
state, reason, entry_ids = "failed", "extraction_failed", None
row_entries: list[str] = []
# Registered BEFORE the thread exists, so the batch is provably active
# from the moment the claim commits — no recover() in a concurrent
# tick can reclaim it in the gap.
handle = _LiveWorker(job["id"], owner)
with self._live_lock:
self._live[job["id"]] = handle
def _row_done(row: dict, entries: list[dict]) -> None:
"""Durable per-row completion, written inside the worker thread the
@@ -1033,63 +1128,117 @@ class SemanticMemory:
json.dumps([e["id"] for e in entries], ensure_ascii=False),
int(self.clock() * 1000)),
)
row_entries.extend(e["id"] for e in entries if e["id"])
def _run() -> None:
"""The WHOLE batch execution, owned by the worker thread (HEL-886).
Row building, resume-set computation, the real adds and the
terminal ``sem_batch`` write all live here, so cancelling the
awaiting coroutine can no longer mark a still-running batch
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.
"""
state, reason, entry_ids = "failed", "extraction_failed", None
row_entries: list[str] = []
try:
anchor = json.loads(job["anchor_json"])
rows = []
for turn_id, role, message_id in anchor["turn_roles"]:
message = self.store.query_one(
"SELECT * FROM chat_message WHERE id=? AND turn_id=? AND role=? AND status='sent'",
(message_id, turn_id, role),
)
if not message:
raise ValueError("archive_missing")
rows.append({"message_id": message_id, "turn_id": turn_id,
"role": role, "text": message["text"]})
if anchor_fingerprint(rows) != anchor["input_sha256"]:
raise ValueError("source_mismatch")
# Resume truth = vector-store anchors ∪ durable per-row records.
done_ids = self.backend.completed_message_ids(job["batch_key"])
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)
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 Exception as exc: # noqa: BLE001 — job isolation, reason recorded
reason = str(exc) or exc.__class__.__name__
if "budget" in reason:
# A refused budget is not an extraction failure: the batch goes
# back to queued WITHOUT burning an attempt — raising the cap
# later resumes it (skipping rows already in the vector store),
# so exhausted budget can never permanently lose these rows.
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state='queued',reason=?,owner=NULL,"
"attempts=MAX(0,attempts-1),lease_until=NULL WHERE id=? AND owner=?",
(reason, job["id"], owner),
)
log.warning("semantic batch %s requeued (budget): %s", job["id"], reason)
else:
log.warning("semantic batch %s failed: %s", job["id"], reason)
finally:
try:
if state == "done":
# entry_ids = every entry this batch ever created, across all
# its partial attempts (sem_row_done holds the earlier ticks').
recorded = [json.loads(r["entry_ids"] or "[]") for r in self.store.query(
"SELECT entry_ids FROM sem_row_done WHERE batch_id=?", (job["id"],))]
entry_ids = json.dumps(
list(dict.fromkeys([e for lst in recorded for e in lst] + row_entries)),
ensure_ascii=False)
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state=?,reason=?,entry_ids=?,owner=NULL,finished_at=? "
"WHERE id=? AND owner=? AND state='pending'",
(state, reason, entry_ids, int(self.clock() * 1000), job["id"], owner),
)
finally:
# Unregister LAST: until this runs, recover() and every
# concurrent tick treat the batch as actively owned.
handle.done.set()
with self._live_lock:
self._live.pop(job["id"], None)
try:
anchor = json.loads(job["anchor_json"])
rows = []
for turn_id, role, message_id in anchor["turn_roles"]:
message = self.store.query_one(
"SELECT * FROM chat_message WHERE id=? AND turn_id=? AND role=? AND status='sent'",
(message_id, turn_id, role),
)
if not message:
raise ValueError("archive_missing")
rows.append({"message_id": message_id, "turn_id": turn_id,
"role": role, "text": message["text"]})
if anchor_fingerprint(rows) != anchor["input_sha256"]:
raise ValueError("source_mismatch")
# Resume truth = vector-store anchors ∪ durable per-row records.
done_ids = self.backend.completed_message_ids(job["batch_key"])
done_ids |= {r["message_id"] for r in self.store.query(
"SELECT message_id FROM sem_row_done WHERE batch_id=?", (job["id"],))}
created = await self.backend.add_group(
rows, anchor, job["batch_key"], skip=done_ids, on_row_done=_row_done)
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 Exception as exc: # noqa: BLE001 — job isolation, reason recorded
reason = str(exc) or exc.__class__.__name__
if "budget" in reason:
# A refused budget is not an extraction failure: the batch goes
# back to queued WITHOUT burning an attempt — raising the cap
# later resumes it (skipping rows already in the vector store),
# so exhausted budget can never permanently lose these rows.
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state='queued',reason=?,owner=NULL,"
"attempts=MAX(0,attempts-1),lease_until=NULL WHERE id=? AND owner=?",
(reason, job["id"], owner),
)
log.warning("semantic batch %s requeued (budget): %s", job["id"], reason)
return
log.warning("semantic batch %s failed: %s", job["id"], reason)
finally:
if state == "done":
# entry_ids = every entry this batch ever created, across all
# its partial attempts (sem_row_done holds the earlier ticks').
recorded = [json.loads(r["entry_ids"] or "[]") for r in self.store.query(
"SELECT entry_ids FROM sem_row_done WHERE batch_id=?", (job["id"],))]
entry_ids = json.dumps(
list(dict.fromkeys([e for lst in recorded for e in lst] + row_entries)),
ensure_ascii=False)
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state=?,reason=?,entry_ids=?,owner=NULL,finished_at=? "
"WHERE id=? AND owner=? AND state='pending'",
(state, reason, entry_ids, int(self.clock() * 1000), job["id"], owner),
)
await asyncio.to_thread(_run)
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.
raise
async def aclose(self, *, drain_timeout: float = 120.0) -> None:
"""Shutdown order (HEL-886): drain OUR still-running workers first.
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).
"""
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()
# ------------------------------------------------------------ read gate
def chain_resolve(self, hit: dict) -> dict: