"""Isolated R2 counterexamples: durable claims, no disclosure without receipts.""" import asyncio import json import time from datetime import datetime from zoneinfo import ZoneInfo import pytest from conftest import engineering_budget from fastapi.testclient import TestClient from test_api import CREATE, ControlledLLM, events, live_server, turn from cybergril.api.app import create_app from cybergril.contracts import LLMDelta from cybergril.life.model import PersistentBudget from cybergril.life.persona import Persona, fingerprint from cybergril.life.runtime import LifeConfig, LifeRuntime from cybergril.life.sharing import digest from cybergril.memory.store import Store from cybergril.think.router import build_router from cybergril.think.scenes import Tier SECRET = "私密蓝铜铃兰独特关键词" LIFE = {"kind": "thought", "content": "我试着给一段旋律换个结尾,停在了自己喜欢的那个音上。", "place": "房间", "salience": .7, "valence": .3} INTERP = "我会先在心里试探一件事的不同可能,表面平静时也可能正有两股劲拉扯。喜欢自己决定节奏,靠近别人时又会留意彼此是否舒服。有时先退一步不是冷淡,是想把感受理清再表达。我愿意保持这种有主见却能听进去的方式,也允许以后真实的相处带来新的理解,而不把任何一次反应当成永远的答案。" PERSONA = {"interpretation": INTERP, "habits": ["整理杯垫时先摆正边角", "喜欢给旋律哼一个不同的结尾", "想到新点子先在心里过一遍"]} class R2LLM(ControlledLLM): def __init__(self): super().__init__() self.judgment = {"narrated": []} self.life_result = LIFE self.persona_result = PERSONA self.reply = "我今天给一段旋律换了个结尾,停在了喜欢的那个音上。" self.background_calls = [] self.background_messages = [] self.memory_calls = [] self.block = False self.entered = None self.release = None async def stream(self, messages, **kwargs): if "只返回JSON,不要Markdown" not in messages[0].content: self.calls.append(messages) if self.mode == "error": raise OSError("private upstream fault") yield LLMDelta(text=self.reply) if self.mode == "slow": await asyncio.sleep(30) if self.mode == "truncated": return yield LLMDelta(done=True, finish_reason="length" if self.mode == "length" else "stop") return prompt = messages[0].content # R2 counters measure life/persona/sharing work. R3 has its own contract # and call ledger; keep the old assertions and injected factory intact. if "压缩这条已经成功保存的聊天" in prompt: self.memory_calls.append(messages) raw = json.loads(messages[1].content)["raw"] yield LLMDelta(text=json.dumps({"gist": raw[:120], "affect": {"v": 0.0, "a": 0.0, "d": 0.0}})) yield LLMDelta(done=True, finish_reason="stop") return self.background_calls.append(prompt) self.background_messages.append(messages) if self.entered: self.entered.set() if self.block: await self.release.wait() if self.mode == "background_error": raise OSError("private upstream fault " + SECRET) if "判定回复" in prompt: raw = self.judgment elif "自主形成有张力" in prompt: raw = self.persona_result elif "提炼后天成长" in prompt: raw = {"text": "这次相处让我更愿意慢一点把自己的想法说清楚。"} else: raw = self.life_result yield LLMDelta(text=json.dumps(raw, ensure_ascii=False)) yield LLMDelta(done=True, finish_reason="stop") def app_for(tmp_path, *, enabled=True, provider=None, poll=3600): provider = provider or R2LLM() router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)}, budget=engineering_budget()) app = create_app(db_path=tmp_path / "r2.db", router=router, life_config=LifeConfig(enabled=enabled, poll_seconds=poll)) return app, provider def add_life(store, content=SECRET, told=0): with store.conn: row = store.execute("INSERT INTO life_event(ts,kind,content,place,valence,salience,source,told,day_key,tz) " "VALUES(?,'thought',?,'房间',0,.7,'generated',?,'2026-10-24','Asia/Shanghai')", (int(time.time() * 1000), content, told)) return row.lastrowid def final_and_receipt(client): final = events(turn(client))[-1] assert final["t"] == "chat.final" receipt = final["receipt"] assert receipt["text_hash"] == digest(final["utterance"]["text"]) return final, receipt def ack(client, receipt): return client.post("/api/chat/received", json={k: receipt[k] for k in ("message_id", "turn_id", "epoch", "token", "text_hash")}) def judge(client, app, message_id): client.portal.call(app.state.sharing.judge, message_id) def selected(provider, *ids): provider.judgment = {"narrated": [{"event_id": i, "evidence": provider.reply} for i in ids]} def test_additive_migration_preserves_populated_old_database(tmp_path): app, _ = app_for(tmp_path, enabled=False) with TestClient(app) as c: c.post("/api/companion", json=CREATE) turn(c) s = app.state.store old = {table: [tuple(r) for r in s.query(f"SELECT * FROM {table}")] for table in ("bazi_core", "companion", "chat_message")} add_life(s) # Reproduce a real R1 life table, without removing any old columns or rows. with Store(tmp_path / "r2.db") as s: before = [tuple(r) for r in s.query("SELECT * FROM life_event")] s.init_schema() s.init_schema() assert [tuple(r) for r in s.query("SELECT * FROM life_event")] == before for table, rows in old.items(): assert [tuple(r) for r in s.query(f"SELECT * FROM {table}")] == rows def test_actual_r1_schema_upgrade_and_repeat(tmp_path): import sqlite3 with sqlite3.connect(tmp_path / "old.db") as conn: conn.execute("CREATE TABLE life_event(id INTEGER PRIMARY KEY, ts INTEGER, kind TEXT, content TEXT, place TEXT, valence REAL, salience REAL, source TEXT, told INTEGER, day_key TEXT)") conn.execute("INSERT INTO life_event VALUES(9,10,'thought',?,'房间',0,.8,'generated',0,'2026-10-01')", (SECRET,)) with Store(tmp_path / "old.db") as s: assert s.query_one("SELECT content FROM life_event WHERE id=9")[0] == SECRET s.init_schema() assert s.query_one("SELECT tz,run_id FROM life_event WHERE id=9")[0] is None def test_new_persona_and_relation_do_not_mutate_any_layer(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: assert c.post("/api/companion", json=CREATE).status_code == 201 view = c.get("/api/persona").json() assert view["state"] == "ready" assert view["interpretation"]["text"] == INTERP assert len(view["seeds"]) == 3 assert view["interpretation"]["provenance"] == "created-R2" before = fingerprint(app.state.store) layers = c.get("/api/persona").json() assert c.patch("/api/relation", json={"relation": "恋人"}).status_code == 200 assert c.get("/api/persona").json() == layers assert fingerprint(app.state.store) == before turn(c, "保留底色空间" + "长" * 3000) prompt = p.calls[-1][0].content assert INTERP in prompt and '"pillars"' in prompt assert "六段" not in prompt assert c.post("/api/companion", json=CREATE).status_code == 409 @pytest.mark.parametrize("hour,life_count", [(11, 1), (12, 0)]) def test_old_profile_never_auto_backfilled_and_explicit_backfill_is_honest(tmp_path, monkeypatch, hour, life_count): app, _ = app_for(tmp_path, enabled=False) with TestClient(app) as c: c.post("/api/companion", json=CREATE) turn(c) s = app.state.store birth = fingerprint(s) raw = s.query_one("SELECT identity_json FROM companion")[0] chats = [tuple(r) for r in s.query("SELECT * FROM chat_message")] # Freeze only the runtime clock before lifespan starts, leaving the real loop enabled. stamp = datetime(2026, 10, 24, hour, 11, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp() monkeypatch.setattr("cybergril.api.app.LifeRuntime", lambda *args: LifeRuntime(*args, clock=lambda: stamp)) app2, p = app_for(tmp_path) with TestClient(app2) as c: c.portal.call(app2.state.life.tick) # settle the current slot; repeated ticks are idempotent assert c.get("/api/persona").json()["state"] == "not_initialized" assert c.post("/api/persona/retry").status_code == 409 assert not app2.state.store.query("SELECT * FROM persona_interp") assert not app2.state.store.query("SELECT * FROM persona_job") assert len(app2.state.store.query("SELECT * FROM life_event")) == life_count assert len(p.background_calls) == life_count assert all("本人生活自述" in prompt for prompt in p.background_calls) persona = app2.state.persona c.portal.call(lambda: persona.ensure(backfill=True)) view = c.get("/api/persona").json() assert view["interpretation"]["provenance"] == "backfilled-R2" assert view["interpretation"]["created_at"] >= app2.state.store.query_one("SELECT created_at FROM bazi_core")[0] assert fingerprint(app2.state.store) == birth assert app2.state.store.query_one("SELECT identity_json FROM companion")[0] == raw assert [tuple(r) for r in app2.state.store.query("SELECT * FROM chat_message")] == chats def test_generation_requests_carry_voice_and_current_world_without_rewriting_output(tmp_path): # This verifies the actual provider boundary, not model content quality. app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) runtime = setup_runtime(app, fixed_clock()) c.portal.call(runtime.tick) persona_request = next(m for m in p.background_messages if "自主形成有张力" in m[0].content) life_request = next(m for m in p.background_messages if "本人生活自述" in m[0].content) for messages in (persona_request, life_request): assert [m.role for m in messages] == ["system", "user"] assert "第一人称“我”" in messages[0].content assert "禁止用“它”指代她" in messages[0].content assert '"pillars"' in persona_request[1].content for constraint in ("高层卧室", "窗边", "慵懒沙发", "女性化装饰", "办公室", "茶水间", "禁止编造无来源", "不默认每天读书", "雨夜等不能当作当前真实天气事实"): assert constraint in life_request[0].content assert INTERP in life_request[1].content assert c.get("/api/persona").json()["interpretation"]["text"] == PERSONA["interpretation"] row = app.state.store.query_one("SELECT content,place,told FROM life_event ORDER BY id DESC LIMIT 1") assert tuple(row) == (LIFE["content"], LIFE["place"], 0) def test_failed_persona_retry_has_no_template_or_half_seeds(tmp_path): p = R2LLM() p.persona_result = {"interpretation": "错误短标签", "habits": ["伪造"]} app, _ = app_for(tmp_path, provider=p) with TestClient(app) as c: c.post("/api/companion", json=CREATE) assert c.get("/api/persona").json()["state"] == "failed" assert not app.state.store.query("SELECT * FROM persona_seed") p.persona_result = PERSONA assert c.post("/api/persona/retry").json()["state"] == "ready" count = len(p.background_calls) c.post("/api/persona/retry") assert len(p.background_calls) == count @pytest.mark.parametrize("ack_first", [True, False]) def test_disclosure_requires_receipt_and_judgment_in_either_order(tmp_path, ack_first): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) one, two = add_life(app.state.store, LIFE["content"]), add_life(app.state.store, LIFE["content"]) selected(p, one, two) _, r = final_and_receipt(c) assert c.get("/api/life").json()["events"] == [] if ack_first: assert ack(c, r).status_code == 200 else: judge(c, app, r["message_id"]) assert not app.state.store.query("SELECT * FROM telling_log") if ack_first: judge(c, app, r["message_id"]) else: assert ack(c, r).status_code == 200 assert len(c.get("/api/life").json()["events"]) == 2 for _ in range(3): ack(c, r) judge(c, app, r["message_id"]) assert len(app.state.store.query("SELECT * FROM telling_log")) == 2 assert len(app.state.store.query("SELECT * FROM sharing_attempt")) == 1 assert c.get("/api/messages").json()["messages"][-1]["lifeIds"] == [one, two] @pytest.mark.parametrize("field,bad", [("token", "x" * 43), ("epoch", 987), ("message_id", 987), ("turn_id", "a" * 36), ("text_hash", "0" * 64)]) def test_forged_receipts_never_publish(tmp_path, field, bad): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) selected(p, eid) _, r = final_and_receipt(c) judge(c, app, r["message_id"]) assert ack(c, dict(r, **{field: bad})).status_code == 404 assert c.get("/api/life").json()["events"] == [] history = json.dumps(c.get("/api/messages").json(), ensure_ascii=False) assert r["token"] not in history and SECRET not in history @pytest.mark.parametrize("bad", ["unknown", "duplicate", "bad_evidence", "word_only", "error"]) def test_invalid_or_non_narrative_judgments_fail_closed(tmp_path, bad): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) _, r = final_and_receipt(c) selected(p, eid) if bad == "unknown": selected(p, eid, 99999) elif bad == "duplicate": selected(p, eid, eid) elif bad == "bad_evidence": p.judgment["narrated"][0]["evidence"] = "这段原话根本不存在于完整回复" elif bad == "word_only": p.judgment = {"narrated": []} else: p.mode = "background_error" ack(c, r) judge(c, app, r["message_id"]) assert c.get("/api/life").json()["events"] == [] assert not app.state.store.query("SELECT * FROM telling_log") @pytest.mark.parametrize("mode", ["error", "truncated", "length"]) def test_failed_and_incomplete_turn_has_no_receipt_or_disclosure(tmp_path, mode): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) add_life(app.state.store) p.mode = mode assert events(turn(c))[-1]["t"] == "chat.error" assert not app.state.store.query("SELECT * FROM sharing_attempt") assert not app.state.store.query("SELECT * FROM telling_log") @pytest.mark.parametrize("judged", [True, False]) def test_restart_and_replay_preserve_legal_receipt_without_reissuing_token(tmp_path, judged): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) selected(p, eid) _, receipt = final_and_receipt(c) if judged: judge(c, app, receipt["message_id"]) app2, p2 = app_for(tmp_path) selected(p2, eid) with TestClient(app2) as c: assert c.get("/api/life").json()["events"] == [] assert ack(c, receipt).status_code == 200 judge(c, app2, receipt["message_id"]) assert len(c.get("/api/life").json()["events"]) == 1 replay = events(turn(c, turn_id=receipt["turn_id"]))[-1] assert replay["receipt"] == receipt assert replay["epoch"] > receipt["epoch"] assert not p2.calls assert len(app2.state.store.query("SELECT * FROM telling_log")) == 1 def test_expired_and_interrupted_judgment_never_publish(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) selected(p, eid) _, r = final_and_receipt(c) s = app.state.store with s.conn: s.execute("UPDATE sharing_attempt SET state='evaluating',lease_until=0") app.state.sharing.recover() assert ack(c, r).status_code == 200 judge(c, app, r["message_id"]) assert not s.query("SELECT * FROM telling_log") with s.conn: s.execute("UPDATE sharing_attempt SET expires_at=0") assert ack(c, r).status_code == 404 @pytest.mark.parametrize("bad_id", ["1", "2", "999999", "fake", "-1", "0", "999999999999999999999999999999", "1.0"]) def test_hidden_unknown_and_forged_ids_have_identical_404(tmp_path, bad_id): app, _ = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) add_life(app.state.store) add_life(app.state.store, told=2) r = c.get("/api/life/" + bad_id) assert r.status_code == 404 assert r.json() == {"detail": "这一条现在打不开。"} for endpoint in ("/api/life", "/api/persona", "/api/health", "/api/messages"): assert SECRET not in json.dumps(c.get(endpoint).json(), ensure_ascii=False) def test_pagination_is_over_allowed_set_and_growth_is_guarded(tmp_path): app, _ = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) s = app.state.store public = [add_life(s, "已公开" + str(i), told=1) for i in range(3)] hidden = add_life(s) with s.conn: s.execute("INSERT INTO growth_event(ts,source,ref_id,text,model,created_at) VALUES(1,'life',?,?, 'test',1)", (hidden, SECRET)) s.execute("INSERT INTO growth_event(ts,source,ref_id,text,model,created_at) VALUES(1,'unknown',?,?, 'test',1)", (hidden, SECRET)) first = c.get("/api/life?limit=2").json() assert [e["id"] for e in first["events"]] == list(reversed(public[1:])) second = c.get("/api/life", params={"limit": 2, "before": first["next_before"]}).json() assert [e["id"] for e in second["events"]] == public[:1] assert second["next_before"] is None assert c.get("/api/persona").json()["growth"] == [] for query in ("limit=0", "limit=101", "before=0", "before=999999999999999999999999"): assert c.get("/api/life?" + query).status_code == 422 def fixed_clock(): return [datetime(2026, 10, 24, 7, 10, tzinfo=ZoneInfo("Asia/Shanghai")).timestamp()] def setup_runtime(app, clock, config=None): app.state.sharing.clock = lambda: clock[0] app.state.persona.clock = lambda: clock[0] return LifeRuntime(app.state.store, app.state.life.router, app.state.life.models, config or LifeConfig(enabled=True), app.state.sharing, app.state.persona, clock=lambda: clock[0]) def test_schedule_concurrency_restart_downtime_and_timezone(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) clock = fixed_clock() runtime = setup_runtime(app, clock) async def concurrent_ticks(): await asyncio.gather(runtime.tick(), runtime.tick(), runtime.tick()) c.portal.call(concurrent_ticks) assert len(app.state.store.query("SELECT * FROM life_event")) == 1 c.portal.call(setup_runtime(app, clock).tick) assert len(app.state.store.query("SELECT * FROM life_event")) == 1 clock[0] += 2 * 86400 c.portal.call(runtime.tick) assert len(app.state.store.query("SELECT * FROM life_event")) == 2 assert app.state.store.query_one("SELECT count(*) n FROM life_run WHERE status='skipped'")["n"] == 7 first = dict(app.state.store.query_one("SELECT * FROM life_event ORDER BY id LIMIT 1")) # Same local date and slot in a different IANA zone must not collide or rewrite history. clock[0] = datetime(2026, 10, 24, 7, 10, tzinfo=ZoneInfo("UTC")).timestamp() utc = setup_runtime(app, clock, LifeConfig(enabled=True, timezone="UTC")) c.portal.call(utc.tick) assert dict(app.state.store.query_one("SELECT * FROM life_event ORDER BY id LIMIT 1")) == first assert len(app.state.store.query("SELECT * FROM life_event")) == 3 assert all(r["told"] == 0 for r in app.state.store.query("SELECT told FROM life_event")) for row in app.state.store.query("SELECT * FROM life_event"): assert row["day_key"] == datetime.fromtimestamp(row["ts"] / 1000, ZoneInfo(row["tz"])).date().isoformat() assert len(p.background_calls) == 4 # persona plus exactly three event generations def test_abandoned_claim_is_not_stolen_or_regenerated(tmp_path): app, _ = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) clock = fixed_clock() runtime = setup_runtime(app, clock) with app.state.store.conn: app.state.store.execute("INSERT INTO life_run(tz,day_key,slot,status,owner,started_at,lease_until) VALUES('Asia/Shanghai','2026-10-24',0,'pending','dead',0,?)", (int(clock[0] * 1000) + 5000,)) c.portal.call(runtime.tick) assert not app.state.store.query("SELECT * FROM life_event") clock[0] += 6 c.portal.call(runtime.tick) run = app.state.store.query_one("SELECT * FROM life_run") assert run["status"] == "skipped" and run["reason"] == "lease_expired" assert not app.state.store.query("SELECT * FROM life_event") def test_failures_pause_durably_without_template(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) p.mode = "background_error" clock = fixed_clock() runtime = setup_runtime(app, clock) for _ in range(3): c.portal.call(runtime.tick) clock[0] += 4 * 3600 c.portal.call(setup_runtime(app, clock).tick) assert not app.state.store.query("SELECT * FROM life_event") assert app.state.store.query_one("SELECT value FROM life_control WHERE key='paused'") assert len(app.state.store.query("SELECT * FROM life_run WHERE status='error'")) == 3 assert SECRET not in json.dumps(runtime.status(), ensure_ascii=False) def test_budget_warning_stop_and_restart_cannot_reset_usage(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) guard = app.state.life.router.guard guard.record(int(guard.limit * .71), "test") assert app.state.life.status()["budget_warning"] guard.record(int(guard.limit * .25), "test") before = len(p.background_calls) clock = fixed_clock() runtime = setup_runtime(app, clock) c.portal.call(runtime.tick) assert runtime.status()["state"] == "budget_stopped" assert len(p.background_calls) == before assert not app.state.store.query("SELECT * FROM life_event") app2, p2 = app_for(tmp_path) with TestClient(app2) as c: assert app2.state.life.router.guard.is_tight() assert not p2.background_calls def test_growth_only_from_verified_sources_and_no_private_candidates(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) hidden = add_life(app.state.store) _, r = final_and_receipt(c) ack(c, r) judge(c, app, r["message_id"]) count = len(p.background_calls) c.portal.call(app.state.persona.grow, "life", hidden) c.portal.call(app.state.persona.grow, "chat", r["message_id"]) assert len(p.background_calls) == count assert c.get("/api/persona").json()["growth"] == [] public = add_life(app.state.store, content=LIFE["content"], told=1) c.portal.call(app.state.persona.grow, "life", public) assert len(c.get("/api/persona").json()["growth"]) == 1 c.portal.call(app.state.persona.grow, "life", public) assert len(c.get("/api/persona").json()["growth"]) == 1 @pytest.mark.asyncio async def test_persona_concurrent_claim_and_life_cancel_have_no_orphans(tmp_path): app, p = app_for(tmp_path, enabled=False) with TestClient(app) as c: c.post("/api/companion", json=CREATE) store = app.state.store router, models = app.state.life.router, app.state.life.models router.guard = PersistentBudget(store, router.guard) persona = Persona(store, router, models, enabled=True) p.block, p.entered, p.release = True, asyncio.Event(), asyncio.Event() first = asyncio.create_task(persona.ensure()) await p.entered.wait() assert not await persona.ensure() p.release.set() assert await first assert len(store.query("SELECT * FROM persona_interp")) == 1 assert len(store.query("SELECT * FROM persona_seed")) == 3 clock = fixed_clock() runtime = setup_runtime(app, clock) p.entered, p.release = asyncio.Event(), asyncio.Event() task = asyncio.create_task(runtime.tick()) await p.entered.wait() task.cancel() with pytest.raises(asyncio.CancelledError): await task assert store.query_one("SELECT status FROM life_run")[0] == "skipped" assert not store.query("SELECT * FROM life_event") @pytest.mark.asyncio async def test_real_loopback_disconnect_never_creates_a_receipt(tmp_path): import httpx app, p = app_for(tmp_path) with live_server(app) as url: async with httpx.AsyncClient(base_url=url) as c: await c.post("/api/companion", json=CREATE) add_life(app.state.store) epoch = (await c.get("/api/health")).json()["epoch"] p.mode = "slow" from uuid import uuid4 async with c.stream("POST", "/api/chat", json={"text": "部分流断线", "turn_id": str(uuid4()), "epoch": epoch}) as r: async for line in r.aiter_lines(): if line.startswith("data:"): break # New turn waits for cancellation cleanup on the server before proceeding. p.mode = "normal" reply = await c.post("/api/chat", json={"text": "下一轮", "turn_id": str(uuid4()), "epoch": epoch}) assert events(reply)[-1]["t"] == "chat.final" assert len(app.state.store.query("SELECT * FROM sharing_attempt")) == 1 assert not app.state.store.query("SELECT * FROM telling_log") @pytest.mark.parametrize("role,status", [("companion", "cancelled"), ("companion", "failed"), ("user", "failed"), ("user", "pending")]) def test_receipt_is_bound_to_an_entire_successful_turn(tmp_path, role, status): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) selected(p, eid) _, r = final_and_receipt(c) judge(c, app, r["message_id"]) with app.state.store.conn: app.state.store.execute("UPDATE chat_message SET status=? WHERE turn_id=? AND role=?", (status, r["turn_id"], role)) assert ack(c, r).status_code == 404 assert not app.state.store.query("SELECT * FROM telling_log") assert not app.state.store.query("SELECT * FROM life_event WHERE told=1") def test_told_and_log_are_atomic_under_write_failure(tmp_path, monkeypatch): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) eid = add_life(app.state.store) selected(p, eid) _, r = final_and_receipt(c) judge(c, app, r["message_id"]) original = app.state.store.execute def failing(sql, params=()): if "UPDATE life_event SET told=1" in sql: raise OSError("injected disk failure") return original(sql, params) monkeypatch.setattr(app.state.store, "execute", failing) with pytest.raises(OSError): ack(c, r) assert not app.state.store.query("SELECT * FROM telling_log") assert app.state.store.query_one("SELECT told FROM life_event")[0] == 0 assert app.state.store.query_one("SELECT ack_at FROM sharing_attempt")[0] is None monkeypatch.setattr(app.state.store, "execute", original) assert ack(c, r).status_code == 200 assert len(app.state.store.query("SELECT * FROM telling_log")) == 1 def test_persona_layers_roll_back_together_on_seed_write_failure(tmp_path, monkeypatch): app, _ = app_for(tmp_path, enabled=False) with TestClient(app) as c: c.post("/api/companion", json=CREATE) persona = Persona(app.state.store, app.state.life.router, app.state.life.models, enabled=True) before = fingerprint(app.state.store) original = app.state.store.execute def failing(sql, params=()): if "INSERT INTO persona_seed" in sql: raise OSError("injected disk failure") return original(sql, params) monkeypatch.setattr(app.state.store, "execute", failing) assert not c.portal.call(lambda: persona.ensure(backfill=True)) assert not app.state.store.query("SELECT * FROM persona_interp") assert not app.state.store.query("SELECT * FROM persona_seed") monkeypatch.setattr(app.state.store, "execute", original) assert c.portal.call(lambda: persona.ensure(backfill=True)) assert fingerprint(app.state.store) == before def test_lifespan_cancels_owned_generation_and_joins_task(tmp_path): app, p = app_for(tmp_path, poll=.01) with TestClient(app) as c: c.post("/api/companion", json=CREATE) runtime = app.state.life clock = fixed_clock() async def freeze_and_block_next(): # HEL-879 determinism fix: the clock freeze and the block must be # ONE atomic step on this loop. They used to be two portal calls, # and a 10ms life tick could slip between them — a frozen-clock # tick then claimed the day UNBLOCKED, the run was marked done, # and wait_started timed out forever (full-suite flake; single-run # passed). Also wait for any in-flight real-day generation first: # a tick that already claimed the real day may resume past this # point, and its later provider calls must not trip the block. loop = asyncio.get_running_loop() deadline = loop.time() + 5 while app.state.store.query_one( "SELECT 1 FROM life_run WHERE status='pending'"): if loop.time() > deadline: raise TimeoutError("real-day run never settled") await asyncio.sleep(0.005) runtime.clock = lambda: clock[0] p.block, p.entered, p.release = True, asyncio.Event(), asyncio.Event() c.portal.call(freeze_and_block_next) async def wait_started(): await asyncio.wait_for(p.entered.wait(), 1) c.portal.call(wait_started) assert app.state.store.query_one("SELECT status FROM life_run WHERE day_key='2026-10-24'")[0] == "pending" assert runtime.state == "stopped" with Store(tmp_path / "r2.db") as s: assert not s.query("SELECT * FROM life_run WHERE status='pending'") assert not s.query("SELECT * FROM life_event") def test_separate_sqlite_connections_cannot_claim_same_slot(tmp_path): import concurrent.futures import threading app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) barrier = threading.Barrier(2) clock = fixed_clock() def attempt(): with Store(tmp_path / "r2.db") as s: router, models = app.state.life.router, app.state.life.models runtime = LifeRuntime(s, router, models, LifeConfig(enabled=True), app.state.sharing, app.state.persona, clock=lambda: clock[0]) barrier.wait(timeout=3) asyncio.run(runtime.generate("2026-10-24", 0)) with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: jobs = [pool.submit(attempt) for _ in range(2)] for job in jobs: job.result(timeout=5) assert len(app.state.store.query("SELECT * FROM life_event")) == 1 assert len(app.state.store.query("SELECT * FROM life_run WHERE status='done'")) == 1 assert len(p.background_calls) == 2 def test_server_loop_advances_with_no_browser_requests(tmp_path): app, _ = app_for(tmp_path, poll=.01) with TestClient(app) as c: c.post("/api/companion", json=CREATE) clock = fixed_clock() app.state.life.clock = lambda: clock[0] async def wait_count(n): async with asyncio.timeout(1): while len(app.state.store.query("SELECT * FROM life_event")) != n: await asyncio.sleep(.005) c.portal.call(wait_count, 1) clock[0] += 4 * 3600 c.portal.call(wait_count, 2) clock[0] += 4 * 3600 c.portal.call(wait_count, 3) # These are server iterations in compressed time, no fetch/poll of an API. assert len(app.state.store.query("SELECT * FROM life_run WHERE status='done'")) == 3 def test_client_cannot_choose_public_events_and_message_refs_are_trimmed(tmp_path): app, p = app_for(tmp_path) with TestClient(app) as c: c.post("/api/companion", json=CREATE) hidden = add_life(app.state.store) _, receipt = final_and_receipt(c) payload = {k: receipt[k] for k in ("message_id", "turn_id", "epoch", "token", "text_hash")} assert c.post("/api/chat/received", json=dict(payload, event_ids=[hidden])).status_code == 422 # Even an imported stale reference must go through the server's public guard. with app.state.store.conn: app.state.store.execute("INSERT INTO telling_log VALUES(?,?,1)", (hidden, receipt["message_id"])) response = c.get("/api/messages").json() assert response["messages"][-1]["lifeIds"] == [] assert SECRET not in json.dumps(response, ensure_ascii=False) assert not app.state.store.query("SELECT id FROM life_event WHERE told=1")