cmvr-visual/tts/tests/test_lifecycle.py

215 lines
8.2 KiB
Python
Raw Permalink Normal View History

import asyncio
import importlib
import os
from pathlib import Path
import signal
import sys
from types import SimpleNamespace
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
speech_module = importlib.import_module('tts.app')
from tts.app import SpeechRequest, TTSSettings, create_app
class Connection:
def __init__(self, disconnected=False):
self.disconnected = disconnected
self.checked = asyncio.Event()
async def is_disconnected(self):
self.checked.set()
return self.disconnected
def settings_for(tmp_path):
models = tmp_path / 'models'
(models / 'voices').mkdir(parents=True)
for name in ['config.json', 'kokoro-v1_0.pth', 'voices/zf_xiaobei.pt', 'voices/zm_yunxi.pt']:
(models / name).write_bytes(b'fixture')
return TTSSettings('private-key', models, tmp_path / 'work', timeout_seconds=.01)
def speech_endpoint(app):
return next(route.endpoint for route in app.routes if route.path == '/v1/audio/speech')
@pytest.mark.parametrize('failure', [OSError, asyncio.CancelledError])
def test_response_send_failure_removes_request_directory(tmp_path, failure):
async def scenario():
settings = settings_for(tmp_path)
async def synthesize(body, destination, settings):
destination.write_bytes(b'RIFF\x04\x00\x00\x00WAVE')
endpoint = speech_endpoint(create_app(settings, synthesize=synthesize))
response = await endpoint(SpeechRequest(input='你好'), Connection())
assert len(list(settings.work_dir.iterdir())) == 1
async def receive():
return {'type': 'http.request', 'body': b'', 'more_body': False}
async def send(message):
if message['type'] == 'http.response.body':
raise failure()
with pytest.raises(failure):
await response({'type': 'http', 'method': 'POST', 'path': '/',
'headers': [], 'extensions': {}, 'asgi': {'spec_version': '2.4'}},
receive, send)
assert list(settings.work_dir.iterdir()) == []
asyncio.run(scenario())
def test_disconnected_queued_request_never_starts_model_and_releases_files(tmp_path):
async def scenario():
settings = settings_for(tmp_path)
started = asyncio.Event()
calls = []
async def synthesize(body, destination, settings):
calls.append(body.input)
started.set()
await asyncio.Event().wait()
endpoint = speech_endpoint(create_app(settings, synthesize=synthesize))
active = asyncio.create_task(endpoint(SpeechRequest(input='active'), Connection()))
await started.wait()
connection = Connection(disconnected=True)
queued = asyncio.create_task(endpoint(SpeechRequest(input='cancelled'), connection))
try:
done, _ = await asyncio.wait({queued}, timeout=.25)
assert queued in done, 'Disconnected requests must not wait for the active model'
assert queued.cancelled()
assert calls == ['active']
assert len(list(settings.work_dir.iterdir())) == 1
finally:
active.cancel()
queued.cancel()
await asyncio.gather(active, queued, return_exceptions=True)
assert list(settings.work_dir.iterdir()) == []
asyncio.run(scenario())
class ProcessGroup:
pid = 987654321 # Always fake: no test sends an OS signal.
def __init__(self, leader_finished=False, has_descendant=True):
self.returncode = 0 if leader_finished else None
self.has_descendant = has_descendant
self.started = asyncio.Event()
self.signals = []
async def wait(self):
self.started.set()
if self.returncode is None:
await asyncio.Event().wait()
return self.returncode
def killpg(self, pid, action):
assert pid == self.pid
if not self.has_descendant and self.returncode is not None:
raise ProcessLookupError()
if action:
self.signals.append(action)
if action == signal.SIGTERM:
self.returncode = 0 # Leader exits, descendant deliberately ignores TERM.
elif action == 9:
self.returncode = 0
self.has_descendant = False
@pytest.mark.parametrize('outcome', ['timeout', 'cancel', 'leader_already_exited'])
def test_cleanup_kills_remaining_group_after_leader_exits(tmp_path, monkeypatch, outcome):
async def scenario():
process = ProcessGroup(leader_finished=outcome == 'leader_already_exited')
async def create_process(*args, **kwargs):
return process
monkeypatch.setattr(speech_module.asyncio, 'create_subprocess_exec', create_process)
monkeypatch.setattr(speech_module, 'os', SimpleNamespace(
name='posix', environ=os.environ, killpg=process.killpg))
monkeypatch.setattr(speech_module, 'signal', SimpleNamespace(SIGTERM=15, SIGKILL=9))
monkeypatch.setattr(speech_module, 'PROCESS_GROUP_GRACE_SECONDS', .01, raising=False)
settings = settings_for(tmp_path)
task = asyncio.create_task(speech_module.run_synthesis(
SpeechRequest(input='你好'), tmp_path / 'speech.wav', settings))
if outcome == 'cancel':
await process.started.wait()
task.cancel()
if outcome == 'timeout':
with pytest.raises(asyncio.TimeoutError):
await task
elif outcome == 'cancel':
with pytest.raises(asyncio.CancelledError):
await task
else:
await task
assert signal.SIGTERM in process.signals
assert 9 in process.signals
assert process.has_descendant is False
asyncio.run(scenario())
def test_model_child_receives_only_runtime_environment_not_service_secrets(tmp_path, monkeypatch):
async def scenario():
captured = {}
process = ProcessGroup(leader_finished=True, has_descendant=False)
async def create_process(*args, **kwargs):
captured.update(kwargs['env'])
return process
monkeypatch.setenv('TTS_API_KEY', 'tts-secret')
monkeypatch.setenv('INFERENCE_API_KEY', 'gpu-secret')
monkeypatch.setenv('MYSQL_PASSWORD', 'database-secret')
monkeypatch.setenv('HF_HOME', '/workspace/cmvr-visual/tts-cache')
monkeypatch.setattr(speech_module.asyncio, 'create_subprocess_exec', create_process)
monkeypatch.setattr(speech_module, 'os', SimpleNamespace(
name='posix', environ=os.environ, killpg=process.killpg))
await speech_module.run_synthesis(SpeechRequest(input='你好'), tmp_path / 'speech.wav',
settings_for(tmp_path))
unexpected = sorted(key for key in ('TTS_API_KEY', 'INFERENCE_API_KEY', 'MYSQL_PASSWORD')
if key in captured)
assert unexpected == []
assert captured['HF_HOME'] == '/workspace/cmvr-visual/tts-cache'
assert captured['CUDA_VISIBLE_DEVICES'] == ''
assert captured['HF_HUB_OFFLINE'] == '1'
asyncio.run(scenario())
def test_cancellation_during_timeout_cleanup_cannot_interrupt_group_kill(tmp_path, monkeypatch):
async def scenario():
process = ProcessGroup()
terminating = asyncio.Event()
async def create_process(*args, **kwargs):
return process
def killpg(pid, action):
process.killpg(pid, action)
if action == 15:
terminating.set()
monkeypatch.setattr(speech_module.asyncio, 'create_subprocess_exec', create_process)
monkeypatch.setattr(speech_module, 'os', SimpleNamespace(
name='posix', environ=os.environ, killpg=killpg))
monkeypatch.setattr(speech_module, 'signal', SimpleNamespace(SIGTERM=15, SIGKILL=9))
monkeypatch.setattr(speech_module, 'PROCESS_GROUP_GRACE_SECONDS', .02)
task = asyncio.create_task(speech_module.run_synthesis(
SpeechRequest(input='你好'), tmp_path / 'speech.wav', settings_for(tmp_path)))
await terminating.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert process.has_descendant is False
assert 9 in process.signals
asyncio.run(scenario())