| 1 | import threading |
| 2 | from unittest import mock |
| 3 | |
| 4 | from lib import health, http, pipeline, schema, youtube_yt |
| 5 | |
| 6 | |
| 7 | def _youtube_stream(config, *, wrapped=False): |
| 8 | retrieve = pipeline._retrieve_stream if wrapped else pipeline._retrieve_stream_impl |
| 9 | return retrieve( |
| 10 | topic="Vuori", |
| 11 | subquery=schema.SubQuery( |
| 12 | label="q", search_query="Vuori", ranking_query="Vuori", sources=["youtube"], |
| 13 | ), |
| 14 | source="youtube", |
| 15 | config=config, |
| 16 | depth="default", |
| 17 | date_range=("2026-06-01", "2026-07-01"), |
| 18 | runtime=schema.ProviderRuntime( |
| 19 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", |
| 20 | ), |
| 21 | mock=False, |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | def test_one_free_video_triggers_backstop_and_preserves_its_transcript(): |
| 26 | free = {"video_id": "free", "transcript_snippet": "free transcript"} |
| 27 | paid = {"video_id": "paid", "transcript_snippet": "paid transcript"} |
| 28 | with ( |
| 29 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 30 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 31 | mock.patch.object( |
| 32 | youtube_yt, "search_youtube_sc", |
| 33 | return_value={"items": [{"video_id": "free", "transcript_snippet": ""}, paid]}, |
| 34 | ) as sc_search, |
| 35 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 36 | ): |
| 37 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 38 | |
| 39 | assert sc_search.call_count == 1 |
| 40 | assert [item["video_id"] for item in items] == ["free", "paid"] |
| 41 | assert items[0]["transcript_snippet"] == "free transcript" |
| 42 | assert "added 1" in artifact["_source_outcome_detail"] |
| 43 | assert "_source_outcome" not in artifact |
| 44 | |
| 45 | |
| 46 | def test_two_free_videos_merge_duplicate_transcript_without_replacing_free_metadata(): |
| 47 | free = [ |
| 48 | {"video_id": "a", "title": "free title", "transcript_snippet": ""}, |
| 49 | {"video_id": "b", "title": "other", "transcript_snippet": "free transcript"}, |
| 50 | ] |
| 51 | sc = [ |
| 52 | {"video_id": "a", "title": "paid title", "transcript_snippet": "rescued"}, |
| 53 | {"video_id": "c", "title": "new", "transcript_snippet": ""}, |
| 54 | ] |
| 55 | with ( |
| 56 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 57 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": free}), |
| 58 | mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": sc}) as search, |
| 59 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 60 | ): |
| 61 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 62 | |
| 63 | assert search.call_count == 1 |
| 64 | assert [item["video_id"] for item in items] == ["a", "b", "c"] |
| 65 | assert items[0]["title"] == "free title" |
| 66 | assert items[0]["transcript_snippet"] == "rescued" |
| 67 | assert items[1]["transcript_snippet"] == "free transcript" |
| 68 | assert free[0]["transcript_snippet"] == "" |
| 69 | assert "added 1" in artifact["_source_outcome_detail"] |
| 70 | |
| 71 | |
| 72 | def test_backfill_spends_transcript_calls_only_on_missing_or_new_videos(): |
| 73 | free = [ |
| 74 | {"video_id": "ready", "title": "free ready", "transcript_snippet": "free transcript"}, |
| 75 | {"video_id": "missing", "title": "free missing", "transcript_snippet": " "}, |
| 76 | ] |
| 77 | video_ids = ["ready", "missing", *(f"new{i}" for i in range(5))] |
| 78 | raw_search = [ |
| 79 | { |
| 80 | "id": video_id, "title": f"SC {video_id}", "date": "2026-06-15", |
| 81 | "views": 100 - index, |
| 82 | } |
| 83 | for index, video_id in enumerate(video_ids) |
| 84 | ] |
| 85 | with ( |
| 86 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 87 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": free}), |
| 88 | mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=raw_search) as search, |
| 89 | mock.patch.object( |
| 90 | youtube_yt, "_sc_fetch_transcript", |
| 91 | # new0 has no captions; the headroom moves on to new1 and new2. |
| 92 | side_effect=lambda video_id, token: ( |
| 93 | None if video_id == "new0" else f"paid transcript for {video_id}" |
| 94 | ), |
| 95 | ) as transcripts, |
| 96 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 97 | ): |
| 98 | items, _ = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 99 | |
| 100 | search.assert_called_once() |
| 101 | # Paid calls skip the free-transcribed video, and that free transcript |
| 102 | # counts toward the default-depth target of 2, so one paid success meets |
| 103 | # it instead of two more on top (#1315). |
| 104 | assert [call.args[0] for call in transcripts.call_args_list] == ["missing"] |
| 105 | assert [item["video_id"] for item in items] == video_ids |
| 106 | assert items[0]["title"] == "free ready" |
| 107 | assert items[0]["transcript_snippet"] == "free transcript" |
| 108 | assert items[1]["title"] == "free missing" |
| 109 | assert items[1]["transcript_snippet"] == "paid transcript for missing" |
| 110 | assert not items[3].get("transcript_snippet") |
| 111 | assert not items[-1].get("transcript_snippet") |
| 112 | |
| 113 | |
| 114 | def test_keyless_and_disabled_floor_keep_free_results_without_paid_search(): |
| 115 | free = {"video_id": "a", "transcript_snippet": ""} |
| 116 | with ( |
| 117 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 118 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 119 | mock.patch.object(youtube_yt, "search_youtube_sc") as search, |
| 120 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 121 | ): |
| 122 | for config in ( |
| 123 | {}, |
| 124 | {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YT_SC_MIN_ITEMS": "0"}, |
| 125 | {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YT_SC_MIN_ITEMS": "bad"}, |
| 126 | ): |
| 127 | items, artifact = _youtube_stream(config) |
| 128 | assert items == [free] |
| 129 | assert artifact == {} |
| 130 | search.assert_not_called() |
| 131 | |
| 132 | |
| 133 | def test_at_floor_does_not_backfill(): |
| 134 | free = [{"video_id": str(i)} for i in range(3)] |
| 135 | with ( |
| 136 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 137 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": free}), |
| 138 | mock.patch.object(youtube_yt, "search_youtube_sc") as search, |
| 139 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 140 | ): |
| 141 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 142 | assert items == free |
| 143 | assert artifact == {} |
| 144 | search.assert_not_called() |
| 145 | |
| 146 | |
| 147 | def test_custom_floor_backfills_three_free_videos(): |
| 148 | free = [{"video_id": str(i)} for i in range(3)] |
| 149 | with ( |
| 150 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 151 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": free}), |
| 152 | mock.patch.object( |
| 153 | youtube_yt, "search_youtube_sc", return_value={"items": [{"video_id": "new"}]}, |
| 154 | ) as search, |
| 155 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 156 | ): |
| 157 | items, artifact = _youtube_stream({ |
| 158 | "SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_YT_SC_MIN_ITEMS": "4", |
| 159 | }) |
| 160 | assert search.call_count == 1 |
| 161 | assert [item["video_id"] for item in items] == ["0", "1", "2", "new"] |
| 162 | assert "4-video backfill floor" in artifact["_source_outcome_detail"] |
| 163 | |
| 164 | |
| 165 | def test_paid_search_failure_keeps_free_video_and_reports_partial(): |
| 166 | free = {"video_id": "a", "transcript_snippet": "free transcript"} |
| 167 | with ( |
| 168 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 169 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 170 | mock.patch.object(youtube_yt, "search_youtube_sc", side_effect=RuntimeError("SC HTTP 429")) as search, |
| 171 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 172 | ): |
| 173 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 174 | assert search.call_count == 1 |
| 175 | assert items == [free] |
| 176 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 177 | assert "SC HTTP 429" in artifact["_source_outcome"]["detail"] |
| 178 | |
| 179 | |
| 180 | def test_paid_http_429_with_no_free_items_stays_rate_limited(): |
| 181 | def failed_sc(*args, **kwargs): |
| 182 | http._record_failure(http.HTTPError("SC HTTP 429", status_code=429)) |
| 183 | return {"items": []} |
| 184 | |
| 185 | with ( |
| 186 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 187 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": []}), |
| 188 | mock.patch.object(youtube_yt, "search_youtube_sc", side_effect=failed_sc), |
| 189 | ): |
| 190 | items, artifact = _youtube_stream( |
| 191 | {"SCRAPECREATORS_API_KEY": "dummy-key"}, wrapped=True, |
| 192 | ) |
| 193 | assert items == [] |
| 194 | assert artifact["_source_outcome"]["state"] == health.RATE_LIMITED |
| 195 | |
| 196 | |
| 197 | def test_paid_http_429_after_free_item_is_partial_not_source_rate_limit(): |
| 198 | def failed_sc(*args, **kwargs): |
| 199 | http._record_failure(http.HTTPError("SC HTTP 429", status_code=429)) |
| 200 | return {"items": []} |
| 201 | |
| 202 | free = {"video_id": "a"} |
| 203 | with ( |
| 204 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 205 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 206 | mock.patch.object(youtube_yt, "search_youtube_sc", side_effect=failed_sc), |
| 207 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 208 | ): |
| 209 | items, artifact = _youtube_stream( |
| 210 | {"SCRAPECREATORS_API_KEY": "dummy-key"}, wrapped=True, |
| 211 | ) |
| 212 | assert items == [free] |
| 213 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 214 | assert "rate" in artifact["_source_outcome"]["detail"].lower() |
| 215 | |
| 216 | |
| 217 | def test_partial_ytdlp_search_error_stays_visible_after_backfill(): |
| 218 | free = {"video_id": "a"} |
| 219 | with ( |
| 220 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 221 | mock.patch.object( |
| 222 | youtube_yt, "search_and_transcribe", |
| 223 | return_value={"items": [free], "error": "yt-dlp bot gate"}, |
| 224 | ), |
| 225 | mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": []}), |
| 226 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 227 | ): |
| 228 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 229 | assert items == [free] |
| 230 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 231 | assert "yt-dlp bot gate" in artifact["_source_outcome"]["detail"] |
| 232 | |
| 233 | |
| 234 | def test_full_pipeline_reports_clean_backfill_and_searches_paid_once_per_run(): |
| 235 | free = { |
| 236 | "video_id": "a", "title": "Vuori review", "date": "2026-06-15", |
| 237 | "url": "https://www.youtube.com/watch?v=a", "transcript_snippet": "free transcript", |
| 238 | } |
| 239 | paid = [ |
| 240 | { |
| 241 | "video_id": str(i), "title": f"Vuori review {i}", "date": "2026-06-15", |
| 242 | "url": f"https://www.youtube.com/watch?v={i}", "transcript_snippet": "", |
| 243 | } |
| 244 | for i in range(3) |
| 245 | ] |
| 246 | plan = { |
| 247 | "intent": "general", "freshness_mode": "balanced_recent", "cluster_mode": "story", |
| 248 | "subqueries": [ |
| 249 | {"label": "one", "search_query": "Vuori", "ranking_query": "Vuori", "sources": ["youtube"]}, |
| 250 | {"label": "two", "search_query": "Vuori reviews", "ranking_query": "Vuori", "sources": ["youtube"]}, |
| 251 | ], |
| 252 | "source_weights": {"youtube": 1.0}, |
| 253 | } |
| 254 | retrieve = pipeline._retrieve_stream |
| 255 | |
| 256 | def live_youtube(*args, **kwargs): |
| 257 | return retrieve(*args, **{**kwargs, "mock": False}) |
| 258 | |
| 259 | with ( |
| 260 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 261 | mock.patch.object(pipeline, "_retrieve_stream", side_effect=live_youtube), |
| 262 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 263 | mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": paid}) as search, |
| 264 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 265 | ): |
| 266 | report = pipeline.run( |
| 267 | topic="Vuori", config={"SCRAPECREATORS_API_KEY": "dummy-key"}, |
| 268 | depth="default", requested_sources=["youtube"], mock=True, |
| 269 | external_plan=plan, as_of_date="2026-07-01", |
| 270 | ) |
| 271 | |
| 272 | # Both subqueries search the raw topic: the run fetch memo serves the |
| 273 | # second stream (and the thin retry) from the first clean fetch. |
| 274 | assert search.call_count == 1 |
| 275 | assert report.source_status["youtube"].state == health.OK |
| 276 | assert "ScrapeCreators added 3" in report.source_status["youtube"].detail |
| 277 | |
| 278 | |
| 279 | def _run_thin_youtube_report(sc_responses): |
| 280 | free = { |
| 281 | "video_id": "free", "title": "Vuori review", "date": "2026-06-15", |
| 282 | "url": "https://www.youtube.com/watch?v=free", "transcript_snippet": "free transcript", |
| 283 | } |
| 284 | plan = { |
| 285 | "intent": "general", "freshness_mode": "balanced_recent", "cluster_mode": "story", |
| 286 | "subqueries": [{ |
| 287 | "label": "primary", "search_query": "Vuori", "ranking_query": "Vuori", |
| 288 | "sources": ["youtube"], |
| 289 | }], |
| 290 | "source_weights": {"youtube": 1.0}, |
| 291 | } |
| 292 | retrieve = pipeline._retrieve_stream |
| 293 | |
| 294 | def live_youtube(*args, **kwargs): |
| 295 | return retrieve(*args, **{**kwargs, "mock": False}) |
| 296 | |
| 297 | with ( |
| 298 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 299 | mock.patch.object(pipeline, "_retrieve_stream", side_effect=live_youtube), |
| 300 | mock.patch.object(youtube_yt, "search_and_transcribe", return_value={"items": [free]}), |
| 301 | mock.patch.object(youtube_yt, "search_youtube_sc", side_effect=sc_responses) as search, |
| 302 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 303 | ): |
| 304 | report = pipeline.run( |
| 305 | topic="Vuori", config={"SCRAPECREATORS_API_KEY": "dummy-key"}, |
| 306 | depth="default", requested_sources=["youtube"], mock=True, |
| 307 | external_plan=plan, as_of_date="2026-07-01", |
| 308 | ) |
| 309 | return report, search.call_count |
| 310 | |
| 311 | |
| 312 | def test_thin_retry_reuses_a_clean_empty_backfill_instead_of_refetching(): |
| 313 | # A clean (error-free) backfill is the answer for this query in this run: |
| 314 | # the identical thin-source retry is served from the run fetch memo. |
| 315 | unused = [ |
| 316 | { |
| 317 | "video_id": str(i), "title": f"Vuori review {i}", "date": "2026-06-15", |
| 318 | "url": f"https://www.youtube.com/watch?v={i}", |
| 319 | } |
| 320 | for i in range(2) |
| 321 | ] |
| 322 | report, calls = _run_thin_youtube_report([ |
| 323 | {"items": []}, {"items": unused}, |
| 324 | ]) |
| 325 | assert calls == 1 |
| 326 | assert report.source_status["youtube"].state == health.OK |
| 327 | assert [item.item_id for item in report.items_by_source["youtube"]] == ["free"] |
| 328 | |
| 329 | |
| 330 | def test_clean_sparse_topic_stays_ok_after_empty_backfill_and_retry(): |
| 331 | report, calls = _run_thin_youtube_report([{"items": []}, {"items": []}]) |
| 332 | assert calls == 1 |
| 333 | assert report.source_status["youtube"].state == health.OK |
| 334 | assert [item.item_id for item in report.items_by_source["youtube"]] == ["free"] |
| 335 | assert "added 0" in report.source_status["youtube"].detail |
| 336 | |
| 337 | |
| 338 | def test_paid_429_after_free_item_stops_paid_thin_retry(): |
| 339 | report, calls = _run_thin_youtube_report([ |
| 340 | {"items": [], "error": "SC HTTP 429"}, |
| 341 | ]) |
| 342 | assert calls == 1 |
| 343 | assert report.source_status["youtube"].state == health.PARTIAL |
| 344 | assert "429" in report.source_status["youtube"].detail |
| 345 | |
| 346 | |
| 347 | def test_transient_paid_failure_stays_partial_if_retry_finds_no_new_video(): |
| 348 | report, calls = _run_thin_youtube_report([ |
| 349 | {"items": [], "error": "SC connection reset"}, |
| 350 | {"items": [], "error": "SC connection reset"}, |
| 351 | ]) |
| 352 | assert calls == 2 |
| 353 | assert report.source_status["youtube"].state == health.PARTIAL |
| 354 | assert "connection reset" in report.source_status["youtube"].detail |
| 355 | |
| 356 | |
| 357 | def test_retry_error_stays_partial_even_when_retry_adds_a_video(): |
| 358 | new = { |
| 359 | "video_id": "new", "title": "Vuori review new", "date": "2026-06-15", |
| 360 | "url": "https://www.youtube.com/watch?v=new", |
| 361 | } |
| 362 | report, calls = _run_thin_youtube_report([ |
| 363 | {"items": [], "error": "SC connection reset"}, |
| 364 | {"items": [new], "error": "SC connection reset"}, |
| 365 | ]) |
| 366 | assert calls == 2 |
| 367 | assert "new" in {item.item_id for item in report.items_by_source["youtube"]} |
| 368 | assert report.source_status["youtube"].state == health.PARTIAL |
| 369 | assert "connection reset" in report.source_status["youtube"].detail |
| 370 | |
| 371 | |
| 372 | def test_ytdlp_bot_gate_and_paid_exception_do_not_retry_paid_search(): |
| 373 | free = {"video_id": "free"} |
| 374 | with ( |
| 375 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 376 | mock.patch.object( |
| 377 | youtube_yt, "search_and_transcribe", |
| 378 | return_value={"items": [free], "error": "Sign in to confirm you're not a bot"}, |
| 379 | ), |
| 380 | mock.patch.object( |
| 381 | youtube_yt, "search_youtube_sc", side_effect=RuntimeError("SC disconnected"), |
| 382 | ) as search, |
| 383 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 384 | ): |
| 385 | items, artifact = _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 386 | assert items == [free] |
| 387 | assert search.call_count == 1 |
| 388 | assert artifact["_source_outcome"]["state"] == health.PARTIAL |
| 389 | assert "not a bot" in artifact["_source_outcome"]["detail"] |
| 390 | assert "SC disconnected" in artifact["_source_outcome"]["detail"] |
| 391 | |
| 392 | |
| 393 | def test_freshness_mode_reaches_both_youtube_searches(): |
| 394 | """plan.freshness_mode is threaded into the yt-dlp and ScrapeCreators searches.""" |
| 395 | free = { |
| 396 | "video_id": "free", "title": "Vuori review", "date": "2026-06-15", |
| 397 | "url": "https://www.youtube.com/watch?v=free", "transcript_snippet": "free transcript", |
| 398 | } |
| 399 | plan = { |
| 400 | "intent": "how_to", "freshness_mode": "evergreen_ok", "cluster_mode": "story", |
| 401 | "subqueries": [{ |
| 402 | "label": "primary", "search_query": "Vuori", "ranking_query": "Vuori", |
| 403 | "sources": ["youtube"], |
| 404 | }], |
| 405 | "source_weights": {"youtube": 1.0}, |
| 406 | } |
| 407 | retrieve = pipeline._retrieve_stream |
| 408 | |
| 409 | def live_youtube(*args, **kwargs): |
| 410 | return retrieve(*args, **{**kwargs, "mock": False}) |
| 411 | |
| 412 | with ( |
| 413 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 414 | mock.patch.object(pipeline, "_retrieve_stream", side_effect=live_youtube), |
| 415 | mock.patch.object( |
| 416 | youtube_yt, "search_and_transcribe", return_value={"items": [free]}, |
| 417 | ) as free_search, |
| 418 | mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": []}) as sc_search, |
| 419 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 420 | ): |
| 421 | pipeline.run( |
| 422 | topic="Vuori", config={"SCRAPECREATORS_API_KEY": "dummy-key"}, |
| 423 | depth="default", requested_sources=["youtube"], mock=True, |
| 424 | external_plan=plan, as_of_date="2026-07-01", |
| 425 | ) |
| 426 | |
| 427 | assert free_search.call_count >= 1 |
| 428 | assert sc_search.call_count >= 1 |
| 429 | for call in free_search.call_args_list + sc_search.call_args_list: |
| 430 | assert call.kwargs.get("freshness_mode") == "evergreen_ok" |
| 431 | |
| 432 | |
| 433 | def _run_ends_during(free_result): |
| 434 | """A live config whose run is cancelled while yt-dlp is still working. |
| 435 | |
| 436 | The stream starts inside the budget (``_retrieve_stream_impl`` refuses a |
| 437 | stopped run up front), then the main thread gives up on it, as when the |
| 438 | lane is abandoned at the stream deadline. |
| 439 | """ |
| 440 | cancel = threading.Event() |
| 441 | config = {"SCRAPECREATORS_API_KEY": "dummy-key", "_enrich_cancel": cancel} |
| 442 | |
| 443 | def _free_search(*args, **kwargs): |
| 444 | cancel.set() |
| 445 | return free_result(**kwargs) if callable(free_result) else free_result |
| 446 | |
| 447 | return config, _free_search |
| 448 | |
| 449 | |
| 450 | def test_abandoned_lane_skips_paid_search_after_the_run_ends(): |
| 451 | """#1315: once the run is over, an empty yt-dlp result buys no SC search.""" |
| 452 | config, free_search = _run_ends_during({"items": []}) |
| 453 | with ( |
| 454 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 455 | mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=free_search) as free, |
| 456 | mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search, |
| 457 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 458 | ): |
| 459 | items, _ = _youtube_stream(config) |
| 460 | |
| 461 | free.assert_called_once() |
| 462 | assert items == [] |
| 463 | sc_search.assert_not_called() |
| 464 | |
| 465 | |
| 466 | def test_interpreter_shutdown_is_not_an_empty_ytdlp_result(): |
| 467 | """#1315: the straggler's RuntimeError must not trigger a paid search.""" |
| 468 | shutdown = RuntimeError("cannot schedule new futures after interpreter shutdown") |
| 469 | with ( |
| 470 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 471 | mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=shutdown), |
| 472 | mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search, |
| 473 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 474 | ): |
| 475 | _youtube_stream({"SCRAPECREATORS_API_KEY": "dummy-key"}) |
| 476 | |
| 477 | sc_search.assert_not_called() |
| 478 | |
| 479 | |
| 480 | def test_transcript_rescue_inside_an_over_run_spends_nothing(): |
| 481 | """#1315: per-video SC rescue in pool workers sees the stop gate.""" |
| 482 | rescued = {} |
| 483 | |
| 484 | def _transcribe(**kwargs): |
| 485 | rescued.update(youtube_yt.fetch_transcripts_parallel(["v1", "v2"], token=kwargs["token"])) |
| 486 | return {"items": []} |
| 487 | |
| 488 | config, free_search = _run_ends_during(_transcribe) |
| 489 | with ( |
| 490 | mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), |
| 491 | mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=free_search), |
| 492 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=False), |
| 493 | mock.patch.object(youtube_yt, "_fetch_transcript_direct", return_value=None), |
| 494 | mock.patch.object(youtube_yt.http, "get") as paid_get, |
| 495 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False), |
| 496 | ): |
| 497 | _youtube_stream(config) |
| 498 | |
| 499 | assert rescued == {"v1": None, "v2": None} |
| 500 | paid_get.assert_not_called() |
| 501 | |
| 502 | |
| 503 | def test_sc_paid_endpoints_refuse_inside_a_stopped_context(): |
| 504 | with mock.patch.object(youtube_yt.http, "get") as paid_get, \ |
| 505 | mock.patch.object(youtube_yt, "_ytdlp_comments_result", return_value=([], False)), \ |
| 506 | youtube_yt.sc_spend_until(lambda: True): |
| 507 | assert youtube_yt._sc_youtube_search("vuori", "dummy-key") == [] |
| 508 | assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") is None |
| 509 | assert youtube_yt._fetch_video_comments("v1", "dummy-key") == [] |
| 510 | paid_get.assert_not_called() |
| 511 | |
| 512 | |
| 513 | def test_sc_paid_endpoints_still_spend_while_the_run_is_live(): |
| 514 | with mock.patch.object( |
| 515 | youtube_yt.http, "get", return_value={"transcript": "live transcript"}, |
| 516 | ) as paid_get, youtube_yt.sc_spend_until(lambda: False): |
| 517 | assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") == "live transcript" |
| 518 | paid_get.assert_called_once() |
| 519 | |
| 520 | |
| 521 | def test_sc_transcript_buys_no_next_language_after_the_run_ends(): |
| 522 | """#1315: the run ends while `en` is in flight; `es` and `pt` are not bought.""" |
| 523 | stopped = threading.Event() |
| 524 | |
| 525 | def _empty_then_stop(*args, **kwargs): |
| 526 | stopped.set() |
| 527 | return {"transcript": None} |
| 528 | |
| 529 | with mock.patch.object(youtube_yt.http, "get", side_effect=_empty_then_stop) as paid_get, \ |
| 530 | mock.patch.dict("os.environ", {"LAST30DAYS_YT_SUB_LANGS": "en,es,pt"}), \ |
| 531 | youtube_yt.sc_spend_until(stopped.is_set): |
| 532 | assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") is None |
| 533 | assert [c.kwargs["params"]["language"] for c in paid_get.call_args_list] == ["en"] |
| 534 | |
| 535 | |
| 536 | def test_sc_requests_carry_the_run_cancel_and_deadline(): |
| 537 | """#1315: retries of a paid request stop at the run's deadline or cancel.""" |
| 538 | cancel = threading.Event() |
| 539 | run_deadline = 1.0 # monotonic; earlier than any per-call deadline below |
| 540 | with mock.patch.object(youtube_yt.http, "get", return_value={}) as paid_get, \ |
| 541 | mock.patch.object(youtube_yt, "_ytdlp_comments_result", return_value=([], False)), \ |
| 542 | mock.patch.object(youtube_yt.time, "monotonic", return_value=0.0), \ |
| 543 | youtube_yt.sc_spend_until(lambda: False, cancel=cancel, deadline=run_deadline): |
| 544 | youtube_yt._sc_youtube_search("vuori", "dummy-key") |
| 545 | youtube_yt._fetch_video_comments("v1", "dummy-key") |
| 546 | youtube_yt._sc_fetch_transcript("v1", "dummy-key") |
| 547 | assert paid_get.call_count >= 3 |
| 548 | for call in paid_get.call_args_list: |
| 549 | assert call.kwargs["cancel"] is cancel |
| 550 | assert call.kwargs["deadline_monotonic"] == run_deadline |
| 551 | |
| 552 | |
| 553 | def test_sc_transcript_keeps_its_own_deadline_outside_a_run(): |
| 554 | with mock.patch.object(youtube_yt.http, "get", return_value={"transcript": "t"}) as paid_get: |
| 555 | assert youtube_yt._sc_fetch_transcript("v1", "dummy-key") == "t" |
| 556 | kwargs = paid_get.call_args.kwargs |
| 557 | assert "cancel" not in kwargs |
| 558 | assert kwargs["deadline_monotonic"] > 0 |
| 559 |