返回 last30days-skill
test_pr23_pipeline_concurrency_deadlines_mock.py
根目录 / tests / test_pr23_pipeline_concurrency_deadlines_mock.py
1 """Regression tests for PR 23: pipeline concurrency, deadlines, containment & mock isolation.
2
3 Covers HIGH-013, HIGH-015, HIGH-016, HIGH-017, HIGH-018, HIGH-020, HIGH-021, HIGH-024.
4 """
5
6 from __future__ import annotations
7
8 import concurrent.futures
9 import concurrent.futures.thread
10 import contextvars
11 from datetime import date, datetime, timedelta, timezone
12 import json
13 import os
14 from pathlib import Path
15 import queue
16 import subprocess
17 import sys
18 import threading
19 import time
20 from unittest import mock
21
22 import pytest
23
24 from lib import dates, fetch_memo, health, http, jobs, pipeline, schema, x_api, x_envelope
25
26
27 # ---------------------------------------------------------------------------
28 # Helpers
29 # ---------------------------------------------------------------------------
30
31
32 def _make_x_envelope(tmp_path: Path, topic: str, rows: list[dict]) -> x_envelope.Envelope:
33 from_date, to_date = dates.get_date_range(30)
34 payload = {
35 "schema": x_envelope.SCHEMA,
36 "generated_at": datetime.now(timezone.utc).isoformat(),
37 "topic": topic,
38 "window": {"from": from_date, "to": to_date},
39 "provider": "x-connector",
40 "status": "ok",
41 "calls": [{"lane": "topic", "handles": [], "posts": rows}],
42 }
43 path = tmp_path / "x_posts.json"
44 path.write_text(json.dumps(payload), encoding="utf-8")
45 return x_envelope.read(str(path), (from_date, to_date), topic)
46
47
48 def _x_row(index: int, handle: str, text: str, *, likes: int = 20) -> dict:
49 _, to_date = dates.get_date_range(30)
50 day = (date.fromisoformat(to_date) - timedelta(days=1 + (index % 15))).isoformat()
51 when = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc) + timedelta(
52 hours=8 + (index % 12), minutes=(index * 13) % 60
53 )
54 ms = int(when.timestamp() * 1000)
55 snowflake = str(((ms - x_api._SNOWFLAKE_EPOCH_MS) << 22) | (((index + 1) * 104729) & ((1 << 22) - 1)))
56 return {
57 "id": snowflake,
58 "author_handle": handle,
59 "created_at": when.strftime("%Y-%m-%dT%H:%M:%SZ"),
60 "text": text,
61 "likes": likes,
62 "reposts": 2,
63 "replies": 1,
64 "quotes": 0,
65 }
66
67
68 def _stub_report(topic: str) -> schema.Report:
69 return schema.Report(
70 topic=topic,
71 range_from="2026-06-01",
72 range_to="2026-07-01",
73 generated_at="2026-07-01T00:00:00+00:00",
74 provider_runtime=schema.ProviderRuntime(
75 reasoning_provider="local",
76 planner_model="deterministic",
77 rerank_model="local-score",
78 ),
79 query_plan=schema.QueryPlan(
80 intent="factual",
81 freshness_mode="balanced_recent",
82 cluster_mode="none",
83 raw_topic=topic,
84 subqueries=[],
85 source_weights={},
86 ),
87 clusters=[],
88 ranked_candidates=[],
89 items_by_source={},
90 errors_by_source={},
91 )
92
93
94 # ---------------------------------------------------------------------------
95 # HIGH-013: Deterministic single-subquery Phase 1 submission for --x-posts
96 # ---------------------------------------------------------------------------
97
98
99 def test_high013_x_envelope_submits_only_first_x_subquery_deterministically(tmp_path):
100 topic = "ai agents"
101 envelope = _make_x_envelope(
102 tmp_path,
103 topic,
104 [
105 _x_row(0, "alice", "ai agents runtime overview and benchmarks", likes=80),
106 _x_row(1, "bob", "ai agents tooling feedback from production", likes=45),
107 ],
108 )
109 plan = {
110 "intent": "general",
111 "freshness_mode": "balanced_recent",
112 "cluster_mode": "story",
113 "subqueries": [
114 {
115 "label": "primary",
116 "search_query": topic,
117 "ranking_query": f"What are people saying about {topic}?",
118 "sources": ["x"],
119 "weight": 1.0,
120 },
121 {
122 "label": "narrow-angle",
123 "search_query": "quantum toaster recipes",
124 "ranking_query": "quantum toaster recipes",
125 "sources": ["x"],
126 "weight": 0.4,
127 },
128 ],
129 "source_weights": {"x": 1.0},
130 }
131 phase1_labels: list[str] = []
132 original = pipeline._retrieve_stream_impl
133
134 def spy(*args, **kwargs):
135 if kwargs.get("source") == "x":
136 phase1_labels.append(kwargs["subquery"].label)
137 return original(*args, **kwargs)
138
139 with mock.patch("lib.env.x_backend_chain", return_value=[]), \
140 mock.patch("lib.pipeline._retry_thin_sources"), \
141 mock.patch("lib.pipeline._retrieve_stream_impl", side_effect=spy):
142 report = pipeline.run(
143 topic=topic,
144 config={"_max_source_fetches": 5},
145 depth="default",
146 requested_sources=["x"],
147 mock=False,
148 external_plan=plan,
149 x_posts=envelope,
150 web_backend="none",
151 save_dir="",
152 )
153
154 assert phase1_labels == ["primary"]
155 assert len(report.items_by_source["x"]) == 2
156 assert report.source_status["x"].state == health.OK
157
158
159 def test_high013_x_envelope_preserves_combined_stream_limit(tmp_path):
160 topic = "ai agents"
161 onsets = ("br", "k", "pl", "st", "gr", "v", "dr", "sh")
162 vowels = ("a", "e", "i", "o", "u", "ai", "oo")
163 codas = ("n", "x", "lt", "mp", "rd", "sk", "th", "z")
164
165 def word(n: int) -> str:
166 return onsets[n % 8] + vowels[(n // 8) % 7] + codas[(n // 56) % 8]
167
168 rows = [
169 _x_row(i, f"user{i}", f"ai agents {word(i * 3)} {word(i * 3 + 1)} {word(i * 3 + 2)}", likes=100 - i)
170 for i in range(40)
171 ]
172 envelope = _make_x_envelope(tmp_path, topic, rows)
173 plan = {
174 "intent": "general",
175 "freshness_mode": "balanced_recent",
176 "cluster_mode": "story",
177 "subqueries": [
178 {"label": "primary", "search_query": topic, "ranking_query": topic, "sources": ["x"]},
179 {"label": "secondary", "search_query": "agents", "ranking_query": "agents", "sources": ["x"]},
180 ],
181 "source_weights": {"x": 1.0},
182 }
183 with mock.patch("lib.env.x_backend_chain", return_value=[]), \
184 mock.patch("lib.pipeline._retry_thin_sources"):
185 report = pipeline.run(
186 topic=topic,
187 config={"_max_source_fetches": 3},
188 depth="default",
189 requested_sources=["x"],
190 mock=False,
191 external_plan=plan,
192 x_posts=envelope,
193 web_backend="none",
194 save_dir="",
195 )
196
197 # per_stream_limit (12) * _source_fetch_cap("x", {_max_source_fetches: 3}) (3) = 36
198 assert len(report.items_by_source["x"]) == 36
199
200
201 def test_high013_x_envelope_honors_zero_max_source_fetches(tmp_path):
202 topic = "ai agents"
203 envelope = _make_x_envelope(tmp_path, topic, [_x_row(0, "alice", "ai agents launch")])
204 plan = {
205 "intent": "general",
206 "freshness_mode": "balanced_recent",
207 "cluster_mode": "story",
208 "subqueries": [
209 {"label": "primary", "search_query": topic, "ranking_query": topic, "sources": ["x"]},
210 ],
211 "source_weights": {"x": 1.0},
212 }
213 calls: list[str] = []
214 with mock.patch("lib.env.x_backend_chain", return_value=[]), \
215 mock.patch("lib.pipeline._retry_thin_sources"), \
216 mock.patch("lib.pipeline._retrieve_stream", side_effect=lambda **kw: (calls.append(kw["source"]), ([], {}))[1]):
217 pipeline.run(
218 topic=topic,
219 config={"_max_source_fetches": 0},
220 depth="quick",
221 requested_sources=["x"],
222 mock=False,
223 external_plan=plan,
224 x_posts=envelope,
225 web_backend="none",
226 save_dir="",
227 )
228 assert calls == []
229
230
231 # ---------------------------------------------------------------------------
232 # HIGH-015: Rescue done futures & dequeued enrichment reports at deadlines
233 # ---------------------------------------------------------------------------
234
235
236 def test_high015_wait_for_research_rescues_done_futures_past_deadline():
237 f_done = concurrent.futures.Future()
238 f_done.set_result("completed-at-boundary")
239 f_pending = concurrent.futures.Future()
240 f_cancelled = concurrent.futures.Future()
241 f_cancelled.cancel()
242
243 config = {"_research_deadline": time.monotonic() - 1.0}
244 done, pending = pipeline._wait_for_research([f_done, f_pending, f_cancelled], config)
245
246 assert done == {f_done}
247 assert pending == {f_pending, f_cancelled}
248
249
250 def test_high015_completed_streams_rescues_done_future_for_ordinary_batch():
251 f_done = concurrent.futures.Future()
252 f_done.set_result(([{"id": "1"}], {}))
253 f_hung = concurrent.futures.Future()
254
255 subquery = schema.SubQuery(label="primary", search_query="q", ranking_query="q", sources=["reddit", "x"])
256 futures = {f_done: (subquery, "reddit"), f_hung: (subquery, "x")}
257 wait_config = {"_research_deadline": time.monotonic() - 1.0}
258 bundle = schema.RetrievalBundle()
259
260 yielded = list(pipeline._completed_streams(
261 [(futures, wait_config, time.monotonic() + 180.0, False)], bundle,
262 ))
263
264 assert len(yielded) == 1
265 future, _sq, source, budget_expired = yielded[0]
266 assert future is f_done
267 assert source == "reddit"
268 assert budget_expired is True
269 assert "reddit" not in bundle.errors_by_source
270 assert bundle.source_status["x"].state == health.TIMEOUT
271
272
273 def test_high015_nominate_candidates_rescues_future_done_at_deadline(monkeypatch):
274 today = dates.get_date_range(5)[0]
275 raw = {
276 "id": "hn1",
277 "title": "Boundary discovery story",
278 "url": "https://example.com/boundary",
279 "hn_url": "https://news.ycombinator.com/item?id=99",
280 "author": "alice",
281 "date": today,
282 "engagement": {"points": 150, "comments": 40},
283 "relevance": 0.9,
284 }
285 monkeypatch.setattr(pipeline, "_fetch_discovery_source", lambda *a, **k: ([raw], None))
286 # Force deadline already expired so _wait_for_research exits immediately,
287 # while the future finishes before the not_done sweep.
288 real_wait = pipeline._wait_for_research
289
290 def boundary_wait(futures, config):
291 for future in futures:
292 future.result(timeout=2)
293 expired_cfg = {**config, "_research_deadline": time.monotonic() - 1.0}
294 return real_wait(futures, expired_cfg)
295
296 monkeypatch.setattr(pipeline, "_wait_for_research", boundary_wait)
297 plan = mock.Mock(sources=["hackernews"], domain="boundary")
298 bundle = pipeline.nominate_candidates(
299 plan,
300 from_date=dates.get_date_range(30)[0],
301 to_date=dates.get_date_range(30)[1],
302 depth="quick",
303 mock=False,
304 config={},
305 lookback_days=30,
306 )
307 assert len(bundle.items_by_source.get("hackernews", [])) == 1
308 assert bundle.source_status["hackernews"].state == health.OK
309
310
311 def test_high015_enrich_nominations_preserves_dequeued_and_ready_reports_at_deadline(monkeypatch):
312 n1 = pipeline.Nomination(name="Topic One", seed_score=90.0)
313 n2 = pipeline.Nomination(name="Topic Two", seed_score=80.0)
314 r1 = _stub_report("Topic One")
315 r2 = _stub_report("Topic Two")
316 both_enqueued = threading.Event()
317 calls = {"n": 0}
318 lock = threading.Lock()
319 real_monotonic = time.monotonic
320
321 def fake_run(*, topic, **_kwargs):
322 with lock:
323 calls["n"] += 1
324 if calls["n"] == 2:
325 both_enqueued.set()
326 return r1 if topic == "Topic One" else r2
327
328 # Advance synthetic clock past deadline right as the first blocking get() returns.
329 now = [100.0]
330 first_get = {"done": False}
331 real_get = queue.Queue.get
332
333 def get_then_expire(self, block=True, timeout=None):
334 if block and not first_get["done"]:
335 first_get["done"] = True
336 assert both_enqueued.wait(timeout=5)
337 # Ensure both workers have put into results_queue before returning.
338 deadline_wait = real_monotonic() + 2.0
339 while self.qsize() < 2 and real_monotonic() < deadline_wait:
340 time.sleep(0.01)
341 item = real_get(self, block=block, timeout=timeout)
342 now[0] = 200.0 # Cross the deadline immediately after dequeuing item 1
343 return item
344 return real_get(self, block=block, timeout=timeout)
345
346 monkeypatch.setattr(pipeline, "run", fake_run)
347 monkeypatch.setattr(pipeline.time, "monotonic", lambda: now[0])
348 monkeypatch.setattr(queue.Queue, "get", get_then_expire)
349
350 results = pipeline.enrich_nominations([n1, n2], config={}, budget_seconds=1.0, max_workers=2)
351 by_name = {entry.nomination.name: entry for entry in results}
352 assert by_name["Topic One"].report is r1
353 assert by_name["Topic One"].error is None
354 assert by_name["Topic Two"].report is r2
355 assert by_name["Topic Two"].error is None
356
357
358 # ---------------------------------------------------------------------------
359 # HIGH-016: Incremental collection, non-starving async 5xx retries & 429s
360 # ---------------------------------------------------------------------------
361
362
363 def test_high016_transient_5xx_retry_succeeds_while_sibling_hangs(monkeypatch):
364 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 1.2)
365 monkeypatch.setattr(pipeline, "_TRANSIENT_RETRY_DELAY_SECONDS", 0.05)
366
367 release = threading.Event()
368 attempts: dict[str, int] = {"x": 0, "reddit": 0}
369 retry_finished_at: list[float] = []
370 started = time.monotonic()
371 today = dates.get_date_range(5)[0]
372
373 def fake_retrieve(**kwargs):
374 source = kwargs["source"]
375 attempts[source] = attempts.get(source, 0) + 1
376 if source == "reddit":
377 release.wait(timeout=5.0)
378 return [], {}
379 if attempts["x"] == 1:
380 raise http.HTTPError("HTTP 503: Service Unavailable", status_code=503)
381 retry_finished_at.append(time.monotonic() - started)
382 return (
383 [
384 {
385 "id": "X1",
386 "text": "Async retry probe succeeded on X",
387 "url": "https://x.com/alice/status/1",
388 "author_handle": "alice",
389 "date": today,
390 "engagement": {"likes": 50},
391 "relevance": 0.9,
392 }
393 ],
394 {},
395 )
396
397 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
398 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
399 try:
400 report = pipeline.run(
401 topic="async retry probe",
402 config={},
403 depth="quick",
404 requested_sources=["reddit", "x"],
405 mock=True,
406 web_backend="none",
407 )
408 finally:
409 release.set()
410
411 assert attempts["x"] == 2
412 assert retry_finished_at and retry_finished_at[0] < 0.8, (
413 f"retry should finish while sibling hangs, not after timeout ({retry_finished_at})"
414 )
415 assert len(report.items_by_source.get("x", [])) == 1
416 assert report.source_status["x"].state == health.OK
417 assert report.source_status["reddit"].state == health.TIMEOUT
418
419
420 def test_high016_parallel_5xx_retries_run_concurrently_and_only_once(monkeypatch):
421 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 2.0)
422 monkeypatch.setattr(pipeline, "_TRANSIENT_RETRY_DELAY_SECONDS", 0.25)
423
424 attempts: dict[str, int] = {"reddit": 0, "hackernews": 0}
425 retry_times: dict[str, float] = {}
426 lock = threading.Lock()
427 today = dates.get_date_range(5)[0]
428
429 def fake_retrieve(**kwargs):
430 source = kwargs["source"]
431 with lock:
432 attempts[source] += 1
433 count = attempts[source]
434 if count == 1:
435 raise http.HTTPError("HTTP 503: Service Unavailable", status_code=503)
436 with lock:
437 retry_times[source] = time.monotonic()
438 if source == "hackernews":
439 raise http.HTTPError("HTTP 502: Bad Gateway", status_code=502)
440 return (
441 [
442 {
443 "id": "R1",
444 "title": "Parallel retry probe discussion",
445 "url": "https://reddit.com/r/example/comments/1",
446 "subreddit": "example",
447 "date": today,
448 "engagement": {"score": 40, "num_comments": 10},
449 "selftext": "Parallel retry probe",
450 "relevance": 0.9,
451 }
452 ],
453 {},
454 )
455
456 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
457 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
458 started = time.monotonic()
459 report = pipeline.run(
460 topic="parallel retry probe",
461 config={},
462 depth="quick",
463 requested_sources=["reddit", "hackernews"],
464 mock=True,
465 web_backend="none",
466 )
467 elapsed = time.monotonic() - started
468
469 assert attempts == {"reddit": 2, "hackernews": 2}
470 assert abs(retry_times["reddit"] - retry_times["hackernews"]) < 0.2
471 assert elapsed < 0.9, f"retries should not serialize backoff ({elapsed:.2f}s)"
472 assert report.source_status["reddit"].state == health.OK
473 assert report.source_status["hackernews"].state == health.ERROR
474 assert "retried once, still failed" in report.errors_by_source["hackernews"]
475
476
477 def test_high016_rate_limit_signals_incrementally_before_slow_sibling_finishes(monkeypatch):
478 plan = {
479 "intent": "general",
480 "freshness_mode": "balanced_recent",
481 "cluster_mode": "story",
482 "subqueries": [
483 {"label": "sq1", "search_query": "topic", "ranking_query": "topic", "sources": ["x", "reddit"]},
484 {"label": "sq2", "search_query": "topic angle", "ranking_query": "topic", "sources": ["x"]},
485 ],
486 "source_weights": {"x": 1.0, "reddit": 1.0},
487 }
488 x_429_signalled = threading.Event()
489 sq2_observed_before_reddit = threading.Event()
490 reddit_finished = threading.Event()
491 sq2_saw_rate_limit: list[bool] = []
492
493 def fake_retrieve(**kwargs):
494 source = kwargs["source"]
495 label = kwargs["subquery"].label
496 rate_limited = kwargs["rate_limited_sources"]
497 lock = kwargs["rate_limit_lock"]
498 if source == "reddit":
499 # Hold reddit open until sq2 observes the incremental 429 signal.
500 x_429_signalled.wait(timeout=2.0)
501 sq2_observed_before_reddit.wait(timeout=1.5)
502 reddit_finished.set()
503 return [], {}
504 if label == "sq1":
505 x_429_signalled.set()
506 raise http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
507 # sq2 runs after sq1 frees a worker slot (max_workers=2); main thread
508 # must record 429 while reddit is still running.
509 deadline = time.monotonic() + 1.0
510 while time.monotonic() < deadline:
511 with lock:
512 if "x" in rate_limited:
513 sq2_saw_rate_limit.append(not reddit_finished.is_set())
514 sq2_observed_before_reddit.set()
515 return [], {}
516 time.sleep(0.01)
517 sq2_saw_rate_limit.append(False)
518 sq2_observed_before_reddit.set()
519 return [], {}
520
521 monkeypatch.setattr(pipeline, "_inner_max_workers", lambda *a, **k: 2)
522 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
523 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
524 report = pipeline.run(
525 topic="rate limit probe",
526 config={"_max_source_fetches": 3},
527 depth="default",
528 requested_sources=["x", "reddit"],
529 mock=True,
530 external_plan=plan,
531 web_backend="none",
532 )
533
534 assert sq2_saw_rate_limit == [True]
535 assert report.source_status["x"].state == health.RATE_LIMITED
536
537
538 def test_high016_two_source_subrun_uses_full_max_workers_concurrently(monkeypatch):
539 """A 2-source comparison sub-run (max_workers=2) must run both primary searches
540 concurrently without reserving an idle retry slot."""
541 plan = {
542 "intent": "general",
543 "freshness_mode": "balanced_recent",
544 "cluster_mode": "story",
545 "subqueries": [
546 {
547 "label": "primary",
548 "search_query": "two source comparison",
549 "ranking_query": "two source comparison",
550 "sources": ["reddit", "x"],
551 },
552 ],
553 "source_weights": {"reddit": 1.0, "x": 1.0},
554 }
555 both_started = threading.Barrier(2, timeout=2.0)
556 lock = threading.Lock()
557 state = {"active": 0, "peak": 0}
558
559 def fake_retrieve(**kwargs):
560 with lock:
561 state["active"] += 1
562 state["peak"] = max(state["peak"], state["active"])
563 try:
564 both_started.wait()
565 return [], {}
566 finally:
567 with lock:
568 state["active"] -= 1
569
570 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
571 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
572 report = pipeline.run(
573 topic="two source comparison",
574 config={},
575 depth="quick",
576 requested_sources=["reddit", "x"],
577 mock=True,
578 external_plan=plan,
579 web_backend="none",
580 internal_subrun=True,
581 )
582 assert report is not None
583 assert state["peak"] == 2
584
585
586 def test_high016_ready_retry_preempts_queued_primary_deterministically(monkeypatch):
587 """Backoff consumes zero regular slots, and once a retry is scheduled and due
588 it deterministically runs ahead of queued primary searches (no fixed-sleep race)."""
589 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 2.0)
590 monkeypatch.setattr(pipeline, "_TRANSIENT_RETRY_DELAY_SECONDS", 0.05)
591 monkeypatch.setattr(pipeline, "_inner_max_workers", lambda *a, **k: 2)
592
593 plan = {
594 "intent": "general",
595 "freshness_mode": "balanced_recent",
596 "cluster_mode": "story",
597 "subqueries": [
598 {
599 "label": "primary",
600 "search_query": "priority retry probe",
601 "ranking_query": "priority retry probe",
602 "sources": ["x", "reddit", "hackernews", "bluesky"],
603 },
604 ],
605 "source_weights": {"x": 1.0, "reddit": 1.0, "hackernews": 1.0, "bluesky": 1.0},
606 }
607 hn_entered = threading.Event()
608 retry_scheduled = threading.Event()
609 retry_ready_at: list[float] = []
610 release_hn = threading.Event()
611 order: list[str] = []
612 attempts: dict[str, int] = {"x": 0}
613 lock = threading.Lock()
614 state = {"active": 0, "peak": 0}
615 today = dates.get_date_range(5)[0]
616
617 orig_submit_delayed = pipeline._DaemonExecutor.submit_delayed
618
619 def spy_submit_delayed(self, ready_at, fn, /, *args, **kwargs):
620 retry_ready_at.append(ready_at)
621 retry_scheduled.set()
622 return orig_submit_delayed(self, ready_at, fn, *args, **kwargs)
623
624 def fake_retrieve(**kwargs):
625 source = kwargs["source"]
626 with lock:
627 state["active"] += 1
628 state["peak"] = max(state["peak"], state["active"])
629 try:
630 if source == "x":
631 with lock:
632 attempts["x"] += 1
633 attempt = attempts["x"]
634 if attempt == 1:
635 raise http.HTTPError("HTTP 503: Service Unavailable", status_code=503)
636 with lock:
637 order.append("x-retry")
638 release_hn.set()
639 return (
640 [
641 {
642 "id": "X-RETRY",
643 "text": "Priority retry probe recovered ahead of queued primary",
644 "url": "https://x.com/alice/status/99",
645 "author_handle": "alice",
646 "date": today,
647 "engagement": {"likes": 42},
648 "relevance": 0.9,
649 }
650 ],
651 {},
652 )
653 if source == "reddit":
654 # Wait deterministically until hackernews grabbed x's freed slot
655 # AND the retry is both scheduled and past its ready_at timestamp.
656 assert hn_entered.wait(timeout=2.0)
657 assert retry_scheduled.wait(timeout=2.0)
658 wait_left = retry_ready_at[0] - time.monotonic() + 0.01
659 if wait_left > 0:
660 time.sleep(wait_left)
661 return [], {}
662 if source == "hackernews":
663 hn_entered.set()
664 release_hn.wait(timeout=2.0)
665 return [], {}
666 with lock:
667 order.append(source)
668 return [], {}
669 finally:
670 with lock:
671 state["active"] -= 1
672
673 monkeypatch.setattr(pipeline._DaemonExecutor, "submit_delayed", spy_submit_delayed)
674 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
675 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
676 try:
677 report = pipeline.run(
678 topic="priority retry probe",
679 config={},
680 depth="default",
681 requested_sources=["x", "reddit", "hackernews", "bluesky"],
682 mock=True,
683 external_plan=plan,
684 web_backend="none",
685 internal_subrun=True,
686 )
687 finally:
688 release_hn.set()
689
690 assert attempts["x"] == 2
691 assert state["peak"] <= 3 # max_workers (2) + at most 1 overflow retry worker
692 assert order == ["x-retry", "bluesky"], (
693 f"ready retry must run ahead of queued primary search: {order}"
694 )
695 assert len(report.items_by_source.get("x", [])) == 1
696 assert report.source_status["x"].state == health.OK
697
698
699 def test_high016_full_pool_during_backoff_still_runs_retry_within_bounded_burst(monkeypatch):
700 """When all max_workers regular workers fill with long searches during a 503's
701 backoff (S1 503s, S5 takes S1's slot, S2..S5 stay busy), the single bounded
702 overflow worker must still wake at retry_at and complete S1's retry while
703 keeping total active concurrency <= max_workers + 1."""
704 monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 2.0)
705 monkeypatch.setattr(pipeline, "_TRANSIENT_RETRY_DELAY_SECONDS", 0.05)
706
707 # internal_subrun=True -> max_workers=4 across 5 streams (x + 4 slow sources).
708 plan = {
709 "intent": "general",
710 "freshness_mode": "balanced_recent",
711 "cluster_mode": "story",
712 "subqueries": [
713 {
714 "label": "primary",
715 "search_query": "saturated backoff probe",
716 "ranking_query": "saturated backoff probe",
717 "sources": ["x", "reddit", "hackernews", "bluesky", "arxiv"],
718 },
719 ],
720 "source_weights": {
721 "x": 1.0, "reddit": 1.0, "hackernews": 1.0, "bluesky": 1.0, "arxiv": 1.0,
722 },
723 }
724 release_slow = threading.Event()
725 all_four_slow_active = threading.Event()
726 slow_seen: set[str] = set()
727 retry_saw_all_slow_blocked: list[bool] = []
728 attempts: dict[str, int] = {"x": 0}
729 lock = threading.Lock()
730 state = {"active": 0, "peak": 0}
731 today = dates.get_date_range(5)[0]
732
733 def fake_retrieve(**kwargs):
734 source = kwargs["source"]
735 with lock:
736 state["active"] += 1
737 state["peak"] = max(state["peak"], state["active"])
738 try:
739 if source != "x":
740 with lock:
741 slow_seen.add(source)
742 if len(slow_seen) == 4:
743 all_four_slow_active.set()
744 release_slow.wait(timeout=5.0)
745 return [], {}
746 with lock:
747 attempts["x"] += 1
748 attempt = attempts["x"]
749 if attempt == 1:
750 raise http.HTTPError("HTTP 503: Service Unavailable", status_code=503)
751 # All 4 slow searches must already be holding the 4 regular workers,
752 # and none have been released yet when the overflow retry runs.
753 assert all_four_slow_active.wait(timeout=2.0)
754 retry_saw_all_slow_blocked.append(not release_slow.is_set())
755 release_slow.set()
756 return (
757 [
758 {
759 "id": "X-OVERFLOW",
760 "text": "Saturated backoff probe recovered via single overflow retry worker",
761 "url": "https://x.com/alice/status/101",
762 "author_handle": "alice",
763 "date": today,
764 "engagement": {"likes": 55},
765 "relevance": 0.9,
766 }
767 ],
768 {},
769 )
770 finally:
771 with lock:
772 state["active"] -= 1
773
774 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
775 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
776 try:
777 report = pipeline.run(
778 topic="saturated backoff probe",
779 config={},
780 depth="default",
781 requested_sources=["x", "reddit", "hackernews", "bluesky", "arxiv"],
782 mock=True,
783 external_plan=plan,
784 web_backend="none",
785 internal_subrun=True,
786 )
787 finally:
788 release_slow.set()
789
790 assert attempts["x"] == 2
791 assert len(slow_seen) == 4
792 assert retry_saw_all_slow_blocked == [True]
793 assert state["peak"] <= 5, f"peak concurrency exceeded max_workers + 1 (peak={state['peak']})"
794 assert len(report.items_by_source.get("x", [])) == 1
795 assert report.source_status["x"].state == health.OK
796
797
798 def test_high016_priority_queue_beats_pending_on_shared_regular_worker():
799 """Directly verify _priority_pending preempts _pending when a regular worker
800 frees up while the single overflow worker is already occupied."""
801 release_s1 = threading.Event()
802 release_r1 = threading.Event()
803 s1_started = threading.Event()
804 r1_started = threading.Event()
805 order: list[str] = []
806
807 try:
808 with pipeline._abandoning_executor(max_workers=1) as pool:
809 f_s1 = pool.submit(lambda: (s1_started.set(), release_s1.wait(timeout=5.0))[1])
810 assert s1_started.wait(timeout=2.0)
811
812 # Occupy the single overflow worker with r1.
813 f_r1 = pool.submit_delayed(
814 time.monotonic(), lambda: (r1_started.set(), release_r1.wait(timeout=5.0))[1],
815 )
816 assert r1_started.wait(timeout=2.0)
817
818 # Queue regular s2 first, then ready retry r2; when s1 frees the
819 # regular worker, r2 must run before s2.
820 f_s2 = pool.submit(lambda: order.append("s2"))
821 f_r2 = pool.submit_delayed(time.monotonic(), lambda: order.append("r2"))
822 release_s1.set()
823 f_s1.result(timeout=2.0)
824 f_r2.result(timeout=2.0)
825 f_s2.result(timeout=2.0)
826 release_r1.set()
827 f_r1.result(timeout=2.0)
828 finally:
829 release_s1.set()
830 release_r1.set()
831
832 assert order == ["r2", "s2"]
833
834
835 def test_high016_multiple_delayed_retries_run_in_parallel_and_cancel_cleanly_on_shutdown():
836 """Slow first retry must not block a second ready retry when another worker
837 is free, and shutdown(wait=False, cancel_futures=True) must cancel pending
838 delayed retries immediately."""
839 both_retries = threading.Barrier(2, timeout=2.0)
840 with pipeline._abandoning_executor(max_workers=2) as pool:
841 ready_at = time.monotonic() + 0.05
842 f1 = pool.submit_delayed(ready_at, lambda: (both_retries.wait(), "r1")[1])
843 f2 = pool.submit_delayed(ready_at, lambda: (both_retries.wait(), "r2")[1])
844 assert f1.result(timeout=2.0) == "r1"
845 assert f2.result(timeout=2.0) == "r2"
846
847 ran_late: list[int] = []
848 t0 = time.monotonic()
849 with pipeline._abandoning_executor(max_workers=2) as pool:
850 f_far = pool.submit_delayed(time.monotonic() + 30.0, ran_late.append, 1)
851 elapsed = time.monotonic() - t0
852 assert elapsed < 1.0, f"shutdown blocked on pending delayed retry ({elapsed:.2f}s)"
853 assert f_far.cancelled()
854 assert ran_late == []
855
856
857 def test_high016_regular_submit_while_delayed_pending_keeps_timer_watcher_alive():
858 """When an idle worker watching _delayed is pulled onto a new regular submit()
859 with free slots still available under max_workers, a fresh worker must be
860 spawned so the delayed retry still fires on time without waiting for busy tasks."""
861 release = threading.Event()
862 slow1_started = threading.Event()
863 slow2_started = threading.Event()
864
865 def slow(flag: threading.Event) -> str:
866 flag.set()
867 release.wait(timeout=5.0)
868 return "slow"
869
870 try:
871 with pipeline._abandoning_executor(max_workers=4) as pool:
872 pool.submit(slow, slow1_started)
873 assert slow1_started.wait(timeout=2.0)
874
875 # Schedule a delayed retry while 1 worker is busy and 1 idle worker watches _delayed.
876 t0 = time.monotonic()
877 f_delayed = pool.submit_delayed(t0 + 0.05, lambda: "retry-ok")
878 # Submit a second slow task before +0.05s; must not strand f_delayed.
879 pool.submit(slow, slow2_started)
880 assert slow2_started.wait(timeout=2.0)
881
882 assert f_delayed.result(timeout=0.8) == "retry-ok"
883 assert not release.is_set()
884 finally:
885 release.set()
886
887
888 # ---------------------------------------------------------------------------
889 # HIGH-017: Single-fetch caps & thread-safe _jobs_lane / LaneBudget
890 # ---------------------------------------------------------------------------
891
892
893 @pytest.mark.parametrize("source", ["perplexity", "jobs", "trustpilot", "amazon", "meta_ads"])
894 def test_high017_single_entity_sources_stay_capped_under_override(source):
895 assert pipeline._source_fetch_cap(source, {}) == 1
896 assert pipeline._source_fetch_cap(source, {"_max_source_fetches": 5}) == 1
897 assert pipeline._source_fetch_cap(source, {"_max_source_fetches": 0}) == 0
898 assert pipeline._source_fetch_cap(source, {"_max_source_fetches": -3}) == 0
899 assert pipeline._source_fetch_cap("x", {"_max_source_fetches": -2}) == 0
900
901
902 def test_high017_jobs_lane_budget_init_is_thread_safe():
903 config = {"_jobs_lane": {}}
904 barrier = threading.Barrier(12, timeout=5)
905 budgets: list[jobs.LaneBudget] = []
906 lock = threading.Lock()
907
908 def worker():
909 barrier.wait()
910 b = pipeline._jobs_lane_budget(config)
911 with lock:
912 budgets.append(b)
913
914 threads = [threading.Thread(target=worker) for _ in range(12)]
915 for t in threads:
916 t.start()
917 for t in threads:
918 t.join(timeout=5)
919 assert not t.is_alive()
920
921 assert len(budgets) == 12
922 assert len({id(b) for b in budgets}) == 1
923 assert config["_jobs_lane"] == {"budget": budgets[0]}
924
925
926 def test_high017_lane_budget_concurrent_mutations_are_synchronized():
927 budget = jobs.LaneBudget(60.0)
928 barrier = threading.Barrier(8, timeout=5)
929 errors: list[BaseException] = []
930
931 def worker(idx: int):
932 try:
933 barrier.wait()
934 for j in range(50):
935 budget.note_slow(f"slow-{idx}-{j}")
936 budget.note_unanswered(f"unanswered-{idx}-{j}")
937 budget.record_landed(f"https://example.com/{idx}/{j}", f"https://dest.example/{idx}/{j}")
938 assert budget.get_landed(f"https://example.com/{idx}/{j}") == f"https://dest.example/{idx}/{j}"
939 budget.mark_unreachable({f"host-{idx}-{j}.example"})
940 assert budget.is_unreachable(f"host-{idx}-{j}.example")
941 budget.limit_discovery(30.0)
942 budget.remaining()
943 budget.spent()
944 budget.stop(f"step-{idx}")
945 budget.settled = True
946 budget.reason()
947 except BaseException as exc:
948 errors.append(exc)
949
950 threads = [threading.Thread(target=worker, args=(i,)) for i in range(8)]
951 for t in threads:
952 t.start()
953 for t in threads:
954 t.join(timeout=10)
955 assert not t.is_alive()
956
957 assert errors == []
958 assert len(budget.slow) == 400
959 assert len(budget.unanswered_snapshot()) == 400
960 assert len(budget.landed) == 400
961 assert len(budget.unreachable) == 400
962 assert budget.stopped_at.startswith("step-")
963 assert budget.settled is True
964
965
966 # ---------------------------------------------------------------------------
967 # HIGH-018: Daemon-thread _abandoning_executor & cancellable fetch_memo
968 # ---------------------------------------------------------------------------
969
970
971 def test_high018_abandoning_executor_uses_daemon_threads_cancels_queued_and_preserves_context():
972 release = threading.Event()
973 started = threading.Event()
974 worker_info: dict[str, object] = {}
975 queued_ran: list[int] = []
976
977 ctx_var: contextvars.ContextVar[str] = contextvars.ContextVar("pr23_ctx", default="unset")
978 ctx_seen: list[str] = []
979
980 with pipeline._abandoning_executor(max_workers=2) as pool:
981 token = ctx_var.set("carried-value")
982 try:
983 f_ctx = http.submit_with_context(pool, ctx_var.get)
984 finally:
985 ctx_var.reset(token)
986 ctx_seen.append(f_ctx.result(timeout=5))
987
988 assert ctx_seen == ["carried-value"]
989
990 def hung():
991 t = threading.current_thread()
992 worker_info["daemon"] = t.daemon
993 worker_info["in_cf_registry"] = t in concurrent.futures.thread._threads_queues
994 started.set()
995 release.wait(timeout=5.0)
996 return "done"
997
998 try:
999 with pipeline._abandoning_executor(max_workers=1) as pool:
1000 f_hung = pool.submit(hung)
1001 assert started.wait(timeout=5.0)
1002 queued = [pool.submit(queued_ran.append, i) for i in range(3)]
1003 assert all(f.cancelled() for f in queued)
1004 assert not f_hung.done()
1005 finally:
1006 release.set()
1007
1008 assert worker_info["daemon"] is True
1009 assert worker_info["in_cf_registry"] is False
1010 assert queued_ran == []
1011
1012
1013 def test_high018_abandoned_straggler_does_not_block_interpreter_exit():
1014 scripts_dir = str(Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts")
1015 code = (
1016 "import threading, time\n"
1017 "from lib import pipeline\n"
1018 "started = threading.Event()\n"
1019 "def hang():\n"
1020 " started.set()\n"
1021 " time.sleep(30)\n"
1022 "with pipeline._abandoning_executor(max_workers=1) as pool:\n"
1023 " pool.submit(hang)\n"
1024 " assert started.wait(timeout=5)\n"
1025 " print(time.monotonic(), flush=True)\n"
1026 )
1027 env = {**os.environ, "PYTHONPATH": scripts_dir}
1028 proc = subprocess.run(
1029 [sys.executable, "-c", code],
1030 env=env,
1031 capture_output=True,
1032 text=True,
1033 timeout=20.0,
1034 )
1035 assert proc.returncode == 0, proc.stderr
1036 # The monotonic clock is shared across processes. Start the exit budget
1037 # when the worker is running, after the child has imported the pipeline.
1038 elapsed = time.monotonic() - float(proc.stdout.strip())
1039 assert elapsed < 2.5, f"interpreter blocked on abandoned straggler ({elapsed:.2f}s)"
1040
1041
1042 def test_high018_fetch_memo_waiter_unblocks_promptly_on_cancel():
1043 owner_started = threading.Event()
1044 release = threading.Event()
1045 cancel = threading.Event()
1046
1047 def slow_owner():
1048 owner_started.set()
1049 release.wait(timeout=10.0)
1050 return {"items": [{"id": "1"}]}
1051
1052 owner = threading.Thread(
1053 target=fetch_memo.fetch_once,
1054 args=(("pr23", "cancel-test"), slow_owner),
1055 kwargs={"timeout": 10.0},
1056 daemon=True,
1057 )
1058 owner.start()
1059 assert owner_started.wait(timeout=5.0)
1060 try:
1061 threading.Timer(0.05, cancel.set).start()
1062 t0 = time.monotonic()
1063 with pytest.raises(fetch_memo.MemoWaitTimeout) as caught:
1064 fetch_memo.fetch_once(
1065 ("pr23", "cancel-test"),
1066 slow_owner,
1067 timeout=10.0,
1068 cancel=cancel,
1069 )
1070 elapsed = time.monotonic() - t0
1071 assert caught.value.outcome_state == health.TIMEOUT
1072 assert elapsed < 0.8, f"cancelled waiter did not unblock promptly ({elapsed:.2f}s)"
1073
1074 # Already-cancelled caller must not invoke a fresh fetch either.
1075 ran: list[int] = []
1076 with pytest.raises(fetch_memo.MemoWaitTimeout):
1077 fetch_memo.fetch_once(
1078 ("pr23", "fresh-key-cancelled"),
1079 lambda: (ran.append(1), {"items": []})[1],
1080 timeout=5.0,
1081 cancel=cancel,
1082 )
1083 assert ran == []
1084 finally:
1085 release.set()
1086 owner.join(timeout=5.0)
1087
1088
1089 # ---------------------------------------------------------------------------
1090 # HIGH-020: Phase 1 per-source normalization/post-processing containment
1091 # ---------------------------------------------------------------------------
1092
1093
1094 def test_high020_malformed_source_normalization_does_not_crash_healthy_sources(monkeypatch):
1095 today = dates.get_date_range(5)[0]
1096 healthy_reddit = [
1097 {
1098 "id": "R1",
1099 "title": "Containment test healthy discussion",
1100 "url": "https://reddit.com/r/example/comments/containment-1",
1101 "subreddit": "example",
1102 "date": today,
1103 "engagement": {"score": 90, "num_comments": 25},
1104 "selftext": "Containment test healthy discussion",
1105 "relevance": 0.9,
1106 }
1107 ]
1108
1109 def fake_retrieve(**kwargs):
1110 if kwargs["source"] == "reddit":
1111 return healthy_reddit, {}
1112 return [{"id": "bad"}], {}
1113
1114 orig_norm = pipeline._normalize_score_dedupe
1115
1116 def exploding_norm(source, *args, **kwargs):
1117 if source == "hackernews":
1118 raise TypeError("unexpected schema drift in hackernews payload")
1119 return orig_norm(source, *args, **kwargs)
1120
1121 monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
1122 monkeypatch.setattr(pipeline, "_normalize_score_dedupe", exploding_norm)
1123 monkeypatch.setattr(pipeline, "_retry_thin_sources", mock.Mock())
1124
1125 report = pipeline.run(
1126 topic="containment test",
1127 config={},
1128 depth="quick",
1129 requested_sources=["reddit", "hackernews"],
1130 mock=True,
1131 web_backend="none",
1132 )
1133
1134 assert len(report.items_by_source.get("reddit", [])) == 1
1135 assert report.source_status["reddit"].state == health.OK
1136 assert report.source_status["hackernews"].state == health.SCHEMA_DRIFT
1137 assert "unexpected schema drift" in report.errors_by_source["hackernews"]
1138
1139
1140 # ---------------------------------------------------------------------------
1141 # HIGH-021: GitHub project/person pre-loop mock, plan, first-party & no-fallback
1142 # ---------------------------------------------------------------------------
1143
1144
1145 def test_high021_mock_true_never_calls_live_github_project_or_person():
1146 plan = {
1147 "intent": "person",
1148 "freshness_mode": "balanced_recent",
1149 "cluster_mode": "topic",
1150 "subqueries": [
1151 {"label": "primary", "search_query": "octocat", "ranking_query": "octocat", "sources": ["github"]},
1152 ],
1153 "source_weights": {"github": 1.0},
1154 }
1155 with mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person, \
1156 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_project:
1157 r_person = pipeline.run(
1158 topic="octocat",
1159 config={},
1160 depth="quick",
1161 requested_sources=["github"],
1162 mock=True,
1163 web_backend="none",
1164 external_plan=plan,
1165 github_user="octocat",
1166 )
1167 r_project = pipeline.run(
1168 topic="octocat/hello-world",
1169 config={},
1170 depth="quick",
1171 requested_sources=["github"],
1172 mock=True,
1173 web_backend="none",
1174 external_plan=plan,
1175 github_repos=["octocat/hello-world"],
1176 )
1177 mock_person.assert_not_called()
1178 mock_project.assert_not_called()
1179 assert r_person is not None
1180 assert r_project is not None
1181
1182
1183 def test_high021_external_plan_omitting_github_skips_project_and_person_preloop():
1184 plan_no_github = {
1185 "intent": "person",
1186 "freshness_mode": "balanced_recent",
1187 "cluster_mode": "topic",
1188 "subqueries": [
1189 {"label": "primary", "search_query": "octocat", "ranking_query": "octocat", "sources": ["hackernews"]},
1190 ],
1191 "source_weights": {"hackernews": 1.0},
1192 }
1193 with mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})), \
1194 mock.patch("lib.pipeline._retry_thin_sources"), \
1195 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person, \
1196 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_project:
1197 pipeline.run(
1198 topic="octocat",
1199 config={"GITHUB_TOKEN": "dummy-token"},
1200 depth="quick",
1201 requested_sources=["hackernews", "github"],
1202 mock=False,
1203 web_backend="none",
1204 external_plan=plan_no_github,
1205 github_user="octocat",
1206 )
1207 pipeline.run(
1208 topic="octocat",
1209 config={"GITHUB_TOKEN": "dummy-token"},
1210 depth="quick",
1211 requested_sources=["hackernews", "github"],
1212 mock=False,
1213 web_backend="none",
1214 external_plan=plan_no_github,
1215 github_repos=["octocat/hello-world"],
1216 )
1217 mock_person.assert_not_called()
1218 mock_project.assert_not_called()
1219
1220
1221 def test_high021_quick_engine_plan_omitting_github_still_runs_pinned_github():
1222 quick_engine_plan = schema.QueryPlan(
1223 intent="general",
1224 freshness_mode="balanced_recent",
1225 cluster_mode="topic",
1226 raw_topic="acme widget",
1227 subqueries=[
1228 schema.SubQuery(
1229 label="primary",
1230 search_query="acme widget",
1231 ranking_query="acme widget",
1232 sources=["reddit", "hackernews"],
1233 weight=1.0,
1234 ),
1235 ],
1236 source_weights={"reddit": 1.0, "hackernews": 1.0},
1237 )
1238 drill_plan = schema.QueryPlan(
1239 intent="general",
1240 freshness_mode="balanced_recent",
1241 cluster_mode="topic",
1242 raw_topic="acme widget",
1243 subqueries=[
1244 schema.SubQuery(
1245 label="primary",
1246 search_query="acme widget",
1247 ranking_query="acme widget",
1248 sources=["reddit"],
1249 weight=1.0,
1250 ),
1251 ],
1252 source_weights={"reddit": 1.0},
1253 notes=["drill-mode"],
1254 )
1255 with mock.patch("lib.pipeline.planner.plan_query", return_value=quick_engine_plan), \
1256 mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})), \
1257 mock.patch("lib.pipeline._retry_thin_sources"), \
1258 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_project, \
1259 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person:
1260 pipeline.run(
1261 topic="acme widget",
1262 config={"GITHUB_TOKEN": "dummy-token"},
1263 depth="quick",
1264 mock=False,
1265 web_backend="none",
1266 github_repos=["acme/widget"],
1267 )
1268 pipeline.run(
1269 topic="octocat",
1270 config={"GITHUB_TOKEN": "dummy-token"},
1271 depth="quick",
1272 mock=False,
1273 web_backend="none",
1274 github_user="octocat",
1275 )
1276 mock_project.assert_called_once()
1277 mock_person.assert_called_once()
1278
1279 # Drill-mode plan omitting github must still skip pinned lookups.
1280 with mock.patch("lib.pipeline.planner.plan_query", return_value=drill_plan), \
1281 mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})), \
1282 mock.patch("lib.pipeline._retry_thin_sources"), \
1283 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_drill_project, \
1284 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_drill_person:
1285 pipeline.run(
1286 topic="acme widget",
1287 config={"GITHUB_TOKEN": "dummy-token"},
1288 depth="quick",
1289 mock=False,
1290 web_backend="none",
1291 github_repos=["acme/widget"],
1292 )
1293 pipeline.run(
1294 topic="octocat",
1295 config={"GITHUB_TOKEN": "dummy-token"},
1296 depth="quick",
1297 mock=False,
1298 web_backend="none",
1299 github_user="octocat",
1300 )
1301 mock_drill_project.assert_not_called()
1302 mock_drill_person.assert_not_called()
1303
1304
1305 @pytest.mark.parametrize("target", ["project", "person"])
1306 def test_high021_missing_github_auth_records_skipped_unconfigured_without_fallback(target):
1307 plan = {
1308 "intent": "product" if target == "project" else "person",
1309 "freshness_mode": "balanced_recent",
1310 "cluster_mode": "none",
1311 "subqueries": [
1312 {"label": "primary", "search_query": "acme widget", "ranking_query": "acme widget", "sources": ["github"]},
1313 ],
1314 "source_weights": {"github": 1.0},
1315 }
1316 extra = {"github_repos": ["acme/widget"]} if target == "project" else {"github_user": "octocat"}
1317 with mock.patch("lib.pipeline.github.resolve_token", return_value=None) as mock_resolve, \
1318 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_project, \
1319 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person, \
1320 mock.patch("lib.pipeline._retrieve_stream") as mock_retrieve:
1321 report = pipeline.run(
1322 topic="acme widget",
1323 config={},
1324 depth="default",
1325 requested_sources=["github"],
1326 mock=False,
1327 web_backend="none",
1328 external_plan=plan,
1329 **extra,
1330 )
1331
1332 mock_resolve.assert_called_once_with(None)
1333 mock_project.assert_not_called()
1334 mock_person.assert_not_called()
1335 mock_retrieve.assert_not_called()
1336 outcome = report.source_status["github"]
1337 assert outcome.state == schema.SKIPPED_UNCONFIGURED
1338 assert outcome.attempted is False
1339 assert "no GitHub token or gh login available" in outcome.detail
1340
1341
1342 @pytest.mark.parametrize("target", ["project", "person"])
1343 def test_high021_pinned_github_resolves_token_once_on_authenticated_empty_result(target):
1344 plan = {
1345 "intent": "product" if target == "project" else "person",
1346 "freshness_mode": "balanced_recent",
1347 "cluster_mode": "none",
1348 "subqueries": [
1349 {"label": "primary", "search_query": "acme widget", "ranking_query": "acme widget", "sources": ["github"]},
1350 ],
1351 "source_weights": {"github": 1.0},
1352 }
1353 extra = {"github_repos": ["acme/widget"]} if target == "project" else {"github_user": "octocat"}
1354 with mock.patch("lib.pipeline.github.resolve_token", return_value="ghp_from_cli") as mock_resolve, \
1355 mock.patch("lib.pipeline.github.search_github_project", return_value=[]) as mock_project, \
1356 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person, \
1357 mock.patch("lib.pipeline._retrieve_stream") as mock_retrieve:
1358 report = pipeline.run(
1359 topic="acme widget",
1360 config={},
1361 depth="default",
1362 requested_sources=["github"],
1363 mock=False,
1364 web_backend="none",
1365 external_plan=plan,
1366 **extra,
1367 )
1368
1369 mock_resolve.assert_called_once_with(None)
1370 if target == "project":
1371 mock_project.assert_called_once()
1372 assert mock_project.call_args.kwargs["token"] == "ghp_from_cli"
1373 mock_person.assert_not_called()
1374 else:
1375 mock_person.assert_called_once()
1376 assert mock_person.call_args.kwargs["token"] == "ghp_from_cli"
1377 mock_project.assert_not_called()
1378 mock_retrieve.assert_not_called()
1379 assert report.source_status["github"].state == schema.NO_RESULTS
1380
1381
1382 def test_high021_person_and_project_preloop_pass_first_party_handles():
1383 today = dates.get_date_range(5)[0]
1384 # Unrelated title with zero lexical overlap against "What is @octocat doing on GitHub?",
1385 # alongside a strongly overlapping item so prune_low_relevance would drop it
1386 # unless first_party_handles exempts author="octocat".
1387 low_overlap_own = {
1388 "id": "GH-OWN",
1389 "title": "Fix SIMD register spilling in allocator",
1390 "snippet": "Rewrites loop invariant motion.",
1391 "url": "https://github.com/octocat/compiler/pull/42",
1392 "author": "octocat",
1393 "container": "octocat/compiler",
1394 "date": today,
1395 "engagement": {"comments": 5},
1396 "relevance": 0.1,
1397 }
1398 high_overlap_other = {
1399 "id": "GH-HIGH",
1400 "title": "octocat GitHub roadmap summary",
1401 "snippet": "What is octocat doing on GitHub",
1402 "url": "https://github.com/other/docs/issues/1",
1403 "author": "other",
1404 "container": "other/docs",
1405 "date": today,
1406 "engagement": {"comments": 50},
1407 "relevance": 0.95,
1408 }
1409 plan = {
1410 "intent": "person",
1411 "freshness_mode": "balanced_recent",
1412 "cluster_mode": "topic",
1413 "subqueries": [
1414 {"label": "primary", "search_query": "octocat", "ranking_query": "octocat", "sources": ["github"]},
1415 ],
1416 "source_weights": {"github": 1.0},
1417 }
1418 seen_handles: list[set[str]] = []
1419 orig_norm = pipeline._normalize_score_dedupe
1420
1421 def spy_norm(*args, **kwargs):
1422 seen_handles.append(set(kwargs.get("first_party_handles") or ()))
1423 return orig_norm(*args, **kwargs)
1424
1425 with mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})), \
1426 mock.patch("lib.pipeline._retry_thin_sources"), \
1427 mock.patch("lib.pipeline.github.enrich_candidates_with_stars"), \
1428 mock.patch("lib.pipeline._normalize_score_dedupe", side_effect=spy_norm), \
1429 mock.patch("lib.pipeline.github.search_github_person", return_value=[low_overlap_own, high_overlap_other]):
1430 person_report = pipeline.run(
1431 topic="octocat",
1432 config={"GITHUB_TOKEN": "dummy-token"},
1433 depth="quick",
1434 requested_sources=["github"],
1435 mock=False,
1436 web_backend="none",
1437 external_plan=plan,
1438 github_user="octocat",
1439 )
1440
1441 assert seen_handles and "octocat" in seen_handles[0]
1442 assert "https://github.com/octocat/compiler/pull/42" in {
1443 i.url for i in person_report.items_by_source.get("github", [])
1444 }
1445
1446 seen_handles.clear()
1447 with mock.patch("lib.pipeline._retrieve_stream", return_value=([], {})), \
1448 mock.patch("lib.pipeline._retry_thin_sources"), \
1449 mock.patch("lib.pipeline.github.enrich_candidates_with_stars"), \
1450 mock.patch("lib.pipeline._normalize_score_dedupe", side_effect=spy_norm), \
1451 mock.patch("lib.pipeline.github.search_github_project", return_value=[low_overlap_own, high_overlap_other]):
1452 project_report = pipeline.run(
1453 topic="octocat",
1454 config={"GITHUB_TOKEN": "dummy-token"},
1455 depth="quick",
1456 requested_sources=["github"],
1457 mock=False,
1458 web_backend="none",
1459 external_plan=plan,
1460 github_user="octocat",
1461 github_repos=["octocat/compiler"],
1462 )
1463
1464 assert seen_handles and "octocat" in seen_handles[0]
1465 assert "https://github.com/octocat/compiler/pull/42" in {
1466 i.url for i in project_report.items_by_source.get("github", [])
1467 }
1468
1469
1470 @pytest.mark.parametrize("mode", ["empty", "error"])
1471 def test_high021_pinned_github_repos_suppresses_generic_fallback_on_empty_or_error(mode):
1472 plan = {
1473 "intent": "product",
1474 "freshness_mode": "balanced_recent",
1475 "cluster_mode": "none",
1476 "subqueries": [
1477 {"label": "primary", "search_query": "acme widget", "ranking_query": "acme widget", "sources": ["github"]},
1478 ],
1479 "source_weights": {"github": 1.0},
1480 }
1481 project_mock = (
1482 mock.patch("lib.pipeline.github.search_github_project", return_value=[])
1483 if mode == "empty"
1484 else mock.patch("lib.pipeline.github.search_github_project", side_effect=RuntimeError("API down"))
1485 )
1486 with project_mock as mock_project, \
1487 mock.patch("lib.pipeline.github.search_github_person", return_value=[]) as mock_person, \
1488 mock.patch("lib.pipeline._retrieve_stream") as mock_retrieve:
1489 report = pipeline.run(
1490 topic="acme widget",
1491 config={"GITHUB_TOKEN": "dummy-token"},
1492 depth="default",
1493 requested_sources=["github"],
1494 mock=False,
1495 web_backend="none",
1496 external_plan=plan,
1497 github_repos=["acme/widget"],
1498 github_user="acme-dev",
1499 )
1500
1501 mock_project.assert_called_once()
1502 mock_person.assert_not_called()
1503 mock_retrieve.assert_not_called()
1504 if mode == "empty":
1505 assert report.source_status["github"].state == schema.NO_RESULTS
1506 assert "Project mode found no activity for acme/widget" in report.source_status["github"].detail
1507 else:
1508 assert report.source_status["github"].state == health.ERROR
1509 assert report.errors_by_source["github"] == "Project-mode failed: API down"
1510
1511
1512 # ---------------------------------------------------------------------------
1513 # HIGH-024: Digg enrichment skipped under mock=True
1514 # ---------------------------------------------------------------------------
1515
1516
1517 def test_high024_mock_run_skips_digg_enrich_source_items(monkeypatch):
1518 mock_digg_item = schema.SourceItem(
1519 item_id="mock2def",
1520 source="digg",
1521 title="Second Digg cluster on ai agents",
1522 body="Another angle on ai agents.",
1523 url="https://digg.com/ai/mock2def-ai-agents",
1524 engagement={"postCount": 3, "uniqueAuthors": 2, "rank": 18, "rank_score": 33.0},
1525 metadata={"posts": []},
1526 )
1527 called: list[int] = []
1528
1529 def fail_if_called(items, **kwargs):
1530 called.append(len(items))
1531 return items
1532
1533 monkeypatch.setattr(pipeline.digg, "enrich_source_items", fail_if_called)
1534
1535 # Mock finalize must not invoke digg.enrich_source_items or fixture_source_record.
1536 with mock.patch(
1537 "lib.http.fixture_source_record",
1538 side_effect=AssertionError("fixture_source_record must not fire for digg under mock=True"),
1539 ):
1540 finalized = pipeline._finalize_items_by_source(
1541 {"digg": [mock_digg_item]}, topic="ai agents", depth="quick", mock=True,
1542 )
1543 assert len(finalized["digg"]) == 1
1544 assert called == []
1545
1546 # Full mock pipeline.run() with digg must also never touch digg.enrich_source_items.
1547 report = pipeline.run(
1548 topic="ai agents",
1549 config={},
1550 depth="quick",
1551 requested_sources=["digg"],
1552 mock=True,
1553 web_backend="none",
1554 )
1555 assert report is not None
1556 assert called == []
1557
1558 # Positive control: mock=False still invokes digg.enrich_source_items.
1559 pipeline._finalize_items_by_source(
1560 {"digg": [mock_digg_item]}, topic="ai agents", depth="quick", mock=False,
1561 )
1562 assert called == [1]
1563
1563 lines PYTHON