HEL-885 rework: per-row progress matches what was really sent, cross-day and unknown-outcome accounting stay conservative, positive caps require the ledger authority, and the release dependency-fill command actually exists - every Memory.add now carries an anchor for exactly its own row (the HEL-882 whole-batch anchor let the first stored vector mark unsent rows complete; the manager's real-SDK partial reproduction showed the user's original words never leaving the process), a row finishing with a legitimately EMPTY extraction gets a durable sem_row_done record (r4.sql additive table) written inside the worker thread the moment its add completes, resume skips = vector-store anchors ∪ sem_row_done so no row is lost, none falsely complete, and finished work is never re-sent across budget-refusal/crash/restart/lease/concurrency, entry_ids merge across partial attempts, and the swallowed-failure detection is per-row; PersistentBudget.settle/release book on hold.day (the old write to state.day manufactured -80 used on the new day and re-opened headroom the reservation day had already spent; token_usage/request_usage refund the paying day, budget_total stays global) and the empty-budget_total TypeError crash in total_requests_used/total_tokens_used is fixed - the old one-shot-total test passed only because that crash surfaced as chat.error, it now books the total honestly; _atomic_reserve no longer purges aged reserve: rows (a crashed worker's hold is an UNKNOWN outcome - an hour-old timeout is not proof the call never happened; unknown consumption stays billed across restarts, only a provably-unsent release() ever removes a hold, embed_ops and llm_ops share the fix); Mem0Backend refuses construction before importing mem0 when any cap>0 lacks a (non-empty dict) authority block - ledger_authority_required - or when the prefix check fails, closing the fresh-empty-ledger bypass the manager reproduced live, config/semantic.example.yaml ships the authority block as REQUIRED with the explicit cumulative formula (embed_cap=500+approved-increment e.g. 680, embed_reserve=2 frozen untouched, min_used=498; never write 180 as the cumulative cap of a 498-used account) mirrored into docs/budget-plan-hel874.md §2 with the HEL-885 accounting rules; deploy/hel874-release.md §4 replaces the nonexistent uv pip download (rc=2, re-verified) with python3 -m pip download --only-binary :all: --platform manylinux2014_x86_64 --python-version 3.11 --implementation cp --abi cp311 + sha256 manifest + uv pip install --no-index --find-links offline merge + same-process co-import verdict, honest missing-materials list unchanged (no 3.11 wheels cached, zero downloads this card, no version swaps), and tools/check_release_offline_hel882.py gains R7 probing both command surfaces offline; verification: 281 python tests pass on 3.11.16 venv + requirements.lock offline (9 new tests/test_rework_hel885.py cases: partial batch claims only the sent row / empty-extraction row completes and is never resent / process restart sends only the missing row / concurrent ticks never double-send / cross-day settle and release book on the reservation day / aged unknown llm+embed reservations never refunded / missing-empty-malformed-wrong authority all fail closed; test_resume_never_loses_or_duplicates_rows rewritten to drive the REAL product path instead of hand-planting single-row anchors the product never wrote), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned mem0 2.2.1 install on the deterministic boundary: contract re-run 12/12 (harness now hands a synthetic authority prefix - production defaults not relaxed), new tools/verify_semantic_recovery_hel885.py 7/7 (S0 authority fail-closed, S1 per-row partial with exactly 1 HTTP, S2 restart sends only the missing row proven by HTTP count since mem0 prompts legitimately carry old rows in rolling history, S3 lease recovery + concurrent ticks single-send, S4a/S4b unknown reservations kept), both manager review scripts re-run VERBATIM against this head (partial: completed=[2] only, resume done with 2 entries, HTTP=2, user words actually sent; extra: new-day used=0, over-cap request refused, aged reservation second_allowed=false, uv probe still rc=2), release offline check R1-R7 green, dual-target requirement checks 4/4 with handoff-HEL-885.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:01:44 +08:00
co-authored by multica-agent
parent 59fb06304f
commit 78b6267d3a
23 changed files with 1603 additions and 111 deletions
+26 -11
View File
@@ -50,14 +50,16 @@ class PersistentBudget(BudgetGuard):
)["n"]
def total_requests_used(self):
return self.store.query_one(
"SELECT coalesce(value,0) v FROM budget_total WHERE key='total_requests'"
)["v"]
row = self.store.query_one(
"SELECT coalesce((SELECT value FROM budget_total WHERE key='total_requests'),0) v"
)
return row["v"] if row else 0
def total_tokens_used(self):
return self.store.query_one(
"SELECT coalesce(value,0) v FROM budget_total WHERE key='total_tokens'"
)["v"]
row = self.store.query_one(
"SELECT coalesce((SELECT value FROM budget_total WHERE key='total_tokens'),0) v"
)
return row["v"] if row else 0
def reserve(self, tokens, scene):
"""Legacy background-scene token reservation (95% stop), kept for compatibility."""
@@ -126,7 +128,14 @@ class PersistentBudget(BudgetGuard):
reserved_tokens=tokens, requests=requests, day=day)
def settle(self, hold, *, actual_tokens=None):
"""Real usage adjusts the reserved tokens; unknown usage keeps the reserve."""
"""Real usage adjusts the reserved tokens; unknown usage keeps the reserve.
HEL-885: the correction lands on the day the hold was RESERVED on
(``hold.day``) — a request crossing midnight adjusts the old day's row
to its actual spend. Writing to ``self.state.day`` (the HEL-882 bug)
manufactured negative usage on the new day and re-opened headroom the
old day had already consumed.
"""
if hold is None:
return
self._roll()
@@ -137,7 +146,7 @@ class PersistentBudget(BudgetGuard):
self.store.execute(
"INSERT INTO token_usage VALUES(?,?,?) ON CONFLICT(day,scene) DO UPDATE "
"SET used=used+excluded.used",
(self.state.day, hold.scene, delta),
(hold.day, hold.scene, delta),
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_tokens',?) ON CONFLICT(key) DO UPDATE "
@@ -145,7 +154,13 @@ class PersistentBudget(BudgetGuard):
)
def release(self, hold):
"""Refund only provably-unsent reservations (no provider, nothing left)."""
"""Refund only provably-unsent reservations (no provider, nothing left).
HEL-885: the refund returns to ``hold.day`` — the day that actually
paid the reservation — for the daily tables too; the one-shot
``budget_total`` counters are cross-day and refund in place. Refunding
into ``self.state.day`` inflated the new day with negative usage.
"""
if hold is None:
return
self._roll()
@@ -153,12 +168,12 @@ class PersistentBudget(BudgetGuard):
self.store.execute(
"INSERT INTO token_usage VALUES(?,?,?) ON CONFLICT(day,scene) DO UPDATE "
"SET used=used+excluded.used",
(self.state.day, hold.scene, -hold.reserved_tokens),
(hold.day, hold.scene, -hold.reserved_tokens),
)
self.store.execute(
"INSERT INTO request_usage VALUES(?,?,?) ON CONFLICT(day,category) DO UPDATE "
"SET requests=requests+excluded.requests",
(self.state.day, hold.category, -hold.requests),
(hold.day, hold.category, -hold.requests),
)
self.store.execute(
"INSERT INTO budget_total VALUES('total_requests',?) ON CONFLICT(key) DO UPDATE "
+11
View File
@@ -22,6 +22,17 @@ CREATE TABLE IF NOT EXISTS sem_covered (
message_id INTEGER PRIMARY KEY REFERENCES chat_message(id),
batch_id INTEGER NOT NULL REFERENCES sem_batch(id)
);
-- HEL-885 per-row completion: durable proof one row's add fully finished —
-- including a legitimate EMPTY extraction that stored no vector. Resume skips
-- rows proven done here or by vector-store anchors; finished rows are never
-- re-sent after a crash, restart or budget-refusal cycle.
CREATE TABLE IF NOT EXISTS sem_row_done (
batch_id INTEGER NOT NULL REFERENCES sem_batch(id),
message_id INTEGER NOT NULL,
entry_ids TEXT NOT NULL DEFAULT '[]', -- JSON list of backend entry ids this row created
done_at INTEGER NOT NULL,
PRIMARY KEY(batch_id, message_id)
);
-- Life activity continuity: start / continue / interrupt / resume / finish.
CREATE TABLE IF NOT EXISTS life_activity (
+147 -46
View File
@@ -41,6 +41,20 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
refusal re-queues the batch without burning an attempt; once budget returns,
the job resumes and skips rows whose entries already live in the vector store
(store-level idempotency: no lost rows, no duplicated sends, restart-safe).
- Per-row progress (HEL-885): every ``Memory.add`` carries an anchor for exactly
the ONE row it sends — a stored vector vouches for its own row and nothing
else (the HEL-882 whole-batch anchor let the first vector mark unsent rows
complete; the manager's real-SDK reproduction showed the user row never
leaving the process). A row whose add fully finished — including a
legitimate EMPTY extraction that stored no vector — is recorded in
``sem_row_done``; resume skips rows proven done by either the vector-store
anchors or that durable row record, so no row is lost, none is falsely
complete, and finished work is never re-sent.
- Unknown reservations are never refunded (HEL-885): a reservation whose
outcome is unknown (worker crashed after the wire, never settled) stays
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.
- The stub backend is an orchestration double for engineering verification and
isolated tests only; it is not semantic and never claimed as such.
"""
@@ -144,17 +158,32 @@ class StubBackend:
self._entries: dict[str, dict] = {}
self._seq = 0
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str) -> list[dict]:
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]:
"""Per-row mirror of the mem0 contract: one entry per row, each with
that row's own anchor (HEL-885) — orchestration progress parity."""
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 = []
text = "\n".join(r["text"] for r in rows)
self._seq += 1
entry_id = f"stub-{self._seq}"
self._entries[entry_id] = {
"id": entry_id, "data": text,
"payload": {"data": text, "src_group": batch_key, **anchor},
}
created.append({"id": entry_id, "data": text})
for row in send:
row_anchor = {
"turn_ids": [row["turn_id"]],
"turn_roles": [[row["turn_id"], row["role"], row["message_id"]]],
"input_sha256": anchor_fingerprint([row]),
}
self._seq += 1
entry_id = f"stub-{self._seq}"
self._entries[entry_id] = {
"id": entry_id, "data": row["text"],
"payload": {"data": row["text"], "src_group": batch_key, **row_anchor},
}
entry = {"id": entry_id, "data": row["text"]}
created.append(entry)
if on_row_done is not None:
on_row_done(row, [entry])
return created
return await asyncio.to_thread(_add)
@@ -199,7 +228,9 @@ class EmbedLedgerGuard:
HEL-874: debits go through ``reserve``/``settle``/``release`` so the
check-and-hold is one serialized SQLite transaction — concurrent workers can
never overspend the cap. Stale holds (crashed workers) are purged by age.
never overspend the cap. Stale holds are NEVER purged (HEL-885): a crashed
worker's reservation has an unknown outcome and stays counted; only a
provably-unsent ``release()`` removes it.
HEL-882: ``daily_cap`` adds the execution-table C per-day top on top of the
lifetime cap (both enforced, tightest wins; the ts column is UTC ISO so the
@@ -290,8 +321,15 @@ def _pid() -> int:
return os.getpid()
def _reserve_cutoff() -> str:
"""ISO stamp older than any live reservation may be (crashed workers)."""
def _reserve_cutoff() -> str: # noqa: DEE001 — kept for audit tooling reference
"""Deprecated (HEL-885): aged ``reserve:`` rows are NEVER auto-deleted.
A hold whose worker died is an UNKNOWN outcome — the request may well be
sitting answered on the wire (the exact "sent then crashed before settle"
case). The manager's independent reproduction showed the old 1-hour purge
re-opening cumulative caps. ``_atomic_reserve`` no longer calls this; it
stays only so historical audit scripts importing it keep working.
"""
import time as _time
return _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime(_time.time() - 3600))
@@ -306,6 +344,11 @@ def _atomic_reserve(conn, *, table: str, cap: int, keep: int, items: int, note:
same serialized transaction — lifetime cap and daily top both apply, the
tightest one refuses. Reservation rows carry today's UTC timestamp so the
pending holds themselves count toward the day they were taken on.
HEL-885: aged ``reserve:`` rows are never purged here. A reservation is
removed ONLY by ``release()`` with provably-unsent evidence — a crashed
worker's hold has an unknown outcome and stays counted (conservative:
unknown consumption is billed, never refunded as "never happened").
"""
import time as _time
@@ -313,10 +356,6 @@ def _atomic_reserve(conn, *, table: str, cap: int, keep: int, items: int, note:
now = _time.strftime("%Y-%m-%dT%H:%M:%SZ", _time.gmtime())
conn.execute("BEGIN IMMEDIATE")
try:
conn.execute(
f"DELETE FROM {table} WHERE note LIKE ? AND ts < ?",
(EmbedLedgerGuard.RESERVE_NOTE + "%", _reserve_cutoff()),
)
if counted_kinds:
marks = ",".join("?" * len(counted_kinds))
row = conn.execute(
@@ -552,22 +591,28 @@ class Mem0Backend:
# Must precede the mem0 import; same ordering guarantee as the spike.
os.environ.setdefault("MEM0_TELEMETRY", "False")
try:
from mem0 import Memory # noqa: PLC0415 — fixed install, lazy by design
except ImportError as exc: # fail closed, never a silent fallback
raise RuntimeError("mem0_not_installed") from exc
self.ledger = ledger or EmbedLedgerGuard(
config.get("ledger_path", ""), config.get("embed_cap", 0),
daily_cap=config.get("embed_daily"))
self.llm_guard = llm_guard or LlmLedgerGuard(
config.get("ledger_path", ""), config.get("llm_cap", 0),
daily_cap=config.get("llm_daily"))
# HEL-882: a fresh file must never re-open the frozen balance — with any
# approved cap the configured ledger has to still be the authoritative
# account carrying the frozen prefix.
# HEL-885: the authority block is REQUIRED, never optional. The
# HEL-882 code skipped verification entirely when ``authority`` was
# absent, so a fresh empty ledger + positive caps constructed and sent
# (manager's real-SDK reproduction). Now: any positive cap without a
# (non-empty, dict) authority block — or with one that does not match
# the authoritative account — fails closed BEFORE the SDK is even
# imported: a fresh file can never re-open the frozen 498/500 headroom.
authority = config.get("authority")
if authority and (self.ledger.cap > 0 or self.llm_guard.cap > 0):
if self.ledger.cap > 0 or self.llm_guard.cap > 0:
if not isinstance(authority, dict) or not authority:
raise SemanticBudgetError("ledger_authority_required")
verify_ledger_authority(config.get("ledger_path", ""), authority)
try:
from mem0 import Memory # noqa: PLC0415 — fixed install, lazy by design
except ImportError as exc: # fail closed, never a silent fallback
raise RuntimeError("mem0_not_installed") from exc
# Unified provider-exit gate: the SDK's internal extraction LLM is a real
# provider exit like any other; when the product hands its router guard
# over, every extraction call also reserves request count + conservative
@@ -717,6 +762,13 @@ class Mem0Backend:
Reads the vector store's own payload (src_group anchor) — a crashed or
restarted worker finds what earlier attempts persisted, so recovery
resends only the missing rows and never duplicates completed ones.
HEL-885: every add carries a PER-ROW anchor, so each stored point
vouches for exactly the one message in its own ``turn_roles`` — vector
existence never claims other rows of the batch are done (that whole-
batch-anchor claim was the HEL-882 permanent-loss defect). Rows whose
extraction legitimately stored nothing carry no point; their durable
completion proof is the caller-side ``sem_row_done`` record.
"""
try:
from qdrant_client import models as qmodels # noqa: PLC0415 — lazy, pinned SDK
@@ -744,48 +796,65 @@ class Mem0Backend:
break
return done
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str) -> list[dict]:
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]:
"""One entry per row, each carrying that row's own anchor (HEL-885).
``skip`` holds message_ids already proven complete (vector-store
anchors ∪ the durable ``sem_row_done`` record) — those rows are never
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.
"""
# 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]:
# Recovery skips rows whose entries already live in the vector store
# (crash/restart/budget-exhaustion resume); the anchor sent with the
# remaining rows equals exactly that send's input set.
done = self.completed_message_ids(batch_key)
# 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 []
send_anchor = {
"turn_ids": [r["turn_id"] for r in send],
"turn_roles": [[r["turn_id"], r["role"], r["message_id"]] for r in send],
"input_sha256": anchor_fingerprint(send),
}
failures_before = list(getattr(self._failures, "list", []) or [])
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, **send_anchor},
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"]:
created.append(entry)
# 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: if our guards refused anything
# during this add, that refusal is the truth, not the empty list.
failures = (getattr(self._failures, "list", []) or [])[len(failures_before):]
if failures:
raise SemanticBudgetError(f"semantic_add_swallowed_failure:{failures[0]}")
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)
@@ -949,6 +1018,23 @@ class SemanticMemory:
"WHERE id=?", (owner, now + 40000, job["id"]),
)
state, reason, entry_ids = "failed", "extraction_failed", None
row_entries: list[str] = []
def _row_done(row: dict, entries: list[dict]) -> None:
"""Durable per-row completion, written inside the worker thread the
moment a row's add fully finished (HEL-885) — a legitimately empty
extraction stored no vector, so this record is its only resend
proof; a crash between rows can never resend a finished row."""
with self.store.conn:
self.store.execute(
"INSERT OR IGNORE INTO sem_row_done(batch_id,message_id,entry_ids,done_at) "
"VALUES(?,?,?,?)",
(job["id"], row["message_id"],
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"])
try:
anchor = json.loads(job["anchor_json"])
rows = []
@@ -963,8 +1049,15 @@ class SemanticMemory:
"role": role, "text": message["text"]})
if anchor_fingerprint(rows) != anchor["input_sha256"]:
raise ValueError("source_mismatch")
created = await self.backend.add_group(rows, anchor, job["batch_key"])
entry_ids = json.dumps([e["id"] for e in created], ensure_ascii=False)
# 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__
@@ -983,6 +1076,14 @@ class SemanticMemory:
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=? "