feat(dl): name the free space of a nearly full temp volume on the failure line

This commit is contained in:
imSp4rky
2026-11-28 14:35:29 -07:00
parent 5167f4f9d9
commit 7856d53950
8 changed files with 156 additions and 9 deletions
+5
View File
@@ -308,6 +308,11 @@ 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.
**Inspect:** unshackle adds this part when the volume of `directories.temp` has less than 1 GiB free. Make space on that volume, or set `directories.temp` to a larger volume (see [Directories](../reference/configuration/directories.md)), and run the download again. Over the REST API the job error carries the same line, and a full disk in the downloader gives `DOWNLOAD_ERROR`.
!!! example "The wrong titles/metadata keep coming back"
**Symptom:** a service returns outdated titles even after the source changed.
+97
View File
@@ -0,0 +1,97 @@
"""The failure line names the free space of a nearly full temp volume, read once per error."""
import shutil
import subprocess
from pathlib import Path
from types import SimpleNamespace
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.config import config
from unshackle.core.temp import TASK_PREFIX
@pytest.fixture
def temp(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
monkeypatch.setattr(config.directories, "temp", tmp_path)
return tmp_path
def free_space(monkeypatch: pytest.MonkeyPatch, free: int) -> list[str]:
"""Make each disk_usage read report ``free`` bytes and return the list of read paths."""
reads: 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]
monkeypatch.setattr(dl_module.shutil, "disk_usage", usage)
return reads
def test_a_nearly_full_temp_volume_is_named_on_the_line(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
free_space(monkeypatch, 38_000_000)
error = subprocess.CalledProcessError(2, ["packager"])
_, line = dl.failure_lines(error)
assert line == f" CalledProcessError: {str(error).rstrip('.')}, 38.0 MB free on {temp}"
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)
error = ValueError("boom")
assert dl.failure_lines(error) == [":x: Download Failed...", " ValueError: boom"]
def test_a_temp_dir_that_cannot_be_read_adds_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path / "missing")
assert dl.failure_lines(ValueError("boom"))[1] == " ValueError: boom"
def test_a_later_report_reuses_the_first_reading(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
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)
assert dl.failure_lines(error) == first
assert len(reads) == 1
def test_a_click_exception_keeps_only_its_message(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
reads = free_space(monkeypatch, 0)
assert dl.failure_lines(click.ClickException("no key"))[1] == " no key"
assert reads == []
def test_a_task_temp_dir_is_named_by_the_temp_dir_that_holds_it(temp: Path, monkeypatch: pytest.MonkeyPatch) -> None:
reads = free_space(monkeypatch, 0)
monkeypatch.setattr(config.directories, "temp", temp / f"{TASK_PREFIX}example")
assert dl.failure_lines(ValueError("boom"))[1] == f" ValueError: boom, 0 bytes free on {temp}"
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 decrypt(*args: Any, **kwargs: Any) -> None:
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)
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 == keys.decrypt_verified
assert verify.DECRYPT_HOOK == cmd.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"
+3 -1
View File
@@ -17,6 +17,7 @@ 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.drm import Widevine, key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
@@ -117,7 +118,8 @@ def test_the_retry_after_a_bad_vault_key_ends_in_the_import_error(
assert not (tmp_path / "video.mp4.enc").exists()
def test_a_download_stopped_by_a_click_exception_reports_only_its_message() -> None:
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)
error = ImportService.missing_key(SimpleNamespace(drm=[FakeDRM({})]))
lines = dl.failure_lines(error)
+4 -1
View File
@@ -15,6 +15,7 @@ import rnet
from tests.downloaders.test_content_encoding import _FakeRnetResponse
from tests.downloaders.test_rnet_session_paths import SESSIONS
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.session import MaxRetriesError
from unshackle.core.utilities import get_free_port
@@ -117,14 +118,16 @@ def test_disk_full_is_not_retried(tmp_path, monkeypatch, serve):
assert raised.value.errno == errno.ENOSPC
assert server.requests == 1
assert dl.retries_exhausted(raised.value)
assert raised.value.error_code == APIErrorCode.DOWNLOAD_ERROR
def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
server = serve(503)
with pytest.raises(rq.HTTPError):
with pytest.raises(rq.HTTPError) as raised:
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
assert server.requests == dl.MAX_ATTEMPTS
assert not hasattr(raised.value, "error_code")
@pytest.mark.parametrize("make_session", SESSIONS)
+35 -2
View File
@@ -21,6 +21,7 @@ import mediaexport
from click.core import ParameterSource
from langcodes import Language
from pymediainfo import MediaInfo
from rich import filesize
from rich.console import Group
from rich.padding import Padding
from rich.rule import Rule
@@ -74,7 +75,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 with_task_temp
from unshackle.core.temp import 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
@@ -370,6 +371,28 @@ 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
class dl:
def find_custom_font(self, font_name: str) -> Path | None:
"""
@@ -2913,6 +2936,8 @@ class dl:
line = f"{type(e).__name__}: {e}"
if retries_exhausted(e):
line += f", {'; '.join(e.__notes__)}"
if free := low_free_space(e):
line = line.removesuffix(".") + free
return [":x: Download Failed...", f" {line}"]
def start_key_resolution(
@@ -2931,7 +2956,15 @@ class dl:
export=partial(self.write_export, export) if export else None,
debug_logger=self.debug_logger,
)
verify.DECRYPT_HOOK = self.keys.decrypt_verified
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
def cdm_for(self, system: str, quality: int | None = None) -> object | None:
"""Get the CDM for one DRM system, ``widevine`` or ``playready``.
+3
View File
@@ -33,6 +33,7 @@ from rich import filesize
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.utilities import get_debug_logger, get_extension, log_event
from unshackle.core.utils import run_proxy
@@ -1205,6 +1206,8 @@ def download(
# so the caller fails fast instead of hitting a missing segment at merge time
if not cancelled:
exc.add_note(f"{GAVE_UP_NOTE} {failures} failed attempts over {_time() - started:.0f}s")
if disk_error:
coded(exc, APIErrorCode.DOWNLOAD_ERROR)
raise
return
if not part_mode:
+8 -4
View File
@@ -70,15 +70,19 @@ def sweep_task_dirs(root: Path) -> None:
entry.unlink(missing_ok=True)
def temp_root() -> Path:
"""The configured temp dir, also when config.directories.temp points at a task dir inside it."""
temp = config.directories.temp
return temp.parent if temp.name.startswith(TASK_PREFIX) else temp
def resume_stash() -> Path | None:
"""The dir beside the task dirs that keeps a failed track's segments for the next run.
None outside a task dir: there config.directories.temp itself outlives the run.
"""
temp = config.directories.temp
if not temp.name.startswith(TASK_PREFIX):
return None
return temp.parent / RESUME_STASH
root = temp_root()
return None if root == config.directories.temp else root / RESUME_STASH
def _move_with_sidecar(source: Path, target: Path) -> bool: