返回 last30days-skill
test_quality_nudge.py
根目录 / tests / test_quality_nudge.py
1 """Tests for post-research quality score and upgrade nudge.
2
3 Reddit is always a core source (free public JSON). X remains supported when
4 active, but its absence is optional and must not lower the quality grade or
5 trigger an authentication nudge.
6 ScrapeCreators adds TikTok + Instagram as bonus sources, not core.
7 """
8
9 import threading
10
11 import pytest
12 from unittest.mock import patch
13
14 # ---------------------------------------------------------------------------
15 # Helpers
16 # ---------------------------------------------------------------------------
17
18
19 def _base_config(**overrides):
20 """Return a minimal config dict."""
21 config = {
22 "AUTH_TOKEN": None,
23 "CT0": None,
24 "XAI_API_KEY": None,
25 "XQUIK_API_KEY": None,
26 "SCRAPECREATORS_API_KEY": None,
27 }
28 config.update(overrides)
29 return config
30
31
32 def _base_results(**overrides):
33 """Return a minimal research_results dict with no errors."""
34 results = {
35 "x_error": None,
36 "youtube_error": None,
37 "reddit_error": None,
38 }
39 results.update(overrides)
40 return results
41
42
43 def _compute(config_overrides=None, result_overrides=None, ytdlp_installed=False):
44 """Helper to call compute_quality_score with mocked yt-dlp check."""
45 from lib.quality_nudge import compute_quality_score
46 from lib import youtube_yt
47
48 config = _base_config(**(config_overrides or {}))
49 results = _base_results(**(result_overrides or {}))
50
51 with patch.object(youtube_yt, "is_ytdlp_installed", return_value=ytdlp_installed):
52 return compute_quality_score(config, results)
53
54 # ---------------------------------------------------------------------------
55 # Tests
56 # ---------------------------------------------------------------------------
57
58
59 class TestBaseline:
60 """HN + Polymarket + Reddit active; X omitted and YouTube missing."""
61
62 def test_score_75(self):
63 q = _compute()
64 assert q["score_pct"] == 75
65
66 def test_active_sources(self):
67 q = _compute()
68 assert "hn" in q["core_active"]
69 assert "polymarket" in q["core_active"]
70 assert "reddit" in q["core_active"]
71 assert len(q["core_active"]) == 3
72
73 def test_only_youtube_is_missing(self):
74 q = _compute()
75 assert q["core_missing"] == ["youtube"]
76 assert "x" not in q["core_active"]
77
78 def test_reddit_not_in_missing(self):
79 """Reddit is always active - never appears in missing."""
80 q = _compute()
81 assert "reddit" not in q["core_missing"]
82 assert "reddit_comments" not in q["core_missing"]
83
84 def test_nudge_mentions_youtube_not_x(self):
85 q = _compute()
86 assert q["nudge_text"] is not None
87 assert "YouTube" in q["nudge_text"]
88 assert "X/Twitter" not in q["nudge_text"]
89
90 def test_nudge_does_not_mention_reddit(self):
91 """Reddit is free - nudge should not tell user to get SC for it."""
92 q = _compute()
93 assert "Reddit with comments" not in q["nudge_text"]
94
95
96 class TestXCookies:
97 """+X cookies -> 80%."""
98
99 def test_score_80(self):
100 q = _compute(config_overrides={"AUTH_TOKEN": "tok123"})
101 assert q["score_pct"] == 80
102
103 def test_nudge_mentions_yt_only(self):
104 q = _compute(config_overrides={"AUTH_TOKEN": "tok123"})
105 assert "YouTube" in q["nudge_text"]
106 assert "X/Twitter" not in q["nudge_text"]
107
108 def test_x_remains_active_when_configured(self):
109 q = _compute(config_overrides={"AUTH_TOKEN": "tok123"})
110 assert "x" in q["core_active"]
111
112
113 class TestXquikKey:
114 """+Xquik key -> 80% without browser-cookie or xAI credentials."""
115
116 def test_score_80(self):
117 q = _compute(config_overrides={"XQUIK_API_KEY": "xq_test"})
118 assert q["score_pct"] == 80
119 assert "x" in q["core_active"]
120
121 def test_nudge_mentions_yt_only(self):
122 q = _compute(config_overrides={"XQUIK_API_KEY": "xq_test"})
123 assert "YouTube" in q["nudge_text"]
124 assert "X/Twitter" not in q["nudge_text"]
125
126
127 class TestActiveSourceX:
128 """The runtime active-source list preserves X without legacy credentials."""
129
130 def test_active_x_is_counted(self):
131 q = _compute(result_overrides={"active_sources": ["reddit", "x", "youtube"]})
132 assert "x" in q["core_active"]
133
134
135 class TestConfiguredXErrored:
136 """A configured X that errored is a real outage: docked and surfaced,
137 never disguised as an optional omission."""
138
139 def test_errored_x_docks_the_score(self):
140 q = _compute(
141 config_overrides={"AUTH_TOKEN": "tok123"},
142 result_overrides={"x_error": "401 unauthorized"},
143 ytdlp_installed=True,
144 )
145 assert q["score_pct"] == 80 # 4/5 - X stays in the denominator
146 assert q["core_missing"] == ["x"]
147 assert q["core_errored"] == ["x"]
148
149 def test_errored_x_nudge_surfaces_the_repair(self):
150 q = _compute(
151 config_overrides={"AUTH_TOKEN": "tok123"},
152 result_overrides={"x_error": "401 unauthorized"},
153 ytdlp_installed=True,
154 )
155 assert q["nudge_text"] is not None
156 assert "X/Twitter (errored this run)" in q["nudge_text"]
157
158 def test_runtime_active_x_that_errored_is_also_docked(self):
159 q = _compute(
160 result_overrides={
161 "active_sources": ["reddit", "x", "youtube"],
162 "x_error": "429 rate limited",
163 },
164 ytdlp_installed=True,
165 )
166 assert q["core_errored"] == ["x"]
167 assert q["score_pct"] == 80
168
169
170 class TestXPlusYtdlp:
171 """+X + yt-dlp -> 100%. No SC needed for full core coverage."""
172
173 def test_score_100(self):
174 q = _compute(
175 config_overrides={"AUTH_TOKEN": "tok123"},
176 ytdlp_installed=True,
177 )
178 assert q["score_pct"] == 100
179
180 def test_nudge_is_none(self):
181 """Full core coverage with zero paid keys."""
182 q = _compute(
183 config_overrides={"AUTH_TOKEN": "tok123"},
184 ytdlp_installed=True,
185 )
186 assert q["nudge_text"] is None
187
188
189 class TestFullCoverageWithSC:
190 """+X + yt-dlp + SC -> still 100%, SC adds bonus sources."""
191
192 def test_score_100(self):
193 q = _compute(
194 config_overrides={
195 "AUTH_TOKEN": "tok123",
196 "SCRAPECREATORS_API_KEY": "sc_key",
197 },
198 ytdlp_installed=True,
199 )
200 assert q["score_pct"] == 100
201
202 def test_nudge_is_none(self):
203 q = _compute(
204 config_overrides={
205 "AUTH_TOKEN": "tok123",
206 "SCRAPECREATORS_API_KEY": "sc_key",
207 },
208 ytdlp_installed=True,
209 )
210 assert q["nudge_text"] is None
211
212
213 class TestSCDoesNotAffectCoreScore:
214 """SC key should not change core score - it only adds bonus sources."""
215
216 def test_sc_alone_still_75(self):
217 """SC key without yt-dlp is still 75% of non-optional core."""
218 q = _compute(config_overrides={"SCRAPECREATORS_API_KEY": "sc_key"})
219 assert q["score_pct"] == 75
220
221 def test_sc_plus_ytdlp_is_100(self):
222 q = _compute(
223 config_overrides={"SCRAPECREATORS_API_KEY": "sc_key"},
224 ytdlp_installed=True,
225 )
226 assert q["score_pct"] == 100
227
228 def test_no_x_cookie_nudge_after_complete_available_source_run(self):
229 q = _compute(
230 config_overrides={"SCRAPECREATORS_API_KEY": "sc_key"},
231 ytdlp_installed=True,
232 )
233 assert q["nudge_text"] is None
234
235
236 class TestYouTubeFallbackProvider:
237 """YouTube data from fallback/provider paths is degraded, not missing."""
238
239 def test_fallback_youtube_data_without_ytdlp_counts_active_not_missing(self):
240 q = _compute(
241 config_overrides={
242 "AUTH_TOKEN": "tok123",
243 "SCRAPECREATORS_API_KEY": "sc_key",
244 },
245 ytdlp_installed=False,
246 result_overrides={
247 "youtube_videos_count": 5,
248 "youtube_transcripts_count": 4,
249 },
250 )
251 assert q["score_pct"] == 100
252 assert "youtube" in q["core_active"]
253 assert "youtube" not in q["core_missing"]
254 assert "youtube" in q["core_degraded"]
255 assert q["nudge_text"] is not None
256 assert "Missing: YouTube" not in q["nudge_text"]
257 assert "Degraded: YouTube" in q["nudge_text"]
258 assert "fallback/provider" in q["nudge_text"]
259 assert "local yt-dlp is not installed" in q["nudge_text"]
260 assert "stale yt-dlp" not in q["nudge_text"].lower()
261
262 def test_ytdlp_install_check_runs_once_per_score(self):
263 from lib.quality_nudge import compute_quality_score
264 from lib import youtube_yt
265
266 with patch.object(youtube_yt, "is_ytdlp_installed", return_value=False) as ytdlp_check:
267 compute_quality_score(
268 _base_config(AUTH_TOKEN="tok123"),
269 _base_results(
270 youtube_videos_count=5,
271 youtube_transcripts_count=4,
272 ),
273 )
274
275 ytdlp_check.assert_called_once()
276
277 def test_no_fallback_data_without_ytdlp_still_missing(self):
278 q = _compute(
279 config_overrides={"SCRAPECREATORS_API_KEY": "sc_key"},
280 ytdlp_installed=False,
281 result_overrides={
282 "youtube_videos_count": 0,
283 "youtube_transcripts_count": 0,
284 },
285 )
286 assert "youtube" in q["core_missing"]
287 assert "youtube" not in q["core_active"]
288 assert "youtube" not in q["core_degraded"]
289 assert "Missing: YouTube" in q["nudge_text"]
290 assert "X/Twitter" not in q["nudge_text"]
291
292
293 class TestDisclaimerAlwaysPresent:
294 """Nudge always includes no-affiliate disclaimer when present."""
295
296 def test_disclaimer_baseline(self):
297 q = _compute()
298 assert "no affiliation" in q["nudge_text"]
299
300 def test_disclaimer_partial(self):
301 q = _compute(config_overrides={"AUTH_TOKEN": "tok123"})
302 assert "no affiliation" in q["nudge_text"]
303
304 def test_disclaimer_not_present_at_100(self):
305 q = _compute(
306 config_overrides={"AUTH_TOKEN": "tok123"},
307 ytdlp_installed=True,
308 )
309 assert q["nudge_text"] is None
310
311
312 class TestRedditNeverInCoreErrored:
313 """Reddit errors don't affect core score since it's always-active via public path."""
314
315 def test_reddit_error_does_not_affect_score(self):
316 q = _compute(
317 config_overrides={"AUTH_TOKEN": "tok123"},
318 result_overrides={"reddit_error": "429 Too Many Requests"},
319 ytdlp_installed=True,
320 )
321 # Reddit is always-active in core (public path), error doesn't demote it
322 assert "reddit" in q["core_active"]
323 assert q["score_pct"] == 100
324
325
326 class TestYouTubeDegraded:
327 """YouTube is `degraded` when videos returned but transcripts below threshold.
328
329 Canonical failure mode: a stale yt-dlp binary still finds videos via search
330 but silently fails every transcript fetch because YouTube's caption format
331 has moved on. Pre-fix the user got no signal of this; the footer hid zero,
332 and quality_nudge only checked top-level errors.
333 """
334
335 def test_zero_of_six_transcripts_flags_degraded(self):
336 q = _compute(
337 ytdlp_installed=True,
338 result_overrides={
339 "youtube_videos_count": 6,
340 "youtube_transcripts_count": 0,
341 },
342 )
343 assert "youtube" in q["core_degraded"]
344 assert q["nudge_text"] is not None
345 # Counts surface in the message so the user sees the actual ratio
346 assert "6 videos" in q["nudge_text"]
347 assert "0 transcripts" in q["nudge_text"]
348 assert "stale yt-dlp" in q["nudge_text"].lower()
349 # Updates path mentions all three common package managers
350 assert "scoop" in q["nudge_text"].lower()
351 assert "brew" in q["nudge_text"].lower()
352 assert "pip install" in q["nudge_text"].lower()
353
354 def test_five_of_six_transcripts_does_not_flag_degraded(self):
355 # 83% transcript success - well above the 50% threshold
356 # X is also enabled so all 5 cores are active and no nudge should fire
357 q = _compute(
358 config_overrides={"AUTH_TOKEN": "tok123"},
359 ytdlp_installed=True,
360 result_overrides={
361 "youtube_videos_count": 6,
362 "youtube_transcripts_count": 5,
363 },
364 )
365 assert "youtube" not in q["core_degraded"]
366 assert q["nudge_text"] is None # All 5 core sources active, no degradation
367
368 def test_zero_videos_does_not_flag_degraded(self):
369 # No videos returned -> degraded check is meaningless and must not fire
370 q = _compute(
371 ytdlp_installed=True,
372 result_overrides={
373 "youtube_videos_count": 0,
374 "youtube_transcripts_count": 0,
375 },
376 )
377 assert "youtube" not in q["core_degraded"]
378
379 def test_one_of_three_transcripts_flags_degraded(self):
380 # 33% - below 50% threshold; the canonical "yt-dlp partially working" case
381 q = _compute(
382 ytdlp_installed=True,
383 result_overrides={
384 "youtube_videos_count": 3,
385 "youtube_transcripts_count": 1,
386 },
387 )
388 assert "youtube" in q["core_degraded"]
389 assert "Degraded: YouTube" in q["nudge_text"]
390
391 def test_threshold_tunable_via_config(self):
392 # Operator overrides threshold via env-style config to be more permissive
393 q = _compute(
394 config_overrides={"DEGRADED_TRANSCRIPT_THRESHOLD": "0.1"},
395 ytdlp_installed=True,
396 result_overrides={
397 "youtube_videos_count": 10,
398 "youtube_transcripts_count": 2, # 20%, below default 50% but above override 10%
399 },
400 )
401 assert "youtube" not in q["core_degraded"]
402
403 def test_degraded_does_not_affect_score(self):
404 # Degradation is informational, not score-affecting; YouTube still counts as active
405 q = _compute(
406 config_overrides={"AUTH_TOKEN": "tok123"},
407 ytdlp_installed=True,
408 result_overrides={
409 "youtube_videos_count": 6,
410 "youtube_transcripts_count": 0,
411 },
412 )
413 assert "youtube" in q["core_active"]
414 assert q["score_pct"] == 100 # Full active count regardless of degradation
415 # But nudge still fires
416 assert q["nudge_text"] is not None
417 assert "Degraded: YouTube" in q["nudge_text"]
418
419
420 class TestYouTubeCaptionsDisabledDoesNotFalseFlag:
421 """Captions-disabled videos must not lower the transcript-fetch ratio.
422
423 A video where the uploader disabled captions can never produce a transcript,
424 no matter how fresh yt-dlp is. Counting it in the denominator of the
425 degraded-ratio check produces false positives - one captions-disabled video
426 in a small result set was triggering a "stale yt-dlp binary" nudge that was
427 wrong. Fix: subtract captions_disabled from the denominator.
428 """
429
430 def test_zero_captions_disabled_preserves_existing_behavior(self):
431 # Pre-existing case: 0 of 6 transcripts is still degraded (no captions
432 # disabled to discount). Behavior is unchanged from TestYouTubeDegraded.
433 q = _compute(
434 ytdlp_installed=True,
435 result_overrides={
436 "youtube_videos_count": 6,
437 "youtube_transcripts_count": 0,
438 "youtube_captions_disabled_count": 0,
439 },
440 )
441 assert "youtube" in q["core_degraded"]
442
443 def test_all_videos_captions_disabled_does_not_flag(self):
444 # Every returned video had captions disabled by the uploader.
445 # That's not a yt-dlp problem - it's an upstream content fact. Must not
446 # flag degraded.
447 q = _compute(
448 ytdlp_installed=True,
449 result_overrides={
450 "youtube_videos_count": 3,
451 "youtube_transcripts_count": 0,
452 "youtube_captions_disabled_count": 3,
453 },
454 )
455 assert "youtube" not in q["core_degraded"]
456
457 def test_mixed_uses_corrected_denominator(self):
458 # 6 videos, 3 captions_disabled, 2 transcripts.
459 # Naive (buggy) ratio: 2/6 = 33% (would flag).
460 # Corrected ratio: 2/(6-3) = 67% (does NOT flag).
461 # This case demonstrates the fix changes the verdict.
462 q = _compute(
463 ytdlp_installed=True,
464 result_overrides={
465 "youtube_videos_count": 6,
466 "youtube_transcripts_count": 2,
467 "youtube_captions_disabled_count": 3,
468 },
469 )
470 assert "youtube" not in q["core_degraded"]
471
472 def test_mixed_still_flags_when_truly_degraded(self):
473 # Even after discounting captions-disabled, the ratio is still bad.
474 # 8 videos, 1 captions_disabled, 1 transcript -> 1/(8-1) = 14% (flags).
475 q = _compute(
476 ytdlp_installed=True,
477 result_overrides={
478 "youtube_videos_count": 8,
479 "youtube_transcripts_count": 1,
480 "youtube_captions_disabled_count": 1,
481 },
482 )
483 assert "youtube" in q["core_degraded"]
484 # Nudge should still mention the stale yt-dlp possibility but also
485 # acknowledge that captions-disabled is a separate cause.
486 assert q["nudge_text"] is not None
487 assert "captions disabled" in q["nudge_text"].lower()
488
489 def test_missing_count_defaults_to_zero(self):
490 # Older callers that don't pass the new key still work (default 0).
491 q = _compute(
492 ytdlp_installed=True,
493 result_overrides={
494 "youtube_videos_count": 6,
495 "youtube_transcripts_count": 0,
496 # youtube_captions_disabled_count intentionally omitted
497 },
498 )
499 assert "youtube" in q["core_degraded"]
500
501
502 class TestStaleNudgeRequiresActualFetchFailures:
503 """Zero failed fetches must suppress the stale-yt-dlp nudge (#531).
504
505 The report counts (youtube_videos_count / youtube_transcripts_count) are
506 computed from post-pruning items. A run where every transcript fetch
507 succeeded but the fetched videos were later pruned by freshness scoring
508 looks identical to a stale-binary run from those counts alone, producing
509 a false "stale yt-dlp binary" nudge. When actual fetch outcomes are
510 available and show zero failures, the binary demonstrably works.
511 """
512
513 def test_zero_failures_does_not_flag(self):
514 # The #531 repro: 2 in-report videos, 0 transcripts among them, but
515 # all 6 attempted fetches succeeded (on videos pruned later).
516 q = _compute(
517 ytdlp_installed=True,
518 result_overrides={
519 "youtube_videos_count": 2,
520 "youtube_transcripts_count": 0,
521 "youtube_captions_disabled_count": 0,
522 "youtube_transcript_fetch_attempts": 6,
523 "youtube_transcript_fetch_failures": 0,
524 },
525 )
526 assert "youtube" not in q["core_degraded"]
527
528 def test_actual_failures_still_flag(self):
529 q = _compute(
530 ytdlp_installed=True,
531 result_overrides={
532 "youtube_videos_count": 6,
533 "youtube_transcripts_count": 0,
534 "youtube_captions_disabled_count": 0,
535 "youtube_transcript_fetch_attempts": 6,
536 "youtube_transcript_fetch_failures": 6,
537 },
538 )
539 assert "youtube" in q["core_degraded"]
540
541 def test_missing_fetch_stats_preserves_existing_behavior(self):
542 # Callers that don't pass fetch stats (or the SC path, which doesn't
543 # use the local yt-dlp binary) fall back to the ratio heuristic.
544 q = _compute(
545 ytdlp_installed=True,
546 result_overrides={
547 "youtube_videos_count": 6,
548 "youtube_transcripts_count": 0,
549 "youtube_captions_disabled_count": 0,
550 },
551 )
552 assert "youtube" in q["core_degraded"]
553
554 def test_zero_attempts_preserves_existing_behavior(self):
555 q = _compute(
556 ytdlp_installed=True,
557 result_overrides={
558 "youtube_videos_count": 6,
559 "youtube_transcripts_count": 0,
560 "youtube_captions_disabled_count": 0,
561 "youtube_transcript_fetch_attempts": 0,
562 "youtube_transcript_fetch_failures": 0,
563 },
564 )
565 assert "youtube" in q["core_degraded"]
566
567
568 class TestYouTubeTimeoutIsNotStaleBinary:
569 """An engine timeout must not prescribe a yt-dlp upgrade."""
570
571 def test_timeout_names_the_timeout_without_upgrade_advice(self):
572 from lib import prescriptions
573
574 q = _compute(
575 ytdlp_installed=True,
576 result_overrides={"youtube_error": "youtube timed out after 180s"},
577 )
578 stale = prescriptions.get("youtube", "ytdlp_stale")
579 assert q["core_errored"] == ["youtube"]
580 assert "youtube timed out after 180s" in q["nudge_text"]
581 assert "update yt-dlp" not in q["nudge_text"]
582 assert stale.fix_cli not in q["nudge_text"]
583
584 def test_other_errors_keep_upgrade_advice(self):
585 from lib import prescriptions
586
587 q = _compute(
588 ytdlp_installed=True,
589 result_overrides={"youtube_error": "ERROR: Unable to extract video data"},
590 )
591 stale = prescriptions.get("youtube", "ytdlp_stale")
592 assert f"YouTube errored - update yt-dlp: {stale.fix_cli}" in q["nudge_text"]
593
594
595 class TestInstagramSilentFailure:
596 """Instagram is a `bonus` source via SC. Silent-failure detection: if SC
597 is configured but the source returned zero items, surface a nudge so the
598 user understands why the brief lacks an Instagram section.
599
600 Pre-fix the user got no signal - SC's /v2/instagram/reels/search 500s
601 frequently on multi-token queries and the pipeline silently returned
602 empty without any indication.
603 """
604
605 def test_zero_items_with_sc_flags_bonus_errored(self):
606 q = _compute(
607 config_overrides={
608 "AUTH_TOKEN": "tok123",
609 "SCRAPECREATORS_API_KEY": "sc_key",
610 },
611 ytdlp_installed=True,
612 result_overrides={"instagram_items_count": 0},
613 )
614 assert q["bonus_errored"] == ["instagram:no_items"]
615 assert q["nudge_text"] is not None
616 assert "Instagram" in q["nudge_text"]
617
618 def test_zero_items_without_sc_does_not_flag(self):
619 q = _compute(
620 config_overrides={"AUTH_TOKEN": "tok123"},
621 ytdlp_installed=True,
622 result_overrides={"instagram_items_count": 0},
623 )
624 assert q["bonus_errored"] == []
625
626 def test_nonzero_items_does_not_flag(self):
627 q = _compute(
628 config_overrides={
629 "AUTH_TOKEN": "tok123",
630 "SCRAPECREATORS_API_KEY": "sc_key",
631 },
632 ytdlp_installed=True,
633 result_overrides={"instagram_items_count": 5},
634 )
635 assert q["bonus_errored"] == []
636 assert q["nudge_text"] is None
637
638 def test_nonzero_items_do_not_add_instagram_advice_to_other_nudges(self):
639 q = _compute(
640 config_overrides={"SCRAPECREATORS_API_KEY": "sc_key"},
641 result_overrides={"instagram_items_count": 5},
642 )
643 assert q["bonus_errored"] == []
644 assert "YouTube" in q["nudge_text"]
645 assert "Instagram" not in q["nudge_text"]
646 assert "single-word topic" not in q["nudge_text"]
647
648 def test_missing_key_means_source_did_not_run(self):
649 q = _compute(
650 config_overrides={
651 "AUTH_TOKEN": "tok123",
652 "SCRAPECREATORS_API_KEY": "sc_key",
653 },
654 ytdlp_installed=True,
655 )
656 assert q["bonus_errored"] == []
657 assert q["nudge_text"] is None
658
659 @pytest.mark.parametrize("error,outcome,label", [
660 (None, "instagram:no_items", "Bonus source unavailable: Instagram."),
661 ("HTTP 404", "instagram:failed", "Bonus source failed: Instagram."),
662 ])
663 def test_nudge_text_explains_workaround(self, error, outcome, label):
664 q = _compute(
665 config_overrides={
666 "AUTH_TOKEN": "tok123",
667 "SCRAPECREATORS_API_KEY": "sc_key",
668 },
669 ytdlp_installed=True,
670 result_overrides={"instagram_items_count": 0, "instagram_error": error},
671 )
672 assert q["bonus_errored"] == [outcome]
673 assert q["nudge_text"] is not None
674 assert label in q["nudge_text"]
675 assert "Instagram returned 0 reels" in q["nudge_text"]
676 assert "retries with hashtag-form automatically" in q["nudge_text"]
677 assert "Try a single-word topic" in q["nudge_text"]
678
679 def test_bonus_errored_does_not_affect_core_score(self):
680 q = _compute(
681 config_overrides={
682 "AUTH_TOKEN": "tok123",
683 "SCRAPECREATORS_API_KEY": "sc_key",
684 },
685 ytdlp_installed=True,
686 result_overrides={"instagram_items_count": 0},
687 )
688 assert q["score_pct"] == 100
689 assert q["bonus_errored"] == ["instagram:no_items"]
690 assert q["nudge_text"] is not None
691 assert "Bonus source unavailable" in q["nudge_text"]
692
693 def test_bonus_errored_instagram_http_error_emits_failed_label(self):
694 """When instagram_error is set (HTTP error), nudge says 'Bonus source failed'."""
695 q = _compute(
696 config_overrides={
697 "AUTH_TOKEN": "tok123",
698 "SCRAPECREATORS_API_KEY": "sc_key",
699 },
700 ytdlp_installed=True,
701 result_overrides={"instagram_items_count": 0, "instagram_error": "HTTP 404"},
702 )
703 assert q["bonus_errored"] == ["instagram:failed"]
704 assert q["nudge_text"] is not None
705 assert "Bonus source failed" in q["nudge_text"]
706 assert "Instagram" in q["nudge_text"]
707
708 def test_bonus_errored_field_always_present(self):
709 q = _compute()
710 assert q.get("bonus_errored") == []
711
712 def test_exclude_sources_instagram_suppresses_silent_failure(self):
713 """User set EXCLUDE_SOURCES=instagram - the source intentionally did
714 not run, so the zero-count instagram_items_count written by
715 last30days.py is a non-event, not a silent failure. Pre-fix: the
716 nudge fired anyway because the gate only checked SC-key + count.
717 """
718 q = _compute(
719 config_overrides={
720 "AUTH_TOKEN": "tok123",
721 "SCRAPECREATORS_API_KEY": "sc_key",
722 "EXCLUDE_SOURCES": "instagram",
723 },
724 ytdlp_installed=True,
725 result_overrides={"instagram_items_count": 0},
726 )
727 assert q["bonus_errored"] == []
728 assert q["nudge_text"] is None
729
730 def test_exclude_sources_multi_value_with_instagram(self):
731 """Canonical parsing pattern is comma-separated; case-insensitive."""
732 q = _compute(
733 config_overrides={
734 "AUTH_TOKEN": "tok123",
735 "SCRAPECREATORS_API_KEY": "sc_key",
736 "EXCLUDE_SOURCES": "threads, Instagram , pinterest",
737 },
738 ytdlp_installed=True,
739 result_overrides={"instagram_items_count": 0},
740 )
741 assert q["bonus_errored"] == []
742
743 def test_exclude_sources_other_value_still_flags(self):
744 """EXCLUDE_SOURCES that does not mention instagram must not suppress
745 the silent-failure nudge for instagram.
746 """
747 q = _compute(
748 config_overrides={
749 "AUTH_TOKEN": "tok123",
750 "SCRAPECREATORS_API_KEY": "sc_key",
751 "EXCLUDE_SOURCES": "threads",
752 },
753 ytdlp_installed=True,
754 result_overrides={"instagram_items_count": 0},
755 )
756 assert q["bonus_errored"] == ["instagram:no_items"]
757
758 def test_include_sources_without_instagram_suppresses_silent_failure(self):
759 """User set INCLUDE_SOURCES to an opt-in allowlist that omits
760 instagram — the pipeline skips the source by allowlist filter, so
761 the zero-count instagram_items_count is intentional, not a silent
762 failure. Symmetric to the EXCLUDE_SOURCES=instagram guard.
763 """
764 q = _compute(
765 config_overrides={
766 "AUTH_TOKEN": "tok123",
767 "SCRAPECREATORS_API_KEY": "sc_key",
768 "INCLUDE_SOURCES": "reddit,hn,x,youtube",
769 },
770 ytdlp_installed=True,
771 result_overrides={"instagram_items_count": 0},
772 )
773 assert q["bonus_errored"] == []
774 assert q["nudge_text"] is None
775
776 def test_include_sources_multi_value_without_instagram(self):
777 """Canonical parsing pattern is comma-separated; case-insensitive."""
778 q = _compute(
779 config_overrides={
780 "AUTH_TOKEN": "tok123",
781 "SCRAPECREATORS_API_KEY": "sc_key",
782 "INCLUDE_SOURCES": " Reddit, HN , YouTube ",
783 },
784 ytdlp_installed=True,
785 result_overrides={"instagram_items_count": 0},
786 )
787 assert q["bonus_errored"] == []
788
789 def test_include_sources_with_instagram_still_flags(self):
790 """INCLUDE_SOURCES that explicitly names instagram must not suppress
791 the silent-failure nudge — the source was opted in, so a zero count
792 is a real silent failure.
793 """
794 q = _compute(
795 config_overrides={
796 "AUTH_TOKEN": "tok123",
797 "SCRAPECREATORS_API_KEY": "sc_key",
798 "INCLUDE_SOURCES": "reddit,instagram",
799 },
800 ytdlp_installed=True,
801 result_overrides={"instagram_items_count": 0},
802 )
803 assert q["bonus_errored"] == ["instagram:no_items"]
804
805 def test_include_sources_empty_does_not_suppress(self):
806 """Empty/unset INCLUDE_SOURCES means no allowlist filter, so the
807 silent-failure gate should still fire when instagram is zero.
808 """
809 q = _compute(
810 config_overrides={
811 "AUTH_TOKEN": "tok123",
812 "SCRAPECREATORS_API_KEY": "sc_key",
813 "INCLUDE_SOURCES": "",
814 },
815 ytdlp_installed=True,
816 result_overrides={"instagram_items_count": 0},
817 )
818 assert q["bonus_errored"] == ["instagram:no_items"]
819
820
821 class TestBearerCredential:
822 """X_BEARER_TOKEN counts as an X credential where the xapi backend can
823 run (a Grok Bot host, or an explicit xapi pin); an ambient bearer on a
824 plain host stays what it is today: not a configured X source."""
825
826 def test_bearer_counts_on_grok_bot(self):
827 q = _compute(
828 config_overrides={"LAST30DAYS_HOST": "grok-bot", "X_BEARER_TOKEN": "dummy-bearer"},
829 ytdlp_installed=True,
830 )
831 assert "x" in q["core_active"]
832 assert q["score_pct"] == 100
833
834 def test_bearer_counts_when_xapi_is_pinned(self):
835 q = _compute(
836 config_overrides={"X_BEARER_TOKEN": "dummy-bearer", "LAST30DAYS_X_BACKEND": "xapi"},
837 ytdlp_installed=True,
838 )
839 assert "x" in q["core_active"]
840
841 def test_ambient_bearer_on_plain_host_is_an_optional_omission(self):
842 q = _compute(config_overrides={"X_BEARER_TOKEN": "dummy-bearer"}, ytdlp_installed=True)
843 assert "x" not in q["core_active"]
844 assert q["core_missing"] == []
845 assert q["nudge_text"] is None
846
847 def test_grok_bot_x_error_nudge_names_bearer_never_x_login(self):
848 q = _compute(
849 config_overrides={"LAST30DAYS_HOST": "grok-bot", "X_BEARER_TOKEN": "dummy-bearer"},
850 result_overrides={"x_error": "401 unauthorized"},
851 ytdlp_installed=True,
852 )
853 assert q["core_errored"] == ["x"]
854 text = q["nudge_text"].lower()
855 assert "x_bearer_token" in text
856 for word in ("x.com", "cookie", "bird", "auth_token", "ct0", "xquik", "grok cli", "grok login"):
857 assert word not in text, word
858
859 def test_declared_lane_without_envelope_prescribes_the_connector(self):
860 from lib import x_envelope
861 q = _compute(
862 config_overrides={"LAST30DAYS_HOST": "grok-bot"},
863 result_overrides={"x_error": x_envelope.DETAIL_NOT_PASSED, "active_sources": ["x"]},
864 ytdlp_installed=True,
865 )
866 assert q["core_errored"] == ["x"]
867 text = q["nudge_text"].lower()
868 assert "connector" in text
869 assert "--x-posts" in text
870 for word in ("x.com", "cookie", "bird", "auth_token", "ct0"):
871 assert word not in text, word
872
873 def test_grok_bot_credit_error_nudge_says_top_up(self):
874 q = _compute(
875 config_overrides={"LAST30DAYS_HOST": "grok-bot", "X_BEARER_TOKEN": "dummy-bearer"},
876 result_overrides={"x_error": "xapi: payment required (X API credits exhausted)"},
877 ytdlp_installed=True,
878 )
879 assert "top up" in q["nudge_text"].lower()
880 assert "x.com" not in q["nudge_text"].lower()
881
882
883 class TestXaiErrorRemediation:
884 """The selected API backend must not prescribe a browser-cookie login."""
885
886 @pytest.mark.parametrize("host", [None, "grok-bot"])
887 @pytest.mark.parametrize("message", [
888 "All X backends failed — xai: HTTP 403: Permission denied",
889 "xai: HTTP 401: Unauthorized",
890 "All X backends failed — xai: HTTP 404: Model not found",
891 ])
892 def test_runtime_xai_error_points_to_key_and_model_permissions(self, host, message):
893 q = _compute(
894 config_overrides={"XAI_API_KEY": "dummy-xai-key", "LAST30DAYS_HOST": host},
895 result_overrides={"x_error": message},
896 ytdlp_installed=True,
897 )
898 assert "XAI_API_KEY" in q["nudge_text"]
899 assert "LAST30DAYS_X_MODEL" in q["nudge_text"]
900 assert "console.x.ai" in q["nudge_text"]
901 assert "log into x.com" not in q["nudge_text"]
902 assert "X_BEARER_TOKEN" not in q["nudge_text"]
903
904 def test_runtime_bird_error_is_not_changed_by_a_fallback_xai_key(self):
905 q = _compute(
906 config_overrides={"AUTH_TOKEN": "dummy-cookie", "CT0": "dummy-ct0", "XAI_API_KEY": "dummy-xai-key"},
907 result_overrides={"x_error": "All X backends failed — bird: expired cookies"},
908 ytdlp_installed=True,
909 )
910 assert "log into x.com" in q["nudge_text"]
911 assert "console.x.ai" not in q["nudge_text"]
912
913 @pytest.mark.parametrize("backend,credentials,error,expected,unexpected", [
914 ("xai", {"XAI_API_KEY": "dummy-xai-key"}, "HTTP 403: Permission denied", "console.x.ai", "log into x.com"),
915 ("bird", {"AUTH_TOKEN": "dummy-cookie", "CT0": "dummy-ct0"}, "expired cookies", "log into x.com", "console.x.ai"),
916 ])
917 def test_thin_retry_failure_preserves_backend_repair(self, backend, credentials, error, expected, unexpected):
918 from lib import bird_x, pipeline, schema
919
920 config = _base_config(**credentials)
921 config["LAST30DAYS_X_BACKEND"] = backend
922 plan = schema.QueryPlan(
923 intent="breaking_news",
924 freshness_mode="strict_recent",
925 cluster_mode="story",
926 raw_topic="OpenClaw",
927 subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],
928 source_weights={"x": 1.0},
929 )
930 bundle = schema.RetrievalBundle()
931 runtime = schema.ProviderRuntime("local", "", "", backend)
932
933 with patch.object(bird_x, "is_bird_installed", return_value=True), \
934 patch.object(pipeline, "_fetch_x_backend", return_value=([], error)):
935 pipeline._retry_thin_sources(
936 topic="OpenClaw",
937 bundle=bundle,
938 plan=plan,
939 config=config,
940 depth="default",
941 date_range=("2026-09-01", "2026-09-30"),
942 runtime=runtime,
943 mock=False,
944 rate_limited_sources=set(),
945 rate_limit_lock=threading.Lock(),
946 settings=pipeline.DEPTH_SETTINGS["default"],
947 )
948
949 assert bundle.errors_by_source["x"].startswith("Simplified-query retry failed: All X backends failed — ")
950 q = _compute(config_overrides=config, result_overrides={"x_error": bundle.errors_by_source["x"]}, ytdlp_installed=True)
951 assert expected in q["nudge_text"]
952 assert unexpected not in q["nudge_text"]
953
954 @pytest.mark.parametrize("status,message,expected_state,expected_fix", [
955 (403, "Forbidden", "auth-failed", "console.x.ai"),
956 (402, "Quota blocked", "payment-required", "billing"),
957 (429, "Quota blocked", "rate-limited", "rate limit"),
958 (None, "Request deadline exceeded", "timeout", "timed out"),
959 ])
960 def test_raised_xai_error_from_thin_retry_keeps_cause(self, status, message, expected_state, expected_fix):
961 from lib import http, pipeline, schema, xai_x
962
963 config = _base_config(XAI_API_KEY="dummy-xai-key")
964 config["LAST30DAYS_X_BACKEND"] = "xai"
965 plan = schema.QueryPlan(
966 intent="breaking_news",
967 freshness_mode="strict_recent",
968 cluster_mode="story",
969 raw_topic="OpenClaw",
970 subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],
971 source_weights={"x": 1.0},
972 )
973 bundle = schema.RetrievalBundle()
974 runtime = schema.ProviderRuntime("local", "", "", "xai")
975 error = http.DeadlineExceeded() if status is None else http.HTTPError(message, status_code=status)
976
977 with patch.object(xai_x, "search_x", side_effect=error):
978 pipeline._retry_thin_sources(
979 topic="OpenClaw",
980 bundle=bundle,
981 plan=plan,
982 config=config,
983 depth="default",
984 date_range=("2026-09-01", "2026-09-30"),
985 runtime=runtime,
986 mock=False,
987 rate_limited_sources=set(),
988 rate_limit_lock=threading.Lock(),
989 settings=pipeline.DEPTH_SETTINGS["default"],
990 )
991
992 assert bundle.errors_by_source["x"].startswith("Simplified-query retry failed: All X backends failed — xai:")
993 assert bundle.source_status["x"].state == expected_state
994 q = _compute(
995 config_overrides=config,
996 result_overrides={"x_error": bundle.errors_by_source["x"]},
997 ytdlp_installed=True,
998 )
999 assert expected_fix in q["nudge_text"]
1000 assert "log into x.com" not in q["nudge_text"]
1001
1002 def test_raised_xai_auth_error_still_uses_xquik_fallback(self):
1003 from lib import http, pipeline, schema, xai_x, xquik
1004
1005 config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")
1006 plan = schema.QueryPlan(
1007 intent="breaking_news",
1008 freshness_mode="strict_recent",
1009 cluster_mode="story",
1010 raw_topic="OpenClaw",
1011 subqueries=[schema.SubQuery("primary", "OpenClaw", "Recent OpenClaw news", ["x"])],
1012 source_weights={"x": 1.0},
1013 )
1014 bundle = schema.RetrievalBundle()
1015 runtime = schema.ProviderRuntime("local", "", "", "xai")
1016 fallback_item = {
1017 "text": "Recent OpenClaw update",
1018 "url": "https://x.com/example/status/1234567890123456789",
1019 "author_handle": "example",
1020 "date": "2026-09-15",
1021 "engagement": {"likes": 2},
1022 "relevance": 0.9,
1023 }
1024
1025 with patch.object(xai_x, "search_x", side_effect=http.HTTPError("Forbidden", status_code=403)), \
1026 patch.object(xquik, "search_xquik", return_value={"items": []}) as fallback_search, \
1027 patch.object(xquik, "parse_xquik_response", return_value=[fallback_item]):
1028 pipeline._retry_thin_sources(
1029 topic="OpenClaw",
1030 bundle=bundle,
1031 plan=plan,
1032 config=config,
1033 depth="default",
1034 date_range=("2026-09-01", "2026-09-30"),
1035 runtime=runtime,
1036 mock=False,
1037 rate_limited_sources=set(),
1038 rate_limit_lock=threading.Lock(),
1039 settings=pipeline.DEPTH_SETTINGS["default"],
1040 )
1041
1042 fallback_search.assert_called_once()
1043 assert bundle.items_by_source["x"]
1044 assert bundle.errors_by_source["x"].startswith("X served via xquik after xai:")
1045 q = _compute(config_overrides=config, result_overrides={"x_error": bundle.errors_by_source["x"]}, ytdlp_installed=True)
1046 assert "console.x.ai" in q["nudge_text"]
1047 assert "log into x.com" not in q["nudge_text"]
1048
1049 @pytest.mark.parametrize("status,message,expected_state,expected_fix", [
1050 (403, "Forbidden", "auth-failed", "console.x.ai"),
1051 (402, "Quota blocked", "ok", "billing"),
1052 (429, "Quota blocked", "ok", "rate limit"),
1053 (None, "Request deadline exceeded", "ok", "timed out"),
1054 ])
1055 def test_xai_fallback_keeps_repair_in_final_report(self, status, message, expected_state, expected_fix):
1056 import last30days as cli
1057 from lib import http, pipeline, providers, render, schema, xai_x, xquik
1058
1059 config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")
1060 runtime = schema.ProviderRuntime("local", "", "", "xai")
1061 fallback_item = {
1062 "text": "Recent OpenClaw update",
1063 "url": "https://x.com/example/status/1234567890123456789",
1064 "author_handle": "example",
1065 "date": "2026-09-15",
1066 "engagement": {"likes": 2},
1067 "relevance": 0.9,
1068 }
1069 error = http.DeadlineExceeded() if status is None else http.HTTPError(message, status_code=status)
1070 with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \
1071 patch.object(xai_x, "search_x", side_effect=error), \
1072 patch.object(xquik, "search_xquik", return_value={"items": []}), \
1073 patch.object(xquik, "parse_xquik_response", return_value=[fallback_item]):
1074 report = pipeline.run(
1075 topic="OpenClaw", config=config, depth="default", mock=False,
1076 requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",
1077 external_plan={
1078 "intent": "breaking_news", "freshness_mode": "strict_recent",
1079 "cluster_mode": "story",
1080 "subqueries": [{
1081 "label": "primary", "search_query": "OpenClaw",
1082 "ranking_query": "OpenClaw", "sources": ["x"],
1083 }],
1084 },
1085 )
1086
1087 assert report.items_by_source["x"]
1088 assert "x" not in report.errors_by_source
1089 assert report.source_status["x"].state == expected_state
1090 assert "xai:" in report.source_status["x"].detail
1091 assert "re-login needed" not in report.source_status["x"].detail
1092 rendered = render.render_compact(report)
1093 if status == 403:
1094 assert "xai: HTTP 403" in rendered
1095 assert "re-login needed" not in rendered
1096 research_results = cli._quality_research_results(
1097 report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}
1098 )
1099 assert research_results["x_error"] is None
1100 assert research_results["x_degraded_error"].startswith("X served via xquik after xai:")
1101 q = _compute(
1102 config_overrides=config,
1103 result_overrides=research_results,
1104 ytdlp_installed=True,
1105 )
1106 assert "x" in q["core_active"]
1107 assert "x" in q["core_degraded"]
1108 assert expected_fix in q["nudge_text"]
1109 assert "log into x.com" not in q["nudge_text"]
1110
1111 def test_xai_rate_limit_does_not_skip_working_backup_on_later_x_subquery(self):
1112 import last30days as cli
1113 from lib import http, pipeline, providers, schema, xai_x, xquik
1114
1115 config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")
1116 runtime = schema.ProviderRuntime("local", "", "", "xai")
1117 fallback_items = [
1118 [{
1119 "id": f"x{index}{slot}",
1120 "text": f"Recent OpenClaw update {index} {slot}",
1121 "url": f"https://x.com/example/status/12345678901234567{index}{slot}",
1122 "author_handle": "",
1123 "date": "2026-09-15",
1124 "engagement": {"likes": 2},
1125 "relevance": 0.9,
1126 } for slot in range(3)]
1127 for index in (0, 1, 2)
1128 ]
1129 second_query_items = []
1130 add_items = schema.RetrievalBundle.add_items
1131
1132 def capture_items(bundle, label, source, items):
1133 if label == "second" and source == "x":
1134 second_query_items.extend(items)
1135 return add_items(bundle, label, source, items)
1136
1137 with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \
1138 patch.object(pipeline, "_inner_max_workers", return_value=1), \
1139 patch.object(schema.RetrievalBundle, "add_items", new=capture_items), \
1140 patch.object(xai_x, "search_x", side_effect=http.HTTPError("Quota blocked", status_code=429)) as xai_search, \
1141 patch.object(xquik, "search_xquik", return_value={"items": []}) as fallback_search, \
1142 patch.object(xquik, "parse_xquik_response", side_effect=fallback_items):
1143 report = pipeline.run(
1144 topic="OpenClaw", config=config, depth="default", mock=False,
1145 requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",
1146 external_plan={
1147 "intent": "breaking_news", "freshness_mode": "strict_recent",
1148 "cluster_mode": "story",
1149 "subqueries": [
1150 {
1151 "label": label, "search_query": f"OpenClaw {label}",
1152 "ranking_query": "OpenClaw", "sources": ["x"],
1153 }
1154 for label in ("first", "second")
1155 ],
1156 },
1157 )
1158
1159 # The failed xai call is not memoized, so each subquery tries it; the
1160 # backup's clean result is fetched once and served to both subqueries.
1161 assert xai_search.call_count >= 2
1162 assert fallback_search.call_count == 1
1163 assert any(
1164 "status/123456789012345670" in item.url
1165 for item in second_query_items
1166 )
1167 assert report.source_status["x"].lane_failure_state == schema.RATE_LIMITED
1168 research_results = cli._quality_research_results(
1169 report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}
1170 )
1171 assert "HTTP 429" in research_results["x_degraded_error"]
1172 q = _compute(config_overrides=config, result_overrides=research_results, ytdlp_installed=True)
1173 assert "x" in q["core_degraded"]
1174 assert "rate limit" in q["nudge_text"]
1175
1176 @pytest.mark.parametrize("xai_status,expected_state,expected_fix", [
1177 (429, "ok", "rate limit"),
1178 (403, "auth-failed", "console.x.ai"),
1179 ])
1180 def test_rate_limited_backup_stops_later_x_subqueries(self, xai_status, expected_state, expected_fix):
1181 import last30days as cli
1182 from lib import http, pipeline, providers, schema, xai_x, xquik
1183
1184 config = _base_config(XAI_API_KEY="dummy-xai-key", XQUIK_API_KEY="dummy-xquik-key")
1185 runtime = schema.ProviderRuntime("local", "", "", "xai")
1186 topic = "OpenClaw launch update"
1187 assert len(xquik.expand_xquik_queries(topic, "default")) == 2
1188 get_calls = 0
1189
1190 def partial_xquik_response(*args, **kwargs):
1191 nonlocal get_calls
1192 get_calls += 1
1193 if get_calls == 1:
1194 return {"tweets": [{
1195 "id": "1234567890123456789",
1196 "author": {"username": "example"},
1197 "createdAt": "2026-09-15T12:00:00Z",
1198 "text": "Recent OpenClaw update",
1199 }]}
1200 http._raise(http.HTTPError("Too many requests", status_code=429))
1201
1202 def rejected_xai_response(*args, **kwargs):
1203 message = "Forbidden" if xai_status == 403 else "Quota blocked"
1204 http._raise(http.HTTPError(message, status_code=xai_status))
1205
1206 with patch.object(providers, "resolve_runtime", return_value=(runtime, None)), \
1207 patch.object(pipeline, "_inner_max_workers", return_value=1), \
1208 patch.object(xai_x, "search_x", wraps=xai_x.search_x) as xai_search, \
1209 patch.object(xquik, "search_xquik", wraps=xquik.search_xquik) as fallback_search, \
1210 patch.object(http, "post", side_effect=rejected_xai_response) as xai_post, \
1211 patch.object(http, "get", side_effect=partial_xquik_response):
1212 report = pipeline.run(
1213 topic=topic, config=config, depth="default", mock=False,
1214 requested_sources=["x"], web_backend="none", as_of_date="2026-09-30",
1215 external_plan={
1216 "intent": "breaking_news", "freshness_mode": "strict_recent",
1217 "cluster_mode": "story",
1218 "subqueries": [
1219 {
1220 "label": label, "search_query": f"OpenClaw {label}",
1221 "ranking_query": "OpenClaw", "sources": ["x"],
1222 }
1223 for label in ("first", "second")
1224 ],
1225 },
1226 )
1227
1228 assert xai_search.call_count == 1
1229 assert xai_post.call_count == 1
1230 assert fallback_search.call_count == 1
1231 assert report.items_by_source["x"]
1232 assert report.source_status["x"].state == expected_state
1233 assert report.source_status["x"].lane_failure_state == schema.RATE_LIMITED
1234 assert "xquik also rate-limited" in report.source_status["x"].detail
1235 assert f"xai: HTTP {xai_status}" in report.source_status["x"].detail
1236 results = cli._quality_research_results(
1237 report, {"available_sources": ["x"]}, {"attempts": 0, "failures": 0}
1238 )
1239 q = _compute(config_overrides=config, result_overrides=results, ytdlp_installed=True)
1240 assert expected_fix in q["nudge_text"]
1241 assert "log into x.com" not in q["nudge_text"]
1242
1243
1244 class TestYouTubeTranscriptTargetAndBotCheck:
1245 """#1449: health is measured against the transcript target, and a bot
1246 check gets its own cause instead of stale-yt-dlp upgrade advice."""
1247
1248 def test_four_of_six_with_target_two_is_not_degraded(self):
1249 q = _compute(
1250 ytdlp_installed=True,
1251 result_overrides={
1252 "youtube_videos_count": 6,
1253 "youtube_transcripts_count": 4,
1254 "youtube_transcript_fetch_attempts": 6,
1255 "youtube_transcript_fetch_failures": 2,
1256 "youtube_transcript_target": 2,
1257 },
1258 )
1259 assert "youtube" not in q["core_degraded"]
1260
1261 def test_issue_run_four_of_fifteen_with_target_two_is_not_degraded(self):
1262 q = _compute(
1263 ytdlp_installed=True,
1264 result_overrides={
1265 "youtube_videos_count": 15,
1266 "youtube_transcripts_count": 4,
1267 "youtube_transcript_fetch_attempts": 6,
1268 "youtube_transcript_fetch_failures": 4,
1269 "youtube_transcript_target": 2,
1270 "youtube_bot_checked": 1,
1271 "youtube_sc_rescued": 2,
1272 },
1273 )
1274 assert "youtube" not in q["core_degraded"]
1275
1276 def test_zero_of_target_is_still_degraded(self):
1277 q = _compute(
1278 ytdlp_installed=True,
1279 result_overrides={
1280 "youtube_videos_count": 15,
1281 "youtube_transcripts_count": 0,
1282 "youtube_transcript_fetch_attempts": 6,
1283 "youtube_transcript_fetch_failures": 6,
1284 "youtube_transcript_target": 2,
1285 },
1286 )
1287 assert "youtube" in q["core_degraded"]
1288
1289 def test_bot_check_with_rescues_names_the_cause_without_upgrade_advice(self):
1290 q = _compute(
1291 config_overrides={"SCRAPECREATORS_API_KEY": "sc-dummy"},
1292 ytdlp_installed=True,
1293 result_overrides={
1294 "youtube_videos_count": 15,
1295 "youtube_transcripts_count": 1,
1296 "youtube_transcript_fetch_attempts": 6,
1297 "youtube_transcript_fetch_failures": 5,
1298 "youtube_transcript_target": 8,
1299 "youtube_bot_checked": 1,
1300 "youtube_sc_rescued": 1,
1301 },
1302 )
1303 assert "youtube" in q["core_degraded"]
1304 text = q["nudge_text"]
1305 assert "bot-checked yt-dlp" in text
1306 assert "ScrapeCreators rescued 1 of them" in text
1307 assert "LAST30DAYS_YOUTUBE_SSH_HOST" in text
1308 assert "won't help" in text
1309 assert "stale yt-dlp binary" not in text
1310 assert "brew upgrade" not in text
1311 assert "pip install" not in text
1312 # A keyed run is not told to add the key it already has.
1313 assert "add SCRAPECREATORS_API_KEY" not in text
1314
1315 def test_bot_check_without_a_key_suggests_ssh_host_and_scrapecreators_key(self):
1316 q = _compute(
1317 ytdlp_installed=True,
1318 result_overrides={
1319 "youtube_videos_count": 8,
1320 "youtube_transcripts_count": 0,
1321 "youtube_transcript_fetch_attempts": 6,
1322 "youtube_transcript_fetch_failures": 6,
1323 "youtube_transcript_target": 2,
1324 "youtube_bot_checked": 1,
1325 },
1326 )
1327 assert "youtube" in q["core_degraded"]
1328 text = q["nudge_text"]
1329 assert "bot-checked yt-dlp" in text
1330 assert "LAST30DAYS_YOUTUBE_SSH_HOST" in text
1331 assert "SCRAPECREATORS_API_KEY" in text
1332 assert "stale yt-dlp binary" not in text
1333 assert "brew upgrade" not in text
1334
1335 def test_failures_without_a_bot_check_keep_the_stale_ytdlp_advice(self):
1336 q = _compute(
1337 ytdlp_installed=True,
1338 result_overrides={
1339 "youtube_videos_count": 8,
1340 "youtube_transcripts_count": 0,
1341 "youtube_transcript_fetch_attempts": 6,
1342 "youtube_transcript_fetch_failures": 6,
1343 "youtube_transcript_target": 2,
1344 "youtube_bot_checked": 0,
1345 },
1346 )
1347 text = q["nudge_text"]
1348 assert "stale yt-dlp" in text.lower()
1349 assert "brew" in text.lower()
1350 assert "bot-checked" not in text
1351
1352
1353 class TestBonusHintYouTubeComments:
1354 """The SC bonus hint must not ask for youtube_comments that is already on.
1355
1356 yt-dlp fetches YouTube comments keyless, and an existing INCLUDE_SOURCES
1357 entry needs no hint either (issue #1437).
1358 """
1359
1360 def _text(self, ytdlp_installed, include_sources=None, exclude_sources=None):
1361 overrides = {}
1362 if include_sources is not None:
1363 overrides["INCLUDE_SOURCES"] = include_sources
1364 if exclude_sources is not None:
1365 overrides["EXCLUDE_SOURCES"] = exclude_sources
1366 q = _compute(
1367 config_overrides={"SCRAPECREATORS_API_KEY": "sc-key", **overrides},
1368 ytdlp_installed=ytdlp_installed,
1369 result_overrides={
1370 "youtube_videos_count": 8,
1371 "youtube_transcripts_count": 0,
1372 "youtube_transcript_fetch_attempts": 6,
1373 "youtube_transcript_fetch_failures": 6,
1374 "youtube_transcript_target": 2,
1375 },
1376 )
1377 assert q["nudge_text"]
1378 return q["nudge_text"]
1379
1380 def test_ytdlp_installed_drops_youtube_comments_from_the_hint(self):
1381 text = self._text(ytdlp_installed=True)
1382 assert "SC key also powers" in text
1383 assert "YouTube comments" not in text
1384
1385 def test_include_sources_entry_drops_youtube_comments_from_the_hint(self):
1386 text = self._text(
1387 ytdlp_installed=False, include_sources="threads,pinterest,youtube_comments"
1388 )
1389 assert "SC key also powers" in text
1390 assert "YouTube comments" not in text
1391
1392 def test_missing_comments_key_still_asks_for_the_opt_in(self):
1393 text = self._text(ytdlp_installed=False, include_sources="threads,pinterest")
1394 assert "SC key also powers Threads, Pinterest, YouTube comments." in text
1395
1396 def test_excluded_comments_are_not_recommended(self):
1397 """EXCLUDE_SOURCES overrides INCLUDE_SOURCES, so the hint cannot work."""
1398 text = self._text(
1399 ytdlp_installed=False,
1400 include_sources="threads,pinterest",
1401 exclude_sources="youtube_comments",
1402 )
1403 assert "SC key also powers Threads, Pinterest." in text
1404 assert "YouTube comments" not in text
1405
1405 lines PYTHON