fix(subprocess): log handled tool failures at debug and drop an empty ccextractor output

This commit is contained in:
imSp4rky
2026-12-02 15:57:11 -07:00
parent eeab646272
commit ce0babb4f2
7 changed files with 192 additions and 39 deletions
+1 -1
View File
@@ -376,4 +376,4 @@ The debug log is tuned for **developers troubleshooting pipeline flow** (maximum
Give every entry a single-sentence `message` that stands on its own. Put all structured data (`context`, counts, ids, `duration_ms`) in **fields**, not in the prose. This separation lets the log be both human-scannable and machine-filterable. A message like `"Parsed DASH manifest"` with `context={"video": 4, "audio": 2}` beats `"Parsed manifest with 4 video and 2 audio tracks"`. Give every entry a single-sentence `message` that stands on its own. Put all structured data (`context`, counts, ids, `duration_ms`) in **fields**, not in the prose. This separation lets the log be both human-scannable and machine-filterable. A message like `"Parsed DASH manifest"` with `context={"video": 4, "audio": 2}` beats `"Parsed manifest with 4 video and 2 audio tracks"`.
!!! tip "Let tool runs log themselves" !!! tip "Let tool runs log themselves"
For external-tool calls (FFmpeg, mkvmerge, `dovi_tool`, and friends), route through `run_step` / `run_tool` / `ffprobe`, which auto-emit a `tool_run` entry capturing the binary's version, return code, and duration consistently. `run_tool` also raises `ToolFailed`, whose message names the tool, the exit code and the last lines the tool wrote. Only fall back to calling `log_tool_run` manually for a direct `subprocess.run` you genuinely cannot route through those helpers. Auto-logging is the preferred path precisely because it captures those fields the same way every time. For external-tool calls (FFmpeg, mkvmerge, `dovi_tool`, and friends), route through `run_step` / `run_tool` / `ffprobe`, which auto-emit a `tool_run` entry capturing the binary's version, return code, and duration consistently. `run_tool` also raises `ToolFailed`, whose message names the tool, the exit code and the last lines the tool wrote. A failure that the caller recovers from (a retry, a fallback) is named with `handled=` (exit codes or stderr text): its `tool_run` entry is `DEBUG`, not `ERROR`, and the call still raises. Only fall back to calling `log_tool_run` manually for a direct `subprocess.run` you genuinely cannot route through those helpers. Auto-logging is the preferred path precisely because it captures those fields the same way every time.
+110 -2
View File
@@ -1,5 +1,7 @@
import json
import subprocess import subprocess
import sys import sys
from collections.abc import Callable, Iterator
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
@@ -7,12 +9,15 @@ import pytest
from unshackle.core import binaries from unshackle.core import binaries
from unshackle.core.api.errors import categorize_exception from unshackle.core.api.errors import categorize_exception
from unshackle.core.config import config
from unshackle.core.drm import decrypters from unshackle.core.drm import decrypters
from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Subtitle from unshackle.core.tracks import Audio, Hybrid, Subtitle, Video
from unshackle.core.tracks import hybrid as hybrid_module
from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend
from unshackle.core.utilities import close_debug_logger, init_debug_logger
from unshackle.core.utils import subprocess as subprocess_module from unshackle.core.utils import subprocess as subprocess_module
from unshackle.core.utils.subprocess import ToolFailed, run_tool, tool_reason from unshackle.core.utils.subprocess import ToolFailed, run_step, run_tool, tool_reason
KEY = "b5df2ae3f63b8dda9049d6e41422e075" KEY = "b5df2ae3f63b8dda9049d6e41422e075"
POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts") POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts")
@@ -138,3 +143,106 @@ def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key(
assert message.startswith("mp4decrypt failed (exit 1): ERROR: cannot open output file (out.mp4) -5; command: ") assert message.startswith("mp4decrypt failed (exit 1): ERROR: cannot open output file (out.mp4) -5; command: ")
assert f"1:{KEY}" in message assert f"1:{KEY}" in message
assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR
@pytest.fixture
def debug_entries(tmp_path: Path) -> Iterator[Callable[[], list[dict]]]:
"""An enabled debug logger; the fixture value reads its entries back."""
path = tmp_path / "debug.jsonl"
init_debug_logger(log_path=path, enabled=True)
yield lambda: [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
close_debug_logger()
def levels(entries: list[dict], operation: str | None = "tool_run") -> list[str]:
"""The levels of the entries of operation, or of every entry when operation is None."""
return [e["level"] for e in entries if operation is None or e.get("operation") == operation]
@pytest.mark.parametrize(("code", "level"), [(10, "DEBUG"), (3, "ERROR")])
def test_run_tool_logs_a_handled_exit_code_at_debug(
debug_entries: Callable[[], list[dict]], code: int, level: str
) -> None:
with pytest.raises(ToolFailed):
run_tool("tool", exits(code), "tool step", handled=(10,))
assert levels(debug_entries()) == [level]
@pytest.mark.parametrize(("stderr", "level"), [("bad MAX_PQ_LUMINANCE value", "DEBUG"), ("Invalid PPS index", "ERROR")])
def test_run_step_logs_a_handled_stderr_marker_at_debug(
debug_entries: Callable[[], list[dict]], stderr: str, level: str
) -> None:
with pytest.raises(RuntimeError, match=stderr):
run_step(exits(1, stderr=stderr), label="tool step", handled=("MAX_PQ_LUMINANCE",))
assert levels(debug_entries()) == [level]
def dovi_stub(tmp_path: Path, mode_3_error: str) -> Path:
"""A dovi_tool that fails with mode_3_error under -m and writes the RPU without it."""
return stub(
tmp_path,
"dovi_tool",
f'if [ "$1" = "-m" ]; then echo {mode_3_error!r} >&2; exit 1; fi\nprintf rpu > "$4"',
)
@POSIX_STUBS
def test_a_max_pq_rpu_retries_untouched_without_an_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]]
) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: invalid MAX_PQ_LUMINANCE in RPU"))
Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type]
assert (tmp_path / "RPU_UNT.bin").read_bytes() == b"rpu"
assert "ERROR" not in levels(debug_entries(), None)
@POSIX_STUBS
def test_a_real_rpu_failure_still_logs_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]]
) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: Invalid PPS index"))
with pytest.raises(ValueError, match="corrupt"):
Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type]
entries = debug_entries()
assert levels(entries) == ["ERROR"] and levels(entries, "hybrid_extract_rpu") == ["ERROR"]
@POSIX_STUBS
def test_a_stream_without_hdr10plus_metadata_logs_no_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]]
) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
tool = stub(tmp_path, "hdr10plus_tool", 'echo "File doesn\'t contain dynamic metadata, stopping." >&2; exit 1')
monkeypatch.setattr(hybrid_module, "HDR10PlusTool", tool)
hybrid = Hybrid.__new__(Hybrid)
hybrid.hdr10plus_file = "HDR10Plus.json"
with pytest.raises(hybrid_module.NoHDR10PlusMetadata):
hybrid.extract_hdr10plus(None) # type: ignore[arg-type]
assert "ERROR" not in levels(debug_entries(), None)
@pytest.mark.skipif(not (binaries.CCExtractor and binaries.FFMPEG), reason="needs ccextractor and FFmpeg")
@pytest.mark.parametrize("suffix", ["mp4", "ts"])
def test_a_video_without_captions_gives_no_cc_track(
tmp_path: Path, debug_entries: Callable[[], list[dict]], suffix: str
) -> None:
clip = tmp_path / f"v.{suffix}"
subprocess.run(
[binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=25", "-t", "2"]
+ ["-c:v", "mpeg4", clip],
check=True,
)
video = Video(url="", codec=Video.Codec.AVC, language="en", id_="v")
video.path = clip
assert video.ccextractor(track_id="cc", out_path=tmp_path / "cc.srt", language="en") is None
assert not (tmp_path / "cc.srt").exists()
assert "ERROR" not in levels(debug_entries())
+19 -5
View File
@@ -13,7 +13,22 @@ from unshackle.core.tracks import Video
from unshackle.core.tracks import video as video_module from unshackle.core.tracks import video as video_module
def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def no_captions_exit(args: list[Any]) -> subprocess.CompletedProcess:
"""ccextractor exits 2 when the input file is missing and 10 when it finds no captions."""
if not Path(args[-1]).exists():
raise subprocess.CalledProcessError(2, args)
raise subprocess.CalledProcessError(10, args)
def empty_output(args: list[Any]) -> subprocess.CompletedProcess:
Path(args[-2]).write_bytes(b"")
return subprocess.CompletedProcess(args, 0, b"", b"")
@pytest.mark.parametrize("ccextractor", [no_captions_exit, empty_output])
def test_no_captions_retries_on_the_repackaged_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ccextractor: Any
) -> None:
original = tmp_path / "v.mp4" original = tmp_path / "v.mp4"
original.write_bytes(b"x") original.write_bytes(b"x")
repacked = tmp_path / "v_repack.mp4" repacked = tmp_path / "v_repack.mp4"
@@ -27,11 +42,9 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M
inputs: list[Path] = [] inputs: list[Path] = []
def fake_run(args: list[Any], **_: Any) -> None: def fake_run(args: list[Any], **_: Any) -> subprocess.CompletedProcess:
inputs.append(Path(args[-1])) inputs.append(Path(args[-1]))
if not Path(args[-1]).exists(): return ccextractor(args)
raise subprocess.CalledProcessError(2, args) # ccextractor: no input file
raise subprocess.CalledProcessError(10, args) # ccextractor: no captions found
monkeypatch.setattr(video_module.binaries, "CCExtractor", Path("/usr/bin/ccextractor")) monkeypatch.setattr(video_module.binaries, "CCExtractor", Path("/usr/bin/ccextractor"))
monkeypatch.setattr(video_module.subprocess, "run", fake_run) monkeypatch.setattr(video_module.subprocess, "run", fake_run)
@@ -39,3 +52,4 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M
assert track.ccextractor("cc", tmp_path / "cc.srt", Language.get("en")) is None assert track.ccextractor("cc", tmp_path / "cc.srt", Language.get("en")) is None
assert inputs == [original, repacked] assert inputs == [original, repacked]
assert not (tmp_path / "cc.srt").exists()
+21 -6
View File
@@ -420,19 +420,32 @@ class Hybrid:
dv_stream = config.directories.temp / "DV.hevc" dv_stream = config.directories.temp / "DV.hevc"
spinner = f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream..." spinner = f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream..."
max_pq = "MAX_PQ_LUMINANCE"
try: try:
dovi.extract_rpu(dv_stream, rpu_path, mode=None if untouched else 3, status=spinner) dovi.extract_rpu(
dv_stream,
rpu_path,
mode=None if untouched else 3,
status=spinner,
handled=() if untouched else (max_pq,),
)
except RuntimeError as e: except RuntimeError as e:
stderr_text = str(e) stderr_text = str(e)
if not untouched and max_pq in stderr_text:
log_event(
"hybrid_extract_rpu",
level="DEBUG",
message="RPU -m 3 rejects MAX_PQ_LUMINANCE, extracting untouched",
context={"error": stderr_text},
)
self.extract_rpu(video, untouched=True)
return
log_event( log_event(
"hybrid_extract_rpu", "hybrid_extract_rpu",
level="ERROR", level="ERROR",
message=f"Failed extracting{' untouched ' if untouched else ' '}RPU", message=f"Failed extracting{' untouched ' if untouched else ' '}RPU",
context={"untouched": untouched, "error": stderr_text}, context={"untouched": untouched, "error": stderr_text},
) )
if "MAX_PQ_LUMINANCE" in stderr_text:
self.extract_rpu(video, untouched=True)
return
if "Invalid PPS index" in stderr_text: if "Invalid PPS index" in stderr_text:
raise ValueError("Dolby Vision VideoTrack seems to be corrupt") from None raise ValueError("Dolby Vision VideoTrack seems to be corrupt") from None
raise ValueError( raise ValueError(
@@ -846,6 +859,7 @@ class Hybrid:
if not HDR10PlusTool: if not HDR10PlusTool:
raise ValueError("HDR10Plus_tool not found, HDR10+ to DV conversion needs it") raise ValueError("HDR10Plus_tool not found, HDR10+ to DV conversion needs it")
no_metadata = "dynamic metadata"
try: try:
run_step( run_step(
[ [
@@ -858,16 +872,17 @@ class Hybrid:
status="Extracting HDR10+ metadata...", status="Extracting HDR10+ metadata...",
output=config.directories.temp / self.hdr10plus_file, output=config.directories.temp / self.hdr10plus_file,
label="hdr10plus_tool extract", label="hdr10plus_tool extract",
handled=(no_metadata,),
) )
except RuntimeError as e: except RuntimeError as e:
if no_metadata in str(e):
raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream") from None
log_event( log_event(
"hybrid_extract_hdr10plus", "hybrid_extract_hdr10plus",
level="ERROR", level="ERROR",
message="Failed extracting HDR10+ metadata", message="Failed extracting HDR10+ metadata",
context={"error": str(e)}, context={"error": str(e)},
) )
if "dynamic metadata" in str(e):
raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream") from None
raise ValueError("Failed extracting HDR10+ metadata") from None raise ValueError("Failed extracting HDR10+ metadata") from None
file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file) file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file)
+11 -2
View File
@@ -652,7 +652,11 @@ class Video(Track):
def ccextractor( def ccextractor(
self, track_id: Any, out_path: Path | str, language: Language, original: bool = False self, track_id: Any, out_path: Path | str, language: Language, original: bool = False
) -> Subtitle | None: ) -> Subtitle | None:
"""Return a TextTrack object representing CC track extracted by CCExtractor.""" """Return the CC track that CCExtractor extracts, or None when the video has no captions.
CCExtractor reports no captions with exit 10. Version 0.93 exits 0 with an empty file when it cannot read
an MP4, so an empty file also counts as no captions.
"""
if not self.path: if not self.path:
raise ValueError("You must download the track first.") raise ValueError("You must download the track first.")
@@ -662,12 +666,15 @@ class Video(Track):
out_path = Path(out_path) out_path = Path(out_path)
ccextractor = binaries.CCExtractor ccextractor = binaries.CCExtractor
no_captions = 10
def run_ccextractor(video_path: Path, fallback: str) -> bool: def run_ccextractor(video_path: Path, fallback: str) -> bool:
try: try:
run_tool( run_tool(
"ccextractor", "ccextractor",
[ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path], [ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path],
"ccextractor", "ccextractor",
handled=(no_captions,),
) )
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
out_path.unlink(missing_ok=True) out_path.unlink(missing_ok=True)
@@ -676,9 +683,11 @@ class Video(Track):
f"ccextractor crashed (signal {-e.returncode}) on {video_path.name}; {fallback}" f"ccextractor crashed (signal {-e.returncode}) on {video_path.name}; {fallback}"
) )
return out_path.exists() return out_path.exists()
if e.returncode != 10: # 10 = No captions found if e.returncode != no_captions:
raise raise
return out_path.exists() return out_path.exists()
if out_path.exists() and not out_path.stat().st_size:
out_path.unlink()
return out_path.exists() return out_path.exists()
# Try on the original file first (preserves container-level CC data like c608 boxes), # Try on the original file first (preserves container-level CC data like c608 boxes),
+2 -16
View File
@@ -34,6 +34,7 @@ def extract_rpu(
mode: int | None = 3, mode: int | None = 3,
status: str | None = "Extracting DV RPU...", status: str | None = "Extracting DV RPU...",
label: str = "dovi_tool extract-rpu", label: str = "dovi_tool extract-rpu",
handled: tuple[int | str, ...] = (),
) -> bytes: ) -> bytes:
"""Extract DV RPU NALs from a raw HEVC bitstream. `mode=None` skips the -m flag (untouched).""" """Extract DV RPU NALs from a raw HEVC bitstream. `mode=None` skips the -m flag (untouched)."""
tool = require_dovi_tool() tool = require_dovi_tool()
@@ -41,7 +42,7 @@ def extract_rpu(
if mode is not None: if mode is not None:
args += ["-m", str(mode)] args += ["-m", str(mode)]
args += ["extract-rpu", source, "-o", output] args += ["extract-rpu", source, "-o", output]
return run_step(args, status=status, output=output, label=label) return run_step(args, status=status, output=output, label=label, handled=handled)
def inject_rpu( def inject_rpu(
@@ -145,23 +146,8 @@ def generate(
) )
def extract_rpu_with_fallback(source: Path, output: Path, *, label: str = "dovi_tool extract-rpu") -> bytes:
"""Try `-m 3` first. On a MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr.
Used when the caller wants automatic normalization but cannot abort if the source
rejects mode-3 conversion.
"""
try:
return extract_rpu(source, output, mode=3, label=label)
except RuntimeError as e:
if "MAX_PQ_LUMINANCE" not in str(e):
raise
return extract_rpu(source, output, mode=None, status="Extracting DV RPU (untouched)...", label=label)
__all__ = ( __all__ = (
"extract_rpu", "extract_rpu",
"extract_rpu_with_fallback",
"inject_rpu", "inject_rpu",
"editor", "editor",
"info_summary", "info_summary",
+28 -7
View File
@@ -17,19 +17,21 @@ def log_tool_run(
returncode: int | None, returncode: int | None,
*, *,
duration_ms: float | None = None, duration_ms: float | None = None,
handled: bool = False,
**context: object, **context: object,
) -> None: ) -> None:
"""Send a structured ``tool_run`` debug-log entry for an external tool invocation. """Send a structured ``tool_run`` debug-log entry for an external tool invocation.
Central helper so every binary call (FFmpeg, mkvpropedit, dovi_tool, and the other Central helper so every binary call (FFmpeg, mkvpropedit, dovi_tool, and the other
tools) logs the same shape. No-op when debug logging is off. tools) logs the same shape. A failure logs ERROR, or DEBUG when the caller handles it.
No-op when debug logging is off.
""" """
dl = get_debug_logger() dl = get_debug_logger()
if not dl: if not dl:
return return
failed = bool(returncode) failed = bool(returncode)
dl.log( dl.log(
level="ERROR" if failed else "DEBUG", level="ERROR" if failed and not handled else "DEBUG",
operation="tool_run", operation="tool_run",
message=f"{label} {'failed' if failed else 'ok'}", message=f"{label} {'failed' if failed else 'ok'}",
context={ context={
@@ -84,14 +86,31 @@ class ToolFailed(subprocess.CalledProcessError):
return f"{self.tool} failed ({exit_text}){f': {reason}' if reason else ''}; command: {command}" return f"{self.tool} failed ({exit_text}){f': {reason}' if reason else ''}; command: {command}"
def run_tool(tool: str, args: Sequence[str | Path], label: str, **context: object) -> subprocess.CompletedProcess: def is_handled(returncode: int, stderr: bytes, handled: tuple[int | str, ...]) -> bool:
"""Run args with its output captured as bytes, log a tool_run entry under label, and raise ToolFailed on a non-zero exit.""" """True when ``handled`` names the exit code, or a text that stderr contains."""
return any(h == returncode if isinstance(h, int) else h.encode() in stderr for h in handled)
def run_tool(
tool: str, args: Sequence[str | Path], label: str, *, handled: tuple[int | str, ...] = (), **context: object
) -> subprocess.CompletedProcess:
"""Run args with its output captured as bytes, log a tool_run entry under label, and raise ToolFailed on a non-zero exit.
A failure that ``handled`` names (an exit code or a stderr text) still raises, but logs at DEBUG.
"""
start = time.monotonic() start = time.monotonic()
p = subprocess.run(args, capture_output=True) p = subprocess.run(args, capture_output=True)
error = ToolFailed(tool, p.returncode, args, p.stdout, p.stderr) if p.returncode else None error = ToolFailed(tool, p.returncode, args, p.stdout, p.stderr) if p.returncode else None
if error: if error:
context["reason"] = error.reason context["reason"] = error.reason
log_tool_run(label, tool, p.returncode, duration_ms=round((time.monotonic() - start) * 1000, 1), **context) log_tool_run(
label,
tool,
p.returncode,
duration_ms=round((time.monotonic() - start) * 1000, 1),
handled=bool(error) and is_handled(p.returncode, p.stderr, handled),
**context,
)
if error: if error:
raise error raise error
return p return p
@@ -245,12 +264,14 @@ def run_step(
output: Path | None = None, output: Path | None = None,
label: str = "subprocess step", label: str = "subprocess step",
timeout: float | None = None, timeout: float | None = None,
handled: tuple[int | str, ...] = (),
) -> bytes: ) -> bytes:
"""Operate a CLI step that writes to `output` (when provided). Returns stderr bytes. """Operate a CLI step that writes to `output` (when provided). Returns stderr bytes.
Raises RuntimeError with the stderr tail when the process exits non-zero, or when Raises RuntimeError with the stderr tail when the process exits non-zero, or when
you give `output` and it does not exist or is empty after the step. A timeout also you give `output` and it does not exist or is empty after the step. A timeout also
raises RuntimeError. raises RuntimeError. A failure that `handled` names (an exit code or a stderr text)
still raises, but logs at DEBUG.
""" """
if output is not None: if output is not None:
output.unlink(missing_ok=True) output.unlink(missing_ok=True)
@@ -275,7 +296,7 @@ def run_step(
if dl := get_debug_logger(): if dl := get_debug_logger():
dl.log( dl.log(
level="ERROR" if failed else "DEBUG", level="ERROR" if failed and not is_handled(p.returncode, stderr, handled) else "DEBUG",
operation="tool_run", operation="tool_run",
message=f"{label} {'failed' if failed else 'ok'}", message=f"{label} {'failed' if failed else 'ok'}",
context={ context={