Files
VoiceStudio/tests/test_batch_queue_restore.py
Palash Debnath ce3827b613 fix(batch): check the speech model inside the transcribe step, not ahead of the whole pipeline (#4625)
* fix(batch): check the speech model when restoring, not in every pipeline run

#4623 added the missing-model check to the batch transcribe stage. Every
batch pipeline test that does not stub it then failed in CI's model-free
environment, leaving main red. Restored jobs are the only ones that skip
enqueue's check, so restore now checks once and shows such a job as failed
with Retry, leaving the pipeline as it was.

Also confines queue record paths to the batch folder after resolving them
(the CodeQL path alerts on the record writer) and reads test files as UTF-8.

* fix(batch): check the speech model inside the transcribe step itself

Review found that a job queued before its speech model was removed could
still download it, and that checking at restore can run before startup
swaps a missing saved model for an installed one. The check now runs in the
transcribe function, right before the backend loads, for every job: queued,
retried or restored. Pipeline tests that stub the guarded transcribe call
never reach it; the one test that runs it with a stubbed model opts out.

Queue record paths are checked after resolving but replaced and removed by
their own directory entry, so a link can't make a cleanup delete another
job's record.
2026-12-03 16:42:04 -08:00

224 lines
9.0 KiB
Python

"""Unfinished batch jobs survive a quit, crash or update restart.
The queue used to live only in memory: a backend restart dropped the rest of a
long batch, and its uploads stayed on disk with nothing pointing at them.
"""
import asyncio
import json
import pytest
# The hermetic test env has no speech model; restore checks for one.
pytestmark = [pytest.mark.asyncio, pytest.mark.usefixtures("asr_model_installed")]
@pytest.fixture
def batch(tmp_path, monkeypatch):
from api.routers import batch
monkeypatch.setattr(batch, "DATA_DIR", str(tmp_path))
monkeypatch.setattr(batch, "_jobs", {})
monkeypatch.setattr(batch, "_queue", asyncio.Queue())
monkeypatch.setattr(batch, "_ensure_queue", lambda: None)
return batch
def _queued(batch, tmp_path, job_id, created_at, status="queued"):
root = tmp_path / "batch"
root.mkdir(exist_ok=True)
video = root / f"{job_id}.mp4"
video.write_bytes(b"video")
job = {
"id": job_id, "status": status, "filename": f"{job_id}.mp4", "video_path": str(video),
"langs": ["es", "fr"], "voice_id": "v1", "preserve_bg": False,
"translation_provider": "argos", "created_at": created_at, "attempts": 2,
}
batch._jobs[job_id] = job
batch._save_record(job)
return job
async def _restart(batch, monkeypatch):
"""A fresh process: nothing in memory, only what is on disk."""
monkeypatch.setattr(batch, "_jobs", {})
monkeypatch.setattr(batch, "_queue", asyncio.Queue())
return await batch.restore_interrupted_jobs()
async def test_restart_queues_unfinished_jobs_again_in_order(batch, tmp_path, monkeypatch):
_queued(batch, tmp_path, "second", created_at=20)
running = _queued(batch, tmp_path, "first", created_at=10, status="running")
partial = tmp_path / "batch" / "first"
partial.mkdir()
(partial / "dubbed_es.wav").write_bytes(b"half")
assert await _restart(batch, monkeypatch) == 2
assert [batch._queue.get_nowait(), batch._queue.get_nowait()] == ["first", "second"]
job = batch._jobs["first"]
assert job["status"] == "queued" and job["restored"] is True
assert job["langs"] == ["es", "fr"] and job["voice_id"] == "v1"
assert job["preserve_bg"] is False and job["attempts"] == 2
assert job["video_path"] == running["video_path"]
# A half-written output from the killed run is not mistaken for a result.
assert not partial.exists()
async def test_finished_cancelled_and_deleted_jobs_are_not_restored(batch, tmp_path, monkeypatch):
for job_id in ("done", "cancelled", "deleted"):
_queued(batch, tmp_path, job_id, created_at=1)
batch._discard_record("done") # the worker's terminal path
batch.cancel_batch_job("cancelled")
batch._jobs["deleted"]["status"] = "failed"
batch.delete_batch_job("deleted")
assert await _restart(batch, monkeypatch) == 0
assert batch._jobs == {}
async def test_shutdown_keeps_the_running_job_for_the_next_start(batch, tmp_path, monkeypatch):
_queued(batch, tmp_path, "live", created_at=1)
started = asyncio.Event()
async def pipeline(job_id, job):
started.set()
await asyncio.sleep(3600)
monkeypatch.setattr(batch, "_run_batch_pipeline", pipeline)
await batch._queue.put("live")
worker = asyncio.ensure_future(batch._worker())
await asyncio.wait_for(started.wait(), 5)
worker.cancel() # backend shutdown cancels the worker task
with pytest.raises(asyncio.CancelledError):
await worker
assert await _restart(batch, monkeypatch) == 1
async def test_a_record_without_its_upload_or_outside_the_folder_is_dropped(batch, tmp_path, monkeypatch):
gone = _queued(batch, tmp_path, "gone", created_at=1)
(tmp_path / "batch" / "gone.mp4").unlink()
outside = tmp_path / "elsewhere.mp4"
outside.write_bytes(b"video")
record = tmp_path / "batch" / "escape.queued.json"
record.write_text(json.dumps({**gone, "id": "escape", "video_path": str(outside)}))
(tmp_path / "batch" / "broken.queued.json").write_text("{not json")
assert await _restart(batch, monkeypatch) == 0
assert not list((tmp_path / "batch").glob("*.queued.json"))
assert outside.exists()
async def test_records_hold_only_the_upload_name_and_survive_a_moved_data_folder(
batch, tmp_path, monkeypatch):
_queued(batch, tmp_path, "moved", created_at=1)
record = json.loads((tmp_path / "batch" / "moved.queued.json").read_text(encoding="utf-8"))
assert record["video_path"] == "moved.mp4"
# The user moves the data folder; the copied record still finds its upload.
moved_to = tmp_path / "elsewhere"
moved_to.mkdir()
(tmp_path / "batch").rename(moved_to / "batch")
monkeypatch.setattr(batch, "DATA_DIR", str(moved_to))
assert await _restart(batch, monkeypatch) == 1
assert batch._jobs["moved"]["video_path"] == str((moved_to / "batch" / "moved.mp4").resolve())
async def test_a_save_racing_a_cancel_does_not_bring_the_job_back(batch, tmp_path, monkeypatch):
job = _queued(batch, tmp_path, "raced", created_at=1)
batch.cancel_batch_job("raced")
batch._save_record(job) # the retry's write finishing after the cancel
assert await _restart(batch, monkeypatch) == 0
async def test_the_worker_drops_the_record_of_a_job_cancelled_while_queued(batch, tmp_path):
job = _queued(batch, tmp_path, "skipped", created_at=1)
job["status"] = "cancelled"
await batch._queue.put("skipped")
worker = asyncio.create_task(batch._worker())
await batch._queue.join()
worker.cancel()
with pytest.raises(asyncio.CancelledError):
await worker
assert not (tmp_path / "batch" / "skipped.queued.json").exists()
async def test_a_record_that_cannot_be_removed_is_marked_finished(batch, tmp_path, monkeypatch):
_queued(batch, tmp_path, "stuck", created_at=1)
(tmp_path / "batch" / "stuck").mkdir()
(tmp_path / "batch" / "stuck" / "dubbed_es.mp4").write_bytes(b"result")
def refuse(_path):
raise batch.FileCleanupError("locked")
with monkeypatch.context() as patch:
patch.setattr(batch, "unlink_if_present", refuse)
batch._discard_record("stuck") # the worker's terminal path
assert await _restart(batch, monkeypatch) == 0
# The finished job's results are left alone.
assert (tmp_path / "batch" / "stuck" / "dubbed_es.mp4").exists()
@pytest.mark.parametrize("field, value", [
("created_at", "yesterday"), ("created_at", True), ("attempts", "2"), ("attempts", 0),
("langs", ["es", 3]), ("video_path", 7), ("voice_id", ["v1"]),
])
async def test_one_malformed_record_is_dropped_without_blocking_the_rest(
batch, tmp_path, monkeypatch, field, value):
_queued(batch, tmp_path, "good", created_at=5)
_queued(batch, tmp_path, "bad", created_at=1)
path = tmp_path / "batch" / "bad.queued.json"
record = json.loads(path.read_text(encoding="utf-8"))
record[field] = value
path.write_text(json.dumps(record), encoding="utf-8")
assert await _restart(batch, monkeypatch) == 1
assert list(batch._jobs) == ["good"]
assert not path.exists()
async def test_a_job_finding_its_speech_model_removed_fails_instead_of_downloading(
monkeypatch, tmp_path):
# Enqueue checks the model; a job that waited in the queue (or came back
# after a restart) must check again rather than let the transcriber fetch it.
from api.routers import batch
from services import asr_backend
monkeypatch.setattr(batch, "DATA_DIR", str(tmp_path))
missing = {"error": "asr_model_missing", "missing_repo_id": "Systran/faster-whisper-large-v3",
"recommended": None}
monkeypatch.setattr(asr_backend, "asr_model_missing_error", lambda **_kw: missing)
loaded = []
monkeypatch.setattr(asr_backend, "load_active_asr_backend", lambda: loaded.append(1))
class _Probe:
stdout = b""
stderr = b"Duration: 00:00:02.00, start: 0.000000, bitrate: 1000 kb/s\n"
monkeypatch.setattr("subprocess.run", lambda *a, **k: _Probe())
monkeypatch.setattr("services.ffmpeg_utils.find_ffmpeg", lambda: "ffmpeg")
video = tmp_path / "in.mp4"
video.write_bytes(b"video")
job = {"id": "nomodel", "status": "running", "filename": "in.mp4", "video_path": str(video),
"langs": ["es"], "voice_id": None, "preserve_bg": False,
"translation_provider": "argos", "created_at": 1, "attempts": 1}
with pytest.raises(RuntimeError, match="speech-to-text"):
await batch._run_batch_pipeline("nomodel", job)
assert loaded == []
async def test_a_record_linked_to_another_jobs_record_never_removes_that_record(
batch, tmp_path, monkeypatch):
_queued(batch, tmp_path, "real", created_at=1)
link = tmp_path / "batch" / "alias.queued.json"
try:
link.symlink_to(tmp_path / "batch" / "real.queued.json")
except OSError:
pytest.skip("symlinks need extra rights on this host")
assert await _restart(batch, monkeypatch) == 1
assert list(batch._jobs) == ["real"]
# The mismatched link is dropped; the record it pointed at stays.
assert not link.is_symlink()
assert (tmp_path / "batch" / "real.queued.json").is_file()