501 lines
23 KiB
Python
501 lines
23 KiB
Python
"""HEL-919 · 同一位她接续包离线测试(合成旧档案 + 替身,零真实调用/零网络)。
|
||
|
||
覆盖验收清单:
|
||
- 空档案拒绝(不冒充同一位她接续成功);缺出生/缺诠释拒绝;
|
||
- 非空同一档案前后保留(身份指纹、出生、记忆、聊天、生活逐表计数相等);
|
||
- 旧 seal 与旧账不变(源库逐项核对;副本冻结为 cont_prior_*,live seal 移除),
|
||
新计数单独可核(PersistentBudget 在副本上继续累计,重启不重置);
|
||
- 数据目录(向量库/推导史)随实例迁移;
|
||
- 幂等(同源 no-op)/ 不同源拒绝 / 回退精确还原;
|
||
- window_guard:默认关闭、未批准、过期、错误实例全部拒绝,有效窗口放行;
|
||
- 队列盘点只含数量与 ID,不含任何内容文本。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import importlib.util
|
||
import json
|
||
import sqlite3
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
from cybergril.life.model import PersistentBudget
|
||
from cybergril.memory.store import Store
|
||
from cybergril.think.budget import BudgetConfig, BudgetGuard, BudgetStop
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
PKG = ROOT / "deploy" / "hel919-continuation"
|
||
|
||
|
||
def _load_migrator():
|
||
spec = importlib.util.spec_from_file_location("migrate_same_her", PKG / "migrate_same_her.py")
|
||
mod = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(mod)
|
||
return mod
|
||
|
||
|
||
MIG = _load_migrator()
|
||
|
||
|
||
# ---------------------------------------------------------------- 合成旧档案
|
||
|
||
def build_synthetic_archive(path: Path, *, sealed: bool = True, seed: int = 1) -> None:
|
||
"""隔离合成库:非空同一位她 + 旧用量 + 旧封账 + 待处理队列(无任何真实数据)。"""
|
||
store = Store(path)
|
||
with store.conn:
|
||
store.execute("INSERT INTO companion VALUES(1, ?)", (json.dumps(
|
||
{"name": f"测试她{seed}", "birth": "2001-02-03 04:05"}, ensure_ascii=False),))
|
||
store.execute(
|
||
"INSERT INTO bazi_core VALUES(1,'{\"y\":2001}',?,'辛','金','{}','{}',0.6,'[]',1,?)",
|
||
(json.dumps({"year": "辛巳", "month": "庚寅", "day": "辛卯", "time": "庚寅"}), seed))
|
||
store.execute("INSERT INTO persona_interp VALUES(1,?,?,'stub-model',1,'synthetic')",
|
||
(f"诠释原文{seed}", f"pillars-hash-{seed}"))
|
||
store.execute("INSERT INTO persona_seed VALUES(1,?,1,'synthetic',1)", (f"初始习惯{seed}",))
|
||
# chat_message: id, ts, role, text, turn_id, status
|
||
for i in range(3):
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES(?,?,?,?,?)",
|
||
(1000 + i, "user" if i % 2 == 0 else "companion",
|
||
f"synthetic turn {seed}-{i}", f"t{seed}-{i}", "sent"))
|
||
store.execute("INSERT INTO mem_episodic(ts,role,raw,gist,salience,accessibility) "
|
||
"VALUES(1000,'user','合成原文','合成要点',0.5,1.0)")
|
||
store.execute("INSERT INTO mem_relational(kind,content,first_seen,last_used,strength) "
|
||
"VALUES('ritual','合成暗语',1,2,0.8)")
|
||
store.execute("INSERT INTO life_event(ts,kind,content,salience,source,day_key) "
|
||
"VALUES(1000,'scene','合成生活',0.4,'generated','2026-11-01')")
|
||
store.execute("INSERT INTO dyad_event(id,ts,kind,summary,severity) VALUES(1,1000,'repair','合成事件',0.1)")
|
||
# 待处理队列(只证明盘点,不含真实内容)
|
||
store.execute("INSERT INTO chat_affect_job VALUES(3,'pending','synthetic',0,1,NULL)")
|
||
store.execute("INSERT INTO growth_job VALUES('chat',1,'pending','synthetic',0)")
|
||
# 旧用量 + 旧封账:走真实 PersistentBudget 路径
|
||
cfg = BudgetConfig(daily_tokens=1_000_000,
|
||
daily_requests={"dialogue": 10, "life": 10, "background": 10, "semantic": 10},
|
||
total_requests=55)
|
||
guard = PersistentBudget(store, BudgetGuard(cfg))
|
||
hold = guard.acquire("dialogue_main", requests=1, tokens=1234)
|
||
guard.settle(hold, actual_tokens=1000)
|
||
if sealed:
|
||
guard.seal()
|
||
store.close()
|
||
|
||
|
||
def build_semantic_dirs(base: Path) -> tuple[Path, Path]:
|
||
vec, hist = base / "vec", base / "hist"
|
||
vec.mkdir(parents=True), hist.mkdir(parents=True)
|
||
(vec / "v.bin").write_bytes(b"synthetic-vector")
|
||
(hist / "h.json").write_text("{}")
|
||
return vec, hist
|
||
|
||
|
||
@pytest.fixture()
|
||
def synth(tmp_path):
|
||
src = tmp_path / "old" / "companion.db"
|
||
build_synthetic_archive(src)
|
||
base = tmp_path / "hel919"
|
||
(base / "data").mkdir(parents=True)
|
||
return src, base
|
||
|
||
|
||
# ---------------------------------------------------------------- preflight
|
||
|
||
def test_preflight_refuses_empty_archive(tmp_path):
|
||
empty = tmp_path / "empty.db"
|
||
Store(empty).close() # 全新空库:companion 表为空
|
||
with pytest.raises(SystemExit):
|
||
MIG.preflight(empty)
|
||
|
||
|
||
def test_preflight_refuses_missing_birth(tmp_path):
|
||
src, _ = build_partial(tmp_path, drop="bazi_core")
|
||
with pytest.raises(SystemExit):
|
||
MIG.preflight(src)
|
||
|
||
|
||
def test_preflight_refuses_missing_persona(tmp_path):
|
||
src, _ = build_partial(tmp_path, drop="persona_interp")
|
||
with pytest.raises(SystemExit):
|
||
MIG.preflight(src)
|
||
|
||
|
||
def build_partial(tmp_path, *, drop: str):
|
||
src = tmp_path / "partial.db"
|
||
build_synthetic_archive(src, seed=2)
|
||
conn = sqlite3.connect(src)
|
||
with conn:
|
||
conn.execute(f"DELETE FROM {drop}")
|
||
conn.close()
|
||
return src, tmp_path
|
||
|
||
|
||
def test_preflection_reports_counts_and_ids_only(synth):
|
||
src, _ = synth
|
||
report = MIG.preflight(src)
|
||
assert report["ok"] and report["identity"]["name"] == "测试她1"
|
||
assert report["provenance"]["chat_message"] == 3
|
||
assert report["queues"]["chat_affect_job"]["pending"] == 1
|
||
assert report["queues"]["chat_affect_job"]["pending_ids"] == ["3"]
|
||
assert report["accounting"]["sealed"]["sealed"] == 1
|
||
# 内容不出现在任何 JSON 输出里
|
||
blob = json.dumps(report, ensure_ascii=False)
|
||
for secret in ("合成原文", "合成暗语", "合成生活", "诠释原文1"):
|
||
assert secret not in blob
|
||
|
||
|
||
# ---------------------------------------------------------------- migrate
|
||
|
||
def _migrate(src, base, dirs=()):
|
||
return MIG.migrate(src, base, [(str(s), rel) for s, rel in dirs])
|
||
|
||
|
||
def test_migrate_preserves_same_her_and_freezes_old_ledger(synth, tmp_path):
|
||
src, base = synth
|
||
vec, hist = build_semantic_dirs(tmp_path / "sem")
|
||
before_bytes = src.read_bytes()
|
||
out = _migrate(src, base, dirs=[(vec, "sem/vec"), (hist, "sem/hist")])
|
||
rec = out["record"]
|
||
# 同一位她:身份指纹一致、出处逐表计数一致(自检已断言,这里独立复核)
|
||
assert out["selfcheck"]["same_her"] and out["selfcheck"]["provenance_preserved"]
|
||
conn = sqlite3.connect(f"file:{base/'data'/'companion.db'}?mode=ro", uri=True)
|
||
conn.row_factory = sqlite3.Row
|
||
assert conn.execute("SELECT count(*) n FROM companion").fetchone()["n"] == 1
|
||
assert conn.execute("SELECT count(*) n FROM chat_message").fetchone()["n"] == 3
|
||
assert conn.execute("SELECT count(*) n FROM mem_episodic").fetchone()["n"] == 1
|
||
total = {r["key"]: r["value"] for r in conn.execute("SELECT * FROM budget_total")}
|
||
conn.close()
|
||
# 旧账逐字保留:旧键(含 sealed/sealed_*)一个不改、不删、不改名,
|
||
# 只新增 cont_scope/cont_source_sha256/cont_migrated_at 三个出处标记
|
||
cont_added = {"cont_scope", "cont_source_sha256", "cont_migrated_at"}
|
||
sconn = sqlite3.connect(f"file:{src}?mode=ro", uri=True)
|
||
sconn.row_factory = sqlite3.Row
|
||
src_total = MIG._accounting(sconn)["budget_total"]
|
||
sconn.close()
|
||
assert {k: v for k, v in total.items() if k not in cont_added} == src_total
|
||
assert cont_added <= set(total)
|
||
assert total["sealed"] == 1 and total["sealed_requests"] == 1 # 旧封账原样(迁移前真实用量 1 次)
|
||
assert total["total_requests"] == 1 and total["total_tokens"] == 1000
|
||
# 源库逐字节不变
|
||
assert src.read_bytes() == before_bytes
|
||
# 数据目录随实例迁移
|
||
assert (base / "data" / "sem" / "vec" / "v.bin").read_bytes() == b"synthetic-vector"
|
||
assert (base / "data" / "sem" / "hist" / "h.json").exists()
|
||
assert set(rec["target"]["data_dirs"]) == {"sem/vec", "sem/hist"}
|
||
# 迁移记录内容不含聊天/生活文本
|
||
blob = json.dumps(rec, ensure_ascii=False)
|
||
for secret in ("合成原文", "合成暗语", "合成生活"):
|
||
assert secret not in blob
|
||
|
||
|
||
def test_migrate_idempotent_same_source_and_refuses_different(synth, tmp_path):
|
||
src, base = synth
|
||
assert _migrate(src, base)["ok"]
|
||
again = _migrate(src, base)
|
||
assert again.get("idempotent_noop") is True
|
||
other = tmp_path / "other.db"
|
||
build_synthetic_archive(other, seed=9)
|
||
with pytest.raises(SystemExit):
|
||
_migrate(other, base)
|
||
|
||
|
||
def test_rollback_restores_pre_migration_state(synth):
|
||
src, base = synth
|
||
# 目标已有旧库(非本工具产物)→ 备份 → 迁移 → 回退还原
|
||
pre = base / "data" / "companion.db"
|
||
Store(pre).close()
|
||
assert _migrate(src, base)["ok"]
|
||
out = MIG.rollback(base)
|
||
assert out["ok"]
|
||
conn = sqlite3.connect(f"file:{pre}?mode=ro", uri=True)
|
||
assert conn.execute("SELECT count(*) n FROM companion").fetchone()[0] == 0 # 还原为迁移前的空库
|
||
conn.close()
|
||
assert not (base / "data" / "continuation.json").exists()
|
||
|
||
|
||
def test_rollback_removes_copy_when_target_was_absent(tmp_path):
|
||
src = tmp_path / "fresh.db"
|
||
build_synthetic_archive(src)
|
||
base = tmp_path / "inst"
|
||
(base / "data").mkdir(parents=True)
|
||
assert _migrate(src, base)["ok"]
|
||
out = MIG.rollback(base)
|
||
assert out["ok"] and not (base / "data" / "companion.db").exists()
|
||
|
||
|
||
def test_refuse_migrate_onto_live_instance(synth):
|
||
src, base = synth
|
||
(base / "window-active").write_text("")
|
||
with pytest.raises(SystemExit):
|
||
_migrate(src, base)
|
||
|
||
|
||
# ------------------------------------------------------- 新账隔离 + 重启不重置
|
||
|
||
def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
|
||
src, base = synth
|
||
assert _migrate(src, base)["ok"]
|
||
tdb = base / "data" / "companion.db"
|
||
cfg = BudgetConfig(daily_tokens=5000, daily_requests={
|
||
"dialogue": 5, "life": 5, "background": 5, "semantic": 5})
|
||
# 旧口径(scope="")在源库与副本上都被旧封账拒绝:旧账没被改写、没被绕过
|
||
for db in (src, tdb):
|
||
legacy = Store(db, init=False)
|
||
with pytest.raises(BudgetStop):
|
||
PersistentBudget(legacy, BudgetGuard(cfg)).acquire("dialogue_main", tokens=1)
|
||
legacy.close()
|
||
# 接续实例(scope="hel919"):新授权范围生效,新计数落在独立 hel919:* 键
|
||
store = Store(tdb, init=False)
|
||
deadline = int(time.time()) + 3600
|
||
guard = PersistentBudget(store, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||
assert guard.total_requests_used() == 0 # 新 scope 从零起,不借旧计数也不清旧键
|
||
hold = guard.acquire("dialogue_main", tokens=500)
|
||
guard.settle(hold, actual_tokens=400)
|
||
assert guard.total_requests_used() == 1 and guard.total_tokens_used() == 400
|
||
t = {r["key"]: r["value"] for r in store.query("SELECT key,value FROM budget_total")}
|
||
assert t["total_requests"] == 1 and t["total_tokens"] == 1000 # 旧键未动
|
||
assert t["hel919:total_requests"] == 1 and t["hel919:total_tokens"] == 400
|
||
store.close()
|
||
# 进程"重启":重开库,新 scope 计数不重置;旧口径读者依旧被旧封账拒绝
|
||
store2 = Store(tdb, init=False)
|
||
guard2 = PersistentBudget(store2, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||
assert guard2.total_requests_used() == 1 and guard2.total_tokens_used() == 400
|
||
hold = guard2.acquire("life_event", tokens=100)
|
||
guard2.settle(hold, actual_tokens=100)
|
||
assert guard2.total_requests_used() == 2
|
||
with pytest.raises(BudgetStop):
|
||
PersistentBudget(store2, BudgetGuard(cfg)).acquire("dialogue_main", tokens=1)
|
||
store2.close()
|
||
# 新账封账(close 路径的库内效果):新 scope 拒绝一切;旧键依旧原样
|
||
store3 = Store(tdb, init=False)
|
||
guard3 = PersistentBudget(store3, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||
marker = guard3.seal()
|
||
with pytest.raises(BudgetStop):
|
||
guard3.acquire("dialogue_main", tokens=1)
|
||
t = {r["key"]: r["value"] for r in store3.query("SELECT key,value FROM budget_total")}
|
||
assert t["sealed"] == 1 and t["sealed_requests"] == 1 # 旧封账未被触碰
|
||
assert t["hel919:sealed"] == 1 and t["hel919:sealed_requests"] == 2
|
||
store3.close()
|
||
assert marker["requests"] == 2
|
||
|
||
|
||
def test_rollback_refuses_new_chat_and_memory_by_default(synth):
|
||
src, base = synth
|
||
_migrate(src, base)
|
||
target = base / "data" / "companion.db"
|
||
store = Store(target, init=False)
|
||
with store.conn:
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
||
"VALUES(9999,'user','new synthetic conversation','new','sent')")
|
||
# Same row count: updating a memory is also new experience to preserve.
|
||
store.execute("UPDATE mem_episodic SET gist='updated synthetic memory'")
|
||
store.close()
|
||
with pytest.raises(SystemExit, match="post_migration_data_changed"):
|
||
MIG.rollback(base)
|
||
conn = sqlite3.connect(target)
|
||
assert conn.execute("SELECT count(*) FROM chat_message").fetchone()[0] == 4
|
||
assert conn.execute("SELECT gist FROM mem_episodic").fetchone()[0] == "updated synthetic memory"
|
||
conn.close()
|
||
|
||
|
||
def test_force_rollback_archives_database_wal_and_vectors_and_is_restorable(synth, tmp_path):
|
||
src, base = synth
|
||
vec, _ = build_semantic_dirs(tmp_path / "sem")
|
||
_migrate(src, base, dirs=[(vec, "sem/vec")])
|
||
data = base / "data"
|
||
store = Store(data / "companion.db", init=False)
|
||
# Keep this connection open: the new chat may only be present in the WAL.
|
||
with store.conn:
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) "
|
||
"VALUES(9999,'user','WAL synthetic conversation','new','sent')")
|
||
(data / "sem/vec/v.bin").write_bytes(b"new-synthetic-vector")
|
||
with pytest.raises(SystemExit, match="post_migration_data_changed"):
|
||
MIG.rollback(base)
|
||
result = MIG.rollback(base, force=True)
|
||
store.close()
|
||
archive = Path(result["preserved_archive"])
|
||
assert json.loads((archive / "manifest.json").read_text())["complete"]
|
||
assert not (data / "companion.db").exists()
|
||
restored = tmp_path / "restored"
|
||
import shutil
|
||
shutil.copytree(archive / "data", restored)
|
||
conn = sqlite3.connect(restored / "companion.db")
|
||
assert conn.execute("SELECT text FROM chat_message WHERE turn_id='new'").fetchone()[0] == "WAL synthetic conversation"
|
||
conn.close()
|
||
assert (restored / "sem/vec/v.bin").read_bytes() == b"new-synthetic-vector"
|
||
assert json.loads((restored / "continuation.json").read_text())["scope"] == "hel919"
|
||
|
||
|
||
def test_force_rollback_archive_failure_leaves_all_data(synth, monkeypatch):
|
||
src, base = synth
|
||
_migrate(src, base)
|
||
target = base / "data/companion.db"
|
||
before = target.read_bytes()
|
||
def broken_backup(*args):
|
||
raise OSError("synthetic archive disk failure")
|
||
monkeypatch.setattr(MIG, "_consistency_copy", broken_backup)
|
||
with pytest.raises(SystemExit, match="rollback_archive_failed"):
|
||
MIG.rollback(base, force=True)
|
||
assert target.read_bytes() == before
|
||
assert (base / "data/continuation.json").exists()
|
||
|
||
|
||
def test_rollback_refuses_running_instance(synth):
|
||
src, base = synth
|
||
_migrate(src, base)
|
||
(base / "window-active").touch()
|
||
with pytest.raises(SystemExit, match="refused_live_instance"):
|
||
MIG.rollback(base, force=True)
|
||
|
||
|
||
@pytest.mark.parametrize("deadline", [None, "missing", float("nan"), float("inf"), -1, True])
|
||
def test_scoped_deadline_missing_or_invalid_refuses_without_counters(tmp_path, deadline):
|
||
from conftest import engineering_budget
|
||
|
||
store = Store(tmp_path / "invalid-window.db")
|
||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919", deadline=deadline)
|
||
with pytest.raises(BudgetStop, match="window_deadline_missing_or_invalid"):
|
||
guard.acquire("dialogue_main", tokens=1)
|
||
assert guard.total_requests_used() == 0 and guard.used == 0
|
||
store.close()
|
||
|
||
|
||
def test_deadline_is_pinned_and_allows_inflight_settlement(synth):
|
||
from conftest import engineering_budget
|
||
|
||
src, base = synth
|
||
_migrate(src, base)
|
||
store = Store(base / "data/companion.db", init=False)
|
||
now = [100]
|
||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||
deadline=200, clock=lambda: now[0])
|
||
hold = guard.acquire("dialogue_main", tokens=500)
|
||
now[0] = 200
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
guard.acquire("pattern_detect", tokens=200)
|
||
guard.settle(hold, actual_tokens=400) # already in flight may drain after deadline
|
||
assert guard.total_requests_used() == 1 and guard.total_tokens_used() == 400
|
||
with pytest.raises(BudgetStop, match="window_deadline_changed"):
|
||
PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919", deadline=300)
|
||
restarted = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||
deadline=200, clock=lambda: now[0])
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
restarted.acquire("life_event", tokens=100)
|
||
assert restarted.total_requests_used() == 1
|
||
store.close()
|
||
|
||
|
||
def test_live_api_and_background_refuse_at_deadline_before_provider(tmp_path, monkeypatch):
|
||
from fastapi.testclient import TestClient
|
||
from test_api import CREATE, events, turn
|
||
from test_hard_gates_hel882 import gated_app
|
||
|
||
from cybergril.life.model import structured
|
||
from cybergril.think.scenes import Scene
|
||
|
||
deadline = int(time.time()) + 300
|
||
monkeypatch.setenv("CYBERGRIL_BUDGET_SCOPE", "hel919")
|
||
monkeypatch.setenv("CYBERGRIL_WINDOW_DEADLINE", str(deadline))
|
||
app, provider = gated_app(tmp_path)
|
||
with TestClient(app) as client:
|
||
assert client.post("/api/companion", json=CREATE).status_code == 201
|
||
guard = app.state.life.router.guard
|
||
assert events(turn(client, "synthetic before deadline"))[-1]["t"] == "chat.final"
|
||
calls, count = len(provider.calls), guard.total_requests_used()
|
||
# The process remains alive. No watcher runs in this in-process test.
|
||
guard.clock = lambda: deadline
|
||
assert client.get("/api/companion").status_code == 200
|
||
assert events(turn(client, "synthetic after deadline"))[-1]["t"] == "chat.error"
|
||
for scene in (Scene.LIFE_EVENT, Scene.PATTERN_DETECT):
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
client.portal.call(structured, app.state.life.router, app.state.life.models,
|
||
scene, "synthetic offline check", {})
|
||
assert len(provider.calls) == calls
|
||
assert guard.total_requests_used() == count
|
||
|
||
|
||
def test_sdk_embedding_and_extraction_refuse_after_deadline(tmp_path, monkeypatch):
|
||
from conftest import engineering_budget
|
||
from test_semantic_recovery_hel882 import _make_ledger, config_for, install_fake
|
||
|
||
from cybergril.memory.semantic import Mem0Backend
|
||
|
||
install_fake(monkeypatch)
|
||
ledger = tmp_path / "semantic-ledger.db"
|
||
_make_ledger(ledger)
|
||
store = Store(tmp_path / "semantic-product.db")
|
||
now = [100]
|
||
guard = PersistentBudget(store, BudgetGuard(engineering_budget()), scope="hel919",
|
||
deadline=200, clock=lambda: now[0])
|
||
backend = Mem0Backend(config_for(tmp_path, ledger), request_guard=guard)
|
||
assert backend._memory.embedding_model.embed("synthetic before deadline") == [0.0]
|
||
used = backend.ledger.used()
|
||
now[0] = 200
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
backend._memory.embedding_model.embed("synthetic after deadline")
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
backend._memory.embedding_model.embed_batch(["synthetic after deadline"])
|
||
with pytest.raises(BudgetStop, match="window_expired"):
|
||
backend._memory.llm.generate_response(messages=[{"role": "user", "content": "synthetic"}])
|
||
assert backend.ledger.used() == used
|
||
assert guard.total_requests_used() == 0
|
||
store.close()
|
||
|
||
|
||
# ---------------------------------------------------------------- window guard
|
||
|
||
def _guard(base: Path):
|
||
return subprocess.run(
|
||
[sys.executable, str(PKG / "window_guard_hel919.py"), str(base)],
|
||
capture_output=True, text=True)
|
||
|
||
|
||
def _make_window(base: Path, *, approved=True, deadline_in=3600, instance="hel919"):
|
||
w = {"instance": instance, "approved": approved,
|
||
"started_at": 1, "deadline_at": 2,
|
||
"deadline_epoch": int(time.time()) + deadline_in,
|
||
"authorization_comment": "synthetic"}
|
||
(base / "window.json").write_text(json.dumps(w))
|
||
(base / "window-active").write_text("")
|
||
|
||
|
||
def test_window_guard_default_closed_and_expiry(synth):
|
||
_, base = synth
|
||
assert _guard(base).returncode != 0 # 无标记:默认关闭
|
||
_make_window(base)
|
||
assert _guard(base).returncode == 0 # 有效窗口放行
|
||
_make_window(base, deadline_in=-10)
|
||
assert _guard(base).returncode != 0 # 过期拒绝(重启不放行)
|
||
_make_window(base, approved=False)
|
||
assert _guard(base).returncode != 0 # 未批准拒绝
|
||
_make_window(base, instance="other")
|
||
assert _guard(base).returncode != 0 # 非本实例拒绝
|
||
(base / "window.json").write_text("{broken")
|
||
assert _guard(base).returncode != 0 # 损坏拒绝
|
||
|
||
|
||
# ---------------------------------------------------------------- CLI 通路
|
||
|
||
def test_cli_preflight_migrate_rollback(synth):
|
||
src, base = synth
|
||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||
"preflight", "--db", str(src)],
|
||
capture_output=True, text=True)
|
||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||
"migrate", "--db", str(src), "--base", str(base)],
|
||
capture_output=True, text=True)
|
||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||
"migrate", "--db", str(src), "--base", str(base)],
|
||
capture_output=True, text=True)
|
||
assert r.returncode == 0 and json.loads(r.stdout).get("idempotent_noop")
|
||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||
"rollback", "--base", str(base)],
|
||
capture_output=True, text=True)
|
||
assert r.returncode == 0 and json.loads(r.stdout)["ok"]
|
||
r = subprocess.run([sys.executable, str(PKG / "migrate_same_her.py"),
|
||
"rollback", "--base", str(base)],
|
||
capture_output=True, text=True)
|
||
assert r.returncode != 0 # 无可回退:拒绝
|