AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix(reddit): report keyless 429/403 as transport failures, not no-results (#900)
Eugene57f8d2c87a8d
diff --git a/changelog.d/899.fixed.md b/changelog.d/899.fixed.mdnew file mode 100644index 00000000..e8d4cfa9--- /dev/null+++ b/changelog.d/899.fixed.md@@ -0,0 +1 @@+Reddit HTTP 429/403 on the keyless lanes is no longer reported as a clean `no-results`: the failure now survives the worker-thread hop into the run outcome, so `source_status` carries `rate-limited`/`auth-failed` with the status in `detail` and `doctor --postmortem` lists Reddit under Failed instead of "No failures on the last run." `doctor --probe` now checks the RSS endpoint the engine actually uses (the old `/r/all/hot.json` probe is permanently 403 keyless) and counts a 403/429 there as blocked rather than reachable. Under `LAST30DAYS_STRICT_EXIT` a blocked Reddit run now exits 3 instead of 0.diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pyindex dc0e0f32..49d71f39 100644--- a/skills/last30days/scripts/lib/doctor.py+++ b/skills/last30days/scripts/lib/doctor.py@@ -53,7 +53,7 @@ import urllib.requestfrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional-from . import backends, env, health, prescriptions+from . import backends, env, health, http, prescriptionsfrom .backends import TIER_ERROR, TIER_OK, TIER_WARN# Rollup tiers (R1). ok/warn/error are U2's; only "off" is doctor's own.@@ -1469,12 +1469,30 @@ def _write_cache(report: Dict[str, Any], config: Dict[str, Any]) -> bool:# Free, keyless liveness endpoints (reachability check, tiny payload)._HTTP_PROBE_URLS = {- "reddit": "https://www.reddit.com/r/all/hot.json?limit=1",+ # The keyless engine's real discovery endpoint (reddit_rss._build_urls).+ # /r/all/hot.json is permanently 403 keyless (see the reddit_keyless module+ # docstring) and no lane requests it any more, so probing it measured an+ # endpoint the engine had already abandoned.+ "reddit": "https://www.reddit.com/search.rss?q=test&sort=relevance&t=month","hackernews": "https://hn.algolia.com/api/v1/search?query=test&hitsPerPage=1","polymarket": "https://gamma-api.polymarket.com/events?limit=1","github": "https://api.github.com/rate_limit",}+# Per-source exception to "a 4xx still means the endpoint responded". The+# keyless Reddit lanes send no credentials, so a 403/429 there is the host+# refusing this client — the exact failure the engine hits — not reachability.+_PROBE_BLOCKED_STATUSES = {"reddit": frozenset({403, 429})}++# Probe with the identity the lane sends, or the probe measures the User-Agent+# rather than the endpoint (get_text sends http.BROWSER_USER_AGENT).+_PROBE_HEADERS = {+ "reddit": {+ "User-Agent": http.BROWSER_USER_AGENT,+ "Accept": "application/atom+xml",+ },+}+DEFAULT_PROBE_TIMEOUT_SECONDS = 10@@ -1501,18 +1519,32 @@ def _probeable_sources() -> tuple:return tuple(dict.fromkeys(list(_HTTP_PROBE_URLS) + cli_only))-def _http_ok(url: str, timeout: float) -> tuple:+def _http_ok(+ url: str,+ timeout: float,+ *,+ blocked_statuses: frozenset = frozenset(),+ headers: Optional[Dict[str, str]] = None,+) -> tuple:"""Reachability check: a 4xx still means the endpoint responded; 5xx or a- connection/timeout error means it did not."""+ connection/timeout error means it did not.++ ``blocked_statuses`` names the per-source codes that mean "responded, but+ refused us" (Reddit's keyless 403/429) — those are a failure, not+ reachability. ``headers`` overrides the probe identity so a source can be+ probed with the same User-Agent its lane sends.+ """+ def _verdict(code: int) -> tuple:+ return code < 500 and code not in blocked_statuses, f"HTTP {code}"+try:req = urllib.request.Request(- url, headers={"User-Agent": "last30days-doctor"}+ url, headers=headers or {"User-Agent": "last30days-doctor"})with urllib.request.urlopen(req, timeout=timeout) as resp:- code = getattr(resp, "status", 200) or 200- return code < 500, f"HTTP {code}"+ return _verdict(getattr(resp, "status", 200) or 200)except urllib.error.HTTPError as exc:- return exc.code < 500, f"HTTP {exc.code}"+ return _verdict(exc.code)except Exception as exc:return False, f"{type(exc).__name__}: {exc}"@@ -1520,7 +1552,12 @@ def _http_ok(url: str, timeout: float) -> tuple:def _probe_source(name: str, config: Dict[str, Any], timeout: float) -> Optional[Dict[str, Any]]:url = _HTTP_PROBE_URLS.get(name)if url:- ok, detail = _http_ok(url, timeout)+ ok, detail = _http_ok(+ url,+ timeout,+ blocked_statuses=_PROBE_BLOCKED_STATUSES.get(name, frozenset()),+ headers=_PROBE_HEADERS.get(name),+ )return {"ok": ok, "detail": detail, "probed": True}cli = CLI_DEPENDENCIES.get(name)if cli:diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.pyindex 12095f0e..0d6e7120 100644--- a/skills/last30days/scripts/lib/http.py+++ b/skills/last30days/scripts/lib/http.py@@ -9,6 +9,7 @@ import threadingimport timeimport urllib.errorimport urllib.request+from concurrent.futures import Futurefrom contextlib import contextmanagerfrom contextvars import ContextVar, copy_contextfrom pathlib import Path@@ -432,6 +433,27 @@ def capture_failures():_failure_sink.reset(token)+@contextmanager+def tee_failures():+ """Observe failures locally WITHOUT hiding them from the enclosing sink.++ ``capture_failures()`` *replaces* the context-local sink, so nesting it+ inside a retrieval context swallows the very failure the pipeline needs.+ This yields a local list and forwards its contents to the parent sink on+ exit, so a swallow site (``get_text`` returns None and drops the status)+ can recover what it lost while the pipeline still sees the failure.+ """+ parent = _failure_sink.get()+ local: list[HTTPError] = []+ token = _failure_sink.set(local)+ try:+ yield local+ finally:+ _failure_sink.reset(token)+ if parent is not None:+ parent.extend(local)++@contextmanagerdef expected_misses(*status_codes: int):"""Exclude adapter-declared probe misses from captured run failures."""@@ -444,7 +466,7 @@ def expected_misses(*status_codes: int):_expected_miss_statuses.reset(token)-def submit_with_context(executor, func, /, *args, **kwargs):+def submit_with_context(executor, func, /, *args, **kwargs) -> Future:"""Submit a worker with the caller's failure-capture context."""context = copy_context()return executor.submit(context.run, func, *args, **kwargs)diff --git a/skills/last30days/scripts/lib/reddit_listing.py b/skills/last30days/scripts/lib/reddit_listing.pyindex 8061eb43..0b13bc13 100644--- a/skills/last30days/scripts/lib/reddit_listing.py+++ b/skills/last30days/scripts/lib/reddit_listing.py@@ -148,9 +148,17 @@ def _fetch_one_with_status(timeframe: str = TIMEFRAME,) -> tuple[List[Dict[str, Any]], Optional[str]]:try:- text = http.reddit_keyless_get_text(_listing_url(subreddit, sort, timeframe), timeout=LISTING_TIMEOUT,- accept="text/html")- return (parse_cards(text, query) if text else []), None+ # tee_failures, not capture_failures: the latter would replace the+ # pipeline's sink and hide this failure from it. get_text launders a+ # terminal HTTP failure into None, so the tee is how this lane recovers+ # the status code it needs to report (issue #899).+ with http.tee_failures() as swallowed:+ text = http.reddit_keyless_get_text(_listing_url(subreddit, sort, timeframe), timeout=LISTING_TIMEOUT,+ accept="text/html")+ if text is None:+ # An empty body ("") is a real empty listing; None never is.+ return [], (str(swallowed[-1]) if swallowed else "no response")+ return parse_cards(text, query), Noneexcept Exception as e:_log(f"listing fetch failed r/{subreddit} {sort}: {e}")return [], str(e)@@ -178,7 +186,9 @@ def fetch_listings(jobs = [(sub, sort) for sub in subreddits for sort in sorts]all_posts: List[Dict[str, Any]] = []with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) as executor:- futures = {executor.submit(_fetch_one, sub, sort, query, timeframe): (sub, sort)+ # submit_with_context, not executor.submit — see the note in+ # fetch_discovery_listings below (issue #899).+ futures = {http.submit_with_context(executor, _fetch_one, sub, sort, query, timeframe): (sub, sort)for sub, sort in jobs}for future in futures:try:@@ -208,8 +218,14 @@ def fetch_discovery_listings(items: List[Dict[str, Any]] = []errors: List[str] = []with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, len(jobs)) or 1) as executor:+ # submit_with_context, not executor.submit: a plain submit starts the+ # worker with an empty context, dropping the pipeline's+ # capture_failures() sink so a listing's 429/403 is silently discarded+ # and the source reports a clean no-results (issue #899).futures = {- executor.submit(_fetch_one_with_status, subreddit, sort, query, "week"): (subreddit, sort)+ http.submit_with_context(+ executor, _fetch_one_with_status, subreddit, sort, query, "week"+ ): (subreddit, sort)for subreddit, sort in jobs}for future, (subreddit, sort) in futures.items():diff --git a/skills/last30days/scripts/lib/reddit_rss.py b/skills/last30days/scripts/lib/reddit_rss.pyindex 19054389..0a91e99b 100644--- a/skills/last30days/scripts/lib/reddit_rss.py+++ b/skills/last30days/scripts/lib/reddit_rss.py@@ -203,7 +203,14 @@ def search_rss(all_posts: List[Dict[str, Any]] = []workers = min(MAX_WORKERS, len(urls)) or 1with ThreadPoolExecutor(max_workers=workers) as executor:- futures = {executor.submit(_fetch_feed, url, query): url for url in urls}+ # submit_with_context, not executor.submit: a plain submit starts the+ # worker with an empty context, dropping the pipeline's+ # capture_failures() sink so a feed's 429/403 is silently discarded and+ # the source reports a clean no-results (issue #899).+ futures = {+ http.submit_with_context(executor, _fetch_feed, url, query): url+ for url in urls+ }for future in futures:try:all_posts.extend(future.result(timeout=FEED_TIMEOUT + 5))diff --git a/tests/test_discover_mode.py b/tests/test_discover_mode.pyindex 8f03e1aa..ddc9ae2e 100644--- a/tests/test_discover_mode.py+++ b/tests/test_discover_mode.py@@ -5,6 +5,7 @@ import jsonimport osimport subprocessimport sys+import urllib.errorfrom pathlib import Pathfrom unittest import mock@@ -379,6 +380,33 @@ def test_listing_failure_is_not_reported_as_clean_no_results():assert report.source_status["reddit"].detail == "connection timed out"+def test_discovery_listing_block_is_reported_as_rate_limited():+ # get_text swallows the 429 and hands back None; without the tee the lane+ # could not tell that apart from an empty listing and the sweep reported a+ # clean no-results (issue #899).+ blocked = urllib.error.HTTPError(+ "https://www.reddit.com/svc/shreddit/community-more-posts/rising/",+ 429,+ "Too Many Requests",+ {},+ None,+ )++ with mock.patch.object(pipeline, "available_sources", return_value=["reddit"]), \+ mock.patch("lib.http.time.sleep"), \+ mock.patch("lib.http.urllib.request.urlopen", side_effect=blocked):+ report = pipeline.run_discover(+ domain="AI agents",+ config={},+ as_of_date="2026-07-10",+ subreddits=["AI_Agents"],+ )++ outcome = report.source_status["reddit"]+ assert outcome.state == "rate-limited"+ assert "429" in (outcome.detail or "")++def test_reddit_discovery_adapter_preserves_partial_feed_errors():item = {"url": "https://reddit.com/r/example/comments/1",diff --git a/tests/test_doctor.py b/tests/test_doctor.pyindex b430e8d4..b523194f 100644--- a/tests/test_doctor.py+++ b/tests/test_doctor.py@@ -22,12 +22,13 @@ import osimport sysimport tempfileimport unittest+import urllib.errorfrom contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Pathfrom unittest import mockimport last30days as cli-from lib import backends, doctor, health, prescriptions+from lib import backends, doctor, health, http, prescriptionsBIRD_STATUS_OFF = {"installed": False,@@ -959,6 +960,54 @@ class LiveProbe(unittest.TestCase):def test_probe_source_credit_gated_returns_none(self):self.assertIsNone(doctor._probe_source("tiktok", {}, 5))+ def test_reddit_probe_targets_the_endpoint_the_engine_uses(self):+ # /r/all/hot.json is permanently 403 keyless and no lane requests it;+ # probing it certified an endpoint the engine had abandoned (#899).+ url = doctor._HTTP_PROBE_URLS["reddit"]+ self.assertIn("search.rss", url)+ self.assertNotIn("hot.json", url)++ def _probe_reddit_with_status(self, code):+ error = urllib.error.HTTPError(+ doctor._HTTP_PROBE_URLS["reddit"], code, "Blocked", {}, None+ )+ with mock.patch(+ "lib.doctor.urllib.request.urlopen", side_effect=error+ ):+ return doctor._probe_source("reddit", {}, 5)++ def test_reddit_probe_403_is_not_reachable(self):+ res = self._probe_reddit_with_status(403)+ self.assertFalse(res["ok"])+ self.assertIn("403", res["detail"])++ def test_reddit_probe_429_is_not_reachable(self):+ res = self._probe_reddit_with_status(429)+ self.assertFalse(res["ok"])+ self.assertIn("429", res["detail"])++ def test_non_reddit_probe_keeps_4xx_as_reachable(self):+ # The blocked-status carve-out is per-source: a 4xx elsewhere still+ # means the endpoint responded.+ error = urllib.error.HTTPError(+ doctor._HTTP_PROBE_URLS["github"], 403, "Forbidden", {}, None+ )+ with mock.patch("lib.doctor.urllib.request.urlopen", side_effect=error):+ res = doctor._probe_source("github", {}, 5)+ self.assertTrue(res["ok"])++ def test_reddit_probe_sends_the_engine_user_agent(self):+ # Probing with a different UA measures the User-Agent, not the endpoint.+ seen = {}++ def capture(req, timeout=None):+ seen["ua"] = req.get_header("User-agent")+ raise urllib.error.HTTPError(req.full_url, 500, "boom", {}, None)++ with mock.patch("lib.doctor.urllib.request.urlopen", capture):+ doctor._probe_source("reddit", {}, 5)+ self.assertEqual(http.BROWSER_USER_AGENT, seen["ua"])+def test_probe_failure_is_isolated(self):def flaky(name, config, timeout):if name == "reddit":diff --git a/tests/test_reddit_transport_outcomes.py b/tests/test_reddit_transport_outcomes.pynew file mode 100644index 00000000..46bad8ca--- /dev/null+++ b/tests/test_reddit_transport_outcomes.py@@ -0,0 +1,102 @@+"""Reddit transport failures must not be reported as a clean no-results.++Regression coverage for issue #899: on a datacenter egress Reddit answers+429/403 on the keyless lanes, the adapters swallow that into an empty list, and+the run used to export ``"reddit": "no-results"`` with ``doctor --postmortem``+printing "No failures on the last run." These tests drive the real pipeline and+the real postmortem renderer over a mocked socket, so the whole chain --+capture sink -> source outcome -> postmortem bucket -- stays honest.+"""++import urllib.error+from unittest import mock++from lib import doctor, pipeline, schema+++def _plan(source):+ return {+ "intent": "general",+ "freshness_mode": "balanced_recent",+ "cluster_mode": "none",+ "source_weights": {source: 1.0},+ "subqueries": [{+ "label": "primary",+ "search_query": "claude code user feedback",+ "ranking_query": "claude code user feedback",+ "sources": [source],+ }],+ }+++def _run_reddit_against(error):+ runtime = schema.ProviderRuntime("local", "test-planner", "test-reranker")+ with mock.patch.object(+ pipeline.providers, "resolve_runtime", return_value=(runtime, mock.Mock())+ ), mock.patch.object(+ pipeline, "available_sources", return_value=["reddit"]+ ), mock.patch("lib.http.time.sleep"), mock.patch(+ "lib.http.urllib.request.urlopen", side_effect=error+ ):+ return pipeline.run(+ topic="claude code user feedback",+ config={"EXCLUDE_SOURCES": ""},+ depth="quick",+ requested_sources=["reddit"],+ mock=False,+ as_of_date="2026-07-10",+ external_plan=_plan("reddit"),+ )+++def _postmortem_from(report):+ return {+ "engine_version": "test",+ "mode": "postmortem",+ "present": True,+ "topic": report.topic,+ "at": report.generated_at,+ "outcomes": {+ source: schema.to_dict(outcome)+ for source, outcome in report.source_status.items()+ },+ }+++def test_reddit_rate_limit_is_not_reported_as_clean_no_results():+ report = _run_reddit_against(+ urllib.error.HTTPError(+ "https://www.reddit.com/search.rss", 429, "Too Many Requests", {}, None+ )+ )++ outcome = report.source_status["reddit"]+ assert outcome.state == schema.RATE_LIMITED+ assert "429" in (outcome.detail or "")+++def test_reddit_block_is_not_reported_as_clean_no_results():+ report = _run_reddit_against(+ urllib.error.HTTPError(+ "https://www.reddit.com/search.rss", 403, "Blocked", {}, None+ )+ )++ # 403 lands on auth-failed via http.classify_failure. The point of the test+ # is that a blocked host is a failure state at all, not which noun it gets.+ assert report.source_status["reddit"].state != schema.NO_RESULTS+++def test_postmortem_does_not_claim_success_after_a_reddit_block():+ report = _run_reddit_against(+ urllib.error.HTTPError(+ "https://www.reddit.com/search.rss", 429, "Too Many Requests", {}, None+ )+ )++ text = doctor.render_postmortem_text(_postmortem_from(report))++ assert "No failures on the last run." not in text+ assert "Succeeded: reddit" not in text+ assert "Failed:" in text+ assert schema.RATE_LIMITED in textdiff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.pyindex 573f42b3..98f1f69f 100644--- a/tests/test_source_outcomes.py+++ b/tests/test_source_outcomes.py@@ -4,7 +4,19 @@ from unittest.mock import MagicMock, patchimport pytest-from lib import bird_x, health, http, jobs, pipeline, reddit, render, schema, youtube_yt+from lib import (+ bird_x,+ health,+ http,+ jobs,+ pipeline,+ reddit,+ reddit_listing,+ reddit_rss,+ render,+ schema,+ youtube_yt,+)def _report(*, source_status=None, items_by_source=None, errors_by_source=None):@@ -138,6 +150,73 @@ def test_reddit_nested_worker_propagates_failure_capture(mock_urlopen, _mock_sleassert failures[-1].outcome_state == schema.RATE_LIMITED+def _reddit_429(url="https://www.reddit.com/search.rss"):+ return urllib.error.HTTPError(url, 429, "Too Many Requests", {}, None)+++@patch("lib.http.time.sleep")+@patch("lib.http.urllib.request.urlopen")+def test_reddit_rss_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):+ # get_text launders the 429 into None; the sink is what must survive the+ # ThreadPoolExecutor hop into the feed workers (issue #899).+ mock_urlopen.side_effect = _reddit_429()++ with http.capture_failures() as failures:+ posts = reddit_rss.search_rss("test topic", depth="quick")++ assert posts == []+ assert failures[-1].outcome_state == schema.RATE_LIMITED+++@patch("lib.http.time.sleep")+@patch("lib.http.urllib.request.urlopen")+def test_reddit_listing_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):+ mock_urlopen.side_effect = _reddit_429(+ "https://www.reddit.com/svc/shreddit/community-more-posts/hot/"+ )++ with http.capture_failures() as failures:+ posts = reddit_listing.fetch_listings(["example"], depth="quick", query="test topic")++ assert posts == []+ assert failures[-1].outcome_state == schema.RATE_LIMITED+++@patch("lib.http.time.sleep")+@patch("lib.http.urllib.request.urlopen")+def test_reddit_discovery_listing_fanout_propagates_failure_capture(mock_urlopen, _mock_sleep):+ mock_urlopen.side_effect = _reddit_429(+ "https://www.reddit.com/svc/shreddit/community-more-posts/rising/"+ )++ with http.capture_failures() as failures:+ result = reddit_listing.fetch_discovery_listings(["example"], query="test topic")++ assert result["items"] == []+ # The discovery path reads this list, not the sink — a blocked feed must not+ # look like an empty one there either.+ assert result["errors"]+ assert any("429" in error for error in result["errors"])+ assert failures[-1].outcome_state == schema.RATE_LIMITED+++@patch("lib.http.urllib.request.urlopen")+def test_tee_failures_does_not_hide_from_parent_sink(mock_urlopen):+ # tee_failures must never become capture_failures: the latter replaces the+ # sink, which would silently re-break the Reddit lanes above.+ mock_urlopen.side_effect = urllib.error.HTTPError(+ "https://api.example.com/missing", 404, "Not Found", {}, None+ )++ with http.capture_failures() as parent:+ with http.tee_failures() as local:+ with pytest.raises(http.HTTPError):+ http.get("https://api.example.com/missing", retries=1)++ assert len(local) == 1+ assert local == parent++@patch("lib.http.urllib.request.urlopen")def test_jobs_expected_probe_misses_do_not_degrade_final_result(mock_urlopen):miss = urllib.error.HTTPError(