Skip to content

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

feat(pipeline): typed per-run source outcomes with doctor-aligned failure states (#797)

Matt Van Horn021bdbf60e12
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 6cd49b3a..2668c788 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -355,6 +355,16 @@ Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json
Web search has **no** env pin — pin it per-run with `--web-backend=<name>` only (see [Web search backend priority](#web-search-backend-priority)).
+### Strict exit for degraded runs
+
+By default a research run exits `0` even when a source failed mid-run (rate-limited, auth-failed, unreachable, timeout, schema-drift) — the report still renders, with the failure annotated in the per-source footer and a partial-coverage warning. Wrappers that need to distinguish degraded coverage from success (cron briefs, CI, downstream agents) can opt in:
+
+| Var | Effect |
+| --- | --- |
+| `LAST30DAYS_STRICT_EXIT` | Truthy (`1`/`true`/`yes`/`on`): the engine exits `3` when any source outcome is neither `ok`, `no-results`, nor `skipped-unconfigured`. A one-line `strict-exit: degraded sources: ...` note goes to stderr. Default (unset): exit `0`, unchanged behavior. |
+
+Exit codes with the flag on: `0` clean run, `3` completed-but-degraded (report was produced), non-zero others unchanged (hard failures). Same hybrid pattern as `LAST30DAYS_DEBUG` — works shell-exported or in `.env`.
+
---
## Trend monitoring (`--store` + watchlist + briefings)
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index a8883add..85adb1de 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -157,6 +157,8 @@ These LAWs dominate every other rule in this file. If you find yourself about to
**LAW 6 - NO RAW RANKED EVIDENCE CLUSTERS IN BODY.** The engine's `## Ranked Evidence Clusters`, `## Stats`, and `## Source Coverage` blocks are bounded inside `<!-- EVIDENCE FOR SYNTHESIS -->` / `<!-- END EVIDENCE FOR SYNTHESIS -->` comments in the `--emit compact` / `--emit md` stdout. They are raw evidence for YOU to read, not output to emit. Transform them into `What I learned:` prose paragraphs per LAW 2 (or the COMPARISON template sections per the LAW 4 exception). If your response contains the literal string `### 1.` followed by a score tuple like `(score N, M items, sources: ...)`, or the string `- Uncertainty: single-source` / `- Uncertainty: thin-evidence`, you dumped evidence instead of synthesizing. STOP and regenerate.
+**Per-run source outcomes (doctor-aligned):** Read `## Partial Coverage` and `Report.source_status` before synthesizing. `no-results` means the source completed cleanly with zero matches. `partial`, `rate-limited`, `auth-failed`, `unreachable`, `timeout`, `schema-drift`, `skipped-unconfigured`, and `error` mean the run did not establish that the source was quiet. Never write "nothing on X/Reddit/YouTube" for those states; qualify the conclusion as partial coverage and rely only on evidence that was actually returned. The engine footer carries the user-visible outcome and `doctor` pointer, so do not invent a repair prescription in prose. `doctor` predicts configuration health before a run; `source_status` reports what happened during this run.
+
**Observed LAW 6 violation (2026-04-19, Hermes Agent Use Cases disaster):** two consecutive `/last30days Hermes Agent (Actual) Use Cases` runs returned the raw `## Ranked Evidence Clusters` block verbatim as user output, with 8 cluster entries carrying `(score N, M items, sources: ...)` tuples and `- Uncertainty: single-source` lines. Root cause: the prior canonical-boundary text said "Pass through the lines ABOVE this boundary verbatim," which the model scoped broadly to include the scratchpad. The current boundary text and this LAW 6 scope pass-through to the PASS-THROUGH FOOTER block only. A third run on the same topic framed as "Hermes Workflows" produced the correct `What I learned:` prose synthesis, which is the shape every run must produce.
**Worked example (LAW 6 transformation).** Evidence block you read:
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 64b6021d..1f6f7b97 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -777,6 +777,40 @@ def _load_last_report_cache(
return None
+_STRICT_EXIT_OK_STATES = {"ok", "no-results", "skipped-unconfigured"}
+
+
+def _strict_exit_code(
+ report: schema.Report,
+ entity_reports: list[tuple[str, schema.Report]] | None,
+ config: dict[str, object],
+) -> int:
+ """Opt-in machine-detectable degraded-run signal (issue #384).
+
+ When LAST30DAYS_STRICT_EXIT is truthy, a run whose report carries any
+ source outcome that is neither clean nor a plain no-results exits 3 so
+ cron/CI wrappers can distinguish degraded coverage from success. Default
+ behavior (exit 0, warning rendered in the report footer) is unchanged.
+ """
+ raw = str(config.get("LAST30DAYS_STRICT_EXIT") or "").strip().lower()
+ if raw not in {"1", "true", "yes", "on"}:
+ return 0
+ reports = [report] + [rep for _, rep in (entity_reports or [])]
+ degraded = sorted({
+ name
+ for rep in reports
+ for name, outcome in (rep.source_status or {}).items()
+ if outcome.state not in _STRICT_EXIT_OK_STATES
+ })
+ if not degraded:
+ return 0
+ sys.stderr.write(
+ f"[last30days] strict-exit: degraded sources: {', '.join(degraded)}\n"
+ )
+ sys.stderr.flush()
+ return 3
+
+
def _render_save_and_print(
args: argparse.Namespace,
report: schema.Report,
@@ -873,7 +907,7 @@ def _render_save_and_print(
sys.stderr.write(f"[last30days] HTML publish failed: {exc}\n")
sys.stderr.flush()
print(rendered)
- return 0
+ return _strict_exit_code(report, entity_reports, config)
def _propagate_config_to_environ(config: dict[str, object]) -> None:
diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.py
index b54644cd..200a0434 100644
--- a/skills/last30days/scripts/lib/bird_x.py
+++ b/skills/last30days/scripts/lib/bird_x.py
@@ -12,7 +12,7 @@ import sys
import time
from pathlib import Path
-from . import env, http, log, subproc
+from . import env, health, http, log, subproc
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
@@ -87,6 +87,19 @@ def _log(msg: str):
log.source_log("Bird", msg, tty_only=False)
+def classify_run_failure(detail: str) -> str:
+ """Map Bird's subprocess-only failure shapes to run outcome states."""
+ text = detail.lower()
+ if any(marker in text for marker in ("interstitial", "non-json", "invalid json")):
+ return health.SCHEMA_DRIFT
+ if any(
+ marker in text
+ for marker in ("cookie expired", "expired cookie", "unauthorized", "forbidden", "login required")
+ ):
+ return health.AUTH_FAILED
+ return http.classify_failure(message=detail)
+
+
def _extract_core_subject(topic: str) -> str:
"""Extract core subject from verbose query for X search.
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 09b23a12..0298d75a 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -466,6 +466,9 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('LAST30DAYS_DOCTOR_TTL', None),
('LAST30DAYS_REDDIT_SC_MIN_ITEMS', None),
('LAST30DAYS_STORE', None),
+ # Opt-in strict exit: truthy -> CLI exits 3 when any source outcome is
+ # degraded (neither ok, no-results, nor skipped-unconfigured). #384.
+ ('LAST30DAYS_STRICT_EXIT', None),
('LAST30DAYS_MEMORY_DIR', None),
('OPENAI_MODEL_PIN', None),
('XAI_MODEL_PIN', None),
diff --git a/skills/last30days/scripts/lib/github.py b/skills/last30days/scripts/lib/github.py
index e838e8cd..8ec91b0b 100644
--- a/skills/last30days/scripts/lib/github.py
+++ b/skills/last30days/scripts/lib/github.py
@@ -81,8 +81,18 @@ def _fetch_json(
url: str,
token: Optional[str] = None,
timeout: int = 15,
+ failure_out: Optional[List[str]] = None,
) -> Optional[Dict[str, Any]]:
- """Fetch JSON from GitHub API. Returns None on failure."""
+ """Fetch JSON from GitHub API. Returns None on failure.
+
+ When ``failure_out`` is provided, a short human-readable reason is
+ appended for every failure branch so callers can distinguish transport
+ failures from genuinely empty results (issue #384).
+ """
+
+ def _note(msg: str) -> None:
+ if failure_out is not None:
+ failure_out.append(msg)
headers = {
"User-Agent": USER_AGENT,
"Accept": "application/vnd.github+json",
@@ -98,17 +108,22 @@ def _fetch_json(
except urllib.error.HTTPError as e:
if e.code == 403:
_log(f"403 rate limited or forbidden: {url}")
+ _note("HTTP 403: rate limited or forbidden")
return None
if e.code == 422:
_log(f"422 unprocessable: {url}")
+ _note("HTTP 422: unprocessable query")
return None
_log(f"HTTP {e.code}: {e.reason}")
+ _note(f"HTTP {e.code}: {e.reason}")
return None
except (urllib.error.URLError, OSError, TimeoutError) as e:
_log(f"Network error: {e}")
+ _note(f"network error: {e}")
return None
except json.JSONDecodeError as e:
_log(f"JSON decode error: {e}")
+ _note(f"invalid JSON: {e}")
return None
@@ -197,11 +212,16 @@ def search_github(
}
url = f"{SEARCH_URL}?{urllib.parse.urlencode(params)}"
- data = _fetch_json(url, token=resolved_token, timeout=30)
+ fetch_failures: List[str] = []
+ data = _fetch_json(url, token=resolved_token, timeout=30, failure_out=fetch_failures)
if not data:
envelope = {"items": [], "context": {"core": core, "from_date": from_date,
"to_date": to_date, "count": count}}
- if not authed:
+ if authed and fetch_failures:
+ # Authenticated transport failures must not be laundered into a
+ # clean no-results outcome (issue #384).
+ envelope["error"] = f"GitHub API request failed: {fetch_failures[-1]}"
+ elif not authed:
# Could be the anon rate limit (403) or an unprocessable query (422)
# -- _fetch_json maps both to None. Don't over-claim which; suggest a
# token since that fixes the common (rate-limit) case.
diff --git a/skills/last30days/scripts/lib/health.py b/skills/last30days/scripts/lib/health.py
index de6f63b6..b623e8b0 100644
--- a/skills/last30days/scripts/lib/health.py
+++ b/skills/last30days/scripts/lib/health.py
@@ -28,6 +28,16 @@ BROKEN = "broken" # present but won't execute (stale shim, bad perms)
TIMEOUT = "timeout" # exceeded the probe deadline
ERROR = "error" # ran and failed for another reason
+# Per-run outcomes. Doctor does not emit these: it predicts source readiness
+# before retrieval, while Report.source_status records what happened in one run.
+NO_RESULTS = "no-results"
+PARTIAL = "partial"
+RATE_LIMITED = "rate-limited"
+AUTH_FAILED = "auth-failed"
+UNREACHABLE = "unreachable"
+SCHEMA_DRIFT = "schema-drift"
+SKIPPED_UNCONFIGURED = "skipped-unconfigured"
+
@dataclass
class SourceHealth:
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index 201d7e6e..9cb4e3f9 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -8,9 +8,12 @@ import threading
import time
import urllib.error
import urllib.request
+from contextlib import contextmanager
+from contextvars import ContextVar, copy_context
from typing import Any, Dict, Optional, Union
from urllib.parse import urlencode
+from . import health
from . import log as _log
DEFAULT_TIMEOUT = 30
@@ -31,6 +34,15 @@ RETRY_DELAY = 2.0
MIN_DNS_RETRIES = 3
USER_AGENT = "last30days-skill/3.0 (Assistant Skill)"
+_failure_sink: ContextVar[Optional[list["HTTPError"]]] = ContextVar(
+ "last30days_http_failure_sink",
+ default=None,
+)
+_expected_miss_statuses: ContextVar[frozenset[int]] = ContextVar(
+ "last30days_http_expected_miss_statuses",
+ default=frozenset(),
+)
+
def _is_dns_failure(err: urllib.error.URLError) -> bool:
"""Return True if a URLError was caused by DNS resolution (gaierror)."""
@@ -39,10 +51,121 @@ def _is_dns_failure(err: urllib.error.URLError) -> bool:
class HTTPError(Exception):
"""HTTP request error with status code."""
- def __init__(self, message: str, status_code: Optional[int] = None, body: Optional[str] = None):
+ def __init__(
+ self,
+ message: str,
+ status_code: Optional[int] = None,
+ body: Optional[str] = None,
+ outcome_state: Optional[str] = None,
+ ):
super().__init__(message)
self.status_code = status_code
self.body = body
+ self.outcome_state = outcome_state or classify_failure(
+ status_code=status_code,
+ message=message,
+ )
+
+
+@contextmanager
+def capture_failures():
+ """Capture terminal request failures in the current retrieval context.
+
+ Source modules historically catch ``HTTPError`` and return an empty result.
+ The context-local sink lets the pipeline retain that failure without shared
+ mutable state across its worker threads.
+ """
+ failures: list[HTTPError] = []
+ token = _failure_sink.set(failures)
+ try:
+ yield failures
+ finally:
+ _failure_sink.reset(token)
+
+
+@contextmanager
+def expected_misses(*status_codes: int):
+ """Exclude adapter-declared probe misses from captured run failures."""
+ token = _expected_miss_statuses.set(
+ _expected_miss_statuses.get().union(status_codes)
+ )
+ try:
+ yield
+ finally:
+ _expected_miss_statuses.reset(token)
+
+
+def submit_with_context(executor, func, /, *args, **kwargs):
+ """Submit a worker with the caller's failure-capture context."""
+ context = copy_context()
+ return executor.submit(context.run, func, *args, **kwargs)
+
+
+def _record_failure(error: HTTPError) -> None:
+ if error.status_code in _expected_miss_statuses.get():
+ return
+ sink = _failure_sink.get()
+ if sink is not None:
+ sink.append(error)
+
+
+def _raise(error: HTTPError) -> None:
+ _record_failure(error)
+ raise error
+
+
+def classify_failure(*, status_code: Optional[int] = None, message: str = "") -> str:
+ """Map a request failure to the doctor-aligned per-run vocabulary."""
+ text = message.lower()
+ if status_code == 429 or any(
+ marker in text for marker in ("http 429", "status 429", "rate limit", "too many requests")
+ ):
+ return health.RATE_LIMITED
+ if status_code in (401, 402, 403) or any(
+ marker in text
+ for marker in (
+ "http 401",
+ "http 402",
+ "http 403",
+ "status 401",
+ "status 402",
+ "status 403",
+ "unauthorized",
+ "forbidden",
+ "authentication failed",
+ "expired token",
+ )
+ ):
+ return health.AUTH_FAILED
+ if status_code == 408 or "timed out" in text or "timeout" in text:
+ return health.TIMEOUT
+ if any(
+ marker in text
+ for marker in (
+ "invalid json",
+ "json decode",
+ "schema",
+ "interstitial",
+ "non-json",
+ )
+ ):
+ return health.SCHEMA_DRIFT
+ if any(
+ marker in text
+ for marker in (
+ "url error",
+ "connection error",
+ "connection refused",
+ "connection reset",
+ "name or service not known",
+ "temporary failure in name resolution",
+ "nodename nor servname",
+ "dns",
+ "network is unreachable",
+ )
+ ):
+ return health.UNREACHABLE
+ return health.ERROR
def request(
@@ -125,13 +248,13 @@ def request(
# Don't retry client errors (4xx) except rate limits
if 400 <= e.code < 500 and e.code != 429:
- raise last_error
+ _raise(last_error)
# Cap 429 retries separately to avoid wasting latency
if e.code == 429:
rate_limit_count += 1
if rate_limit_count >= max_429_retries:
- raise last_error
+ _raise(last_error)
# HTTP errors respect the caller's original `retries`; only DNS
# failures get the widened `effective_retries` budget.
@@ -157,7 +280,15 @@ def request(
break
except urllib.error.URLError as e:
log(f"URL Error: {e.reason}")
- last_error = HTTPError(f"URL Error: {e.reason}")
+ reason = getattr(e, "reason", None)
+ # urllib commonly wraps socket.timeout (an alias of TimeoutError
+ # since 3.10) in URLError; classify those as timeouts, not
+ # unreachable hosts, so the recovery guidance is right.
+ wrapped_timeout = isinstance(reason, TimeoutError) or "timed out" in str(reason).lower()
+ last_error = HTTPError(
+ f"URL Error: {e.reason}",
+ outcome_state=health.TIMEOUT if wrapped_timeout else health.UNREACHABLE,
+ )
if _is_dns_failure(e):
# DNS resolution failures are transient; expand the retry budget
# to MIN_DNS_RETRIES if the caller passed fewer, and use
@@ -189,12 +320,19 @@ def request(
break
except json.JSONDecodeError as e:
log(f"JSON decode error: {e}")
- last_error = HTTPError(f"Invalid JSON response: {e}")
- raise last_error
+ last_error = HTTPError(
+ f"Invalid JSON response: {e}",
+ outcome_state=health.SCHEMA_DRIFT,
+ )
+ _raise(last_error)
except (OSError, TimeoutError, ConnectionResetError) as e:
# Handle socket-level errors (connection reset, timeout, etc.)
log(f"Connection error: {type(e).__name__}: {e}")
- last_error = HTTPError(f"Connection error: {type(e).__name__}: {e}")
+ state = health.TIMEOUT if isinstance(e, TimeoutError) else health.UNREACHABLE
+ last_error = HTTPError(
+ f"Connection error: {type(e).__name__}: {e}",
+ outcome_state=state,
+ )
if attempt < retries - 1:
# Socket errors respect the caller's original retry budget.
time.sleep(RETRY_DELAY * (attempt + 1))
@@ -205,8 +343,9 @@ def request(
attempt += 1
if last_error:
- raise last_error
- raise HTTPError("Request failed with no error details")
+ _raise(last_error)
+ error = HTTPError("Request failed with no error details")
+ _raise(error)
def get(url: str, headers: Optional[Dict[str, str]] = None, **kwargs) -> Dict[str, Any]:
diff --git a/skills/last30days/scripts/lib/instagram.py b/skills/last30days/scripts/lib/instagram.py
index cb09d888..8292df27 100644
--- a/skills/last30days/scripts/lib/instagram.py
+++ b/skills/last30days/scripts/lib/instagram.py
@@ -568,7 +568,7 @@ def enrich_with_comments(
enriched_count = 0
with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
- futures = {executor.submit(_enrich_one, item): item for item in top_items}
+ futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
for future in as_completed(futures):
if future.result():
enriched_count += 1
diff --git a/skills/last30days/scripts/lib/jobs.py b/skills/last30days/scripts/lib/jobs.py
index bbe9e465..58419f90 100644
--- a/skills/last30days/scripts/lib/jobs.py
+++ b/skills/last30days/scripts/lib/jobs.py
@@ -141,7 +141,8 @@ def _resolve_careers_page(
candidates.extend([f"https://{host}/careers", f"https://{host}/jobs"])
for url in candidates:
- html = http.get_text(url, accept="text/html", retries=1)
+ with http.expected_misses(403, 404):
+ html = http.get_text(url, accept="text/html", retries=1)
if html and _looks_like_careers_html(html):
return html, url
@@ -209,7 +210,8 @@ def _probe_ats(company: str) -> tuple[str | None, str | None, list[str]]:
for provider in (ATS_PROVIDER_GREENHOUSE, ATS_PROVIDER_ASHBY, ATS_PROVIDER_LEVER):
attempts.append(f"probe:{provider}:{slug}")
try:
- items = _fetch_ats(provider, slug)
+ with http.expected_misses(400, 401, 403, 404):
+ items = _fetch_ats(provider, slug)
except http.HTTPError as exc:
if exc.status_code in {400, 401, 403, 404}:
continue
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index 7b29ab61..557d20b1 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -23,7 +23,9 @@ from . import (
github,
grounding,
hackernews,
+ health,
hiring_signals,
+ http,
instagram,
jobs,
linkedin,
@@ -459,6 +461,14 @@ def run(
print("[Planner] (no subqueries in plan)", file=sys.stderr)
bundle = schema.RetrievalBundle(artifacts={"grounding": []})
+ for source in (requested_sources or []):
+ if source not in available:
+ bundle.record_failure(
+ source,
+ schema.SKIPPED_UNCONFIGURED,
+ "Source was requested but is not configured for this run.",
+ attempted=False,
+ )
# Expose plan_source to the renderer so render_compact can emit the
# DEGRADED RUN banner when a named-entity topic was invoked bare
# (source=deterministic AND no pre-research flags). LAW 7 backstop.
@@ -474,6 +484,7 @@ def run(
# Project mode takes priority over person mode
if github_repos and "github" in available:
+ bundle.mark_attempted("github")
try:
project_items = github.search_github_project(
github_repos, from_date, to_date,
@@ -491,9 +502,12 @@ def run(
_github_enriched_repos = {r.lower() for r in github_repos}
except Exception as exc:
bundle.errors_by_source["github"] = f"Project-mode failed: {exc}"
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure("github", state, str(exc), attempted=attempted)
_github_person_done = False
if github_user and "github" in available and not _github_custom_done:
+ bundle.mark_attempted("github")
try:
person_items = github.search_github_person(
github_user, from_date, to_date,
@@ -511,6 +525,8 @@ def run(
_github_person_done = True
except Exception as exc:
bundle.errors_by_source["github"] = f"Person-mode failed: {exc}"
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure("github", state, str(exc), attempted=attempted)
# Trustpilot session warm-up happens inside search_trustpilot at the
# first (capped, single) fetch -- lazily, so it never delays the other
@@ -547,6 +563,7 @@ def run(
if current >= cap:
continue
source_fetch_count[source] = current + 1
+ bundle.mark_attempted(source)
futures[
executor.submit(
_retrieve_stream,
@@ -581,6 +598,8 @@ def run(
with rate_limit_lock:
rate_limited_sources.add(source)
bundle.errors_by_source[source] = str(exc)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(source, state, str(exc), attempted=attempted)
continue
# Retry once for transient 5xx errors
if _is_transient_error(exc):
@@ -602,11 +621,26 @@ def run(
trustpilot_domain_is_hint=trustpilot_domain_is_hint,
)
except Exception as retry_exc:
- bundle.errors_by_source[source] = f"{exc} (retried once, still failed: {retry_exc})"
+ detail = f"{exc} (retried once, still failed: {retry_exc})"
+ bundle.errors_by_source[source] = detail
+ state, attempted = _classify_source_failure(retry_exc)
+ bundle.record_failure(source, state, detail, attempted=attempted)
continue
else:
bundle.errors_by_source[source] = str(exc)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(source, state, str(exc), attempted=attempted)
continue
+ outcome_note = None
+ if isinstance(artifact, dict) and artifact.get("_source_outcome"):
+ artifact = dict(artifact)
+ outcome_note = artifact.pop("_source_outcome")
+ bundle.record_failure(
+ source,
+ outcome_note["state"],
+ outcome_note["detail"],
+ attempted=outcome_note.get("attempted", True),
+ )
normalized = _normalize_score_dedupe(
source, raw_items, from_date, to_date,
freshness_mode=plan.freshness_mode,
@@ -680,6 +714,7 @@ def run(
items_by_source = _finalize_items_by_source(
bundle.items_by_source, topic=topic, config=config, depth=depth, mock=mock,
)
+ source_status = _finalize_source_status(bundle.source_status, items_by_source)
candidates = weighted_rrf(bundle.items_by_source_and_query, plan, pool_limit=settings["pool_limit"])
# Normalized set of handles this run resolved for the topic. A candidate
# authored by one of these is first-party and is exempted from the
@@ -729,6 +764,7 @@ def run(
ranked_candidates=ranked_candidates,
items_by_source=items_by_source,
errors_by_source=bundle.errors_by_source,
+ source_status=source_status,
warnings=warnings,
artifacts=bundle.artifacts,
)
@@ -935,6 +971,178 @@ def _is_rate_limit_error(exc: Exception) -> bool:
return "429" in str(exc)
+class SourceRunError(RuntimeError):
+ """Source-specific failure that survived a module's fallback logic."""
+
+ def __init__(self, message: str, state: schema.RunOutcomeState | None = None):
+ super().__init__(message)
+ self.outcome_state = state or http.classify_failure(message=message)
+
+
+def _classify_source_failure(exc: Exception) -> tuple[schema.RunOutcomeState, bool]:
+ """Classify HTTP, subprocess, and module-specific failures consistently."""
+ detail = str(exc)
+ lowered = detail.lower()
+ if any(marker in lowered for marker in ("not configured", "no api key", "not installed")):
+ return schema.SKIPPED_UNCONFIGURED, False
+ if any(
+ marker in lowered
+ for marker in ("cookie expired", "expired cookie", "login required", "not logged in")
+ ):
+ return schema.AUTH_FAILED, True
+ state = getattr(exc, "outcome_state", None) or http.classify_failure(
+ status_code=getattr(exc, "status_code", None),
+ message=detail,
+ )
+ return state, True
+
+
+def _outcome_artifact(
+ state: schema.RunOutcomeState,
+ detail: str,
+ *,
+ attempted: bool = True,
+) -> dict[str, Any]:
+ return {
+ "_source_outcome": {
+ "state": state,
+ "detail": detail,
+ "attempted": attempted,
+ }
+ }
+
+
+def _result_outcome_artifact(source: str, result: Any) -> dict[str, Any]:
+ """Convert a legacy ``{"error": ...}`` source result into typed status."""
+ if not isinstance(result, dict) or not result.get("error"):
+ return {}
+ detail = str(result["error"])
+ if source == "reddit":
+ state = reddit.classify_run_failure(detail)
+ attempted = True
+ elif source == "youtube":
+ state = youtube_yt.classify_run_failure(detail)
+ attempted = state != schema.SKIPPED_UNCONFIGURED
+ elif source == "x":
+ state = bird_x.classify_run_failure(detail)
+ attempted = True
+ elif source == "truthsocial" and detail == "Truth Social token expired":
+ state = schema.AUTH_FAILED
+ attempted = True
+ elif source == "bluesky" and "network-level block" in detail.lower():
+ state = schema.UNREACHABLE
+ attempted = True
+ else:
+ state, attempted = _classify_source_failure(SourceRunError(detail))
+ return _outcome_artifact(state, detail, attempted=attempted)
+
+
+def _legacy_artifact_outcome(
+ source: str,
+ artifact: Any,
+) -> dict[str, Any] | None:
+ """Map known pre-outcome artifact contracts to a typed outcome note."""
+ if not isinstance(artifact, dict):
+ return None
+ explicit = artifact.get("_source_outcome")
+ if isinstance(explicit, dict):
+ return explicit
+ if source == "perplexity" and artifact.get("error"):
+ error = str(artifact["error"])
+ detail = str(
+ artifact.get("asyncErrorMessage")
+ or artifact.get("message")
+ or error
+ )
+ state = (
+ health.TIMEOUT
+ if error.lower() == "timeout"
+ else http.classify_failure(
+ status_code=artifact.get("statusCode"),
+ message=f"{error}: {detail}",
+ )
+ )
+ return _outcome_artifact(state, detail)["_source_outcome"]
+ if (
+ source == "grounding"
+ and artifact.get("reason") == "keyless-search-unavailable"
+ ):
+ return _outcome_artifact(
+ schema.UNREACHABLE,
+ "Keyless web search unavailable",
+ )["_source_outcome"]
+ return None
+
+
+def _resolve_stream_outcome(
+ source: str,
+ artifact: Any,
+ failures: list[http.HTTPError],
+) -> dict[str, Any] | None:
+ """Choose the most specific artifact or captured HTTP outcome."""
+ artifact_outcome = _legacy_artifact_outcome(source, artifact)
+ if not failures:
+ return artifact_outcome
+ # Pick the most specific failure rather than the last-appended one:
+ # parallel workers append in nondeterministic order, and an auth failure
+ # must not be masked by a later 429 (wrong doctor prescription).
+ _FAILURE_SPECIFICITY = {
+ health.AUTH_FAILED: 0,
+ health.RATE_LIMITED: 1,
+ health.SCHEMA_DRIFT: 2,
+ health.TIMEOUT: 3,
+ health.UNREACHABLE: 4,
+ health.ERROR: 5,
+ }
+ failure = min(
+ failures,
+ key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
+ )
+ captured_outcome = _outcome_artifact(
+ failure.outcome_state,
+ str(failure),
+ )["_source_outcome"]
+ if artifact_outcome is None:
+ return captured_outcome
+ if (
+ artifact_outcome.get("state") == health.ERROR
+ and failure.outcome_state != health.ERROR
+ ):
+ return captured_outcome
+ return artifact_outcome
+
+
+def _finalize_source_status(
+ outcomes: dict[str, schema.SourceOutcome],
+ items_by_source: dict[str, list[schema.SourceItem]],
+) -> dict[str, schema.SourceOutcome]:
+ """Sync outcome counts to the final post-filter evidence set."""
+ finalized: dict[str, schema.SourceOutcome] = {}
+ for source, outcome in outcomes.items():
+ count = len(items_by_source.get(source, []))
+ state = outcome.state
+ detail = outcome.detail
+ fix_hint = outcome.fix_hint
+ if state == schema.NO_RESULTS and count:
+ state = health.OK
+ detail = None
+ fix_hint = None
+ elif state == health.OK and not count:
+ state = schema.NO_RESULTS
+ elif state == schema.PARTIAL and not count:
+ state = http.classify_failure(message=detail or "")
+ finalized[source] = schema.SourceOutcome(
+ source=source,
+ state=state,
+ items_returned=count,
+ attempted=outcome.attempted,
+ detail=detail,
+ at=outcome.at,
+ fix_hint=fix_hint,
+ )
+ return finalized
+
+
def _is_transient_error(exc: Exception) -> bool:
"""Detect 5xx server errors that are worth retrying."""
status = getattr(exc, "status_code", None)
@@ -1072,12 +1280,26 @@ def _run_supplemental_searches(
from_items = _from_lane(handles, FROM_LANE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 FROM-lane search failed: {exc}", file=sys.stderr)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(
+ x_slug,
+ state,
+ f"Phase 2 FROM-lane: {exc}",
+ attempted=attempted,
+ )
if not bundle.items_by_source.get(x_slug):
bundle.errors_by_source[x_slug] = f"Phase 2 FROM-lane: {exc}"
try:
about_items = _about_lane(handles, MENTION_LANE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 ABOUT-lane search failed: {exc}", file=sys.stderr)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(
+ x_slug,
+ state,
+ f"Phase 2 ABOUT-lane: {exc}",
+ attempted=attempted,
+ )
raw_items = from_items + about_items
if raw_items:
@@ -1101,6 +1323,13 @@ def _run_supplemental_searches(
raw_items = _from_lane(related_handles, RELATED_HANDLE_COUNT_PER)
except Exception as exc:
print(f"[Pipeline] Phase 2 related handle search failed: {exc}", file=sys.stderr)
+ state, attempted = _classify_source_failure(exc)
+ bundle.record_failure(
+ x_slug,
+ state,
+ f"Phase 2 related handle search: {exc}",
+ attempted=attempted,
+ )
raw_items = []
if raw_items:
@@ -1189,8 +1418,10 @@ def _retry_thin_sources(
weight=0.3,
)
- def _retry_one_source(source: str) -> tuple[str, list[schema.SourceItem]]:
- raw_items, _artifact = _retrieve_stream(
+ def _retry_one_source(
+ source: str,
+ ) -> tuple[str, list[schema.SourceItem], dict[str, Any] | None]:
+ raw_items, artifact = _retrieve_stream(
topic=topic,
subquery=retry_subquery,
source=source,
@@ -1204,6 +1435,7 @@ def _retry_thin_sources(
web_backend=web_backend,
raw_topic=topic,
)
+ outcome_note = artifact.get("_source_outcome") if isinstance(artifact, dict) else None
normalized = _normalize_score_dedupe(
source,
raw_items,
@@ -1213,8 +1445,8 @@ def _retry_thin_sources(
ranking_query=retry_subquery.ranking_query,
)
if source == "jobs":
- return source, normalized
- return source, normalized[:settings["per_stream_limit"]]
+ return source, normalized, outcome_note
+ return source, normalized[:settings["per_stream_limit"]], outcome_note
retryable = [s for s in thin_sources if s not in rate_limited_sources]
@@ -1224,16 +1456,29 @@ def _retry_thin_sources(
for future in as_completed(futures):
source = futures[future]
try:
- source, normalized = future.result()
+ source, normalized, outcome_note = future.result()
+ if outcome_note:
+ bundle.record_failure(
+ source,
+ outcome_note["state"],
+ outcome_note["detail"],
+ attempted=outcome_note.get("attempted", True),
+ )
existing_urls = {item.url for item in bundle.items_by_source.get(source, []) if item.url}
new_items = [item for item in normalized if item.url not in existing_urls]
if new_items:
- bundle.items_by_source.setdefault(source, []).extend(new_items)
primary_label = plan.subqueries[0].label if plan.subqueries else "primary"
- bundle.items_by_source_and_query.setdefault((primary_label, source), []).extend(new_items)
+ bundle.add_items(primary_label, source, new_items)
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,
+ )
def _fetch_x_backend(backend, subquery, from_date, to_date, depth, config):
@@ -1286,7 +1531,28 @@ def _merge_reddit_items(free: list[dict], sc: list[dict]) -> list[dict]:
return merged
-def _retrieve_stream(
+def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
+ """Run one stream and retain HTTP failures swallowed by source adapters."""
+ try:
+ with http.capture_failures() as failures:
+ items, artifact = _retrieve_stream_impl(*args, **kwargs)
+ except Exception as exc:
+ if failures and not getattr(exc, "outcome_state", None):
+ failure = failures[-1]
+ raise SourceRunError(str(exc), failure.outcome_state) from exc
+ raise
+ outcome_note = _resolve_stream_outcome(
+ str(kwargs.get("source") or ""),
+ artifact,
+ failures,
+ )
+ if outcome_note:
+ artifact = dict(artifact or {})
+ artifact["_source_outcome"] = outcome_note
+ return items, artifact
+
+
+def _retrieve_stream_impl(
*,
topic: str,
subquery: schema.SubQuery,
@@ -1338,6 +1604,7 @@ def _retrieve_stream(
)
if sc_first:
# env.REDDIT_BACKEND_PIN_VAR=scrapecreators: SC primary, public fallback
+ primary_failure: Exception | None = None
try:
result = reddit.search_and_enrich(
reddit_query, from_date, to_date, depth=depth,
@@ -1352,26 +1619,43 @@ def _retrieve_stream(
"using public fallback\n"
)
except Exception as exc:
+ primary_failure = exc
sys.stderr.write(
f"[Reddit] ScrapeCreators primary failed "
f"({type(exc).__name__}: {exc}), using public fallback\n"
)
+ public_failure: Exception | None = None
try:
public_results = reddit_public.search_reddit_public(
reddit_query, from_date, to_date, depth=depth,
subreddits=subreddits,
)
if public_results:
+ if primary_failure is not None:
+ state = reddit.classify_run_failure(str(primary_failure))
+ return public_results, _outcome_artifact(
+ state,
+ f"Reddit primary failed; public fallback returned "
+ f"{len(public_results)} items: {primary_failure}",
+ )
return public_results, {}
sys.stderr.write(
"[Reddit] Public fallback returned no items after "
"ScrapeCreators primary miss\n"
)
except Exception as exc:
+ public_failure = exc
sys.stderr.write(
f"[Reddit] Public fallback also failed "
f"({type(exc).__name__}: {exc})\n"
)
+ failure = public_failure or primary_failure
+ if failure is not None:
+ state = reddit.classify_run_failure(str(failure))
+ raise SourceRunError(
+ f"Reddit primary and fallback produced no results after failure: {failure}",
+ state,
+ )
return [], {}
# Default: public Reddit first (free). ScrapeCreators backfills when the
@@ -1383,18 +1667,21 @@ def _retrieve_stream(
except (TypeError, ValueError):
min_items = 0
public_results: list[dict] = []
+ public_failure: Exception | None = None
try:
public_results = reddit_public.search_reddit_public(
reddit_query, from_date, to_date, depth=depth,
subreddits=subreddits, dedicated_subreddits=dedicated_subreddits,
) or []
except Exception as exc:
+ public_failure = exc
sys.stderr.write(
f"[Reddit] Public search failed ({type(exc).__name__}: {exc})"
)
if not has_sc_key:
sys.stderr.write("\n")
- return [], {}
+ state = reddit.classify_run_failure(str(exc))
+ raise SourceRunError(f"Reddit public search failed: {exc}", state) from exc
sys.stderr.write(", using ScrapeCreators backup\n")
# Enough free results, or no key to backfill with -> done. max(min_items,
# 1) keeps the default (min_items=0) as empty-only AND treats exactly
@@ -1418,8 +1705,20 @@ def _retrieve_stream(
f"[Reddit] ScrapeCreators backup also failed "
f"({type(exc).__name__}: {exc})\n"
)
- return public_results, {}
- return _merge_reddit_items(public_results, sc_items), {}
+ state = reddit.classify_run_failure(str(exc))
+ return public_results, _outcome_artifact(
+ state,
+ f"Reddit backup failed after {len(public_results)} public items: {exc}",
+ )
+ merged = _merge_reddit_items(public_results, sc_items)
+ if public_failure is not None:
+ state = reddit.classify_run_failure(str(public_failure))
+ return merged, _outcome_artifact(
+ state,
+ f"Reddit public search failed; backup returned {len(sc_items)} items: "
+ f"{public_failure}",
+ )
+ return merged, {}
if source == "x":
# One X source, an ordered chain of interchangeable backends. Try the
# primary; fall through to the next only if it returns nothing or errors.
@@ -1437,18 +1736,34 @@ def _retrieve_stream(
if items:
if i > 0:
print(f"[X] primary backend(s) returned nothing; used fallback '{backend}'", file=sys.stderr)
+ if last_error:
+ state = (
+ bird_x.classify_run_failure(last_error)
+ if last_error.startswith("bird:")
+ else http.classify_failure(message=last_error)
+ )
+ return items, _outcome_artifact(
+ state,
+ f"X fallback '{backend}' returned {len(items)} items after {last_error}",
+ )
return items, {}
if err:
last_error = f"{backend}: {err}"
print(f"[X] backend '{backend}' failed ({err}); trying next", file=sys.stderr)
if last_error:
- raise RuntimeError(f"All X backends failed — {last_error}")
+ state = (
+ bird_x.classify_run_failure(last_error)
+ if last_error.startswith("bird:")
+ else http.classify_failure(message=last_error)
+ )
+ raise SourceRunError(f"All X backends failed — {last_error}", state)
return [], {}
if source == "youtube":
# Use raw_topic so expand_youtube_queries() generates diverse variants
# from the original user topic, not the planner's narrowed search_query.
yt_query = raw_topic or subquery.search_query
result = None
+ youtube_failure: str | None = None
# ScrapeCreators key (when present) is the default-on backup tier: it
# powers the per-video transcript fallback, the SC search fallback, and
# comment enrichment. None when no key, which keeps everything keyless.
@@ -1462,13 +1777,22 @@ def _retrieve_stream(
result = youtube_yt.search_and_transcribe(
yt_query, from_date, to_date, depth=depth, token=sc_token,
)
- except Exception:
+ if result.get("error"):
+ youtube_failure = str(result["error"])
+ except Exception as exc:
+ youtube_failure = str(exc)
result = None
# Fall back to SC YouTube search if yt-dlp failed or isn't installed.
if (result is None or not result.get("items")) and sc_token:
- result = youtube_yt.search_youtube_sc(
- yt_query, from_date, to_date, depth=depth, token=sc_token,
- )
+ try:
+ result = youtube_yt.search_youtube_sc(
+ yt_query, from_date, to_date, depth=depth, token=sc_token,
+ )
+ if result.get("error"):
+ youtube_failure = str(result["error"])
+ except Exception as exc:
+ youtube_failure = str(exc)
+ result = None
if result is None:
result = {"items": []}
# Enrich top videos with comments (default-on when a key is present).
@@ -1477,6 +1801,10 @@ def _retrieve_stream(
youtube_yt.enrich_with_comments(
items, token=config.get("SCRAPECREATORS_API_KEY", ""),
)
+ if youtube_failure:
+ state = youtube_yt.classify_run_failure(youtube_failure)
+ attempted = state != schema.SKIPPED_UNCONFIGURED
+ return items, _outcome_artifact(state, youtube_failure, attempted=attempted)
return items, {}
if source == "tiktok":
# Use raw_topic so expand_tiktok_queries() generates diverse variants
@@ -1495,7 +1823,7 @@ def _retrieve_stream(
if items and env.is_tiktok_comments_available(config):
sc_token = config.get("SCRAPECREATORS_API_KEY", "")
tiktok.enrich_with_comments(items, token=sc_token)
- return items, {}
+ return items, _result_outcome_artifact(source, result)
if source == "instagram":
# Use raw_topic so expand_instagram_queries() generates diverse variants
# from the original user topic, not the planner's narrowed search_query.
@@ -1513,7 +1841,7 @@ def _retrieve_stream(
instagram.enrich_with_comments(
items, token=config.get("SCRAPECREATORS_API_KEY", ""),
)
- return items, {}
+ return items, _result_outcome_artifact(source, result)
if source == "linkedin":
token = config.get("SCRAPECREATORS_API_KEY", "")
result = linkedin.search_linkedin(
@@ -1531,33 +1859,45 @@ def _retrieve_stream(
items += linkedin.enrich_articles(
items, raw_topic or topic, token, from_date=from_date, to_date=to_date
)
- return items, {}
+ return items, _result_outcome_artifact(source, result)
if source == "hackernews":
result = hackernews.search_hackernews(subquery.search_query, from_date, to_date, depth=depth)
- return hackernews.parse_hackernews_response(result, query=subquery.search_query), {}
+ return (
+ hackernews.parse_hackernews_response(result, query=subquery.search_query),
+ _result_outcome_artifact(source, result),
+ )
if source == "stocktwits":
# Pass raw_topic so symbol detection sees the full topic, not the
# narrowed per-subquery search_query (same rationale as reddit).
result = stocktwits.search_stocktwits(
raw_topic or topic or subquery.search_query, from_date, to_date, depth=depth)
- return stocktwits.parse_stocktwits_response(result, query=subquery.search_query), {}
+ return (
+ stocktwits.parse_stocktwits_response(result, query=subquery.search_query),
+ _result_outcome_artifact(source, result),
+ )
if source == "digg":
result = digg.search_digg(subquery.search_query, from_date, to_date, depth=depth)
items = digg.parse_digg_response(result, query=subquery.search_query)
# Enrichment with attached X posts is deferred to
# _finalize_items_by_source so it runs on the items that actually
# survive dedupe rather than on top-K of the raw fanout.
- return items, {}
+ return items, _result_outcome_artifact(source, result)
if source == "arxiv":
result = arxiv.search_arxiv(subquery.search_query, from_date, to_date, depth=depth)
# Relevance keys off the stable research topic, not the per-subquery
# search_query, so off-topic narrowing does not let weak matches through.
relevance_topic = raw_topic or topic or subquery.search_query
- return arxiv.parse_arxiv_response(result, query=relevance_topic), {}
+ return (
+ arxiv.parse_arxiv_response(result, query=relevance_topic),
+ _result_outcome_artifact(source, result),
+ )
if source == "techmeme":
result = techmeme.search_techmeme(subquery.search_query, from_date, to_date, depth=depth)
relevance_topic = raw_topic or topic or subquery.search_query
- return techmeme.parse_techmeme_response(result, query=relevance_topic), {}
+ return (
+ techmeme.parse_techmeme_response(result, query=relevance_topic),
+ _result_outcome_artifact(source, result),
+ )
if source == "trustpilot":
# Brand-shape gate keys off the stable research topic, not the narrowed
# per-subquery search_query, so the company is detected consistently.
@@ -1567,20 +1907,23 @@ def _retrieve_stream(
explicit_domain=trustpilot_domain,
domain_is_hint=trustpilot_domain_is_hint,
)
- return trustpilot.parse_trustpilot_response(result, query=relevance_topic), {}
+ return (
+ trustpilot.parse_trustpilot_response(result, query=relevance_topic),
+ _result_outcome_artifact(source, result),
+ )
if source == "bluesky":
result = bluesky.search_bluesky(subquery.search_query, from_date, to_date, depth=depth, config=config)
- return bluesky.parse_bluesky_response(result), {}
+ return bluesky.parse_bluesky_response(result), _result_outcome_artifact(source, result)
if source == "threads":
result = threads.search_threads(
subquery.search_query, from_date, to_date,
depth=depth,
token=config.get("SCRAPECREATORS_API_KEY"),
)
- return threads.parse_threads_response(result), {}
+ return threads.parse_threads_response(result), _result_outcome_artifact(source, result)
if source == "truthsocial":
result = truthsocial.search_truthsocial(subquery.search_query, from_date, to_date, depth=depth, config=config)
- return truthsocial.parse_truthsocial_response(result), {}
+ return truthsocial.parse_truthsocial_response(result), _result_outcome_artifact(source, result)
if source == "polymarket":
result = polymarket.search_polymarket(subquery.search_query, from_date, to_date, depth=depth)
# Relevance filtering keys off the stable original research topic, not the
@@ -1588,7 +1931,10 @@ def _retrieve_stream(
# and would let off-topic markets through on broad subqueries while dropping
# everything on narrow ones).
relevance_topic = raw_topic or topic or subquery.search_query
- return polymarket.parse_polymarket_response(result, topic=relevance_topic), {}
+ return (
+ polymarket.parse_polymarket_response(result, topic=relevance_topic),
+ _result_outcome_artifact(source, result),
+ )
if source == "github":
# Resolve once at the pipeline boundary so search and enrich
# share the result; otherwise each call would re-run the env
@@ -1601,14 +1947,14 @@ def _retrieve_stream(
# is now always eligible, so raising would spam "github failed" on every
# tokenless run. The condition is logged in github.search_github.
items = github.enrich_with_comments(items, depth=depth, token=token)
- return items, {}
+ return items, _result_outcome_artifact(source, response)
if source == "pinterest":
result = pinterest.search_pinterest(
subquery.search_query, from_date, to_date,
depth=depth,
token=env.get_pinterest_token(config),
)
- return pinterest.parse_pinterest_response(result), {}
+ return pinterest.parse_pinterest_response(result), _result_outcome_artifact(source, result)
if source == "xiaohongshu":
return xiaohongshu_api.search_feeds(
subquery.search_query,
diff --git a/skills/last30days/scripts/lib/polymarket.py b/skills/last30days/scripts/lib/polymarket.py
index 87a5d96b..235c6f57 100644
--- a/skills/last30days/scripts/lib/polymarket.py
+++ b/skills/last30days/scripts/lib/polymarket.py
@@ -343,7 +343,7 @@ def _run_queries_parallel(
futures = {}
for i, q in enumerate(queries, start=start_idx):
for p in range(1, pages + 1):
- future = executor.submit(_search_single_query, q, p)
+ future = http.submit_with_context(executor, _search_single_query, q, p)
futures[future] = i
for future in as_completed(futures):
diff --git a/skills/last30days/scripts/lib/reddit.py b/skills/last30days/scripts/lib/reddit.py
index b138e066..092903e3 100644
--- a/skills/last30days/scripts/lib/reddit.py
+++ b/skills/last30days/scripts/lib/reddit.py
@@ -22,7 +22,7 @@ def _first_of(*values, default=None):
return v
return default
-from . import dates, http, log
+from . import dates, health, http, log
SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/reddit"
@@ -78,6 +78,16 @@ def _log(msg: str):
log.source_log("Reddit", msg, tty_only=False)
+def classify_run_failure(detail: str) -> str:
+ """Map Reddit auth and anti-bot responses that do not carry HTTP status."""
+ text = detail.lower()
+ if any(marker in text for marker in ("interstitial", "blocked by reddit", "too many requests")):
+ return health.RATE_LIMITED
+ if any(marker in text for marker in ("login required", "invalid token", "expired token")):
+ return health.AUTH_FAILED
+ return http.classify_failure(message=detail)
+
+
def _extract_core_subject(topic: str) -> str:
"""Extract core subject from verbose query.
@@ -487,7 +497,9 @@ def search_reddit(
with ThreadPoolExecutor(max_workers=min(5, len(subreddits))) as executor:
futures = {}
for sub in subreddits:
- futures[executor.submit(_subreddit_search, sub, core, token, "relevance", timeframe)] = sub
+ futures[http.submit_with_context(
+ executor, _subreddit_search, sub, core, token, "relevance", timeframe,
+ )] = sub
for future in as_completed(futures):
sub = futures[future]
sub_posts = future.result()
@@ -506,7 +518,9 @@ def search_reddit(
# from relevant communities instead of keyword-matched noise.
sort = "top" if intent in ("product", "comparison") else ("relevance" if i == 0 else "top")
_log(f"Global search {i+1}/{max_global}: '{query}' (sort={sort})")
- futures[executor.submit(_global_search, query, token, sort, timeframe)] = query
+ futures[http.submit_with_context(
+ executor, _global_search, query, token, sort, timeframe,
+ )] = query
for future in as_completed(futures):
query = futures[future]
posts = future.result()
@@ -529,7 +543,9 @@ def search_reddit(
futures = {}
for sub in discovered_subs[:subreddit_limit]:
_log(f"Subreddit search: r/{sub} for '{core}'")
- futures[executor.submit(_subreddit_search, sub, core, token, "relevance", timeframe)] = sub
+ futures[http.submit_with_context(
+ executor, _subreddit_search, sub, core, token, "relevance", timeframe,
+ )] = sub
for future in as_completed(futures):
sub = futures[future]
sub_posts = future.result()
@@ -622,7 +638,9 @@ def enrich_with_comments(
with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
futures = {
- executor.submit(fetch_post_comments, item.get("url", ""), token): item
+ http.submit_with_context(
+ executor, fetch_post_comments, item.get("url", ""), token,
+ ): item
for item in top_items
if item.get("url")
}
diff --git a/skills/last30days/scripts/lib/reddit_keyless.py b/skills/last30days/scripts/lib/reddit_keyless.py
index a377f573..5860fa64 100644
--- a/skills/last30days/scripts/lib/reddit_keyless.py
+++ b/skills/last30days/scripts/lib/reddit_keyless.py
@@ -24,6 +24,7 @@ from typing import Any, Dict, List, Optional
from collections import Counter
+from . import http
from . import reddit_rss, reddit_shreddit, reddit_listing, reddit_arctic
# Scores are backfilled from popular derived subreddits, so an engagement-first
# final sort buries on-topic RSS hits under viral off-topic posts. A relevance
@@ -189,7 +190,7 @@ def _enrich(posts: List[Dict[str, Any]], depth: str) -> List[Dict[str, Any]]:
try:
with ThreadPoolExecutor(max_workers=min(limit, MAX_ENRICH_WORKERS)) as executor:
futures = {
- executor.submit(_enrich_one, post): i
+ http.submit_with_context(executor, _enrich_one, post): i
for i, post in enumerate(to_enrich)
}
done, not_done = concurrent.futures.wait(futures, timeout=ENRICH_BUDGET)
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index e57bdeae..b7e91b75 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -8,7 +8,7 @@ from collections import Counter
from datetime import date
from urllib.parse import urlparse
-from . import dates, schema, signals, skill_meta
+from . import dates, health, schema, signals, skill_meta
def _skill_version() -> str:
@@ -62,6 +62,10 @@ def _render_badge() -> list[str]:
]
SOURCE_LABELS = {
+ "reddit": "Reddit",
+ "youtube": "YouTube",
+ "tiktok": "TikTok",
+ "instagram": "Instagram",
"grounding": "Web",
"hackernews": "Hacker News",
"truthsocial": "Truth Social",
@@ -186,6 +190,10 @@ def render_compact(report: schema.Report, cluster_limit: int = 8, fun_level: str
if top_comments:
lines.extend([""] + top_comments)
+ outcome_note = _render_source_outcome_note(report)
+ if outcome_note:
+ lines.extend([""] + outcome_note)
+
lines.extend(_render_source_coverage(report))
# Close EVIDENCE FOR SYNTHESIS envelope before anything that passes through verbatim.
lines.append("")
@@ -1350,8 +1358,14 @@ def _render_source_coverage(report: schema.Report) -> list[str]:
"## Source Coverage",
"",
]
- for source, items in sorted(report.items_by_source.items()):
- lines.append(f"- {_source_label(source)}: {len(items)} item{'s' if len(items) != 1 else ''}")
+ sources = sorted(set(report.items_by_source) | set(report.source_status))
+ for source in sources:
+ items = report.items_by_source.get(source, [])
+ line = f"- {_source_label(source)}: {len(items)} item{'s' if len(items) != 1 else ''}"
+ outcome = report.source_status.get(source)
+ if outcome and outcome.state != health.OK:
+ line += f" ({_format_outcome(outcome)})"
+ lines.append(line)
if report.errors_by_source:
lines.append("")
lines.append("## Source Errors")
@@ -1361,6 +1375,47 @@ def _render_source_coverage(report: schema.Report) -> list[str]:
return lines
+def _render_source_outcome_note(report: schema.Report) -> list[str]:
+ """Tell the synthesizer that a failed source is not evidence of silence."""
+ affected = [
+ outcome
+ for outcome in report.source_status.values()
+ if outcome.state not in (health.OK, schema.NO_RESULTS)
+ ]
+ if not affected:
+ return []
+ summaries = "; ".join(
+ f"{_source_label(outcome.source)} {_format_outcome(outcome)}"
+ for outcome in sorted(affected, key=lambda item: item.source)
+ )
+ return [
+ "## Partial Coverage",
+ "",
+ f"> {summaries}.",
+ "> Do not interpret a failed source as no discussion on that source. "
+ "Synthesize only from available evidence; run `doctor` for fix prescriptions.",
+ ]
+
+
+def _format_outcome(outcome: schema.SourceOutcome) -> str:
+ detail = " ".join((outcome.detail or "").split())
+ if len(detail) > 140:
+ detail = detail[:137].rstrip() + "..."
+ state = outcome.state
+ if state == schema.PARTIAL:
+ noun = "item" if outcome.items_returned == 1 else "items"
+ summary = f"partial after {outcome.items_returned} {noun}"
+ elif state == schema.NO_RESULTS:
+ summary = "no results"
+ else:
+ summary = state
+ if detail:
+ summary += f": {detail}"
+ if outcome.fix_hint == "doctor":
+ summary += " (run doctor for fixes)"
+ return summary
+
+
# Known publications for the Web line of the emoji-tree footer.
# Maps apex domain to a clean display name. Unknown domains fall back to
# the bare domain string (protocol stripped, www. removed).
@@ -1525,7 +1580,7 @@ def _footer_line_for_source(emoji: str, label: str, count: int, item_word: str,
def _build_source_footer_lines(report: schema.Report) -> list[str]:
- """Return emoji-tree body lines (without tree characters) for each populated source.
+ """Return emoji-tree lines for populated and outcome-bearing sources.
The caller adds the tree characters (├─ / └─) after assembling all lines.
"""
@@ -1551,7 +1606,11 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
)
parts.append(f"{with_transcripts}/{len(items)} with transcripts")
stats = " │ ".join(parts)
- out.append(_footer_line_for_source(emoji, label, len(items), item_word, stats))
+ line = _footer_line_for_source(emoji, label, len(items), item_word, stats)
+ outcome = report.source_status.get(source_key)
+ if outcome and outcome.state != health.OK:
+ line += f" │ ⚠ {_format_outcome(outcome)}"
+ out.append(line)
# Polymarket (special: count + odds string from existing helper)
polymarket_items = report.items_by_source.get("polymarket") or []
@@ -1562,9 +1621,13 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
count_str = f"{count:,}" if count >= 1000 else str(count)
plural = "markets" if count != 1 else "market"
if odds_str:
- out.append(f"📊 Polymarket: {count_str} {plural} │ {odds_str}")
+ line = f"📊 Polymarket: {count_str} {plural} │ {odds_str}"
else:
- out.append(f"📊 Polymarket: {count_str} {plural}")
+ line = f"📊 Polymarket: {count_str} {plural}"
+ outcome = report.source_status.get("polymarket")
+ if outcome and outcome.state != health.OK:
+ line += f" │ ⚠ {_format_outcome(outcome)}"
+ out.append(line)
# Web (sources from grounding)
web_items = report.items_by_source.get("grounding") or []
@@ -1574,9 +1637,25 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
count_str = f"{count:,}" if count >= 1000 else str(count)
plural = "pages" if count != 1 else "page"
if names:
- out.append(f"🌐 Web: {count_str} {plural} - {names}")
+ line = f"🌐 Web: {count_str} {plural} - {names}"
else:
- out.append(f"🌐 Web: {count_str} {plural}")
+ line = f"🌐 Web: {count_str} {plural}"
+ outcome = report.source_status.get("grounding")
+ if outcome and outcome.state != health.OK:
+ line += f" │ ⚠ {_format_outcome(outcome)}"
+ out.append(line)
+
+ populated = {source for source, items in report.items_by_source.items() if items}
+ footer_meta = {
+ source: (emoji, label)
+ for source, emoji, label, _item_word, _engagement in _FOOTER_SOURCES
+ }
+ footer_meta.update({"polymarket": ("📊", "Polymarket"), "grounding": ("🌐", "Web")})
+ for source, outcome in sorted(report.source_status.items()):
+ if source in populated:
+ continue
+ emoji, label = footer_meta.get(source, ("⚪", _source_label(source)))
+ out.append(f"{emoji} {label}: {_format_outcome(outcome)}")
return out
@@ -1619,7 +1698,7 @@ def _render_emoji_footer(report: schema.Report, save_path: str | None) -> list[s
"""Produce the deterministic magic footer block.
Returns a list of markdown lines, including enclosing ``---`` separators.
- Returns an empty list if no sources are populated.
+ Returns an empty list if the report has neither source items nor outcomes.
"""
source_lines = _build_source_footer_lines(report)
if not source_lines:
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index d9a600b8..713bc047 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -3,8 +3,11 @@
from __future__ import annotations
from dataclasses import asdict, dataclass, field, is_dataclass
+from datetime import datetime, timezone
from typing import Any, Literal
+from . import health
+
def _drop_none(value: Any) -> Any:
"""Recursively remove None values from dataclass-derived structures."""
@@ -139,6 +142,69 @@ class Cluster:
raise ValueError("representative_ids must be a subset of candidate_ids")
+RunOutcomeState = Literal[
+ "ok",
+ "no-results",
+ "partial",
+ "rate-limited",
+ "auth-failed",
+ "unreachable",
+ "timeout",
+ "schema-drift",
+ "skipped-unconfigured",
+ "error",
+]
+
+NO_RESULTS = health.NO_RESULTS
+PARTIAL = health.PARTIAL
+RATE_LIMITED = health.RATE_LIMITED
+AUTH_FAILED = health.AUTH_FAILED
+UNREACHABLE = health.UNREACHABLE
+SCHEMA_DRIFT = health.SCHEMA_DRIFT
+SKIPPED_UNCONFIGURED = health.SKIPPED_UNCONFIGURED
+
+
+def _utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+@dataclass
+class SourceOutcome:
+ """What happened to one source during this run.
+
+ Doctor predicts whether a source is configured and healthy before a run;
+ this records the observed retrieval result. Shared states reuse
+ ``health.py`` values (``ok``, ``timeout``, ``error``), while the remaining
+ states describe run-only outcomes.
+ """
+
+ source: str
+ state: RunOutcomeState
+ items_returned: int = 0
+ attempted: bool = True
+ detail: str | None = None
+ at: str = field(default_factory=_utc_now)
+ fix_hint: str | None = None
+
+ def __post_init__(self) -> None:
+ valid_states = {
+ health.OK,
+ health.TIMEOUT,
+ health.ERROR,
+ NO_RESULTS,
+ PARTIAL,
+ RATE_LIMITED,
+ AUTH_FAILED,
+ UNREACHABLE,
+ SCHEMA_DRIFT,
+ SKIPPED_UNCONFIGURED,
+ }
+ if self.state not in valid_states:
+ raise ValueError(f"Unknown source outcome state: {self.state}")
+ if self.items_returned < 0:
+ raise ValueError("items_returned cannot be negative")
+
+
@dataclass
class Report:
"""Final pipeline output."""
@@ -153,6 +219,7 @@ class Report:
ranked_candidates: list[Candidate]
items_by_source: dict[str, list[SourceItem]]
errors_by_source: dict[str, str]
+ source_status: dict[str, SourceOutcome] = field(default_factory=dict)
warnings: list[str] = field(default_factory=list)
artifacts: dict[str, Any] = field(default_factory=dict)
@@ -164,12 +231,57 @@ class RetrievalBundle:
items_by_source_and_query: dict[tuple[str, str], list[SourceItem]] = field(default_factory=dict)
items_by_source: dict[str, list[SourceItem]] = field(default_factory=dict)
errors_by_source: dict[str, str] = field(default_factory=dict)
+ source_status: dict[str, SourceOutcome] = field(default_factory=dict)
artifacts: dict[str, Any] = field(default_factory=dict)
+ def mark_attempted(self, source: str) -> None:
+ """Register a planned source before its first retrieval starts."""
+ self.source_status.setdefault(
+ source,
+ SourceOutcome(source=source, state=NO_RESULTS),
+ )
+
+ def record_failure(
+ self,
+ source: str,
+ state: RunOutcomeState,
+ detail: str,
+ *,
+ attempted: bool = True,
+ ) -> None:
+ """Record a failure, preserving already-returned items as partial."""
+ count = len(self.items_by_source.get(source, []))
+ outcome_state: RunOutcomeState = PARTIAL if count else state
+ self.errors_by_source.setdefault(source, detail)
+ self.source_status[source] = SourceOutcome(
+ source=source,
+ state=outcome_state,
+ items_returned=count,
+ attempted=attempted,
+ detail=detail,
+ fix_hint="doctor",
+ )
+
def add_items(self, label: str, source: str, items: list[SourceItem]) -> None:
"""Atomically append items to both items_by_source_and_query and items_by_source."""
self.items_by_source_and_query.setdefault((label, source), []).extend(items)
self.items_by_source.setdefault(source, []).extend(items)
+ previous = self.source_status.get(source)
+ state: RunOutcomeState = health.OK if items else NO_RESULTS
+ detail = None
+ fix_hint = None
+ if previous and previous.state not in (health.OK, NO_RESULTS):
+ state = PARTIAL if self.items_by_source[source] else previous.state
+ detail = previous.detail
+ fix_hint = previous.fix_hint
+ self.source_status[source] = SourceOutcome(
+ source=source,
+ state=state,
+ items_returned=len(self.items_by_source[source]),
+ attempted=True,
+ detail=detail,
+ fix_hint=fix_hint,
+ )
def to_dict(value: Any) -> Any:
@@ -287,6 +399,18 @@ def report_from_dict(payload: dict[str, Any]) -> Report:
for source, items in (payload.get("items_by_source") or {}).items()
},
errors_by_source=dict(payload.get("errors_by_source") or {}),
+ source_status={
+ source: SourceOutcome(
+ source=outcome.get("source") or source,
+ state=outcome["state"],
+ items_returned=int(outcome.get("items_returned") or 0),
+ attempted=bool(outcome.get("attempted", True)),
+ detail=outcome.get("detail"),
+ at=outcome.get("at") or _utc_now(),
+ fix_hint=outcome.get("fix_hint"),
+ )
+ for source, outcome in (payload.get("source_status") or {}).items()
+ },
warnings=list(payload.get("warnings") or []),
artifacts=dict(payload.get("artifacts") or {}),
)
diff --git a/skills/last30days/scripts/lib/tiktok.py b/skills/last30days/scripts/lib/tiktok.py
index c35771eb..ef4c9a76 100644
--- a/skills/last30days/scripts/lib/tiktok.py
+++ b/skills/last30days/scripts/lib/tiktok.py
@@ -524,7 +524,7 @@ def enrich_with_comments(
enriched_count = 0
with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
- futures = {executor.submit(_enrich_one, item): item for item in top_items}
+ futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
for future in as_completed(futures):
if future.result():
enriched_count += 1
diff --git a/skills/last30days/scripts/lib/youtube_yt.py b/skills/last30days/scripts/lib/youtube_yt.py
index a1fde08d..966d9f0c 100644
--- a/skills/last30days/scripts/lib/youtube_yt.py
+++ b/skills/last30days/scripts/lib/youtube_yt.py
@@ -56,7 +56,7 @@ def reset_transcript_fetch_stats() -> None:
# Max words to keep from each transcript
TRANSCRIPT_MAX_WORDS = 5000
-from . import dates, http, log, subproc
+from . import dates, health, http, log, subproc
from .query import infer_query_intent
from .relevance import token_overlap_relevance as _compute_relevance
@@ -143,6 +143,21 @@ def _log(msg: str):
log.source_log("YouTube", msg, tty_only=False)
+def classify_run_failure(detail: str) -> str:
+ """Map yt-dlp's text-only throttling and bot-gate errors."""
+ text = detail.lower()
+ if any(marker in text for marker in ("yt-dlp not installed", "yt-dlp not found")):
+ return health.SKIPPED_UNCONFIGURED
+ if any(
+ marker in text
+ for marker in ("http error 429", "confirm you're not a bot", "confirm you’re not a bot", "bot-gate")
+ ):
+ return health.RATE_LIMITED
+ if any(marker in text for marker in ("sign in", "login required", "cookies are no longer valid")):
+ return health.AUTH_FAILED
+ return http.classify_failure(message=detail)
+
+
def is_ytdlp_installed() -> bool:
"""Check if yt-dlp is available locally, or if SSH routing is configured.
@@ -833,8 +848,8 @@ def fetch_transcripts_parallel(
with tempfile.TemporaryDirectory() as temp_dir:
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
- executor.submit(
- fetch_transcript, vid, temp_dir, statuses[vid], token,
+ http.submit_with_context(
+ executor, fetch_transcript, vid, temp_dir, statuses[vid], token,
): vid
for vid in video_ids
}
@@ -1082,7 +1097,7 @@ def enrich_with_comments(
enriched_count = 0
with ThreadPoolExecutor(max_workers=min(4, len(top_items))) as executor:
- futures = {executor.submit(_enrich_one, item): item for item in top_items}
+ futures = {http.submit_with_context(executor, _enrich_one, item): item for item in top_items}
for future in as_completed(futures):
if future.result():
enriched_count += 1
diff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.py
new file mode 100644
index 00000000..9ac3a59a
--- /dev/null
+++ b/tests/test_source_outcomes.py
@@ -0,0 +1,393 @@
+import socket
+import urllib.error
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from lib import bird_x, health, http, jobs, pipeline, reddit, render, schema, youtube_yt
+
+
+def _report(*, source_status=None, items_by_source=None, errors_by_source=None):
+ return schema.Report(
+ topic="test topic",
+ range_from="2026-06-10",
+ range_to="2026-07-10",
+ generated_at="2026-07-10T18:22:03Z",
+ provider_runtime=schema.ProviderRuntime(
+ reasoning_provider="gemini",
+ planner_model="test-planner",
+ rerank_model="test-reranker",
+ ),
+ query_plan=schema.QueryPlan(
+ intent="general",
+ freshness_mode="balanced_recent",
+ cluster_mode="story",
+ raw_topic="test topic",
+ subqueries=[
+ schema.SubQuery(
+ label="primary",
+ search_query="test topic",
+ ranking_query="test topic",
+ sources=["x"],
+ )
+ ],
+ source_weights={"x": 1.0},
+ ),
+ clusters=[],
+ ranked_candidates=[],
+ items_by_source=items_by_source or {},
+ errors_by_source=errors_by_source or {},
+ source_status=source_status or {},
+ )
+
+
+ ("error", "expected"),
+ [
+ (http.HTTPError("HTTP 429", status_code=429), schema.RATE_LIMITED),
+ (http.HTTPError("HTTP 401", status_code=401), schema.AUTH_FAILED),
+ (http.HTTPError("HTTP 402", status_code=402), schema.AUTH_FAILED),
+ (http.HTTPError("HTTP 403", status_code=403), schema.AUTH_FAILED),
+ (http.HTTPError("Invalid JSON response"), schema.SCHEMA_DRIFT),
+ (http.HTTPError("Connection error: reset"), schema.UNREACHABLE),
+ (http.HTTPError("Request timed out"), health.TIMEOUT),
+ ],
+)
+def test_http_error_exposes_run_outcome_state(error, expected):
+ assert error.outcome_state == expected
+
+
+@patch("lib.http.time.sleep")
+@patch("lib.http.urllib.request.urlopen")
+def test_http_wrapper_classifies_dns_failure(mock_urlopen, _mock_sleep):
+ mock_urlopen.side_effect = urllib.error.URLError(
+ socket.gaierror(-2, "Name or service not known")
+ )
+
+ with pytest.raises(http.HTTPError) as caught:
+ http.get("https://unreachable.example", retries=1)
+
+ assert caught.value.outcome_state == schema.UNREACHABLE
+
+
+def test_source_specific_text_failures_are_mapped():
+ assert bird_x.classify_run_failure("likely Twitter anti-bot interstitial") == schema.SCHEMA_DRIFT
+ assert reddit.classify_run_failure("blocked by Reddit interstitial") == schema.RATE_LIMITED
+ assert youtube_yt.classify_run_failure("Sign in to confirm you're not a bot") == schema.RATE_LIMITED
+
+
+def test_bundle_distinguishes_clean_no_results_from_failure():
+ clean = schema.RetrievalBundle()
+ clean.mark_attempted("x")
+
+ failed = schema.RetrievalBundle()
+ failed.mark_attempted("x")
+ failed.record_failure("x", schema.RATE_LIMITED, "HTTP 429")
+
+ assert clean.source_status["x"].state == schema.NO_RESULTS
+ assert failed.source_status["x"].state == schema.RATE_LIMITED
+ assert failed.source_status["x"].fix_hint == "doctor"
+
+
+@patch("lib.http.urllib.request.urlopen")
+def test_stream_adapter_recovers_http_failure_laundered_as_empty(mock_urlopen):
+ mock_urlopen.side_effect = urllib.error.HTTPError(
+ "https://api.example.com",
+ 401,
+ "Unauthorized",
+ {},
+ None,
+ )
+
+ def source_that_launders_failure(*_args, **_kwargs):
+ try:
+ http.get("https://api.example.com", retries=1)
+ except http.HTTPError:
+ return [], {}
+ raise AssertionError("request should have failed")
+
+ with patch("lib.pipeline._retrieve_stream_impl", side_effect=source_that_launders_failure):
+ items, artifact = pipeline._retrieve_stream()
+
+ assert items == []
+ assert artifact["_source_outcome"]["state"] == schema.AUTH_FAILED
+
+
+@patch("lib.http.time.sleep")
+@patch("lib.http.urllib.request.urlopen")
+def test_reddit_nested_worker_propagates_failure_capture(mock_urlopen, _mock_sleep):
+ mock_urlopen.side_effect = urllib.error.HTTPError(
+ "https://api.scrapecreators.com/v1/reddit/search",
+ 429,
+ "Too Many Requests",
+ {},
+ None,
+ )
+
+ with http.capture_failures() as failures:
+ result = reddit.search_reddit(
+ "test topic",
+ "2026-06-10",
+ "2026-07-10",
+ depth="quick",
+ token="dummy-token",
+ )
+
+ assert result["items"] == []
+ assert failures[-1].outcome_state == schema.RATE_LIMITED
+
+
+@patch("lib.http.urllib.request.urlopen")
+def test_jobs_expected_probe_misses_do_not_degrade_final_result(mock_urlopen):
+ miss = urllib.error.HTTPError(
+ "https://boards-api.greenhouse.io/v1/boards/example/jobs",
+ 404,
+ "Not Found",
+ {},
+ None,
+ )
+ success = MagicMock()
+ success.status = 200
+ success.read.return_value = (
+ b'{"jobs":[{"id":"1","title":"Engineer",'
+ b'"jobUrl":"https://jobs.ashbyhq.com/example/1"}]}'
+ )
+ success.__enter__.return_value = success
+ success.__exit__.return_value = False
+ mock_urlopen.side_effect = [miss, success]
+
+ with patch("lib.jobs._candidate_slugs", return_value=["example"]):
+ with http.capture_failures() as failures:
+ provider, slug, _ = jobs._probe_ats("Example")
+
+ assert provider == jobs.ATS_PROVIDER_ASHBY
+ assert slug == "example"
+ assert failures == []
+
+
+ ("source", "artifact", "expected"),
+ [
+ ("perplexity", {"error": "timeout"}, health.TIMEOUT),
+ (
+ "grounding",
+ {"reason": "keyless-search-unavailable"},
+ schema.UNREACHABLE,
+ ),
+ ],
+)
+def test_stream_adapter_converts_legacy_error_artifacts(source, artifact, expected):
+ with patch("lib.pipeline._retrieve_stream_impl", return_value=([], artifact)):
+ _, converted = pipeline._retrieve_stream(source=source)
+
+ assert converted["_source_outcome"]["state"] == expected
+
+
+ ("source", "detail", "expected"),
+ [
+ ("truthsocial", "Truth Social token expired", schema.AUTH_FAILED),
+ (
+ "bluesky",
+ "Cloudflare blocked the request (403 Forbidden). This is a network-level block, not an auth issue.",
+ schema.UNREACHABLE,
+ ),
+ ],
+)
+def test_legacy_result_uses_source_specific_outcome(source, detail, expected):
+ artifact = pipeline._result_outcome_artifact(source, {"error": detail})
+
+ assert artifact["_source_outcome"]["state"] == expected
+
+
+def test_captured_http_failure_overrides_generic_artifact_error():
+ failure = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
+ outcome = pipeline._resolve_stream_outcome(
+ "tiktok",
+ pipeline._outcome_artifact(health.ERROR, "request failed"),
+ [failure],
+ )
+
+ assert outcome["state"] == schema.RATE_LIMITED
+
+
+def test_bundle_records_items_then_429_as_partial():
+ item = schema.SourceItem(
+ item_id="x1",
+ source="x",
+ title="A post",
+ body="body",
+ url="https://x.com/example/status/1",
+ )
+ bundle = schema.RetrievalBundle()
+ bundle.mark_attempted("x")
+ bundle.add_items("primary", "x", [item])
+ bundle.record_failure("x", schema.RATE_LIMITED, "429 after first page")
+
+ outcome = bundle.source_status["x"]
+ assert outcome.state == schema.PARTIAL
+ assert outcome.items_returned == 1
+ assert outcome.detail == "429 after first page"
+
+
+def test_pipeline_records_clean_empty_source_as_no_results():
+ plan = {
+ "intent": "general",
+ "freshness_mode": "balanced_recent",
+ "cluster_mode": "story",
+ "subqueries": [
+ {
+ "label": "primary",
+ "search_query": "test topic",
+ "ranking_query": "test topic",
+ "sources": ["x"],
+ }
+ ],
+ "source_weights": {"x": 1.0},
+ }
+ with patch("lib.pipeline._retrieve_stream", return_value=([], {})):
+ report = pipeline.run(
+ topic="test topic",
+ config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
+ depth="quick",
+ requested_sources=["x"],
+ mock=True,
+ external_plan=plan,
+ )
+
+ assert report.source_status["x"].state == schema.NO_RESULTS
+ assert "x" not in report.errors_by_source
+
+
+def test_pipeline_preserves_typed_http_failure():
+ plan = {
+ "intent": "general",
+ "freshness_mode": "balanced_recent",
+ "cluster_mode": "story",
+ "subqueries": [
+ {
+ "label": "primary",
+ "search_query": "test topic",
+ "ranking_query": "test topic",
+ "sources": ["x"],
+ }
+ ],
+ "source_weights": {"x": 1.0},
+ }
+ failure = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
+ with patch("lib.pipeline._retrieve_stream", side_effect=failure):
+ report = pipeline.run(
+ topic="test topic",
+ config={"LAST30DAYS_REASONING_PROVIDER": "gemini"},
+ depth="quick",
+ requested_sources=["x"],
+ mock=True,
+ external_plan=plan,
+ )
+
+ assert report.source_status["x"].state == schema.RATE_LIMITED
+ assert report.source_status["x"].items_returned == 0
+ assert "x" in report.errors_by_source
+
+
+def test_footer_and_synthesis_note_surface_failed_source():
+ report = _report(
+ source_status={
+ "x": schema.SourceOutcome(
+ source="x",
+ state=schema.RATE_LIMITED,
+ detail="HTTP 429 after retry budget",
+ fix_hint="doctor",
+ )
+ },
+ errors_by_source={"x": "HTTP 429 after retry budget"},
+ )
+
+ text = render.render_compact(report)
+
+ assert "## Partial Coverage" in text
+ assert "Do not interpret a failed source as no discussion" in text
+ assert "🔵 X: rate-limited: HTTP 429 after retry budget (run doctor for fixes)" in text
+
+
+def test_report_source_status_round_trips_through_schema_serialization():
+ report = _report(
+ source_status={
+ "x": schema.SourceOutcome(
+ source="x",
+ state=schema.PARTIAL,
+ items_returned=12,
+ detail="429 after 12 items",
+ at="2026-07-10T18:22:03Z",
+ fix_hint="doctor",
+ )
+ }
+ )
+
+ payload = schema.to_dict(report)
+ restored = schema.report_from_dict(payload)
+
+ assert payload["source_status"]["x"]["state"] == schema.PARTIAL
+ assert restored.source_status["x"] == report.source_status["x"]
+
+
+# --- strict exit (LAST30DAYS_STRICT_EXIT, issue #384) ---
+
+import last30days as cli
+
+
+def _outcome(source, state, **kwargs):
+ return schema.SourceOutcome(source=source, state=state, **kwargs)
+
+
+def test_strict_exit_disabled_by_default_even_when_degraded():
+ report = _report(
+ source_status={"x": _outcome("x", schema.RATE_LIMITED, detail="429")}
+ )
+ assert cli._strict_exit_code(report, None, {}) == 0
+
+
+def test_strict_exit_returns_3_for_degraded_run(capsys):
+ report = _report(
+ source_status={"x": _outcome("x", schema.AUTH_FAILED, detail="401")}
+ )
+ rc = cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "1"})
+ assert rc == 3
+ assert "strict-exit: degraded sources: x" in capsys.readouterr().err
+
+
+def test_strict_exit_clean_states_return_0():
+ report = _report(
+ source_status={
+ "reddit": _outcome("reddit", health.OK, items_returned=12),
+ "hn": _outcome("hn", schema.NO_RESULTS),
+ "tiktok": _outcome("tiktok", schema.SKIPPED_UNCONFIGURED, attempted=False),
+ }
+ )
+ assert cli._strict_exit_code(report, None, {"LAST30DAYS_STRICT_EXIT": "true"}) == 0
+
+
+def test_strict_exit_checks_entity_reports_in_comparison_runs():
+ lead = _report(source_status={"reddit": _outcome("reddit", health.OK)})
+ entity = _report(
+ source_status={"x": _outcome("x", schema.UNREACHABLE, detail="dns")}
+ )
+ rc = cli._strict_exit_code(lead, [("other", entity)], {"LAST30DAYS_STRICT_EXIT": "on"})
+ assert rc == 3
+
+
+def test_strict_exit_env_key_is_registered():
+ # Unregistered keys are silently dropped by env config loading (#707 class).
+ from lib import env as env_module
+ import inspect
+
+ assert "LAST30DAYS_STRICT_EXIT" in inspect.getsource(env_module)
+
+
+def test_captured_failure_selection_prefers_most_specific():
+ auth = http.HTTPError("HTTP 401: Unauthorized", status_code=401)
+ rate = http.HTTPError("HTTP 429: Too Many Requests", status_code=429)
+ # Order must not matter: auth-failed wins over rate-limited either way.
+ for failures in ([auth, rate], [rate, auth]):
+ outcome = pipeline._resolve_stream_outcome("x", None, failures)
+ assert outcome["state"] == schema.AUTH_FAILED