| 1 | """Regression tests for PR 35: X backends & vendored bird-search reliability. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-139: grok_x JSON wrapper unwrapping with numeric id and multi-key prose fallback. |
| 5 | - HIGH-145: xai_x envelope null-safety (content/choices/message/text) & K/M/B engagement parsing. |
| 6 | - HIGH-146: x_judge LOW_SIGNAL_QUERY_TOKENS exclusion on planner ranking queries. |
| 7 | - HIGH-147: x_api full-archive 403 expected_misses isolation & conditional 7-day truncation warning. |
| 8 | - HIGH-148: x_api handle-lane error propagation into pipeline & pre-start deadline/cancel error. |
| 9 | - HIGH-149: xquik HTTP 429 early stop & non-auth failure reporting in search_xquik. |
| 10 | - HIGH-151: xurl_x explicit UTF-8 subprocess decoding under ASCII/C locale. |
| 11 | - HIGH-162: bird-search TweetWithVisibilityResults, TimelineReplaceEntry cursor, and null-safe parsing. |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import json |
| 17 | import os |
| 18 | import shutil |
| 19 | import stat |
| 20 | import subprocess |
| 21 | import threading |
| 22 | import urllib.error |
| 23 | from datetime import datetime, timezone |
| 24 | from io import BytesIO |
| 25 | from pathlib import Path |
| 26 | from unittest import mock |
| 27 | |
| 28 | import pytest |
| 29 | |
| 30 | from lib import grok_x, health, http, pipeline, schema, x_api, x_judge, xai_x, xquik, xurl_x |
| 31 | |
| 32 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 33 | BIRD_UTILS_TEST = REPO_ROOT / "tests" / "test_bird_search_utils.test.mjs" |
| 34 | HAS_NODE = shutil.which("node") is not None |
| 35 | |
| 36 | WINDOW = ("2026-07-14", "2026-08-13") |
| 37 | IN_WINDOW_ID = "2087568620465607078" # 2026-08-12T15:55:18Z |
| 38 | DUMMY_TOKEN = "dummy-x-bearer-secret-000" |
| 39 | FIXED_NOW = datetime(2026, 9, 8, 12, 0, 0, tzinfo=timezone.utc) |
| 40 | FROM = "2026-08-10" |
| 41 | TO = "2026-09-08" |
| 42 | |
| 43 | |
| 44 | def _grok_block( |
| 45 | post_id: str = IN_WINDOW_ID, |
| 46 | handle: str = "steipete", |
| 47 | created: str = "Wed, 12 Aug 2026 15:55:18 GMT", |
| 48 | likes: int = 1462, |
| 49 | text: str = "cli was a year ago.", |
| 50 | ) -> str: |
| 51 | return ( |
| 52 | f"id: {post_id}\n" |
| 53 | f"handle: {handle}\n" |
| 54 | f"created_at: {created}\n" |
| 55 | f"likes: {likes}\n" |
| 56 | f"reposts: 48\nreplies: 95\nquotes: 20\n" |
| 57 | f"text: {text}\n" |
| 58 | ) |
| 59 | |
| 60 | |
| 61 | def _xai_wrap(items: list[dict]) -> dict: |
| 62 | return { |
| 63 | "output": [ |
| 64 | { |
| 65 | "type": "message", |
| 66 | "content": [{"type": "output_text", "text": json.dumps({"items": items})}], |
| 67 | } |
| 68 | ] |
| 69 | } |
| 70 | |
| 71 | |
| 72 | def _make_source_item(source: str, item_id: str, url: str, author: str | None = None, body: str = ""): |
| 73 | return schema.SourceItem( |
| 74 | item_id=item_id, |
| 75 | source=source, |
| 76 | title=f"Item {item_id}", |
| 77 | body=body, |
| 78 | url=url, |
| 79 | author=author, |
| 80 | ) |
| 81 | |
| 82 | |
| 83 | def _make_plan(topic: str) -> schema.QueryPlan: |
| 84 | return schema.QueryPlan( |
| 85 | intent="exploration", |
| 86 | freshness_mode="balanced_recent", |
| 87 | cluster_mode="topic", |
| 88 | raw_topic=topic, |
| 89 | subqueries=[ |
| 90 | schema.SubQuery( |
| 91 | label="primary", |
| 92 | search_query=topic, |
| 93 | ranking_query=f"What recent evidence from the last 30 days is most relevant to {topic}?", |
| 94 | sources=["x"], |
| 95 | ) |
| 96 | ], |
| 97 | source_weights={"x": 1.0}, |
| 98 | ) |
| 99 | |
| 100 | |
| 101 | # --------------------------------------------------------------------------- |
| 102 | # HIGH-139: grok_x JSON CLI wrapper unwrapping & multi-key prose fallback |
| 103 | # --------------------------------------------------------------------------- |
| 104 | |
| 105 | |
| 106 | class TestHigh139GrokWrapperParsing: |
| 107 | @pytest.mark.parametrize("collection_key", ["posts", "items", "results", "data", "tweets"]) |
| 108 | def test_numeric_wrapper_id_unwraps_collection_keys_before_direct_post(self, collection_key): |
| 109 | envelope = { |
| 110 | "id": 42, |
| 111 | collection_key: [ |
| 112 | { |
| 113 | "url": f"https://x.com/steipete/status/{IN_WINDOW_ID}", |
| 114 | "text": "real post inside collection", |
| 115 | "likes": 120, |
| 116 | } |
| 117 | ], |
| 118 | } |
| 119 | items = grok_x.parse_x_response({"text": json.dumps(envelope)}, "steipete", *WINDOW) |
| 120 | assert len(items) == 1 |
| 121 | assert items[0]["author_handle"] == "steipete" |
| 122 | assert items[0]["url"] == f"https://x.com/steipete/status/{IN_WINDOW_ID}" |
| 123 | assert items[0]["engagement"]["likes"] == 120 |
| 124 | |
| 125 | def test_numeric_wrapper_id_unwraps_json_in_content_string(self): |
| 126 | inner_posts = json.dumps([ |
| 127 | { |
| 128 | "id": IN_WINDOW_ID, |
| 129 | "handle": "steipete", |
| 130 | "text": "wrapped JSON string payload", |
| 131 | "likes": 300, |
| 132 | } |
| 133 | ]) |
| 134 | envelope = {"id": 99, "content": inner_posts} |
| 135 | items = grok_x.parse_x_response({"text": json.dumps(envelope)}, "steipete", *WINDOW) |
| 136 | assert len(items) == 1 |
| 137 | assert items[0]["author_handle"] == "steipete" |
| 138 | assert items[0]["text"] == "wrapped JSON string payload" |
| 139 | |
| 140 | def test_numeric_wrapper_id_with_prose_blocks_in_content_not_misparsed_as_single_post(self): |
| 141 | envelope = {"id": 42, "content": _grok_block(text="prose inside numeric-id wrapper")} |
| 142 | items = grok_x.parse_x_response({"text": json.dumps(envelope)}, "steipete", *WINDOW) |
| 143 | assert len(items) == 1 |
| 144 | assert items[0]["author_handle"] == "steipete" |
| 145 | assert items[0]["url"].endswith(f"/{IN_WINDOW_ID}") |
| 146 | assert items[0]["text"] == "prose inside numeric-id wrapper" |
| 147 | |
| 148 | def test_wrapper_fallback_does_not_break_on_status_message_before_result(self): |
| 149 | envelope = { |
| 150 | "id": 7, |
| 151 | "message": "ok", |
| 152 | "result": _grok_block(text="found in result after ok message"), |
| 153 | } |
| 154 | items = grok_x.parse_x_response({"text": json.dumps(envelope)}, "steipete", *WINDOW) |
| 155 | assert len(items) == 1 |
| 156 | assert items[0]["author_handle"] == "steipete" |
| 157 | assert items[0]["text"] == "found in result after ok message" |
| 158 | |
| 159 | def test_wrapper_fallback_checks_output_after_non_post_message_and_nested_dict(self): |
| 160 | envelope = { |
| 161 | "message": "completed", |
| 162 | "text": "summary only", |
| 163 | "output": _grok_block(text="found in output key"), |
| 164 | } |
| 165 | items = grok_x.parse_x_response({"text": json.dumps(envelope)}, "steipete", *WINDOW) |
| 166 | assert len(items) == 1 |
| 167 | assert items[0]["text"] == "found in output key" |
| 168 | |
| 169 | nested = { |
| 170 | "id": 12, |
| 171 | "message": {"content": _grok_block(text="nested wrapper dict prose")}, |
| 172 | } |
| 173 | nested_items = grok_x.parse_x_response({"text": json.dumps(nested)}, "steipete", *WINDOW) |
| 174 | assert len(nested_items) == 1 |
| 175 | assert nested_items[0]["text"] == "nested wrapper dict prose" |
| 176 | |
| 177 | def test_direct_single_post_json_still_parses_and_placeholder_still_rejected(self): |
| 178 | single_post = { |
| 179 | "id": IN_WINDOW_ID, |
| 180 | "handle": "steipete", |
| 181 | "text": "direct single post object", |
| 182 | "likes": 55, |
| 183 | } |
| 184 | items = grok_x.parse_x_response({"text": json.dumps(single_post)}, "steipete", *WINDOW) |
| 185 | assert len(items) == 1 |
| 186 | assert items[0]["author_handle"] == "steipete" |
| 187 | assert items[0]["engagement"]["likes"] == 55 |
| 188 | |
| 189 | placeholder = { |
| 190 | "id": IN_WINDOW_ID, |
| 191 | "handle": "unknown", |
| 192 | "text": "fabricated", |
| 193 | } |
| 194 | assert grok_x.parse_x_response({"text": json.dumps(placeholder)}, "steipete", *WINDOW) == [] |
| 195 | |
| 196 | def test_real_tweet_embedding_json_in_text_is_not_hijacked_by_inner_snippet(self): |
| 197 | tweet_with_embedded_json = { |
| 198 | "id": IN_WINDOW_ID, |
| 199 | "author_handle": "alice", |
| 200 | "text": 'Debugging API payload: {"id": "123", "user": "bob", "text": "err"}', |
| 201 | "likes": 17, |
| 202 | } |
| 203 | items = grok_x.parse_x_response({"text": json.dumps(tweet_with_embedded_json)}, "alice", *WINDOW) |
| 204 | assert len(items) == 1 |
| 205 | assert items[0]["author_handle"] == "alice" |
| 206 | assert items[0]["url"] == f"https://x.com/alice/status/{IN_WINDOW_ID}" |
| 207 | assert "Debugging API payload:" in items[0]["text"] |
| 208 | |
| 209 | # Same protection when author uses `username` (no `author_handle`/`handle`/`url`), |
| 210 | # including when the embedded JSON lives in `content`. |
| 211 | username_tweet = { |
| 212 | "id": IN_WINDOW_ID, |
| 213 | "username": "alice", |
| 214 | "text": 'Debugging API payload: {"id": "123", "user": "bob", "text": "err"}', |
| 215 | } |
| 216 | items_u = grok_x.parse_x_response({"text": json.dumps(username_tweet)}, "alice", *WINDOW) |
| 217 | assert len(items_u) == 1 |
| 218 | assert items_u[0]["author_handle"] == "alice" |
| 219 | assert items_u[0]["url"] == f"https://x.com/alice/status/{IN_WINDOW_ID}" |
| 220 | |
| 221 | username_content_tweet = { |
| 222 | "id": IN_WINDOW_ID, |
| 223 | "username": "alice", |
| 224 | "content": 'Example payload: {"id": "123", "username": "bob", "text": "err"}', |
| 225 | "likes": 25, |
| 226 | } |
| 227 | items_uc = grok_x.parse_x_response({"text": json.dumps(username_content_tweet)}, "alice", *WINDOW) |
| 228 | assert len(items_uc) == 1 |
| 229 | assert items_uc[0]["author_handle"] == "alice" |
| 230 | assert items_uc[0]["url"] == f"https://x.com/alice/status/{IN_WINDOW_ID}" |
| 231 | assert "Example payload:" in items_uc[0]["text"] |
| 232 | |
| 233 | def test_wrapper_with_numeric_id_username_and_structured_result_still_unwraps(self): |
| 234 | structured_wrapper = { |
| 235 | "id": 42, |
| 236 | "username": "cli_bot", |
| 237 | "result": { |
| 238 | "posts": [ |
| 239 | { |
| 240 | "id": IN_WINDOW_ID, |
| 241 | "username": "alice", |
| 242 | "text": "wrapped inside structured result", |
| 243 | "likes": 77, |
| 244 | } |
| 245 | ] |
| 246 | }, |
| 247 | } |
| 248 | items = grok_x.parse_x_response({"text": json.dumps(structured_wrapper)}, "alice", *WINDOW) |
| 249 | assert len(items) == 1 |
| 250 | assert items[0]["author_handle"] == "alice" |
| 251 | assert items[0]["url"] == f"https://x.com/alice/status/{IN_WINDOW_ID}" |
| 252 | assert items[0]["text"] == "wrapped inside structured result" |
| 253 | |
| 254 | # Same wrapper inside a top-level JSON array must still unwrap result.posts |
| 255 | # instead of matching the wrapper object itself via _fields_from_json_obj. |
| 256 | array_of_wrappers = [{"type": "system", "message": "init"}, structured_wrapper] |
| 257 | items_arr = grok_x.parse_x_response({"text": json.dumps(array_of_wrappers)}, "alice", *WINDOW) |
| 258 | assert len(items_arr) == 1 |
| 259 | assert items_arr[0]["author_handle"] == "alice" |
| 260 | assert items_arr[0]["url"] == f"https://x.com/alice/status/{IN_WINDOW_ID}" |
| 261 | assert items_arr[0]["text"] == "wrapped inside structured result" |
| 262 | |
| 263 | def test_duplicate_post_prefers_more_complete_copy_regardless_of_order(self): |
| 264 | wrapped_stub = { |
| 265 | "type": "preview", |
| 266 | "result": [ |
| 267 | { |
| 268 | "url": f"https://x.com/steipete/status/{IN_WINDOW_ID}", |
| 269 | "text": "short", |
| 270 | } |
| 271 | ], |
| 272 | } |
| 273 | complete_post = { |
| 274 | "id": IN_WINDOW_ID, |
| 275 | "author_handle": "steipete", |
| 276 | "text": "steipete shipped the full post text with details.", |
| 277 | "likes": 1462, |
| 278 | "reposts": 48, |
| 279 | "replies": 95, |
| 280 | "quotes": 20, |
| 281 | "created_at": "Wed, 12 Aug 2026 15:55:18 GMT", |
| 282 | } |
| 283 | for payload in ([wrapped_stub, complete_post], [complete_post, wrapped_stub]): |
| 284 | items = grok_x.parse_x_response({"text": json.dumps(payload)}, "steipete", *WINDOW) |
| 285 | assert len(items) == 1 |
| 286 | assert items[0]["author_handle"] == "steipete" |
| 287 | assert items[0]["text"] == "steipete shipped the full post text with details." |
| 288 | assert items[0]["date"] == "2026-08-12" |
| 289 | assert items[0]["engagement"] == { |
| 290 | "likes": 1462, |
| 291 | "reposts": 48, |
| 292 | "replies": 95, |
| 293 | "quotes": 20, |
| 294 | } |
| 295 | assert items[0]["relevance"] > 0.0 |
| 296 | |
| 297 | def test_duplicate_post_id_with_different_authors_does_not_merge(self): |
| 298 | alice_post = { |
| 299 | "id": IN_WINDOW_ID, |
| 300 | "author_handle": "alice", |
| 301 | "text": "alice original post", |
| 302 | "likes": 12, |
| 303 | } |
| 304 | bob_post = { |
| 305 | "id": IN_WINDOW_ID, |
| 306 | "author_handle": "bob", |
| 307 | "text": "bob much longer conflicting text that must never be credited to alice", |
| 308 | "likes": 9999, |
| 309 | } |
| 310 | items = grok_x.parse_x_response({"text": json.dumps([alice_post, bob_post])}, "alice", *WINDOW) |
| 311 | assert len(items) == 1 |
| 312 | assert items[0]["author_handle"] == "alice" |
| 313 | assert items[0]["text"] == "alice original post" |
| 314 | assert items[0]["engagement"]["likes"] == 12 |
| 315 | |
| 316 | def test_as_int_handles_overflowing_counts_without_crashing_parse(self): |
| 317 | for raw in ("1e308K", "1e309", "9" * 400, "1" + "0" * 307 + "K"): |
| 318 | assert grok_x._as_int(raw) is None |
| 319 | |
| 320 | post = { |
| 321 | "id": IN_WINDOW_ID, |
| 322 | "author_handle": "steipete", |
| 323 | "text": "post with overflowing engagement count", |
| 324 | "likes": "1e308K", |
| 325 | "reposts": "1e309", |
| 326 | "replies": 7, |
| 327 | } |
| 328 | items = grok_x.parse_x_response({"text": json.dumps([post])}, "steipete", *WINDOW) |
| 329 | assert len(items) == 1 |
| 330 | assert items[0]["engagement"]["likes"] is None |
| 331 | assert items[0]["engagement"]["reposts"] is None |
| 332 | assert items[0]["engagement"]["replies"] == 7 |
| 333 | |
| 334 | def test_top_level_json_array_of_cli_wrappers_unwraps_prose_and_collections(self): |
| 335 | prose_stream = [ |
| 336 | {"type": "system", "message": "init"}, |
| 337 | {"type": "result", "id": 11, "result": _grok_block(text="from top-level array prose wrapper")}, |
| 338 | ] |
| 339 | items = grok_x.parse_x_response({"text": json.dumps(prose_stream)}, "steipete", *WINDOW) |
| 340 | assert len(items) == 1 |
| 341 | assert items[0]["author_handle"] == "steipete" |
| 342 | assert items[0]["text"] == "from top-level array prose wrapper" |
| 343 | |
| 344 | json_stream = [ |
| 345 | {"type": "system", "message": "init"}, |
| 346 | { |
| 347 | "type": "result", |
| 348 | "id": 12, |
| 349 | "posts": [ |
| 350 | { |
| 351 | "url": f"https://x.com/steipete/status/{IN_WINDOW_ID}", |
| 352 | "text": "from top-level array collection wrapper", |
| 353 | "likes": 42, |
| 354 | } |
| 355 | ], |
| 356 | }, |
| 357 | ] |
| 358 | items_json = grok_x.parse_x_response({"text": json.dumps(json_stream)}, "steipete", *WINDOW) |
| 359 | assert len(items_json) == 1 |
| 360 | assert items_json[0]["text"] == "from top-level array collection wrapper" |
| 361 | |
| 362 | |
| 363 | # --------------------------------------------------------------------------- |
| 364 | # HIGH-145: xai_x envelope null-safety & engagement/relevance robustness |
| 365 | # --------------------------------------------------------------------------- |
| 366 | |
| 367 | |
| 368 | class TestHigh145XaiXRobustParsing: |
| 369 | @pytest.mark.parametrize( |
| 370 | "raw,expected", |
| 371 | [ |
| 372 | ("1.2K", 1200), |
| 373 | ("2.3K", 2300), |
| 374 | ("39k", 39000), |
| 375 | ("1.5M", 1_500_000), |
| 376 | ("2B", 2_000_000_000), |
| 377 | ("1,462", 1462), |
| 378 | ("1,234,567", 1_234_567), |
| 379 | ("100.0", 100), |
| 380 | (0, 0), |
| 381 | ("", None), |
| 382 | ("N/A", None), |
| 383 | ("-5", None), |
| 384 | ("12abc", None), |
| 385 | ("inf", None), |
| 386 | ("NaN", None), |
| 387 | ("١٢٣", None), |
| 388 | ("9999B", None), |
| 389 | ("9" * 400, None), |
| 390 | (float("inf"), None), |
| 391 | (float("nan"), None), |
| 392 | (True, None), |
| 393 | (False, None), |
| 394 | ], |
| 395 | ) |
| 396 | def test_safe_int_abbreviated_commas_and_malformed_inputs(self, raw, expected): |
| 397 | assert xai_x._safe_int(raw) == expected |
| 398 | |
| 399 | def test_parse_x_response_handles_abbreviated_engagement_and_bad_relevance(self): |
| 400 | resp = _xai_wrap([ |
| 401 | { |
| 402 | "text": "viral post", |
| 403 | "url": f"https://x.com/steipete/status/{IN_WINDOW_ID}", |
| 404 | "author_handle": "steipete", |
| 405 | "engagement": { |
| 406 | "likes": "1.2K", |
| 407 | "reposts": "1,462", |
| 408 | "replies": "", |
| 409 | "quotes": "N/A", |
| 410 | }, |
| 411 | "relevance": "high", |
| 412 | } |
| 413 | ]) |
| 414 | items = xai_x.parse_x_response(resp, *WINDOW) |
| 415 | assert len(items) == 1 |
| 416 | assert items[0]["engagement"] == { |
| 417 | "likes": 1200, |
| 418 | "reposts": 1462, |
| 419 | "replies": None, |
| 420 | "quotes": None, |
| 421 | } |
| 422 | assert items[0]["relevance"] == 0.5 |
| 423 | |
| 424 | def test_non_dict_response_returns_empty(self): |
| 425 | for bad in (None, [], "string", 123): |
| 426 | assert xai_x.parse_x_response(bad, *WINDOW) == [] # type: ignore[arg-type] |
| 427 | |
| 428 | @pytest.mark.parametrize( |
| 429 | "malformed_envelope", |
| 430 | [ |
| 431 | {"output": [{"type": "message", "content": None}]}, |
| 432 | {"output": [{"type": "message", "content": 123}]}, |
| 433 | {"output": [{"type": "message", "content": [{"type": "output_text", "text": None}]}]}, |
| 434 | {"output": [{"type": "message", "content": [{"type": "output_text", "text": 42}]}]}, |
| 435 | {"output": [{"text": 123}]}, |
| 436 | {"choices": None}, |
| 437 | {"choices": [None]}, |
| 438 | {"choices": [{"message": None}]}, |
| 439 | {"choices": [{"message": "not-a-dict"}]}, |
| 440 | {"choices": [{"message": {"content": None}}]}, |
| 441 | {"choices": [{"message": {"content": 123}}]}, |
| 442 | {"output": [{"type": "message", "content": [{"type": "output_text", "text": '{"items": null}'}]}]}, |
| 443 | {"output": [{"type": "message", "content": [{"type": "output_text", "text": '{"items": "not-a-list"}'}]}]}, |
| 444 | ], |
| 445 | ) |
| 446 | def test_malformed_envelopes_raise_schema_drift_not_type_or_attribute_error(self, malformed_envelope): |
| 447 | with pytest.raises(http.HTTPError) as exc_info: |
| 448 | xai_x.parse_x_response(malformed_envelope, *WINDOW) |
| 449 | assert exc_info.value.outcome_state == health.SCHEMA_DRIFT |
| 450 | |
| 451 | def test_skips_null_content_and_null_choice_to_parse_valid_sibling(self): |
| 452 | valid_payload = json.dumps({ |
| 453 | "items": [ |
| 454 | { |
| 455 | "text": "valid item", |
| 456 | "url": f"https://x.com/steipete/status/{IN_WINDOW_ID}", |
| 457 | "author_handle": "steipete", |
| 458 | "relevance": None, |
| 459 | } |
| 460 | ] |
| 461 | }) |
| 462 | resp_output = { |
| 463 | "output": [ |
| 464 | {"type": "message", "content": None}, |
| 465 | {"type": "message", "content": [{"type": "output_text", "text": None}, {"type": "output_text", "text": valid_payload}]}, |
| 466 | ] |
| 467 | } |
| 468 | items = xai_x.parse_x_response(resp_output, *WINDOW) |
| 469 | assert len(items) == 1 |
| 470 | assert items[0]["relevance"] == 0.5 |
| 471 | |
| 472 | resp_choices = { |
| 473 | "choices": [ |
| 474 | None, |
| 475 | {"message": None}, |
| 476 | {"message": {"content": None}}, |
| 477 | {"message": {"content": valid_payload}}, |
| 478 | ] |
| 479 | } |
| 480 | items_choices = xai_x.parse_x_response(resp_choices, *WINDOW) |
| 481 | assert len(items_choices) == 1 |
| 482 | assert items_choices[0]["author_handle"] == "steipete" |
| 483 | |
| 484 | # Whitespace-only message content / output string must not short-circuit valid siblings. |
| 485 | resp_ws_content = { |
| 486 | "output": [ |
| 487 | {"type": "message", "content": " \n\t "}, |
| 488 | {"type": "message", "content": [{"type": "output_text", "text": valid_payload}]}, |
| 489 | ] |
| 490 | } |
| 491 | items_ws = xai_x.parse_x_response(resp_ws_content, *WINDOW) |
| 492 | assert len(items_ws) == 1 |
| 493 | assert items_ws[0]["author_handle"] == "steipete" |
| 494 | |
| 495 | resp_ws_output = { |
| 496 | "output": " ", |
| 497 | "choices": [{"message": {"content": valid_payload}}], |
| 498 | } |
| 499 | items_ws_out = xai_x.parse_x_response(resp_ws_output, *WINDOW) |
| 500 | assert len(items_ws_out) == 1 |
| 501 | assert items_ws_out[0]["author_handle"] == "steipete" |
| 502 | |
| 503 | def test_malformed_xai_response_fails_over_cleanly_in_attempt_x_backend(self, monkeypatch): |
| 504 | monkeypatch.setattr( |
| 505 | pipeline.xai_x, |
| 506 | "search_x", |
| 507 | lambda *a, **k: {"choices": [{"message": None}]}, |
| 508 | ) |
| 509 | items, detail, state = pipeline._attempt_x_backend( |
| 510 | "xai", "topic", WINDOW[0], WINDOW[1], "quick", {"XAI_API_KEY": "xai-dummy"}, |
| 511 | ) |
| 512 | assert items == [] |
| 513 | assert detail |
| 514 | assert state == health.SCHEMA_DRIFT |
| 515 | |
| 516 | |
| 517 | # --------------------------------------------------------------------------- |
| 518 | # HIGH-146: x_judge excludes LOW_SIGNAL_QUERY_TOKENS on ranking_query |
| 519 | # --------------------------------------------------------------------------- |
| 520 | |
| 521 | |
| 522 | class TestHigh146XJudgeLowSignalExclusion: |
| 523 | def test_planner_scaffolding_words_do_not_make_off_topic_posts_on_topic(self): |
| 524 | ranking_query = "What recent evidence from the last 30 days is most relevant to Rome?" |
| 525 | off_topic_posts = [ |
| 526 | {"author_handle": "spam1", "text": "Zelensky addressed world leaders in the last 30 days"}, |
| 527 | {"author_handle": "spam1", "text": "Most people agree this new evidence is relevant"}, |
| 528 | {"author_handle": "spam2", "text": "Recent update from the last few days"}, |
| 529 | {"author_handle": "spam2", "text": "30 new tips for people around the world"}, |
| 530 | {"author_handle": "spam3", "text": "The most recent story in the world today"}, |
| 531 | {"author_handle": "spam3", "text": "Evidence shows last week was busy"}, |
| 532 | ] |
| 533 | on_topic_posts = [ |
| 534 | {"author_handle": "romefan", "text": "Trevi Fountain in Rome today"}, |
| 535 | {"author_handle": "romefan", "text": "Best pasta spots in Rome"}, |
| 536 | ] |
| 537 | |
| 538 | for post in off_topic_posts: |
| 539 | assert x_judge._compute_relevance(ranking_query, post["text"]) == 0.0 |
| 540 | |
| 541 | corpus = on_topic_posts + off_topic_posts |
| 542 | judgment = x_judge.judge_x_corpus(corpus, "Rome", ranking_query=ranking_query) |
| 543 | assert judgment["on_topic_items"] == on_topic_posts |
| 544 | assert len(judgment["off_topic_items"]) == len(off_topic_posts) |
| 545 | assert judgment["on_topic_ratio"] == pytest.approx(2 / 8) |
| 546 | assert judgment["is_off_topic_flood"] is True |
| 547 | assert x_judge.should_retry_x_search(corpus, "Rome", ranking_query=ranking_query, depth="default") is True |
| 548 | assert x_judge.prune_off_topic_items(corpus, "Rome", ranking_query=ranking_query) == on_topic_posts |
| 549 | |
| 550 | _, extracted = x_judge.promotable_handles( |
| 551 | corpus, "Rome", ["spam1", "spam2", "romefan"], ranking_query=ranking_query, |
| 552 | ) |
| 553 | assert extracted == ["romefan"] |
| 554 | |
| 555 | def test_case_sensitive_us_acronym_inside_planner_ranking_query(self): |
| 556 | ranking_query = "What recent evidence from the last 30 days is most relevant to US?" |
| 557 | # Lowercase pronoun "us" plus scaffolding words must score 0.0, not fall back to scaffolding. |
| 558 | assert x_judge._compute_relevance(ranking_query, "Tell us what happened in the last 30 days") == 0.0 |
| 559 | # Uppercase country acronym "US" passes. |
| 560 | assert x_judge._compute_relevance(ranking_query, "US tariff news over the last 30 days") == 1.0 |
| 561 | |
| 562 | def test_all_low_signal_query_falls_back_like_prepared_query(self): |
| 563 | assert x_judge._compute_relevance("latest news", "Breaking latest news update") > 0.0 |
| 564 | |
| 565 | |
| 566 | # --------------------------------------------------------------------------- |
| 567 | # HIGH-147: x_api full-archive 403 expected_misses & conditional truncation |
| 568 | # --------------------------------------------------------------------------- |
| 569 | |
| 570 | |
| 571 | class TestHigh147XApiExpectedMissAndTruncation: |
| 572 | def _urlopen_for(self, responses: list[tuple[int, str]]): |
| 573 | seq = iter(responses) |
| 574 | |
| 575 | def fake_urlopen(req, timeout=None): |
| 576 | status, body = next(seq) |
| 577 | if status >= 400: |
| 578 | raise urllib.error.HTTPError( |
| 579 | req.full_url, |
| 580 | status, |
| 581 | "Error", |
| 582 | hdrs={}, |
| 583 | fp=BytesIO(body.encode("utf-8")), |
| 584 | ) |
| 585 | resp = mock.MagicMock() |
| 586 | resp.__enter__.return_value = resp |
| 587 | resp.__exit__.return_value = False |
| 588 | resp.status = status |
| 589 | resp.read.return_value = body.encode("utf-8") |
| 590 | return resp |
| 591 | |
| 592 | return fake_urlopen |
| 593 | |
| 594 | def test_enrollment_403_probe_does_not_pollute_failure_sink_or_misreport_auth_failed(self, monkeypatch): |
| 595 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 596 | monkeypatch.setattr( |
| 597 | http.urllib.request, |
| 598 | "urlopen", |
| 599 | self._urlopen_for([ |
| 600 | (403, '{"reason":"client-not-enrolled","title":"Client Forbidden"}'), |
| 601 | (200, json.dumps({"data": [], "meta": {"result_count": 0}})), |
| 602 | ]), |
| 603 | ) |
| 604 | with http.capture_failures() as failures: |
| 605 | result = x_api.search_x(DUMMY_TOKEN, "quiet topic", FROM, TO, depth="quick") |
| 606 | |
| 607 | assert result == {"items": [], "warning": x_api.TRUNCATION_DETAIL} |
| 608 | assert failures == [], f"enrollment probe 403 polluted failure sink: {failures}" |
| 609 | assert pipeline._resolve_stream_outcome("x", {}, failures) is None |
| 610 | |
| 611 | def test_enrollment_403_with_old_as_of_window_does_not_pollute_failure_sink(self, monkeypatch): |
| 612 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 613 | monkeypatch.setattr( |
| 614 | http.urllib.request, |
| 615 | "urlopen", |
| 616 | self._urlopen_for([ |
| 617 | (403, '{"reason":"client-not-enrolled"}'), |
| 618 | ]), |
| 619 | ) |
| 620 | with http.capture_failures() as failures: |
| 621 | result = x_api.search_x(DUMMY_TOKEN, "old window", "2026-08-01", "2026-08-20", depth="quick") |
| 622 | |
| 623 | assert result == {"items": [], "warning": x_api.TRUNCATION_DETAIL} |
| 624 | assert failures == [] |
| 625 | assert pipeline._resolve_stream_outcome("x", {}, failures) is None |
| 626 | |
| 627 | def test_plain_non_enrollment_403_still_returns_err_forbidden(self, monkeypatch): |
| 628 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 629 | monkeypatch.setattr( |
| 630 | http.urllib.request, |
| 631 | "urlopen", |
| 632 | self._urlopen_for([(403, '{"title":"Forbidden","detail":"revoked"}')]), |
| 633 | ) |
| 634 | with http.capture_failures() as failures: |
| 635 | result = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick") |
| 636 | |
| 637 | assert result == {"items": [], "error": x_api.ERR_FORBIDDEN} |
| 638 | assert http.classify_failure(message=result["error"]) == health.AUTH_FAILED |
| 639 | assert failures == [] |
| 640 | |
| 641 | def test_recent_window_within_7_days_omits_truncation_warning(self, monkeypatch): |
| 642 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 643 | with mock.patch("lib.x_api.http.get") as mock_get: |
| 644 | mock_get.side_effect = [ |
| 645 | http.HTTPError("HTTP 403: Forbidden", status_code=403, body="client-not-enrolled"), |
| 646 | {"data": [{"id": "1", "text": "fresh post", "created_at": "2026-09-07T10:00:00Z"}], "meta": {"result_count": 1}}, |
| 647 | ] |
| 648 | # 2-day window (2026-09-06..2026-09-08) is strictly inside recent floor (2026-09-01T12:00:30Z). |
| 649 | result = x_api.search_x(DUMMY_TOKEN, "topic", "2026-09-06", TO, depth="quick") |
| 650 | |
| 651 | assert "error" not in result |
| 652 | assert "warning" not in result |
| 653 | assert len(result["items"]) == 1 |
| 654 | |
| 655 | |
| 656 | # --------------------------------------------------------------------------- |
| 657 | # HIGH-148: x_api handle-lane errors & pre-start deadline/cancel error |
| 658 | # --------------------------------------------------------------------------- |
| 659 | |
| 660 | |
| 661 | class TestHigh148XApiHandleLaneErrorsAndPreStartBudget: |
| 662 | @pytest.mark.parametrize( |
| 663 | "exc,expected_error", |
| 664 | [ |
| 665 | (http.HTTPError("HTTP 401", status_code=401), x_api.ERR_UNAUTHORIZED), |
| 666 | (http.HTTPError("HTTP 402", status_code=402), x_api.ERR_PAYMENT_REQUIRED), |
| 667 | (http.HTTPError("HTTP 403", status_code=403, body="Forbidden"), x_api.ERR_FORBIDDEN), |
| 668 | (http.HTTPError("HTTP 429", status_code=429), x_api.ERR_RATE_LIMITED), |
| 669 | (http.DeadlineExceeded(), x_api.ERR_TIMED_OUT), |
| 670 | ], |
| 671 | ) |
| 672 | def test_search_handles_and_mentions_populate_errors_sink(self, monkeypatch, exc, expected_error): |
| 673 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 674 | with mock.patch("lib.x_api.http.get", side_effect=exc): |
| 675 | from_errors: list[str] = [] |
| 676 | from_items = x_api.search_handles( |
| 677 | ["alice", "bob"], "topic", FROM, TO, token=DUMMY_TOKEN, errors=from_errors, |
| 678 | ) |
| 679 | about_errors: list[str] = [] |
| 680 | about_items = x_api.search_mentions( |
| 681 | ["alice"], FROM, TO, topic="topic", token=DUMMY_TOKEN, errors=about_errors, |
| 682 | ) |
| 683 | |
| 684 | assert from_items == [] |
| 685 | assert from_errors == [expected_error] |
| 686 | assert about_items == [] |
| 687 | assert about_errors == [expected_error] |
| 688 | |
| 689 | def test_search_x_past_deadline_or_cancelled_returns_err_timed_out(self, monkeypatch): |
| 690 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 691 | monkeypatch.setattr(x_api.time, "monotonic", lambda: 1000.0) |
| 692 | with mock.patch("lib.x_api.http.get") as mock_get: |
| 693 | expired = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick", deadline=999.0) |
| 694 | cancel = threading.Event() |
| 695 | cancel.set() |
| 696 | cancelled = x_api.search_x(DUMMY_TOKEN, "topic", FROM, TO, depth="quick", cancel=cancel) |
| 697 | |
| 698 | mock_get.assert_not_called() |
| 699 | assert expired == {"items": [], "error": x_api.ERR_TIMED_OUT} |
| 700 | assert cancelled == {"items": [], "error": x_api.ERR_TIMED_OUT} |
| 701 | |
| 702 | def test_cancelled_handle_lane_returns_warning_not_error(self, monkeypatch): |
| 703 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 704 | cancel = threading.Event() |
| 705 | cancel.set() |
| 706 | warnings: list[str] = [] |
| 707 | errors: list[str] = [] |
| 708 | with mock.patch("lib.x_api.http.get") as mock_get: |
| 709 | from_items = x_api.search_handles( |
| 710 | ["steipete"], "topic", FROM, TO, token=DUMMY_TOKEN, |
| 711 | warnings=warnings, errors=errors, cancel=cancel, |
| 712 | ) |
| 713 | about_items = x_api.search_mentions( |
| 714 | ["steipete"], FROM, TO, topic="topic", token=DUMMY_TOKEN, |
| 715 | warnings=warnings, errors=errors, cancel=cancel, |
| 716 | ) |
| 717 | |
| 718 | mock_get.assert_not_called() |
| 719 | assert from_items == [] |
| 720 | assert about_items == [] |
| 721 | assert warnings == [x_api.DEADLINE_DETAIL] |
| 722 | assert errors == [] |
| 723 | |
| 724 | def test_pipeline_xapi_handle_lane_401_records_auth_failed_and_skips_about_lane(self, monkeypatch): |
| 725 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 726 | bundle = schema.RetrievalBundle() |
| 727 | bundle.items_by_source["x"] = [ |
| 728 | _make_source_item("x", "X1", "https://x.com/steipete/status/1", author="steipete", body="AI safety analysis"), |
| 729 | ] |
| 730 | runtime = schema.ProviderRuntime( |
| 731 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None, |
| 732 | ) |
| 733 | with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \ |
| 734 | mock.patch("lib.entity_extract.extract_entities", return_value={"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}), \ |
| 735 | mock.patch("lib.x_api.http.get", side_effect=http.HTTPError("Unauthorized", status_code=401)), \ |
| 736 | mock.patch("lib.x_api.search_mentions", wraps=x_api.search_mentions) as about_spy: |
| 737 | pipeline._run_supplemental_searches( |
| 738 | topic="AI safety", |
| 739 | bundle=bundle, |
| 740 | plan=_make_plan("AI safety"), |
| 741 | config={"X_BEARER_TOKEN": DUMMY_TOKEN}, |
| 742 | depth="default", |
| 743 | date_range=(FROM, TO), |
| 744 | runtime=runtime, |
| 745 | mock=False, |
| 746 | rate_limited_sources=set(), |
| 747 | rate_limit_lock=threading.Lock(), |
| 748 | x_handle="steipete", |
| 749 | ) |
| 750 | |
| 751 | about_spy.assert_not_called() |
| 752 | assert bundle.source_status["x"].state == health.AUTH_FAILED |
| 753 | assert "authentication failed" in (bundle.source_status["x"].detail or "") |
| 754 | |
| 755 | def test_pipeline_xapi_handle_lane_402_records_payment_required_and_skips_subsequent_lanes(self, monkeypatch): |
| 756 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 757 | bundle = schema.RetrievalBundle() |
| 758 | runtime = schema.ProviderRuntime( |
| 759 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None, |
| 760 | ) |
| 761 | with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \ |
| 762 | mock.patch("lib.entity_extract.extract_entities", return_value={"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}), \ |
| 763 | mock.patch("lib.x_api.http.get", side_effect=http.HTTPError("Payment Required", status_code=402)) as mock_get: |
| 764 | pipeline._run_supplemental_searches( |
| 765 | topic="AI safety", |
| 766 | bundle=bundle, |
| 767 | plan=_make_plan("AI safety"), |
| 768 | config={"X_BEARER_TOKEN": DUMMY_TOKEN}, |
| 769 | depth="default", |
| 770 | date_range=(FROM, TO), |
| 771 | runtime=runtime, |
| 772 | mock=False, |
| 773 | rate_limited_sources=set(), |
| 774 | rate_limit_lock=threading.Lock(), |
| 775 | x_handle="steipete", |
| 776 | x_related=["peer1"], |
| 777 | ) |
| 778 | |
| 779 | assert mock_get.call_count == 1 |
| 780 | assert bundle.source_status["x"].state == health.PAYMENT_REQUIRED |
| 781 | assert bundle.failure_state_by_source["x"] == health.PAYMENT_REQUIRED |
| 782 | assert "payment required" in (bundle.source_status["x"].detail or "") |
| 783 | |
| 784 | def test_pipeline_xapi_handle_lane_429_records_rate_limited(self, monkeypatch): |
| 785 | monkeypatch.setattr(x_api, "_utcnow", lambda: FIXED_NOW) |
| 786 | bundle = schema.RetrievalBundle() |
| 787 | runtime = schema.ProviderRuntime( |
| 788 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None, |
| 789 | ) |
| 790 | with mock.patch("lib.env.x_backend_chain", return_value=["xapi"]), \ |
| 791 | mock.patch("lib.entity_extract.extract_entities", return_value={"x_handles": [], "x_hashtags": [], "reddit_subreddits": []}), \ |
| 792 | mock.patch("lib.x_api.http.get", side_effect=http.HTTPError("Too Many Requests", status_code=429)): |
| 793 | pipeline._run_supplemental_searches( |
| 794 | topic="AI safety", |
| 795 | bundle=bundle, |
| 796 | plan=_make_plan("AI safety"), |
| 797 | config={"X_BEARER_TOKEN": DUMMY_TOKEN}, |
| 798 | depth="default", |
| 799 | date_range=(FROM, TO), |
| 800 | runtime=runtime, |
| 801 | mock=False, |
| 802 | rate_limited_sources=set(), |
| 803 | rate_limit_lock=threading.Lock(), |
| 804 | x_handle="steipete", |
| 805 | ) |
| 806 | |
| 807 | assert bundle.source_status["x"].state == health.RATE_LIMITED |
| 808 | assert "rate limit" in (bundle.source_status["x"].detail or "") |
| 809 | |
| 810 | |
| 811 | # --------------------------------------------------------------------------- |
| 812 | # HIGH-149: xquik HTTP 429 early stop & non-auth error surfacing |
| 813 | # --------------------------------------------------------------------------- |
| 814 | |
| 815 | |
| 816 | class TestHigh149XquikRateLimitAndErrorSurfacing: |
| 817 | def test_429_breaks_query_loop_immediately_and_returns_rate_limited_error(self): |
| 818 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["q1", "q2", "q3"]), \ |
| 819 | mock.patch( |
| 820 | "lib.xquik.http.get", |
| 821 | side_effect=http.HTTPError("blocked", status_code=429), |
| 822 | ) as mock_get: |
| 823 | result = xquik.search_xquik("topic", FROM, TO, depth="deep", token="dummy-key") |
| 824 | |
| 825 | assert mock_get.call_count == 1 |
| 826 | assert result["items"] == [] |
| 827 | assert "error" in result |
| 828 | assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED |
| 829 | |
| 830 | def test_429_bare_code_with_forbidden_topic_still_classifies_rate_limited(self): |
| 831 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["forbidden city", "q2"]), \ |
| 832 | mock.patch( |
| 833 | "lib.xquik.http.get", |
| 834 | side_effect=http.HTTPError("throttled (429)", status_code=429), |
| 835 | ) as mock_get: |
| 836 | result = xquik.search_xquik("forbidden city", FROM, TO, depth="default", token="dummy-key") |
| 837 | |
| 838 | assert mock_get.call_count == 1 |
| 839 | assert result["items"] == [] |
| 840 | assert "HTTP 429 rate limit" in result["error"] |
| 841 | assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED |
| 842 | |
| 843 | def test_429_after_503_stops_and_preserves_rate_limited_specificity(self): |
| 844 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["q1", "q2", "q3"]), \ |
| 845 | mock.patch( |
| 846 | "lib.xquik.http.get", |
| 847 | side_effect=[ |
| 848 | http.HTTPError("HTTP 503: Service Unavailable", status_code=503), |
| 849 | http.HTTPError("Too Many Requests", status_code=429), |
| 850 | ], |
| 851 | ) as mock_get: |
| 852 | result = xquik.search_xquik("topic", FROM, TO, depth="deep", token="dummy-key") |
| 853 | |
| 854 | assert mock_get.call_count == 2 |
| 855 | assert result["items"] == [] |
| 856 | assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED |
| 857 | |
| 858 | def test_query_text_with_403_forbidden_does_not_outrank_real_429_or_misclassify_503(self): |
| 859 | # Single-query 503 for topic "403 Forbidden" must stay health.ERROR (never AUTH_FAILED) |
| 860 | # both directly and downstream in pipeline._attempt_x_backend. |
| 861 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["403 Forbidden"]), \ |
| 862 | mock.patch( |
| 863 | "lib.xquik.http.get", |
| 864 | side_effect=http.HTTPError("HTTP 503: Service Unavailable", status_code=503), |
| 865 | ): |
| 866 | single = xquik.search_xquik("403 Forbidden", FROM, TO, depth="quick", token="dummy-key") |
| 867 | assert single["items"] == [] |
| 868 | assert "403 Forbidden" not in single["error"] |
| 869 | assert http.classify_failure(message=single["error"]) == health.ERROR |
| 870 | |
| 871 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["403 Forbidden"]), \ |
| 872 | mock.patch( |
| 873 | "lib.xquik.http.get", |
| 874 | side_effect=http.HTTPError("HTTP 503: Service Unavailable", status_code=503), |
| 875 | ): |
| 876 | _, detail, state = pipeline._attempt_x_backend( |
| 877 | "xquik", "403 Forbidden", FROM, TO, "quick", {"XQUIK_API_KEY": "dummy-key"}, |
| 878 | ) |
| 879 | assert detail |
| 880 | assert state == health.ERROR |
| 881 | |
| 882 | # Multi-query: 503 on "403 Forbidden" followed by 429 -> 429 wins as RATE_LIMITED. |
| 883 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["403 Forbidden", "followup query"]), \ |
| 884 | mock.patch( |
| 885 | "lib.xquik.http.get", |
| 886 | side_effect=[ |
| 887 | http.HTTPError("HTTP 503: Service Unavailable", status_code=503), |
| 888 | http.HTTPError("Too Many Requests", status_code=429), |
| 889 | ], |
| 890 | ) as mock_get: |
| 891 | result = xquik.search_xquik("403 Forbidden", FROM, TO, depth="default", token="dummy-key") |
| 892 | |
| 893 | assert mock_get.call_count == 2 |
| 894 | assert result["items"] == [] |
| 895 | assert "403 Forbidden" not in result["error"] |
| 896 | assert "Too Many Requests" in result["error"] |
| 897 | assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED |
| 898 | |
| 899 | def test_429_through_real_http_get_makes_single_attempt_without_retry(self, monkeypatch): |
| 900 | attempts: list[str] = [] |
| 901 | |
| 902 | def fake_urlopen(req, timeout=None): |
| 903 | attempts.append(req.full_url) |
| 904 | raise urllib.error.HTTPError( |
| 905 | req.full_url, |
| 906 | 429, |
| 907 | "Too Many Requests", |
| 908 | hdrs={"Retry-After": "30"}, |
| 909 | fp=BytesIO(b'{"error":"rate limited"}'), |
| 910 | ) |
| 911 | |
| 912 | monkeypatch.setattr(http.urllib.request, "urlopen", fake_urlopen) |
| 913 | monkeypatch.setattr(http.time, "sleep", lambda _s: (_ for _ in ()).throw(AssertionError("429 must not sleep/retry"))) |
| 914 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["q1", "q2", "q3"]): |
| 915 | result = xquik.search_xquik("topic", FROM, TO, depth="deep", token="dummy-key") |
| 916 | |
| 917 | assert len(attempts) == 1 |
| 918 | assert result["items"] == [] |
| 919 | assert http.classify_failure(message=result["error"]) == health.RATE_LIMITED |
| 920 | |
| 921 | def test_handle_search_keeps_default_429_retry_while_topic_search_caps_at_one(self, monkeypatch): |
| 922 | # Mocked check: search_xquik passes max_429_retries=1; search_handles does not. |
| 923 | with mock.patch("lib.xquik.http.get", return_value={"tweets": []}) as mock_get: |
| 924 | xquik.search_xquik("topic", FROM, TO, depth="quick", token="dummy-key") |
| 925 | assert mock_get.call_args.kwargs.get("max_429_retries") == 1 |
| 926 | mock_get.reset_mock() |
| 927 | xquik.search_handles(["alice"], "topic", FROM, TO, token="dummy-key") |
| 928 | assert "max_429_retries" not in mock_get.call_args.kwargs |
| 929 | |
| 930 | # End-to-end check: a brief 429 on search_handles retries and recovers the handle's post. |
| 931 | calls = {"n": 0} |
| 932 | tweet_payload = json.dumps({ |
| 933 | "tweets": [ |
| 934 | { |
| 935 | "id": "555", |
| 936 | "text": "recovered after transient 429", |
| 937 | "createdAt": "2026-08-20T12:00:00Z", |
| 938 | "author": {"username": "alice"}, |
| 939 | } |
| 940 | ] |
| 941 | }).encode("utf-8") |
| 942 | |
| 943 | def fake_urlopen(req, timeout=None): |
| 944 | calls["n"] += 1 |
| 945 | if calls["n"] == 1: |
| 946 | raise urllib.error.HTTPError( |
| 947 | req.full_url, |
| 948 | 429, |
| 949 | "Too Many Requests", |
| 950 | hdrs={"Retry-After": "0.01"}, |
| 951 | fp=BytesIO(b'{"error":"brief rate limit"}'), |
| 952 | ) |
| 953 | resp = mock.MagicMock() |
| 954 | resp.__enter__.return_value = resp |
| 955 | resp.__exit__.return_value = False |
| 956 | resp.status = 200 |
| 957 | resp.read.return_value = tweet_payload |
| 958 | return resp |
| 959 | |
| 960 | monkeypatch.setattr(http.urllib.request, "urlopen", fake_urlopen) |
| 961 | monkeypatch.setattr(http.time, "sleep", lambda _s: None) |
| 962 | items = xquik.search_handles(["alice"], "topic", FROM, TO, token="dummy-key") |
| 963 | assert calls["n"] == 2 |
| 964 | assert len(items) == 1 |
| 965 | assert items[0]["url"] == "https://x.com/alice/status/555" |
| 966 | |
| 967 | def test_429_after_first_query_items_stops_remaining_queries_and_keeps_items(self): |
| 968 | tweet = { |
| 969 | "id": "1001", |
| 970 | "text": "valid item", |
| 971 | "createdAt": "2026-08-20T12:00:00Z", |
| 972 | "author": {"username": "alice"}, |
| 973 | } |
| 974 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["q1", "q2", "q3"]), \ |
| 975 | mock.patch( |
| 976 | "lib.xquik.http.get", |
| 977 | side_effect=[{"tweets": [tweet]}, http.HTTPError("Too Many Requests", status_code=429)], |
| 978 | ) as mock_get: |
| 979 | result = xquik.search_xquik("topic", FROM, TO, depth="deep", token="dummy-key") |
| 980 | |
| 981 | assert mock_get.call_count == 2 |
| 982 | assert len(result["items"]) == 1 |
| 983 | assert "error" not in result |
| 984 | |
| 985 | @pytest.mark.parametrize( |
| 986 | "side_effect,expected_state", |
| 987 | [ |
| 988 | (http.HTTPError("HTTP 503: Service Unavailable", status_code=503), health.ERROR), |
| 989 | (http.DeadlineExceeded(), health.TIMEOUT), |
| 990 | (TimeoutError(), health.TIMEOUT), |
| 991 | (OSError("connection reset by peer"), health.UNREACHABLE), |
| 992 | ], |
| 993 | ) |
| 994 | def test_non_auth_failures_surface_error_when_no_items_returned(self, side_effect, expected_state): |
| 995 | with mock.patch("lib.xquik.expand_xquik_queries", return_value=["q1", "q2"]), \ |
| 996 | mock.patch("lib.xquik.http.get", side_effect=side_effect) as mock_get: |
| 997 | result = xquik.search_xquik("topic", FROM, TO, depth="default", token="dummy-key") |
| 998 | |
| 999 | assert result["items"] == [] |
| 1000 | assert "error" in result and result["error"] |
| 1001 | assert http.classify_failure(message=result["error"]) == expected_state |
| 1002 | if isinstance(side_effect, http.DeadlineExceeded): |
| 1003 | assert mock_get.call_count == 1 |
| 1004 | |
| 1005 | def test_non_list_tweets_payload_surfaces_error_and_reaches_pipeline_chain(self): |
| 1006 | with mock.patch("lib.xquik.http.get", return_value={"tweets": "not-a-list"}): |
| 1007 | result = xquik.search_xquik("topic", FROM, TO, depth="quick", token="dummy-key") |
| 1008 | |
| 1009 | assert result["items"] == [] |
| 1010 | assert "no tweets array" in result.get("error", "") |
| 1011 | |
| 1012 | sq = schema.SubQuery(label="primary", search_query="topic", ranking_query="topic?", sources=["x"]) |
| 1013 | runtime = schema.ProviderRuntime( |
| 1014 | reasoning_provider="mock", planner_model="mock", rerank_model="mock", x_search_backend=None, |
| 1015 | ) |
| 1016 | with mock.patch("lib.env.x_backend_chain", return_value=["xquik"]), \ |
| 1017 | mock.patch("lib.xquik.http.get", return_value={"tweets": "not-a-list"}): |
| 1018 | with pytest.raises(pipeline.SourceRunError) as exc_info: |
| 1019 | pipeline._retrieve_stream( |
| 1020 | topic="topic", |
| 1021 | subquery=sq, |
| 1022 | source="x", |
| 1023 | config={"XQUIK_API_KEY": "dummy-key"}, |
| 1024 | depth="quick", |
| 1025 | date_range=(FROM, TO), |
| 1026 | runtime=runtime, |
| 1027 | mock=False, |
| 1028 | ) |
| 1029 | assert "no tweets array" in str(exc_info.value) |
| 1030 | |
| 1031 | |
| 1032 | # --------------------------------------------------------------------------- |
| 1033 | # HIGH-151: xurl_x explicit UTF-8 subprocess decoding under ASCII/C locale |
| 1034 | # --------------------------------------------------------------------------- |
| 1035 | |
| 1036 | |
| 1037 | class TestHigh151XurlUtf8SubprocessDecoding: |
| 1038 | def test_subprocess_calls_pass_utf8_encoding_and_replace_errors(self): |
| 1039 | xurl_x.clear_availability_cache() |
| 1040 | try: |
| 1041 | with mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout="bearer: ✓\n")) as run_mock: |
| 1042 | assert xurl_x.is_available() is True |
| 1043 | assert run_mock.call_args.kwargs.get("encoding") == "utf-8" |
| 1044 | assert run_mock.call_args.kwargs.get("errors") == "replace" |
| 1045 | finally: |
| 1046 | xurl_x.clear_availability_cache() |
| 1047 | |
| 1048 | payload = {"data": [{"id": "1", "text": "hello 🚀 “quotes”", "author_id": "u1"}]} |
| 1049 | with mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout=json.dumps(payload))) as run_mock: |
| 1050 | res = xurl_x.search_x("hello") |
| 1051 | assert res["data"][0]["text"] == "hello 🚀 “quotes”" |
| 1052 | assert run_mock.call_args.kwargs.get("encoding") == "utf-8" |
| 1053 | assert run_mock.call_args.kwargs.get("errors") == "replace" |
| 1054 | assert run_mock.call_args.args[0][:3] == ["xurl", "search", "hello"] |
| 1055 | |
| 1056 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell shim for LC_ALL=C locale test") |
| 1057 | def test_real_subprocess_under_c_locale_handles_utf8_checkmark_and_emoji(self, tmp_path): |
| 1058 | fake_xurl = tmp_path / "xurl" |
| 1059 | fake_xurl.write_text( |
| 1060 | "#!/usr/bin/env python3\n" |
| 1061 | "import json, sys\n" |
| 1062 | "if sys.argv[1:3] == ['auth', 'status']:\n" |
| 1063 | " sys.stdout.buffer.write('oauth1: ✗\\nbearer: ✓\\n'.encode('utf-8'))\n" |
| 1064 | " sys.exit(0)\n" |
| 1065 | "if sys.argv[1] == 'search':\n" |
| 1066 | " payload = {'data': [{'id': '123', 'text': 'Emoji 🚀 smart “quotes” 日本語', 'author_id': 'u1'}],\n" |
| 1067 | " 'includes': {'users': [{'id': 'u1', 'username': 'alice'}]}}\n" |
| 1068 | " sys.stdout.buffer.write(json.dumps(payload, ensure_ascii=False).encode('utf-8'))\n" |
| 1069 | " sys.exit(0)\n" |
| 1070 | "sys.exit(2)\n", |
| 1071 | encoding="utf-8", |
| 1072 | ) |
| 1073 | fake_xurl.chmod(fake_xurl.stat().st_mode | stat.S_IXUSR) |
| 1074 | |
| 1075 | env = os.environ.copy() |
| 1076 | env["PATH"] = f"{tmp_path}{os.pathsep}{env.get('PATH', '')}" |
| 1077 | env["LC_ALL"] = "C" |
| 1078 | env["LANG"] = "C" |
| 1079 | env["PYTHONUTF8"] = "0" |
| 1080 | env["PYTHONPATH"] = str(REPO_ROOT / "skills" / "last30days" / "scripts") |
| 1081 | |
| 1082 | script = ( |
| 1083 | "import json\n" |
| 1084 | "from lib import xurl_x\n" |
| 1085 | "xurl_x.clear_availability_cache()\n" |
| 1086 | "avail = xurl_x.is_available()\n" |
| 1087 | "res = xurl_x.search_x('emoji test')\n" |
| 1088 | "items = xurl_x.parse_x_response(res, topic='emoji')\n" |
| 1089 | "print(json.dumps({'avail': avail, 'text': items[0]['text']}, ensure_ascii=True))\n" |
| 1090 | ) |
| 1091 | proc = subprocess.run( |
| 1092 | ["python3", "-X", "utf8=0", "-c", script], |
| 1093 | env=env, |
| 1094 | capture_output=True, |
| 1095 | text=True, |
| 1096 | encoding="utf-8", |
| 1097 | check=False, |
| 1098 | ) |
| 1099 | assert proc.returncode == 0, f"stdout={proc.stdout!r} stderr={proc.stderr!r}" |
| 1100 | parsed = json.loads(proc.stdout.strip()) |
| 1101 | assert parsed["avail"] is True |
| 1102 | assert parsed["text"] == "Emoji 🚀 smart “quotes” 日本語" |
| 1103 | |
| 1104 | |
| 1105 | # --------------------------------------------------------------------------- |
| 1106 | # HIGH-162: Node test suite for vendored bird-search twitter-client-utils.js |
| 1107 | # --------------------------------------------------------------------------- |
| 1108 | |
| 1109 | |
| 1110 | def _node_major_version() -> int | None: |
| 1111 | if not HAS_NODE: |
| 1112 | return None |
| 1113 | proc = subprocess.run( |
| 1114 | ["node", "-v"], |
| 1115 | capture_output=True, |
| 1116 | text=True, |
| 1117 | encoding="utf-8", |
| 1118 | errors="replace", |
| 1119 | check=False, |
| 1120 | ) |
| 1121 | if proc.returncode != 0: |
| 1122 | return None |
| 1123 | head = proc.stdout.strip().lstrip("v").split(".", 1)[0] |
| 1124 | return int(head) if head.isdigit() else None |
| 1125 | |
| 1126 | |
| 1127 | def test_high162_bird_search_utils_node_suite(): |
| 1128 | major = _node_major_version() |
| 1129 | if major is None or major < 18: |
| 1130 | pytest.skip(f"node >= 18 is required for `node --test` (found: {major})") |
| 1131 | proc = subprocess.run( |
| 1132 | ["node", "--test", str(BIRD_UTILS_TEST)], |
| 1133 | cwd=REPO_ROOT, |
| 1134 | capture_output=True, |
| 1135 | text=True, |
| 1136 | encoding="utf-8", |
| 1137 | errors="replace", |
| 1138 | check=False, |
| 1139 | ) |
| 1140 | assert proc.returncode == 0, f"node --test failed:\nstdout:\n{proc.stdout}\nstderr:\n{proc.stderr}" |
| 1141 |