返回 last30days-skill
pipeline.py
根目录 / skills / last30days / scripts / lib / pipeline.py
1 """v3.0.0 orchestration pipeline."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import contextvars
7 import copy
8 import functools
9 from collections.abc import Callable, Iterable, Iterator, Mapping
10 import heapq
11 import math
12 import os
13 import queue
14 import re
15 import sqlite3
16 import sys
17 import threading
18 import time
19 from collections import Counter, deque
20 from concurrent.futures import FIRST_COMPLETED, Future, as_completed, wait as futures_wait
21 from dataclasses import dataclass, field, replace
22 from datetime import date, datetime, timedelta, timezone
23 from pathlib import Path
24 from shutil import which
25 from typing import Any
26
27 _ORIGINAL_WHICH = which
28
29 from . import (
30 amazon,
31 arxiv,
32 bird_x,
33 bluesky,
34 brightdata,
35 company_resolve,
36 corpus,
37 dates,
38 dedupe,
39 deepline,
40 devto,
41 digg,
42 dripstack,
43 entity_extract,
44 env,
45 fetch_memo,
46 github,
47 grok_x,
48 grounding,
49 hackernews,
50 health,
51 hiring_signals,
52 http,
53 instagram,
54 jobs,
55 jobs_digest,
56 jobs_story,
57 juejin,
58 linkedin,
59 library,
60 library_index,
61 log,
62 meta_ads,
63 normalize,
64 permission_preflight,
65 perplexity,
66 person,
67 pinterest,
68 planner,
69 polymarket,
70 providers,
71 query,
72 reddit,
73 reddit_envelope,
74 reddit_health,
75 reddit_keyless,
76 reddit_listing,
77 reddit_public,
78 reddit_session,
79 relevance,
80 rerank,
81 schema,
82 shortform_envelope,
83 shortform_oss,
84 signals,
85 snippet,
86 stocktwits,
87 techmeme,
88 news_rss,
89 telegram,
90 threads,
91 tiktok,
92 topic_shape,
93 truthsocial,
94 trustpilot,
95 v2ex,
96 x_api,
97 x_envelope,
98 x_judge,
99 xai_x,
100 xiaohongshu_api,
101 xquik,
102 xurl_x,
103 youtube_yt,
104 )
105 from .cluster import cluster_candidates
106 from .cluster_diversity import diversify_clusters
107 from . import fusion
108 from . import render
109 from .fusion import collapse_duplicate_urls, source_item_key, weighted_rrf
110
111 DISCOVERY_SOURCES = ("reddit", "hackernews", "digg", "x")
112 _DISCOVERY_GENERIC_DOMAIN_TERMS = {
113 "ai", "artificial", "intelligence", "tech", "technology", "trending", "trend",
114 }
115
116 # ``digg_stream_limit`` is how many Digg stories one search keeps once the
117 # Digg bar has sorted them. It is higher than ``per_stream_limit`` because a
118 # Digg search now returns the highest-scored stories as well as the most
119 # relevant ones.
120 DEPTH_SETTINGS = {
121 "quick": {"per_stream_limit": 6, "digg_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
122 "default": {"per_stream_limit": 12, "digg_stream_limit": 20, "pool_limit": 40, "rerank_limit": 40},
123 "deep": {"per_stream_limit": 20, "digg_stream_limit": 30, "pool_limit": 60, "rerank_limit": 60},
124 }
125
126 SEARCH_ALIAS = {
127 "hn": "hackernews",
128 "dev.to": "devto",
129 "bsky": "bluesky",
130 "truth": "truthsocial",
131 "web": "grounding",
132 "xhs": "xiaohongshu",
133 "meta": "meta_ads",
134 "meta-ads": "meta_ads",
135 "xquik": "x", # xquik is a backend of the single "x" source, not its own source
136 }
137
138 # trustpilot is capped at 1: every subquery would use the identical company
139 # identifier, so N streams are pure redundancy -- and each extra stream risks
140 # its own WAF-cookie Chrome harvest.
141 # amazon is capped at 1 for the same reason as trustpilot: the model supplies
142 # one product keyword for the run, so every subquery would issue the identical
143 # product search. Extra streams would be pure redundancy at one credit each.
144 # meta_ads is capped at 1 for the same reason as amazon: one advertiser page is
145 # resolved per run, so every subquery would issue the identical page fetch.
146 MAX_SOURCE_FETCHES: dict[str, int] = {
147 "x": 2, "jobs": 1, "linkedin": 1, "stocktwits": 1, "trustpilot": 1, "amazon": 1,
148 "telegram": 1, "meta_ads": 1, "devto": 1, "v2ex": 1,
149 "juejin": 1,
150 }
151
152 # Sources whose thin result is their normal success state, so the "<3 items"
153 # retry would re-fetch them after every success -- bypassing
154 # MAX_SOURCE_FETCHES and, for the resolved-entity sources, re-resolving
155 # WITHOUT the caller's override (a lookalike-misattribution path).
156 # trustpilot returns at most ONE item by design.
157 # perplexity answers once per run.
158 # meta_ads resolves one advertiser page per run, so a brand that genuinely
159 # ran two creatives this month is complete; a retry would re-resolve the
160 # page and re-spend the discovery credit.
161 THIN_RETRY_EXEMPT: frozenset[str] = frozenset({"trustpilot", "perplexity", "meta_ads"})
162
163 # Stream-artifact keys promoted to named top-level report artifacts. A stream
164 # artifact only ever reaches the report as an anonymous entry in the grounding
165 # list, so anything the renderer needs by name has to be lifted out of it --
166 # most importantly on a zero-item run, which is exactly when naming the
167 # resolved advertiser and its counts matters most.
168 STREAM_ARTIFACT_LIFT_KEYS: tuple[str, ...] = ("meta_ads_page", "meta_ads_tally")
169
170 # Shared wall-clock bounds for fan-out waits (CR-012/CR-016). Each bounded
171 # fan-out waits with futures_wait(timeout=...) inside _abandoning_executor, so
172 # a hung lane degrades to a TIMEOUT partial instead of stalling run() forever.
173 # Worst case per stream is one timeout ceiling (+ one inline 5xx retry in the
174 # main fan-out, itself bounded by the lane's own timeouts); no new config knobs.
175 STREAM_FUTURE_TIMEOUT_SECONDS = 180.0
176 PLANNER_TIMEOUT_SECONDS = 30.0
177 _TRANSIENT_RETRY_DELAY_SECONDS = 3.0
178 # Leave time for the background adapter to return its final poll receipt.
179 DEEP_RESEARCH_RECEIPT_SECONDS = 1.0
180 # A job board lists the roles open today, so it cannot answer a window that
181 # ended in the past.
182 JOBS_PAST_WINDOW_SKIP = "skipped: a job board shows the roles open today, not those of a past window"
183 DISCOVERY_FUTURE_TIMEOUT_SECONDS = 60.0
184 # The keyless Reddit lane stops this long before the stream wait ends, which
185 # leaves time to return, normalize and score the threads it found.
186 REDDIT_LANE_RETURN_MARGIN_SECONDS = 20.0
187 # With a ScrapeCreators key the free lane stops this much earlier still, so a
188 # backfill of a thin or timed-out free result gets a turn inside the same wait.
189 REDDIT_SC_BACKFILL_RESERVE_SECONDS = 45.0
190 # A backfill is not started with less than this left, and is abandoned this
191 # long before the stream wait ends so the free threads are still returned.
192 REDDIT_SC_BACKFILL_MIN_SECONDS = 8.0
193 REDDIT_SC_BACKFILL_RETURN_MARGIN_SECONDS = 5.0
194 THIN_RETRY_FUTURE_TIMEOUT_SECONDS = 120.0
195 # Leave 20 seconds of the five-minute foreground window for report output.
196 FINALIZATION_WORK_CUTOFF_SECONDS = 280.0
197 DISCOVERY_FINALIZATION_RESERVE_SECONDS = 10.0
198 # One X source, ordered backends: grok (up to 240s/call) + xai (90-180s) would
199 # stack sequentially inside one unbounded future under MCP's kill. The chain
200 # owns a shared monotonic deadline (x_api's TIMEOUT 30/RETRIES 2/DEADLINE 90
201 # pattern); backends past the deadline are skipped.
202 X_CHAIN_DEADLINE_SECONDS = 90.0
203 # Ceiling for a user-set X chain budget. The measured grok call is 150-170s at
204 # the default depth, whose per-call ceiling is 240s (grok_x._TIMEOUT_SECONDS);
205 # a deep call can be bounded at 360s, but this chain knob only needs to cover
206 # the measured call plus headroom.
207 X_CHAIN_DEADLINE_MAX_SECONDS = 240.0
208 # Margin kept between the X chain budget and the stream wait that inherited it,
209 # so the lane can return, normalize and score the last call's items.
210 X_STREAM_WAIT_MARGIN_SECONDS = 10.0
211
212
213 def _research_stopped(config: dict[str, Any]) -> bool:
214 cancel = config.get("_enrich_cancel")
215 deadline = config.get("_research_deadline")
216 return bool(
217 (cancel is not None and cancel.is_set())
218 or (deadline is not None and time.monotonic() >= deadline)
219 )
220
221
222 def _research_deadline(config: dict[str, Any], seconds: float) -> float:
223 deadline = time.monotonic() + seconds
224 inherited = config.get("_research_deadline")
225 return min(deadline, inherited) if inherited is not None else deadline
226
227
228 def _x_lane_deadline(config: dict[str, Any], seconds: float) -> float:
229 """A supplemental X lane's own budget, never past the run's cutoff.
230
231 ``run()`` records its finalization cutoff in ``_finalization_deadline`` when
232 an explicit X budget raised the stream wait. The supplemental handle lanes
233 start after the main collection, so left on ``_research_deadline`` alone
234 their own budget can outlive that cutoff: a 200s X stream that uses most of
235 the window leaves a fresh 150s lane (grok and the bird/xapi/xquik lanes
236 share that constant) running past the host's finalization deadline. Clamp
237 every supplemental lane to the recorded cutoff, and keep the previous
238 behaviour when no cutoff was recorded.
239 """
240 deadline = _research_deadline(config, seconds)
241 cutoff = config.get("_finalization_deadline")
242 return min(deadline, cutoff) if cutoff is not None else deadline
243
244
245 def _configured_x_budget_seconds(config: dict[str, Any]) -> float | None:
246 """The explicit LAST30DAYS_X_BUDGET_SECONDS value, or None when unusable."""
247 raw = config.get("LAST30DAYS_X_BUDGET_SECONDS")
248 if raw is None or str(raw).strip() == "":
249 return None
250 try:
251 value = float(raw)
252 except (TypeError, ValueError):
253 return None
254 if not math.isfinite(value) or value <= 0:
255 return None
256 return min(value, X_CHAIN_DEADLINE_MAX_SECONDS)
257
258
259 def _x_chain_budget_seconds(config: dict[str, Any]) -> float:
260 """X chain budget: the explicit setting, else the fixed 90s default."""
261 budget = _configured_x_budget_seconds(config)
262 return X_CHAIN_DEADLINE_SECONDS if budget is None else budget
263
264
265 def _plan_includes_x(plan: schema.DiscoveryPlan, available: Any) -> bool:
266 """Whether this plan schedules an X stream in the main fan-out."""
267 return "x" in available and any(
268 "x" in subquery.sources for subquery in plan.subqueries
269 )
270
271
272 def _x_lane_scheduled(
273 plan: schema.DiscoveryPlan, available: Any, config: dict[str, Any],
274 ) -> bool:
275 """Whether a configured X stream will actually be submitted."""
276 if not _plan_includes_x(plan, available):
277 return False
278 cap = _source_fetch_cap("x", config)
279 return cap is None or cap > 0
280
281
282 def _x_stream_wait_seconds(config: dict[str, Any]) -> float:
283 """Stream wait that covers an explicitly configured X chain budget."""
284 budget = _configured_x_budget_seconds(config)
285 if budget is None:
286 return STREAM_FUTURE_TIMEOUT_SECONDS
287 return max(
288 STREAM_FUTURE_TIMEOUT_SECONDS,
289 budget + X_STREAM_WAIT_MARGIN_SECONDS,
290 )
291
292
293 def _finalization_deadline(config: dict[str, Any], run_started: float) -> float:
294 if config.get("_deep_research"):
295 if "_finalization_deadline" in config:
296 deadline = config["_finalization_deadline"]
297 else:
298 deadline = (
299 run_started
300 + perplexity.deep_timeout_seconds(config)
301 + DEEP_RESEARCH_RECEIPT_SECONDS
302 + FINALIZATION_WORK_CUTOFF_SECONDS
303 )
304 else:
305 deadline = run_started + FINALIZATION_WORK_CUTOFF_SECONDS
306 deadline = min(deadline, config.get("_finalization_deadline", deadline))
307 inherited = config.get("_research_deadline")
308 if inherited is not None:
309 deadline = min(deadline, inherited - DISCOVERY_FINALIZATION_RESERVE_SECONDS)
310 return deadline
311
312
313 def _check_research(config: dict[str, Any]) -> None:
314 if _research_stopped(config):
315 raise TimeoutError("research budget exhausted or cancelled")
316
317
318 def _wait_for_research(futures, config: dict[str, Any]):
319 pending = set(futures)
320 done = set()
321 while pending and not _research_stopped(config):
322 remaining = config["_research_deadline"] - time.monotonic()
323 completed, pending = futures_wait(
324 pending, timeout=max(0, min(0.1, remaining)), return_when=FIRST_COMPLETED,
325 )
326 done.update(completed)
327 # Rescue any future that finished right as the deadline elapsed so
328 # completed results are never dropped and misclassified as TIMEOUT.
329 finished = {f for f in pending if f.done() and not f.cancelled()}
330 if finished:
331 done.update(finished)
332 pending -= finished
333 return done, pending
334
335
336 def _run_transient_retry(
337 retry_config: dict[str, Any],
338 fn: Callable[..., Any],
339 kwargs: dict[str, Any],
340 ) -> Any:
341 _check_research(retry_config)
342 return fn(**kwargs)
343
344
345 def _delayed_retry(
346 retry_at: float,
347 retry_config: dict[str, Any],
348 fn: Callable[..., Any],
349 kwargs: dict[str, Any],
350 ) -> Any:
351 cancel = retry_config.get("_enrich_cancel")
352 deadline = retry_config.get("_research_deadline")
353 wait_until = min(retry_at, deadline) if deadline is not None else retry_at
354 wait_seconds = max(0.0, wait_until - time.monotonic())
355 if wait_seconds > 0:
356 if cancel is None:
357 time.sleep(wait_seconds)
358 else:
359 cancel.wait(wait_seconds)
360 return _run_transient_retry(retry_config, fn, kwargs)
361
362
363 def _completed_streams(
364 batches,
365 bundle: schema.RetrievalBundle,
366 retry_origins: dict[Any, Exception] | None = None,
367 ):
368 for futures, wait_config, wait_deadline, _keep_ready in batches:
369 # Every batch carries an absolute monotonic deadline fixed before
370 # fan-out, so time spent submitting the streams cannot push the wait
371 # past the run's finalization cutoff. The batch's own research
372 # deadline can only shorten it further.
373 deadline = wait_deadline
374 inherited = wait_config.get("_research_deadline")
375 if inherited is not None:
376 deadline = min(deadline, inherited)
377 collection_wait = max(0.0, deadline - time.monotonic())
378 yielded: set[Any] = set()
379 while not _research_stopped(wait_config):
380 pending = {f for f in futures if f not in yielded}
381 if not pending:
382 break
383 remaining = deadline - time.monotonic()
384 completed, _ = futures_wait(
385 pending,
386 timeout=max(0, min(0.1, remaining)),
387 return_when=FIRST_COMPLETED,
388 )
389 for future in completed:
390 yielded.add(future)
391 subquery, source = futures[future]
392 yield future, subquery, source, False
393 pending = {f for f in futures if f not in yielded}
394 finished = {f for f in pending if f.done() and not f.cancelled()}
395 timed_out_futures = pending - finished
396 for future in timed_out_futures:
397 _subquery, source = futures[future]
398 future.cancel()
399 if future.done() and not future.cancelled():
400 finished.add(future)
401 continue
402 # Report the wait the collector actually had, not the pre-fan-out
403 # budget, so a cutoff-clamped wait is never mislabelled.
404 detail = f"{source} timed out after {collection_wait:g}s"
405 if retry_origins is not None and future in retry_origins:
406 detail = f"{retry_origins[future]} (retried once, still failed: {detail})"
407 bundle.errors_by_source[source] = detail
408 bundle.record_failure(source, health.TIMEOUT, detail, attempted=True)
409 for future in finished:
410 yielded.add(future)
411 subquery, source = futures[future]
412 yield future, subquery, source, True
413
414
415 class _DaemonExecutor:
416 """Bounded daemon-thread executor returning standard ``Future`` objects.
417
418 Unlike ``concurrent.futures.ThreadPoolExecutor``, worker threads are
419 created as daemon threads and never register in
420 ``concurrent.futures.thread._threads_queues``. Abandoned stragglers
421 therefore cannot block Python interpreter shutdown.
422
423 Supports :meth:`submit_delayed` for retries whose backoff consumes zero
424 worker slots while waiting and whose ready work runs ahead of queued
425 regular submissions. When all ``max_workers`` regular workers are busy and
426 a delayed or priority retry needs to run, at most one bounded overflow
427 daemon worker is spawned for priority retries only (never regular work).
428 """
429
430 def __init__(self, max_workers: int) -> None:
431 self._max_workers = max(1, int(max_workers))
432 self._cond = threading.Condition(threading.Lock())
433 self._priority_pending: deque[
434 tuple[Future, Callable[..., Any], tuple[Any, ...], dict[str, Any]]
435 ] = deque()
436 self._pending: deque[
437 tuple[Future, Callable[..., Any], tuple[Any, ...], dict[str, Any]]
438 ] = deque()
439 self._delayed: list[
440 tuple[float, int, Future, Callable[..., Any], tuple[Any, ...], dict[str, Any]]
441 ] = []
442 self._threads: set[threading.Thread] = set()
443 self._overflow_worker: threading.Thread | None = None
444 self._idle_workers = 0
445 self._shutdown = False
446 self._next_worker_id = 0
447 self._next_seq = 0
448
449 def _spawn_worker_locked(self) -> None:
450 worker_id = self._next_worker_id
451 self._next_worker_id += 1
452 worker = threading.Thread(
453 target=self._worker_loop,
454 name=f"last30days-daemon-{worker_id}",
455 daemon=True,
456 )
457 self._threads.add(worker)
458 worker.start()
459
460 def _ensure_workers_locked(self) -> None:
461 ready_count = len(self._priority_pending) + len(self._pending)
462 timer_slot = 1 if self._delayed else 0
463 needed = (ready_count + timer_slot) - self._idle_workers
464 while needed > 0 and len(self._threads) < self._max_workers:
465 self._spawn_worker_locked()
466 needed -= 1
467 if (
468 (self._delayed or self._priority_pending)
469 and self._idle_workers == 0
470 and len(self._threads) >= self._max_workers
471 and self._overflow_worker is None
472 ):
473 worker = threading.Thread(
474 target=self._overflow_worker_loop,
475 name="last30days-daemon-retry-overflow",
476 daemon=True,
477 )
478 self._overflow_worker = worker
479 worker.start()
480
481 def _execute_item(
482 self,
483 item: tuple[Future, Callable[..., Any], tuple[Any, ...], dict[str, Any]],
484 ) -> None:
485 future, fn, args, kwargs = item
486 if not future.set_running_or_notify_cancel():
487 return
488 try:
489 result = fn(*args, **kwargs)
490 except BaseException as exc:
491 future.set_exception(exc)
492 else:
493 future.set_result(result)
494
495 def _promote_delayed_locked(self) -> int:
496 promoted = 0
497 now = time.monotonic()
498 while self._delayed:
499 ready_at, _seq, future, fn, args, kwargs = self._delayed[0]
500 if future.cancelled():
501 heapq.heappop(self._delayed)
502 continue
503 if ready_at > now:
504 break
505 heapq.heappop(self._delayed)
506 self._priority_pending.append((future, fn, args, kwargs))
507 promoted += 1
508 return promoted
509
510 def submit(self, fn: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Future:
511 ctx = contextvars.copy_context()
512 with self._cond:
513 if self._shutdown:
514 raise RuntimeError("cannot schedule new futures after shutdown")
515 future: Future = Future()
516 self._pending.append((future, ctx.run, (fn, *args), kwargs))
517 self._ensure_workers_locked()
518 self._cond.notify()
519 return future
520
521 def submit_delayed(
522 self, ready_at: float, fn: Callable[..., Any], /, *args: Any, **kwargs: Any,
523 ) -> Future:
524 ctx = contextvars.copy_context()
525 with self._cond:
526 if self._shutdown:
527 raise RuntimeError("cannot schedule new futures after shutdown")
528 future: Future = Future()
529 if ready_at <= time.monotonic():
530 self._priority_pending.append((future, ctx.run, (fn, *args), kwargs))
531 self._ensure_workers_locked()
532 self._cond.notify()
533 else:
534 seq = self._next_seq
535 self._next_seq += 1
536 heapq.heappush(self._delayed, (ready_at, seq, future, ctx.run, (fn, *args), kwargs))
537 self._ensure_workers_locked()
538 self._cond.notify_all()
539 return future
540
541 def _worker_loop(self) -> None:
542 try:
543 while True:
544 with self._cond:
545 while True:
546 self._promote_delayed_locked()
547 if self._priority_pending:
548 item = self._priority_pending.popleft()
549 elif self._pending:
550 item = self._pending.popleft()
551 else:
552 item = None
553 if item is not None:
554 self._ensure_workers_locked()
555 if (
556 self._priority_pending
557 or self._pending
558 or self._overflow_worker is not None
559 ):
560 self._cond.notify_all()
561 break
562 if self._shutdown and not self._delayed:
563 return
564 wait_timeout = (
565 max(0.0, self._delayed[0][0] - time.monotonic())
566 if self._delayed else None
567 )
568 self._idle_workers += 1
569 try:
570 self._cond.wait(timeout=wait_timeout)
571 finally:
572 self._idle_workers -= 1
573 self._execute_item(item)
574 item = None
575 finally:
576 with self._cond:
577 self._threads.discard(threading.current_thread())
578
579 def _overflow_worker_loop(self) -> None:
580 try:
581 while True:
582 with self._cond:
583 while True:
584 self._promote_delayed_locked()
585 if self._priority_pending:
586 if self._idle_workers > 0:
587 self._cond.notify_all()
588 self._cond.wait(timeout=0.05)
589 continue
590 item = self._priority_pending.popleft()
591 if self._priority_pending:
592 self._cond.notify_all()
593 break
594 if self._delayed:
595 if self._idle_workers > 0:
596 self._cond.notify_all()
597 self._overflow_worker = None
598 return
599 wait_timeout = max(0.0, self._delayed[0][0] - time.monotonic())
600 self._cond.wait(timeout=wait_timeout)
601 continue
602 self._overflow_worker = None
603 return
604 self._execute_item(item)
605 item = None
606 finally:
607 with self._cond:
608 if self._overflow_worker is threading.current_thread():
609 self._overflow_worker = None
610
611 def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
612 with self._cond:
613 self._shutdown = True
614 if cancel_futures:
615 while self._delayed:
616 _ready_at, _seq, future, _fn, _args, _kwargs = heapq.heappop(self._delayed)
617 future.cancel()
618 while self._priority_pending:
619 future, _fn, _args, _kwargs = self._priority_pending.popleft()
620 future.cancel()
621 while self._pending:
622 future, _fn, _args, _kwargs = self._pending.popleft()
623 future.cancel()
624 self._cond.notify_all()
625 threads = list(self._threads) if wait else []
626 if wait and self._overflow_worker is not None:
627 threads.append(self._overflow_worker)
628 current = threading.current_thread()
629 for thread in threads:
630 if thread is not current:
631 thread.join()
632
633 def __enter__(self) -> _DaemonExecutor:
634 return self
635
636 def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
637 self.shutdown(wait=True)
638
639
640 @contextlib.contextmanager
641 def _abandoning_executor(max_workers: int) -> Iterator[_DaemonExecutor]:
642 """Bounded daemon-thread executor whose exit never joins running workers.
643
644 Exiting with ``shutdown(wait=False, cancel_futures=True)`` cancels queued
645 work and abandons any timed-out stragglers without registering threads in
646 ``concurrent.futures.thread._threads_queues``, so stragglers cannot block
647 either the caller or interpreter exit.
648 """
649 pool = _DaemonExecutor(max_workers=max_workers)
650 try:
651 yield pool
652 finally:
653 pool.shutdown(wait=False, cancel_futures=True)
654
655
656 def _lift_stream_artifacts(bundle) -> None:
657 """Promote per-stream artifacts the renderer reads by name."""
658 for stream_artifact in bundle.artifacts.get("grounding", []):
659 if not isinstance(stream_artifact, dict):
660 continue
661 for key in STREAM_ARTIFACT_LIFT_KEYS:
662 value = stream_artifact.get(key)
663 if value:
664 bundle.artifacts[key] = value
665
666
667 _FAILURE_SPECIFICITY = health.FAILURE_SPECIFICITY
668 _JOBS_LANE_LOCK = threading.Lock()
669 _SINGLE_FETCH_ONLY_SOURCES: frozenset[str] = frozenset({
670 "perplexity", "jobs", "trustpilot", "amazon", "meta_ads",
671 })
672
673
674 @dataclass
675 class PaidSourceBudget:
676 """Command-wide, thread-safe budget for paid source adapter calls."""
677
678 used: int = 0
679 owner: str | None = None
680 _lock: Any = field(default_factory=threading.Lock, repr=False)
681
682 def try_consume(self, limit: int, *, claimant: str | None = None) -> bool:
683 with self._lock:
684 if self.owner is not None and claimant != self.owner:
685 return False
686 if self.used >= limit:
687 return False
688 self.used += 1
689 return True
690
691
692 def _source_fetch_cap(source: str, config: dict[str, Any]) -> int | None:
693 """Return the effective per-run cap for one source.
694
695 Perplexity, jobs, trustpilot, amazon, and meta_ads are single-entity or
696 shared-state sources (and/or paid per call). A generic fetch-cap override
697 may lower their cap (e.g. to 0) but must not multiply them past 1 across
698 planner subqueries.
699 """
700 override = config.get("_max_source_fetches")
701 if source in _SINGLE_FETCH_ONLY_SOURCES:
702 return 1 if override is None else max(0, min(1, int(override)))
703 cap = MAX_SOURCE_FETCHES.get(source)
704 if cap is not None and override is not None:
705 return max(0, int(override))
706 return cap
707
708
709 def _resolve_depth_settings(depth: str, config: dict[str, Any]) -> dict[str, int]:
710 """Depth profile with optional CLI cap overrides applied (issue #716).
711
712 Returns a copy so the module-level DEPTH_SETTINGS is never mutated. Overrides
713 are applied as given (not max()'d against the default) so callers can also
714 lower a cap; negative values are floored at 0. `--max-results`
715 raises the final ranked pool (pool_limit/rerank_limit); `--max-per-source`
716 raises the per-stream truncation applied before pooling, Digg's included. The per-source fetch
717 cap (`--max-source-fetches`) is applied separately at the fetch site.
718 """
719 settings = dict(DEPTH_SETTINGS[depth])
720 # `is not None` (not truthiness) so an explicit 0 is honored as a real lower
721 # bound rather than ignored as "unset" — matches how main() stashes these.
722 # The caps are used directly as slice bounds, where a negative value keeps
723 # every item except the last |cap| instead of capping the stream, so floor
724 # them at 0 (the documented lower bound, as `_source_fetch_cap` does).
725 max_per_source = config.get("_max_per_source")
726 if max_per_source is not None:
727 per_stream_limit = max(0, int(max_per_source))
728 settings["per_stream_limit"] = per_stream_limit
729 settings["digg_stream_limit"] = per_stream_limit
730 max_results = config.get("_max_results")
731 if max_results is not None:
732 pool_limit = max(0, int(max_results))
733 settings["pool_limit"] = pool_limit
734 settings["rerank_limit"] = pool_limit
735 return settings
736
737 # Per-handle result caps for the X handle-search lanes. The FROM lane (the
738 # subject's own timeline) is the single best source for a person topic, so it
739 # gets the highest cap; the ABOUT (mention) and related-handle lanes stay
740 # modest so total volume and request budget don't balloon.
741 FROM_LANE_COUNT_PER = 8
742 MENTION_LANE_COUNT_PER = 5
743 RELATED_HANDLE_COUNT_PER = 3
744
745
746 def _has_perplexity_provider(config: dict[str, Any]) -> bool:
747 # Prefer direct Agent/Search APIs, but preserve the synchronous OpenRouter
748 # Sonar fallback for existing installs.
749 return bool(
750 config.get("PERPLEXITY_API_KEY") or config.get("OPENROUTER_API_KEY")
751 )
752
753 MOCK_AVAILABLE_SOURCES = [
754 "reddit",
755 "x",
756 "youtube",
757 "tiktok",
758 "instagram",
759 "hackernews",
760 "bluesky",
761 "truthsocial",
762 "polymarket",
763 "grounding",
764 "xiaohongshu",
765 "github",
766 "perplexity",
767 "threads",
768 "pinterest",
769 "digg",
770 "arxiv",
771 "techmeme",
772 "news_rss",
773 "trustpilot",
774 "amazon",
775 "meta_ads",
776 "jobs",
777 "linkedin",
778 "corpus",
779 "dripstack",
780 "telegram",
781 "devto",
782 "v2ex",
783 "juejin",
784 ]
785
786 # Full set of searchable source names accepted by --search /
787 # LAST30DAYS_DEFAULT_SEARCH. Superset of MOCK_AVAILABLE_SOURCES so live-only
788 # sources without mock fixtures (e.g. StockTwits) are accepted on the CLI
789 # without altering mock-mode source availability.
790 KNOWN_SEARCH_SOURCES: frozenset[str] = frozenset(MOCK_AVAILABLE_SOURCES) | {"stocktwits"}
791
792
793 def normalize_requested_sources(sources: list[str] | None) -> list[str] | None:
794 if not sources:
795 return None
796 normalized = []
797 for source in sources:
798 key = SEARCH_ALIAS.get(source.lower(), source.lower())
799 if key not in normalized:
800 normalized.append(key)
801 return normalized
802
803
804 def _excluded_sources(config: dict[str, Any]) -> set[str]:
805 return env.exclude_sources(config)
806
807
808 def with_plan_source_omissions(
809 config: dict[str, Any], plan: dict | None,
810 ) -> dict[str, Any]:
811 """Apply a validated plan's exclusions without changing shared configuration."""
812 omissions = (plan or {}).get("omit_sources")
813 if not omissions:
814 return config
815 excluded = _excluded_sources(config).union(omissions)
816 return {**config, "EXCLUDE_SOURCES": ",".join(sorted(excluded))}
817
818
819 class NoRequestedSourceAvailable(RuntimeError):
820 """None of the sources the user asked for with --search is configured."""
821
822
823 _ORIGINAL_IS_YTDLP_INSTALLED = youtube_yt.is_ytdlp_installed
824
825
826 def _resolve_ytdlp(config: Mapping[str, Any] | None = None) -> tuple[bool, str | None]:
827 """Return ``(has_ytdlp, validated_ssh_host)``, validating the SSH alias once."""
828 raw_ssh = (config or {}).get("LAST30DAYS_YOUTUBE_SSH_HOST")
829 with youtube_yt.ssh_host_scope(raw_ssh):
830 ssh_host = youtube_yt._ytdlp_ssh_host()
831 if ssh_host:
832 return True, ssh_host
833 if which is not _ORIGINAL_WHICH:
834 return bool(which("yt-dlp")), None
835 # Clear any rejected config alias so is_ytdlp_installed() does not re-warn;
836 # if an invalid alias lives in os.environ, bypass _ytdlp_ssh_host unless
837 # is_ytdlp_installed was monkeypatched by a test.
838 with youtube_yt.ssh_host_scope(None):
839 if (
840 "LAST30DAYS_YOUTUBE_SSH_HOST" in os.environ
841 and youtube_yt.is_ytdlp_installed is _ORIGINAL_IS_YTDLP_INSTALLED
842 ):
843 return youtube_yt.shutil.which("yt-dlp") is not None, None
844 return youtube_yt.is_ytdlp_installed(), None
845
846
847 def _has_ytdlp(config: Mapping[str, Any] | None = None) -> bool:
848 """Return True when yt-dlp is available locally or via SSH routing."""
849 return _resolve_ytdlp(config)[0]
850
851
852 def available_sources(
853 config: dict[str, Any],
854 requested_sources: list[str] | None = None,
855 *,
856 x_pending: bool | None = None,
857 local_only: bool = False,
858 x_envelope: bool = False,
859 suppress_x_host_lane: bool = False,
860 ) -> list[str]:
861 """List the sources the next run can serve.
862
863 ``local_only=True`` is the safe/diagnose flavor (doctor's permission
864 block): availability is answered from local evidence only, so the X
865 check never spawns xurl's live ``whoami`` network call. Research-time
866 callers keep the default live semantics.
867
868 X is listed when an engine backend is available, or browser auth is
869 pending, or the hosting model declared the X connector lane
870 (``env.x_host_lane_declared``), or a validated ``--x-posts`` envelope is
871 present for this run (``x_envelope``), in every cookie mode.
872 ``suppress_x_host_lane`` turns only the lane branch off (discovery
873 enrichment passes); an envelope still counts.
874 """
875 available: list[str] = []
876 # reddit_public needs no API key - always available
877 available.append("reddit")
878 if corpus.resolve_directories(
879 config.get("_CORPUS_DIRS"), config.get("LAST30DAYS_CORPUS_DIRS")
880 ):
881 available.append("corpus")
882 has_ytdlp, validated_ssh = _resolve_ytdlp(config)
883 with youtube_yt.ssh_host_scope(validated_ssh):
884 if env.is_tiktok_available(config):
885 available.append("tiktok")
886 if env.is_instagram_available(config):
887 available.append("instagram")
888 if env.get_x_source(config, local_only=local_only):
889 available.append("x")
890 elif x_envelope or (
891 not suppress_x_host_lane and env.x_host_lane_declared(config)
892 ):
893 # Host-fetched X lane: the model passes connector results through
894 # --x-posts, so X is served without an engine backend.
895 available.append("x")
896 else:
897 # Safe inspection (--diagnose/--preflight) skips browser-cookie
898 # extraction, so get_x_source is None even though a real run would
899 # authenticate X via FROM_BROWSER. Report it as available so consumers
900 # of available_sources (SKILL.md ACTIVE_SOURCES_LIST) don't under-report.
901 # diagnose() precomputes the predicate and passes it via x_pending to
902 # avoid evaluating it twice in one diagnose() call.
903 if x_pending is None:
904 x_pending = env.x_pending_browser_auth(config, local_only=local_only)
905 if x_pending and health.probe_dependency("node").status == health.OK:
906 available.append("x")
907 if has_ytdlp or env.is_youtube_sc_available(config):
908 available.append("youtube")
909 available.extend(["hackernews", "polymarket"])
910 # StockTwits is gated to ticker/crypto topics only (flag set in run()).
911 if config.get("_financial_topic"):
912 available.append("stocktwits")
913 # GitHub is reachable via the unauthenticated REST tier too, so it is
914 # available even without a token/gh CLI (a token only raises rate limits).
915 available.append("github")
916 # DripStack is opt-in only (owner decision, #791): a commercial
917 # third-party API must never receive default-run traffic. Opt in per run
918 # (--search dripstack) or persistently (INCLUDE_SOURCES=dripstack in
919 # .env, the LinkedIn/Perplexity pattern); the search API is free and
920 # public (no key), so the opt-in itself is the gate.
921 include_sources = {
922 token.strip()
923 for token in (config.get("INCLUDE_SOURCES") or "").lower().split(",")
924 if token.strip()
925 }
926 if "dripstack" in include_sources or (
927 requested_sources and "dripstack" in requested_sources
928 ):
929 available.append("dripstack")
930 # dev.to follows the same default-off policy. Host-inferred tags
931 # (--devto-tags) activate it for that run, the --trustpilot-domain idiom,
932 # so tech topics get it without default runs sending every topic there.
933 if (
934 "devto" in include_sources
935 or (requested_sources and "devto" in requested_sources)
936 or config.get("_devto_tags")
937 ):
938 available.append("devto")
939 # V2EX is opt-in for the same reason: SOV2EX is a community-run index
940 # that should only see queries from users who asked for V2EX.
941 if "v2ex" in include_sources or (
942 requested_sources and "v2ex" in requested_sources
943 ):
944 available.append("v2ex")
945 # Juejin is opt-in like dev.to and V2EX: its search API serves Juejin's
946 # own web client and should only see queries from users who asked for it.
947 if "juejin" in include_sources or (
948 requested_sources and "juejin" in requested_sources
949 ):
950 available.append("juejin")
951 if which("digg-pp-cli"):
952 available.append("digg")
953 # arXiv is default-on when its Printing Press CLI is installed (zero auth).
954 # The adapter relevance-and-recency gates so it stays quiet off-topic.
955 if which("arxiv-pp-cli"):
956 available.append("arxiv")
957 # Techmeme is default-on when its CLI is installed (zero auth; sub-second
958 # local sync before each run's first search).
959 if which("techmeme-pp-cli"):
960 available.append("techmeme")
961 # News RSS is default-on when its Printing Press CLI is installed (free,
962 # keyless Google News + Bing News RSS + optional synced OPML feeds).
963 if which("news-rss-pp-cli"):
964 available.append("news_rss")
965 if env.is_bluesky_available(config):
966 available.append("bluesky")
967 if env.is_truthsocial_available(config):
968 available.append("truthsocial")
969 # Grounding (general web) is available when a paid backend is configured OR
970 # the keyless floor is permitted (i.e. the host has no native search). On a
971 # native-search host with no paid key, keyless_web_allowed is False and the
972 # engine leaves general web to the model's own search.
973 if (config.get("BRAVE_API_KEY") or config.get("EXA_API_KEY")
974 or config.get("SERPER_API_KEY") or config.get("PARALLEL_API_KEY")
975 or env.keyless_web_allowed(config)):
976 available.append("grounding")
977 if requested_sources and "jobs" in requested_sources:
978 available.append("jobs")
979 # Perplexity Agent API: opt-in additive source via INCLUDE_SOURCES=perplexity
980 if _has_perplexity_provider(config) and (
981 "perplexity" in include_sources or (requested_sources and "perplexity" in requested_sources)
982 ):
983 available.append("perplexity")
984 # LinkedIn: opt-in additive source via INCLUDE_SOURCES=linkedin (same
985 # consent pattern as Perplexity). Unlike tiktok/instagram, which are
986 # offered during SKILL.md Step 0 onboarding, LinkedIn is power-user-only
987 # and must not silently activate for existing SCRAPECREATORS_API_KEY
988 # holders.
989 if config.get("SCRAPECREATORS_API_KEY") and (
990 "linkedin" in include_sources or (requested_sources and "linkedin" in requested_sources)
991 ):
992 available.append("linkedin")
993 # The person's own LinkedIn posts: a person run only, with a profile read
994 # from an anchored URL. Never a keyword search, so no other run gets it.
995 if _person_posts_mode(config):
996 available.append(PERSON_POSTS_SOURCE)
997 # Trustpilot: opt-in additive source via INCLUDE_SOURCES=trustpilot (same
998 # consent pattern as Perplexity/LinkedIn). Off by default -- unlike arXiv and
999 # Techmeme, which are zero-auth, it can spawn a one-time headless-Chrome WAF
1000 # cookie harvest on a brand topic, so activating it is the user's choice.
1001 if (
1002 which("trustpilot-pp-cli")
1003 and trustpilot._harvest_allowed(config)
1004 and (
1005 "trustpilot" in include_sources
1006 or (requested_sources and "trustpilot" in requested_sources)
1007 )
1008 ):
1009 available.append("trustpilot")
1010 # Amazon: opt-in additive source, dual-gated. The Bright Data CLI must be
1011 # on the agent subprocess PATH and carry a credential signal, AND the run
1012 # must ask for it -- the model per-run via --search, or the user durably
1013 # via INCLUDE_SOURCES=amazon. Never inferred from topic shape: the engine
1014 # misroutes most shopping phrasings, and auto-firing would spend a CLI
1015 # owner's credits on runs that have nothing to do with products.
1016 if brightdata.is_available(config) and (
1017 "amazon" in include_sources or (requested_sources and "amazon" in requested_sources)
1018 ):
1019 available.append("amazon")
1020 # Meta Ads: opt-in additive source on the Amazon precedent. The
1021 # ScrapeCreators key must be present AND the run must ask for it -- the
1022 # model per-run via --search, or the user durably via
1023 # INCLUDE_SOURCES=meta_ads. Never inferred from topic shape: keyword ad
1024 # search on a non-brand topic returns a wrong-entity advertiser, and
1025 # auto-firing would spend credits resolving it.
1026 if config.get("SCRAPECREATORS_API_KEY") and (
1027 "meta_ads" in include_sources
1028 or (requested_sources and "meta_ads" in requested_sources)
1029 ):
1030 available.append("meta_ads")
1031 exclude = _excluded_sources(config)
1032 if (
1033 "xiaohongshu" not in exclude
1034 and (
1035 "xiaohongshu" in include_sources
1036 or (requested_sources and "xiaohongshu" in requested_sources)
1037 )
1038 and env.is_xiaohongshu_available(config)
1039 ):
1040 available.append("xiaohongshu")
1041 # Threads: opt-in via INCLUDE_SOURCES (same pattern as perplexity/linkedin).
1042 # Was auto-on with the key; gated so the onboarding "Everything" tier is a
1043 # real choice vs the "Recommended" (TikTok/Instagram) tier.
1044 if env.is_threads_available(config) and (
1045 "threads" in include_sources or (requested_sources and "threads" in requested_sources)
1046 ):
1047 available.append("threads")
1048 # Pinterest: opt-in via INCLUDE_SOURCES. Previously read requested_sources
1049 # only, so a persisted INCLUDE_SOURCES=pinterest never activated it; now it
1050 # honors both the per-run --sources list and the saved config.
1051 if env.is_pinterest_available(config) and (
1052 "pinterest" in include_sources or (requested_sources and "pinterest" in requested_sources)
1053 ):
1054 available.append("pinterest")
1055 # Telegram: opt-in via INCLUDE_SOURCES AND requires a channel list. The
1056 # channel list (TELEGRAM_SOURCES env or --telegram-sources CLI) is the gate:
1057 # without named channels there is no discovery endpoint to call.
1058 if config.get("SCRAPECREATORS_API_KEY") and (
1059 "telegram" in include_sources or (requested_sources and "telegram" in requested_sources)
1060 ):
1061 if telegram.is_telegram_configured(config):
1062 available.append("telegram")
1063 # xquik is a backend of the single "x" source (see env.x_backend_chain),
1064 # not a separate parallel source — registered via the "x" entry above.
1065 if exclude:
1066 available = [s for s in available if s not in exclude]
1067 return available
1068
1069
1070 def _mock_discovery_items(
1071 source: str,
1072 domain: str,
1073 to_date: str,
1074 ) -> list[dict[str, Any]]:
1075 """Deterministic listing fixtures for the public --mock CLI contract."""
1076 labels = [
1077 "Agent memory protocols",
1078 "Browser-using agents",
1079 "Local agent runtimes",
1080 "Multi-agent orchestration",
1081 "Agent security sandboxes",
1082 "Voice agent latency",
1083 ]
1084 end = datetime.fromisoformat(to_date).date()
1085 items: list[dict[str, Any]] = []
1086 for index, label in enumerate(labels, start=1):
1087 published = (end - timedelta(days=index)).isoformat()
1088 slug = re.sub(r"[^a-z0-9]+", "-", label.lower()).strip("-")
1089 if source == "reddit":
1090 items.append({
1091 "id": f"discovery-r-{index}",
1092 "title": label,
1093 "url": f"https://reddit.com/r/example/comments/{slug}",
1094 "subreddit": "example",
1095 "date": published,
1096 "engagement": {"score": 180 - index * 10, "num_comments": 30 + index},
1097 "selftext": label,
1098 "relevance": 0.9,
1099 "why_relevant": "Mock discovery listing",
1100 })
1101 elif source == "hackernews":
1102 items.append({
1103 "id": f"discovery-hn-{index}",
1104 "title": label,
1105 "url": f"https://example.com/{slug}",
1106 "hn_url": f"https://news.ycombinator.com/item?id={index}",
1107 "author": f"example{index}",
1108 "date": published,
1109 "engagement": {"points": 120 - index * 8, "comments": 20 + index},
1110 "relevance": 0.88,
1111 "why_relevant": "Mock HN discovery listing",
1112 })
1113 elif source == "digg":
1114 items.append({
1115 "id": f"discovery-d-{index}",
1116 "title": label,
1117 "url": f"https://digg.com/ai/{slug}",
1118 "tldr": label,
1119 "date": published,
1120 "engagement": {"postCount": 30 - index, "uniqueAuthors": 12 - index},
1121 "relevance": 0.9,
1122 "why_relevant": "Mock Digg discovery cluster",
1123 })
1124 elif source == "x":
1125 items.append({
1126 "id": f"discovery-x-{index}",
1127 "text": label,
1128 "url": f"https://x.com/example{index}/status/{index}",
1129 "author_handle": f"example{index}",
1130 "date": published,
1131 "engagement": {"likes": 140 - index * 9, "reposts": 18 + index},
1132 "relevance": 0.9,
1133 "why_relevant": "Mock X discovery activity",
1134 })
1135 return items
1136
1137
1138 def _matches_discovery_domain(domain: str, text: str) -> bool:
1139 """Require a distinctive domain term, not a generic token such as ``AI``."""
1140 def terms(value: str) -> set[str]:
1141 # Keep BOTH the surface form and the naive stem: replacing the token
1142 # broke non-plurals ("bias" -> "bia", "crisis" -> "crisi") so in-domain
1143 # listings stopped intersecting. The union preserves plural matching
1144 # without corrupting the anchor.
1145 words: set[str] = set()
1146 for word in relevance.tokenize(value):
1147 words.add(word)
1148 if len(word) > 4 and word.endswith("s") and not word.endswith("ss"):
1149 words.add(word[:-1])
1150 return words
1151
1152 domain_terms = terms(domain)
1153 anchors = domain_terms - _DISCOVERY_GENERIC_DOMAIN_TERMS
1154 return bool((anchors or domain_terms) & terms(text))
1155
1156
1157 def _fetch_discovery_source(
1158 source: str,
1159 plan: schema.DiscoveryPlan,
1160 *,
1161 from_date: str,
1162 to_date: str,
1163 depth: str,
1164 mock: bool,
1165 config: dict[str, Any],
1166 keyword_gate: bool = True,
1167 warnings: list[str] | None = None,
1168 ) -> tuple[list[dict[str, Any]], str | None]:
1169 """Fetch one listing/river source for the nominate stage.
1170
1171 ``keyword_gate`` controls whether items are filtered to the domain by
1172 ``_matches_discovery_domain``. Domain-scoped discovery (``--discover X``)
1173 keeps the gate on; global trending (``--discover`` with no domain) turns it
1174 off, because there is no keyword to gate against - the river feeds ARE the
1175 "what is hot right now" signal, and the confidence floor downstream is what
1176 keeps junk out, not a keyword match. ``warnings``, when given, collects
1177 backend receipts that are not failures (xapi's truncated window).
1178 """
1179 if _research_stopped(config):
1180 return [], "discovery research cancelled or timed out"
1181 if mock:
1182 return _mock_discovery_items(source, plan.domain, to_date), None
1183 if source == "reddit":
1184 result = reddit_listing.fetch_discovery_listings(
1185 plan.subreddits, depth=depth, query=plan.domain,
1186 )
1187 items = result.get("items") or []
1188 if keyword_gate:
1189 items = [
1190 item for item in items
1191 if _matches_discovery_domain(
1192 plan.domain,
1193 f"{item.get('title') or ''} {item.get('selftext') or ''}",
1194 )
1195 ]
1196 return items, "; ".join(result.get("errors") or []) or None
1197 if source == "hackernews":
1198 result = hackernews.fetch_discovery_listings(from_date, to_date, depth=depth)
1199 items = result.get("items") or []
1200 for item in items:
1201 item["relevance"] = relevance.token_overlap_relevance(
1202 plan.domain,
1203 str(item.get("title") or ""),
1204 )
1205 # HN is a broad technology listing, so keep only domain-bearing stories
1206 # when a domain is in play; global trending keeps the whole front page.
1207 if keyword_gate:
1208 items = [
1209 item for item in items
1210 if _matches_discovery_domain(plan.domain, str(item.get("title") or ""))
1211 ]
1212 errors = result.get("errors") or []
1213 return items, "; ".join(errors) or None
1214 if source == "digg":
1215 if plan.domain.strip():
1216 result = digg.search_digg(plan.domain, from_date, to_date, depth=depth)
1217 items = digg.parse_digg_response(result, query=plan.domain, from_date=from_date)
1218 else:
1219 # Global trending has nothing to search for: Digg's own top
1220 # stories across every topic are its "what is hot" listing.
1221 result = digg.top_stories(depth=depth)
1222 items = digg.parse_top_response(result, from_date=from_date)
1223 # Digg is a broad listing, so keep only domain-bearing
1224 # clusters when scoped; global trending keeps the whole feed.
1225 if keyword_gate:
1226 items = [
1227 item for item in items
1228 if _matches_discovery_domain(plan.domain, str(item.get("title") or ""))
1229 ]
1230 return items, result.get("error")
1231 if source == "x":
1232 # Discovery uses domain directly as query (no planner search_query)
1233 query = plan.domain
1234 last_error = ""
1235 chain_deadline = _research_deadline(config, _x_chain_budget_seconds(config))
1236 cutoff = config.get("_finalization_deadline")
1237 if cutoff is not None:
1238 chain_deadline = min(chain_deadline, cutoff)
1239 x_warnings: list[str] = []
1240 for backend in env.x_backend_chain(config):
1241 if _research_stopped(config) or time.monotonic() >= chain_deadline:
1242 last_error = f"{last_error}; X chain budget exhausted (timed out or cancelled)".strip("; ")
1243 break
1244 items, error, _ = _attempt_x_backend(
1245 backend, query, from_date, to_date, depth, config,
1246 warnings=x_warnings, deadline=chain_deadline,
1247 )
1248 if items:
1249 # Earlier failed-over backends' errors are observability, not
1250 # degradation - but the producing backend's own error means
1251 # these items are partial and must surface as such.
1252 if last_error:
1253 print(f"[x] earlier backend failed: {last_error}", file=sys.stderr)
1254 if warnings is not None:
1255 warnings.extend(x_warnings)
1256 return items, error or None
1257 if error:
1258 last_error = f"{backend}: {error}"
1259 if warnings is not None:
1260 warnings.extend(x_warnings)
1261 return [], last_error or None
1262 raise ValueError(f"Unsupported discovery source: {source}")
1263
1264
1265 def _discovery_engagement(
1266 items: list[schema.SourceItem],
1267 ) -> dict[str, dict[str, float | int]]:
1268 totals: dict[str, dict[str, float | int]] = {}
1269 for item in items:
1270 bucket = totals.setdefault(item.source, {})
1271 for field, value in item.engagement.items():
1272 if not isinstance(value, (int, float)) or isinstance(value, bool):
1273 continue
1274 # Rank/score/reach metadata is not additive engagement: summing
1275 # Digg ranks across items fabricates a metric (agent-export uses
1276 # the same counter-field rule).
1277 if not schema._is_counter_field(field):
1278 continue
1279 bucket[field] = bucket.get(field, 0) + value
1280 return {
1281 source: dict(sorted(metrics.items()))
1282 for source, metrics in sorted(totals.items())
1283 }
1284
1285
1286 def _discovery_momentum(items: list[schema.SourceItem], to_date: str) -> str:
1287 as_of = datetime.fromisoformat(to_date).date()
1288 ages: list[int] = []
1289 for item in items:
1290 try:
1291 published = datetime.fromisoformat((item.published_at or "").replace("Z", "+00:00")).date()
1292 except (TypeError, ValueError):
1293 continue
1294 ages.append(max(0, (as_of - published).days))
1295 return "new-this-week" if ages and max(ages) < 7 else "building"
1296
1297
1298 def nominate_candidates(
1299 plan: schema.DiscoveryPlan,
1300 *,
1301 from_date: str,
1302 to_date: str,
1303 depth: str,
1304 mock: bool,
1305 config: dict[str, Any],
1306 lookback_days: int,
1307 keyword_gate: bool = True,
1308 ) -> schema.RetrievalBundle:
1309 """Stage 1 of discovery: fetch, normalize, and bundle candidate hot items
1310 from the river/listing feeds.
1311
1312 This is the topic-nomination pass. For domain discovery ``keyword_gate`` is
1313 on and the feeds are filtered to the domain; for global trending it is off
1314 and the feeds' own hot ranking IS the signal. The returned bundle feeds the
1315 clustering + enrichment stages downstream. Every source's failure is
1316 recorded on the bundle (never raised) so a single dead feed cannot sink the
1317 run - the confidence floor decides whether the surviving evidence is enough.
1318 """
1319 bundle = schema.RetrievalBundle()
1320 config = dict(config)
1321 config["_research_deadline"] = _research_deadline(config, DISCOVERY_FUTURE_TIMEOUT_SECONDS)
1322 # Shared receipts sink: only X appends (xapi's truncated window); the
1323 # executor submit below passes it to every source, the rest ignore it.
1324 x_receipts: list[str] = []
1325 with _abandoning_executor(max_workers=max(1, len(plan.sources))) as executor:
1326 futures = {
1327 executor.submit(
1328 _fetch_discovery_source,
1329 source,
1330 plan,
1331 from_date=from_date,
1332 to_date=to_date,
1333 depth=depth,
1334 mock=mock,
1335 config=config,
1336 keyword_gate=keyword_gate,
1337 warnings=x_receipts,
1338 ): source
1339 for source in plan.sources
1340 }
1341 # Bounded wait (reddit-lane futures_wait pattern): a hung feed degrades
1342 # to a TIMEOUT partial instead of stalling nominate forever.
1343 done, not_done = _wait_for_research(futures, config)
1344 for future in not_done:
1345 source = futures[future]
1346 future.cancel()
1347 if future.done() and not future.cancelled():
1348 done.add(future)
1349 continue
1350 bundle.mark_attempted(source)
1351 detail = f"{source} timed out after {DISCOVERY_FUTURE_TIMEOUT_SECONDS:g}s"
1352 bundle.errors_by_source[source] = detail
1353 bundle.record_failure(
1354 source,
1355 health.TIMEOUT,
1356 detail,
1357 attempted=True,
1358 )
1359 for future in done:
1360 source = futures[future]
1361 bundle.mark_attempted(source)
1362 try:
1363 raw_items, partial_error = future.result(timeout=0)
1364 except Exception as exc:
1365 state, attempted = _classify_source_failure(exc)
1366 bundle.record_failure(source, state, str(exc), attempted=attempted)
1367 continue
1368 try:
1369 normalized = normalize.normalize_source_items(
1370 source,
1371 raw_items,
1372 from_date,
1373 to_date,
1374 freshness_mode="breaking",
1375 )
1376 # Global trending has no domain; annotate against a neutral
1377 # phrase so snippet extraction still works without biasing
1378 # relevance toward any keyword.
1379 prepared = relevance.PreparedQuery(plan.domain or "trending now")
1380 normalized = signals.annotate_stream(
1381 normalized,
1382 prepared,
1383 "breaking",
1384 reference_date=to_date,
1385 max_days=lookback_days,
1386 )
1387 normalized = dedupe.dedupe_items(normalized)
1388 for item in normalized:
1389 item.snippet = snippet.extract_best_snippet(item, prepared)
1390 bundle.add_items("discovery-listings", source, normalized)
1391 if partial_error:
1392 failure_state = (
1393 bird_x.classify_run_failure(partial_error)
1394 if source == "x" and partial_error.startswith("bird:")
1395 else http.classify_failure(message=partial_error)
1396 )
1397 bundle.record_failure(
1398 source,
1399 failure_state,
1400 partial_error,
1401 )
1402 except Exception as exc:
1403 state, attempted = _classify_source_failure(exc)
1404 bundle.record_failure(source, state, str(exc), attempted=attempted)
1405 # Backend receipts that are not failures (xapi's truncated window): the
1406 # same x_partial_coverage key the main path uses. X extends the sink just
1407 # before returning, so a finished X future's receipts are complete. The
1408 # executor exit does not join stragglers: a timed-out X can still append
1409 # after the wait, and its receipts are dropped along with its items.
1410 x_finished = any(futures[future] == "x" for future in done)
1411 if x_finished and x_receipts:
1412 bundle.artifacts.setdefault("x_partial_coverage", []).extend(list(x_receipts))
1413 return bundle
1414
1415
1416 @dataclass(frozen=True)
1417 class Nomination:
1418 """A named candidate topic produced by the nominate stage.
1419
1420 ``seed_score`` is the cheap pre-enrichment rank - seed velocity on the
1421 nominate stage, blended with the HOST judge's content-worthiness on the
1422 protocol resume leg (see ``rerank.judge_blended_score``). Enough to
1423 decide WHICH candidates deserve a full pipeline pass, but not the final
1424 ranking signal (that comes from enriched evidence downstream).
1425 ``junk_shape`` flags help-me/beginner/musing shapes that should not
1426 become content topics; ``worthiness`` is the host judge's 0-100 content
1427 score, None on the heuristic path.
1428 """
1429
1430 name: str
1431 seed_score: float
1432 items: list[schema.SourceItem] = field(default_factory=list)
1433 summary: str = ""
1434 junk_shape: bool = False
1435 worthiness: float | None = None
1436
1437
1438 def _cluster_entity_counts(
1439 cluster: schema.Cluster,
1440 candidate_map: dict[str, schema.Candidate],
1441 ) -> Counter:
1442 """Entity-token frequencies across a cluster's members (title + snippet)."""
1443 counts: Counter = Counter()
1444 for candidate_id in cluster.candidate_ids:
1445 candidate = candidate_map.get(candidate_id)
1446 if candidate:
1447 counts.update(entity_extract.extract_text_entities(
1448 f"{candidate.title} {candidate.snippet}"
1449 ))
1450 return counts
1451
1452
1453 # Bound on how many distinguishing entity tokens a colliding cluster may try
1454 # before it is treated as indistinguishable from the earlier story. Keeps a
1455 # pathological cluster (dozens of unique tokens, every resulting name already
1456 # taken) from scanning its whole vocabulary.
1457 _DISAMBIGUATION_TOKEN_LIMIT = 5
1458
1459
1460 def _disambiguated_topic_name(
1461 name: str,
1462 cluster: schema.Cluster,
1463 earlier_cluster: schema.Cluster,
1464 candidate_map: dict[str, schema.Candidate],
1465 entity_counts_cache: dict[str, Counter],
1466 taken_names: dict[str, schema.Cluster],
1467 ) -> str | None:
1468 """Disambiguate a colliding topic name by appending the later cluster's
1469 strongest entity token that the earlier cluster does not share.
1470
1471 Distinguishing tokens are tried in descending strength order (bounded at
1472 ``_DISAMBIGUATION_TOKEN_LIMIT``) and the first resulting name not already
1473 present in ``taken_names`` (casefolded keys) wins: a first-choice suffix
1474 colliding with an already-taken name must not drop a distinct story while
1475 another distinguishing token remains.
1476
1477 ``entity_counts_cache`` (keyed by cluster id, owned by the caller) memoizes
1478 per-cluster entity counts so repeated collisions against the same cluster
1479 never recompute them.
1480
1481 Returns None when no distinguishing entity yields an unused name - the
1482 clusters cannot be told apart by content, so the caller treats them as the
1483 same story.
1484 """
1485 def cached_counts(target: schema.Cluster) -> Counter:
1486 counts = entity_counts_cache.get(target.cluster_id)
1487 if counts is None:
1488 counts = _cluster_entity_counts(target, candidate_map)
1489 entity_counts_cache[target.cluster_id] = counts
1490 return counts
1491
1492 later_counts = cached_counts(cluster)
1493 earlier_entities = set(cached_counts(earlier_cluster))
1494 name_tokens = {token.casefold() for token in name.split()}
1495 choices = [
1496 (count, token) for token, count in later_counts.items()
1497 if token not in earlier_entities and token.casefold() not in name_tokens
1498 ]
1499 # Strongest first = most frequent across the cluster; alphabetical
1500 # tie-break keeps the result deterministic.
1501 ranked = sorted(choices, key=lambda entry: (-entry[0], entry[1]))
1502 for _, token in ranked[:_DISAMBIGUATION_TOKEN_LIMIT]:
1503 display = token
1504 for candidate_id in cluster.candidate_ids:
1505 candidate = candidate_map.get(candidate_id)
1506 if candidate is None:
1507 continue
1508 match = next(
1509 (
1510 word.strip("\"'`()[]{}.,:;!?")
1511 for word in f"{candidate.title} {candidate.snippet}".split()
1512 if word.strip("\"'`()[]{}.,:;!?").lower() == token
1513 ),
1514 None,
1515 )
1516 if match:
1517 display = match
1518 break
1519 resolved = f"{name} {display}"
1520 if resolved.casefold() not in taken_names:
1521 return resolved
1522 return None
1523
1524
1525 def nominate_topic_pool(
1526 bundle: schema.RetrievalBundle,
1527 query_plan: schema.QueryPlan,
1528 plan: schema.DiscoveryPlan,
1529 *,
1530 from_date: str,
1531 to_date: str,
1532 limit: int,
1533 ) -> list[tuple[Nomination, str]]:
1534 """Stage 1b of discovery: cluster nominated items into named candidate
1535 topics, rank them, and pair each with its source cluster id.
1536
1537 This is the shared core behind ``nominate_topics`` (the one-shot path,
1538 which drops the cluster ids) and the leg-1 nominate-only sweep (which
1539 keys nominations-bundle rows on them, see ``run_discover_nominate``).
1540
1541 Naming and junk classification are the deterministic ``topic_shape``
1542 heuristics and ranking is velocity-only - the engine runs no LLM here.
1543 Reasoning-model judgment lives in the host-judged protocol: the host
1544 renames, junk-filters, and worthiness-scores this pool from the leg-1
1545 bundle, and ``run_discover_resume`` applies those verdicts. The one-shot
1546 path ships the heuristic names as-is.
1547
1548 Casefold name collisions are disambiguated (the later cluster's strongest
1549 non-shared entity token is appended, trying successive tokens when the
1550 first-choice suffix is itself already taken) rather than blindly dropped:
1551 short distilled names collide far more often than raw 96-char titles, and
1552 a silent drop hides a distinct story. A colliding cluster is dropped only
1553 when it shares a representative candidate with the earlier one (the same
1554 story surfacing twice) or when no distinguishing entity token yields an
1555 unused name.
1556
1557 Returns at most ``limit`` ``(nomination, cluster_id)`` pairs, never
1558 padded - fewer clusters than ``limit`` means a shorter list, and the
1559 confidence floor downstream decides whether what survived is worth
1560 showing.
1561 """
1562 candidates = weighted_rrf(
1563 bundle.items_by_source_and_query,
1564 query_plan,
1565 pool_limit=80,
1566 range_from=from_date,
1567 range_to=to_date,
1568 )
1569 for candidate in candidates:
1570 velocity = rerank.discovery_velocity_score(candidate.source_items, as_of_date=to_date)
1571 candidate.final_score = min(100.0, 12.0 * math.log1p(velocity)) if velocity else 0.0
1572 candidates.sort(key=lambda candidate: (-candidate.final_score, candidate.title.lower()))
1573 clusters = cluster_candidates(candidates, query_plan)
1574 candidate_map = {candidate.candidate_id: candidate for candidate in candidates}
1575
1576 ranked_clusters: list[tuple[float, schema.Cluster, list[schema.SourceItem]]] = []
1577 for cluster in clusters:
1578 cluster_items: list[schema.SourceItem] = []
1579 for candidate_id in cluster.candidate_ids:
1580 candidate = candidate_map.get(candidate_id)
1581 if candidate:
1582 cluster_items.extend(candidate.source_items)
1583 score = rerank.discovery_velocity_score(cluster_items, as_of_date=to_date)
1584 if score <= 0:
1585 continue
1586 ranked_clusters.append((score, cluster, cluster_items))
1587 ranked_clusters.sort(key=lambda entry: (-entry[0], entry[1].title.lower()))
1588
1589 # Heuristic naming from each cluster's leader text (title + snippet).
1590 named: list[tuple[float, schema.Cluster, list[schema.SourceItem], str, bool]] = []
1591 for score, cluster, cluster_items in ranked_clusters:
1592 leader = candidate_map.get(cluster.representative_ids[0]) if cluster.representative_ids else None
1593 title = (leader.title if leader else cluster.title) or ""
1594 snip = (leader.snippet if leader else "") or ""
1595 name = topic_shape.distill_topic_name(title, snip) or plan.domain or title
1596 junk_shape = topic_shape.is_junk_shape(title, snip)
1597 named.append((score, cluster, cluster_items, name, junk_shape))
1598 named.sort(key=lambda entry: (-entry[0], entry[3].lower()))
1599
1600 pool: list[tuple[Nomination, str]] = []
1601 taken_names: dict[str, schema.Cluster] = {}
1602 entity_counts_cache: dict[str, Counter] = {}
1603 for score, cluster, cluster_items, name, junk_shape in named:
1604 name_key = name.casefold()
1605 if name_key in taken_names:
1606 earlier_cluster = taken_names[name_key]
1607 if set(cluster.representative_ids) & set(earlier_cluster.representative_ids):
1608 continue # same story surfacing twice
1609 resolved = _disambiguated_topic_name(
1610 name, cluster, earlier_cluster, candidate_map, entity_counts_cache,
1611 taken_names,
1612 )
1613 if resolved is None:
1614 continue # indistinguishable by content: treat as the same story
1615 name = resolved
1616 name_key = name.casefold()
1617 taken_names[name_key] = cluster
1618 leader = candidate_map.get(cluster.representative_ids[0]) if cluster.representative_ids else None
1619 summary = (leader.snippet if leader else "") or (leader.title if leader else name)
1620 pool.append((Nomination(
1621 name=name,
1622 seed_score=score,
1623 items=cluster_items,
1624 summary=summary,
1625 junk_shape=junk_shape,
1626 ), cluster.cluster_id))
1627 if len(pool) >= limit:
1628 break
1629 return pool
1630
1631
1632 def nominate_topics(
1633 bundle: schema.RetrievalBundle,
1634 query_plan: schema.QueryPlan,
1635 plan: schema.DiscoveryPlan,
1636 *,
1637 from_date: str,
1638 to_date: str,
1639 limit: int,
1640 ) -> list[Nomination]:
1641 """``nominate_topic_pool`` without the cluster ids: the one-shot
1642 discovery path's contract (see that function for the full semantics)."""
1643 return [
1644 nomination
1645 for nomination, _cluster_id in nominate_topic_pool(
1646 bundle, query_plan, plan, from_date=from_date, to_date=to_date, limit=limit,
1647 )
1648 ]
1649
1650
1651 # Enrichment fan-out bounds. Sub-runs hit the same upstream APIs as a normal
1652 # research pass, so parallelism stays low and the whole batch runs against a
1653 # wall-clock budget - a slow topic is dropped, never fatal.
1654 ENRICH_LIMIT = 6
1655 ENRICH_DEPTH = "quick"
1656 ENRICH_MAX_WORKERS = 3
1657 ENRICH_BUDGET_SECONDS = 240.0
1658
1659
1660 @dataclass
1661 class EnrichedTopic:
1662 """A nomination plus the full-pipeline evidence gathered for it.
1663
1664 ``report`` is None when enrichment for this topic failed or ran past the
1665 batch budget - the topic survives as nomination-only and the confidence
1666 floor downstream decides whether its seed evidence is enough to show.
1667 """
1668
1669 nomination: Nomination
1670 report: schema.Report | None = None
1671 error: str | None = None
1672
1673
1674 def enrich_nominations(
1675 nominations: list[Nomination],
1676 *,
1677 config: dict[str, Any],
1678 requested_sources: list[str] | None = None,
1679 mock: bool = False,
1680 depth: str = ENRICH_DEPTH,
1681 lookback_days: int = 30,
1682 as_of_date: str | None = None,
1683 max_workers: int = ENRICH_MAX_WORKERS,
1684 budget_seconds: float = ENRICH_BUDGET_SECONDS,
1685 ) -> list[EnrichedTopic]:
1686 """Stage 2 of discovery: run the real research pipeline on each nomination.
1687
1688 Each nominated topic gets a full ``run()`` pass (``internal_subrun=True``,
1689 same lane as comparison-mode sub-runs), which buys the whole multi-source
1690 corpus - Reddit with comments, X, YouTube, Techmeme, arXiv, HN, Polymarket,
1691 web - plus clustering and ranking, with zero bespoke fetch code.
1692
1693 Failure containment: a topic whose sub-run raises is returned with
1694 ``report=None`` and the error recorded; topics still unfinished when the
1695 batch budget expires are likewise dropped to nomination-only. The batch
1696 never raises and preserves nomination order.
1697 """
1698 if not nominations:
1699 return []
1700
1701 # Cooperative cancel: not-yet-started sub-runs and streams skip new
1702 # network work once the batch budget expires. The event rides the
1703 # per-worker config copy into run() -> _retrieve_stream_impl, which exits
1704 # early when set; in-flight requests still run to their own timeouts.
1705 cancel = threading.Event()
1706 deadline = _research_deadline(config, max(1.0, budget_seconds))
1707
1708 def _run_one(nomination: Nomination) -> schema.Report:
1709 worker_config = dict(config)
1710 worker_config["_enrich_cancel"] = cancel
1711 worker_config["_research_deadline"] = deadline
1712 _check_research(worker_config)
1713 return run(
1714 topic=nomination.name,
1715 config=worker_config,
1716 depth=depth,
1717 requested_sources=requested_sources,
1718 mock=mock,
1719 lookback_days=lookback_days,
1720 as_of_date=as_of_date,
1721 internal_subrun=True,
1722 # Enrichment passes never carry a connector envelope, so the
1723 # per-session lane signal must not plan X in and record a
1724 # spurious X error on every nominated topic.
1725 suppress_x_host_lane=True,
1726 )
1727
1728 # Daemon threads + a semaphore instead of ThreadPoolExecutor: executor
1729 # threads are non-daemon and joined at interpreter shutdown, so one hung
1730 # sub-run could keep the whole process alive long after its topic was
1731 # downgraded to nomination-only. Daemon workers make the wall-clock budget
1732 # real - stragglers cannot delay process exit. Abandonment is safe because
1733 # internal_subrun passes write nothing to disk (no save, no library sync,
1734 # no store), and every fetch layer inside run() carries its own timeout.
1735 youtube_yt.reset_search_cache()
1736 enriched: dict[str, EnrichedTopic] = {}
1737 results_queue: queue.Queue[tuple[Nomination, schema.Report | None, Exception | None]] = queue.Queue()
1738 slots = threading.Semaphore(max(1, max_workers))
1739
1740 def _worker(nomination: Nomination) -> None:
1741 with slots:
1742 if cancel.is_set():
1743 results_queue.put((nomination, None, TimeoutError("enrichment budget exhausted")))
1744 return
1745 try:
1746 results_queue.put((nomination, _run_one(nomination), None))
1747 except Exception as exc: # noqa: BLE001 - containment is the contract
1748 results_queue.put((nomination, None, exc))
1749
1750 with fetch_memo.run_scope():
1751 for nomination in nominations:
1752 ctx = contextvars.copy_context()
1753 threading.Thread(
1754 target=ctx.run,
1755 args=(_worker, nomination),
1756 name=f"discover-enrich-{nomination.name[:32]}",
1757 daemon=True,
1758 ).start()
1759
1760 def _record_result(
1761 nomination: Nomination,
1762 report: schema.Report | None,
1763 exc: Exception | None,
1764 ) -> None:
1765 if exc is None:
1766 enriched[nomination.name] = EnrichedTopic(
1767 nomination=nomination, report=report,
1768 )
1769 return
1770 if isinstance(exc, TimeoutError) and time.monotonic() >= deadline:
1771 # A sub-run's budget-exhaustion TimeoutError at/past the deadline
1772 # keeps the canonical "enrichment budget exhausted" downgrade below.
1773 return
1774 enriched[nomination.name] = EnrichedTopic(
1775 nomination=nomination,
1776 error=f"{type(exc).__name__}: {exc}",
1777 )
1778 print(
1779 f"[Discover] enrichment failed for {nomination.name!r}: "
1780 f"{type(exc).__name__}: {exc}",
1781 file=sys.stderr,
1782 )
1783
1784 pending = len(nominations)
1785 try:
1786 while pending and (remaining := deadline - time.monotonic()) > 0:
1787 try:
1788 nomination, report, exc = results_queue.get(timeout=min(remaining, 0.5))
1789 except queue.Empty:
1790 continue
1791 pending -= 1
1792 _record_result(nomination, report, exc)
1793 # Drain any additional reports that already landed in the queue before
1794 # or right at the deadline boundary so completed work is never dropped.
1795 while pending:
1796 try:
1797 nomination, report, exc = results_queue.get_nowait()
1798 except queue.Empty:
1799 break
1800 pending -= 1
1801 _record_result(nomination, report, exc)
1802 finally:
1803 # Budget expired (or all done, or the drain itself failed):
1804 # unfinished topics fall through below as nomination-only; their
1805 # daemon workers are abandoned and cannot block exit. Signal
1806 # cooperative cancel so queued workers skip new sub-runs and
1807 # not-yet-started streams exit early; in-flight spend continues to
1808 # its own timeout.
1809 cancel.set()
1810
1811 results: list[EnrichedTopic] = []
1812 for nomination in nominations:
1813 entry = enriched.get(nomination.name)
1814 if entry is None:
1815 entry = EnrichedTopic(
1816 nomination=nomination,
1817 error="enrichment budget exhausted",
1818 )
1819 print(
1820 f"[Discover] enrichment budget exhausted before {nomination.name!r} "
1821 "finished; keeping nomination-only evidence",
1822 file=sys.stderr,
1823 )
1824 results.append(entry)
1825 return results
1826
1827
1828 def _enriched_evidence_items(entry: EnrichedTopic) -> list[schema.SourceItem]:
1829 """The items a topic is judged on: the enriched corpus when the pipeline
1830 pass succeeded, the nomination's seed items otherwise."""
1831 if entry.report is not None:
1832 flattened: list[schema.SourceItem] = []
1833 for source_items in entry.report.items_by_source.values():
1834 flattened.extend(source_items)
1835 if flattened:
1836 return flattened
1837 return entry.nomination.items
1838
1839
1840 def _best_community_comment(items: list[schema.SourceItem]) -> str | None:
1841 """The strongest verbatim community comment across a topic's evidence,
1842 formatted with attribution - the voice-of-the-people line on a trend card.
1843
1844 Vote strength is per-platform-normalized (signals.normalized_comment_vote)
1845 so one viral platform's counts don't drown out the rest.
1846 """
1847 best: tuple[float, str, str | None, float | int | None] | None = None
1848 for item in items:
1849 comments = item.metadata.get("top_comments") or []
1850 for comment in comments:
1851 # A pending comment's score is withheld, so it has no vote strength.
1852 if not isinstance(comment, dict) or comment.get("score_pending"):
1853 continue
1854 body = (comment.get("excerpt") or comment.get("text") or comment.get("body") or "").strip()
1855 if len(body) < 12:
1856 continue
1857 strength = signals.normalized_comment_vote(item.source, comment.get("score"))
1858 if best is None or strength > best[0]:
1859 best = (strength, body, comment.get("author"), comment.get("score"))
1860 if best is None:
1861 return None
1862 _, body, author, score = best
1863 # Comment bodies that themselves start/end with quote characters would
1864 # render as doubled quotes inside our wrapping quotes.
1865 body = body.strip('"“”‘’\'').strip()
1866 if len(body) > 200:
1867 body = body[:197].rsplit(" ", 1)[0] + "..."
1868 attribution = f" - {author}" if author else ""
1869 votes = (
1870 f" ({int(score):,} votes)"
1871 if isinstance(score, (int, float)) and not isinstance(score, bool) and score > 0
1872 else ""
1873 )
1874 return f'"{body}"{attribution}{votes}'
1875
1876
1877 @dataclass(frozen=True)
1878 class _DiscoverySweep:
1879 """The shared front half of both discovery entry points: the resolved
1880 plan and window, the swept listing bundle, and finalized per-source
1881 status. Everything downstream (judging, enrichment, floor, queue)
1882 belongs to the caller's leg."""
1883
1884 plan: schema.DiscoveryPlan
1885 query_plan: schema.QueryPlan
1886 from_date: str
1887 to_date: str
1888 bundle: schema.RetrievalBundle
1889 source_status: dict[str, schema.SourceOutcome]
1890
1891
1892 def _discovery_sweep(
1893 *,
1894 domain: str,
1895 config: dict[str, Any],
1896 depth: str,
1897 requested_sources: list[str] | None,
1898 mock: bool,
1899 subreddits: list[str] | None,
1900 lookback_days: int,
1901 as_of_date: str | None,
1902 ) -> _DiscoverySweep:
1903 """Resolve the momentum window, validate/bound the listing sources, build
1904 the discovery plan, sweep the river feeds, and finalize source status.
1905
1906 Shared verbatim by ``run_discover`` (one-shot) and
1907 ``run_discover_nominate`` (protocol leg 1) so the two paths can never
1908 drift on what a sweep means."""
1909 from_date, to_date = dates.get_date_range(lookback_days, as_of_date=as_of_date)
1910 requested = normalize_requested_sources(requested_sources)
1911 unsupported = sorted(set(requested or []) - set(DISCOVERY_SOURCES))
1912 if unsupported:
1913 raise ValueError(
1914 "Discovery supports listing sources only: reddit, hackernews, digg "
1915 f"(unsupported: {', '.join(unsupported)})"
1916 )
1917 available = list(DISCOVERY_SOURCES) if mock else [
1918 source for source in available_sources(config, requested, x_pending=False)
1919 if source in DISCOVERY_SOURCES
1920 ]
1921 if requested:
1922 available = [source for source in available if source in requested]
1923 plan = planner.build_discovery_plan(
1924 domain,
1925 available_sources=available,
1926 subreddits=subreddits,
1927 )
1928
1929 global_mode = not plan.domain
1930 domain_label = plan.domain or "everything"
1931 query_plan = schema.QueryPlan(
1932 intent="breaking_news",
1933 freshness_mode="breaking",
1934 cluster_mode="story",
1935 raw_topic=plan.domain,
1936 subqueries=[schema.SubQuery(
1937 label="discovery-listings",
1938 search_query=plan.domain,
1939 ranking_query=f"What is accelerating in {domain_label}?",
1940 sources=list(plan.sources),
1941 )],
1942 source_weights={source: 1.0 for source in plan.sources},
1943 notes=["discover-mode", "listing-sweep"],
1944 )
1945
1946 with fetch_memo.run_scope():
1947 bundle = nominate_candidates(
1948 plan,
1949 from_date=from_date,
1950 to_date=to_date,
1951 depth=depth,
1952 mock=mock,
1953 config=config,
1954 lookback_days=lookback_days,
1955 # Global trending has no keyword to gate against - the river feeds' own
1956 # hot ranking is the signal and the confidence floor culls the junk.
1957 keyword_gate=not global_mode,
1958 )
1959
1960 source_status: dict[str, schema.SourceOutcome] = {}
1961 for source in DISCOVERY_SOURCES:
1962 if source in bundle.source_status:
1963 continue
1964 detail = (
1965 "Source is not configured for discovery."
1966 )
1967 source_status[source] = schema.SourceOutcome(
1968 source=source,
1969 state=schema.SKIPPED_UNCONFIGURED,
1970 attempted=False,
1971 detail=detail,
1972 fix_hint="doctor",
1973 )
1974 source_status.update(_finalize_source_status(bundle.source_status, bundle.items_by_source))
1975 return _DiscoverySweep(
1976 plan=plan,
1977 query_plan=query_plan,
1978 from_date=from_date,
1979 to_date=to_date,
1980 bundle=bundle,
1981 source_status=source_status,
1982 )
1983
1984
1985 def _degraded_discovery_sources(
1986 source_status: dict[str, schema.SourceOutcome],
1987 ) -> list[str]:
1988 """Sources whose outcome is neither clean nor an expected skip."""
1989 return [
1990 source for source, outcome_state in source_status.items()
1991 if outcome_state.state not in {health.OK, schema.NO_RESULTS, schema.SKIPPED_UNCONFIGURED}
1992 ]
1993
1994
1995 @dataclass(frozen=True)
1996 class DiscoverNominateResult:
1997 """Leg 1 output of the host-judged discovery protocol: the ranked judge
1998 pool as ``(nomination, cluster_id)`` pairs plus the sweep context the CLI
1999 needs to write the nominations bundle - or to render the nothing-solid
2000 brief when the pool is empty."""
2001
2002 plan: schema.DiscoveryPlan
2003 from_date: str
2004 to_date: str
2005 source_status: dict[str, schema.SourceOutcome]
2006 pool: list[tuple[Nomination, str]]
2007 warnings: list[str] = field(default_factory=list)
2008
2009
2010 def run_discover_nominate(
2011 *,
2012 domain: str,
2013 config: dict[str, Any],
2014 depth: str = "default",
2015 requested_sources: list[str] | None = None,
2016 mock: bool = False,
2017 subreddits: list[str] | None = None,
2018 lookback_days: int = 30,
2019 as_of_date: str | None = None,
2020 ) -> DiscoverNominateResult:
2021 """Protocol leg 1: sweep the listings and build the FULL judge pool.
2022
2023 Same sweep and clustering as ``run_discover``, but the pool is cut at
2024 ``rerank.JUDGE_POOL_LIMIT`` (not the enrichment limit). Like every
2025 discovery path it is deterministic-heuristic: no provider is ever
2026 resolved, so names and junk flags are the ``topic_shape`` baselines the
2027 host judges against. No enrichment, no confidence floor, no queue
2028 writes - those belong to legs 2 and 3.
2029 """
2030 sweep = _discovery_sweep(
2031 domain=domain,
2032 config=config,
2033 depth=depth,
2034 requested_sources=requested_sources,
2035 mock=mock,
2036 subreddits=subreddits,
2037 lookback_days=lookback_days,
2038 as_of_date=as_of_date,
2039 )
2040 pool = nominate_topic_pool(
2041 sweep.bundle, sweep.query_plan, sweep.plan,
2042 from_date=sweep.from_date,
2043 to_date=sweep.to_date,
2044 limit=rerank.JUDGE_POOL_LIMIT,
2045 )
2046 return DiscoverNominateResult(
2047 plan=sweep.plan,
2048 from_date=sweep.from_date,
2049 to_date=sweep.to_date,
2050 source_status=sweep.source_status,
2051 pool=pool,
2052 warnings=list(sweep.bundle.artifacts.get("x_partial_coverage", [])),
2053 )
2054
2055
2056 def nominate_nothing_solid_report(result: DiscoverNominateResult) -> schema.DiscoveryReport:
2057 """The honest-empty leg-1 report: a zero-nomination sweep renders the
2058 same nothing-solid brief a one-shot run would (and writes no bundle)."""
2059 warnings = [
2060 "The listing sweep nominated no topics this window; reporting "
2061 "nothing solid instead of ranked noise."
2062 ]
2063 failed = _degraded_discovery_sources(result.source_status)
2064 if failed:
2065 warnings.append(f"Some discovery sources degraded: {', '.join(sorted(failed))}.")
2066 warnings.extend(result.warnings)
2067 return schema.DiscoveryReport(
2068 domain=result.plan.domain,
2069 range_from=result.from_date,
2070 range_to=result.to_date,
2071 generated_at=datetime.now(timezone.utc).isoformat(),
2072 plan=result.plan,
2073 topics=[],
2074 source_status=result.source_status,
2075 warnings=warnings,
2076 outcome="nothing-solid",
2077 weak_signal=None,
2078 )
2079
2080
2081 def _floor_survivor_records(
2082 enriched_entries: list[EnrichedTopic],
2083 *,
2084 to_date: str,
2085 topic_limit: int,
2086 ) -> tuple[
2087 list[dict[str, Any]],
2088 tuple[float, str] | None,
2089 tuple[float, str] | None,
2090 ]:
2091 """Apply the discovery confidence floor to enriched entries in order,
2092 returning the survivor records plus the strongest non-junk and junk weak
2093 signals among the failures.
2094
2095 Shared verbatim by ``run_discover`` (one-shot) and ``run_discover_resume``
2096 (protocol leg 2) so floor semantics can never drift between the paths.
2097 """
2098 survivors: list[dict[str, Any]] = []
2099 weak_signal: tuple[float, str] | None = None
2100 junk_weak_signal: tuple[float, str] | None = None
2101 for entry in enriched_entries:
2102 nomination = entry.nomination
2103 evidence_items = _enriched_evidence_items(entry)
2104 sources = sorted({item.source for item in evidence_items})
2105 native_total = sum(
2106 rerank.discovery_engagement_total(item) for item in evidence_items
2107 )
2108 score = rerank.discovery_velocity_score(evidence_items, as_of_date=to_date)
2109 if not rerank.passes_discovery_floor(
2110 source_count=len(sources),
2111 engagement_total=native_total,
2112 item_count=len(evidence_items),
2113 junk_shape=nomination.junk_shape,
2114 # Junk corroboration counts distinct SEED listing sources, never
2115 # the enriched corpus - a successful enrichment pass is
2116 # multi-source for almost any topic, so it would never bind.
2117 seed_source_count=len({item.source for item in nomination.items}),
2118 ):
2119 # Sub-floor evidence never ranks; remember what came closest so a
2120 # nothing-solid brief can still name the strongest weak signal.
2121 # Junk-shaped failures are tracked separately: the brief prefers
2122 # the strongest NON-junk failure and names a junk one only when
2123 # every failure is junk-shaped (never empty when failures exist).
2124 if nomination.junk_shape:
2125 if junk_weak_signal is None or score > junk_weak_signal[0]:
2126 junk_weak_signal = (score, nomination.name)
2127 elif weak_signal is None or score > weak_signal[0]:
2128 weak_signal = (score, nomination.name)
2129 continue
2130 if len(survivors) >= topic_limit:
2131 break
2132 source_phrase = ", ".join(sources[:-1]) + (
2133 f" and {sources[-1]}" if len(sources) > 1 else (sources[0] if sources else "the listings")
2134 )
2135 noun = "evidence item" if entry.report is not None else "listing item"
2136 why = (
2137 f"{len(evidence_items)} {noun}{'s' if len(evidence_items) != 1 else ''} on "
2138 f"{source_phrase} generated {native_total:,.0f} native interactions. "
2139 f"{nomination.summary[:220]}"
2140 )
2141 top_comment = _best_community_comment(evidence_items) if entry.report is not None else None
2142 # Stage-2 angle input: the survivor's strongest evidence, enriched
2143 # corpus when the pipeline pass succeeded, seed items otherwise
2144 # (evidence_items already resolves that).
2145 top_titles = [
2146 item.title.strip()
2147 for item in sorted(
2148 evidence_items,
2149 key=rerank.discovery_engagement_total,
2150 reverse=True,
2151 )
2152 if item.title and item.title.strip()
2153 ][:3]
2154 survivors.append({
2155 "name": nomination.name,
2156 "why": why,
2157 "momentum": _discovery_momentum(evidence_items, to_date),
2158 "velocity_score": round(score, 2),
2159 "sources": sources,
2160 "engagement_by_source": _discovery_engagement(evidence_items),
2161 "evidence_urls": list(dict.fromkeys(item.url for item in evidence_items if item.url))[:5],
2162 "top_comment": top_comment,
2163 "titles": "; ".join(top_titles),
2164 "engagement_phrase": f"{native_total:,.0f} native interactions across {source_phrase}",
2165 })
2166 return survivors, weak_signal, junk_weak_signal
2167
2168
2169 def _fold_same_story_records(survivors: list[dict[str, Any]]) -> list[dict[str, Any]]:
2170 """Same-story fold + velocity ordering over floor-survivor records.
2171
2172 Floor survivors that share enriched evidence are the SAME story wearing
2173 two judged names (the real-run failure: two topics quoting the identical
2174 1,635-vote comment). Duplicates = identical non-None top comment OR >= 2
2175 shared evidence URLs; the lower-velocity twin is dropped, and a winning
2176 replacement re-scans the kept list to a fixpoint so chained overlap
2177 (A~C~B) still collapses to one survivor. Selection stays seed-ordered
2178 upstream; this only prunes, then sorts by displayed velocity (stable) so
2179 rank 1 is the highest velocity_score.
2180 """
2181 def _same_story(a: dict[str, Any], b: dict[str, Any]) -> bool:
2182 if a["top_comment"] is not None and a["top_comment"] == b["top_comment"]:
2183 return True
2184 return len(set(a["evidence_urls"]) & set(b["evidence_urls"])) >= 2
2185
2186 folded: list[dict[str, Any]] = []
2187 for record in survivors:
2188 # Fold to a fixpoint: when the incoming record REPLACES a kept one,
2189 # the replacement may share evidence with entries the dropped record
2190 # never matched (three-way chains: A kept, C shares the comment with
2191 # A and URLs with B). The winner re-scans the remaining kept entries
2192 # until nothing matches, so one story always yields one survivor.
2193 incoming: dict[str, Any] | None = record
2194 while incoming is not None:
2195 dup_index = next(
2196 (index for index, kept in enumerate(folded) if _same_story(incoming, kept)),
2197 None,
2198 )
2199 if dup_index is None:
2200 folded.append(incoming)
2201 break
2202 kept = folded[dup_index]
2203 if incoming["velocity_score"] > kept["velocity_score"]:
2204 folded.pop(dup_index)
2205 dropped_name, kept_name = kept["name"], incoming["name"]
2206 else:
2207 dropped_name, kept_name = incoming["name"], kept["name"]
2208 incoming = None # dropped; the kept entry stays in place
2209 log.source_log(
2210 "Discover",
2211 f"folded duplicate story {dropped_name!r} into {kept_name!r} (shared evidence)",
2212 tty_only=False,
2213 )
2214
2215 folded.sort(key=lambda record: record["velocity_score"], reverse=True)
2216 return folded
2217
2218
2219 def _records_to_discovery_topics(
2220 folded: list[dict[str, Any]],
2221 ) -> list[schema.DiscoveryTopic]:
2222 """Folded survivor records to ranked topics (ranks = 1-based positions)."""
2223 return [
2224 schema.DiscoveryTopic(
2225 rank=position,
2226 name=record["name"],
2227 why_spiking=record["why"],
2228 momentum=record["momentum"],
2229 velocity_score=record["velocity_score"],
2230 sources=record["sources"],
2231 engagement_by_source=record["engagement_by_source"],
2232 command=f'/last30days "{record["name"].replace(chr(34), chr(39))}"',
2233 evidence_urls=record["evidence_urls"],
2234 top_comment=record["top_comment"],
2235 corroboration_count=len(record["sources"]),
2236 )
2237 for position, record in enumerate(folded, start=1)
2238 ]
2239
2240
2241 def _discovery_report_warnings(
2242 topics: list[schema.DiscoveryTopic],
2243 outcome: str,
2244 source_status: dict[str, schema.SourceOutcome],
2245 ) -> list[str]:
2246 """Coverage warnings shared by the one-shot and resume discovery paths.
2247 The resume leg never re-sweeps: it passes the bundle's RESTORED leg-1
2248 sweep status, so a degraded feed from the sweep still reaches the leg-2
2249 report exactly as the one-shot reports it."""
2250 warnings: list[str] = []
2251 if outcome == "nothing-solid":
2252 warnings.append(
2253 "No topic cleared the discovery confidence floor this window; "
2254 "reporting nothing solid instead of ranked noise."
2255 )
2256 elif len(topics) < 5:
2257 warnings.append("Fewer than five topic clusters cleared the confidence floor this window.")
2258 if topics and all(len(topic.sources) == 1 for topic in topics):
2259 warnings.append("Discovery evidence is single-source; configure Digg for broader confirmation.")
2260 failed = _degraded_discovery_sources(source_status)
2261 if failed:
2262 warnings.append(f"Some discovery sources degraded: {', '.join(sorted(failed))}.")
2263 return warnings
2264
2265
2266 def run_discover(
2267 *,
2268 domain: str,
2269 config: dict[str, Any],
2270 depth: str = "default",
2271 requested_sources: list[str] | None = None,
2272 mock: bool = False,
2273 subreddits: list[str] | None = None,
2274 lookback_days: int = 30,
2275 as_of_date: str | None = None,
2276 limit: int = 10,
2277 enrich: bool = False,
2278 enrich_requested_sources: list[str] | None = None,
2279 ) -> schema.DiscoveryReport:
2280 """Sweep category listings and rank the topics gaining velocity.
2281
2282 ``requested_sources`` bounds the listing sweep (discovery-capable feeds
2283 only). ``enrich_requested_sources`` bounds the per-topic research passes:
2284 None means every available source - which is what lets Techmeme, arXiv,
2285 YouTube, Polymarket, and community comments reach discovery despite having
2286 no river feed of their own. Pass the user's original --search list here so
2287 an explicit source boundary holds through enrichment too.
2288 """
2289 sweep = _discovery_sweep(
2290 domain=domain,
2291 config=config,
2292 depth=depth,
2293 requested_sources=requested_sources,
2294 mock=mock,
2295 subreddits=subreddits,
2296 lookback_days=lookback_days,
2297 as_of_date=as_of_date,
2298 )
2299 plan = sweep.plan
2300 from_date, to_date = sweep.from_date, sweep.to_date
2301 source_status = sweep.source_status
2302
2303 # The engine never names or angles topics with an LLM: the one-shot path
2304 # is deterministic-heuristic by design, and reasoning-model judgment
2305 # lives in the host-judged SKILL.md protocol. Say so loudly once per live
2306 # run; --mock stays silent (a deliberate mock run is not a degraded run).
2307 if not mock:
2308 log.source_log(
2309 "Discover",
2310 "one-shot run: topic names use deterministic heuristics and no "
2311 "content angles are generated - a reasoning-model host running "
2312 "the SKILL.md discovery protocol gets host-judged names, junk "
2313 "filtering, and podcast/X angles",
2314 tty_only=False,
2315 )
2316
2317 topic_limit = max(5, min(10, limit))
2318 nominations = nominate_topics(
2319 sweep.bundle, sweep.query_plan, plan,
2320 from_date=from_date,
2321 to_date=to_date,
2322 limit=ENRICH_LIMIT if enrich else topic_limit,
2323 )
2324
2325 if enrich and nominations:
2326 enriched_entries = enrich_nominations(
2327 nominations,
2328 config=config,
2329 requested_sources=enrich_requested_sources,
2330 mock=mock,
2331 lookback_days=lookback_days,
2332 as_of_date=as_of_date,
2333 )
2334 else:
2335 enriched_entries = [
2336 EnrichedTopic(nomination=nomination) for nomination in nominations
2337 ]
2338
2339 survivors, weak_signal, junk_weak_signal = _floor_survivor_records(
2340 enriched_entries, to_date=to_date, topic_limit=topic_limit,
2341 )
2342 folded = _fold_same_story_records(survivors)
2343 # One-shot topics ship without angles (podcast_angle / x_article_angle
2344 # stay None and the renderer omits those lines): content angles are a
2345 # host-judged protocol deliverable, written on the finalize leg.
2346 topics = _records_to_discovery_topics(folded)
2347
2348 if weak_signal is None:
2349 weak_signal = junk_weak_signal
2350
2351 outcome = "ok" if topics else "nothing-solid"
2352
2353 return schema.DiscoveryReport(
2354 domain=plan.domain,
2355 range_from=from_date,
2356 range_to=to_date,
2357 generated_at=datetime.now(timezone.utc).isoformat(),
2358 plan=plan,
2359 topics=topics,
2360 source_status=source_status,
2361 warnings=(
2362 _discovery_report_warnings(topics, outcome, source_status)
2363 + sweep.bundle.artifacts.get("x_partial_coverage", [])
2364 ),
2365 outcome=outcome,
2366 weak_signal=weak_signal[1] if weak_signal and not topics else None,
2367 )
2368
2369
2370 # Protocol leg 2 (resume) deep-tier enrichment bounds. The module-level
2371 # ENRICH_* constants above stay the one-shot --discover contract (quick depth,
2372 # 240s budget, 3 workers); a deep-tier bundle upgrades its per-topic sub-runs
2373 # to the default research depth with a wider wall-clock budget and one more
2374 # worker, because leg 2 is the protocol's only research pass. Shallow-tier
2375 # bundles keep the one-shot quick constants. Both tiers flow through
2376 # enrich_nominations' PARAMETERS - the constants themselves are never edited,
2377 # so neither tier can leak into the other path.
2378 RESUME_DEEP_ENRICH_DEPTH = "default"
2379 RESUME_DEEP_ENRICH_MAX_WORKERS = 4
2380 RESUME_DEEP_ENRICH_BUDGET_SECONDS = 450.0
2381
2382
2383 def _resume_enrich_budget_seconds(config: dict[str, Any]) -> float:
2384 """Deep-tier batch budget: LAST30DAYS_ENRICH_BUDGET_SECONDS from the
2385 RESOLVED config dict only (env.get_config already layers the process env
2386 over the .env files) - never read from bare os.environ. Blank,
2387 non-numeric, or non-positive values fall back to the 450s default."""
2388 raw = config.get("LAST30DAYS_ENRICH_BUDGET_SECONDS")
2389 if raw is None or str(raw).strip() == "":
2390 return RESUME_DEEP_ENRICH_BUDGET_SECONDS
2391 try:
2392 value = float(raw)
2393 except (TypeError, ValueError):
2394 return RESUME_DEEP_ENRICH_BUDGET_SECONDS
2395 return value if value > 0 else RESUME_DEEP_ENRICH_BUDGET_SECONDS
2396
2397
2398 @dataclass(frozen=True)
2399 class DiscoverResumeResult:
2400 """Leg 2 output of the host-judged discovery protocol: the floored,
2401 folded, velocity-ranked report plus the per-topic angle inputs (keyed by
2402 surviving nomination id) that the host writes leg-3 angles from.
2403 ``report.source_status`` is the bundle's restored leg-1 sweep status -
2404 leg 2 never re-sweeps the listing feeds, so the sweep's degraded-coverage
2405 signal must survive the handoff instead of reading as clean."""
2406
2407 report: schema.DiscoveryReport
2408 angle_inputs: dict[str, dict[str, str]]
2409
2410
2411 def run_discover_resume(
2412 bundle: Any,
2413 judgments: dict[str, Any],
2414 *,
2415 config: dict[str, Any],
2416 mock: bool = False,
2417 ) -> DiscoverResumeResult:
2418 """Protocol leg 2: apply host judgments to the leg-1 bundle, enrich the
2419 slot winners, and floor/fold/rank on the same code path as the one-shot
2420 run.
2421
2422 ``bundle`` is a ``discovery_handoff.NominationsBundle`` and ``judgments``
2423 the mapping ``discovery_handoff.read_judgments`` returns (annotated
2424 loosely because discovery_handoff imports this module at load time).
2425
2426 Judgment application is per field: an absent host name falls back to the
2427 bundle's heuristic name, an absent junk flag to the heuristic junk flag,
2428 and absent worthiness to the neutral blend default (None -> 50 inside
2429 ``rerank.judge_blended_score`` - the same treatment the judge-absent path
2430 always used). Applied names are collision-resolved over the whole pool
2431 before anything keys on them, and the applied name IS the enrichment
2432 sub-run topic.
2433
2434 Slot selection: host-junk rows never contend for enrichment slots, and a
2435 heuristic-junk fallback row with fewer than ``rerank.FLOOR_MIN_SOURCES``
2436 distinct seed sources is skipped pre-enrichment (it structurally cannot
2437 pass the floor's seed-corroboration rule). Both stay eligible to be the
2438 junk-tracked weak signal of a nothing-solid brief, and the brief prefers
2439 a non-junk weak signal exactly like the one-shot path. At the floor,
2440 host-judged rows pass ``junk_shape=False`` (host-junk never earned a
2441 slot) while heuristic-fallback rows keep their heuristic flag with the
2442 existing seed-source corroboration.
2443
2444 Velocity, momentum, and the enrichment window all score against the
2445 bundle's momentum window (from_date/to_date), never the resume-time
2446 clock: the host may judge up to the handoff TTL after the sweep, and the
2447 numbers must describe the window the sweep captured.
2448 """
2449 # Runtime-only import: discovery_handoff imports pipeline at module load,
2450 # so the reverse import must happen at call time (no import-time cycle).
2451 from . import discovery_handoff
2452
2453 to_date = bundle.to_date
2454 verdicts = [
2455 discovery_handoff.judgment_for(judgments, entry.nomination_id)
2456 for entry in bundle.nominations
2457 ]
2458 applied_names = discovery_handoff.resolve_name_collisions([
2459 (
2460 entry.nomination,
2461 verdict.name or entry.heuristic_name or entry.nomination.name,
2462 )
2463 for entry, verdict in zip(bundle.nominations, verdicts)
2464 ])
2465
2466 ranked: list[tuple[float, str, Nomination]] = []
2467 junk_weak_signal: tuple[float, str] | None = None
2468 for entry, verdict, name in zip(bundle.nominations, verdicts, applied_names):
2469 items = entry.nomination.items
2470 velocity = rerank.discovery_velocity_score(items, as_of_date=to_date)
2471 seed_source_count = len({item.source for item in items})
2472 host_junk = verdict.junk is True
2473 fallback_junk = verdict.junk is None and entry.heuristic_junk
2474 if host_junk or (
2475 fallback_junk and seed_source_count < rerank.FLOOR_MIN_SOURCES
2476 ):
2477 if junk_weak_signal is None or velocity > junk_weak_signal[0]:
2478 junk_weak_signal = (velocity, name)
2479 continue
2480 worthiness = (
2481 float(verdict.worthiness) if verdict.worthiness is not None else None
2482 )
2483 blended = rerank.judge_blended_score(velocity, worthiness)
2484 ranked.append((
2485 blended,
2486 entry.nomination_id,
2487 replace(
2488 entry.nomination,
2489 name=name,
2490 seed_score=blended,
2491 junk_shape=(
2492 False if verdict.junk is not None else entry.heuristic_junk
2493 ),
2494 worthiness=worthiness,
2495 ),
2496 ))
2497
2498 ranked.sort(key=lambda row: (-row[0], row[2].name.lower()))
2499 selected = ranked[:ENRICH_LIMIT]
2500 nominations = [nomination for _blended, _nomination_id, nomination in selected]
2501
2502 if bundle.tier == "shallow":
2503 depth, max_workers, budget_seconds = (
2504 ENRICH_DEPTH, ENRICH_MAX_WORKERS, ENRICH_BUDGET_SECONDS,
2505 )
2506 else:
2507 depth = RESUME_DEEP_ENRICH_DEPTH
2508 max_workers = RESUME_DEEP_ENRICH_MAX_WORKERS
2509 budget_seconds = _resume_enrich_budget_seconds(config)
2510
2511 enriched_entries = enrich_nominations(
2512 nominations,
2513 config=config,
2514 requested_sources=bundle.enrichment_source_boundary,
2515 mock=mock,
2516 depth=depth,
2517 lookback_days=bundle.lookback_days,
2518 as_of_date=to_date,
2519 max_workers=max_workers,
2520 budget_seconds=budget_seconds,
2521 ) if nominations else []
2522
2523 # topic_limit mirrors the one-shot default cap (limit=10); the slot cut
2524 # above already bounds the pool at ENRICH_LIMIT.
2525 survivors, weak_signal, floor_junk_weak_signal = _floor_survivor_records(
2526 enriched_entries, to_date=to_date, topic_limit=10,
2527 )
2528 if floor_junk_weak_signal is not None and (
2529 junk_weak_signal is None
2530 or floor_junk_weak_signal[0] > junk_weak_signal[0]
2531 ):
2532 junk_weak_signal = floor_junk_weak_signal
2533 folded = _fold_same_story_records(survivors)
2534 topics = _records_to_discovery_topics(folded)
2535
2536 nomination_id_by_name = {
2537 nomination.name: nomination_id
2538 for _blended, nomination_id, nomination in selected
2539 }
2540 angle_inputs = {
2541 nomination_id_by_name[record["name"]]: {
2542 "name": record["name"],
2543 "titles": record["titles"],
2544 "top_comment": record["top_comment"] or "",
2545 "engagement": record["engagement_phrase"],
2546 }
2547 for record in folded
2548 }
2549
2550 if weak_signal is None:
2551 weak_signal = junk_weak_signal
2552 outcome = "ok" if topics else "nothing-solid"
2553 plan = schema.DiscoveryPlan(
2554 domain=bundle.domain,
2555 category=None,
2556 subreddits=[],
2557 sources=(
2558 list(bundle.requested_sources)
2559 if bundle.requested_sources
2560 else sorted({
2561 item.source
2562 for entry in bundle.nominations
2563 for item in entry.nomination.items
2564 })
2565 ),
2566 )
2567 # The bundle's restored leg-1 sweep status (empty for pre-field bundles):
2568 # degraded sweep coverage must reach this report's status map and its
2569 # degraded-sources warning exactly as the one-shot reports it.
2570 source_status = dict(getattr(bundle, "source_status", None) or {})
2571 report = schema.DiscoveryReport(
2572 domain=bundle.domain,
2573 range_from=bundle.from_date,
2574 range_to=to_date,
2575 generated_at=datetime.now(timezone.utc).isoformat(),
2576 plan=plan,
2577 topics=topics,
2578 source_status=source_status,
2579 warnings=(
2580 _discovery_report_warnings(topics, outcome, source_status)
2581 + list(getattr(bundle, "warnings", None) or [])
2582 ),
2583 outcome=outcome,
2584 weak_signal=weak_signal[1] if weak_signal and not topics else None,
2585 )
2586 return DiscoverResumeResult(report=report, angle_inputs=angle_inputs)
2587
2588
2589 def diagnose(
2590 config: dict[str, Any],
2591 requested_sources: list[str] | None = None,
2592 *,
2593 safe: bool = False,
2594 x_envelope: bool = False,
2595 probe_x: bool = True,
2596 ) -> dict[str, Any]:
2597 # ``x_envelope`` is True when a validated --x-posts envelope is present for
2598 # this invocation, so available_sources lists x even without a backend
2599 # and the optional-source omission note does not fire.
2600 requested_sources = normalize_requested_sources(requested_sources)
2601 probe_x = (
2602 probe_x and not safe and not x_envelope
2603 and not env.x_host_lane_declared(config)
2604 and (requested_sources is None or "x" in requested_sources)
2605 and "x" not in _excluded_sources(config)
2606 )
2607 google_key = _google_key(config)
2608 x_status = env.get_x_source_status(config, probe=probe_x)
2609 # Compute once and reuse for both the diag flag and available_sources below.
2610 # safe=True (doctor/--diagnose/--preflight) must stay network-free.
2611 x_pending = (
2612 env.x_pending_browser_auth(config, local_only=not probe_x)
2613 and health.probe_dependency("node").status == health.OK
2614 )
2615 native_web_backend = None
2616 if config.get("BRAVE_API_KEY"):
2617 native_web_backend = "brave"
2618 elif config.get("EXA_API_KEY"):
2619 native_web_backend = "exa"
2620 elif config.get("SERPER_API_KEY"):
2621 native_web_backend = "serper"
2622 elif config.get("PARALLEL_API_KEY"):
2623 native_web_backend = "parallel"
2624 providers_status = {
2625 "google": bool(google_key),
2626 "openai": bool(config.get("OPENAI_API_KEY")) and config.get("OPENAI_AUTH_STATUS") == env.AUTH_STATUS_OK,
2627 "xai": bool(config.get("XAI_API_KEY")),
2628 "openrouter": bool(config.get("OPENROUTER_API_KEY")),
2629 "perplexity": bool(config.get("PERPLEXITY_API_KEY")),
2630 }
2631 reasoning_provider_available = any(
2632 providers_status[name] for name in ("google", "openai", "xai", "openrouter")
2633 )
2634 external_commands = {
2635 "yt-dlp": bool(which("yt-dlp")),
2636 "digg-pp-cli": bool(which("digg-pp-cli")),
2637 "arxiv-pp-cli": bool(which("arxiv-pp-cli")),
2638 "techmeme-pp-cli": bool(which("techmeme-pp-cli")),
2639 "trustpilot-pp-cli": bool(which("trustpilot-pp-cli")),
2640 "brightdata": bool(which("brightdata")),
2641 "gh": bool(which("gh")),
2642 }
2643 # Network-free two-field probe (bird_installed/bird_authenticated
2644 # precedent): "installed" is PATH resolution, "authenticated" is a
2645 # presence-only credential signal that never reads the secret.
2646 brightdata_status = brightdata.gate_status(config)
2647 credential_destinations = {
2648 "global_env": str(env.CONFIG_FILE) if env.CONFIG_FILE else None,
2649 }
2650 browser_cookies = {
2651 "mode": config.get("_BROWSER_COOKIE_MODE", "off"),
2652 "browsers": list(config.get("_BROWSER_COOKIE_BROWSERS") or []),
2653 "reads_values": False if safe else config.get("_BROWSER_COOKIE_MODE") == "read",
2654 }
2655 ignored_project_keys = list(config.get("_IGNORED_PROJECT_CONFIG_KEYS") or [])
2656 ignored_endpoint_overrides = [
2657 key for key in ignored_project_keys if key in permission_preflight.ENDPOINT_OVERRIDE_KEYS
2658 ]
2659 local_writes: list[dict[str, str]] = []
2660 if config.get("LAST30DAYS_MEMORY_DIR"):
2661 local_writes.append({"kind": "report", "path": str(config.get("LAST30DAYS_MEMORY_DIR"))})
2662 reasoning_provider_cfg = (config.get("LAST30DAYS_REASONING_PROVIDER") or "auto").strip().lower()
2663 reasoning_provider_forced_local = reasoning_provider_cfg in {"local", "off", "none"}
2664 diag = {
2665 "providers": providers_status,
2666 "local_mode": not reasoning_provider_available or reasoning_provider_forced_local,
2667 "reasoning_provider": reasoning_provider_cfg,
2668 # The host-fetched connector lane serves X when no engine backend
2669 # exists and the model declared the lane.
2670 "x_backend": x_status["source"] or (
2671 "connector" if env.x_host_lane_declared(config) else None
2672 ),
2673 "bird_installed": x_status["bird_installed"],
2674 "bird_authenticated": x_status["bird_authenticated"],
2675 "bird_username": x_status["bird_username"],
2676 "x_pending_browser_auth": x_pending,
2677 "xquik_available": x_status.get("xquik_available", False),
2678 "xquik_working": x_status.get("xquik_working"),
2679 "xquik_status": x_status.get("xquik_status", ""),
2680 "native_web_backend": native_web_backend,
2681 "native_search": env.is_native_search(config),
2682 "has_scrapecreators": bool(config.get("SCRAPECREATORS_API_KEY")),
2683 "has_github": bool(config.get("GITHUB_TOKEN") or which("gh")),
2684 "brightdata_installed": brightdata_status["brightdata_installed"],
2685 "brightdata_authenticated": brightdata_status["brightdata_authenticated"],
2686 # Fresh browser session or a cached company record: the host resolves
2687 # a --trustpilot-domain only then. Local reads; never opens a browser.
2688 "trustpilot_can_run": (
2689 "trustpilot" not in _excluded_sources(config)
2690 and trustpilot.can_run_now(config)["can_run"]
2691 ),
2692 # safe=True (doctor/--diagnose/--preflight) must stay network-free:
2693 # answer X availability from local evidence only. x_pending is
2694 # precomputed by diagnose() to avoid double evaluation.
2695 "available_sources": available_sources(
2696 config, requested_sources, x_pending=x_pending, local_only=not probe_x,
2697 x_envelope=x_envelope,
2698 ),
2699 "safe": safe,
2700 "config_source": config.get("_CONFIG_SOURCE"),
2701 "ignored_project_config": config.get("_IGNORED_PROJECT_CONFIG"),
2702 "ignored_project_config_keys": ignored_project_keys,
2703 "ignored_endpoint_overrides": ignored_endpoint_overrides,
2704 "browser_cookies": browser_cookies,
2705 "external_commands": external_commands,
2706 "credential_destinations": credential_destinations,
2707 "local_writes": local_writes,
2708 }
2709 diag["permission_preflight"] = permission_preflight.build(
2710 config, diag, requested_sources=requested_sources,
2711 )
2712 return diag
2713
2714
2715 def _inner_max_workers(stream_count: int, *, internal_subrun: bool) -> int:
2716 """Worker-pool size for the per-stream fanout inside a single pipeline run.
2717
2718 Top-level runs use up to 16 workers. Subruns of ``run_competitor_fanout``
2719 cap the inner pool to 4 so a six-way competitor fan-out stays below
2720 roughly 30 worker threads in aggregate instead of ~96.
2721 """
2722 if internal_subrun:
2723 return max(2, min(4, stream_count or 1))
2724 return max(4, min(16, stream_count or 1))
2725
2726
2727 def is_blank_save_dir(save_dir: Path | str | None) -> bool:
2728 """True when ``save_dir`` is a non-empty whitespace-only path string."""
2729 if save_dir is None:
2730 return False
2731 text = str(save_dir)
2732 return text != "" and not text.strip()
2733
2734
2735 def is_scoped_save_dir(save_dir: Path | str | None) -> bool:
2736 """True when ``save_dir`` points to a directory other than DEFAULT_MEMORY_DIR.
2737
2738 Preserves non-empty paths verbatim (never strips leading/trailing spaces).
2739 Whitespace-only inputs and resolution failures fail closed as scoped (True)
2740 so they never select the shared default library or global briefing archive.
2741 """
2742 if save_dir is None or str(save_dir) == "":
2743 return False
2744 if is_blank_save_dir(save_dir):
2745 return True
2746 try:
2747 return (
2748 Path(save_dir).expanduser().resolve()
2749 != Path(library.DEFAULT_MEMORY_DIR).expanduser().resolve()
2750 )
2751 except (OSError, ValueError, TypeError, RuntimeError):
2752 return True
2753
2754
2755 def scoped_store_db_path(save_dir: Path | str | None) -> Path | None:
2756 """Return the scoped research.db path, or None to use the shared default store.
2757
2758 Preserves non-empty paths verbatim and preserves an existing legacy
2759 ``DEFAULT_MEMORY_DIR/research.db`` created by earlier builds rather than
2760 abandoning its saved findings and discovery queue.
2761 """
2762 if save_dir is None or str(save_dir) == "":
2763 return None
2764 if is_blank_save_dir(save_dir):
2765 raise ValueError("--save-dir / LAST30DAYS_MEMORY_DIR cannot be whitespace-only.")
2766 try:
2767 resolved = Path(save_dir).expanduser().resolve()
2768 except (OSError, ValueError, TypeError, RuntimeError):
2769 return Path(save_dir).expanduser() / "research.db"
2770 candidate = resolved / "research.db"
2771 if is_scoped_save_dir(resolved):
2772 return candidate
2773 if candidate.is_file():
2774 return candidate
2775 return None
2776
2777
2778 def library_context_index_path(
2779 config: dict[str, Any], save_dir: Path | str | None,
2780 ) -> Path | None:
2781 setting = str(config.get("LAST30DAYS_LIBRARY_CONTEXT") or "off").strip().lower()
2782 if (
2783 setting in {"0", "false", "no", "off"}
2784 or save_dir == ""
2785 or is_blank_save_dir(save_dir)
2786 or (save_dir is None and is_blank_save_dir(config.get("LAST30DAYS_MEMORY_DIR")))
2787 ):
2788 return None
2789 if path := config.get("_LAST30DAYS_LIBRARY_DB"):
2790 return Path(path).expanduser()
2791 if is_scoped_save_dir(save_dir):
2792 assert save_dir is not None
2793 return Path(save_dir).expanduser().resolve() / ".last30days-library.db"
2794 return library_index.DEFAULT_LIBRARY_DB
2795
2796
2797 def _load_library_context(
2798 *,
2799 topic: str,
2800 config: dict[str, Any],
2801 mock: bool,
2802 internal_subrun: bool,
2803 x_handle: str | None,
2804 github_user: str | None,
2805 github_repos: list[str] | None,
2806 save_dir: Path | str | None = None,
2807 ) -> tuple[list[schema.LibraryContext], str | None]:
2808 """Resolve compact prior-run context without making a research run depend on it."""
2809 if mock or internal_subrun:
2810 return [], None
2811 db_path = library_context_index_path(config, save_dir)
2812 if db_path is None:
2813 return [], None
2814
2815 scoped = is_scoped_save_dir(save_dir)
2816 memory_dir = (
2817 save_dir
2818 if save_dir is not None
2819 else config.get("LAST30DAYS_MEMORY_DIR") or library.DEFAULT_MEMORY_DIR
2820 )
2821 briefs_dir = config.get("_LAST30DAYS_LIBRARY_BRIEFS_DIR") or (
2822 Path(memory_dir).expanduser() / "briefings"
2823 if scoped
2824 else library.DEFAULT_BRIEFS_DIR
2825 )
2826 store_db = config.get("_LAST30DAYS_STORE_DB")
2827 if not store_db:
2828 # Scoped runs read only a store inside the save dir (usually absent);
2829 # the shared store would leak other scopes' sightings into this one.
2830 store_db = (
2831 scoped_store_db_path(save_dir)
2832 or library_index.DEFAULT_STORE_DB
2833 )
2834 queries = [topic, x_handle or "", github_user or "", *(github_repos or [])]
2835 queries = list(dict.fromkeys(value.strip() for value in queries if value and value.strip()))
2836 try:
2837 library_index.sync_library(memory_dir, briefs_dir, db_path=db_path)
2838 matches: list[library_index.LibrarySearchMatch] = []
2839 for query_text in queries:
2840 matches.extend(
2841 library_index.search(
2842 query_text,
2843 limit=6,
2844 db_path=db_path,
2845 store_db_path=store_db,
2846 )
2847 )
2848 except (library_index.LibrarySearchUnavailable, OSError, sqlite3.DatabaseError) as exc:
2849 return [], f"Library context unavailable: {exc}"
2850
2851 contexts: list[schema.LibraryContext] = []
2852 seen_runs: set[tuple[str, date]] = set()
2853 for match in sorted(
2854 matches,
2855 key=lambda item: (-item.published_date.toordinal(), item.rank, item.topic.casefold()),
2856 ):
2857 if match.run_key in seen_runs:
2858 continue
2859 seen_runs.add(match.run_key)
2860 contexts.append(
2861 schema.LibraryContext(
2862 topic=match.topic,
2863 published_date=match.published_date.isoformat(),
2864 headline=match.headline,
2865 summary=match.snippet or match.headline,
2866 source_kind=match.source_kind,
2867 )
2868 )
2869 if len(contexts) == 3:
2870 break
2871 return contexts, None
2872
2873
2874 def _scoped_fetch_memo(fn: Callable[..., schema.Report]) -> Callable[..., schema.Report]:
2875 """Isolate top-level ``pipeline.run`` calls in their own ``fetch_memo.run_scope()``."""
2876 @functools.wraps(fn)
2877 def _wrapped(*args: Any, **kwargs: Any) -> schema.Report:
2878 if kwargs.get("internal_subrun"):
2879 return fn(*args, **kwargs)
2880 with fetch_memo.run_scope():
2881 return fn(*args, **kwargs)
2882 return _wrapped
2883
2884
2885 @_scoped_fetch_memo
2886 def run(
2887 *,
2888 topic: str,
2889 config: dict[str, Any],
2890 depth: str,
2891 requested_sources: list[str] | None = None,
2892 mock: bool = False,
2893 x_handle: str | None = None,
2894 x_related: list[str] | None = None,
2895 web_backend: str = "auto",
2896 external_plan: dict | None = None,
2897 subreddits: list[str] | None = None,
2898 tiktok_hashtags: list[str] | None = None,
2899 tiktok_creators: list[str] | None = None,
2900 ig_creators: list[str] | None = None,
2901 lookback_days: int = 30,
2902 as_of_date: str | None = None,
2903 github_user: str | None = None,
2904 github_repos: list[str] | None = None,
2905 trustpilot_domain: str | None = None,
2906 trustpilot_domain_is_hint: bool = False,
2907 hiring_signals_mode: bool = False,
2908 internal_subrun: bool = False,
2909 suppress_x_host_lane: bool = False,
2910 save_dir: Path | str | None = None,
2911 corpus_dirs: list[str] | None = None,
2912 corpus_all_time: bool = False,
2913 x_posts: x_envelope.Envelope | None = None,
2914 reddit_threads: reddit_envelope.Envelope | None = None,
2915 shortform_urls: shortform_envelope.Envelope | None = None,
2916 ) -> schema.Report:
2917 _check_research(config)
2918 # Isolate run-scoped mutations (_financial_topic, envelopes, resolved
2919 # endpoints, lane budgets) from the caller's dict so concurrent callers
2920 # (comparison fan-out, discovery enrichment) never race or leak state.
2921 config = dict(config)
2922 if external_plan is not None:
2923 planner.validate_external_plan(external_plan)
2924 config = with_plan_source_omissions(config, external_plan)
2925 excluded_sources = _excluded_sources(config)
2926 # ``suppress_x_host_lane`` is distinct from ``internal_subrun``: comparison
2927 # entities share the latter and must still honor the connector lane;
2928 # only discovery enrichment passes set the former.
2929 # ``x_posts`` is a validated ``--x-posts`` envelope: when present
2930 # it replaces the engine's X fetch for this run and is served once.
2931 # Standalone runs (not competitor/discover sub-runs) own the YouTube
2932 # search-cache lifecycle. Comparison fan-out clears once before submit so
2933 # parallel entity sub-runs can still share in-run hits.
2934 if not internal_subrun:
2935 youtube_yt.reset_search_cache()
2936 settings = _resolve_depth_settings(depth, config)
2937 requested_sources = normalize_requested_sources(requested_sources)
2938 local_corpus_drill = config.get("_drill_mode") and requested_sources == ["corpus"]
2939 if local_corpus_drill:
2940 web_backend = "none"
2941 # Wall-clock origin for budget-aware enrichment lanes. Amazon review
2942 # enrichment starts at search time (inside _retrieve_stream_impl) so it
2943 # overlaps other sources instead of waiting for them all to finish.
2944 run_started = time.monotonic()
2945 from_date, to_date = dates.get_date_range(lookback_days, as_of_date=as_of_date)
2946 jobs_past_window = to_date < dates.get_date_range(0)[1]
2947 resolved_corpus_dirs = corpus.resolve_directories(
2948 corpus_dirs or config.get("_CORPUS_DIRS"),
2949 config.get("LAST30DAYS_CORPUS_DIRS"),
2950 )
2951 corpus_enabled = bool(resolved_corpus_dirs) and "corpus" not in excluded_sources
2952 corpus_requested = bool(requested_sources and "corpus" in requested_sources)
2953 if corpus_enabled and requested_sources and "corpus" not in requested_sources:
2954 requested_sources = [*requested_sources, "corpus"]
2955 # The --search list as the user gave it, before the engine attaches its
2956 # own lanes, so the dropped-source warning can tell what it would drop.
2957 search_list = list(requested_sources or [])
2958 # A run about a company keeps the jobs lane under a --search list that
2959 # omits it: hosts routinely pass full source lists and would silently
2960 # lose the lane. EXCLUDE_SOURCES=jobs is the opt-out; quick runs keep
2961 # their small source budget.
2962 company_signal = str(config.get("_company_signal") or "")
2963 company_jobs_attached = bool(
2964 requested_sources
2965 and company_signal
2966 and depth != "quick"
2967 and "jobs" not in requested_sources
2968 and "jobs" not in excluded_sources
2969 )
2970 if company_jobs_attached:
2971 requested_sources = [*requested_sources, "jobs"]
2972
2973 # Host-fetched X lane. EXCLUDE_SOURCES=x or a --search list without
2974 # x wins: the envelope is ignored with a receipt line and stays unconsumed.
2975 envelope = x_posts
2976 if envelope is not None and (
2977 "x" in excluded_sources
2978 or (requested_sources and "x" not in requested_sources)
2979 ):
2980 log.source_log(
2981 "x", "host-fetched X: envelope ignored (x is excluded from this run)",
2982 tty_only=False,
2983 )
2984 envelope = None
2985 # The lane signal without an envelope is a broken handoff, not a reason to
2986 # spend a backup backend: X records the fixed not-passed outcome.
2987 x_lane_missing = (
2988 envelope is None
2989 and not mock
2990 and not local_corpus_drill
2991 and not suppress_x_host_lane
2992 and env.x_host_lane_declared(config)
2993 )
2994 if envelope is not None or x_lane_missing:
2995 # Ride the config dict (the _polymarket_keywords idiom) so the stream
2996 # workers and the handle-lane section see it without widening their
2997 # signatures. Copy first: comparison entities shallow-copy the shared
2998 # config and must never inherit another entity's envelope.
2999 config = dict(config)
3000 config["_x_envelope"] = envelope
3001 config["_x_lane_missing"] = x_lane_missing
3002
3003 # Host-found Reddit thread refs (--reddit-threads). They serve every
3004 # Reddit stream of the run; a run that excludes Reddit ignores them.
3005 reddit_refs_envelope = reddit_threads
3006 if reddit_refs_envelope is not None and (
3007 "reddit" in excluded_sources
3008 or (requested_sources and "reddit" not in requested_sources)
3009 ):
3010 log.source_log(
3011 "reddit", "host Reddit threads: envelope ignored (reddit is excluded from this run)",
3012 tty_only=False,
3013 )
3014 reddit_refs_envelope = None
3015 if reddit_refs_envelope is not None:
3016 config = dict(config)
3017 config["_reddit_envelope"] = reddit_refs_envelope
3018
3019 # Host-found TikTok / Instagram URLs (--shortform-urls). Only the keyless
3020 # short-form lane reads them; a run searching neither platform ignores them.
3021 if shortform_urls is not None and not any(
3022 name not in excluded_sources
3023 and (not requested_sources or name in requested_sources)
3024 for name in ("tiktok", "instagram")
3025 ):
3026 log.source_log(
3027 "TikTok", "host short-form URLs: envelope ignored (TikTok and Instagram are excluded from this run)",
3028 tty_only=False,
3029 )
3030 shortform_urls = None
3031 if shortform_urls is not None:
3032 config = dict(config)
3033 config["_shortform_envelope"] = shortform_urls
3034
3035 # Gate StockTwits to ticker/crypto topics. Single chokepoint: when False,
3036 # available_sources() never registers stocktwits, so the planner can't
3037 # assign it (eligible_sources = available ∩ capabilities).
3038 config["_financial_topic"] = stocktwits.is_financial_topic(topic)
3039
3040 # A host-supplied plan's source lists are final: company-topic jobs is an
3041 # automatic lane only for engine-planned runs.
3042 host_plan = external_plan is not None
3043 auto_company_jobs = not host_plan and _company_topic_likely(topic)
3044 if local_corpus_drill:
3045 runtime = schema.ProviderRuntime("local", "deterministic", "local-score")
3046 reasoning_provider = None
3047 available_before_search = available = ["corpus"]
3048 elif mock:
3049 runtime = providers.mock_runtime(config, depth)
3050 reasoning_provider = None
3051 available_before_search = list(MOCK_AVAILABLE_SOURCES)
3052 available = list(requested_sources or MOCK_AVAILABLE_SOURCES)
3053 if corpus_enabled and "corpus" not in available:
3054 available.append("corpus")
3055 if not corpus_enabled and not corpus_requested:
3056 available = [source for source in available if source != "corpus"]
3057 if not requested_sources and not hiring_signals_mode and not auto_company_jobs:
3058 available = [source for source in available if source != "jobs"]
3059 else:
3060 runtime, reasoning_provider = providers.resolve_runtime(config, depth)
3061 available = available_sources(
3062 config, requested_sources,
3063 suppress_x_host_lane=suppress_x_host_lane,
3064 x_envelope=envelope is not None,
3065 )
3066 available_before_search = list(available)
3067 if requested_sources:
3068 available = [source for source in available if source in requested_sources]
3069 # Keep an explicitly requested but unconfigured corpus in the plan long
3070 # enough to record its skipped-unconfigured source outcome. It is never
3071 # submitted to the network executor below.
3072 if corpus_requested and "corpus" not in excluded_sources and "corpus" not in available:
3073 available.append("corpus")
3074 if web_backend == "none":
3075 available = [s for s in available if s != "grounding"]
3076 elif web_backend in ("brave", "exa", "serper", "parallel", "parallel-mcp", "keyless") and "grounding" not in available:
3077 available.append("grounding")
3078 if (
3079 hiring_signals_mode
3080 or (not requested_sources and auto_company_jobs)
3081 ) and "jobs" not in available:
3082 available.append("jobs")
3083 # A host plan about a company gets the jobs lane whether or not the plan
3084 # names it: the lane is free and bounded, and a host that forgets one
3085 # word must not cost the run a working board. Quick runs keep the
3086 # sanitizer's two-source budget, as for the installed lanes below.
3087 if (
3088 host_plan
3089 and not requested_sources
3090 and "jobs" not in available
3091 and "jobs" not in excluded_sources
3092 and (
3093 _external_plan_names_source(external_plan, "jobs")
3094 or (company_signal and depth != "quick")
3095 )
3096 ):
3097 available.append("jobs")
3098 if hiring_signals_mode:
3099 config = dict(config)
3100 config["_hiring_signals_mode"] = True
3101 if not requested_sources:
3102 available = ["jobs"]
3103 available = [source for source in available if source not in excluded_sources]
3104 if not available:
3105 if requested_sources:
3106 raise NoRequestedSourceAvailable(
3107 "None of the sources in --search can run here: "
3108 + ", ".join(requested_sources)
3109 + ". Run `last30days.py doctor` to see what each one needs."
3110 )
3111 raise RuntimeError("No sources are available for this run.")
3112 # A person run's own posts are not a source the host names in --search:
3113 # keep the lane whatever the list says. EXCLUDE_SOURCES still opts out.
3114 if (
3115 PERSON_POSTS_SOURCE in available_before_search
3116 and PERSON_POSTS_SOURCE not in available
3117 and PERSON_POSTS_SOURCE not in excluded_sources
3118 ):
3119 available.append(PERSON_POSTS_SOURCE)
3120
3121 planner_requested_sources = (
3122 [source for source in requested_sources if source not in excluded_sources]
3123 if requested_sources else None
3124 )
3125 if hiring_signals_mode and not planner_requested_sources:
3126 planner_requested_sources = ["jobs"]
3127
3128 if external_plan is not None:
3129 # External plan provided (e.g., from Claude Code via --plan flag).
3130 if hiring_signals_mode:
3131 # Hiring-signals mode always runs the jobs lane. Add it before
3132 # sanitizing: with a jobs-only source set, sanitize would drop every
3133 # subquery that does not already name jobs.
3134 external_plan = copy.deepcopy(external_plan)
3135 for subquery in external_plan["subqueries"]:
3136 sources = subquery.setdefault("sources", [])
3137 if isinstance(sources, list) and "jobs" not in sources:
3138 sources.append("jobs")
3139 plan = planner._sanitize_plan(
3140 external_plan, topic, available, planner_requested_sources, depth,
3141 honor_plan_sources=True,
3142 )
3143 # Quick runs keep the sanitizer's two-source budget, plus any paid
3144 # lane this run asked for.
3145 _ensure_unplanned_lanes_in_host_plan(
3146 plan, available,
3147 asked=_paid_lanes_asked_for(planner_requested_sources, config),
3148 installed=depth != "quick",
3149 config=config,
3150 requested_sources=planner_requested_sources,
3151 trustpilot_domain=trustpilot_domain,
3152 )
3153 if depth != "quick" and not hiring_signals_mode:
3154 _ensure_company_jobs_in_host_plan(plan, available, company_signal)
3155 if search_list:
3156 _warn_search_dropped_plan_sources(
3157 external_plan,
3158 search_list,
3159 available_before_search,
3160 excluded_sources,
3161 jobs_attached=company_jobs_attached,
3162 jobs_past_window=jobs_past_window,
3163 company_signal=company_signal,
3164 )
3165 plan_source = "external"
3166 else:
3167 _check_research(config)
3168 plan = planner.plan_query(
3169 topic=topic,
3170 available_sources=available,
3171 requested_sources=planner_requested_sources,
3172 depth=depth,
3173 provider=None if mock else reasoning_provider,
3174 model=None if mock else runtime.planner_model,
3175 context=config.get("_auto_resolve_context", ""),
3176 internal_subrun=internal_subrun,
3177 deadline=_research_deadline(config, PLANNER_TIMEOUT_SECONDS),
3178 cancel=config.get("_enrich_cancel"),
3179 )
3180 # Source labelling: the fallback path annotates notes with "fallback-plan"
3181 # or "deterministic-comparison-plan"; anything else came from the LLM.
3182 if any("fallback" in note or "deterministic" in note for note in (plan.notes or [])):
3183 plan_source = "deterministic"
3184 elif not mock and reasoning_provider and runtime.planner_model:
3185 plan_source = "llm"
3186 else:
3187 plan_source = "deterministic"
3188
3189 # A person run: the person's anchors join any the plan supplied, and the
3190 # identity gate fails closed even when no anchor is known.
3191 person_ctx = config.get("_person")
3192 if person_ctx is not None:
3193 plan.person_identity_anchors = _merged_person_anchors(
3194 plan.person_identity_anchors, person_ctx.anchors,
3195 )
3196 plan.person_run = True
3197
3198 _check_research(config)
3199 # Safety net: ensure grounding appears in all subqueries even if the planner
3200 # omits it. This is redundant when the planner includes grounding via
3201 # SOURCE_CAPABILITIES, but kept as a fallback.
3202 if (
3203 web_backend != "none"
3204 and "grounding" in available
3205 and "drill-mode" not in plan.notes
3206 ):
3207 for sq in plan.subqueries:
3208 if "grounding" not in sq.sources:
3209 sq.sources.append("grounding")
3210 if "drill-mode" not in plan.notes and (not host_plan or hiring_signals_mode):
3211 # Drill plans re-fetch only the sources that contributed to the matched
3212 # cluster, and host plans name their final source set; the company-topic
3213 # jobs injection must not widen either.
3214 _ensure_jobs_in_plan(
3215 plan, available,
3216 explicit=hiring_signals_mode or company_jobs_attached,
3217 topic=topic,
3218 )
3219 for opt_in_source in ("devto", "v2ex", "juejin"):
3220 _ensure_opt_in_source_in_plan(plan, available, opt_in_source)
3221 if "corpus" in available and plan.subqueries:
3222 # Corpus is deterministic and user-registered, so it always gets one
3223 # bounded stream even when a quick/LLM plan omits it. Reuse the primary
3224 # subquery instead of multiplying local scans across every subquery.
3225 if "corpus" not in plan.subqueries[0].sources:
3226 plan.subqueries[0].sources.append("corpus")
3227 if "corpus" not in plan.source_weights:
3228 plan.source_weights["corpus"] = _mean_source_weight(plan.source_weights)
3229 plan.source_weights = planner._normalize_weights(plan.source_weights)
3230
3231 # Add the paid-only Perplexity lane after all normal-source safety nets.
3232 # This preserves the planner's primary subquery, gives the bounded paid
3233 # call the whole user topic, and prevents grounding, jobs, or corpus from
3234 # being attached to the dedicated lane.
3235 _ensure_perplexity_in_plan(
3236 plan,
3237 topic,
3238 available,
3239 force=bool(config.get("_deep_research")),
3240 )
3241
3242 # Always-on planner trace. Emits one summary line plus one per subquery
3243 # so retrieval-breadth failures like the 2026-04-19 Hermes Agent Use Cases
3244 # disaster are visible without --debug. Stderr only; does not leak into
3245 # the user-facing stdout synthesis.
3246 print(
3247 f"[Planner] Plan: intent={plan.intent}, freshness={plan.freshness_mode}, "
3248 f"cluster_mode={plan.cluster_mode}, subqueries={len(plan.subqueries)}, "
3249 f"source={plan_source}",
3250 file=sys.stderr,
3251 )
3252 if plan.subqueries:
3253 for index, sq in enumerate(plan.subqueries, start=1):
3254 sources_str = ",".join(sq.sources) if sq.sources else "(none)"
3255 print(
3256 f"[Planner] sq{index} label={sq.label} "
3257 f'search="{sq.search_query}" sources=[{sources_str}]',
3258 file=sys.stderr,
3259 )
3260 else:
3261 print("[Planner] (no subqueries in plan)", file=sys.stderr)
3262
3263 polymarket_hints = getattr(plan, "polymarket_hints", None)
3264 if polymarket_hints:
3265 config = dict(config)
3266 config["_polymarket_hints"] = polymarket_hints
3267
3268 if reddit_refs_envelope is not None:
3269 # Each Reddit stream receives the host threads its terms match.
3270 reddit_refs_envelope.bind_subqueries(
3271 (sq.label, (sq.search_query, sq.ranking_query))
3272 for sq in plan.subqueries if "reddit" in sq.sources
3273 )
3274
3275 bundle = schema.RetrievalBundle(artifacts={"grounding": []})
3276 deferred_retryable_failures: dict[str, dict[str, Any]] = {}
3277 out_of_time_sources: set[str] = set()
3278 # Searches an enablement plan runs for the capability alone. Their Digg
3279 # stories are not expected to name the run topic.
3280 capability_searches = fusion.capability_labels(plan)
3281 digg_bar_dropped = False
3282 if envelope is not None:
3283 # The footer names the X provenance (render._render_stats).
3284 bundle.artifacts["x_provenance"] = envelope.provenance
3285 # Handles the user named explicitly. Available before any retrieval, unlike
3286 # the entity-extracted set, so Phase 1 and quick-depth runs get first-party
3287 # protection too. Without this the exemption reached only the Phase 2
3288 # supplement path -- which quick runs skip entirely -- so a subject-authored
3289 # post retrieved in Phase 1 was still pruned before fusion, which is exactly
3290 # the evidence loss this change exists to prevent.
3291 explicit_first_party = {
3292 h.lstrip("@").strip().lower()
3293 for h in ([x_handle, github_user, *(x_related or [])])
3294 if h and h.strip()
3295 }
3296 # Creator accounts named via --ig-creators / --creators carry the same
3297 # explicit intent: the run is searching those accounts, and a creator's
3298 # caption rarely repeats the topic's literal tokens, so without an
3299 # exemption the relevance floor prunes them as third-party noise (issue
3300 # #1101: 36 creator reels fetched, 0 reported). The exemption is scoped
3301 # per platform, NOT merged into the global set: each flag names accounts
3302 # on one platform, and an unrelated same-name account elsewhere must not
3303 # bypass the floors.
3304 creator_first_party = _creator_first_party_by_source(tiktok_creators, ig_creators)
3305 if person_ctx is not None and person_ctx.full_name:
3306 # The person's own posts rarely repeat their name; scoped to the
3307 # posts lane, so no same-name account elsewhere is exempted.
3308 creator_first_party[PERSON_POSTS_SOURCE] = {person_ctx.full_name.lower()}
3309 # Real X handles: --x-handle, --x-related, or @mentions in the topic. These
3310 # determine whether the deferred X floor applies. Topic words like "peter"
3311 # are NOT real handles and should not trigger the floor — when no real
3312 # handle is identified, the floor is skipped entirely (policy: a noisier
3313 # report beats losing the subject's evidence).
3314 explicit_x_handles = {
3315 h.lstrip("@").strip().lower()
3316 for h in ([x_handle, *(x_related or [])])
3317 if h and h.strip()
3318 } | _topic_handle_mentions(topic)
3319 # Plus handle-shaped tokens from the topic. Phase 1 and quick-depth runs
3320 # never reach automatic handle resolution, so without this a quick search
3321 # naming a subject still discards everything that subject wrote.
3322 explicit_first_party |= _topic_first_party_candidates(topic)
3323
3324 for source in (requested_sources or []):
3325 if source not in available:
3326 bundle.record_failure(
3327 source,
3328 schema.SKIPPED_UNCONFIGURED,
3329 "Source was requested but is not configured for this run.",
3330 attempted=False,
3331 )
3332 if corpus_requested and not corpus_enabled:
3333 bundle.record_failure(
3334 "corpus",
3335 schema.SKIPPED_UNCONFIGURED,
3336 "Corpus was requested but no readable directory was configured.",
3337 attempted=False,
3338 )
3339 # Expose plan_source to the renderer so render_compact can emit the
3340 # DEGRADED RUN banner when a named-entity topic was invoked bare
3341 # (source=deterministic AND no pre-research flags). LAW 7 backstop.
3342 bundle.artifacts["plan_source"] = plan_source
3343 bundle.artifacts["corpus_in_export"] = bool(config.get("_CORPUS_IN_EXPORT"))
3344 # Hiring-signals is deliberately jobs-only with no multi-source --plan, so
3345 # the LAW 7 degraded-run and Step 0.55 pre-research banners do not apply -
3346 # they would contradict the documented jobs-scoped flow. Suppress them.
3347 bundle.artifacts["hiring_signals_mode"] = hiring_signals_mode
3348 # Record the resolved Amazon keyword whenever the lane is planned, so the
3349 # footer can name it on an empty result. A search that matched nothing
3350 # still spent a credit, and the fix is almost always the keyword -- a
3351 # suppressed line means nobody ever learns it was wrong. A lane that is
3352 # available but in no subquery never searched, so it names no keyword.
3353 if any("amazon" in subquery.sources for subquery in plan.subqueries):
3354 bundle.artifacts["amazon_query"] = (
3355 str(config.get("_amazon_query") or "").strip() or topic
3356 )
3357
3358 # Project-mode or person-mode GitHub: run once before the main subquery loop
3359 _github_custom_done = False
3360 _github_enriched_repos: set[str] = set()
3361 _github_in_plan = any("github" in sq.sources for sq in plan.subqueries)
3362 _github_pinned_allowed = (
3363 not mock
3364 and "github" in available
3365 and (
3366 _github_in_plan
3367 or (not host_plan and "drill-mode" not in plan.notes)
3368 )
3369 )
3370 _github_token = (
3371 github.resolve_token(config.get("GITHUB_TOKEN"))
3372 if _github_pinned_allowed and (github_repos or github_user)
3373 else None
3374 )
3375
3376 # Project mode takes priority over person mode
3377 if github_repos and _github_pinned_allowed:
3378 _github_custom_done = True
3379 if not _github_token:
3380 bundle.record_failure(
3381 "github",
3382 schema.SKIPPED_UNCONFIGURED,
3383 f"Project mode could not check {', '.join(github_repos)}: "
3384 "no GitHub token or gh login available",
3385 attempted=False,
3386 )
3387 else:
3388 bundle.mark_attempted("github")
3389 try:
3390 project_failures = []
3391 project_items = github.search_github_project(
3392 github_repos, from_date, to_date,
3393 depth=depth, token=_github_token, failure_out=project_failures,
3394 )
3395 if project_items:
3396 normalized = _normalize_score_dedupe(
3397 "github", project_items, from_date, to_date,
3398 freshness_mode=plan.freshness_mode,
3399 ranking_query=f"What are {', '.join(github_repos)} doing on GitHub?",
3400 first_party_handles=explicit_first_party,
3401 )
3402 primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
3403 bundle.add_items(primary_label, "github", normalized)
3404 _github_enriched_repos = {r.lower() for r in github_repos}
3405 elif not project_failures:
3406 bundle.record_failure(
3407 "github",
3408 schema.NO_RESULTS,
3409 f"Project mode found no activity for {', '.join(github_repos)} in the window",
3410 )
3411 if project_failures:
3412 failures = sorted(set(project_failures))
3413 state = min(
3414 (http.classify_failure(message=reason) for _, reason in failures),
3415 key=lambda value: health.FAILURE_SPECIFICITY.get(value, 9),
3416 )
3417 detail = " | ".join(f"{repo}: {reason}" for repo, reason in failures)
3418 bundle.record_failure("github", state, detail)
3419 except Exception as exc:
3420 bundle.errors_by_source["github"] = f"Project-mode failed: {exc}"
3421 state, attempted = _classify_source_failure(exc)
3422 bundle.record_failure("github", state, str(exc), attempted=attempted)
3423
3424 _github_person_done = False
3425 if github_user and _github_pinned_allowed and not _github_custom_done:
3426 _github_person_done = True
3427 if not _github_token:
3428 bundle.record_failure(
3429 "github",
3430 schema.SKIPPED_UNCONFIGURED,
3431 f"Person mode could not check @{github_user}: "
3432 "no GitHub token or gh login available",
3433 attempted=False,
3434 )
3435 else:
3436 bundle.mark_attempted("github")
3437 try:
3438 person_items = github.search_github_person(
3439 github_user, from_date, to_date,
3440 depth=depth, token=_github_token,
3441 )
3442 if person_items:
3443 normalized = _normalize_score_dedupe(
3444 "github", person_items, from_date, to_date,
3445 freshness_mode=plan.freshness_mode,
3446 ranking_query=f"What is @{github_user} doing on GitHub?",
3447 first_party_handles=explicit_first_party,
3448 )
3449 if person_ctx is not None:
3450 # Authored by the person's resolved account.
3451 for item in normalized:
3452 item.metadata["identity_anchor"] = True
3453 # Use the first subquery's label so RRF can look up the weight
3454 primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
3455 bundle.add_items(primary_label, "github", normalized)
3456 else:
3457 # A pinned --github-user that yields nothing must not be
3458 # silently backfilled by generic keyword search: the report
3459 # would then present unrelated repos as this person's work.
3460 bundle.record_failure(
3461 "github",
3462 schema.NO_RESULTS,
3463 f"Person mode found no activity for @{github_user} in the window",
3464 )
3465 except Exception as exc:
3466 bundle.errors_by_source["github"] = f"Person-mode failed: {exc}"
3467 state, attempted = _classify_source_failure(exc)
3468 bundle.record_failure("github", state, str(exc), attempted=attempted)
3469
3470 # Trustpilot session warm-up happens inside search_trustpilot at the
3471 # first (capped, single) fetch -- lazily, so it never delays the other
3472 # sources' streams and never fires for runs whose plan fetches no
3473 # Trustpilot. The module-level lock in lib/trustpilot.py serializes
3474 # concurrent vs-mode sub-runs so they never race Chrome harvests.
3475
3476 # Thread-safe set prevents redundant fetches after a source returns 429
3477 rate_limited_sources: set[str] = set()
3478 rate_limit_lock = threading.Lock()
3479
3480 # Local corpus retrieval is intentionally outside the network executor and
3481 # retry budget. One bounded stream participates in the same signal scoring,
3482 # fusion, reranking, and per-source result cap as remote sources.
3483 if corpus_enabled and plan.subqueries:
3484 primary = plan.subqueries[0]
3485 bundle.mark_attempted("corpus")
3486 result = corpus.search(
3487 primary.search_query if local_corpus_drill else topic,
3488 resolved_corpus_dirs,
3489 from_date=from_date,
3490 to_date=to_date,
3491 all_time=corpus_all_time,
3492 limit=settings["per_stream_limit"],
3493 cache_dir=None if config.get("_no_research_persistence") else env.CONFIG_DIR,
3494 )
3495 prepared_query = relevance.PreparedQuery(primary.ranking_query)
3496 lookback_window_days = (
3497 datetime.strptime(to_date, "%Y-%m-%d").date()
3498 - datetime.strptime(from_date, "%Y-%m-%d").date()
3499 ).days
3500 corpus_items = signals.annotate_stream(
3501 result.items,
3502 prepared_query,
3503 plan.freshness_mode,
3504 reference_date=to_date,
3505 max_days=lookback_window_days,
3506 )
3507 corpus_items = signals.prune_low_relevance(corpus_items)
3508 corpus_items = dedupe.dedupe_items(corpus_items)
3509 for item in corpus_items:
3510 item.snippet = snippet.extract_best_snippet(item, prepared_query)
3511 bundle.add_items(primary.label, "corpus", corpus_items)
3512 if result.notes:
3513 outcome = bundle.source_status["corpus"]
3514 bundle.source_status["corpus"] = schema.SourceOutcome(
3515 source="corpus",
3516 state=outcome.state,
3517 items_returned=outcome.items_returned,
3518 attempted=True,
3519 detail="; ".join(result.notes),
3520 )
3521 bundle.artifacts["corpus"] = {
3522 "files_scanned": result.files_scanned,
3523 "cache_hits": result.cache_hits,
3524 "all_time": corpus_all_time,
3525 }
3526
3527 futures = {}
3528 # Per-source fetch budget prevents redundant API calls
3529 source_fetch_count: dict[str, int] = {}
3530 stream_count = sum(
3531 1
3532 for subquery in plan.subqueries
3533 for source in subquery.sources
3534 if source in available and source != "corpus"
3535 )
3536 max_workers = _inner_max_workers(stream_count, internal_subrun=internal_subrun)
3537 # One holder, shared by every copy of the config made below: the jobs
3538 # lane's time budget for this topic (see ``_jobs_lane_budget``).
3539 # It goes into a copy, so the caller's config is left as it was.
3540 config = {**config, "_jobs_lane": {}}
3541 if not jobs_past_window and "jobs" in available and any(
3542 "jobs" in subquery.sources for subquery in plan.subqueries
3543 ):
3544 # The stories the jobs lane searches each board for, fixed before
3545 # the first jobs stream starts because that stream settles the
3546 # lane's budget.
3547 config["_jobs_story_terms"] = _jobs_story_terms(plan, topic, config)
3548 # Only an explicit, usable budget raises the wait; without one the run keeps
3549 # exactly the base behaviour (fixed 180s shared wait, no cutoff clamp). When
3550 # it is set and X will be submitted, the raise is capped by this run's
3551 # finalization cutoff: if less time remains, the worker gets exactly the
3552 # cutoff as its deadline. The cutoff is recorded in the run config so later
3553 # X work — the supplemental handle lanes and the thin-result retries'
3554 # chain calls — clamps to that same bound.
3555 # The batch takes the absolute deadline, never the relative budget, so any
3556 # time spent submitting the streams cannot extend the collector's wait.
3557 stream_wait = STREAM_FUTURE_TIMEOUT_SECONDS
3558 finalization_cutoff = None
3559 if (
3560 _configured_x_budget_seconds(config) is not None
3561 and _x_lane_scheduled(plan, available, config)
3562 ):
3563 finalization_cutoff = _finalization_deadline(config, run_started)
3564 config["_finalization_deadline"] = finalization_cutoff
3565 stream_wait = min(
3566 _x_stream_wait_seconds(config),
3567 max(0.0, finalization_cutoff - time.monotonic()),
3568 )
3569 stream_deadline = _research_deadline(config, stream_wait)
3570 if finalization_cutoff is not None:
3571 stream_deadline = min(stream_deadline, finalization_cutoff)
3572 stream_config = dict(config)
3573 stream_config["_research_deadline"] = stream_deadline
3574 batches = [(futures, stream_config, stream_deadline, False)]
3575 background_futures = {}
3576 with contextlib.ExitStack() as stack:
3577 executor = stack.enter_context(_abandoning_executor(max_workers=max_workers))
3578 for subquery in plan.subqueries:
3579 for source in subquery.sources:
3580 if source not in available:
3581 continue
3582 if source == "corpus":
3583 continue
3584 # Skip GitHub keyword search if person-mode already ran
3585 if source == "github" and (_github_person_done or _github_custom_done):
3586 continue
3587 # The person's posts run once, below, never per subquery.
3588 if source == PERSON_POSTS_SOURCE:
3589 continue
3590 if source == "jobs" and jobs_past_window:
3591 bundle.source_status["jobs"] = schema.SourceOutcome(
3592 source="jobs",
3593 state=schema.NO_RESULTS,
3594 attempted=False,
3595 detail=JOBS_PAST_WINDOW_SKIP,
3596 )
3597 continue
3598 # Enforce per-source fetch cap. A CLI override (issue #716) raises
3599 # the cap for capped sources so every X subquery in a multi-angle
3600 # --plan fetches, instead of only the first two. A host-fetched X
3601 # envelope is single-serve, so submit only the first planned X
3602 # subquery deterministically (its combined stream_limit still uses
3603 # _source_fetch_cap("x", config) below).
3604 cap = _source_fetch_cap(source, config)
3605 if source == "x" and config.get("_x_envelope") is not None:
3606 cap = 1 if cap is None else min(1, cap)
3607 if cap is not None:
3608 if cap <= 0:
3609 continue
3610 current = source_fetch_count.get(source, 0)
3611 if current >= cap:
3612 continue
3613 shared_paid_budget = config.get("_perplexity_paid_budget")
3614 if (
3615 source == "perplexity"
3616 and isinstance(shared_paid_budget, PaidSourceBudget)
3617 and not shared_paid_budget.try_consume(
3618 cap,
3619 claimant=topic,
3620 )
3621 ):
3622 bundle.artifacts.setdefault("paid_source_budget", {})[
3623 "perplexity"
3624 ] = {
3625 "state": "skipped-budget",
3626 "attempted": False,
3627 "owner": shared_paid_budget.owner,
3628 "claimant": topic,
3629 }
3630 continue
3631 source_fetch_count[source] = current + 1
3632 bundle.mark_attempted(source)
3633 active_futures, active_executor, active_config = futures, executor, stream_config
3634 if (
3635 source == "perplexity"
3636 and config.get("_deep_research")
3637 and str(config.get("PERPLEXITY_API_KEY") or "").strip()
3638 ):
3639 background_timeout = perplexity.deep_timeout_seconds(config)
3640 active_config = {
3641 **config,
3642 "_research_deadline": _research_deadline(config, background_timeout),
3643 }
3644 background_wait_config = {
3645 **active_config,
3646 "_research_deadline": _research_deadline(
3647 config, background_timeout + DEEP_RESEARCH_RECEIPT_SECONDS,
3648 ),
3649 }
3650 active_executor = stack.enter_context(_abandoning_executor(max_workers=1))
3651 active_futures = background_futures
3652 batches.append((
3653 background_futures,
3654 background_wait_config,
3655 background_wait_config["_research_deadline"],
3656 True,
3657 ))
3658 active_futures[
3659 active_executor.submit(
3660 _retrieve_stream,
3661 topic=topic,
3662 subquery=subquery,
3663 source=source,
3664 config=active_config,
3665 depth=depth,
3666 date_range=(from_date, to_date),
3667 runtime=runtime,
3668 mock=mock,
3669 rate_limited_sources=rate_limited_sources,
3670 rate_limit_lock=rate_limit_lock,
3671 web_backend=web_backend,
3672 raw_topic=topic,
3673 subreddits=subreddits,
3674 tiktok_hashtags=tiktok_hashtags,
3675 tiktok_creators=tiktok_creators,
3676 ig_creators=ig_creators,
3677 trustpilot_domain=trustpilot_domain,
3678 trustpilot_domain_is_hint=trustpilot_domain_is_hint,
3679 run_started=run_started,
3680 freshness_mode=plan.freshness_mode,
3681 )
3682 ] = (subquery, source)
3683
3684 # The person's own LinkedIn posts: one read, in the same executor and
3685 # under the same deadline as every other stream.
3686 person_posts_mode = _person_posts_mode(config)
3687 if (
3688 person_posts_mode
3689 and not mock
3690 and plan.subqueries
3691 and PERSON_POSTS_SOURCE in available
3692 ):
3693 bundle.mark_attempted(PERSON_POSTS_SOURCE)
3694 futures[
3695 executor.submit(
3696 _fetch_person_posts,
3697 mode=person_posts_mode,
3698 profile_url=person_ctx.linkedin_url,
3699 stored_posts=list((person_ctx.profile or {}).get("posts") or []),
3700 author=person_ctx.full_name,
3701 config=stream_config,
3702 from_date=from_date,
3703 to_date=to_date,
3704 )
3705 ] = (plan.subqueries[0], PERSON_POSTS_SOURCE)
3706
3707 # Collect ordinary streams and any asynchronous 5xx retries as each
3708 # future completes, before waiting on the longer background request.
3709 retry_origins: dict[Any, Exception] = {}
3710 for future, subquery, source, budget_expired in _completed_streams(
3711 batches, bundle, retry_origins=retry_origins,
3712 ):
3713 try:
3714 raw_items, artifact = future.result(timeout=0)
3715 except Exception as exc:
3716 _record_reddit_exception_notes(bundle, source, exc)
3717 # Share 429 signal immediately (even if it came from a 5xx retry)
3718 # so pending futures skip this source.
3719 if _is_rate_limit_error(exc):
3720 with rate_limit_lock:
3721 rate_limited_sources.add(source)
3722 if future in retry_origins:
3723 orig_exc = retry_origins[future]
3724 detail = f"{orig_exc} (retried once, still failed: {exc})"
3725 bundle.errors_by_source[source] = detail
3726 state, attempted = _classify_source_failure(exc)
3727 bundle.record_failure(source, state, detail, attempted=attempted)
3728 continue
3729 if _is_rate_limit_error(exc):
3730 bundle.errors_by_source[source] = str(exc)
3731 state, attempted = _classify_source_failure(exc)
3732 bundle.record_failure(source, state, str(exc), attempted=attempted)
3733 continue
3734 # Schedule one asynchronous retry for transient 5xx errors so
3735 # a slow sibling stream neither starves retries nor serializes
3736 # backoff sleeps on the collection thread. Never retry once the
3737 # budget expired, cancel fired, or remaining time cannot cover
3738 # the backoff delay.
3739 if (
3740 future not in background_futures
3741 and source != PERSON_POSTS_SOURCE
3742 and _is_transient_error(exc)
3743 ):
3744 now = time.monotonic()
3745 remaining = stream_config["_research_deadline"] - now
3746 if (
3747 budget_expired
3748 or _research_stopped(stream_config)
3749 or remaining <= _TRANSIENT_RETRY_DELAY_SECONDS
3750 ):
3751 bundle.errors_by_source[source] = str(exc)
3752 state, attempted = _classify_source_failure(exc)
3753 bundle.record_failure(source, state, str(exc), attempted=attempted)
3754 continue
3755 retry_at = now + _TRANSIENT_RETRY_DELAY_SECONDS
3756 retry_kwargs = dict(
3757 topic=topic, subquery=subquery, source=source,
3758 config=stream_config, depth=depth, date_range=(from_date, to_date),
3759 runtime=runtime, mock=mock,
3760 rate_limited_sources=rate_limited_sources,
3761 rate_limit_lock=rate_limit_lock,
3762 web_backend=web_backend,
3763 raw_topic=topic,
3764 subreddits=subreddits,
3765 tiktok_hashtags=tiktok_hashtags,
3766 tiktok_creators=tiktok_creators,
3767 ig_creators=ig_creators,
3768 trustpilot_domain=trustpilot_domain,
3769 trustpilot_domain_is_hint=trustpilot_domain_is_hint,
3770 run_started=run_started,
3771 freshness_mode=plan.freshness_mode,
3772 )
3773 if hasattr(executor, "submit_delayed"):
3774 retry_future = executor.submit_delayed(
3775 retry_at,
3776 _run_transient_retry,
3777 stream_config,
3778 _retrieve_stream,
3779 retry_kwargs,
3780 )
3781 else:
3782 retry_future = executor.submit(
3783 _delayed_retry,
3784 retry_at,
3785 stream_config,
3786 _retrieve_stream,
3787 retry_kwargs,
3788 )
3789 retry_origins[retry_future] = exc
3790 futures[retry_future] = (subquery, source)
3791 continue
3792 bundle.errors_by_source[source] = str(exc)
3793 state, attempted = _classify_source_failure(exc)
3794 bundle.record_failure(source, state, str(exc), attempted=attempted)
3795 continue
3796 try:
3797 if source == PERSON_POSTS_SOURCE and isinstance(artifact, dict):
3798 artifact = dict(artifact)
3799 person_ctx.older_posts = list(artifact.pop("_person_older_posts", None) or [])
3800 person_ctx.posts_read = bool(artifact.pop("_person_posts_read", False))
3801 if isinstance(artifact, dict) and artifact.get("_source_skipped"):
3802 # The lane chose not to run (jobs' past-window skip is the
3803 # precedent): not attempted, so it is no failure, no degraded
3804 # source and no warning.
3805 bundle.source_status[source] = schema.SourceOutcome(
3806 source=source,
3807 state=schema.NO_RESULTS,
3808 attempted=False,
3809 detail=artifact["_source_skipped"],
3810 )
3811 continue
3812 outcome_note = None
3813 if isinstance(artifact, dict) and artifact.get("_source_outcome"):
3814 artifact = dict(artifact)
3815 outcome_note = artifact.pop("_source_outcome")
3816 if (
3817 source == "youtube"
3818 and not raw_items
3819 and _retryable_youtube_outcome(outcome_note)
3820 and not artifact.get("_source_out_of_time")
3821 ):
3822 deferred_retryable_failures.setdefault(source, outcome_note)
3823 else:
3824 bundle.record_failure(
3825 source,
3826 outcome_note["state"],
3827 outcome_note["detail"],
3828 attempted=outcome_note.get("attempted", True),
3829 )
3830 # A lane that already ran out of time would only run out
3831 # again in the thin-results retry or the transcript backfill.
3832 if artifact.pop("_source_out_of_time", False):
3833 out_of_time_sources.add(source)
3834 if isinstance(artifact, dict) and artifact.get("_source_outcome_detail"):
3835 artifact = dict(artifact)
3836 detail_rate_limited = _detail_rate_limits_source(source, artifact)
3837 lane_state = artifact.pop("_source_outcome_detail_state", None)
3838 detail_note = artifact.pop("_source_outcome_detail")
3839 bundle.record_detail(
3840 source, detail_note, state=lane_state
3841 )
3842 if detail_rate_limited:
3843 # Do not re-fan-out against a host still inside its window.
3844 with rate_limit_lock:
3845 rate_limited_sources.add(source)
3846 if isinstance(artifact, dict) and artifact.get("_source_outcome_deferred"):
3847 artifact = dict(artifact)
3848 deferred_retryable_failures.setdefault(
3849 source, artifact.pop("_source_outcome_deferred")
3850 )
3851 if isinstance(artifact, dict):
3852 artifact.pop("_x_backup_not_rate_limited", None)
3853 bar_notes: list[str] = []
3854 normalized = _normalize_score_dedupe(
3855 source, raw_items, from_date, to_date,
3856 freshness_mode=plan.freshness_mode,
3857 ranking_query=subquery.ranking_query,
3858 first_party_handles=explicit_first_party,
3859 first_party_by_source=creator_first_party,
3860 # X defers its relevance floor until resolved_handles exists.
3861 # Everything else prunes here as before.
3862 defer_relevance_prune=(source == "x"),
3863 before_dedupe=_digg_bar_before_dedupe(
3864 settings, topic, subquery.label, bar_notes,
3865 judged=subquery.label not in capability_searches,
3866 ) if source == "digg" else None,
3867 )
3868 # Jobs is exempt from per_stream_limit: a careers board is a complete
3869 # snapshot of open roles, and truncating it to the default 12 drops
3870 # strategic postings (the whole point of hiring-signals coverage).
3871 # A host-fetched envelope serves every topic row to the first X
3872 # stream, so that one stream carries what the backend's X streams
3873 # together would have (per_stream_limit x the X fetch cap).
3874 if source == "digg":
3875 # The bar already ran before de-duplication; this pass only
3876 # applies the limits to what is left.
3877 normalized, _ = _apply_digg_bar(
3878 normalized, settings, topic, subquery.label,
3879 judged=subquery.label not in capability_searches,
3880 )
3881 for bar_note in bar_notes:
3882 digg_bar_dropped = True
3883 bundle.record_detail(source, bar_note)
3884 elif source != "jobs":
3885 if source == "polymarket":
3886 # The parser already ranked these markets for the subject;
3887 # a related player's award race shares no words with the
3888 # topic, so token relevance would cut it first.
3889 normalized = polymarket.by_selection(normalized)
3890 stream_limit = settings["per_stream_limit"]
3891 host_fetched_x = source == "x" and config.get("_x_envelope") is not None
3892 if host_fetched_x:
3893 stream_limit *= _source_fetch_cap("x", config) or 1
3894 normalized = _apply_reddit_stream_keepers(
3895 source, normalized, stream_limit, topic,
3896 host_fetched_x=host_fetched_x, protected_authors=explicit_first_party,
3897 )
3898 if isinstance(artifact, dict) and artifact.get("_source_outcome_if_empty"):
3899 artifact = dict(artifact)
3900 deferred_outcome = artifact.pop("_source_outcome_if_empty")
3901 if not normalized:
3902 if _retryable_youtube_outcome(deferred_outcome):
3903 deferred_retryable_failures.setdefault(source, deferred_outcome)
3904 else:
3905 bundle.record_failure(
3906 source,
3907 deferred_outcome["state"],
3908 deferred_outcome["detail"],
3909 attempted=deferred_outcome.get("attempted", True),
3910 )
3911 bundle.add_items(subquery.label, source, normalized)
3912 if _is_jobs_board(source, artifact):
3913 # The board's own counts and digest are read by name, and stay
3914 # whatever happens to the board's items below.
3915 bundle.artifacts["jobs"] = _jobs_board_artifact(artifact)
3916 bundle.jobs_board_rows = list(raw_items)
3917 artifact = {key: value for key, value in artifact.items() if key != "digest"}
3918 elif (
3919 source == "jobs" and isinstance(artifact, dict)
3920 and artifact.get("job_site_unreadable") and "jobs" not in bundle.artifacts
3921 ):
3922 # The company's job site is known and cannot be read: the
3923 # footer says so rather than printing nothing.
3924 bundle.artifacts["jobs_site_unreadable"] = str(artifact["job_site_unreadable"])
3925 if artifact.get("job_site_unreadable_reason"):
3926 bundle.artifacts["jobs_site_unreadable_reason"] = str(
3927 artifact["job_site_unreadable_reason"]
3928 )
3929 if artifact:
3930 bundle.artifacts.setdefault("grounding", []).append(artifact)
3931 except Exception as exc:
3932 bundle.errors_by_source[source] = str(exc)
3933 state, attempted = _classify_source_failure(exc)
3934 bundle.record_failure(source, state, str(exc), attempted=attempted)
3935 continue
3936
3937 # Sources of the prominent Digg stories, fetched once per run and before the
3938 # supplemental searches add their own calls. The quotes land on the
3939 # stories now; the match keys mark confirmed candidates after fusion.
3940 _check_research(config)
3941 digg_sources_spent = _DiggSourcesSpent()
3942 digg_story_by_key = _digg_story_sources(
3943 bundle, topic=topic, depth=depth, config=config, spent=digg_sources_spent,
3944 )
3945
3946 # Phase 2: supplemental entity-based searches
3947 _check_research(config)
3948 supplemental_handles: list[str] = []
3949 _run_supplemental_searches(
3950 topic=topic,
3951 bundle=bundle,
3952 plan=plan,
3953 config=config,
3954 depth=depth,
3955 date_range=(from_date, to_date),
3956 runtime=runtime,
3957 mock=mock,
3958 rate_limited_sources=rate_limited_sources,
3959 rate_limit_lock=rate_limit_lock,
3960 x_handle=x_handle,
3961 x_related=x_related,
3962 resolved_handles_out=supplemental_handles,
3963 )
3964
3965 # Phase 2b: retry thin sources with simplified query
3966 # Note: _github_skip_sources tells the retry to not re-run GitHub keyword search
3967 # when project-mode or person-mode already provided authoritative data.
3968 _github_skip_retry = {"corpus"}
3969 if _github_person_done or _github_custom_done:
3970 _github_skip_retry.add("github")
3971 if jobs_past_window:
3972 _github_skip_retry.add("jobs")
3973 if digg_bar_dropped and not bundle.items_by_source.get("digg"):
3974 # Digg returned stories and none named the topic. It has shown it
3975 # does not cover this topic, so a second search would only repeat that.
3976 _github_skip_retry.add("digg")
3977 pre_retry_counts = {
3978 source: len(bundle.items_by_source.get(source, []))
3979 for source in deferred_retryable_failures
3980 }
3981 _retry_thin_sources(
3982 topic=topic,
3983 bundle=bundle,
3984 plan=plan,
3985 config=config,
3986 depth=depth,
3987 date_range=(from_date, to_date),
3988 runtime=runtime,
3989 mock=mock,
3990 rate_limited_sources=rate_limited_sources,
3991 rate_limit_lock=rate_limit_lock,
3992 settings=settings,
3993 web_backend=web_backend,
3994 skip_sources=_github_skip_retry,
3995 subreddits=subreddits,
3996 tiktok_hashtags=tiktok_hashtags,
3997 tiktok_creators=tiktok_creators,
3998 ig_creators=ig_creators,
3999 first_party_handles=explicit_first_party,
4000 first_party_by_source=creator_first_party,
4001 run_started=run_started,
4002 out_of_time_sources=out_of_time_sources,
4003 )
4004 # Digg stories the retry found get their sources too, out of whatever
4005 # story budget and time the first pass left. Without this they carry no
4006 # quotes and cannot confirm other results.
4007 digg.merge_stories(digg_story_by_key, _digg_story_sources(
4008 bundle, topic=topic, depth=depth, config=config, spent=digg_sources_spent,
4009 ))
4010 for source, outcome in deferred_retryable_failures.items():
4011 if (
4012 source in bundle.errors_by_source
4013 or len(bundle.items_by_source.get(source, [])) > pre_retry_counts[source]
4014 ):
4015 continue
4016 bundle.record_failure(
4017 source, outcome["state"], outcome["detail"],
4018 attempted=outcome.get("attempted", True),
4019 )
4020
4021 # Reclassify partial failures as DEGRADED instead of silently dropping them.
4022 # A source that 429'd on one subquery but succeeded on another is not a hard
4023 # failure, but it is not healthy either: it likely returned fewer results
4024 # than it should have. Move it out of errors_by_source (so it isn't reported
4025 # as "failed") and into degraded_by_source (so it survives into warnings),
4026 # rather than deleting the signal outright as the engine used to.
4027 degraded_by_source: dict[str, str] = {}
4028 for source in list(bundle.errors_by_source):
4029 if bundle.items_by_source.get(source):
4030 degraded_by_source[source] = bundle.errors_by_source[source]
4031 del bundle.errors_by_source[source]
4032
4033 hiring_summary = _apply_hiring_signal_gate(
4034 bundle,
4035 explicit=hiring_signals_mode,
4036 topic=topic,
4037 )
4038 if hiring_summary:
4039 bundle.artifacts["hiring_signals"] = hiring_summary
4040
4041 _check_research(config)
4042 # Normalized set of handles this run resolved for the topic. A candidate
4043 # authored by one of these is first-party and is exempted from the
4044 # entity-miss demotion in rerank (a post never repeats its own author's
4045 # name, so the body-text grounding check would otherwise zero out the
4046 # subject's own highest-signal posts). Built before fusion so the
4047 # per-author cap can give the topic's subject a higher allowance than an
4048 # incidental third-party account.
4049 resolved_handles = explicit_first_party | {
4050 h.lstrip("@").strip().lower()
4051 for h in supplemental_handles
4052 if h and h.strip()
4053 } | {h for handles in creator_first_party.values() for h in handles}
4054 # resolved_handles feeds rerank/fusion, where the first-party marks only
4055 # resist demotion of items that already passed the inclusion floors and a
4056 # named account is treated as the subject across surfaces. The inclusion
4057 # gate (prune_low_relevance) instead gets the platform-scoped
4058 # creator_first_party map so a cross-platform name collision cannot
4059 # bypass the floors.
4060 # Real X handles from explicit flags, @mentions in topic, or Phase 2 discovery.
4061 # When no real handle is identified, skip the X floor entirely — a noisier
4062 # report beats losing the subject's evidence. Topic tokens like "peter" are
4063 # NOT real handles: they populate resolved_handles for downstream first-party
4064 # protection but should NOT trigger the floor.
4065 real_x_handles = explicit_x_handles | {
4066 h.lstrip("@").strip().lower()
4067 for h in supplemental_handles
4068 if h and h.strip()
4069 }
4070 # Deferred X relevance floor. Phase 1 skipped it so this could run with the
4071 # run's actual resolved handles rather than a guess made before anyone knew
4072 # who the subject was. Applied per subquery stream so fusion sees the same
4073 # shape it always has. Only applied when we have real X handles — topic
4074 # tokens alone cannot identify the subject.
4075 if real_x_handles:
4076 # IG/TikTok creator exemptions stay on their own platforms: a creator
4077 # handle must not exempt a same-name X account from this floor. Only
4078 # creator-ONLY handles are subtracted, where X provenance means
4079 # real_x_handles (explicit X flags, @mentions in the topic, Phase 2
4080 # discovery) - a plain topic token or --github-user match is NOT X
4081 # provenance and does not preserve the exemption.
4082 x_floor_handles = resolved_handles - _creator_only_handles(
4083 creator_first_party, real_x_handles
4084 )
4085 # Prune once on the merged X stream, then sync each per-query X stream
4086 # to the exact surviving items so an all-fail rescue on one weak
4087 # subquery cannot diverge fusion inputs from report/source_status.
4088 x_stream = bundle.items_by_source.get("x")
4089 if x_stream:
4090 pruned = signals.prune_low_relevance(
4091 x_stream,
4092 first_party_handles=x_floor_handles,
4093 first_party_by_source=creator_first_party,
4094 )
4095 _log_prune_drop("x", len(x_stream), len(pruned), scope="merged stream")
4096 bundle.items_by_source["x"] = pruned
4097 all_x_ids = {id(item) for item in x_stream}
4098 kept_x_ids = {id(item) for item in pruned}
4099 kept_x_keys = {source_item_key(item) for item in pruned}
4100 for key, stream in list(bundle.items_by_source_and_query.items()):
4101 if key[1] != "x" or not stream:
4102 continue
4103 filtered = [
4104 item for item in stream
4105 if (
4106 id(item) in kept_x_ids
4107 if id(item) in all_x_ids
4108 else source_item_key(item) in kept_x_keys
4109 )
4110 ]
4111 _log_prune_drop("x", len(stream), len(filtered), scope="per-query stream")
4112 bundle.items_by_source_and_query[key] = filtered
4113
4114 # Finalize after the deferred floor so the report's per-source view and the
4115 # source_status counts describe the same post-floor evidence set fusion sees.
4116 finalization_deadline = _finalization_deadline(config, run_started)
4117 items_by_source = _finalize_items_by_source(
4118 bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
4119 elapsed=time.monotonic() - run_started, out_of_time=out_of_time_sources,
4120 finalization_deadline=finalization_deadline,
4121 )
4122 # Fusion gates on identity too, but the footer counts and Top voices read
4123 # this per-source view, so a namesake left here still reaches the report.
4124 # Gated after enrichment so a backfilled transcript can supply the anchor.
4125 gated_items_by_source: dict[str, list[schema.SourceItem]] = {}
4126 dropped_by_identity: dict[str, int] = {}
4127 for source, items in items_by_source.items():
4128 kept = [
4129 item for item in items
4130 if entity_extract.matches_person_identity(
4131 item, plan.person_identity_anchors, x_handle,
4132 person_run=getattr(plan, "person_run", False),
4133 )
4134 ]
4135 if len(kept) < len(items):
4136 dropped_by_identity[source] = len(items) - len(kept)
4137 gated_items_by_source[source] = kept
4138 items_by_source = gated_items_by_source
4139 if person_ctx is not None:
4140 person_ctx.dropped_counts = dropped_by_identity
4141 person_ctx.in_window_posts = len(items_by_source.get(PERSON_POSTS_SOURCE, []))
4142 person_ctx.first_party_in_window = _first_party_in_window(
4143 items_by_source, x_handle=x_handle, github_person=_github_person_done,
4144 from_date=from_date, to_date=to_date,
4145 )
4146 bundle.artifacts["person_profile"] = person_ctx.to_dict()
4147 retained_poly = items_by_source.get("polymarket", [])
4148 poly_eids = fusion.polymarket_event_ids_by_url(
4149 (
4150 *retained_poly,
4151 *(
4152 item
4153 for key, stream in bundle.items_by_source_and_query.items()
4154 if key[1] == "polymarket"
4155 for item in stream
4156 ),
4157 )
4158 )
4159 retained_markets = {
4160 source_item_key(item, polymarket_eids_by_url=poly_eids)
4161 for item in retained_poly
4162 }
4163 for key, stream in bundle.items_by_source_and_query.items():
4164 if key[1] == "polymarket":
4165 bundle.items_by_source_and_query[key] = [
4166 item
4167 for item in stream
4168 if source_item_key(item, polymarket_eids_by_url=poly_eids) in retained_markets
4169 ]
4170 source_status = _finalize_source_status(bundle.source_status, items_by_source)
4171 _attach_reddit_lane_notes(bundle, source_status)
4172
4173 candidates = weighted_rrf(
4174 bundle.items_by_source_and_query,
4175 plan,
4176 pool_limit=settings["pool_limit"],
4177 range_from=from_date,
4178 range_to=to_date,
4179 first_party_handles=resolved_handles,
4180 primary_handle=x_handle,
4181 )
4182 # Only a Digg story that is certain to stay in the report may confirm
4183 # another result: one the filters above kept, and that the subject prune
4184 # after reranking cannot remove. The confirmation feeds the rerank score,
4185 # so it has to be settled here, before that prune runs.
4186 digg_prunable = {
4187 item.url
4188 for candidate in candidates
4189 if not rerank.escapes_entity_miss_prune(candidate, topic=topic)
4190 for item in candidate.source_items
4191 if item.source == "digg"
4192 }
4193 digg.tag_confirmed_candidates(
4194 candidates,
4195 digg.surviving_stories(digg_story_by_key, [
4196 item for item in items_by_source.get("digg", [])
4197 if item.url not in digg_prunable
4198 ]),
4199 )
4200 private_candidates = [
4201 candidate
4202 for candidate in candidates
4203 if schema.candidate_has_corpus(candidate)
4204 ]
4205 private_candidate_ids = {id(candidate) for candidate in private_candidates}
4206 public_candidates = [
4207 candidate for candidate in candidates if id(candidate) not in private_candidate_ids
4208 ]
4209 _check_research(config)
4210 if reasoning_provider is not None:
4211 reasoning_provider.set_request_budget(finalization_deadline, config.get("_enrich_cancel"))
4212 ranked_public = rerank.rerank_candidates(
4213 topic=topic,
4214 plan=plan,
4215 candidates=public_candidates,
4216 provider=None if mock else reasoning_provider,
4217 model=None if mock else runtime.rerank_model,
4218 shortlist_size=settings["rerank_limit"],
4219 resolved_handles=resolved_handles,
4220 primary_handle=x_handle,
4221 )
4222 # Corpus titles/snippets must never enter a hosted reasoning prompt. Score
4223 # every candidate carrying corpus evidence with the deterministic fallback,
4224 # even when the rest of the run uses a remote reranker.
4225 ranked_private = rerank.rerank_candidates(
4226 topic=topic,
4227 plan=plan,
4228 candidates=private_candidates,
4229 provider=None,
4230 model=None,
4231 shortlist_size=settings["rerank_limit"],
4232 resolved_handles=resolved_handles,
4233 primary_handle=x_handle,
4234 )
4235 reranked_public = ranked_public
4236 ranked_public = rerank.prune_fallback_entity_misses(ranked_public, topic=topic)
4237 # The footer leaves these out of its totals; an item that merely has no
4238 # candidate (author cap, pool size) is not among them and still counts.
4239 rejected_items = rerank.rejected_item_keys(reranked_public, ranked_public)
4240 if rejected_items:
4241 bundle.artifacts[rerank.REJECTED_ITEMS_ARTIFACT] = rejected_items
4242 if hiring_summary:
4243 # The diagnostic source dump retains pruned jobs; hiring aggregation
4244 # needs their rejection identities after they leave the ranked pool.
4245 hiring_summary["rejected_job_keys"] = _rejected_job_keys(
4246 public_candidates, ranked_public, bundle.artifacts.get("jobs"), topic,
4247 )
4248 # Private corpus already cleared a body-aware retrieval floor; do not apply
4249 # the public title/snippet visibility gate (filenames often omit the head
4250 # token even when the document body matched).
4251 ranked_candidates = sorted(
4252 [*ranked_public, *ranked_private],
4253 key=rerank.candidate_sort_key,
4254 )
4255 _add_ranked_roles_to_jobs_digest(bundle, ranked_candidates, hiring_summary)
4256 _check_research(config)
4257 rerank.score_fun(
4258 topic=topic,
4259 candidates=ranked_public,
4260 provider=None if mock else reasoning_provider,
4261 model=None if mock else runtime.rerank_model,
4262 )
4263 rerank.score_fun(
4264 topic=topic,
4265 candidates=ranked_private,
4266 provider=None,
4267 model=None,
4268 )
4269
4270 # Phase 3: post-rerank GitHub star enrichment. Record/replay-aware so the
4271 # eval harness stays fully offline: this path calls the GitHub API (and the
4272 # gh-credential fallback) outside the _retrieve_stream seam, so it gets its
4273 # own fixture exchange keyed by phase.
4274 if "github" in available and not mock:
4275 _check_research(config)
4276 star_request = {
4277 "source": "github",
4278 "phase": "post_rerank_star_enrichment",
4279 "topic": topic,
4280 "depth": depth,
4281 }
4282 star_matched, star_replayed = http.fixture_source_replay(star_request)
4283 if star_matched:
4284 star_map = star_replayed if isinstance(star_replayed, dict) else {}
4285 github.apply_star_map(ranked_candidates, star_map)
4286 else:
4287 collected_snapshots: dict[str, dict[str, Any]] = {}
4288 github.enrich_candidates_with_stars(
4289 ranked_candidates,
4290 token=config.get("GITHUB_TOKEN"),
4291 already_enriched=_github_enriched_repos,
4292 collect_snapshots=collected_snapshots,
4293 )
4294 http.fixture_source_record(star_request, collected_snapshots)
4295
4296 # Reorder here, not in render, so chat numbering, the saved file and
4297 # --drill N (report.clusters[N - 1]) agree on which cluster is which.
4298 clusters = diversify_clusters(
4299 cluster_candidates(ranked_candidates, plan), ranked_candidates, plan,
4300 )
4301 warnings = _warnings(items_by_source, ranked_candidates, bundle.errors_by_source, degraded_by_source)
4302 # One-sided entity coverage is a reporting warning, not a source failure:
4303 # marking the source PARTIAL would trip LAST30DAYS_STRICT_EXIT on runs that
4304 # returned good X results.
4305 warnings.extend(bundle.artifacts.get("x_partial_coverage", []))
4306 # Backend receipts that are not failures (xapi's truncated window), and
4307 # the Meta Ads footer inputs. A stream artifact only ever reaches the
4308 # report as an anonymous entry in this list, so the advertiser and the
4309 # pre-truncation counts have to be lifted to named top-level artifacts or
4310 # the footer cannot render them -- least of all on a zero-item run, which
4311 # is exactly when naming the advertiser matters most.
4312 for stream_artifact in bundle.artifacts.get("grounding", []):
4313 if isinstance(stream_artifact, dict):
4314 warnings.extend(stream_artifact.get("x_receipts", []))
4315 _lift_stream_artifacts(bundle)
4316 library_context, library_warning = _load_library_context(
4317 topic=topic,
4318 config=config,
4319 mock=mock,
4320 internal_subrun=internal_subrun,
4321 x_handle=x_handle,
4322 github_user=github_user,
4323 github_repos=github_repos,
4324 save_dir=save_dir,
4325 )
4326 if library_warning:
4327 warnings.append(library_warning)
4328 bundle.artifacts["usage"] = reasoning_provider.total_usage if reasoning_provider else None
4329
4330 return schema.Report(
4331 topic=topic,
4332 range_from=from_date,
4333 range_to=to_date,
4334 generated_at=datetime.now(timezone.utc).isoformat(),
4335 provider_runtime=runtime,
4336 query_plan=plan,
4337 clusters=clusters,
4338 ranked_candidates=ranked_candidates,
4339 items_by_source=items_by_source,
4340 errors_by_source=bundle.errors_by_source,
4341 source_status=source_status,
4342 warnings=warnings,
4343 artifacts=bundle.artifacts,
4344 library_context=library_context,
4345 )
4346
4347
4348 def _candidate_polymarket_items(candidate: schema.Candidate) -> list[schema.SourceItem]:
4349 items = [
4350 item for item in (candidate.source_items or ())
4351 if item.source == "polymarket"
4352 ]
4353 if items:
4354 return items
4355 if candidate.source == "polymarket":
4356 return [
4357 schema.SourceItem(
4358 item_id=candidate.item_id,
4359 source="polymarket",
4360 title=candidate.title,
4361 body="",
4362 url=candidate.url,
4363 snippet=candidate.snippet,
4364 metadata=dict(candidate.metadata or {}),
4365 )
4366 ]
4367 return []
4368
4369
4370 def _candidate_polymarket_event_id(candidate: schema.Candidate) -> str:
4371 for item in _candidate_polymarket_items(candidate):
4372 eid = fusion._polymarket_event_id(item)
4373 if eid:
4374 return eid
4375 if candidate.source == "polymarket":
4376 return str((candidate.metadata or {}).get("event_id") or "").strip()
4377 return ""
4378
4379
4380 def _polymarket_candidates_conflict(
4381 a: schema.Candidate,
4382 b: schema.Candidate,
4383 ) -> bool:
4384 id_a = _candidate_polymarket_event_id(a)
4385 id_b = _candidate_polymarket_event_id(b)
4386 return bool(id_a and id_b and id_a != id_b)
4387
4388
4389 def _candidate_is_duplicate(
4390 candidate: schema.Candidate,
4391 kept: list[schema.Candidate],
4392 *,
4393 conflicted_poly_urls: set[str] | None = None,
4394 ) -> bool:
4395 cand_eid = _candidate_polymarket_event_id(candidate)
4396 cand_is_poly = bool(_candidate_polymarket_items(candidate))
4397 cand_norm_url = fusion._normalize_url(candidate.url) if candidate.url else ""
4398 cand_text = " ".join((candidate.title, candidate.snippet)).strip()
4399 for existing in kept:
4400 existing_eid = _candidate_polymarket_event_id(existing)
4401 if cand_eid and existing_eid:
4402 if cand_eid == existing_eid:
4403 return True
4404 continue
4405 existing_norm_url = fusion._normalize_url(existing.url) if existing.url else ""
4406 existing_is_poly = bool(_candidate_polymarket_items(existing))
4407 if (
4408 conflicted_poly_urls
4409 and cand_norm_url
4410 and cand_norm_url in conflicted_poly_urls
4411 and cand_norm_url == existing_norm_url
4412 ):
4413 if bool(cand_eid) != bool(existing_eid):
4414 continue
4415 if cand_is_poly != existing_is_poly:
4416 continue
4417 if cand_is_poly and existing_is_poly:
4418 if not cand_eid and not existing_eid:
4419 return True
4420 continue
4421 if existing.candidate_id == candidate.candidate_id:
4422 return True
4423 if candidate.url and existing.url == candidate.url:
4424 return True
4425 if (
4426 not cand_is_poly
4427 and not existing_is_poly
4428 and cand_norm_url
4429 and existing_norm_url == cand_norm_url
4430 and candidate.source == existing.source
4431 ):
4432 return True
4433 if cand_text:
4434 existing_text = " ".join((existing.title, existing.snippet)).strip()
4435 if existing_text and dedupe.hybrid_similarity(cand_text, existing_text) >= 0.7:
4436 return True
4437 return False
4438
4439
4440 def merge_drill_report(
4441 report: schema.Report,
4442 drill_report: schema.Report,
4443 matched_clusters: list[schema.Cluster],
4444 *,
4445 target: str,
4446 ) -> schema.Report:
4447 """Merge a narrow follow-up into its cached report while preserving other clusters."""
4448 merged = copy.deepcopy(report)
4449 selected_cluster_ids = {cluster.cluster_id for cluster in matched_clusters}
4450 selected_candidate_ids = {
4451 candidate_id
4452 for cluster in matched_clusters
4453 for candidate_id in cluster.candidate_ids
4454 }
4455 original_candidates = {
4456 candidate.candidate_id: candidate for candidate in merged.ranked_candidates
4457 }
4458 unrelated_candidates = [
4459 candidate for candidate in merged.ranked_candidates
4460 if candidate.candidate_id not in selected_candidate_ids
4461 ]
4462 original_summary = ""
4463 for cluster in matched_clusters:
4464 for candidate_id in cluster.representative_ids:
4465 candidate = original_candidates.get(candidate_id)
4466 if candidate:
4467 original_summary = candidate.snippet or candidate.explanation or candidate.title
4468 if original_summary:
4469 break
4470 if original_summary:
4471 break
4472
4473 all_poly_eids = fusion.polymarket_event_ids_by_url(
4474 item
4475 for cand in (*merged.ranked_candidates, *drill_report.ranked_candidates)
4476 for item in _candidate_polymarket_items(cand)
4477 )
4478 conflicted_poly_urls = {
4479 url for url, eids in all_poly_eids.items() if len(eids) > 1
4480 }
4481 unrelated_candidate_indexes = {
4482 candidate.candidate_id: index
4483 for index, candidate in enumerate(unrelated_candidates)
4484 }
4485 unrelated_poly_event_indexes: dict[str, int] = {}
4486 unrelated_poly_idless_url_indexes: dict[str, int] = {}
4487 unrelated_source_url_indexes: dict[tuple[str, str], int] = {}
4488 for index, candidate in enumerate(unrelated_candidates):
4489 eid = _candidate_polymarket_event_id(candidate)
4490 is_poly = bool(_candidate_polymarket_items(candidate))
4491 norm = fusion._normalize_url(candidate.url) if candidate.url else ""
4492 if eid:
4493 unrelated_poly_event_indexes.setdefault(eid, index)
4494 elif is_poly:
4495 if norm:
4496 unrelated_poly_idless_url_indexes.setdefault(norm, index)
4497 elif norm:
4498 unrelated_source_url_indexes.setdefault((candidate.source, norm), index)
4499 selected_base_candidates = [
4500 copy.deepcopy(candidate)
4501 for candidate in merged.ranked_candidates
4502 if candidate.candidate_id in selected_candidate_ids
4503 ]
4504 selected_base_by_id = {
4505 candidate.candidate_id: candidate for candidate in selected_base_candidates
4506 }
4507 used_candidate_ids = {candidate.candidate_id for candidate in unrelated_candidates}
4508
4509 def _disambiguate_candidate_id(
4510 candidate: schema.Candidate,
4511 cand_eid: str,
4512 reserved_ids: set[str],
4513 ) -> None:
4514 base_id = candidate.candidate_id
4515 poly_items = _candidate_polymarket_items(candidate)
4516 if poly_items:
4517 disambiguated = fusion.polymarket_url_key(poly_items[0], all_poly_eids)
4518 if disambiguated and disambiguated not in reserved_ids:
4519 candidate.candidate_id = disambiguated
4520 return
4521 if cand_eid:
4522 with_eid = f"{base_id}\x1fevent={cand_eid}"
4523 if with_eid not in reserved_ids:
4524 candidate.candidate_id = with_eid
4525 return
4526 source_tag = (candidate.source or "item").strip() or "item"
4527 with_source = f"{base_id}\x1fsource={source_tag}"
4528 if with_source not in reserved_ids:
4529 candidate.candidate_id = with_source
4530 return
4531 suffix = 2
4532 while f"{with_source}:{suffix}" in reserved_ids:
4533 suffix += 1
4534 candidate.candidate_id = f"{with_source}:{suffix}"
4535
4536 focused_candidates: list[schema.Candidate] = []
4537 for from_drill, candidate in [
4538 *((True, copy.deepcopy(c)) for c in drill_report.ranked_candidates),
4539 *((False, c) for c in selected_base_candidates),
4540 ]:
4541 cand_eid = _candidate_polymarket_event_id(candidate)
4542 cand_is_poly = bool(_candidate_polymarket_items(candidate))
4543 cand_norm_url = fusion._normalize_url(candidate.url) if candidate.url else ""
4544 unrelated_index = unrelated_poly_event_indexes.get(cand_eid) if cand_eid else None
4545 if unrelated_index is None:
4546 by_id = unrelated_candidate_indexes.get(candidate.candidate_id)
4547 if by_id is not None:
4548 unrelated_cand = unrelated_candidates[by_id]
4549 unrelated_eid = _candidate_polymarket_event_id(unrelated_cand)
4550 unrelated_is_poly = bool(_candidate_polymarket_items(unrelated_cand))
4551 if not _polymarket_candidates_conflict(candidate, unrelated_cand) and not (
4552 cand_norm_url in conflicted_poly_urls
4553 and (
4554 bool(cand_eid) != bool(unrelated_eid)
4555 or cand_is_poly != unrelated_is_poly
4556 )
4557 ):
4558 unrelated_index = by_id
4559 if unrelated_index is None and cand_norm_url:
4560 if not cand_is_poly:
4561 unrelated_index = unrelated_source_url_indexes.get(
4562 (candidate.source, cand_norm_url)
4563 )
4564 elif not cand_eid:
4565 unrelated_index = unrelated_poly_idless_url_indexes.get(cand_norm_url)
4566 if unrelated_index is not None:
4567 existing_unrelated = unrelated_candidates[unrelated_index]
4568 candidate.candidate_id = existing_unrelated.candidate_id
4569 candidate.cluster_id = existing_unrelated.cluster_id
4570 unrelated_candidates[unrelated_index] = candidate
4571 continue
4572 if not _candidate_is_duplicate(
4573 candidate,
4574 focused_candidates,
4575 conflicted_poly_urls=conflicted_poly_urls,
4576 ):
4577 reserved_ids = (
4578 used_candidate_ids
4579 | {
4580 base_cand.candidate_id
4581 for base_cand in selected_base_candidates
4582 if not _candidate_is_duplicate(
4583 base_cand,
4584 [candidate],
4585 conflicted_poly_urls=conflicted_poly_urls,
4586 )
4587 }
4588 if from_drill
4589 else used_candidate_ids
4590 )
4591 base_collision = selected_base_by_id.get(candidate.candidate_id) if from_drill else None
4592 if base_collision is not None and (
4593 _polymarket_candidates_conflict(candidate, base_collision)
4594 or (
4595 cand_norm_url in conflicted_poly_urls
4596 and (
4597 bool(cand_eid) != bool(_candidate_polymarket_event_id(base_collision))
4598 or cand_is_poly != bool(_candidate_polymarket_items(base_collision))
4599 )
4600 )
4601 ):
4602 _disambiguate_candidate_id(candidate, cand_eid, reserved_ids)
4603 if candidate.candidate_id in used_candidate_ids:
4604 _disambiguate_candidate_id(candidate, cand_eid, reserved_ids)
4605 used_candidate_ids.add(candidate.candidate_id)
4606 focused_candidates.append(candidate)
4607
4608 primary_cluster = matched_clusters[0]
4609 for candidate in focused_candidates:
4610 candidate.cluster_id = primary_cluster.cluster_id
4611 focused_ids = [candidate.candidate_id for candidate in focused_candidates]
4612 focused_sources = sorted({
4613 source
4614 for candidate in focused_candidates
4615 for source in schema.candidate_sources(candidate)
4616 })
4617 replacement_cluster = schema.Cluster(
4618 cluster_id=primary_cluster.cluster_id,
4619 title=primary_cluster.title,
4620 candidate_ids=focused_ids,
4621 representative_ids=focused_ids[:3],
4622 sources=focused_sources,
4623 score=max((candidate.final_score for candidate in focused_candidates), default=0.0),
4624 uncertainty="single-source" if len(focused_sources) == 1 else None,
4625 )
4626
4627 first_selected_index = min(
4628 index
4629 for index, cluster in enumerate(merged.clusters)
4630 if cluster.cluster_id in selected_cluster_ids
4631 )
4632 remaining_clusters = [
4633 cluster for cluster in merged.clusters
4634 if cluster.cluster_id not in selected_cluster_ids
4635 ]
4636 remaining_clusters.insert(first_selected_index, replacement_cluster)
4637 merged.clusters = remaining_clusters
4638
4639 merged.ranked_candidates = focused_candidates + unrelated_candidates
4640
4641 all_sources = set(merged.items_by_source) | set(drill_report.items_by_source)
4642 new_item_count = 0
4643 merged_items: dict[str, list[schema.SourceItem]] = {}
4644 for source in sorted(all_sources):
4645 old_items = merged.items_by_source.get(source, [])
4646 new_items = drill_report.items_by_source.get(source, [])
4647 # Collapse exact URL matches first, preferring the drill's copy (it
4648 # carries fresh transcripts/comments); fuzzy dedupe alone keeps both
4649 # when enrichment changed the text substantially. For Polymarket,
4650 # delegate to dedupe_items so distinct event_ids sharing a reused slug
4651 # stay separate while same-event matched bundles merge coherently.
4652 if source == "polymarket":
4653 combined = dedupe.dedupe_items([*copy.deepcopy(new_items), *old_items])
4654 else:
4655 new_urls = {item.url for item in new_items if item.url}
4656 kept_old = [item for item in old_items if not (item.url and item.url in new_urls)]
4657 combined = dedupe.dedupe_items([*copy.deepcopy(new_items), *kept_old])
4658 old_unique = dedupe.dedupe_items(old_items)
4659 new_item_count += max(0, len(combined) - len(old_unique))
4660 merged_items[source] = combined
4661 merged.items_by_source = merged_items
4662
4663 merged.generated_at = drill_report.generated_at
4664 merged.query_plan = drill_report.query_plan
4665 # The drill's retrieval window is the report's window now (a --days/--as-of
4666 # override on the drill must not be mislabeled with the cached range).
4667 merged.range_from = drill_report.range_from
4668 merged.range_to = drill_report.range_to
4669 attempted_sources = {
4670 source
4671 for source, outcome in drill_report.source_status.items()
4672 if outcome.attempted or outcome.state == schema.SKIPPED_UNCONFIGURED
4673 }
4674 for source in attempted_sources:
4675 if source in drill_report.errors_by_source:
4676 merged.errors_by_source[source] = drill_report.errors_by_source[source]
4677 else:
4678 merged.errors_by_source.pop(source, None)
4679 merged.source_status[source] = drill_report.source_status[source]
4680 merged.source_status = _finalize_source_status(
4681 merged.source_status,
4682 merged.items_by_source,
4683 )
4684 degraded_by_source = {
4685 source: outcome.detail or "partial results"
4686 for source, outcome in merged.source_status.items()
4687 if outcome.state == schema.PARTIAL
4688 }
4689 merged.warnings = _warnings(
4690 merged.items_by_source,
4691 merged.ranked_candidates,
4692 merged.errors_by_source,
4693 degraded_by_source,
4694 )
4695 merged.artifacts.update(copy.deepcopy(drill_report.artifacts))
4696 history = list(merged.artifacts.get("drill_history") or [])
4697 history.append({
4698 "target": target,
4699 "clusters": [cluster.title for cluster in matched_clusters],
4700 "new_items": new_item_count,
4701 "generated_at": drill_report.generated_at,
4702 })
4703 merged.artifacts["drill_history"] = history
4704 merged.artifacts["drill_context"] = {
4705 "target": target,
4706 "cluster_titles": [cluster.title for cluster in matched_clusters],
4707 "original_summary": original_summary,
4708 "new_items": new_item_count,
4709 "sources": focused_sources,
4710 }
4711 merged.drill_of = primary_cluster.title
4712 return merged
4713
4714
4715 def _batch_subject_handles(raw_items: list[dict], *, top_n: int = 2) -> set[str]:
4716 """Most-mentioned handles in a batch of X items, as first-party candidates.
4717
4718 Mirrors entity_extract's ranking but runs before pruning rather than after,
4719 and keys on *mentions only* rather than mentions plus authors. That
4720 distinction is the safety property: a prolific commentator inflates the
4721 author count, but being mentioned by other accounts is what identifies the
4722 subject of a topic. Capped at the top few so a busy thread cannot exempt
4723 the whole batch.
4724 """
4725 counts: Counter = Counter()
4726 for item in raw_items or []:
4727 text = str((item or {}).get("text") or "")
4728 for mention in re.findall(r"@([A-Za-z0-9_]{1,15})", text):
4729 counts[mention.lower()] += 1
4730 if not counts:
4731 return set()
4732 return {handle for handle, _ in counts.most_common(top_n)}
4733
4734
4735 # Reddit engagement keepers: per stream, the top-N threads by upvotes plus
4736 # comments that clear the relevance floor and name the primary entity survive
4737 # per_stream_limit truncation even when their local rank score is low. The
4738 # stream order is 65% title relevance, so the month's most-discussed on-topic
4739 # thread (16K upvotes, 0.19 relevance) was otherwise cut behind one-upvote
4740 # posts with better title overlap.
4741 REDDIT_STREAM_KEEPERS = 3
4742
4743
4744 def _x_raw_engagement(item: schema.SourceItem) -> float:
4745 """Likes, reposts, replies, and quotes as a plain number."""
4746 eng = item.engagement or {}
4747 return float(sum(
4748 value for key in ("likes", "reposts", "replies", "quotes")
4749 if isinstance(value := eng.get(key), (int, float)) and not isinstance(value, bool)
4750 ))
4751
4752
4753 def _x_post_qualifies(item: schema.SourceItem, entity: str, floor: float) -> bool:
4754 """On-topic enough for an engagement slot: clears the floor and names the entity."""
4755 if (item.local_relevance or 0.0) < floor or _x_raw_engagement(item) <= 0:
4756 return False
4757 if not entity:
4758 return True
4759 return rerank._entity_grounded(f"{item.title or ''} {item.body or ''}", entity)
4760
4761
4762 def _apply_reddit_stream_keepers(
4763 source: str,
4764 items: list[schema.SourceItem],
4765 limit: int,
4766 topic: str,
4767 *,
4768 host_fetched_x: bool = False,
4769 protected_authors: Iterable[str] = (),
4770 ) -> list[schema.SourceItem]:
4771 """Truncate a stream to *limit*, holding slots for engagement keepers.
4772
4773 Reddit holds a few slots for its most-engaged on-topic threads. A
4774 host-fetched X stream holds half its slots for its most-engaged on-topic
4775 posts, because its popular pass reaches back across the whole window and
4776 those posts would otherwise lose to fresher low-engagement ones. Posts by
4777 ``protected_authors`` (the run's explicitly named handles) are never
4778 displaced, because the first-party relevance exemption runs after this cut.
4779 """
4780 kept = list(items[:limit])
4781 if len(items) <= limit:
4782 return kept
4783 entity = rerank._primary_entity(topic or "") if topic else ""
4784 floor = fusion.relevance_floor_for_entity(entity)
4785 if source == "reddit":
4786 keepers = [
4787 item
4788 for item in sorted(items, key=fusion.raw_engagement, reverse=True)
4789 if fusion.reddit_thread_qualifies(item, entity, floor)
4790 ][:REDDIT_STREAM_KEEPERS]
4791 elif source == "x" and host_fetched_x:
4792 keepers = [
4793 item
4794 for item in sorted(items, key=_x_raw_engagement, reverse=True)
4795 if _x_post_qualifies(item, entity, floor)
4796 ][: max(1, limit // 2)]
4797 else:
4798 return kept
4799 keeper_ids = {id(item) for item in keepers}
4800 protected = {author.lstrip("@").lower() for author in protected_authors if author}
4801 for keeper in keepers:
4802 if any(item is keeper for item in kept):
4803 continue
4804 # Displace the lowest-ranked non-keeper so the slice stays at limit;
4805 # when the slice is already all keepers or protected posts there is
4806 # nothing to trade.
4807 displaced = False
4808 for index in range(len(kept) - 1, -1, -1):
4809 if id(kept[index]) in keeper_ids:
4810 continue
4811 if (kept[index].author or "").lstrip("@").lower() in protected:
4812 continue
4813 del kept[index]
4814 displaced = True
4815 break
4816 if displaced or len(kept) < limit:
4817 kept.append(keeper)
4818 return kept[:limit]
4819
4820
4821 def _apply_digg_bar(
4822 items: list[schema.SourceItem],
4823 settings: Mapping[str, Any],
4824 topic: str,
4825 label: str,
4826 *,
4827 judged: bool = True,
4828 capped: bool = True,
4829 ) -> tuple[list[schema.SourceItem], str | None]:
4830 """Cut one Digg search to the stories the Digg bar keeps, in its order.
4831
4832 Prominent stories lead by Digg Score, ordinary ones follow in the order
4833 they ranked, and the stories that do not name the topic are removed. The
4834 second value is a note saying how many were removed, or None.
4835
4836 ``judged=False`` is for a search that is deliberately not about the run
4837 topic: its stories keep their order and none is removed. Clusters from
4838 digg-pp-cli 2026.10.x are never judged and keep the shared limit.
4839
4840 ``capped=False`` applies the bar without the limits. It is the pass made
4841 before near-duplicates are removed, so that a prominent story is the
4842 copy kept and a story the bar drops cannot displace one it keeps.
4843 """
4844 result = digg.apply_bar(topic if judged else "", items)
4845 stories = result.prominent + result.ordinary
4846 if capped:
4847 stories = stories[: settings["digg_stream_limit"]]
4848 note = None
4849 if result.dropped:
4850 note = (
4851 f"{len(result.dropped)} of {len(items) - len(result.legacy)} stories dropped "
4852 f"for not naming the topic ({label} search)"
4853 )
4854 digg._log(note)
4855 legacy = result.legacy[: settings["per_stream_limit"]] if capped else result.legacy
4856 return stories + legacy, note
4857
4858
4859 def _digg_bar_before_dedupe(
4860 settings: Mapping[str, Any], topic: str, label: str, notes: list[str], *, judged: bool = True,
4861 ) -> Callable[[list[schema.SourceItem]], list[schema.SourceItem]]:
4862 """The Digg bar as the ``before_dedupe`` step of ``_normalize_score_dedupe``.
4863
4864 Any note about dropped stories is appended to ``notes``.
4865 """
4866 def apply(items: list[schema.SourceItem]) -> list[schema.SourceItem]:
4867 kept, note = _apply_digg_bar(items, settings, topic, label, judged=judged, capped=False)
4868 if note:
4869 notes.append(note)
4870 return kept
4871
4872 return apply
4873
4874
4875 def _creator_first_party_by_source(
4876 tiktok_creators: Iterable[str] | None,
4877 ig_creators: Iterable[str] | None,
4878 ) -> dict[str, set[str]]:
4879 """Platform-scoped creator handles for the relevance prune.
4880
4881 --ig-creators names Instagram accounts and --creators names TikTok
4882 accounts; each exemption applies only on its own platform. Merging both
4883 into one global handle set would let an unrelated same-name account on
4884 another platform bypass the relevance and engagement floors.
4885 """
4886
4887 def _norm(handles: Iterable[str] | None) -> set[str]:
4888 return {
4889 h.lstrip("@").strip().lower()
4890 for h in (handles or [])
4891 if h and h.strip()
4892 }
4893
4894 return {"instagram": _norm(ig_creators), "tiktok": _norm(tiktok_creators)}
4895
4896
4897 def _creator_only_handles(
4898 creator_first_party: Mapping[str, set[str]],
4899 *x_provenance_sets: Iterable[str],
4900 ) -> set[str]:
4901 """Creator handles that carry no X provenance.
4902
4903 A handle named ONLY via --ig-creators / --creators must not exempt a
4904 same-name X account from the deferred X floor. But the same person is
4905 often named on both surfaces (--x-handle foo --ig-creators foo): the
4906 normalized sets collapse that to one string, so subtracting the whole
4907 creator set would strip the explicitly requested X exemption too. The
4908 subtraction therefore covers only handles absent from every
4909 X-provenance set (explicit flags, topic mentions, Phase 2 discovery).
4910 """
4911 creator_flat = {h for handles in creator_first_party.values() for h in handles}
4912 x_provenance = {h for handles in x_provenance_sets for h in handles}
4913 return creator_flat - x_provenance
4914
4915
4916 def _log_prune_drop(
4917 source: str, before: int, after: int, scope: str | None = None
4918 ) -> None:
4919 """Log when the relevance prune removes items from a stream.
4920
4921 The prune is silent by design inside ``signals`` (a pure function), but a
4922 silent drop is invisible to the user: issue #1101 fetched 36 creator reels
4923 and reported zero with no line explaining why. Log the count and the reason
4924 class here, next to the other per-stream retrieval logs. The all-weak
4925 ``filtered or items`` rescue keeps the originals, so before == after and
4926 nothing is logged - a rescue is not a drop.
4927 """
4928 dropped = before - after
4929 if dropped <= 0:
4930 return
4931 scope_note = f" ({scope})" if scope else ""
4932 log.source_log(
4933 render.SOURCE_LABELS.get(source, source.capitalize()),
4934 f"relevance prune dropped {dropped} of {before} items below the "
4935 f"relevance/engagement floor{scope_note}",
4936 tty_only=False,
4937 )
4938
4939
4940 def _normalize_score_dedupe(
4941 source: str,
4942 raw_items: list[dict],
4943 from_date: str,
4944 to_date: str,
4945 freshness_mode: str,
4946 ranking_query: str,
4947 first_party_handles: Iterable[str] | None = None,
4948 first_party_by_source: Mapping[str, Iterable[str]] | None = None,
4949 defer_relevance_prune: bool = False,
4950 before_dedupe: Callable[[list[schema.SourceItem]], list[schema.SourceItem]] | None = None,
4951 ) -> list[schema.SourceItem]:
4952 """Normalize, annotate, prune, dedupe, and extract snippets for a batch of raw items.
4953
4954 ``before_dedupe`` filters and reorders the batch just before
4955 near-duplicates are removed. De-duplication keeps the earlier of two
4956 similar items, so a source that drops items by its own rule has to do it
4957 first: otherwise an item it would drop can displace a similar one it
4958 would keep.
4959
4960 ``defer_relevance_prune`` skips the relevance floor here so the caller can
4961 apply it once the run has resolved who the topic's subject is. Pruning X
4962 before handle resolution is the ordering bug behind the whole first-party
4963 evidence loss: the floor cannot exempt an author nobody has identified yet,
4964 and no amount of guessing at prune time substitutes for knowing.
4965
4966 ``first_party_handles`` names accounts this run is explicitly searching, so
4967 their own posts survive the relevance floor (see signals.prune_low_relevance).
4968 """
4969 normalized = normalize.normalize_source_items(
4970 source, raw_items, from_date, to_date,
4971 freshness_mode=freshness_mode,
4972 )
4973 prepared_query = relevance.PreparedQuery(ranking_query)
4974 lookback_window_days = (
4975 datetime.strptime(to_date, "%Y-%m-%d").date()
4976 - datetime.strptime(from_date, "%Y-%m-%d").date()
4977 ).days
4978 normalized = signals.annotate_stream(
4979 normalized,
4980 prepared_query,
4981 freshness_mode,
4982 reference_date=to_date,
4983 max_days=lookback_window_days,
4984 )
4985 if source != "jobs" and not defer_relevance_prune:
4986 floor_handles = set(first_party_handles or ())
4987 if source == "x":
4988 # Union, never a fallback. The caller's set is derived partly from
4989 # topic tokens, so it is non-empty for essentially every real topic
4990 # -- gating this on "no handles supplied" would make it dead code
4991 # and leave the name-only case exactly as broken as before.
4992 #
4993 # Reuses the engine's own resolution signal on the batch already in
4994 # hand: posts *about* a subject mention their handle, so the
4995 # most-mentioned account in a topic's own results is the subject.
4996 # Costs nothing extra -- no search, no network -- and closes the
4997 # case where the handle never appears in the topic at all
4998 # ("Peter Steinberger" -> @steipete).
4999 floor_handles |= _batch_subject_handles(raw_items)
5000 # A Digg story with a UUID is judged by the Digg bar at the stream
5001 # cut, not by this floor: the floor scores against the planner's
5002 # ranking query, whose filler words push a story that names the topic
5003 # in its title under it. Clusters from digg-pp-cli 2026.10.x have no
5004 # UUID and stay under the floor.
5005 bar_judged = [
5006 item for item in normalized
5007 if source == "digg" and item.metadata.get(digg.STORY_ID_KEY)
5008 ]
5009 if bar_judged:
5010 exempt = {id(item) for item in bar_judged}
5011 floor_judged = [item for item in normalized if id(item) not in exempt]
5012 kept = exempt | {
5013 id(item)
5014 for item in signals.prune_low_relevance(
5015 floor_judged,
5016 first_party_handles=floor_handles,
5017 first_party_by_source=first_party_by_source,
5018 )
5019 }
5020 pre_prune_count = len(normalized)
5021 normalized = [item for item in normalized if id(item) in kept]
5022 else:
5023 pre_prune_count = len(normalized)
5024 normalized = signals.prune_low_relevance(
5025 normalized,
5026 first_party_handles=floor_handles,
5027 first_party_by_source=first_party_by_source,
5028 )
5029 _log_prune_drop(source, pre_prune_count, len(normalized))
5030 if before_dedupe is not None:
5031 normalized = before_dedupe(normalized)
5032 normalized = dedupe.dedupe_items(normalized)
5033 for item in normalized:
5034 item.snippet = snippet.extract_best_snippet(item, prepared_query)
5035 return normalized
5036
5037
5038 def _finalize_items_by_source(
5039 items_by_source_raw: dict[str, list[schema.SourceItem]],
5040 topic: str = "",
5041 config: dict | None = None,
5042 depth: str = "default",
5043 mock: bool = False,
5044 elapsed: float = 0.0,
5045 out_of_time: set[str] | None = None,
5046 finalization_deadline: float | None = None,
5047 ) -> dict[str, list[schema.SourceItem]]:
5048 config = config or {}
5049 run_started = time.monotonic() - elapsed
5050 if finalization_deadline is None:
5051 finalization_deadline = _finalization_deadline(config, run_started)
5052 cancel = config.get("_enrich_cancel")
5053 finalized = {}
5054 for source, items in items_by_source_raw.items():
5055 _check_research(config)
5056 items = sorted(items, key=lambda item: item.local_rank_score or 0.0, reverse=True)
5057 if source == "polymarket":
5058 items = polymarket.by_selection(items)
5059 if source == "digg":
5060 # De-duplication keeps the earlier of two similar stories. Two
5061 # searches can return the same event as a prominent story and as
5062 # a smaller one, so prominent stories go first here and the copy
5063 # kept is the one that carries the fetched quotes and can
5064 # confirm other results.
5065 prominent = digg.apply_bar(topic, items).prominent
5066 leading = {id(item) for item in prominent}
5067 items = prominent + [item for item in items if id(item) not in leading]
5068 # Same thread from two subquery streams: fold the enriched copy into
5069 # the first before the text-similarity dedupe, which would otherwise
5070 # keep whichever copy ranked higher and drop its comments.
5071 items = collapse_duplicate_urls(items)
5072 items = dedupe.dedupe_items(items)
5073 if source == "digg":
5074 items = sorted(items, key=lambda item: item.local_rank_score or 0.0, reverse=True)
5075 enrichment_request = {
5076 "source": source,
5077 "phase": "post_ranking_enrichment",
5078 "topic": topic,
5079 "depth": depth,
5080 }
5081 _key_youtube_fixture_by_entity_count(enrichment_request, source, config)
5082 if source == "youtube" and items and not mock and source not in (out_of_time or ()):
5083 # Same budget-at-the-survivors principle as the digg branch
5084 # below: retrieval-time transcripts go to each search's
5085 # top-by-views candidates, while final selection ranks by
5086 # relevance. Backfill survivors that arrived without one so the
5087 # transcript budget lands on videos the brief actually shows
5088 # (#542).
5089 matched, replayed = http.fixture_source_replay(enrichment_request)
5090 if matched:
5091 items = _merge_replayed_enrichment(items, replayed)
5092 elif time.monotonic() < finalization_deadline:
5093 sc_token = (
5094 config.get("SCRAPECREATORS_API_KEY")
5095 if config and env.is_youtube_sc_available(config) else None
5096 )
5097 with youtube_yt.ssh_host_scope(config.get("LAST30DAYS_YOUTUBE_SSH_HOST")), \
5098 youtube_yt.sc_spend_until(
5099 lambda: _research_stopped(config),
5100 cancel=cancel,
5101 deadline=finalization_deadline,
5102 return_deadline=finalization_deadline,
5103 ):
5104 youtube_yt.backfill_transcripts(
5105 items, topic=topic, depth=depth, token=sc_token,
5106 entity_count=_comparison_entity_count(config),
5107 )
5108 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5109 else:
5110 http.fixture_source_record(enrichment_request, [])
5111 # Post-merge topic bar for Polymarket: the entity matcher, with the
5112 # run's hints, over each item's matched market and event title. It
5113 # stands in for the generic relevance floor, which exempts matched
5114 # markets (signals.prune_low_relevance), and drops off-topic markets
5115 # (e.g., WTI crude oil, Elon tweet counts) before footer emission.
5116 if source == "polymarket" and topic:
5117 items = polymarket.filter_items_against_topic(
5118 topic, items, (config or {}).get("_polymarket_hints"),
5119 )
5120 # --polymarket-keywords (via config): additional keyword filter
5121 # for ambiguous single-token topics (e.g., "Warriors" → nba,gsw).
5122 keywords = config.get("_polymarket_keywords") if isinstance(config, dict) else None
5123 if keywords:
5124 items = polymarket.filter_items_against_keywords(items, keywords)
5125 if (
5126 source == "digg"
5127 and not mock
5128 and any(not item.metadata.get(digg.STORY_ID_KEY) for item in items)
5129 ):
5130 # Clusters from digg-pp-cli 2026.10.x only; all-topic stories got
5131 # their quotes from _digg_story_sources. Pull top-ranked X posts
5132 # only for the survivors that will appear in the brief. Spending
5133 # the enrichment budget here (rather than at retrieval time)
5134 # keeps the inline 'via Digg' quotes paired with the clusters
5135 # dedupe actually kept.
5136 matched, replayed = http.fixture_source_replay(enrichment_request)
5137 if matched:
5138 items = _merge_replayed_enrichment(items, replayed)
5139 elif time.monotonic() < finalization_deadline:
5140 digg.enrich_source_items(
5141 items, top_k=3, deadline=finalization_deadline, cancel=cancel,
5142 )
5143 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5144 else:
5145 http.fixture_source_record(enrichment_request, [])
5146 if source == "reddit" and items and not mock:
5147 # The lane enriched its own top picks before this ranking; give
5148 # the threads that survived their top comments too.
5149 matched, replayed = http.fixture_source_replay(enrichment_request)
5150 if matched:
5151 items = _merge_replayed_enrichment(items, replayed)
5152 elif time.monotonic() < finalization_deadline:
5153 reddit_keyless.enrich_source_items(
5154 items, depth=depth, deadline=finalization_deadline,
5155 )
5156 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5157 else:
5158 http.fixture_source_record(enrichment_request, [])
5159 if source == "devto" and items and not mock:
5160 matched, replayed = http.fixture_source_replay(enrichment_request)
5161 if matched:
5162 items = _merge_replayed_enrichment(items, replayed)
5163 elif time.monotonic() < finalization_deadline:
5164 devto.enrich_source_items(items, deadline=finalization_deadline)
5165 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5166 else:
5167 http.fixture_source_record(enrichment_request, [])
5168 if source == "v2ex" and items and not mock:
5169 matched, replayed = http.fixture_source_replay(enrichment_request)
5170 if matched:
5171 items = _merge_replayed_enrichment(items, replayed)
5172 elif time.monotonic() < finalization_deadline:
5173 v2ex.enrich_source_items(items, deadline=finalization_deadline)
5174 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5175 else:
5176 http.fixture_source_record(enrichment_request, [])
5177 if source == "juejin" and items and not mock:
5178 matched, replayed = http.fixture_source_replay(enrichment_request)
5179 if matched:
5180 items = _merge_replayed_enrichment(items, replayed)
5181 elif time.monotonic() < finalization_deadline:
5182 juejin.enrich_source_items(items, deadline=finalization_deadline)
5183 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5184 else:
5185 http.fixture_source_record(enrichment_request, [])
5186 if source == "amazon" and items and not mock:
5187 # Attach-if-missing: review enrichment now runs at search time in
5188 # _retrieve_stream_impl, so items arriving here should already have
5189 # top_comments. enrich_source_items no-ops when top_comments is set.
5190 # This path handles fixture replay and any edge cases where retrieve
5191 # didn't enrich (e.g., run_started was not passed).
5192 matched, replayed = http.fixture_source_replay(enrichment_request)
5193 if matched:
5194 items = _merge_replayed_enrichment(items, replayed)
5195 elif time.monotonic() < finalization_deadline:
5196 amazon.enrich_source_items(
5197 items,
5198 depth=depth,
5199 config=config,
5200 keyword=str((config or {}).get("_amazon_query") or "").strip() or topic,
5201 elapsed=max(0.0, time.monotonic() - run_started),
5202 deadline=finalization_deadline,
5203 )
5204 http.fixture_source_record(enrichment_request, schema.to_dict(items))
5205 else:
5206 http.fixture_source_record(enrichment_request, [])
5207 finalized[source] = items
5208 return finalized
5209
5210
5211 @dataclass
5212 class _DiggSourcesSpent:
5213 """What a run's story-source passes have used of their shared allowance.
5214
5215 ``story_ids`` are the stories offered to the fetch, not every story seen.
5216 """
5217
5218 story_ids: set[str] = field(default_factory=set)
5219 seconds: float = 0.0
5220
5221
5222 def _digg_story_sources(
5223 bundle: schema.RetrievalBundle,
5224 *,
5225 topic: str,
5226 depth: str,
5227 config: dict[str, Any],
5228 spent: _DiggSourcesSpent | None = None,
5229 ) -> dict[str, list[dict[str, Any]]]:
5230 """Fetch the prominent Digg stories' sources and attach their quotes.
5231
5232 Returns the map from source match key to story that
5233 ``digg.tag_confirmed_candidates`` reads after fusion. Only the stories
5234 the Digg bar finds prominent for ``topic`` are offered to the fetch, so
5235 no other story has its sources read or confirms another result. The
5236 fetch is bounded by the run's deadline and cancel signal, and a
5237 comparison's runs share one story budget between them. Empty at quick
5238 depth, when the run holds no prominent Digg story, and when every fetch
5239 fails. Recorded and replayed as its own fixture exchange so the eval
5240 harness stays offline.
5241
5242 ``spent`` holds the ids of the stories earlier calls in this run offered
5243 to the fetch and the seconds they used, and is updated in place. A call
5244 after the first offers only prominent stories that arrived since, and
5245 gets only the story budget and the time those earlier calls left, so the
5246 run's total stays within one budget and one
5247 ``digg.SOURCES_TOTAL_SECONDS``.
5248 """
5249 spent = spent if spent is not None else _DiggSourcesSpent()
5250 seen = spent.story_ids
5251 later_pass = bool(seen)
5252 entity_count = _comparison_entity_count(config)
5253 budget = digg.story_budget(depth, entity_count) - min(
5254 len(seen), digg.story_budget(depth, entity_count),
5255 )
5256 seconds_left = digg.SOURCES_TOTAL_SECONDS - spent.seconds
5257 # Asked again here because the bar writes nothing on the items.
5258 stories = [
5259 item for item in digg.apply_bar(topic, bundle.items_by_source.get("digg", [])).prominent
5260 if str(item.metadata[digg.STORY_ID_KEY]) not in seen
5261 ]
5262 seen.update(str(item.metadata[digg.STORY_ID_KEY]) for item in stories)
5263 if not stories or budget <= 0 or seconds_left <= 0:
5264 return {}
5265 request = {"source": "digg", "phase": "story_sources", "topic": topic, "depth": depth}
5266 if later_pass:
5267 # Its own exchange, so it never replays the first pass's recording.
5268 request["pass"] = "retry"
5269 if entity_count > 1:
5270 # A comparison run fetches fewer stories, so it never replays a
5271 # single-topic recording; those keep their original keys.
5272 request["comparison_entity_count"] = entity_count
5273 matched, replayed = http.fixture_source_replay(request)
5274 if matched:
5275 fetched = replayed if isinstance(replayed, dict) else {}
5276 else:
5277 started = time.monotonic()
5278 fetched = digg.fetch_story_sources(
5279 stories, depth, stopped=lambda: _research_stopped(config),
5280 # The time this run's passes have left, or the run's own
5281 # deadline when that comes first.
5282 deadline=_research_deadline(config, seconds_left),
5283 cancel=config.get("_enrich_cancel"),
5284 entity_count=entity_count,
5285 budget=budget,
5286 )
5287 spent.seconds += time.monotonic() - started
5288 http.fixture_source_record(request, fetched)
5289 return digg.apply_story_sources(stories, fetched)
5290
5291
5292 def _merge_replayed_enrichment(
5293 items: list[schema.SourceItem],
5294 replayed: list[dict],
5295 ) -> list[schema.SourceItem]:
5296 """Apply recorded post-ranking enrichment onto freshly computed items.
5297
5298 Enrichment (transcripts, Digg posts) only mutates ``metadata``. Merging by
5299 item_id instead of replacing the list keeps normalization, scoring, and
5300 dedupe regressions visible to the eval - fixture state must not overwrite
5301 what the current pipeline computed.
5302 """
5303 replayed_by_id = {
5304 entry.get("item_id"): entry for entry in replayed if isinstance(entry, dict)
5305 }
5306 for item in items:
5307 record = replayed_by_id.get(item.item_id)
5308 if record and record.get("metadata"):
5309 item.metadata.update(record["metadata"])
5310 return items
5311
5312
5313 def _jobs_lane_budget(config: dict[str, Any]) -> jobs.LaneBudget:
5314 """The one time budget the jobs lane has for this topic's run.
5315
5316 ``run`` puts a holder in the config before it copies it for its passes,
5317 so the first pass, a retry after a server error and the thin-results
5318 retry all draw on the same budget. A comparison gives each entity an
5319 equal share.
5320 """
5321 holder = config.get("_jobs_lane")
5322 if isinstance(holder, dict):
5323 with _JOBS_LANE_LOCK:
5324 budget = holder.get("budget")
5325 if budget is None:
5326 budget = jobs.LaneBudget(
5327 jobs.JOBS_BUDGET_SECONDS / max(1, _comparison_entity_count(config)),
5328 )
5329 holder["budget"] = budget
5330 return budget
5331 return jobs.LaneBudget(
5332 jobs.JOBS_BUDGET_SECONDS / max(1, _comparison_entity_count(config)),
5333 )
5334
5335
5336 def _jobs_story_terms(
5337 plan: schema.QueryPlan, topic: str, config: dict[str, Any],
5338 ) -> list[str]:
5339 """The run's story terms: the host plan's, else drawn from its subqueries.
5340
5341 Drawn terms leave out the topic (the company, or the person it names),
5342 the company the topic resolved to and those the host named, and every
5343 entity of a comparison.
5344 """
5345 if plan.jobs_queries:
5346 terms, origin = list(plan.jobs_queries), "host plan"
5347 else:
5348 company = config.get("_company") or {}
5349 excluded = [
5350 topic,
5351 str(company.get("company") or ""),
5352 *_host_companies(company),
5353 *(config.get("_comparison_entities") or []),
5354 *planner._comparison_entities(topic),
5355 ]
5356 terms = jobs_story.derive_terms(
5357 (subquery.search_query for subquery in plan.subqueries), excluded,
5358 )
5359 origin = "drawn from the plan's subqueries"
5360 log.source_log(
5361 "Jobs",
5362 f"story terms ({origin}): {', '.join(terms) or 'none'}",
5363 tty_only=False,
5364 )
5365 return terms
5366
5367
5368 def _host_companies(company: dict[str, Any]) -> list[str]:
5369 """The companies the host named (``--company``, then ``--ticker``), in order."""
5370 names = [str(name) for name in company.get("host_companies") or [] if name]
5371 single = str(company.get("host_company") or "")
5372 if single and single not in names:
5373 names.insert(0, single)
5374 return names
5375
5376
5377 def _search_jobs_lane(
5378 company: dict[str, Any],
5379 topic: str,
5380 *,
5381 config: dict[str, Any],
5382 depth: str,
5383 date_range: tuple[str, str],
5384 web_backend: str,
5385 ) -> tuple[list[dict], dict]:
5386 """Search the board of the company the topic resolved to.
5387
5388 A person's name searches the company they lead, starting from its
5389 official site. When the lookup named no company and the topic has no
5390 board of its own (a person, searched by name), each company the host
5391 named with ``--company`` or ``--ticker`` is tried in order and the first one with a board
5392 is used. Those come with no official site, so a board gives a digest only
5393 when it names that company itself. Every company tried draws on one
5394 budget, and a board that is not the topic's own says whose it is under
5395 ``board_of``.
5396 """
5397 budget = _jobs_lane_budget(config)
5398 if budget.settled or budget.spent():
5399 # This run's lane already has its answer, or no time left to look.
5400 return [], {}
5401 name = str(company.get("company") or topic)
5402 hosts = [] if company.get("company") else _host_companies(company)
5403 tries = 1 + len(hosts)
5404 site = str(company.get("company_site") or company.get("topic_site") or "")
5405 # The official site the resolver returned for a company the host named.
5406 host_sites = {
5407 str(key): str(value)
5408 for key, value in (company.get("host_company_sites") or {}).items() if value
5409 }
5410
5411 def named(found: dict) -> dict:
5412 # A board that is not the topic's own says whose it is.
5413 of = str(found.get("company") or name)
5414 if not jobs._same_company(of, topic):
5415 found["board_of"] = of
5416 return found
5417
5418 # The board the host found by web search is read first. One that is the
5419 # company's ends the lane; any other is kept only if the lane finds no
5420 # board itself.
5421 held: tuple[list[dict], dict] | None = None
5422 board_url = str(config.get("_jobs_board") or "").strip()
5423 if board_url:
5424 with http.tee_failures() as failures:
5425 host_items, host_artifact = jobs.search_board_url(
5426 board_url, [name, *hosts], date_range, config,
5427 site=site, sites=host_sites,
5428 explicit=bool(config.get("_hiring_signals_mode")), budget=budget,
5429 # Until the board is known to be the company's it has one
5430 # share of the budget, like each company still to be tried.
5431 discovery_seconds=budget.remaining() / (1 + tries),
5432 )
5433 if _is_jobs_board("jobs", host_artifact):
5434 if host_artifact.get("owned"):
5435 budget.settled = True
5436 return host_items, named(host_artifact)
5437 held = (host_items, host_artifact)
5438
5439 def search(target: str, left: int, **where: Any) -> tuple[list[dict], dict]:
5440 return jobs.search_jobs(
5441 target,
5442 date_range,
5443 config,
5444 depth=depth,
5445 explicit=bool(config.get("_hiring_signals_mode")),
5446 entity_count=_comparison_entity_count(config),
5447 budget=budget,
5448 # Finding one company's board may use an equal share of what is
5449 # left, so the next company still gets its turn.
5450 discovery_seconds=budget.remaining() / left if left > 1 else None,
5451 **where,
5452 )
5453
5454 with http.tee_failures() as failures:
5455 items, artifact = search(
5456 name,
5457 tries,
5458 web_backend=web_backend,
5459 site=site,
5460 )
5461 if _is_jobs_board("jobs", artifact):
5462 if not jobs._same_company(name, topic):
5463 artifact["board_of"] = name
5464 else:
5465 for index, host_company in enumerate(hosts):
5466 host_items, host_artifact = search(
5467 host_company, tries - 1 - index, web_backend="none",
5468 **({"site": host_sites[host_company]} if host_company in host_sites else {}),
5469 )
5470 if _is_jobs_board("jobs", host_artifact):
5471 host_artifact["board_of"] = host_company
5472 items, artifact = host_items, host_artifact
5473 break
5474 # The topic's own result stands, with the reason the budget
5475 # ended the search when it did.
5476 for key in ("_source_outcome", "_source_out_of_time"):
5477 if key in host_artifact and not items:
5478 artifact = {**artifact, key: host_artifact[key]}
5479 # A named company whose job site is known and not read keeps
5480 # its footer line; the first such company is the one named.
5481 unreadable = host_artifact.get("job_site_unreadable")
5482 if unreadable and not artifact.get("job_site_unreadable"):
5483 artifact = {
5484 **artifact, "job_site_unreadable": unreadable,
5485 "job_site_unreadable_reason": host_artifact.get("job_site_unreadable_reason", ""),
5486 }
5487 if held and not _is_jobs_board("jobs", artifact):
5488 items, artifact = held[0], named(held[1])
5489 # A board tied to no company here is shown under the name it states.
5490 stated = str(artifact.get("board_company") or "")
5491 if stated and not jobs._same_company(stated, topic):
5492 artifact["board_of"] = stated
5493 if not items and not _is_jobs_board("jobs", artifact) and not (
5494 budget.stopped_at or budget.spent() or budget.has_unanswered()
5495 or artifact.get("job_site_unreadable")
5496 ):
5497 jobs.log_no_board([name, *hosts])
5498 # Nothing failed and time was left: the answer will not change on a
5499 # second pass. A failure or a spent budget leaves the retry its chance
5500 # within what is left of the budget.
5501 budget.settled = _is_jobs_board("jobs", artifact) or not (
5502 failures or budget.stopped_at or budget.spent() or budget.has_unanswered()
5503 )
5504 return items, artifact
5505
5506
5507 def _is_jobs_board(source: str, artifact: Any) -> bool:
5508 """Whether a jobs fetch read the company's board directly."""
5509 return source == "jobs" and isinstance(artifact, dict) and artifact.get("tier") == "ats"
5510
5511
5512 def _jobs_board_artifact(artifact: dict[str, Any]) -> dict[str, Any]:
5513 """The board data a run keeps, with no digest when the caller asked for none."""
5514 if env.jobs_digest_disabled():
5515 return {key: value for key, value in artifact.items() if key != "digest"}
5516 return artifact
5517
5518
5519 # -- person runs ----------------------------------------------------------------
5520
5521 # The person's own LinkedIn posts, read once per person run.
5522 PERSON_POSTS_SOURCE = "linkedin_profile"
5523 # Older posts kept for the Person Profile, and each one's text cap.
5524 PERSON_OLDER_POSTS_MAX = 6
5525 PERSON_OLDER_POST_CHARS = 300
5526 # How far back older posts reach.
5527 PERSON_POSTS_LOOKBACK_DAYS = 365
5528 PERSON_POSTS_PAGES = deepline.DEFAULT_CAPS[deepline.TOOL_POSTS]
5529
5530 _PERSON_POSTS_FAILURE_STATES: dict[str, str] = {
5531 deepline.AUTH_FAILED: schema.AUTH_FAILED,
5532 deepline.OUT_OF_CREDITS: schema.PAYMENT_REQUIRED,
5533 deepline.RATE_LIMITED: schema.RATE_LIMITED,
5534 deepline.TIMEOUT: health.TIMEOUT,
5535 }
5536
5537
5538 def _person_posts_mode(config: dict[str, Any]) -> str | None:
5539 """How this run reads the person's posts: "stored", "deepline", or None.
5540
5541 Only a person run whose LinkedIn profile was read from an anchored URL
5542 qualifies. A ScrapeCreators profile read already returned the posts
5543 ("stored"); otherwise a Deepline key reads them ("deepline").
5544 """
5545 ctx = config.get("_person")
5546 if ctx is None or ctx.linkedin_status != person.LINKEDIN_CHECKED or not ctx.linkedin_url:
5547 return None
5548 profile = ctx.profile or {}
5549 if profile.get("source") == "scrapecreators" and profile.get("posts"):
5550 return "stored"
5551 if deepline.is_available(config):
5552 return "deepline"
5553 return None
5554
5555
5556 def _read_person_posts(
5557 profile_url: str, config: dict[str, Any], from_date: str,
5558 ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
5559 """Up to two pages of the person's posts from Deepline, and the failure that
5560 ended the read before any post arrived (None when the read worked)."""
5561 import uuid
5562
5563 client = deepline.from_config(config, uuid.uuid4().hex)
5564 if client is None:
5565 return [], {"state": schema.SKIPPED_UNCONFIGURED, "detail": "No Deepline key", "attempted": False}
5566 cutoff = (
5567 date.fromisoformat(from_date) - timedelta(days=PERSON_POSTS_LOOKBACK_DAYS)
5568 ).isoformat()
5569 posts: list[dict[str, Any]] = []
5570 token = None
5571 for _page in range(PERSON_POSTS_PAGES):
5572 result = client.get_posts(
5573 profile_url,
5574 deadline_monotonic=config.get("_research_deadline"),
5575 posted_limit="year",
5576 pagination_token=token,
5577 )
5578 if result["status"] != deepline.OK:
5579 state = _PERSON_POSTS_FAILURE_STATES.get(result["status"], "error")
5580 detail = f"LinkedIn posts read failed: {result['status']}"
5581 if result.get("detail"):
5582 detail += f" ({result['detail']})"
5583 if posts:
5584 # A later page failed: keep the posts already read, but the
5585 # read is incomplete, so the count is a floor, not a total.
5586 return posts, {"state": state, "detail": detail, "partial": True}
5587 return [], {"state": state, "detail": detail}
5588 page = result["data"] or {}
5589 posts.extend(page.get("posts") or [])
5590 token = page.get("next_token")
5591 days = [post.get("date") for post in posts if post.get("date")]
5592 # A second page only helps while this one still reaches inside the
5593 # year and the older-activity list is not yet full.
5594 older = [day for day in days if day < from_date]
5595 if not token or (days and min(days) < cutoff) or len(older) >= PERSON_OLDER_POSTS_MAX:
5596 break
5597 return posts, None
5598
5599
5600 def _split_person_posts(
5601 posts: list[dict[str, Any]], *, author: str, from_date: str, to_date: str,
5602 owner_id: str = "",
5603 ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
5604 """(in-window raw items, older-activity entries newest first).
5605
5606 Undated posts are dropped: older activity is shown by its real date, and
5607 the window cannot be checked without one. The upstream's own date limit is
5608 not trusted, so the year cutoff is applied here.
5609 """
5610 cutoff = (
5611 date.fromisoformat(from_date) - timedelta(days=PERSON_POSTS_LOOKBACK_DAYS)
5612 ).isoformat()
5613 in_window: list[dict[str, Any]] = []
5614 older: list[dict[str, Any]] = []
5615 seen: set[str] = set()
5616 for post in posts:
5617 day = str(post.get("date") or "")
5618 key = str(post.get("url") or post.get("id") or "")
5619 if not day or (key and key in seen):
5620 continue
5621 if key:
5622 seen.add(key)
5623 text = str(post.get("text") or "").strip()
5624 # A post another member wrote shows on the profile's activity because
5625 # the person shared it; it is not their own words.
5626 post_author = str(post.get("author_id") or "").lower()
5627 is_reshare = bool(post.get("is_reshare")) or bool(
5628 owner_id and post_author and post_author != owner_id.lower()
5629 )
5630 if from_date <= day <= to_date:
5631 in_window.append({
5632 "id": post.get("id"),
5633 "url": post.get("url"),
5634 "text": text,
5635 "date": day,
5636 "is_reshare": is_reshare,
5637 "author": author,
5638 "engagement": dict(post.get("engagement") or {}),
5639 })
5640 elif cutoff <= day < from_date:
5641 if len(text) > PERSON_OLDER_POST_CHARS:
5642 text = text[: PERSON_OLDER_POST_CHARS - 1].rstrip() + "\u2026"
5643 older.append({"date": day, "url": post.get("url"), "text": text, "is_reshare": is_reshare})
5644 older.sort(key=lambda entry: entry["date"], reverse=True)
5645 return in_window, older[:PERSON_OLDER_POSTS_MAX]
5646
5647
5648 def _fetch_person_posts(
5649 *,
5650 mode: str,
5651 profile_url: str,
5652 stored_posts: list[dict[str, Any]],
5653 author: str,
5654 config: dict[str, Any],
5655 from_date: str,
5656 to_date: str,
5657 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
5658 """The posts lane's stream result: in-window raw items, plus an artifact
5659 carrying the older posts and, on failure or an empty window, the outcome.
5660
5661 Never raises: a failure is an outcome, and the generic transient retry
5662 must not re-run this lane through the keyword-search path.
5663 """
5664 try:
5665 if mode == "stored":
5666 posts, failure = list(stored_posts), None
5667 else:
5668 posts, failure = _read_person_posts(profile_url, config, from_date)
5669 in_window, older = _split_person_posts(
5670 posts, author=author, from_date=from_date, to_date=to_date,
5671 owner_id=profile_url.rstrip("/").rsplit("/", 1)[-1],
5672 )
5673 except Exception as exc: # noqa: BLE001 - a lane failure is an outcome
5674 return [], {
5675 "_person_older_posts": [],
5676 "_source_outcome": {"state": "error", "detail": f"LinkedIn posts lane failed: {type(exc).__name__}"},
5677 }
5678 artifact: dict[str, Any] = {"_person_older_posts": older, "_person_posts_read": failure is None}
5679 if failure is not None and failure.get("partial"):
5680 # The posts that arrived still count; only the total is unknown.
5681 log.source_log("LinkedIn profile", f"posts read incomplete: {failure['detail']}", tty_only=False)
5682 elif failure is not None:
5683 artifact["_source_outcome"] = failure
5684 elif not in_window:
5685 # Like a pinned GitHub user with no activity: recorded, never
5686 # backfilled with a keyword search for the name.
5687 artifact["_source_outcome"] = {
5688 "state": schema.NO_RESULTS,
5689 "detail": "No LinkedIn posts by the person in the window",
5690 }
5691 log.source_log(
5692 "LinkedIn profile",
5693 f"{len(in_window)} post(s) in the window, {len(older)} older",
5694 tty_only=False,
5695 )
5696 return in_window, artifact
5697
5698
5699 def _merged_person_anchors(plan_anchors: list[str], person_anchors: list[str]) -> list[str]:
5700 """The plan's anchors followed by the person's, each once, ignoring case."""
5701 merged: list[str] = []
5702 seen: set[str] = set()
5703 for anchor in [*plan_anchors, *person_anchors]:
5704 text = " ".join(str(anchor or "").split())
5705 if text and text.casefold() not in seen:
5706 seen.add(text.casefold())
5707 merged.append(text)
5708 return merged
5709
5710
5711 def _first_party_in_window(
5712 items_by_source: dict[str, list[schema.SourceItem]],
5713 *,
5714 x_handle: str | None,
5715 github_person: bool,
5716 from_date: str,
5717 to_date: str,
5718 ) -> int:
5719 """Dated in-window items from the person's own accounts: their LinkedIn
5720 posts, posts by the resolved X handle, and GitHub person-mode activity."""
5721
5722 def in_window(item: schema.SourceItem) -> bool:
5723 return bool(item.published_at) and from_date <= item.published_at[:10] <= to_date
5724
5725 handle = (x_handle or "").lstrip("@").lower()
5726 count = sum(in_window(item) for item in items_by_source.get(PERSON_POSTS_SOURCE, []))
5727 if handle:
5728 count += sum(
5729 in_window(item) for item in items_by_source.get("x", [])
5730 if (item.author or "").lstrip("@").lower() == handle
5731 )
5732 if github_person:
5733 count += sum(in_window(item) for item in items_by_source.get("github", []))
5734 return count
5735
5736
5737 def _rejected_job_keys(
5738 candidates: list[schema.Candidate],
5739 ranked: list[schema.Candidate],
5740 board: Any,
5741 topic: str,
5742 ) -> list[str]:
5743 """The postings ranking dropped, which the hiring sections then leave out.
5744
5745 Ranking judges a posting against the topic's name. On the company's own
5746 board that is a fair test of a stray posting when the topic is the
5747 company, whose postings name it. When the topic is the person who leads
5748 the company, no posting names the topic, so ranking drops every one it
5749 looks at: that says nothing about the roles, and none is recorded.
5750 """
5751 if (
5752 isinstance(board, dict)
5753 and board.get("owned")
5754 and not jobs._same_company(str(board.get("company") or ""), topic)
5755 ):
5756 return []
5757 retained_ids = {candidate.candidate_id for candidate in ranked}
5758 return sorted({
5759 fusion.candidate_key(item)
5760 for candidate in candidates
5761 if candidate.candidate_id not in retained_ids
5762 for item in candidate.source_items
5763 if item.source == "jobs"
5764 })
5765
5766
5767 def _engine_ranked_job_urls(
5768 ranked: list[schema.Candidate],
5769 hiring_summary: dict[str, Any] | None,
5770 ) -> list[str]:
5771 """Posting URLs of the roles the run itself put highest, best first.
5772
5773 Two lists, taken in turn: the job postings in ranking order, and the
5774 roles the Hiring Signals block names (its strategic single roles, then
5775 the evidence under each theme, as many of each as the block prints) when
5776 the run has that block. Postings the ranking rejected are left out.
5777 """
5778 summary = hiring_summary if isinstance(hiring_summary, dict) else {}
5779 rejected = set(summary.get("rejected_job_keys") or [])
5780 ranked_urls = [
5781 item.url
5782 for candidate in ranked
5783 for item in candidate.source_items
5784 if item.source == "jobs" and item.url and fusion.candidate_key(item) not in rejected
5785 ]
5786 named: list[str] = []
5787 if summary.get("include") or summary.get("mode") == "explicit":
5788 named.extend(
5789 str(role.get("url") or "") for role in (summary.get("strategic_candidates") or [])[:8]
5790 )
5791 for signal in (summary.get("signals") or [])[:4]:
5792 named.extend(str(role.get("url") or "") for role in (signal.get("evidence") or [])[:3])
5793 urls: list[str] = []
5794 for index in range(max(len(ranked_urls), len(named))):
5795 for source_urls in (ranked_urls, named):
5796 if index < len(source_urls) and source_urls[index] and source_urls[index] not in urls:
5797 urls.append(source_urls[index])
5798 return urls
5799
5800
5801 def _add_ranked_roles_to_jobs_digest(
5802 bundle: schema.RetrievalBundle,
5803 ranked: list[schema.Candidate],
5804 hiring_summary: dict[str, Any] | None,
5805 ) -> None:
5806 """Give the Jobs Digest the roles this run ranked highest.
5807
5808 The digest is chosen by rarity when the board is read, before anything is
5809 ranked, and the report's hiring section is written from the digest alone.
5810 Up to ``jobs_digest.ENGINE_ROLE_SLOTS`` of its places go to the ranked
5811 roles it left out. The board's rows are dropped afterwards.
5812 """
5813 rows, bundle.jobs_board_rows = bundle.jobs_board_rows, []
5814 board = bundle.artifacts.get("jobs")
5815 digest = board.get("digest") if isinstance(board, dict) else None
5816 if not rows or not isinstance(digest, dict) or not digest.get("roles"):
5817 return
5818 # Roles the board keeps out of the digest (Apple's retail store roles)
5819 # stay out however well they rank.
5820 rows = [row for row in rows if not row.get("digest_excluded")]
5821 # Ranking sees normalized items; the digest holds the board's own URLs.
5822 board_urls = {fusion._normalize_url(str(row.get("url") or "")): str(row["url"])
5823 for row in rows if row.get("url")}
5824 urls = [
5825 board_urls[key]
5826 for key in (fusion._normalize_url(url) for url in _engine_ranked_job_urls(ranked, hiring_summary))
5827 if key in board_urls
5828 ]
5829 board["digest"] = jobs_digest.add_engine_roles(digest, rows, list(dict.fromkeys(urls)))
5830
5831
5832 def _apply_hiring_signal_gate(
5833 bundle: schema.RetrievalBundle,
5834 *,
5835 explicit: bool,
5836 topic: str,
5837 ) -> dict[str, Any] | None:
5838 # On a standard run, a board whose titles cluster into no clear theme
5839 # leaves the evidence pool, so scattered postings are not ranked and
5840 # clustered beside what people said. The board's counts and digest live in
5841 # ``bundle.artifacts["jobs"]`` and are not touched here.
5842 jobs_items = bundle.items_by_source.get("jobs") or []
5843 if not jobs_items:
5844 if explicit:
5845 return hiring_signals.analyze([], explicit=True, topic=topic)
5846 return None
5847
5848 summary = hiring_signals.analyze(jobs_items, explicit=explicit, topic=topic)
5849 if not explicit and not summary.get("include"):
5850 bundle.items_by_source.pop("jobs", None)
5851 for key in list(bundle.items_by_source_and_query):
5852 if key[1] == "jobs":
5853 del bundle.items_by_source_and_query[key]
5854 return summary
5855
5856
5857 def _mean_source_weight(weights: Mapping[str, float]) -> float:
5858 """Return the mean positive weight in ``weights``, or 1.0 when empty.
5859
5860 Post-plan source injectors add sources onto an already-normalized map whose
5861 values sum to 1.0; inserting at the mean prevents a raw 1.0 entry from
5862 halving every planned source on renormalization.
5863 """
5864 positive = [w for w in weights.values() if w > 0]
5865 return (sum(positive) / len(positive)) if positive else 1.0
5866
5867
5868 def _ensure_opt_in_source_in_plan(
5869 plan: schema.QueryPlan, available: list[str], source: str,
5870 ) -> None:
5871 """Give an activated off-by-default source (dev.to, V2EX) the primary subquery.
5872
5873 These sources are off by default, so a plan built from the default source
5874 list never names them. Once a flag or INCLUDE_SOURCES turns one on,
5875 activation must not be a no-op.
5876 """
5877 if source not in available or not plan.subqueries:
5878 return
5879 # A plan that already routes the source keeps its route: MAX_SOURCE_FETCHES
5880 # allows one fetch, and a second route would spend it first.
5881 if not any(source in subquery.sources for subquery in plan.subqueries):
5882 plan.subqueries[0].sources.append(source)
5883 if source not in plan.source_weights:
5884 plan.source_weights[source] = _mean_source_weight(plan.source_weights)
5885 plan.source_weights = planner._normalize_weights(plan.source_weights)
5886
5887
5888 # Paid lanes the host requests per run outside the plan (runbook Step 0.5e /
5889 # 0.5f): source -> (config key of its targeting flag, log label). They join a
5890 # host plan only when this run asked: the source is in --search, or its
5891 # targeting flag is set. INCLUDE_SOURCES alone makes the lane available but
5892 # leaves the per-topic decision with the host.
5893 HOST_PLAN_PAID_LANES = {
5894 "amazon": ("_amazon_query", "Amazon"),
5895 "meta_ads": ("_meta_ads_page", "Meta Ads"),
5896 }
5897
5898
5899 def _paid_lanes_asked_for(
5900 requested_sources: list[str] | None,
5901 config: dict[str, Any] | None,
5902 ) -> list[str]:
5903 requested = requested_sources or []
5904 return [
5905 source for source, (flag_key, _label) in HOST_PLAN_PAID_LANES.items()
5906 if source in requested or str((config or {}).get(flag_key) or "").strip()
5907 ]
5908
5909
5910 def _backfill_lane_can_run(
5911 source: str,
5912 config: dict[str, Any] | None,
5913 requested_sources: list[str] | None,
5914 trustpilot_domain: str | None,
5915 ) -> bool:
5916 """Whether a backfill candidate could return data in this session.
5917
5918 Backfill exists for lanes the host forgot, so it must not add one the
5919 host was told to skip because it cannot run now. Trustpilot needs a
5920 browser session or a cached company record (``trustpilot_can_run`` in
5921 --diagnose); without one the lane is a guaranteed SESSION_NEEDED skip.
5922 An explicit ask (--search trustpilot, --trustpilot-domain) still adds it,
5923 so the user sees why it did not run. Local reads only."""
5924 if source != "trustpilot":
5925 return True
5926 if trustpilot_domain or "trustpilot" in (requested_sources or []):
5927 return True
5928 return bool(trustpilot.can_run_now(config).get("can_run"))
5929
5930
5931 def _ensure_unplanned_lanes_in_host_plan(
5932 plan: schema.QueryPlan,
5933 available: list[str],
5934 *,
5935 asked: list[str] | tuple[str, ...] = (),
5936 installed: bool = True,
5937 config: dict[str, Any] | None = None,
5938 requested_sources: list[str] | None = None,
5939 trustpilot_domain: str | None = None,
5940 ) -> None:
5941 if not plan.subqueries:
5942 return
5943 planned = {source for subquery in plan.subqueries for source in subquery.sources}
5944 candidates = (*(planner.HOST_PLAN_BACKFILL_SOURCES if installed else ()), *asked)
5945 missing = []
5946 for source in candidates:
5947 if source not in available or source in planned or source in missing:
5948 continue
5949 if source in asked or _backfill_lane_can_run(
5950 source, config, requested_sources, trustpilot_domain,
5951 ):
5952 missing.append(source)
5953 else:
5954 log.source_log(
5955 "Planner",
5956 f"Not adding {source} to the --plan: it cannot run this session "
5957 "(no browser session or cached record; see trustpilot_can_run "
5958 "in --diagnose).",
5959 tty_only=False,
5960 )
5961 for source, (_flag_key, label) in HOST_PLAN_PAID_LANES.items():
5962 if source in available and source not in planned and source not in missing:
5963 log.source_log(
5964 label,
5965 "available but not requested for this run; not run "
5966 f"(add {source} to --search to run it).",
5967 tty_only=False,
5968 )
5969 if not missing:
5970 return
5971 plan.subqueries[0].sources.extend(missing)
5972 default_weight = _mean_source_weight(plan.source_weights)
5973 for source in missing:
5974 plan.source_weights.setdefault(source, default_weight)
5975 plan.source_weights = planner._normalize_weights(plan.source_weights)
5976 log.source_log(
5977 "Planner",
5978 "Added installed/opted-in/requested sources absent from every --plan subquery to "
5979 f"{plan.subqueries[0].label}: {', '.join(missing)} "
5980 "(use EXCLUDE_SOURCES or, for optional lanes, plan omit_sources to skip them).",
5981 tty_only=False,
5982 )
5983
5984
5985 def _ensure_company_jobs_in_host_plan(
5986 plan: schema.QueryPlan,
5987 available: list[str],
5988 company_signal: str,
5989 ) -> None:
5990 """Give the jobs lane the primary subquery of a host plan about a company.
5991
5992 ``company_signal`` says what makes the run about a company (the official
5993 site, a host ticker or company, the company the topic resolved to); with
5994 none the plan is left as it is, so a musician or a concept gets no jobs
5995 lane. ``available`` already leaves jobs out under EXCLUDE_SOURCES or a
5996 ``--search`` list without it.
5997 """
5998 if not company_signal or "jobs" not in available or not plan.subqueries:
5999 return
6000 if "drill-mode" in plan.notes:
6001 return
6002 if any("jobs" in subquery.sources for subquery in plan.subqueries):
6003 return
6004 plan.subqueries[0].sources.append("jobs")
6005 plan.source_weights.setdefault("jobs", _mean_source_weight(plan.source_weights))
6006 plan.source_weights = planner._normalize_weights(plan.source_weights)
6007 log.source_log(
6008 "Planner",
6009 f"Added jobs to {plan.subqueries[0].label}: the run is about a company "
6010 f"({company_signal}) and no --plan subquery names it "
6011 "(set EXCLUDE_SOURCES=jobs to skip it).",
6012 tty_only=False,
6013 )
6014
6015
6016 # Lanes the engine attaches on its own. A --search list never drops them in
6017 # the sense a host needs to hear about.
6018 ENGINE_ATTACHED_SOURCES = frozenset(
6019 {"grounding", "corpus", "perplexity", "amazon", "meta_ads"}
6020 )
6021
6022
6023 def _warn_search_dropped_plan_sources(
6024 external_plan: dict,
6025 search_list: list[str],
6026 available_before_search: list[str],
6027 excluded_sources: set[str],
6028 *,
6029 jobs_attached: bool,
6030 jobs_past_window: bool,
6031 company_signal: str,
6032 ) -> None:
6033 """Name, once, each --plan source that only the --search list removed.
6034
6035 A source counts when the plan names it, the run could serve it, and
6036 EXCLUDE_SOURCES does not list it. Engine-attached lanes never count, nor
6037 does jobs on a past window, where the lane is skipped whatever --search
6038 says. ``jobs_attached`` means the jobs lane survived the --search list
6039 because the run is about a company; the line then says so.
6040 """
6041 can_serve = set(available_before_search) - excluded_sources
6042 named: list[str] = []
6043 for subquery in external_plan.get("subqueries") or []:
6044 if not isinstance(subquery, dict):
6045 continue
6046 for source in subquery.get("sources") or []:
6047 if isinstance(source, str) and source not in named:
6048 named.append(source)
6049 dropped = [
6050 source for source in named
6051 if source in can_serve
6052 and source not in search_list
6053 and source not in ENGINE_ATTACHED_SOURCES
6054 and not (source == "jobs" and (jobs_attached or jobs_past_window))
6055 ]
6056 parts: list[str] = []
6057 if dropped:
6058 them = "it" if len(dropped) == 1 else "them"
6059 parts.append(
6060 f"--search dropped {', '.join(dropped)}: the --plan names {them} "
6061 f"and the run could search {them}, but --search does not list {them}."
6062 )
6063 if jobs_attached and not jobs_past_window and "jobs" in named:
6064 parts.append(
6065 "The --plan names jobs and --search would have dropped it; kept "
6066 f"because the run is about a company ({company_signal}) "
6067 "(set EXCLUDE_SOURCES=jobs to skip it)."
6068 )
6069 if parts:
6070 log.source_log("Planner", " ".join(parts), tty_only=False)
6071
6072
6073 def _external_plan_names_source(external_plan: Any, source: str) -> bool:
6074 if not isinstance(external_plan, dict):
6075 return False
6076 subqueries = external_plan.get("subqueries")
6077 if not isinstance(subqueries, list):
6078 return False
6079 return any(
6080 isinstance(subquery, dict)
6081 and isinstance(subquery.get("sources"), list)
6082 and source in subquery["sources"]
6083 for subquery in subqueries
6084 )
6085
6086
6087 def _ensure_jobs_in_plan(
6088 plan: schema.QueryPlan,
6089 available: list[str],
6090 *,
6091 explicit: bool,
6092 topic: str,
6093 ) -> None:
6094 if "jobs" not in available:
6095 return
6096 if not (explicit or _company_topic_likely(topic)):
6097 return
6098 if "jobs" not in plan.source_weights:
6099 plan.source_weights["jobs"] = _mean_source_weight(plan.source_weights)
6100 plan.source_weights = planner._normalize_weights(plan.source_weights)
6101 for subquery in plan.subqueries:
6102 if "jobs" not in subquery.sources:
6103 subquery.sources.append("jobs")
6104
6105
6106 def _ensure_perplexity_in_plan(
6107 plan: schema.QueryPlan,
6108 topic: str,
6109 available: list[str],
6110 *,
6111 force: bool,
6112 ) -> None:
6113 """Route a bounded paid Perplexity action through the whole topic.
6114
6115 Deep Research forces its explicit lane. Normal modes are rerouted only when
6116 the sanitized plan already selected Perplexity.
6117 """
6118 if "perplexity" not in available:
6119 return
6120 planned = any(
6121 "perplexity" in subquery.sources for subquery in plan.subqueries
6122 )
6123 if not force and not planned:
6124 return
6125 retained: list[schema.SubQuery] = []
6126 for subquery in plan.subqueries:
6127 sources = [
6128 source for source in subquery.sources if source != "perplexity"
6129 ]
6130 if sources:
6131 retained.append(replace(subquery, sources=sources))
6132 perplexity_weight = (
6133 sum(sq.weight for sq in retained) / len(retained)
6134 if retained else 1.0
6135 )
6136 retained.append(
6137 schema.SubQuery(
6138 label="deep-research" if force else "perplexity-whole-topic",
6139 search_query=topic,
6140 ranking_query=f"What current source-grounded evidence matters for {topic}?",
6141 sources=["perplexity"],
6142 weight=perplexity_weight,
6143 ),
6144 )
6145 plan.subqueries = planner._normalize_subquery_weights(retained)
6146 plan.source_weights.setdefault(
6147 "perplexity", _mean_source_weight(plan.source_weights),
6148 )
6149 plan.source_weights = planner._normalize_weights(plan.source_weights)
6150
6151
6152 _company_topic_likely = company_resolve.company_topic_likely
6153
6154
6155 def _warnings(
6156 items_by_source: dict[str, list[schema.SourceItem]],
6157 candidates: list[schema.Candidate],
6158 errors_by_source: dict[str, str],
6159 degraded_by_source: dict[str, str] | None = None,
6160 ) -> list[str]:
6161 warnings: list[str] = []
6162 if not candidates:
6163 warnings.append("No candidates survived retrieval and ranking.")
6164 if len(candidates) < 5:
6165 warnings.append("Evidence is thin for this topic.")
6166 top_sources = {
6167 source
6168 for candidate in candidates[:5]
6169 for source in schema.candidate_sources(candidate)
6170 }
6171 if len(top_sources) <= 1 and len(candidates) >= 3:
6172 warnings.append("Top evidence is highly concentrated in one source.")
6173 if errors_by_source:
6174 warnings.append(f"Some sources failed: {', '.join(sorted(errors_by_source))}")
6175 if degraded_by_source:
6176 # Partial failures: the source returned some items but errored/timed out
6177 # on at least one subquery, so its coverage is likely incomplete. Kept
6178 # distinct from hard failures so the signal is not silently dropped.
6179 warnings.append(
6180 f"Some sources returned partial results (degraded): {', '.join(sorted(degraded_by_source))}"
6181 )
6182 if not items_by_source:
6183 warnings.append("No source returned usable items.")
6184 return warnings
6185
6186
6187 _STATUS_PREFIX = r"\b(?:https?(?:/\d(?:\.\d)?)?(?:\s+error)?|status(?:[\s_]*code)?|code)\s*[:=#]?\s*"
6188
6189
6190 def _mentions_status(msg: str, code_pattern: str, phrases: tuple[str, ...]) -> bool:
6191 """True when ``msg`` names an HTTP status matching ``code_pattern``.
6192
6193 A bare number is not enough (``"batch 429 failed"`` is not a rate
6194 limit): the code must follow an HTTP/status/code marker, or co-occur
6195 with one of ``phrases`` (``"rate limited (429)"``). Digit-aware
6196 boundaries keep ``"14293"`` from reading as a 429.
6197 """
6198 if not msg:
6199 return False
6200 code = r"(?:" + code_pattern + r")(?!\d)"
6201 if re.search(_STATUS_PREFIX + code, msg, re.IGNORECASE):
6202 return True
6203 lowered = msg.lower()
6204 return any(p in lowered for p in phrases) and re.search(r"(?<!\d)" + code, msg) is not None
6205
6206
6207 _RATE_LIMIT_PHRASES = ("rate limit", "rate-limit", "ratelimit", "too many requests")
6208 _SERVER_ERROR_PHRASES = (
6209 "server error",
6210 "bad gateway",
6211 "service unavailable",
6212 "gateway timeout",
6213 "gateway time-out",
6214 )
6215
6216
6217 def _is_rate_limit_error(exc: Exception) -> bool:
6218 """Detect 429 rate-limit errors by status code or message text."""
6219 if hasattr(exc, "status_code") and getattr(exc, "status_code", None) == 429:
6220 return True
6221 return _mentions_status(str(exc), "429", _RATE_LIMIT_PHRASES)
6222
6223
6224 class SourceRunError(RuntimeError):
6225 """Source-specific failure that survived a module's fallback logic."""
6226
6227 def __init__(
6228 self,
6229 message: str,
6230 state: schema.RunOutcomeState | None = None,
6231 lane_notes: Iterable[str] = (),
6232 ):
6233 super().__init__(message)
6234 self.outcome_state = state or http.classify_failure(message=message)
6235 # Display notes the lane observed. They never decide the state or the reason.
6236 self.lane_notes = tuple(dict.fromkeys(lane_notes))
6237
6238
6239 def _classify_source_failure(exc: Exception) -> tuple[schema.RunOutcomeState, bool]:
6240 """Classify HTTP, subprocess, and module-specific failures consistently."""
6241 detail = str(exc)
6242 lowered = detail.lower()
6243 if any(marker in lowered for marker in ("not configured", "no api key", "not installed")):
6244 return schema.SKIPPED_UNCONFIGURED, False
6245 if any(
6246 marker in lowered
6247 for marker in (
6248 "cookie expired",
6249 "expired cookie",
6250 "login required",
6251 "not logged in",
6252 "grok session expired",
6253 "session expired or was revoked",
6254 "invalid_grant",
6255 "not signed in",
6256 )
6257 ):
6258 return schema.AUTH_FAILED, True
6259 state = getattr(exc, "outcome_state", None) or http.classify_failure(
6260 status_code=getattr(exc, "status_code", None),
6261 message=detail,
6262 )
6263 return state, True
6264
6265
6266 def _reddit_on_topic_count(
6267 items: list[dict],
6268 from_date: str,
6269 to_date: str,
6270 ranking_query: str,
6271 freshness_mode: str | None,
6272 ) -> int:
6273 """How many free Reddit threads will survive this stream's relevance prune.
6274
6275 The ScrapeCreators floor is measured on this, not on the raw count: a run
6276 whose site search is refused still returns dozens of listing threads from
6277 the targeted subreddits, nearly all pruned as off topic a moment later
6278 ("relevance prune dropped 99 of 106"), so the raw count never fell under
6279 the floor and the backfill never ran. Same normalize, annotate and prune
6280 as ``_normalize_score_dedupe``; on any error the raw count is used.
6281 """
6282 if not items:
6283 return 0
6284 try:
6285 mode = freshness_mode or "balanced_recent"
6286 normalized = normalize.normalize_source_items(
6287 "reddit", copy.deepcopy(items), from_date, to_date, freshness_mode=mode,
6288 )
6289 days = (date.fromisoformat(to_date) - date.fromisoformat(from_date)).days
6290 annotated = signals.annotate_stream(
6291 normalized, relevance.PreparedQuery(ranking_query), mode,
6292 reference_date=to_date, max_days=days,
6293 )
6294 return len(signals.prune_low_relevance(annotated, passing_only=True))
6295 except Exception:
6296 return len(items)
6297
6298
6299 def _run_reddit_backfill(config: dict[str, Any], call) -> Any:
6300 """Run the ScrapeCreators backfill, giving up shortly before the stream
6301 wait ends so a slow backfill cannot turn the free threads into a timeout.
6302 Raises ``TimeoutError`` when it does not finish in time."""
6303 research_deadline = config.get("_research_deadline")
6304 cancel = config.get("_enrich_cancel")
6305 if research_deadline is None and cancel is None:
6306 return call()
6307 if _research_stopped(config):
6308 raise TimeoutError("ScrapeCreators backfill timed out: research cancelled or timed out")
6309 if research_deadline is not None:
6310 remaining = research_deadline - REDDIT_SC_BACKFILL_RETURN_MARGIN_SECONDS - time.monotonic()
6311 if remaining < REDDIT_SC_BACKFILL_MIN_SECONDS:
6312 raise TimeoutError(
6313 "ScrapeCreators backfill timed out: no time left in the run's budget"
6314 )
6315 wait_deadline = time.monotonic() + remaining
6316 timeout_detail = f"ScrapeCreators backfill timed out: did not finish in {remaining:.0f}s"
6317 else:
6318 wait_deadline = time.monotonic() + STREAM_FUTURE_TIMEOUT_SECONDS
6319 timeout_detail = "ScrapeCreators backfill timed out: research cancelled or timed out"
6320 backfill_cancel = threading.Event()
6321
6322 def _bounded_call():
6323 with reddit.sc_spend_until(deadline=wait_deadline, cancel=cancel), \
6324 reddit.sc_spend_until(deadline=wait_deadline, cancel=backfill_cancel):
6325 return call()
6326
6327 with _abandoning_executor(max_workers=1) as executor:
6328 future = http.submit_with_context(executor, _bounded_call)
6329 wait_config = {**config, "_research_deadline": wait_deadline}
6330 done, _pending = _wait_for_research([future], wait_config)
6331 if future in done or (future.done() and not future.cancelled()):
6332 return future.result(timeout=0)
6333 future.cancel()
6334 if future.done() and not future.cancelled():
6335 return future.result(timeout=0)
6336 backfill_cancel.set()
6337 raise TimeoutError(timeout_detail)
6338
6339
6340 def _reddit_served_artifact(
6341 items: list[dict], paths: dict[str, str], *, extra: tuple[str, ...] = (),
6342 count: int | None = None,
6343 ) -> dict[str, Any]:
6344 """The served-path detail for a Reddit lane that delivered items.
6345
6346 The source stays ``ok`` whichever path served (#959, #1083): a refused
6347 site search with threads from the web floor reads
6348 ``web+arctic served 14; search blocked``, never partial. No detail
6349 state is set, so a failed path never lands in ``rate_limited_sources``.
6350 """
6351 if not items and not count:
6352 return {}
6353 return {
6354 "_source_outcome_detail": reddit_health.served_detail(
6355 items, paths, extra=extra, count=count,
6356 ),
6357 }
6358
6359
6360 def _with_reddit_lane_notes(artifact: dict[str, Any], notes: list[str]) -> dict[str, Any]:
6361 """``artifact`` with the Reddit lane's notes appended to its detail."""
6362 if not notes:
6363 return artifact
6364 artifact = dict(artifact)
6365 prior = artifact.get("_source_outcome_detail")
6366 artifact["_source_outcome_detail"] = "; ".join([prior, *notes] if prior else notes)
6367 return artifact
6368
6369
6370 def _record_reddit_exception_notes(
6371 bundle: schema.RetrievalBundle, source: str, exc: BaseException,
6372 ) -> None:
6373 """Keep the lane notes a failed Reddit stream carried, so the final report can show them."""
6374 if source != "reddit":
6375 return
6376 known = reddit_keyless.searxng_note_texts()
6377 for note in getattr(exc, "lane_notes", ()):
6378 if note in known:
6379 bundle.record_detail(source, note)
6380
6381
6382 def _attach_reddit_lane_notes(
6383 bundle: schema.RetrievalBundle,
6384 source_status: dict[str, schema.SourceOutcome],
6385 ) -> None:
6386 """Show the run's observed SearXNG notes on Reddit's final failure detail.
6387
6388 The bundle keeps a hard failure's own detail and drops the staged notes, and between
6389 streams it keeps whichever failure outranks the others. So the notes stay as separate
6390 data in ``detail_by_source`` until the winning outcome is chosen and classified. Only
6391 then are the missing ones added after the winner's own reason. The state, the reason
6392 and ``errors_by_source`` are never touched. A delivered or empty outcome already shows
6393 its notes and is left alone.
6394 """
6395 outcome = source_status.get("reddit")
6396 if outcome is None or not outcome.detail or outcome.state in (health.OK, schema.NO_RESULTS):
6397 return
6398 known = reddit_keyless.searxng_note_texts()
6399 seen = (bundle.detail_by_source.get("reddit") or "").split("; ")
6400 missing = [note for note in dict.fromkeys(seen) if note in known and note not in outcome.detail]
6401 if missing:
6402 outcome.detail = "; ".join([outcome.detail, *missing])
6403
6404
6405 def _reddit_sc_incomplete_notes(result: Any) -> list[str]:
6406 """Extract deadline-incompleteness notes from a ScrapeCreators Reddit result."""
6407 if not isinstance(result, dict):
6408 return []
6409 notes: list[str] = []
6410 if result.get("incomplete"):
6411 notes.append(str(result.get("incomplete_note") or "Reddit search incomplete (deadline reached)"))
6412 if result.get("comments_incomplete"):
6413 notes.append(str(result.get("comments_note") or "Reddit comments incomplete (deadline reached)"))
6414 return notes
6415
6416
6417 def _outcome_artifact(
6418 state: schema.RunOutcomeState,
6419 detail: str,
6420 *,
6421 attempted: bool = True,
6422 ) -> dict[str, Any]:
6423 return {
6424 "_source_outcome": {
6425 "state": state,
6426 "detail": detail,
6427 "attempted": attempted,
6428 }
6429 }
6430
6431
6432 def _captured_failures_are_only_timeouts() -> bool:
6433 """True when nothing is captured, or every captured failure is a timeout.
6434
6435 A timeout's own note is then the more specific account of the same failure. A failure of
6436 another kind, such as a 429, keeps its priority and its kind through the stream resolver.
6437 """
6438 return all(failure.outcome_state == health.TIMEOUT for failure in http.captured_failures())
6439
6440
6441 def _reddit_timeout_artifact() -> dict[str, Any]:
6442 # Give the stream resolver first choice of any recorded transport failure.
6443 if http.has_captured_failures():
6444 return {}
6445 return _outcome_artifact(
6446 health.TIMEOUT, "Reddit ran out of search time before it found threads",
6447 )
6448
6449
6450 def _result_outcome_artifact(source: str, result: Any) -> dict[str, Any]:
6451 """Convert a legacy ``{"error": ...}`` source result into typed status."""
6452 if not isinstance(result, dict) or not result.get("error"):
6453 return {}
6454 detail = str(result["error"])
6455 if source == "reddit":
6456 state = reddit.classify_run_failure(detail)
6457 attempted = True
6458 elif source == "youtube":
6459 state = youtube_yt.classify_run_failure(detail)
6460 attempted = state != schema.SKIPPED_UNCONFIGURED
6461 elif source == "x":
6462 state = bird_x.classify_run_failure(detail)
6463 attempted = True
6464 elif source == "truthsocial" and detail == "Truth Social token expired":
6465 state = schema.AUTH_FAILED
6466 attempted = True
6467 elif source == "bluesky" and "network-level block" in detail.lower():
6468 state = schema.UNREACHABLE
6469 attempted = True
6470 else:
6471 state, attempted = _classify_source_failure(SourceRunError(detail))
6472 return _outcome_artifact(state, detail, attempted=attempted)
6473
6474
6475 def _legacy_artifact_outcome(
6476 source: str,
6477 artifact: Any,
6478 ) -> dict[str, Any] | None:
6479 """Map known pre-outcome artifact contracts to a typed outcome note."""
6480 if not isinstance(artifact, dict):
6481 return None
6482 explicit = artifact.get("_source_outcome")
6483 if isinstance(explicit, dict):
6484 return explicit
6485 if source == "perplexity":
6486 candidates: list[tuple[str | None, dict[str, Any]]] = [(None, artifact)]
6487 if artifact.get("mode") == "both":
6488 for leg in ("search", "agent"):
6489 value = artifact.get(leg)
6490 if isinstance(value, dict):
6491 candidates.append((leg, value))
6492 outcomes: list[dict[str, Any]] = []
6493 for leg, candidate in candidates:
6494 if not candidate.get("error"):
6495 continue
6496 error = str(candidate["error"])
6497 detail = str(
6498 candidate.get("backgroundErrorMessage")
6499 or candidate.get("backgroundPollError")
6500 or candidate.get("agentErrorMessage")
6501 or candidate.get("asyncErrorMessage")
6502 or candidate.get("message")
6503 or error
6504 )
6505 if leg:
6506 detail = f"{leg} leg: {detail}"
6507 status_code = candidate.get("statusCode")
6508 if status_code is None:
6509 status_code = candidate.get("backgroundPollStatusCode")
6510 state = (
6511 health.TIMEOUT
6512 if error.lower() == "timeout"
6513 else http.classify_failure(
6514 status_code=status_code,
6515 message=f"{error}: {detail}",
6516 )
6517 )
6518 outcomes.append(_outcome_artifact(state, detail)["_source_outcome"])
6519 if outcomes:
6520 return min(
6521 outcomes,
6522 key=lambda outcome: _FAILURE_SPECIFICITY.get(outcome["state"], 9),
6523 )
6524 if (
6525 source == "grounding"
6526 and artifact.get("reason") == "keyless-search-unavailable"
6527 ):
6528 return _outcome_artifact(
6529 schema.UNREACHABLE,
6530 "Keyless web search unavailable",
6531 )["_source_outcome"]
6532 return None
6533
6534
6535 def _summarize_lane_failures(failures: list[http.HTTPError], source: str = "") -> str:
6536 """One line naming what a source lost to swallowed sub-request failures.
6537
6538 ``"3 sub-requests rate-limited (HTTP 429); 1 sub-request blocked (HTTP 403)"``.
6539 Used as ``SourceOutcome.detail`` on a source that still delivered items,
6540 so the loss is visible to ``doctor --postmortem`` without branding the
6541 source partial (issue #985 wording; PR #959 semantics).
6542 """
6543 counts: dict[tuple[str, int | None], int] = {}
6544 for failure in failures:
6545 state = getattr(failure, "outcome_state", None) or health.ERROR
6546 code = getattr(failure, "status_code", None)
6547 counts[(state, code)] = counts.get((state, code), 0) + 1
6548 labels = {
6549 health.RATE_LIMITED: "rate-limited",
6550 health.AUTH_FAILED: "blocked",
6551 health.PAYMENT_REQUIRED: health.credits_exhausted_label(source),
6552 health.TIMEOUT: "timed out",
6553 health.UNREACHABLE: "unreachable",
6554 health.SCHEMA_DRIFT: "returned an unexpected shape",
6555 }
6556 parts = []
6557 for (state, code), n in sorted(counts.items(), key=lambda kv: -kv[1]):
6558 noun = "sub-request" if n == 1 else "sub-requests"
6559 label = labels.get(state, "failed")
6560 suffix = f" (HTTP {code})" if code else ""
6561 parts.append(f"{n} {noun} {label}{suffix}")
6562 return "; ".join(parts)
6563
6564
6565 def _resolve_stream_outcome(
6566 source: str,
6567 artifact: Any,
6568 failures: list[http.HTTPError],
6569 ) -> dict[str, Any] | None:
6570 """Choose the most specific artifact or captured HTTP outcome."""
6571 artifact_outcome = _legacy_artifact_outcome(source, artifact)
6572 if not failures:
6573 return artifact_outcome
6574 # Pick the most specific failure rather than the last-appended one:
6575 # parallel workers append in nondeterministic order, and an auth failure
6576 # must not be masked by a later 429 (wrong doctor prescription).
6577 failure = min(
6578 failures,
6579 key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
6580 )
6581 captured_outcome = _outcome_artifact(
6582 failure.outcome_state,
6583 str(failure),
6584 )["_source_outcome"]
6585 if artifact_outcome is None:
6586 return captured_outcome
6587 if (
6588 artifact_outcome.get("state") == health.ERROR
6589 and failure.outcome_state != health.ERROR
6590 ):
6591 return captured_outcome
6592 return artifact_outcome
6593
6594
6595 def _finalize_source_status(
6596 outcomes: dict[str, schema.SourceOutcome],
6597 items_by_source: dict[str, list[schema.SourceItem]],
6598 ) -> dict[str, schema.SourceOutcome]:
6599 """Sync outcome counts to the final post-filter evidence set."""
6600 finalized: dict[str, schema.SourceOutcome] = {}
6601 for source, outcome in outcomes.items():
6602 count = len(items_by_source.get(source, []))
6603 state = outcome.state
6604 detail = outcome.detail
6605 fix_hint = outcome.fix_hint
6606 if state == schema.NO_RESULTS and count:
6607 state = health.OK
6608 detail = None
6609 fix_hint = None
6610 elif state == health.OK and not count:
6611 state = outcome.lane_failure_state or schema.NO_RESULTS
6612 elif state == schema.PARTIAL and not count:
6613 if source == "digg" and digg.is_upgrade_note(detail):
6614 # An older Digg CLI that matched nothing is an empty answer
6615 # with an upgrade note, not a failed search.
6616 state = schema.NO_RESULTS
6617 else:
6618 state = http.classify_failure(message=detail or "")
6619 finalized[source] = schema.SourceOutcome(
6620 source=source,
6621 state=state,
6622 items_returned=count,
6623 attempted=outcome.attempted,
6624 detail=detail,
6625 at=outcome.at,
6626 fix_hint=fix_hint,
6627 lane_failure_state=outcome.lane_failure_state,
6628 )
6629 return finalized
6630
6631
6632 def _is_transient_error(exc: Exception) -> bool:
6633 """Detect 5xx server errors that are worth retrying."""
6634 status = getattr(exc, "status_code", None)
6635 if isinstance(status, int) and 500 <= status < 600:
6636 return True
6637 return _mentions_status(str(exc), r"5\d\d", _SERVER_ERROR_PHRASES)
6638
6639
6640 def _retryable_youtube_outcome(outcome: dict[str, Any]) -> bool:
6641 state = outcome.get("state")
6642 if state in (health.TIMEOUT, health.UNREACHABLE):
6643 return True
6644 return state == health.ERROR and _is_transient_error(
6645 SourceRunError(str(outcome.get("detail") or ""))
6646 )
6647
6648
6649 def _retryable_youtube_error(message: str, state: str | None = None) -> bool:
6650 return _retryable_youtube_outcome({
6651 "state": state or youtube_yt.classify_run_failure(message),
6652 "detail": message,
6653 })
6654
6655
6656 def _topic_handle_mentions(topic: str) -> set[str]:
6657 """@mentions in the topic, which are real X handles.
6658
6659 These are used to determine whether the subject was identified: an
6660 @mention like "@steipete" is a real handle that can exempt its owner from
6661 the relevance floor. Regular words like "Peter" are not real handles.
6662 """
6663 return {
6664 mention.lower()
6665 for mention in re.findall(r"@([A-Za-z0-9_]{1,15})", topic or "")
6666 }
6667
6668
6669 def _topic_first_party_candidates(topic: str) -> set[str]:
6670 """Handle-shaped tokens in the topic itself, usable before any retrieval.
6671
6672 Phase 1 runs before automatic handle resolution, and a quick-depth run
6673 skips that resolution entirely, so neither has access to the extracted
6674 handle set. Without this a quick search for "Peter Steinberger steipete"
6675 still drops every post steipete wrote, which is the exact failure this
6676 branch exists to fix.
6677
6678 Deliberately permissive about what looks like a handle and strict about
6679 what it does: a candidate only ever matters if a retrieved post's *author*
6680 matches it, so an ordinary word like "lunch" costs nothing -- no author is
6681 named "lunch". The realistic false positive is an account named after a
6682 topic word, which the frequency-ranked path could surface anyway.
6683 """
6684 tokens = set()
6685 for mention in re.findall(r"@([A-Za-z0-9_]{1,15})", topic or ""):
6686 tokens.add(mention.lower())
6687 for word in re.findall(r"[A-Za-z0-9_]{3,15}", topic or ""):
6688 lowered = word.lower()
6689 # Skip query scaffolding ("review", "news", "latest"): it describes the
6690 # search, not the subject, and rerank._handle_is_topic skips it too.
6691 if lowered not in relevance.STOPWORDS and lowered not in relevance.LOW_SIGNAL_QUERY_TOKENS:
6692 tokens.add(lowered)
6693 return tokens
6694
6695
6696 def _handle_contains_topic_word(handle: str, topic: str) -> bool:
6697 """True when ``handle`` contains a whole topic word of three or more letters.
6698
6699 Covers short subject names that sit inside a longer handle ("vuejs" for
6700 "Vue"), which rerank._handle_is_topic misses because it only counts
6701 containment for words of four or more letters. The containment runs one
6702 way only, so a short fragment of a longer topic word ("go" in "Google")
6703 never matches, and query scaffolding words ("review", "news") are skipped.
6704 """
6705 for word in re.findall(r"[a-z0-9]+", (topic or "").lower()):
6706 if len(word) < 3:
6707 continue
6708 if word in relevance.STOPWORDS or word in relevance.LOW_SIGNAL_QUERY_TOKENS:
6709 continue
6710 if word in handle:
6711 return True
6712 return False
6713
6714
6715 def _name_lane_subject(topic: str) -> str:
6716 """Resolve the entity name to search for by name, not the whole topic.
6717
6718 Phrase-quoting a raw topic ("Peter Steinberger steipete") matches nothing
6719 on X: nobody writes the handle and the display name together. Prefer a
6720 title-cased proper noun the way the planner's keyword query does, and fall
6721 back to the first compound term, then to the topic.
6722 """
6723 import re as _re
6724 compounds = query.extract_compound_terms(topic) or []
6725 title_cased = [
6726 term for term in compounds
6727 if _re.match(r"^(?:[A-Z][a-z]+\s+){1,}[A-Z][a-z]+$", term)
6728 ]
6729 if title_cased:
6730 return title_cased[0]
6731 if compounds:
6732 return compounds[0]
6733 return topic.strip()
6734
6735
6736 def _run_supplemental_searches(
6737 *,
6738 topic: str,
6739 bundle: schema.RetrievalBundle,
6740 plan: schema.QueryPlan,
6741 config: dict[str, Any],
6742 depth: str,
6743 date_range: tuple[str, str],
6744 runtime: schema.ProviderRuntime,
6745 mock: bool,
6746 rate_limited_sources: set[str],
6747 rate_limit_lock: threading.Lock,
6748 x_handle: str | None = None,
6749 x_related: list[str] | None = None,
6750 resolved_handles_out: list[str] | None = None,
6751 ) -> None:
6752 """Phase 2: extract entities from Phase 1 results, run targeted supplemental searches."""
6753 if _research_stopped(config):
6754 return
6755 # The sanitized plan already intersects requested, available, and excluded
6756 # sources. A handle or host envelope must not expand that source boundary.
6757 if not any("x" in subquery.sources for subquery in plan.subqueries):
6758 return
6759 from_date, to_date = date_range
6760
6761 # Host-fetched X lane: the envelope's lane calls replace the backend
6762 # lanes and are served at every depth (the host already paid for them),
6763 # before the quick/mock return and before the chain is recomputed.
6764 # Extracted-handle promotion is skipped on envelope runs; a declared lane
6765 # without an envelope runs no lane at all (the topic stream already
6766 # recorded the not-passed outcome).
6767 if config.get("_x_lane_missing"):
6768 return
6769 envelope = config.get("_x_envelope")
6770 if envelope is not None:
6771 _serve_envelope_lanes(
6772 envelope, bundle=bundle, plan=plan, x_handle=x_handle, x_related=x_related,
6773 from_date=from_date, to_date=to_date,
6774 )
6775 return
6776
6777 if depth == "quick" or mock:
6778 return
6779
6780 # Convert SourceItems to dicts for entity_extract. All X items (whatever
6781 # backend fetched them — bird, xai, xurl, xquik) land under the single "x"
6782 # slug, so this reads the whole X corpus.
6783 x_dicts = [
6784 {"author_handle": item.author or "", "text": item.body or ""}
6785 for item in bundle.items_by_source.get("x", [])
6786 if entity_extract.matches_person_identity(
6787 item, plan.person_identity_anchors, x_handle,
6788 person_run=getattr(plan, "person_run", False),
6789 )
6790 ]
6791 reddit_dicts = [
6792 {
6793 "subreddit": item.container or "",
6794 "comment_insights": item.metadata.get("comment_insights", []),
6795 "top_comments": [
6796 {"excerpt": c.get("excerpt", c.get("text", ""))}
6797 for c in (item.metadata.get("top_comments") or [])
6798 if isinstance(c, dict)
6799 ],
6800 }
6801 for item in bundle.items_by_source.get("reddit", [])
6802 ]
6803
6804 if not x_dicts and not reddit_dicts and not x_handle and not x_related:
6805 return
6806
6807 entities = entity_extract.extract_entities(
6808 reddit_dicts, x_dicts,
6809 max_handles=3, max_subreddits=3,
6810 )
6811
6812 handles = entities.get("x_handles", [])
6813
6814 # Add explicit --x-handle if provided
6815 if x_handle:
6816 handle_clean = x_handle.lstrip("@").lower()
6817 if handle_clean not in [h.lower() for h in handles]:
6818 handles.insert(0, handle_clean)
6819
6820 # Collect related handles (searched separately with lower weight)
6821 related_handles = []
6822 if x_related:
6823 primary_lower = x_handle.lstrip("@").lower() if x_handle else ""
6824 for rh in x_related:
6825 rh_clean = rh.lstrip("@").lower().strip()
6826 if rh_clean and rh_clean != primary_lower and rh_clean not in [h.lower() for h in handles]:
6827 related_handles.append(rh_clean)
6828
6829 # Surface every handle this run resolved back to the caller. resolved_handles
6830 # is built later from --x-handle / --github-user / --x-related only, so
6831 # without this an auto-discovered subject handle never reaches it and every
6832 # downstream first-party protection (entity-miss exemption, FIRST_PARTY_FLOOR,
6833 # interaction floor) stays inert on any run that did not pass --x-handle.
6834 # Populated before the early return below so a run whose lanes cannot execute
6835 # still contributes its resolved handles.
6836 if resolved_handles_out is not None:
6837 # Only corroborated handles get first-party status. The extracted set is
6838 # frequency-ranked over retrieved post text, so a prolific commentator --
6839 # or an engagement-farming account that posts on every topic -- lands in
6840 # it without being the subject. First-party status is strong: it exempts
6841 # an author from the relevance floor entirely and raises their per-author
6842 # cap, so granting it on frequency alone would let a spam account buy
6843 # immunity from filtering. Require the handle to look like the topic's
6844 # subject, or to have been named explicitly by the user.
6845 explicit = {
6846 h.lstrip("@").strip().lower()
6847 for h in ([x_handle] + list(x_related or []))
6848 if h and h.strip()
6849 }
6850 seen = {h.lower() for h in resolved_handles_out}
6851 for h in [*handles, *related_handles]:
6852 clean = h.lstrip("@").strip().lower()
6853 if not clean or clean in seen:
6854 continue
6855 # "Looks like the topic's subject" is rerank's test: a handle that
6856 # contains a topic word or is spelled from word prefixes. A bare
6857 # substring match either way admitted fragments ("go" for "Google")
6858 # and missed real subjects ("steipete" for "Peter Steinberger").
6859 # Rerank's containment needs a 4+ letter word, so a short subject
6860 # name inside a longer handle ("vuejs" for "Vue") is added here.
6861 corroborated = (
6862 clean in explicit
6863 or rerank._handle_is_topic(clean, topic)
6864 or _handle_contains_topic_word(clean, topic)
6865 )
6866 if corroborated:
6867 resolved_handles_out.append(clean)
6868 seen.add(clean)
6869
6870 if not handles and not related_handles:
6871 return
6872
6873 # Pick the X handle-search backend: the first handle-capable backend in the
6874 # chain (grok, bird, xapi, or xquik). These supplemental from:/mentions lanes are
6875 # complementary to the topic search, so when the topic primary can't run
6876 # them (xai/xurl have no handle-lane implementation) but a capable backend
6877 # is available, use it rather than skipping Phase 2. bird scrapes X GraphQL
6878 # with the user's browser cookies; xquik runs the same lanes over its REST
6879 # API. All items land under the single "x" slug.
6880 x_slug = "x"
6881
6882 def _record_handle_lane_failures(lane: str, failures: list[str]) -> bool:
6883 """Surface handle-lane failures the adapter would otherwise swallow.
6884
6885 bird and xquik report a per-handle failure by returning no items, so an
6886 empty lane is indistinguishable from a subject who simply did not post.
6887 Left unrecorded, the run reports the X source as a clean zero and the
6888 report states as fact that nothing was posted.
6889
6890 Returns True when the failure is auth-shaped, so the caller's existing
6891 AUTH_FAILED branch owns the message and the fix hint. Everything else
6892 (timeout, spawn failure, non-zero exit, bad JSON) is recorded here.
6893 ``record_failure`` keeps already-returned items as partial.
6894 """
6895 if not failures:
6896 return False
6897 detail = "; ".join(failures[:3])
6898 if len(failures) > 3:
6899 detail += f" (+{len(failures) - 3} more)"
6900 # Only xquik reports an auth-shaped handle-lane failure; bird's are all
6901 # transport (timeout / spawn / exit / JSON). Match the two phrases
6902 # xquik._execute_search actually emits rather than adding a fifth
6903 # copy of this repo's auth-marker vocabulary.
6904 lowered = detail.lower()
6905 if "auth failed" in lowered or "key unpaid" in lowered:
6906 return True
6907 bundle.record_failure(
6908 x_slug,
6909 health.TIMEOUT if any(marker in lowered for marker in ("timed out", "cancelled")) else health.UNREACHABLE,
6910 f"Phase 2 {lane}-lane: {detail}",
6911 attempted=True,
6912 )
6913 return False
6914
6915 chain = env.x_backend_chain(config)
6916 # Trust an explicit runtime backend as the head of the chain.
6917 pinned = runtime.x_search_backend
6918 if pinned:
6919 chain = [pinned] + [b for b in chain if b != pinned]
6920 primary = next((b for b in chain if b in ("grok", "bird", "xapi", "xquik")), None)
6921
6922 # Name lane (posts naming the subject in plain text, no @-mention) is
6923 # grok-only for now: it needs phrase-quoting and negation operators the
6924 # other handle-capable backends do not expose uniformly. It is NOT a
6925 # fallback for the mention lane -- most discussion of a person or company
6926 # never @-mentions them, so the two lanes reach disjoint sets.
6927 _name_lane = None
6928 cancel = config.get("_enrich_cancel")
6929 # Both supplemental budgets clamp to the run's recorded finalization cutoff:
6930 # the lanes run after the main collection, so their own budget alone could
6931 # outlive the window the raised X stream wait was capped to.
6932 supplemental_deadline = _x_lane_deadline(config, x_api.LANE_BUDGET_SECONDS)
6933
6934 if primary == "grok":
6935 # One budget shared by all three lanes, started here rather than per
6936 # lane: the point is to bound the total, not each part.
6937 lane_deadline = _x_lane_deadline(config, grok_x.LANE_BUDGET_SECONDS)
6938
6939 def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:
6940 items, revoked = grok_x.search_handles(
6941 hs, topic, from_date, to_date, count_per=count,
6942 deadline=lane_deadline, and_topic=and_topic, cancel=cancel,
6943 )
6944 return items, revoked
6945
6946 def _about_lane(hs: list, count: int) -> tuple[list, bool]:
6947 items, revoked = grok_x.search_mentions(
6948 hs, from_date, to_date, topic=topic, count_per=count,
6949 deadline=lane_deadline, cancel=cancel,
6950 )
6951 return items, revoked
6952
6953 def _name_lane(hs: list, count: int) -> tuple[list, bool]:
6954 # Use the resolved entity name, not the raw topic. Phrase-quoting
6955 # the whole topic ("Peter Steinberger steipete") matches nothing on
6956 # X; the subject's name is what other people actually write.
6957 subject = _name_lane_subject(topic)
6958 if not subject.strip():
6959 return [], False
6960 items, revoked = grok_x.search_name(
6961 subject, from_date, to_date, exclude_handles=hs, count_per=count,
6962 deadline=lane_deadline, cancel=cancel,
6963 )
6964 return items, revoked
6965 elif primary == "bird":
6966 def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:
6967 # bird_x.search_handles doesn't support and_topic yet
6968 failures: list[str] = []
6969 items = bird_x.search_handles(
6970 hs, topic, from_date, count_per=count, failure_out=failures,
6971 to_date=to_date, deadline=supplemental_deadline, cancel=cancel,
6972 )
6973 return items, _record_handle_lane_failures("FROM", failures)
6974
6975 def _about_lane(hs: list, count: int) -> tuple[list, bool]:
6976 failures: list[str] = []
6977 items = bird_x.search_mentions(
6978 hs, from_date, count_per=count, failure_out=failures,
6979 to_date=to_date, deadline=supplemental_deadline, cancel=cancel,
6980 )
6981 return items, _record_handle_lane_failures("ABOUT", failures)
6982 elif primary == "xapi":
6983 # Direct X API v2 with the app-only bearer: from:/@ lanes run over
6984 # search/all with the recent-search fallback. One budget shared by
6985 # every lane below (same shape as the grok lanes): a slow key bounds
6986 # the whole supplemental phase, not each call.
6987 xapi_token = config.get("X_BEARER_TOKEN") or ""
6988 xapi_deadline = supplemental_deadline
6989
6990 xapi_fatal_payment = False
6991
6992 def _xapi_lane_receipt(lane_warnings: list[str]) -> None:
6993 # A deadline stop is incomplete coverage, reported in
6994 # report.warnings (the x_partial_coverage artifact), never a
6995 # healthy-looking silence and never a source failure.
6996 sink = bundle.artifacts.setdefault("x_partial_coverage", [])
6997 for note in lane_warnings:
6998 line = f"X handle lanes: {note}"
6999 if line not in sink:
7000 sink.append(line)
7001
7002 def _record_xapi_lane_errors(lane: str, lane_errors: list[str]) -> bool:
7003 nonlocal xapi_fatal_payment
7004 if not lane_errors:
7005 return False
7006 detail = "; ".join(lane_errors[:3])
7007 if len(lane_errors) > 3:
7008 detail += f" (+{len(lane_errors) - 3} more)"
7009 winning_state = min(
7010 (http.classify_failure(message=err) for err in lane_errors),
7011 key=lambda st: _FAILURE_SPECIFICITY.get(st, 9),
7012 )
7013 if winning_state == health.AUTH_FAILED:
7014 return True
7015 if winning_state == health.PAYMENT_REQUIRED:
7016 xapi_fatal_payment = True
7017 bundle.record_failure(
7018 x_slug,
7019 winning_state,
7020 f"Phase 2 {lane}-lane: {detail}",
7021 attempted=True,
7022 )
7023 return False
7024
7025 def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:
7026 if xapi_fatal_payment:
7027 return [], False
7028 # x_api.search_handles doesn't support and_topic; topic ranks only
7029 lane_warnings: list[str] = []
7030 lane_errors: list[str] = []
7031 items = x_api.search_handles(
7032 hs, topic, from_date, to_date, count_per=count, token=xapi_token,
7033 deadline=xapi_deadline, warnings=lane_warnings, errors=lane_errors, cancel=cancel,
7034 )
7035 _xapi_lane_receipt(lane_warnings)
7036 return items, _record_xapi_lane_errors("FROM", lane_errors)
7037
7038 def _about_lane(hs: list, count: int) -> tuple[list, bool]:
7039 if xapi_fatal_payment:
7040 return [], False
7041 lane_warnings: list[str] = []
7042 lane_errors: list[str] = []
7043 items = x_api.search_mentions(
7044 hs, from_date, to_date, topic=topic, count_per=count, token=xapi_token,
7045 deadline=xapi_deadline, warnings=lane_warnings, errors=lane_errors, cancel=cancel,
7046 )
7047 _xapi_lane_receipt(lane_warnings)
7048 return items, _record_xapi_lane_errors("ABOUT", lane_errors)
7049 elif primary == "xquik":
7050 xquik_token = env.get_xquik_token(config)
7051
7052 def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:
7053 # xquik.search_handles doesn't support and_topic yet
7054 failures: list[str] = []
7055 items = xquik.search_handles(
7056 hs, topic, from_date, to_date, count_per=count, token=xquik_token,
7057 failure_out=failures, deadline=supplemental_deadline, cancel=cancel,
7058 )
7059 return items, _record_handle_lane_failures("FROM", failures)
7060
7061 def _about_lane(hs: list, count: int) -> tuple[list, bool]:
7062 failures: list[str] = []
7063 items = xquik.search_mentions(
7064 hs, from_date, to_date, topic=topic, count_per=count,
7065 token=xquik_token, failure_out=failures, deadline=supplemental_deadline, cancel=cancel,
7066 )
7067 return items, _record_handle_lane_failures("ABOUT", failures)
7068 else:
7069 return # primary X backend has no handle-lane support (xai/xurl) or none configured
7070
7071 def _guard_lane(lane):
7072 def guarded(*args, **kwargs):
7073 if _research_stopped(config) or time.monotonic() >= supplemental_deadline:
7074 if primary == "xapi":
7075 _xapi_lane_receipt([x_api.DEADLINE_DETAIL])
7076 else:
7077 bundle.record_failure(x_slug, health.TIMEOUT, "X supplemental research cancelled or timed out", attempted=True)
7078 return [], False
7079 return lane(*args, **kwargs)
7080 return guarded
7081
7082 _from_lane = _guard_lane(_from_lane)
7083 _about_lane = _guard_lane(_about_lane)
7084 if _name_lane is not None:
7085 _name_lane = _guard_lane(_name_lane)
7086
7087 # Skip if the X source is rate-limited.
7088 if x_slug in rate_limited_sources:
7089 return
7090
7091 # Collect existing URLs for deduplication
7092 existing_urls = {
7093 item.url
7094 for items in bundle.items_by_source.values()
7095 for item in items
7096 if item.url
7097 }
7098
7099 ranking_query = plan.subqueries[0].ranking_query if plan.subqueries else topic
7100 primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
7101
7102 # Split FROM promotion: determine which handles get FROM lane and how.
7103 # - Primary explicit handle (--x-handle): always FROM, no AND topic, full weight
7104 # - x_related handles: searched separately with lower weight (0.3), kept in
7105 # related_handles variable for the supplemental-related section below
7106 # - Extracted handles: FROM only if ≥2 on-topic hits AND ratio ≥0.5,
7107 # and those pulls DO AND the topic (from:handle Rome)
7108 primary_explicit = [x_handle] if x_handle else []
7109
7110 explicit_promotable, extracted_promotable = x_judge.promotable_handles(
7111 x_dicts, # Phase 1 X items for judging
7112 topic,
7113 handles, # entity_extract handles
7114 explicit_handles=primary_explicit,
7115 ranking_query=ranking_query,
7116 )
7117
7118 # All promotable handles for ABOUT and NAME lanes (primary only, not related)
7119 all_promotable = list(set(explicit_promotable + extracted_promotable))
7120
7121 # Search primary handles (full weight): FROM lane (their own tweets) +
7122 # ABOUT lane (tweets mentioning them). Both engagement-weighted and deduped
7123 # by URL at normalize time.
7124 any_revoked = False # Track auth revocation across lanes
7125 if all_promotable:
7126 # Independent try/except per lane so a failure in one does not discard
7127 # the other's already-computed results.
7128 from_items: list = []
7129 about_items: list = []
7130 about_revoked = False
7131 name_revoked = False
7132
7133 # FROM lane: explicit handles without AND topic (person posts omit their own name)
7134 if explicit_promotable:
7135 try:
7136 explicit_items, explicit_revoked = _from_lane(explicit_promotable, FROM_LANE_COUNT_PER, and_topic=False)
7137 from_items.extend(explicit_items)
7138 if explicit_revoked:
7139 any_revoked = True
7140 bundle.record_failure(
7141 x_slug, schema.AUTH_FAILED,
7142 f"Phase 2 FROM-lane (explicit): {primary} authentication failed (session expired, revoked, or key unpaid)",
7143 attempted=True,
7144 )
7145 except Exception as exc:
7146 print(f"[Pipeline] Phase 2 FROM-lane (explicit) failed: {exc}", file=sys.stderr)
7147 state, attempted = _classify_source_failure(exc)
7148 if state == schema.AUTH_FAILED:
7149 any_revoked = True
7150 bundle.record_failure(
7151 x_slug, state, f"Phase 2 FROM-lane (explicit): {exc}", attempted=attempted,
7152 )
7153
7154 # FROM lane: extracted handles WITH AND topic (from:handle Rome)
7155 if extracted_promotable and not any_revoked:
7156 try:
7157 extracted_items, extracted_revoked = _from_lane(extracted_promotable, FROM_LANE_COUNT_PER, and_topic=True)
7158 from_items.extend(extracted_items)
7159 if extracted_revoked:
7160 any_revoked = True
7161 bundle.record_failure(
7162 x_slug, schema.AUTH_FAILED,
7163 f"Phase 2 FROM-lane (extracted): {primary} authentication failed (session expired, revoked, or key unpaid)",
7164 attempted=True,
7165 )
7166 except Exception as exc:
7167 print(f"[Pipeline] Phase 2 FROM-lane (extracted) failed: {exc}", file=sys.stderr)
7168 state, attempted = _classify_source_failure(exc)
7169 if state == schema.AUTH_FAILED:
7170 any_revoked = True
7171 bundle.record_failure(
7172 x_slug, state, f"Phase 2 FROM-lane (extracted): {exc}", attempted=attempted,
7173 )
7174
7175 if not any_revoked:
7176 try:
7177 about_items, about_revoked = _about_lane(all_promotable, MENTION_LANE_COUNT_PER)
7178 if about_revoked:
7179 any_revoked = True
7180 bundle.record_failure(
7181 x_slug, schema.AUTH_FAILED,
7182 f"Phase 2 ABOUT-lane: {primary} authentication failed (session expired, revoked, or key unpaid)",
7183 attempted=True,
7184 )
7185 except Exception as exc:
7186 print(f"[Pipeline] Phase 2 ABOUT-lane search failed: {exc}", file=sys.stderr)
7187 state, attempted = _classify_source_failure(exc)
7188 if state == schema.AUTH_FAILED:
7189 any_revoked = True
7190 bundle.record_failure(
7191 x_slug,
7192 state,
7193 f"Phase 2 ABOUT-lane: {exc}",
7194 attempted=attempted,
7195 )
7196 name_items: list = []
7197 if _name_lane is not None and not any_revoked:
7198 try:
7199 name_items, name_revoked = _name_lane(all_promotable, MENTION_LANE_COUNT_PER)
7200 if name_revoked:
7201 any_revoked = True
7202 bundle.record_failure(
7203 x_slug, schema.AUTH_FAILED,
7204 f"Phase 2 NAME-lane: {primary} authentication failed (session expired, revoked, or key unpaid)",
7205 attempted=True,
7206 )
7207 except Exception as exc:
7208 print(f"[Pipeline] Phase 2 NAME-lane search failed: {exc}", file=sys.stderr)
7209 state, attempted = _classify_source_failure(exc)
7210 if state == schema.AUTH_FAILED:
7211 any_revoked = True
7212 bundle.record_failure(
7213 x_slug, state, f"Phase 2 NAME-lane: {exc}", attempted=attempted,
7214 )
7215
7216 raw_items = from_items + about_items + name_items
7217
7218 # Partial coverage is a reportable outcome, not a normal result: a
7219 # report carrying only one side of an entity topic is incomplete, and
7220 # without this it looks indistinguishable from genuinely thin
7221 # discussion.
7222 if _name_lane is not None and not any_revoked:
7223 empty = [
7224 label for label, items in
7225 (("by", from_items), ("mention", about_items), ("name", name_items))
7226 if not items
7227 ]
7228 if empty and len(empty) < 3:
7229 # A warning, not a source outcome. record_failure would set the
7230 # X source to PARTIAL, which is outside _STRICT_EXIT_OK_STATES
7231 # and would make wrappers using LAST30DAYS_STRICT_EXIT exit 3 on
7232 # runs that returned perfectly good X coverage. An empty lane is
7233 # common and legitimate: the name lane carries an engagement
7234 # floor and the mention lane is empty for most non-famous
7235 # handles.
7236 bundle.artifacts.setdefault("x_partial_coverage", []).append(
7237 f"X partial coverage: {', '.join(empty)} lane(s) returned "
7238 "nothing; the report may show only one side of this entity."
7239 )
7240
7241 if raw_items:
7242 # First-party handles: only primary explicit handle, not promoted commentators
7243 # (first-party exempts from relevance floor; granting to commentators
7244 # would let junk become un-prunable)
7245 first_party_for_normalize = list(set(
7246 h.lower().lstrip("@") for h in primary_explicit if h
7247 ))
7248 normalized = _normalize_score_dedupe(
7249 x_slug, raw_items, from_date, to_date,
7250 freshness_mode=plan.freshness_mode,
7251 ranking_query=ranking_query,
7252 first_party_handles=first_party_for_normalize,
7253 )
7254 # Deduplicate against Phase 1 URLs
7255 normalized = [item for item in normalized if item.url not in existing_urls]
7256 if normalized:
7257 bundle.add_items(primary_label, x_slug, normalized)
7258 # Update existing URLs for related-handle dedup
7259 for item in normalized:
7260 if item.url:
7261 existing_urls.add(item.url)
7262
7263 # Search related handles with lower weight (0.3)
7264 # Related handles are explicit (--x-related), so FROM without AND topic.
7265 if related_handles and not any_revoked:
7266 try:
7267 raw_items, rel_revoked = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER, and_topic=False)
7268 if rel_revoked:
7269 any_revoked = True
7270 bundle.record_failure(
7271 x_slug, schema.AUTH_FAILED,
7272 f"Phase 2 related handle search: {primary} authentication failed (session expired, revoked, or key unpaid)",
7273 attempted=True,
7274 )
7275 except Exception as exc:
7276 print(f"[Pipeline] Phase 2 related handle search failed: {exc}", file=sys.stderr)
7277 state, attempted = _classify_source_failure(exc)
7278 if state == schema.AUTH_FAILED:
7279 any_revoked = True
7280 bundle.record_failure(
7281 x_slug,
7282 state,
7283 f"Phase 2 related handle search: {exc}",
7284 attempted=attempted,
7285 )
7286 raw_items = []
7287
7288 if raw_items:
7289 normalized = _normalize_score_dedupe(
7290 x_slug, raw_items, from_date, to_date,
7291 freshness_mode=plan.freshness_mode,
7292 ranking_query=ranking_query,
7293 first_party_handles=related_handles,
7294 )
7295 # Deduplicate against all existing URLs (Phase 1 + primary handles)
7296 normalized = [item for item in normalized if item.url not in existing_urls]
7297 if normalized:
7298 # Use a separate subquery label with lower weight so RRF
7299 # scores related-handle results below primary results.
7300 bundle.add_items("supplemental-related", x_slug, normalized)
7301 # Register the supplemental-related label in the plan for fusion
7302 if not any(sq.label == "supplemental-related" for sq in plan.subqueries):
7303 plan.subqueries.append(
7304 schema.SubQuery(
7305 label="supplemental-related",
7306 search_query=", ".join(related_handles),
7307 ranking_query=ranking_query,
7308 sources=[x_slug],
7309 weight=0.3,
7310 )
7311 )
7312
7313
7314 def _retry_thin_sources(
7315 *,
7316 topic: str,
7317 bundle: schema.RetrievalBundle,
7318 plan: schema.QueryPlan,
7319 config: dict[str, Any],
7320 depth: str,
7321 date_range: tuple[str, str],
7322 runtime: schema.ProviderRuntime,
7323 mock: bool,
7324 rate_limited_sources: set[str],
7325 rate_limit_lock: threading.Lock,
7326 settings: dict[str, Any],
7327 web_backend: str = "auto",
7328 skip_sources: set[str] | None = None,
7329 subreddits: list[str] | None = None,
7330 tiktok_hashtags: list[str] | None = None,
7331 tiktok_creators: list[str] | None = None,
7332 ig_creators: list[str] | None = None,
7333 first_party_handles: Iterable[str] | None = None,
7334 first_party_by_source: Mapping[str, Iterable[str]] | None = None,
7335 run_started: float | None = None,
7336 out_of_time_sources: set[str] | None = None,
7337 ) -> None:
7338 """Retry sources with thin results using simplified core subject query.
7339
7340 Sources whose retry ran out of time are added to ``out_of_time_sources``.
7341 """
7342 if depth == "quick":
7343 return
7344 # No new paid/network work after the enrichment budget expired.
7345 if _research_stopped(config):
7346 return
7347 config = dict(config)
7348 config["_research_deadline"] = _research_deadline(config, THIN_RETRY_FUTURE_TIMEOUT_SECONDS)
7349
7350 planned_sources: list[str] = []
7351 for subquery in plan.subqueries:
7352 for source in subquery.sources:
7353 if source not in planned_sources:
7354 planned_sources.append(source)
7355 _skip = (skip_sources or set()) | THIN_RETRY_EXEMPT
7356 thin_sources = [
7357 source
7358 for source in planned_sources
7359 if len(bundle.items_by_source.get(source, [])) < 3
7360 and source not in bundle.errors_by_source
7361 and source not in _skip
7362 ]
7363
7364 if not thin_sources:
7365 return
7366
7367 core = query.extract_core_subject(topic, max_words=3)
7368 if not core:
7369 return
7370 # Note: we intentionally do NOT skip when core == topic. For short topics
7371 # like "Kanye West", the 3-word core IS the topic — but the planner may
7372 # have sent a different (worse) query to the source. Retrying with the
7373 # raw core subject is still valuable.
7374
7375 from_date, to_date = date_range
7376
7377 # Create a retry subquery with the simplified core subject
7378 retry_subquery = schema.SubQuery(
7379 label="retry",
7380 search_query=core,
7381 ranking_query=f"What recent evidence from the last 30 days matters for {core}?",
7382 sources=thin_sources,
7383 weight=0.3,
7384 )
7385
7386 def _retry_one_source(
7387 source: str,
7388 ) -> tuple[
7389 str, list[schema.SourceItem], dict[str, Any] | None, tuple, bool, dict[str, Any] | None,
7390 ]:
7391 raw_items, artifact = _retrieve_stream(
7392 topic=topic,
7393 subquery=retry_subquery,
7394 source=source,
7395 config=config,
7396 depth=depth,
7397 date_range=date_range,
7398 runtime=runtime,
7399 mock=mock,
7400 rate_limited_sources=rate_limited_sources,
7401 rate_limit_lock=rate_limit_lock,
7402 web_backend=web_backend,
7403 raw_topic=topic,
7404 subreddits=subreddits,
7405 tiktok_hashtags=tiktok_hashtags,
7406 tiktok_creators=tiktok_creators,
7407 ig_creators=ig_creators,
7408 run_started=run_started,
7409 # Skip Amazon review enrichment here to avoid duplicate Bright Data
7410 # pulls for ASINs already enriched in Phase 1. Finalize will enrich
7411 # any genuinely new products that weren't in Phase 1.
7412 skip_amazon_enrichment=True,
7413 freshness_mode=plan.freshness_mode,
7414 )
7415 outcome_note = artifact.get("_source_outcome") if isinstance(artifact, dict) else None
7416 detail_note = artifact.get("_source_outcome_detail") if isinstance(artifact, dict) else None
7417 detail_state = artifact.get("_source_outcome_detail_state") if isinstance(artifact, dict) else None
7418 out_of_time = isinstance(artifact, dict) and bool(artifact.get("_source_out_of_time"))
7419 bar_notes: list[str] = []
7420 normalized = _normalize_score_dedupe(
7421 source,
7422 raw_items,
7423 from_date,
7424 to_date,
7425 freshness_mode=plan.freshness_mode,
7426 ranking_query=retry_subquery.ranking_query,
7427 first_party_handles=first_party_handles,
7428 first_party_by_source=first_party_by_source,
7429 # Match Phase 1: X defers its relevance floor until the run has
7430 # resolved handles. Applying it here would discard a subject-
7431 # authored post that does not repeat the subject's name, and the
7432 # later resolved-handle floor cannot recover a post that never
7433 # entered the bundle.
7434 defer_relevance_prune=(source == "x"),
7435 before_dedupe=_digg_bar_before_dedupe(
7436 settings, topic, retry_subquery.label, bar_notes,
7437 ) if source == "digg" else None,
7438 )
7439 if source == "jobs":
7440 return (
7441 source, normalized, outcome_note, (detail_note, detail_state), out_of_time,
7442 (artifact, list(raw_items)) if _is_jobs_board(source, artifact) else None,
7443 )
7444 if source == "digg":
7445 normalized, _ = _apply_digg_bar(
7446 normalized, settings, topic, retry_subquery.label,
7447 )
7448 for bar_note in bar_notes:
7449 detail_note = f"{detail_note}; {bar_note}" if detail_note else bar_note
7450 else:
7451 normalized = _apply_reddit_stream_keepers(
7452 source, normalized, settings["per_stream_limit"], topic
7453 )
7454 if isinstance(artifact, dict) and artifact.get("_source_outcome_deferred"):
7455 outcome_note = outcome_note or artifact["_source_outcome_deferred"]
7456 if not normalized and isinstance(artifact, dict):
7457 outcome_note = outcome_note or artifact.get("_source_outcome_if_empty")
7458 return source, normalized, outcome_note, (detail_note, detail_state), out_of_time, None
7459
7460 retryable = [s for s in thin_sources if s not in rate_limited_sources]
7461
7462 with _abandoning_executor(max_workers=min(4, len(retryable) or 1)) as executor:
7463 futures = {executor.submit(_retry_one_source, s): s for s in retryable}
7464 done, not_done = _wait_for_research(futures, config)
7465 for future in not_done:
7466 source = futures[future]
7467 future.cancel()
7468 if future.done() and not future.cancelled():
7469 done.add(future)
7470 continue
7471 detail = f"{source} timed out after {THIN_RETRY_FUTURE_TIMEOUT_SECONDS:g}s"
7472 print(f"[Pipeline] Retry timed out for {source}: {detail}", file=sys.stderr)
7473 bundle.record_failure(source, health.TIMEOUT, f"Simplified-query retry failed: {detail}", attempted=True)
7474 for future in done:
7475 source = futures[future]
7476 try:
7477 (
7478 source, normalized, outcome_note, (detail_note, detail_state), out_of_time,
7479 jobs_board,
7480 ) = future.result(timeout=0)
7481 except Exception as exc:
7482 print(f"[Pipeline] Retry failed for {source}: {type(exc).__name__}: {exc}", file=sys.stderr)
7483 _record_reddit_exception_notes(bundle, source, exc)
7484 state, attempted = _classify_source_failure(exc)
7485 bundle.record_failure(
7486 source,
7487 state,
7488 f"Simplified-query retry failed: {exc}",
7489 attempted=attempted,
7490 )
7491 continue
7492 if out_of_time and out_of_time_sources is not None:
7493 out_of_time_sources.add(source)
7494 try:
7495 if outcome_note:
7496 bundle.record_failure(
7497 source,
7498 outcome_note["state"],
7499 outcome_note["detail"],
7500 attempted=outcome_note.get("attempted", True),
7501 )
7502 if detail_note:
7503 bundle.record_detail(source, detail_note, state=detail_state)
7504 existing_urls = {item.url for item in bundle.items_by_source.get(source, []) if item.url}
7505 new_items = [item for item in normalized if item.url not in existing_urls]
7506
7507 if new_items:
7508 primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
7509 bundle.add_items(primary_label, source, new_items)
7510 # A board read only on this retry still gives the footer its
7511 # counts and the report its digest.
7512 if jobs_board and "jobs" not in bundle.artifacts:
7513 bundle.artifacts["jobs"] = _jobs_board_artifact(jobs_board[0])
7514 bundle.jobs_board_rows = jobs_board[1]
7515 except Exception as exc:
7516 print(f"[Pipeline] Retry failed for {source}: {type(exc).__name__}: {exc}", file=sys.stderr)
7517 state, attempted = _classify_source_failure(exc)
7518 bundle.record_failure(
7519 source,
7520 state,
7521 f"Simplified-query retry failed: {exc}",
7522 attempted=attempted,
7523 )
7524
7525
7526 def _fetch_x_backend(backend, query, from_date, to_date, depth, config, warnings=None, deadline=None):
7527 """Fetch X items from a single backend. Returns (items, error_str).
7528
7529 ``warnings``, when given, collects backend receipts that are not
7530 failures (Bird's skipped optional retries or xapi's recent-search window
7531 truncation) so the X branch can surface them as run artifacts.
7532 ``deadline`` is the chain's shared ``time.monotonic()`` budget; backends
7533 that accept one (bird/grok/xai/xurl/xquik/xapi) clamp their waits to the
7534 time left.
7535
7536 Backends are tried in priority order by the caller (env.x_backend_chain);
7537 a non-empty error_str signals a hard failure (auth/payment/etc.) so the
7538 caller can fail over to the next backend or surface the error honestly.
7539
7540 For grok, auth_revoked signals mid-run session revocation: the error
7541 string includes "grok session expired" so _classify_source_failure maps
7542 it to AUTH_FAILED with a proper fix hint, distinct from "never signed in".
7543
7544 The ``query`` parameter is the compiled search query - typically
7545 ``raw_topic or topic`` (like Reddit/YouTube), NOT the planner's
7546 ``search_query`` which may contain operator strings like "Rome Italy".
7547 """
7548 if _research_stopped(config) or (deadline is not None and time.monotonic() >= deadline):
7549 return [], "X research cancelled or timed out"
7550 cancel = config.get("_enrich_cancel")
7551 if backend == "bird":
7552 result = bird_x.search_x(query, from_date, to_date, depth=depth, deadline=deadline, cancel=cancel)
7553 items = bird_x.parse_bird_response(result, query=query)
7554 elif backend == "grok":
7555 result = grok_x.search_x(
7556 query, from_date, to_date, depth=depth, deadline=deadline,
7557 cancel=config.get("_enrich_cancel"),
7558 )
7559 items = result.get("items", []) if isinstance(result, dict) else []
7560 if isinstance(result, dict) and result.get("auth_revoked"):
7561 err = result.get("error") or "grok session expired or was revoked"
7562 return items, f"grok: {err}"
7563 elif backend == "xai":
7564 model = config.get("LAST30DAYS_X_MODEL") or config.get("XAI_MODEL_PIN") or providers.XAI_DEFAULT
7565 result = xai_x.search_x(config["XAI_API_KEY"], model, query, from_date, to_date, depth=depth, deadline_monotonic=deadline, cancel=cancel)
7566 items = xai_x.parse_x_response(result, from_date=from_date, to_date=to_date)
7567 elif backend == "xurl":
7568 result = xurl_x.search_x(query, depth=depth, deadline=deadline)
7569 items = xurl_x.parse_x_response(result, topic=query)
7570 elif backend == "xquik":
7571 result = xquik.search_xquik(query, from_date, to_date, depth=depth, token=env.get_xquik_token(config), deadline=deadline, cancel=cancel)
7572 items = xquik.parse_xquik_response(result)
7573 elif backend == "xapi":
7574 result = x_api.search_x(config.get("X_BEARER_TOKEN") or "", query, from_date, to_date, depth=depth, deadline=deadline, cancel=cancel)
7575 items = result.get("items", []) if isinstance(result, dict) else []
7576 else:
7577 return [], f"unknown X backend: {backend}"
7578 warning = result.get("warning") if isinstance(result, dict) else None
7579 if warning:
7580 print(f"[X] {backend}: {warning}", file=sys.stderr)
7581 if warnings is not None:
7582 warnings.append(f"X: {backend} {warning}")
7583 err = result.get("error") if isinstance(result, dict) else ""
7584 return items, (err or "")
7585
7586
7587 def _attempt_x_backend(backend, query, from_date, to_date, depth, config, warnings=None, deadline=None):
7588 try:
7589 items, error = _fetch_x_backend(
7590 backend, query, from_date, to_date, depth, config,
7591 warnings=warnings, deadline=deadline,
7592 )
7593 except http.HTTPError as exc:
7594 detail = str(exc)
7595 cause = (
7596 f"HTTP {exc.status_code}"
7597 if exc.status_code is not None
7598 else {
7599 health.AUTH_FAILED: "authentication failed",
7600 health.PAYMENT_REQUIRED: "payment required",
7601 health.RATE_LIMITED: "rate limited",
7602 health.TIMEOUT: "timed out",
7603 health.UNREACHABLE: "connection error",
7604 health.SCHEMA_DRIFT: "invalid JSON",
7605 }.get(exc.outcome_state)
7606 )
7607 if cause and cause.lower() not in detail.lower():
7608 detail = f"{cause}: {detail}"
7609 return [], detail, exc.outcome_state
7610 except Exception as exc:
7611 detail = f"{type(exc).__name__}: {exc}"
7612 if isinstance(exc, TimeoutError):
7613 state = health.TIMEOUT
7614 elif backend == "bird":
7615 state = bird_x.classify_run_failure(detail)
7616 else:
7617 state = _classify_source_failure(exc)[0]
7618 return [], detail, state
7619 detail = str(error or "")
7620 if not detail:
7621 return items, "", None
7622 state = (
7623 bird_x.classify_run_failure(detail)
7624 if backend == "bird"
7625 else _classify_source_failure(SourceRunError(detail))[0]
7626 )
7627 return items, detail, state
7628
7629
7630 def _reddit_post_key(item: dict) -> str:
7631 """Stable per-thread dedupe key (base36 post id from the url/permalink)."""
7632 url = item.get("url") or item.get("permalink") or ""
7633 m = re.search(r"/comments/([A-Za-z0-9]+)", url)
7634 return m.group(1) if m else url
7635
7636
7637 def _merge_reddit_items(free: list[dict], sc: list[dict]) -> list[dict]:
7638 """Merge free + ScrapeCreators Reddit items, free first, deduped by post id.
7639
7640 Used when the thinness-floor trigger backfills a thin free run with SC, so a
7641 thread present in both is never double-listed. A thread both hold keeps the
7642 free copy, with SC's live score and comments folded in field by field, so
7643 a pending or unknown archive score never hides the live one.
7644 """
7645 from . import reddit_hydrate
7646
7647 merged = list(free)
7648 by_key = {_reddit_post_key(it): it for it in free}
7649 for it in sc:
7650 key = _reddit_post_key(it)
7651 if not key:
7652 continue
7653 existing = by_key.get(key)
7654 if existing is None:
7655 by_key[key] = it
7656 merged.append(it)
7657 continue
7658 if existing is it:
7659 continue
7660 incoming = dict(it)
7661 engagement = dict(incoming.get("engagement") or {})
7662 engagement.setdefault("score", incoming.get("score"))
7663 engagement.setdefault("num_comments", incoming.get("num_comments"))
7664 incoming["engagement"] = engagement
7665 incoming.setdefault("engagement_source", reddit_hydrate.LIVE)
7666 if incoming.get("top_comments"):
7667 incoming["top_comments"] = reddit_hydrate._stamp_depth(incoming["top_comments"])
7668 incoming.setdefault("comments_source", "sc")
7669 reddit_hydrate.merge_post(existing, incoming)
7670 return merged
7671
7672
7673 def _merge_youtube_items(free: list[dict], sc: list[dict]) -> list[dict]:
7674 merged = copy.deepcopy(free)
7675 by_id = {item.get("video_id"): item for item in merged if item.get("video_id")}
7676 for item in sc:
7677 video_id = item.get("video_id")
7678 if not video_id:
7679 continue
7680 existing = by_id.get(video_id)
7681 if existing is None:
7682 merged.append(item)
7683 by_id[video_id] = item
7684 elif not str(existing.get("transcript_snippet") or "").strip() and item.get("transcript_snippet"):
7685 existing["transcript_snippet"] = item["transcript_snippet"]
7686 existing["transcript_highlights"] = item.get("transcript_highlights", [])
7687 return merged
7688
7689
7690 def _detail_rate_limits_source(source: str, artifact: dict) -> bool:
7691 if artifact.get("_source_outcome_detail_state") != health.RATE_LIMITED:
7692 return False
7693 if source == "reddit":
7694 # Reddit delivered items, so some path still serves: a throttled
7695 # path (site search, a web rung, a listing) skips only itself for the
7696 # run (reddit_health) and is a detail note, never a source skip.
7697 return False
7698 return source != "x" or not bool(artifact.get("_x_backup_not_rate_limited"))
7699
7700
7701 # TikTok videos per run that get comments from the free public endpoint (the
7702 # lane keeps about this many; ScrapeCreators comments cover three).
7703 PUBLIC_COMMENT_POSTS = 12
7704 # Most of the stream deadline the public attempt may use, and what it always
7705 # leaves for the ScrapeCreators fallback.
7706 PUBLIC_COMMENT_BUDGET_SECONDS = 15.0
7707 SC_COMMENT_RESERVE_SECONDS = 10.0
7708
7709
7710 def _comment_candidates(
7711 items: list[dict],
7712 from_date: str,
7713 to_date: str,
7714 creators: Iterable[str] | None = None,
7715 want: int = 3,
7716 topic: str = "",
7717 ) -> list[dict]:
7718 """The posts worth paying comment enrichment for.
7719
7720 Search results arrive before the date and relevance filters run, and the
7721 loudest of them are often old or off-topic (a 2022 #bully video for "Kanye
7722 West"). Picking the top posts by engagement from the raw list spent every
7723 comment call on posts the report then dropped.
7724
7725 Posts dated outside the window are never candidates (an undated post can
7726 still be kept). A post is preferred when it is on-topic the way the report
7727 judges it: by the early score, by its text plus fetched caption (the report
7728 rescores with the caption, so a spoken-caption match counts), or by being a
7729 requested creator's post (the platform-scoped exemption the relevance prune
7730 applies). Enrichment ranks its input by engagement and takes ``want``, so
7731 other posts only fill the slots preferred posts leave empty, loudest
7732 first, and never displace one. The dicts are shared, so comments attached
7733 here stay on the kept items.
7734 """
7735 handles = {h.lstrip("@").strip().lower() for h in (creators or []) if h and h.strip()}
7736
7737 def in_window(item: dict) -> bool:
7738 day = str(item.get("date") or "")
7739 return not day or from_date <= day <= to_date
7740
7741 def preferred(item: dict) -> bool:
7742 author = str(item.get("author_name") or "").lstrip("@").strip().lower()
7743 if author and author in handles:
7744 return True
7745 score = item.get("relevance")
7746 if score is None or float(score) >= relevance.RELEVANCE_FLOOR:
7747 return True
7748 body = " ".join(
7749 str(item.get(key) or "") for key in ("text", "caption_snippet")
7750 ).strip()
7751 return bool(topic and body) and (
7752 relevance.token_overlap_relevance(topic, body, item.get("hashtags") or None)
7753 >= relevance.RELEVANCE_FLOOR
7754 )
7755
7756 def loudness(item: dict) -> int:
7757 eng = item.get("engagement") or {}
7758 return sum(int(eng.get(key) or 0) for key in ("views", "likes", "comments"))
7759
7760 dated = [item for item in items if in_window(item)]
7761 first = [item for item in dated if preferred(item)]
7762 if len(first) >= want:
7763 return first
7764 rest = sorted((item for item in dated if not preferred(item)), key=loudness, reverse=True)
7765 return first + rest[: want - len(first)]
7766
7767
7768 def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
7769 """Run one stream and retain HTTP failures swallowed by source adapters."""
7770 # run_started is passed through but not used here; it goes to _retrieve_stream_impl
7771 source = str(kwargs.get("source") or "")
7772
7773 def publish_rate_limit(state):
7774 limited = kwargs.get("rate_limited_sources")
7775 if state == health.RATE_LIMITED and limited is not None:
7776 lock = kwargs.get("rate_limit_lock")
7777 with lock if lock is not None else contextlib.nullcontext():
7778 limited.add(source)
7779
7780 fixture_request = {
7781 "source": source,
7782 "topic": kwargs.get("topic") or "",
7783 "search_query": getattr(kwargs.get("subquery"), "search_query", ""),
7784 "date_range": list(kwargs.get("date_range") or ()),
7785 "depth": kwargs.get("depth") or "",
7786 }
7787 _key_youtube_fixture_by_entity_count(fixture_request, source, kwargs.get("config"))
7788 module_backed = source in {
7789 "reddit",
7790 "x",
7791 "youtube",
7792 "stocktwits",
7793 "digg",
7794 "arxiv",
7795 "techmeme",
7796 "news_rss",
7797 "trustpilot",
7798 "github",
7799 }
7800 if module_backed:
7801 matched, replayed = http.fixture_source_replay(fixture_request)
7802 if matched:
7803 replay_artifact = replayed[1] or {}
7804 publish_rate_limit((replay_artifact.get("_source_outcome") or {}).get("state"))
7805 if _detail_rate_limits_source(source, replay_artifact):
7806 publish_rate_limit(health.RATE_LIMITED)
7807 return replayed[0], replayed[1]
7808 try:
7809 with http.capture_failures() as failures, \
7810 http.fixture_module_capture(module_backed):
7811 items, artifact = _retrieve_stream_impl(*args, **kwargs)
7812 except Exception as exc:
7813 recorded_exc = exc
7814 if failures and not getattr(exc, "outcome_state", None):
7815 failure = min(
7816 failures,
7817 key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
7818 )
7819 recorded_exc = SourceRunError(str(exc), failure.outcome_state)
7820 publish_rate_limit(_classify_source_failure(recorded_exc)[0])
7821 if module_backed:
7822 http.fixture_source_record_error(fixture_request, recorded_exc)
7823 if recorded_exc is not exc:
7824 raise recorded_exc from exc
7825 raise
7826 outcome_note = _resolve_stream_outcome(
7827 str(kwargs.get("source") or ""),
7828 artifact,
7829 failures,
7830 )
7831 if outcome_note:
7832 # Lane-level HTTP failures (e.g. a blocked shreddit partial on a
7833 # datacenter IP) are captured by the sink even when the source
7834 # delivered items. Only attach them when the run produced nothing,
7835 # or when the impl attached its own explicit outcome artifact (e.g.
7836 # "primary failed; fallback returned N items"). A swallowed lane
7837 # failure must not brand a successful source auth-failed/partial.
7838 # An adapter-declared outcome (typed ``_source_outcome`` or a legacy
7839 # ``{"error": ...}`` / per-leg artifact) is explicit and always
7840 # brands the source, even with items; only failures the adapter
7841 # swallowed into the capture sink are demoted to detail.
7842 explicit = isinstance(artifact, dict) and (
7843 bool(artifact.get("_source_outcome"))
7844 or _legacy_artifact_outcome(str(kwargs.get("source") or ""), artifact) is not None
7845 )
7846 if explicit or not items:
7847 artifact = dict(artifact or {})
7848 artifact["_source_outcome"] = outcome_note
7849 elif failures:
7850 # The source delivered items. Keep it ``ok`` but carry what the
7851 # swallowed sub-requests lost, so doctor can still show it, and
7852 # the most specific failure state so a later empty filter result
7853 # or the thin-source retry can act on it.
7854 # Append to any detail the impl already set (e.g. a Reddit
7855 # backfill note) rather than overwriting it.
7856 artifact = dict(artifact or {})
7857 summary = _summarize_lane_failures(failures, str(kwargs.get("source") or ""))
7858 prior = artifact.get("_source_outcome_detail")
7859 artifact["_source_outcome_detail"] = f"{prior}; {summary}" if prior else summary
7860 states = [f.outcome_state for f in failures]
7861 if artifact.get("_source_outcome_detail_state"):
7862 states.append(artifact["_source_outcome_detail_state"])
7863 artifact["_source_outcome_detail_state"] = min(
7864 states, key=lambda state: _FAILURE_SPECIFICITY.get(state, 9)
7865 )
7866 publish_rate_limit((artifact.get("_source_outcome") or {}).get("state"))
7867 if _detail_rate_limits_source(source, artifact):
7868 publish_rate_limit(health.RATE_LIMITED)
7869 if module_backed:
7870 http.fixture_source_record(fixture_request, [items, artifact])
7871 return items, artifact
7872
7873
7874 def _serve_envelope_topic(envelope: x_envelope.Envelope) -> tuple[list[dict], dict]:
7875 """Serve the envelope's topic-lane rows once.
7876
7877 The first X subquery takes the rows and the envelope-status outcome;
7878 every later call (a second planner subquery, judge-retry, thin-retry)
7879 gets no items and no error, and no backend is ever consulted.
7880 """
7881 items = envelope.take_topic()
7882 if items is None:
7883 return [], {}
7884 artifact: dict[str, Any] = {}
7885 if envelope.warnings:
7886 # A narrower host window is a receipt (report.warnings), not a failure.
7887 artifact["x_receipts"] = [f"X: {warning}" for warning in envelope.warnings]
7888 outcome = envelope.outcome()
7889 if outcome is not None:
7890 state, detail = outcome
7891 artifact.update(_outcome_artifact(state, detail))
7892 return items, artifact
7893
7894
7895 def _serve_envelope_lanes(
7896 envelope: x_envelope.Envelope,
7897 *,
7898 bundle: schema.RetrievalBundle,
7899 plan: schema.QueryPlan,
7900 x_handle: str | None,
7901 x_related: list[str] | None,
7902 from_date: str,
7903 to_date: str,
7904 ) -> None:
7905 """Serve the envelope's from/mention/related calls into the lane merge.
7906
7907 Mirrors the backend lanes: primary-handle rows (from + mention) join the
7908 primary subquery with first-party handling for the explicit handle and
7909 the per-handle lane counts; related rows join ``supplemental-related``
7910 at the 0.3 weight. Lane claims were already validated at read time.
7911 """
7912 calls = envelope.take_lanes()
7913 if not calls:
7914 return
7915 x_slug = "x"
7916 existing_urls = {
7917 item.url
7918 for items in bundle.items_by_source.values()
7919 for item in items
7920 if item.url
7921 }
7922 ranking_query = plan.subqueries[0].ranking_query if plan.subqueries else ""
7923 primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
7924 primary_handles = sorted(
7925 {x_handle.lstrip("@").strip().lower()} if x_handle and x_handle.strip() else set()
7926 )
7927 related_handles = [
7928 h.lstrip("@").strip().lower()
7929 for h in (x_related or [])
7930 if h.strip() and h.lstrip("@").strip().lower() not in primary_handles
7931 ]
7932
7933 def _cap_per_author(posts: list[dict], cap: int) -> list[dict]:
7934 seen: Counter[str] = Counter()
7935 kept: list[dict] = []
7936 for post in posts:
7937 author = str(post.get("author_handle") or "").lower()
7938 if seen[author] >= cap:
7939 continue
7940 seen[author] += 1
7941 kept.append(post)
7942 return kept
7943
7944 primary_items: list[dict] = []
7945 related_items: list[dict] = []
7946 for call in calls:
7947 if call.lane == "from":
7948 primary_items.extend(_cap_per_author(call.posts, FROM_LANE_COUNT_PER))
7949 elif call.lane == "mention":
7950 primary_items.extend(
7951 call.posts[: MENTION_LANE_COUNT_PER * max(1, len(call.handles))]
7952 )
7953 elif call.lane == "related":
7954 related_items.extend(_cap_per_author(call.posts, RELATED_HANDLE_COUNT_PER))
7955
7956 if primary_items:
7957 normalized = _normalize_score_dedupe(
7958 x_slug, primary_items, from_date, to_date,
7959 freshness_mode=plan.freshness_mode,
7960 ranking_query=ranking_query,
7961 first_party_handles=primary_handles,
7962 )
7963 normalized = [item for item in normalized if item.url not in existing_urls]
7964 if normalized:
7965 bundle.add_items(primary_label, x_slug, normalized)
7966 existing_urls.update(item.url for item in normalized if item.url)
7967
7968 if related_items:
7969 normalized = _normalize_score_dedupe(
7970 x_slug, related_items, from_date, to_date,
7971 freshness_mode=plan.freshness_mode,
7972 ranking_query=ranking_query,
7973 first_party_handles=related_handles,
7974 )
7975 normalized = [item for item in normalized if item.url not in existing_urls]
7976 if normalized:
7977 bundle.add_items("supplemental-related", x_slug, normalized)
7978 if not any(sq.label == "supplemental-related" for sq in plan.subqueries):
7979 plan.subqueries.append(
7980 schema.SubQuery(
7981 label="supplemental-related",
7982 search_query=", ".join(related_handles),
7983 ranking_query=ranking_query,
7984 sources=[x_slug],
7985 weight=0.3,
7986 )
7987 )
7988
7989
7990 # Artifact keys that mark a stream result as a failure (or a deferred one).
7991 # The fetch memo never caches such a result, so the thin-source retry and the
7992 # next stream still make a real attempt after a transient failure.
7993 _STREAM_FAILURE_ARTIFACT_KEYS = (
7994 "_source_outcome",
7995 "_source_outcome_deferred",
7996 "_source_outcome_if_empty",
7997 "_source_outcome_detail_state",
7998 )
7999
8000
8001 def _clean_stream_result(result: tuple[list[dict], dict]) -> bool:
8002 _items, artifact = result
8003 return not (
8004 isinstance(artifact, dict)
8005 and any(artifact.get(key) for key in _STREAM_FAILURE_ARTIFACT_KEYS)
8006 )
8007
8008
8009 def _clean_search_result(result: Any) -> bool:
8010 """A legacy ``{"error": ...}`` search result is a failure and is not cached."""
8011 return not (isinstance(result, dict) and result.get("error"))
8012
8013
8014 def _memo_wait_seconds(config: dict[str, Any]) -> float:
8015 """How long a stream may wait on an identical in-flight fetch: its own budget."""
8016 return max(
8017 0.0,
8018 _research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS) - time.monotonic(),
8019 )
8020
8021
8022 _X_MEMO_WAIT_GRACE_SECONDS = 5.0
8023
8024
8025 def _attempt_x_backend_memo(
8026 backend, query, from_date, to_date, depth, config, warnings=None, deadline=None,
8027 ):
8028 """:func:`_attempt_x_backend`, once per backend and query per run.
8029
8030 Only the backend call is shared: the judge and prune still run per
8031 subquery with that subquery's ranking query.
8032 """
8033 def _fetch():
8034 local_warnings: list[str] = []
8035 items, err, err_state = _attempt_x_backend(
8036 backend, query, from_date, to_date, depth, config,
8037 warnings=local_warnings, deadline=deadline,
8038 )
8039 return items, err, err_state, local_warnings
8040
8041 # The owner is bounded by the same chain deadline, so a waiter allows a
8042 # short grace past it for the owner to publish instead of timing out first.
8043 wait = (
8044 max(0.0, deadline - time.monotonic()) + _X_MEMO_WAIT_GRACE_SECONDS
8045 if deadline is not None
8046 else _memo_wait_seconds(config)
8047 )
8048 try:
8049 items, err, err_state, backend_warnings = fetch_memo.fetch_once(
8050 ("x", backend, query, from_date, to_date, depth),
8051 _fetch,
8052 timeout=wait,
8053 cacheable=lambda outcome: not outcome[1],
8054 cancel=config.get("_enrich_cancel"),
8055 )
8056 except fetch_memo.MemoWaitTimeout as exc:
8057 # A chain error like any backend timeout, so the chain's own error
8058 # handling and outcome reporting apply.
8059 return [], str(exc), health.TIMEOUT
8060 if warnings is not None:
8061 warnings.extend(backend_warnings)
8062 return items, err, err_state
8063
8064
8065 _SSH_HOST_UNSET: Any = object()
8066
8067
8068 def _fetch_youtube_stream(
8069 yt_query: str,
8070 from_date: str,
8071 to_date: str,
8072 depth: str,
8073 config: dict[str, Any],
8074 *,
8075 has_ytdlp: bool,
8076 freshness_mode: str | None = None,
8077 ssh_host: Any = _SSH_HOST_UNSET,
8078 ) -> tuple[list[dict], dict]:
8079 """Search, backfill, transcribe, and comment-enrich one YouTube query."""
8080 # An abandoned lane keeps running after the report is saved; once the
8081 # run is over, every ScrapeCreators call in it is wasted credit (#1315).
8082 deadline = config.get("_research_deadline")
8083 scoped_ssh = (
8084 config.get("LAST30DAYS_YOUTUBE_SSH_HOST")
8085 if ssh_host is _SSH_HOST_UNSET
8086 else ssh_host
8087 )
8088 with youtube_yt.ssh_host_scope(scoped_ssh), \
8089 youtube_yt.sc_spend_until(
8090 lambda: _research_stopped(config),
8091 cancel=config.get("_enrich_cancel"),
8092 deadline=deadline,
8093 return_deadline=(
8094 deadline - youtube_yt._LANE_RETURN_MARGIN_SECONDS
8095 if deadline is not None else None
8096 ),
8097 ):
8098 return _fetch_youtube_stream_live(
8099 yt_query, from_date, to_date, depth, config,
8100 has_ytdlp=has_ytdlp, freshness_mode=freshness_mode,
8101 )
8102
8103
8104 def _comparison_entity_count(config: dict[str, Any] | None) -> int:
8105 return int((config or {}).get("_comparison_entity_count") or 1)
8106
8107
8108 def _key_youtube_fixture_by_entity_count(
8109 request: dict[str, Any], source: str, config: dict[str, Any] | None,
8110 ) -> None:
8111 # Only comparison runs carry the count, so fixtures already recorded for
8112 # single-topic runs keep their original keys.
8113 entity_count = _comparison_entity_count(config)
8114 if source == "youtube" and entity_count > 1:
8115 request["comparison_entity_count"] = entity_count
8116
8117
8118 def _interpreter_shutting_down(exc: BaseException) -> bool:
8119 """An abandoned lane outliving main() can no longer start thread pools."""
8120 return isinstance(exc, RuntimeError) and "interpreter shutdown" in str(exc)
8121
8122
8123 def _fetch_youtube_stream_live(
8124 yt_query: str,
8125 from_date: str,
8126 to_date: str,
8127 depth: str,
8128 config: dict[str, Any],
8129 *,
8130 has_ytdlp: bool,
8131 freshness_mode: str | None,
8132 ) -> tuple[list[dict], dict]:
8133 result = None
8134 run_over = False
8135 youtube_failure: str | None = None
8136 recovered_failure: str | None = None
8137 # ScrapeCreators key (when present) is the default-on backup tier: it
8138 # powers the per-video transcript fallback, the SC search fallback, and
8139 # comment enrichment. None when no key, which keeps everything keyless.
8140 sc_token = (
8141 config.get("SCRAPECREATORS_API_KEY", "")
8142 if env.is_youtube_sc_available(config) else None
8143 )
8144 entity_count = _comparison_entity_count(config)
8145 # Try yt-dlp first; the SC transcript fallback covers per-video failures.
8146 if has_ytdlp:
8147 try:
8148 result = youtube_yt.search_and_transcribe(
8149 yt_query, from_date, to_date, depth=depth, token=sc_token,
8150 freshness_mode=freshness_mode, entity_count=entity_count,
8151 )
8152 if result.get("error"):
8153 youtube_failure = str(result["error"])
8154 except Exception as exc:
8155 youtube_failure = str(exc)
8156 result = None
8157 # Not an empty yt-dlp result: the process is exiting.
8158 run_over = _interpreter_shutting_down(exc)
8159 out_of_time = (result or {}).get("out_of_time")
8160 if not out_of_time and youtube_yt._lane_out_of_time():
8161 out_of_time = "lane deadline passed"
8162 run_over = run_over or bool(out_of_time) or _research_stopped(config)
8163 free_items = list((result or {}).get("items") or [])
8164 min_items = env.youtube_sc_min_items(config)
8165 backfill_thin = bool(free_items) and len(free_items) < min_items
8166 thin_detail: str | None = None
8167 thin_error = False
8168 thin_retryable = False
8169 if (not free_items or backfill_thin) and sc_token and not run_over:
8170 backfill_scope = (
8171 http.capture_failures() if free_items else contextlib.nullcontext([])
8172 )
8173 try:
8174 with backfill_scope as sc_failures:
8175 transcribed_free_ids = {
8176 item["video_id"] for item in free_items
8177 if item.get("video_id")
8178 and str(item.get("transcript_snippet") or "").strip()
8179 }
8180 sc_result = youtube_yt.search_youtube_sc(
8181 yt_query, from_date, to_date, depth=depth, token=sc_token,
8182 skip_transcript_ids=transcribed_free_ids,
8183 freshness_mode=freshness_mode, entity_count=entity_count,
8184 )
8185 sc_error = str(sc_result["error"]) if sc_result.get("error") else None
8186 if backfill_thin:
8187 merged = _merge_youtube_items(free_items, sc_result.get("items") or [])
8188 result = {"items": merged}
8189 thin_detail = (
8190 f"yt-dlp returned {len(free_items)} videos below the "
8191 f"{min_items}-video backfill floor; ScrapeCreators added "
8192 f"{len(merged) - len(free_items)} videos"
8193 )
8194 if youtube_failure:
8195 thin_detail += f"; yt-dlp search: {youtube_failure}"
8196 if sc_error:
8197 thin_detail += f"; ScrapeCreators search: {sc_error}"
8198 if sc_failures:
8199 thin_detail += f"; ScrapeCreators: {_summarize_lane_failures(sc_failures, 'youtube')}"
8200 thin_error = bool(youtube_failure or sc_error or sc_failures)
8201 thin_retryable = thin_error and (
8202 len(merged) < min_items
8203 and (not youtube_failure or _retryable_youtube_error(youtube_failure))
8204 and (not sc_error or _retryable_youtube_error(sc_error))
8205 and all(
8206 _retryable_youtube_error(str(f), f.outcome_state)
8207 for f in sc_failures
8208 )
8209 )
8210 youtube_failure = None
8211 recovered_failure = None
8212 else:
8213 result = sc_result
8214 if sc_error:
8215 youtube_failure = sc_error
8216 elif result.get("items") and youtube_failure:
8217 recovered_failure = youtube_failure
8218 youtube_failure = None
8219 except Exception as exc:
8220 prior_youtube_failure = youtube_failure
8221 youtube_failure = str(exc)
8222 result = {"items": free_items} if free_items else None
8223 if backfill_thin:
8224 thin_error = True
8225 thin_detail = (
8226 f"yt-dlp returned {len(free_items)} videos below the "
8227 f"{min_items}-video backfill floor; ScrapeCreators failed: {exc}"
8228 )
8229 if prior_youtube_failure:
8230 thin_detail += f"; yt-dlp search: {prior_youtube_failure}"
8231 thin_retryable = (
8232 _retryable_youtube_error(
8233 str(exc), getattr(exc, "outcome_state", None)
8234 )
8235 and (not prior_youtube_failure or _retryable_youtube_error(prior_youtube_failure))
8236 )
8237 if result is None:
8238 result = {"items": []}
8239 # Enrich top videos with comments (default-on when a key is present).
8240 items = youtube_yt.parse_youtube_response(result)
8241 if not out_of_time and youtube_yt._lane_out_of_time():
8242 out_of_time = "lane deadline passed"
8243 if items and env.is_youtube_comments_available(config) and not out_of_time:
8244 youtube_yt.enrich_with_comments(
8245 items, token=sc_token or "", entity_count=entity_count,
8246 )
8247 if not out_of_time and youtube_yt._lane_out_of_time():
8248 out_of_time = "lane deadline passed"
8249 if out_of_time:
8250 detail = f"youtube timed out: {out_of_time}"
8251 if thin_detail or youtube_failure:
8252 detail += f"; {thin_detail or youtube_failure}"
8253 return items, {
8254 **_outcome_artifact(health.TIMEOUT, detail),
8255 "_source_out_of_time": True,
8256 }
8257 if thin_detail:
8258 if not thin_error:
8259 return items, {"_source_outcome_detail": thin_detail}
8260 outcome = _outcome_artifact(health.PARTIAL, thin_detail)
8261 if thin_retryable:
8262 return items, {
8263 "_source_outcome_detail": thin_detail,
8264 "_source_outcome_deferred": outcome["_source_outcome"],
8265 }
8266 return items, outcome
8267 if youtube_failure:
8268 state = youtube_yt.classify_run_failure(youtube_failure)
8269 attempted = state != schema.SKIPPED_UNCONFIGURED
8270 return items, _outcome_artifact(state, youtube_failure, attempted=attempted)
8271 if recovered_failure:
8272 state = youtube_yt.classify_run_failure(recovered_failure)
8273 attempted = state != schema.SKIPPED_UNCONFIGURED
8274 return items, {
8275 "_source_outcome_if_empty": _outcome_artifact(
8276 state, recovered_failure, attempted=attempted,
8277 )["_source_outcome"]
8278 }
8279 return items, {}
8280
8281
8282 def _retrieve_stream_impl(
8283 *,
8284 topic: str,
8285 subquery: schema.SubQuery,
8286 source: str,
8287 config: dict[str, Any],
8288 depth: str,
8289 date_range: tuple[str, str],
8290 runtime: schema.ProviderRuntime,
8291 mock: bool,
8292 rate_limited_sources: set[str] | None = None,
8293 rate_limit_lock: threading.Lock | None = None,
8294 web_backend: str = "auto",
8295 raw_topic: str = "",
8296 subreddits: list[str] | None = None,
8297 tiktok_hashtags: list[str] | None = None,
8298 tiktok_creators: list[str] | None = None,
8299 ig_creators: list[str] | None = None,
8300 trustpilot_domain: str | None = None,
8301 trustpilot_domain_is_hint: bool = False,
8302 run_started: float | None = None,
8303 skip_amazon_enrichment: bool = False,
8304 freshness_mode: str | None = None,
8305 ) -> tuple[list[dict], dict]:
8306 # Early exit if source was rate-limited by a sibling future
8307 if rate_limited_sources is not None:
8308 if rate_limit_lock is not None:
8309 with rate_limit_lock:
8310 is_rate_limited = source in rate_limited_sources
8311 else:
8312 is_rate_limited = source in rate_limited_sources
8313 if is_rate_limited:
8314 return [], {}
8315 # Cooperative enrichment cancel: the batch budget expired, so skip new
8316 # network work instead of burning credits past the deadline.
8317 if _research_stopped(config):
8318 return [], {"_source_outcome": {
8319 "state": health.TIMEOUT, "detail": "research cancelled or timed out", "attempted": False,
8320 }}
8321 from_date, to_date = date_range
8322 if mock:
8323 return _mock_stream_results(source, subquery)
8324 if source == "grounding":
8325 return grounding.web_search(
8326 subquery.search_query, date_range, config, backend=web_backend,
8327 include_news=freshness_mode == "strict_recent",
8328 )
8329 if source == "jobs":
8330 # The company the topic resolved to, so a person's name searches the
8331 # board of the company they lead, starting from its official site.
8332 return _search_jobs_lane(
8333 config.get("_company") or {},
8334 raw_topic or topic or subquery.search_query,
8335 config=config,
8336 depth=depth,
8337 date_range=date_range,
8338 web_backend=web_backend,
8339 )
8340 if source == "reddit":
8341 # Use raw_topic so expand_reddit_queries() generates diverse variants
8342 # from the original user topic, not the planner's narrowed search_query.
8343 reddit_query = raw_topic or subquery.search_query
8344 dedicated_subreddits = config.get("_dedicated_subreddits") or None
8345 has_sc_key = bool(config.get("SCRAPECREATORS_API_KEY"))
8346 research_deadline = config.get("_research_deadline")
8347 if env.reddit_scrapecreators_primary(config):
8348 # env.REDDIT_BACKEND_PIN_VAR=scrapecreators: SC primary, public fallback
8349 if config.get("_reddit_envelope") is not None:
8350 log.source_log(
8351 "reddit",
8352 "host Reddit threads are not used while Reddit is pinned to ScrapeCreators",
8353 tty_only=False,
8354 )
8355 primary_failure: Exception | None = None
8356 try:
8357 with http.tee_failures() as sc_primary_failures, reddit.sc_spend_until(
8358 deadline=config.get("_research_deadline"),
8359 cancel=config.get("_enrich_cancel"),
8360 ):
8361 result = reddit.search_and_enrich_memo(
8362 reddit_query, from_date, to_date, depth=depth,
8363 token=config.get("SCRAPECREATORS_API_KEY"),
8364 subreddits=subreddits,
8365 )
8366 items = reddit.parse_reddit_response(result)
8367 if items:
8368 sc_notes = _reddit_sc_incomplete_notes(result)
8369 return items, (
8370 {"_source_outcome_detail": "; ".join(sc_notes)} if sc_notes else {}
8371 )
8372 if isinstance(result, dict) and result.get("incomplete"):
8373 primary_failure = TimeoutError(
8374 str(
8375 result.get("incomplete_note")
8376 or "Reddit ScrapeCreators search timed out before completing"
8377 )
8378 )
8379 sys.stderr.write(
8380 f"[Reddit] ScrapeCreators primary incomplete with no usable items "
8381 f"({primary_failure}), using public fallback\n"
8382 )
8383 elif sc_primary_failures:
8384 primary_failure = min(
8385 sc_primary_failures,
8386 key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
8387 )
8388 sys.stderr.write(
8389 f"[Reddit] ScrapeCreators primary failed with no usable items "
8390 f"({primary_failure}), using public fallback\n"
8391 )
8392 else:
8393 sys.stderr.write(
8394 "[Reddit] ScrapeCreators primary returned no items, "
8395 "using public fallback\n"
8396 )
8397 except Exception as exc:
8398 primary_failure = exc
8399 sys.stderr.write(
8400 f"[Reddit] ScrapeCreators primary failed "
8401 f"({type(exc).__name__}: {exc}), using public fallback\n"
8402 )
8403 # Leave time to hand back the public lane's partial results. The paid primary has
8404 # spent part of the budget, so size the margin from what is left now (as the
8405 # public-first lane does) rather than a flat 20s that can swallow a short budget.
8406 public_deadline = (
8407 research_deadline - min(
8408 REDDIT_LANE_RETURN_MARGIN_SECONDS,
8409 max(0.0, research_deadline - time.monotonic()) * 0.15,
8410 )
8411 if research_deadline is not None else None
8412 )
8413 public_failure: Exception | None = None
8414 fallback_notes: list[str] = []
8415 try:
8416 with reddit_keyless.lane_deadline(public_deadline), \
8417 reddit_keyless.lane_notes() as fallback_notes, \
8418 reddit_keyless.lane_paths() as lane_paths:
8419 public_results = reddit_public.search_reddit_public(
8420 reddit_query, from_date, to_date, depth=depth,
8421 subreddits=subreddits, config=config,
8422 )
8423 if public_results:
8424 if primary_failure is not None:
8425 state = (
8426 getattr(primary_failure, "outcome_state", None)
8427 or (
8428 health.TIMEOUT
8429 if isinstance(primary_failure, TimeoutError)
8430 else reddit.classify_run_failure(str(primary_failure))
8431 )
8432 )
8433 if state == health.RATE_LIMITED:
8434 # ScrapeCreators 429 does not mean reddit.com's public
8435 # fallback is rate-limited; reporting RATE_LIMITED here
8436 # puts "reddit" in rate_limited_sources and skips later
8437 # subqueries before they can use the working fallback.
8438 state = health.PARTIAL
8439 return public_results, _with_reddit_lane_notes(_outcome_artifact(
8440 state,
8441 f"Reddit primary failed; public fallback returned "
8442 f"{len(public_results)} items: {primary_failure}",
8443 ), fallback_notes)
8444 return public_results, _with_reddit_lane_notes({}, fallback_notes)
8445 sys.stderr.write(
8446 "[Reddit] Public fallback returned no items after "
8447 "ScrapeCreators primary miss\n"
8448 )
8449 except Exception as exc:
8450 public_failure = exc
8451 sys.stderr.write(
8452 f"[Reddit] Public fallback also failed "
8453 f"({type(exc).__name__}: {exc})\n"
8454 )
8455 failure = public_failure or primary_failure
8456 if failure is not None:
8457 state = (
8458 getattr(failure, "outcome_state", None)
8459 or (
8460 health.TIMEOUT
8461 if isinstance(failure, TimeoutError)
8462 else reddit.classify_run_failure(str(failure))
8463 )
8464 )
8465 raise SourceRunError(
8466 f"Reddit primary and fallback produced no results after failure: {failure}",
8467 state,
8468 lane_notes=fallback_notes,
8469 )
8470 if lane_paths.get("web") == health.TIMEOUT or reddit_keyless._out_of_time(public_deadline):
8471 return [], _with_reddit_lane_notes(_reddit_timeout_artifact(), fallback_notes)
8472 return [], _with_reddit_lane_notes({}, fallback_notes)
8473
8474 # Default: public Reddit first (free). ScrapeCreators backfills when the
8475 # free path returns fewer than the thinness floor (env.reddit_sc_min_items:
8476 # unset -> env.REDDIT_SC_MIN_ITEMS_DEFAULT, explicit 0 -> empty-only,
8477 # malformed -> 0 so a typo never spends extra credits).
8478 min_items = env.reddit_sc_min_items(config)
8479 public_results: list[dict] = []
8480 public_failure: Exception | None = None
8481 # The lane returns what it has before the stream wait gives up on
8482 # it; a lane still running then is reported as a timeout with nothing.
8483 # Scale return margin and SC reserve proportionally to remaining budget
8484 # so tight budgets (<= 65s) still give the free lane a real turn.
8485 research_deadline = config.get("_research_deadline")
8486 if research_deadline is not None:
8487 rem = max(0.0, research_deadline - time.monotonic())
8488 margin = min(REDDIT_LANE_RETURN_MARGIN_SECONDS, rem * 0.15)
8489 reserve = (
8490 min(REDDIT_SC_BACKFILL_RESERVE_SECONDS, rem * 0.35)
8491 if has_sc_key else 0.0
8492 )
8493 lane_deadline: float | None = research_deadline - margin - reserve
8494 else:
8495 lane_deadline = None
8496 lane_notes: list[str] = []
8497 lane_paths: dict[str, str] = {}
8498 # The consented logged-in session, when its gate passes (read once per
8499 # run; None otherwise). Its budget is spent per entity.
8500 lane_topic = raw_topic or reddit_query
8501 lane_session = reddit_session.session_for(config, topic=lane_topic)
8502 if "_reddit_named_subreddits" in config:
8503 lane_named = reddit_session.named_subreddits("", config.get("_reddit_named_subreddits") or ())
8504 else:
8505 lane_named = reddit_session.named_subreddits(lane_topic, dedicated_subreddits or ())
8506 try:
8507 with reddit_keyless.lane_deadline(lane_deadline), \
8508 reddit_keyless.lane_notes() as lane_notes, \
8509 reddit_keyless.lane_paths() as lane_paths, \
8510 reddit_session.lane(lane_session, lane_topic, named=lane_named), \
8511 reddit_envelope.lane(config.get("_reddit_envelope"), subquery.label):
8512 public_results = reddit_public.search_reddit_public(
8513 reddit_query, from_date, to_date, depth=depth,
8514 subreddits=subreddits, dedicated_subreddits=dedicated_subreddits,
8515 config=config,
8516 ) or []
8517 except Exception as exc:
8518 public_failure = exc
8519 sys.stderr.write(
8520 f"[Reddit] Public search failed ({type(exc).__name__}: {exc})"
8521 )
8522 if not has_sc_key:
8523 sys.stderr.write("\n")
8524 state = (
8525 health.TIMEOUT
8526 if isinstance(exc, TimeoutError)
8527 else reddit.classify_run_failure(str(exc))
8528 )
8529 raise SourceRunError(
8530 f"Reddit public search failed: {exc}", state, lane_notes=lane_notes,
8531 ) from exc
8532 sys.stderr.write(", using ScrapeCreators backup\n")
8533 # An actual web cutoff outranks completed failures; running inside the
8534 # return margin does not (every path may have finished and failed).
8535 free_cut_off = (
8536 not public_results and public_failure is None
8537 and lane_paths.get("web") == health.TIMEOUT
8538 )
8539 free_timed_out = free_cut_off or (
8540 not public_results and public_failure is None
8541 and reddit_keyless._out_of_time(lane_deadline)
8542 )
8543 if free_timed_out and not has_sc_key:
8544 return [], _with_reddit_lane_notes(_reddit_timeout_artifact(), lane_notes)
8545 free_failed = (
8546 not public_results and public_failure is None
8547 and reddit_health.every_path_failed(lane_paths)
8548 )
8549 if free_failed and not has_sc_key:
8550 # Every path Reddit was asked through refused or failed: a
8551 # transport failure, never a topic nobody posted about.
8552 return [], _with_reddit_lane_notes(
8553 _outcome_artifact(*reddit_health.failure_outcome(lane_paths)), lane_notes,
8554 )
8555 # The floor counts the free threads that are on topic for this stream,
8556 # the ones its relevance prune will keep. Enough of them, or no key to
8557 # backfill with -> done. max(min_items, 1) keeps the default
8558 # (min_items=0) as empty-only AND treats exactly `min_items` results
8559 # as acceptable (no backfill) for min_items > 0.
8560 on_topic = _reddit_on_topic_count(
8561 public_results, from_date, to_date,
8562 subquery.ranking_query or reddit_query, freshness_mode,
8563 ) if has_sc_key and min_items > 0 else len(public_results)
8564 if on_topic >= max(min_items, 1) or not has_sc_key:
8565 return public_results, _with_reddit_lane_notes(
8566 _reddit_served_artifact(public_results, lane_paths), lane_notes,
8567 )
8568 if public_results:
8569 sys.stderr.write(
8570 f"[Reddit] Free path returned {len(public_results)} "
8571 f"({on_topic} on topic, below the {min_items}-item floor); "
8572 "backfilling with ScrapeCreators\n"
8573 )
8574 elif free_timed_out:
8575 sys.stderr.write(
8576 "[Reddit] Free path ran out of time with no threads; "
8577 "backfilling with ScrapeCreators\n"
8578 )
8579 # With free items in hand, scope the backfill's own HTTP failures
8580 # away from the stream's capture sink: a ScrapeCreators 429 is not a
8581 # reddit.com rate limit, and a RATE_LIMITED lane state would put
8582 # 'reddit' in rate_limited_sources and skip later Reddit streams and
8583 # the thin-source retry. Its failures become the detail note instead.
8584 # With no free items the backfill IS the source, so failures reach
8585 # the stream sink as before.
8586 backfill_scope = (
8587 http.capture_failures() if public_results else contextlib.nullcontext([])
8588 )
8589 try:
8590 with backfill_scope as backfill_failures:
8591 result = _run_reddit_backfill(config, lambda: reddit.search_and_enrich_memo(
8592 reddit_query, from_date, to_date, depth=depth,
8593 token=config.get("SCRAPECREATORS_API_KEY"),
8594 subreddits=subreddits,
8595 ))
8596 sc_items = reddit.parse_reddit_response(result)
8597 except Exception as exc:
8598 sys.stderr.write(
8599 f"[Reddit] ScrapeCreators backup also failed "
8600 f"({type(exc).__name__}: {exc})\n"
8601 )
8602 state = (
8603 health.TIMEOUT
8604 if isinstance(exc, TimeoutError)
8605 else reddit.classify_run_failure(str(exc))
8606 )
8607 if public_results:
8608 # The free path delivered: Reddit is working. The failed
8609 # backfill is a detail note, never the source's outcome.
8610 served = _reddit_served_artifact(public_results, lane_paths)
8611 artifact = {
8612 "_source_outcome_detail": "; ".join(filter(None, [
8613 served.get("_source_outcome_detail"),
8614 f"ScrapeCreators backfill failed after "
8615 f"{len(public_results)} free items: {exc}",
8616 ])),
8617 }
8618 if state != health.RATE_LIMITED:
8619 # A ScrapeCreators rate limit says nothing about
8620 # reddit.com (and the run memo already stops a retry).
8621 artifact["_source_outcome_detail_state"] = state
8622 return public_results, _with_reddit_lane_notes(artifact, lane_notes)
8623 failed_paths = reddit_health.failures(lane_paths)
8624 return public_results, _with_reddit_lane_notes(_outcome_artifact(
8625 state,
8626 f"Reddit backup failed after {len(public_results)} public items: {exc}"
8627 + "".join(f"; {failed}" for failed in failed_paths),
8628 ), lane_notes)
8629 merged = _merge_reddit_items(public_results, sc_items)
8630 sc_notes = _reddit_sc_incomplete_notes(result)
8631 backfill_timeout = (
8632 _outcome_artifact(
8633 health.TIMEOUT,
8634 str(
8635 result.get("incomplete_note")
8636 or "Reddit ScrapeCreators backfill timed out before completing"
8637 ),
8638 )
8639 if isinstance(result, dict) and result.get("incomplete") else None
8640 )
8641 if not merged and free_cut_off:
8642 # Both stages ran out of time, so the paid backfill's own note is the specific
8643 # one. Only a captured failure of another kind is left to the stream resolver.
8644 if backfill_timeout is not None and _captured_failures_are_only_timeouts():
8645 return [], _with_reddit_lane_notes(backfill_timeout, lane_notes)
8646 return [], _with_reddit_lane_notes(_reddit_timeout_artifact(), lane_notes)
8647 if not merged and free_failed:
8648 return [], _with_reddit_lane_notes(
8649 _outcome_artifact(*reddit_health.failure_outcome(lane_paths)), lane_notes,
8650 )
8651 if not merged and backfill_timeout is not None:
8652 return [], _with_reddit_lane_notes(backfill_timeout, lane_notes)
8653 if not merged and free_timed_out:
8654 return [], _with_reddit_lane_notes(_reddit_timeout_artifact(), lane_notes)
8655 if public_failure is not None:
8656 state = (
8657 health.TIMEOUT
8658 if isinstance(public_failure, TimeoutError)
8659 else reddit.classify_run_failure(str(public_failure))
8660 )
8661 detail = (
8662 f"Reddit public search failed; backup returned {len(sc_items)} items: "
8663 f"{public_failure}"
8664 )
8665 if sc_notes:
8666 detail = f"{detail}; {'; '.join(sc_notes)}"
8667 return merged, _outcome_artifact(state, detail)
8668 trigger = (
8669 f"below the {min_items}-item floor" if min_items > 0 else "free path empty"
8670 )
8671 backfill_detail = (
8672 f"ScrapeCreators backfill ran ({len(public_results)} free items, "
8673 f"{trigger}); added {len(merged) - len(public_results)} items"
8674 )
8675 if sc_notes:
8676 backfill_detail = f"{backfill_detail}; {'; '.join(sc_notes)}"
8677 if backfill_failures:
8678 summary = _summarize_lane_failures(backfill_failures, "reddit")
8679 backfill_detail = f"{backfill_detail}; ScrapeCreators backfill lost {summary}"
8680 added = len(merged) - len(public_results)
8681 served = _reddit_served_artifact(
8682 public_results, lane_paths, extra=("sc",) if added else (), count=len(merged),
8683 ).get("_source_outcome_detail")
8684 if served:
8685 backfill_detail = f"{served}; {backfill_detail}"
8686 return merged, _with_reddit_lane_notes({"_source_outcome_detail": backfill_detail}, lane_notes)
8687 if source == "x":
8688 if config.get("_x_lane_missing"):
8689 # The model declared the connector lane but passed no envelope.
8690 return [], _outcome_artifact(health.ERROR, x_envelope.DETAIL_NOT_PASSED)
8691 envelope = config.get("_x_envelope")
8692 if envelope is not None:
8693 # Host-fetched lane: the envelope replaces the backend chain and
8694 # is single-serve, so no backend runs and no judge-retry follows.
8695 return _serve_envelope_topic(envelope)
8696
8697 # Compile X query from raw_topic (like Reddit/YouTube), not planner's
8698 # search_query which may contain operator strings like "Rome Italy".
8699 x_query = raw_topic or topic or subquery.search_query
8700 ranking_query = subquery.ranking_query
8701
8702 # One X source, an ordered chain of interchangeable backends. Try the
8703 # primary; fall through to the next only if it returns nothing or errors.
8704 chain = env.x_backend_chain(config)
8705 # Trust an explicit runtime backend as the primary (already resolved as
8706 # available), keeping the rest of the chain as failover backups.
8707 pinned = runtime.x_search_backend
8708 if pinned:
8709 chain = [pinned] + [b for b in chain if b != pinned]
8710 if not chain:
8711 raise SourceRunError(
8712 "No X backend is available (not configured).",
8713 schema.SKIPPED_UNCONFIGURED,
8714 )
8715 last_error = ""
8716 chain_errors: list[tuple[str, schema.RunOutcomeState]] = []
8717 last_state = health.ERROR
8718 items = []
8719 used_backend = None
8720 used_backend_auth_failed = False
8721 x_warnings: list[str] = []
8722 artifact: dict[str, Any] = {}
8723 chain_deadline = _research_deadline(config, _x_chain_budget_seconds(config))
8724 cutoff = config.get("_finalization_deadline")
8725 if cutoff is not None:
8726 chain_deadline = min(chain_deadline, cutoff)
8727 for i, backend in enumerate(chain):
8728 if _research_stopped(config) or time.monotonic() >= chain_deadline:
8729 msg = "X chain budget exhausted (timed out or cancelled)"
8730 last_error = f"{last_error}; {msg}".strip("; ") if last_error else msg
8731 last_state = health.TIMEOUT
8732 chain_errors.append((msg, last_state))
8733 print("[X] chain budget exhausted; skipping remaining backends", file=sys.stderr)
8734 break
8735 with http.tee_failures() as backend_failures:
8736 items, err, err_state = _attempt_x_backend_memo(
8737 backend, x_query, from_date, to_date, depth, config, warnings=x_warnings,
8738 deadline=chain_deadline,
8739 )
8740 if items:
8741 if i > 0:
8742 # xapi is metered: name the spend when it served as a backup.
8743 spend = " (spends X API credits)" if backend == "xapi" else ""
8744 print(
8745 f"[X] primary backend(s) returned nothing; used fallback '{backend}'{spend}",
8746 file=sys.stderr,
8747 )
8748 # Record failover/error artifact metadata and break so x_receipts
8749 # and x_judge retry/pruning always run before returning.
8750 if chain_errors:
8751 prior_error, prior_state = min(
8752 chain_errors,
8753 key=lambda entry: _FAILURE_SPECIFICITY.get(entry[1], 9),
8754 )
8755 backup_rate_limited = err_state == health.RATE_LIMITED or any(
8756 failure.outcome_state == health.RATE_LIMITED for failure in backend_failures
8757 )
8758 detail = f"X served via {backend} after {prior_error}"
8759 if err:
8760 detail += f"; {backend}: {err}"
8761 if backup_rate_limited and err_state != health.RATE_LIMITED:
8762 detail += f"; {backend} also rate-limited"
8763 if prior_state == schema.AUTH_FAILED:
8764 repair = (
8765 "; re-login needed for primary backend"
8766 if prior_error.startswith(("grok:", "bird:")) else ""
8767 )
8768 artifact = _outcome_artifact(
8769 schema.AUTH_FAILED,
8770 f"{detail}{repair}",
8771 )
8772 if backup_rate_limited:
8773 artifact["_source_outcome_detail"] = f"{backend} also rate-limited"
8774 artifact["_source_outcome_detail_state"] = health.RATE_LIMITED
8775 elif err and err_state == schema.AUTH_FAILED:
8776 repair = "; re-login needed" if backend in ("grok", "bird") else ""
8777 artifact = _outcome_artifact(
8778 schema.AUTH_FAILED,
8779 f"X served {len(items)} items via {backend} but also errored: {err}{repair}",
8780 )
8781 else:
8782 artifact = {
8783 "_source_outcome_detail": detail,
8784 "_source_outcome_detail_state": health.RATE_LIMITED if backup_rate_limited else prior_state,
8785 "_x_backup_not_rate_limited": not backup_rate_limited,
8786 }
8787 elif err:
8788 # Mixed result: backend returned items BUT also hit an error
8789 # (e.g., grok got some posts then auth was revoked mid-fanout).
8790 # Surface the error so the user gets re-login guidance.
8791 artifact = _outcome_artifact(
8792 err_state or health.ERROR,
8793 f"X returned {len(items)} items but also errored: {err}",
8794 )
8795 used_backend = backend
8796 used_backend_auth_failed = bool(err and err_state == schema.AUTH_FAILED)
8797 break
8798 if err:
8799 last_error = f"{backend}: {err}"
8800 last_state = err_state or health.ERROR
8801 chain_errors.append((last_error, last_state))
8802 print(f"[X] backend '{backend}' failed ({err}); trying next", file=sys.stderr)
8803
8804 if not items and (last_error or chain_errors):
8805 candidates: list[tuple[str, schema.RunOutcomeState]] = [
8806 (
8807 err_msg,
8808 bird_x.classify_run_failure(err_msg)
8809 if err_msg.startswith("bird:") and err_st == health.ERROR
8810 else err_st,
8811 )
8812 for err_msg, err_st in chain_errors
8813 ]
8814 if not candidates and last_error:
8815 candidates.append((
8816 last_error,
8817 bird_x.classify_run_failure(last_error)
8818 if last_error.startswith("bird:")
8819 else last_state,
8820 ))
8821 if _research_stopped(config) or time.monotonic() >= chain_deadline:
8822 if not any(st == health.TIMEOUT for _, st in candidates):
8823 candidates.append(
8824 ("X search timed out before completing failover chain", health.TIMEOUT)
8825 )
8826 winning_error, winning_state = min(
8827 candidates,
8828 key=lambda entry: _FAILURE_SPECIFICITY.get(entry[1], 9),
8829 )
8830 raise SourceRunError(f"All X backends failed — {winning_error}", winning_state)
8831
8832 # Retrieve-judge-retry: judge corpus and retry if off-topic flood.
8833 # Skip retry on quick/mock (same as Phase 2).
8834 if x_warnings:
8835 # e.g. xapi's "window truncated to 7 days": a receipt that reaches
8836 # report.warnings (see the grounding artifacts walk in
8837 # _build_report), never a source failure.
8838 artifact["x_receipts"] = list(x_warnings)
8839 if items and depth != "quick" and not mock:
8840 items_for_judge = [
8841 {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}
8842 for it in items
8843 ]
8844 if (
8845 used_backend
8846 and not used_backend_auth_failed
8847 and x_judge.should_retry_x_search(items_for_judge, x_query, ranking_query=ranking_query, depth=depth)
8848 ):
8849 # Retry with cleaned query (1 retry, ≤2 extra grok calls)
8850 # Strip noise words but preserve all significant terms to avoid
8851 # losing disambiguating terms (e.g., "react server components")
8852 core_tokens = query.extract_core_subject(x_query)
8853 retry_query = core_tokens or x_query
8854 print(f"[X] corpus off-topic; retrying with '{retry_query}'", file=sys.stderr)
8855
8856 if _research_stopped(config) or time.monotonic() >= chain_deadline:
8857 print("[X] chain budget exhausted; skipping judge retry", file=sys.stderr)
8858 else:
8859 retry_items, retry_err, retry_state = _attempt_x_backend_memo(
8860 used_backend, retry_query, from_date, to_date, depth, config,
8861 deadline=chain_deadline,
8862 )
8863 if retry_items:
8864 # Judge retry corpus
8865 retry_for_judge = [
8866 {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}
8867 for it in retry_items
8868 ]
8869 retry_judgment = x_judge.judge_x_corpus(
8870 retry_for_judge, x_query, ranking_query=ranking_query
8871 )
8872 orig_judgment = x_judge.judge_x_corpus(
8873 items_for_judge, x_query, ranking_query=ranking_query
8874 )
8875 # Use retry if better on-topic ratio
8876 if retry_judgment["on_topic_ratio"] > orig_judgment["on_topic_ratio"]:
8877 print(
8878 f"[X] retry improved on-topic ratio: "
8879 f"{orig_judgment['on_topic_ratio']:.0%} -> "
8880 f"{retry_judgment['on_topic_ratio']:.0%}",
8881 file=sys.stderr,
8882 )
8883 items = retry_items
8884 if retry_err:
8885 eff_retry_state = retry_state or health.ERROR
8886 if (
8887 eff_retry_state == schema.AUTH_FAILED
8888 and (artifact.get("_source_outcome") or {}).get("state") != schema.AUTH_FAILED
8889 ):
8890 repair = "; re-login needed" if used_backend in ("grok", "bird") else ""
8891 artifact.update(_outcome_artifact(
8892 schema.AUTH_FAILED,
8893 f"X retry via {used_backend} returned {len(retry_items)} items "
8894 f"but also errored: {retry_err}{repair}",
8895 ))
8896 else:
8897 retry_note = f"X retry via {used_backend} returned partial results ({retry_err})"
8898 existing_detail = artifact.get("_source_outcome_detail")
8899 artifact["_source_outcome_detail"] = (
8900 f"{existing_detail}; {retry_note}"
8901 if existing_detail else retry_note
8902 )
8903 existing_state = artifact.get("_source_outcome_detail_state")
8904 if (
8905 existing_state is None
8906 or _FAILURE_SPECIFICITY.get(eff_retry_state, 9)
8907 < _FAILURE_SPECIFICITY.get(existing_state, 9)
8908 ):
8909 artifact["_source_outcome_detail_state"] = eff_retry_state
8910 if eff_retry_state == health.RATE_LIMITED:
8911 artifact["_x_backup_not_rate_limited"] = False
8912
8913 # Prune off-topic items before the pool. Eight on-topic → ok with 8.
8914 # Zero on-topic after retry → no-results, not ok with 40 junk.
8915 # Only prune items that have text to judge; items without text pass through.
8916 original_count = len(items)
8917 items_with_text = [(i, it) for i, it in enumerate(items) if it.get("text", "").strip()]
8918
8919 if items_with_text:
8920 items_for_prune = [
8921 {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}
8922 for _, it in items_with_text
8923 ]
8924 judgment = x_judge.judge_x_corpus(
8925 items_for_prune, x_query, ranking_query=ranking_query
8926 )
8927 # Build set of indices for on-topic items
8928 on_topic_indices = set()
8929 for (orig_idx, _), pruned_item in zip(items_with_text, items_for_prune):
8930 if pruned_item in judgment["on_topic_items"]:
8931 on_topic_indices.add(orig_idx)
8932
8933 # Keep items that are on-topic OR have no text (can't judge)
8934 items = [
8935 it for i, it in enumerate(items)
8936 if i in on_topic_indices or not it.get("text", "").strip()
8937 ]
8938
8939 # Record warning if significant pruning occurred (artifact, not failure)
8940 if len(items) < original_count:
8941 pruned = original_count - len(items)
8942 artifact.setdefault("_warnings", []).append(
8943 f"X: pruned {pruned} off-topic items; {len(items)} on-topic remain"
8944 )
8945
8946 return items, artifact
8947 if source == "youtube":
8948 # Use raw_topic so expand_youtube_queries() generates diverse variants
8949 # from the original user topic, not the planner's narrowed search_query.
8950 yt_query = raw_topic or subquery.search_query
8951 has_ytdlp, ssh_host = _resolve_ytdlp(config)
8952 with youtube_yt.ssh_host_scope(ssh_host):
8953 # One memo unit covers yt-dlp search, the ScrapeCreators fallback and
8954 # merge, transcripts, and comments, so subquery streams and the
8955 # thin-source retry share one fetch (hosts without yt-dlp included).
8956 return fetch_memo.fetch_once(
8957 (
8958 "youtube", yt_query, from_date, to_date, depth, freshness_mode, has_ytdlp,
8959 ssh_host,
8960 env.is_youtube_sc_available(config),
8961 env.is_youtube_comments_available(config),
8962 env.youtube_sc_min_items(config),
8963 _comparison_entity_count(config),
8964 ),
8965 lambda: _fetch_youtube_stream(
8966 yt_query, from_date, to_date, depth, config, has_ytdlp=has_ytdlp,
8967 freshness_mode=freshness_mode, ssh_host=ssh_host,
8968 ),
8969 timeout=_memo_wait_seconds(config),
8970 cacheable=_clean_stream_result,
8971 cancel=config.get("_enrich_cancel"),
8972 )
8973 if source == "tiktok":
8974 # Use raw_topic so expand_tiktok_queries() generates diverse variants
8975 # from the original user topic, not the planner's narrowed search_query.
8976 tiktok_query = raw_topic or subquery.search_query
8977 has_ytdlp, ssh_host = _resolve_ytdlp(config)
8978
8979 def _fetch_tiktok() -> tuple[list[dict], dict]:
8980 # Leave time to publish collected videos before the outer stream wait expires.
8981 deadline = _research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS) - 1.0
8982 cancel = config.get("_enrich_cancel")
8983 result = tiktok.search_and_enrich(
8984 tiktok_query,
8985 from_date,
8986 to_date,
8987 depth=depth,
8988 token=env.get_tiktok_token(config),
8989 hashtags=tiktok_hashtags,
8990 creators=tiktok_creators,
8991 config=config,
8992 deadline=deadline,
8993 cancel=cancel,
8994 )
8995 items = tiktok.parse_tiktok_response(result)
8996 if (
8997 items
8998 and env.is_tiktok_comments_available(config)
8999 and not items[0].get("_oss_backend")
9000 and result.get("error") != tiktok.BUDGET_ERROR
9001 ):
9002 sc_token = config.get("SCRAPECREATORS_API_KEY", "")
9003 try:
9004 public_got = 0
9005 # The public attempt gets its own short budget and always
9006 # leaves the fallback time, so a stalled endpoint cannot
9007 # use up the deadline ScrapeCreators would answer within.
9008 public_deadline = min(
9009 time.monotonic() + PUBLIC_COMMENT_BUDGET_SECONDS,
9010 deadline - SC_COMMENT_RESERVE_SECONDS,
9011 )
9012 if env.is_tiktok_public_comments_on(config) and public_deadline > time.monotonic():
9013 # Free and keyless, so every kept-sized slate of videos
9014 # gets comments, not just the three ScrapeCreators pays for.
9015 slate = _comment_candidates(
9016 items, from_date, to_date, tiktok_creators,
9017 want=PUBLIC_COMMENT_POSTS, topic=tiktok_query,
9018 )
9019 try:
9020 tiktok.enrich_with_comments(
9021 slate, token="", max_posts=PUBLIC_COMMENT_POSTS,
9022 deadline=public_deadline, cancel=cancel, public=True,
9023 )
9024 except http.DeadlineExceeded:
9025 # Only the public budget ran out: keep what came
9026 # back and let the fallback run on the real deadline.
9027 if (cancel is not None and cancel.is_set()) or time.monotonic() >= deadline:
9028 raise
9029 public_got = sum(1 for item in slate if item.get("top_comments"))
9030 if not public_got:
9031 # Endpoint off, blocked or empty: ScrapeCreators as before.
9032 tiktok.enrich_with_comments(
9033 _comment_candidates(items, from_date, to_date, tiktok_creators, topic=tiktok_query),
9034 token=sc_token, deadline=deadline, cancel=cancel,
9035 )
9036 except http.DeadlineExceeded:
9037 result["error"] = tiktok.BUDGET_ERROR
9038 elif (
9039 items
9040 and items[0].get("_oss_backend")
9041 and env.is_tiktok_public_comments_on(config)
9042 and result.get("error") != tiktok.BUDGET_ERROR
9043 ):
9044 # Keyless lane: the public endpoint is the only comment source,
9045 # and the lane already returns only in-window, on-topic videos.
9046 try:
9047 tiktok.enrich_with_comments(
9048 items, token="", max_posts=PUBLIC_COMMENT_POSTS,
9049 deadline=deadline, cancel=cancel, public=True,
9050 )
9051 except http.DeadlineExceeded:
9052 result["error"] = tiktok.BUDGET_ERROR
9053 return items, _result_outcome_artifact(source, result)
9054
9055 with youtube_yt.ssh_host_scope(ssh_host):
9056 return fetch_memo.fetch_once(
9057 (
9058 "tiktok", tiktok_query, from_date, to_date, depth,
9059 bool(env.get_tiktok_token(config)),
9060 has_ytdlp, ssh_host,
9061 tuple(tiktok_hashtags or ()), tuple(tiktok_creators or ()),
9062 env.is_tiktok_comments_available(config),
9063 env.is_tiktok_public_comments_on(config),
9064 ),
9065 _fetch_tiktok,
9066 timeout=_memo_wait_seconds(config),
9067 cacheable=_clean_stream_result,
9068 cancel=config.get("_enrich_cancel"),
9069 )
9070 if source == "instagram":
9071 # Use raw_topic so expand_instagram_queries() generates diverse variants
9072 # from the original user topic, not the planner's narrowed search_query.
9073 ig_query = raw_topic or subquery.search_query
9074 has_ytdlp, ssh_host = _resolve_ytdlp(config)
9075 ig_deadline = _research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS)
9076 # Leave time to publish collected reels before the outer stream wait expires.
9077 remaining = max(0, ig_deadline - time.monotonic())
9078 ig_deadline -= min(1.0, remaining / 10)
9079 ig_cancel = config.get("_enrich_cancel")
9080
9081 def _fetch_instagram() -> tuple[list[dict], dict]:
9082 result = instagram.search_and_enrich(
9083 ig_query,
9084 from_date,
9085 to_date,
9086 depth=depth,
9087 token=env.get_instagram_token(config),
9088 ig_creators=ig_creators,
9089 config=config,
9090 deadline=ig_deadline,
9091 cancel=ig_cancel,
9092 )
9093 items = instagram.parse_instagram_response(result)
9094 if (
9095 items
9096 and env.is_instagram_comments_available(config)
9097 and not items[0].get("_oss_backend")
9098 ):
9099 instagram.enrich_with_comments(
9100 _comment_candidates(items, from_date, to_date, ig_creators, topic=ig_query),
9101 token=config.get("SCRAPECREATORS_API_KEY", ""),
9102 deadline=ig_deadline, cancel=ig_cancel,
9103 )
9104 if (ig_cancel is not None and ig_cancel.is_set()) or time.monotonic() >= ig_deadline:
9105 return items, _outcome_artifact(
9106 health.PARTIAL if items else health.TIMEOUT, instagram.RESEARCH_TIMEOUT,
9107 )
9108 return items, _result_outcome_artifact(source, result)
9109
9110 with youtube_yt.ssh_host_scope(ssh_host):
9111 return fetch_memo.fetch_once(
9112 (
9113 "instagram", ig_query, from_date, to_date, depth,
9114 bool(env.get_instagram_token(config)),
9115 has_ytdlp, ssh_host,
9116 tuple(ig_creators or ()),
9117 env.is_instagram_comments_available(config),
9118 ),
9119 _fetch_instagram,
9120 timeout=_memo_wait_seconds(config),
9121 cacheable=_clean_stream_result,
9122 cancel=ig_cancel,
9123 )
9124 if source == "linkedin":
9125 token = config.get("SCRAPECREATORS_API_KEY", "")
9126 result = linkedin.search_linkedin(
9127 subquery.search_query,
9128 from_date,
9129 to_date,
9130 depth=depth,
9131 token=token,
9132 )
9133 items = linkedin.parse_linkedin_response(
9134 result, from_date=from_date, to_date=to_date
9135 )
9136 # Articles never appear in post search — surface them (high signal)
9137 # via a bounded profile-enrichment lane on person topics.
9138 items += linkedin.enrich_articles(
9139 items, raw_topic or topic, token, from_date=from_date, to_date=to_date
9140 )
9141 return items, _result_outcome_artifact(source, result)
9142 if source == "hackernews":
9143 result = hackernews.search_hackernews(subquery.search_query, from_date, to_date, depth=depth)
9144 items = hackernews.parse_hackernews_response(result, query=subquery.search_query)
9145 # Attach top-level comments to the highest-point stories (bounded by
9146 # hackernews.ENRICH_LIMITS per depth).
9147 items = hackernews.enrich_top_stories(items, depth=depth)
9148 return items, _result_outcome_artifact(source, result)
9149 if source == "devto":
9150 relevance_topic = raw_topic or topic or subquery.search_query
9151 result = devto.search_devto(
9152 relevance_topic, from_date, to_date, depth=depth,
9153 tags=(config or {}).get("_devto_tags"),
9154 search_query=subquery.search_query,
9155 )
9156 items = devto.parse_devto_response(result, query=relevance_topic)
9157 # Comment enrichment is deferred to _finalize_items_by_source so it
9158 # lands on the articles that survive relevance pruning.
9159 return items, _result_outcome_artifact(source, result)
9160 if source == "v2ex":
9161 relevance_topic = raw_topic or topic or subquery.search_query
9162 result = v2ex.search_v2ex(
9163 relevance_topic, from_date, to_date, depth=depth,
9164 search_query=subquery.search_query,
9165 )
9166 items = v2ex.parse_v2ex_response(result, query=relevance_topic)
9167 # Reply enrichment is deferred to _finalize_items_by_source so it
9168 # lands on the topics that survive relevance pruning.
9169 return items, _result_outcome_artifact(source, result)
9170 if source == "juejin":
9171 relevance_topic = raw_topic or topic or subquery.search_query
9172 result = juejin.search_juejin(
9173 relevance_topic, from_date, to_date, depth=depth,
9174 search_query=subquery.search_query,
9175 )
9176 items = juejin.parse_juejin_response(result, query=relevance_topic)
9177 # Comment enrichment is deferred to _finalize_items_by_source so it
9178 # lands on the articles that survive relevance pruning.
9179 if detail := result.get("partial_error"):
9180 if items:
9181 return items, _outcome_artifact(schema.PARTIAL, detail)
9182 return items, _result_outcome_artifact(source, {"error": detail})
9183 return items, _result_outcome_artifact(source, result)
9184 if source == "stocktwits":
9185 # Pass raw_topic so symbol detection sees the full topic, not the
9186 # narrowed per-subquery search_query (same rationale as reddit).
9187 result = stocktwits.search_stocktwits(
9188 raw_topic or topic or subquery.search_query, from_date, to_date, depth=depth)
9189 return (
9190 stocktwits.parse_stocktwits_response(result, query=subquery.search_query),
9191 _result_outcome_artifact(source, result),
9192 )
9193 if source == "dripstack":
9194 result = dripstack.search_dripstack(
9195 subquery.search_query, from_date, to_date, depth=depth)
9196 relevance_topic = raw_topic or topic or subquery.search_query
9197 return (
9198 dripstack.parse_dripstack_response(result, query=relevance_topic),
9199 _result_outcome_artifact(source, result),
9200 )
9201 if source == "digg":
9202 # The thin-source retry's core subject often equals a planner
9203 # subquery's search, so share the identical CLI call within a run.
9204 result = fetch_memo.fetch_once(
9205 ("digg", subquery.search_query, from_date, to_date, depth),
9206 lambda: digg.search_digg(
9207 subquery.search_query, from_date, to_date, depth=depth,
9208 include_top_scored=True,
9209 deadline=config.get("_research_deadline"),
9210 cancel=config.get("_enrich_cancel"),
9211 ),
9212 timeout=_memo_wait_seconds(config),
9213 cacheable=_clean_search_result,
9214 cancel=config.get("_enrich_cancel"),
9215 )
9216 items = digg.parse_digg_response(
9217 result, query=subquery.search_query, from_date=from_date,
9218 )
9219 # Enrichment with attached X posts is deferred to
9220 # _finalize_items_by_source so it runs on the items that actually
9221 # survive dedupe rather than on top-K of the raw fanout.
9222 upgrade = digg.upgrade_note(result)
9223 if upgrade:
9224 return items, _outcome_artifact(health.PARTIAL, upgrade)
9225 score_pass = digg.score_pass_note(result)
9226 if score_pass:
9227 # The most relevant stories arrived, so Digg stays OK and the
9228 # lost highest-scored half is a note on its outcome.
9229 return items, {"_source_outcome_detail": score_pass}
9230 return items, _result_outcome_artifact(source, result)
9231 if source == "arxiv":
9232 result = arxiv.search_arxiv(subquery.search_query, from_date, to_date, depth=depth)
9233 # Relevance keys off the stable research topic, not the per-subquery
9234 # search_query, so off-topic narrowing does not let weak matches through.
9235 relevance_topic = raw_topic or topic or subquery.search_query
9236 return (
9237 arxiv.parse_arxiv_response(result, query=relevance_topic, to_date=to_date),
9238 _result_outcome_artifact(source, result),
9239 )
9240 if source == "techmeme":
9241 result = techmeme.search_techmeme(subquery.search_query, from_date, to_date, depth=depth)
9242 relevance_topic = raw_topic or topic or subquery.search_query
9243 return (
9244 techmeme.parse_techmeme_response(result, query=relevance_topic),
9245 _result_outcome_artifact(source, result),
9246 )
9247 if source == "news_rss":
9248 result = news_rss.search_news_rss(
9249 subquery.search_query, from_date, to_date, depth=depth, config=config,
9250 )
9251 relevance_topic = raw_topic or topic or subquery.search_query
9252 items = news_rss.parse_news_rss_response(result, query=relevance_topic)
9253 artifact = _result_outcome_artifact(source, result)
9254 if not artifact:
9255 failure_summary = news_rss.summarize_fetch_failures(result)
9256 if failure_summary:
9257 if items:
9258 artifact = _outcome_artifact(schema.PARTIAL, failure_summary)
9259 else:
9260 state, attempted = _classify_source_failure(SourceRunError(failure_summary))
9261 artifact = _outcome_artifact(state, failure_summary, attempted=attempted)
9262 return items, artifact
9263 if source == "trustpilot":
9264 # Brand-shape gate keys off the stable research topic, not the narrowed
9265 # per-subquery search_query, so the company is detected consistently.
9266 relevance_topic = raw_topic or topic or subquery.search_query
9267 result = trustpilot.search_trustpilot(
9268 relevance_topic, from_date, to_date, depth=depth, config=config,
9269 explicit_domain=trustpilot_domain,
9270 domain_is_hint=trustpilot_domain_is_hint,
9271 )
9272 if result.get("needs_session"):
9273 # An expected skip (no browser is ever opened for a session), not
9274 # a failure: recorded like a board that cannot answer the window.
9275 return [], {"_source_skipped": str(result.get("skipped") or "")}
9276 return (
9277 trustpilot.parse_trustpilot_response(result, query=relevance_topic),
9278 _result_outcome_artifact(source, result),
9279 )
9280 if source == "amazon":
9281 # The search keyword is model-supplied and may differ from the topic
9282 # ("Matt Van Horn" searches "June Oven"), so it keys off the stable
9283 # research topic rather than the narrowed per-subquery search_query.
9284 keyword = (
9285 str((config or {}).get("_amazon_query") or "").strip()
9286 or raw_topic or topic or subquery.search_query
9287 )
9288 domain = str((config or {}).get("LAST30DAYS_AMAZON_DOMAIN") or amazon.DEFAULT_DOMAIN)
9289 result = amazon.search_products(keyword, domain=domain, config=config)
9290 products = amazon.parse_search_response(result, keyword, domain=domain)
9291 artifact = _result_outcome_artifact(source, result)
9292
9293 # Skip enrichment when called from thin retry (_retry_thin_sources) to
9294 # avoid duplicate Bright Data pulls for ASINs already enriched in Phase 1.
9295 # Finalize will enrich any NEW products (enrich_source_items no-ops when
9296 # top_comments is already set, so duplicates get skipped there too).
9297 if skip_amazon_enrichment:
9298 return products, artifact
9299
9300 # Start review enrichment now, while other sources are still running.
9301 # Elapsed is measured from run_started so multi-source runs that finish
9302 # search quickly (30-90s) still have 190-250s of budget (clamped to 180).
9303 # This replaces the old deferred-to-finalize path which left only crumbs
9304 # (e.g. 11s) after long retrieval phases.
9305 elapsed = time.monotonic() - run_started if run_started else 0.0
9306 enriched, review_status = amazon.enrich_with_reviews(
9307 products,
9308 depth=depth,
9309 config=config,
9310 elapsed=elapsed,
9311 keyword=keyword,
9312 )
9313
9314 # Record PARTIAL status if review lane was skipped or all pulls dropped
9315 if review_status:
9316 artifact = artifact or {}
9317 artifact = dict(artifact) if artifact else {}
9318 artifact["_source_outcome"] = {
9319 "state": schema.PARTIAL,
9320 "detail": amazon.outcome_detail(review_status),
9321 "attempted": True,
9322 }
9323
9324 return enriched, artifact
9325 if source == "meta_ads":
9326 # The advertiser is resolved from the stable research topic, not the
9327 # narrowed per-subquery search_query: a subquery like "kettle reviews"
9328 # would resolve a different page than the brand the run is about.
9329 brand = raw_topic or topic or subquery.search_query
9330 result = meta_ads.search_meta_ads(
9331 brand,
9332 from_date,
9333 to_date,
9334 depth=depth,
9335 token=(config or {}).get("SCRAPECREATORS_API_KEY") or "",
9336 country=str(
9337 (config or {}).get("LAST30DAYS_META_ADS_COUNTRY")
9338 or meta_ads.DEFAULT_COUNTRY
9339 ),
9340 page_override=str((config or {}).get("_meta_ads_page") or "").strip(),
9341 )
9342 if result.get("partial"):
9343 # A partial lane carries `error` too, so the generic classifier
9344 # would run and have its verdict overwritten here regardless.
9345 artifact = {
9346 "_source_outcome": {
9347 "state": schema.PARTIAL,
9348 "detail": str(result.get("error") or "partial"),
9349 "attempted": True,
9350 }
9351 }
9352 elif result.get("outcome_state") and result.get("error"):
9353 artifact = _outcome_artifact(
9354 result["outcome_state"], str(result["error"]), attempted=True
9355 )
9356 else:
9357 artifact = dict(_result_outcome_artifact(source, result) or {})
9358 # The footer needs the resolved advertiser and the pre-truncation
9359 # counts even on a run that produced zero items, and stream artifacts
9360 # only reach the report through the grounding list, so they ride here
9361 # and are lifted to top-level artifacts after retrieval.
9362 artifact["meta_ads_page"] = result.get("page") or {}
9363 artifact["meta_ads_tally"] = result.get("tally") or {}
9364 return result.get("ads") or [], artifact
9365 if source == "bluesky":
9366 result = bluesky.search_bluesky(subquery.search_query, from_date, to_date, depth=depth, config=config)
9367 return bluesky.parse_bluesky_response(result), _result_outcome_artifact(source, result)
9368 if source == "threads":
9369 result = threads.search_threads(
9370 subquery.search_query, from_date, to_date,
9371 depth=depth,
9372 token=config.get("SCRAPECREATORS_API_KEY"),
9373 )
9374 return threads.parse_threads_response(result), _result_outcome_artifact(source, result)
9375 if source == "telegram":
9376 result = telegram.search_telegram(
9377 subquery.search_query, from_date, to_date,
9378 depth=depth,
9379 token=config.get("SCRAPECREATORS_API_KEY"),
9380 config=config,
9381 )
9382 return telegram.parse_telegram_response(result), _result_outcome_artifact(source, result)
9383 if source == "truthsocial":
9384 result = truthsocial.search_truthsocial(subquery.search_query, from_date, to_date, depth=depth, config=config)
9385 return truthsocial.parse_truthsocial_response(result), _result_outcome_artifact(source, result)
9386 if source == "polymarket":
9387 # Polymarket searches the stable research topic (plus the host's
9388 # aliases and related names), not the per-subquery search_query, so
9389 # every subquery and the thin-source retry share one search. The same
9390 # topic judges relevance: a narrowed subquery would let off-topic
9391 # markets through on broad passes and drop everything on narrow ones.
9392 relevance_topic = raw_topic or topic or subquery.search_query
9393 hints = polymarket.PolymarketHints.coerce((config or {}).get("_polymarket_hints"))
9394 result = fetch_memo.fetch_once(
9395 ("polymarket", relevance_topic, hints, from_date, to_date, depth),
9396 lambda: polymarket.search_polymarket(
9397 relevance_topic, from_date, to_date, depth=depth, hints=hints,
9398 deadline=_research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS),
9399 ),
9400 timeout=_memo_wait_seconds(config),
9401 cacheable=_clean_search_result,
9402 cancel=config.get("_enrich_cancel"),
9403 )
9404 if result.get("partial"):
9405 # Some term searches failed while others returned events: keep
9406 # what came back, report the lane partial, and (via `error`) keep
9407 # the incomplete result out of the fetch memo.
9408 artifact = {
9409 "_source_outcome": {
9410 "state": schema.PARTIAL,
9411 "detail": str(result.get("error") or "partial"),
9412 "attempted": True,
9413 }
9414 }
9415 else:
9416 artifact = _result_outcome_artifact(source, result)
9417 return (
9418 polymarket.parse_polymarket_response(
9419 result, topic=relevance_topic, hints=hints, to_date=to_date,
9420 ),
9421 artifact,
9422 )
9423 if source == "github":
9424 token = github.resolve_token(config.get("GITHUB_TOKEN"))
9425 deadline = config.get("_research_deadline")
9426 stopped_fn = lambda: _research_stopped(config)
9427 response = github.search_github(
9428 subquery.search_query,
9429 from_date,
9430 to_date,
9431 depth=depth,
9432 token=token,
9433 deadline=deadline,
9434 stopped=stopped_fn,
9435 )
9436 # Judge results against the stable research topic, not the narrowed
9437 # per-subquery search_query, as polymarket does above.
9438 relevance_topic = raw_topic or topic or subquery.search_query
9439 items = github.parse_github_response(response, topic=relevance_topic)
9440 # Title-first search can return zero topical matches when the planner
9441 # added extra keywords that appear only in issue bodies. Retry once
9442 # across title and body only after a clean, non-error, non-empty core
9443 # search while the run still has budget left so rate-limited, cancelled,
9444 # or qualifier-only queries never double-fetch.
9445 if (
9446 not items
9447 and not response.get("error")
9448 and not _research_stopped(config)
9449 and github.strip_search_qualifiers(github.extract_core_subject(subquery.search_query))
9450 ):
9451 fallback_response = github.search_github(
9452 subquery.search_query,
9453 from_date,
9454 to_date,
9455 depth=depth,
9456 token=token,
9457 title_only=False,
9458 deadline=deadline,
9459 stopped=stopped_fn,
9460 )
9461 fallback_items = github.parse_github_response(
9462 fallback_response, topic=relevance_topic
9463 )
9464 if fallback_items or fallback_response.get("error"):
9465 response = fallback_response
9466 items = fallback_items
9467 # Note: an unauth rate-limit (response["error"]) is expected on the
9468 # tokenless anon tier and returns empty here rather than raising — github
9469 # is now always eligible, so raising would spam "github failed" on every
9470 # tokenless run. The condition is logged in github.search_github.
9471 # Reserve a short return margin before _research_deadline so slow comment
9472 # fetches never cause the stream collector to discard already-found issues.
9473 comment_deadline = (deadline - 1.0) if deadline is not None else None
9474 if token and items and not _research_stopped(config):
9475 items = github.enrich_with_comments(
9476 items, depth=depth, deadline=comment_deadline, stopped=stopped_fn, to_date=to_date,
9477 )
9478 if response.get("stopped_reason"):
9479 state = schema.PARTIAL if items else health.TIMEOUT
9480 detail = str(response.get("error") or response["stopped_reason"])
9481 return items, _outcome_artifact(state, detail, attempted=True)
9482 return items, _result_outcome_artifact(source, response)
9483 if source == "pinterest":
9484 result = pinterest.search_pinterest(
9485 subquery.search_query, from_date, to_date,
9486 depth=depth,
9487 token=env.get_pinterest_token(config),
9488 )
9489 return pinterest.parse_pinterest_response(result), _result_outcome_artifact(source, result)
9490 if source == "xiaohongshu":
9491 return xiaohongshu_api.search_feeds(
9492 subquery.search_query,
9493 from_date,
9494 to_date,
9495 env.get_xiaohongshu_api_base(config),
9496 depth=depth,
9497 ), {}
9498 if source == "perplexity":
9499 return perplexity.search(subquery.search_query, date_range, config, deep=config.get("_deep_research", False))
9500 raise RuntimeError(f"Unsupported source: {source}")
9501
9502
9503 def _google_key(config: dict[str, Any]) -> str | None:
9504 return config.get("GOOGLE_API_KEY") or config.get("GEMINI_API_KEY") or config.get("GOOGLE_GENAI_API_KEY")
9505
9506
9507
9508
9509 def _mock_stream_results(source: str, subquery: schema.SubQuery) -> tuple[list[dict], dict]:
9510 # Namespace URLs and the canned comment by topic: real runs never hand two
9511 # distinct stories byte-identical evidence, and discovery's same-story fold
9512 # (correctly) collapses topics that share it. Mock enrichment sub-runs feed
9513 # this fixture one topic per subquery, so the slug keeps them distinct.
9514 slug = re.sub(r"[^a-z0-9]+", "-", subquery.search_query.lower()).strip("-") or "topic"
9515 payloads = {
9516 "reddit": [
9517 {
9518 "id": "R1",
9519 "title": f"{subquery.search_query} discussion thread",
9520 "url": f"https://reddit.com/r/example/comments/{slug}-1",
9521 "subreddit": "example",
9522 "date": dates.get_date_range(5)[0],
9523 "engagement": {"score": 120, "num_comments": 48, "upvote_ratio": 0.91},
9524 "selftext": f"Community discussion about {subquery.search_query}.",
9525 "top_comments": [{"excerpt": f"Strong firsthand feedback from {subquery.search_query} users."}],
9526 "relevance": 0.82,
9527 "why_relevant": "Mock Reddit result",
9528 }
9529 ],
9530 "x": [
9531 {
9532 "id": "X1",
9533 "text": f"People on X are discussing {subquery.search_query} right now.",
9534 "url": f"https://x.com/example/status/{slug}-1",
9535 "author_handle": "example",
9536 "date": dates.get_date_range(2)[0],
9537 "engagement": {"likes": 200, "reposts": 35, "replies": 18, "quotes": 4},
9538 "relevance": 0.79,
9539 "why_relevant": "Mock X result",
9540 }
9541 ],
9542 "grounding": [
9543 {
9544 "id": "WB1",
9545 "title": f"{subquery.search_query} article",
9546 "url": f"https://example.com/article/{slug}",
9547 "source_domain": "example.com",
9548 "snippet": f"Recent web reporting about {subquery.search_query}.",
9549 "date": dates.get_date_range(7)[0],
9550 "relevance": 0.88,
9551 "why_relevant": "Brave web search",
9552 }
9553 ],
9554 "digg": [
9555 {
9556 "id": "mock1abc",
9557 "title": f"Digg cluster about {subquery.search_query}",
9558 "url": f"https://digg.com/ai/mock1abc-{slug}",
9559 "tldr": f"Curated cluster summarizing recent {subquery.search_query} discussion across the AI 1000.",
9560 "author": "",
9561 "date": dates.get_date_range(3)[0],
9562 "engagement": {"postCount": 8, "uniqueAuthors": 5, "rank": 2, "rank_score": 49.0},
9563 "first_post_age": "3d",
9564 "posts": [
9565 {
9566 "username": "exampledev",
9567 "display_name": "Example Dev",
9568 "category": "Engineer",
9569 "rank": 142,
9570 "body": f"Quote from the AI 1000 about {subquery.search_query}.",
9571 "post_type": "tweet",
9572 "x_url": "https://x.com/exampledev/status/1",
9573 "posted_at": dates.get_date_range(3)[0],
9574 },
9575 ],
9576 "relevance": 0.84,
9577 "why_relevant": "Mock Digg cluster",
9578 },
9579 {
9580 "id": "mock2def",
9581 "title": f"Second Digg cluster on {subquery.search_query}",
9582 "url": f"https://digg.com/ai/mock2def-{slug}",
9583 "tldr": f"Another angle on {subquery.search_query}.",
9584 "author": "",
9585 "date": dates.get_date_range(8)[0],
9586 "engagement": {"postCount": 3, "uniqueAuthors": 2, "rank": 18, "rank_score": 33.0},
9587 "first_post_age": "8d",
9588 "posts": [],
9589 "relevance": 0.71,
9590 "why_relevant": "Mock Digg cluster",
9591 },
9592 ],
9593 "arxiv": [
9594 {
9595 "id": f"http://arxiv.org/abs/2606.00001v1-{slug}",
9596 "title": f"A Survey of {subquery.search_query}",
9597 "url": f"https://arxiv.org/abs/2606.00001v1-{slug}",
9598 "summary": f"We present a comprehensive study of {subquery.search_query} and its recent advances.",
9599 "author": "Ada Lovelace et al.",
9600 "authors": ["Ada Lovelace", "Alan Turing"],
9601 "date": dates.get_date_range(20)[0],
9602 "engagement": {},
9603 "relevance": 0.86,
9604 "why_relevant": "Mock arXiv paper",
9605 },
9606 ],
9607 "techmeme": [
9608 {
9609 "id": f"https://www.techmeme.com/260627/p1-{slug}",
9610 "title": f"Major development in {subquery.search_query} reshapes the industry",
9611 "url": f"https://www.techmeme.com/260627/p1-{slug}",
9612 "source_name": "techcrunch.com",
9613 "date": dates.get_date_range(1)[0],
9614 "engagement": {},
9615 "relevance": 0.83,
9616 "why_relevant": "Mock Techmeme headline",
9617 },
9618 ],
9619 "news_rss": [
9620 {
9621 "id": f"nr-{slug}-1",
9622 "title": f"Mainstream coverage highlights major developments around {subquery.search_query}",
9623 "summary": f"Reporting across multiple national outlets examines recent milestones for {subquery.search_query}.",
9624 "url": f"https://www.reuters.com/world/{slug}-developments",
9625 "publisher": "Reuters",
9626 "publisher_domain": "reuters.com",
9627 "date": dates.get_date_range(2)[0],
9628 "cluster_count": 3,
9629 "cluster_outlets": ["Reuters", "Bloomberg", "Associated Press"],
9630 "rss_source": "google-news+bing-news",
9631 "relevance": 0.86,
9632 "why_relevant": "Reuters · 3 outlets · google-news+bing-news",
9633 },
9634 ],
9635 "dripstack": [
9636 {
9637 "id": "DS1",
9638 "title": f"Deep dive: {subquery.search_query} from a paid newsletter",
9639 "url": f"https://newsletter.example.com/deep-dive-{slug}",
9640 "author": "newsletter.example.com",
9641 "date": dates.get_date_range(3)[0],
9642 "engagement": {},
9643 "relevance": 0.85,
9644 "why_relevant": "Mock DripStack newsletter result",
9645 "snippet": f"Professional analyst coverage of {subquery.search_query}.",
9646 "metadata": {
9647 "publication_slug": "newsletter.example.com",
9648 "post_slug": "deep-dive",
9649 "relevance_score": 85,
9650 "match_confidence": "strong",
9651 },
9652 },
9653 ],
9654 "trustpilot": [
9655 {
9656 "id": "example.com",
9657 "title": f"{subquery.search_query}: TrustScore 3.4",
9658 "url": f"https://www.trustpilot.com/review/{slug}.example.com",
9659 "summary": f"Across recent reviews, customers were split on {subquery.search_query}: some praised support, others cited delays.",
9660 "name": subquery.search_query,
9661 "trustScore": 3.4,
9662 "reviewCount": 128,
9663 "date": dates.get_date_range(1)[0],
9664 "engagement": {"reviews": 128, "trustScore": 3.4},
9665 "relevance": 0.8,
9666 "why_relevant": "Mock Trustpilot sentiment",
9667 },
9668 ],
9669 # Three products spanning the drift states the footer renders: one
9670 # sagging below its all-time average (with enough in-window reviews
9671 # to clear the arrow threshold), one steady, and one too new to have
9672 # a baseline. Mock runs exercise the full R1c line without a CLI.
9673 "amazon": [
9674 {
9675 "asin": "B0MOCK00X1",
9676 "date": dates.get_date_range(1)[1],
9677 "name": f"{subquery.search_query} Pro Model | Flagship Edition",
9678 "short_name": "Pro Model",
9679 "brand": subquery.search_query.split()[0].title() if subquery.search_query else "Example",
9680 "url": "https://www.amazon.com/dp/B0MOCK00X1",
9681 "rating": 4.4,
9682 "num_ratings": 459,
9683 "price": 39.99,
9684 "currency": "USD",
9685 "badge": "Best Seller",
9686 "sponsored": False,
9687 "relevance": 0.85,
9688 "why_relevant": "Mock Amazon product",
9689 "product_rating": 4.4,
9690 "product_rating_count": 459,
9691 "star_distribution": {
9692 "one_star": 28, "two_star": 9, "three_star": 28,
9693 "four_star": 60, "five_star": 335,
9694 },
9695 "top_comments": [
9696 {
9697 "score": 3, "rating": 2, "verified": True,
9698 "date": dates.get_date_range(3)[1],
9699 "excerpt": "The tray shifts in transit and the lid jams shut.",
9700 "title": "Lid jams",
9701 },
9702 {
9703 "score": 1, "rating": 4, "verified": True,
9704 "date": dates.get_date_range(9)[1],
9705 "excerpt": "Solid build, but arrived with a dented panel.",
9706 "title": "Shipping dent",
9707 },
9708 {
9709 "score": 0, "rating": 5, "verified": True,
9710 "date": dates.get_date_range(14)[1],
9711 "excerpt": "Keeps everything cold through a full school day.",
9712 "title": "Works great",
9713 },
9714 {
9715 "score": 0, "rating": 4, "verified": True,
9716 "date": dates.get_date_range(19)[1],
9717 "excerpt": "Good size for the price.",
9718 "title": "Good value",
9719 },
9720 {
9721 "score": 0, "rating": 4, "verified": False,
9722 "date": dates.get_date_range(24)[1],
9723 "excerpt": "Does the job, nothing fancy.",
9724 "title": "Fine",
9725 },
9726 ],
9727 },
9728 {
9729 "asin": "B0MOCK00X2",
9730 "date": dates.get_date_range(1)[1],
9731 "name": f"{subquery.search_query} Classic | Everyday Model",
9732 "short_name": "Classic",
9733 "brand": subquery.search_query.split()[0].title() if subquery.search_query else "Example",
9734 "url": "https://www.amazon.com/dp/B0MOCK00X2",
9735 "rating": 4.7,
9736 "num_ratings": 8446,
9737 "price": 24.99,
9738 "currency": "USD",
9739 "sponsored": False,
9740 "relevance": 0.8,
9741 "why_relevant": "Mock Amazon product",
9742 "product_rating": 4.7,
9743 "product_rating_count": 8446,
9744 "star_distribution": {
9745 "one_star": 120, "two_star": 90, "three_star": 300,
9746 "four_star": 1010, "five_star": 6926,
9747 },
9748 "top_comments": [
9749 {
9750 "score": 12, "rating": 5, "verified": True,
9751 "date": dates.get_date_range(4)[1],
9752 "excerpt": "Third one we've bought. They last.",
9753 "title": "Repeat buyer",
9754 },
9755 ],
9756 },
9757 {
9758 "asin": "B0MOCK00X3",
9759 "date": dates.get_date_range(1)[1],
9760 "name": f"{subquery.search_query} Mini | New Release",
9761 "short_name": "Mini",
9762 "brand": subquery.search_query.split()[0].title() if subquery.search_query else "Example",
9763 "url": "https://www.amazon.com/dp/B0MOCK00X3",
9764 "rating": None,
9765 "num_ratings": 57,
9766 "price": 19.99,
9767 "currency": "USD",
9768 "sponsored": False,
9769 "relevance": 0.72,
9770 "why_relevant": "Mock Amazon product",
9771 },
9772 ],
9773 "jobs": [
9774 {
9775 "id": "J1",
9776 "title": "Founding Enterprise Solutions Engineer",
9777 "url": f"https://boards.greenhouse.io/example/jobs/{slug}-1",
9778 "description": (
9779 f"Work with enterprise customers on SSO, SOC 2, security, "
9780 f"and procurement workflows for {subquery.search_query}."
9781 ),
9782 "department": "Sales",
9783 "location": "San Francisco, CA",
9784 "date": dates.get_date_range(4)[0],
9785 "provider": "mock",
9786 "relevance": 0.8,
9787 "why_relevant": "Mock public job posting",
9788 },
9789 {
9790 "id": "J2",
9791 "title": "Security Platform Engineer",
9792 "url": f"https://boards.greenhouse.io/example/jobs/{slug}-2",
9793 "description": "Build enterprise security, audit, and admin workflows.",
9794 "department": "Engineering",
9795 "location": "Remote",
9796 "date": dates.get_date_range(6)[0],
9797 "provider": "mock",
9798 "relevance": 0.78,
9799 "why_relevant": "Mock public job posting",
9800 },
9801 ],
9802 }
9803 if source == "grounding":
9804 return payloads.get(source, []), {
9805 "label": subquery.label,
9806 "mock": True,
9807 "webSearchQueries": [subquery.search_query],
9808 "resultCount": 1,
9809 }
9810 return payloads.get(source, []), {}
9811
9811 lines PYTHON