返回 last30days-skill
test_youtube_transcript_budget.py
根目录 / tests / test_youtube_transcript_budget.py
1 """YouTube keeps time for transcripts and stops hammering yt-dlp after a block."""
2
3 import json
4 import os
5 import shutil
6 import sys
7 import threading
8
9 import pytest
10
11 from lib import subproc, youtube_yt
12
13
14 _START = 1_000.0
15 # Lane return point is the spend deadline minus the 10s hand-back margin.
16 _INITIAL_SECONDS_LEFT = 170.0
17
18
19 def _item(video_id: str) -> dict:
20 return {
21 "video_id": video_id,
22 "title": "Placeholder video",
23 "date": "2026-10-01",
24 "engagement": {"views": 10},
25 }
26
27
28 def _install_clock(monkeypatch, now: float) -> dict:
29 clock = {"now": now}
30 monkeypatch.setattr(youtube_yt.time, "monotonic", lambda: clock["now"])
31 return clock
32
33
34 def _run_expanded_searches(
35 monkeypatch,
36 *,
37 depth: str,
38 seconds_left_after_first: float,
39 first_items: list,
40 ):
41 clock = _install_clock(monkeypatch, _START)
42 searches = []
43
44 def fake_search(query, *_args, **_kwargs):
45 searches.append(query)
46 if len(searches) == 1:
47 used = _INITIAL_SECONDS_LEFT - seconds_left_after_first
48 clock["now"] += used
49 return {"items": list(first_items)}
50 return {"items": [_item("later")]}
51
52 monkeypatch.setattr(
53 youtube_yt, "expand_youtube_queries", lambda *_a, **_k: ["one", "two", "three"],
54 )
55 def fake_transcripts(video_ids, **_kwargs):
56 return {video_id: "placeholder transcript words" for video_id in video_ids}
57
58 monkeypatch.setattr(youtube_yt, "search_youtube", fake_search)
59 monkeypatch.setattr(youtube_yt, "fetch_transcripts_parallel", fake_transcripts)
60 deadline = _START + youtube_yt._LANE_RETURN_MARGIN_SECONDS + _INITIAL_SECONDS_LEFT
61 with youtube_yt.sc_spend_until(lambda: False, deadline=deadline):
62 result = youtube_yt.search_and_transcribe(
63 "placeholder topic", "2026-09-01", "2026-10-23", depth=depth,
64 )
65 return searches, result
66
67
68 def test_deep_search_does_not_start_when_time_left_is_under_the_reserve(monkeypatch):
69 searches, result = _run_expanded_searches(
70 monkeypatch, depth="deep", seconds_left_after_first=70.0, first_items=[_item("vidA")],
71 )
72
73 assert searches == ["one"]
74 assert "out_of_time" not in result
75
76
77 def test_default_search_still_starts_when_its_smaller_reserve_is_left(monkeypatch):
78 searches, result = _run_expanded_searches(
79 monkeypatch, depth="default", seconds_left_after_first=70.0, first_items=[_item("vidA")],
80 )
81
82 assert searches == ["one", "two", "three"]
83 assert "out_of_time" not in result
84
85
86 def test_default_search_does_not_start_when_time_left_is_under_its_reserve(monkeypatch):
87 searches, _result = _run_expanded_searches(
88 monkeypatch, depth="default", seconds_left_after_first=50.0, first_items=[_item("vidA")],
89 )
90
91 assert searches == ["one"]
92
93
94 def test_empty_first_search_still_runs_the_next_one_under_the_reserve(monkeypatch):
95 searches, _result = _run_expanded_searches(
96 monkeypatch, depth="deep", seconds_left_after_first=50.0, first_items=[],
97 )
98
99 # No videos yet, so the next search still runs. Once it finds one, the
100 # reserve stops a further search.
101 assert searches == ["one", "two"]
102
103
104 def test_without_a_lane_deadline_every_expanded_search_runs(monkeypatch):
105 searches = []
106
107 def fake_search(query, *_args, **_kwargs):
108 searches.append(query)
109 return {"items": [_item("vidA")]}
110
111 monkeypatch.setattr(
112 youtube_yt, "expand_youtube_queries", lambda *_a, **_k: ["one", "two", "three"],
113 )
114 monkeypatch.setattr(youtube_yt, "search_youtube", fake_search)
115 monkeypatch.setattr(
116 youtube_yt, "fetch_transcripts_parallel",
117 lambda video_ids, **_kwargs: {video_id: "placeholder transcript words" for video_id in video_ids},
118 )
119
120 youtube_yt.search_and_transcribe(
121 "placeholder topic", "2026-09-01", "2026-10-23", depth="deep",
122 )
123
124 assert searches == ["one", "two", "three"]
125
126
127 def _transcript_commands(monkeypatch, stderr: str):
128 calls = []
129
130 def fake_run(cmd, timeout=30, **_kwargs):
131 video_id = next(
132 (str(part).rsplit("v=", 1)[-1] for part in cmd if "watch?v=" in str(part)),
133 "",
134 )
135 calls.append(video_id)
136 return subproc.SubprocResult(returncode=1, stdout="", stderr=stderr)
137
138 monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True)
139 monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None)
140 monkeypatch.setattr(youtube_yt, "_transcript_backoff", lambda *_a, **_k: 0.0)
141 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
142 return calls
143
144
145 @pytest.mark.parametrize(
146 "stderr",
147 [
148 "ERROR: Sign in to confirm you're not a bot",
149 "ERROR: HTTP Error 429: Too Many Requests",
150 ],
151 )
152 def test_after_a_block_later_transcripts_skip_ytdlp_for_scrapecreators(monkeypatch, stderr):
153 ytdlp_calls = _transcript_commands(monkeypatch, stderr)
154 sc_calls = []
155
156 def fake_sc(video_id, _token):
157 sc_calls.append(video_id)
158 return "placeholder transcript words about the topic"
159
160 monkeypatch.setattr(youtube_yt, "_sc_fetch_transcript", fake_sc)
161 monkeypatch.setattr(
162 youtube_yt, "_fetch_transcript_direct",
163 lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("direct HTTP after a block")),
164 )
165
166 results = youtube_yt.fetch_transcripts_parallel(
167 ["vidA", "vidB", "vidC"], max_workers=1, token="test-key",
168 )
169
170 assert ytdlp_calls == ["vidA"]
171 assert sc_calls == ["vidA", "vidB", "vidC"]
172 assert all(results[video_id] for video_id in ("vidA", "vidB", "vidC"))
173
174
175 @pytest.fixture
176 def ssh_transcript_runner(monkeypatch, tmp_path):
177 shell = shutil.which("sh", path=os.defpath)
178 if shell is None:
179 pytest.skip("POSIX shell required for the remote SSH script")
180 remote_tmp = tmp_path / "remote-tmp"
181 remote_tmp.mkdir()
182 run = subproc.run_with_timeout
183
184 def install(stderr, returncode=1, vtt=None):
185 executable = tmp_path / "yt-dlp"
186 executable.write_text(
187 f"#!{sys.executable}\n"
188 "import sys\n"
189 "from pathlib import Path\n"
190 f"vtt = {vtt!r}\n"
191 "if vtt is not None:\n"
192 " output = sys.argv[sys.argv.index('-o') + 1]\n"
193 " Path(output.replace('%(id)s', 'fixture') + '.en.vtt').write_text(vtt)\n"
194 f"sys.stderr.write({stderr!r})\n"
195 f"sys.exit({returncode})\n",
196 )
197 executable.chmod(0o755)
198 env = dict(os.environ, PATH=str(tmp_path) + os.pathsep + os.defpath,
199 TMPDIR=str(remote_tmp))
200 calls = []
201
202 def run_remote(cmd, *, timeout, **kwargs):
203 assert cmd[:5] == ["ssh", "-o", "BatchMode=yes", "--", "fixture-host"]
204 result = run([shell, "-c", cmd[-1]], timeout=timeout, env=env, **kwargs)
205 calls.append(result)
206 assert list(remote_tmp.iterdir()) == []
207 return result
208
209 monkeypatch.setenv("LAST30DAYS_YOUTUBE_SSH_HOST", "fixture-host")
210 monkeypatch.setattr(subproc, "run_with_timeout", run_remote)
211 return calls
212
213 return install
214
215
216 @pytest.mark.parametrize("stderr", [
217 "ERROR: Sign in to confirm you're not a bot",
218 "ERROR: HTTP Error 429: Too Many Requests",
219 ])
220 @pytest.mark.parametrize("vtt", [None, "WEBVTT\n\nSSH caption words\n"])
221 def test_ssh_block_skips_later_calls_and_preserves_vtt(
222 monkeypatch, ssh_transcript_runner, stderr, vtt,
223 ):
224 calls = ssh_transcript_runner(stderr, vtt=vtt)
225 released_block_states = []
226 release = youtube_yt._ytdlp_slots.release
227
228 def record_release():
229 released_block_states.append(youtube_yt._youtube_transcripts_blocked())
230 release()
231
232 sc_calls = []
233
234 def rescue(video_id, _token):
235 sc_calls.append(video_id)
236 return "rescued transcript words"
237
238 monkeypatch.setattr(youtube_yt._ytdlp_slots, "release", record_release)
239 monkeypatch.setattr(youtube_yt, "_sc_fetch_transcript", rescue)
240 monkeypatch.setattr(
241 youtube_yt, "_fetch_transcript_direct",
242 lambda *_a, **_k: pytest.fail("direct HTTP after a keyed SSH block"),
243 )
244
245 results = youtube_yt.fetch_transcripts_parallel(
246 ["vidA", "vidB"], max_workers=1, token="test-key",
247 )
248
249 assert len(calls) == 1
250 assert calls[0].returncode == 1
251 assert calls[0].stderr == stderr
252 assert calls[0].stdout == (vtt or "")
253 assert released_block_states == [True]
254 assert sc_calls == (["vidB"] if vtt else ["vidA", "vidB"])
255 assert results["vidA"] == ("SSH caption words" if vtt else "rescued transcript words")
256 assert results["vidB"] == "rescued transcript words"
257
258
259 @pytest.mark.parametrize("stderr,returncode,token", [
260 ("ERROR: Sign in to confirm you're not a bot", 1, None),
261 ("ERROR: connection refused", 1, "test-key"),
262 ("", 0, "test-key"),
263 ])
264 def test_ssh_without_a_key_or_block_keeps_direct_fallback(
265 monkeypatch, ssh_transcript_runner, stderr, returncode, token,
266 ):
267 calls = ssh_transcript_runner(stderr, returncode=returncode)
268 direct_calls = []
269
270 def direct(video_id, **_kwargs):
271 direct_calls.append(video_id)
272 return "WEBVTT\n\ndirect caption words\n"
273
274 monkeypatch.setattr(youtube_yt, "_fetch_transcript_direct", direct)
275 monkeypatch.setattr(
276 youtube_yt, "_sc_fetch_transcript",
277 lambda *_a, **_k: pytest.fail("paid fallback after a direct transcript"),
278 )
279
280 results = youtube_yt.fetch_transcripts_parallel(
281 ["vidA", "vidB"], max_workers=1, token=token,
282 )
283
284 assert len(calls) == 2
285 assert direct_calls == ["vidA", "vidB"]
286 assert results == {"vidA": "direct caption words", "vidB": "direct caption words"}
287
288
289 def test_workers_waiting_for_a_slot_skip_ytdlp_after_a_block(monkeypatch):
290 # Five workers, two slots. The two that hold a slot must not finish until
291 # the other three are queued in acquire, so every worker has already passed
292 # the check that happens before the wait.
293 videos = ["vidA", "vidB", "vidC", "vidD", "vidE"]
294 state = {"inside": 0, "waiting": 0, "timed_acquires": 0}
295 lock = threading.Lock()
296 queued = threading.Event()
297 ytdlp_calls = []
298
299 def _note_progress():
300 if state["inside"] >= 2 and state["waiting"] >= 3:
301 queued.set()
302
303 class _Gate:
304 def __init__(self):
305 self._sem = threading.Semaphore(2)
306
307 def acquire(self, blocking=True, timeout=None):
308 with lock:
309 state["waiting"] += 1
310 if timeout is not None:
311 state["timed_acquires"] += 1
312 _note_progress()
313 try:
314 if timeout is None:
315 return self._sem.acquire(blocking=blocking)
316 return self._sem.acquire(blocking=blocking, timeout=timeout)
317 finally:
318 with lock:
319 state["waiting"] -= 1
320
321 def release(self):
322 self._sem.release()
323
324 def __enter__(self):
325 self.acquire()
326 return self
327
328 def __exit__(self, *_args):
329 self.release()
330 return False
331
332 def fake_run(cmd, timeout=30, **_kwargs):
333 video_id = next(
334 (str(part).rsplit("v=", 1)[-1] for part in cmd if "watch?v=" in str(part)),
335 "",
336 )
337 with lock:
338 state["inside"] += 1
339 inside = state["inside"]
340 _note_progress()
341 if inside <= 2 and not queued.wait(5):
342 raise AssertionError("transcript workers did not queue for a yt-dlp slot")
343 ytdlp_calls.append(video_id)
344 return subproc.SubprocResult(
345 returncode=1,
346 stdout="",
347 stderr="ERROR: Sign in to confirm you're not a bot",
348 )
349
350 def fake_sc(video_id, _token):
351 sc_calls.append(video_id)
352 return "placeholder transcript words about the topic"
353
354 sc_calls = []
355 monkeypatch.setattr(youtube_yt, "_ytdlp_slots", _Gate())
356 monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True)
357 monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None)
358 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
359 monkeypatch.setattr(youtube_yt, "_sc_fetch_transcript", fake_sc)
360 monkeypatch.setattr(
361 youtube_yt, "_fetch_transcript_direct",
362 lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("direct HTTP after a block")),
363 )
364
365 deadline = youtube_yt.time.monotonic() + youtube_yt._LANE_RETURN_MARGIN_SECONDS + 100.0
366 with youtube_yt.sc_spend_until(lambda: False, deadline=deadline):
367 results = youtube_yt.fetch_transcripts_parallel(
368 videos, max_workers=5, token="test-key",
369 )
370
371 assert state["timed_acquires"] == 5
372 assert len(ytdlp_calls) == 2
373 assert sorted(sc_calls) == videos
374 assert all(results[video_id] for video_id in videos)
375
376
377 def test_timeout_does_not_send_later_transcripts_straight_to_scrapecreators(monkeypatch):
378 ytdlp_calls = []
379
380 def fake_run(cmd, timeout=30, **_kwargs):
381 video_id = next(
382 (str(part).rsplit("v=", 1)[-1] for part in cmd if "watch?v=" in str(part)),
383 "",
384 )
385 ytdlp_calls.append(video_id)
386 raise subproc.SubprocTimeout(f"Command yt-dlp timed out after {timeout}s")
387
388 monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True)
389 monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None)
390 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
391 monkeypatch.setattr(
392 youtube_yt, "_sc_fetch_transcript",
393 lambda _video_id, _token: "placeholder transcript words about the topic",
394 )
395
396 youtube_yt.fetch_transcripts_parallel(
397 ["vidA", "vidB"], max_workers=1, token="test-key",
398 )
399
400 assert ytdlp_calls == ["vidA", "vidB"]
401
402
403 def test_block_without_a_scrapecreators_key_still_tries_ytdlp(monkeypatch):
404 ytdlp_calls = _transcript_commands(
405 monkeypatch, "ERROR: Sign in to confirm you're not a bot",
406 )
407 sc_calls = []
408 monkeypatch.setattr(
409 youtube_yt, "_sc_fetch_transcript",
410 lambda video_id, _token: sc_calls.append(video_id),
411 )
412
413 youtube_yt.fetch_transcripts_parallel(
414 ["vidA", "vidB"], max_workers=1, token=None,
415 )
416
417 assert ytdlp_calls == ["vidA", "vidA", "vidA", "vidB", "vidB", "vidB"]
418 assert sc_calls == []
419
420
421 def test_search_bot_check_sends_transcripts_straight_to_scrapecreators(monkeypatch):
422 # yt-dlp prints a video, then exits on a bot-check. search_youtube keeps
423 # the video and does not return an error, so the block has to come from stderr.
424 ytdlp_calls = []
425 direct_calls = []
426 sc_calls = []
427 video = {
428 "id": "vidA",
429 "title": "Placeholder video",
430 "view_count": 10,
431 "like_count": 1,
432 "comment_count": 0,
433 "upload_date": "20261001",
434 "description": "placeholder",
435 "channel": "Placeholder",
436 }
437
438 def fake_run(cmd, timeout=30, **_kwargs):
439 blob = " ".join(str(part) for part in cmd)
440 if "ytsearch" in blob:
441 return subproc.SubprocResult(
442 returncode=1,
443 stdout=json.dumps(video) + "\n",
444 stderr="ERROR: Sign in to confirm you're not a bot",
445 )
446 video_id = next(
447 (str(part).rsplit("v=", 1)[-1] for part in cmd if "watch?v=" in str(part)),
448 "",
449 )
450 ytdlp_calls.append(video_id)
451 return subproc.SubprocResult(
452 returncode=1,
453 stdout="",
454 stderr="ERROR: Sign in to confirm you're not a bot",
455 )
456
457 def fake_sc(video_id, _token):
458 sc_calls.append(video_id)
459 return "placeholder transcript words about the topic"
460
461 monkeypatch.setattr(youtube_yt, "expand_youtube_queries", lambda *_a, **_k: ["one"])
462 monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True)
463 monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None)
464 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
465 monkeypatch.setattr(
466 youtube_yt, "_fetch_transcript_direct",
467 lambda video_id, *_a, **_k: direct_calls.append(video_id),
468 )
469 monkeypatch.setattr(youtube_yt, "_sc_fetch_transcript", fake_sc)
470 youtube_yt.reset_search_cache()
471 try:
472 result = youtube_yt.search_and_transcribe(
473 "placeholder topic", "2026-09-01", "2026-10-23", depth="default", token="test-key",
474 )
475 finally:
476 youtube_yt.reset_search_cache()
477
478 assert [item["video_id"] for item in result["items"]] == ["vidA"]
479 assert "error" not in result
480 assert ytdlp_calls == []
481 assert direct_calls == []
482 assert sc_calls == ["vidA"]
483 assert result["items"][0]["transcript_snippet"]
484
485
486 def test_expired_lane_names_the_deadline_instead_of_the_fast_timeout(monkeypatch, tmp_path, capsys):
487 monkeypatch.setattr(youtube_yt.time, "monotonic", lambda: _START)
488 status = {}
489 with youtube_yt.sc_spend_until(lambda: False, deadline=_START):
490 transcript = youtube_yt._fetch_transcript_ytdlp(
491 "vidA", str(tmp_path), status=status, fast_fail=True,
492 )
493
494 assert transcript is None
495 assert "lane deadline" in status["ytdlp_error"].lower()
496 assert "12" not in status["ytdlp_error"]
497 logged = capsys.readouterr().err
498 assert "lane deadline" in logged.lower()
499 assert "timed out after 12" not in logged
500
501
502 def test_short_lane_budget_is_not_logged_as_the_fast_timeout(monkeypatch, tmp_path, capsys):
503 monkeypatch.setattr(youtube_yt.time, "monotonic", lambda: _START)
504 seen = {}
505
506 def fake_run(_cmd, timeout=30, **_kwargs):
507 seen["timeout"] = timeout
508 raise subproc.SubprocTimeout(f"Command yt-dlp timed out after {timeout}s")
509
510 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
511 status = {}
512 # 3 seconds of lane time, under the 12s fast attempt.
513 with youtube_yt.sc_spend_until(
514 lambda: False,
515 deadline=_START + youtube_yt._LANE_RETURN_MARGIN_SECONDS + 3.0,
516 ):
517 transcript = youtube_yt._fetch_transcript_ytdlp(
518 "vidA", str(tmp_path), status=status, fast_fail=True,
519 )
520
521 assert transcript is None
522 assert seen["timeout"] == pytest.approx(3.0)
523 assert "lane deadline" in status["ytdlp_error"].lower()
524 assert "timed out after 12" not in capsys.readouterr().err
525
526
527 def test_full_attempt_timeout_keeps_its_own_message(monkeypatch, tmp_path):
528 monkeypatch.setattr(youtube_yt.time, "monotonic", lambda: _START)
529
530 def fake_run(_cmd, timeout=30, **_kwargs):
531 raise subproc.SubprocTimeout(f"Command yt-dlp timed out after {timeout}s")
532
533 monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run)
534 status = {}
535 with youtube_yt.sc_spend_until(
536 lambda: False,
537 deadline=_START + youtube_yt._LANE_RETURN_MARGIN_SECONDS + 100.0,
538 ):
539 youtube_yt._fetch_transcript_ytdlp(
540 "vidA", str(tmp_path), status=status, fast_fail=True,
541 )
542
543 assert status["ytdlp_error"] == "timed out after 12.0s"
544
544 lines PYTHON