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:
@@ -246,7 +246,8 @@ def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
|
||||
legacy.close()
|
||||
# 接续实例(scope="hel919"):新授权范围生效,新计数落在独立 hel919:* 键
|
||||
store = Store(tdb, init=False)
|
||||
guard = PersistentBudget(store, BudgetGuard(cfg), scope="hel919")
|
||||
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)
|
||||
@@ -257,7 +258,7 @@ def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
|
||||
store.close()
|
||||
# 进程"重启":重开库,新 scope 计数不重置;旧口径读者依旧被旧封账拒绝
|
||||
store2 = Store(tdb, init=False)
|
||||
guard2 = PersistentBudget(store2, BudgetGuard(cfg), scope="hel919")
|
||||
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)
|
||||
@@ -267,7 +268,7 @@ def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
|
||||
store2.close()
|
||||
# 新账封账(close 路径的库内效果):新 scope 拒绝一切;旧键依旧原样
|
||||
store3 = Store(tdb, init=False)
|
||||
guard3 = PersistentBudget(store3, BudgetGuard(cfg), scope="hel919")
|
||||
guard3 = PersistentBudget(store3, BudgetGuard(cfg), scope="hel919", deadline=deadline)
|
||||
marker = guard3.seal()
|
||||
with pytest.raises(BudgetStop):
|
||||
guard3.acquire("dialogue_main", tokens=1)
|
||||
@@ -278,6 +279,169 @@ def test_new_usage_isolated_persistent_and_old_seal_still_enforced(synth):
|
||||
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):
|
||||
|
||||
Reference in New Issue
Block a user