refactor(temp): read the free space where the failed step deletes its temp files

This commit is contained in:
imSp4rky
2026-11-29 15:23:03 -07:00
parent 977cbe4aa8
commit 1ebc3e3624
13 changed files with 155 additions and 59 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.
!!! 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. 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`.
**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`. A hybrid step that fails on a full disk gives a line like `Hybrid 2160p failed, skipping it: [Errno 28] No space left on device, 38.0 MB free on C:\unshackle\temp`.
Before or during the track downloads, 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.
+34 -16
View File
@@ -2,6 +2,7 @@
import shutil
import subprocess
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -9,10 +10,13 @@ from typing import Any
import click
import pytest
from unshackle.commands import dl as dl_module
from unshackle.commands.dl import dl
from unshackle.core import temp as temp_module
from unshackle.core.config import config
from unshackle.core.temp import TASK_PREFIX
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.manifests import DASH
from unshackle.core.temp import LOW_FREE_SPACE, TASK_PREFIX
from unshackle.core.tracks import Video
@pytest.fixture
@@ -27,9 +31,9 @@ def free_space(monkeypatch: pytest.MonkeyPatch, free: int) -> list[str]:
def usage(path: Any) -> Any:
reads.append(str(path))
return shutil._ntuple_diskusage(10 * dl_module.LOW_FREE_SPACE, 0, free) # type: ignore[attr-defined]
return shutil._ntuple_diskusage(10 * LOW_FREE_SPACE, 0, free) # type: ignore[attr-defined]
monkeypatch.setattr(dl_module.shutil, "disk_usage", usage)
monkeypatch.setattr(temp_module.shutil, "disk_usage", usage)
return reads
@@ -43,7 +47,7 @@ def test_a_nearly_full_temp_volume_is_named_on_the_line(temp: Path, monkeypatch:
def test_enough_free_space_leaves_the_line_as_it_was(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
free_space(monkeypatch, dl_module.LOW_FREE_SPACE)
free_space(monkeypatch, LOW_FREE_SPACE)
error = ValueError("boom")
assert dl.failure_lines(error) == [":x: Download Failed...", " ValueError: boom"]
@@ -59,7 +63,7 @@ def test_a_later_report_reuses_the_first_reading(temp: Path, monkeypatch: pytest
reads = free_space(monkeypatch, 38_000_000)
error = OSError(28, "No space left on device")
first = dl.failure_lines(error)
free_space(monkeypatch, 5 * dl_module.LOW_FREE_SPACE)
free_space(monkeypatch, 5 * LOW_FREE_SPACE)
assert dl.failure_lines(error) == first
assert len(reads) == 1
@@ -80,18 +84,32 @@ def test_a_task_temp_dir_is_named_by_the_temp_dir_that_holds_it(temp: Path, monk
assert reads == [str(temp)]
def test_a_failed_decrypt_is_read_before_its_track_deletes_its_files(
temp: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
free_space(monkeypatch, 38_000_000)
failure = subprocess.CalledProcessError(2, ["packager"])
def test_a_failed_track_is_read_before_it_deletes_its_files(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
written = temp / "Video_v.mp4"
seen: list[bool] = []
failure = OSError(28, "No space left on device")
def decrypt(*args: Any, **kwargs: Any) -> None:
def usage(path: Any) -> Any:
seen.append(written.exists())
return SimpleNamespace(free=38_000_000)
def parser(track: Video, ctx: Any) -> None:
written.write_bytes(b"partial")
raise failure
run = SimpleNamespace(keys=SimpleNamespace(decrypt_verified=decrypt))
with pytest.raises(subprocess.CalledProcessError):
dl.decrypt_verified(run, "drm", temp / "video.mp4", track=None) # type: ignore[arg-type]
free_space(monkeypatch, 5 * dl_module.LOW_FREE_SPACE)
monkeypatch.setattr(temp_module.shutil, "disk_usage", usage)
monkeypatch.setattr(DASH, "download_track", staticmethod(parser))
DOWNLOAD_CANCELLED.clear()
DOWNLOAD_LICENCE_ONLY.clear()
track = Video(
url="https://x.example/v.mpd", language="en", codec=Video.Codec.AVC, id_="v", descriptor=Video.Descriptor.DASH
)
with pytest.raises(OSError):
track.download( # type: ignore[arg-type]
session=SimpleNamespace(proxies={}), prepare_drm=partial(lambda: None), progress=partial(lambda **kw: None)
)
free_space(monkeypatch, 5 * LOW_FREE_SPACE)
assert seen == [True]
assert not written.exists()
assert dl.failure_lines(failure)[1].endswith(f", 38.0 MB free on {temp}")
+1 -1
View File
@@ -42,7 +42,7 @@ def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook(
)
keys = cmd.keys
assert verify.DECRYPT_HOOK == cmd.decrypt_verified
assert verify.DECRYPT_HOOK == cmd.keys.decrypt_verified
assert (keys.cdm_only, keys.vaults_only, keys.best_available) == (cdm_only, vaults_only, best_available)
assert keys.source is cmd._remote_service and keys.service is service and keys.cdms is cmd
assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE"
+29 -1
View File
@@ -21,7 +21,7 @@ import unshackle.commands.dl as dl_module
from tests.admission import refusal
from tests.remote.sessions import launch_session
from tests.remote.unit.test_remote_service_helpers import _sent_create_data
from unshackle.core import mux_step
from unshackle.core import mux_step, temp
from unshackle.core.api import download_manager, handlers, key_policy
from unshackle.core.config import config
from unshackle.core.mux_step import hybrid_plan, hybrid_source_tracks, hybrid_step_error, missing_hybrid_error
@@ -705,10 +705,38 @@ def test_a_hybrid_failure_is_reported_so_the_title_goes_on(monkeypatch: pytest.M
raise error
monkeypatch.setattr(mux_step, "Hybrid", failed_hybrid)
monkeypatch.setattr(temp, "LOW_FREE_SPACE", 0)
assert hybrid_step_error([], "TEST", "HDR10-DV-2160p.hevc") == str(error)
def test_a_hybrid_that_fills_the_temp_volume_names_the_free_space_before_its_files_go(
quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
base = tmp_path / "base.mkv"
base.write_bytes(b"")
stream = tmp_path / "HDR10.hevc"
present: list[bool] = []
def full(self: Hybrid) -> None:
stream.write_bytes(b"hevc")
raise OSError(28, "No space left on device")
def usage(path: Any) -> Any:
present.append(stream.exists())
return SimpleNamespace(free=38_000_000)
stub_hybrid_steps(monkeypatch, "measure_dv", "level_6")
monkeypatch.setattr(Hybrid, "injecting", full)
monkeypatch.setattr(temp.shutil, "disk_usage", usage)
video = SimpleNamespace(id="b", path=base, width=None, height=2160, range=Video.Range.HDR10)
error = hybrid_step_error([video], "TEST", "HDR10-DV-2160p.hevc") # type: ignore[list-item]
assert error == f"[Errno 28] No space left on device, 38.0 MB free on {tmp_path}"
assert present == [True] and not stream.exists()
def test_a_working_hybrid_reports_no_error_and_an_exit_passes_through(monkeypatch: pytest.MonkeyPatch) -> None:
seen: dict[str, Any] = {}
monkeypatch.setattr(mux_step, "Hybrid", lambda tracks, source, output_name: seen.update(name=output_name))
+2 -2
View File
@@ -17,8 +17,8 @@ import pytest
from pywidevine.pssh import PSSH
from tests.core.key_resolver import key_table, resolver, vaults_of
from unshackle.commands import dl as dl_module
from unshackle.commands.dl import dl
from unshackle.core import temp
from unshackle.core.drm import Widevine, key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.import_service import ImportService
@@ -119,7 +119,7 @@ def test_the_retry_after_a_bad_vault_key_ends_in_the_import_error(
def test_a_download_stopped_by_a_click_exception_reports_only_its_message(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl_module, "LOW_FREE_SPACE", 0)
monkeypatch.setattr(temp, "LOW_FREE_SPACE", 0)
error = ImportService.missing_key(SimpleNamespace(drm=[FakeDRM({})]))
lines = dl.failure_lines(error)
+29
View File
@@ -2,10 +2,13 @@
import logging
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from unshackle.core import binaries
from unshackle.core import temp as temp_module
from unshackle.core.config import config
from unshackle.core.mux_step import mux_title
from unshackle.core.placement import Placement
@@ -17,6 +20,11 @@ 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")
@pytest.fixture(autouse=True)
def roomy_temp(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(temp_module, "LOW_FREE_SPACE", 0)
def mux(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, script: str) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
stub = tmp_path / "mkvmerge"
@@ -70,3 +78,24 @@ def test_a_killed_muxer_stops_the_run(tmp_path: Path, monkeypatch: pytest.Monkey
mux(tmp_path, monkeypatch, "kill -9 $$")
assert raised.value.reason == "mkvmerge failed (signal 9)"
def test_the_stop_names_a_nearly_full_temp_volume_read_before_the_temp_files_go(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
rpu = tmp_path / "RPU.bin"
rpu.write_bytes(b"rpu")
seen: list[bool] = []
def usage(path: Any) -> Any:
seen.append(rpu.exists())
return SimpleNamespace(free=38_000_000)
monkeypatch.setattr(temp_module, "LOW_FREE_SPACE", 1024**3)
monkeypatch.setattr(temp_module.shutil, "disk_usage", usage)
with pytest.raises(RunStopped) as raised:
mux(tmp_path, monkeypatch, "exit 2")
assert raised.value.reason == f"mkvmerge failed (exit 2), 38.0 MB free on {tmp_path}"
assert seen == [True]
assert not rpu.exists()
+17
View File
@@ -13,6 +13,7 @@ from uuid import UUID
import pytest
from tests.core.test_all_drm import playready, widevine
from unshackle.core import temp
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, MonaLisa, verify
from unshackle.core.events import events
@@ -192,6 +193,22 @@ def test_a_failure_closes_the_decrypter_and_removes_the_output(tmp_path, seen):
assert not ctx.save_path.exists()
def test_a_failed_rolling_merge_reads_the_free_space_before_it_removes_the_output(tmp_path, monkeypatch):
ctx = make_ctx(tmp_path)
present: list[bool] = []
def usage(path: Any) -> Any:
present.append(ctx.save_path.exists())
return SimpleNamespace(free=38_000_000)
monkeypatch.setattr(temp.shutil, "disk_usage", usage)
with pytest.raises(ConnectionError) as raised:
fetch(ctx, FakeDownloader(fail_after=2), rolling=True, init=INIT)
assert present == [True] and not ctx.save_path.exists()
assert temp.low_free_space(raised.value).startswith(", 38.0 MB free on ")
def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path):
ctx = make_ctx(tmp_path)
ctx.save_path.write_bytes(INIT)
+2 -33
View File
@@ -81,7 +81,7 @@ from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.run_plan import PlanError, RunOutcome, RunStopped, bitrate_range, check_options
from unshackle.core.service import grow_session_pool
from unshackle.core.services import ROUTING_PARAMS, Services
from unshackle.core.temp import temp_root, with_task_temp
from unshackle.core.temp import low_free_space, temp_root, with_task_temp
from unshackle.core.title_metadata import Enrichment, TitleMetadata, apply_enrich
from unshackle.core.title_source import KeyArrival, TitleSource
from unshackle.core.titles import Movie, Movies, Series, Song, Title_T
@@ -385,28 +385,6 @@ def download_tracks_in_passes(
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
LOW_FREE_SPACE = 1024**3
"""Free bytes on the temp volume below which a failure line names them."""
def low_free_space(e: BaseException) -> str:
"""``", 38.0 MB free on <temp>"`` when the temp volume is nearly full at ``e``'s first report, else empty.
The reading is kept on ``e``: a failed track deletes its files before the run reports it, and the
API job reports it again after the task temp dir is gone, so the first reading is the true one.
"""
if (cached := getattr(e, "free_space", None)) is not None:
return str(cached)
temp = temp_root()
try:
free = shutil.disk_usage(temp).free
except OSError:
free = LOW_FREE_SPACE
note = f", {filesize.decimal(free)} free on {temp}" if free < LOW_FREE_SPACE else ""
e.free_space = note # type: ignore[attr-defined]
return note
DISK_NEED_FACTOR = 2
"""Times its estimated track size that a title needs on the temp volume: each encrypted track and its decrypted copy."""
@@ -2590,7 +2568,6 @@ class dl:
else None,
)
except RunStopped as stopped:
stopped.reason += low_free_space(stopped)
self.log.error(stopped.reason)
raise
sidecar_files.update(mux_sidecars)
@@ -3026,15 +3003,7 @@ class dl:
export=partial(self.write_export, export) if export else None,
debug_logger=self.debug_logger,
)
verify.DECRYPT_HOOK = self.decrypt_verified
def decrypt_verified(self, *args: Any, **kwargs: Any) -> None:
"""The run's verified decrypt, which reads the free space of a failed decrypt before its track deletes its files."""
try:
self.keys.decrypt_verified(*args, **kwargs)
except Exception as e:
low_free_space(e)
raise
verify.DECRYPT_HOOK = self.keys.decrypt_verified
def cdm_for(self, system: str, quality: int | None = None) -> object | None:
"""Get the CDM for one DRM system, ``widevine`` or ``playready``.
+3 -1
View File
@@ -23,6 +23,7 @@ from unshackle.core.drm.verify import decrypt_track, has_encrypted_sample_entry
from unshackle.core.events import events
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.session import AnySession
from unshackle.core.temp import low_free_space
from unshackle.core.tracks import DownloadContext, Track
from unshackle.core.tracks.segment_store import SegmentStore, decrypted
from unshackle.core.tracks.track import assert_fragments_decrypted
@@ -230,10 +231,11 @@ def fetch_segments(
ctx.progress(**status_update)
head_init = decrypter.finish() if decrypter else init
except BaseException:
except BaseException as e:
if decrypter:
decrypter.close()
if merger and not store.checkpoint(merger.cursor, merger.length):
low_free_space(e)
ctx.save_path.unlink(missing_ok=True)
raise
return merger, head_init
+7 -3
View File
@@ -21,6 +21,7 @@ from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, SyncLive, console
from unshackle.core.placement import Placement
from unshackle.core.run_plan import RunStopped
from unshackle.core.temp import low_free_space
from unshackle.core.titles import Movie
from unshackle.core.titles.episode import Episode
from unshackle.core.tracks import Audio, Tracks, Video
@@ -84,7 +85,7 @@ def hybrid_step_error(tracks: list[Video], source: str, output_name: str) -> str
try:
Hybrid(tracks, source, output_name=output_name)
except (ValueError, KeyError, OSError, RuntimeError) as e:
return str(e) or type(e).__name__
return (str(e) or type(e).__name__) + low_free_space(e)
return None
@@ -117,7 +118,8 @@ def mux_title(
"""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.
A failed mux stops the run with RunStopped, whose reason names the muxer, its exit and its error.
A failed mux stops the run with RunStopped, whose reason names the muxer, its exit, its error and the free space
of a nearly full temp volume, read before the temp files go.
"""
outputs: list[MuxOutput] = []
sidecars: dict[Path | None, list[Path]] = {}
@@ -335,7 +337,9 @@ def mux_title(
else:
log.warning(line)
if failure:
raise RunStopped(failure)
stopped = RunStopped(failure)
stopped.reason += low_free_space(stopped)
raise stopped
if write_sidecars:
sidecar_targets: list[tuple[Path | None, str, Path]] = []
+23
View File
@@ -14,6 +14,7 @@ from pathlib import Path
from typing import ParamSpec, TypeVar
from filelock import FileLock
from rich import filesize
from unshackle.core.config import config
@@ -128,6 +129,28 @@ def temp_root() -> Path:
return temp.parent if temp.name.startswith(TASK_PREFIX) else temp
LOW_FREE_SPACE = 1024**3
"""Free bytes on the temp volume below which a failure line names them."""
def low_free_space(e: BaseException) -> str:
"""``", 38.0 MB free on <temp>"`` when the temp volume is nearly full at ``e``'s first reading, else empty.
Code that deletes temp files on a failure reads it first. The reading is kept on ``e``, so a later report,
also one after the task temp dir is gone, gives the first reading.
"""
if (cached := getattr(e, "free_space", None)) is not None:
return str(cached)
temp = temp_root()
try:
free = shutil.disk_usage(temp).free
except OSError:
free = LOW_FREE_SPACE
note = f", {filesize.decimal(free)} free on {temp}" if free < LOW_FREE_SPACE else ""
e.free_space = note # type: ignore[attr-defined]
return note
def resume_stash() -> Path | None:
"""The dir beside the task dirs that keeps a failed track's segments for the next run.
+4
View File
@@ -17,6 +17,7 @@ from rich.rule import Rule
from unshackle.core.binaries import FFMPEG, FFProbe, HDR10PlusTool
from unshackle.core.config import config
from unshackle.core.console import console
from unshackle.core.temp import low_free_space
from unshackle.core.utilities import log_event, standard_resolution
from unshackle.core.utils import dovi
from unshackle.core.utils.subprocess import run_step
@@ -320,6 +321,9 @@ class Hybrid:
self.level_5(area[0])
self.injecting()
except BaseException as e:
low_free_space(e)
raise
finally:
# The title goes on after a failed resolution, and level_5 reuses an RPU_L5.bin it finds,
# so the files of this resolution's crop must not outlive it.
+3 -1
View File
@@ -38,6 +38,7 @@ from unshackle.core.drm.verify import (
)
from unshackle.core.events import events
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text
from unshackle.core.temp import low_free_space
from unshackle.core.tracks.segment_store import SegmentStore
from unshackle.core.utilities import language_name, log_event
from unshackle.core.utils import run_proxy
@@ -832,8 +833,9 @@ class Track:
abandon()
progress(downloaded="[yellow]SKIPPED")
return
except (Exception, KeyboardInterrupt):
except (Exception, KeyboardInterrupt) as e:
if not DOWNLOAD_LICENCE_ONLY.is_set():
low_free_space(e)
abandon()
raise