fix(dl): stop a failed mux with one line that names the free space

This commit is contained in:
imSp4rky
2026-11-28 15:26:38 -07:00
parent 418d69b1ec
commit 74856d2ddb
7 changed files with 145 additions and 38 deletions
+1 -1
View File
@@ -309,7 +309,7 @@ Each command reports how many files it removed and how much space it freed, then
**Inspect:** the connection to the CDN host dropped on every attempt. This is almost always the network, the VPN, or the proxy, not the service. Run the download again: unshackle keeps the segments it already has. Over HTTP/2, all segments share one connection, so one drop fails every segment in flight. Set `network.http1_only: true` (see [Network & proxy](../reference/configuration/network.md)) to spread them over separate connections. Operate unshackle with `-d` to see each retry as a `segment_retry` entry in the JSON debug log. **Inspect:** the connection to the CDN host dropped on every attempt. This is almost always the network, the VPN, or the proxy, not the service. Run the download again: unshackle keeps the segments it already has. Over HTTP/2, all segments share one connection, so one drop fails every segment in flight. Set `network.http1_only: true` (see [Network & proxy](../reference/configuration/network.md)) to spread them over separate connections. Operate unshackle with `-d` to see each retry as a `segment_retry` entry in the JSON debug log.
!!! example "The temp directory is nearly full" !!! example "The temp directory is nearly full"
**Symptom:** the failure line ends with the free space of the temp volume, for example `CalledProcessError: Command '[...]' returned non-zero exit status 2, 38.0 MB free on C:\unshackle\temp`. A tool such as shaka-packager often reports a full disk only as a write failure. **Symptom:** the failure line ends with the free space of the temp volume, for example `CalledProcessError: Command '[...]' returned non-zero exit status 2, 38.0 MB free on C:\unshackle\temp`. A tool such as shaka-packager often reports a full disk only as a write failure. A full disk during the mux gives a line like `mkvmerge failed (exit 2): An exception occurred when writing the destination file. The drive may be full. ..., 38.0 MB free on C:\unshackle\temp`.
Before the track downloads start, a warning can also show the problem, for example `Temp volume C:\unshackle\temp has 3.1 GB free, the selected tracks need about 9.4 GB`. unshackle gives this warning when the free space is less than two times the estimated size of the video and audio tracks of the title. The factor is two because each encrypted track and its decrypted copy are on the temp volume together. The estimate is the manifest bitrate multiplied by the playing time, so only DASH and ISM tracks get it: an HLS or URL track gives no warning. The warning does not stop the download, and `--skip-dl` and `--sample` runs do not check. Before the track downloads start, a warning can also show the problem, for example `Temp volume C:\unshackle\temp has 3.1 GB free, the selected tracks need about 9.4 GB`. unshackle gives this warning when the free space is less than two times the estimated size of the video and audio tracks of the title. The factor is two because each encrypted track and its decrypted copy are on the temp volume together. The estimate is the manifest bitrate multiplied by the playing time, so only DASH and ISM tracks get it: an HLS or URL track gives no warning. The warning does not stop the download, and `--skip-dl` and `--sample` runs do not check.
+72
View File
@@ -0,0 +1,72 @@
"""A failed mkvmerge stops the run with one line that names the tool, its exit and its error."""
import logging
from pathlib import Path
import pytest
from unshackle.core import binaries
from unshackle.core.config import config
from unshackle.core.mux_step import mux_title
from unshackle.core.placement import Placement
from unshackle.core.run_plan import RunStopped
from unshackle.core.titles import Movie
from unshackle.core.tracks import Video
from unshackle.core.tracks import tracks as tracks_module
pytestmark = pytest.mark.skipif(not Path("/bin/sh").exists(), reason="needs a POSIX shell for the mkvmerge stub")
def mux(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, script: str) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
stub = tmp_path / "mkvmerge"
stub.write_text(f"#!/bin/sh\n{script}\n")
stub.chmod(0o755)
monkeypatch.setattr(binaries, "MKVToolNix", stub)
monkeypatch.setattr(tracks_module, "file_track_ids", lambda path: {"video": 0})
movie = Movie(id_="movie-0001", service=type("EXAMPLE", (), {}), name="Some Movie", year=2024)
video = Video(url="https://x.example/v.m3u8", language="en", codec=Video.Codec.AVC, id_="v")
video.path = tmp_path / "v.mp4"
video.path.write_bytes(b"video")
movie.tracks.add(video)
mux_title(
movie,
Placement(movie, root=tmp_path / "out", no_folder=True, no_source=True, sample=False),
log=logging.getLogger("dl"),
service_tag="EXAMPLE",
split_audio=None,
merge_video=None,
audio_expected=False,
skip_subtitles=True,
quality=[],
range_=[],
vcodec=[],
generate_dv=False,
progress_sink=None,
write_sidecars=None,
)
def test_a_write_error_is_the_reason_of_the_stop(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
error = "The drive may be full. Exception details: No space left to write to"
with pytest.raises(RunStopped) as raised:
mux(tmp_path, monkeypatch, f"echo '#GUI#warning a minor thing'\necho '#GUI#error {error}'\nexit 2")
assert raised.value.reason == f"mkvmerge failed (exit 2): {error}"
assert [r.levelno for r in caplog.records if r.name == "dl" and r.levelno > logging.DEBUG] == [logging.WARNING]
def test_a_failure_with_no_error_line_names_the_exit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
with pytest.raises(RunStopped) as raised:
mux(tmp_path, monkeypatch, "exit 2")
assert raised.value.reason == "mkvmerge failed (exit 2)"
def test_a_killed_muxer_stops_the_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
with pytest.raises(RunStopped) as raised:
mux(tmp_path, monkeypatch, "kill -9 $$")
assert raised.value.reason == "mkvmerge failed (signal 9)"
+20 -1
View File
@@ -28,7 +28,10 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest import pytest
from requests import Session from requests import Session
from tests.downloaders.test_outage_budget import _FullDisk
from unshackle.core.api.errors import categorize_exception
from unshackle.core.constants import DownloadCancelled from unshackle.core.constants import DownloadCancelled
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.utils.sslciphers import SSLCiphers from unshackle.core.utils.sslciphers import SSLCiphers
dl = importlib.import_module("unshackle.core.downloaders.requests") dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -103,6 +106,11 @@ def die_without_result(queue, kwargs):
os._exit(3) os._exit(3)
def full_disk_worker(queue, kwargs):
dl.open = _FullDisk
dl.mp_worker(queue, kwargs)
def run_mp(urls, tmp_path): def run_mp(urls, tmp_path):
for _ in dl.download_multiprocess( for _ in dl.download_multiprocess(
urls=urls, urls=urls,
@@ -148,9 +156,20 @@ def test_multiprocess_child_crash_raises(server, tmp_path):
# any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally. # any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally.
good = {"url": url(server, "/seg/0.bin")} good = {"url": url(server, "/seg/0.bin")}
bad = {"nourl": True} bad = {"nourl": True}
with pytest.raises(RuntimeError): with pytest.raises(RuntimeError) as raised:
run_mp([good, bad], tmp_path) run_mp([good, bad], tmp_path)
assert not hasattr(raised.value, "error_code")
def test_a_full_disk_in_a_child_keeps_its_download_error_code(server, tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", full_disk_worker)
with pytest.raises(RuntimeError) as raised:
run_mp([{"url": url(server, "/seg/0.bin")}, {"url": url(server, "/seg/1.bin")}], tmp_path)
assert dl.retries_exhausted(raised.value)
assert categorize_exception(raised.value).error_code == APIErrorCode.DOWNLOAD_ERROR
def test_multiprocess_child_death_raises(tmp_path, monkeypatch): def test_multiprocess_child_death_raises(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", die_without_result) monkeypatch.setattr(dl, "mp_worker", die_without_result)
+5
View File
@@ -2543,6 +2543,7 @@ class dl:
self.completed_files.append(final_path) self.completed_files.append(final_path)
self.log.debug(f"Saved: {final_path.name}") self.log.debug(f"Saved: {final_path.name}")
elif isinstance(title, (Movie, Episode)): elif isinstance(title, (Movie, Episode)):
try:
outputs, mux_sidecars = mux_title( outputs, mux_sidecars = mux_title(
title, title,
placement, placement,
@@ -2566,6 +2567,10 @@ class dl:
if sidecar_subtitles if sidecar_subtitles
else None, else None,
) )
except RunStopped as stopped:
stopped.reason += low_free_space(stopped)
self.log.error(stopped.reason)
raise
sidecar_files.update(mux_sidecars) sidecar_files.update(mux_sidecars)
for temp_path in sidecar_original_paths.values(): for temp_path in sidecar_original_paths.values():
temp_path.unlink(missing_ok=True) temp_path.unlink(missing_ok=True)
+7 -2
View File
@@ -1361,8 +1361,8 @@ def mp_worker(queue: Any, kwargs: dict[str, Any]) -> None:
"""Child entry point (top-level so ``spawn`` can pickle it). """Child entry point (top-level so ``spawn`` can pickle it).
Rebuilds the HTTP session, iterates ``requests()`` for its url slice, and relays every event Rebuilds the HTTP session, iterates ``requests()`` for its url slice, and relays every event
over the shared queue. Errors travel as a ``__mp_error__`` sentinel. This child always sends a over the shared queue. Errors travel as a ``__mp_error__`` sentinel with the notes and API error code of the
``__mp_done__`` sentinel last, so the parent knows that this child is complete. error. This child always sends a ``__mp_done__`` sentinel last, so the parent knows that this child is complete.
""" """
try: try:
# spawn re-imports this module, dropping any timing constants the bench patched in # spawn re-imports this module, dropping any timing constants the bench patched in
@@ -1387,6 +1387,9 @@ def mp_worker(queue: Any, kwargs: dict[str, Any]) -> None:
"__mp_error__": " ".join(f"{type(exc).__name__}: {exc}".split()), "__mp_error__": " ".join(f"{type(exc).__name__}: {exc}".split()),
"__mp_traceback__": traceback.format_exc(), "__mp_traceback__": traceback.format_exc(),
"__mp_notes__": [str(note) for note in getattr(exc, "__notes__", ())], "__mp_notes__": [str(note) for note in getattr(exc, "__notes__", ())],
"__mp_error_code__": code
if isinstance(code := getattr(exc, "error_code", None), APIErrorCode)
else None,
} }
) )
finally: finally:
@@ -1508,6 +1511,8 @@ def download_multiprocess(
child_error = RuntimeError(f"segment download child failed: {event['__mp_error__']}") child_error = RuntimeError(f"segment download child failed: {event['__mp_error__']}")
for note in event.get("__mp_notes__", ()): for note in event.get("__mp_notes__", ()):
child_error.add_note(note) child_error.add_note(note)
if code := event.get("__mp_error_code__"):
coded(child_error, code)
raise child_error raise child_error
if "total" in event: if "total" in event:
continue continue
+17 -11
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import logging import logging
import shutil import shutil
import sys
from collections.abc import Callable, Sequence from collections.abc import Callable, Sequence
from concurrent import futures from concurrent import futures
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
@@ -21,6 +20,7 @@ from rich.progress import Progress, SpinnerColumn, TaskID, TextColumn, TimeRemai
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, SyncLive, console from unshackle.core.console import GradientPulseBarColumn, SyncLive, console
from unshackle.core.placement import Placement from unshackle.core.placement import Placement
from unshackle.core.run_plan import RunStopped
from unshackle.core.titles import Movie from unshackle.core.titles import Movie
from unshackle.core.titles.episode import Episode from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Tracks, Video from unshackle.core.tracks import Audio, Tracks, Video
@@ -28,6 +28,7 @@ from unshackle.core.tracks.dv_fixup import apply_dv_fixup
from unshackle.core.tracks.hybrid import Hybrid from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.selection import select_hybrid_bases from unshackle.core.tracks.selection import select_hybrid_bases
from unshackle.core.utilities import standard_resolution from unshackle.core.utilities import standard_resolution
from unshackle.core.utils.subprocess import tool_reason
MuxOutput = tuple[Path, Audio.Codec | None] MuxOutput = tuple[Path, Audio.Codec | None]
@@ -113,7 +114,7 @@ def mux_title(
"""Mux the tracks of a title, then delete them; the muxed files and the sidecar files of each. """Mux the tracks of a title, then delete them; the muxed files and the sidecar files of each.
Each output is a muxed file with the audio codec it holds when the audio is split by codec. Each output is a muxed file with the audio codec it holds when the audio is split by codec.
A failed mux exits the run. A failed mux stops the run with RunStopped, whose reason names the muxer, its exit and its error.
""" """
outputs: list[MuxOutput] = [] outputs: list[MuxOutput] = []
sidecars: dict[Path | None, list[Path]] = {} sidecars: dict[Path | None, list[Path]] = {}
@@ -232,7 +233,6 @@ def mux_title(
try: try:
with SyncLive(Padding(progress, (0, 5, 1, 5)), console=console, refresh_per_second=20): with SyncLive(Padding(progress, (0, 5, 1, 5)), console=console, refresh_per_second=20):
mux_failed = False
mux_concurrency = max(1, int(config.muxing.get("concurrency", 4))) mux_concurrency = max(1, int(config.muxing.get("concurrency", 4)))
with ( with (
@@ -310,23 +310,29 @@ def mux_title(
mux_video_group(group) mux_video_group(group)
mux_results = [f.result() for f in mux_futures] mux_results = [f.result() for f in mux_futures]
failure: str | None = None
for (_, _, audio_codec), (muxed_path, return_code, errors) in zip( for (_, _, audio_codec), (muxed_path, return_code, errors) in zip(
multiplex_tasks, mux_results, strict=True multiplex_tasks, mux_results, strict=True
): ):
outputs.append((muxed_path, audio_codec)) outputs.append((muxed_path, audio_codec))
if return_code >= 2: failed = return_code >= 2 or return_code < 0
log.error(f"Failed to Mux video to Matroska file ({return_code}):") error_lines = [e for e in errors if not e.startswith("#GUI#warning")]
elif return_code == 1 or errors: if failed and not failure:
tool = "MP4Box" if muxed_path.suffix == ".mp4" else "mkvmerge"
exit_text = f"signal {-return_code}" if return_code < 0 else f"exit {return_code}"
reason = tool_reason("\n".join(e.removeprefix("#GUI#error") for e in error_lines))
failure = f"{tool} failed ({exit_text}){f': {reason}' if reason else ''}"
elif not failed and (return_code == 1 or errors):
log.warning("mkvmerge had at least one warning or error, continuing anyway...") log.warning("mkvmerge had at least one warning or error, continuing anyway...")
for line in errors: for line in errors:
if line.startswith("#GUI#error"): if failed and line in error_lines:
log.debug(line)
elif line.startswith("#GUI#error"):
log.error(line) log.error(line)
else: else:
log.warning(line) log.warning(line)
if return_code >= 2: if failure:
mux_failed = True raise RunStopped(failure)
if mux_failed:
sys.exit(1)
if write_sidecars: if write_sidecars:
sidecar_targets: list[tuple[Path | None, str, Path]] = [] sidecar_targets: list[tuple[Path | None, str, Path]] = []
+1 -1
View File
@@ -28,7 +28,7 @@ class PlanError(click.ClickException):
class RunStopped(SystemExit): class RunStopped(SystemExit):
"""A run that a missing track or language stopped, with the reason dl logged.""" """A run that a missing track or language or a failed mux stopped, with the reason dl logged."""
def __init__(self, reason: str) -> None: def __init__(self, reason: str) -> None:
super().__init__(1) super().__init__(1)