Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(pipeline): bound X-chain and stream waits with deadlines (#1165)

Ilia Alshanetskya78a919e294a
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 9cbd41a2..003963b6 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -105,6 +105,7 @@ These variables configure the local Go MCP server and are read from its process
|---|---|---|---|
| `LAST30DAYS_PYTHON` | unset | An executable name or path | Selects the Python 3.12+ interpreter used by the MCP server. A caller-supplied `RunOptions.PythonPath` remains the test/caller override; otherwise this variable must resolve to an executable. When it is unset, the server looks up `python3` on `PATH`. An empty or unresolvable value is an error rather than a fallback. |
| `LAST30DAYS_MCP_ALLOW_BROWSER_COOKIES` | unset (deny) | `1`, `true`, `yes`, or `on`, case-insensitive | A recognized truthy value removes the MCP layer's default `--no-browser-cookies` flag. Every other value keeps that denial. This switch grants no consent by itself: browser-cookie access still requires the engine's separately recorded consent and `FROM_BROWSER` configuration. |
+| `LAST30DAYS_MCP_TIMEOUT` | `600` seconds (10 minutes) | A positive Go duration such as `10m`, `90s`, or `1m30s`, or a positive integer number of seconds such as `600` | Caps each research subprocess. The default accommodates deep discovery enrichment. Invalid, zero, and negative values use the default. An explicit caller timeout takes precedence. Source and enrichment deadlines can finish earlier; increasing this cap also extends how long a hung subprocess can occupy an MCP slot. |
## API keys (`.env`)
diff --git a/changelog.d/+timeout-architecture.fixed.md b/changelog.d/+timeout-architecture.fixed.md
new file mode 100644
index 00000000..0330996f
--- /dev/null
+++ b/changelog.d/+timeout-architecture.fixed.md
@@ -0,0 +1 @@
+Bound X searches, source waits, and discovery enrichment with shared deadlines. Cancelled enrichment stops later supplemental searches, X retries, and pipeline provider phases; completed evidence survives source timeouts as partial results. Bird searches that complete empty before the budget blocks optional retries retain their no-results status and show a partial-coverage warning. In-flight subprocesses retain their bounded timeouts. Raised the MCP subprocess timeout to 600 seconds (10 minutes) to accommodate deep enrichment; `LAST30DAYS_MCP_TIMEOUT` overrides it. The longer cap also lets a hung subprocess occupy an MCP slot longer.
diff --git a/mcp/internal/engine/run.go b/mcp/internal/engine/run.go
index 5f635c70..b79a3008 100644
--- a/mcp/internal/engine/run.go
+++ b/mcp/internal/engine/run.go
@@ -27,10 +27,11 @@ const MinPythonVersion = "3.12"
// have a direct route from the failure to a fix.
const PythonInstallURL = "https://www.python.org/downloads/"
-// DefaultTimeout caps a single research subprocess. The engine's deep mode
-// can run several minutes; five minutes is a safe upper bound that still
-// fails fast when something hangs.
-const DefaultTimeout = 5 * time.Minute
+// DefaultTimeout caps a single research subprocess. The engine's deep-tier
+// resume enrichment alone budgets 450s, so ten minutes is the floor that lets
+// a full run finish; the per-stream and X-chain deadlines inside the pipeline
+// still fail fast when something hangs.
+const DefaultTimeout = 10 * time.Minute
// TimeoutEnvOverride lets operators override DefaultTimeout per install
// (seconds, integer). Honored by Run when RunOptions.Timeout is zero.
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index 67ce8102..4b8f9cdf 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -359,7 +359,29 @@ def _invoke_bird_subprocess(query: str, count: int, timeout: int):
return result, None
-def _run_bird_search(query: str, count: int, timeout: int) -> Dict[str, Any]:
+def _invalid_json_error(
+ attempts: int,
+ decode_error: Optional[str],
+ budget_exhausted: bool = False,
+) -> Dict[str, Any]:
+ noun = "attempt" if attempts == 1 else "attempts"
+ skipped = ", retry skipped: chain budget exhausted" if budget_exhausted else ""
+ return {
+ "error": (
+ f"Invalid JSON response after {attempts} {noun}{skipped} "
+ f"(likely Twitter anti-bot interstitial): {decode_error}"
+ ),
+ "items": [],
+ }
+
+
+def _run_bird_search(
+ query: str,
+ count: int,
+ timeout: int,
+ deadline: Optional[float] = None,
+ cancel: Any = None,
+) -> Dict[str, Any]:
"""Run a search using the vendored bird-search.mjs module.
Retries the subprocess on JSON-decode failure (typically a Twitter
@@ -372,14 +394,27 @@ def _run_bird_search(query: str, count: int, timeout: int) -> Dict[str, Any]:
query: Full search query string (including since: filter)
count: Number of results to request
timeout: Timeout in seconds (per attempt)
+ deadline: Optional shared ``time.monotonic()`` deadline. A decode
+ retry runs only when the delay plus at least one second of
+ subprocess time still fits; its timeout is re-clamped after the
+ delay.
Returns:
Raw Bird JSON response or error dict.
"""
last_decode_error: Optional[str] = None
+ attempt_timeout: Optional[int] = timeout
for attempt in range(MAX_JSON_DECODE_RETRIES):
- result, terminal_error = _invoke_bird_subprocess(query, count, timeout)
+ if cancel is not None and cancel.is_set():
+ return {"error": "bird: research cancelled", "items": []}
+ if attempt > 0:
+ attempt_timeout = _clamped_bird_timeout(timeout, deadline)
+ if attempt_timeout is None:
+ return _invalid_json_error(
+ attempt, last_decode_error, budget_exhausted=True,
+ )
+ result, terminal_error = _invoke_bird_subprocess(query, count, attempt_timeout)
if terminal_error is not None:
return terminal_error
@@ -413,21 +448,29 @@ def _run_bird_search(query: str, count: int, timeout: int) -> Dict[str, Any]:
)
last_decode_error = str(e)
if attempt_num < MAX_JSON_DECODE_RETRIES:
+ if deadline is not None and (
+ deadline - time.monotonic() < JSON_DECODE_RETRY_DELAY + 1
+ ):
+ log.source_log(
+ "X/bird",
+ f"{log_msg}; retry skipped, chain budget exhausted",
+ tty_only=False,
+ )
+ return _invalid_json_error(
+ attempt_num, last_decode_error, budget_exhausted=True,
+ )
log.source_log(
"X/bird",
f"{log_msg}; retrying in {JSON_DECODE_RETRY_DELAY:.0f}s",
tty_only=False,
)
- time.sleep(JSON_DECODE_RETRY_DELAY)
+ if cancel is not None:
+ cancel.wait(JSON_DECODE_RETRY_DELAY)
+ else:
+ time.sleep(JSON_DECODE_RETRY_DELAY)
continue
log.source_log("X/bird", log_msg, tty_only=False)
- return {
- "error": (
- f"Invalid JSON response after {MAX_JSON_DECODE_RETRIES} attempts "
- f"(likely Twitter anti-bot interstitial): {e}"
- ),
- "items": [],
- }
+ return _invalid_json_error(attempt_num, last_decode_error)
if isinstance(parsed, list):
return {"items": parsed}
@@ -440,11 +483,46 @@ def _run_bird_search(query: str, count: int, timeout: int) -> Dict[str, Any]:
}
+def _clamped_bird_timeout(base: int, deadline: Optional[float]) -> Optional[int]:
+ """Per-attempt timeout clamped to the chain's remaining budget.
+
+ Returns None when the deadline already passed so the caller skips the
+ subprocess instead of starting a call guaranteed to overrun the chain.
+ """
+ if deadline is None:
+ return base
+ remaining = deadline - time.monotonic()
+ if remaining < 1:
+ return None
+ return max(1, min(base, int(remaining)))
+
+
+def _budget_stop(
+ response: Dict[str, Any],
+ last_clean_response: Optional[Dict[str, Any]],
+) -> Dict[str, Any]:
+ """Outcome when an optional zero-result retry no longer fits the budget.
+
+ A clean empty response stays a no-results outcome with a coverage warning;
+ otherwise the earlier search's own error (interstitial, timeout) is more
+ diagnostic than a generic budget message.
+ """
+ _log("chain budget exhausted; skipping remaining zero-result retries")
+ if last_clean_response is not None:
+ return {
+ **last_clean_response,
+ "warning": "Partial coverage: optional zero-result retries skipped because the search budget was exhausted.",
+ }
+ return response
+
+
def search_x(
topic: str,
from_date: str,
to_date: str,
depth: str = "default",
+ deadline: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Search X using Bird CLI with automatic retry on 0 results.
@@ -453,12 +531,20 @@ def search_x(
from_date: Start date (YYYY-MM-DD)
to_date: Inclusive end date (YYYY-MM-DD)
depth: Research depth - "quick", "default", or "deep"
+ deadline: Optional shared wall-clock deadline (``time.monotonic()``
+ instant) from the X backend chain. Each of the up-to-four
+ sequential searches clamps its per-attempt timeout to the time
+ left; searches past the deadline never start.
Returns:
Raw Bird JSON response or error dict.
"""
count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
- timeout = 30 if depth == "quick" else 45 if depth == "default" else 60
+ cancel_kwargs = {"cancel": cancel} if cancel is not None else {}
+ base_timeout = 30 if depth == "quick" else 45 if depth == "default" else 60
+ timeout = _clamped_bird_timeout(base_timeout, deadline)
+ if timeout is None:
+ return {"error": "bird: chain budget exhausted", "items": []}
# Extract core subject - X search is literal, not semantic
core_subject = _extract_core_subject(topic)
@@ -468,7 +554,7 @@ def search_x(
date_filters = _date_filters(from_date, to_date)
_log(f"Searching: {query}")
- response = _run_bird_search(query, count, timeout)
+ response = _run_bird_search(query, count, timeout, deadline=deadline, **cancel_kwargs)
last_clean_response = response if not response.get("error") else None
# Check if we got results
@@ -483,7 +569,10 @@ def search_x(
or_parts = ' OR '.join(f'"{t}"' for t in compounds[:3])
_log(f"0 results for '{core_topic}', retrying with OR groups: {or_parts}")
query = f"({or_parts}) {date_filters}"
- response = _run_bird_search(query, count, timeout)
+ timeout = _clamped_bird_timeout(base_timeout, deadline)
+ if timeout is None:
+ return _budget_stop(response, last_clean_response)
+ response = _run_bird_search(query, count, timeout, deadline=deadline, **cancel_kwargs)
if not response.get("error"):
last_clean_response = response
items = parse_bird_response(response, query=core_topic)
@@ -493,7 +582,10 @@ def search_x(
shorter = ' '.join(core_words[:2])
_log(f"0 results for '{core_topic}', retrying with '{shorter}'")
query = f"{shorter} {date_filters}"
- response = _run_bird_search(query, count, timeout)
+ timeout = _clamped_bird_timeout(base_timeout, deadline)
+ if timeout is None:
+ return _budget_stop(response, last_clean_response)
+ response = _run_bird_search(query, count, timeout, deadline=deadline, **cancel_kwargs)
if not response.get("error"):
last_clean_response = response
items = parse_bird_response(response, query=core_topic)
@@ -518,10 +610,15 @@ def search_x(
retry_terms = anchor if strongest == anchor else f"{anchor} {strongest}"
_log(f"0 results for '{core_topic}', retrying anchored on '{retry_terms}'")
query = f"{retry_terms} {date_filters}"
- response = _run_bird_search(query, count, timeout)
+ timeout = _clamped_bird_timeout(base_timeout, deadline)
+ if timeout is None:
+ return _budget_stop(response, last_clean_response)
+ response = _run_bird_search(query, count, timeout, deadline=deadline, **cancel_kwargs)
if not response.get("error"):
last_clean_response = response
+ if cancel is not None and cancel.is_set():
+ return {**response, "error": "bird: research cancelled"}
if response.get("error") and last_clean_response is not None:
_log("Optional retry failed after a clean empty response; preserving no-results outcome")
return last_clean_response
@@ -536,6 +633,8 @@ def search_handles(
failure_out: Optional[List[str]] = None,
*,
to_date: Optional[str] = None,
+ deadline: Optional[float] = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""Search specific X handles for topic-related content.
@@ -566,6 +665,10 @@ def search_handles(
failure_out.append(msg)
def _search_one_handle(handle: str) -> List[Dict[str, Any]]:
+ timeout = _clamped_bird_timeout(15, deadline)
+ if timeout is None or (cancel is not None and cancel.is_set()):
+ _note("bird handle research cancelled or timed out")
+ return []
handle = handle.lstrip("@")
# Always unfiltered: pull the timeline, rank by topic relevance below.
query = f"from:{handle} {date_filters}"
@@ -578,7 +681,7 @@ def search_handles(
]
try:
- result = subproc.run_with_timeout(cmd, timeout=15, env=_subprocess_env())
+ result = subproc.run_with_timeout(cmd, timeout=timeout, env=_subprocess_env())
except subproc.SubprocTimeout:
_log(f"Handle search timed out for @{handle}")
_note(f"@{handle}: bird-search timed out after 15s")
@@ -633,6 +736,8 @@ def search_mentions(
failure_out: Optional[List[str]] = None,
*,
to_date: Optional[str] = None,
+ deadline: Optional[float] = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""Search for tweets ABOUT/TO each handle — the mention lane.
@@ -660,6 +765,10 @@ def search_mentions(
failure_out.append(msg)
def _search_one(handle: str) -> List[Dict[str, Any]]:
+ timeout = _clamped_bird_timeout(15, deadline)
+ if timeout is None or (cancel is not None and cancel.is_set()):
+ _note("bird mention research cancelled or timed out")
+ return []
handle = handle.lstrip("@")
query = f"@{handle} {date_filters}"
cmd = [
@@ -669,7 +778,7 @@ def search_mentions(
"--json",
]
try:
- result = subproc.run_with_timeout(cmd, timeout=15, env=_subprocess_env())
+ result = subproc.run_with_timeout(cmd, timeout=timeout, env=_subprocess_env())
except subproc.SubprocTimeout:
_log(f"Mention search timed out for @{handle}")
_note(f"@{handle}: bird-search timed out after 15s")
diff --git a/skills/last30days/scripts/lib/grok_x.py b/skills/last30days/scripts/lib/grok_x.py
index b4f7ec86..fb977b2b 100644
--- a/skills/last30days/scripts/lib/grok_x.py
+++ b/skills/last30days/scripts/lib/grok_x.py
@@ -845,6 +845,7 @@ def _run_query(
attempts: int = 2,
relevance_topic: str = "",
deadline: Optional[float] = None,
+ cancel: Optional[Any] = None,
) -> Tuple[List[Dict[str, Any]], str, bool]:
"""Run one query, retrying only when the response looks fabricated.
@@ -860,11 +861,13 @@ def _run_query(
prompt = _PROMPT.format(tool=tool, query=query, limit=min(limit, _MAX_LIMIT_PER_CALL))
last_error = ""
for attempt in range(1, attempts + 1):
+ if cancel is not None and cancel.is_set():
+ return [], last_error or "X research cancelled", False
if deadline is not None:
remaining = deadline - time.monotonic()
if remaining < _MIN_USEFUL_CALL_SECONDS:
- return [], last_error or "X lane budget exhausted", False
- timeout = min(timeout, int(remaining))
+ return [], "X lane budget exhausted (timed out)", False
+ timeout = min(timeout, max(1, int(remaining)))
_log(f"searching: {query}" + (f" (attempt {attempt})" if attempt > 1 else ""))
response = _invoke(prompt, timeout)
if response.get("error"):
@@ -892,6 +895,8 @@ def search_x(
from_date: str,
to_date: str,
depth: str = "default",
+ deadline: Optional[float] = None,
+ cancel: Optional[Any] = None,
) -> Dict[str, Any]:
"""Search X for a topic, fanning out to reach the depth's target count.
@@ -900,6 +905,13 @@ def search_x(
ahead of bird in the chain -- silently downgrading a `--deep` run from 60
posts to 10.
+ ``deadline`` is the X chain's shared ``time.monotonic()`` budget (see
+ pipeline's ``X_CHAIN_DEADLINE_SECONDS``): each fan-out call clamps its
+ per-call timeout to the time left, and calls past the deadline are never
+ started, so grok cannot consume the whole chain budget alone. ``cancel``
+ is an optional ``threading.Event`` (the enrichment batch's cooperative
+ cancel): set means not-yet-started fan-out queries are skipped.
+
Returns {'items': [...]}; 'error' is set only for an actual invocation
failure. A completed run that found nothing returns an empty list with no
error, matching bird and xquik -- reporting "no results" as a hard failure
@@ -917,15 +929,27 @@ def search_x(
invocation_failed = False
auth_revoked = False
for mode_query in _fanout_queries(topic, from_date, to_date, calls):
+ if deadline is not None and time.monotonic() >= deadline:
+ if not last_error:
+ last_error = "X lane budget exhausted"
+ invocation_failed = True
+ _log("chain deadline reached; skipping remaining grok queries")
+ break
+ if cancel is not None and getattr(cancel, "is_set", lambda: False)():
+ if not last_error:
+ last_error = "enrichment budget exhausted"
+ invocation_failed = True
+ _log("enrichment cancelled; skipping remaining grok queries")
+ break
items, error, revoked = _run_query(mode_query, from_date, to_date, depth=depth,
- relevance_topic=topic)
+ relevance_topic=topic, deadline=deadline, cancel=cancel)
if revoked:
auth_revoked = True
last_error = error or "Grok session expired or was revoked"
break
if error and not items:
last_error = error
- if "not found" in error or "timed out" in error or "exited" in error:
+ if any(marker in error for marker in ("not found", "timed out", "exited", "cancelled", "budget exhausted")):
invocation_failed = True
for item in items:
key = item["url"]
@@ -938,11 +962,19 @@ def search_x(
item["id"] = f"GK{index}"
if collected:
result: Dict[str, Any] = {"items": collected[:target]}
+ if not auth_revoked and (
+ (cancel is not None and cancel.is_set())
+ or (deadline is not None and time.monotonic() >= deadline)
+ or "budget exhausted" in last_error
+ ):
+ result["error"] = "X research cancelled or timed out"
if auth_revoked:
result["auth_revoked"] = True
return result
if auth_revoked:
return {"items": [], "error": last_error, "auth_revoked": True}
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
+ return {"items": [], "error": "X research cancelled or timed out"}
if invocation_failed:
return {"items": [], "error": last_error}
return {"items": []}
@@ -957,6 +989,7 @@ def search_handles(
count_per: int = 8,
deadline: Optional[float] = None,
and_topic: bool = False,
+ cancel: Optional[Any] = None,
) -> Tuple[List[Dict[str, Any]], bool]:
"""BY lane: posts authored by each handle.
@@ -973,7 +1006,7 @@ def search_handles(
collected: List[Dict[str, Any]] = []
auth_revoked = False
for handle in handles:
- if deadline is not None and time.monotonic() >= deadline:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
_log("lane budget exhausted; skipping remaining handles")
break
clean = _clean_handle(handle)
@@ -987,7 +1020,7 @@ def search_handles(
items, _, revoked = _run_query(
query,
from_date, to_date, limit=count_per, relevance_topic=topic,
- attempts=1, deadline=deadline,
+ attempts=1, deadline=deadline, cancel=cancel,
)
if revoked:
_log("Grok session revoked; stopping lane")
@@ -1008,6 +1041,7 @@ def search_mentions(
topic: str = "",
count_per: int = 5,
deadline: Optional[float] = None,
+ cancel: Optional[Any] = None,
) -> Tuple[List[Dict[str, Any]], bool]:
"""ABOUT lane (mention form): posts @-mentioning each handle.
@@ -1016,7 +1050,7 @@ def search_mentions(
collected: List[Dict[str, Any]] = []
auth_revoked = False
for handle in handles:
- if deadline is not None and time.monotonic() >= deadline:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
_log("lane budget exhausted; skipping remaining handles")
break
clean = _clean_handle(handle)
@@ -1025,7 +1059,7 @@ def search_mentions(
items, _, revoked = _run_query(
f"@{clean} -from:{clean} since:{from_date} until:{to_date}",
from_date, to_date, limit=count_per, relevance_topic=topic,
- attempts=1, deadline=deadline,
+ attempts=1, deadline=deadline, cancel=cancel,
)
if revoked:
_log("Grok session revoked; stopping lane")
@@ -1047,6 +1081,7 @@ def search_name(
count_per: int = 8,
min_faves: int = 2,
deadline: Optional[float] = None,
+ cancel: Optional[Any] = None,
) -> Tuple[List[Dict[str, Any]], bool]:
"""ABOUT lane (name form): posts naming the subject in plain text.
@@ -1075,7 +1110,7 @@ def search_name(
if part
)
items, _, revoked = _run_query(
- query, from_date, to_date, limit=count_per, attempts=1, deadline=deadline,
+ query, from_date, to_date, limit=count_per, attempts=1, deadline=deadline, cancel=cancel,
)
if revoked:
_log("Grok session revoked")
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index b5f0c26c..57bcd83c 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -764,6 +764,7 @@ def request(
max_429_retries: int = MAX_429_RETRIES,
raw: bool = False,
deadline_monotonic: float | None = None,
+ cancel: threading.Event | None = None,
) -> Union[Dict[str, Any], str]:
"""Make an HTTP request and return JSON response.
@@ -852,7 +853,12 @@ def request(
if remaining <= 0 or delay >= remaining:
last_error = deadline_error()
return False
- time.sleep(delay)
+ if cancel is not None:
+ if cancel.wait(delay):
+ last_error = deadline_error()
+ return False
+ else:
+ time.sleep(delay)
return True
def open_and_read(
@@ -875,32 +881,47 @@ def request(
request_timeout: float,
) -> tuple[int, str | None, urllib.error.HTTPError | None]:
"""Stop waiting at the wall deadline, even during DNS or body reads."""
- if deadline_monotonic is None:
+ if deadline_monotonic is None and cancel is None:
return open_and_read(request_timeout)
- remaining = deadline_monotonic - time.monotonic()
+ wait_deadline = deadline_monotonic or (time.monotonic() + request_timeout)
+ remaining = wait_deadline - time.monotonic()
if remaining <= 0:
raise deadline_error()
future: Future = Future()
def worker() -> None:
try:
+ if cancel is not None and cancel.is_set():
+ raise deadline_error()
future.set_result(open_and_read(request_timeout))
except BaseException as exc:
future.set_exception(exc)
threading.Thread(target=worker, daemon=True).start()
- try:
- return future.result(timeout=remaining)
- except TimeoutError as exc:
- # A worker-side socket TimeoutError is a transport failure, not
- # proof that the command-wide wall deadline expired. Re-read a
- # completed future so its original exception reaches the normal
- # transport classifier below.
- if future.done():
- return future.result()
- raise deadline_error() from exc
+ if cancel is None:
+ try:
+ return future.result(timeout=remaining)
+ except TimeoutError as exc:
+ if future.done():
+ return future.result()
+ raise deadline_error() from exc
+ while True:
+ if cancel.is_set():
+ raise deadline_error()
+ remaining = wait_deadline - time.monotonic()
+ if remaining <= 0:
+ raise deadline_error()
+ try:
+ return future.result(timeout=min(remaining, 0.1))
+ except TimeoutError:
+ # Preserve worker-side socket failures for transport classification.
+ if future.done():
+ return future.result()
while attempt < effective_retries:
+ if cancel is not None and cancel.is_set():
+ last_error = deadline_error()
+ break
request_timeout = timeout
if deadline_monotonic is not None:
remaining = deadline_monotonic - time.monotonic()
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index ac0794d7..19337485 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import contextlib
import copy
-from collections.abc import Iterable, Mapping
+from collections.abc import Iterable, Iterator, Mapping
import math
import queue
import re
@@ -13,7 +13,7 @@ import sys
import threading
import time
from collections import Counter
-from concurrent.futures import ThreadPoolExecutor, as_completed
+from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait as futures_wait
from dataclasses import dataclass, field, replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
@@ -138,6 +138,71 @@ THIN_RETRY_EXEMPT: frozenset[str] = frozenset({"trustpilot", "perplexity", "meta
# resolved advertiser and its counts matters most.
STREAM_ARTIFACT_LIFT_KEYS: tuple[str, ...] = ("meta_ads_page", "meta_ads_tally")
+# Shared wall-clock bounds for fan-out waits (CR-012/CR-016). Each bounded
+# fan-out waits with futures_wait(timeout=...) inside _abandoning_executor, so
+# a hung lane degrades to a TIMEOUT partial instead of stalling run() forever.
+# Worst case per stream is one timeout ceiling (+ one inline 5xx retry in the
+# main fan-out, itself bounded by the lane's own timeouts); no new config knobs.
+STREAM_FUTURE_TIMEOUT_SECONDS = 180.0
+DISCOVERY_FUTURE_TIMEOUT_SECONDS = 60.0
+THIN_RETRY_FUTURE_TIMEOUT_SECONDS = 120.0
+# One X source, ordered backends: grok (up to 240s/call) + xai (90-180s) would
+# stack sequentially inside one unbounded future under MCP's kill. The chain
+# owns a shared monotonic deadline (x_api's TIMEOUT 30/RETRIES 2/DEADLINE 90
+# pattern); backends past the deadline are skipped.
+X_CHAIN_DEADLINE_SECONDS = 90.0
+
+
+def _research_stopped(config: dict[str, Any]) -> bool:
+ cancel = config.get("_enrich_cancel")
+ deadline = config.get("_research_deadline")
+ return bool(
+ (cancel is not None and cancel.is_set())
+ or (deadline is not None and time.monotonic() >= deadline)
+ )
+
+
+def _research_deadline(config: dict[str, Any], seconds: float) -> float:
+ deadline = time.monotonic() + seconds
+ inherited = config.get("_research_deadline")
+ return min(deadline, inherited) if inherited is not None else deadline
+
+
+def _check_research(config: dict[str, Any]) -> None:
+ if _research_stopped(config):
+ raise TimeoutError("research budget exhausted or cancelled")
+
+
+def _wait_for_research(futures, config: dict[str, Any]):
+ pending = set(futures)
+ done = set()
+ while pending and not _research_stopped(config):
+ remaining = config["_research_deadline"] - time.monotonic()
+ completed, pending = futures_wait(
+ pending, timeout=max(0, min(0.1, remaining)), return_when=FIRST_COMPLETED,
+ )
+ done.update(completed)
+ return done, pending
+
+
+def _abandoning_executor(max_workers: int) -> Iterator[ThreadPoolExecutor]:
+ """ThreadPoolExecutor whose exit does not join running workers.
+
+ The stock context manager exits via shutdown(wait=True), which blocks on
+ the very straggler a futures_wait budget just declared timed out, so the
+ budget would bound only the wait, not the caller. Exiting with
+ shutdown(wait=False, cancel_futures=True) drops queued work and lets a
+ running straggler finish and discard its result in the background (the
+ amazon review-lane pattern). The interpreter still joins those threads at
+ exit, so each straggler stays bounded by its lane's own timeouts.
+ """
+ pool = ThreadPoolExecutor(max_workers=max_workers)
+ try:
+ yield pool
+ finally:
+ pool.shutdown(wait=False, cancel_futures=True)
+
def _lift_stream_artifacts(bundle) -> None:
"""Promote per-stream artifacts the renderer reads by name."""
@@ -546,6 +611,7 @@ def _fetch_discovery_source(
mock: bool,
config: dict[str, Any],
keyword_gate: bool = True,
+ warnings: list[str] | None = None,
) -> tuple[list[dict[str, Any]], str | None]:
"""Fetch one listing/river source for the nominate stage.
@@ -554,8 +620,11 @@ def _fetch_discovery_source(
keeps the gate on; global trending (``--discover`` with no domain) turns it
off, because there is no keyword to gate against - the river feeds ARE the
"what is hot right now" signal, and the confidence floor downstream is what
- keeps junk out, not a keyword match.
+ keeps junk out, not a keyword match. ``warnings``, when given, collects
+ backend receipts that are not failures (xapi's truncated window).
"""
+ if _research_stopped(config):
+ return [], "discovery research cancelled or timed out"
if mock:
return _mock_discovery_items(source, plan.domain, to_date), None
if source == "reddit":
@@ -604,9 +673,15 @@ def _fetch_discovery_source(
# Discovery uses domain directly as query (no planner search_query)
query = plan.domain
last_error = ""
+ chain_deadline = _research_deadline(config, X_CHAIN_DEADLINE_SECONDS)
+ x_warnings: list[str] = []
for backend in env.x_backend_chain(config):
+ if _research_stopped(config) or time.monotonic() >= chain_deadline:
+ last_error = f"{last_error}; X chain budget exhausted (timed out or cancelled)".strip("; ")
+ break
items, error = _fetch_x_backend(
backend, query, from_date, to_date, depth, config,
+ warnings=x_warnings, deadline=chain_deadline,
)
if items:
# Earlier failed-over backends' errors are observability, not
@@ -614,9 +689,13 @@ def _fetch_discovery_source(
# these items are partial and must surface as such.
if last_error:
print(f"[x] earlier backend failed: {last_error}", file=sys.stderr)
+ if warnings is not None:
+ warnings.extend(x_warnings)
return items, error or None
if error:
last_error = f"{backend}: {error}"
+ if warnings is not None:
+ warnings.extend(x_warnings)
return [], last_error or None
raise ValueError(f"Unsupported discovery source: {source}")
@@ -676,7 +755,12 @@ def nominate_candidates(
run - the confidence floor decides whether the surviving evidence is enough.
"""
bundle = schema.RetrievalBundle()
- with ThreadPoolExecutor(max_workers=max(1, len(plan.sources))) as executor:
+ config = dict(config)
+ config["_research_deadline"] = _research_deadline(config, DISCOVERY_FUTURE_TIMEOUT_SECONDS)
+ # Shared receipts sink: only X appends (xapi's truncated window); the
+ # executor submit below passes it to every source, the rest ignore it.
+ x_receipts: list[str] = []
+ with _abandoning_executor(max_workers=max(1, len(plan.sources))) as executor:
futures = {
executor.submit(
_fetch_discovery_source,
@@ -688,14 +772,35 @@ def nominate_candidates(
mock=mock,
config=config,
keyword_gate=keyword_gate,
+ warnings=x_receipts,
): source
for source in plan.sources
}
- for future in as_completed(futures):
+ # Bounded wait (reddit-lane futures_wait pattern): a hung feed degrades
+ # to a TIMEOUT partial instead of stalling nominate forever.
+ done, not_done = _wait_for_research(futures, config)
+ for future in not_done:
source = futures[future]
bundle.mark_attempted(source)
+ future.cancel()
+ detail = f"{source} timed out after {DISCOVERY_FUTURE_TIMEOUT_SECONDS:g}s"
+ bundle.errors_by_source[source] = detail
+ bundle.record_failure(
+ source,
+ health.TIMEOUT,
+ detail,
+ attempted=True,
+ )
+ for future in done:
+ source = futures[future]
+ bundle.mark_attempted(source)
+ try:
+ raw_items, partial_error = future.result(timeout=0)
+ except Exception as exc:
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(source, state, str(exc), attempted=attempted)
+ continue
try:
- raw_items, partial_error = future.result()
normalized = normalize.normalize_source_items(
source,
raw_items,
@@ -732,6 +837,14 @@ def nominate_candidates(
except Exception as exc:
state, attempted = _classify_source_failure(exc)
bundle.record_failure(source, state, str(exc), attempted=attempted)
+ # Backend receipts that are not failures (xapi's truncated window): the
+ # same x_partial_coverage key the main path uses. X extends the sink just
+ # before returning, so a finished X future's receipts are complete. The
+ # executor exit does not join stragglers: a timed-out X can still append
+ # after the wait, and its receipts are dropped along with its items.
+ x_finished = any(futures[future] == "x" for future in done)
+ if x_finished and x_receipts:
+ bundle.artifacts.setdefault("x_partial_coverage", []).extend(list(x_receipts))
return bundle
@@ -1020,15 +1133,21 @@ def enrich_nominations(
if not nominations:
return []
+ # Cooperative cancel: not-yet-started sub-runs and streams skip new
+ # network work once the batch budget expires. The event rides the
+ # per-worker config copy into run() -> _retrieve_stream_impl, which exits
+ # early when set; in-flight requests still run to their own timeouts.
+ cancel = threading.Event()
+ deadline = _research_deadline(config, max(1.0, budget_seconds))
+
def _run_one(nomination: Nomination) -> schema.Report:
- # Per-worker copy: run() mutates config in place
- # (config["_financial_topic"] = ...), so sharing one dict across
- # daemon threads lets topic A's flag overwrite topic B's mid-run,
- # with stragglers mutating past budget expiry. Same idiom as the
- # competitor runner (entity_config = dict(config)).
+ worker_config = dict(config)
+ worker_config["_enrich_cancel"] = cancel
+ worker_config["_research_deadline"] = deadline
+ _check_research(worker_config)
return run(
topic=nomination.name,
- config=dict(config),
+ config=worker_config,
depth=depth,
requested_sources=requested_sources,
mock=mock,
@@ -1055,6 +1174,9 @@ def enrich_nominations(
def _worker(nomination: Nomination) -> None:
with slots:
+ if cancel.is_set():
+ results_queue.put((nomination, None, TimeoutError("enrichment budget exhausted")))
+ return
try:
results_queue.put((nomination, _run_one(nomination), None))
except Exception as exc: # noqa: BLE001 - containment is the contract
@@ -1068,30 +1190,38 @@ def enrich_nominations(
daemon=True,
).start()
- deadline = time.monotonic() + max(1.0, budget_seconds)
pending = len(nominations)
- while pending and (remaining := deadline - time.monotonic()) > 0:
- try:
- nomination, report, exc = results_queue.get(timeout=min(remaining, 0.5))
- except queue.Empty:
- continue
- pending -= 1
- if exc is None:
- enriched[nomination.name] = EnrichedTopic(
- nomination=nomination, report=report,
- )
- else:
- enriched[nomination.name] = EnrichedTopic(
- nomination=nomination,
- error=f"{type(exc).__name__}: {exc}",
- )
- print(
- f"[Discover] enrichment failed for {nomination.name!r}: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- # Budget expired (or all done): unfinished topics fall through below as
- # nomination-only; their daemon workers are abandoned and cannot block exit.
+ try:
+ while pending and (remaining := deadline - time.monotonic()) > 0:
+ try:
+ nomination, report, exc = results_queue.get(timeout=min(remaining, 0.5))
+ except queue.Empty:
+ continue
+ if time.monotonic() >= deadline:
+ break
+ pending -= 1
+ if exc is None:
+ enriched[nomination.name] = EnrichedTopic(
+ nomination=nomination, report=report,
+ )
+ else:
+ enriched[nomination.name] = EnrichedTopic(
+ nomination=nomination,
+ error=f"{type(exc).__name__}: {exc}",
+ )
+ print(
+ f"[Discover] enrichment failed for {nomination.name!r}: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ finally:
+ # Budget expired (or all done, or the drain itself failed):
+ # unfinished topics fall through below as nomination-only; their
+ # daemon workers are abandoned and cannot block exit. Signal
+ # cooperative cancel so queued workers skip new sub-runs and
+ # not-yet-started streams exit early; in-flight spend continues to
+ # its own timeout.
+ cancel.set()
results: list[EnrichedTopic] = []
for nomination in nominations:
@@ -1638,7 +1768,10 @@ def run_discover(
plan=plan,
topics=topics,
source_status=source_status,
- warnings=_discovery_report_warnings(topics, outcome, source_status),
+ warnings=(
+ _discovery_report_warnings(topics, outcome, source_status)
+ + sweep.bundle.artifacts.get("x_partial_coverage", [])
+ ),
outcome=outcome,
weak_signal=weak_signal[1] if weak_signal and not topics else None,
)
@@ -2091,6 +2224,7 @@ def run(
corpus_all_time: bool = False,
x_posts: x_envelope.Envelope | None = None,
) -> schema.Report:
+ _check_research(config)
# ``suppress_x_host_lane`` is distinct from ``internal_subrun``: comparison
# entities share the latter and must still honor the connector lane;
# only discovery enrichment passes set the former.
@@ -2211,6 +2345,7 @@ def run(
)
plan_source = "external"
else:
+ _check_research(config)
plan = planner.plan_query(
topic=topic,
available_sources=available,
@@ -2230,6 +2365,7 @@ def run(
else:
plan_source = "deterministic"
+ _check_research(config)
# Safety net: ensure grounding appears in all subqueries even if the planner
# omits it. This is redundant when the planner includes grounding via
# SOURCE_CAPABILITIES, but kept as a fallback.
@@ -2485,7 +2621,9 @@ def run(
if source in available and source != "corpus"
)
max_workers = _inner_max_workers(stream_count, internal_subrun=internal_subrun)
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ stream_config = dict(config)
+ stream_config["_research_deadline"] = _research_deadline(config, STREAM_FUTURE_TIMEOUT_SECONDS)
+ with _abandoning_executor(max_workers=max_workers) as executor:
for subquery in plan.subqueries:
for source in subquery.sources:
if source not in available:
@@ -2531,7 +2669,7 @@ def run(
topic=topic,
subquery=subquery,
source=source,
- config=config,
+ config=stream_config,
depth=depth,
date_range=(from_date, to_date),
runtime=runtime,
@@ -2550,10 +2688,25 @@ def run(
)
] = (subquery, source)
- for future in as_completed(futures):
+ # Bounded fan-out (reddit-lane futures_wait pattern): the whole Phase 1
+ # waits at most STREAM_FUTURE_TIMEOUT_SECONDS, so a hung lane degrades
+ # to a TIMEOUT partial instead of stalling run() forever. Worst case
+ # per stream is the wait ceiling plus, for a stream that failed fast
+ # with a 5xx while budget remained, one inline retry bounded by that
+ # lane's own timeouts. No retry starts after the wait timed out or
+ # the enrichment cancel fired.
+ done, not_done = _wait_for_research(futures, stream_config)
+ budget_expired = bool(not_done)
+ for future in not_done:
+ subquery, source = futures[future]
+ future.cancel()
+ detail = f"{source} timed out after {STREAM_FUTURE_TIMEOUT_SECONDS:g}s"
+ bundle.errors_by_source[source] = detail
+ bundle.record_failure(source, health.TIMEOUT, detail, attempted=True)
+ for future in done:
subquery, source = futures[future]
try:
- raw_items, artifact = future.result()
+ raw_items, artifact = future.result(timeout=0)
except Exception as exc:
# Share 429 signal so pending futures skip this source
if _is_rate_limit_error(exc):
@@ -2563,13 +2716,28 @@ def run(
state, attempted = _classify_source_failure(exc)
bundle.record_failure(source, state, str(exc), attempted=attempted)
continue
- # Retry once for transient 5xx errors
+ # Retry once for transient 5xx errors, but never after the
+ # wait already timed out or cancel fired: the retry's lane
+ # timeouts plus the blocking sleep would run past the budget
+ # that just expired.
if _is_transient_error(exc):
- time.sleep(3)
+ if budget_expired or _research_stopped(stream_config):
+ bundle.errors_by_source[source] = str(exc)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(source, state, str(exc), attempted=attempted)
+ continue
+ delay = min(3, max(0, stream_config["_research_deadline"] - time.monotonic()))
+ cancel = stream_config.get("_enrich_cancel")
+ if cancel is None:
+ time.sleep(delay)
+ else:
+ cancel.wait(delay)
try:
- raw_items, artifact = _retrieve_stream(
+ _check_research(stream_config)
+ retry_future = executor.submit(
+ _retrieve_stream,
topic=topic, subquery=subquery, source=source,
- config=config, depth=depth, date_range=(from_date, to_date),
+ config=stream_config, depth=depth, date_range=(from_date, to_date),
runtime=runtime, mock=mock,
rate_limited_sources=rate_limited_sources,
rate_limit_lock=rate_limit_lock,
@@ -2583,6 +2751,11 @@ def run(
trustpilot_domain_is_hint=trustpilot_domain_is_hint,
run_started=run_started,
)
+ retry_done, _ = _wait_for_research([retry_future], stream_config)
+ if not retry_done:
+ retry_future.cancel()
+ raise TimeoutError("stream retry timed out")
+ raw_items, artifact = retry_future.result(timeout=0)
except Exception as retry_exc:
detail = f"{exc} (retried once, still failed: {retry_exc})"
bundle.errors_by_source[source] = detail
@@ -2636,6 +2809,7 @@ def run(
bundle.artifacts.setdefault("grounding", []).append(artifact)
# Phase 2: supplemental entity-based searches
+ _check_research(config)
supplemental_handles: list[str] = []
_run_supplemental_searches(
topic=topic,
@@ -2702,6 +2876,7 @@ def run(
if hiring_summary:
bundle.artifacts["hiring_signals"] = hiring_summary
+ _check_research(config)
items_by_source = _finalize_items_by_source(
bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
elapsed=time.monotonic() - run_started,
@@ -2788,6 +2963,7 @@ def run(
public_candidates = [
candidate for candidate in candidates if id(candidate) not in private_candidate_ids
]
+ _check_research(config)
ranked_public = rerank.rerank_candidates(
topic=topic,
plan=plan,
@@ -2834,6 +3010,7 @@ def run(
candidate.title,
),
)
+ _check_research(config)
rerank.score_fun(
topic=topic,
candidates=ranked_public,
@@ -2852,6 +3029,7 @@ def run(
# gh-credential fallback) outside the _retrieve_stream seam, so it gets its
# own fixture exchange keyed by phase.
if "github" in available and not mock:
+ _check_research(config)
star_request = {
"source": "github",
"phase": "post_rerank_star_enrichment",
@@ -3298,6 +3476,7 @@ def _finalize_items_by_source(
) -> dict[str, list[schema.SourceItem]]:
finalized = {}
for source, items in items_by_source_raw.items():
+ _check_research(config or {})
items = sorted(items, key=lambda item: item.local_rank_score or 0.0, reverse=True)
# Same thread from two subquery streams: fold the enriched copy into
# the first before the text-similarity dedupe, which would otherwise
@@ -3897,6 +4076,8 @@ def _run_supplemental_searches(
resolved_handles_out: list[str] | None = None,
) -> None:
"""Phase 2: extract entities from Phase 1 results, run targeted supplemental searches."""
+ if _research_stopped(config):
+ return
# The sanitized plan already intersects requested, available, and excluded
# sources. A handle or host envelope must not expand that source boundary.
if not any("x" in subquery.sources for subquery in plan.subqueries):
@@ -4040,7 +4221,7 @@ def _run_supplemental_searches(
return True
bundle.record_failure(
x_slug,
- health.UNREACHABLE,
+ health.TIMEOUT if any(marker in lowered for marker in ("timed out", "cancelled")) else health.UNREACHABLE,
f"Phase 2 {lane}-lane: {detail}",
attempted=True,
)
@@ -4059,23 +4240,25 @@ def _run_supplemental_searches(
# fallback for the mention lane -- most discussion of a person or company
# never @-mentions them, so the two lanes reach disjoint sets.
_name_lane = None
+ cancel = config.get("_enrich_cancel")
+ supplemental_deadline = _research_deadline(config, x_api.LANE_BUDGET_SECONDS)
if primary == "grok":
# One budget shared by all three lanes, started here rather than per
# lane: the point is to bound the total, not each part.
- lane_deadline = time.monotonic() + grok_x.LANE_BUDGET_SECONDS
+ lane_deadline = _research_deadline(config, grok_x.LANE_BUDGET_SECONDS)
def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:
items, revoked = grok_x.search_handles(
hs, topic, from_date, to_date, count_per=count,
- deadline=lane_deadline, and_topic=and_topic,
+ deadline=lane_deadline, and_topic=and_topic, cancel=cancel,
)
return items, revoked
def _about_lane(hs: list, count: int) -> tuple[list, bool]:
items, revoked = grok_x.search_mentions(
hs, from_date, to_date, topic=topic, count_per=count,
- deadline=lane_deadline,
+ deadline=lane_deadline, cancel=cancel,
)
return items, revoked
@@ -4088,7 +4271,7 @@ def _run_supplemental_searches(
return [], False
items, revoked = grok_x.search_name(
subject, from_date, to_date, exclude_handles=hs, count_per=count,
- deadline=lane_deadline,
+ deadline=lane_deadline, cancel=cancel,
)
return items, revoked
elif primary == "bird":
@@ -4097,7 +4280,7 @@ def _run_supplemental_searches(
failures: list[str] = []
items = bird_x.search_handles(
hs, topic, from_date, count_per=count, failure_out=failures,
- to_date=to_date,
+ to_date=to_date, deadline=supplemental_deadline, cancel=cancel,
)
return items, _record_handle_lane_failures("FROM", failures)
@@ -4105,7 +4288,7 @@ def _run_supplemental_searches(
failures: list[str] = []
items = bird_x.search_mentions(
hs, from_date, count_per=count, failure_out=failures,
- to_date=to_date,
+ to_date=to_date, deadline=supplemental_deadline, cancel=cancel,
)
return items, _record_handle_lane_failures("ABOUT", failures)
elif primary == "xapi":
@@ -4114,7 +4297,7 @@ def _run_supplemental_searches(
# every lane below (same shape as the grok lanes): a slow key bounds
# the whole supplemental phase, not each call.
xapi_token = config.get("X_BEARER_TOKEN") or ""
- xapi_deadline = time.monotonic() + x_api.LANE_BUDGET_SECONDS
+ xapi_deadline = _research_deadline(config, x_api.LANE_BUDGET_SECONDS)
def _xapi_lane_receipt(lane_warnings: list[str]) -> None:
# A deadline stop is incomplete coverage, reported in
@@ -4131,7 +4314,7 @@ def _run_supplemental_searches(
lane_warnings: list[str] = []
items = x_api.search_handles(
hs, topic, from_date, to_date, count_per=count, token=xapi_token,
- deadline=xapi_deadline, warnings=lane_warnings,
+ deadline=xapi_deadline, warnings=lane_warnings, cancel=cancel,
)
_xapi_lane_receipt(lane_warnings)
return items, False
@@ -4140,7 +4323,7 @@ def _run_supplemental_searches(
lane_warnings: list[str] = []
items = x_api.search_mentions(
hs, from_date, to_date, topic=topic, count_per=count, token=xapi_token,
- deadline=xapi_deadline, warnings=lane_warnings,
+ deadline=xapi_deadline, warnings=lane_warnings, cancel=cancel,
)
_xapi_lane_receipt(lane_warnings)
return items, False
@@ -4152,7 +4335,7 @@ def _run_supplemental_searches(
failures: list[str] = []
items = xquik.search_handles(
hs, topic, from_date, to_date, count_per=count, token=xquik_token,
- failure_out=failures,
+ failure_out=failures, deadline=supplemental_deadline, cancel=cancel,
)
return items, _record_handle_lane_failures("FROM", failures)
@@ -4160,12 +4343,25 @@ def _run_supplemental_searches(
failures: list[str] = []
items = xquik.search_mentions(
hs, from_date, to_date, topic=topic, count_per=count,
- token=xquik_token, failure_out=failures,
+ token=xquik_token, failure_out=failures, deadline=supplemental_deadline, cancel=cancel,
)
return items, _record_handle_lane_failures("ABOUT", failures)
else:
return # primary X backend has no handle-lane support (xai/xurl) or none configured
+ def _guard_lane(lane):
+ def guarded(*args, **kwargs):
+ if _research_stopped(config) or time.monotonic() >= supplemental_deadline:
+ bundle.record_failure(x_slug, health.TIMEOUT, "X supplemental research cancelled or timed out", attempted=True)
+ return [], False
+ return lane(*args, **kwargs)
+ return guarded
+
+ _from_lane = _guard_lane(_from_lane)
+ _about_lane = _guard_lane(_about_lane)
+ if _name_lane is not None:
+ _name_lane = _guard_lane(_name_lane)
+
# Skip if the X source is rate-limited.
if x_slug in rate_limited_sources:
return
@@ -4410,6 +4606,11 @@ def _retry_thin_sources(
"""Retry sources with thin results using simplified core subject query."""
if depth == "quick":
return
+ # No new paid/network work after the enrichment budget expired.
+ if _research_stopped(config):
+ return
+ config = dict(config)
+ config["_research_deadline"] = _research_deadline(config, THIN_RETRY_FUTURE_TIMEOUT_SECONDS)
planned_sources: list[str] = []
for subquery in plan.subqueries:
@@ -4501,13 +4702,30 @@ def _retry_thin_sources(
retryable = [s for s in thin_sources if s not in rate_limited_sources]
- from concurrent.futures import ThreadPoolExecutor, as_completed
- with ThreadPoolExecutor(max_workers=min(4, len(retryable) or 1)) as executor:
+ with _abandoning_executor(max_workers=min(4, len(retryable) or 1)) as executor:
futures = {executor.submit(_retry_one_source, s): s for s in retryable}
- for future in as_completed(futures):
+ done, not_done = _wait_for_research(futures, config)
+ for future in not_done:
+ source = futures[future]
+ future.cancel()
+ detail = f"{source} timed out after {THIN_RETRY_FUTURE_TIMEOUT_SECONDS:g}s"
+ print(f"[Pipeline] Retry timed out for {source}: {detail}", file=sys.stderr)
+ bundle.record_failure(source, health.TIMEOUT, f"Simplified-query retry failed: {detail}", attempted=True)
+ for future in done:
source = futures[future]
try:
- source, normalized, outcome_note, (detail_note, detail_state) = future.result()
+ source, normalized, outcome_note, (detail_note, detail_state) = future.result(timeout=0)
+ except Exception as exc:
+ print(f"[Pipeline] Retry failed for {source}: {type(exc).__name__}: {exc}", file=sys.stderr)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(
+ source,
+ state,
+ f"Simplified-query retry failed: {exc}",
+ attempted=attempted,
+ )
+ continue
+ try:
if outcome_note:
bundle.record_failure(
source,
@@ -4534,12 +4752,15 @@ def _retry_thin_sources(
)
-def _fetch_x_backend(backend, query, from_date, to_date, depth, config, warnings=None):
+def _fetch_x_backend(backend, query, from_date, to_date, depth, config, warnings=None, deadline=None):
"""Fetch X items from a single backend. Returns (items, error_str).
``warnings``, when given, collects backend receipts that are not
- failures (xapi's "window truncated to 7 days" after the recent-search
- fallback) so the X branch can surface them as run artifacts.
+ failures (Bird's skipped optional retries or xapi's recent-search window
+ truncation) so the X branch can surface them as run artifacts.
+ ``deadline`` is the chain's shared ``time.monotonic()`` budget; backends
+ that accept one (bird/grok/xai/xurl/xquik/xapi) clamp their waits to the
+ time left.
Backends are tried in priority order by the caller (env.x_backend_chain);
a non-empty error_str signals a hard failure (auth/payment/etc.) so the
@@ -4553,35 +4774,41 @@ def _fetch_x_backend(backend, query, from_date, to_date, depth, config, warnings
``raw_topic or topic`` (like Reddit/YouTube), NOT the planner's
``search_query`` which may contain operator strings like "Rome Italy".
"""
+ if _research_stopped(config) or (deadline is not None and time.monotonic() >= deadline):
+ return [], "X research cancelled or timed out"
+ cancel = config.get("_enrich_cancel")
if backend == "bird":
- result = bird_x.search_x(query, from_date, to_date, depth=depth)
+ result = bird_x.search_x(query, from_date, to_date, depth=depth, deadline=deadline, cancel=cancel)
items = bird_x.parse_bird_response(result, query=query)
elif backend == "grok":
- result = grok_x.search_x(query, from_date, to_date, depth=depth)
+ result = grok_x.search_x(
+ query, from_date, to_date, depth=depth, deadline=deadline,
+ cancel=config.get("_enrich_cancel"),
+ )
items = result.get("items", []) if isinstance(result, dict) else []
if isinstance(result, dict) and result.get("auth_revoked"):
err = result.get("error") or "grok session expired or was revoked"
return items, f"grok: {err}"
elif backend == "xai":
model = config.get("LAST30DAYS_X_MODEL") or config.get("XAI_MODEL_PIN") or providers.XAI_DEFAULT
- result = xai_x.search_x(config["XAI_API_KEY"], model, query, from_date, to_date, depth=depth)
+ result = xai_x.search_x(config["XAI_API_KEY"], model, query, from_date, to_date, depth=depth, deadline_monotonic=deadline, cancel=cancel)
items = xai_x.parse_x_response(result)
elif backend == "xurl":
- result = xurl_x.search_x(query, depth=depth)
+ result = xurl_x.search_x(query, depth=depth, deadline=deadline)
items = xurl_x.parse_x_response(result, topic=query)
elif backend == "xquik":
- result = xquik.search_xquik(query, from_date, to_date, depth=depth, token=env.get_xquik_token(config))
+ result = xquik.search_xquik(query, from_date, to_date, depth=depth, token=env.get_xquik_token(config), deadline=deadline, cancel=cancel)
items = xquik.parse_xquik_response(result)
elif backend == "xapi":
- result = x_api.search_x(config.get("X_BEARER_TOKEN") or "", query, from_date, to_date, depth=depth)
+ result = x_api.search_x(config.get("X_BEARER_TOKEN") or "", query, from_date, to_date, depth=depth, deadline=deadline, cancel=cancel)
items = result.get("items", []) if isinstance(result, dict) else []
- warning = result.get("warning") if isinstance(result, dict) else None
- if warning:
- print(f"[X] xapi: {warning}", file=sys.stderr)
- if warnings is not None:
- warnings.append(f"X: xapi {warning}")
else:
return [], f"unknown X backend: {backend}"
+ warning = result.get("warning") if isinstance(result, dict) else None
+ if warning:
+ print(f"[X] {backend}: {warning}", file=sys.stderr)
+ if warnings is not None:
+ warnings.append(f"X: {backend} {warning}")
err = result.get("error") if isinstance(result, dict) else ""
return items, (err or "")
@@ -4613,6 +4840,14 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
"""Run one stream and retain HTTP failures swallowed by source adapters."""
# run_started is passed through but not used here; it goes to _retrieve_stream_impl
source = str(kwargs.get("source") or "")
+
+ def publish_rate_limit(state):
+ limited = kwargs.get("rate_limited_sources")
+ if state == health.RATE_LIMITED and limited is not None:
+ lock = kwargs.get("rate_limit_lock")
+ with lock if lock is not None else contextlib.nullcontext():
+ limited.add(source)
+
fixture_request = {
"source": source,
"topic": kwargs.get("topic") or "",
@@ -4634,6 +4869,9 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
if module_backed:
matched, replayed = http.fixture_source_replay(fixture_request)
if matched:
+ replay_artifact = replayed[1] or {}
+ publish_rate_limit((replay_artifact.get("_source_outcome") or {}).get("state"))
+ publish_rate_limit(replay_artifact.get("_source_outcome_detail_state"))
return replayed[0], replayed[1]
try:
with http.capture_failures() as failures, \
@@ -4647,6 +4885,7 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
)
recorded_exc = SourceRunError(str(exc), failure.outcome_state)
+ publish_rate_limit(_classify_source_failure(recorded_exc)[0])
if module_backed:
http.fixture_source_record_error(fixture_request, recorded_exc)
if recorded_exc is not exc:
@@ -4692,6 +4931,8 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
artifact["_source_outcome_detail_state"] = min(
states, key=lambda state: _FAILURE_SPECIFICITY.get(state, 9)
)
+ publish_rate_limit((artifact.get("_source_outcome") or {}).get("state"))
+ publish_rate_limit(artifact.get("_source_outcome_detail_state"))
if module_backed:
http.fixture_source_record(fixture_request, [items, artifact])
return items, artifact
@@ -4839,6 +5080,12 @@ def _retrieve_stream_impl(
# Early exit if source was rate-limited by a sibling future
if rate_limited_sources is not None and source in rate_limited_sources:
return [], {}
+ # Cooperative enrichment cancel: the batch budget expired, so skip new
+ # network work instead of burning credits past the deadline.
+ if _research_stopped(config):
+ return [], {"_source_outcome": {
+ "state": health.TIMEOUT, "detail": "research cancelled or timed out", "attempted": False,
+ }}
from_date, to_date = date_range
if mock:
return _mock_stream_results(source, subquery)
@@ -5047,9 +5294,17 @@ def _retrieve_stream_impl(
items = []
used_backend = None
x_warnings: list[str] = []
+ chain_deadline = _research_deadline(config, X_CHAIN_DEADLINE_SECONDS)
for i, backend in enumerate(chain):
+ if _research_stopped(config) or time.monotonic() >= chain_deadline:
+ msg = "X chain budget exhausted (timed out or cancelled)"
+ last_error = f"{last_error}; {msg}".strip("; ") if last_error else msg
+ chain_errors.append(msg)
+ print("[X] chain budget exhausted; skipping remaining backends", file=sys.stderr)
+ break
items, err = _fetch_x_backend(
backend, x_query, from_date, to_date, depth, config, warnings=x_warnings,
+ deadline=chain_deadline,
)
if items:
if i > 0:
@@ -5111,7 +5366,9 @@ def _retrieve_stream_impl(
last_error = candidate
break
state = (
- bird_x.classify_run_failure(last_error)
+ health.TIMEOUT
+ if _research_stopped(config) or time.monotonic() >= chain_deadline
+ else bird_x.classify_run_failure(last_error)
if last_error.startswith("bird:")
else http.classify_failure(message=last_error)
)
@@ -5139,30 +5396,34 @@ def _retrieve_stream_impl(
print(f"[X] corpus off-topic; retrying with '{retry_query}'", file=sys.stderr)
if used_backend:
- retry_items, retry_err = _fetch_x_backend(
- used_backend, retry_query, from_date, to_date, depth, config
- )
- if retry_items:
- # Judge retry corpus
- retry_for_judge = [
- {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}
- for it in retry_items
- ]
- retry_judgment = x_judge.judge_x_corpus(
- retry_for_judge, x_query, ranking_query=ranking_query
+ if _research_stopped(config) or time.monotonic() >= chain_deadline:
+ print("[X] chain budget exhausted; skipping judge retry", file=sys.stderr)
+ else:
+ retry_items, retry_err = _fetch_x_backend(
+ used_backend, retry_query, from_date, to_date, depth, config,
+ deadline=chain_deadline,
)
- orig_judgment = x_judge.judge_x_corpus(
- items_for_judge, x_query, ranking_query=ranking_query
- )
- # Use retry if better on-topic ratio
- if retry_judgment["on_topic_ratio"] > orig_judgment["on_topic_ratio"]:
- print(
- f"[X] retry improved on-topic ratio: "
- f"{orig_judgment['on_topic_ratio']:.0%} -> "
- f"{retry_judgment['on_topic_ratio']:.0%}",
- file=sys.stderr,
+ if retry_items:
+ # Judge retry corpus
+ retry_for_judge = [
+ {"author_handle": it.get("author_handle", ""), "text": it.get("text", "")}
+ for it in retry_items
+ ]
+ retry_judgment = x_judge.judge_x_corpus(
+ retry_for_judge, x_query, ranking_query=ranking_query
+ )
+ orig_judgment = x_judge.judge_x_corpus(
+ items_for_judge, x_query, ranking_query=ranking_query
)
- items = retry_items
+ # Use retry if better on-topic ratio
+ if retry_judgment["on_topic_ratio"] > orig_judgment["on_topic_ratio"]:
+ print(
+ f"[X] retry improved on-topic ratio: "
+ f"{orig_judgment['on_topic_ratio']:.0%} -> "
+ f"{retry_judgment['on_topic_ratio']:.0%}",
+ file=sys.stderr,
+ )
+ items = retry_items
# Prune off-topic items before the pool. Eight on-topic → ok with 8.
# Zero on-topic after retry → no-results, not ok with 40 junk.
diff --git a/skills/last30days/scripts/lib/x_api.py b/skills/last30days/scripts/lib/x_api.py
index 76adf376..6179bcf2 100644
--- a/skills/last30days/scripts/lib/x_api.py
+++ b/skills/last30days/scripts/lib/x_api.py
@@ -450,6 +450,7 @@ def _failure_for(exc: http.HTTPError) -> _XApiFailure:
def _get(
token: str, url: str, params: Dict[str, Any], deadline: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""One authenticated GET; every failure surfaces as ``_XApiFailure``.
@@ -466,6 +467,7 @@ def _get(
timeout=TIMEOUT_SECONDS,
retries=RETRIES,
deadline_monotonic=deadline,
+ **({"cancel": cancel} if cancel is not None else {}),
)
except http.HTTPError as exc:
raise _failure_for(exc) from None
@@ -486,6 +488,7 @@ def _search_pages(
params: Dict[str, Any],
count: int,
deadline: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Follow ``next_token`` until ``count`` posts are collected.
@@ -502,6 +505,11 @@ def _search_pages(
# Bound the walk even when every page carries a next_token.
max_pages = max(1, -(-count // MIN_PAGE_RESULTS))
for page_index in range(max_pages):
+ if cancel is not None and cancel.is_set():
+ if not data:
+ raise _XApiFailure(ERR_TIMED_OUT)
+ truncated = True
+ break
if page_index and deadline is not None and time.monotonic() >= deadline:
_log(f"search deadline ({DEADLINE_SECONDS}s) reached; keeping {len(data)} posts")
truncated = True
@@ -509,7 +517,7 @@ def _search_pages(
# A fresh dict per page: the transport must never see a later
# page's next_token on an earlier request.
try:
- response = _get(token, url, dict(page_params), deadline)
+ response = _get(token, url, dict(page_params), deadline, **({"cancel": cancel} if cancel is not None else {}))
except _XApiFailure as exc:
if data and str(exc) == ERR_TIMED_OUT:
# The budget ran out mid-walk: the pages already collected
@@ -546,6 +554,7 @@ def _run_search(
id_prefix: str,
label: str,
deadline: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Full-archive search with the recent-search fallback.
@@ -567,7 +576,7 @@ def _run_search(
"tweet.fields": "created_at,public_metrics,note_tweet,entities",
"user.fields": "username",
}
- if deadline is not None and time.monotonic() >= deadline:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
_log(f"{label}: lane budget ({LANE_BUDGET_SECONDS:.0f}s) exhausted before the search started")
return {"items": [], "warning": DEADLINE_DETAIL}
_log(f"Searching: {label}")
@@ -575,7 +584,7 @@ def _run_search(
if deadline is None:
deadline = time.monotonic() + DEADLINE_SECONDS
try:
- response = _search_pages(token, _SEARCH_ALL_URL, params, count, deadline)
+ response = _search_pages(token, _SEARCH_ALL_URL, params, count, deadline, **({"cancel": cancel} if cancel is not None else {}))
except _XApiFailure as exc:
if not exc.enrollment:
_log(f"{label}: {exc}")
@@ -589,7 +598,7 @@ def _run_search(
return {"items": [], "warning": TRUNCATION_DETAIL}
params["start_time"] = max(start, floor)
try:
- response = _search_pages(token, _SEARCH_RECENT_URL, params, count, deadline)
+ response = _search_pages(token, _SEARCH_RECENT_URL, params, count, deadline, **({"cancel": cancel} if cancel is not None else {}))
except _XApiFailure as exc2:
_log(f"{label}: {exc2}")
return {"items": [], "error": str(exc2)}
@@ -614,12 +623,16 @@ def search_x(
from_date: str,
to_date: str,
depth: str = "default",
+ deadline: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Topic search via X API v2.
Returns ``{"items": [...]}`` or ``{"items": [], "error": "..."}`` (the
xquik shape); ``"warning"`` carries the truncation detail after the
- recent-search fallback.
+ recent-search fallback. ``deadline`` is the X chain's shared
+ ``time.monotonic()`` budget; without one the search gets its own
+ ``DEADLINE_SECONDS``.
"""
if not token:
return {"items": [], "error": ERR_NO_TOKEN}
@@ -630,7 +643,8 @@ def search_x(
return {"items": [], "error": ERR_EMPTY_QUERY}
return _run_search(
token, compiled, from_date, to_date, count,
- topic=query, id_prefix="XAPI", label="topic",
+ topic=query, id_prefix="XAPI", label="topic", deadline=deadline,
+ **({"cancel": cancel} if cancel is not None else {}),
)
@@ -726,6 +740,7 @@ def search_handles(
token: str = "",
deadline: Optional[float] = None,
warnings: Optional[List[str]] = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""FROM lane: posts authored BY each handle (their own timeline).
@@ -741,6 +756,7 @@ def search_handles(
return _run_search(
token, f"from:{handle} -is:retweet", from_date, to_date, count_per,
topic=topic, id_prefix="XF", label=f"from:{handle}", deadline=deadline,
+ **({"cancel": cancel} if cancel is not None else {}),
)
return _run_handle_lanes(clean, _search_one, id_prefix="XF", warnings=warnings)
@@ -756,6 +772,7 @@ def search_mentions(
token: str = "",
deadline: Optional[float] = None,
warnings: Optional[List[str]] = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""ABOUT lane: posts mentioning each handle, authored by OTHERS.
@@ -771,6 +788,7 @@ def search_mentions(
return _run_search(
token, f"@{handle} -from:{handle} -is:retweet", from_date, to_date, count_per,
topic=topic, id_prefix="XA", label=f"@{handle}", deadline=deadline,
+ **({"cancel": cancel} if cancel is not None else {}),
)
return _run_handle_lanes(
diff --git a/skills/last30days/scripts/lib/xai_x.py b/skills/last30days/scripts/lib/xai_x.py
index 3c7b5365..88622b17 100644
--- a/skills/last30days/scripts/lib/xai_x.py
+++ b/skills/last30days/scripts/lib/xai_x.py
@@ -74,6 +74,8 @@ def search_x(
to_date: str,
depth: str = "default",
mock_response: Optional[Dict] = None,
+ deadline_monotonic: Optional[float] = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Search X for relevant posts using xAI API with live search.
@@ -85,6 +87,14 @@ def search_x(
to_date: End date (YYYY-MM-DD)
depth: Research depth - "quick", "default", or "deep"
mock_response: Mock response for testing
+ deadline_monotonic: Optional shared wall-clock deadline (``time.monotonic()``
+ instant) from the X backend chain. Bounds the whole call including
+ retries; without one this call owns its own timeout only.
+
+ The transport runs with ``retries=1`` (a global default change from the
+ inherited ``retries=5``): one 90-180s live-search call must not become a
+ 10-15 minute stall. DNS-resolution failures are the exception: the
+ transport widens those to three attempts.
Returns:
Raw API response
@@ -122,7 +132,16 @@ def search_x(
],
}
- return http.post(XAI_RESPONSES_URL, payload, headers=headers, timeout=timeout)
+ # A single non-DNS attempt: the per-call timeout already spans the model's
+ # full live-search latency, and the inherited http default (retries=5)
+ # would turn one 90-180s call into a 10-15 minute stall. The shared chain
+ # deadline bounds the wait wall-clock; failover to the next X backend
+ # covers the miss.
+ return http.post(
+ XAI_RESPONSES_URL, payload, headers=headers, timeout=timeout,
+ retries=1, deadline_monotonic=deadline_monotonic,
+ cancel=cancel,
+ )
def parse_x_response(response: Dict[str, Any]) -> List[Dict[str, Any]]:
diff --git a/skills/last30days/scripts/lib/xquik.py b/skills/last30days/scripts/lib/xquik.py
index b4f31e09..973dcf85 100644
--- a/skills/last30days/scripts/lib/xquik.py
+++ b/skills/last30days/scripts/lib/xquik.py
@@ -7,6 +7,7 @@ bookmarks). Requires an API key from xquik.com.
from __future__ import annotations
+import time
from datetime import datetime
from typing import Any, Dict, List, Optional
@@ -79,6 +80,8 @@ def search_xquik(
to_date: str,
depth: str = "default",
token: str = "",
+ deadline: float | None = None,
+ cancel: Any = None,
) -> Dict[str, Any]:
"""Search X via Xquik REST API.
@@ -88,6 +91,10 @@ def search_xquik(
to_date: End date (YYYY-MM-DD)
depth: Research depth - "quick", "default", or "deep"
token: Xquik API key
+ deadline: Optional shared wall-clock deadline (``time.monotonic()``
+ instant) from the X backend chain. Queries past the deadline are
+ never started; the per-request timeout/retry pair still bounds
+ each call (mirrors ``x_api``'s TIMEOUT_SECONDS/RETRIES pattern).
Returns:
Dict with "items" list and optional "error" string.
@@ -101,12 +108,17 @@ def search_xquik(
seen_ids: set[str] = set()
for query_text in queries:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
+ _log("chain deadline reached; skipping remaining queries")
+ return {"items": all_items, "error": "Xquik research cancelled or timed out"}
q = f"{query_text} since:{from_date} until:{to_date}"
items, auth_error = _execute_search(
q, cfg["limit"], token,
label=query_text, id_prefix="XQ",
seen_ids=seen_ids, relevance_query=query_text,
index_offset=len(all_items),
+ deadline_monotonic=deadline,
+ cancel=cancel,
)
if auth_error:
# Auth/payment failure is fatal for the whole source (e.g. 401/403,
@@ -115,6 +127,8 @@ def search_xquik(
return {"items": [], "error": auth_error}
all_items.extend(items)
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
+ return {"items": all_items, "error": "Xquik research cancelled or timed out"}
return {"items": all_items}
@@ -128,7 +142,9 @@ def _execute_search(
seen_ids: set[str],
relevance_query: str,
index_offset: int = 0,
+ deadline_monotonic: float | None = None,
failure_out: Optional[List[str]] = None,
+ cancel: Any = None,
) -> tuple[List[Dict[str, Any]], str | None]:
"""Run one Xquik search call and parse its tweets.
@@ -144,12 +160,18 @@ def _execute_search(
handle lanes that differs from the search query (``from:handle``).
``index_offset`` keeps item ids unique across multiple calls that share an
accumulator (multi-query topic search, per-handle lanes).
+ ``deadline_monotonic`` bounds the request including retries at the
+ transport (mirrors ``x_api._get``).
"""
full_url = f"{_BASE_URL}/x/tweets/search?q={_url_encode(q)}&queryType=Top&limit={limit}"
_log(f"Searching: {label}")
try:
request_headers = {"X-Api-Key": token}
- response = http.get(full_url, headers=request_headers, timeout=30, retries=2)
+ response = http.get(
+ full_url, headers=request_headers, timeout=30, retries=2,
+ deadline_monotonic=deadline_monotonic,
+ cancel=cancel,
+ )
except http.HTTPError as exc:
status = getattr(exc, "status_code", None)
if status == 402:
@@ -208,6 +230,8 @@ def search_handles(
count_per: int = 8,
token: str = "",
failure_out: Optional[List[str]] = None,
+ deadline: float | None = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""FROM lane: tweets authored BY each handle (their own timeline).
@@ -225,6 +249,10 @@ def search_handles(
items: List[Dict[str, Any]] = []
seen_ids: set[str] = set()
for raw in handles:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
+ if failure_out is not None:
+ failure_out.append("Xquik research cancelled or timed out")
+ break
handle = str(raw).lstrip("@").strip()
if not handle:
continue
@@ -235,6 +263,8 @@ def search_handles(
seen_ids=seen_ids, relevance_query=topic,
index_offset=len(items),
failure_out=failure_out,
+ deadline_monotonic=deadline,
+ cancel=cancel,
)
if auth_error:
# Fatal auth/payment failure — stop, keep what we have. Surface the
@@ -256,6 +286,8 @@ def search_mentions(
count_per: int = 5,
token: str = "",
failure_out: Optional[List[str]] = None,
+ deadline: float | None = None,
+ cancel: Any = None,
) -> List[Dict[str, Any]]:
"""ABOUT lane: tweets mentioning each handle, authored by OTHERS.
@@ -272,6 +304,10 @@ def search_mentions(
items: List[Dict[str, Any]] = []
seen_ids: set[str] = set()
for raw in handles:
+ if (cancel is not None and cancel.is_set()) or (deadline is not None and time.monotonic() >= deadline):
+ if failure_out is not None:
+ failure_out.append("Xquik research cancelled or timed out")
+ break
handle = str(raw).lstrip("@").strip()
if not handle:
continue
@@ -282,6 +318,8 @@ def search_mentions(
seen_ids=seen_ids, relevance_query=topic,
index_offset=len(items),
failure_out=failure_out,
+ deadline_monotonic=deadline,
+ cancel=cancel,
)
if auth_error:
if failure_out is not None:
diff --git a/skills/last30days/scripts/lib/xurl_x.py b/skills/last30days/scripts/lib/xurl_x.py
index 2d267526..c49b1243 100644
--- a/skills/last30days/scripts/lib/xurl_x.py
+++ b/skills/last30days/scripts/lib/xurl_x.py
@@ -16,6 +16,7 @@ import re
import shutil
import stat
import subprocess
+import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -262,12 +263,16 @@ def _classify_cli_failure(output: str) -> str:
def search_x(
query: str,
depth: str = "default",
+ deadline: Optional[float] = None,
) -> Dict[str, Any]:
"""Search X via xurl CLI using X API v2 search/recent.
Args:
query: Search query string
depth: "quick", "default", or "deep"
+ deadline: Optional shared wall-clock deadline (``time.monotonic()``
+ instant) from the X backend chain. The single subprocess timeout
+ is clamped to the time left; a call past the deadline never starts.
Returns:
Raw JSON response from X API v2 tweets/search/recent, or a dict
@@ -277,6 +282,12 @@ def search_x(
max_results = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
# X API v2 search/recent requires max_results in 10–100 range
max_results = max(10, min(100, max_results))
+ timeout = 30
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining < 1:
+ return {"error": "xurl: chain budget exhausted"}
+ timeout = max(1, min(timeout, int(remaining)))
charge = None
try:
@@ -288,7 +299,7 @@ def search_x(
["xurl", "search", query, "-n", str(max_results), "--auth", "app"],
capture_output=True,
text=True,
- timeout=30,
+ timeout=timeout,
)
if result.returncode != 0:
diff --git a/tests/test_bird_x.py b/tests/test_bird_x.py
index 18adfa08..87d8ba40 100644
--- a/tests/test_bird_x.py
+++ b/tests/test_bird_x.py
@@ -581,7 +581,7 @@ class TestStrongestTokenRetryAnchored(unittest.TestCase):
queries = []
- def fake_run(query, count, timeout):
+ def fake_run(query, count, timeout, deadline=None):
queries.append(query)
return {"items": []} # always 0 → forces every retry tier
@@ -603,7 +603,7 @@ class TestStrongestTokenRetryAnchored(unittest.TestCase):
queries = []
- def fake_run(query, count, timeout):
+ def fake_run(query, count, timeout, deadline=None):
queries.append(query)
return {"items": []}
@@ -622,7 +622,7 @@ class TestBirdRetryQueryCorrectness(unittest.TestCase):
queries = []
- def fake_run(query, count, timeout):
+ def fake_run(query, count, timeout, deadline=None):
queries.append(query)
if len(queries) == 1:
return {"items": []}
diff --git a/tests/test_discover_floor.py b/tests/test_discover_floor.py
index 5710c19a..c8109b07 100644
--- a/tests/test_discover_floor.py
+++ b/tests/test_discover_floor.py
@@ -50,7 +50,7 @@ def _reddit_item(item_id: str, title: str, score: int, comments: int, *, date: s
def _run_discover_with(items_by_source: dict[str, list[dict]], **kwargs) -> schema.DiscoveryReport:
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
return items_by_source.get(source, []), None
with mock.patch.object(
diff --git a/tests/test_discover_mode.py b/tests/test_discover_mode.py
index 9e2f3146..ec0e7769 100644
--- a/tests/test_discover_mode.py
+++ b/tests/test_discover_mode.py
@@ -100,7 +100,7 @@ def test_global_discovery_disables_keyword_gate():
"""Global trending fetches with keyword_gate=False; domain runs keep it on."""
seen: dict[str, bool] = {}
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
seen[plan.domain or "global"] = keyword_gate
return [], None
@@ -250,7 +250,7 @@ def test_discovery_renderer_snapshot():
def test_keyless_discovery_degrades_without_digg():
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
return pipeline._mock_discovery_items(source, plan.domain, to_date), None
with mock.patch.object(pipeline, "available_sources", return_value=["reddit", "hackernews"]), \
@@ -323,7 +323,7 @@ def test_discovery_reads_browser_credentials_and_does_not_schedule_pending_x():
assert x_pending is False
return ["reddit", "hackernews"] + (["x"] if x_pending is not False else [])
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
fetched_sources.append(source)
return pipeline._mock_discovery_items(source, plan.domain, to_date), None
@@ -363,7 +363,7 @@ def test_authenticated_x_discovery_uses_available_backend():
def test_listing_failure_is_not_reported_as_clean_no_results():
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
if source == "reddit":
return [], "connection timed out"
return pipeline._mock_discovery_items(source, plan.domain, to_date), None
@@ -767,7 +767,7 @@ def test_x_fallback_success_is_clean(monkeypatch):
calls = []
- def fake_fetch(backend, subquery, from_date, to_date, depth, config):
+ def fake_fetch(backend, subquery, from_date, to_date, depth, config, warnings=None, deadline=None):
calls.append(backend)
if backend == "bird":
return [], "cookie expired"
@@ -1448,7 +1448,7 @@ def test_discovery_cli_nominate_only_zero_nominations_nothing_solid(tmp_path, ca
["--discover", "AI agents", "--save-dir", str(tmp_path), "--nominate-only"]
)
- def empty_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def empty_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
return [], None
with mock.patch.object(
diff --git a/tests/test_discover_nominate.py b/tests/test_discover_nominate.py
index d15f61e3..67995e75 100644
--- a/tests/test_discover_nominate.py
+++ b/tests/test_discover_nominate.py
@@ -52,7 +52,7 @@ def test_nominate_candidates_threads_keyword_gate():
plan = _plan("", ["reddit"])
seen: dict[str, bool] = {}
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
seen["keyword_gate"] = keyword_gate
return [], None
@@ -72,7 +72,7 @@ def test_nominate_candidates_records_source_failure_without_raising():
still yields candidates, and the call never raises."""
plan = _plan("AI agents", ["reddit", "hackernews"])
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
if source == "hackernews":
raise TimeoutError("hn listing timed out")
return pipeline._mock_discovery_items(source, plan.domain, to_date), None
diff --git a/tests/test_discover_nominate_topics.py b/tests/test_discover_nominate_topics.py
index 06b6a621..8c592b4b 100644
--- a/tests/test_discover_nominate_topics.py
+++ b/tests/test_discover_nominate_topics.py
@@ -424,7 +424,7 @@ def _hn_raw(item_id: str, title: str, points: int, comments: int, *, date: str =
def _nominate_only(items_by_source: dict[str, list[dict]], **kwargs) -> "pipeline.DiscoverNominateResult":
- def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True):
+ def fake_fetch(source, plan, *, from_date, to_date, depth, mock, config, keyword_gate=True, warnings=None):
return items_by_source.get(source, []), None
with mock.patch.object(
diff --git a/tests/test_pipeline_cancellation.py b/tests/test_pipeline_cancellation.py
new file mode 100644
index 00000000..bd473180
--- /dev/null
+++ b/tests/test_pipeline_cancellation.py
@@ -0,0 +1,544 @@
+from __future__ import annotations
+
+import threading
+import time
+import urllib.error
+from dataclasses import replace
+from unittest import mock
+from uuid import uuid4
+
+import pytest
+
+from lib import dates, health, http, pipeline, schema
+
+
+def x_run(monkeypatch):
+ topic = f"Widget compiler {uuid4().hex}"
+ today = dates.get_date_range(30)[1]
+ post = {
+ "id": "1", "url": "https://x.com/widget/status/1",
+ "author_handle": "widget", "text": f"{topic} ships incremental builds",
+ "date": today, "engagement": {"likes": 100}, "relevance": 1.0,
+ }
+ plan = schema.QueryPlan(
+ raw_topic=topic, intent="opinion", freshness_mode="balanced_recent",
+ cluster_mode="debate", source_weights={"x": 1.0},
+ subqueries=[schema.SubQuery(
+ label="primary", search_query=topic, ranking_query=topic, sources=["x"],
+ )],
+ )
+ runtime = schema.ProviderRuntime(
+ reasoning_provider="native", planner_model="", rerank_model="",
+ x_search_backend="xapi",
+ )
+ monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
+ monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["x"])
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi"])
+ monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: plan)
+ monkeypatch.setattr(pipeline.entity_extract, "extract_entities", lambda *a, **k: {
+ "x_handles": ["widget"], "x_hashtags": [], "reddit_subreddits": [],
+ })
+ return topic, post, plan, runtime
+
+
[email protected]("expired", [True, False])
+def test_enrichment_lifecycle_stops_late_supplemental_requests(monkeypatch, x_run, expired):
+ topic, post, _, _ = x_run
+ release = threading.Event()
+ finished = threading.Event()
+ stream_finished = threading.Event()
+ calls = []
+ if not expired:
+ release.set()
+
+ def topic_search(*args, **kwargs):
+ calls.append("topic")
+ assert release.wait(5)
+ return {"items": [post, {
+ **post, "id": "2", "url": "https://x.com/widget/status/2",
+ "text": f"{topic} community discusses authentication errors and setup tutorials for new users",
+ }]}
+
+ def from_search(*args, **kwargs):
+ calls.append("FROM")
+ return []
+
+ def about_search(*args, **kwargs):
+ calls.append("ABOUT")
+ return []
+
+ original_run = pipeline.run
+ original_stream = pipeline._retrieve_stream
+
+ def tracked_stream(**kwargs):
+ try:
+ return original_stream(**kwargs)
+ finally:
+ stream_finished.set()
+
+ def tracked_run(**kwargs):
+ try:
+ return original_run(**kwargs)
+ finally:
+ finished.set()
+
+ monkeypatch.setattr(pipeline, "run", tracked_run)
+ monkeypatch.setattr(pipeline, "_retrieve_stream", tracked_stream)
+ monkeypatch.setattr(pipeline.x_api, "search_x", topic_search)
+ monkeypatch.setattr(pipeline.x_api, "search_handles", from_search)
+ monkeypatch.setattr(pipeline.x_api, "search_mentions", about_search)
+ start = time.monotonic()
+ try:
+ result = pipeline.enrich_nominations(
+ [pipeline.Nomination(name=topic, seed_score=1)],
+ config={"X_BEARER_TOKEN": "dummy", "LAST30DAYS_X_BACKEND": "xapi"},
+ depth="default", requested_sources=["x"], budget_seconds=1 if expired else 5,
+ max_workers=1,
+ )
+ elapsed = time.monotonic() - start
+ finally:
+ release.set()
+ assert finished.wait(5), "the actual abandoned pipeline worker must finish"
+ assert stream_finished.wait(5), "the in-flight stream must finish before checking for late requests"
+ if expired:
+ assert elapsed < 2
+ assert result[0].error == "enrichment budget exhausted"
+ assert calls == ["topic"], f"new adapter requests after return: {calls}"
+ else:
+ assert result[0].report is not None and result[0].error is None
+ assert "FROM" in calls and "ABOUT" in calls
+
+
[email protected]("stop", ["cancel", "deadline"])
+def test_x_failover_stops_after_inflight_backend(monkeypatch, x_run, stop):
+ topic, _, plan, runtime = x_run
+ cancel = threading.Event()
+ config = {"_enrich_cancel": cancel, "_research_deadline": time.monotonic() + 10}
+ calls = []
+
+ def first(*args, **kwargs):
+ calls.append("xapi")
+ if stop == "cancel":
+ cancel.set()
+ else:
+ config["_research_deadline"] = time.monotonic() - 1
+ return {"items": []}
+
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
+ monkeypatch.setattr(pipeline.x_api, "search_x", first)
+ monkeypatch.setattr(pipeline.xquik, "search_xquik", lambda *a, **k: calls.append("xquik") or {"items": []})
+ try:
+ pipeline._retrieve_stream_impl(
+ topic=topic, subquery=plan.subqueries[0], source="x", config=config,
+ depth="quick", date_range=dates.get_date_range(30), runtime=runtime, mock=False,
+ )
+ except pipeline.SourceRunError:
+ pass
+ assert calls == ["xapi"]
+
+
[email protected]("backend", ["xapi", "bird", "xquik", "grok"])
+def test_supplemental_stops_between_lanes(monkeypatch, x_run, backend):
+ topic, _, plan, runtime = x_run
+ runtime = replace(runtime, x_search_backend=backend)
+ cancel = threading.Event()
+ calls = []
+ adapter = {"xapi": pipeline.x_api, "bird": pipeline.bird_x,
+ "xquik": pipeline.xquik, "grok": pipeline.grok_x}[backend]
+
+ def from_search(*args, **kwargs):
+ calls.append("FROM")
+ cancel.set()
+ return ([], False) if backend == "grok" else []
+
+ def about_search(*args, **kwargs):
+ calls.append("ABOUT")
+ return ([], False) if backend == "grok" else []
+
+ monkeypatch.setattr(adapter, "search_handles", from_search)
+ monkeypatch.setattr(adapter, "search_mentions", about_search)
+ monkeypatch.setattr(pipeline.grok_x, "search_name", lambda *a, **k: calls.append("NAME") or ([], False))
+ pipeline._run_supplemental_searches(
+ topic=topic, bundle=schema.RetrievalBundle(), plan=plan,
+ config={"_enrich_cancel": cancel, "X_BEARER_TOKEN": "dummy", "XQUIK_API_KEY": "dummy"},
+ depth="default", date_range=dates.get_date_range(30), runtime=runtime, mock=False,
+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(), x_handle="widget",
+ x_related=["related"],
+ )
+ assert calls == ["FROM"]
+
+
+def test_enrichment_skips_queued_nomination_after_budget(monkeypatch, x_run):
+ topic, post, _, _ = x_run
+ release = threading.Event()
+ finished = threading.Event()
+ calls = []
+
+ def search(*args, **kwargs):
+ calls.append(args[1])
+ try:
+ assert release.wait(5)
+ return {"items": [post]}
+ finally:
+ finished.set()
+
+ monkeypatch.setattr(pipeline.x_api, "search_x", search)
+ try:
+ result = pipeline.enrich_nominations(
+ [pipeline.Nomination(name=name, seed_score=1) for name in (topic, "queued widget")],
+ config={"X_BEARER_TOKEN": "dummy"}, requested_sources=["x"],
+ max_workers=1, budget_seconds=1,
+ )
+ finally:
+ release.set()
+ assert finished.wait(5)
+ for thread in threading.enumerate():
+ if thread.name.startswith("discover-enrich-"):
+ thread.join(timeout=5)
+ assert not thread.is_alive()
+ assert calls == [topic]
+ assert all(entry.report is None and entry.error for entry in result)
+
+
[email protected]("phase", ["stream", "discovery", "thin"])
+def test_fanout_timeout_stops_late_x_failover(monkeypatch, x_run, phase):
+ topic, _, plan, runtime = x_run
+ release = threading.Event()
+ finished = threading.Event()
+ calls = []
+ original_stream = pipeline._retrieve_stream
+ original_discovery = pipeline._fetch_discovery_source
+
+ def stream(*args, **kwargs):
+ try:
+ return original_stream(*args, **kwargs)
+ finally:
+ finished.set()
+
+ def discovery(*args, **kwargs):
+ try:
+ return original_discovery(*args, **kwargs)
+ finally:
+ finished.set()
+
+ def search(*args, **kwargs):
+ calls.append("xapi")
+ assert release.wait(5)
+ return {"items": []}
+
+ monkeypatch.setattr(pipeline, "_retrieve_stream", stream)
+ monkeypatch.setattr(pipeline, "_fetch_discovery_source", discovery)
+ monkeypatch.setattr(pipeline.x_api, "search_x", search)
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
+ monkeypatch.setattr(pipeline.xquik, "search_xquik", lambda *a, **k: calls.append("xquik") or {"items": []})
+ for constant in ("STREAM_FUTURE_TIMEOUT_SECONDS", "DISCOVERY_FUTURE_TIMEOUT_SECONDS", "THIN_RETRY_FUTURE_TIMEOUT_SECONDS"):
+ monkeypatch.setattr(pipeline, constant, 0.05)
+ started = time.monotonic()
+ try:
+ if phase == "stream":
+ result = pipeline.run(topic=topic, config={"X_BEARER_TOKEN": "dummy"}, depth="quick", requested_sources=["x"])
+ elif phase == "discovery":
+ result = pipeline.nominate_candidates(
+ mock.Mock(domain=topic, sources=["x"]), from_date=dates.get_date_range(30)[0],
+ to_date=dates.get_date_range(30)[1], depth="quick", mock=False, config={}, lookback_days=30,
+ )
+ else:
+ result = schema.RetrievalBundle()
+ pipeline._retry_thin_sources(
+ topic=topic, bundle=result, plan=plan, config={}, depth="default",
+ date_range=dates.get_date_range(30), runtime=runtime, mock=False,
+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),
+ settings={"per_stream_limit": 6},
+ )
+ assert time.monotonic() - started < 1
+ assert result.source_status["x"].state == health.TIMEOUT
+ finally:
+ release.set()
+ assert finished.wait(5)
+ assert calls == ["xapi"]
+
+
+def test_provider_scoring_does_not_start_after_cancelled_rerank(monkeypatch, x_run):
+ topic, post, _, _ = x_run
+ cancel = threading.Event()
+ calls = []
+ monkeypatch.setattr(pipeline.x_api, "search_x", lambda *a, **k: {"items": [post]})
+ original = pipeline.rerank.rerank_candidates
+
+ def rerank(**kwargs):
+ calls.append("rerank")
+ result = original(**kwargs)
+ cancel.set()
+ return result
+
+ monkeypatch.setattr(pipeline.rerank, "rerank_candidates", rerank)
+ monkeypatch.setattr(pipeline.rerank, "score_fun", lambda **k: calls.append("score"))
+ with pytest.raises(TimeoutError):
+ pipeline.run(topic=topic, config={"_enrich_cancel": cancel}, depth="quick", requested_sources=["x"])
+ assert "rerank" in calls and "score" not in calls
+
+
+def test_planner_does_not_start_after_cancelled_source_resolution(monkeypatch, x_run):
+ topic, _, _, _ = x_run
+ cancel = threading.Event()
+ calls = []
+
+ def available(*args, **kwargs):
+ cancel.set()
+ return ["x"]
+
+ original = pipeline.planner.plan_query
+
+ def plan(**kwargs):
+ calls.append("planner")
+ return original(**kwargs)
+
+ monkeypatch.setattr(pipeline, "available_sources", available)
+ monkeypatch.setattr(pipeline.planner, "plan_query", plan)
+ with pytest.raises(TimeoutError):
+ pipeline.run(topic=topic, config={"_enrich_cancel": cancel}, depth="quick", requested_sources=["x"])
+ assert calls == []
+
+
[email protected]("adapter", ["grok", "bird", "xquik", "xapi"])
+def test_adapter_cancellation_stops_its_next_request(monkeypatch, adapter):
+ cancel = threading.Event()
+ calls = []
+
+ def request(*args, **kwargs):
+ calls.append(adapter)
+ cancel.set()
+ if adapter == "grok":
+ return {"error": "temporary transport failure"}
+ if adapter == "bird":
+ from lib.subproc import SubprocResult
+ return SubprocResult(0, "<html>interstitial</html>", ""), None
+ if adapter == "xapi":
+ return {
+ "data": [{"id": "1", "text": "Widget release", "created_at": dates.get_date_range(30)[1]}],
+ "meta": {"next_token": "next-page"},
+ }
+ return {"tweets": []}
+
+ if adapter == "grok":
+ monkeypatch.setattr(pipeline.grok_x, "_invoke", request)
+ result = pipeline.grok_x.search_x("widget compiler", *dates.get_date_range(30), cancel=cancel)
+ elif adapter == "bird":
+ monkeypatch.setattr(pipeline.bird_x, "_invoke_bird_subprocess", request)
+ result = pipeline.bird_x.search_x("widget compiler", *dates.get_date_range(30), cancel=cancel)
+ elif adapter == "xquik":
+ monkeypatch.setattr(pipeline.xquik.http, "get", request)
+ topic = "best widget compiler tools for incremental development"
+ assert len(pipeline.xquik.expand_xquik_queries(topic, "default")) > 1
+ result = pipeline.xquik.search_xquik(topic, *dates.get_date_range(30), token="dummy", cancel=cancel)
+ else:
+ monkeypatch.setattr(pipeline.x_api.http, "get", request)
+ result = pipeline.x_api.search_x("dummy", "widget compiler", *dates.get_date_range(30), cancel=cancel)
+ assert result["items"], "keep the completed page as partial evidence"
+ assert calls == [adapter]
+ assert result.get("error") or result.get("warning")
+
+
+def test_http_cancellation_stops_retry_without_backoff(monkeypatch):
+ cancel = threading.Event()
+ calls = []
+
+ def request(*args, **kwargs):
+ calls.append("request")
+ cancel.set()
+ raise urllib.error.HTTPError("https://example.invalid", 503, "temporarily unavailable", {}, None)
+
+ monkeypatch.setattr(http.urllib.request, "urlopen", request)
+ started = time.monotonic()
+ with pytest.raises(http.DeadlineExceeded):
+ http.get("https://example.invalid", retries=3, cancel=cancel)
+ assert time.monotonic() - started < 0.5
+ assert calls == ["request"]
+
+
+def test_http_cancellation_bounds_inflight_body_wait(monkeypatch):
+ cancel = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+ calls = []
+ response = mock.MagicMock()
+ response.__enter__.return_value = response
+ response.status = 200
+
+ def read():
+ calls.append("body")
+ cancel.set()
+ try:
+ assert release.wait(5)
+ return b'{"ok": true}'
+ finally:
+ finished.set()
+
+ response.read.side_effect = read
+ monkeypatch.setattr(http.urllib.request, "urlopen", lambda *a, **k: response)
+ started = time.monotonic()
+ try:
+ with pytest.raises(http.DeadlineExceeded):
+ http.get("https://example.invalid", retries=3, cancel=cancel)
+ assert time.monotonic() - started < 0.5
+ assert not finished.is_set(), "the caller must stop waiting while the body read remains blocked"
+ finally:
+ release.set()
+ assert finished.wait(5)
+ assert calls == ["body"]
+
+
[email protected]("outcome", ["cancelled", "partial", "empty"])
+def test_xquik_final_query_preserves_stop_status_and_items(monkeypatch, outcome):
+ cancel = threading.Event()
+ tweet = {"id": "123", "text": "Widget release", "author": {"username": "widget"}}
+
+ def request(*args, **kwargs):
+ if outcome != "empty":
+ cancel.set()
+ if outcome == "cancelled":
+ raise http.DeadlineExceeded()
+ return {"tweets": [tweet] if outcome == "partial" else []}
+
+ monkeypatch.setattr(pipeline.xquik.http, "get", request)
+ result = pipeline.xquik.search_xquik("Widget", *dates.get_date_range(30), depth="quick", token="dummy", cancel=cancel)
+ if outcome == "empty":
+ assert result == {"items": []}
+ else:
+ assert "timed out" in result.get("error", "")
+ assert len(result["items"]) == (1 if outcome == "partial" else 0)
+
+
+def test_sole_xquik_backend_reports_cancelled_final_request(monkeypatch, x_run):
+ topic, _, plan, runtime = x_run
+ cancel = threading.Event()
+
+ def request(*args, **kwargs):
+ cancel.set()
+ raise http.DeadlineExceeded()
+
+ monkeypatch.setattr(pipeline.xquik.http, "get", request)
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xquik"])
+ with pytest.raises(pipeline.SourceRunError) as caught:
+ pipeline._retrieve_stream_impl(
+ topic=topic, subquery=plan.subqueries[0], source="x",
+ config={"XQUIK_API_KEY": "dummy", "_enrich_cancel": cancel},
+ depth="quick", date_range=dates.get_date_range(30),
+ runtime=replace(runtime, x_search_backend="xquik"), mock=False,
+ )
+ assert caught.value.outcome_state == health.TIMEOUT
+
+
+def test_grok_retains_items_and_reports_cancelled_fanout(monkeypatch):
+ cancel = threading.Event()
+
+ def invoke(*args, **kwargs):
+ cancel.set()
+ return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
+
+ monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
+ result = pipeline.grok_x.search_x("Widget compiler", "2026-07-14", "2026-08-13", cancel=cancel)
+ assert result["items"], "the completed query remains useful partial evidence"
+ assert "timed out" in result.get("error", "")
+
+
[email protected]("cancelled", [True, False])
+def test_grok_final_empty_query_reports_cancellation(monkeypatch, cancelled):
+ cancel = threading.Event()
+
+ def invoke(*args, **kwargs):
+ if cancelled:
+ cancel.set()
+ return {"text": "No matching posts found."}
+
+ monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
+ result = pipeline.grok_x.search_x("Widget", "2026-07-14", "2026-08-13", depth="quick", cancel=cancel)
+ if cancelled:
+ assert "timed out" in result.get("error", "")
+ else:
+ assert result == {"items": []}
+
+
+def test_grok_partial_cancellation_keeps_revoked_session_reason(monkeypatch):
+ cancel = threading.Event()
+ calls = []
+
+ def invoke(*args, **kwargs):
+ calls.append("invoke")
+ if len(calls) == 1:
+ return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
+ cancel.set()
+ return {"error": "Grok session expired", "auth_revoked": True}
+
+ monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
+ items, error = pipeline._fetch_x_backend(
+ "grok", "Widget compiler", "2026-07-14", "2026-08-13", "default",
+ {"_enrich_cancel": cancel},
+ )
+ assert len(items) == 1
+ assert "session expired" in error
+ assert "timed out" not in error
+
+
[email protected]("partial", [True, False])
+def test_grok_short_remaining_budget_reports_timeout(monkeypatch, partial):
+ now = [100.0]
+ deadline = 120.0 if partial else 105.0
+ calls = []
+
+ def invoke(*args, **kwargs):
+ calls.append("invoke")
+ now[0] = 116.0
+ return {"text": "id: 2087568620465607078\nhandle: widget\ncreated_at: Wed, 12 Aug 2026 15:55:18 GMT\nlikes: 10\ntext: Widget compiler release\n"}
+
+ monkeypatch.setattr(pipeline.grok_x.time, "monotonic", lambda: now[0])
+ monkeypatch.setattr(pipeline.grok_x, "_invoke", invoke)
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["grok"])
+ kwargs = dict(
+ topic="Widget", subquery=schema.SubQuery(label="primary", search_query="Widget", ranking_query="Widget", sources=["x"]),
+ source="x", config={"_research_deadline": deadline}, depth="default",
+ date_range=("2026-07-14", "2026-08-13"), mock=False,
+ runtime=schema.ProviderRuntime(reasoning_provider="native", planner_model="", rerank_model="", x_search_backend="grok"),
+ )
+ if partial:
+ items, artifact = pipeline._retrieve_stream(**kwargs)
+ assert len(items) == 1
+ assert artifact["_source_outcome"]["state"] == health.TIMEOUT
+ assert calls == ["invoke"]
+ else:
+ with pytest.raises(pipeline.SourceRunError) as caught:
+ pipeline._retrieve_stream(**kwargs)
+ assert caught.value.outcome_state == health.TIMEOUT
+ assert calls == []
+ assert now[0] < deadline
+
+
[email protected]("failure", ["exception", "outcome"])
+def test_rate_limit_stops_queued_streams_before_fanout_finishes(monkeypatch, x_run, failure):
+ topic, _, plan, _ = x_run
+ plan.subqueries = [replace(plan.subqueries[0], label=f"query-{index}") for index in range(6)]
+ barrier = threading.Barrier(4)
+ calls = []
+ lock = threading.Lock()
+
+ def request(*args, **kwargs):
+ with lock:
+ index = len(calls)
+ calls.append(index)
+ if index < 4:
+ barrier.wait(2)
+ if index == 0:
+ if failure == "exception":
+ raise http.HTTPError("Rate limit exceeded", status_code=429)
+ return {"items": [], "error": "xapi: rate limited (429)"}
+ threading.Event().wait(0.2)
+ return {"items": []}
+
+ monkeypatch.setattr(pipeline.x_api, "search_x", request)
+ report = pipeline.run(
+ topic=topic, config={"X_BEARER_TOKEN": "dummy", "_max_source_fetches": 6},
+ depth="quick", requested_sources=["x"], internal_subrun=True,
+ )
+ assert calls == [0, 1, 2, 3], "queued X streams must see the completed worker's rate-limit signal"
+ assert report.source_status["x"].state == health.RATE_LIMITED
diff --git a/tests/test_timeout_architecture.py b/tests/test_timeout_architecture.py
new file mode 100644
index 00000000..9dcf9418
--- /dev/null
+++ b/tests/test_timeout_architecture.py
@@ -0,0 +1,566 @@
+"""Timeout architecture: shared X-chain deadline and bounded stream waits."""
+
+import queue
+import threading
+import time
+from unittest import mock
+from uuid import uuid4
+
+import pytest
+
+from lib import health, http, pipeline, render, schema, xai_x
+
+
+def test_stream_timeouts_are_bounded():
+ for name in (
+ "STREAM_FUTURE_TIMEOUT_SECONDS",
+ "DISCOVERY_FUTURE_TIMEOUT_SECONDS",
+ "THIN_RETRY_FUTURE_TIMEOUT_SECONDS",
+ "X_CHAIN_DEADLINE_SECONDS",
+ ):
+ value = getattr(pipeline, name)
+ assert 0 < value <= 600, f"{name}={value} must be a finite wall-clock bound"
+
+
+def test_fetch_x_backend_forwards_deadline(monkeypatch):
+ seen = {}
+ monkeypatch.setattr(
+ pipeline.grok_x, "search_x",
+ lambda *a, **k: (seen.update(grok=k.get("deadline")), {"items": []})[1],
+ )
+ monkeypatch.setattr(
+ pipeline.xai_x, "search_x",
+ lambda *a, **k: (seen.update(xai=k.get("deadline_monotonic")), {"items": []})[1],
+ )
+ monkeypatch.setattr(pipeline.xai_x, "parse_x_response", lambda r: [])
+ monkeypatch.setattr(
+ pipeline.xquik, "search_xquik",
+ lambda *a, **k: (seen.update(xquik=k.get("deadline")), {"items": []})[1],
+ )
+ monkeypatch.setattr(pipeline.xquik, "parse_xquik_response", lambda r: [])
+ monkeypatch.setattr(
+ pipeline.x_api, "search_x",
+ lambda *a, **k: (seen.update(xapi=k.get("deadline")), {"items": []})[1],
+ )
+ monkeypatch.setattr(
+ pipeline.bird_x, "search_x",
+ lambda *a, **k: (seen.update(bird=k.get("deadline")), {"items": [], "error": ""})[1],
+ )
+ monkeypatch.setattr(pipeline.bird_x, "parse_bird_response", lambda *a, **k: [])
+ monkeypatch.setattr(
+ pipeline.xurl_x, "search_x",
+ lambda *a, **k: (seen.update(xurl=k.get("deadline")), {"items": [], "error": ""})[1],
+ )
+ monkeypatch.setattr(pipeline.xurl_x, "parse_x_response", lambda *a, **k: [])
+ deadline = time.monotonic() + 90
+ cfg = {"XAI_API_KEY": "k", "X_BEARER_TOKEN": "b"}
+ monkeypatch.setattr(pipeline.env, "get_xquik_token", lambda c: "q")
+ pipeline._fetch_x_backend("grok", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["grok"] == deadline
+ pipeline._fetch_x_backend("xai", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["xai"] == deadline
+ pipeline._fetch_x_backend("xquik", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["xquik"] == deadline
+ pipeline._fetch_x_backend("xapi", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["xapi"] == deadline
+ pipeline._fetch_x_backend("bird", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["bird"] == deadline
+ pipeline._fetch_x_backend("xurl", "q", "2026-08-01", "2026-08-31", "quick", cfg, deadline=deadline)
+ assert seen["xurl"] == deadline
+
+
+def test_x_chain_skips_past_deadline(monkeypatch):
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi", "xquik"])
+ calls = []
+ monkeypatch.setattr(
+ pipeline, "_fetch_x_backend",
+ lambda *a, **k: (calls.append(a[0]), ([], "boom"))[1],
+ )
+ # First monotonic() call sets the deadline, the second (chain check) is past it.
+ monkeypatch.setattr(
+ pipeline.time, "monotonic",
+ mock.Mock(side_effect=[1000.0, 2000.0, 2000.0]),
+ )
+ plan = mock.Mock()
+ plan.domain = "topic"
+ items, err = pipeline._fetch_discovery_source(
+ "x", plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, keyword_gate=True,
+ )
+ assert items == []
+ assert "budget exhausted" in (err or "")
+ assert calls == [], "no backend may start past the shared deadline"
+
+
+def test_enrich_cancel_skips_network(monkeypatch):
+ cancel = threading.Event()
+ cancel.set()
+ subquery = schema.SubQuery(
+ label="primary", search_query="topic",
+ ranking_query="topic", sources=["reddit"], weight=1.0,
+ )
+ items, artifact = pipeline._retrieve_stream_impl(
+ topic="topic", subquery=subquery, source="reddit",
+ config={"_enrich_cancel": cancel}, depth="quick",
+ date_range=("2026-08-01", "2026-08-31"),
+ runtime=mock.Mock(), mock=True,
+ )
+ assert items == []
+ assert artifact["_source_outcome"]["state"] == health.TIMEOUT
+ assert artifact["_source_outcome"]["attempted"] is False
+
+
+def test_enrich_cancel_skips_real_transport(monkeypatch):
+ """Same early exit with mock=False: no transport call may fire."""
+ cancel = threading.Event()
+ cancel.set()
+ monkeypatch.setattr(
+ pipeline.grounding, "web_search",
+ mock.Mock(side_effect=AssertionError("transport must not fire")),
+ )
+ subquery = schema.SubQuery(
+ label="primary", search_query="topic",
+ ranking_query="topic", sources=["grounding"], weight=1.0,
+ )
+ items, artifact = pipeline._retrieve_stream_impl(
+ topic="topic", subquery=subquery, source="grounding",
+ config={"_enrich_cancel": cancel}, depth="quick",
+ date_range=("2026-08-01", "2026-08-31"),
+ runtime=mock.Mock(), mock=False,
+ )
+ assert items == []
+ assert artifact["_source_outcome"]["state"] == health.TIMEOUT
+ assert artifact["_source_outcome"]["attempted"] is False
+ assert pipeline.grounding.web_search.call_count == 0
+
+
+def test_discovery_timeout_records_timeout_partial(monkeypatch):
+ monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
+ def slow(*a, **k):
+ time.sleep(0.4)
+ return [], None
+ monkeypatch.setattr(pipeline, "_fetch_discovery_source", slow)
+ plan = mock.Mock()
+ plan.sources = ["reddit"]
+ plan.domain = "topic"
+ start = time.monotonic()
+ bundle = pipeline.nominate_candidates(
+ plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, lookback_days=30,
+ )
+ elapsed = time.monotonic() - start
+ assert elapsed < 1.5, f"hung lane must not stall nominate (took {elapsed:.2f}s)"
+ outcome = bundle.source_status["reddit"]
+ assert outcome.state == health.TIMEOUT
+
+
+def test_xai_single_attempt_with_deadline(monkeypatch):
+ seen = {}
+ def fake_post(url, payload, headers=None, **kwargs):
+ seen.update(kwargs)
+ return {"output": []}
+ monkeypatch.setattr(pipeline.xai_x.http, "post", fake_post)
+ deadline = time.monotonic() + 90
+ xai_x.search_x("k", "m", "topic", "2026-08-01", "2026-08-31", deadline_monotonic=deadline)
+ assert seen.get("retries") == 1
+ assert seen.get("deadline_monotonic") == deadline
+
+
+def test_bird_clamps_timeout_to_remaining_deadline(monkeypatch):
+ from lib import bird_x
+ seen = []
+ monkeypatch.setattr(
+ bird_x, "_run_bird_search",
+ lambda q, count, timeout, deadline=None: (seen.append(timeout), {"items": [], "error": ""})[1],
+ )
+ monkeypatch.setattr(bird_x, "parse_bird_response", lambda *a, **k: [])
+ bird_x.search_x("topic", "2026-08-01", "2026-08-31", depth="default",
+ deadline=time.monotonic() + 5)
+ assert seen, "at least the first search must run"
+ assert all(t <= 5 for t in seen), f"per-attempt timeouts must fit the budget: {seen}"
+
+
+def test_bird_skips_subprocess_past_deadline(monkeypatch):
+ from lib import bird_x
+ calls = []
+ monkeypatch.setattr(
+ bird_x, "_run_bird_search",
+ lambda *a, **k: (calls.append(a), {"items": [], "error": ""})[1],
+ )
+ result = bird_x.search_x("topic", "2026-08-01", "2026-08-31",
+ deadline=time.monotonic() - 1)
+ assert calls == []
+ assert "budget exhausted" in result.get("error", "")
+
+
+def test_xurl_skips_subprocess_past_deadline(monkeypatch):
+ from lib import xurl_x
+ calls = []
+ monkeypatch.setattr(
+ xurl_x.subprocess, "run",
+ lambda *a, **k: (calls.append(k.get("timeout")), mock.Mock(returncode=0, stdout="{}", stderr=""))[1],
+ )
+ result = xurl_x.search_x("topic", deadline=time.monotonic() - 1)
+ assert calls == []
+ assert "budget exhausted" in result.get("error", "")
+ xurl_x.search_x("topic", deadline=time.monotonic() + 5)
+ assert calls and calls[-1] <= 5
+
+
+def test_grok_fanout_respects_cancel(monkeypatch):
+ from lib import grok_x
+ calls = []
+ monkeypatch.setattr(grok_x, "binary_path", lambda: "/usr/bin/grok")
+ def fake_run(cmd, **kwargs):
+ import subprocess
+ calls.append(cmd)
+ return subprocess.CompletedProcess(cmd, 0, "no posts", "")
+ monkeypatch.setattr(grok_x.subprocess, "run", fake_run)
+ cancel = threading.Event()
+ cancel.set()
+ result = grok_x.search_x("topic", "2026-08-01", "2026-08-31", cancel=cancel)
+ assert calls == [], "a cancelled fan-out must not start subprocesses"
+ assert result["items"] == []
+
+
+def test_discovery_xapi_warning_reaches_bundle_artifact(monkeypatch):
+ monkeypatch.setattr(pipeline.env, "x_backend_chain", lambda c: ["xapi"])
+ monkeypatch.setattr(
+ pipeline.x_api, "search_x",
+ lambda *a, **k: {"items": [{"id": "1"}], "warning": "window truncated to 7 days"},
+ )
+ plan = mock.Mock()
+ plan.domain = "topic"
+ warnings: list[str] = []
+ items, err = pipeline._fetch_discovery_source(
+ "x", plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, keyword_gate=True,
+ warnings=warnings,
+ )
+ assert items and err is None
+ assert warnings == ["X: xapi window truncated to 7 days"]
+
+
+def test_nominate_surfaces_x_receipts_as_artifact(monkeypatch):
+ def fake_source(source, plan, **kwargs):
+ warnings = kwargs.get("warnings")
+ if warnings is not None:
+ warnings.extend(["X: xapi window truncated to 7 days"])
+ return [], None
+ monkeypatch.setattr(pipeline, "_fetch_discovery_source", fake_source)
+ plan = mock.Mock()
+ plan.sources = ["x"]
+ plan.domain = "topic"
+ bundle = pipeline.nominate_candidates(
+ plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, lookback_days=30,
+ )
+ assert bundle.artifacts.get("x_partial_coverage") == ["X: xapi window truncated to 7 days"]
+
+
+def test_thin_retry_skipped_when_cancelled(monkeypatch):
+ cancel = threading.Event()
+ cancel.set()
+ calls = []
+ monkeypatch.setattr(
+ pipeline, "_retrieve_stream",
+ lambda **k: (calls.append(k.get("source")), ([], {}))[1],
+ )
+ bundle = schema.RetrievalBundle()
+ plan = mock.Mock()
+ plan.subqueries = [schema.SubQuery(
+ label="primary", search_query="Kanye West",
+ ranking_query="Kanye West", sources=["reddit"], weight=1.0,
+ )]
+ plan.freshness_mode = "breaking"
+ pipeline._retry_thin_sources(
+ topic="Kanye West", bundle=bundle, plan=plan,
+ config={"_enrich_cancel": cancel}, depth="default",
+ date_range=("2026-08-01", "2026-08-31"), runtime=mock.Mock(),
+ mock=False, rate_limited_sources=set(),
+ rate_limit_lock=threading.Lock(),
+ settings={"per_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
+ )
+ assert calls == [], "no thin-retry fetch may start once cancelled"
+
+
+def test_inline_retry_skipped_after_budget_expiry(monkeypatch):
+ monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 0.05)
+ retrieve_calls: list[str] = []
+ sleep_calls: list[float] = []
+ gate = threading.Event()
+ def fake_retrieve(**kwargs):
+ retrieve_calls.append(kwargs.get("source"))
+ if kwargs.get("source") == "reddit":
+ gate.wait(0.6)
+ return [], {}
+ raise http.HTTPError("Service unavailable", status_code=503)
+ monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
+ monkeypatch.setattr(time, "sleep", lambda s: sleep_calls.append(s))
+ report = pipeline.run(
+ topic="timeout probe",
+ config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
+ depth="quick",
+ requested_sources=["reddit", "x"],
+ mock=True,
+ )
+ assert retrieve_calls.count("x") == 1, "a timed-out budget must not buy a retry"
+ assert sleep_calls == []
+ assert report is not None
+
+
+def test_cancel_set_on_drain_failure(monkeypatch):
+ seen: dict = {}
+ def fake_run(**kwargs):
+ seen["cancel"] = kwargs["config"].get("_enrich_cancel")
+ return mock.Mock()
+ monkeypatch.setattr(pipeline, "run", fake_run)
+ orig_get = queue.Queue.get
+ first = {"done": False}
+ def flaky_get(self, *a, **k):
+ if not first["done"]:
+ first["done"] = True
+ raise RuntimeError("drain boom")
+ return orig_get(self, *a, **k)
+ monkeypatch.setattr(queue.Queue, "get", flaky_get)
+ nominations = [pipeline.Nomination(name="t", seed_score=1.0)]
+ with pytest.raises(RuntimeError, match="drain boom"):
+ pipeline.enrich_nominations(nominations, config={}, budget_seconds=5)
+ assert seen["cancel"] is not None and seen["cancel"].is_set()
+
+
+# Hung-lane regressions: the worker blocks far past the budget, so a caller
+# that still joins it on executor exit fails the elapsed bound.
+HANG_SECONDS = 5.0
+RETURN_BOUND_SECONDS = 1.5
+
+
+def test_nominate_does_not_join_hung_lane(monkeypatch):
+ monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
+ release = threading.Event()
+ def hung(*a, **k):
+ release.wait(HANG_SECONDS)
+ return [], None
+ monkeypatch.setattr(pipeline, "_fetch_discovery_source", hung)
+ plan = mock.Mock()
+ plan.sources = ["reddit"]
+ plan.domain = "topic"
+ start = time.monotonic()
+ try:
+ bundle = pipeline.nominate_candidates(
+ plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, lookback_days=30,
+ )
+ elapsed = time.monotonic() - start
+ finally:
+ release.set()
+ assert elapsed < RETURN_BOUND_SECONDS, f"nominate joined the hung lane ({elapsed:.2f}s)"
+ assert bundle.source_status["reddit"].state == health.TIMEOUT
+
+
+def test_nominate_drops_receipts_from_timed_out_x(monkeypatch):
+ monkeypatch.setattr(pipeline, "DISCOVERY_FUTURE_TIMEOUT_SECONDS", 0.05)
+ release = threading.Event()
+ def x_straggler(source, plan, **kwargs):
+ kwargs["warnings"].append("X: straggler receipt")
+ release.wait(HANG_SECONDS)
+ return [], None
+ monkeypatch.setattr(pipeline, "_fetch_discovery_source", x_straggler)
+ plan = mock.Mock()
+ plan.sources = ["x"]
+ plan.domain = "topic"
+ try:
+ bundle = pipeline.nominate_candidates(
+ plan, from_date="2026-08-01", to_date="2026-08-31",
+ depth="quick", mock=False, config={}, lookback_days=30,
+ )
+ finally:
+ release.set()
+ assert bundle.source_status["x"].state == health.TIMEOUT
+ assert "x_partial_coverage" not in bundle.artifacts
+
+
+def test_run_does_not_join_hung_stream(monkeypatch):
+ monkeypatch.setattr(pipeline, "STREAM_FUTURE_TIMEOUT_SECONDS", 0.2)
+ release = threading.Event()
+ def fake_retrieve(**kwargs):
+ if kwargs.get("source") == "reddit":
+ release.wait(HANG_SECONDS)
+ return [], {}
+ monkeypatch.setattr(pipeline, "_retrieve_stream", fake_retrieve)
+ start = time.monotonic()
+ try:
+ report = pipeline.run(
+ topic="timeout probe",
+ config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
+ depth="quick",
+ requested_sources=["reddit", "x"],
+ mock=True,
+ )
+ elapsed = time.monotonic() - start
+ finally:
+ release.set()
+ assert elapsed < RETURN_BOUND_SECONDS + 1.0, f"run() joined the hung stream ({elapsed:.2f}s)"
+ assert report.source_status["reddit"].state == health.TIMEOUT
+
+
+def test_thin_retry_does_not_join_hung_retry(monkeypatch):
+ monkeypatch.setattr(pipeline, "THIN_RETRY_FUTURE_TIMEOUT_SECONDS", 0.05)
+ release = threading.Event()
+ def hung(**kwargs):
+ release.wait(HANG_SECONDS)
+ return [], {}
+ monkeypatch.setattr(pipeline, "_retrieve_stream", hung)
+ bundle = schema.RetrievalBundle()
+ plan = mock.Mock()
+ plan.subqueries = [schema.SubQuery(
+ label="primary", search_query="Kanye West",
+ ranking_query="Kanye West", sources=["reddit"], weight=1.0,
+ )]
+ plan.freshness_mode = "breaking"
+ start = time.monotonic()
+ try:
+ pipeline._retry_thin_sources(
+ topic="Kanye West", bundle=bundle, plan=plan,
+ config={}, depth="default",
+ date_range=("2026-08-01", "2026-08-31"), runtime=mock.Mock(),
+ mock=False, rate_limited_sources=set(),
+ rate_limit_lock=threading.Lock(),
+ settings={"per_stream_limit": 6, "pool_limit": 15, "rerank_limit": 12},
+ )
+ elapsed = time.monotonic() - start
+ finally:
+ release.set()
+ assert elapsed < RETURN_BOUND_SECONDS, f"thin retry joined the hung lane ({elapsed:.2f}s)"
+ assert bundle.source_status["reddit"].state == health.TIMEOUT
+
+
+def _interstitial():
+ from lib.subproc import SubprocResult
+ return SubprocResult(returncode=0, stdout="<!DOCTYPE html><html>blocked</html>", stderr="")
+
+
+def test_bird_decode_retry_skipped_when_delay_exceeds_budget(monkeypatch):
+ from lib import bird_x
+ timeouts, sleeps = [], []
+ monkeypatch.setattr(
+ bird_x, "_invoke_bird_subprocess",
+ lambda q, c, timeout: (timeouts.append(timeout), (_interstitial(), None))[1],
+ )
+ monkeypatch.setattr(bird_x.time, "sleep", lambda s: sleeps.append(s))
+ response = bird_x._run_bird_search(
+ "q", count=10, timeout=60,
+ deadline=time.monotonic() + bird_x.JSON_DECODE_RETRY_DELAY - 2,
+ )
+ assert timeouts == [60] and sleeps == [], "no retry may start without budget for it"
+ assert "budget exhausted" in response["error"]
+ assert bird_x.classify_run_failure(response["error"]) == health.SCHEMA_DRIFT
+
+
+def test_bird_decode_retry_reclamps_timeout_to_remaining_budget(monkeypatch):
+ from lib import bird_x
+ timeouts = []
+ monkeypatch.setattr(
+ bird_x, "_invoke_bird_subprocess",
+ lambda q, c, timeout: (timeouts.append(timeout), (_interstitial(), None))[1],
+ )
+ monkeypatch.setattr(bird_x.time, "sleep", lambda s: None)
+ bird_x._run_bird_search("q", count=10, timeout=60, deadline=time.monotonic() + 30)
+ assert len(timeouts) == 2
+ assert timeouts[0] == 60 and timeouts[1] <= 30, f"retry must fit the budget: {timeouts}"
+
+
+def test_bird_budget_stop_keeps_clean_empty_outcome(monkeypatch):
+ from lib import bird_x
+ deadline = time.monotonic() + 30
+ calls = []
+ def fake_run(query, count, timeout, deadline=None):
+ calls.append(query)
+ monkeypatch.setattr(bird_x.time, "monotonic", lambda: deadline + 1)
+ return {"items": []}
+ monkeypatch.setattr(bird_x, "_run_bird_search", fake_run)
+ response = bird_x.search_x(
+ "multi word agent topic", "2026-08-01", "2026-08-31", deadline=deadline,
+ )
+ assert len(calls) == 1, "zero-result retries must not start past the deadline"
+ assert response == {
+ "items": [],
+ "warning": "Partial coverage: optional zero-result retries skipped because the search budget was exhausted.",
+ }, f"clean no-results must carry a coverage warning without an error: {response}"
+
+
[email protected]("entrypoint", ["research", "discovery"])
[email protected]("outcome", ["budget-stop", "complete", "first-failure"])
+def test_bird_budget_warning_reaches_report(monkeypatch, entrypoint, outcome):
+ topic = f"Widget compiler development {uuid4().hex}"
+ now = [1000.0]
+ calls = []
+ config = {
+ "LAST30DAYS_X_BACKEND": "bird", "AUTH_TOKEN": "dummy", "CT0": "dummy",
+ "_research_deadline": 1005.0,
+ }
+ plan = schema.QueryPlan(
+ raw_topic=topic, intent="opinion", freshness_mode="balanced_recent",
+ cluster_mode="debate", source_weights={"x": 1.0},
+ subqueries=[schema.SubQuery(
+ label="primary", search_query=topic, ranking_query=topic, sources=["x"],
+ )],
+ )
+ runtime = schema.ProviderRuntime(
+ reasoning_provider="native", planner_model="", rerank_model="",
+ x_search_backend="bird",
+ )
+
+ def bird_search(query, count, timeout, deadline=None, **kwargs):
+ calls.append((query, timeout, deadline))
+ if outcome != "complete":
+ now[0] = deadline - 0.5
+ if outcome == "first-failure":
+ return {"items": [], "error": "Invalid JSON response (anti-bot interstitial)"}
+ return {"items": []}
+
+ monkeypatch.setattr(pipeline.providers, "resolve_runtime", lambda *a: (runtime, None))
+ monkeypatch.setattr(pipeline, "available_sources", lambda *a, **k: ["x"])
+ monkeypatch.setattr(pipeline.env, "_x_backend_available", lambda backend, *a: backend == "bird")
+ monkeypatch.setattr(pipeline.planner, "plan_query", lambda **k: plan)
+ monkeypatch.setattr(pipeline.bird_x, "_run_bird_search", bird_search)
+ monkeypatch.setattr(time, "monotonic", lambda: now[0])
+ assert pipeline.env.x_backend_chain(config) == ["bird"]
+
+ if entrypoint == "discovery":
+ report = pipeline.run_discover(
+ domain=topic, config=config, depth="quick", requested_sources=["x"],
+ )
+ compact = render.render_discovery(report)
+ assert report.topics == []
+ else:
+ report = pipeline.run(
+ topic=topic, config=config, depth="quick", requested_sources=["x"],
+ internal_subrun=True,
+ )
+ compact = render.render_compact(report)
+ assert report.items_by_source.get("x", []) == []
+ if outcome == "first-failure":
+ assert "Invalid JSON response" in report.errors_by_source["x"]
+ else:
+ assert report.errors_by_source == {}
+
+ receipts = [warning for warning in report.warnings if "search budget" in warning]
+ if outcome == "budget-stop":
+ assert len(calls) == 1
+ assert calls[0][1:] == (5, 1005.0)
+ assert report.source_status["x"].state == schema.NO_RESULTS
+ assert receipts == [
+ "X: bird Partial coverage: optional zero-result retries skipped because the search budget was exhausted."
+ ]
+ assert receipts[0] in compact
+ elif outcome == "complete":
+ assert len(calls) > 1
+ assert report.source_status["x"].state == schema.NO_RESULTS
+ assert receipts == []
+ assert "search budget" not in compact
+ else:
+ assert len(calls) == 1
+ assert report.source_status["x"].state == health.SCHEMA_DRIFT
+ assert "Invalid JSON response" in report.source_status["x"].detail
+ assert receipts == []