HEL-879 rework: fix the four manager-review edges - (1) dual-port launcher owns the app lifecycle exactly once: uvicorn listeners run with lifespan=off, either listener ending stops the other BEFORE the shared store closes, cancellation cleans up listeners first, and create_app's lifespan gains a fail-closed double-entry guard (the old shape silently re-initialized Store/epoch/life/chat_lock on the second entry); (2) room ownership survives delete failures: end_session keeps the session in a bounded persisted cleanup ledger until the remote delete lands (retry/idempotent, LiveKit 404 = already gone = settled), expiry moves rooms into that ledger instead of silently dropping them (the manager measured zero DELETE attempts on expired ends), graceful shutdown does not hang up live calls, restart compensates only this instance's own recorded rooms bounded by attempts/TTL+grace with abandonment recorded, and the router answers 503 (not 404) while a room is still owned so the browser keeps its owed DELETE; (3) TurnLedger binds each speech handle to its own generation stream explicitly (oldest pending handle gets the stream the SDK starts; a newer speech retires an older generation-less handle) - a handle without a generation can no longer steal the next turn's stream/receipt, the worker discards interrupted/failed bindings fail-closed before consuming; (4) release snapshot v3: verify requires three-way count equality (manifest source = manifest snapshot = restored actual; rows_match is an extra constraint, never an OR bypass), the rollback drill actually restores by source path into a persistent isolated tree and opens the restored DBs there, same-basename DBs get collision-free archive names, duplicate sources are refused; new regression file tests/test_voice_rework_hel879.py 14/14 reproducing every edge first, full pytest 338/338

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 04:10:23 +08:00
co-authored by multica-agent
parent 7f0a739213
commit 78a5cfd8d7
11 changed files with 1194 additions and 172 deletions
+169 -40
View File
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
"""HEL-879 · 发布归档一致性快照与回退证据(HEL-896 有限收口版;不冒充 R6 完整备份)。
HEL-896 工具的总管独立复审发现四个失败边界,本版全部收口:
HEL-896 工具的总管独立复审发现四个失败边界,v2 全部收口;v3 收口总管对 v2 的
独立复核(HEL-879 edges):
1. checkpoint 返回值必须核对:`PRAGMA wal_checkpoint(TRUNCATE)` 返回 (busy, log,
checkpointed),busy≠0 即未完成——旧版照抄复制并在 manifest 记 rows_match=False
仍打包成功。本版 busy≠0 / 源表行数≠快照行数一律**明确失败**:CLI 非 0、不产生
仍打包成功。busy≠0 / 源表行数≠快照行数一律**明确失败**:CLI 非 0、不产生
可交付归档(tar 不生成,半成品目录清除)。「先停服」是操作前提,不是忽略实际
失败结果的理由。
2. 目录内真实 SQLite 走一致性路径:history_root/vector_root 等数据目录里的
@@ -13,29 +14,35 @@ HEL-896 工具的总管独立复审发现四个失败边界,本版全部收口
(`semantic.py` 的 history_db_path 就在 history_root 内)。停服口径对它们逐个
checkpoint+复制+逐表核对;**在线口径只允许显式单库 --db(backup API),传入含
SQLite 的目录直接拒绝**——在线目录裸复制正是丢 WAL 的不安全口径。
3. verify 拒绝 rows_match=False 的旧包,并按源路径映射做回退演练:解包到隔离新
目录、实际打开每个库核对行数与哈希(对照 manifest 记录的源行数与快照行数,
两者必须相等且与解包实测一致),非只打开 tar 中快照自证;输出 rollback_plan
(源路径 → 解包恢复路径)。
4. 完整实例归档只支持停服/释放全部写入方;在线模式仅显式单库 backup API。
3. verify 拒绝 rows_match=False/缺失的旧包;三个计数(manifest 源行数、manifest
快照行数、解包实测)必须直接相等——v2 的 `rows_match is True or ...` 允许记录
标记绕过源计数比较(源 2/快照 1 + rows_match=true 仍 ok,总管实测)。回退演练
按源路径映射**实际恢复**到归档旁的持久独立目标树并打开恢复库核行数与哈希,
输出 rollback_plan(源路径 → 真实恢复路径)。
4. 归档侧同名覆盖:不同目录的同名 `ledger.db` 在 v2 都写入 `databases/ledger.db`,
后写覆盖前写、快照先交成功包再由 verify 发现。v3 对归档目标名做无冲突映射
(同名源追加解析路径摘要),同一源重复传入直接拒绝。
完整实例归档只支持停服/释放全部写入方;在线模式仅显式单库 backup API。
产物:`<out>/<name>/` 下的 `databases/`(一致性快照库,含目录内发现的 SQLite)、
`files/`(其余数据文件原样)、`MANIFEST.json`(逐文件 SHA256、源路径、代码精确
提交、逐表行数核对结果)、`<name>.tar.gz`。归档永不删除;本工具不实现 R6。
自测(`--selftest`,临时目录,零产品数据)复现:旧版失败形状(busy checkpoint 仍
打包、rows_match=False 旧包 verify 仍 ok、在线目录含 SQLite)与本版修复,输出
`docs/rework/hel879/release-snapshot/selftest.json`。
自测(`--selftest`,临时目录,零产品数据)复现:全部旧失败形状(busy checkpoint
仍打包、rows_match=False 旧包 verify 仍 ok、在线目录含 SQLite、v2 的 OR 绕过与
同名覆盖)与本版修复,输出 `docs/rework/hel879/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/ # 停服口径(推荐,目录内 SQLite 一并一致性处理)
--out archives/ # 停服口径(推荐,目录内 SQLite 一并一致性处理)
python3 tools/release_snapshot_hel896.py snapshot --name ... --db path/a.db \
--out archives/ --online # 在线口径:仅显式单库 backup API,含 SQLite 的
# --file 目录会被拒绝
python3 tools/release_snapshot_hel896.py verify --archive archives/hel8xx-release.tar.gz
--out archives/ --online # 在线口径:仅显式单库 backup API,含 SQLite 的
# --file 目录会被拒绝
python3 tools/release_snapshot_hel896.py verify --archive archives/hel8xx-release.tar.gz \
[--restore-dir DIR] # 回退演练默认恢复到归档旁 verify-restore-<name>-<时间>/
"""
from __future__ import annotations
@@ -53,7 +60,7 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
SQLITE_MAGIC = b"SQLite format 3\x00"
TOOL_VERSION = 2
TOOL_VERSION = 3
class SnapshotError(RuntimeError):
@@ -132,26 +139,52 @@ def git_head() -> str:
return "unknown"
def _unique_name(taken: set[str], display: str, key: str) -> str:
"""Archive-side name that cannot collide: two different source DBs with
the same basename must never overwrite each other in `databases/`
(HEL-879 总管复核第 4 项). Same-basename sources get a short digest of
their resolved source path appended."""
if display not in taken:
taken.add(display)
return display
digest = hashlib.sha256(key.encode()).hexdigest()[:8]
stem, suffix = Path(display).stem, Path(display).suffix
unique = f"{stem}__{digest}{suffix}"
while unique in taken:
unique = f"{stem}__{digest}{len(taken)}{suffix}"
taken.add(unique)
return unique
def make_snapshot(name: str, dbs: list[Path], files: list[Path], out_dir: Path, *, online: bool) -> dict:
"""做一致性快照。任一环节失败:不产生 tar、清除半成品、抛 SnapshotError。
收口语义(HEL-879):
- 全部 --db 与目录内发现的 SQLite 都走一致性路径并逐表核对源/快照行数;
- 行数不一致或 checkpoint busy = 明确失败(旧版记 rows_match=False 仍打包);
- 在线模式含 SQLite 的 --file 目录直接拒绝(在线目录裸复制丢 WAL)。
- 在线模式含 SQLite 的 --file 目录直接拒绝(在线目录裸复制丢 WAL);
- 同一源重复传入或归档侧目标名冲突 = 明确失败/唯一化(同名 ledger.db
后写覆盖前写、快照先报成功包再由 verify 发现——旧版真实缺陷)。
"""
resolved = [str(Path(db).resolve()) for db in dbs]
duplicates = sorted({p for p in resolved if resolved.count(p) > 1})
if duplicates:
raise SnapshotError(f"--db 同一源重复传入,拒绝:{duplicates}")
stamp = time.strftime("%Y%m%d-%H%M%S")
root = out_dir / f"{name}-{stamp}"
manifest: dict = {"name": name, "created": stamp, "code_commit": git_head(),
"tool": "release_snapshot_hel896.py", "tool_version": TOOL_VERSION,
"mode": "online-backup-api" if online else "stop-checkpoint-copy",
"databases": [], "files": [], "verify": "not-run"}
taken_db_names: set[str] = set()
taken_file_names: set[str] = set()
try:
(root / "databases").mkdir(parents=True, exist_ok=True)
for db in dbs:
if not Path(db).is_file():
raise SnapshotError(f"--db 不是文件:{db}")
dst = root / "databases" / db.name
dst = root / "databases" / _unique_name(
taken_db_names, Path(db).name, str(Path(db).resolve()))
method = snapshot_db(Path(db), dst, online=online)
src_counts = table_counts(Path(db))
dst_counts = table_counts(dst)
@@ -176,7 +209,9 @@ def make_snapshot(name: str, dbs: list[Path], files: list[Path], out_dir: Path,
for emb in embedded:
# 停服口径:目录内真实 SQLite 一并走 checkpoint+复制+逐表核对。
rel = emb.relative_to(src) if emb.is_relative_to(src) else Path(emb.name)
dst = root / "databases" / f"{src.name}__{rel}".replace("/", "__")
display = f"{src.name}__{rel}".replace("/", "__")
dst = root / "databases" / _unique_name(
taken_db_names, display, str(emb.resolve()))
method = snapshot_db(emb, dst, online=False)
src_counts = table_counts(emb)
dst_counts = table_counts(dst)
@@ -189,7 +224,7 @@ def make_snapshot(name: str, dbs: list[Path], files: list[Path], out_dir: Path,
"source_table_counts": src_counts,
"snapshot_table_counts": dst_counts,
"rows_match": True})
dst = root / "files" / src.name
dst = root / "files" / _unique_name(taken_file_names, src.name, str(src.resolve()))
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()}
@@ -216,15 +251,29 @@ def make_snapshot(name: str, dbs: list[Path], files: list[Path], out_dir: Path,
raise
def verify_archive(archive: Path) -> dict:
"""回退演练:隔离新目录解包,实际打开各库核对行数与哈希,按源路径映射。
def _restore_target(restore_root: Path, source: str) -> Path:
"""Map a recorded source path into the isolated restore tree, preserving
the full source hierarchy so same-basename DBs can never collide there."""
sanitized = source.strip("/").replace("/", "__")
return restore_root / "by-source" / sanitized
def verify_archive(archive: Path, restore_root: Path | None = None) -> dict:
"""回退演练:隔离新目录解包,按源路径映射**实际恢复**到独立目标树,
打开恢复出的每个库核对行数与哈希(不是只打开 tar 内布局自证)。
收口语义(HEL-879):
- manifest 记录 rows_match=False(旧版失败包)→ ok=False 拒绝;
- 行数同时对照 source_table_counts 与 snapshot_table_counts:两者必须相等,
且与解包实测一致(旧版只比快照自证,源=1 行/快照=0 行的漏行包仍 ok)。
- 三个计数必须直接相等:manifest 源行数 = manifest 快照行数 = 解包实测;
`rows_match` 只是额外约束,缺失或矛盾明确拒绝(旧版 OR 逻辑允许记录值
绕过源计数比较);
- 恢复目标树默认落在归档旁的持久目录,rollback_plan 指向真实存在的恢复
文件(旧版输出随 TemporaryDirectory 消失的路径)。
"""
result: dict = {"archive": str(archive), "sha256": sha256(archive), "checks": []}
archive = Path(archive)
if restore_root is None:
restore_root = archive.parent / f"verify-restore-{archive.stem}-{time.strftime('%Y%m%d-%H%M%S')}"
result: dict = {"archive": str(archive), "sha256": sha256(archive),
"restore_root": str(restore_root), "checks": []}
with tempfile.TemporaryDirectory(prefix="hel879-verify-") as tmp:
with tarfile.open(archive) as tf:
tf.extractall(tmp)
@@ -237,39 +286,56 @@ def verify_archive(archive: Path) -> dict:
rollback_plan = []
for d in manifest["databases"]:
snap = root / d["snapshot"]
digest = sha256(snap)
# The actual restore step: copy into the isolated target tree at
# the recorded source path's mapped location, then verify THERE.
restored = _restore_target(restore_root, str(d.get("source") or d["snapshot"]))
restored.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(snap, restored)
digest = sha256(restored)
try:
counts = table_counts(snap)
counts = table_counts(restored)
except sqlite3.Error as exc:
result["checks"].append({"db": d["snapshot"], "sha256_ok": digest == d["sha256"],
"rows_ok": False, "error": str(exc),
result["checks"].append({"db": d["snapshot"], "restored": str(restored),
"sha256_ok": False, "rows_ok": False, "error": str(exc),
"rows_match_recorded": d.get("rows_match")})
ok_all = False
continue
recorded_rows_match = d.get("rows_match")
src_counts = d.get("source_table_counts")
snap_counts = d.get("snapshot_table_counts")
rows_ok = counts == snap_counts and (
recorded_rows_match is True or (src_counts is not None and counts == src_counts))
legacy_reject = recorded_rows_match is False or (
recorded_rows_match is None and src_counts != snap_counts)
# Three-way equality is the only passing shape; the recorded flag
# is an extra constraint, never a substitute for the comparison.
counts_agree = (
isinstance(src_counts, dict) and isinstance(snap_counts, dict)
and counts == src_counts and counts == snap_counts
)
rows_ok = counts_agree
legacy_reject = recorded_rows_match is not True or not counts_agree
ok = digest == d["sha256"] and rows_ok and not legacy_reject
ok_all &= ok
result["checks"].append({"db": d["snapshot"], "sha256_ok": digest == d["sha256"],
result["checks"].append({"db": d["snapshot"], "restored": str(restored),
"sha256_ok": digest == d["sha256"],
"rows_ok": rows_ok, "counts": counts,
"source_counts": src_counts,
"snapshot_counts": snap_counts,
"rows_match_recorded": recorded_rows_match,
"rejected_legacy_package": legacy_reject})
rollback_plan.append({"source": d.get("source"), "restored_path": str(snap),
"restore_action": "停服后复制回源路径(行数与哈希已在本演练核对)"})
rollback_plan.append({"source": d.get("source"), "restored_path": str(restored),
"restore_action": "停服后复制回源路径(行数与哈希已在恢复树实际核对)"})
for f in manifest["files"]:
base = root / f["snapshot"]
restored_dir = _restore_target(restore_root, str(f.get("source") or f["snapshot"]))
restored_dir.parent.mkdir(parents=True, exist_ok=True)
if base.is_dir():
shutil.copytree(base, restored_dir, dirs_exist_ok=True)
else:
shutil.copy2(base, restored_dir)
for rel, want in f["entries"].items():
p = (base / rel) if base.is_dir() else base
p = (restored_dir / rel) if restored_dir.is_dir() else restored_dir
ok = sha256(p) == want
ok_all &= ok
result["checks"].append({"file": str(p.relative_to(root)), "sha256_ok": ok})
rollback_plan.append({"source": f.get("source"), "restored_path": str(base),
result["checks"].append({"file": rel, "restored": str(p), "sha256_ok": ok})
rollback_plan.append({"source": f.get("source"), "restored_path": str(restored_dir),
"restore_action": "停服后按相对结构复制回源目录"})
result["rollback_plan"] = rollback_plan
result["ok"] = ok_all
@@ -476,6 +542,67 @@ def selftest(out_dir: Path) -> int:
checks.append({"name": "backup_api_snapshot_complete",
"ok": api_counts.get("companion") == 1 and api_counts.get("chat_message") == 1,
"detail": json.dumps(api_counts)})
# ── 总管对 v2 的 edges(HEL-879 独立复核)──
# Edge A:manifest 记 rows_match=true 但源计数被改为 events=2(快照=1)。
# v2 的 `rows_match is True or ...` 绕过源计数比较 → 仍 ok;v3 必须拒绝。
clean = make_snapshot("edge-counts", [db], [], out, online=False)
edge_unpack = out / "edge-unpack"
with tarfile.open(clean["archive"]) as tf:
tf.extractall(edge_unpack)
edge_pkg = next(edge_unpack.iterdir())
edge_manifest_path = edge_pkg / "MANIFEST.json"
edge_manifest = json.loads(edge_manifest_path.read_text(encoding="utf-8"))
edge_manifest["databases"][0]["source_table_counts"]["events"] = 2
edge_manifest_path.write_text(json.dumps(edge_manifest, ensure_ascii=False))
edge_tar = tmp / "edge-counts-tampered.tar.gz"
with tarfile.open(edge_tar, "w:gz") as tf:
tf.add(edge_pkg, arcname=edge_pkg.name)
edge_verify = verify_archive(edge_tar, restore_root=tmp / "edge-restore")
checks.append({"name": "fix_rows_match_true_cannot_bypass_source_counts",
"ok": edge_verify["ok"] is False and all(
c.get("rejected_legacy_package") for c in edge_verify["checks"]
if "rejected_legacy_package" in c),
"detail": f"ok={edge_verify['ok']} "
f"counts={edge_verify['checks'][0].get('counts')} "
f"source={edge_verify['checks'][0].get('source_counts')}"})
# Edge B:两份不同目录的同名 ledger.db。v2 后写覆盖前写、快照仍交成功包;
# v3 无冲突映射 + verify 全过 + 恢复树里两个源路径各自落位。
la = tmp / "ledger-a" / "ledger.db"
lb = tmp / "ledger-b" / "ledger.db"
for path, value in [(la, "first"), (lb, "second")]:
path.parent.mkdir(parents=True, exist_ok=True)
with sqlite3.connect(str(path)) as conn:
conn.execute("CREATE TABLE item(value TEXT)")
conn.execute("INSERT INTO item VALUES(?)", (value,))
same = make_snapshot("same-basename", [la, lb], [], out, online=False)
snap_names = [Path(d["snapshot"]).name for d in same["databases"]]
same_restore = tmp / "same-restore"
same_verify = verify_archive(Path(same["archive"]), restore_root=same_restore)
plan = same_verify.get("rollback_plan", [])
restored_paths = [e["restored_path"] for e in plan if e.get("source", "").endswith("ledger.db")]
distinct = len(set(restored_paths)) == 2 and all(
Path(p).is_file() for p in restored_paths)
rows = sorted(sqlite3.connect(f"file:{p}?mode=ro", uri=True)
.execute("SELECT value FROM item").fetchone()[0]
for p in restored_paths)
dup_failed = None
try:
make_snapshot("dup-source", [la, la], [], out, online=False)
except SnapshotError as exc:
dup_failed = str(exc)
checks.append({"name": "fix_same_basename_no_overwrite_and_duplicate_refused",
"ok": (len(set(snap_names)) == 2 and same_verify["ok"] is True
and distinct and rows == ["first", "second"]
and dup_failed is not None),
"detail": f"snap_names={snap_names} verify_ok={same_verify['ok']} "
f"restored_rows={rows} dup_refused={'yes' if dup_failed else 'no'}"})
# 恢复路径必须真实存在于恢复树(不是随 TemporaryDirectory 消失的路径)。
checks.append({"name": "restore_drill_paths_persist",
"ok": all(Path(p).is_file() for p in restored_paths)
and same_restore.is_dir(),
"detail": f"restore_root={same_restore}"})
ok = all(c["ok"] for c in checks)
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / "selftest.json").write_text(
@@ -499,6 +626,8 @@ def main() -> int:
ap.add_argument("--online", action="store_true",
help="在线口径:仅显式单库 backup API(默认停服+checkpoint;含 SQLite 的 --file 目录会被拒绝)")
ap.add_argument("--archive", type=Path)
ap.add_argument("--restore-dir", type=Path,
help="回退演练的恢复目标树(默认:归档旁 verify-restore-<name>-<时间>/,持久保留供回滚使用)")
args = ap.parse_args()
if args.selftest:
return selftest(REPO / "docs/rework/hel879/release-snapshot")
@@ -519,7 +648,7 @@ def main() -> int:
if args.command == "verify":
if not args.archive:
ap.error("verify 需要 --archive")
result = verify_archive(args.archive)
result = verify_archive(args.archive, restore_root=args.restore_dir)
print(json.dumps(result, ensure_ascii=False, indent=1))
return 0 if result["ok"] else 1
ap.print_help()