| 1 | """A YouTube lane that runs into the stream deadline keeps the videos it found.""" |
| 2 | |
| 3 | import json |
| 4 | import threading |
| 5 | import time |
| 6 | |
| 7 | import pytest |
| 8 | |
| 9 | from lib import fetch_memo, health, pipeline, youtube_yt |
| 10 | |
| 11 | |
| 12 | def _plan(topic: str) -> dict: |
| 13 | return { |
| 14 | "intent": "comparison", |
| 15 | "freshness_mode": "balanced_recent", |
| 16 | "cluster_mode": "story", |
| 17 | "subqueries": [{ |
| 18 | "label": "primary", |
| 19 | "search_query": topic, |
| 20 | "ranking_query": topic, |
| 21 | "sources": ["youtube"], |
| 22 | "weight": 1.0, |
| 23 | }], |
| 24 | "source_weights": {"youtube": 1.0}, |
| 25 | } |
| 26 | |
| 27 | |
| 28 | def _search_payload(cmd, videos: int) -> str: |
| 29 | query = next(str(part) for part in cmd if "ytsearch" in str(part)) |
| 30 | slug = query.split(":", 1)[-1] |
| 31 | return "\n".join( |
| 32 | json.dumps({ |
| 33 | "id": f"video-{n:02d}", |
| 34 | "title": f"Alpha video {n}", |
| 35 | "description": slug, |
| 36 | "channel": "Desk", |
| 37 | "view_count": 1000 + n, |
| 38 | "upload_date": "20261015", |
| 39 | }) |
| 40 | for n in range(videos) |
| 41 | ) + "\n" |
| 42 | |
| 43 | |
| 44 | def _run_lane( |
| 45 | monkeypatch, *, transcript_seconds: float, later_search_seconds: float = 0.0, |
| 46 | videos: int = 30, calls: dict | None = None, first_search_seconds: float = 0.0, |
| 47 | sc_key: bool = False, failing_first_searches: int = 0, |
| 48 | ): |
| 49 | calls = {"search": 0, "transcript": 0} if calls is None else calls |
| 50 | |
| 51 | def fake_run(cmd, timeout=120, **kwargs): |
| 52 | if any("ytsearch" in str(part) for part in cmd): |
| 53 | calls["search"] += 1 |
| 54 | if calls["search"] <= failing_first_searches: |
| 55 | raise youtube_yt.subproc.SubprocTimeout("search timed out") |
| 56 | slow = first_search_seconds if calls["search"] == 1 else later_search_seconds |
| 57 | if slow: |
| 58 | time.sleep(min(slow, timeout)) |
| 59 | if timeout < slow: |
| 60 | raise youtube_yt.subproc.SubprocTimeout("search timed out") |
| 61 | return youtube_yt.subproc.SubprocResult( |
| 62 | returncode=0, stdout=_search_payload(cmd, videos), stderr="", |
| 63 | ) |
| 64 | return youtube_yt.subproc.SubprocResult(returncode=1, stdout="", stderr="") |
| 65 | |
| 66 | released = threading.Event() |
| 67 | |
| 68 | def slow_transcript(video_id, *args, **kwargs): |
| 69 | calls["transcript"] += 1 |
| 70 | released.wait(transcript_seconds) |
| 71 | return f"{video_id} explains the comparison with specific numbers." |
| 72 | |
| 73 | def paid_search(*args, **kwargs): |
| 74 | calls["sc_search"] = calls.get("sc_search", 0) + 1 |
| 75 | return {"items": []} |
| 76 | |
| 77 | monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 3.0) |
| 78 | monkeypatch.setattr(pipeline, "THIN_RETRY_FUTURE_TIMEOUT_SECONDS", 3.0) |
| 79 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 1.0, raising=False) |
| 80 | monkeypatch.setattr(pipeline, "which", lambda cmd: "/usr/bin/yt-dlp" if cmd == "yt-dlp" else None) |
| 81 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True) |
| 82 | monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run) |
| 83 | monkeypatch.setattr(youtube_yt, "fetch_transcript", slow_transcript) |
| 84 | monkeypatch.setattr(youtube_yt, "enrich_with_comments", lambda items, token, **k: items) |
| 85 | monkeypatch.setattr(youtube_yt, "search_youtube_sc", paid_search) |
| 86 | config = {"EXCLUDE_SOURCES": "youtube_comments"} |
| 87 | if sc_key: |
| 88 | config["SCRAPECREATORS_API_KEY"] = "test-key" |
| 89 | youtube_yt.reset_search_cache() |
| 90 | fetch_memo.reset() |
| 91 | try: |
| 92 | report = pipeline.run( |
| 93 | topic="Alpha", |
| 94 | config=config, |
| 95 | depth="deep", |
| 96 | requested_sources=["youtube"], |
| 97 | mock=False, |
| 98 | external_plan=_plan("Alpha"), |
| 99 | web_backend="none", |
| 100 | lookback_days=30, |
| 101 | as_of_date="2026-10-23", |
| 102 | internal_subrun=True, |
| 103 | ) |
| 104 | finally: |
| 105 | released.set() |
| 106 | youtube_yt.reset_search_cache() |
| 107 | fetch_memo.reset() |
| 108 | return report.source_status["youtube"] |
| 109 | |
| 110 | |
| 111 | def test_slow_transcripts_do_not_discard_found_videos(monkeypatch): |
| 112 | outcome = _run_lane(monkeypatch, transcript_seconds=5.0) |
| 113 | |
| 114 | assert outcome.items_returned > 0, (outcome.state, outcome.detail) |
| 115 | assert outcome.state == health.PARTIAL, (outcome.state, outcome.detail) |
| 116 | assert "transcript" in (outcome.detail or "") |
| 117 | |
| 118 | |
| 119 | def test_slow_search_is_cut_off_at_the_lane_deadline(monkeypatch): |
| 120 | outcome = _run_lane(monkeypatch, transcript_seconds=0.0, later_search_seconds=30.0) |
| 121 | |
| 122 | assert outcome.items_returned > 0, (outcome.state, outcome.detail) |
| 123 | assert outcome.state != health.TIMEOUT, (outcome.state, outcome.detail) |
| 124 | |
| 125 | |
| 126 | def test_out_of_time_lane_does_no_more_youtube_work(monkeypatch): |
| 127 | calls = {"search": 0, "transcript": 0} |
| 128 | outcome = _run_lane(monkeypatch, transcript_seconds=4.0, videos=1, calls=calls) |
| 129 | |
| 130 | assert outcome.state == health.PARTIAL, (outcome.state, outcome.detail) |
| 131 | assert calls["transcript"] == 1, calls |
| 132 | |
| 133 | |
| 134 | def test_lane_with_no_videos_at_the_deadline_is_not_retried(monkeypatch): |
| 135 | calls = {"search": 0, "transcript": 0} |
| 136 | outcome = _run_lane(monkeypatch, transcript_seconds=0.0, first_search_seconds=30.0, calls=calls) |
| 137 | |
| 138 | assert outcome.state == health.TIMEOUT, (outcome.state, outcome.detail) |
| 139 | assert calls["search"] == 1, calls |
| 140 | |
| 141 | |
| 142 | def test_out_of_time_lane_buys_no_scrapecreators_backfill(monkeypatch): |
| 143 | calls = {"search": 0, "transcript": 0} |
| 144 | outcome = _run_lane(monkeypatch, transcript_seconds=4.0, videos=1, calls=calls, sc_key=True) |
| 145 | |
| 146 | assert outcome.state == health.PARTIAL, (outcome.state, outcome.detail) |
| 147 | assert calls.get("sc_search", 0) == 0, calls |
| 148 | assert calls["transcript"] == 1, calls |
| 149 | |
| 150 | |
| 151 | def test_transcript_past_the_lane_deadline_buys_no_scrapecreators_rescue(monkeypatch, tmp_path): |
| 152 | paid = [] |
| 153 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 10.0, raising=False) |
| 154 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True) |
| 155 | monkeypatch.setattr(youtube_yt, "_ytdlp_ssh_host", lambda: None) |
| 156 | monkeypatch.setattr(youtube_yt, "_sc_fetch_transcript", lambda *a, **k: paid.append(a) or "bought") |
| 157 | with youtube_yt.sc_spend_until(lambda: False, deadline=time.monotonic() + 5): |
| 158 | transcript = youtube_yt.fetch_transcript("vid", str(tmp_path), {}, "test-key") |
| 159 | |
| 160 | assert transcript is None |
| 161 | assert paid == [] |
| 162 | |
| 163 | |
| 164 | def test_lane_whose_transcripts_all_fail_at_the_deadline_is_out_of_time(monkeypatch): |
| 165 | def failed_at_deadline(video_ids, **kwargs): |
| 166 | while not youtube_yt._lane_out_of_time(): |
| 167 | time.sleep(0.01) |
| 168 | return {vid: None for vid in video_ids} |
| 169 | |
| 170 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 0.0, raising=False) |
| 171 | monkeypatch.setattr(youtube_yt, "search_youtube", lambda *a, **k: { |
| 172 | "items": [{"video_id": "video-00", "engagement": {"views": 1000}}], |
| 173 | }) |
| 174 | monkeypatch.setattr(youtube_yt, "fetch_transcripts_parallel", failed_at_deadline) |
| 175 | with youtube_yt.sc_spend_until(lambda: False, deadline=time.monotonic() + 0.5): |
| 176 | result = youtube_yt.search_and_transcribe("Alpha", "2026-09-23", "2026-10-23") |
| 177 | |
| 178 | assert result["items"], result |
| 179 | assert result.get("out_of_time"), result |
| 180 | |
| 181 | |
| 182 | def test_retry_that_runs_out_of_time_does_no_more_youtube_work(monkeypatch): |
| 183 | calls = {"search": 0, "transcript": 0} |
| 184 | outcome = _run_lane( |
| 185 | monkeypatch, transcript_seconds=4.0, videos=1, calls=calls, failing_first_searches=3, |
| 186 | ) |
| 187 | |
| 188 | assert calls["search"] > 3, calls |
| 189 | assert outcome.state == health.PARTIAL, (outcome.state, outcome.detail) |
| 190 | assert calls["transcript"] == 1, calls |
| 191 | |
| 192 | |
| 193 | def test_lane_that_finishes_in_time_is_not_partial(monkeypatch): |
| 194 | outcome = _run_lane(monkeypatch, transcript_seconds=0.0) |
| 195 | |
| 196 | assert outcome.items_returned > 0, (outcome.state, outcome.detail) |
| 197 | assert outcome.state != health.PARTIAL, (outcome.state, outcome.detail) |
| 198 | assert outcome.state != health.TIMEOUT, (outcome.state, outcome.detail) |
| 199 | |
| 200 | |
| 201 | @pytest.mark.parametrize("sc_key", [False, True]) |
| 202 | def test_comment_deadline_preserves_videos_without_restarting_work(monkeypatch, sc_key): |
| 203 | expired = threading.Event() |
| 204 | late_calls = [] |
| 205 | comments_started = [] |
| 206 | |
| 207 | def fake_run(cmd, timeout=120, **kwargs): |
| 208 | if expired.is_set(): |
| 209 | late_calls.append(cmd) |
| 210 | if any("ytsearch" in str(part) for part in cmd): |
| 211 | return youtube_yt.subproc.SubprocResult( |
| 212 | returncode=0, stdout=_search_payload(cmd, 1), stderr="", |
| 213 | ) |
| 214 | if "--write-comments" in cmd: |
| 215 | comments_started.append(cmd) |
| 216 | time.sleep(timeout) |
| 217 | expired.set() |
| 218 | raise youtube_yt.subproc.SubprocTimeout("comment deadline reached") |
| 219 | return youtube_yt.subproc.SubprocResult( |
| 220 | returncode=1, stdout="", stderr="fixture transcript unavailable", |
| 221 | ) |
| 222 | |
| 223 | def paid_get(url, **kwargs): |
| 224 | if expired.is_set(): |
| 225 | late_calls.append(url) |
| 226 | return {"transcript": None, "comments": []} |
| 227 | |
| 228 | monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 3.0) |
| 229 | monkeypatch.setattr(pipeline, "THIN_RETRY_FUTURE_TIMEOUT_SECONDS", 3.0) |
| 230 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 1.0) |
| 231 | monkeypatch.setattr(pipeline, "which", lambda cmd: "/usr/bin/yt-dlp" if cmd == "yt-dlp" else None) |
| 232 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True) |
| 233 | monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run) |
| 234 | monkeypatch.setattr(youtube_yt.http, "get", paid_get) |
| 235 | config = {"LAST30DAYS_YT_SC_MIN_ITEMS": "0"} |
| 236 | if sc_key: |
| 237 | config["SCRAPECREATORS_API_KEY"] = "dummy-key" |
| 238 | youtube_yt.reset_search_cache() |
| 239 | try: |
| 240 | report = pipeline.run( |
| 241 | topic="Alpha", config=config, depth="default", |
| 242 | requested_sources=["youtube"], mock=False, |
| 243 | external_plan=_plan("Alpha"), web_backend="none", |
| 244 | lookback_days=30, as_of_date="2026-10-23", internal_subrun=True, |
| 245 | ) |
| 246 | finally: |
| 247 | youtube_yt.reset_search_cache() |
| 248 | |
| 249 | assert comments_started |
| 250 | assert late_calls == [] |
| 251 | outcome = report.source_status["youtube"] |
| 252 | assert outcome.items_returned > 0, (outcome.state, outcome.detail) |
| 253 | assert outcome.state == health.PARTIAL, (outcome.state, outcome.detail) |
| 254 | assert "timed out" in (outcome.detail or "") |
| 255 | |
| 256 | |
| 257 | @pytest.mark.parametrize("endpoint", ["comments", "search", "transcript"]) |
| 258 | def test_paid_enrichment_requests_end_at_the_lane_return_deadline(monkeypatch, endpoint): |
| 259 | requested_deadlines = [] |
| 260 | has_ytdlp = endpoint != "transcript" |
| 261 | |
| 262 | def fake_run(cmd, timeout=120, **kwargs): |
| 263 | if any("ytsearch" in str(part) for part in cmd): |
| 264 | return youtube_yt.subproc.SubprocResult( |
| 265 | returncode=0, stdout=_search_payload(cmd, 1), stderr="", |
| 266 | ) |
| 267 | return youtube_yt.subproc.SubprocResult( |
| 268 | returncode=1, stdout="", stderr="fixture yt-dlp unavailable", |
| 269 | ) |
| 270 | |
| 271 | def paid_get(url, **kwargs): |
| 272 | if url.endswith("/" + endpoint): |
| 273 | deadline = kwargs.get("deadline_monotonic") |
| 274 | requested_deadlines.append(deadline) |
| 275 | if deadline is not None: |
| 276 | time.sleep(max(0.0, deadline - time.monotonic())) |
| 277 | raise youtube_yt.http.DeadlineExceeded() |
| 278 | return {"videos": [{ |
| 279 | "id": "paid-video", "title": "Alpha", "date": "2026-10-15", "views": 10, |
| 280 | }]} |
| 281 | |
| 282 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 1.0) |
| 283 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: has_ytdlp) |
| 284 | monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run) |
| 285 | monkeypatch.setattr(youtube_yt.http, "get", paid_get) |
| 286 | deadline = time.monotonic() + 3.0 |
| 287 | config = { |
| 288 | "_research_deadline": deadline, |
| 289 | "SCRAPECREATORS_API_KEY": "dummy-key", |
| 290 | "LAST30DAYS_YT_SC_MIN_ITEMS": "3" if endpoint == "search" else "0", |
| 291 | "EXCLUDE_SOURCES": "" if endpoint == "comments" else "youtube_comments", |
| 292 | } |
| 293 | youtube_yt.reset_search_cache() |
| 294 | try: |
| 295 | items, artifact = pipeline._fetch_youtube_stream( |
| 296 | "Alpha", "2026-09-23", "2026-10-23", |
| 297 | "default" if endpoint == "transcript" else "quick", |
| 298 | config, has_ytdlp=has_ytdlp, |
| 299 | ) |
| 300 | finally: |
| 301 | youtube_yt.reset_search_cache() |
| 302 | |
| 303 | assert requested_deadlines |
| 304 | assert all(value is not None and value <= deadline - 1.0 for value in requested_deadlines) |
| 305 | assert len(requested_deadlines) == 1 |
| 306 | assert items |
| 307 | assert artifact.get("_source_out_of_time"), artifact |
| 308 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 309 | |
| 310 | |
| 311 | @pytest.mark.parametrize("fallback_fails", [False, True]) |
| 312 | def test_thin_fallback_expiry_keeps_videos_and_marks_the_lane(monkeypatch, fallback_fails): |
| 313 | clock = [100.0] |
| 314 | paid_calls = [] |
| 315 | |
| 316 | def fake_run(cmd, **kwargs): |
| 317 | return youtube_yt.subproc.SubprocResult( |
| 318 | returncode=0, stdout=_search_payload(cmd, 1), stderr="", |
| 319 | ) |
| 320 | |
| 321 | def paid_get(url, **kwargs): |
| 322 | paid_calls.append(url) |
| 323 | clock[0] = 102.0 |
| 324 | if fallback_fails: |
| 325 | raise youtube_yt.http.DeadlineExceeded() |
| 326 | return {"videos": [{ |
| 327 | "id": "paid-video", "title": "Alpha", "date": "2026-10-15", "views": 10, |
| 328 | }]} |
| 329 | |
| 330 | monkeypatch.setattr(youtube_yt.time, "monotonic", lambda: clock[0]) |
| 331 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 1.0) |
| 332 | monkeypatch.setattr(youtube_yt, "is_ytdlp_installed", lambda: True) |
| 333 | monkeypatch.setattr(youtube_yt.subproc, "run_with_timeout", fake_run) |
| 334 | monkeypatch.setattr(youtube_yt.http, "get", paid_get) |
| 335 | config = { |
| 336 | "_research_deadline": 102.0, |
| 337 | "SCRAPECREATORS_API_KEY": "dummy-key", |
| 338 | "EXCLUDE_SOURCES": "youtube_comments", |
| 339 | } |
| 340 | youtube_yt.reset_search_cache() |
| 341 | try: |
| 342 | items, artifact = pipeline._fetch_youtube_stream( |
| 343 | "Alpha", "2026-09-23", "2026-10-23", "quick", config, has_ytdlp=True, |
| 344 | ) |
| 345 | finally: |
| 346 | youtube_yt.reset_search_cache() |
| 347 | |
| 348 | assert len(paid_calls) == 1 |
| 349 | assert any(item["video_id"] == "video-00" for item in items) |
| 350 | assert artifact.get("_source_out_of_time"), artifact |
| 351 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 352 |