"""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"