Files
CyberGril/spike/hel857/ledger.py
T
zonggongandmultica-agent e31ae2d946 HEL-857: approved Mem0 isolation spike - zero-model gates all pass, A/B synthetic scenarios within 26/60 real-call budget
- Fixed mem0 source commit 2c81af3 (2.2.1) in isolated venv, qdrant embedded + fastembed local zh embeddings (95.3MB, within 500MB cap)
- Gate0 transport-level persistent debit ledger: 61st call blocked pre-send, failures count, cross-process persistence, retries disabled+counted (fake transport, zero network)
- Gate1 qdrant embedded checks: keyword_search functional (Chinese segmentation gap recorded honestly), restart subprocess, clean-copy restore, no telemetry collections
- Gate2 privacy with stub LLM: P1-P5 zero leak, first-share timing F1-F6 (failed/cancel/unconfirmed no migration, ack+judged migrates told content with anchors, duplicate receipt idempotent), full backup incl. unshared internal memories restores clean
- A/B same-material same-criteria: Mem0 paraphrase recall strictly better than current lexical path (S3, model answers in Chinese), S1-S9 all pass, no regression
- Headline findings: Chinese input extracted as English memories (default upstream prompt), BM25 lexical channel inert for Chinese, ADD-only infer confirmed with our update orchestration, custom metadata needs direct payload read
- 26/60 real outbound via persistent ledger (incl. one parse-failure retry), usage/latency per row; embeddings 28/500; HEL-835 quota untouched
- Experiment branch only: no merge to main/product, no deploy, no real-profile access; handoff JSON + dual-base requirement checks pass

Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 23:19:26 +08:00

255 lines
10 KiB
Python

