Files
CyberGril/tests/test_voice_review_hel902.py
T
施工员2号andmultica-agent 07dda2bfa2 HEL-904: backend rework — recoverable register-failure mapping, worker-state corruption docstring, call-window voice pin closes capture/worker race
- register(): local metadata write failure -> LocalRecordFailed -> 503 Chinese
  message with the cg- id (shared registration NOT rolled back, refresh list to
  recover, never re-register); register_asr journaled BEFORE local persist so
  failed registrations still count in the resource ledger
- write_worker_voice(): docstring now states the whole-file rewrite on
  unreadable/corrupt state (other keys preserved only when parseable)
- capture->worker race closed with a session-immutable-snapshot equivalent:
  _capture_voice holds the captured voice (no await gap); apply_selection
  defers its worker-state write while any call is live; open_session releases
  the hold on failure/cancel; VoiceSessionService.on_session_settled releases
  on explicit end, end-into-debt and TTL expiry; response voice == the voice
  the worker actually reads for that call, mid-call changes affect the next
  call only; overlapping-call residual documented honestly
- tests: hel902 fault-injection case 1 rewritten for the new contract
  (recovery + restart + 409 gate kept), 4 new deterministic Event-gated race
  tests (worker read delayed past dispatch, concurrent apply, failure/cancel
  cleanup, next-call voice), zero sleep-based assertions
- docs: contract §2.2/§2.5/§3 updated; r5 followup package tightened (head
  milestones d167ba9/b09a907/pending-review, register ASR vs call ASR split,
  call-ASR counting means + honest pending blocker, single-timebase frame
  silence measurement, D1 female_soft reference audio pinned by sha256,
  recycling checklist, shared-TTS snapshot/restore, git-revert is not
  recycling, caps count failures/retries/outbound-no-response)
- evidence: pytest 380/380 (376 baseline + 4), verify chain 12/12, ruff clean,
  requirement checks 4/4 (origin/main and b09a907, with/without handoff)

Co-authored-by: multica-agent <github@multica.ai>
2026-10-28 01:09:19 +08:00

