feat(download): skip the static IPs when the probe already saw them bot-checked
Since 30-sep-2026 YouTube bot-checks anonymous requests from every one of our non-residential IPs per video: the same video fails on the 3 statics and the server's own IP, with every player client, and the paid residential proxy answers it. The metering probe learns that verdict first; the download then repeated four anonymous attempts (~8 s, four more hits on IPs YouTube is scoring) before reaching the paid proxy for the same answer. The probe now leaves a one-shot verdict per URL, app.py passes it to the job as DOWNLOAD_SKIP_STATICS=1 (and into the resume manifest), and plan_download_attempts drops the free attempts when a paid proxy exists.
This commit is contained in:
parent
8ee8ae36c6
commit
faff66de0b
6 changed files with 143 additions and 5 deletions
14
CLAUDE.md
14
CLAUDE.md
|
|
@ -718,7 +718,19 @@ ones: while it named the pages it knew, a hashtag page and the legacy
|
||||||
`/<vanity>` channel URL went straight through, and one of them walked to
|
`/<vanity>` channel URL went straight through, and one of them walked to
|
||||||
page 23 on the static pool and then paid the per-GB proxy to walk it
|
page 23 on the static pool and then paid the per-GB proxy to walk it
|
||||||
again (20-sep-2026).
|
again (20-sep-2026).
|
||||||
`PAID_PROXY_DAILY_MB` (default
|
Since 30-sep-2026 YouTube answers the bot-check to anonymous requests
|
||||||
|
from every one of our non-residential IPs (the 3 statics and the server's
|
||||||
|
own IP alike), **per video**: the same video fails on all of them and a few
|
||||||
|
popular ones pass on all of them, whatever the client (web, mweb, ios,
|
||||||
|
android_vr, tv, web_embedded, with or without a player PO token). Only an
|
||||||
|
authenticated session or a residential IP gets through. So when the probe
|
||||||
|
saw every static bot-checked and the paid proxy answer, the job carries
|
||||||
|
`DOWNLOAD_SKIP_STATICS=1` (`metering.pop_statics_bot_checked`, also in the
|
||||||
|
resume manifest) and `plan_download_attempts` goes straight to the paid
|
||||||
|
attempts instead of repeating four anonymous hits for the same verdict.
|
||||||
|
The proxy watcher also checks the ytcfg `LOGGED_IN` marker when
|
||||||
|
`YOUTUBE_COOKIES` is set and pages on the first probe that says the session
|
||||||
|
is gone. `PAID_PROXY_DAILY_MB` (default
|
||||||
500) is the hard ceiling: past it the paid proxy is dropped from the probe
|
500) is the hard ceiling: past it the paid proxy is dropped from the probe
|
||||||
and from every new job's env until UTC midnight. The watcher probes the
|
and from every new job's env until UTC midnight. The watcher probes the
|
||||||
static pool against a real YouTube watch page (playable markers), not
|
static pool against a real YouTube watch page (playable markers), not
|
||||||
|
|
|
||||||
18
app.py
18
app.py
|
|
@ -427,6 +427,9 @@ async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
minutes = max(1, math.ceil(minutes))
|
minutes = max(1, math.ceil(minutes))
|
||||||
|
# The probe already learned whether this video is bot-checked on every
|
||||||
|
# static IP; the download skips those attempts then (DOWNLOAD_SKIP_STATICS).
|
||||||
|
request.state.skip_statics = bool(url) and _metering.pop_statics_bot_checked(url)
|
||||||
|
|
||||||
# Free account past its balance: the first video (up to
|
# Free account past its balance: the first video (up to
|
||||||
# FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is
|
# FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is
|
||||||
|
|
@ -1144,7 +1147,7 @@ def _install_drain_signal_handler():
|
||||||
|
|
||||||
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark,
|
def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark,
|
||||||
webhook_url=None, webhook_secret=None, base_url=None,
|
webhook_url=None, webhook_secret=None, base_url=None,
|
||||||
partial=None, source_cap_minutes=None):
|
partial=None, source_cap_minutes=None, skip_statics=False):
|
||||||
try:
|
try:
|
||||||
path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)
|
path = os.path.join(OUTPUT_DIR, job_id, _RESUME_FILE)
|
||||||
with open(path, "w") as f:
|
with open(path, "w") as f:
|
||||||
|
|
@ -1166,6 +1169,8 @@ def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, water
|
||||||
"partial": partial,
|
"partial": partial,
|
||||||
# Same reason for the whole-video jobs' safety cap.
|
# Same reason for the whole-video jobs' safety cap.
|
||||||
"source_cap_minutes": source_cap_minutes,
|
"source_cap_minutes": source_cap_minutes,
|
||||||
|
# The probe's "statics bot-checked for this video" verdict.
|
||||||
|
"skip_statics": bool(skip_statics),
|
||||||
}, f)
|
}, f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"⚠️ Could not write resume manifest for {job_id}: {e}")
|
print(f"⚠️ Could not write resume manifest for {job_id}: {e}")
|
||||||
|
|
@ -1265,6 +1270,10 @@ def _resume_interrupted_jobs() -> set:
|
||||||
env["SOURCE_CAP_MINUTES"] = str(m["source_cap_minutes"])
|
env["SOURCE_CAP_MINUTES"] = str(m["source_cap_minutes"])
|
||||||
else:
|
else:
|
||||||
env.pop("SOURCE_CAP_MINUTES", None)
|
env.pop("SOURCE_CAP_MINUTES", None)
|
||||||
|
if m.get("skip_statics"):
|
||||||
|
env["DOWNLOAD_SKIP_STATICS"] = "1"
|
||||||
|
else:
|
||||||
|
env.pop("DOWNLOAD_SKIP_STATICS", None)
|
||||||
|
|
||||||
m["attempts"] = attempts
|
m["attempts"] = attempts
|
||||||
try:
|
try:
|
||||||
|
|
@ -3118,6 +3127,11 @@ async def process_endpoint(
|
||||||
else:
|
else:
|
||||||
env.pop("SOURCE_CAP_MINUTES", None)
|
env.pop("SOURCE_CAP_MINUTES", None)
|
||||||
source_cap = None
|
source_cap = None
|
||||||
|
skip_statics = bool(url) and bool(getattr(request.state, "skip_statics", False))
|
||||||
|
if skip_statics:
|
||||||
|
env["DOWNLOAD_SKIP_STATICS"] = "1"
|
||||||
|
else:
|
||||||
|
env.pop("DOWNLOAD_SKIP_STATICS", None)
|
||||||
if partial:
|
if partial:
|
||||||
# main.py cuts the source down to this many minutes before anything
|
# main.py cuts the source down to this many minutes before anything
|
||||||
# reads it, so the whole pipeline (and the editor) sees a short video.
|
# reads it, so the whole pipeline (and the editor) sees a short video.
|
||||||
|
|
@ -3167,7 +3181,7 @@ async def process_endpoint(
|
||||||
watermark=jobs[job_id]['watermark'],
|
watermark=jobs[job_id]['watermark'],
|
||||||
webhook_url=webhook_url, webhook_secret=webhook_secret,
|
webhook_url=webhook_url, webhook_secret=webhook_secret,
|
||||||
base_url=api_base, partial=partial,
|
base_url=api_base, partial=partial,
|
||||||
source_cap_minutes=source_cap)
|
source_cap_minutes=source_cap, skip_statics=skip_statics)
|
||||||
|
|
||||||
_enqueue_job(job_id, priority)
|
_enqueue_job(job_id, priority)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -113,6 +113,29 @@ def static_failure_warrants_paid(err) -> bool:
|
||||||
# executor thread that runs the probe, drained on the event loop).
|
# executor thread that runs the probe, drained on the event loop).
|
||||||
_paid_probe_events: list = []
|
_paid_probe_events: list = []
|
||||||
|
|
||||||
|
# URLs whose probe saw EVERY static IP answer the bot-check and the paid proxy
|
||||||
|
# answer the video. Since 30-sep-2026 that verdict is per video and identical
|
||||||
|
# on every one of our IPs (measured: 9 of 10 videos, 3 statics + the server's
|
||||||
|
# own IP, twice each), so the download repeating the four anonymous attempts
|
||||||
|
# costs ~8 s and four more hits on IPs YouTube is already scoring, for the
|
||||||
|
# same answer. app.py pops the verdict when it builds the job.
|
||||||
|
_static_bot_verdicts: set = set()
|
||||||
|
|
||||||
|
|
||||||
|
def pop_statics_bot_checked(url) -> bool:
|
||||||
|
"""True (once) when the probe of ``url`` found the static pool bot-checked
|
||||||
|
for this video and had to use the paid proxy."""
|
||||||
|
try:
|
||||||
|
_static_bot_verdicts.remove(url)
|
||||||
|
return True
|
||||||
|
except KeyError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _all_bot_checked(static_errors) -> bool:
|
||||||
|
return bool(static_errors) and all(
|
||||||
|
"not a bot" in (e or "") for e in static_errors.values())
|
||||||
|
|
||||||
|
|
||||||
def pop_paid_probe_events() -> list:
|
def pop_paid_probe_events() -> list:
|
||||||
out, _paid_probe_events[:] = list(_paid_probe_events), []
|
out, _paid_probe_events[:] = list(_paid_probe_events), []
|
||||||
|
|
@ -293,6 +316,8 @@ def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path):
|
||||||
_paid_probe_events.append({
|
_paid_probe_events.append({
|
||||||
"url": url, "static_errors": dict(static_errors),
|
"url": url, "static_errors": dict(static_errors),
|
||||||
"bytes_estimate": 1_800_000 * (1 + step)})
|
"bytes_estimate": 1_800_000 * (1 + step)})
|
||||||
|
if _all_bot_checked(static_errors):
|
||||||
|
_static_bot_verdicts.add(url)
|
||||||
return float(duration) / 60.0
|
return float(duration) / 60.0
|
||||||
last_err = ValueError("no duration in metadata")
|
last_err = ValueError("no duration in metadata")
|
||||||
if info.get("extractor") == "generic":
|
if info.get("extractor") == "generic":
|
||||||
|
|
|
||||||
19
main.py
19
main.py
|
|
@ -694,9 +694,17 @@ def is_youtube_url(url):
|
||||||
return host.endswith(("youtube.com", "youtu.be", "youtube-nocookie.com", "googlevideo.com"))
|
return host.endswith(("youtube.com", "youtu.be", "youtube-nocookie.com", "googlevideo.com"))
|
||||||
|
|
||||||
|
|
||||||
def plan_download_attempts(direct_first, statics, paid, have_hd, youtube=True):
|
def plan_download_attempts(direct_first, statics, paid, have_hd, youtube=True,
|
||||||
|
skip_statics=False):
|
||||||
"""Ordered (label, capped, proxy) download plan — pure, unit-tested.
|
"""Ordered (label, capped, proxy) download plan — pure, unit-tested.
|
||||||
|
|
||||||
|
``skip_statics`` (env ``DOWNLOAD_SKIP_STATICS=1``, set by app.py when the
|
||||||
|
metering probe already saw every static IP bot-checked for this video and
|
||||||
|
the paid proxy answer): go straight to the paid attempts. The verdict is
|
||||||
|
per video and the same on every IP (30-sep-2026), so the free attempts
|
||||||
|
would only add latency and more hits on IPs YouTube is scoring. Ignored
|
||||||
|
without a paid proxy: the statics are then all there is.
|
||||||
|
|
||||||
``youtube=False`` (a direct file URL): the server's own IP first, then one
|
``youtube=False`` (a direct file URL): the server's own IP first, then one
|
||||||
static proxy as the only fallback; the paid per-GB proxy is never used.
|
static proxy as the only fallback; the paid per-GB proxy is never used.
|
||||||
|
|
||||||
|
|
@ -710,6 +718,8 @@ def plan_download_attempts(direct_first, statics, paid, have_hd, youtube=True):
|
||||||
if statics:
|
if statics:
|
||||||
plan.append(('static-fallback', False, statics[0]))
|
plan.append(('static-fallback', False, statics[0]))
|
||||||
return plan
|
return plan
|
||||||
|
if skip_statics and paid:
|
||||||
|
statics, direct_first = [], False
|
||||||
plan = []
|
plan = []
|
||||||
if direct_first:
|
if direct_first:
|
||||||
plan.append(('HD-direct', False, None))
|
plan.append(('HD-direct', False, None))
|
||||||
|
|
@ -1048,6 +1058,10 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
|
||||||
# Every attempt asks for the same 1080p spec: the fallback used to ask
|
# Every attempt asks for the same 1080p spec: the fallback used to ask
|
||||||
# for `best[ext=mp4]/best`, the best single-file format, which on
|
# for `best[ext=mp4]/best`, the best single-file format, which on
|
||||||
# YouTube is the 360p progressive one even with 1080p streams listed.
|
# YouTube is the 360p progressive one even with 1080p streams listed.
|
||||||
|
_skip_statics = os.environ.get("DOWNLOAD_SKIP_STATICS", "").strip() == "1"
|
||||||
|
if _skip_statics and _proxy and is_youtube_url(url):
|
||||||
|
print("🌐 The probe found the static IPs bot-checked for this video: "
|
||||||
|
"downloading through the paid proxy directly.")
|
||||||
attempts = [
|
attempts = [
|
||||||
(label,
|
(label,
|
||||||
fallback_args if label.startswith('fallback') else hd_args,
|
fallback_args if label.startswith('fallback') else hd_args,
|
||||||
|
|
@ -1055,7 +1069,8 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
|
||||||
proxy,
|
proxy,
|
||||||
not (label.startswith('fallback') and hd_args))
|
not (label.startswith('fallback') and hd_args))
|
||||||
for label, capped, proxy in plan_download_attempts(
|
for label, capped, proxy in plan_download_attempts(
|
||||||
_direct_first, _statics, _proxy, bool(hd_args), youtube=is_youtube_url(url))
|
_direct_first, _statics, _proxy, bool(hd_args), youtube=is_youtube_url(url),
|
||||||
|
skip_statics=_skip_statics)
|
||||||
]
|
]
|
||||||
if not is_youtube_url(url):
|
if not is_youtube_url(url):
|
||||||
print("🌐 Direct file URL: downloading from the server's own IP (no proxy).")
|
print("🌐 Direct file URL: downloading from the server's own IP (no proxy).")
|
||||||
|
|
|
||||||
|
|
@ -70,3 +70,20 @@ def test_direct_file_urls_skip_the_proxy_chain():
|
||||||
assert main.is_youtube_url("https://youtu.be/x")
|
assert main.is_youtube_url("https://youtu.be/x")
|
||||||
assert not main.is_youtube_url("https://litter.catbox.moe/u90j4q.mp4")
|
assert not main.is_youtube_url("https://litter.catbox.moe/u90j4q.mp4")
|
||||||
assert not main.is_youtube_url("https://tmpfiles.org/dl/1/2/v.mp4")
|
assert not main.is_youtube_url("https://tmpfiles.org/dl/1/2/v.mp4")
|
||||||
|
|
||||||
|
|
||||||
|
class TestSkipStatics:
|
||||||
|
"""The probe already saw every static IP bot-checked for this video
|
||||||
|
(30-sep-2026: per video, identical on every IP): the download goes
|
||||||
|
straight to the paid attempts instead of repeating four anonymous hits."""
|
||||||
|
|
||||||
|
def test_skip_statics_goes_straight_to_paid(self):
|
||||||
|
got = plan(True, STATICS, PAID, True, skip_statics=True)
|
||||||
|
assert got == [('HD', True, PAID), ('fallback', True, PAID)]
|
||||||
|
|
||||||
|
def test_skip_statics_without_paid_keeps_the_statics(self):
|
||||||
|
assert plan(False, STATICS, None, True, skip_statics=True) == \
|
||||||
|
plan(False, STATICS, None, True)
|
||||||
|
|
||||||
|
def test_default_is_unchanged(self):
|
||||||
|
assert plan(True, STATICS, PAID, True, skip_statics=False) == plan(True, STATICS, PAID, True)
|
||||||
|
|
|
||||||
|
|
@ -66,3 +66,58 @@ class TestDirectFileProbe:
|
||||||
monkeypatch.setattr(metering, "_ffprobe_url_seconds", boom)
|
monkeypatch.setattr(metering, "_ffprobe_url_seconds", boom)
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
metering.probe_url_minutes("https://cdn.example.com/v.mp4")
|
metering.probe_url_minutes("https://cdn.example.com/v.mp4")
|
||||||
|
|
||||||
|
|
||||||
|
class TestStaticsBotCheckedVerdict:
|
||||||
|
"""When every static answers the bot-check and the paid proxy answers the
|
||||||
|
video, the probe leaves a one-shot verdict for the download to skip the
|
||||||
|
statics (main.plan_download_attempts skip_statics)."""
|
||||||
|
|
||||||
|
def _fake_ydl(self, monkeypatch, paid):
|
||||||
|
import types, sys, security_utils
|
||||||
|
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
|
||||||
|
class _YDL:
|
||||||
|
def __init__(self, opts): self.proxy = opts.get("proxy")
|
||||||
|
def __enter__(self): return self
|
||||||
|
def __exit__(self, *a): return False
|
||||||
|
def extract_info(self_, url, download=False):
|
||||||
|
if self_.proxy == paid:
|
||||||
|
return {"extractor": "youtube", "duration": 600}
|
||||||
|
raise RuntimeError("ERROR: [youtube] x: Sign in to confirm you're not a bot.")
|
||||||
|
monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL))
|
||||||
|
|
||||||
|
def test_verdict_is_left_once_and_popped(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1,http://s2")
|
||||||
|
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||||
|
monkeypatch.delenv("DIRECT_FIRST", raising=False)
|
||||||
|
monkeypatch.delenv("YOUTUBE_COOKIES", raising=False)
|
||||||
|
self._fake_ydl(monkeypatch, "http://paid")
|
||||||
|
metering._static_bot_verdicts.clear()
|
||||||
|
metering.pop_paid_probe_events()
|
||||||
|
url = "https://www.youtube.com/watch?v=eWpDO6w362Q"
|
||||||
|
assert metering.probe_url_minutes(url) == 10.0
|
||||||
|
assert metering.pop_statics_bot_checked(url) is True
|
||||||
|
assert metering.pop_statics_bot_checked(url) is False
|
||||||
|
assert metering.pop_paid_probe_events() # the paid probe is still recorded
|
||||||
|
|
||||||
|
def test_no_verdict_when_a_static_failed_for_another_reason(self, monkeypatch):
|
||||||
|
monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1")
|
||||||
|
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||||
|
monkeypatch.delenv("DIRECT_FIRST", raising=False)
|
||||||
|
monkeypatch.delenv("YOUTUBE_COOKIES", raising=False)
|
||||||
|
import types, sys, security_utils
|
||||||
|
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
|
||||||
|
class _YDL:
|
||||||
|
def __init__(self, opts): self.proxy = opts.get("proxy")
|
||||||
|
def __enter__(self): return self
|
||||||
|
def __exit__(self, *a): return False
|
||||||
|
def extract_info(self_, url, download=False):
|
||||||
|
if self_.proxy == "http://paid":
|
||||||
|
return {"extractor": "youtube", "duration": 600}
|
||||||
|
raise RuntimeError("HTTP Error 429: Too Many Requests")
|
||||||
|
monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL))
|
||||||
|
metering._static_bot_verdicts.clear()
|
||||||
|
url = "https://www.youtube.com/watch?v=abcdefghijk"
|
||||||
|
assert metering.probe_url_minutes(url) == 10.0
|
||||||
|
assert metering.pop_statics_bot_checked(url) is False
|
||||||
|
metering.pop_paid_probe_events()
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue