返回 last30days-skill
test_pipeline_v3.py
根目录 / tests / test_pipeline_v3.py
1 import contextlib
2 import dataclasses
3 import threading
4 from datetime import datetime, timezone
5 import time
6 import unittest
7
8 import pytest
9 from unittest.mock import patch
10
11 from lib import health
12 from lib import fanout
13 from lib import http
14 from lib import pipeline
15 from lib import polymarket
16 from lib import rerank
17 from lib import schema
18 from lib import subproc
19
20
21 class DepthSettingsOverrideTests(unittest.TestCase):
22 def test_no_overrides_returns_depth_defaults(self):
23 settings = pipeline._resolve_depth_settings("deep", {})
24 self.assertEqual(pipeline.DEPTH_SETTINGS["deep"], settings)
25
26 def test_overrides_raise_caps_and_do_not_mutate_module_defaults(self):
27 before = dict(pipeline.DEPTH_SETTINGS["deep"])
28 settings = pipeline._resolve_depth_settings(
29 "deep", {"_max_per_source": 60, "_max_results": 200}
30 )
31 self.assertEqual(60, settings["per_stream_limit"])
32 self.assertEqual(200, settings["pool_limit"])
33 self.assertEqual(200, settings["rerank_limit"])
34 # Module-level defaults must be untouched (issue #716 regression guard).
35 self.assertEqual(before, pipeline.DEPTH_SETTINGS["deep"])
36
37 def test_overrides_can_also_lower_caps(self):
38 settings = pipeline._resolve_depth_settings("deep", {"_max_results": 10})
39 self.assertEqual(10, settings["rerank_limit"])
40
41 def test_zero_override_is_honored_not_swallowed(self):
42 # 0 is a valid explicit value (e.g. disable a source), not "unset".
43 settings = pipeline._resolve_depth_settings(
44 "deep", {"_max_results": 0, "_max_per_source": 0}
45 )
46 self.assertEqual(0, settings["pool_limit"])
47 self.assertEqual(0, settings["rerank_limit"])
48 self.assertEqual(0, settings["per_stream_limit"])
49
50 def test_negative_overrides_are_clamped_to_zero(self):
51 # The caps reach list slicing directly (e.g. legacy[:per_stream_limit]),
52 # where a negative bound keeps everything but the last |cap| items: a
53 # cap of -2 retains more than a cap of 2. Clamp to the documented lower
54 # bound instead of inverting the cap.
55 settings = pipeline._resolve_depth_settings(
56 "deep", {"_max_results": -5, "_max_per_source": -2}
57 )
58 self.assertEqual(0, settings["per_stream_limit"])
59 self.assertEqual(0, settings["digg_stream_limit"])
60 self.assertEqual(0, settings["pool_limit"])
61 self.assertEqual(0, settings["rerank_limit"])
62
63
64 class PipelineV3Tests(unittest.TestCase):
65 def test_failed_rerank_keeps_agent_export_usage_null(self):
66 calls = 0
67
68 def response(url, body, **kwargs):
69 nonlocal calls
70 calls += 1
71 if calls > 1:
72 raise http.HTTPError("timed out")
73 return {
74 "candidates": [{"content": {"parts": [{"text": '{"scores": []}'}]}}],
75 "usageMetadata": {
76 "promptTokenCount": 10,
77 "candidatesTokenCount": 1,
78 "totalTokenCount": 11,
79 },
80 }
81
82 with patch.object(pipeline, "available_sources", return_value=["reddit"]), patch.object(
83 pipeline, "_retrieve_stream",
84 side_effect=lambda **kwargs: pipeline._mock_stream_results(
85 kwargs["source"], kwargs["subquery"]
86 ),
87 ), patch.object(pipeline, "_retry_thin_sources"), patch.object(
88 pipeline.providers.http, "post", side_effect=response
89 ):
90 report = pipeline.run(
91 topic="AI coding agents",
92 config={"GOOGLE_API_KEY": "dummy-key", "LAST30DAYS_REASONING_PROVIDER": "gemini"},
93 depth="quick",
94 requested_sources=["reddit"],
95 web_backend="none",
96 external_plan={
97 "intent": "research",
98 "freshness_mode": "balanced_recent",
99 "cluster_mode": "topic",
100 "subqueries": [{
101 "label": "primary",
102 "search_query": "AI coding agents",
103 "ranking_query": "AI coding agents",
104 "sources": ["reddit"],
105 }],
106 },
107 )
108
109 self.assertGreaterEqual(calls, 2)
110 self.assertIsNone(schema.to_agent_export(report)["usage"])
111
112 def test_agent_export_usage_includes_final_rerank_calls(self):
113 calls = []
114
115 def response(url, body, **kwargs):
116 self.assertIn("generativelanguage.googleapis.com", url)
117 calls.append(body)
118 prompt_tokens = len(calls) * 10
119 return {
120 "candidates": [{"content": {"parts": [{"text": '{"scores": []}'}]}}],
121 "usageMetadata": {
122 "promptTokenCount": prompt_tokens,
123 "candidatesTokenCount": 1,
124 "totalTokenCount": prompt_tokens + 1,
125 },
126 }
127
128 with patch.object(pipeline, "available_sources", return_value=["reddit"]), patch.object(
129 pipeline, "_retrieve_stream",
130 side_effect=lambda **kwargs: pipeline._mock_stream_results(
131 kwargs["source"], kwargs["subquery"]
132 ),
133 ), patch.object(pipeline, "_retry_thin_sources"), patch.object(
134 pipeline.providers.http, "post", side_effect=response
135 ):
136 report = pipeline.run(
137 topic="AI coding agents",
138 config={"GOOGLE_API_KEY": "dummy-key", "LAST30DAYS_REASONING_PROVIDER": "gemini"},
139 depth="quick",
140 requested_sources=["reddit"],
141 web_backend="none",
142 external_plan={
143 "intent": "research",
144 "freshness_mode": "balanced_recent",
145 "cluster_mode": "topic",
146 "subqueries": [{
147 "label": "primary",
148 "search_query": "AI coding agents",
149 "ranking_query": "AI coding agents",
150 "sources": ["reddit"],
151 }],
152 },
153 )
154
155 self.assertGreaterEqual(len(calls), 2)
156 expected = {
157 "calls": len(calls),
158 "promptTokens": sum(i * 10 for i in range(1, len(calls) + 1)),
159 "completionTokens": len(calls),
160 "totalTokens": sum(i * 10 + 1 for i in range(1, len(calls) + 1)),
161 }
162 self.assertEqual(expected, schema.to_agent_export(report)["usage"])
163
164 def test_mock_pipeline_report_without_live_credentials(self):
165 report = pipeline.run(
166 topic="test topic",
167 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
168 depth="quick",
169 requested_sources=["reddit", "x", "grounding"],
170 mock=True,
171 )
172 self.assertEqual("test topic", report.topic)
173 self.assertTrue(report.ranked_candidates)
174 self.assertTrue(report.clusters)
175 self.assertIn("x", report.items_by_source)
176 # Grounding items now enter the ranked pool (web search backends produce real items)
177 self.assertIn("grounding", report.items_by_source)
178 self.assertEqual("gemini", report.provider_runtime.reasoning_provider)
179
180 def test_empty_explicit_plan_is_rejected(self):
181 with self.assertRaisesRegex(ValueError, "intent"):
182 pipeline.run(
183 topic="test topic",
184 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
185 depth="quick",
186 external_plan={},
187 mock=True,
188 )
189
190 def test_external_plan_honors_per_subquery_sources_at_default_depth(self):
191 # Issue #1073: --plan sources are a contract at default/deep.
192 plan = {
193 "intent": "opinion",
194 "freshness_mode": "balanced_recent",
195 "cluster_mode": "debate",
196 "subqueries": [
197 {
198 "label": "primary",
199 "search_query": "late diagnosed autism adults",
200 "ranking_query": "What are people saying about late diagnosed autism in adults?",
201 "sources": ["reddit", "x", "youtube"],
202 "weight": 1.0,
203 }
204 ],
205 }
206 report = pipeline.run(
207 topic="late diagnosed autism adults",
208 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
209 depth="default",
210 requested_sources=["reddit", "x", "youtube", "hackernews", "polymarket", "github"],
211 mock=True,
212 web_backend="none",
213 external_plan=plan,
214 )
215 self.assertEqual(
216 ["reddit", "x", "youtube"],
217 report.query_plan.subqueries[0].sources,
218 )
219 self.assertNotIn("hackernews", report.items_by_source)
220 self.assertNotIn("polymarket", report.items_by_source)
221 self.assertNotIn("github", report.items_by_source)
222
223 def test_planner_trace_always_fires_on_mock_run(self):
224 """Unit 5: The unified planner trace emits one summary line plus one
225 line per subquery on every run, regardless of --debug. 2026-04-19
226 Hermes Agent Use Cases failure: retrieval-breadth issues were invisible
227 because the internal planner path logged nothing.
228 """
229 import io
230 import contextlib
231 buf = io.StringIO()
232 with contextlib.redirect_stderr(buf):
233 pipeline.run(
234 topic="test topic",
235 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
236 depth="quick",
237 requested_sources=["reddit", "x", "grounding"],
238 mock=True,
239 )
240 output = buf.getvalue()
241 self.assertIn("[Planner] Plan: intent=", output)
242 self.assertIn("subqueries=", output)
243 self.assertIn("source=", output)
244 # At least one per-subquery line.
245 self.assertIn("[Planner] sq1 label=", output)
246
247 def test_parallel_web_backend_enables_grounding_source(self):
248 plan = {
249 "intent": "news",
250 "freshness_mode": "balanced_recent",
251 "cluster_mode": "timeline",
252 "subqueries": [
253 {
254 "label": "primary",
255 "search_query": "test topic",
256 "ranking_query": "What happened with test topic?",
257 "sources": ["grounding"],
258 }
259 ],
260 "source_weights": {"grounding": 1.0},
261 }
262 report = pipeline.run(
263 topic="test topic",
264 config={"LAST30DAYS_REASONING_PROVIDER": "auto"},
265 depth="quick",
266 requested_sources=["grounding"],
267 web_backend="parallel",
268 external_plan=plan,
269 )
270 # Anchor on the stable source key, not the exact wording of the
271 # grounding.py error message. Phrasing can shift (e.g., when the
272 # missing-key check moves or the message is reworded) without
273 # changing the contract that the grounding source registers an
274 # error when its required backend key is unset.
275 self.assertIn("grounding", report.errors_by_source)
276
277 def test_parallel_mcp_enables_grounding_without_key_on_native_host(self):
278 def mcp_response(message, _api_key, _session_id=None):
279 results = {
280 "initialize": {"protocolVersion": "2025-03-26"},
281 "notifications/initialized": {},
282 "tools/list": {"tools": [{"name": "web_search"}]},
283 "tools/call": {"structuredContent": {"results": [{
284 "url": "https://example.com/update",
285 "title": "Test topic update",
286 "publish_date": "2026-08-01",
287 "excerpts": ["New evidence about test topic"],
288 }]}},
289 }
290 return {"result": results[message["method"]]}, None
291
292 with patch("lib.parallel_mcp._request", side_effect=mcp_response):
293 report = pipeline.run(
294 topic="test topic",
295 config={"LAST30DAYS_REASONING_PROVIDER": "auto", "LAST30DAYS_NATIVE_SEARCH": "1"},
296 depth="quick",
297 requested_sources=["grounding"],
298 web_backend="parallel-mcp",
299 as_of_date="2026-08-26",
300 )
301 self.assertNotIn("grounding", report.errors_by_source)
302 self.assertEqual(1, len(report.items_by_source["grounding"]))
303 self.assertEqual("2026-08-01", report.items_by_source["grounding"][0].published_at)
304
305 def test_hiring_signals_mode_enables_jobs_source_in_mock_run(self):
306 report = pipeline.run(
307 topic="Listen Labs",
308 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
309 depth="quick",
310 requested_sources=["jobs"],
311 mock=True,
312 hiring_signals_mode=True,
313 )
314 self.assertIn("jobs", report.items_by_source)
315 self.assertIn("hiring_signals", report.artifacts)
316 self.assertTrue(report.artifacts["hiring_signals"]["include"])
317
318 def test_hiring_signals_mode_defaults_to_jobs_source(self):
319 report = pipeline.run(
320 topic="Listen Labs",
321 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
322 depth="quick",
323 mock=True,
324 hiring_signals_mode=True,
325 )
326 self.assertEqual(["jobs"], sorted(report.items_by_source))
327 self.assertTrue(report.artifacts["hiring_signals"]["include"])
328
329 def test_explicit_sources_suppress_automatic_company_jobs(self):
330 report = pipeline.run(
331 topic="Listen Labs",
332 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
333 depth="quick",
334 requested_sources=["grounding", "x"],
335 mock=True,
336 )
337 self.assertEqual({"grounding", "x"}, set(report.items_by_source))
338 self.assertTrue(
339 all("jobs" not in subquery.sources for subquery in report.query_plan.subqueries)
340 )
341
342 def test_hiring_signals_forces_jobs_with_explicit_non_jobs_sources(self):
343 report = pipeline.run(
344 topic="Listen Labs",
345 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
346 depth="quick",
347 requested_sources=["grounding", "x"],
348 mock=True,
349 hiring_signals_mode=True,
350 )
351 self.assertEqual({"grounding", "jobs", "x"}, set(report.items_by_source))
352
353 def test_standard_company_run_fetches_jobs_for_signal_gate(self):
354 report = pipeline.run(
355 topic="Listen Labs",
356 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
357 depth="quick",
358 mock=True,
359 )
360 self.assertIn("jobs", report.items_by_source)
361 self.assertIn("hiring_signals", report.artifacts)
362
363 def test_standard_mock_run_does_not_add_jobs_for_generic_topic(self):
364 report = pipeline.run(
365 topic="how to deploy on Fly.io",
366 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
367 depth="quick",
368 mock=True,
369 )
370 self.assertNotIn("jobs", report.items_by_source)
371 self.assertNotIn("hiring_signals", report.artifacts)
372
373 def test_single_word_generic_topic_does_not_add_jobs(self):
374 report = pipeline.run(
375 topic="bitcoin",
376 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
377 depth="quick",
378 mock=True,
379 )
380 self.assertNotIn("jobs", report.items_by_source)
381 self.assertNotIn("hiring_signals", report.artifacts)
382
383 def test_question_comparison_topic_does_not_add_jobs(self):
384 report = pipeline.run(
385 topic="Python vs Ruby benchmark?",
386 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
387 depth="quick",
388 mock=True,
389 )
390 self.assertNotIn("jobs", report.items_by_source)
391 self.assertNotIn("hiring_signals", report.artifacts)
392
393 def test_bare_language_comparison_topics_do_not_add_jobs(self):
394 for topic in ("python vs ruby", "Python vs Ruby"):
395 with self.subTest(topic=topic):
396 self.assertFalse(pipeline._company_topic_likely(topic))
397
398 def test_company_comparison_topics_add_jobs(self):
399 for topic in ("Stripe vs Brex", "OpenAI versus Anthropic"):
400 with self.subTest(topic=topic):
401 self.assertTrue(pipeline._company_topic_likely(topic))
402
403 def test_standard_mode_omits_weak_large_company_jobs_signal(self):
404 with patch("lib.pipeline._retrieve_stream") as mock_retrieve:
405 def fake_retrieve(**kwargs):
406 if kwargs["source"] == "jobs":
407 return (
408 [
409 {
410 "id": "J1",
411 "title": "Retail Associate",
412 "description": "Store operations",
413 "url": "https://example.com/jobs/1",
414 "department": "Retail",
415 "date": "2026-06-01",
416 "provider": "mock",
417 }
418 ],
419 {},
420 )
421 return pipeline._mock_stream_results(kwargs["source"], kwargs["subquery"])
422
423 mock_retrieve.side_effect = fake_retrieve
424 report = pipeline.run(
425 topic="Apple",
426 config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
427 depth="quick",
428 requested_sources=["jobs"],
429 mock=True,
430 )
431 self.assertNotIn("jobs", report.items_by_source)
432 self.assertFalse(report.artifacts["hiring_signals"]["include"])
433
434
435 class TestSourceFetchCap(unittest.TestCase):
436 def test_paid_budget_rejects_non_owner_before_owner_claims(self):
437 paid_budget = pipeline.PaidSourceBudget(owner="main")
438
439 self.assertFalse(paid_budget.try_consume(1, claimant="peer"))
440 self.assertEqual(0, paid_budget.used)
441 self.assertTrue(paid_budget.try_consume(1, claimant="main"))
442 self.assertEqual(1, paid_budget.used)
443
444 """X source fetch count must be capped by MAX_SOURCE_FETCHES."""
445
446 def test_x_capped_in_max_source_fetches(self):
447 """MAX_SOURCE_FETCHES must cap X at 2 to prevent 429 cascades."""
448 self.assertIn("x", pipeline.MAX_SOURCE_FETCHES)
449 self.assertEqual(pipeline.MAX_SOURCE_FETCHES["x"], 2)
450
451 def test_jobs_capped_in_max_source_fetches(self):
452 self.assertIn("jobs", pipeline.MAX_SOURCE_FETCHES)
453 self.assertEqual(pipeline.MAX_SOURCE_FETCHES["jobs"], 1)
454
455 def test_perplexity_paid_call_cap_cannot_be_raised_by_generic_override(self):
456 self.assertEqual(
457 1,
458 pipeline._source_fetch_cap(
459 "perplexity",
460 {"_max_source_fetches": 10},
461 ),
462 )
463 self.assertEqual(
464 0,
465 pipeline._source_fetch_cap(
466 "perplexity",
467 {"_max_source_fetches": 0},
468 ),
469 )
470
471 def test_deep_research_lane_is_isolated_and_does_not_replace_primary(self):
472 primary = schema.SubQuery(
473 label="primary",
474 search_query="narrow angle",
475 ranking_query="narrow angle",
476 sources=["reddit", "grounding", "perplexity"],
477 )
478 plan = schema.QueryPlan(
479 intent="general",
480 freshness_mode="balanced_recent",
481 cluster_mode="story",
482 raw_topic="whole topic",
483 subqueries=[primary],
484 source_weights={"reddit": 1.0, "grounding": 1.0, "perplexity": 1.0},
485 )
486
487 pipeline._ensure_perplexity_in_plan(
488 plan,
489 "whole topic",
490 ["reddit", "grounding", "perplexity"],
491 force=True,
492 )
493
494 self.assertEqual("primary", plan.subqueries[0].label)
495 self.assertEqual(["reddit", "grounding"], plan.subqueries[0].sources)
496 self.assertEqual("deep-research", plan.subqueries[-1].label)
497 self.assertEqual(["perplexity"], plan.subqueries[-1].sources)
498
499 @patch("lib.pipeline._retry_thin_sources")
500 @patch("lib.pipeline._retrieve_stream")
501 def test_run_caps_primary_x_fetches_without_capping_reddit(self, mock_retrieve, _retry):
502 mock_retrieve.return_value = ([], {})
503 report = pipeline.run(
504 topic="compare iPhone vs Android",
505 config={},
506 depth="default",
507 requested_sources=["reddit", "x"],
508 mock=True,
509 web_backend="none",
510 external_plan={
511 "intent": "comparison",
512 "freshness_mode": "balanced_recent",
513 "cluster_mode": "topic",
514 "subqueries": [
515 {"label": label, "search_query": f"phones {label}",
516 "ranking_query": f"phones {label}", "sources": ["x", "reddit"]}
517 for label in ["price", "camera", "battery", "privacy"]
518 ],
519 },
520 )
521 self.assertEqual(4, len(report.query_plan.subqueries))
522 submissions = {(call.kwargs["source"], call.kwargs["subquery"].label)
523 for call in mock_retrieve.call_args_list}
524 self.assertEqual(
525 {("x", "price"), ("x", "camera"),
526 *[("reddit", label) for label in ["price", "camera", "battery", "privacy"]]},
527 submissions,
528 )
529 self.assertEqual(6, mock_retrieve.call_count)
530
531 @patch("lib.pipeline._retrieve_stream")
532 def test_zero_source_fetch_override_suppresses_capped_source(self, mock_retrieve):
533 """A 0 override is explicit and should suppress capped-source submissions."""
534 mock_retrieve.side_effect = lambda **kwargs: pipeline._mock_stream_results(
535 kwargs["source"], kwargs["subquery"]
536 )
537 pipeline.run(
538 topic="compare iPhone vs Android vs Pixel vs Samsung",
539 config={
540 "LAST30DAYS_REASONING_PROVIDER": "gemini",
541 "_max_source_fetches": 0,
542 },
543 depth="quick",
544 requested_sources=["reddit", "x"],
545 mock=True,
546 )
547 x_calls = [
548 call for call in mock_retrieve.call_args_list
549 if call.kwargs.get("source") == "x"
550 ]
551 reddit_calls = [
552 call for call in mock_retrieve.call_args_list
553 if call.kwargs.get("source") == "reddit"
554 ]
555 self.assertEqual([], x_calls)
556 self.assertGreater(len(reddit_calls), 0)
557
558 @patch("lib.pipeline._retrieve_stream")
559 def test_deep_research_subquery_fanout_submits_once(self, mock_retrieve):
560 mock_retrieve.return_value = ([], {})
561 plan = {
562 "intent": "comparison",
563 "freshness_mode": "balanced_recent",
564 "cluster_mode": "debate",
565 "subqueries": [
566 {
567 "label": f"angle-{index}",
568 "search_query": f"topic angle {index}",
569 "ranking_query": f"topic angle {index}",
570 "sources": ["perplexity"],
571 }
572 for index in range(3)
573 ],
574 "source_weights": {"perplexity": 1.0},
575 }
576
577 pipeline.run(
578 topic="whole topic",
579 config={
580 "LAST30DAYS_REASONING_PROVIDER": "gemini",
581 "PERPLEXITY_API_KEY": "pplx-test",
582 "_deep_research": True,
583 "_max_source_fetches": 10,
584 },
585 depth="default",
586 requested_sources=["reddit", "perplexity"],
587 mock=True,
588 external_plan=plan,
589 )
590
591 perplexity_calls = [
592 call
593 for call in mock_retrieve.call_args_list
594 if call.kwargs.get("source") == "perplexity"
595 ]
596 self.assertEqual(1, len(perplexity_calls))
597 self.assertEqual(
598 "whole topic",
599 perplexity_calls[0].kwargs["subquery"].search_query,
600 )
601
602 @patch("lib.pipeline._retrieve_stream")
603 def test_normal_perplexity_subquery_fanout_submits_once(self, mock_retrieve):
604 mock_retrieve.return_value = ([], {})
605 plan = {
606 "intent": "comparison",
607 "freshness_mode": "balanced_recent",
608 "cluster_mode": "debate",
609 "subqueries": [
610 {
611 "label": f"angle-{index}",
612 "search_query": f"topic angle {index}",
613 "ranking_query": f"topic angle {index}",
614 "sources": ["perplexity"],
615 }
616 for index in range(4)
617 ],
618 "source_weights": {"perplexity": 1.0},
619 }
620
621 pipeline.run(
622 topic="whole topic",
623 config={
624 "LAST30DAYS_REASONING_PROVIDER": "gemini",
625 "PERPLEXITY_API_KEY": "pplx-test",
626 "_max_source_fetches": 10,
627 },
628 depth="default",
629 requested_sources=["perplexity"],
630 mock=True,
631 external_plan=plan,
632 )
633
634 perplexity_calls = [
635 call
636 for call in mock_retrieve.call_args_list
637 if call.kwargs.get("source") == "perplexity"
638 ]
639 self.assertEqual(1, len(perplexity_calls))
640 self.assertEqual(
641 "whole topic",
642 perplexity_calls[0].kwargs["subquery"].search_query,
643 )
644
645 @patch("lib.pipeline._retrieve_stream")
646 def test_shared_paid_budget_caps_competitor_subruns(self, mock_retrieve):
647 mock_retrieve.return_value = ([], {})
648 paid_budget = pipeline.PaidSourceBudget()
649 plan = {
650 "intent": "general",
651 "freshness_mode": "balanced_recent",
652 "cluster_mode": "story",
653 "subqueries": [
654 {
655 "label": "primary",
656 "search_query": "entity angle",
657 "ranking_query": "entity angle",
658 "sources": ["perplexity"],
659 }
660 ],
661 "source_weights": {"perplexity": 1.0},
662 }
663
664 for entity in ("main", "peer-a", "peer-b"):
665 pipeline.run(
666 topic=entity,
667 config={
668 "LAST30DAYS_REASONING_PROVIDER": "gemini",
669 "PERPLEXITY_API_KEY": "pplx-test",
670 "_perplexity_paid_budget": paid_budget,
671 },
672 depth="quick",
673 requested_sources=["perplexity"],
674 mock=True,
675 external_plan=plan,
676 internal_subrun=True,
677 )
678
679 perplexity_calls = [
680 call
681 for call in mock_retrieve.call_args_list
682 if call.kwargs.get("source") == "perplexity"
683 ]
684 self.assertEqual(1, len(perplexity_calls))
685 self.assertEqual(1, paid_budget.used)
686
687 @patch("lib.pipeline._retrieve_stream")
688 def test_shared_paid_budget_is_reserved_for_main_competitor_topic(
689 self,
690 mock_retrieve,
691 ):
692 mock_retrieve.return_value = ([], {})
693 paid_budget = pipeline.PaidSourceBudget(owner="main")
694 barrier = threading.Barrier(3)
695 plan = {
696 "intent": "general",
697 "freshness_mode": "balanced_recent",
698 "cluster_mode": "story",
699 "subqueries": [
700 {
701 "label": "primary",
702 "search_query": "entity angle",
703 "ranking_query": "entity angle",
704 "sources": ["perplexity"],
705 }
706 ],
707 "source_weights": {"perplexity": 1.0},
708 }
709
710 def run_entity(entity):
711 barrier.wait()
712 return pipeline.run(
713 topic=entity,
714 config={
715 "LAST30DAYS_REASONING_PROVIDER": "gemini",
716 "PERPLEXITY_API_KEY": "pplx-test",
717 "_perplexity_paid_budget": paid_budget,
718 },
719 depth="quick",
720 requested_sources=["perplexity"],
721 mock=True,
722 external_plan=plan,
723 internal_subrun=True,
724 )
725
726 results = fanout.run_competitor_fanout(
727 main_topic="main",
728 main_runner=lambda: run_entity("main"),
729 competitors=["peer-a", "peer-b"],
730 competitor_runner=run_entity,
731 )
732
733 perplexity_calls = [
734 call
735 for call in mock_retrieve.call_args_list
736 if call.kwargs.get("source") == "perplexity"
737 ]
738 self.assertEqual(1, len(perplexity_calls))
739 self.assertEqual("main", perplexity_calls[0].kwargs["topic"])
740 self.assertEqual(1, paid_budget.used)
741 for entity, report in results[1:]:
742 receipt = report.artifacts["paid_source_budget"]["perplexity"]
743 self.assertEqual("skipped-budget", receipt["state"])
744 self.assertFalse(receipt["attempted"])
745 self.assertEqual("main", receipt["owner"])
746 self.assertEqual(entity, receipt["claimant"])
747
748
749 class TestRateLimitSharing(unittest.TestCase):
750 """429 signals should be shared across subqueries."""
751
752 def test_is_rate_limit_error_detects_429_status(self):
753 exc = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
754 self.assertTrue(pipeline._is_rate_limit_error(exc))
755
756 def test_is_rate_limit_error_ignores_non_429(self):
757 exc = http.HTTPError("HTTP 400: Bad Request", status_code=400)
758 self.assertFalse(pipeline._is_rate_limit_error(exc))
759
760 def test_is_rate_limit_error_detects_429_in_string(self):
761 exc = RuntimeError("xAI returned 429 rate limit")
762 self.assertTrue(pipeline._is_rate_limit_error(exc))
763
764 def test_is_rate_limit_error_rejects_unrelated_error(self):
765 exc = RuntimeError("Connection refused")
766 self.assertFalse(pipeline._is_rate_limit_error(exc))
767
768 def test_is_rate_limit_error_rejects_embedded_digits(self):
769 # CR-007: "14293" must not read as a 429.
770 exc = RuntimeError("request id 14293 failed")
771 self.assertFalse(pipeline._is_rate_limit_error(exc))
772
773 def test_is_rate_limit_error_detects_standalone_code(self):
774 exc = RuntimeError("failed with HTTP 429")
775 self.assertTrue(pipeline._is_rate_limit_error(exc))
776
777 def test_is_rate_limit_error_rejects_bare_number(self):
778 # A bare 429 with no HTTP/status/rate-limit marker is not a rate
779 # limit; misreading it skips the source for the rest of the run.
780 exc = RuntimeError("batch 429 failed")
781 self.assertFalse(pipeline._is_rate_limit_error(exc))
782
783 def test_is_rate_limit_error_accepts_real_message_shapes(self):
784 for msg in (
785 "HTTP 429: Too Many Requests",
786 "HTTP Error 429: Too Many Requests",
787 "xapi: http 429",
788 "status: 429",
789 "status_code=429",
790 "Reddit rate limited (429) fetching https://example.com",
791 "429 Too Many Requests",
792 ):
793 with self.subTest(msg=msg):
794 self.assertTrue(pipeline._is_rate_limit_error(RuntimeError(msg)))
795
796 def test_is_transient_error_rejects_embedded_digits(self):
797 # CR-023: "15003" must not read as a 500.
798 exc = RuntimeError("job 15003 failed")
799 self.assertFalse(pipeline._is_transient_error(exc))
800
801 def test_is_transient_error_detects_full_5xx_range(self):
802 for code in ("500", "501", "502", "503", "504", "505", "507", "508", "520", "524", "599"):
803 with self.subTest(code=code):
804 exc = RuntimeError(f"upstream failed with HTTP {code}")
805 self.assertTrue(pipeline._is_transient_error(exc))
806
807 def test_is_transient_error_rejects_bare_number(self):
808 exc = RuntimeError("job 500 rows failed")
809 self.assertFalse(pipeline._is_transient_error(exc))
810
811 def test_is_transient_error_accepts_real_message_shapes(self):
812 for msg in (
813 "HTTP 503: Service Unavailable",
814 "HTTP Error 502: Bad Gateway",
815 "HTTP/1.1 504 Gateway Timeout",
816 "error code 520",
817 "upstream returned 502 Bad Gateway",
818 ):
819 with self.subTest(msg=msg):
820 self.assertTrue(pipeline._is_transient_error(RuntimeError(msg)))
821
822 def test_is_transient_error_rejects_unrelated_error(self):
823 exc = RuntimeError("Connection refused")
824 self.assertFalse(pipeline._is_transient_error(exc))
825
826 def test_retrieve_stream_exception_path_prefers_specific_failure(self):
827 # CR-008: the exception path must use _FAILURE_SPECIFICITY, so an
828 # AUTH_FAILED captured earlier is not masked by a later 429.
829 from lib import schema as _schema
830
831 def boom(*_args, **_kwargs):
832 # Record into the enclosing capture sink: auth first, 429 last,
833 # so the old failures[-1] code would have picked RATE_LIMITED.
834 http._record_failure(http.HTTPError("HTTP 401", status_code=401))
835 http._record_failure(http.HTTPError("HTTP 429", status_code=429))
836 raise RuntimeError("stream blew up")
837
838 with patch("lib.pipeline._retrieve_stream_impl", side_effect=boom):
839 with self.assertRaises(pipeline.SourceRunError) as caught:
840 pipeline._retrieve_stream(
841 topic="test",
842 subquery=_schema.SubQuery(
843 label="test",
844 search_query="test query",
845 ranking_query="test query",
846 sources=["x"],
847 ),
848 source="other",
849 config={},
850 depth="quick",
851 date_range=("2026-02-15", "2026-03-17"),
852 runtime=_schema.ProviderRuntime(
853 reasoning_provider="mock",
854 planner_model="mock",
855 rerank_model="mock",
856 ),
857 mock=True,
858 )
859 self.assertEqual(caught.exception.outcome_state, _schema.AUTH_FAILED)
860
861 def test_retrieve_stream_skips_rate_limited_source(self):
862 """_retrieve_stream should return empty when source is rate-limited."""
863 from lib import schema
864 rate_limited = {"x"}
865 lock = threading.Lock()
866 subquery = schema.SubQuery(
867 label="test",
868 search_query="test query",
869 ranking_query="test query",
870 sources=["x"],
871 )
872 items, artifact = pipeline._retrieve_stream(
873 topic="test",
874 subquery=subquery,
875 source="x",
876 config={},
877 depth="quick",
878 date_range=("2026-02-15", "2026-03-17"),
879 runtime=schema.ProviderRuntime(
880 reasoning_provider="mock",
881 planner_model="mock",
882 rerank_model="mock",
883 ),
884 mock=True,
885 rate_limited_sources=rate_limited,
886 rate_limit_lock=lock,
887 )
888 self.assertEqual(items, [])
889 self.assertEqual(artifact, {})
890
891
892 class TestThinSourceRetryPlannedSource(unittest.TestCase):
893 @patch("lib.pipeline._retrieve_stream")
894 def test_retry_includes_planned_source_with_zero_initial_items(self, mock_retrieve):
895 mock_retrieve.return_value = (
896 [
897 {
898 "id": "X100",
899 "text": "OpenClaw funding update from an investor",
900 "url": "https://x.com/example/status/100",
901 "author_handle": "example",
902 "date": "2026-03-15",
903 "engagement": {"likes": 25, "reposts": 4, "replies": 2},
904 "relevance": 0.8,
905 "why_relevant": "retry result",
906 }
907 ],
908 {},
909 )
910
911 plan = schema.QueryPlan(
912 intent="breaking_news",
913 freshness_mode="strict_recent",
914 cluster_mode="story",
915 raw_topic="latest OpenClaw funding updates",
916 subqueries=[
917 schema.SubQuery(
918 label="primary",
919 search_query="latest OpenClaw funding updates",
920 ranking_query="What recent evidence matters for OpenClaw funding?",
921 sources=["x", "reddit"],
922 )
923 ],
924 source_weights={"x": 1.0, "reddit": 1.0},
925 )
926 bundle = schema.RetrievalBundle(
927 items_by_source={
928 "reddit": [
929 _make_source_item("reddit", "r1", "https://reddit.com/1"),
930 _make_source_item("reddit", "r2", "https://reddit.com/2"),
931 _make_source_item("reddit", "r3", "https://reddit.com/3"),
932 ]
933 }
934 )
935
936 pipeline._retry_thin_sources(
937 topic="latest OpenClaw funding updates",
938 bundle=bundle,
939 plan=plan,
940 config={},
941 depth="default",
942 date_range=("2026-02-15", "2026-03-17"),
943 runtime=_make_runtime("bird"),
944 mock=False,
945 rate_limited_sources=set(),
946 rate_limit_lock=threading.Lock(),
947 settings=pipeline.DEPTH_SETTINGS["default"],
948 )
949
950 self.assertEqual(["x"], [call.kwargs["source"] for call in mock_retrieve.call_args_list])
951 self.assertIn("x", bundle.items_by_source)
952 self.assertEqual("https://x.com/example/status/100", bundle.items_by_source["x"][0].url)
953
954
955 class TestPinnedGithubPersonAuthority(unittest.TestCase):
956 @patch("lib.pipeline._retrieve_stream")
957 @patch("lib.pipeline.github.search_github_person", return_value=[])
958 def test_empty_person_result_suppresses_generic_fanout_and_retry(
959 self, mock_person_search, mock_retrieve
960 ):
961 plan = {
962 "intent": "person",
963 "freshness_mode": "balanced_recent",
964 "cluster_mode": "topic",
965 "subqueries": [
966 {
967 "label": "primary",
968 "search_query": "octocat recent activity",
969 "ranking_query": "What has @octocat done on GitHub recently?",
970 "sources": ["github"],
971 }
972 ],
973 "source_weights": {"github": 1.0},
974 }
975
976 report = pipeline.run(
977 topic="octocat",
978 config={"GITHUB_TOKEN": "dummy-token"},
979 depth="default",
980 requested_sources=["github"],
981 mock=False,
982 web_backend="none",
983 external_plan=plan,
984 github_user="octocat",
985 )
986
987 mock_person_search.assert_called_once()
988 mock_retrieve.assert_not_called()
989 self.assertEqual(schema.NO_RESULTS, report.source_status["github"].state)
990 self.assertIn(
991 "Person mode found no activity for @octocat",
992 report.source_status["github"].detail,
993 )
994
995 @patch("lib.pipeline._retrieve_stream")
996 @patch(
997 "lib.pipeline.github.search_github_person",
998 side_effect=RuntimeError("GitHub API unavailable"),
999 )
1000 def test_person_failure_suppresses_generic_fanout_and_retry(
1001 self, mock_person_search, mock_retrieve
1002 ):
1003 plan = {
1004 "intent": "person",
1005 "freshness_mode": "balanced_recent",
1006 "cluster_mode": "topic",
1007 "subqueries": [
1008 {
1009 "label": "primary",
1010 "search_query": "octocat recent activity",
1011 "ranking_query": "What has @octocat done on GitHub recently?",
1012 "sources": ["github"],
1013 }
1014 ],
1015 "source_weights": {"github": 1.0},
1016 }
1017
1018 report = pipeline.run(
1019 topic="octocat",
1020 config={"GITHUB_TOKEN": "dummy-token"},
1021 depth="default",
1022 requested_sources=["github"],
1023 mock=False,
1024 web_backend="none",
1025 external_plan=plan,
1026 github_user="octocat",
1027 )
1028
1029 mock_person_search.assert_called_once()
1030 mock_retrieve.assert_not_called()
1031 self.assertEqual(health.ERROR, report.source_status["github"].state)
1032 self.assertEqual(
1033 "GitHub API unavailable",
1034 report.source_status["github"].detail,
1035 )
1036 self.assertEqual(
1037 "Person-mode failed: GitHub API unavailable",
1038 report.errors_by_source["github"],
1039 )
1040
1041
1042 def _ghostty_enrichment(release_date: str) -> dict:
1043 """GitHub fetch result for ghostty-org/ghostty as _enrich_project_repo
1044 returns it. The newest release object is the 2022 "tip" nightly, so the
1045 adapter's release date sits years outside any report window."""
1046 return {
1047 "info": {
1048 "stars": 52000,
1049 "open_issues": 2900,
1050 "description": "Ghostty is a fast, feature-rich, cross-platform terminal emulator",
1051 "language": "Zig",
1052 },
1053 "readme": "Ghostty is a terminal emulator.",
1054 "releases": [
1055 {"tag": "tip", "name": 'Ghostty Tip ("Nightly")', "date": release_date, "body": ""},
1056 ],
1057 "top_issues": {},
1058 }
1059
1060
1061 class TestPinnedGithubProjectSurvivesDateWindow(unittest.TestCase):
1062 """--github-repo pins a live repo snapshot. Ghostty's newest release object
1063 is dated 2022, and dating the snapshot by it made the report's date filter
1064 drop the pinned repo after "[GitHub] Project-mode returned 1 items",
1065 leaving a false "GitHub: 0 items (no results)" in Source Coverage."""
1066
1067 _PLAN = {
1068 "intent": "product",
1069 "freshness_mode": "balanced_recent",
1070 "cluster_mode": "none",
1071 "subqueries": [
1072 {
1073 "label": "primary",
1074 "search_query": "ghostty terminal",
1075 "ranking_query": "What are people saying about Ghostty terminal?",
1076 "sources": ["github"],
1077 }
1078 ],
1079 "source_weights": {"github": 1.0},
1080 }
1081
1082 def _run(self, release_date: str):
1083 with patch("lib.github._resolve_token", return_value="dummy-token"), patch(
1084 "lib.github._enrich_project_repo",
1085 return_value=_ghostty_enrichment(release_date),
1086 ), patch("lib.pipeline._retrieve_stream", return_value=([], {})):
1087 return pipeline.run(
1088 topic="Ghostty terminal",
1089 config={},
1090 depth="default",
1091 requested_sources=["github"],
1092 mock=False,
1093 web_backend="none",
1094 external_plan=self._PLAN,
1095 github_repos=["ghostty-org/ghostty"],
1096 )
1097
1098 def test_out_of_window_release_still_reaches_report(self):
1099 report = self._run("2022-11-17")
1100
1101 items = report.items_by_source.get("github", [])
1102 self.assertEqual(["https://github.com/ghostty-org/ghostty"], [i.url for i in items])
1103 self.assertNotEqual(schema.NO_RESULTS, report.source_status["github"].state)
1104 # The live snapshot is dated to the window end, not the stale release;
1105 # the release date stays visible in the snippet text.
1106 self.assertEqual(report.range_to, items[0].published_at)
1107
1108 def test_in_window_release_keeps_release_date(self):
1109 """Control: an in-window release still dates the item, so the date is
1110 the only variable the out-of-window case exercises."""
1111 today = datetime.now(timezone.utc).date().isoformat()
1112 report = self._run(today)
1113
1114 items = report.items_by_source.get("github", [])
1115 self.assertEqual(["https://github.com/ghostty-org/ghostty"], [i.url for i in items])
1116 self.assertEqual(today, items[0].published_at)
1117
1118
1119 class TestTrustpilotNeverRetriedAsThin(unittest.TestCase):
1120 @patch("lib.pipeline._retrieve_stream")
1121 def test_trustpilot_excluded_from_thin_source_retry(self, mock_retrieve):
1122 """Trustpilot returns at most one item by design, so the '<3 items'
1123 thinness rule must never re-fetch it: a retry would bypass
1124 MAX_SOURCE_FETCHES and re-resolve without the caller's
1125 --trustpilot-domain (a lookalike-misattribution path)."""
1126 mock_retrieve.return_value = ([], {})
1127
1128 plan = schema.QueryPlan(
1129 intent="product",
1130 freshness_mode="balanced_recent",
1131 cluster_mode="none",
1132 raw_topic="ThriftBooks",
1133 subqueries=[
1134 schema.SubQuery(
1135 label="primary",
1136 search_query="thriftbooks",
1137 ranking_query="What matters for ThriftBooks?",
1138 sources=["trustpilot", "x"],
1139 )
1140 ],
1141 source_weights={"trustpilot": 1.0, "x": 1.0},
1142 )
1143 bundle = schema.RetrievalBundle(
1144 items_by_source={
1145 # one successful trustpilot item -- its normal success state,
1146 # yet still "<3" and thus retry-eligible without the exclusion
1147 "trustpilot": [
1148 _make_source_item("trustpilot", "tp1", "https://www.trustpilot.com/review/x.com"),
1149 ],
1150 }
1151 )
1152
1153 pipeline._retry_thin_sources(
1154 topic="ThriftBooks",
1155 bundle=bundle,
1156 plan=plan,
1157 config={},
1158 depth="default",
1159 date_range=("2026-06-04", "2026-07-04"),
1160 runtime=_make_runtime("bird"),
1161 mock=False,
1162 rate_limited_sources=set(),
1163 rate_limit_lock=threading.Lock(),
1164 settings=pipeline.DEPTH_SETTINGS["default"],
1165 )
1166
1167 retried = [call.kwargs["source"] for call in mock_retrieve.call_args_list]
1168 self.assertNotIn("trustpilot", retried)
1169 self.assertIn("x", retried) # other thin sources still retry
1170
1171
1172 def _make_runtime(x_backend="bird"):
1173 return schema.ProviderRuntime(
1174 reasoning_provider="mock",
1175 planner_model="mock",
1176 rerank_model="mock",
1177 x_search_backend=x_backend,
1178 )
1179
1180
1181 def _make_plan(topic="test topic"):
1182 return schema.QueryPlan(
1183 intent="exploration",
1184 freshness_mode="balanced_recent",
1185 cluster_mode="topic",
1186 raw_topic=topic,
1187 subqueries=[
1188 schema.SubQuery(
1189 label="primary",
1190 search_query=topic,
1191 ranking_query=f"What recent evidence matters for {topic}?",
1192 sources=["x", "reddit"],
1193 )
1194 ],
1195 source_weights={"x": 1.0, "reddit": 1.0},
1196 )
1197
1198
1199 def _make_source_item(source, item_id, url, author=None, body="", container=None, metadata=None):
1200 return schema.SourceItem(
1201 item_id=item_id,
1202 source=source,
1203 title=f"Item {item_id}",
1204 body=body,
1205 url=url,
1206 author=author,
1207 container=container,
1208 metadata=metadata or {},
1209 )
1210
1211
1212 class TestXBackendChainAndFailover(unittest.TestCase):
1213 """One X source, an ordered backend chain with failover; never parallel."""
1214
1215 @patch("lib.xurl_x.is_available", return_value=False)
1216 def test_chain_orders_by_priority(self, _xurl):
1217 from lib import env
1218 chain = env.x_backend_chain({"XAI_API_KEY": "k", "XQUIK_API_KEY": "q"})
1219 self.assertEqual(["xai", "xquik"], chain) # xai primary, xquik backup
1220
1221 @patch("lib.xurl_x.is_available", return_value=False)
1222 def test_pin_forces_single_backend(self, _xurl):
1223 from lib import env
1224 chain = env.x_backend_chain(
1225 {"XAI_API_KEY": "k", "XQUIK_API_KEY": "q", "LAST30DAYS_X_BACKEND": "xquik"}
1226 )
1227 self.assertEqual(["xquik"], chain) # pin = no failover
1228
1229 @patch("lib.xurl_x.is_available", return_value=False)
1230 def test_chain_empty_when_nothing_configured(self, _xurl):
1231 from lib import env
1232 self.assertEqual([], env.x_backend_chain({}))
1233
1234 @patch("lib.env.x_backend_chain", return_value=["bird", "xquik"])
1235 def test_failover_to_next_backend_on_empty(self, _chain):
1236 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1237
1238 def fake_fetch(backend, *a, **k):
1239 if backend == "xquik":
1240 return ([{"id": "XQ1", "url": "https://x.com/a/status/1"}], "")
1241 return ([], "") # bird returns nothing
1242
1243 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1244 items, _ = pipeline._retrieve_stream(
1245 topic="q", subquery=sq, source="x", config={}, depth="default",
1246 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1247 )
1248 self.assertEqual(1, len(items))
1249 self.assertEqual("XQ1", items[0]["id"])
1250
1251 @patch("lib.env.x_backend_chain", return_value=["xquik"])
1252 def test_sole_backend_error_raises_honestly(self, _chain):
1253 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1254 with patch("lib.pipeline._fetch_x_backend", return_value=([], "Xquik key unpaid (402)")):
1255 with self.assertRaises(RuntimeError):
1256 pipeline._retrieve_stream(
1257 topic="q", subquery=sq, source="x", config={}, depth="default",
1258 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1259 )
1260
1261 def test_xquik_is_not_a_separate_source(self):
1262 # xquik registers only as a backend of "x", never its own source.
1263 avail = pipeline.available_sources({"XQUIK_API_KEY": "k"})
1264 self.assertIn("x", avail)
1265 self.assertNotIn("xquik", avail)
1266
1267
1268 class TestMixedResultRevocation(unittest.TestCase):
1269 """Mixed-result revocation: when grok returns items AND an error, preserve both."""
1270
1271 @patch("lib.env.x_backend_chain", return_value=["grok"])
1272 def test_items_with_auth_error_surfaces_error(self, _chain):
1273 """Grok returns some items but then auth is revoked → error is surfaced."""
1274 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1275
1276 def fake_fetch(backend, *a, **k):
1277 if backend == "grok":
1278 # Mixed result: got some items, but also hit auth revocation
1279 return (
1280 [{"id": "G1", "url": "https://x.com/a/status/1"}],
1281 "grok: grok session expired or was revoked",
1282 )
1283 return ([], "")
1284
1285 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1286 items, artifact = pipeline._retrieve_stream(
1287 topic="q", subquery=sq, source="x", config={}, depth="default",
1288 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1289 )
1290 self.assertEqual(1, len(items))
1291 # The artifact should have _source_outcome with the error info
1292 outcome = artifact.get("_source_outcome", {})
1293 self.assertIn("grok session expired", outcome.get("detail", "").lower())
1294 # State should be AUTH_FAILED since the error contains auth markers
1295 self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
1296
1297 @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
1298 def test_fallback_after_auth_failed_keeps_auth_failed_state(self, _chain):
1299 """Grok auth fails → bird succeeds → state is AUTH_FAILED (not OK).
1300
1301 The user needs re-login guidance for grok even though fallback served items.
1302 """
1303 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1304
1305 def fake_fetch(backend, *a, **k):
1306 if backend == "grok":
1307 return ([], "grok: grok session expired or was revoked")
1308 if backend == "bird":
1309 return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
1310 return ([], "")
1311
1312 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1313 items, artifact = pipeline._retrieve_stream(
1314 topic="q", subquery=sq, source="x", config={}, depth="default",
1315 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1316 )
1317 self.assertEqual(1, len(items))
1318 outcome = artifact.get("_source_outcome", {})
1319 # State should be AUTH_FAILED so user gets re-login guidance
1320 self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
1321 self.assertIn("re-login", outcome.get("detail", "").lower())
1322
1323 @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
1324 def test_fallback_after_non_auth_error_is_ok(self, _chain):
1325 """Grok fails with non-auth error → bird succeeds → state is OK."""
1326 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1327
1328 def fake_fetch(backend, *a, **k):
1329 if backend == "grok":
1330 return ([], "grok: network timeout")
1331 if backend == "bird":
1332 return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
1333 return ([], "")
1334
1335 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1336 items, artifact = pipeline._retrieve_stream(
1337 topic="q", subquery=sq, source="x", config={}, depth="default",
1338 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1339 )
1340 self.assertEqual(1, len(items))
1341 self.assertNotIn("_source_outcome", artifact)
1342 self.assertIn("grok: network timeout", artifact["_source_outcome_detail"])
1343 self.assertEqual(health.TIMEOUT, artifact["_source_outcome_detail_state"])
1344
1345 @patch("lib.env.x_backend_chain", return_value=["bird", "grok"])
1346 def test_prior_non_auth_then_current_auth_fail_yields_auth_failed(self, _chain):
1347 """Bird non-auth fail → Grok items + revocation → AUTH_FAILED, items kept.
1348
1349 If an earlier backend fails for a non-auth reason and the current backend
1350 returns items plus an auth revocation error, the outcome must be AUTH_FAILED
1351 (not OK) so the user gets re-login guidance.
1352 """
1353 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1354
1355 def fake_fetch(backend, *a, **k):
1356 if backend == "bird":
1357 # Bird fails with a non-auth error
1358 return ([], "bird: network timeout")
1359 if backend == "grok":
1360 # Grok returns items but also signals auth revocation
1361 return (
1362 [{"id": "G1", "url": "https://x.com/a/status/1"}],
1363 "grok: grok session expired or was revoked",
1364 )
1365 return ([], "")
1366
1367 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1368 items, artifact = pipeline._retrieve_stream(
1369 topic="q", subquery=sq, source="x", config={}, depth="default",
1370 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1371 )
1372 # Items should be preserved
1373 self.assertEqual(1, len(items))
1374 outcome = artifact.get("_source_outcome", {})
1375 # State must be AUTH_FAILED, not OK
1376 self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
1377 # Re-login guidance must be present
1378 self.assertIn("re-login", outcome.get("detail", "").lower())
1379
1380 @patch("lib.env.x_backend_chain", return_value=["grok", "bird"])
1381 def test_not_logged_in_triggers_auth_failed_fallback(self, _chain):
1382 """Grok 'not logged in' → bird fallback → AUTH_FAILED state preserved.
1383
1384 The 'not logged in' message from Grok is a recognized revocation marker.
1385 If Grok fails with this message and bird fallback succeeds, the outcome
1386 must be AUTH_FAILED so the user gets re-login guidance.
1387 """
1388 sq = schema.SubQuery(label="primary", search_query="q", ranking_query="q?", sources=["x"])
1389
1390 def fake_fetch(backend, *a, **k):
1391 if backend == "grok":
1392 # Grok fails with 'not logged in' error
1393 return ([], "grok: not logged in")
1394 if backend == "bird":
1395 return ([{"id": "B1", "url": "https://x.com/a/status/1"}], "")
1396 return ([], "")
1397
1398 with patch("lib.pipeline._fetch_x_backend", side_effect=fake_fetch):
1399 items, artifact = pipeline._retrieve_stream(
1400 topic="q", subquery=sq, source="x", config={}, depth="default",
1401 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None), mock=False,
1402 )
1403 self.assertEqual(1, len(items))
1404 outcome = artifact.get("_source_outcome", {})
1405 # State must be AUTH_FAILED because 'not logged in' is an auth marker
1406 self.assertEqual(schema.AUTH_FAILED, outcome.get("state"))
1407 self.assertIn("re-login", outcome.get("detail", "").lower())
1408
1409
1410 class TestRetrievalBundleAuthPreservation(unittest.TestCase):
1411 """AUTH_FAILED state must be preserved through add_items.
1412
1413 When a lane records AUTH_FAILED before items are added, the state
1414 must not be downgraded to PARTIAL by subsequent add_items calls.
1415 """
1416
1417 def test_add_items_preserves_auth_failed_state(self):
1418 """add_items should preserve AUTH_FAILED state, not downgrade to PARTIAL."""
1419 bundle = schema.RetrievalBundle()
1420 bundle.mark_attempted("x")
1421 # First: record auth failure (no items yet)
1422 bundle.record_failure("x", schema.AUTH_FAILED, "grok session expired", attempted=True)
1423 # At this point, state should be AUTH_FAILED
1424 self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
1425
1426 # Now add items
1427 items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
1428 bundle.add_items("primary", "x", items)
1429
1430 # State must still be AUTH_FAILED, not PARTIAL
1431 self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
1432 # Detail should be preserved
1433 self.assertEqual("grok session expired", bundle.source_status["x"].detail)
1434 # Items should be recorded
1435 self.assertEqual(1, len(bundle.items_by_source["x"]))
1436
1437 def test_add_items_keeps_partial_for_non_auth_failures(self):
1438 """For non-auth failures, add_items should still produce PARTIAL."""
1439 bundle = schema.RetrievalBundle()
1440 bundle.mark_attempted("x")
1441 # Record a non-auth failure
1442 bundle.record_failure("x", health.TIMEOUT, "request timed out", attempted=True)
1443 self.assertEqual(health.TIMEOUT, bundle.source_status["x"].state)
1444
1445 # Add items
1446 items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
1447 bundle.add_items("primary", "x", items)
1448
1449 # State should become PARTIAL (not TIMEOUT)
1450 self.assertEqual(schema.PARTIAL, bundle.source_status["x"].state)
1451 # Detail should be preserved
1452 self.assertEqual("request timed out", bundle.source_status["x"].detail)
1453
1454 def test_record_failure_preserves_auth_failed_when_items_exist(self):
1455 """record_failure should preserve AUTH_FAILED even when items already exist.
1456
1457 When Phase 1 has already collected X posts and a supplemental Grok lane
1458 reports revocation, record_failure must not convert AUTH_FAILED to PARTIAL.
1459 """
1460 bundle = schema.RetrievalBundle()
1461 bundle.mark_attempted("x")
1462
1463 # Phase 1 already collected items
1464 phase1_items = [_make_source_item("x", "X1", "https://x.com/a/status/1")]
1465 bundle.add_items("primary", "x", phase1_items)
1466 self.assertEqual(health.OK, bundle.source_status["x"].state)
1467
1468 # Supplemental lane reports auth failure
1469 bundle.record_failure("x", schema.AUTH_FAILED, "grok session revoked", attempted=True)
1470
1471 # State must be AUTH_FAILED, not PARTIAL
1472 self.assertEqual(schema.AUTH_FAILED, bundle.source_status["x"].state)
1473 # Detail should be set
1474 self.assertEqual("grok session revoked", bundle.source_status["x"].detail)
1475 # Items should still be there
1476 self.assertEqual(1, len(bundle.items_by_source["x"]))
1477
1478
1479 class TestSupplementalSearches(unittest.TestCase):
1480 """R1: Phase 2 entity drilling should be wired into the pipeline."""
1481
1482 def test_run_supplemental_searches_exists(self):
1483 """_run_supplemental_searches must be a callable in pipeline module."""
1484 self.assertTrue(
1485 hasattr(pipeline, "_run_supplemental_searches"),
1486 "_run_supplemental_searches function not found in pipeline module",
1487 )
1488 self.assertTrue(callable(pipeline._run_supplemental_searches))
1489
1490 @patch("lib.bird_x.search_handles")
1491 @patch("lib.entity_extract.extract_entities")
1492 def test_entity_extract_called_after_phase1(self, mock_extract, mock_handles):
1493 """Phase 2 should call entity_extract on Phase 1 X results, then search_handles."""
1494 mock_extract.return_value = {"x_handles": ["analyst1", "reporter2"], "x_hashtags": [], "reddit_subreddits": []}
1495 mock_handles.return_value = [
1496 {
1497 "id": "supp1",
1498 "text": "Supplemental tweet from analyst1",
1499 "url": "https://x.com/analyst1/status/999",
1500 "author_handle": "analyst1",
1501 "date": "2026-03-15",
1502 "engagement": {"likes": 50},
1503 "relevance": 0.8,
1504 "why_relevant": "direct handle search",
1505 }
1506 ]
1507
1508 bundle = schema.RetrievalBundle()
1509 # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITS
1510 bundle.items_by_source["x"] = [
1511 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
1512 _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),
1513 _make_source_item("x", "X3", "https://x.com/reporter2/status/3", author="reporter2", body="AI safety report"),
1514 _make_source_item("x", "X4", "https://x.com/reporter2/status/4", author="reporter2", body="AI safety news"),
1515 ]
1516
1517 plan = _make_plan("AI safety")
1518 config = {}
1519
1520 pipeline._run_supplemental_searches(
1521 topic="AI safety",
1522 bundle=bundle,
1523 plan=plan,
1524 config=config,
1525 depth="default",
1526 date_range=("2026-02-15", "2026-03-17"),
1527 runtime=_make_runtime("bird"),
1528 mock=False,
1529 rate_limited_sources=set(),
1530 rate_limit_lock=threading.Lock(),
1531 )
1532
1533 mock_extract.assert_called_once()
1534 mock_handles.assert_called_once()
1535 # Supplemental items should be merged into bundle
1536 x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
1537 self.assertIn("https://x.com/analyst1/status/999", x_urls)
1538
1539 @patch("lib.env.x_backend_chain", return_value=["xquik"])
1540 @patch("lib.xquik.search_xquik", return_value={"items": []})
1541 def test_x_topic_lane_uses_raw_topic_via_xquik(self, mock_search, _chain):
1542 """The X topic lane uses raw_topic (like Reddit/YouTube), not the
1543 planner's search_query. This avoids phrase-quoting issues like "Rome Italy"
1544 returning off-topic results. Disambiguation lives in ranking_query."""
1545 anchored = schema.SubQuery(
1546 label="primary", search_query="kevin rose digg founder",
1547 ranking_query="What has Kevin Rose, founder of Digg, been doing?",
1548 sources=["x"],
1549 )
1550 pipeline._retrieve_stream(
1551 topic="kevin rose digg founder", subquery=anchored, source="x",
1552 config={"XQUIK_API_KEY": "k"}, depth="default",
1553 date_range=("2026-05-19", "2026-06-18"), runtime=_make_runtime(None),
1554 mock=False, raw_topic="kevin rose",
1555 )
1556 mock_search.assert_called_once()
1557 # X now uses raw_topic, not search_query (like Reddit/YouTube)
1558 self.assertEqual("kevin rose", mock_search.call_args[0][0])
1559
1560 @patch("lib.env.get_xquik_token", return_value="k")
1561 @patch("lib.env.x_backend_chain", return_value=["xquik"])
1562 @patch("lib.xquik.search_mentions", return_value=[])
1563 @patch("lib.xquik.search_handles")
1564 @patch("lib.entity_extract.extract_entities")
1565 def test_handle_lanes_route_to_xquik_when_primary(
1566 self, mock_extract, mock_xq_handles, mock_xq_mentions, *_patches
1567 ):
1568 """When xquik is the primary X backend, the FROM/ABOUT handle lanes run
1569 via xquik and items land under the single 'x' slug."""
1570 mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
1571 mock_xq_handles.return_value = [{
1572 "id": "XF1", "text": "from analyst1", "url": "https://x.com/analyst1/status/777",
1573 "author_handle": "analyst1", "date": "2026-03-15",
1574 "engagement": {"likes": 30}, "relevance": 0.8, "why_relevant": "",
1575 }]
1576
1577 bundle = schema.RetrievalBundle()
1578 # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITS
1579 bundle.items_by_source["x"] = [
1580 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
1581 _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),
1582 ]
1583
1584 pipeline._run_supplemental_searches(
1585 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
1586 depth="default", date_range=("2026-02-15", "2026-03-17"),
1587 runtime=_make_runtime(None), mock=False,
1588 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
1589 )
1590
1591 mock_xq_handles.assert_called_once()
1592 x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
1593 self.assertIn("https://x.com/analyst1/status/777", x_urls)
1594 # There is no separate 'xquik' source — everything is under 'x'.
1595 self.assertNotIn("xquik", bundle.items_by_source)
1596
1597 @patch("lib.env.get_xquik_token", return_value="k")
1598 @patch("lib.env.x_backend_chain", return_value=["xai", "xquik"])
1599 @patch("lib.xquik.search_mentions", return_value=[])
1600 @patch("lib.xquik.search_handles")
1601 @patch("lib.entity_extract.extract_entities")
1602 def test_handle_lanes_use_xquik_when_xai_is_primary(
1603 self, mock_extract, mock_xq_handles, *_patches
1604 ):
1605 """When xAI is the topic primary but xquik is in the chain, the
1606 supplemental handle lanes still run via xquik (first handle-capable
1607 backend) rather than being skipped."""
1608 mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
1609 mock_xq_handles.return_value = [{
1610 "id": "XF1", "text": "from analyst1", "url": "https://x.com/analyst1/status/888",
1611 "author_handle": "analyst1", "date": "2026-03-15",
1612 "engagement": {"likes": 5}, "relevance": 0.8, "why_relevant": "",
1613 }]
1614 bundle = schema.RetrievalBundle()
1615 # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITS
1616 bundle.items_by_source["x"] = [
1617 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1", body="AI safety analysis"),
1618 _make_source_item("x", "X2", "https://x.com/analyst1/status/2", author="analyst1", body="AI safety research"),
1619 ]
1620 pipeline._run_supplemental_searches(
1621 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
1622 depth="default", date_range=("2026-02-15", "2026-03-17"),
1623 runtime=_make_runtime("xai"), mock=False,
1624 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
1625 )
1626 mock_xq_handles.assert_called_once()
1627 x_urls = {item.url for item in bundle.items_by_source.get("x", [])}
1628 self.assertIn("https://x.com/analyst1/status/888", x_urls)
1629
1630 @patch("lib.env.get_xquik_token", return_value="k")
1631 @patch("lib.env.x_backend_chain", return_value=["xquik"])
1632 @patch("lib.xquik._execute_search", return_value=([], "Xquik key unpaid: payment required (402)"))
1633 @patch("lib.entity_extract.extract_entities")
1634 def test_xquik_handle_lane_auth_failure_reaches_source_status(
1635 self, mock_extract, _mock_exec, *_patches
1636 ):
1637 """An unpaid xquik key produced an empty FROM lane and no outcome, so
1638 the run reported X as a clean zero and the report stated as fact that
1639 the subject posted nothing."""
1640 mock_extract.return_value = {
1641 "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],
1642 }
1643 bundle = schema.RetrievalBundle()
1644 bundle.items_by_source["x"] = [
1645 _make_source_item("x", "X1", "https://x.com/analyst1/status/1",
1646 author="analyst1", body="AI safety analysis"),
1647 _make_source_item("x", "X2", "https://x.com/analyst1/status/2",
1648 author="analyst1", body="AI safety research"),
1649 ]
1650
1651 pipeline._run_supplemental_searches(
1652 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
1653 depth="default", date_range=("2026-02-15", "2026-03-17"),
1654 runtime=_make_runtime(None), mock=False,
1655 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
1656 )
1657
1658 outcome = bundle.source_status.get("x")
1659 self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")
1660 self.assertEqual(schema.AUTH_FAILED, outcome.state)
1661 self.assertTrue(outcome.attempted)
1662
1663 @patch("lib.env.get_xquik_token", return_value="k")
1664 @patch("lib.env.x_backend_chain", return_value=["xquik"])
1665 @patch("lib.xquik.http.get")
1666 @patch("lib.entity_extract.extract_entities")
1667 def test_xquik_handle_lane_rate_limit_reaches_source_status(
1668 self, mock_extract, mock_get, *_patches
1669 ):
1670 """A 429 is not an auth failure, so it took the non-fatal path inside
1671 _execute_search and reported nothing at all: the lane came back empty
1672 with no outcome and the run called it genuine silence."""
1673 mock_extract.return_value = {
1674 "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],
1675 }
1676 mock_get.side_effect = http.HTTPError(
1677 "HTTP 429: Too Many Requests", status_code=429,
1678 )
1679 bundle = schema.RetrievalBundle()
1680 bundle.items_by_source["x"] = [
1681 _make_source_item("x", "X1", "https://x.com/analyst1/status/1",
1682 author="analyst1", body="AI safety analysis"),
1683 _make_source_item("x", "X2", "https://x.com/analyst1/status/2",
1684 author="analyst1", body="AI safety research"),
1685 ]
1686
1687 pipeline._run_supplemental_searches(
1688 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
1689 depth="default", date_range=("2026-02-15", "2026-03-17"),
1690 runtime=_make_runtime(None), mock=False,
1691 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
1692 )
1693
1694 outcome = bundle.source_status.get("x")
1695 self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")
1696 # PARTIAL rather than AUTH_FAILED: a 429 is transient, and Phase 1
1697 # items survived, so record_failure keeps them and marks the source.
1698 self.assertEqual(schema.PARTIAL, outcome.state)
1699 self.assertIn("429", outcome.detail)
1700
1701 @patch("lib.env.x_backend_chain", return_value=["bird"])
1702 @patch("lib.bird_x.search_mentions", return_value=[])
1703 @patch("lib.bird_x.subproc.run_with_timeout")
1704 @patch("lib.entity_extract.extract_entities")
1705 def test_bird_handle_lane_transport_failure_reaches_source_status(
1706 self, mock_extract, mock_run, *_patches
1707 ):
1708 """Same defect on the bird path: a bird-search timeout returned no
1709 items and no outcome, so an unreachable lane looked like silence."""
1710 mock_extract.return_value = {
1711 "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],
1712 }
1713 mock_run.side_effect = subproc.SubprocTimeout("timed out")
1714 bundle = schema.RetrievalBundle()
1715 bundle.items_by_source["x"] = [
1716 _make_source_item("x", "X1", "https://x.com/analyst1/status/1",
1717 author="analyst1", body="AI safety analysis"),
1718 _make_source_item("x", "X2", "https://x.com/analyst1/status/2",
1719 author="analyst1", body="AI safety research"),
1720 ]
1721
1722 pipeline._run_supplemental_searches(
1723 topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},
1724 depth="default", date_range=("2026-02-15", "2026-03-17"),
1725 runtime=_make_runtime(None), mock=False,
1726 rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
1727 )
1728
1729 outcome = bundle.source_status.get("x")
1730 self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")
1731 # PARTIAL, not UNREACHABLE: X delivered Phase 1 items and only the
1732 # Phase 2 handle lane failed, which is what record_failure encodes.
1733 self.assertEqual(schema.PARTIAL, outcome.state)
1734 self.assertIn("timed out", outcome.detail)
1735 self.assertIn("@analyst1", outcome.detail)
1736
1737 @patch("lib.bird_x.search_mentions", return_value=[])
1738 @patch("lib.bird_x.search_handles")
1739 @patch("lib.entity_extract.extract_entities")
1740 def test_supplemental_items_deduplicated_by_url(self, mock_extract, mock_handles, mock_mentions):
1741 """Supplemental items with same URL as Phase 1 should not be duplicated."""
1742 mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
1743 mock_handles.return_value = [
1744 {
1745 "id": "dup1",
1746 "text": "AI safety technical analysis from the author",
1747 "url": "https://x.com/analyst1/status/1",
1748 "author_handle": "analyst1",
1749 "date": "2026-03-15",
1750 "engagement": {"likes": 50},
1751 "relevance": 0.8,
1752 "why_relevant": "duplicate",
1753 },
1754 {
1755 "id": "unique2", "text": "New AI safety benchmark results",
1756 "url": "https://x.com/analyst1/status/2",
1757 "author_handle": "analyst1", "date": "2026-03-16",
1758 "engagement": {"likes": 20}, "relevance": 0.8,
1759 },
1760 ]
1761
1762 bundle = schema.RetrievalBundle()
1763 original = _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1")
1764 bundle.items_by_source["x"] = [original]
1765
1766 plan = _make_plan("AI safety")
1767
1768 pipeline._run_supplemental_searches(
1769 topic="AI safety",
1770 bundle=bundle,
1771 plan=plan,
1772 config={},
1773 depth="default",
1774 date_range=("2026-02-15", "2026-03-17"),
1775 runtime=_make_runtime("bird"),
1776 mock=False,
1777 rate_limited_sources=set(),
1778 rate_limit_lock=threading.Lock(),
1779 x_handle="analyst1",
1780 )
1781
1782 mock_handles.assert_called_once()
1783 mock_mentions.assert_called_once()
1784 x_items = bundle.items_by_source.get("x", [])
1785 urls = [item.url for item in x_items]
1786 self.assertCountEqual(["https://x.com/analyst1/status/1",
1787 "https://x.com/analyst1/status/2"], urls)
1788 self.assertIs(original, x_items[0])
1789
1790 @patch("lib.bird_x.search_mentions")
1791 @patch("lib.bird_x.search_handles")
1792 @patch("lib.entity_extract.extract_entities")
1793 def test_from_lane_uses_raised_cap_mention_lane_modest(self, mock_extract, mock_handles, mock_mentions):
1794 """U4: the FROM lane (subject's own timeline) uses the raised per-handle
1795 cap; the mention lane stays modest."""
1796 mock_extract.return_value = {"x_handles": ["subject1"], "x_hashtags": [], "reddit_subreddits": []}
1797 mock_handles.return_value = []
1798 mock_mentions.return_value = []
1799 bundle = schema.RetrievalBundle()
1800 # Handles need ≥2 on-topic posts to be promotable per x_judge.MIN_ON_TOPIC_HITS
1801 bundle.items_by_source["x"] = [
1802 _make_source_item("x", "X1", "https://x.com/subject1/status/1", author="subject1", body="subject1 discussion"),
1803 _make_source_item("x", "X2", "https://x.com/subject1/status/2", author="subject1", body="subject1 update"),
1804 ]
1805 pipeline._run_supplemental_searches(
1806 topic="subject1",
1807 bundle=bundle,
1808 plan=_make_plan("subject1"),
1809 config={},
1810 depth="default",
1811 date_range=("2026-02-15", "2026-03-17"),
1812 runtime=_make_runtime("bird"),
1813 mock=False,
1814 rate_limited_sources=set(),
1815 rate_limit_lock=threading.Lock(),
1816 )
1817 from_call = mock_handles.call_args_list[0]
1818 self.assertEqual(pipeline.FROM_LANE_COUNT_PER, from_call.kwargs.get("count_per"))
1819 self.assertEqual(pipeline.MENTION_LANE_COUNT_PER, mock_mentions.call_args.kwargs.get("count_per"))
1820
1821 def _assert_phase2_guard(self, **blocked):
1822 for allowed in (False, True):
1823 with self.subTest(allowed=allowed):
1824 bundle = schema.RetrievalBundle()
1825 bundle.items_by_source["x"] = [
1826 _make_source_item("x", "X1", "https://x.com/subject1/status/1", author="subject1"),
1827 ]
1828 options = dict(depth="default", mock=False, rate_limited_sources=set(), backend="bird")
1829 if not allowed:
1830 options.update(blocked)
1831 backend = options.pop("backend")
1832 with patch("lib.env.x_backend_chain", return_value=[]), patch(
1833 "lib.entity_extract.extract_entities",
1834 return_value={"x_handles": [], "x_hashtags": [], "reddit_subreddits": []},
1835 ), patch("lib.bird_x.search_handles", return_value=[{
1836 "id": "guard-control", "text": "subject1 test update",
1837 "url": "https://x.com/subject1/status/2", "author_handle": "subject1",
1838 "date": "2026-03-15", "engagement": {"likes": 12}, "relevance": 1.0,
1839 }]) as handles, patch("lib.bird_x.search_mentions", return_value=[]) as mentions:
1840 pipeline._run_supplemental_searches(
1841 topic="subject1", bundle=bundle, plan=_make_plan("subject1"),
1842 config={}, date_range=("2026-02-15", "2026-03-17"),
1843 runtime=_make_runtime(backend), rate_limit_lock=threading.Lock(),
1844 x_handle="subject1", **options,
1845 )
1846 if allowed:
1847 self.assertEqual(handles.call_count, 1)
1848 self.assertEqual(handles.call_args.args, (["subject1"], "subject1", "2026-02-15"))
1849 self.assertEqual(mentions.call_count, 1)
1850 self.assertEqual(
1851 [i.url for i in bundle.items_by_source["x"]],
1852 ["https://x.com/subject1/status/1", "https://x.com/subject1/status/2"],
1853 )
1854 else:
1855 handles.assert_not_called()
1856 mentions.assert_not_called()
1857 self.assertEqual([i.item_id for i in bundle.items_by_source["x"]], ["X1"])
1858
1859 def test_phase2_skipped_in_quick_mode(self):
1860 self._assert_phase2_guard(depth="quick")
1861
1862 def test_phase2_skipped_in_mock_mode(self):
1863 self._assert_phase2_guard(mock=True)
1864
1865 def test_phase2_skipped_when_x_rate_limited(self):
1866 self._assert_phase2_guard(rate_limited_sources={"x"})
1867
1868 def test_phase2_skipped_when_backend_has_no_handle_support(self):
1869 self._assert_phase2_guard(backend="xai")
1870
1871
1872 class TestThinSourceRetry(unittest.TestCase):
1873 """R2: Dynamic query refinement on thin results."""
1874
1875 def test_retry_thin_sources_exists(self):
1876 """_retry_thin_sources must be a callable in pipeline module."""
1877 self.assertTrue(
1878 hasattr(pipeline, "_retry_thin_sources"),
1879 "_retry_thin_sources function not found in pipeline module",
1880 )
1881 self.assertTrue(callable(pipeline._retry_thin_sources))
1882
1883 @patch("lib.pipeline._retrieve_stream")
1884 def test_thin_source_retried_with_core_subject(self, mock_retrieve):
1885 """Sources with < 3 items and no errors should be retried."""
1886 mock_retrieve.return_value = (
1887 [
1888 {
1889 "id": "retry1",
1890 "title": "Retry result",
1891 "url": "https://reddit.com/r/test/2",
1892 "subreddit": "test",
1893 "date": "2026-03-15",
1894 "engagement": {"score": 10},
1895 "selftext": "Retry content",
1896 "relevance": 0.7,
1897 "why_relevant": "retry",
1898 }
1899 ],
1900 {},
1901 )
1902
1903 bundle = schema.RetrievalBundle()
1904 # Only 1 reddit item (thin)
1905 bundle.items_by_source["reddit"] = [
1906 _make_source_item("reddit", "R1", "https://reddit.com/r/test/1", container="test"),
1907 ]
1908 # 5 X items (not thin)
1909 bundle.items_by_source["x"] = [
1910 _make_source_item("x", f"X{i}", f"https://x.com/a/{i}") for i in range(5)
1911 ]
1912
1913 plan = _make_plan("advanced AI safety techniques")
1914 settings = pipeline.DEPTH_SETTINGS["default"]
1915
1916 pipeline._retry_thin_sources(
1917 topic="advanced AI safety techniques",
1918 bundle=bundle,
1919 plan=plan,
1920 config={},
1921 depth="default",
1922 date_range=("2026-02-15", "2026-03-17"),
1923 runtime=_make_runtime(),
1924 mock=False,
1925 rate_limited_sources=set(),
1926 rate_limit_lock=threading.Lock(),
1927 settings=settings,
1928 )
1929
1930 # _retrieve_stream should have been called for reddit (thin source)
1931 mock_retrieve.assert_called()
1932 call_sources = [c.kwargs.get("source") for c in mock_retrieve.call_args_list]
1933 self.assertIn("reddit", call_sources)
1934 # X should NOT have been retried
1935 self.assertNotIn("x", call_sources)
1936 mock_retrieve.assert_called_once()
1937 retry = mock_retrieve.call_args.kwargs["subquery"]
1938 self.assertEqual(retry.search_query, "advanced ai safety")
1939 self.assertEqual(
1940 retry.ranking_query,
1941 "What recent evidence from the last 30 days matters for advanced ai safety?",
1942 )
1943 self.assertEqual(retry.sources, ["reddit"])
1944 self.assertEqual(
1945 [i.url for i in bundle.items_by_source["reddit"]],
1946 ["https://reddit.com/r/test/1", "https://reddit.com/r/test/2"],
1947 )
1948
1949 def test_sources_with_enough_items_not_retried(self):
1950 """Sources with >= 3 items should not be retried."""
1951 bundle = schema.RetrievalBundle()
1952 bundle.items_by_source["reddit"] = [
1953 _make_source_item("reddit", f"R{i}", f"https://reddit.com/r/test/{i}") for i in range(5)
1954 ]
1955 bundle.items_by_source["x"] = [
1956 _make_source_item("x", f"X{i}", f"https://x.com/a/{i}") for i in range(5)
1957 ]
1958
1959 plan = _make_plan("AI safety")
1960 settings = pipeline.DEPTH_SETTINGS["default"]
1961
1962 with patch("lib.pipeline._retrieve_stream") as mock_retrieve:
1963 pipeline._retry_thin_sources(
1964 topic="AI safety",
1965 bundle=bundle,
1966 plan=plan,
1967 config={},
1968 depth="default",
1969 date_range=("2026-02-15", "2026-03-17"),
1970 runtime=_make_runtime(),
1971 mock=False,
1972 rate_limited_sources=set(),
1973 rate_limit_lock=threading.Lock(),
1974 settings=settings,
1975 )
1976 mock_retrieve.assert_not_called()
1977
1978 def test_errored_sources_not_retried(self):
1979 """Sources in errors_by_source should not be retried even if thin.
1980 Non-errored thin sources SHOULD still be retried."""
1981 bundle = schema.RetrievalBundle()
1982 bundle.items_by_source["reddit"] = [
1983 _make_source_item("reddit", "R1", "https://reddit.com/r/test/1"),
1984 ]
1985 bundle.errors_by_source["reddit"] = "API error"
1986
1987 plan = _make_plan("AI safety")
1988 settings = pipeline.DEPTH_SETTINGS["default"]
1989
1990 mock_items = [{"id": "X1", "title": "test", "url": "https://x.com/1", "text": "test"}]
1991 with patch("lib.pipeline._retrieve_stream", return_value=(mock_items, {})) as mock_retrieve:
1992 pipeline._retry_thin_sources(
1993 topic="AI safety",
1994 bundle=bundle,
1995 plan=plan,
1996 config={},
1997 depth="default",
1998 date_range=("2026-02-15", "2026-03-17"),
1999 runtime=_make_runtime(),
2000 mock=False,
2001 rate_limited_sources=set(),
2002 rate_limit_lock=threading.Lock(),
2003 settings=settings,
2004 )
2005 # x (non-errored, thin) should be retried; reddit (errored) should not
2006 if mock_retrieve.call_count > 0:
2007 self.assertNotIn("reddit", [c.kwargs.get("source") for c in mock_retrieve.call_args_list])
2008
2009 def test_retry_skipped_in_quick_mode(self):
2010 """_retry_thin_sources should return immediately in quick mode."""
2011 bundle = schema.RetrievalBundle()
2012 bundle.items_by_source["reddit"] = [
2013 _make_source_item("reddit", "R1", "https://reddit.com/r/test/1"),
2014 ]
2015
2016 plan = _make_plan("AI safety")
2017 settings = pipeline.DEPTH_SETTINGS["quick"]
2018
2019 with patch("lib.pipeline._retrieve_stream") as mock_retrieve:
2020 pipeline._retry_thin_sources(
2021 topic="AI safety",
2022 bundle=bundle,
2023 plan=plan,
2024 config={},
2025 depth="quick",
2026 date_range=("2026-02-15", "2026-03-17"),
2027 runtime=_make_runtime(),
2028 mock=False,
2029 rate_limited_sources=set(),
2030 rate_limit_lock=threading.Lock(),
2031 settings=settings,
2032 )
2033 mock_retrieve.assert_not_called()
2034
2035 def test_perplexity_is_not_retried_when_results_are_thin(self):
2036 plan = schema.QueryPlan(
2037 intent="general",
2038 freshness_mode="balanced_recent",
2039 cluster_mode="story",
2040 raw_topic="AI safety",
2041 subqueries=[
2042 schema.SubQuery(
2043 label="primary",
2044 search_query="AI safety",
2045 ranking_query="AI safety",
2046 sources=["perplexity"],
2047 )
2048 ],
2049 source_weights={"perplexity": 1.0},
2050 )
2051 bundle = schema.RetrievalBundle()
2052
2053 with patch("lib.pipeline._retrieve_stream") as mock_retrieve:
2054 pipeline._retry_thin_sources(
2055 topic="AI safety",
2056 bundle=bundle,
2057 plan=plan,
2058 config={},
2059 depth="default",
2060 date_range=("2026-02-15", "2026-03-17"),
2061 runtime=_make_runtime(),
2062 mock=False,
2063 rate_limited_sources=set(),
2064 rate_limit_lock=threading.Lock(),
2065 settings=pipeline.DEPTH_SETTINGS["default"],
2066 )
2067
2068 mock_retrieve.assert_not_called()
2069
2070
2071 class TestErrorCleanup(unittest.TestCase):
2072 def _run_with_failed_stream(self, successful_items):
2073 def retrieve(**kwargs):
2074 if kwargs["subquery"].label == "failed":
2075 raise RuntimeError("fixture lane unavailable")
2076 return successful_items, {}
2077
2078 with patch.object(pipeline, "_retrieve_stream", side_effect=retrieve) as retrieval, \
2079 patch.object(pipeline, "_retry_thin_sources"):
2080 report = pipeline.run(
2081 topic="AI safety", config={}, depth="default", mock=True,
2082 requested_sources=["x"], web_backend="none", as_of_date="2026-03-17",
2083 external_plan={
2084 "intent": "exploration", "freshness_mode": "balanced_recent",
2085 "cluster_mode": "topic",
2086 "subqueries": [
2087 {"label": label, "search_query": f"AI safety {label}",
2088 "ranking_query": "AI safety", "sources": ["x"]}
2089 for label in ["success", "failed"]
2090 ],
2091 },
2092 )
2093 self.assertCountEqual(["success", "failed"], [
2094 call.kwargs["subquery"].label for call in retrieval.call_args_list])
2095 return report
2096
2097 def test_error_becomes_partial_warning_when_another_stream_succeeds(self):
2098 report = self._run_with_failed_stream([{
2099 "id": "survivor", "text": "AI safety evaluation results",
2100 "url": "https://x.com/researcher/status/1", "author_handle": "researcher",
2101 "date": "2026-03-15", "engagement": {"likes": 50},
2102 }])
2103 self.assertEqual(["survivor"], [item.item_id for item in report.items_by_source["x"]])
2104 self.assertNotIn("x", report.errors_by_source)
2105 self.assertEqual(schema.PARTIAL, report.source_status["x"].state)
2106 self.assertIn("fixture lane unavailable", report.source_status["x"].detail)
2107 self.assertIn("Some sources returned partial results (degraded): x", report.warnings)
2108 self.assertNotIn("Some sources failed: x", report.warnings)
2109
2110 def test_error_remains_hard_failure_when_no_stream_returns_items(self):
2111 report = self._run_with_failed_stream([])
2112 self.assertEqual([], report.items_by_source.get("x", []))
2113 self.assertEqual("fixture lane unavailable", report.errors_by_source["x"])
2114 self.assertNotEqual(schema.PARTIAL, report.source_status["x"].state)
2115 self.assertIn("Some sources failed: x", report.warnings)
2116 self.assertNotIn("Some sources returned partial results (degraded): x", report.warnings)
2117
2118
2119 class TestXHandleFlag(unittest.TestCase):
2120 """R3: --x-handle CLI flag and pipeline parameter."""
2121
2122 def test_cli_accepts_x_handle_flag(self):
2123 """build_parser() should accept --x-handle."""
2124 import last30days as cli
2125
2126 parser = cli.build_parser()
2127 args = parser.parse_args(["test topic", "--x-handle", "elonmusk"])
2128 self.assertEqual(args.x_handle, "elonmusk")
2129
2130 def test_cli_x_handle_default_is_none(self):
2131 """--x-handle should default to None."""
2132 import last30days as cli
2133
2134 parser = cli.build_parser()
2135 args = parser.parse_args(["test topic"])
2136 self.assertIsNone(args.x_handle)
2137
2138 def test_pipeline_run_accepts_x_handle(self):
2139 """pipeline.run() should accept x_handle keyword argument."""
2140 import inspect
2141 sig = inspect.signature(pipeline.run)
2142 self.assertIn("x_handle", sig.parameters, "pipeline.run() must accept x_handle parameter")
2143
2144 def test_x_handle_passed_to_supplemental_searches(self):
2145 with patch("lib.providers.resolve_runtime", return_value=(_make_runtime(), None)), patch(
2146 "lib.pipeline.available_sources", return_value=["x"],
2147 ), patch("lib.pipeline._fetch_x_backend", return_value=([], None)), patch(
2148 "lib.env.x_backend_chain", return_value=["bird"],
2149 ), patch("lib.entity_extract.extract_entities", return_value={
2150 "x_handles": [], "x_hashtags": [], "reddit_subreddits": [],
2151 }), patch("lib.bird_x.search_handles", return_value=[{
2152 "id": "explicit-handle", "text": "test topic from testuser",
2153 "url": "https://x.com/testuser/status/123", "author_handle": "testuser",
2154 "date": "2026-03-15", "engagement": {"likes": 15}, "relevance": 1.0,
2155 }]) as handles, patch("lib.bird_x.search_mentions", return_value=[]):
2156 report = pipeline.run(
2157 topic="test topic", config={}, depth="default", requested_sources=["x"],
2158 mock=False, x_handle="testuser", web_backend="none", as_of_date="2026-03-17",
2159 external_plan={
2160 "intent": "exploration", "freshness_mode": "balanced_recent", "cluster_mode": "topic",
2161 "subqueries": [{"label": "primary", "search_query": "test topic",
2162 "ranking_query": "test topic", "sources": ["x"]}],
2163 },
2164 )
2165 handles.assert_called_once()
2166 self.assertEqual(handles.call_args.args, (["testuser"], "test topic", "2026-02-15"))
2167 self.assertEqual(handles.call_args.kwargs["to_date"], "2026-03-17")
2168 self.assertEqual(handles.call_args.kwargs["count_per"], pipeline.FROM_LANE_COUNT_PER)
2169 self.assertEqual([i.url for i in report.items_by_source["x"]], ["https://x.com/testuser/status/123"])
2170
2171
2172 class TestWarnings(unittest.TestCase):
2173 def _item(self, source="reddit"):
2174 return schema.SourceItem(item_id="1", source=source, title="t", body="b", url="u")
2175
2176 def _candidate(self, source="reddit", score=50.0):
2177 c = schema.Candidate(
2178 candidate_id="c1", item_id="1", source=source, title="t", url="u",
2179 snippet="s", subquery_labels=["main"], native_ranks={"main:reddit": 1},
2180 local_relevance=0.5, freshness=50, engagement=10, source_quality=0.7,
2181 rrf_score=0.01, sources=[source],
2182 )
2183 c.final_score = score
2184 return c
2185
2186 def test_no_candidates_warning(self):
2187 w = pipeline._warnings({"reddit": [self._item()]}, [], {})
2188 self.assertTrue(any("No candidates" in msg for msg in w))
2189
2190 def test_thin_evidence_warning(self):
2191 candidates = [self._candidate() for _ in range(3)]
2192 w = pipeline._warnings({"reddit": [self._item()]}, candidates, {})
2193 self.assertTrue(any("thin" in msg.lower() for msg in w))
2194
2195 def test_single_source_concentration(self):
2196 candidates = [self._candidate() for _ in range(5)]
2197 w = pipeline._warnings({"reddit": [self._item()]}, candidates, {})
2198 self.assertTrue(any("concentrated" in msg.lower() for msg in w))
2199
2200 def test_source_errors_listed(self):
2201 w = pipeline._warnings({}, [self._candidate()], {"x": "timeout"})
2202 self.assertTrue(any("x" in msg for msg in w))
2203
2204 def test_no_items_warning(self):
2205 w = pipeline._warnings({}, [], {})
2206 self.assertTrue(any("No source returned" in msg for msg in w))
2207
2208
2209 class TestXRelatedSupplementalSearch(unittest.TestCase):
2210 """Tests for --x-related weighted supplemental search."""
2211
2212 @patch("lib.bird_x.search_handles")
2213 @patch("lib.entity_extract.extract_entities")
2214 def test_x_related_triggers_supplemental_related_label(self, mock_extract, mock_handles):
2215 """x_related handles should be searched and added with supplemental-related label."""
2216 mock_extract.return_value = {"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}
2217 mock_handles.return_value = [
2218 {
2219 "id": "rel1",
2220 "text": "Related tweet from biancacensori",
2221 "url": "https://x.com/biancacensori/status/555",
2222 "author_handle": "biancacensori",
2223 "date": "2026-03-15",
2224 "engagement": {"likes": 30},
2225 "relevance": 0.7,
2226 "why_relevant": "related handle search",
2227 }
2228 ]
2229
2230 bundle = schema.RetrievalBundle()
2231 bundle.items_by_source["x"] = [
2232 _make_source_item("x", "X1", "https://x.com/kanyewest/status/1", author="kanyewest"),
2233 ]
2234
2235 plan = _make_plan("Kanye West")
2236
2237 pipeline._run_supplemental_searches(
2238 topic="Kanye West",
2239 bundle=bundle,
2240 plan=plan,
2241 config={},
2242 depth="default",
2243 date_range=("2026-02-15", "2026-03-17"),
2244 runtime=_make_runtime("bird"),
2245 mock=False,
2246 rate_limited_sources=set(),
2247 rate_limit_lock=threading.Lock(),
2248 x_related=["biancacensori"],
2249 )
2250
2251 # search_handles should have been called for the related handle
2252 mock_handles.assert_called()
2253 # The supplemental-related subquery label should exist in the plan
2254 labels = [sq.label for sq in plan.subqueries]
2255 self.assertIn("supplemental-related", labels)
2256 # The supplemental-related subquery should have weight 0.3
2257 related_sq = [sq for sq in plan.subqueries if sq.label == "supplemental-related"][0]
2258 self.assertAlmostEqual(related_sq.weight, 0.3)
2259
2260 @patch("lib.bird_x.search_handles")
2261 @patch("lib.entity_extract.extract_entities")
2262 def test_no_x_related_no_supplemental_related_label(self, mock_extract, mock_handles):
2263 """Without x_related, supplemental-related label should not appear."""
2264 mock_extract.return_value = {"x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": []}
2265 mock_handles.return_value = [
2266 {
2267 "id": "supp1",
2268 "text": "Supplemental tweet",
2269 "url": "https://x.com/analyst1/status/999",
2270 "author_handle": "analyst1",
2271 "date": "2026-03-15",
2272 "engagement": {"likes": 50},
2273 "relevance": 0.8,
2274 "why_relevant": "direct handle search",
2275 }
2276 ]
2277
2278 bundle = schema.RetrievalBundle()
2279 bundle.items_by_source["x"] = [
2280 _make_source_item("x", "X1", "https://x.com/analyst1/status/1", author="analyst1"),
2281 ]
2282
2283 plan = _make_plan("AI safety")
2284
2285 pipeline._run_supplemental_searches(
2286 topic="AI safety",
2287 bundle=bundle,
2288 plan=plan,
2289 config={},
2290 depth="default",
2291 date_range=("2026-02-15", "2026-03-17"),
2292 runtime=_make_runtime("bird"),
2293 mock=False,
2294 rate_limited_sources=set(),
2295 rate_limit_lock=threading.Lock(),
2296 )
2297
2298 # supplemental-related label should NOT exist (no x_related provided)
2299 labels = [sq.label for sq in plan.subqueries]
2300 self.assertNotIn("supplemental-related", labels)
2301
2302
2303 class TestRetryThinSourcesCoreEqualsTopic(unittest.TestCase):
2304 """Test that _retry_thin_sources fires even when core == topic (the fix)."""
2305
2306 @patch("lib.pipeline._retrieve_stream")
2307 def test_retry_fires_when_core_equals_topic(self, mock_retrieve):
2308 """Topic 'Kanye West' with 0 YouTube items should trigger retry.
2309
2310 Previously this was skipped because core 'kanye west' == topic.
2311 The fix ensures retry still fires for short topics.
2312 """
2313 mock_retrieve.return_value = (
2314 [
2315 {
2316 "id": "YT1",
2317 "title": "Kanye West new album leak",
2318 "url": "https://www.youtube.com/watch?v=abc123",
2319 "date": "2026-03-15",
2320 "engagement": {"views": 1000},
2321 "relevance": 0.8,
2322 "why_relevant": "retry result",
2323 }
2324 ],
2325 {},
2326 )
2327
2328 plan = schema.QueryPlan(
2329 intent="breaking_news",
2330 freshness_mode="strict_recent",
2331 cluster_mode="story",
2332 raw_topic="Kanye West",
2333 subqueries=[
2334 schema.SubQuery(
2335 label="primary",
2336 search_query="Kanye West",
2337 ranking_query="What recent evidence matters for Kanye West?",
2338 sources=["youtube", "x"],
2339 )
2340 ],
2341 source_weights={"youtube": 1.0, "x": 1.0},
2342 )
2343 bundle = schema.RetrievalBundle()
2344 # YouTube has 0 items (thin), X has enough
2345 bundle.items_by_source["x"] = [
2346 _make_source_item("x", f"X{i}", f"https://x.com/a/{i}") for i in range(5)
2347 ]
2348
2349 pipeline._retry_thin_sources(
2350 topic="Kanye West",
2351 bundle=bundle,
2352 plan=plan,
2353 config={},
2354 depth="default",
2355 date_range=("2026-02-15", "2026-03-17"),
2356 runtime=_make_runtime(),
2357 mock=False,
2358 rate_limited_sources=set(),
2359 rate_limit_lock=threading.Lock(),
2360 settings=pipeline.DEPTH_SETTINGS["default"],
2361 )
2362
2363 # _retrieve_stream should have been called for youtube
2364 mock_retrieve.assert_called()
2365 retried_sources = [c.kwargs["source"] for c in mock_retrieve.call_args_list]
2366 self.assertIn("youtube", retried_sources)
2367 # YouTube should now have items in the bundle
2368 self.assertIn("youtube", bundle.items_by_source)
2369
2370
2371 class TestZeroKeyPipelineRun(unittest.TestCase):
2372 """Pipeline should complete with local fallbacks when no reasoning keys are configured."""
2373
2374 @patch("lib.pipeline._retrieve_stream")
2375 def test_zero_key_run_produces_report(self, mock_retrieve):
2376 mock_retrieve.side_effect = lambda **kwargs: pipeline._mock_stream_results(
2377 kwargs["source"], kwargs["subquery"]
2378 )
2379 config = {"LAST30DAYS_REASONING_PROVIDER": "auto"}
2380 report = pipeline.run(
2381 topic="test zero key topic",
2382 config=config,
2383 depth="quick",
2384 requested_sources=["hackernews"],
2385 )
2386 self.assertEqual("test zero key topic", report.topic)
2387 self.assertEqual("local", report.provider_runtime.reasoning_provider)
2388 self.assertEqual("deterministic", report.provider_runtime.planner_model)
2389 self.assertTrue(
2390 any("fallback" in note for note in report.query_plan.notes),
2391 f"Expected fallback plan, got notes: {report.query_plan.notes}",
2392 )
2393 for candidate in report.ranked_candidates:
2394 self.assertEqual("fallback-local-score", candidate.explanation)
2395
2396
2397 class TestExcludeSources(unittest.TestCase):
2398 """EXCLUDE_SOURCES env var filters sources out of available_sources().
2399
2400 The existing INCLUDE_SOURCES allowlist (used by Perplexity opt-in) does
2401 not cover this case — tiktok and instagram are added unconditionally
2402 when SCRAPECREATORS_API_KEY is set, with no way to opt out short of
2403 unsetting the key. EXCLUDE_SOURCES gives runs a per-invocation denylist.
2404 """
2405
2406 def test_excludes_tiktok_and_instagram(self):
2407 config = {
2408 "SCRAPECREATORS_API_KEY": "test-key",
2409 "EXCLUDE_SOURCES": "tiktok,instagram",
2410 }
2411 sources = pipeline.available_sources(config)
2412 self.assertNotIn("tiktok", sources)
2413 self.assertNotIn("instagram", sources)
2414 self.assertIn("reddit", sources)
2415 self.assertIn("hackernews", sources)
2416
2417 def test_no_exclusion_when_unset(self):
2418 config = {"SCRAPECREATORS_API_KEY": "test-key"}
2419 sources = pipeline.available_sources(config)
2420 self.assertIn("tiktok", sources)
2421 self.assertIn("instagram", sources)
2422
2423 def test_empty_exclude_sources_is_noop(self):
2424 config = {
2425 "SCRAPECREATORS_API_KEY": "test-key",
2426 "EXCLUDE_SOURCES": "",
2427 }
2428 sources = pipeline.available_sources(config)
2429 self.assertIn("tiktok", sources)
2430 self.assertIn("instagram", sources)
2431
2432 def test_whitespace_and_case_insensitive(self):
2433 config = {
2434 "SCRAPECREATORS_API_KEY": "test-key",
2435 "EXCLUDE_SOURCES": " TikTok , INSTAGRAM ",
2436 }
2437 sources = pipeline.available_sources(config)
2438 self.assertNotIn("tiktok", sources)
2439 self.assertNotIn("instagram", sources)
2440
2441 def test_excludes_non_scrapecreators_source(self):
2442 """EXCLUDE_SOURCES applies to any source, not just SC-backed ones."""
2443 config = {"EXCLUDE_SOURCES": "hackernews"}
2444 sources = pipeline.available_sources(config)
2445 self.assertNotIn("hackernews", sources)
2446 self.assertIn("reddit", sources)
2447
2448
2449 class TestPerplexityAvailability(unittest.TestCase):
2450 def test_agent_background_failure_uses_safe_provider_detail(self):
2451 outcome = pipeline._legacy_artifact_outcome(
2452 "perplexity",
2453 {
2454 "error": "failed",
2455 "backgroundErrorMessage": "Provider reported an incomplete run",
2456 },
2457 )
2458
2459 self.assertEqual(health.ERROR, outcome["state"])
2460 self.assertEqual("Provider reported an incomplete run", outcome["detail"])
2461
2462 def test_agent_background_poll_429_is_rate_limited(self):
2463 outcome = pipeline._legacy_artifact_outcome(
2464 "perplexity",
2465 {
2466 "error": "poll_error",
2467 "backgroundPollError": "HTTP 429: Too Many Requests",
2468 "backgroundPollStatusCode": 429,
2469 },
2470 )
2471
2472 self.assertEqual(health.RATE_LIMITED, outcome["state"])
2473 self.assertEqual("HTTP 429: Too Many Requests", outcome["detail"])
2474
2475 def test_perplexity_source_available_with_openrouter_fallback(self):
2476 sources = pipeline.available_sources(
2477 {"OPENROUTER_API_KEY": "test-key", "INCLUDE_SOURCES": "perplexity"}
2478 )
2479 self.assertIn("perplexity", sources)
2480
2481 def test_perplexity_source_not_available_with_direct_key_without_opt_in(self):
2482 sources = pipeline.available_sources({"PERPLEXITY_API_KEY": "test-key"})
2483 self.assertNotIn("perplexity", sources)
2484
2485 def test_perplexity_source_available_with_direct_key(self):
2486 sources = pipeline.available_sources(
2487 {"PERPLEXITY_API_KEY": "test-key", "INCLUDE_SOURCES": "perplexity"}
2488 )
2489 self.assertIn("perplexity", sources)
2490
2491 def test_perplexity_diagnose_reports_direct_provider(self):
2492 diag = pipeline.diagnose({"PERPLEXITY_API_KEY": "test-key"})
2493 self.assertTrue(diag["providers"]["perplexity"])
2494 self.assertTrue(diag["local_mode"])
2495
2496
2497 class TestLinkedinAvailability(unittest.TestCase):
2498 """LinkedIn is power-user opt-in (INCLUDE_SOURCES=linkedin), unlike
2499 tiktok/instagram which activate on SCRAPECREATORS_API_KEY alone. This
2500 keeps existing SCRAPECREATORS_API_KEY holders from silently picking up a
2501 new source — and spending new credits — on their next run."""
2502
2503 def test_not_available_with_key_alone(self):
2504 sources = pipeline.available_sources({"SCRAPECREATORS_API_KEY": "test-key"})
2505 self.assertNotIn("linkedin", sources)
2506 # tiktok/instagram remain unconditional with just the key
2507 self.assertIn("tiktok", sources)
2508 self.assertIn("instagram", sources)
2509
2510 def test_available_with_key_and_include_sources(self):
2511 sources = pipeline.available_sources(
2512 {"SCRAPECREATORS_API_KEY": "test-key", "INCLUDE_SOURCES": "linkedin"}
2513 )
2514 self.assertIn("linkedin", sources)
2515
2516 def test_available_with_key_and_requested_sources(self):
2517 sources = pipeline.available_sources(
2518 {"SCRAPECREATORS_API_KEY": "test-key"}, requested_sources=["linkedin"]
2519 )
2520 self.assertIn("linkedin", sources)
2521
2522 def test_not_available_with_include_sources_but_no_key(self):
2523 sources = pipeline.available_sources({"INCLUDE_SOURCES": "linkedin"})
2524 self.assertNotIn("linkedin", sources)
2525
2526
2527 class TestKeylessGroundingAvailability(unittest.TestCase):
2528 """Grounding (general web) availability is host-aware.
2529
2530 Non-native hosts get the keyless floor by default; native-search hosts leave
2531 general web to the model's own search unless a paid key is configured.
2532 """
2533
2534 def test_grounding_available_without_key_on_non_native_host(self):
2535 sources = pipeline.available_sources({})
2536 self.assertIn("grounding", sources)
2537
2538 def test_grounding_suppressed_without_key_on_native_host(self):
2539 config = {"LAST30DAYS_NATIVE_SEARCH": "1"}
2540 sources = pipeline.available_sources(config)
2541 self.assertNotIn("grounding", sources)
2542
2543 def test_grounding_available_with_paid_key_even_on_native_host(self):
2544 config = {"LAST30DAYS_NATIVE_SEARCH": "1", "BRAVE_API_KEY": "k"}
2545 sources = pipeline.available_sources(config)
2546 self.assertIn("grounding", sources)
2547
2548
2549 class TestExcludeSourcesEndToEnd(unittest.TestCase):
2550 """Wiring regression: EXCLUDE_SOURCES from the process environment must
2551 reach available_sources() via env.get_config(). The unit tests above
2552 construct config dicts directly; this one exercises the env-to-config
2553 path so a missing entry in env.py's keys list is caught immediately."""
2554
2555 def test_exclude_sources_from_env_propagates_through_get_config(self):
2556 import os
2557 from unittest.mock import patch as _patch
2558 from lib import env as env_mod
2559 from importlib import reload
2560 with _patch.dict(os.environ, {
2561 "LAST30DAYS_CONFIG_DIR": "",
2562 "EXCLUDE_SOURCES": "tiktok,instagram",
2563 "SCRAPECREATORS_API_KEY": "fake",
2564 }, clear=False):
2565 reload(env_mod)
2566 cfg = env_mod.get_config()
2567 self.assertEqual(cfg.get("EXCLUDE_SOURCES"), "tiktok,instagram")
2568 sources = pipeline.available_sources(cfg)
2569 self.assertNotIn("tiktok", sources)
2570 self.assertNotIn("instagram", sources)
2571
2572
2573 class TestInnerMaxWorkers(unittest.TestCase):
2574 """Cap inner ThreadPoolExecutor concurrency under competitor fanout.
2575
2576 Without the cap, six competitor sub-runs each open their own
2577 ``ThreadPoolExecutor(max_workers=16)``, peaking around 96 worker threads
2578 that all hammer the same upstream APIs. ``internal_subrun=True`` should
2579 reduce the inner pool so the nested fanout stays bounded.
2580 """
2581
2582 def test_normal_run_uses_full_ceiling(self):
2583 self.assertEqual(pipeline._inner_max_workers(20, internal_subrun=False), 16)
2584 self.assertEqual(pipeline._inner_max_workers(10, internal_subrun=False), 10)
2585 self.assertEqual(pipeline._inner_max_workers(1, internal_subrun=False), 4)
2586
2587 def test_subrun_caps_at_four(self):
2588 self.assertEqual(pipeline._inner_max_workers(20, internal_subrun=True), 4)
2589 self.assertEqual(pipeline._inner_max_workers(10, internal_subrun=True), 4)
2590 self.assertEqual(pipeline._inner_max_workers(3, internal_subrun=True), 3)
2591 self.assertEqual(pipeline._inner_max_workers(1, internal_subrun=True), 2)
2592
2593 def test_subrun_caps_total_concurrency_below_uncapped(self):
2594 # Derive the outer cap from fanout so this test stays meaningful if
2595 # MAX_PARALLEL_SUBRUNS is bumped. The contract under test is "subrun
2596 # mode meaningfully reduces total inner-thread count", not a magic
2597 # number tied to today's value of MAX_PARALLEL_SUBRUNS=6.
2598 from lib import fanout
2599 max_subruns = fanout.MAX_PARALLEL_SUBRUNS
2600 capped = pipeline._inner_max_workers(20, internal_subrun=True) * max_subruns
2601 uncapped = pipeline._inner_max_workers(20, internal_subrun=False) * max_subruns
2602 self.assertLess(capped, uncapped, f"capped={capped} not < uncapped={uncapped}")
2603 # The cap must cut total concurrency to at most half of the un-capped
2604 # value; otherwise the cap is doing real work.
2605 self.assertLessEqual(
2606 capped,
2607 uncapped // 2,
2608 f"capped {capped} should be at most half of uncapped {uncapped}",
2609 )
2610
2611
2612 class TestScrapeCreatorsTierGating(unittest.TestCase):
2613 """The onboarding Recommended vs Everything tiers must be real.
2614
2615 Recommended (key, no INCLUDE_SOURCES) = TikTok + Instagram only.
2616 Everything (INCLUDE_SOURCES lists them) = also Threads, Pinterest, ...
2617 """
2618
2619 KEY = {"SCRAPECREATORS_API_KEY": "k"}
2620
2621 def test_recommended_tier_runs_tiktok_instagram(self):
2622 avail = pipeline.available_sources(dict(self.KEY))
2623 self.assertIn("tiktok", avail)
2624 self.assertIn("instagram", avail)
2625
2626 def test_threads_off_without_include_sources(self):
2627 self.assertNotIn("threads", pipeline.available_sources(dict(self.KEY)))
2628
2629 def test_threads_on_with_include_sources(self):
2630 cfg = {**self.KEY, "INCLUDE_SOURCES": "threads"}
2631 self.assertIn("threads", pipeline.available_sources(cfg))
2632
2633 def test_pinterest_off_without_include_sources(self):
2634 self.assertNotIn("pinterest", pipeline.available_sources(dict(self.KEY)))
2635
2636 def test_pinterest_on_with_persisted_include_sources(self):
2637 # Regression: this failed before U6 because the pinterest gate read
2638 # requested_sources only and ignored a persisted INCLUDE_SOURCES.
2639 cfg = {**self.KEY, "INCLUDE_SOURCES": "pinterest"}
2640 self.assertIn("pinterest", pipeline.available_sources(cfg))
2641
2642 def test_pinterest_on_via_requested_sources(self):
2643 # The per-run --sources path must still work.
2644 avail = pipeline.available_sources(dict(self.KEY), requested_sources=["pinterest"])
2645 self.assertIn("pinterest", avail)
2646
2647 def test_everything_tier_enables_all(self):
2648 cfg = {
2649 **self.KEY,
2650 "INCLUDE_SOURCES": "tiktok,instagram,threads,pinterest,youtube_comments,tiktok_comments",
2651 }
2652 avail = pipeline.available_sources(cfg)
2653 self.assertIn("threads", avail)
2654 self.assertIn("pinterest", avail)
2655
2656
2657 class TestAmazonSourceGating:
2658 """U2: the amazon source is dual-gated -- CLI available AND requested."""
2659
2660 def _config(self, include=""):
2661 return {"INCLUDE_SOURCES": include}
2662
2663 def test_unavailable_without_the_cli_even_when_requested(self):
2664 with patch.object(pipeline.brightdata, "is_available", return_value=False):
2665 available = pipeline.available_sources(self._config(), ["amazon"])
2666 assert "amazon" not in available
2667
2668 def test_unavailable_with_the_cli_when_not_requested(self):
2669 """Installing the CLI for other work must not start spending credits."""
2670 with patch.object(pipeline.brightdata, "is_available", return_value=True):
2671 available = pipeline.available_sources(self._config(), None)
2672 assert "amazon" not in available
2673
2674 def test_available_via_per_run_request(self):
2675 with patch.object(pipeline.brightdata, "is_available", return_value=True):
2676 available = pipeline.available_sources(self._config(), ["amazon"])
2677 assert "amazon" in available
2678
2679 def test_available_via_durable_include_sources(self):
2680 with patch.object(pipeline.brightdata, "is_available", return_value=True):
2681 available = pipeline.available_sources(self._config("amazon"), None)
2682 assert "amazon" in available
2683
2684 def test_search_flag_accepts_the_amazon_token(self):
2685 import last30days
2686 assert "amazon" in last30days.parse_search_flag("reddit,x,amazon")
2687
2688 def test_capped_at_one_fetch_per_run(self):
2689 """One model-supplied keyword per run: extra streams are pure cost."""
2690 assert pipeline.MAX_SOURCE_FETCHES["amazon"] == 1
2691
2692
2693 # ---------------------------------------------------------------------------
2694 # Run-scoped source fetch memo (U4, R5, R6): subquery streams that repeat the
2695 # raw-topic search for TikTok, Instagram, YouTube, and X fetch it once.
2696 # ---------------------------------------------------------------------------
2697
2698 _MEMO_TOPIC = "ghostty terminal"
2699 _MEMO_RANGE = ("2026-09-11", "2026-10-11")
2700 _MEMO_SC_CONFIG = {
2701 "SCRAPECREATORS_API_KEY": "test-key",
2702 "INCLUDE_SOURCES": "tiktok,instagram,tiktok_comments,instagram_comments",
2703 }
2704
2705
2706 def _memo_subqueries(sources, labels=("price", "speed", "themes")):
2707 return [
2708 schema.SubQuery(
2709 label=label,
2710 search_query=f"ghostty {label}",
2711 ranking_query=f"What do people say about ghostty {label}?",
2712 sources=list(sources),
2713 )
2714 for label in labels
2715 ]
2716
2717
2718 def _raw_topic_subquery(source):
2719 return schema.SubQuery(
2720 label="primary",
2721 search_query=_MEMO_TOPIC,
2722 ranking_query=f"What do people say about {_MEMO_TOPIC}?",
2723 sources=[source],
2724 )
2725
2726
2727 def _memo_stream(source, subquery, config, **kwargs):
2728 return pipeline._retrieve_stream(
2729 topic=_MEMO_TOPIC, subquery=subquery, source=source, config=config,
2730 depth="default", date_range=_MEMO_RANGE, runtime=_make_runtime(None),
2731 mock=False, raw_topic=_MEMO_TOPIC, **kwargs,
2732 )
2733
2734
2735 def _memo_streams_concurrently(jobs):
2736 from concurrent.futures import ThreadPoolExecutor
2737
2738 with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
2739 futures = [pool.submit(_memo_stream, *job) for job in jobs]
2740 return [future.result(timeout=10) for future in futures]
2741
2742
2743 def _tiktok_payload(*_args, **_kwargs):
2744 return {"items": [{
2745 "id": "t1", "video_id": "t1", "text": "ghostty terminal setup tour",
2746 "url": "https://www.tiktok.com/@dev/video/1", "author_name": "dev",
2747 "date": "2026-10-01", "engagement": {"views": 900, "likes": 90},
2748 "relevance": 0.9, "why_relevant": "fixture",
2749 }]}
2750
2751
2752 def _instagram_payload(*_args, **_kwargs):
2753 return {"items": [{
2754 "id": "i1", "video_id": "i1", "text": "ghostty terminal reel",
2755 "url": "https://www.instagram.com/reel/abc/", "author_name": "dev",
2756 "date": "2026-10-01", "engagement": {"views": 500, "likes": 50},
2757 "relevance": 0.9, "why_relevant": "fixture",
2758 }]}
2759
2760
2761 def _youtube_payload(*_args, **_kwargs):
2762 return {"items": [
2763 {
2764 "video_id": f"vid{n:08d}", "title": f"ghostty terminal review {n}",
2765 "url": f"https://www.youtube.com/watch?v=vid{n:08d}", "channel_name": "dev",
2766 "date": "2026-10-01", "engagement": {"views": 1000 - n, "likes": 10},
2767 "relevance": 0.9, "why_relevant": "fixture",
2768 }
2769 for n in range(6)
2770 ]}
2771
2772
2773 def _keyless_tiktok_payload(*_args, **_kwargs):
2774 payload = _tiktok_payload()
2775 payload["items"][0]["_oss_backend"] = "yt-dlp"
2776 return payload
2777
2778
2779 class TestKeylessTikTokComments:
2780 """Keyless TikTok items get top comments from the public endpoint."""
2781
2782 def _run(self, config):
2783 [subquery] = _memo_subqueries(["tiktok"], labels=("keyless",))
2784 with patch("lib.tiktok.search_and_enrich", side_effect=_keyless_tiktok_payload), \
2785 patch("lib.tiktok.enrich_with_comments") as comments:
2786 items, _artifact = _memo_stream("tiktok", subquery, config)
2787 return items, comments
2788
2789 def test_keyless_items_are_enriched_without_a_key(self):
2790 items, comments = self._run({})
2791 assert items
2792 assert comments.call_count == 1
2793 assert comments.call_args.kwargs["public"] is True
2794 assert comments.call_args.kwargs["token"] == ""
2795
2796 def test_switch_off_skips_keyless_comments(self):
2797 _items, comments = self._run({"LAST30DAYS_TIKTOK_PUBLIC_COMMENTS": "off"})
2798 assert comments.call_count == 0
2799
2800
2801 def _with_stale_post(payload_fn, url_for):
2802 def payload(*_args, **_kwargs):
2803 data = payload_fn()
2804 kept = data["items"][0]
2805 data["items"] = [
2806 {**kept, "id": "old", "video_id": "old", "url": url_for("old"), "date": "2022-02-03",
2807 "engagement": {"views": 50_000_000}, "relevance": 0.9},
2808 kept,
2809 ]
2810 return data
2811 return payload
2812
2813
2814 def _post(pid, relevance=0.9, date="2026-09-20", author="dev"):
2815 return {"id": pid, "date": date, "relevance": relevance, "author_name": author}
2816
2817
2818 class TestCommentsSpentOnKeptPosts:
2819 """Paid comment calls go to posts the report can keep."""
2820
2821 RANGE = ("2026-09-11", "2026-10-11")
2822
2823 def _ids(self, items, creators=None):
2824 return [i["id"] for i in pipeline._comment_candidates(items, *self.RANGE, creators)]
2825
2826 def test_tiktok_comments_skip_stale_posts(self):
2827 [subquery] = _memo_subqueries(["tiktok"], labels=("comments",))
2828 payload = _with_stale_post(_tiktok_payload, lambda v: f"https://www.tiktok.com/@dev/video/{v}")
2829 with patch("lib.tiktok.search_and_enrich", side_effect=payload), \
2830 patch("lib.tiktok.enrich_with_comments") as comments:
2831 _memo_stream("tiktok", subquery, dict(_MEMO_SC_CONFIG))
2832 assert [i["id"] for i in comments.call_args.args[0]] == ["t1"]
2833
2834 def test_instagram_comments_skip_stale_posts(self):
2835 [subquery] = _memo_subqueries(["instagram"], labels=("comments",))
2836 payload = _with_stale_post(_instagram_payload, lambda v: f"https://www.instagram.com/reel/{v}/")
2837 with patch("lib.instagram.search_and_enrich", side_effect=payload), \
2838 patch("lib.instagram.enrich_with_comments") as comments:
2839 _memo_stream("instagram", subquery, dict(_MEMO_SC_CONFIG))
2840 assert [i["id"] for i in comments.call_args.args[0]] == ["i1"]
2841
2842 def test_off_topic_posts_wait_behind_enough_on_topic_ones(self):
2843 items = [_post("off", relevance=0.0), _post("a"), _post("b"), _post("c"),
2844 _post("undated", date="")]
2845 assert self._ids(items) == ["a", "b", "c", "undated"]
2846
2847 def test_off_topic_posts_only_fill_empty_slots_loudest_first(self):
2848 def loud(pid, views):
2849 return {**_post(pid, relevance=0.0), "engagement": {"views": views}}
2850
2851 items = [loud("quiet", 10), _post("a"), loud("loudest", 9_000), loud("louder", 500),
2852 _post("stale", date="2022-02-03")]
2853 # Enrichment ranks by engagement and takes three: the loud off-topic
2854 # posts must not be able to push "a" out, so only two are offered.
2855 assert self._ids(items) == ["a", "loudest", "louder"]
2856
2857 def test_spoken_caption_match_counts_as_on_topic(self):
2858 spoken = {**_post("spoken", relevance=0.0), "text": "wait for it",
2859 "caption_snippet": "the ghostty terminal config I use every day"}
2860 items = [spoken, _post("a"), _post("b"), _post("c")]
2861 ids = [i["id"] for i in pipeline._comment_candidates(
2862 items, *self.RANGE, topic="ghostty terminal")]
2863 assert ids == ["spoken", "a", "b", "c"]
2864
2865 def test_requested_creator_posts_count_as_on_topic(self):
2866 items = [_post("mine", relevance=0.0, author="@Traveler"), _post("other", relevance=0.0),
2867 _post("a"), _post("b")]
2868 assert self._ids(items, creators=["traveler"]) == ["mine", "a", "b"]
2869
2870
2871 def _attach_comments(items, *_args, **_kwargs):
2872 for item in items:
2873 item["top_comments"] = [{"author": "a", "text": "fire", "digg_count": 9, "date": ""}]
2874 return items
2875
2876
2877 class TestTikTokPublicComments:
2878 """ScrapeCreators runs take TikTok comments from the free public endpoint first."""
2879
2880 def _run(self, config, side_effect=_attach_comments):
2881 [subquery] = _memo_subqueries(["tiktok"], labels=("public",))
2882 with patch("lib.tiktok.search_and_enrich", side_effect=_tiktok_payload), \
2883 patch("lib.tiktok.enrich_with_comments", side_effect=side_effect) as comments:
2884 _memo_stream("tiktok", subquery, config)
2885 return comments
2886
2887 def test_public_endpoint_serves_comments_without_scrapecreators_calls(self):
2888 comments = self._run(dict(_MEMO_SC_CONFIG))
2889 assert comments.call_count == 1
2890 kwargs = comments.call_args.kwargs
2891 assert kwargs["public"] is True and kwargs["token"] == ""
2892 assert kwargs["max_posts"] == pipeline.PUBLIC_COMMENT_POSTS
2893
2894 def test_scrapecreators_backs_up_an_empty_public_endpoint(self):
2895 comments = self._run(dict(_MEMO_SC_CONFIG), side_effect=lambda items, *a, **k: items)
2896 assert comments.call_count == 2
2897 assert comments.call_args_list[0].kwargs["public"] is True
2898 last = comments.call_args_list[1].kwargs
2899 assert last["token"] == "test-key" and "public" not in last
2900
2901 def test_a_stalled_public_endpoint_still_leaves_time_for_scrapecreators(self):
2902 from lib import http as lib_http
2903
2904 def stall_public(items, *a, **kwargs):
2905 if kwargs.get("public"):
2906 raise lib_http.DeadlineExceeded()
2907 return _attach_comments(items)
2908
2909 comments = self._run(dict(_MEMO_SC_CONFIG), side_effect=stall_public)
2910 assert comments.call_count == 2
2911 public, paid = comments.call_args_list
2912 assert public.kwargs["deadline"] <= paid.kwargs["deadline"] - pipeline.SC_COMMENT_RESERVE_SECONDS
2913 assert paid.kwargs["token"] == "test-key"
2914
2915 def test_switch_off_goes_straight_to_scrapecreators(self):
2916 comments = self._run({**_MEMO_SC_CONFIG, "LAST30DAYS_TIKTOK_PUBLIC_COMMENTS": "off"})
2917 assert comments.call_count == 1
2918 assert comments.call_args.kwargs["token"] == "test-key"
2919
2920
2921 class TestSourceFetchMemo:
2922 def test_three_subquery_streams_fetch_each_source_once(self):
2923 subqueries = _memo_subqueries(["tiktok", "instagram", "youtube"])
2924 with patch("lib.tiktok.search_and_enrich", side_effect=_tiktok_payload) as tiktok_search, \
2925 patch("lib.instagram.search_and_enrich", side_effect=_instagram_payload) as ig_search, \
2926 patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload) as yt_search, \
2927 patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
2928 patch("lib.env.is_youtube_comments_available", return_value=True), \
2929 patch("lib.youtube_yt.enrich_with_comments") as yt_comments, \
2930 patch("lib.tiktok.enrich_with_comments", side_effect=_attach_comments) as tiktok_comments, \
2931 patch("lib.instagram.enrich_with_comments") as ig_comments:
2932 results = _memo_streams_concurrently([
2933 (source, subquery, dict(_MEMO_SC_CONFIG))
2934 for subquery in subqueries
2935 for source in ("tiktok", "instagram", "youtube")
2936 ])
2937
2938 assert tiktok_search.call_count == 1
2939 assert ig_search.call_count == 1
2940 assert yt_search.call_count == 1
2941 assert tiktok_comments.call_count == 1
2942 assert ig_comments.call_count == 1
2943 assert yt_comments.call_count == 1
2944 assert all(items for items, _artifact in results)
2945
2946 def test_scrapecreators_only_youtube_searches_once(self):
2947 subqueries = _memo_subqueries(["youtube"])
2948 with patch("lib.pipeline.which", return_value=None), \
2949 patch("lib.youtube_yt.search_youtube_sc", side_effect=_youtube_payload) as sc_search, \
2950 patch("lib.env.is_youtube_comments_available", return_value=False):
2951 results = _memo_streams_concurrently([
2952 ("youtube", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2953 for subquery in subqueries
2954 ])
2955 assert sc_search.call_count == 1
2956 assert all(len(items) == 6 for items, _artifact in results)
2957
2958 def test_hashtag_and_keyword_tiktok_calls_are_different_keys(self):
2959 [subquery] = _memo_subqueries(["tiktok"], labels=("price",))
2960 with patch("lib.tiktok.search_and_enrich", side_effect=_tiktok_payload) as tiktok_search:
2961 _memo_stream("tiktok", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2962 _memo_stream("tiktok", subquery, {"SCRAPECREATORS_API_KEY": "test-key"},
2963 tiktok_hashtags=["ghostty"])
2964 assert tiktok_search.call_count == 2
2965 assert tiktok_search.call_args_list[1].kwargs["hashtags"] == ["ghostty"]
2966
2967 def test_failed_tiktok_search_is_not_reused(self):
2968 [subquery] = _memo_subqueries(["tiktok"], labels=("price",))
2969 responses = [{"items": [], "error": "HTTP 503"}, _tiktok_payload()]
2970 with patch("lib.tiktok.search_and_enrich", side_effect=responses) as tiktok_search:
2971 first_items, first_artifact = _memo_stream("tiktok", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2972 second_items, _ = _memo_stream("tiktok", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2973 assert tiktok_search.call_count == 2
2974 assert first_items == [] and first_artifact
2975 assert second_items
2976
2977 def test_failed_instagram_search_is_not_reused(self):
2978 [subquery] = _memo_subqueries(["instagram"], labels=("price",))
2979 responses = [{"items": [], "error": "HTTP 503"}, _instagram_payload()]
2980 with patch("lib.instagram.search_and_enrich", side_effect=responses) as ig_search:
2981 _memo_stream("instagram", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2982 second_items, _ = _memo_stream("instagram", subquery, {"SCRAPECREATORS_API_KEY": "test-key"})
2983 assert ig_search.call_count == 2
2984 assert second_items
2985
2986 @pytest.mark.parametrize("artifact, clean", [
2987 ({}, True),
2988 ({"_source_outcome_detail": "yt-dlp thin; backfilled"}, True),
2989 ({"_source_outcome": {"state": "error"}}, False),
2990 ({"_source_outcome_deferred": {"state": "partial"}}, False),
2991 ({"_source_outcome_if_empty": {"state": "error"}}, False),
2992 ({"_source_outcome_detail_state": "partial"}, False),
2993 ])
2994 def test_clean_stream_result_rejects_every_failure_marker(self, artifact, clean):
2995 assert pipeline._clean_stream_result(([], artifact)) is clean
2996
2997 def test_x_waiter_gets_owner_result_when_owner_runs_to_chain_deadline(self):
2998 deadline = time.monotonic() + 0.2
2999
3000 def slow_backend(*_args, **_kwargs):
3001 time.sleep(0.35)
3002 return [{"id": "x1"}], None, None
3003
3004 from concurrent.futures import ThreadPoolExecutor
3005 with patch.object(pipeline, "_attempt_x_backend", side_effect=slow_backend) as backend, \
3006 ThreadPoolExecutor(max_workers=2) as pool:
3007 futures = [
3008 pool.submit(
3009 pipeline._attempt_x_backend_memo,
3010 "bird", "ghostty", *_MEMO_RANGE, "default", {}, deadline=deadline,
3011 )
3012 for _ in range(2)
3013 ]
3014 results = [future.result(timeout=10) for future in futures]
3015 assert backend.call_count == 1
3016 assert all(items == [{"id": "x1"}] and err is None for items, err, _ in results)
3017
3018 def test_x_waiter_timeout_is_a_chain_error_not_an_exception(self):
3019 deadline = time.monotonic() + 0.1
3020
3021 def hung_backend(*_args, **_kwargs):
3022 time.sleep(0.6)
3023 return [{"id": "x1"}], None, None
3024
3025 from concurrent.futures import ThreadPoolExecutor
3026 with patch.object(pipeline, "_attempt_x_backend", side_effect=hung_backend), \
3027 patch.object(pipeline, "_X_MEMO_WAIT_GRACE_SECONDS", 0.1), \
3028 ThreadPoolExecutor(max_workers=2) as pool:
3029 owner = pool.submit(
3030 pipeline._attempt_x_backend_memo,
3031 "bird", "ghostty", *_MEMO_RANGE, "default", {}, deadline=deadline,
3032 )
3033 time.sleep(0.05)
3034 waiter = pool.submit(
3035 pipeline._attempt_x_backend_memo,
3036 "bird", "ghostty", *_MEMO_RANGE, "default", {}, deadline=deadline,
3037 )
3038 items, err, err_state = waiter.result(timeout=10)
3039 owner.result(timeout=10)
3040 assert items == [] and err
3041 assert err_state == health.TIMEOUT
3042
3043 def test_youtube_memo_is_keyed_by_freshness_mode(self):
3044 [subquery] = _memo_subqueries(["youtube"], labels=("price",))
3045 with patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload) as yt_search, \
3046 patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
3047 patch("lib.env.is_youtube_comments_available", return_value=False):
3048 _memo_stream("youtube", subquery, {}, freshness_mode="evergreen_ok")
3049 _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
3050 _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
3051 assert yt_search.call_count == 2
3052 assert [c.kwargs["freshness_mode"] for c in yt_search.call_args_list] == [
3053 "evergreen_ok", "balanced_recent",
3054 ]
3055
3056 def _thin_youtube_retry(self, config):
3057 plan = schema.QueryPlan(
3058 intent="general", freshness_mode="balanced_recent", cluster_mode="topic",
3059 raw_topic=_MEMO_TOPIC, subqueries=_memo_subqueries(["youtube"]),
3060 source_weights={"youtube": 1.0},
3061 )
3062 pipeline._retry_thin_sources(
3063 topic=_MEMO_TOPIC, bundle=schema.RetrievalBundle(), plan=plan,
3064 config=config, depth="default", date_range=_MEMO_RANGE,
3065 runtime=_make_runtime(None), mock=False, rate_limited_sources=set(),
3066 rate_limit_lock=threading.Lock(), settings={"per_stream_limit": 20},
3067 )
3068
3069 def test_thin_retry_after_clean_youtube_fetch_makes_no_network_call(self):
3070 [subquery] = _memo_subqueries(["youtube"], labels=("price",))
3071 with patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
3072 patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload) as yt_search, \
3073 patch("lib.env.is_youtube_comments_available", return_value=False):
3074 # Same run, same plan freshness mode as the retry.
3075 _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
3076 self._thin_youtube_retry({})
3077 assert yt_search.call_count == 1
3078
3079 def test_thin_retry_after_failed_youtube_fetch_refetches(self):
3080 [subquery] = _memo_subqueries(["youtube"], labels=("price",))
3081 responses = [{"items": [], "error": "yt-dlp search timed out"}, _youtube_payload()]
3082 with patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
3083 patch("lib.youtube_yt.search_and_transcribe", side_effect=responses) as yt_search, \
3084 patch("lib.env.is_youtube_comments_available", return_value=False):
3085 _items, artifact = _memo_stream("youtube", subquery, {}, freshness_mode="balanced_recent")
3086 assert artifact["_source_outcome"]["state"] == health.TIMEOUT
3087 self._thin_youtube_retry({})
3088 assert yt_search.call_count == 2
3089
3090 def _thin_retry(self, source):
3091 plan = schema.QueryPlan(
3092 intent="general", freshness_mode="balanced_recent", cluster_mode="topic",
3093 raw_topic=_MEMO_TOPIC,
3094 subqueries=[_raw_topic_subquery(source)],
3095 source_weights={source: 1.0},
3096 )
3097 pipeline._retry_thin_sources(
3098 topic=_MEMO_TOPIC, bundle=schema.RetrievalBundle(), plan=plan,
3099 config={}, depth="default", date_range=_MEMO_RANGE,
3100 runtime=_make_runtime(None), mock=False, rate_limited_sources=set(),
3101 rate_limit_lock=threading.Lock(), settings={"per_stream_limit": 20},
3102 )
3103
3104 @pytest.mark.parametrize("source, target", [
3105 ("polymarket", "lib.polymarket.search_polymarket"),
3106 ("digg", "lib.digg.search_digg"),
3107 ])
3108 def test_thin_retry_reuses_clean_raw_topic_fetch(self, source, target):
3109 # Live runs: the planner's subquery searches the raw topic, the thin
3110 # retry's core subject is the same string, so the request repeated.
3111 empty = {"events": [], "results": []}
3112 with patch(target, return_value=empty) as search:
3113 _memo_stream(source, _raw_topic_subquery(source), {})
3114 self._thin_retry(source)
3115 assert search.call_count == 1
3116
3117 @pytest.mark.parametrize("source, target", [
3118 ("polymarket", "lib.polymarket.search_polymarket"),
3119 ("digg", "lib.digg.search_digg"),
3120 ])
3121 def test_thin_retry_refetches_after_failed_fetch(self, source, target):
3122 failed = {"events": [], "results": [], "error": "HTTP 503"}
3123 with patch(target, side_effect=[failed, {"events": [], "results": []}]) as search:
3124 _items, artifact = _memo_stream(source, _raw_topic_subquery(source), {})
3125 assert artifact.get("_source_outcome")
3126 self._thin_retry(source)
3127 assert search.call_count == 2
3128
3129 def test_different_digg_queries_fetch_separately(self):
3130 with patch("lib.digg.search_digg", return_value={"events": [], "results": []}) as search:
3131 for subquery in _memo_subqueries(["digg"], labels=("price", "speed")):
3132 _memo_stream("digg", subquery, {})
3133 assert search.call_count == 2
3134
3135 def test_polymarket_searches_the_run_topic_once_across_subqueries(self):
3136 hints = {"kind": "product", "aliases": ["Ghostty"], "related": []}
3137 with patch("lib.polymarket.search_polymarket", return_value={"events": []}) as search:
3138 for subquery in _memo_subqueries(["polymarket"], labels=("price", "speed")):
3139 _memo_stream("polymarket", subquery, {"_polymarket_hints": hints})
3140 assert search.call_count == 1
3141 args, kwargs = search.call_args
3142 assert args[0] == _MEMO_TOPIC
3143 assert kwargs["hints"] == polymarket.PolymarketHints.coerce(hints)
3144
3145 def test_x_backend_fetched_once_and_each_subquery_judged_with_its_own_ranking_query(self):
3146 subqueries = _memo_subqueries(["x"], labels=("price", "speed"))
3147 posts = [{
3148 "id": "X1", "text": "ghostty terminal is fast", "author_handle": "dev",
3149 "url": "https://x.com/dev/status/1", "date": "2026-10-01",
3150 }]
3151 judged_with: list[str] = []
3152
3153 def _judge(items, _topic, *, ranking_query=""):
3154 judged_with.append(ranking_query)
3155 return {"on_topic_items": list(items), "on_topic_ratio": 1.0}
3156
3157 with patch("lib.env.x_backend_chain", return_value=["bird"]), \
3158 patch("lib.pipeline._fetch_x_backend", return_value=(posts, "")) as fetch, \
3159 patch("lib.x_judge.should_retry_x_search", return_value=False), \
3160 patch("lib.x_judge.judge_x_corpus", side_effect=_judge):
3161 results = [_memo_stream("x", subquery, {}) for subquery in subqueries]
3162
3163 assert fetch.call_count == 1
3164 assert sorted(judged_with) == sorted(sq.ranking_query for sq in subqueries)
3165 assert all(len(items) == 1 for items, _artifact in results)
3166
3167 def _parity_report(self):
3168 plan = {
3169 "intent": "general", "freshness_mode": "balanced_recent", "cluster_mode": "story",
3170 "subqueries": [
3171 {"label": sq.label, "search_query": sq.search_query,
3172 "ranking_query": sq.ranking_query, "sources": list(sq.sources)}
3173 for sq in _memo_subqueries(["tiktok", "instagram", "youtube"])
3174 ],
3175 }
3176 with patch("lib.tiktok.search_and_enrich", side_effect=_tiktok_payload), \
3177 patch("lib.instagram.search_and_enrich", side_effect=_instagram_payload), \
3178 patch("lib.youtube_yt.search_and_transcribe", side_effect=_youtube_payload), \
3179 patch("lib.youtube_yt.search_youtube_sc", return_value={"items": []}), \
3180 patch("lib.youtube_yt.backfill_transcripts"), \
3181 patch("lib.pipeline.which", return_value="/usr/bin/yt-dlp"), \
3182 patch("lib.env.is_youtube_comments_available", return_value=False), \
3183 patch("lib.tiktok.enrich_with_comments"), \
3184 patch("lib.instagram.enrich_with_comments"):
3185 return pipeline.run(
3186 topic=_MEMO_TOPIC, config=dict(_MEMO_SC_CONFIG), depth="default",
3187 requested_sources=["tiktok", "instagram", "youtube"], mock=False,
3188 external_plan=plan, web_backend="none", save_dir="",
3189 )
3190
3191 def test_report_parity_with_memo_bypassed(self):
3192 from lib import fetch_memo
3193
3194 def _summary(report):
3195 return (
3196 {source: sorted(item.url for item in items)
3197 for source, items in report.items_by_source.items()},
3198 {source: outcome.state for source, outcome in report.source_status.items()},
3199 sorted(report.errors_by_source),
3200 [candidate.url for candidate in report.ranked_candidates],
3201 )
3202
3203 memoized = _summary(self._parity_report())
3204 fetch_memo.reset()
3205 with patch("lib.fetch_memo.fetch_once",
3206 side_effect=lambda _key, fetch, **_kwargs: fetch()):
3207 bypassed = _summary(self._parity_report())
3208
3209 assert memoized == bypassed
3210 assert set(memoized[0]) == {"tiktok", "instagram", "youtube"}
3211
3212
3213 if __name__ == "__main__":
3214 unittest.main()
3215
3216
3217 _DIGG_ARTICLE = "https://example-observatory.org/news/webb-water"
3218
3219
3220 _DIGG_STORY_SCORES = [150, 1286, 239, 473, 180, 610, 95, 820, 330, 77, 560, 205, 444, 68, 915]
3221
3222
3223 def _digg_story_rows(count: int = 5, ordinary: int = 0) -> list[dict]:
3224 """``count`` stories that name the topic in their title and are big enough
3225 to be prominent, then ``ordinary`` ones that name it in their title too
3226 and have a higher Digg Score, with too few sources to be prominent."""
3227 from lib import digg
3228
3229 subjects = [
3230 "orbit measured", "water vapor found", "funding approved",
3231 "mirror alignment finished", "naming contest opened",
3232 ]
3233 rows = [
3234 {
3235 "clusterId": f"11111111-2222-3333-4444-{n:012d}",
3236 "clusterUrlId": f"story{n}",
3237 "url": f"https://digg.com/science/story{n}",
3238 "topic": "science",
3239 "title": f"Webb telescope exoplanet {subject}",
3240 "tldr": f"Astronomers report on the exoplanet's {subject}.",
3241 "diggScore": score,
3242 "sourceCount": 37,
3243 "postCount": 37,
3244 "uniqueAuthors": 29,
3245 "publishedAt": "2026-11-08T15:02:00Z",
3246 "firstPostAge": "3d",
3247 }
3248 for n, score in enumerate(_DIGG_STORY_SCORES[:count], start=1)
3249 for subject in [subjects[n - 1] if n <= len(subjects) else f"finding {n} published"]
3250 ]
3251 rows += [
3252 {
3253 "clusterId": f"99999999-2222-3333-4444-{n:012d}",
3254 "clusterUrlId": f"survey{n}",
3255 "url": f"https://digg.com/science/survey{n}",
3256 "topic": "science",
3257 "title": f"Sky survey part {n} covers Webb telescope exoplanet",
3258 "tldr": "The survey lists a new exoplanet.",
3259 "diggScore": 2000 + n,
3260 "sourceCount": 3,
3261 "postCount": 3,
3262 "uniqueAuthors": 3,
3263 "publishedAt": "2026-11-08T15:02:00Z",
3264 "firstPostAge": "3d",
3265 }
3266 for n in range(1, ordinary + 1)
3267 ]
3268 return digg.parse_digg_response(
3269 {"results": rows}, query="webb telescope exoplanet", from_date="2026-10-12",
3270 )
3271
3272
3273 def _hn_row(n: int, title: str, url: str) -> dict:
3274 return {
3275 "id": f"HN{n}",
3276 "title": title,
3277 "url": url,
3278 "hn_url": f"https://news.ycombinator.com/item?id=4590000{n}",
3279 "author": f"reader{n}",
3280 "date": "2026-11-09",
3281 "engagement": {"points": 120, "comments": 40},
3282 "relevance": 0.8,
3283 "why_relevant": "fixture",
3284 }
3285
3286
3287 class DiggStoryConfirmationRunTests(unittest.TestCase):
3288 """A Digg story's sources mark matching items from other sources in a run."""
3289
3290 # The top-scored story (story2, Digg Score 1286) lists the article one
3291 # Hacker News item links to.
3292 TOP_STORY = "11111111-2222-3333-4444-000000000002"
3293
3294 def _run(
3295 self, depth: str, cli, *, supplemental=None, digg_only_on_retry=False, digg_rows=None,
3296 ):
3297 def fake_retrieve(**kwargs):
3298 if kwargs["source"] == "digg":
3299 if digg_only_on_retry and kwargs["subquery"].label != "retry":
3300 return [], {}
3301 return (digg_rows if digg_rows is not None else _digg_story_rows()), {}
3302 if kwargs["source"] == "hackernews":
3303 return [
3304 _hn_row(
3305 1, "Webb telescope finds water vapor on a rocky exoplanet",
3306 "https://www.example-observatory.org/news/webb-water/",
3307 ),
3308 _hn_row(
3309 2, "Exoplanet survey budget for the Webb telescope team",
3310 "https://example-observatory.org/news/another-story",
3311 ),
3312 ], {}
3313 return [], {}
3314
3315 patches = [
3316 patch.object(pipeline, "_retrieve_stream", side_effect=fake_retrieve),
3317 patch("lib.digg.shutil.which", return_value="/fake/digg-pp-cli"),
3318 patch("lib.digg.subproc.run_with_timeout", side_effect=cli),
3319 ]
3320 if supplemental is not None:
3321 patches.append(patch.object(pipeline, "_run_supplemental_searches", side_effect=supplemental))
3322 for active in patches:
3323 active.start()
3324 self.addCleanup(active.stop)
3325 return pipeline.run(
3326 topic="webb telescope exoplanet", config={}, depth=depth, mock=True,
3327 requested_sources=["digg", "hackernews"], web_backend="none",
3328 as_of_date="2026-11-11",
3329 )
3330
3331 def _cli(self, calls: list):
3332 import json as _json
3333
3334 def run(cmd, *, timeout, **_bounds):
3335 calls.append(list(cmd))
3336 rows = []
3337 if cmd[-1] == self.TOP_STORY:
3338 rows = [
3339 {
3340 "kind": "webpage", "body": "", "xUrl": _DIGG_ARTICLE,
3341 "title": "Webb finds water", "author": {"display_name": "Example Observatory"},
3342 },
3343 {
3344 "kind": "x", "body": "Water vapor on a rocky world.",
3345 "xUrl": "https://x.com/astro_ana/status/1986000000000000001",
3346 "author": {"username": "astro_ana", "display_name": "Ana"},
3347 },
3348 ]
3349 return subproc.SubprocResult(
3350 returncode=0, stdout=_json.dumps({"meta": {}, "results": rows}), stderr="",
3351 )
3352
3353 return run
3354
3355 @staticmethod
3356 def _hn(report):
3357 return {
3358 candidate.source_items[0].item_id: candidate
3359 for candidate in report.ranked_candidates
3360 if candidate.source == "hackernews"
3361 }
3362
3363 def test_default_run_marks_the_matching_item_within_the_story_call_budget(self):
3364 calls: list = []
3365 report = self._run("default", self._cli(calls))
3366
3367 hn = self._hn(report)
3368 self.assertEqual(
3369 "https://digg.com/science/story2", hn["HN1"].metadata["digg_story"]["url"],
3370 )
3371 self.assertNotIn("digg_story", hn["HN2"].metadata)
3372 unmarked = dataclasses.replace(hn["HN1"], metadata={
3373 key: value for key, value in hn["HN1"].metadata.items() if key != "digg_story"
3374 })
3375 self.assertGreater(hn["HN1"].final_score, rerank._final_score(unmarked))
3376 self.assertEqual(5, len(calls))
3377 for call in calls:
3378 self.assertEqual(["digg-pp-cli", "posts", "--agent", "--limit", "40", "--"], call[:-1])
3379 self.assertIn(self.TOP_STORY, [call[-1] for call in calls])
3380 top_story = next(
3381 item for item in report.items_by_source["digg"] if item.item_id == "story2"
3382 )
3383 self.assertEqual(["astro_ana"], [post["username"] for post in top_story.metadata["posts"]])
3384
3385 def test_stories_found_only_by_the_retry_search_mark_the_matching_item(self):
3386 calls: list = []
3387 report = self._run("default", self._cli(calls), digg_only_on_retry=True)
3388
3389 self.assertEqual(5, len(calls))
3390 self.assertIn(self.TOP_STORY, [call[-1] for call in calls])
3391 self.assertEqual(
3392 "https://digg.com/science/story2",
3393 self._hn(report)["HN1"].metadata["digg_story"]["url"],
3394 )
3395 top_story = next(
3396 item for item in report.items_by_source["digg"] if item.item_id == "story2"
3397 )
3398 self.assertEqual(["astro_ana"], [post["username"] for post in top_story.metadata["posts"]])
3399
3400 def test_story_the_subject_prune_could_remove_does_not_confirm(self):
3401 # The prune runs after reranking, and the confirmation feeds the
3402 # rerank score, so a story that is not certain to survive it is left
3403 # out of the confirmations up front.
3404 calls: list = []
3405 escapes = rerank.escapes_entity_miss_prune
3406 with patch.object(
3407 rerank, "escapes_entity_miss_prune",
3408 side_effect=lambda candidate, *, topic: (
3409 candidate.source != "digg" and escapes(candidate, topic=topic)
3410 ),
3411 ):
3412 report = self._run("default", self._cli(calls))
3413
3414 self.assertEqual(5, len(calls))
3415 self.assertFalse([c for c in report.ranked_candidates if "digg_story" in c.metadata])
3416
3417 def test_story_sources_are_fetched_before_supplemental_search(self):
3418 calls: list = []
3419 seen_at_supplemental: list[int] = []
3420 self._run(
3421 "default", self._cli(calls),
3422 supplemental=lambda **_kwargs: seen_at_supplemental.append(len(calls)),
3423 )
3424 self.assertEqual([5], seen_at_supplemental)
3425 self.assertEqual(5, len(calls))
3426
3427 def test_quick_run_fetches_no_story_sources(self):
3428 calls: list = []
3429 report = self._run("quick", self._cli(calls))
3430 self.assertEqual([], calls)
3431 self.assertTrue(report.items_by_source["digg"])
3432 self.assertFalse([c for c in report.ranked_candidates if "digg_story" in c.metadata])
3433
3434 def test_ordinary_story_citing_a_result_does_not_confirm_it(self):
3435 # The highest-scored story names the topic in its title and has too
3436 # few sources to be prominent. It lists the article a Hacker News item
3437 # links to, and no other story does.
3438 import json as _json
3439
3440 calls: list = []
3441 article = {
3442 "kind": "webpage", "body": "", "xUrl": _DIGG_ARTICLE,
3443 "title": "Webb finds water", "author": {"display_name": "Example Observatory"},
3444 }
3445
3446 def cli(cmd, *, timeout, **_bounds):
3447 calls.append(cmd[-1])
3448 rows = [article] if cmd[-1].startswith("99999999") else []
3449 return subproc.SubprocResult(
3450 returncode=0, stdout=_json.dumps({"meta": {}, "results": rows}), stderr="",
3451 )
3452
3453 report = self._run("default", cli, digg_rows=_digg_story_rows(ordinary=1))
3454
3455 self.assertIn("survey1", [item.item_id for item in report.items_by_source["digg"]])
3456 self.assertEqual(5, len(calls))
3457 self.assertFalse([call for call in calls if call.startswith("99999999")])
3458 self.assertFalse([c for c in report.ranked_candidates if "digg_story" in c.metadata])
3459
3460 def _story_bundle(self, count: int = 5, ordinary: int = 0):
3461 from lib import normalize
3462
3463 stories = normalize.normalize_source_items(
3464 "digg", _digg_story_rows(count, ordinary), "2026-10-12", "2026-11-11",
3465 )
3466 return schema.RetrievalBundle(items_by_source={"digg": stories})
3467
3468 def _fetch_sources(self, config, seen: list, *, bundle=None, depth: str = "default"):
3469 def run(cmd, *, timeout, **kwargs):
3470 seen.append({"story": cmd[-1], "timeout": timeout, **kwargs})
3471 return subproc.SubprocResult(returncode=0, stdout='{"results": []}', stderr="")
3472
3473 with patch("lib.digg.shutil.which", return_value="/fake/digg-pp-cli"), \
3474 patch("lib.digg.subproc.run_with_timeout", side_effect=run):
3475 return pipeline._digg_story_sources(
3476 bundle if bundle is not None else self._story_bundle(),
3477 topic="webb telescope exoplanet", depth=depth, config=config,
3478 )
3479
3480 @staticmethod
3481 def _top_scored(bundle, count: int) -> set[str]:
3482 """UUIDs of the ``count`` highest-scored stories that name the topic
3483 in their title."""
3484 prominent = [
3485 item for item in bundle.items_by_source["digg"]
3486 if item.title.startswith("Webb telescope exoplanet")
3487 ]
3488 prominent.sort(key=lambda item: -item.engagement["digg_score"])
3489 return {item.metadata["clusterId"] for item in prominent[:count]}
3490
3491 def test_default_run_reads_the_eight_highest_scored_prominent_stories(self):
3492 seen: list = []
3493 bundle = self._story_bundle(10, ordinary=5)
3494 self._fetch_sources({}, seen, bundle=bundle)
3495 self.assertEqual(8, len(seen))
3496 self.assertEqual(self._top_scored(bundle, 8), {call["story"] for call in seen})
3497
3498 def test_run_with_two_prominent_stories_reads_two(self):
3499 seen: list = []
3500 self._fetch_sources({}, seen, bundle=self._story_bundle(2, ordinary=5))
3501 self.assertEqual(2, len(seen))
3502
3503 def test_run_with_no_prominent_story_reads_and_confirms_nothing(self):
3504 seen: list = []
3505 stories = self._fetch_sources({}, seen, bundle=self._story_bundle(0, ordinary=5))
3506 self.assertEqual([], seen)
3507 self.assertEqual({}, stories)
3508
3509 def test_deep_run_reads_twelve_prominent_stories(self):
3510 seen: list = []
3511 bundle = self._story_bundle(15)
3512 self._fetch_sources({}, seen, bundle=bundle, depth="deep")
3513 self.assertEqual(12, len(seen))
3514 self.assertEqual(self._top_scored(bundle, 12), {call["story"] for call in seen})
3515
3516 def test_story_source_calls_carry_the_run_deadline_and_cancel_signal(self):
3517 seen: list = []
3518 cancel = threading.Event()
3519 deadline = time.monotonic() + 2
3520 self._fetch_sources({"_research_deadline": deadline, "_enrich_cancel": cancel}, seen)
3521 self.assertEqual(5, len(seen))
3522 for call in seen:
3523 self.assertLessEqual(call["timeout"], 2)
3524 self.assertEqual(deadline, call["deadline_monotonic"])
3525 self.assertIs(cancel, call["cancel"])
3526
3527 def test_story_source_calls_get_a_deadline_when_the_run_config_has_none(self):
3528 # A hosted run keeps its retrieval deadline on a copy of the config,
3529 # so this call sees none. It still must not start an open-ended fetch.
3530 seen: list = []
3531 before = time.monotonic()
3532 self._fetch_sources({}, seen)
3533 self.assertEqual(5, len(seen))
3534 for call in seen:
3535 self.assertIsNotNone(call["deadline_monotonic"])
3536 self.assertLessEqual(call["deadline_monotonic"], time.monotonic() + 40)
3537 self.assertGreaterEqual(call["deadline_monotonic"], before)
3538
3539 def test_three_entity_comparison_reads_three_stories_per_run(self):
3540 seen: list = []
3541 self._fetch_sources({"_comparison_entity_count": 3}, seen)
3542 self.assertEqual(3, len(seen))
3543
3544 def _second_pass_calls(
3545 self, first_count: int, *, total: int = 5, first_ordinary: int = 0,
3546 depth: str = "default", call_seconds: float = 0, timeouts_out: list | None = None,
3547 ) -> list:
3548 """Story UUIDs a pass after the retry reads, given how many prominent
3549 stories (and ordinary ones) the first pass held; the rest of ``total``
3550 arrive from the retry. Each call takes ``call_seconds`` on a fake
3551 clock, one call at a time so the seconds add up."""
3552 calls: list = []
3553 timeouts: list = []
3554 bundle = self._story_bundle(total, first_ordinary)
3555 stories = bundle.items_by_source["digg"]
3556 bundle.items_by_source["digg"] = stories[:first_count] + stories[total:]
3557 spent = pipeline._DiggSourcesSpent()
3558 clock = [1000.0]
3559
3560 def slow_run(cmd, *, timeout, **kwargs):
3561 calls.append(cmd[-1])
3562 timeouts.append(timeout)
3563 clock[0] += call_seconds
3564 return subproc.SubprocResult(returncode=0, stdout='{"results": []}', stderr="")
3565
3566 patches = [
3567 patch("lib.digg.shutil.which", return_value="/fake/digg-pp-cli"),
3568 patch("lib.digg.subproc.run_with_timeout", side_effect=slow_run),
3569 ]
3570 if call_seconds:
3571 patches += [
3572 patch("lib.digg.SOURCES_CONCURRENCY", 1),
3573 patch("lib.digg.time.monotonic", side_effect=lambda: clock[0]),
3574 ]
3575 with contextlib.ExitStack() as stack:
3576 for active in patches:
3577 stack.enter_context(active)
3578 pipeline._digg_story_sources(
3579 bundle, topic="webb telescope exoplanet", depth=depth, config={}, spent=spent,
3580 )
3581 first_calls = len(calls)
3582 bundle.items_by_source["digg"] = stories
3583 pipeline._digg_story_sources(
3584 bundle, topic="webb telescope exoplanet", depth=depth, config={}, spent=spent,
3585 )
3586 self.assertEqual(first_count, first_calls)
3587 if timeouts_out is not None:
3588 timeouts_out.extend(timeouts[first_calls:])
3589 return calls[first_calls:]
3590
3591 def test_retry_pass_gets_only_the_time_the_first_pass_left(self):
3592 # Two first-pass calls of 15s each leave 10s of the 40s allowance.
3593 timeouts: list = []
3594 calls = self._second_pass_calls(2, depth="deep", call_seconds=15, timeouts_out=timeouts)
3595 self.assertEqual(1, len(calls))
3596 self.assertLessEqual(timeouts[0], 10)
3597
3598 def test_retry_pass_fetches_nothing_once_the_time_is_spent(self):
3599 self.assertEqual([], self._second_pass_calls(2, depth="deep", call_seconds=20))
3600
3601 def test_stories_found_only_by_the_retry_get_their_sources_fetched(self):
3602 self.assertEqual(5, len(self._second_pass_calls(0)))
3603
3604 def test_retry_pass_spends_only_the_budget_the_first_pass_left(self):
3605 # Five of the eight were offered to the first pass.
3606 bundle = self._story_bundle(11)
3607 stories = bundle.items_by_source["digg"]
3608 bundle.items_by_source["digg"] = stories[5:]
3609 calls = self._second_pass_calls(5, total=11)
3610 self.assertEqual(3, len(calls))
3611 self.assertEqual(self._top_scored(bundle, 3), set(calls))
3612
3613 def test_ordinary_stories_of_the_first_pass_use_none_of_the_budget(self):
3614 calls = self._second_pass_calls(2, total=12, first_ordinary=5)
3615 self.assertEqual(6, len(calls))
3616 self.assertFalse([call for call in calls if call.startswith("99999999")])
3617
3618 def test_retry_pass_fetches_nothing_once_the_budget_is_spent(self):
3619 self.assertEqual([], self._second_pass_calls(8, total=11))
3620
3621 def test_run_completes_untagged_when_the_sources_fetch_times_out(self):
3622 def timing_out(cmd, *, timeout, **_bounds):
3623 raise subproc.SubprocTimeout("posts timed out")
3624
3625 report = self._run("default", timing_out)
3626 self.assertEqual(5, len(report.items_by_source["digg"]))
3627 self.assertTrue(self._hn(report))
3628 self.assertFalse([c for c in report.ranked_candidates if "digg_story" in c.metadata])
3629
3630
3631 class DiggQuoteEnrichmentByCliShapeTests(unittest.TestCase):
3632 """After de-duplication only clusters from digg-pp-cli 2026.10.x fetch quotes."""
3633
3634 def _finalize(self, rows: list[dict]) -> list[list[str]]:
3635 from lib import normalize
3636
3637 calls: list[list[str]] = []
3638
3639 def cli(cmd, *, timeout, env=None, on_pid=None, deadline_monotonic=None, cancel=None):
3640 calls.append(list(cmd))
3641 return subproc.SubprocResult(returncode=0, stdout='{"results": []}', stderr="")
3642
3643 items = normalize.normalize_source_items("digg", rows, "2026-10-12", "2026-11-11")
3644 with patch("lib.digg.shutil.which", return_value="/fake/digg-pp-cli"), \
3645 patch("lib.digg.subproc.run_with_timeout", side_effect=cli):
3646 pipeline._finalize_items_by_source({"digg": items}, topic="exoplanet", config={})
3647 return calls
3648
3649 def test_old_cli_cluster_still_gets_the_ranked_posts_call(self):
3650 calls = self._finalize([{
3651 "id": "abc123xy", "title": "Sample cluster", "url": "https://di.gg/ai/abc123xy",
3652 "tldr": "A short summary.", "date": "2026-11-08",
3653 "engagement": {"postCount": 5, "uniqueAuthors": 3, "rank": 1, "rank_score": 50.0},
3654 "posts": [],
3655 }])
3656 self.assertEqual(
3657 [["digg-pp-cli", "posts", "--agent", "--by", "rank", "--limit", "5", "--", "abc123xy"]],
3658 calls,
3659 )
3660
3661 def test_all_topic_story_gets_no_call_after_deduplication(self):
3662 self.assertEqual([], self._finalize(_digg_story_rows(count=2)))
3663
3664
3665 _BAR_WORDS = (
3666 "harbor lantern orchard glacier violin tractor pepper canyon meadow saddle "
3667 "furnace pelican compass marble thistle walnut anchor bonnet cobalt dynamo "
3668 "ember falcon garnet hammock iguana jasmine kettle lagoon mitten nutmeg"
3669 ).split()
3670
3671
3672 def _bar_words(n: int) -> str:
3673 """Three words that differ enough between stories to survive de-duplication."""
3674 return " ".join(_BAR_WORDS[(n + step) % len(_BAR_WORDS)] for step in (0, 11, 17))
3675
3676
3677 def _digg_bar_rows(specs: list[tuple[str, str, int, int]]) -> list[dict]:
3678 """Parsed all-topic stories from (title, summary, Digg Score, source count)."""
3679 from lib import digg
3680
3681 return digg.parse_digg_response(
3682 {
3683 "results": [
3684 {
3685 "clusterId": f"11111111-2222-3333-4444-{n:012d}",
3686 "clusterUrlId": f"story{n}",
3687 "url": f"https://digg.com/tech/story{n}",
3688 "topic": "tech",
3689 "title": title,
3690 "tldr": summary,
3691 "diggScore": score,
3692 "sourceCount": sources,
3693 "postCount": sources,
3694 "uniqueAuthors": 9,
3695 "publishedAt": "2026-11-08T15:02:00Z",
3696 "firstPostAge": "3d",
3697 }
3698 for n, (title, summary, score, sources) in enumerate(specs, start=1)
3699 ]
3700 },
3701 query="fixture",
3702 from_date="2026-10-12",
3703 )
3704
3705
3706 def _digg_legacy_rows(titles: list[str]) -> list[dict]:
3707 """Clusters in the shape digg-pp-cli 2026.10.x returns: no story UUID."""
3708 return [
3709 {
3710 "id": f"legacy{n}", "title": title, "url": f"https://di.gg/ai/legacy{n}",
3711 "tldr": f"Notes on {_bar_words(n + 5)}.", "date": "2026-11-08",
3712 "engagement": {"postCount": 5, "uniqueAuthors": 3, "rank": n, "rank_score": 51.0 - n},
3713 "posts": [], "relevance": 0.6, "why_relevant": "fixture",
3714 }
3715 for n, title in enumerate(titles, start=1)
3716 ]
3717
3718
3719 def _digg_score_of(item) -> float:
3720 return item.engagement["digg_score"]
3721
3722
3723 class DepthSettingsDiggLimitTests(unittest.TestCase):
3724 def test_digg_keeps_more_stories_per_search_than_the_shared_limit(self):
3725 self.assertEqual(20, pipeline._resolve_depth_settings("default", {})["digg_stream_limit"])
3726 self.assertEqual(30, pipeline._resolve_depth_settings("deep", {})["digg_stream_limit"])
3727 quick = pipeline._resolve_depth_settings("quick", {})
3728 self.assertEqual(quick["per_stream_limit"], quick["digg_stream_limit"])
3729
3730 def test_max_per_source_overrides_the_digg_limit_with_the_shared_one(self):
3731 settings = pipeline._resolve_depth_settings("deep", {"_max_per_source": 5})
3732 self.assertEqual(5, settings["digg_stream_limit"])
3733 self.assertEqual(5, settings["per_stream_limit"])
3734 self.assertEqual(30, pipeline.DEPTH_SETTINGS["deep"]["digg_stream_limit"])
3735
3736
3737 class DiggBarRunTests(unittest.TestCase):
3738 """What a run keeps of each Digg search, and in which order."""
3739
3740 def _run(self, topic: str, digg_rows, *, depth: str = "default", config=None):
3741 """Run with Digg only. ``digg_rows(subquery)`` is what each search returns.
3742
3743 Returns the report, the retrieval bundle and the labels of the Digg
3744 searches made, in order.
3745 """
3746 searches: list[str] = []
3747 bundles: list[schema.RetrievalBundle] = []
3748
3749 def fake_retrieve(**kwargs):
3750 if kwargs["source"] != "digg":
3751 return [], {}
3752 searches.append(kwargs["subquery"].label)
3753 return digg_rows(kwargs["subquery"]), {}
3754
3755 def cli(cmd, *, timeout, **_bounds):
3756 return subproc.SubprocResult(
3757 returncode=0, stdout='{"meta": {}, "results": []}', stderr="",
3758 )
3759
3760 patches = [
3761 patch.object(pipeline, "_retrieve_stream", side_effect=fake_retrieve),
3762 patch("lib.digg.shutil.which", return_value="/fake/digg-pp-cli"),
3763 patch("lib.digg.subproc.run_with_timeout", side_effect=cli),
3764 patch.object(
3765 pipeline, "_run_supplemental_searches",
3766 side_effect=lambda **kwargs: bundles.append(kwargs["bundle"]),
3767 ),
3768 ]
3769 for active in patches:
3770 active.start()
3771 self.addCleanup(active.stop)
3772 report = pipeline.run(
3773 topic=topic, config=dict(config or {}), depth=depth, mock=True,
3774 requested_sources=["digg"], web_backend="none", as_of_date="2026-11-11",
3775 )
3776 return report, bundles[0], searches
3777
3778 @staticmethod
3779 def _stream(bundle, label: str = "primary"):
3780 return bundle.items_by_source_and_query.get((label, "digg"), [])
3781
3782 def test_stories_that_never_name_the_topic_leave_no_results_and_no_second_search(self):
3783 rows = _digg_bar_rows([
3784 (f"Report on {_bar_words(n)}", f"Details about {_bar_words(n + 3)}.", 300, 37)
3785 for n in range(20)
3786 ])
3787 report, _bundle, searches = self._run("Ghostty", lambda _subquery: rows)
3788
3789 self.assertEqual([], report.items_by_source.get("digg", []))
3790 outcome = report.source_status["digg"]
3791 self.assertEqual(schema.NO_RESULTS, outcome.state)
3792 self.assertIn("20 of 20 stories dropped", outcome.detail)
3793 self.assertNotIn("digg", report.errors_by_source)
3794 self.assertEqual(["primary"], searches)
3795
3796 def test_story_the_bar_drops_does_not_displace_its_near_duplicate(self):
3797 # The same event told twice. The copy that names the topic only in
3798 # its summary comes first, and de-duplication keeps the earlier of
3799 # two similar stories, so the bar has to run before it.
3800 summary = (
3801 "OpenAI says its newest model release drew record developer signups "
3802 "in the first week, according to figures the company shared."
3803 )
3804 rows = _digg_bar_rows([
3805 ("Newest model release draws record developer signups in first week", summary, 300, 37),
3806 ("OpenAI newest model release draws record developer signups in first week", summary, 250, 30),
3807 ])
3808 report, bundle, _searches = self._run("OpenAI", lambda _subquery: rows)
3809
3810 self.assertEqual(["story2"], [item.item_id for item in self._stream(bundle)])
3811 self.assertIn("1 of 2 stories dropped", report.source_status["digg"].detail)
3812
3813 def test_prominent_story_is_the_copy_kept_when_two_searches_return_the_same_event(self):
3814 # Each search has one telling of the event, so no single stream
3815 # de-duplicates them. The merged Digg items are de-duplicated again,
3816 # ranked by local score, where the small copy can come first.
3817 summary = (
3818 "OpenAI says its newest model release drew record developer signups "
3819 "in the first week, according to figures the company shared."
3820 )
3821 small = _digg_bar_rows([
3822 ("OpenAI newest model release draws record developer signups in first week", summary, 30, 3),
3823 ])
3824 big = _digg_bar_rows([
3825 ("unused", "unused", 1, 1),
3826 ("OpenAI newest model release draws record developer signups in the first week", summary, 900, 60),
3827 ])[1:]
3828 from lib import normalize
3829
3830 items = [
3831 *normalize.normalize_source_items("digg", small, "2026-10-12", "2026-11-11"),
3832 *normalize.normalize_source_items("digg", big, "2026-10-12", "2026-11-11"),
3833 ]
3834 items[0].local_rank_score, items[1].local_rank_score = 0.9, 0.4
3835
3836 finalized = pipeline._finalize_items_by_source({"digg": items}, topic="OpenAI")
3837
3838 self.assertEqual(["story2"], [item.item_id for item in finalized["digg"]])
3839
3840 def test_quick_run_drops_stories_that_never_name_the_topic(self):
3841 rows = _digg_bar_rows([
3842 (f"Report on {_bar_words(n)}", f"Details about {_bar_words(n + 3)}.", 300, 37)
3843 for n in range(8)
3844 ])
3845 report, _bundle, _searches = self._run("Ghostty", lambda _subquery: rows, depth="quick")
3846
3847 self.assertEqual([], report.items_by_source.get("digg", []))
3848 self.assertEqual(schema.NO_RESULTS, report.source_status["digg"].state)
3849 self.assertIn("8 of 8 stories dropped", report.source_status["digg"].detail)
3850
3851 def test_highest_scored_story_arriving_last_leads_and_survives_the_limit(self):
3852 rows = _digg_bar_rows(
3853 [
3854 (f"OpenAI {_bar_words(n)}", f"Details about {_bar_words(n + 3)}.", 41 + n, 37)
3855 for n in range(29)
3856 ]
3857 + [("OpenAI Releases GPT-6.1 Terra", "The model ships to everyone.", 226, 37)]
3858 )
3859 _report, bundle, _searches = self._run("OpenAI", lambda _subquery: rows)
3860
3861 stream = self._stream(bundle)
3862 self.assertEqual("OpenAI Releases GPT-6.1 Terra", stream[0].title)
3863 self.assertEqual([226] + list(range(69, 50, -1)), [_digg_score_of(item) for item in stream])
3864
3865 def test_prominent_stories_lead_and_ordinary_ones_keep_their_order(self):
3866 rows = _digg_bar_rows([
3867 # Ordinary: the title names OpenAI, with too few sources.
3868 ("OpenAI hires a lab director", "The former executive starts next month.", 92, 3),
3869 ("OpenAI opens a harbor office", "Staff move in next month.", 50, 10),
3870 # Ordinary: the title names OpenAI, with too low a Digg Score.
3871 ("OpenAI: the most relevant recent evidence from the last 30 days", "A digest.", 39, 37),
3872 ("OpenAI signs an orchard deal", "The largest of the year.", 300, 37),
3873 ("Maine fishing season opens", "Anglers head out.", 652, 37),
3874 ("Glacier survey finishes early on OpenAI compute", "The team thanked its sponsor.", 500, 4),
3875 # Dropped: big, and names OpenAI only in its summary.
3876 ("Kevin Weil launches Warp Sciences", "The former OpenAI executive starts a lab.", 700, 37),
3877 ])
3878 report, bundle, _searches = self._run("OpenAI", lambda _subquery: rows)
3879
3880 stream = self._stream(bundle)
3881 self.assertEqual(["story4", "story2"], [item.item_id for item in stream[:2]])
3882 ordinary = stream[2:]
3883 self.assertEqual({"story1", "story3", "story6"}, {item.item_id for item in ordinary})
3884 self.assertEqual(
3885 sorted(ordinary, key=lambda item: item.local_rank_score or 0.0, reverse=True),
3886 ordinary,
3887 )
3888 self.assertNotEqual(
3889 sorted(ordinary, key=_digg_score_of, reverse=True), ordinary,
3890 "ordinary stories must not be ordered by Digg Score",
3891 )
3892 self.assertIn("2 of 7 stories dropped", report.source_status["digg"].detail)
3893 self.assertEqual(health.OK, report.source_status["digg"].state)
3894
3895 def test_empty_search_is_still_retried_with_the_core_subject(self):
3896 _report, _bundle, searches = self._run("OpenAI", lambda _subquery: [])
3897 self.assertEqual(["primary", "retry"], searches)
3898
3899 def test_retry_search_goes_through_the_bar_too(self):
3900 rows = _digg_bar_rows([
3901 ("Kevin Weil launches Warp Sciences", "The former OpenAI executive starts a lab.", 92, 37),
3902 ("Maine fishing season opens", "Anglers head out.", 652, 37),
3903 ("OpenAI hires a lab director", "The former executive starts next month.", 900, 3),
3904 ("OpenAI signs an orchard deal", "The largest of the year.", 300, 37),
3905 ])
3906 report, bundle, searches = self._run(
3907 "OpenAI", lambda subquery: rows if subquery.label == "retry" else [],
3908 )
3909
3910 self.assertEqual(["primary", "retry"], searches)
3911 self.assertEqual(
3912 ["story4", "story3"], [item.item_id for item in bundle.items_by_source["digg"]],
3913 )
3914 self.assertIn("2 of 4 stories dropped", report.source_status["digg"].detail)
3915
3916 def test_max_per_source_caps_digg_stories(self):
3917 rows = _digg_bar_rows([
3918 (f"OpenAI {_bar_words(n)}", f"Details about {_bar_words(n + 3)}.", 41 + n, 37)
3919 for n in range(10)
3920 ])
3921 _report, bundle, _searches = self._run(
3922 "OpenAI", lambda _subquery: rows, config={"_max_per_source": 5},
3923 )
3924 self.assertEqual([50, 49, 48, 47, 46], [_digg_score_of(item) for item in self._stream(bundle)])
3925
3926 def test_capability_search_keeps_its_stories_in_the_order_they_ranked(self):
3927 # The capability searches of an enablement plan leave the named tool
3928 # out on purpose, so their stories are not held to naming the topic.
3929 rows = _digg_bar_rows(
3930 [("Grok bot gains computer control tools", "A guide to the MCP servers.", 50, 10)]
3931 + [
3932 (f"MCP server for {_bar_words(n)}", f"Agents get {_bar_words(n + 3)}.", 20, 3)
3933 for n in range(12)
3934 ]
3935 + [("Grok expands", "A funding round.", 900, 37)]
3936 )
3937 report, bundle, _searches = self._run(
3938 "best Grok AI bot to control my computer",
3939 lambda subquery: rows if subquery.label == "capability-1" else [],
3940 )
3941
3942 stream = self._stream(bundle, "capability-1")
3943 self.assertEqual(14, len(stream))
3944 self.assertEqual(
3945 sorted(stream, key=lambda item: item.local_rank_score or 0.0, reverse=True), stream,
3946 )
3947 self.assertNotEqual("Grok expands", stream[0].title)
3948 self.assertNotIn("dropped", report.source_status["digg"].detail or "")
3949
3950 def test_old_cli_clusters_keep_the_shared_limit_and_are_not_judged(self):
3951 rows = _digg_legacy_rows([f"Report on {_bar_words(n)}" for n in range(15)])
3952 report, bundle, _searches = self._run("Ghostty", lambda _subquery: rows)
3953
3954 self.assertEqual(
3955 pipeline.DEPTH_SETTINGS["default"]["per_stream_limit"], len(self._stream(bundle)),
3956 )
3957 self.assertNotIn("dropped", report.source_status["digg"].detail or "")
3958
3959
3960 class DiggRelevanceFloorTests(unittest.TestCase):
3961 """Which Digg items the shared relevance floor still judges."""
3962
3963 RANKING_QUERY = (
3964 "Which noise cancelling headphones compare best on battery comfort and price, "
3965 "and what did OpenAI announce?"
3966 )
3967
3968 def _kept(self, rows: list[dict]) -> list[str]:
3969 return [
3970 item.item_id
3971 for item in pipeline._normalize_score_dedupe(
3972 "digg", rows, "2026-10-12", "2026-11-11",
3973 freshness_mode="balanced_recent", ranking_query=self.RANKING_QUERY,
3974 )
3975 ]
3976
3977 def test_story_naming_the_topic_is_kept_below_the_shared_floor(self):
3978 rows = _digg_bar_rows(
3979 [("Noise cancelling headphones compared on battery, comfort and price", "A review.", 50, 10)]
3980 + [(f"Report on {_bar_words(n)}", f"Details about {_bar_words(n + 3)}.", 5, 2) for n in range(40)]
3981 + [("OpenAI device teased", "A short clip.", 226, 37)]
3982 )
3983 self.assertIn("story42", self._kept(rows))
3984
3985 def test_old_cli_cluster_below_the_shared_floor_is_still_pruned(self):
3986 rows = _digg_legacy_rows(
3987 ["Noise cancelling headphones compared on battery, comfort and price"]
3988 + [f"Report on {_bar_words(n)}" for n in range(3)]
3989 )
3990 for row in rows[1:]:
3991 row["relevance"] = 0.05
3992 self.assertEqual(["legacy1"], self._kept(rows))
3993
3993 lines PYTHON