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
+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