207 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""HEL-902 统一审核:后台重点故障注入补核(总工独立新增).
针对总管列出的统一审核重点,用可控假服务注入故障,零真实调用:
1. 8090 已登记、CyberGril 本地元数据落盘失败 —— 是否留下无法恢复或重复注册的半状态。
(HEL-904 返修:503 中文映射 + 编号可恢复 + 重启断言 + 409 守门保持。)
2. 登记上传成功后面板响应断连(结果已生效、响应丢失)+ 用户重试 —— 共享注册表里出现什么。
3. 通话开启时 worker 音色状态写不进 —— 诚实拒绝且不开房。
4. worker 状态文件可读时其他键保留;文件损坏(读不出 JSON)时其他键是否被丢弃。
(HEL-904:该实况已补入 docstring 与合同,行为不变、如实记录。)
5. 试听流水写不进 —— 「应用前有可听试听」凭据缺失时应用是否守门(fail-closed)。
6. 选择状态落盘失败 —— 整体回滚,worker 文件不被写。
时间与真实性边界:worker 实际在会话入口读音色文件、与真实 worker 的时序一致性
属真机窗口验证范围(见 docs/rework/hel902/);本文件锁 API 侧可离线证明的事实,
capture→worker 实读竞态的确定性时序用例见 tests/test_voice_rework_hel904.py。
"""
import json
import httpx
import pytest
from test_voice_custom import ( # noqa: F401 (复用作者既有桩;同目录根式导入)
BUILTIN,
CREATE,
FakeVoiceStack,
build_app,
make_wav,
)
from cybergril.voice.custom import CustomVoiceService
def _register(client, **params):
return client.post("/api/voice/voices", params={"prompt_text": "参考文字", **params},
content=make_wav(3), headers={"Content-Type": "audio/wav"})
@pytest.fixture
def stack(tmp_path):
return FakeVoiceStack(tmp_path)
@pytest.fixture
def instance(tmp_path, stack):
"""同作者桩,但 raise_server_exceptions=False:故障路径要按产品语义看 500."""
from fastapi.testclient import TestClient
app, custom, worker_state = build_app(tmp_path, stack)
with TestClient(app, raise_server_exceptions=False) as client:
client.post("/api/companion", json=CREATE)
yield client, stack, custom, worker_state, tmp_path
def _swap_panel(custom, stack, handler):
transport = httpx.MockTransport(handler)
stack.transport = transport
custom.http = httpx.AsyncClient(transport=transport, verify=False)
def test_panel_ok_local_metadata_write_fails(instance):
"""8090 登记成功、本地元数据写不进(HEL-904 已修):不裸 500,中文提示
说清编号、共享登记未回滚、刷新可恢复;不逼重复注册;重启后按编号可用;
试听凭据 409 守门不放松."""
client, stack, custom, worker_state, tmp_path = instance
blocked = tmp_path / "blocked-custom.json"
blocked.mkdir()
custom.registry_path = blocked
response = _register(client)
assert response.status_code == 503 # OSError 映射为可恢复的 503 中文文案
detail = response.json()["detail"]
voice_id = stack.uploads[0]["name"]
assert len(stack.uploads) == 1 # 用户没被逼重复登记
assert voice_id in detail # 编号直接给到用户手里
assert "不会" in detail and "回滚" in detail # 不误称共享登记也回滚了
assert "刷新" in detail and "不需要重新登记" in detail # 恢复路径说清楚
# 面板已登记;进程内记录仍在:本进程里看得到、可试听可应用,不是死条目
listing = client.get("/api/voice/voices").json()
assert voice_id in {v["id"] for v in listing["voices"]}
assert client.post("/api/voice/preview", json={"voice": voice_id}).status_code == 200
assert client.post("/api/voice/selection", json={"voice": voice_id}).status_code == 200
assert client.get("/api/voice/selection").json()["voice"] == voice_id
# 「重启」后元数据确实丢失(无 label/时间),但共享注册表仍在,声音仍可列出使用
revived = CustomVoiceService(
config=custom.config, http=custom.http,
selection_path=tmp_path / "sel.json", registry_path=tmp_path / "custom2.json",
journal_path=tmp_path / "usage.jsonl")
assert voice_id in set(stack.ids)
assert voice_id not in revived.custom_voices() # 元数据丢了,声音没丢
assert not revived.call_voice_held()
# 重启恢复后按编号继续用:列表 label=编号;新音色未试听仍 409 守门
app2, custom2, worker2 = build_app(tmp_path, stack)
from fastapi.testclient import TestClient
with TestClient(app2) as client2:
client2.post("/api/companion", json=CREATE)
listing2_raw = client2.get("/api/voice/voices").json()
by_id = {v["id"]: v for v in listing2_raw["voices"]}
assert by_id[voice_id]["label"] == voice_id # 无元数据:以编号为名
assert client2.post("/api/voice/preview", json={"voice": voice_id}).status_code == 200
fresh = _register(client2).json()
assert client2.post("/api/voice/selection", json={"voice": fresh["id"]}).status_code == 409
assert client2.post("/api/voice/preview", json={"voice": fresh["id"]}).status_code == 200
assert client2.post("/api/voice/selection",
json={"voice": fresh["id"]}).status_code == 200
assert set(BUILTIN) <= set(by_id)
assert stack.generic_voice_writes == 0 and stack.deletes == []
def test_upload_response_lost_then_retry_leaves_orphan(instance):
"""上传在面板侧已生效但响应断连 → 503;重试另立新 ID,共享注册表留下无元数据孤儿条目."""
client, stack, custom, worker_state, tmp_path = instance
original = stack._handle
def flaky(request: httpx.Request) -> httpx.Response:
if request.url.host == "panel.test" and request.url.path == "/api/voices/upload":
original(request) # 面板真的登记了(写进共享注册表与上传账)
raise httpx.ConnectError("response lost after panel committed")
return original(request)
_swap_panel(custom, stack, flaky)
first = _register(client)
assert first.status_code == 503 # 诚实说「登记服务不在」,但面板侧已成立
committed = [u["name"] for u in stack.uploads]
assert len(committed) == 1
_swap_panel(custom, stack, original) # 用户看到失败后重试
second = _register(client)
assert second.status_code == 201
orphan, live = committed[0], second.json()["id"]
registry = json.loads(stack.registry_file.read_text())
assert orphan in registry and live in registry
listing = {v["id"]: v for v in client.get("/api/voice/voices").json()["voices"]}
assert orphan in listing and listing[orphan]["label"] == orphan # 孤儿以 ID 为名仍可见
assert listing[live]["label"] == live # 本次登记未起名,同样以 ID 为名(一致行为)
# 既有 11 支与通用助手状态零改写;孤儿条目未被 CyberGril 覆盖或删除
assert set(BUILTIN) <= set(listing)
assert stack.generic_voice_writes == 0
assert stack.deletes == []
def test_session_refuses_when_worker_state_unwritable(instance):
"""通话开启时 worker 音色写不进:诚实 503;恢复后正常开启,选择不受牵连."""
client, stack, custom, worker_state, tmp_path = instance
registered = _register(client).json()
assert client.post("/api/voice/preview", json={"voice": registered["id"]}).status_code == 200
client.post("/api/voice/selection", json={"voice": registered["id"]})
blocked = tmp_path / "blocked-worker.json"
blocked.mkdir()
custom.config.worker_state_file = str(blocked)
response = client.post("/api/voice/session")
assert response.status_code == 503
assert "写不进" in response.json()["detail"]
custom.config.worker_state_file = str(worker_state)
assert client.post("/api/voice/session").status_code == 201
def test_worker_state_other_keys_and_corruption(instance):
"""可读的 worker 文件其他键保留;文件损坏(非 JSON)时重写只剩 voice —— 如实记录行为."""
client, stack, custom, worker_state, tmp_path = instance
registered = _register(client).json()
client.post("/api/voice/preview", json={"voice": registered["id"]})
worker_state.write_text(json.dumps(
{"voice": "default", "persona": "keep-me", "volume": 7}), encoding="utf-8")
client.post("/api/voice/selection", json={"voice": registered["id"]})
state = json.loads(worker_state.read_text())
assert state["voice"] == registered["id"]
assert state["persona"] == "keep-me" and state["volume"] == 7
worker_state.write_text("{not json", encoding="utf-8")
other = _register(client).json()
client.post("/api/voice/preview", json={"voice": other["id"]})
client.post("/api/voice/selection", json={"voice": other["id"]})
state = json.loads(worker_state.read_text())
# 损坏文件读不出 → 整体重写仅含 voice,旧键丢失(该文件由专属 worker 维护;
# 损坏属异常现场。记录事实,不构成合同违约)
assert state == {"voice": other["id"]}
def test_journal_unwritable_keeps_apply_gated(instance):
"""试听流水写不进:试听仍可成功(尽力而为),但应用凭据缺失 → 409 守门不放松."""
client, stack, custom, worker_state, tmp_path = instance
blocked = tmp_path / "blocked-usage.jsonl"
blocked.mkdir()
custom.journal_path = blocked
registered = _register(client).json()
assert client.post("/api/voice/preview", json={"voice": registered["id"]}).status_code == 200
refused = client.post("/api/voice/selection", json={"voice": registered["id"]})
assert refused.status_code == 409 # fail-closed:宁可再听一次,不放过未试听
def test_apply_rolls_back_when_selection_file_unwritable(instance):
"""本地选择状态写不进:整体回滚,worker 文件不动,错误如实 503."""
client, stack, custom, worker_state, tmp_path = instance
registered = _register(client).json()
client.post("/api/voice/preview", json={"voice": registered["id"]})
worker_state.write_text(json.dumps({"voice": "rain"}), encoding="utf-8")
blocked = tmp_path / "blocked-sel.json"
blocked.mkdir()
custom.selection_path = blocked
response = client.post("/api/voice/selection", json={"voice": registered["id"]})
assert response.status_code == 503
assert "写不进" in response.json()["detail"]
assert json.loads(worker_state.read_text())["voice"] == "rain"
assert custom.selection().voice is None