HEL-896 release completion: the A/B/C budget becomes an executable two-instance split, the real-browser false positive is fixed precisely (product untouched), the SDK gap list is corrected to the honest 41-distribution closure with the pip-download erratum, and release archiving becomes a consistency snapshot - (1) budget split: the manager's independent review reproduced on a temp store that writing A's total_requests=55 into the shared product ledger blocks B's mem0_extract and C's dialogue_main with budget_total_requests_exhausted:55/55 while budget_total/request_usage/token_usage have no stage or authorization-source column; docs/budget-package-hel895.md gains §6 making the split executable: A lives ONLY on the isolated 8360 team-test instance with its own DB and models.yaml (55/500000 one-shot totals plus same-value daily category caps), the user instance NEVER carries one-shot totals (its budget_total rows are record-only, no gate), A is sealed by stop+consistent-snapshot archiving with budget_total never zeroed and restart/archive proving the seal holds, old test data has no import path into the user instance (release checklist forbids copying the 8360 data dir), B starts only after baiqizhi approval writes llm_cap/embed_cap per the 500+180 formula with the authority frozen prefix, the real-Mem0 smoke is counted INSIDE B's 60/180, B cap-hit queues batches (no retry burn, no lost rows, FTS fallback, chat uninterrupted) and first-week end requires a fresh approval to continue, and §6.4 gives one responsible limited recommendation (A 55/500k isolated, B 60 LLM/180 embeds, C daily table) plus errata for the two unsafe original claims ('A shares C's daily account' and 'WAL single file copies whole'); tools/verify_budget_split_hel896.py 8/8 on temp stores and stand-ins only (S0 exact-shape repro of the manager's finding, S1 team instance consumes the §1 step plan to 55 then hard-stops with the tightest gate winning - life daily 8/8 rejects before the total, S2 seal survives restart and backup-API archive, S3 user instance B/C unblocked after A with dialogue 60/semantic 40/daily-token stacking and rejections booking nothing, S4 the misconfigured-total guard on the user instance, S5 repo configs and authoritative facts untouched, real caps all stay 0); (2) browser false positive fixed without touching any product file: web/tests/hel895_real.mjs B3 used '!!stage || any visible button' and clicked the FIRST button containing 回 which is the 日子与回忆 home nav button, so stage=false still PASSed and the screenshot stayed on days - the verbatim original rerun reproduces the false 7/7 with B3 stage=false (docs/rework/hel896/browser-before/), and the revised test passes 9 checks by precise interaction: B2 asserts the letter card carries her exact words plus the talk-nav unread aria-label, B3a waits for the VISIBLE reach card (aside.reach.show, aria-hidden=false, non-zero box, exact words) over days, B3b clicks only THAT card's 回她 button and strictly asserts the conversation stage .conversation .sr contains the reach-out text with the unread mark cleared, B4/B5 prove dedup by server message id (data-mid in the record panel: zero duplicates, gap and live reach-outs each exactly once), B5 asserts /api/health epoch bumps exactly +1 (1->2) before rechecking, B6 counts the page's OWN permissions.query/getUserMedia calls from first document load (0/0, instrumented via Page.addScriptToEvaluateOnNewDocument after Page.enable), B7 runs the service under a temp loopback models config (CYBERGRIL_MODELS, all caps 0) plus a sitecustomize socket guard that REJECTS and eagerly reports non-loopback connects (0 attempts, 0 non-loopback DNS lookups, report survives signal death) - under precise interaction the stage really plays, unread really clears, dedup and epoch semantics really hold: it was a test defect, not a product defect, so no interface change and nothing to escalate; (3) SDK honesty: tools/audit_sdk_offline_hel896.py (read-only, zero downloads/installs/inference) computes the 3.11-Linux closure from the installed 3.10 pinned metadata - 55 dists, 41 missing from the product venv (28 pure + 13 native incl. grpcio/numpy/onnxruntime/tokenizers/sqlalchemy/protobuf), all three top-level pins are py3-none-any (no 'cp311 wheel' needed for them), mem0ai's installed direct_url is the local fixed source hel857-src and hel857-data/mem0-2c81af3.tar.gz hashes exactly to the lock's 9dcef930...dda23 (an index mem0ai==2.2.1 wheel proves nothing), the wheel built during hel857 lived only in an ephemeral cache and hatchling is not offline-available, exactly 3 of the 41 are cache-reusable today for 3.11 (greenlet 3.5.6 cp311, pillow 12.3.0 cp311, truststore 0.10.5 py3-none-any - version+tag verified), the fastembed model cache is measured (Qdrant/bge-small-zh-v1.5 + bm25, ~92MB, placement = instance data dir copy), and the seq48-51 pip event is settled by cache forensics: uv's pip-26.2.2 wheel entry (files.pythonhosted.org, sha256 fd7f4dfa...) was CREATED 2026-10-27 02:10:04 inside the HEL-895 run window as the ONLY new cache entry, so that step DID fetch from the network - the prior card's zero-download claim is corrected to 'download' by the conservative reading (byte-level download vs conditional request is indistinguishable from cache evidence) while the lock install itself added no new cache entries; deploy/hel895-release-candidate.md §4 is rewritten to this accurate list, all future installs forced offline/no-index; (4) release archiving: tools/release_snapshot_hel896.py implements the two safe modes (stop+wal_checkpoint(TRUNCATE)+copy, or online SQLite backup API), writes per-file sha256 manifests carrying the exact code commit, per-table row-count verification and a verify-mode rollback drill; its selftest reproduces the manager's WAL finding (online naive copy of the main .db: 'no such table: companion') and proves both fixed modes complete (backup API and checkpoint copies both hold companion=1/chat_message=1, archive hashes+rows verify, commit 04eff61 recorded); §5 of the release doc now carries the copy-paste commands covering the product DB, semantic vector root, history root and the authoritative embed ledger, archives are never deleted, and the section explicitly does NOT claim R6 complete backup; regression on this head: pytest 299/299 (3.11.16 venv + requirements.lock offline), ruff clean (src/tests/tools), web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 55/55 / build passes with CSS still index-DdDYzR5S.css, pinned-SDK reruns all green (close-ownership 16/16, shutdown-queued 12/12, inflight 6/6, semantic-recovery 7/7, mem0-real 12/12, reports in docs/rework/hel896/regression/), check_release_offline R1-R7 passes, real-HTTP pagination 7/7 rerun saved as docs/rework/hel896/http-pagination-rerun.json with the original hel895 evidence byte-untouched, requirement checks 6/6 (origin/main, de8874a3803b, 152479b, each with and without handoff-HEL-896.json); handoff-HEL-896.json written; zero real LLM, zero real embeddings, zero new downloads beyond existing caches, authoritative ledgers and freezes (39/60, 498/500, 2 frozen, HEL-835 gate) untouched, not deployed, PR#11 appended-not-merged, no visual changes, R5/R6/R7 honestly deferred

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 03:06:23 +08:00
co-authored by multica-agent
parent 04eff611e7
commit c121c42e39
31 changed files with 3031 additions and 56 deletions
+259
View File
@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""HEL-896 · 固定 SDK 离线余缺只读审计(零下载、零安装、零推理)。
总管独立复审(HEL-896 附件 §3)核定的事实:三个顶层包的 WHEEL 标签均为
py3-none-any(不是必须另找 cp311 专用轮子);已装 mem0ai 的来源是本地固定源码
hel857-src(direct_url),不是索引包;按 3.11 Linux markers + extras 从 3.10 安装
元数据计算的闭包,产品 3.11 venv 缺 41 个分发(含 grpcio/numpy/onnxruntime/
tokenizers 等原生扩展)——那是「已有安装元数据的依赖闭包」,不是已完成的 cp311
解析结果。本工具把这份闭包逐项核清为可执行清单:
- 每个缺项:版本、3.10 安装的 WHEEL 标签、纯 Python / 原生分类、目标平台
(x86_64 Linux)应取的 wheel 形态、本机缓存可复用条目(uv wheels-v*/pypi 与
pip wheels 缓存,记录路径)、来源与哈希(凡有权威值处);
- mem0ai 固定源码身份:hel857-src direct_url + hel857-data/mem0-2c81af3.tar.gz
实测 SHA256 对照 deploy/mem0-stack.lock 注释;pip-install.log 记录的曾构建
wheel 哈希及其「临时缓存、未持久」事实;
- fastembed 模型缓存实测(hel857-data/fastembed-cache,真实模型目录与大小),
发布机落位路径口径;
- seq48–51 pip 26.2.2 事件的缓存取证:uv 缓存中该 wheel 条目创建于
2026-10-27 02:10:04(HEL-895 运行窗口内),来源 files.pythonhosted.org——
该步「零下载」表述不成立(勘误);requirements.lock 装机全部命中既有缓存
(同期无其他新缓存条目)。
只读:不安装、不下载、不 pip/uv 命令、不 site-packages 复制、不写任何产品或
固定栈目录;唯一输出写 docs/rework/hel896/sdk-audit/。缺项不阻塞其余发布工作;
真正下载只在发布卡按 deploy/hel874-release.md §4 获授权执行。
用法:.venv311/bin/python tools/audit_sdk_offline_hel896.py
"""
from __future__ import annotations
import hashlib
import importlib.metadata as md
import json
import re
from datetime import datetime
from pathlib import Path
from packaging.markers import default_environment
from packaging.requirements import Requirement
REPO = Path(__file__).resolve().parents[1]
HELM = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir")
SDK = HELM / "hel857-venv/lib/python3.10/site-packages"
PROD = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-895-0261e950b9c2/workdir/CyberGril/.venv311/lib/python3.11/site-packages")
SRC = HELM / "hel857-src"
DATA = HELM / "hel857-data"
UV_CACHE = Path.home() / ".cache/uv"
PIP_WHEELS = Path.home() / ".cache/pip/wheels"
LOCK_TARBALL_SHA256 = "9dcef9303ebcec116eec6739f01b8b35bd24459de6a569686b4d19b9412dda23"
PINNED_WHEEL_SHA256 = "698284b6083ab8b7761454d65876a6d1bb983d278ad21a7bee38d760cb20e9db"
def key(n):
return n.lower().replace("_", "-").replace(".", "-")
def sha256_file(p: Path) -> str:
h = hashlib.sha256()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def wheel_tags(dist: md.Distribution) -> list[str]:
raw = dist.read_text("WHEEL") or ""
return re.findall(r"^Tag:\s*(\S+)$", raw, re.M)
def cache_hits(name: str, version: str) -> list[dict]:
hits: list[dict] = []
for gen in ("wheels-v7", "wheels-v6"):
base = UV_CACHE / gen / "pypi" / name
if base.is_dir():
for entry in sorted(base.iterdir()):
if entry.is_dir() and entry.name.startswith(version):
hits.append({"kind": f"uv:{gen}", "path": str(entry),
"name": entry.name, "sha256": None})
if PIP_WHEELS.is_dir():
for whl in sorted(PIP_WHEELS.rglob(f"{name.replace('-', '_')}-{version}-*.whl")):
hits.append({"kind": "pip:wheels", "path": str(whl), "name": whl.name,
"sha256": sha256_file(whl)})
return hits
def main() -> int:
out_dir = REPO / "docs/rework/hel896/sdk-audit"
out_dir.mkdir(parents=True, exist_ok=True)
installed = {key(d.metadata["Name"]): d for d in md.distributions(path=[str(SDK)])}
base = {key(d.metadata["Name"]): d for d in md.distributions(path=[str(PROD)])}
env = default_environment()
env.update(python_version="3.11", python_full_version="3.11.16", extra="")
queue = [("mem0ai", frozenset()), ("qdrant-client", frozenset()), ("fastembed", frozenset())]
seen: set = set()
rows: dict[str, dict] = {}
while queue:
name, extras = queue.pop(0)
if (name, extras) in seen:
continue
seen.add((name, extras))
d = installed.get(name)
if d is None:
rows.setdefault(name, {"name": name, "installed_sdk": False})
continue
if name not in rows:
tags = wheel_tags(d)
native = tags and not any(t.endswith("py3-none-any") or "py2.py3-none-any" in t for t in tags)
rows[name] = {
"name": name, "version": d.version, "wheel_tags": tags,
"native_extension": native,
"installed_sdk": True, "present_product_311": name in base,
"product_version": base[name].version if name in base else None,
"direct_url": d.read_text("direct_url.json"),
}
for raw in d.requires or []:
req = Requirement(raw)
if req.marker and not any(req.marker.evaluate(dict(env, extra=x)) for x in set(extras) | {""}):
continue
queue.append((key(req.name), frozenset(req.extras)))
missing = []
for name, r in sorted(rows.items()):
if not r.get("installed_sdk") or r.get("present_product_311"):
continue
hits = cache_hits(name, r["version"])
if r["native_extension"]:
resolution = ("3.11 目标需 cp311-cp311(或 cp39+ abi3)manylinux x86_64 原生 wheel;"
"3.10 安装标签不可复制,禁混 site-packages")
else:
resolution = "纯 Python py3-none-any:同版本 wheel 可跨 3.10/3.11 使用"
# 缓存「可复用」必须同版本且标签兼容 3.11:纯 py3-none-any,或 cp311 / cp3x-abi3 标签。
def usable(h: dict) -> bool:
tag = h["name"]
if tag.endswith("py3-none-any"):
return True
if "cp311-" in tag:
return True
return bool(re.search(r"cp3\d+-abi3", tag))
reusable = [h for h in hits if usable(h)]
cls = "cache-reusable" if reusable else ("fixed-source" if name == "mem0ai" else "missing-download-at-release")
r.update(cache_hits=hits, cache_hits_usable_for_311=[h["name"] for h in reusable],
resolution=resolution, classification=cls)
missing.append(r)
# mem0ai 固定源码身份核验
tarball = DATA / "mem0-2c81af3.tar.gz"
tar_sha = sha256_file(tarball) if tarball.is_file() else None
mem0 = installed.get("mem0ai")
direct = (mem0.read_text("direct_url.json") if mem0 else "") or ""
install_log = DATA / "pip-install.log"
built_wheel_note = None
if install_log.is_file():
text = install_log.read_text(errors="replace")
m = re.search(r"Created wheel for mem0ai: filename=(\S+) size=(\d+) sha256=([0-9a-f]{64})", text)
if m:
built_wheel_note = {"filename": m.group(1), "size": int(m.group(2)), "sha256": m.group(3),
"ephemeral_wheel_cache": "/tmp/multica-task-1816511421 (不再存在)",
"persisted_anywhere": False}
hatchling = bool(cache_hits("hatchling", "") or cache_hits("hatchling", "1.32.4")) or (PROD.parent / "hatchling").exists()
identity = {
"direct_url_of_installed": direct.strip(),
"fixed_source_dir": str(SRC),
"fixed_source_dir_exists": SRC.is_dir(),
"pinned_tarball": str(tarball),
"pinned_tarball_sha256_measured": tar_sha,
"pinned_tarball_sha256_lock": LOCK_TARBALL_SHA256,
"tarball_matches_lock": tar_sha == LOCK_TARBALL_SHA256,
"index_wheel_2_2_1_proves_same_code": False,
"note": "索引下载的 mem0ai==2.2.1 wheel 不自动等于固定源码;发布必须用本 tarball/源码目录离线构建安装",
"built_wheel_from_hel857_install": built_wheel_note,
"offline_build_backend": {"hatchling_cached_or_local": bool(hatchling),
"note": "离线构建 mem0 wheel 需要 hatchling 及其依赖可离线获得;未命中则发布卡需一并拉取"},
}
# fastembed 模型缓存实测
fe_cache = DATA / "fastembed-cache"
models = {}
if fe_cache.is_dir():
for d in sorted(fe_cache.glob("models--*")):
files = [p for p in d.rglob("*") if p.is_file()]
models[d.name] = {"files": len(files), "bytes": sum(p.stat().st_size for p in files)}
default_cache = Path.home() / ".cache/fastembed"
fastembed_models = {
"cache_dir": str(fe_cache), "exists": fe_cache.is_dir(),
"models": models,
"default_cache_dir": str(default_cache), "default_cache_exists": default_cache.is_dir(),
"release_note": "真实 mem0 模式把 fastembed cache_dir 指向发布实例数据目录内的该缓存拷贝;本次零下载、不推理",
}
# seq48–51 pip 26.2.2 事件缓存取证
pip_entry = UV_CACHE / "wheels-v7/pypi/pip/26.2.2-py3-none-any"
pip_http = UV_CACHE / "wheels-v7/pypi/pip/26.2.2-py3-none-any.http"
archive = UV_CACHE / "archive-v0"
new_archives = [p for p in archive.iterdir() if p.stat().st_mtime >= datetime(2026, 10, 27, 1, 50).timestamp()] if archive.is_dir() else []
http_meta = pip_http.read_bytes()[:400] if pip_http.is_file() else b""
url_m = re.search(rb"https://files\.pythonhosted\.org/\S*pip-26\.2\.2\S*\.whl", http_meta)
sha_m = re.search(rb"sha256=([0-9a-f]{64})|Sha256.{0,4}([0-9a-f]{64})", http_meta)
venv_pip_di = PROD / "pip-26.2.2.dist-info"
pip_event = {
"claim_under_review": "HEL-895 seq48–51:uv pip install --offline pip 失败后去掉 --offline 安装 pip 26.2.2 成功;前卡日志仅存尾两行",
"installed_into": str(venv_pip_di),
"installer": (venv_pip_di / "INSTALLER").read_text().strip() if (venv_pip_di / "INSTALLER").is_file() else None,
"uv_cache_entry_created": datetime.fromtimestamp(pip_entry.stat().st_mtime).isoformat() if pip_entry.is_dir() else None,
"uv_http_cache_created": datetime.fromtimestamp(pip_http.stat().st_mtime).isoformat() if pip_http.is_file() else None,
"recorded_source_url": url_m.group(0).decode() if url_m else None,
"recorded_sha256": (sha_m.group(1) or sha_m.group(2)).decode() if sha_m else None,
"other_new_cache_entries_in_window": [p.name for p in new_archives if p.name != "_hW09NO2UJIjczHf"],
"verdict": ("勘误成立:uv 缓存中 pip-26.2.2 wheel 条目创建于 2026-10-27 02:10:04 +0800(HEL-895 运行窗口内),"
"来源 files.pythonhosted.org,且是该窗口唯一新增缓存条目——该步发生了网络获取,"
"前卡『零下载』对此步不成立;requirements.lock 装机同期未产生任何新缓存条目(全部命中既有缓存)。"
"字节级『完整下载 vs 条件请求』无法由缓存取证区分,按保守口径记为下载。"),
}
top = {n: rows.get(n) for n in ("mem0ai", "qdrant-client", "fastembed")}
result = {
"head": "04eff611e7d85e539d43717711172441420ac853",
"scope": ("只读审计:3.10 固定栈安装元数据按 3.11 Linux markers+extras 求闭包,对照产品 3.11 venv 与本机 uv/pip 缓存;"
"这是依赖闭包清单,不是已完成的 cp311 解析或下载结果"),
"read_only": True, "zero_downloads_this_card": True,
"closure_total": len(rows), "missing_count": len(missing),
"missing_pure_python": sorted(r["name"] for r in missing if not r["native_extension"]),
"missing_native": sorted(r["name"] for r in missing if r["native_extension"]),
"cache_reusable_now": sorted(r["name"] for r in missing if r["classification"] == "cache-reusable"),
"top_level": top,
"missing_detail": missing,
"mem0_identity": identity,
"fastembed_models": fastembed_models,
"pip_2622_event": pip_event,
}
(out_dir / "sdk-audit.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
summary = [
"# HEL-896 · 固定 SDK 离线余缺审计摘要(只读)\n",
f"- 闭包 {len(rows)} 项,产品 3.11 venv 缺 {len(missing)} 项:纯 Python "
f"{len([r for r in missing if not r['native_extension']])} 项、原生扩展 "
f"{len([r for r in missing if r['native_extension']])} 项(" + ", ".join(result["missing_native"]) + ")。",
"- 三个顶层包 WHEEL 均 py3-none-any(纯 Python,可跨 3.10/3.11)。",
f"- mem0ai 固定源码身份:tarball SHA256 {'一致' if identity['tarball_matches_lock'] else '不一致!'}"
f"({identity['pinned_tarball_sha256_measured']});索引同名 wheel 不作数;"
f"hel857 构建过的 wheel({PINNED_WHEEL_SHA256[:12]}…)在临时缓存、未持久。",
f"- 当前缓存可直接复用的缺项 wheel:{result['cache_reusable_now'] or '(mem0 栈闭包内无)'}。",
"- 其余缺项(纯 Python wheel 与 cp311 原生 wheel)由发布卡按 deploy/hel874-release.md §4 "
"获授权后下载并 sha256 留证;缺项不阻塞其余发布工作。",
f"- fastembed 模型缓存实测:{json.dumps(fastembed_models['models'], ensure_ascii=False)}"
"(hel857-data/fastembed-cache,随发布实例落位,零下载)。",
f"- pip 26.2.2 事件:{pip_event['verdict']}",
]
(out_dir / "summary.md").write_text("\n".join(summary) + "\n", encoding="utf-8")
print(json.dumps({"closure_total": len(rows), "missing": len(missing),
"pure": len(result["missing_pure_python"]), "native": len(result["missing_native"]),
"cache_reusable": result["cache_reusable_now"],
"mem0_tarball_matches_lock": identity["tarball_matches_lock"]}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""HEL-896 · 发布归档一致性快照与回退证据(修复 WAL 丢失;不冒充 R6 完整备份)。
总管独立复审(HEL-896 附件 §4)复现:在线库只复制主 `.db` 会丢 WAL 里已提交的资料
(复现件连表都不在;SQLite backup API 则完整)。本工具给出发布卡可直接照抄的归档方式:
停服务 + `PRAGMA wal_checkpoint(TRUNCATE)` 后整目录归档(离线口径,推荐);或
在线用 SQLite backup API 逐库做一致性快照(在线兜底口径)。
产物:`<out>/<name>/` 下的 `databases/`(快照库)、`files/`(其余数据目录原样)、
`MANIFEST.json`(每个文件的 SHA256、源路径、代码精确提交、逐表行数核对结果)、
`<name>.tar.gz`。`--verify` 对既有归档重算哈希并重开快照库核对行数,作为回退演练。
自测(`--selftest`,临时目录,零产品数据)复现两种口径的差异并证明修复,输出
`docs/rework/hel896/release-snapshot/selftest.json`。
用法:
python3 tools/release_snapshot_hel896.py --selftest [outDir]
python3 tools/release_snapshot_hel896.py snapshot --name hel8xx-release \
--db path/a.db --db path/b.sqlite3 --file path/vecdir --file path/hist \
--out archives/ [--online]
python3 tools/release_snapshot_hel896.py verify --archive archives/hel8xx-release.tar.gz
"""
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
import sqlite3
import subprocess
import tarfile
import tempfile
import time
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
def sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def table_counts(db: Path) -> dict[str, int]:
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
try:
tables = [r[0] for r in con.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")]
return {t: con.execute(f"SELECT count(*) FROM \"{t}\"").fetchone()[0] for t in tables}
finally:
con.close()
def checkpoint(db: Path) -> None:
con = sqlite3.connect(str(db))
try:
con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
finally:
con.close()
def snapshot_db(src: Path, dst: Path, *, online: bool) -> str:
"""一致性快照单库。online=False 先 checkpoint(停服口径);True 用 backup API。"""
if not online:
checkpoint(src)
shutil.copy2(src, dst)
return "stop+checkpoint+copy"
with sqlite3.connect(str(src)) as source, sqlite3.connect(str(dst)) as target:
source.backup(target)
return "sqlite-backup-api"
def git_head() -> str:
try:
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=REPO, capture_output=True,
text=True, check=True).stdout.strip()
except Exception:
return "unknown"
def make_snapshot(name: str, dbs: list[Path], files: list[Path], out_dir: Path, *, online: bool) -> dict:
stamp = time.strftime("%Y%m%d-%H%M%S")
root = out_dir / f"{name}-{stamp}"
(root / "databases").mkdir(parents=True, exist_ok=True)
manifest: dict = {"name": name, "created": stamp, "code_commit": git_head(), "tool": "release_snapshot_hel896.py",
"mode": "online-backup-api" if online else "stop-checkpoint-copy",
"databases": [], "files": [], "verify": "not-run"}
for db in dbs:
dst = root / "databases" / db.name
method = snapshot_db(db, dst, online=online)
src_counts = table_counts(db)
dst_counts = table_counts(dst)
ok = src_counts == dst_counts
manifest["databases"].append({"source": str(db), "snapshot": str(dst.relative_to(root)),
"sha256": sha256(dst), "method": method,
"source_table_counts": src_counts, "snapshot_table_counts": dst_counts,
"rows_match": ok})
for f in files:
src = Path(f)
dst = root / "files" / src.name
if src.is_dir():
shutil.copytree(src, dst)
entries = {str(p.relative_to(dst)): sha256(p) for p in sorted(dst.rglob("*")) if p.is_file()}
else:
shutil.copy2(src, dst)
entries = {src.name: sha256(dst)}
manifest["files"].append({"source": str(src), "snapshot": str(dst.relative_to(root)), "entries": entries})
manifest["verify"] = "rows_match=" + str(all(d["rows_match"] for d in manifest["databases"]))
(root / "MANIFEST.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
tar = out_dir / f"{name}-{stamp}.tar.gz"
with tarfile.open(tar, "w:gz") as tf:
tf.add(root, arcname=root.name)
manifest["archive"] = str(tar)
manifest["archive_sha256"] = sha256(tar)
return manifest
def verify_archive(archive: Path) -> dict:
result: dict = {"archive": str(archive), "sha256": sha256(archive), "checks": []}
with tempfile.TemporaryDirectory(prefix="hel896-verify-") as tmp:
with tarfile.open(archive) as tf:
tf.extractall(tmp)
root = next(p for p in Path(tmp).iterdir() if p.is_dir())
manifest = json.loads((root / "MANIFEST.json").read_text(encoding="utf-8"))
result["code_commit"] = manifest.get("code_commit")
result["mode"] = manifest.get("mode")
ok_all = True
for d in manifest["databases"]:
snap = root / d["snapshot"]
digest = sha256(snap)
counts = table_counts(snap)
ok = digest == d["sha256"] and counts == d.get("snapshot_table_counts")
ok_all &= ok
result["checks"].append({"db": d["snapshot"], "sha256_ok": digest == d["sha256"],
"rows_ok": counts == d.get("snapshot_table_counts"),
"counts": counts})
for f in manifest["files"]:
base = root / f["snapshot"]
for rel, want in f["entries"].items():
p = (base / rel) if base.is_dir() else base
ok = sha256(p) == want
ok_all &= ok
result["checks"].append({"file": str(p.relative_to(root)), "sha256_ok": ok})
result["ok"] = ok_all
return result
def selftest(out_dir: Path) -> int:
"""临时库复现:在线裸复制主 .db 丢 WAL 已提交行;checkpoint 与 backup API 都完整。"""
checks: list[dict] = []
with tempfile.TemporaryDirectory(prefix="hel896-snapshot-selftest-") as tmp:
tmp = Path(tmp)
db = tmp / "instance" / "companion.db"
db.parent.mkdir(parents=True)
con = sqlite3.connect(str(db))
con.execute("PRAGMA journal_mode=WAL")
con.execute("CREATE TABLE companion(id INTEGER PRIMARY KEY, payload TEXT)")
con.execute("CREATE TABLE chat_message(id INTEGER PRIMARY KEY, text TEXT)")
con.commit()
con.execute("INSERT INTO companion VALUES(1,'her')")
con.execute("INSERT INTO chat_message VALUES(1,'hello')")
con.commit()
# WAL 保持持有(连接不关、不 checkpoint):已提交行仍在 WAL,不在主 .db。
naive = tmp / "naive-copy.db"
shutil.copy2(db, naive)
try:
row = sqlite3.connect(f"file:{naive}?mode=ro", uri=True).execute(
"SELECT count(*) FROM companion").fetchone()[0]
naive_result = f"rows={row}"
except sqlite3.OperationalError as exc:
naive_result = f"error={exc}"
checks.append({"name": "naive_online_copy_loses_wal", "ok": "rows=1" not in naive_result,
"detail": naive_result})
# backup API(在线口径)
via_api = tmp / "via-backup-api.db"
with sqlite3.connect(str(db)) as source, sqlite3.connect(str(via_api)) as target:
source.backup(target)
api_counts = table_counts(via_api)
checks.append({"name": "backup_api_snapshot_complete", "ok": api_counts == {"companion": 1, "chat_message": 1},
"detail": json.dumps(api_counts)})
# 停服 + checkpoint(离线口径)
con.close()
checkpoint(db)
via_ckpt = tmp / "via-checkpoint.db"
shutil.copy2(db, via_ckpt)
ckpt_counts = table_counts(via_ckpt)
checks.append({"name": "stop_checkpoint_copy_complete", "ok": ckpt_counts == {"companion": 1, "chat_message": 1},
"detail": json.dumps(ckpt_counts)})
# 完整归档 + 回退验证
sem_dir = tmp / "instance" / "vec"
sem_dir.mkdir(exist_ok=True)
(sem_dir / "vectors.bin").write_bytes(b"\x00\x01\x02cg")
out = tmp / "archives"
out.mkdir()
manifest = make_snapshot("hel896-selftest", [db], [sem_dir], out, online=False)
verify = verify_archive(Path(manifest["archive"]))
checks.append({"name": "archive_manifest_hashes_and_rows_verify", "ok": verify["ok"],
"detail": f"commit={verify.get('code_commit')} checks={len(verify['checks'])}"})
ok = all(c["ok"] for c in checks)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "selftest.json").write_text(
json.dumps({"ok": ok, "code_commit": git_head(), "checks": checks}, ensure_ascii=False, indent=2),
encoding="utf-8")
for c in checks:
print(f"{'PASS' if c['ok'] else 'FAIL'} {c['name']} — {c['detail']}")
print(json.dumps({"ok": ok}, ensure_ascii=False))
return 0 if ok else 1
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--selftest", action="store_true")
ap.add_argument("command", nargs="?", choices=["snapshot", "verify"])
ap.add_argument("--name")
ap.add_argument("--db", action="append", default=[], type=Path)
ap.add_argument("--file", action="append", default=[], type=Path)
ap.add_argument("--out", type=Path, default=REPO / "deploy" / "archives")
ap.add_argument("--online", action="store_true", help="在线口径:backup API(默认停服+checkpoint)")
ap.add_argument("--archive", type=Path)
args = ap.parse_args()
if args.selftest:
return selftest(REPO / "docs/rework/hel896/release-snapshot")
if args.command == "snapshot":
if not args.name or not args.db:
ap.error("snapshot 需要 --name 与至少一个 --db")
manifest = make_snapshot(args.name, args.db, args.file, args.out, online=args.online)
print(json.dumps({k: manifest[k] for k in ("archive", "archive_sha256", "code_commit", "mode", "verify")},
ensure_ascii=False, indent=1))
return 0
if args.command == "verify":
if not args.archive:
ap.error("verify 需要 --archive")
result = verify_archive(args.archive)
print(json.dumps(result, ensure_ascii=False, indent=1))
return 0 if result["ok"] else 1
ap.print_help()
return 2
if __name__ == "__main__":
raise SystemExit(main())
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/env python3
"""HEL-896 · A/B/C 分账与阶段切换验证(仅临时库 + 替身,零 provider、零网络)。
总管独立复审(HEL-896 附件 §1)复现的问题:把 A 的一次性总量 55 写进与 B/C 共用的
产品库 PersistentBudget 后,B 的 mem0_extract 与 C 的 dialogue_main 都被
budget_total_requests_exhausted:55/55 挡住,且 budget_total/request_usage/token_usage
无阶段或授权来源字段。本脚本在同一 head 上给出可执行的分账方案并把每一环验证出来:
S0 复现(单账本误配) —— A/B/C 共库时 55 总量挡住 B/C,表格确无阶段/来源字段;
S1 团队测试实例(A) —— 独立库 + total_requests=55/total_tokens=500000 + 当日
类别日顶:按 A 表逐步消费到 55,第 56 次任何类别被拒;
S2 封账 —— 重启不归零;SQLite backup API 一致性快照归档后,归档件
仍是 55/55 且继续拒绝(封账跨重启、跨归档成立);测试档案
只留在团队库;
S3 全新用户实例(B/C) —— 独立新库、不配置一次性总量:A 耗尽后 B(mem0_extract)
与 C(dialogue_main)照常放行;日顶叠加(dialogue 60、
semantic 40、daily_tokens)逐项到顶拒绝;拒绝不落账;
S4 误配守门 —— 用户实例若误写 total 55,B/C 再次被挡(这就是为什么发布
包禁止把 A 总量写进用户实例配置,发布卡按 §6 复核);
S5 冻结保全 —— 全程只写临时目录;仓库配置文件前后哈希不变。
真实 cap 全部保持 0:本脚本不读取也不写入任何生产/权威账(39/60、498/500、冻结 2 条、
HEL-835 闸与 hel857 权威账原样不动)。B 部分的 embed_ops/llm_ops 权威账闸(authority
fail-closed、逐行锚点、公式换算)由既有 verify_semantic_recovery_hel885.py /
verify_mem0_real_hel874.py 在固定 SDK 边界覆盖,不在本脚本重复。
用法:.venv311/bin/python tools/verify_budget_split_hel896.py [输出目录]
"""
from __future__ import annotations
import hashlib
import json
import sqlite3
import sys
import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from cybergril.life.model import PersistentBudget # noqa: E402
from cybergril.memory.store import Store # noqa: E402
from cybergril.think.budget import BudgetConfig, BudgetGuard, BudgetStop # noqa: E402
HEAD = "04eff611e7d85e539d43717711172441420ac853"
RESULTS: list[tuple[str, bool, str]] = []
def check(name: str, ok: bool, detail: str = "") -> None:
RESULTS.append((name, ok, detail))
print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""))
def acquire(guard: PersistentBudget, scene: str, tokens: int = 10, requests: int = 1) -> str:
try:
guard.acquire(scene, tokens=tokens, requests=requests)
return "allowed"
except BudgetStop as exc:
return str(exc)
def snapshot_via_backup_api(src: Path, dst: Path) -> None:
"""一致性快照:SQLite backup API(在线安全;WAL 中已提交行不丢)。"""
with sqlite3.connect(str(src)) as source, sqlite3.connect(str(dst)) as target:
source.backup(target)
def main() -> int:
out_dir = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] / "docs/rework/hel896/budget-split"
out_dir.mkdir(parents=True, exist_ok=True)
repo = Path(__file__).resolve().parents[1]
watched = [repo / "config/models.yaml", repo / "config/semantic.example.yaml"]
before_hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in watched}
report: dict = {"head": HEAD, "no_provider_calls": True, "temp_only": True, "scenes": {}}
with tempfile.TemporaryDirectory(prefix="hel896-budget-split-") as tmp:
tmp = Path(tmp)
# ── S0:复现单账本误配(总管 review_hel895_budget.py 的同形复现) ──
s0 = Store(tmp / "single-ledger.db")
guard0 = PersistentBudget(s0, BudgetGuard(BudgetConfig(
daily_tokens=2_000_000,
daily_requests={"dialogue": 60, "life": 8, "background": 40, "semantic": 40},
total_requests=55, total_tokens=500_000)))
for _ in range(55):
guard0.acquire("dialogue_main", tokens=1)
b_blocked = acquire(guard0, "mem0_extract")
c_blocked = acquire(guard0, "dialogue_main")
columns = {t: [r["name"] for r in s0.execute(f"PRAGMA table_info({t})").fetchall()]
for t in ("budget_total", "request_usage", "token_usage")}
check("S0_single_ledger_repro_A55_blocks_B_and_C",
b_blocked.startswith("budget_total_requests_exhausted") and c_blocked.startswith("budget_total_requests_exhausted"),
f"B={b_blocked} C={c_blocked}")
check("S0_tables_have_no_stage_or_source_columns",
all("stage" not in c and "source" not in c and "auth" not in c for c in columns.values()),
json.dumps(columns, ensure_ascii=False))
report["scenes"]["S0_single_ledger"] = {"team_test_used": guard0.total_requests_used(),
"B_after_A": b_blocked, "C_after_A": c_blocked,
"table_columns": columns}
s0.close()
# ── S1:团队测试实例(A)——独立库,一次性总量 + 当日类别日顶,按 A 表逐步消费 ──
team = Store(tmp / "team-8360.db")
team_cfg = BudgetConfig(daily_tokens=2_000_000,
daily_requests={"dialogue": 60, "life": 8, "background": 40, "semantic": 40},
total_requests=55, total_tokens=500_000)
team_guard = PersistentBudget(team, BudgetGuard(team_cfg))
# A 表逐步(budget-plan-hel874 §1):创建/诠释/习惯 4(background)、对话 16(dialogue)、
# 生活 8(life)、判定/成长/gist 20(background)、主动措辞 3(dialogue),再按表耗到硬顶 55。
plan = [("fact_extract", 4), ("dialogue_main", 16), ("life_event", 8), ("memory_gist", 20), ("proactive_message", 3)]
steps_ok = True
for scene, n in plan:
for _ in range(n):
steps_ok &= acquire(team_guard, scene) == "allowed"
while team_guard.total_requests_used() < 55:
steps_ok &= acquire(team_guard, "dialogue_main") == "allowed"
s1_reject = acquire(team_guard, "dialogue_main")
# life 的当日 8 次在 A 表里已用满:拒绝来自更紧的类别日顶(叠加取最紧,同为硬闸);
# semantic 当日还有余量,第 56 次由一次性总量拒绝。
s1_reject_life = acquire(team_guard, "life_event")
s1_reject_semantic = acquire(team_guard, "mem0_extract")
check("S1_team_instance_A_consumes_55_then_hard_stops",
steps_ok and team_guard.total_requests_used() == 55
and s1_reject.startswith("budget_total_requests_exhausted")
and s1_reject_life.startswith("budget_requests_exhausted:life")
and s1_reject_semantic.startswith("budget_total_requests_exhausted"),
f"used={team_guard.total_requests_used()} dialogue={s1_reject} life={s1_reject_life} semantic={s1_reject_semantic}")
team_tokens_used = team_guard.total_tokens_used()
report["scenes"]["S1_team_instance"] = {"used": team_guard.total_requests_used(),
"tokens_used": team_tokens_used,
"step_plan": plan,
"after_55": {"dialogue": s1_reject, "life": s1_reject_life,
"semantic": s1_reject_semantic}}
# ── S2:封账——重启不归零;backup API 归档件同样封死;测试档案只在团队库 ──
team.close()
team_reopened = Store(tmp / "team-8360.db", init=False)
team_guard2 = PersistentBudget(team_reopened, BudgetGuard(team_cfg))
s2_after_restart = acquire(team_guard2, "dialogue_main")
archive = tmp / "team-8360-sealed.db"
snapshot_via_backup_api(tmp / "team-8360.db", archive)
sealed = Store(archive, init=False)
sealed_guard = PersistentBudget(sealed, BudgetGuard(team_cfg))
s2_archive = acquire(sealed_guard, "mem0_extract")
check("S2_seal_survives_restart_and_archive",
team_guard2.total_requests_used() == 55 and s2_after_restart.startswith("budget_total_requests_exhausted")
and sealed_guard.total_requests_used() == 55 and s2_archive.startswith("budget_total_requests_exhausted"),
f"restart={s2_after_restart} archive={s2_archive} used={sealed_guard.total_requests_used()}")
report["scenes"]["S2_seal"] = {"after_restart": s2_after_restart, "archive_after_backup_api": s2_archive}
team_reopened.close()
sealed.close()
# ── S3:全新用户实例(B/C)——独立新库、无一次性总量:A 耗尽后 B/C 照常放行,日顶叠加 ──
user = Store(tmp / "user-fresh.db")
user_cfg = BudgetConfig(daily_tokens=2_000_000,
daily_requests={"dialogue": 60, "life": 8, "background": 40, "semantic": 40},
total_requests=None, total_tokens=None)
user_guard = PersistentBudget(user, BudgetGuard(user_cfg))
b_start = acquire(user_guard, "mem0_extract")
c_start = acquire(user_guard, "dialogue_main")
# 无一次性总量 = 无总量闸:budget_total 行只作记录(2 次消费照实累计),永不禁停。
check("S3_user_instance_B_and_C_unblocked_after_A",
b_start == "allowed" and c_start == "allowed" and user_guard.config.total_requests is None
and user_guard.total_requests_used() == 2,
f"B={b_start} C={c_start} cumulative_counter={user_guard.total_requests_used()} (record-only, no gate)")
# C 日顶叠加:dialogue 60 到顶拒绝;semantic 40 到顶拒绝;日 token 池到顶拒绝;拒绝不落账。
for _ in range(59):
acquire(user_guard, "dialogue_main")
c_daily = acquire(user_guard, "dialogue_main")
for _ in range(39):
acquire(user_guard, "mem0_extract")
b_daily = acquire(user_guard, "mem0_extract")
dialogue_used = user_guard.requests_used("dialogue")
semantic_used = user_guard.requests_used("semantic")
token_cap = acquire(user_guard, "life_event", tokens=2_000_000_000)
check("S3_daily_caps_stack_on_user_instance",
c_daily.startswith("budget_requests_exhausted:dialogue") and b_daily.startswith("budget_requests_exhausted:semantic")
and dialogue_used == 60 and semantic_used == 40 and token_cap.startswith("budget_tokens_exhausted"),
f"dialogue={c_daily} semantic={b_daily} tokens={token_cap} used d={dialogue_used} s={semantic_used}")
report["scenes"]["S3_user_instance"] = {"B_after_A": b_start, "C_after_A": c_start,
"dialogue_daily_reject": c_daily, "semantic_daily_reject": b_daily,
"token_pool_reject": token_cap,
"budget_total_rows": user_guard.total_requests_used()}
user.close()
# ── S4:误配守门——用户实例若误写 total 55,B/C 再次被挡(发布配置复核点) ──
wrong = Store(tmp / "user-wrong-total.db")
wrong_guard = PersistentBudget(wrong, BudgetGuard(BudgetConfig(
daily_tokens=2_000_000, daily_requests={"dialogue": 60, "life": 8, "background": 40, "semantic": 40},
total_requests=55, total_tokens=500_000)))
for _ in range(55):
wrong_guard.acquire("dialogue_main", tokens=1)
s4_b = acquire(wrong_guard, "mem0_extract")
s4_c = acquire(wrong_guard, "dialogue_main")
check("S4_misconfigured_total_on_user_instance_blocks_B_C",
s4_b.startswith("budget_total_requests_exhausted") and s4_c.startswith("budget_total_requests_exhausted"),
f"B={s4_b} C={s4_c}")
report["scenes"]["S4_misconfig"] = {"B": s4_b, "C": s4_c}
wrong.close()
# ── S5:冻结保全——仓库配置与权威事实零改动 ──
after_hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in watched}
check("S5_repo_configs_unchanged_no_authoritative_writes", before_hashes == after_hashes,
json.dumps(before_hashes, ensure_ascii=False))
report["scenes"]["S5"] = {"config_sha256_before": before_hashes, "config_sha256_after": after_hashes}
ok = all(r[1] for r in RESULTS)
report["checks"] = [{"name": n, "ok": o, "detail": d} for n, o, d in RESULTS]
report["ok"] = ok
(out_dir / "budget-split.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"ok": ok, "checks": len(RESULTS)}, ensure_ascii=False))
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())