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>
This commit is contained in:
施工员2号
2026-10-28 01:09:19 +08:00
co-authored by multica-agent
parent b09a907747
commit 07dda2bfa2
9 changed files with 687 additions and 53 deletions
+31 -4
View File
@@ -3,14 +3,17 @@
针对总管列出的统一审核重点,用可控假服务注入故障,零真实调用:
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 侧可离线证明的事实。
属真机窗口验证范围(见 docs/rework/hel902/);本文件锁 API 侧可离线证明的事实,
capture→worker 实读竞态的确定性时序用例见 tests/test_voice_rework_hel904.py。
"""
import json
@@ -56,21 +59,28 @@ def _swap_panel(custom, stack, handler):
def test_panel_ok_local_metadata_write_fails(instance):
"""8090 登记成功、本地元数据写不进:500(未映射合同错误);状态仍可恢复、不逼重复注册."""
"""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 == 500 # OSError 未被映射为 503/422(产品语义)
assert len(stack.uploads) == 1
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,
@@ -78,6 +88,23 @@ def test_panel_ok_local_metadata_write_fails(instance):
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):
+243
View File
@@ -0,0 +1,243 @@
"""HEL-904 后台返修:capture 音色与 worker 实读竞态的确定性时序用例.
HEL-902 审核第 6 项的收口验证。事实前提(先核真实入口,不猜):
* 专属 worker 是**另一进程**,在自己的会话入口读一次
``voice_state_cybergril.json``(HEL-877 既有行为,合同 §2.5);
* API 进程只知道 dispatch 何时返回,**dispatch 返回 ≠ worker 已读**——
worker 的读时点对 API 不可知;
* 因此修复采用等价的「会话不可变快照」:capture 时登记通话持有,
整个通话窗口(capture→挂断/到期)都按「worker 尚未读」对待,
期间应用的 worker 写入暂缓,状态文件定在本通话捕获值上。
时序全部用 asyncio.Event 门控(无 sleep 凑数);「worker 读文件」由
测试在 dispatch 返回之后亲自读文件扮演——这正是竞态窗口里最坏的读者。
零真实 LLM/嵌入/ASR/TTS 调用、零网络(全假服务)。
"""
from __future__ import annotations
import asyncio
import json
import sys
from pathlib import Path
import httpx
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from test_r2 import R2LLM # noqa: E402
from test_voice_custom import CREATE, FakeVoiceStack, make_wav # noqa: E402
from cybergril.api.app import create_app # noqa: E402
from cybergril.life.runtime import LifeConfig # noqa: E402
from cybergril.think.router import build_router # noqa: E402
from cybergril.think.scenes import Tier # noqa: E402
from cybergril.voice.custom import CustomVoiceConfig, CustomVoiceService # noqa: E402
from cybergril.voice.session import VoiceConfig, VoiceSessionService # noqa: E402
class GatedLiveKitTransport(httpx.AsyncHTTPTransport):
"""可门控的假 LiveKit:dispatch 进站即亮灯,返回被 gate 扣住.
这让测试能把「开房请求在途」精确固定成一个时间点:capture 已写文件、
dispatch 尚未返回,此刻并发发起应用正是审核指出的竞态窗口。
"""
def __init__(self, stack: FakeVoiceStack) -> None:
super().__init__()
self.stack = stack
self.dispatch_in_flight = asyncio.Event()
self.gate = asyncio.Event()
self.fail_dispatch = False
self.fail_delete = False
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
if request.url.host == "tts.test": # TTS 健康/合成走既有桩
return self.stack._handle(request)
path = request.url.path
if path == "/twirp/livekit.AgentDispatchService/CreateDispatch":
self.dispatch_in_flight.set()
await self.gate.wait() # 扣住 dispatch 响应,直到测试放行
if self.fail_dispatch:
raise httpx.ConnectError("dispatch wire cut")
return httpx.Response(200, json={"id": "AD_1", "room": "r"})
if path == "/twirp/livekit.RoomService/DeleteRoom":
if self.fail_delete:
raise httpx.ConnectError("delete wire cut")
return httpx.Response(200, content=b"")
return httpx.Response(404)
def build_gated_app(tmp: Path, stack: FakeVoiceStack, transport: GatedLiveKitTransport):
voice = VoiceSessionService(
config=VoiceConfig(
livekit_url="ws://voice.test:7880", livekit_internal="http://livekit.test",
api_key="devkey", api_secret="test-secret-not-real",
tts_health_url="http://tts.test/health"),
http=httpx.AsyncClient(transport=transport))
worker_state = tmp / "voice_state_cybergril.json"
custom = CustomVoiceService(
config=CustomVoiceConfig(
panel_url="https://panel.test", tts_url="http://tts.test",
registry_file=str(stack.registry_file),
worker_state_file=str(worker_state)),
http=httpx.AsyncClient(transport=stack.transport, verify=False),
selection_path=tmp / "sel.json", registry_path=tmp / "custom.json",
journal_path=tmp / "usage.jsonl")
provider = R2LLM()
router = build_router(providers={t: provider for t in (Tier.HIGH, Tier.STANDARD, Tier.LOW)})
app = create_app(db_path=":memory:", router=router,
life_config=LifeConfig(enabled=True, poll_seconds=3600),
semantic_mode="stub", voice_service=voice,
custom_voice_service=custom)
return app, custom, worker_state
def _worker_reads(worker_state: Path) -> str:
"""扮演 worker 的会话入口读:读时点由测试决定(这里是 dispatch 返回之后)."""
return str(json.loads(worker_state.read_text(encoding="utf-8")).get("voice", ""))
async def _register_and_apply_old(client: httpx.AsyncClient) -> str:
registered = await client.post(
"/api/voice/voices", params={"prompt_text": "参考文字"},
content=make_wav(3), headers={"Content-Type": "audio/wav"})
assert registered.status_code == 201
voice_id = registered.json()["id"]
assert (await client.post("/api/voice/preview", json={"voice": voice_id})).status_code == 200
applied = await client.post("/api/voice/selection", json={"voice": voice_id})
assert applied.status_code == 200
return voice_id
@pytest.fixture
def gated(tmp_path):
stack = FakeVoiceStack(tmp_path)
transport = GatedLiveKitTransport(stack)
app, custom, worker_state = build_gated_app(tmp_path, stack, transport)
return app, stack, transport, custom, worker_state
async def test_worker_read_after_dispatch_sees_pinned_voice(gated):
"""核心时序:worker 读时点被延迟到 dispatch 返回之后、且发生在并发应用
完成之后——本通话保持旧音色(响应=实读),下一通话使用新音色."""
app, stack, transport, custom, worker_state = gated
async with app.router.lifespan_context(app), httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
await client.post("/api/companion", json=CREATE)
old_voice = await _register_and_apply_old(client)
# 开房:capture 已写文件,dispatch 在途(gate 扣住响应)
open_task = asyncio.create_task(client.post("/api/voice/session"))
await asyncio.wait_for(transport.dispatch_in_flight.wait(), timeout=5)
assert _worker_reads(worker_state) == old_voice # capture 已落盘
# 竞态窗口内并发应用新音色(dispatch 尚未返回,worker 必然还没读)
apply_task = asyncio.create_task(
client.post("/api/voice/selection", json={"voice": "rain"}))
applied = await asyncio.wait_for(apply_task, timeout=5)
assert applied.status_code == 200 # 应用成功:选择已记
assert custom.selection().voice == "rain"
# 关键断言(defer 生效):worker 文件仍定在本通话捕获值上
assert _worker_reads(worker_state) == old_voice
transport.gate.set() # 放行 dispatch
opened = (await asyncio.wait_for(open_task, timeout=5)).json()
assert opened["voice"] == old_voice # 响应报告本通话捕获值
# worker 现在才读文件(dispatch 返回之后、通话仍进行中)
assert _worker_reads(worker_state) == old_voice # 读到的=响应报告的
# 挂断结算 → 持有释放;暂缓的写入由下一通 capture 重写生效
ended = await client.delete(f"/api/voice/session/{opened['session_id']}")
assert ended.status_code == 200
assert not custom.call_voice_held()
assert _worker_reads(worker_state) == old_voice # 结算不补写,下一通重写
transport.dispatch_in_flight.clear()
second = (await client.post("/api/voice/session")).json()
assert second["voice"] == "rain"
assert _worker_reads(worker_state) == "rain" # 下一通:新音色生效
await client.delete(f"/api/voice/session/{second['session_id']}")
async def test_end_delete_failure_and_ttl_expiry_settle_hold(gated):
"""挂断失败转清理欠账、TTL 到期(_prune)两条路径都结算持有."""
app, stack, transport, custom, worker_state = gated
async with app.router.lifespan_context(app), httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
await client.post("/api/companion", json=CREATE)
old_voice = await _register_and_apply_old(client)
transport.gate.set()
opened = (await client.post("/api/voice/session")).json()
assert opened["voice"] == old_voice
applied = await client.post("/api/voice/selection", json={"voice": "rain"})
assert applied.status_code == 200
assert _worker_reads(worker_state) == old_voice # 通话活跃:暂缓
# 显式挂断失败(删房线断)→ 503、会话转欠账、持有照样结算
transport.fail_delete = True
ended = await client.delete(f"/api/voice/session/{opened['session_id']}")
assert ended.status_code == 503
assert not custom.call_voice_held() # 转欠账即结算:持有释放
# 暂缓的写入不靠结算补写(下一次 capture 会重写)——但结算后
# 再次应用立即写透,这是面向用户的恢复路径
assert _worker_reads(worker_state) == old_voice
reapplied = await client.post("/api/voice/selection", json={"voice": "rain"})
assert reapplied.status_code == 200
assert _worker_reads(worker_state) == "rain"
# TTL 到期路径:再开一通、拨表到期,_prune 也要释放持有
transport.fail_delete = False
transport.dispatch_in_flight.clear()
third = (await client.post("/api/voice/session")).json()
assert third["voice"] == "rain"
assert custom.call_voice_held()
service = app.state.voice_service
session_obj = service.get(third["session_id"])
session_obj.expires_at = service.clock() - 1 # 拨到过去:立即到期
service._prune()
assert not custom.call_voice_held()
async def test_dispatch_failure_releases_hold(gated):
"""失败清理:dispatch 失败 → 503 且持有立即释放,应用马上写透."""
app, stack, transport, custom, worker_state = gated
async with app.router.lifespan_context(app), httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
await client.post("/api/companion", json=CREATE)
await _register_and_apply_old(client)
transport.fail_dispatch = True
transport.gate.set()
refused = await client.post("/api/voice/session")
assert refused.status_code == 503
assert not custom.call_voice_held() # 失败即结算,无泄漏
applied = await client.post("/api/voice/selection", json={"voice": "rain"})
assert applied.status_code == 200
assert _worker_reads(worker_state) == "rain" # 无活跃通话:立即写透
async def test_cancelled_open_releases_hold(gated):
"""取消清理:开房请求在途被取消(客户端断开)→ 持有释放,不无限暂缓."""
app, stack, transport, custom, worker_state = gated
async with app.router.lifespan_context(app), httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://t") as client:
await client.post("/api/companion", json=CREATE)
await _register_and_apply_old(client)
open_task = asyncio.create_task(client.post("/api/voice/session"))
await asyncio.wait_for(transport.dispatch_in_flight.wait(), timeout=5)
open_task.cancel() # dispatch 在途时客户端取消
with pytest.raises(asyncio.CancelledError):
await open_task # 取消在解除 await 前已完成整个栈展开:持有已释放
assert not custom.call_voice_held() # 取消路径也结算
applied = await client.post("/api/voice/selection", json={"voice": "rain"})
assert applied.status_code == 200
assert _worker_reads(worker_state) == "rain"