#!/usr/bin/env python3
"""HEL-857 出站前持久扣账:传输层计数 + 跨进程 SQLite 账本。
要点(对照批准范围第4条):
- 扣账发生在网络发送之前(debit BEFORE send),BEGIN IMMEDIATE 原子提交;
- 任何出站尝试(失败、取消、provider 自动重试)都先扣账;第 61 次在发送前被拦;
- 账本跨进程/中断/重跑保留(独立 SQLite 文件,FULL 同步);
- provider 自动重试显式关闭(openai client max_retries=0),传输层仍逐尝试计数;
- 每请求记录 usage、状态、耗时、输入规模;输入超 6000 中文字符在扣账后发送前拒绝。
"""
from __future__ import annotations
import json
import os
import sqlite3
import threading
import time
from pathlib import Path
from typing import Any, Dict, Optional
from .common import DATA_DIR, INPUT_CJK_CAP, LLM_CALL_CAP, count_cjk
LEDGER_PATH = Path(os.environ.get("HEL857_LEDGER", DATA_DIR / "ledger.sqlite3"))
class BudgetBlocked(RuntimeError):
"""在发送前被拦截(预算耗尽/输入超限)。未产生任何网络出站。"""
def _connect() -> sqlite3.Connection:
LEDGER_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(str(LEDGER_PATH), timeout=30.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=FULL")
conn.execute(
"CREATE TABLE IF NOT EXISTS outbound ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" ts TEXT NOT NULL,"
" purpose TEXT NOT NULL,"
" pid INTEGER NOT NULL,"
" status TEXT NOT NULL," # debit | blocked_budget | blocked_input | sent | failed | no_network
" http_status INTEGER,"
" latency_ms REAL,"
" cjk_chars INTEGER, total_chars INTEGER,"
" model TEXT, usage_json TEXT, note TEXT)"
)
return conn
class Ledger:
"""跨进程持久出站账本。debit() 在任何网络发送前调用。"""
def __init__(self, path: Optional[Path] = None):
self.path = Path(path) if path else LEDGER_PATH
self.path.parent.mkdir(parents=True, exist_ok=True)
self._local = threading.local()
self._init_db()
def _conn(self) -> sqlite3.Connection:
conn = getattr(self._local, "conn", None)
if conn is None:
conn = sqlite3.connect(str(self.path), timeout=30.0, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=FULL")
self._local.conn = conn
return conn
def _init_db(self) -> None:
with self._exclusive() as conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS outbound ("
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
" ts TEXT NOT NULL, purpose TEXT NOT NULL, pid INTEGER NOT NULL,"
" status TEXT NOT NULL, http_status INTEGER, latency_ms REAL,"
" cjk_chars INTEGER, total_chars INTEGER, model TEXT,"
" usage_json TEXT, note TEXT)"
)
class _Exclusive:
def __init__(self, ledger: "Ledger"):
self.ledger = ledger
def __enter__(self):
self.conn = self.ledger._conn()
for attempt in range(60):
try:
self.conn.execute("BEGIN IMMEDIATE")
return self.conn
except sqlite3.OperationalError:
time.sleep(0.05 * (attempt + 1))
raise RuntimeError("ledger BEGIN IMMEDIATE timeout")
def __exit__(self, exc_type, exc, tb):
if exc_type is None:
self.conn.execute("COMMIT")
else:
self.conn.execute("ROLLBACK")
return False
def _exclusive(self):
return Ledger._Exclusive(self)
# ---- 核心协议 ----
def used(self, purpose: str = "real_llm") -> int:
row = self._conn().execute(
"SELECT COUNT(*) FROM outbound WHERE purpose=? AND status IN ('debit','sent','failed')",
(purpose,),
).fetchone()
return int(row[0])
def debit(self, purpose: str, *, model: str = "", body: bytes = b"",
cjk_chars: int = 0, total_chars: int = 0) -> int:
"""发送前持久扣账。超出上限 → 记 blocked_budget 行并抛 BudgetBlocked。
blocked 行不计入 used()(它们从未出站),但留审计痕迹。
"""
with self._exclusive() as conn:
used = conn.execute(
"SELECT COUNT(*) FROM outbound WHERE purpose=? AND status IN ('debit','sent','failed')",
(purpose,),
).fetchone()[0]
if used >= LLM_CALL_CAP:
conn.execute(
"INSERT INTO outbound(ts,purpose,pid,status,cjk_chars,total_chars,model,note)"
" VALUES(?,?,?,?,?,?,?,?)",
(_now(), purpose, os.getpid(), "blocked_budget",
cjk_chars, total_chars, model, f"used={used} cap={LLM_CALL_CAP}"),
)
raise BudgetBlocked(f"真实请求预算耗尽: {used}/{LLM_CALL_CAP}(发送前拦截)")
cur = conn.execute(
"INSERT INTO outbound(ts,purpose,pid,status,cjk_chars,total_chars,model,note)"
" VALUES(?,?,?,?,?,?,?,?)",
(_now(), purpose, os.getpid(), "debit", cjk_chars, total_chars, model, ""),
)
return int(cur.lastrowid)
def mark(self, row_id: int, status: str, *, http_status: Optional[int] = None,
latency_ms: Optional[float] = None, usage: Optional[Dict[str, Any]] = None,
note: str = "") -> None:
with self._exclusive() as conn:
conn.execute(
"UPDATE outbound SET status=?, http_status=?, latency_ms=?, usage_json=?, note=?"
" WHERE id=?",
(status, http_status, latency_ms,
json.dumps(usage, ensure_ascii=False) if usage else None, note, row_id),
)
def rows(self) -> list[dict]:
cur = self._conn().execute(
"SELECT id,ts,purpose,pid,status,http_status,latency_ms,cjk_chars,total_chars,"
"model,usage_json,note FROM outbound ORDER BY id"
)
cols = [d[0] for d in cur.description]
return [dict(zip(cols, r)) for r in cur.fetchall()]
def summary(self) -> dict:
rows = self.rows()
sent = [r for r in rows if r["status"] in ("debit", "sent", "failed")]
out: Dict[str, Any] = {
"ledger_path": str(self.path),
"total_rows": len(rows),
"debited": len(sent),
"cap": LLM_CALL_CAP,
"remaining": LLM_CALL_CAP - len(sent),
"blocked_budget": sum(1 for r in rows if r["status"] == "blocked_budget"),
"blocked_input": sum(1 for r in rows if r["status"] == "blocked_input"),
"by_status": {},
"usage_totals": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
"rows": rows,
}
for r in rows:
out["by_status"][r["status"]] = out["by_status"].get(r["status"], 0) + 1
if r["usage_json"]:
try:
u = json.loads(r["usage_json"])
out["usage_totals"]["prompt_tokens"] += u.get("prompt_tokens") or 0
out["usage_totals"]["completion_tokens"] += u.get("completion_tokens") or 0
out["usage_totals"]["total_tokens"] += u.get("total_tokens") or 0
except Exception:
pass
return out
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + f".{int(time.time()*1000)%1000:03d}Z"
# ---------------------------------------------------------------------------
# 传输层:每个出站尝试(含任何自动重试)都先扣账再发送
class AccountingTransport:
"""httpx 传输层计数器。包装真实或假传输;扣账在任何网络发送之前。"""
def __init__(self, inner, ledger: Ledger, purpose: str = "real_llm",
enforce_input_cap: bool = True):
self.inner = inner
self.ledger = ledger
self.purpose = purpose
self.enforce_input_cap = enforce_input_cap
def handle_request(self, request):
body = request.content or b""
try:
text = body.decode("utf-8", errors="replace")
except Exception:
text = ""
cjk = count_cjk(text)
total = len(text)
if self.enforce_input_cap and cjk > INPUT_CJK_CAP:
self.ledger.mark(
self.ledger.debit(self.purpose, cjk_chars=cjk, total_chars=total),
"blocked_input", note=f"输入中文字符 {cjk} > {INPUT_CJK_CAP},发送前拒绝",
)
raise BudgetBlocked(f"输入中文字符 {cjk} > {INPUT_CJK_CAP}")
row = self.ledger.debit(self.purpose, cjk_chars=cjk, total_chars=total)
t0 = time.monotonic()
try:
resp = self.inner.handle_request(request)
except Exception as e:
self.ledger.mark(row, "failed", latency_ms=(time.monotonic() - t0) * 1000,
note=f"transport-error:{type(e).__name__}")
raise
latency = (time.monotonic() - t0) * 1000
usage = None
try:
resp.read()
data = json.loads(resp.content.decode("utf-8", errors="replace"))
usage = data.get("usage") if isinstance(data, dict) else None
except Exception:
pass
status = "sent" if resp.status_code < 400 else "failed"
self.ledger.mark(row, status, http_status=resp.status_code,
latency_ms=latency, usage=usage)
return resp
class FakeTransport:
"""假传输:零网络。可编程响应(默认 200 + 假 usage)。"""
def __init__(self, *, status: int = 200, fail_first: int = 0):
self.status = status
self.fail_first = fail_first
self.attempts = 0
def handle_request(self, request):
self.attempts += 1
import httpx
if self.attempts <= self.fail_first:
return httpx.Response(500, request=request, json={"error": "fake-5xx"})
payload = {
"id": "fake", "object": "chat.completion",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "{\"memory\": []}"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
}
return httpx.Response(self.status, request=request, json=payload)