HEL-919: enforce live request deadlines and preserve continuation data on rollback
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -9,16 +9,14 @@ deploy/hel914-user/activate.sh 只接受空库,这是它不能续用的原因
|
||||
三条铁律:
|
||||
1. **源库只读**。一律以 `mode=ro` 打开,任何路径都不写源库;旧封账、旧
|
||||
计数、冻结值、旧失败记录原样保留在源库,迁移后逐项核对不变。
|
||||
2. **旧账冻结、新账隔离**。迁移副本中,旧 `budget_total` 的
|
||||
sealed/sealed_* 标记被移入冻结出处键 `cont_prior_sealed*`(仅删副本里的
|
||||
live sealed 键,源库不动);token_usage/request_usage 历史行与
|
||||
total_requests/total_tokens 计数原样保留,新用量由既有 PersistentBudget
|
||||
机制在**同一副本**上继续累计——新旧在同一份账里天然可分(cont_migrated_at
|
||||
之前/之后),不存在第二份权威账并发消费。语义嵌入权威账(embed_ops)
|
||||
2. **旧账冻结、新账隔离**。旧 sealed*/total_* 原键原值保留,
|
||||
新用量由 PersistentBudget 的 hel919 scope 单独记账。
|
||||
语义嵌入权威账(embed_ops)
|
||||
**不复制**:它仍是唯一权威账文件,经 semantic.template.yaml 的累计上限
|
||||
算式续账(见 README §语义账)。
|
||||
3. **幂等与回退**。同一源重复迁移 = 安全 no-op;不同源拒绝;迁移前目标库
|
||||
如已存在先做一致性备份,`rollback` 按 continuation.json 精确还原或清除。
|
||||
如已存在先做一致性备份。回退发现任何迁移后变化默认拒绝;--force 也须
|
||||
先一致性归档数据库与资料目录并核验成功,才允许回退。
|
||||
|
||||
队列盘点只输出**数量与待处理 ID**(persona_job/growth_job/mem_job/
|
||||
chat_affect_job/sem_batch/sharing_attempt/reach_out/life_activity),不输出
|
||||
@@ -42,6 +40,7 @@ import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
@@ -206,6 +205,73 @@ def _refuse(msg: str, **extra) -> None:
|
||||
raise SystemExit(json.dumps({"ok": False, **extra, "error": msg}, ensure_ascii=False))
|
||||
|
||||
|
||||
def _data_path(data: Path, rel: str) -> Path:
|
||||
path = Path(rel)
|
||||
if not rel or path.is_absolute() or ".." in path.parts or path == Path("."):
|
||||
_refuse("invalid_data_directory", refused="bad_spec")
|
||||
target = data / path
|
||||
try:
|
||||
target.resolve().relative_to(data.resolve())
|
||||
except ValueError:
|
||||
_refuse("data_directory_outside_instance", refused="bad_spec")
|
||||
return target
|
||||
|
||||
|
||||
def _data_snapshot(data: Path) -> dict:
|
||||
"""Logical database + file hashes; detects updates as well as new rows.
|
||||
|
||||
Raw SQLite file hashes miss WAL changes and change on harmless checkpoints.
|
||||
Only digests are recorded; no private row contents enter the report.
|
||||
"""
|
||||
conn = _ro(data / "companion.db")
|
||||
try:
|
||||
digest = hashlib.sha256()
|
||||
for line in conn.iterdump():
|
||||
digest.update(line.encode("utf-8"))
|
||||
digest.update(b"\n")
|
||||
finally:
|
||||
conn.close()
|
||||
files = {}
|
||||
for path in sorted(data.rglob("*")):
|
||||
if path.is_symlink():
|
||||
_refuse("symlink_in_data: preserve manually before rollback", refused="unsafe_data")
|
||||
rel = str(path.relative_to(data))
|
||||
if rel in {"companion.db", "companion.db-wal", "companion.db-shm", "continuation.json"}:
|
||||
continue
|
||||
if path.is_file():
|
||||
files[rel] = _sha256(path)
|
||||
return {"database": digest.hexdigest(), "files": files}
|
||||
|
||||
|
||||
def _archive_before_rollback(base: Path, expected: dict) -> Path:
|
||||
"""Archive first, verify both copies, and leave source intact on any error."""
|
||||
backups = base / "backups"
|
||||
backups.mkdir(parents=True, exist_ok=True)
|
||||
archive = Path(tempfile.mkdtemp(prefix=f"rollback-{int(time.time())}-", dir=backups))
|
||||
data = base / "data"
|
||||
saved = archive / "data"
|
||||
try:
|
||||
saved.mkdir()
|
||||
_consistency_copy(data / "companion.db", saved / "companion.db")
|
||||
for path in data.iterdir():
|
||||
if path.name in {"companion.db", "companion.db-wal", "companion.db-shm"}:
|
||||
continue
|
||||
if path.is_dir():
|
||||
shutil.copytree(path, saved / path.name)
|
||||
else:
|
||||
shutil.copy2(path, saved / path.name)
|
||||
if _data_snapshot(saved) != expected or _data_snapshot(data) != expected:
|
||||
_refuse("rollback_archive_verification_failed", refused="archive_failed",
|
||||
partial_archive=str(archive))
|
||||
(archive / "manifest.json").write_text(json.dumps(
|
||||
{"complete": True, "snapshot": expected, "files": _dir_manifest(saved)},
|
||||
ensure_ascii=False, indent=2) + "\n")
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
_refuse(f"rollback_archive_failed:{type(exc).__name__}", refused="archive_failed",
|
||||
partial_archive=str(archive))
|
||||
return archive
|
||||
|
||||
|
||||
def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
|
||||
pre = preflight(db) # 含空库/缺出生/缺诠释拒绝
|
||||
src_sha = pre["db_sha256"]
|
||||
@@ -255,7 +321,7 @@ def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
|
||||
# 3) 向量/推导史等数据目录随实例迁移(可选;含逐文件哈希清单)。
|
||||
copied_dirs = {}
|
||||
for src_dir, rel in data_dirs:
|
||||
s, d = Path(src_dir), data / rel
|
||||
s, d = Path(src_dir), _data_path(data, rel)
|
||||
if not s.is_dir():
|
||||
_refuse(f"data_dir_missing:{s}", refused="data_dir_missing")
|
||||
if d.exists():
|
||||
@@ -274,9 +340,10 @@ def migrate(db: Path, base: Path, data_dirs: list[tuple[str, str]]) -> dict:
|
||||
"migrated_at": now_iso,
|
||||
"queue_policy": "不删队列、不静默禁用;未批准能力 cap=0 保持关闭;"
|
||||
"旧排队工作执行时计入新账,不执行则保留并在队列盘点中如实报告",
|
||||
"rollback_snapshot": _data_snapshot(data),
|
||||
}
|
||||
cont.write_text(json.dumps(record, ensure_ascii=False, indent=1) + "\n")
|
||||
# 4) 自检:同一位她前后可核 + 旧账冻结 + 副本 live seal 已移除。
|
||||
# 4) 自检:同一位她前后可核,旧账和旧封账逐字保留。
|
||||
conn = _ro(tdb)
|
||||
try:
|
||||
post = {"identity": _identity(conn), "provenance": _counts(conn, SAME_HER_TABLES),
|
||||
@@ -309,27 +376,40 @@ def _int_or_hash(sha: str) -> int:
|
||||
return int(sha[:15], 16)
|
||||
|
||||
|
||||
def rollback(base: Path) -> dict:
|
||||
def rollback(base: Path, *, force: bool = False) -> dict:
|
||||
data = base / "data"
|
||||
cont = data / "continuation.json"
|
||||
if not cont.exists():
|
||||
_refuse("nothing_to_rollback: continuation.json 不存在", refused="no_continuation")
|
||||
for live in (base / "window-active", base / "logs" / "api.pid"):
|
||||
if live.exists():
|
||||
_refuse("refused_live_instance", refused="live_instance")
|
||||
rec = json.loads(cont.read_text())
|
||||
tdb = data / "companion.db"
|
||||
existed = rec["target"].get("target_db_existed_before")
|
||||
backup = rec["target"].get("backup")
|
||||
if existed and (not backup or not Path(backup).is_file()):
|
||||
_refuse("pre_migration_backup_missing", refused="backup_missing")
|
||||
# Validate every deletion target before touching the database or directories.
|
||||
dirs = [_data_path(data, rel) for rel in rec["target"].get("data_dirs", {})]
|
||||
current = _data_snapshot(data)
|
||||
changed = current != rec.get("rollback_snapshot")
|
||||
if changed and not force:
|
||||
_refuse("post_migration_data_changed: use --force only after reviewing preservation",
|
||||
refused="new_data")
|
||||
archive = _archive_before_rollback(base, current) if force else None
|
||||
if existed and backup:
|
||||
Path(backup).exists() or _refuse(f"backup_missing:{backup}", refused="backup_missing")
|
||||
_consistency_copy(Path(backup), tdb)
|
||||
note = "目标库已从迁移前一致性备份还原"
|
||||
else:
|
||||
tdb.exists() and tdb.unlink()
|
||||
for name in ("companion.db", "companion.db-wal", "companion.db-shm"):
|
||||
(data / name).unlink(missing_ok=True)
|
||||
note = "迁移前目标库不存在:迁移副本已删除(源库从未被写过)"
|
||||
for rel in rec["target"].get("data_dirs", {}):
|
||||
d = data / rel
|
||||
for d in dirs:
|
||||
d.exists() and shutil.rmtree(d)
|
||||
cont.unlink()
|
||||
return {"ok": True, "rolled_back": note, "source_untouched": rec["source"]["db"]}
|
||||
return {"ok": True, "rolled_back": note, "source_untouched": rec["source"]["db"],
|
||||
"preserved_archive": str(archive) if archive else None}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -344,6 +424,7 @@ def main() -> int:
|
||||
help="随实例迁移的数据目录(如向量库/推导史),SRC=目标 data 下相对路径")
|
||||
r = sub.add_parser("rollback")
|
||||
r.add_argument("--base", required=True, type=Path)
|
||||
r.add_argument("--force", action="store_true", help="先一致性归档并核验后,再回退变化过的副本")
|
||||
args = ap.parse_args()
|
||||
if args.cmd == "preflight":
|
||||
out = preflight(args.db)
|
||||
@@ -352,12 +433,11 @@ def main() -> int:
|
||||
for pair in args.data_dir:
|
||||
src, sep, rel = pair.partition("=")
|
||||
(src and sep and rel) or _refuse(f"bad_data_dir_spec:{pair}", refused="bad_spec")
|
||||
rel.startswith("/") or ".." not in Path(rel).parts or _refuse(
|
||||
f"bad_data_dir_rel:{rel}", refused="bad_spec")
|
||||
_data_path(args.base / "data", rel)
|
||||
dirs.append((src, rel))
|
||||
out = migrate(args.db, args.base, dirs)
|
||||
else:
|
||||
out = rollback(args.base)
|
||||
out = rollback(args.base, force=args.force)
|
||||
print(json.dumps(out, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user