Files
VoiceStudio/tests/test_dub_fork.py
debpalash 0d4af8a0f0 fix(dub): close fork races with clear history and source replacement
Review fixes for #4538 in the #4572 train: the fork is in flight from the
moment it claims its directory, Clear history picks its ids under the job
lock, a source replaced mid-fork aborts it, missing borrowed media is refused,
an id with a history row is a conflict rather than inherited, an abandoned
fork directory is recoverable, withdrawal markers outlive pruning while held,
media_language is carried over, and POST /dub/fork has a typed response.
2026-12-01 00:08:10 +05:30

734 lines
32 KiB
Python

"""A prepared dubbing job can be forked over its media for another render."""
import errno
import importlib
import logging
import os
import shutil
import threading
import time
import uuid
from collections import OrderedDict
import numpy as np
import pytest
import soundfile as sf
MEDIA = ("original.mp4", "audio.wav", "audio_hq.wav", "vocals.wav", "no_vocals.wav")
@pytest.fixture
def prepared(monkeypatch, tmp_path):
"""Create a prepared job with media, stems, a transcript and one rendered take."""
from core.db import init_db
dp = importlib.import_module("services.dub_pipeline")
init_db()
monkeypatch.setattr(dp, "DUB_DIR", str(tmp_path))
monkeypatch.setattr(dp, "_DUB_DIR_REAL", os.path.realpath(tmp_path))
monkeypatch.setattr(dp, "_dub_jobs", {})
monkeypatch.setattr(dp, "_inflight_jobs", set())
monkeypatch.setattr(dp, "_withdrawn_jobs", OrderedDict())
monkeypatch.setattr(dp, "_job_dir_claims", set())
job_id = "fork-source-" + uuid.uuid4().hex
folder = tmp_path / job_id
folder.mkdir()
(folder / "original.mp4").write_bytes(b"video")
sf.write(folder / "audio.wav", np.zeros(2 * 16000), 16000)
for name in ("audio_hq.wav", "vocals.wav", "no_vocals.wav"):
sf.write(folder / name, np.zeros((2 * 44100, 2)), 44100)
(folder / "seg_en_s1.wav").write_bytes(b"take")
(folder / "thumb.jpg").write_bytes(b"thumbnail")
dp.put_job(job_id, {
"video_path": str(folder / "original.mp4"), "audio_path": str(folder / "audio.wav"),
"vocals_path": str(folder / "vocals.wav"), "no_vocals_path": str(folder / "no_vocals.wav"),
"thumb_path": str(folder / "thumb.jpg"), "duration": 2.0, "filename": "fixture.mp4", "input_type": "video",
"scene_cuts": [0.5], "separate_background": True, "background_separation": "ok",
"external_stems": True, "segments": [{"id": "s1"}], "dubbed_tracks": {"en": {}},
"speaker_clones": {"A": "x"}, "seg_hashes": {"s1": "h"},
})
return dp, job_id, folder
@pytest.fixture
def clients():
"""Mount the real router with loopback and remote peers."""
from fastapi import FastAPI
from fastapi.testclient import TestClient
router = importlib.import_module("api.routers.dub_core").router
app = FastAPI()
app.include_router(router)
return TestClient(app, client=("127.0.0.1", 50000)), TestClient(app, client=("198.51.100.10", 50000))
def new_id():
"""Return an unused job id."""
return "fork-copy-" + uuid.uuid4().hex
def test_fork_shares_media_and_leaves_render_state_behind(prepared):
"""The fork names its own links to the media and starts without a transcript or takes."""
dp, job_id, folder = prepared
fork_id = new_id()
record = dp.fork_job(job_id, fork_id)
fork_dir = folder.parent / fork_id
keys = {"video_path": "original.mp4", "audio_path": "audio.wav",
"vocals_path": "vocals.wav", "no_vocals_path": "no_vocals.wav"}
for key, name in keys.items():
assert record[key] == str(fork_dir / name)
for name in MEDIA:
assert os.path.samefile(fork_dir / name, folder / name), f"{name} is shared, not prepared again"
assert record["thumb_path"] == str(fork_dir / "thumb.jpg")
assert (fork_dir / "thumb.jpg").read_bytes() == b"thumbnail"
assert not os.path.samefile(fork_dir / "thumb.jpg", folder / "thumb.jpg"), "the thumbnail is a copy"
assert sorted(path.name for path in fork_dir.iterdir()) == sorted((*MEDIA, "thumb.jpg")), "takes stay with their job"
assert record["segments"] is None and record["dubbed_tracks"] == {} and record["forked_from"] == job_id
assert "speaker_clones" not in record and "seg_hashes" not in record
assert (record["duration"], record["filename"], record["scene_cuts"]) == (2.0, "fixture.mp4", [0.5])
assert record["external_stems"] is True and record["background_separation"] == "ok"
source = dp.get_job(job_id)
assert source["segments"] == [{"id": "s1"}] and source["speaker_clones"] == {"A": "x"}, "the source is untouched"
assert (folder / "seg_en_s1.wav").read_bytes() == b"take"
dp._dub_jobs.clear()
assert dp.get_job(fork_id)["vocals_path"] == str(fork_dir / "vocals.wav"), "the fork survives a restart"
def test_each_job_keeps_its_media_when_the_other_changes(prepared):
"""Replacing or deleting the source's files leaves the fork's files as they were."""
dp, job_id, folder = prepared
fork_id = new_id()
dp.fork_job(job_id, fork_id)
fork_dir = folder.parent / fork_id
before = (fork_dir / "vocals.wav").read_bytes()
replacement = folder / "vocals.new.wav"
sf.write(replacement, np.ones((44100, 2)) * 0.1, 44100)
os.replace(replacement, folder / "vocals.wav")
assert (fork_dir / "vocals.wav").read_bytes() == before
# Preparing the source again writes its thumbnail in place; the fork has its own.
(folder / "thumb.jpg").write_bytes(b"another frame")
assert (fork_dir / "thumb.jpg").read_bytes() == b"thumbnail"
shutil.rmtree(folder)
for name in MEDIA:
assert (fork_dir / name).is_file()
assert sf.info(fork_dir / "no_vocals.wav").frames == 2 * 44100
def test_fork_copies_and_logs_when_the_volume_cannot_link(prepared, monkeypatch, caplog):
"""Without hard links the fork still works on its own copies, and says why."""
dp, job_id, folder = prepared
def refuse(src, dst, **kwargs):
raise OSError(errno.EXDEV, "Invalid cross-device link")
monkeypatch.setattr(dp.os, "link", refuse)
fork_id = new_id()
with caplog.at_level(logging.INFO, logger="omnivoice.dub_pipeline"):
record = dp.fork_job(job_id, fork_id)
fork_dir = folder.parent / fork_id
for name in MEDIA:
assert (fork_dir / name).read_bytes() == (folder / name).read_bytes()
assert not os.path.samefile(fork_dir / name, folder / name)
assert record["vocals_path"] == str(fork_dir / "vocals.wav")
assert "could not hard-link vocals.wav (Invalid cross-device link); copying it instead" in caplog.text
def test_fork_keeps_paths_outside_the_source_directory(prepared):
"""Stems the preparation cache borrowed from another job are carried as they are."""
dp, job_id, folder = prepared
other = folder.parent / "another-job"
other.mkdir()
borrowed = other / "vocals.wav"
sf.write(borrowed, np.zeros((2 * 44100, 2)), 44100)
dp.get_job(job_id)["vocals_path"] = str(borrowed)
fork_id = new_id()
record = dp.fork_job(job_id, fork_id)
assert record["vocals_path"] == str(borrowed)
assert not (folder.parent / fork_id / "vocals.wav").exists(), "nothing is linked for a path it does not own"
assert record["no_vocals_path"] == str(folder.parent / fork_id / "no_vocals.wav")
def test_fork_refuses_a_taken_id_and_leaves_it_alone(prepared):
"""An id whose directory exists is never reused or written into."""
dp, job_id, folder = prepared
taken = folder.parent / new_id()
taken.mkdir()
(taken / "keep.txt").write_text("mine", encoding="utf-8")
with pytest.raises(FileExistsError):
dp.fork_job(job_id, taken.name)
assert sorted(path.name for path in taken.iterdir()) == ["keep.txt"]
assert dp.get_job(taken.name) is None
@pytest.mark.parametrize("bad_id", ["../escape", "a/b", "", "has space", "x" * 65, ".."])
def test_fork_refuses_unsafe_ids(prepared, bad_id):
"""Ids that could leave the jobs directory or exceed the limit create nothing."""
dp, job_id, folder = prepared
before = sorted(path.name for path in folder.parent.iterdir())
with pytest.raises(ValueError, match="Invalid job_id"):
dp.fork_job(job_id, bad_id)
assert sorted(path.name for path in folder.parent.iterdir()) == before
def test_fork_needs_a_known_prepared_source(prepared):
"""An unknown source and one still being prepared are both refused without a trace."""
dp, job_id, folder = prepared
fork_id = new_id()
with pytest.raises(LookupError):
dp.fork_job("fork-unknown-" + uuid.uuid4().hex, fork_id)
dp.begin_ingest(job_id)
try:
with pytest.raises(ValueError, match="media preparation"):
dp.fork_job(job_id, fork_id)
finally:
dp.end_ingest(job_id)
assert not (folder.parent / fork_id).exists()
def test_failed_fork_leaves_nothing_behind(prepared, monkeypatch):
"""A fork that cannot be saved removes its directory, stays out of memory and frees the id."""
dp, job_id, folder = prepared
fork_id = new_id()
def broken(*args, **kwargs):
raise RuntimeError("database unavailable")
with monkeypatch.context() as patch:
patch.setattr(dp, "_persist_job", broken)
with pytest.raises(RuntimeError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
assert fork_id not in dp._inflight_jobs and fork_id not in dp._dub_jobs
for name in MEDIA:
assert (folder / name).is_file(), "the source keeps its media"
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id, "the id is free again"
@pytest.mark.parametrize("clear_history", [False, True])
def test_fork_deleted_while_its_media_are_copied_is_refused(prepared, monkeypatch, clear_history):
"""A delete of the new job, or "clear history", that lands during the copy wins."""
dp, job_id, folder = prepared
fork_id = new_id()
link, seen = dp._link_or_copy, []
def delete_then_link(src, dst):
if not seen:
seen.append(fork_id in dp._inflight_jobs)
if clear_history:
dp.purge_jobs([], delete_rows=lambda: None, include_inflight=True)
else:
dp.purge_jobs([fork_id], delete_rows=lambda: None)
link(src, dst)
monkeypatch.setattr(dp, "_link_or_copy", delete_then_link)
with pytest.raises(ValueError, match="deleted while it was being created"):
dp.fork_job(job_id, fork_id)
assert seen == [True], "the fork is registered before its first file is linked"
assert not (folder.parent / fork_id).exists()
assert fork_id not in dp._dub_jobs and fork_id not in dp._inflight_jobs
assert fork_id in dp._withdrawn_jobs, "the delete is not undone"
dp._dub_jobs.clear()
assert dp.get_job(fork_id) is None, "nothing was saved"
def test_fork_whose_directory_is_deleted_midway_reports_the_delete(prepared, monkeypatch):
"""A delete that also removes the new directory is reported as the delete it was."""
dp, job_id, folder = prepared
fork_id = new_id()
link, calls = dp._link_or_copy, []
def delete_directory_then_link(src, dst):
if not calls:
dp.purge_jobs([fork_id], delete_rows=lambda: None)
shutil.rmtree(folder.parent / fork_id)
calls.append(dst)
link(src, dst)
monkeypatch.setattr(dp, "_link_or_copy", delete_directory_then_link)
with pytest.raises(ValueError, match="deleted while it was being created"):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
def test_fork_revives_an_id_deleted_before_it_started(prepared):
"""A tombstone from an earlier job of this id does not block a new fork."""
dp, job_id, folder = prepared
fork_id = new_id()
dp._withdrawn_jobs[fork_id] = time.monotonic()
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id
assert fork_id not in dp._withdrawn_jobs and fork_id in dp._dub_jobs
def test_fork_refuses_an_id_an_earlier_attempt_still_holds(prepared):
"""An id whose earlier fork or ingest is still running is in use, even with its directory deleted."""
dp, job_id, folder = prepared
fork_id = new_id()
dp.begin_ingest(fork_id)
with pytest.raises(FileExistsError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists(), "nothing is reserved"
assert fork_id in dp._inflight_jobs, "the earlier attempt keeps its mark"
assert fork_id not in dp._job_dir_claims
assert dp.get_job(fork_id) is None
dp.end_ingest(fork_id)
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id, "the id is free once that attempt ends"
def test_delete_during_a_fork_leaves_the_directory_to_the_fork(clients, prepared, monkeypatch):
"""A delete of the new id never touches the directory; the withdrawn fork stops and removes it."""
dp, job_id, folder = prepared
local, _ = clients
fork_id = new_id()
fork_dir = folder.parent / fork_id
link, calls, seen = dp._link_or_copy, [], {}
def link_then_delete(src, dst):
link(src, dst)
calls.append(dst)
if len(calls) == 1:
seen["status"] = local.delete(f"/dub/history/{fork_id}").status_code
seen["kept"] = sorted(path.name for path in fork_dir.iterdir())
seen["held"] = fork_id in dp._job_dir_claims
monkeypatch.setattr(dp, "_link_or_copy", link_then_delete)
with pytest.raises(ValueError, match="deleted while it was being created"):
dp.fork_job(job_id, fork_id)
assert seen == {"status": 200, "kept": [dp._FORK_MARKER, "original.mp4"], "held": True}, "the delete left the directory alone"
assert len(calls) == 1, "the fork stops at its next file"
assert not fork_dir.exists() and fork_id not in dp._job_dir_claims
assert fork_id not in dp._dub_jobs and fork_id not in dp._inflight_jobs
# Whatever takes the id now is nobody's to remove: the delete has long returned.
monkeypatch.setattr(dp, "_link_or_copy", link)
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id, "the id is free again"
class _WatchedLock:
"""The job lock, reporting when any thread but the one that built it asks for it."""
def __init__(self, inner, watched: dict, reached: threading.Event):
self._inner, self._watched, self._reached = inner, watched, reached
self._owner = threading.get_ident() # the fork runs here; a route runs in a worker thread
def __enter__(self):
if "thread" in self._watched and threading.get_ident() != self._owner:
self._reached.set()
return self._inner.__enter__()
def __exit__(self, *exc):
return self._inner.__exit__(*exc)
def test_delete_right_after_a_fork_is_saved_removes_its_directory(clients, prepared, monkeypatch):
"""A fork lets go of its directory in the step that saves it: a delete from then on is an ordinary one."""
dp, job_id, folder = prepared
local, _ = clients
fork_id = new_id()
fork_dir = folder.parent / fork_id
persist, answers, watched, reached = dp._persist_job, [], {}, threading.Event()
monkeypatch.setattr(dp, "_dub_jobs_lock", _WatchedLock(dp._dub_jobs_lock, watched, reached))
def persist_then_delete(saved_id, *args, **kwargs):
persist(saved_id, *args, **kwargs)
if saved_id == fork_id and "thread" not in watched:
watched["thread"] = threading.Thread(
target=lambda: answers.append(local.delete(f"/dub/history/{fork_id}")), daemon=True,
)
watched["thread"].start()
assert reached.wait(10), "the delete asked for the job lock while the fork still held it"
monkeypatch.setattr(dp, "_persist_job", persist_then_delete)
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id
watched["thread"].join(10)
assert [answer.status_code for answer in answers] == [200]
assert not fork_dir.exists(), "the deleted fork's media are not left behind"
assert fork_id not in dp._dub_jobs and fork_id not in dp._job_dir_claims
dp._withdrawn_jobs.clear()
assert dp.get_job(fork_id) is None, "its row is gone"
for name in MEDIA:
assert (folder / name).is_file()
def test_fork_refuses_an_id_whose_directory_is_being_removed(prepared):
"""While a delete holds the id's directory, a fork of that id is refused and creates nothing."""
dp, job_id, folder = prepared
fork_id = new_id()
with dp.purge_jobs_claiming_dirs([fork_id], delete_rows=lambda: None) as removable:
assert removable == {fork_id}
with pytest.raises(FileExistsError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
assert fork_id not in dp._job_dir_claims and fork_id not in dp._inflight_jobs
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id
def test_purge_during_a_fork_does_not_hand_out_its_directory(prepared, monkeypatch):
"""The purge and the claim are one step: a running fork's directory is never the delete's to remove."""
dp, job_id, folder = prepared
fork_id, other = new_id(), new_id()
link, seen = dp._link_or_copy, []
def link_then_purge(src, dst):
link(src, dst)
if not seen:
with dp.purge_jobs_claiming_dirs([fork_id, other], delete_rows=lambda: None) as removable:
seen.append(set(removable))
monkeypatch.setattr(dp, "_link_or_copy", link_then_purge)
with pytest.raises(ValueError, match="deleted while it was being created"):
dp.fork_job(job_id, fork_id)
assert seen == [{other}]
assert not (folder.parent / fork_id).exists() and not dp._job_dir_claims
def test_delete_route_removes_a_finished_fork_and_only_that(clients, prepared):
"""Deleting a fork through the route removes its directory and leaves the source's media."""
dp, job_id, folder = prepared
local, _ = clients
fork_id = new_id()
dp.fork_job(job_id, fork_id)
assert local.delete(f"/dub/history/{fork_id}").status_code == 200
assert not (folder.parent / fork_id).exists() and fork_id not in dp._dub_jobs
for name in MEDIA:
assert (folder / name).is_file()
other = new_id()
dp.fork_job(job_id, other)
assert local.delete("/dub/history").status_code == 200
assert not (folder.parent / other).exists() and not dp._job_dir_claims
def test_fork_refuses_a_job_without_media(prepared):
"""A subtitle-only job has cues and no media, so there is nothing to fork."""
dp, _, folder = prepared
source_id, fork_id = "fork-subtitles-" + uuid.uuid4().hex, new_id()
(folder.parent / source_id).mkdir()
dp.put_job(source_id, {
"filename": "subtitles.srt", "duration": 2.0, "input_type": "audio", "subtitle_only": True,
"segments": [{"id": "0", "start": 0.0, "end": 2.0, "text": "A line."}], "dubbed_tracks": {},
})
with pytest.raises(ValueError, match="no prepared media"):
dp.fork_job(source_id, fork_id)
assert not (folder.parent / fork_id).exists()
assert fork_id not in dp._dub_jobs and fork_id not in dp._inflight_jobs
assert dp.get_job(source_id)["segments"], "the source keeps its cues"
@pytest.mark.parametrize("name", ["original.mp4", "audio.wav", "vocals.wav", "no_vocals.wav"])
def test_fork_refuses_a_source_that_lost_a_media_file(prepared, name):
"""A declared media file that is gone is refused, never carried into the new job."""
dp, job_id, folder = prepared
fork_id = new_id()
(folder / name).unlink()
with pytest.raises(ValueError, match=f"{name} is missing"):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
assert fork_id not in dp._dub_jobs and fork_id not in dp._inflight_jobs
dp._dub_jobs.pop(job_id)
assert dp.get_job(fork_id) is None, "nothing was saved"
def test_fork_of_a_source_whose_directory_is_gone_is_not_found(prepared):
"""A source deleted after it was looked up is reported as not found."""
dp, job_id, folder = prepared
fork_id = new_id()
shutil.rmtree(folder)
with pytest.raises(LookupError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
def test_fork_without_a_thumbnail_file_carries_none(prepared):
"""A missing thumbnail is optional: the fork is made without one."""
dp, job_id, folder = prepared
(folder / "thumb.jpg").unlink()
fork_id = new_id()
record = dp.fork_job(job_id, fork_id)
assert record["thumb_path"] is None
assert not (folder.parent / fork_id / "thumb.jpg").exists()
def test_moving_new_stems_into_a_job_leaves_a_forks_stems_alone(prepared):
"""Preparing a job again replaces its stems, so the fork's links keep the old audio."""
dp, job_id, folder = prepared
fork_id = new_id()
dp.fork_job(job_id, fork_id)
fork_vocals = folder.parent / fork_id / "vocals.wav"
before = fork_vocals.read_bytes()
fresh = folder / "htdemucs-vocals.wav"
sf.write(fresh, np.ones((44100, 2)) * 0.2, 44100)
expected = fresh.read_bytes()
dp._move_into_job(str(fresh), str(folder / "vocals.wav"))
assert (folder / "vocals.wav").read_bytes() == expected and not fresh.exists()
assert fork_vocals.read_bytes() == before
assert not os.path.samefile(fork_vocals, folder / "vocals.wav")
@pytest.mark.parametrize("publish", ["move", "copy"])
def test_a_stem_a_fork_shares_is_never_written_in_place(prepared, monkeypatch, publish):
"""When a shared stem's name cannot be replaced, preparation fails and both jobs keep their audio."""
dp, job_id, folder = prepared
fork_id = new_id()
dp.fork_job(job_id, fork_id)
fork_vocals = folder.parent / fork_id / "vocals.wav"
before = fork_vocals.read_bytes()
fresh = folder / "htdemucs-vocals.wav"
sf.write(fresh, np.ones((44100, 2)) * 0.2, 44100)
attempts = []
def locked(src, dst):
attempts.append(dst)
raise PermissionError(errno.EACCES, "Access is denied")
monkeypatch.setattr(dp.os, "replace", locked)
monkeypatch.setattr(dp, "_REPLACE_WAIT_S", 0)
publisher = dp._move_into_job if publish == "move" else dp._copy_into_job
with pytest.raises(PermissionError):
publisher(str(fresh), str(folder / "vocals.wav"))
assert len(attempts) == dp._REPLACE_TRIES, "the replacement is retried before giving up"
assert fork_vocals.read_bytes() == before and (folder / "vocals.wav").read_bytes() == before
assert os.path.samefile(fork_vocals, folder / "vocals.wav")
assert fresh.is_file(), "the new stem is not lost"
assert not [path.name for path in folder.iterdir() if path.name.endswith(".tmp")]
def test_moving_into_a_job_falls_back_when_the_name_cannot_be_replaced(prepared, monkeypatch, caplog):
"""A destination nothing else links still gets the new file in place, and the log says how."""
dp, _, folder = prepared
fresh = folder / "htdemucs-vocals.wav"
fresh.write_bytes(b"new stem")
def locked(src, dst):
raise PermissionError(errno.EACCES, "Access is denied")
monkeypatch.setattr(dp.os, "replace", locked)
with caplog.at_level(logging.INFO, logger="omnivoice.dub_pipeline"):
dp._move_into_job(str(fresh), str(folder / "vocals.wav"))
assert (folder / "vocals.wav").read_bytes() == b"new stem" and not fresh.exists()
assert "Prepared dub artifact moved in place (PermissionError)" in caplog.text
def test_link_or_copy_never_writes_over_an_existing_file(prepared):
"""An existing destination may be shared with another job, so it is left alone."""
dp, _, folder = prepared
target = folder / "already-there.wav"
target.write_bytes(b"keep")
with pytest.raises(FileExistsError):
dp._link_or_copy(str(folder / "vocals.wav"), str(target))
assert target.read_bytes() == b"keep"
def test_fork_of_a_source_deleted_midway_is_not_found(prepared, monkeypatch):
"""Media that vanish during the fork report the source as gone and clean up."""
dp, job_id, folder = prepared
fork_id = new_id()
def vanished(src, dst):
raise FileNotFoundError(errno.ENOENT, "No such file or directory")
monkeypatch.setattr(dp, "_link_or_copy", vanished)
with pytest.raises(LookupError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists()
def test_route_forks_once_and_reports_refusals(clients, prepared):
"""The route returns the new job, then maps each refusal to its status."""
dp, job_id, folder = prepared
local, _ = clients
fork_id = new_id()
response = local.post(f"/dub/fork/{job_id}", json={"job_id": fork_id})
assert response.status_code == 200, response.text
assert response.json() == {"job_id": fork_id, "forked_from": job_id, "duration": 2.0}
assert os.path.samefile(folder.parent / fork_id / "vocals.wav", folder / "vocals.wav")
assert local.post(f"/dub/fork/{job_id}", json={"job_id": fork_id}).status_code == 409
assert local.post(f"/dub/fork/{job_id}", json={"job_id": "../up"}).status_code == 422
assert local.post(f"/dub/fork/{job_id}", json={}).status_code == 422
unknown = "fork-unknown-" + uuid.uuid4().hex
assert local.post(f"/dub/fork/{unknown}", json={"job_id": new_id()}).status_code == 404
held = new_id()
dp.begin_ingest(held)
assert local.post(f"/dub/fork/{job_id}", json={"job_id": held}).status_code == 409
dp.get_job(job_id)["audio_path"] = None
response = local.post(f"/dub/fork/{job_id}", json={"job_id": new_id()})
assert (response.status_code, response.json()["detail"]) == (400, "This job has no prepared media to fork")
dp.get_job(job_id)["audio_path"] = str(folder / "audio.wav")
dp._inflight_jobs.add(job_id)
assert local.post(f"/dub/fork/{job_id}", json={"job_id": new_id()}).status_code == 400
def test_route_requires_admin(clients, prepared):
"""A remote caller without administrator access cannot fork a job."""
_, job_id, folder = prepared
_, remote = clients
fork_id = new_id()
assert remote.post(f"/dub/fork/{job_id}", json={"job_id": fork_id}).status_code == 403
assert not (folder.parent / fork_id).exists()
def test_route_reports_a_full_disk(clients, prepared, monkeypatch):
"""Running out of space while copying is a 507, not an unexplained 500."""
dp, job_id, _ = prepared
local, _ = clients
def full(source_id, fork_id):
raise OSError(errno.ENOSPC, "No space left on device")
monkeypatch.setattr(dp, "fork_job", full)
response = local.post(f"/dub/fork/{job_id}", json={"job_id": new_id()})
assert response.status_code == 507
assert "disk space" in response.json()["detail"]
def test_fork_carries_the_media_language(prepared):
"""Captions and the original-audio tag read the spoken language the source recorded."""
dp, job_id, _ = prepared
dp.get_job(job_id)["media_language"] = "en"
assert dp.fork_job(job_id, new_id())["media_language"] == "en"
def test_clear_history_during_the_directory_claim_withdraws_the_fork(prepared, monkeypatch):
"""The fork is in progress from the claim on, before its directory exists."""
dp, job_id, folder = prepared
fork_id = new_id()
makedirs, seen = os.makedirs, []
def clear_then_make(path, *args, **kwargs):
if os.path.basename(path) == fork_id:
seen.append(fork_id in dp._inflight_jobs)
dp.purge_jobs([], delete_rows=lambda: None, include_inflight=True)
return makedirs(path, *args, **kwargs)
monkeypatch.setattr(os, "makedirs", clear_then_make)
with pytest.raises(ValueError, match="deleted while it was being created"):
dp.fork_job(job_id, fork_id)
assert seen == [True]
assert not (folder.parent / fork_id).exists() and fork_id not in dp._dub_jobs
def test_failed_directory_creation_frees_the_id(prepared, monkeypatch):
"""A fork that cannot create its directory leaves no in-progress mark or claim."""
dp, job_id, folder = prepared
fork_id = new_id()
monkeypatch.setattr(os, "makedirs", lambda *a, **k: (_ for _ in ()).throw(OSError(errno.EACCES, "denied")))
with pytest.raises(OSError):
dp.fork_job(job_id, fork_id)
assert fork_id not in dp._inflight_jobs and fork_id not in dp._job_dir_claims
def test_clear_history_selects_its_ids_in_the_locked_step(prepared):
"""Ids chosen by a callable are read after the lock is held and cover every row removed."""
dp, job_id, _ = prepared
held = []
def select():
held.append(dp._dub_jobs_lock._is_owned())
return [job_id]
with dp.purge_jobs_claiming_dirs(select, delete_rows=lambda: None) as removable:
assert removable == {job_id}
assert held == [True]
def test_fork_aborts_when_the_source_is_replaced_midway(prepared, monkeypatch):
"""A source deleted and made again while the media are shared does not lend its new media to the old record."""
dp, job_id, folder = prepared
fork_id = new_id()
link, seen = dp._link_or_copy, []
def replace_source_then_link(src, dst):
if not seen:
seen.append(1)
dp._dub_jobs[job_id] = dict(dp._dub_jobs[job_id])
link(src, dst)
monkeypatch.setattr(dp, "_link_or_copy", replace_source_then_link)
with pytest.raises(LookupError):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists() and fork_id not in dp._dub_jobs
assert fork_id not in dp._inflight_jobs and fork_id not in dp._job_dir_claims
def test_a_retry_clears_the_directory_a_failed_cleanup_left(prepared, monkeypatch, caplog):
"""When removing an abandoned fork's files fails, the same id works on the next attempt."""
dp, job_id, folder = prepared
fork_id = new_id()
fork_dir = folder.parent / fork_id
rmtree = shutil.rmtree
def refuse(path, *args, onerror=None, **kwargs):
onerror(os.remove, os.path.join(path, "original.mp4"), (PermissionError, PermissionError(), None))
def broken(*args, **kwargs):
raise RuntimeError("database unavailable")
with monkeypatch.context() as patch, caplog.at_level(logging.ERROR):
patch.setattr(dp, "_persist_job", broken)
patch.setattr(shutil, "rmtree", refuse)
with pytest.raises(RuntimeError):
dp.fork_job(job_id, fork_id)
assert fork_dir.is_dir() and (fork_dir / dp._FORK_MARKER).is_file()
assert "could not remove" in caplog.text
assert fork_id not in dp._inflight_jobs and fork_id not in dp._job_dir_claims
assert dp.fork_job(job_id, fork_id)["forked_from"] == job_id
assert not (fork_dir / dp._FORK_MARKER).exists(), "a saved fork carries no marker"
# A directory without the marker is a job's: never cleared.
other = new_id()
(folder.parent / other).mkdir()
with pytest.raises(FileExistsError):
dp.fork_job(job_id, other)
assert (folder.parent / other).is_dir()
assert rmtree is shutil.rmtree
def test_fork_refuses_a_borrowed_media_file_that_is_gone(prepared):
"""A carried path to a missing stem is rejected rather than saved; a missing thumbnail is dropped."""
dp, job_id, folder = prepared
gone = folder.parent / "another-job" / "vocals.wav"
job = dp.get_job(job_id)
job["vocals_path"] = str(gone)
fork_id = new_id()
with pytest.raises(ValueError, match="vocals.wav"):
dp.fork_job(job_id, fork_id)
assert not (folder.parent / fork_id).exists() and fork_id not in dp._inflight_jobs
job["vocals_path"] = str(folder / "vocals.wav")
job["thumb_path"] = str(folder.parent / "another-job" / "thumb.jpg")
assert dp.fork_job(job_id, fork_id)["thumb_path"] is None
def test_a_withdrawal_marker_outlives_the_limits_while_its_claim_is_held(prepared, monkeypatch):
"""Age and size pruning keep the marker of an id a running fork still holds."""
dp, _, _ = prepared
held = new_id()
monkeypatch.setattr(dp, "_WITHDRAWN_MAX", 1)
dp._job_dir_claims.add(held)
dp._withdrawn_jobs[held] = 0.0
for index in range(3):
dp._withdrawn_jobs[f"later-{index}"] = 10.0 ** 9
dp._expire_withdrawn(10.0 ** 9 + dp._WITHDRAWN_TTL_S * 2)
assert held in dp._withdrawn_jobs, "age"
dp._withdrawn_jobs.update({f"newer-{index}": time.monotonic() for index in range(5)})
dp._expire_withdrawn(time.monotonic())
assert held in dp._withdrawn_jobs, "size"
dp._release_job_dir(held)
dp._expire_withdrawn(10.0 ** 9 + dp._WITHDRAWN_TTL_S * 2)
assert held not in dp._withdrawn_jobs
def test_fork_does_not_inherit_a_stale_history_row(prepared):
"""An id whose row outlived its directory is a conflict, not a record to merge into."""
dp, job_id, folder = prepared
stale = new_id()
dp.save_job(stale, {"language": "French", "language_code": "fr"}, "old.mp4", 1.0, "oldhash")
with pytest.raises(FileExistsError):
dp.fork_job(job_id, stale)
assert not (folder.parent / stale).exists() and stale not in dp._inflight_jobs
def test_route_documents_its_response():
"""The OpenAPI contract names the fork response fields."""
from fastapi import FastAPI
app = FastAPI()
app.include_router(importlib.import_module("api.routers.dub_core").router)
schema = app.openapi()["components"]["schemas"]["DubForkResponse"]
assert {"job_id", "forked_from", "duration"} <= set(schema["properties"])