Files
CyberGril/tests/test_r4_api.py
T
zonggongandmultica-agent e291058754 HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 23:20:18 +08:00

181 lines
8.9 KiB
Python

"""R4 assembly through the real API: entry chain, activity thread, rituals, sync."""
import json
import pytest
from conftest import engineering_budget
from fastapi.testclient import TestClient
from test_api import CREATE, events, turn
from test_r2 import LIFE, R2LLM
from cybergril.api.app import create_app
from cybergril.contracts import LLMDelta
from cybergril.life.runtime import LifeConfig
from cybergril.think.router import build_router
from cybergril.think.scenes import Tier
class R4LLM(R2LLM):
"""R2 fake plus R4 scenes: life results can drive the activity thread."""
def __init__(self):
super().__init__()
self.life_results = []
self.reach_reply = "刚给窗台的多肉换了位置,想让你也看看那颗新芽。"
def queue_life(self, raw):
self.life_results.append(raw)
async def stream(self, messages, **kwargs):
prompt = messages[0].content
if "主动留言" in prompt:
yield LLMDelta(text=json.dumps({"text": self.reach_reply}, ensure_ascii=False))
yield LLMDelta(done=True, finish_reason="stop")
return
if "生成此刻真实运行中的一条世界内日常经历" in prompt:
raw = self.life_results.pop(0) if self.life_results else LIFE
yield LLMDelta(text=json.dumps(raw, ensure_ascii=False))
yield LLMDelta(done=True, finish_reason="stop")
return
async for delta in super().stream(messages, **kwargs):
yield delta
def r4_app(tmp_path, *, enabled=True, provider=None, semantic="stub", poll=3600):
provider = provider or R4LLM()
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 / "r4.db", router=router,
life_config=LifeConfig(enabled=enabled, poll_seconds=poll),
semantic_mode=semantic)
return app, provider
def test_health_capabilities_report_r4_wiring(tmp_path):
app, _ = r4_app(tmp_path)
with TestClient(app) as client:
health = client.get("/api/health").json()
assert health["version"] == "R4-assembly"
assert health["backend"]["mood"] is True
assert health["backend"]["reach_out"] is True
assert health["backend"]["semantic"] is True
assert health["backend"]["semantic_backend"] == "stub"
assert health["capabilities"]["proactive"] is True
assert health["capabilities"]["semantic_memory"] == "stub"
def test_entry_chain_create_chat_reopen_same_state(tmp_path):
app, provider = r4_app(tmp_path)
with TestClient(app) as client:
assert client.get("/api/companion").status_code == 404
created = client.post("/api/companion", json={**CREATE, "nickname": "小白", "boundary": "慢慢来"})
assert created.status_code == 201
identity = created.json()
assert identity["relation"] == "朋友"
assert identity["color"]["pillars"]
response = turn(client, "今天面试结束了,等结果呢")
assert [e["t"] for e in events(response)] == ["chat.delta", "chat.final"]
messages = client.get("/api/messages").json()["messages"]
assert [m["role"] for m in messages] == ["user", "companion"]
# reopen: fresh client over the same database shows the same state
epoch = client.get("/api/health").json()["epoch"]
with TestClient(create_app(db_path=tmp_path / "r4.db",
router=build_router(providers={t: R4LLM() for t in
(Tier.HIGH, Tier.STANDARD, Tier.LOW)}),
life_config=LifeConfig(enabled=True, poll_seconds=3600),
semantic_mode="stub")) as client2:
health = client2.get("/api/health").json()
assert health["companion_created"] is True
assert health["epoch"] == epoch + 1 # restart bumped the epoch
messages2 = client2.get("/api/messages").json()["messages"]
assert [m["role"] for m in messages2] == ["user", "companion"]
assert messages2[0]["text"] == messages[0]["text"]
def test_chat_turn_interrupts_activity_and_counts_ritual(tmp_path):
app, provider = r4_app(tmp_path)
with TestClient(app) as client:
client.post("/api/companion", json=CREATE)
store = app.state.store
with store.conn: # she is in the middle of something
store.execute(
"INSERT INTO life_activity(title,place,state,started_at) "
"VALUES('整理窗台','卧室','active',1)"
)
before = app.state.dyad.load().intimacy
turn(client, "在忙什么呢")
store = app.state.store
activity = store.query_one("SELECT * FROM life_activity")
assert activity["state"] == "interrupted" and activity["interrupted_at"]
assert app.state.dyad.load().intimacy == pytest.approx(before + 0.01)
async def test_life_slots_drive_activity_and_mood(tmp_path):
# poll is long: only the explicit manual generate() calls below run, no races
app, provider = r4_app(tmp_path, poll=3600)
with TestClient(app) as client:
client.post("/api/companion", json=CREATE)
life = app.state.life
store = app.state.store
# slot 1: she starts an activity; the real event moves her mood
provider.queue_life({**LIFE, "activity": {"action": "start", "title": "给旋律换结尾",
"place": "窗边沙发"}})
await life.generate("2026-10-26", 0)
started = store.query_one("SELECT * FROM life_activity")
assert started["state"] == "active" and started["title"] == "给旋律换结尾"
assert app.state.mood.state.v != app.state.mood.baseline.v
# slot 2: she continues it (same activity row, no second thread)
provider.queue_life({**LIFE, "activity": {"action": "continue"}})
await life.generate("2026-10-26", 1)
assert store.query_one("SELECT COUNT(*) n FROM life_activity")["n"] == 1
# chat interrupts; slot 3 resumes the same thread; slot 4 finishes it
turn(client, "打断你一下")
assert store.query_one("SELECT state FROM life_activity")["state"] == "interrupted"
provider.queue_life({**LIFE, "activity": {"action": "resume"}})
await life.generate("2026-10-26", 2)
row = store.query_one("SELECT * FROM life_activity")
assert row["state"] == "active" and row["resume_count"] == 1
provider.queue_life({**LIFE, "activity": {"action": "finish"}})
await life.generate("2026-10-26", 3)
assert store.query_one("SELECT state FROM life_activity")["state"] == "finished"
# every event-driven change is persisted for restart recovery
assert abs(store.last_state()["valence"] - app.state.mood.state.v) < 1e-6
async def test_semantic_recall_rides_into_chat_context(tmp_path):
app, provider = r4_app(tmp_path, semantic="stub", poll=3600)
with TestClient(app) as client:
client.post("/api/companion", json=CREATE)
store = app.state.store
# an older public turn about the music box, already extracted
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1,'user','音乐盒的发条要顺时针拧','t-old','sent')")
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(2,'companion','好,我记住发条的方向了','t-old','sent')")
semantic = app.state.semantic
semantic.enqueue_uncovered()
await semantic.tick()
assert store.query_one("SELECT state FROM sem_batch")["state"] == "done"
turn(client, "音乐盒怎么上发条来着")
# the gated recall block (or the FTS twin) reached the model context verbatim
sent = " ".join(m.content for m in provider.calls[-1])
assert "发条" in sent
def test_proactive_message_record_dto_flag(tmp_path):
app, provider = r4_app(tmp_path)
with TestClient(app) as client:
client.post("/api/companion", json=CREATE)
turn(client, "在忙什么呢") # an ordinary exchange first
store = app.state.store
with store.conn: # a persisted reach-out row exactly as the engine writes it
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status,proactive) "
"VALUES(1,'companion','想让你看看窗台的新芽。','reach-1','sent',1)")
messages = client.get("/api/messages").json()["messages"]
flagged = [m for m in messages if m.get("proactive") is True]
assert len(flagged) == 1 and flagged[0]["text"] == "想让你看看窗台的新芽。"
ordinary = [m for m in messages if not m.get("proactive")]
assert ordinary # normal replies never carry the flag