From d13fb8e3592c220f88563e2041239beb2d26ccb2 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 9 Sep 2026 12:12:45 +0200 Subject: [PATCH] fix(probe): retry the duration probe anonymously before paying per GB With YOUTUBE_COOKIES attached, YouTube answers UNPLAYABLE for every client (web_embedded, tv_downgraded, web AND mweb) on a share of videos, and yt-dlp reports that as "Video unavailable". Measured in prod on 9-sep-2026 with e_04ZrNroTo, same static IP minutes apart: cookies -> UNPLAYABLE on all three statics; anonymous -> 1080p (137+140). The 6-sep default,mweb fix is no longer enough on its own. The download already recovers from this through its anonymous fallback-static attempt. The probe carried the cookies on every route including the paid one, so it read a cookie problem as an IP problem ("video unavailable" is in _IP_SPECIFIC_HINTS) and escalated to DataImpulse, which fails identically with the same cookies. That is what fired the two paid-proxy alerts that morning, and a probe that dies outright 400s a video the download would have fetched. Probe strategies are now (extractor_args, use_cookies): first attempt on a route authenticated, second anonymous, mirroring the download. With no HD path (self-host without a PO token provider) the fallback keeps the operator's cookies, since it is then the only attempt. Claude-Session: https://claude.ai/code/session_01Qfgs1gca8UeEEZ2pvjjC8i --- CLAUDE.md | 11 ++- cloud/metering.py | 21 +++-- tests/test_probe_anonymous_fallback.py | 111 +++++++++++++++++++++++++ tests/test_yt_clients.py | 7 +- 4 files changed, 142 insertions(+), 8 deletions(-) create mode 100644 tests/test_probe_anonymous_fallback.py diff --git a/CLAUDE.md b/CLAUDE.md index 3696636..8eb115b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -372,7 +372,16 @@ like the download does: an anonymous probe from the static IPs gets "Sign in to confirm you're not a bot" in bursts (4-sep-2026: ~10 probes in one hour, 1.8 MB each on the per-GB proxy) because a datacenter IP's anonymous rate limit is low and we make ~400 YouTube hits a day from three of them, while -the authenticated download sails through the same IPs. `main.py` prints `PROXY_ROUTE=` after +the authenticated download sails through the same IPs. But the **first** +attempt on a route carries them and the second drops them, on the probe as +on the download: with the cookies attached YouTube answers UNPLAYABLE for +every client (`web_embedded`, `tv_downgraded`, `web` **and** `mweb`) on a +share of videos, which yt-dlp reports as "Video unavailable" (9-sep-2026, +same video on all three statics; anonymous on the same IP → 1080p 137+140). +Without that anonymous second attempt the probe read a cookie problem as an +IP problem and escalated to the per-GB proxy, which carries the same cookies +and fails identically, while the download recovered for free on the same +static. `main.py` prints `PROXY_ROUTE=` after every download (winner, paid bytes across all attempts including failed paid ones, each free attempt's error); `app.py` persists it as a `proxy_usage` row at job end and pages Telegram when the paid proxy carried diff --git a/cloud/metering.py b/cloud/metering.py index c667cf0..b72dd79 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -170,8 +170,19 @@ def probe_url_minutes(url: str, allow_paid: bool = True) -> float: # each of those probes then paid the per-GB proxy for nothing. from yt_clients import hd_extractor_args, fallback_extractor_args hd_args = hd_extractor_args(bgutil_http, bgutil_script) - strategies = ([hd_args] if hd_args else []) + [ - fallback_extractor_args(bgutil_http, bgutil_script)] + # (extractor args, send the account cookies). The second attempt on each + # route drops the cookies, exactly like the download's 'fallback-static' + # step (main.py): with the cookies attached YouTube answers UNPLAYABLE for + # every client — web_embedded, tv_downgraded, web AND mweb — on a share of + # videos, and yt-dlp reports that as "Video unavailable" (measured in prod + # 9-sep-2026, all three statics, same video anonymous → 1080p 137+140). + # Without this step the probe read that as an IP problem and escalated to + # the per-GB proxy, which carries the same cookies and fails identically, + # while the download quietly recovered anonymously on the same static. + # With no HD path at all (self-host, no PO token provider) the fallback is + # the only attempt, so it keeps the cookies the operator configured. + strategies = ([(hd_args, True)] if hd_args else []) + [ + (fallback_extractor_args(bgutil_http, bgutil_script), not hd_args)] # Rotated per probe to spread load across the pool, like the download does. statics = [p.strip() for p in @@ -244,10 +255,10 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path): if not static_errors or not any(static_failure_warrants_paid(e) for e in static_errors.values()): break - for extractor_args in strategies: + for step, (extractor_args, use_cookies) in enumerate(strategies): opts = {"skip_download": True, "quiet": True, "no_warnings": True, "logger": _QuietLogger(), "extractor_args": extractor_args} - if ck_path: + if ck_path and use_cookies: opts["cookiefile"] = ck_path if proxy: opts["proxy"] = proxy @@ -259,7 +270,7 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path): if is_paid: _paid_probe_events.append({ "url": url, "static_errors": dict(static_errors), - "bytes_estimate": 1_800_000 * (1 + list(strategies).index(extractor_args))}) + "bytes_estimate": 1_800_000 * (1 + step)}) return float(duration) / 60.0 last_err = ValueError("no duration in metadata") if info.get("extractor") == "generic": diff --git a/tests/test_probe_anonymous_fallback.py b/tests/test_probe_anonymous_fallback.py new file mode 100644 index 0000000..bfd65cc --- /dev/null +++ b/tests/test_probe_anonymous_fallback.py @@ -0,0 +1,111 @@ +"""The duration probe must drop the cookies before it reaches the paid proxy. + +With YOUTUBE_COOKIES attached, YouTube answers UNPLAYABLE for *every* client +(web_embedded, tv_downgraded, web and mweb) on a share of videos, and yt-dlp +reports that as "Video unavailable". Measured in prod on 9-sep-2026, same +video, same static IP, minutes apart: cookies -> UNPLAYABLE on all three +statics; anonymous -> 1080p (137+140). The download already recovers from +this through its anonymous 'fallback-static' attempt (main.plan_download_ +attempts); the probe did not, so it read a cookie problem as an IP problem +and escalated to the per-GB proxy -- which carries the same cookies and fails +the same way. That is what fired the two "Paid proxy used" alerts that day. +""" +import sys +import types + +import pytest + +metering = pytest.importorskip("cloud.metering") + +URL = "https://www.youtube.com/watch?v=e_04ZrNroTo" +NETSCAPE = "# Netscape HTTP Cookie File\n.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tx\n" + + +def _fake_ytdl(monkeypatch, attempts, playable_anonymously=True): + """yt-dlp stand-in: UNPLAYABLE whenever a cookiefile is attached.""" + + class _YDL: + def __init__(self, opts): + self.opts = opts + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def extract_info(self, url, download=False): + attempts.append({"proxy": self.opts.get("proxy"), + "cookies": bool(self.opts.get("cookiefile"))}) + if self.opts.get("cookiefile") or not playable_anonymously: + raise RuntimeError("ERROR: [youtube] e_04ZrNroTo: Video unavailable") + return {"extractor": "youtube", "duration": 214} + + monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL)) + + +@pytest.fixture(autouse=True) +def _env(monkeypatch): + import security_utils + monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u) + monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1") + monkeypatch.setenv("PROXY_URL", "http://paid") + monkeypatch.setenv("YOUTUBE_COOKIES", NETSCAPE) + monkeypatch.delenv("DIRECT_FIRST", raising=False) + metering.pop_paid_probe_events() + yield + metering.pop_paid_probe_events() + + +class TestTheAnonymousRetryComesBeforeTheMoney: + def test_the_static_is_retried_without_cookies(self, monkeypatch): + monkeypatch.setenv("BGUTIL_BASE_URL", "http://127.0.0.1:4416") + attempts = [] + _fake_ytdl(monkeypatch, attempts) + + assert abs(metering.probe_url_minutes(URL) - 214 / 60) < 1e-6 + + assert [(a["proxy"], a["cookies"]) for a in attempts] == [ + ("http://s1", True), # HD with the account cookies + ("http://s1", False), # same IP, anonymous -> answers + ] + + def test_the_paid_proxy_is_never_reached(self, monkeypatch): + monkeypatch.setenv("BGUTIL_BASE_URL", "http://127.0.0.1:4416") + attempts = [] + _fake_ytdl(monkeypatch, attempts) + + metering.probe_url_minutes(URL) + + assert not any(a["proxy"] == "http://paid" for a in attempts) + assert metering.pop_paid_probe_events() == [] + + def test_a_genuinely_dead_video_still_escalates_once(self, monkeypatch): + """The anonymous retry is a free extra chance, not a new gate: when it + fails too, "Video unavailable" stays IP-suspect and the paid proxy is + still allowed its one look.""" + monkeypatch.setenv("BGUTIL_BASE_URL", "http://127.0.0.1:4416") + attempts = [] + _fake_ytdl(monkeypatch, attempts, playable_anonymously=False) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", + lambda url, timeout=30: 0) + + with pytest.raises(ValueError): + metering.probe_url_minutes(URL) + + assert any(a["proxy"] == "http://paid" for a in attempts) + + def test_selfhost_without_a_po_token_provider_keeps_its_cookies(self, monkeypatch): + """No HD path means the fallback is the only attempt: dropping the + operator's cookies there would remove the only session they have.""" + monkeypatch.delenv("BGUTIL_BASE_URL", raising=False) + monkeypatch.delenv("BGUTIL_SCRIPT_PATH", raising=False) + attempts = [] + _fake_ytdl(monkeypatch, attempts) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", + lambda url, timeout=30: 0) + + with pytest.raises(ValueError): + metering.probe_url_minutes(URL) + + assert all(a["cookies"] for a in attempts) diff --git a/tests/test_yt_clients.py b/tests/test_yt_clients.py index d6a914b..181e3f3 100644 --- a/tests/test_yt_clients.py +++ b/tests/test_yt_clients.py @@ -60,7 +60,10 @@ def test_probe_uses_the_same_lists(monkeypatch): monkeypatch.setattr(metering, "_probe_with_proxies", fake) metering.probe_url_minutes("https://www.youtube.com/watch?v=abc") + # (extractor args, send the cookies): the fallback step goes out anonymously, + # like the download's 'fallback-static' attempt — see + # tests/test_probe_anonymous_fallback.py. assert seen["strategies"] == [ - yt_clients.hd_extractor_args("", "/opt/gen.js"), - yt_clients.fallback_extractor_args("", "/opt/gen.js"), + (yt_clients.hd_extractor_args("", "/opt/gen.js"), True), + (yt_clients.fallback_extractor_args("", "/opt/gen.js"), False), ]