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(x): report handle-lane failures instead of silent no-results (#1116)
Ilia Alshanetsky61baf4f9b768
diff --git a/changelog.d/+x-handle-lane-failure-channel.fixed.md b/changelog.d/+x-handle-lane-failure-channel.fixed.mdnew file mode 100644index 00000000..83892b2f--- /dev/null+++ b/changelog.d/+x-handle-lane-failure-channel.fixed.md@@ -0,0 +1 @@+A failed X handle lane is no longer reported as "the subject posted nothing". The bird and xquik FROM/ABOUT lanes signalled a per-handle failure by returning no items, and the pipeline hardcoded the auth flag to `False` for both backends, so a missing `node`, a bird-search timeout, or an unpaid xquik key produced an empty lane with no recorded outcome — indistinguishable from genuine silence. Both adapters now report the reason, the pipeline records it, and the lane's auth message names the backend that actually failed.diff --git a/skills/last30days/scripts/lib/bird_x.py b/skills/last30days/scripts/lib/bird_x.pyindex 353157e1..2fde220a 100644--- a/skills/last30days/scripts/lib/bird_x.py+++ b/skills/last30days/scripts/lib/bird_x.py@@ -124,6 +124,25 @@ def _log(msg: str):log.source_log("Bird", msg, tty_only=False)+def _scrub_credentials(text: str) -> str:+ """Redact X session cookie values from subprocess output.++ A failure reason built from bird-search's stderr reaches the run's+ ``source_status`` detail, which is rendered in the report and returned by+ ``--emit=json``. The vendored client receives AUTH_TOKEN/CT0 in its+ environment, so an error message that echoes a rejected cookie would+ otherwise carry it into user-facing output. Log lines get the same+ treatment because stderr is captured in agent harnesses.+ """+ scrubbed = text+ for name in ("AUTH_TOKEN", "CT0", "TWITTER_AUTH_TOKEN", "TWITTER_CT0"):+ value = _credentials.get(name) or os.environ.get(name)+ # Short values would match too much ordinary text to be worth it.+ if value and len(value) >= 8:+ scrubbed = scrubbed.replace(value, "<redacted>")+ return scrubbed++def classify_run_failure(detail: str) -> str:"""Map Bird's subprocess-only failure shapes to run outcome states."""text = detail.lower()@@ -516,6 +535,7 @@ def search_handles(topic: Optional[str],from_date: str,count_per: int = 5,+ failure_out: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""Search specific X handles for topic-related content.@@ -530,12 +550,19 @@ def search_handles(topic: Search topic — used for relevance ranking only, not the queryfrom_date: Start date (YYYY-MM-DD)count_per: Results to request per handle+ failure_out: When provided, a short reason is appended for every+ per-handle failure branch, so the caller can distinguish a+ transport failure from a handle that genuinely posted nothing.Returns:List of raw item dicts (same format as parse_bird_response output)."""core_topic = _extract_core_subject(topic) if topic else None+ def _note(msg: str) -> None:+ if failure_out is not None:+ failure_out.append(msg)+def _search_one_handle(handle: str) -> List[Dict[str, Any]]:handle = handle.lstrip("@")# Always unfiltered: pull the timeline, rank by topic relevance below.@@ -552,15 +579,21 @@ def search_handles(result = subproc.run_with_timeout(cmd, timeout=15, env=_subprocess_env())except subproc.SubprocTimeout:_log(f"Handle search timed out for @{handle}")+ _note(f"@{handle}: bird-search timed out after 15s")return []except OSError as e:_log(f"Handle search error for @{handle}: {e}")+ _note(f"@{handle}: could not spawn bird-search ({e})")return []output = result.stdout.strip()if result.returncode != 0:if not output:- _log(f"Handle search failed for @{handle}: {result.stderr.strip()}")+ _log(f"Handle search failed for @{handle}: {_scrub_credentials(result.stderr.strip())}")+ _note(+ f"@{handle}: bird-search exited {result.returncode} "+ f"({_scrub_credentials(result.stderr.strip())[:160] or 'no stderr'})"+ )return []# Windows/Node 24: benign libuv assertion can cause non-zero exit# AFTER valid JSON is written to stdout. Trust stdout content.@@ -572,6 +605,7 @@ def search_handles(response = json.loads(output)except json.JSONDecodeError:_log(f"Invalid JSON from handle search for @{handle}")+ _note(f"@{handle}: bird-search returned invalid JSON")return []items = parse_bird_response(response, query=core_topic)# Log on success/empty too (not only on failure): a silent handle search@@ -594,6 +628,7 @@ def search_mentions(handles: List[str],from_date: str,count_per: int = 5,+ failure_out: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""Search for tweets ABOUT/TO each handle — the mention lane.@@ -606,10 +641,17 @@ def search_mentions(handles: List of X handles (without @)from_date: Start date (YYYY-MM-DD)count_per: Results to request per handle+ failure_out: When provided, a short reason is appended for every+ per-handle failure branch, so the caller can distinguish a+ transport failure from a handle nobody mentioned.Returns:List of raw item dicts (same format as parse_bird_response output)."""+ def _note(msg: str) -> None:+ if failure_out is not None:+ failure_out.append(msg)+def _search_one(handle: str) -> List[Dict[str, Any]]:handle = handle.lstrip("@")query = f"@{handle} since:{from_date}"@@ -623,12 +665,18 @@ def search_mentions(result = subproc.run_with_timeout(cmd, timeout=15, env=_subprocess_env())except subproc.SubprocTimeout:_log(f"Mention search timed out for @{handle}")+ _note(f"@{handle}: bird-search timed out after 15s")return []except OSError as e:_log(f"Mention search error for @{handle}: {e}")+ _note(f"@{handle}: could not spawn bird-search ({e})")return []if result.returncode != 0:- _log(f"Mention search failed for @{handle}: {result.stderr.strip()}")+ _log(f"Mention search failed for @{handle}: {_scrub_credentials(result.stderr.strip())}")+ _note(+ f"@{handle}: bird-search exited {result.returncode} "+ f"({_scrub_credentials(result.stderr.strip())[:160] or 'no stderr'})"+ )return []output = result.stdout.strip()if not output:@@ -637,6 +685,7 @@ def search_mentions(response = json.loads(output)except json.JSONDecodeError:_log(f"Invalid JSON from mention search for @{handle}")+ _note(f"@{handle}: bird-search returned invalid JSON")return []items = parse_bird_response(response, query=None)# ABOUT lane = OTHERS mentioning the handle. Drop the handle's own tweetsdiff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 82fb0607..722ff777 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -3997,6 +3997,40 @@ def _run_supplemental_searches(# with the user's browser cookies; xquik runs the same lanes over its REST# API. All items land under the single "x" slug.x_slug = "x"++ def _record_handle_lane_failures(lane: str, failures: list[str]) -> bool:+ """Surface handle-lane failures the adapter would otherwise swallow.++ bird and xquik report a per-handle failure by returning no items, so an+ empty lane is indistinguishable from a subject who simply did not post.+ Left unrecorded, the run reports the X source as a clean zero and the+ report states as fact that nothing was posted.++ Returns True when the failure is auth-shaped, so the caller's existing+ AUTH_FAILED branch owns the message and the fix hint. Everything else+ (timeout, spawn failure, non-zero exit, bad JSON) is recorded here.+ ``record_failure`` keeps already-returned items as partial.+ """+ if not failures:+ return False+ detail = "; ".join(failures[:3])+ if len(failures) > 3:+ detail += f" (+{len(failures) - 3} more)"+ # Only xquik reports an auth-shaped handle-lane failure; bird's are all+ # transport (timeout / spawn / exit / JSON). Match the two phrases+ # xquik._execute_search actually emits rather than adding a fifth+ # copy of this repo's auth-marker vocabulary.+ lowered = detail.lower()+ if "auth failed" in lowered or "key unpaid" in lowered:+ return True+ bundle.record_failure(+ x_slug,+ health.UNREACHABLE,+ f"Phase 2 {lane}-lane: {detail}",+ attempted=True,+ )+ return False+chain = env.x_backend_chain(config)# Trust an explicit runtime backend as the head of the chain.pinned = runtime.x_search_backend@@ -4045,10 +4079,18 @@ def _run_supplemental_searches(elif primary == "bird":def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:# bird_x.search_handles doesn't support and_topic yet- return bird_x.search_handles(hs, topic, from_date, count_per=count), False+ failures: list[str] = []+ items = bird_x.search_handles(+ hs, topic, from_date, count_per=count, failure_out=failures,+ )+ return items, _record_handle_lane_failures("FROM", failures)def _about_lane(hs: list, count: int) -> tuple[list, bool]:- return bird_x.search_mentions(hs, from_date, count_per=count), False+ failures: list[str] = []+ items = bird_x.search_mentions(+ hs, from_date, count_per=count, failure_out=failures,+ )+ return items, _record_handle_lane_failures("ABOUT", failures)elif primary == "xapi":# Direct X API v2 with the app-only bearer: from:/@ lanes run over# search/all with the recent-search fallback. One budget shared by@@ -4090,10 +4132,20 @@ def _run_supplemental_searches(def _from_lane(hs: list, count: int, and_topic: bool = False) -> tuple[list, bool]:# xquik.search_handles doesn't support and_topic yet- return xquik.search_handles(hs, topic, from_date, to_date, count_per=count, token=xquik_token), False+ failures: list[str] = []+ items = xquik.search_handles(+ hs, topic, from_date, to_date, count_per=count, token=xquik_token,+ failure_out=failures,+ )+ return items, _record_handle_lane_failures("FROM", failures)def _about_lane(hs: list, count: int) -> tuple[list, bool]:- return xquik.search_mentions(hs, from_date, to_date, topic=topic, count_per=count, token=xquik_token), False+ failures: list[str] = []+ items = xquik.search_mentions(+ hs, from_date, to_date, topic=topic, count_per=count,+ token=xquik_token, failure_out=failures,+ )+ return items, _record_handle_lane_failures("ABOUT", failures)else:return # primary X backend has no handle-lane support (xai/xurl) or none configured@@ -4152,7 +4204,7 @@ def _run_supplemental_searches(any_revoked = Truebundle.record_failure(x_slug, schema.AUTH_FAILED,- "Phase 2 FROM-lane (explicit): grok session expired or was revoked",+ f"Phase 2 FROM-lane (explicit): {primary} authentication failed (session expired, revoked, or key unpaid)",attempted=True,)except Exception as exc:@@ -4171,7 +4223,7 @@ def _run_supplemental_searches(any_revoked = Truebundle.record_failure(x_slug, schema.AUTH_FAILED,- "Phase 2 FROM-lane (extracted): grok session expired or was revoked",+ f"Phase 2 FROM-lane (extracted): {primary} authentication failed (session expired, revoked, or key unpaid)",attempted=True,)except Exception as exc:@@ -4189,7 +4241,7 @@ def _run_supplemental_searches(any_revoked = Truebundle.record_failure(x_slug, schema.AUTH_FAILED,- "Phase 2 ABOUT-lane: grok session expired or was revoked",+ f"Phase 2 ABOUT-lane: {primary} authentication failed (session expired, revoked, or key unpaid)",attempted=True,)except Exception as exc:@@ -4209,7 +4261,7 @@ def _run_supplemental_searches(any_revoked = Truebundle.record_failure(x_slug, schema.AUTH_FAILED,- "Phase 2 NAME-lane: grok session expired or was revoked",+ f"Phase 2 NAME-lane: {primary} authentication failed (session expired, revoked, or key unpaid)",attempted=True,)except Exception as exc:@@ -4275,7 +4327,7 @@ def _run_supplemental_searches(any_revoked = Truebundle.record_failure(x_slug, schema.AUTH_FAILED,- "Phase 2 related handle search: grok session expired or was revoked",+ f"Phase 2 related handle search: {primary} authentication failed (session expired, revoked, or key unpaid)",attempted=True,)except Exception as exc:diff --git a/skills/last30days/scripts/lib/xquik.py b/skills/last30days/scripts/lib/xquik.pyindex 126fcc6a..b4f31e09 100644--- a/skills/last30days/scripts/lib/xquik.py+++ b/skills/last30days/scripts/lib/xquik.py@@ -128,12 +128,18 @@ def _execute_search(seen_ids: set[str],relevance_query: str,index_offset: int = 0,+ failure_out: Optional[List[str]] = None,) -> tuple[List[Dict[str, Any]], str | None]:"""Run one Xquik search call and parse its tweets.Returns ``(items, auth_error)``. ``auth_error`` is a non-empty string onlyon a fatal auth/payment failure (401/403); transient/HTTP errors log andreturn ``([], None)`` so one bad lane never discards another's results.++ Non-fatal failures (429, 5xx, network error, unparseable payload) append a+ reason to ``failure_out`` instead. They stay out of the return value+ because the caller must keep going to the next handle, but a caller that+ stopped there would report the lane as empty rather than as failed.``relevance_query`` (the topic) is what items are scored against — for thehandle lanes that differs from the search query (``from:handle``).``index_offset`` keeps item ids unique across multiple calls that share an@@ -156,13 +162,22 @@ def _execute_search(if status in (401, 403):return [], f"Xquik auth failed ({status})"_log(f"HTTP error for '{label}': {exc}")+ if failure_out is not None:+ failure_out.append(f"Xquik HTTP error for '{label}': {exc}")return [], Noneexcept Exception as exc:_log(f"Error for '{label}': {exc}")+ if failure_out is not None:+ failure_out.append(f"Xquik request failed for '{label}': {exc}")return [], Nonetweets = response.get("tweets", [])if not isinstance(tweets, list):+ if failure_out is not None:+ failure_out.append(+ f"Xquik returned no tweets array for '{label}' "+ f"(got {type(tweets).__name__})"+ )return [], Noneitems: List[Dict[str, Any]] = []for tweet in tweets:@@ -192,12 +207,18 @@ def search_handles(*,count_per: int = 8,token: str = "",+ failure_out: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""FROM lane: tweets authored BY each handle (their own timeline).The topic is NOT AND'd into the query (that was the from:-AND bug, #610) —we pull the raw timeline and use ``topic`` for relevance ranking only.Returns a flat list of item dicts (mirrors ``bird_x.search_handles``).++ When ``failure_out`` is provided, any failure reason is appended — the+ fatal auth/payment one that stops the lane, and the per-handle transient+ ones (429, 5xx, network, unparseable payload) that do not — so the caller+ can distinguish a failed request from a handle that posted nothing."""if not token or not handles:return []@@ -213,9 +234,15 @@ def search_handles(label=f"from:{handle}", id_prefix="XF",seen_ids=seen_ids, relevance_query=topic,index_offset=len(items),+ failure_out=failure_out,)if auth_error:- break # fatal auth/payment failure — stop, keep what we have+ # Fatal auth/payment failure — stop, keep what we have. Surface the+ # reason: an empty FROM lane is otherwise indistinguishable from a+ # subject who simply did not post.+ if failure_out is not None:+ failure_out.append(auth_error)+ breakitems.extend(got)return items@@ -228,11 +255,17 @@ def search_mentions(topic: str = "",count_per: int = 5,token: str = "",+ failure_out: Optional[List[str]] = None,) -> List[Dict[str, Any]]:"""ABOUT lane: tweets mentioning each handle, authored by OTHERS.Queries ``@handle`` then drops the handle's own tweets (``_is_own``) so onlythird-party mentions remain. Returns a flat list of item dicts.++ When ``failure_out`` is provided, any failure reason is appended — the+ fatal auth/payment one that stops the lane, and the per-handle transient+ ones (429, 5xx, network, unparseable payload) that do not — so the caller+ can distinguish a failed request from a handle nobody mentioned."""if not token or not handles:return []@@ -248,8 +281,11 @@ def search_mentions(label=f"@{handle}", id_prefix="XA",seen_ids=seen_ids, relevance_query=topic,index_offset=len(items),+ failure_out=failure_out,)if auth_error:+ if failure_out is not None:+ failure_out.append(auth_error)breakitems.extend(it for it in got if not _is_own(it.get("url", ""), handle))return itemsdiff --git a/tests/test_bird_x.py b/tests/test_bird_x.pyindex f02e0ea2..04bb621a 100644--- a/tests/test_bird_x.py+++ b/tests/test_bird_x.py@@ -7,6 +7,7 @@ import unittestfrom pathlib import Pathfrom unittest import mock+from lib import bird_xfrom lib.bird_x import parse_bird_responseREPO_ROOT = Path(__file__).resolve().parents[1]@@ -696,3 +697,40 @@ class LeadingMentionsTests(unittest.TestCase):if __name__ == "__main__":unittest.main()+++class CredentialScrubInFailureDetailTests(unittest.TestCase):+ """A handle-lane failure reason is recorded in the run's source_status and+ rendered in the report, so subprocess stderr must not carry the X session+ cookies into user-facing output."""++ def tearDown(self):+ bird_x._credentials.clear()++ def test_injected_cookie_values_are_redacted_from_notes(self):+ bird_x.set_credentials("auth-token-sentinel-value", "ct0-sentinel-value")+ failures: list[str] = []+ proc = mock.Mock(+ returncode=1,+ stdout="",+ stderr="rejected cookie auth_token=auth-token-sentinel-value ct0=ct0-sentinel-value",+ )+ with mock.patch.object(bird_x.subproc, "run_with_timeout", return_value=proc):+ bird_x.search_handles(+ ["someone"], "topic", "2026-05-19", count_per=1,+ failure_out=failures,+ )+ joined = " ".join(failures)+ assert failures, "a non-zero exit must be reported"+ self.assertNotIn("auth-token-sentinel-value", joined)+ self.assertNotIn("ct0-sentinel-value", joined)+ self.assertIn("<redacted>", joined)+ # The actionable part of the reason survives.+ self.assertIn("exited 1", joined)++ def test_scrub_leaves_ordinary_stderr_intact(self):+ bird_x.set_credentials("auth-token-sentinel-value", "ct0-sentinel-value")+ self.assertEqual(+ "connect ETIMEDOUT 104.244.42.1:443",+ bird_x._scrub_credentials("connect ETIMEDOUT 104.244.42.1:443"),+ )diff --git a/tests/test_pipeline_v3.py b/tests/test_pipeline_v3.pyindex 945f3d32..c6c6ff97 100644--- a/tests/test_pipeline_v3.py+++ b/tests/test_pipeline_v3.py@@ -7,6 +7,7 @@ from lib import fanoutfrom lib import httpfrom lib import pipelinefrom lib import schema+from lib import subprocclass DepthSettingsOverrideTests(unittest.TestCase):@@ -1443,6 +1444,113 @@ class TestSupplementalSearches(unittest.TestCase):x_urls = {item.url for item in bundle.items_by_source.get("x", [])}self.assertIn("https://x.com/analyst1/status/888", x_urls)+ @patch("lib.env.get_xquik_token", return_value="k")+ @patch("lib.env.x_backend_chain", return_value=["xquik"])+ @patch("lib.xquik._execute_search", return_value=([], "Xquik key unpaid: payment required (402)"))+ @patch("lib.entity_extract.extract_entities")+ def test_xquik_handle_lane_auth_failure_reaches_source_status(+ self, mock_extract, _mock_exec, *_patches+ ):+ """An unpaid xquik key produced an empty FROM lane and no outcome, so+ the run reported X as a clean zero and the report stated as fact that+ the subject posted nothing."""+ mock_extract.return_value = {+ "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],+ }+ bundle = schema.RetrievalBundle()+ bundle.items_by_source["x"] = [+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1",+ author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2",+ author="analyst1", body="AI safety research"),+ ]++ pipeline._run_supplemental_searches(+ topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},+ depth="default", date_range=("2026-02-15", "2026-03-17"),+ runtime=_make_runtime(None), mock=False,+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),+ )++ outcome = bundle.source_status.get("x")+ self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")+ self.assertEqual(schema.AUTH_FAILED, outcome.state)+ self.assertTrue(outcome.attempted)++ @patch("lib.env.get_xquik_token", return_value="k")+ @patch("lib.env.x_backend_chain", return_value=["xquik"])+ @patch("lib.xquik.http.get")+ @patch("lib.entity_extract.extract_entities")+ def test_xquik_handle_lane_rate_limit_reaches_source_status(+ self, mock_extract, mock_get, *_patches+ ):+ """A 429 is not an auth failure, so it took the non-fatal path inside+ _execute_search and reported nothing at all: the lane came back empty+ with no outcome and the run called it genuine silence."""+ mock_extract.return_value = {+ "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],+ }+ mock_get.side_effect = http.HTTPError(+ "HTTP 429: Too Many Requests", status_code=429,+ )+ bundle = schema.RetrievalBundle()+ bundle.items_by_source["x"] = [+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1",+ author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2",+ author="analyst1", body="AI safety research"),+ ]++ pipeline._run_supplemental_searches(+ topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},+ depth="default", date_range=("2026-02-15", "2026-03-17"),+ runtime=_make_runtime(None), mock=False,+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),+ )++ outcome = bundle.source_status.get("x")+ self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")+ # PARTIAL rather than AUTH_FAILED: a 429 is transient, and Phase 1+ # items survived, so record_failure keeps them and marks the source.+ self.assertEqual(schema.PARTIAL, outcome.state)+ self.assertIn("429", outcome.detail)++ @patch("lib.env.x_backend_chain", return_value=["bird"])+ @patch("lib.bird_x.search_mentions", return_value=[])+ @patch("lib.bird_x.subproc.run_with_timeout")+ @patch("lib.entity_extract.extract_entities")+ def test_bird_handle_lane_transport_failure_reaches_source_status(+ self, mock_extract, mock_run, *_patches+ ):+ """Same defect on the bird path: a bird-search timeout returned no+ items and no outcome, so an unreachable lane looked like silence."""+ mock_extract.return_value = {+ "x_handles": ["analyst1"], "x_hashtags": [], "reddit_subreddits": [],+ }+ mock_run.side_effect = subproc.SubprocTimeout("timed out")+ bundle = schema.RetrievalBundle()+ bundle.items_by_source["x"] = [+ _make_source_item("x", "X1", "https://x.com/analyst1/status/1",+ author="analyst1", body="AI safety analysis"),+ _make_source_item("x", "X2", "https://x.com/analyst1/status/2",+ author="analyst1", body="AI safety research"),+ ]++ pipeline._run_supplemental_searches(+ topic="AI safety", bundle=bundle, plan=_make_plan("AI safety"), config={},+ depth="default", date_range=("2026-02-15", "2026-03-17"),+ runtime=_make_runtime(None), mock=False,+ rate_limited_sources=set(), rate_limit_lock=threading.Lock(),+ )++ outcome = bundle.source_status.get("x")+ self.assertIsNotNone(outcome, "x outcome must exist, not a silent zero")+ # PARTIAL, not UNREACHABLE: X delivered Phase 1 items and only the+ # Phase 2 handle lane failed, which is what record_failure encodes.+ self.assertEqual(schema.PARTIAL, outcome.state)+ self.assertIn("timed out", outcome.detail)+ self.assertIn("@analyst1", outcome.detail)+@patch("lib.bird_x.search_handles")@patch("lib.entity_extract.extract_entities")def test_supplemental_items_deduplicated_by_url(self, mock_extract, mock_handles):diff --git a/tests/test_xquik.py b/tests/test_xquik.pyindex fcf9b818..2c6bec58 100644--- a/tests/test_xquik.py+++ b/tests/test_xquik.py@@ -360,6 +360,78 @@ class TestFromLane(unittest.TestCase):self.assertEqual(len(ids), len(set(ids)))+class TestHandleLaneNonFatalFailures(unittest.TestCase):+ """A 429/5xx, a network error, or a junk payload emptied the lane without+ appending anything to failure_out, so the pipeline recorded a genuine+ no-results and the report said the subject posted nothing."""++ def test_rate_limit_is_reported_not_silent(self):+ from lib import http as http_mod+ from lib import xquik+ failures: list[str] = []+ with patch("lib.xquik.http.get",+ side_effect=http_mod.HTTPError("HTTP 429: Too Many Requests", status_code=429)):+ items = xquik.search_handles(["h1"], "topic", "2026-05-19", "2026-06-18",+ token="k", failure_out=failures)+ self.assertEqual([], items)+ self.assertEqual(1, len(failures))+ self.assertIn("from:h1", failures[0])+ self.assertIn("429", failures[0])++ def test_network_error_is_reported_not_silent(self):+ from lib import xquik+ failures: list[str] = []+ with patch("lib.xquik.http.get", side_effect=OSError("connection reset")):+ items = xquik.search_mentions(["h1"], "2026-05-19", "2026-06-18",+ topic="topic", token="k", failure_out=failures)+ self.assertEqual([], items)+ self.assertEqual(1, len(failures))+ self.assertIn("@h1", failures[0])+ self.assertIn("connection reset", failures[0])++ def test_unparseable_payload_is_reported_not_silent(self):+ from lib import xquik+ failures: list[str] = []+ with patch("lib.xquik.http.get", return_value={"tweets": "not-a-list"}):+ items = xquik.search_handles(["h1"], "topic", "2026-05-19", "2026-06-18",+ token="k", failure_out=failures)+ self.assertEqual([], items)+ self.assertEqual(1, len(failures))+ self.assertIn("from:h1", failures[0])++ def test_one_bad_handle_does_not_stop_the_next(self):+ # Non-fatal failures must be noted without aborting the lane, or a+ # transient error on the first handle would discard the second's items.+ from lib import http as http_mod+ from lib import xquik+ failures: list[str] = []+ responses = [+ http_mod.HTTPError("HTTP 503: Service Unavailable", status_code=503),+ {"tweets": [{"id": "2", "text": "b", "createdAt": "2026-06-15T12:00:00Z",+ "author": {"username": "h2"}}]},+ ]+ with patch("lib.xquik.http.get", side_effect=responses):+ items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19",+ "2026-06-18", token="k", failure_out=failures)+ self.assertEqual(1, len(items))+ self.assertEqual(1, len(failures))+ self.assertIn("from:h1", failures[0])++ def test_fatal_auth_failure_still_stops_the_lane(self):+ # The pre-existing fatal path must keep its break semantics: an unpaid+ # key is not worth retrying per handle.+ from lib import http as http_mod+ from lib import xquik+ failures: list[str] = []+ with patch("lib.xquik.http.get",+ side_effect=http_mod.HTTPError("Payment Required", status_code=402)) as m:+ items = xquik.search_handles(["h1", "h2"], "topic", "2026-05-19",+ "2026-06-18", token="k", failure_out=failures)+ self.assertEqual([], items)+ self.assertEqual(1, m.call_count)+ self.assertEqual(["Xquik key unpaid: payment required (402)"], failures)++class TestAboutLane(unittest.TestCase):def test_mentions_drop_own_tweets(self):from lib import xquik