Skip to content

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

fix(pipeline): harden failure classification (#1164)

Ilia Alshanetsky5ae8ae034315
diff --git a/changelog.d/+failure-classifiers.fixed.md b/changelog.d/+failure-classifiers.fixed.md
new file mode 100644
index 00000000..6e5d7459
--- /dev/null
+++ b/changelog.d/+failure-classifiers.fixed.md
@@ -0,0 +1 @@
+Tightened source failure classification: 429/5xx status matching no longer false-positives on embedded digits, the stream exception path keeps the most specific failure (auth over rate-limit), X URLs keep path/query case when deduping, and an unconfigured X backend reads as skipped rather than failed.
diff --git a/skills/last30days/scripts/lib/fusion.py b/skills/last30days/scripts/lib/fusion.py
index 29c8c593..ca7cad4c 100644
--- a/skills/last30days/scripts/lib/fusion.py
+++ b/skills/last30days/scripts/lib/fusion.py
@@ -28,17 +28,17 @@ def _candidate_sort_key(c: schema.Candidate) -> tuple:
def _normalize_url(url: str) -> str:
- """Normalize URL for dedup: lowercase, strip www/old/m prefixes, remove tracking params."""
- parsed = urlparse(url.strip().lower())
- netloc = parsed.netloc
+ """Normalize URL for dedup: lowercase host, strip www/old/m prefixes, remove tracking params."""
+ parsed = urlparse(url.strip())
+ netloc = parsed.netloc.lower()
for prefix in ("www.", "old.", "m."):
if netloc.startswith(prefix):
netloc = netloc[len(prefix):]
# Strip tracking params
params = parse_qs(parsed.query)
- clean_params = {k: v for k, v in params.items() if not k.startswith("utm_")}
+ clean_params = {k: v for k, v in params.items() if not k.lower().startswith("utm_")}
query = urlencode(clean_params, doseq=True)
- return urlunparse((parsed.scheme, netloc, parsed.path.rstrip("/"), "", query, ""))
+ return urlunparse((parsed.scheme.lower(), netloc, parsed.path.rstrip("/"), "", query, ""))
def candidate_key(item: schema.SourceItem) -> str:
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index cd7bbd4c..82fb0607 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -3538,11 +3538,41 @@ def _warnings(
return warnings
+_STATUS_PREFIX = r"\b(?:https?(?:/\d(?:\.\d)?)?(?:\s+error)?|status(?:[\s_]*code)?|code)\s*[:=#]?\s*"
+
+
+def _mentions_status(msg: str, code_pattern: str, phrases: tuple[str, ...]) -> bool:
+ """True when ``msg`` names an HTTP status matching ``code_pattern``.
+
+ A bare number is not enough (``"batch 429 failed"`` is not a rate
+ limit): the code must follow an HTTP/status/code marker, or co-occur
+ with one of ``phrases`` (``"rate limited (429)"``). Digit-aware
+ boundaries keep ``"14293"`` from reading as a 429.
+ """
+ if not msg:
+ return False
+ code = r"(?:" + code_pattern + r")(?!\d)"
+ if re.search(_STATUS_PREFIX + code, msg, re.IGNORECASE):
+ return True
+ lowered = msg.lower()
+ return any(p in lowered for p in phrases) and re.search(r"(?<!\d)" + code, msg) is not None
+
+
+_RATE_LIMIT_PHRASES = ("rate limit", "rate-limit", "ratelimit", "too many requests")
+_SERVER_ERROR_PHRASES = (
+ "server error",
+ "bad gateway",
+ "service unavailable",
+ "gateway timeout",
+ "gateway time-out",
+)
+
+
def _is_rate_limit_error(exc: Exception) -> bool:
"""Detect 429 rate-limit errors by status code or message text."""
if hasattr(exc, "status_code") and getattr(exc, "status_code", None) == 429:
return True
- return "429" in str(exc)
+ return _mentions_status(str(exc), "429", _RATE_LIMIT_PHRASES)
class SourceRunError(RuntimeError):
@@ -3777,8 +3807,7 @@ def _is_transient_error(exc: Exception) -> bool:
status = getattr(exc, "status_code", None)
if isinstance(status, int) and 500 <= status < 600:
return True
- msg = str(exc)
- return any(code in msg for code in ("500", "502", "503", "504"))
+ return _mentions_status(str(exc), r"5\d\d", _SERVER_ERROR_PHRASES)
def _topic_handle_mentions(topic: str) -> set[str]:
@@ -4544,7 +4573,10 @@ def _retrieve_stream(*args, **kwargs) -> tuple[list[dict], dict]:
except Exception as exc:
recorded_exc = exc
if failures and not getattr(exc, "outcome_state", None):
- failure = failures[-1]
+ failure = min(
+ failures,
+ key=lambda f: _FAILURE_SPECIFICITY.get(f.outcome_state, 9),
+ )
recorded_exc = SourceRunError(str(exc), failure.outcome_state)
if module_backed:
http.fixture_source_record_error(fixture_request, recorded_exc)
@@ -4937,7 +4969,10 @@ def _retrieve_stream_impl(
if pinned:
chain = [pinned] + [b for b in chain if b != pinned]
if not chain:
- raise RuntimeError("No X backend is available.")
+ raise SourceRunError(
+ "No X backend is available (not configured).",
+ schema.SKIPPED_UNCONFIGURED,
+ )
last_error = ""
chain_errors: list[str] = []
items = []
diff --git a/tests/test_fusion_v3.py b/tests/test_fusion_v3.py
index 5d54340c..4efd80fd 100644
--- a/tests/test_fusion_v3.py
+++ b/tests/test_fusion_v3.py
@@ -429,10 +429,39 @@ class TestUrlNormalization(unittest.TestCase):
def test_case_insensitive(self):
from lib.fusion import _normalize_url
self.assertEqual(
- _normalize_url("https://Reddit.com/r/Test"),
+ _normalize_url("https://Reddit.com/r/test"),
_normalize_url("https://reddit.com/r/test"),
)
+ def test_path_case_preserved(self):
+ # CR-009: the path is case-sensitive; only the host lowercases.
+ from lib.fusion import _normalize_url
+ self.assertNotEqual(
+ _normalize_url("https://example.com/Page"),
+ _normalize_url("https://example.com/page"),
+ )
+
+ def test_query_case_preserved(self):
+ # CR-009: the query is case-sensitive; only the host lowercases.
+ from lib.fusion import _normalize_url
+ self.assertNotEqual(
+ _normalize_url("https://youtube.com/watch?v=ABC123"),
+ _normalize_url("https://youtube.com/watch?v=abc123"),
+ )
+
+ def test_uppercase_utm_params_stripped(self):
+ # Tracking params strip case-insensitively, so an uppercase
+ # UTM param does not poison the dedup key.
+ from lib.fusion import _normalize_url
+ self.assertEqual(
+ _normalize_url("https://example.com/page?UTM_SOURCE=x"),
+ _normalize_url("https://example.com/page"),
+ )
+ self.assertEqual(
+ _normalize_url("https://example.com/page?UTM_SOURCE=x"),
+ _normalize_url("https://example.com/page?utm_source=y"),
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.py
index 13c34836..945f3d32 100644
--- a/tests/test_pipeline_v3.py
+++ b/tests/test_pipeline_v3.py
@@ -659,6 +659,99 @@ class TestRateLimitSharing(unittest.TestCase):
exc = RuntimeError("Connection refused")
self.assertFalse(pipeline._is_rate_limit_error(exc))
+ def test_is_rate_limit_error_rejects_embedded_digits(self):
+ # CR-007: "14293" must not read as a 429.
+ exc = RuntimeError("request id 14293 failed")
+ self.assertFalse(pipeline._is_rate_limit_error(exc))
+
+ def test_is_rate_limit_error_detects_standalone_code(self):
+ exc = RuntimeError("failed with HTTP 429")
+ self.assertTrue(pipeline._is_rate_limit_error(exc))
+
+ def test_is_rate_limit_error_rejects_bare_number(self):
+ # A bare 429 with no HTTP/status/rate-limit marker is not a rate
+ # limit; misreading it skips the source for the rest of the run.
+ exc = RuntimeError("batch 429 failed")
+ self.assertFalse(pipeline._is_rate_limit_error(exc))
+
+ def test_is_rate_limit_error_accepts_real_message_shapes(self):
+ for msg in (
+ "HTTP 429: Too Many Requests",
+ "HTTP Error 429: Too Many Requests",
+ "xapi: http 429",
+ "status: 429",
+ "status_code=429",
+ "Reddit rate limited (429) fetching https://example.com",
+ "429 Too Many Requests",
+ ):
+ with self.subTest(msg=msg):
+ self.assertTrue(pipeline._is_rate_limit_error(RuntimeError(msg)))
+
+ def test_is_transient_error_rejects_embedded_digits(self):
+ # CR-023: "15003" must not read as a 500.
+ exc = RuntimeError("job 15003 failed")
+ self.assertFalse(pipeline._is_transient_error(exc))
+
+ def test_is_transient_error_detects_full_5xx_range(self):
+ for code in ("500", "501", "502", "503", "504", "505", "507", "508", "520", "524", "599"):
+ with self.subTest(code=code):
+ exc = RuntimeError(f"upstream failed with HTTP {code}")
+ self.assertTrue(pipeline._is_transient_error(exc))
+
+ def test_is_transient_error_rejects_bare_number(self):
+ exc = RuntimeError("job 500 rows failed")
+ self.assertFalse(pipeline._is_transient_error(exc))
+
+ def test_is_transient_error_accepts_real_message_shapes(self):
+ for msg in (
+ "HTTP 503: Service Unavailable",
+ "HTTP Error 502: Bad Gateway",
+ "HTTP/1.1 504 Gateway Timeout",
+ "error code 520",
+ "upstream returned 502 Bad Gateway",
+ ):
+ with self.subTest(msg=msg):
+ self.assertTrue(pipeline._is_transient_error(RuntimeError(msg)))
+
+ def test_is_transient_error_rejects_unrelated_error(self):
+ exc = RuntimeError("Connection refused")
+ self.assertFalse(pipeline._is_transient_error(exc))
+
+ def test_retrieve_stream_exception_path_prefers_specific_failure(self):
+ # CR-008: the exception path must use _FAILURE_SPECIFICITY, so an
+ # AUTH_FAILED captured earlier is not masked by a later 429.
+ from lib import schema as _schema
+
+ def boom(*_args, **_kwargs):
+ # Record into the enclosing capture sink: auth first, 429 last,
+ # so the old failures[-1] code would have picked RATE_LIMITED.
+ http._record_failure(http.HTTPError("HTTP 401", status_code=401))
+ http._record_failure(http.HTTPError("HTTP 429", status_code=429))
+ raise RuntimeError("stream blew up")
+
+ with patch("lib.pipeline._retrieve_stream_impl", side_effect=boom):
+ with self.assertRaises(pipeline.SourceRunError) as caught:
+ pipeline._retrieve_stream(
+ topic="test",
+ subquery=_schema.SubQuery(
+ label="test",
+ search_query="test query",
+ ranking_query="test query",
+ sources=["x"],
+ ),
+ source="other",
+ config={},
+ depth="quick",
+ date_range=("2026-02-15", "2026-03-17"),
+ runtime=_schema.ProviderRuntime(
+ reasoning_provider="mock",
+ planner_model="mock",
+ rerank_model="mock",
+ ),
+ mock=True,
+ )
+ self.assertEqual(caught.exception.outcome_state, _schema.AUTH_FAILED)
+
def test_retrieve_stream_skips_rate_limited_source(self):
"""_retrieve_stream should return empty when source is rate-limited."""
from lib import schema
diff --git a/tests/test_x_chain_failover.py b/tests/test_x_chain_failover.py
index e3b646c4..9559691f 100644
--- a/tests/test_x_chain_failover.py
+++ b/tests/test_x_chain_failover.py
@@ -212,3 +212,52 @@ def test_timeout_never_exceeds_the_remaining_budget(monkeypatch):
deadline=_time.monotonic() + remaining,
)
assert seen["timeout"] <= remaining
+
+
+def test_no_x_backend_is_skipped_unconfigured(monkeypatch):
+ """CR-025: an empty X chain must read as SKIPPED_UNCONFIGURED, not failure."""
+ from unittest.mock import patch
+
+ from lib import env, schema
+
+ monkeypatch.setattr(env, "x_backend_chain", lambda config: [])
+ subquery = schema.SubQuery(
+ label="test",
+ search_query="test query",
+ ranking_query="test query",
+ sources=["x"],
+ )
+ runtime = schema.ProviderRuntime(
+ reasoning_provider="mock",
+ planner_model="mock",
+ rerank_model="mock",
+ )
+ try:
+ pipeline._retrieve_stream_impl(
+ topic="test",
+ subquery=subquery,
+ source="x",
+ config={},
+ depth="quick",
+ date_range=("2026-02-15", "2026-03-17"),
+ runtime=runtime,
+ mock=False,
+ )
+ except pipeline.SourceRunError as exc:
+ assert exc.outcome_state == schema.SKIPPED_UNCONFIGURED
+ else:
+ raise AssertionError("empty X chain should raise SourceRunError")
+
+
+def test_no_x_backend_message_carries_skip_marker():
+ """The unconfigured-X error must match the _classify_source_failure skip marker."""
+ from lib import schema
+
+ state, attempted = pipeline._classify_source_failure(
+ pipeline.SourceRunError(
+ "No X backend is available (not configured).",
+ schema.SKIPPED_UNCONFIGURED,
+ )
+ )
+ assert state == schema.SKIPPED_UNCONFIGURED
+ assert attempted is False