247 lines
11 KiB
Python
247 lines
11 KiB
Python
#!/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())
|