324 lines
14 KiB
Python
324 lines
14 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()
|
||
# 旧账冻结:live seal 移入 cont_prior_*,历史用量与总量保留
|
||
assert "sealed" not in total and "cont_prior_sealed" in total
|
||
assert total["cont_prior_sealed"] == 1
|
||
assert total["cont_prior_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"
|
||
# 旧库(源)封账依旧拒绝一切
|
||
sconn = Store(src, init=False)
|
||
old = PersistentBudget(sconn, BudgetGuard(BudgetConfig()))
|
||
with pytest.raises(BudgetStop):
|
||
old.acquire("dialogue_main", tokens=1)
|
||
sconn.close()
|
||
# 副本:新授权范围生效,可继续体验;新计数在旧账之上单独可核
|
||
store = Store(tdb, init=False)
|
||
cfg = BudgetConfig(daily_tokens=5000, daily_requests={
|
||
"dialogue": 5, "life": 5, "background": 5, "semantic": 5})
|
||
guard = PersistentBudget(store, BudgetGuard(cfg))
|
||
assert guard.total_requests_used() == 1 # 旧计数保留
|
||
hold = guard.acquire("dialogue_main", tokens=500)
|
||
guard.settle(hold, actual_tokens=400)
|
||
assert guard.total_requests_used() == 2
|
||
assert guard.total_tokens_used() == 1400
|
||
store.close()
|
||
# 进程"重启":重开库,计数与期限类状态不重置
|
||
store2 = Store(tdb, init=False)
|
||
guard2 = PersistentBudget(store2, BudgetGuard(cfg))
|
||
assert guard2.total_requests_used() == 2
|
||
assert guard2.total_tokens_used() == 1400
|
||
hold = guard2.acquire("life_event", tokens=100)
|
||
guard2.settle(hold, actual_tokens=100)
|
||
assert guard2.total_requests_used() == 3
|
||
store2.close()
|
||
# 新账封账后同样拒绝(close 路径的库内效果)
|
||
store3 = Store(tdb, init=False)
|
||
guard3 = PersistentBudget(store3, BudgetGuard(cfg))
|
||
guard3.seal()
|
||
with pytest.raises(BudgetStop):
|
||
guard3.acquire("dialogue_main", tokens=1)
|
||
store3.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 # 无可回退:拒绝
|