From 15195f591ace67bfdb57c633887f1701ac9aa418 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 27 Aug 2026 17:10:13 +0200 Subject: [PATCH] fix(metering): size direct video URLs with ffprobe when yt-dlp reports no duration Cloud metering probed the source with yt-dlp only; its generic extractor never returns a duration for a plain mp4 URL, so every direct-file job (agent uploads on tmpfiles/uguu, a CDN link) died at submit with 'Could not determine the video duration'. On a generic hit the probe now stops walking proxies and reads the container header over HTTP with ffprobe (range requests, browser UA, 30 s timeout); tmpfiles links are refreshed first. Reported by a user driving the MCP from claude.ai. --- cloud/metering.py | 32 ++++++++++++++++++++++++++++++++ tests/test_probe_plan.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/cloud/metering.py b/cloud/metering.py index 42d2f6d..9b09509 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -98,6 +98,10 @@ def probe_url_minutes(url: str) -> float: # SSRF guard: reject non-http(s) / private / metadata hosts before probing. from security_utils import assert_public_url assert_public_url(url) + # Throwaway hosts (tmpfiles.org) sign links with a short-lived stamp; take + # the live one so the probe sees the file and not an HTML page. + import file_hosts + url = file_hosts.resolve(url) bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip() bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip() @@ -151,11 +155,39 @@ def probe_url_minutes(url: str) -> float: if duration: return float(duration) / 60.0 last_err = ValueError("no duration in metadata") + if info.get("extractor") == "generic": + # A direct media file: yt-dlp's generic extractor never + # reports a duration, so stop trying proxies and read the + # container header over HTTP instead. + break except Exception as e: last_err = e + else: + continue + break + # Direct file URLs (agent uploads on tmpfiles/uguu/R2, a CDN mp4): ffprobe + # fetches just the moov atom via range requests. Also the last resort for + # any URL yt-dlp could not size. + try: + seconds = _ffprobe_url_seconds(url) + if seconds > 0: + return seconds / 60.0 + except Exception as e: + last_err = e raise ValueError(f"Could not determine video duration ({last_err})") +def _ffprobe_url_seconds(url: str, timeout: int = 30) -> float: + out = subprocess.check_output( + ["ffprobe", "-v", "error", "-rw_timeout", str(timeout * 1_000_000), + "-user_agent", "Mozilla/5.0 (OpenShorts probe)", + "-show_entries", "format=duration", + "-of", "default=noprint_wrappers=1:nokey=1", url], + stderr=subprocess.STDOUT, timeout=timeout + 5, + ) + return float(out.decode().strip() or 0) + + # --------------------------------------------------------------------------- # # Balance computation (assumes caller holds the user lock when mutating) # --------------------------------------------------------------------------- # diff --git a/tests/test_probe_plan.py b/tests/test_probe_plan.py index fbf124a..17eddbe 100644 --- a/tests/test_probe_plan.py +++ b/tests/test_probe_plan.py @@ -33,3 +33,36 @@ class TestOrdering: def test_no_statics_matches_legacy_paid_only_behavior(self): assert plan(False, [], PAID) == [PAID] + + +class TestDirectFileProbe: + """yt-dlp's generic extractor reports no duration for a plain mp4 URL; the + probe must fall back to ffprobe over HTTP instead of 400-ing the job.""" + + def test_generic_extractor_falls_back_to_ffprobe(self, monkeypatch): + import types, sys, security_utils + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) + class _YDL: + def __init__(self, opts): pass + def __enter__(self): return self + def __exit__(self, *a): return False + def extract_info(self, url, download=False): + return {"extractor": "generic", "duration": None} + monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL)) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", lambda url, timeout=30: 559.4) + assert abs(metering.probe_url_minutes("https://cdn.example.com/v.mp4") - 559.4 / 60) < 1e-6 + + def test_both_fail_raises(self, monkeypatch): + import types, sys, security_utils + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) + class _YDL: + def __init__(self, opts): pass + def __enter__(self): return self + def __exit__(self, *a): return False + def extract_info(self, url, download=False): + raise RuntimeError("Unsupported URL") + monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL)) + def boom(url, timeout=30): raise RuntimeError("no moov") + monkeypatch.setattr(metering, "_ffprobe_url_seconds", boom) + with pytest.raises(ValueError): + metering.probe_url_minutes("https://cdn.example.com/v.mp4")