| 1 | """Regression tests for PR 17: keyless web search, entity resolve, and Parallel MCP hardening. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-091: O(N) HTMLParser chrome-region link parsing & bounded body size in resolve.py |
| 5 | - HIGH-202: Linear-time _BRAVE_AGE_RE, _strip_html, and SERP parsers in web_search_keyless.py |
| 6 | - HIGH-203: LAST30DAYS_SEARXNG_URL scheme/host/metadata validation & redirect_guard on HTML rungs/SearXNG |
| 7 | - HIGH-204: Bounded SERP/SearXNG reads and errors="replace" decoding without UnicodeDecodeError |
| 8 | - HIGH-205: Parallel MCP SSE wall-clock deadline, cancellation, line/event/request caps, and short DELETE cleanup |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import datetime as _dt |
| 14 | import http.client as http_client |
| 15 | import io |
| 16 | import json |
| 17 | import socket |
| 18 | import threading |
| 19 | import time |
| 20 | import urllib.error |
| 21 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 22 | from pathlib import Path |
| 23 | from unittest.mock import MagicMock, patch |
| 24 | from urllib.request import Request |
| 25 | |
| 26 | import pytest |
| 27 | |
| 28 | from lib import grounding, health, http, parallel_mcp, pipeline, resolve, web_fetch_keyless, web_search_keyless |
| 29 | |
| 30 | |
| 31 | def _start_server(handler_cls): |
| 32 | server = ThreadingHTTPServer(("127.0.0.1", 0), handler_cls) |
| 33 | server.daemon_threads = True |
| 34 | thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) |
| 35 | thread.start() |
| 36 | return server, thread, f"http://127.0.0.1:{server.server_port}" |
| 37 | |
| 38 | |
| 39 | def _stop_server(server, thread): |
| 40 | server.shutdown() |
| 41 | server.server_close() |
| 42 | thread.join(2) |
| 43 | |
| 44 | |
| 45 | # --------------------------------------------------------------------------- |
| 46 | # HIGH-091: resolve.py HTMLParser chrome region extraction & body cap |
| 47 | # --------------------------------------------------------------------------- |
| 48 | |
| 49 | |
| 50 | def test_resolve_removes_quadratic_chrome_region_regex(): |
| 51 | assert not hasattr(resolve, "_CHROME_REGION") |
| 52 | |
| 53 | |
| 54 | @pytest.mark.parametrize( |
| 55 | "adversarial_html", |
| 56 | [ |
| 57 | "<nav>" * 20_000, |
| 58 | "<header>" * 20_000, |
| 59 | "<footer>" * 20_000, |
| 60 | "<nav>" * 15_000 + "<footer><a href='https://x.com/acme'>X</a></footer>", |
| 61 | "<header " * 20_000, |
| 62 | "<nav>" * 20_000 + "</nav>", |
| 63 | ], |
| 64 | ) |
| 65 | def test_resolve_official_site_socials_is_linear_on_adversarial_html(adversarial_html: str): |
| 66 | started = time.monotonic() |
| 67 | with patch.object(resolve.http, "get_text", return_value=adversarial_html): |
| 68 | socials = resolve.official_site_socials("acme.com") |
| 69 | elapsed = time.monotonic() - started |
| 70 | assert elapsed < 0.25, f"official_site_socials took {elapsed:.4f}s (possible ReDoS)" |
| 71 | if "x.com/acme" in adversarial_html: |
| 72 | assert socials["x_handle"] == "acme" |
| 73 | else: |
| 74 | assert socials == {"x_handle": "", "github_user": ""} |
| 75 | |
| 76 | |
| 77 | def test_resolve_html_parser_tracks_nested_chrome_ignores_comments_and_scripts(): |
| 78 | page = """ |
| 79 | <html><body> |
| 80 | <!-- <a href="https://x.com/commentedout">Ignored</a> --> |
| 81 | <script>const link = '<a href="https://x.com/inscript">Ignored</a>';</script> |
| 82 | <nav/> |
| 83 | <a href="https://x.com/customer1">Customer</a> |
| 84 | <a href="https://x.com/customer2">Customer 2</a> |
| 85 | <header><nav><a href="https://x.com/BrandHQ?ref=top&src=1">X</a></nav></header> |
| 86 | </footer> |
| 87 | <footer><a href="https://github.com/brand-hq">GitHub</a></footer> |
| 88 | </body></html> |
| 89 | """ |
| 90 | with patch.object(resolve.http, "get_text", return_value=page): |
| 91 | socials = resolve.official_site_socials("brand.example") |
| 92 | assert socials == {"x_handle": "BrandHQ", "github_user": "brand-hq"} |
| 93 | |
| 94 | |
| 95 | def test_resolve_official_site_socials_bounds_response_size_and_decodes_invalid_utf8(): |
| 96 | with patch.object(resolve.http, "get_text", return_value="<html></html>") as mock_get: |
| 97 | resolve.official_site_socials("typesafe.ai") |
| 98 | assert mock_get.call_args.kwargs.get("max_bytes") == resolve._MAX_OFFICIAL_SITE_HTML_BYTES |
| 99 | assert mock_get.call_args.kwargs.get("decode_errors") == "replace" |
| 100 | |
| 101 | # A homepage with non-UTF-8 bytes (e.g. Latin-1 accent) still decodes with replacement |
| 102 | # instead of raising UnicodeDecodeError, and extracts the brand's footer handle. |
| 103 | latin1_page = ( |
| 104 | b"<html><head><title>Caf\xe9 Corp</title></head>" |
| 105 | b"<body><footer><a href='https://x.com/cafecorp'>X</a></footer></body></html>" |
| 106 | ) |
| 107 | resp = MagicMock() |
| 108 | resp.__enter__.return_value = resp |
| 109 | resp.__exit__.return_value = False |
| 110 | resp.status = 200 |
| 111 | resp.headers = {} |
| 112 | resp.read.return_value = latin1_page |
| 113 | with patch.object(resolve.http, "_open_request", return_value=resp): |
| 114 | assert resolve.official_site_socials("cafecorp.example") == { |
| 115 | "x_handle": "cafecorp", |
| 116 | "github_user": "", |
| 117 | } |
| 118 | |
| 119 | # Oversized HTML returned by a mocked get_text is sliced to _MAX_OFFICIAL_SITE_HTML_BYTES. |
| 120 | huge_html = (" " * (resolve._MAX_OFFICIAL_SITE_HTML_BYTES + 1024)) + ( |
| 121 | '<footer><a href="https://x.com/pastlimit">X</a></footer>' |
| 122 | ) |
| 123 | with patch.object(resolve.http, "get_text", return_value=huge_html): |
| 124 | assert resolve.official_site_socials("example.com") == {"x_handle": "", "github_user": ""} |
| 125 | |
| 126 | |
| 127 | # --------------------------------------------------------------------------- |
| 128 | # HIGH-202: web_search_keyless.py ReDoS elimination |
| 129 | # --------------------------------------------------------------------------- |
| 130 | |
| 131 | |
| 132 | def test_brave_age_re_is_linear_on_adversarial_unclosed_spans(): |
| 133 | adversarial_cases = [ |
| 134 | '<span class="t-secondary">' + (" " * 100_000), |
| 135 | '<span class="t-secondary">' + ("- " * 50_000), |
| 136 | '<span class="t-secondary">' * 20_000, |
| 137 | ('<span class="t-secondary">' + (" " * 50)) * 2_000, |
| 138 | ] |
| 139 | started = time.monotonic() |
| 140 | for payload in adversarial_cases: |
| 141 | assert web_search_keyless._BRAVE_AGE_RE.search(payload) is None |
| 142 | elapsed = time.monotonic() - started |
| 143 | assert elapsed < 0.1, f"_BRAVE_AGE_RE took {elapsed:.4f}s (possible ReDoS)" |
| 144 | |
| 145 | # Valid Brave age spans still match and parse identically. |
| 146 | now = _dt.datetime(2026, 11, 15, tzinfo=_dt.timezone.utc) |
| 147 | for raw, expected in ( |
| 148 | ('<span class="t-secondary"> 2 weeks ago - </span>', "2026-11-01"), |
| 149 | ('<span class="t-secondary">Nov 3, 2026 -</span>', "2026-11-03"), |
| 150 | ('<span class="t-secondary">3 days ago</span>', "2026-11-12"), |
| 151 | ): |
| 152 | match = web_search_keyless._BRAVE_AGE_RE.search(raw) |
| 153 | assert match is not None |
| 154 | assert web_search_keyless._brave_date(match.group("age"), now) == expected |
| 155 | |
| 156 | |
| 157 | def test_strip_html_and_serp_parsers_are_linear_on_adversarial_inputs(): |
| 158 | assert not hasattr(web_search_keyless, "_STYLE_SCRIPT_RE") |
| 159 | |
| 160 | started = time.monotonic() |
| 161 | assert web_search_keyless._strip_html("<script>" * 20_000) == "" |
| 162 | assert web_search_keyless._strip_html("<style>" * 20_000) == "" |
| 163 | assert web_search_keyless._strip_html("<script>" * 15_000 + "</script>ok") == "ok" |
| 164 | assert web_search_keyless._strip_html( |
| 165 | "<style>.a{color:red}</style><script>alert(1)</script>Hello & <b>World</b>" |
| 166 | ) == "Hello & World" |
| 167 | |
| 168 | # Unclosed and single-trailing-close SERP inputs across all three HTML parsers. |
| 169 | ddg_unclosed = '<a class="result__a" href="https://example.com/a">' * 5_000 |
| 170 | ddg_trailing = ddg_unclosed + "</a>" |
| 171 | sp_unclosed = '<a class="result-title" href="https://example.com/a">' * 5_000 |
| 172 | sp_trailing = sp_unclosed + "</a>" |
| 173 | brave_hostile = ( |
| 174 | '<div class="snippet" data-type="web"><a href="https://example.com/a">x</a>' |
| 175 | + ('<div class="search-snippet-title">' * 5_000) |
| 176 | + "</div>" |
| 177 | + '<span class="t-secondary">' |
| 178 | + (" " * 50_000) |
| 179 | ) |
| 180 | |
| 181 | assert web_search_keyless.parse_ddg(ddg_unclosed, 10) == [] |
| 182 | web_search_keyless.parse_ddg(ddg_trailing, 10) |
| 183 | assert web_search_keyless.parse_startpage(sp_unclosed, 10) == [] |
| 184 | web_search_keyless.parse_startpage(sp_trailing, 10) |
| 185 | assert web_search_keyless.parse_brave(brave_hostile, 10) == [] |
| 186 | |
| 187 | elapsed = time.monotonic() - started |
| 188 | assert elapsed < 1.0, f"SERP parsers took {elapsed:.4f}s (possible ReDoS)" |
| 189 | |
| 190 | # Real Brave fixture still parses cleanly. |
| 191 | fixture = ( |
| 192 | Path(__file__).resolve().parent.parent / "fixtures" / "brave_reddit_serp.html" |
| 193 | ).read_text(encoding="utf-8") |
| 194 | now = _dt.datetime(2026, 11, 15, tzinfo=_dt.timezone.utc) |
| 195 | items = web_search_keyless.parse_brave(fixture, 20, now=now) |
| 196 | assert len(items) >= 10 |
| 197 | assert any("1xattdz" in item["url"] and item["date"] == "2026-10-16" for item in items) |
| 198 | |
| 199 | |
| 200 | # --------------------------------------------------------------------------- |
| 201 | # HIGH-203: LAST30DAYS_SEARXNG_URL validation & redirect_guard on rungs/SearXNG |
| 202 | # --------------------------------------------------------------------------- |
| 203 | |
| 204 | |
| 205 | @pytest.mark.parametrize( |
| 206 | "bad_url", |
| 207 | [ |
| 208 | "", |
| 209 | " ", |
| 210 | "file:///etc/passwd", |
| 211 | "ftp://searxng.example/search", |
| 212 | "data:text/html,hello", |
| 213 | "javascript:alert(1)", |
| 214 | "gopher://127.0.0.1:70/_", |
| 215 | "http://[::1", |
| 216 | "http://searxng.example:99999", |
| 217 | "http:///no-host", |
| 218 | "https://user:pass@searxng.example", |
| 219 | "https://searxng.example\r\nX-Injected: 1", |
| 220 | "https://searxng.example\\evil", |
| 221 | "https://searxng.example?injected=1", |
| 222 | "https://searxng.example#frag", |
| 223 | "http://169.254.169.254", |
| 224 | "http://169.254.169.254/latest/meta-data", |
| 225 | "http://169.254.1.1:8080", |
| 226 | "http://2852039166/", |
| 227 | "http://0251.0376.0251.0376/", |
| 228 | "http://[::ffff:169.254.169.254]/", |
| 229 | "http://[64:ff9b::169.254.169.254]/", |
| 230 | "http://[fe80::1]:8080/", |
| 231 | "http://[fd00:ec2::254]/", |
| 232 | "http://100.100.100.200/", |
| 233 | "http://metadata.google.internal/", |
| 234 | "http://metadata.goog/", |
| 235 | "http://0.0.0.0:8080/", |
| 236 | "http://[::]:8080/", |
| 237 | "http://169\uff0e254\uff0e169\uff0e254", |
| 238 | "http://169\u3002254\u3002169\u3002254/", |
| 239 | "http://\uff11\uff16\uff19\uff0e\uff12\uff15\uff14\uff0e\uff11\uff16\uff19\uff0e\uff12\uff15\uff14/", |
| 240 | "http://\uff4d\uff45\uff54\uff41\uff44\uff41\uff54\uff41.google.internal/", |
| 241 | "http://\uff4d\uff45\uff54\uff41\uff44\uff41\uff54\uff41.goog/", |
| 242 | "http://169.254.169.254%25eth0/", |
| 243 | ], |
| 244 | ) |
| 245 | def test_searxng_rejects_unsafe_or_malformed_urls_without_raising(bad_url: str): |
| 246 | assert web_search_keyless._validate_searxng_url(bad_url) is None |
| 247 | with patch.object(web_search_keyless.http, "get_text", return_value=None), \ |
| 248 | patch.object(web_search_keyless.http, "get") as mock_get: |
| 249 | items, artifact = web_search_keyless.keyless_search( |
| 250 | "topic", ("2026-10-01", "2026-11-01"), {"LAST30DAYS_SEARXNG_URL": bad_url} |
| 251 | ) |
| 252 | assert items == [] |
| 253 | assert artifact["reason"] == "keyless-search-unavailable" |
| 254 | mock_get.assert_not_called() |
| 255 | |
| 256 | |
| 257 | @pytest.mark.parametrize( |
| 258 | "good_url", |
| 259 | [ |
| 260 | "http://127.0.0.1:8080", |
| 261 | "http://localhost:8888", |
| 262 | "http://[::1]:8080", |
| 263 | "http://192.168.1.50:8080", |
| 264 | "http://10.0.0.5:8080/searx", |
| 265 | "https://searxng.example", |
| 266 | "https://search.example.org/searxng/", |
| 267 | ], |
| 268 | ) |
| 269 | def test_searxng_allows_self_hosted_loopback_lan_and_public_urls(good_url: str): |
| 270 | validated = web_search_keyless._validate_searxng_url(good_url) |
| 271 | assert validated is not None |
| 272 | normalized, origin = validated |
| 273 | assert normalized.startswith(("http://", "https://")) |
| 274 | assert origin[0] in ("http", "https") |
| 275 | |
| 276 | |
| 277 | def test_fetch_page_attaches_public_only_strict_redirect_guard_and_bounds(): |
| 278 | with patch.object(web_search_keyless.http, "get_text", return_value="") as mock_get: |
| 279 | web_search_keyless._fetch_page("ddg", "https://html.duckduckgo.com/html/?q=test") |
| 280 | kwargs = mock_get.call_args.kwargs |
| 281 | assert kwargs["public_only"] is True |
| 282 | assert kwargs["max_bytes"] == web_search_keyless._MAX_SERP_BYTES |
| 283 | assert kwargs["decode_errors"] == "replace" |
| 284 | guard = kwargs["redirect_guard"] |
| 285 | assert callable(guard) |
| 286 | assert guard("https://html.duckduckgo.com/html/?q=test2") is True |
| 287 | assert guard("http://html.duckduckgo.com/html/?q=test2") is False |
| 288 | assert guard("https://evil.example/phish") is False |
| 289 | assert guard("http://127.0.0.1:8080/admin") is False |
| 290 | assert guard("http://169.254.169.254/latest/meta-data/") is False |
| 291 | assert guard("file:///etc/passwd") is False |
| 292 | |
| 293 | # Verify http redirect handler blocks private/off-host redirects with this guard. |
| 294 | handler = http._StripAuthOnCrossOriginRedirect() |
| 295 | req = Request("https://html.duckduckgo.com/html/?q=test") |
| 296 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 297 | setattr(req, http._REDIRECT_GUARD_ATTR, guard) |
| 298 | for target in ( |
| 299 | "http://169.254.169.254/latest/meta-data/", |
| 300 | "http://127.0.0.1:8080/", |
| 301 | "http://html.duckduckgo.com/downgrade", |
| 302 | "https://evil.example/redirect", |
| 303 | ): |
| 304 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 305 | handler.redirect_request(req, None, 302, "Found", {}, target) |
| 306 | assert exc_info.value.code == 403 |
| 307 | |
| 308 | |
| 309 | def test_searxng_live_server_allows_same_origin_and_blocks_cross_origin_redirects(): |
| 310 | target_hits: list[str] = [] |
| 311 | |
| 312 | class TargetHandler(BaseHTTPRequestHandler): |
| 313 | def log_message(self, *_args): |
| 314 | pass |
| 315 | |
| 316 | def do_GET(self): |
| 317 | target_hits.append(self.path) |
| 318 | payload = json.dumps({"results": [{"url": "https://secret.example/1", "title": "Leaked", "content": "x"}]}).encode() |
| 319 | self.send_response(200) |
| 320 | self.send_header("Content-Type", "application/json") |
| 321 | self.send_header("Content-Length", str(len(payload))) |
| 322 | self.end_headers() |
| 323 | self.wfile.write(payload) |
| 324 | |
| 325 | target_srv, target_t, target_base = _start_server(TargetHandler) |
| 326 | |
| 327 | class SearxHandler(BaseHTTPRequestHandler): |
| 328 | def log_message(self, *_args): |
| 329 | pass |
| 330 | |
| 331 | def do_GET(self): |
| 332 | if "evil_redirect" in self.path: |
| 333 | self.send_response(302) |
| 334 | self.send_header("Location", f"{target_base}/secret") |
| 335 | self.end_headers() |
| 336 | return |
| 337 | if "meta_redirect" in self.path: |
| 338 | self.send_response(302) |
| 339 | self.send_header("Location", "http://169.254.169.254/latest/meta-data/") |
| 340 | self.end_headers() |
| 341 | return |
| 342 | if "same_origin_redir" in self.path: |
| 343 | self.send_response(302) |
| 344 | self.send_header("Location", "/search?q=final&format=json") |
| 345 | self.end_headers() |
| 346 | return |
| 347 | payload = json.dumps({ |
| 348 | "results": [{"url": "https://docs.example.org/post", "title": "OK", "content": "snippet"}] |
| 349 | }).encode() |
| 350 | self.send_response(200) |
| 351 | self.send_header("Content-Type", "application/json") |
| 352 | self.send_header("Content-Length", str(len(payload))) |
| 353 | self.end_headers() |
| 354 | self.wfile.write(payload) |
| 355 | |
| 356 | searx_srv, searx_t, searx_base = _start_server(SearxHandler) |
| 357 | try: |
| 358 | # Legitimate local self-hosted SearXNG works, including same-origin redirect. |
| 359 | items = web_search_keyless._search_searxng("same_origin_redir", 5, searx_base) |
| 360 | assert len(items) == 1 |
| 361 | assert items[0]["url"] == "https://docs.example.org/post" |
| 362 | |
| 363 | # Cross-port localhost redirect is blocked before connecting to target_srv. |
| 364 | assert web_search_keyless._search_searxng("evil_redirect", 5, searx_base) == [] |
| 365 | assert target_hits == [] |
| 366 | |
| 367 | # Redirect to cloud metadata IP is blocked cleanly without raising. |
| 368 | assert web_search_keyless._search_searxng("meta_redirect", 5, searx_base) == [] |
| 369 | finally: |
| 370 | _stop_server(searx_srv, searx_t) |
| 371 | _stop_server(target_srv, target_t) |
| 372 | |
| 373 | |
| 374 | def test_searxng_idna_normalizes_valid_idn_and_blocks_fullwidth_redirects(): |
| 375 | validated = web_search_keyless._validate_searxng_url("https://caf\u00e9.example:8443/searx/") |
| 376 | assert validated is not None |
| 377 | normalized, origin = validated |
| 378 | assert normalized == "https://xn--caf-dma.example:8443/searx" |
| 379 | assert origin == ("https", "xn--caf-dma.example", 8443) |
| 380 | |
| 381 | guard = web_search_keyless._searxng_redirect_guard(origin) |
| 382 | assert guard("http://169\uff0e254\uff0e169\uff0e254/latest") is False |
| 383 | assert guard("http://\uff4d\uff45\uff54\uff41\uff44\uff41\uff54\uff41.google.internal/") is False |
| 384 | assert guard("https://caf\u00e9.example:8443/search?q=1") is True |
| 385 | |
| 386 | |
| 387 | @pytest.mark.parametrize( |
| 388 | "resolved_addrs", |
| 389 | [ |
| 390 | [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", 80))], |
| 391 | [(socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("fe80::1", 80, 0, 0))], |
| 392 | [(socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("fd00:ec2::254", 80, 0, 0))], |
| 393 | [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("100.100.100.200", 80))], |
| 394 | [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("0.0.0.0", 80))], |
| 395 | [(socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("::", 80, 0, 0))], |
| 396 | [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("224.0.0.1", 80))], |
| 397 | [ |
| 398 | (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", 80)), |
| 399 | (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", 80)), |
| 400 | ], |
| 401 | ], |
| 402 | ) |
| 403 | def test_searxng_blocks_dns_rebinding_to_imds_and_disallowed_ips_at_connect( |
| 404 | monkeypatch, resolved_addrs, |
| 405 | ): |
| 406 | connect_calls: list[object] = [] |
| 407 | |
| 408 | def fail_connect(self, addr): |
| 409 | connect_calls.append(addr) |
| 410 | raise AssertionError(f"socket.connect should never be called for blocked IP {addr}") |
| 411 | |
| 412 | monkeypatch.setattr(http.socket, "getaddrinfo", lambda *_a, **_kw: resolved_addrs) |
| 413 | monkeypatch.setattr(socket.socket, "connect", fail_connect) |
| 414 | |
| 415 | items = web_search_keyless._search_searxng("topic", 5, "http://169.254.169.254.nip.io") |
| 416 | assert items == [] |
| 417 | assert connect_calls == [] |
| 418 | |
| 419 | |
| 420 | def test_searxng_connect_time_dns_validation_allows_hostname_resolving_to_loopback(monkeypatch): |
| 421 | class LoopbackSearxHandler(BaseHTTPRequestHandler): |
| 422 | def log_message(self, *_args): |
| 423 | pass |
| 424 | |
| 425 | def do_GET(self): |
| 426 | payload = json.dumps({ |
| 427 | "results": [{"url": "https://example.org/local", "title": "Local OK", "content": "hi"}] |
| 428 | }).encode() |
| 429 | self.send_response(200) |
| 430 | self.send_header("Content-Type", "application/json") |
| 431 | self.send_header("Content-Length", str(len(payload))) |
| 432 | self.end_headers() |
| 433 | self.wfile.write(payload) |
| 434 | |
| 435 | srv, thread, _base = _start_server(LoopbackSearxHandler) |
| 436 | port = srv.server_port |
| 437 | try: |
| 438 | monkeypatch.setattr( |
| 439 | http.socket, |
| 440 | "getaddrinfo", |
| 441 | lambda host, p, *_a, **_kw: [ |
| 442 | (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", int(p or port))) |
| 443 | ], |
| 444 | ) |
| 445 | items = web_search_keyless._search_searxng("topic", 5, f"http://local-searx.example:{port}") |
| 446 | assert len(items) == 1 |
| 447 | assert items[0]["url"] == "https://example.org/local" |
| 448 | finally: |
| 449 | _stop_server(srv, thread) |
| 450 | |
| 451 | |
| 452 | # --------------------------------------------------------------------------- |
| 453 | # HIGH-204: Bounded reads & errors="replace" decoding without UnicodeDecodeError |
| 454 | # --------------------------------------------------------------------------- |
| 455 | |
| 456 | |
| 457 | def test_keyless_search_bounds_reads_and_decodes_invalid_utf8_without_raising(monkeypatch): |
| 458 | class MixedHandler(BaseHTTPRequestHandler): |
| 459 | def log_message(self, *_args): |
| 460 | pass |
| 461 | |
| 462 | def do_GET(self): |
| 463 | if "oversized" in self.path: |
| 464 | body = b'{"results":[' + (b" " * 4096) + b"]}" |
| 465 | self.send_response(200) |
| 466 | self.send_header("Content-Length", str(len(body))) |
| 467 | self.end_headers() |
| 468 | try: |
| 469 | self.wfile.write(body) |
| 470 | except OSError: |
| 471 | pass |
| 472 | return |
| 473 | if "latin1_json" in self.path: |
| 474 | body = b'{"results":[{"url":"https://example.com/cafe","title":"Caf\xe9","content":"ok"}]}' |
| 475 | self.send_response(200) |
| 476 | self.send_header("Content-Length", str(len(body))) |
| 477 | self.end_headers() |
| 478 | self.wfile.write(body) |
| 479 | return |
| 480 | if "latin1_html" in self.path: |
| 481 | body = ( |
| 482 | b'<a class="result__a" href="https://example.com/cafe">Caf\xe9 Guide</a>' |
| 483 | b'<a class="result__snippet" href="//x">Best caf\xe9 spots</a>' |
| 484 | ) |
| 485 | self.send_response(200) |
| 486 | self.send_header("Content-Length", str(len(body))) |
| 487 | self.end_headers() |
| 488 | self.wfile.write(body) |
| 489 | return |
| 490 | if "bad_shape" in self.path: |
| 491 | body = b'{"results": 42}' |
| 492 | self.send_response(200) |
| 493 | self.send_header("Content-Length", str(len(body))) |
| 494 | self.end_headers() |
| 495 | self.wfile.write(body) |
| 496 | return |
| 497 | self.send_response(404) |
| 498 | self.end_headers() |
| 499 | |
| 500 | srv, thread, base = _start_server(MixedHandler) |
| 501 | try: |
| 502 | # 1. Oversized SearXNG response rejected by max_bytes without raising. |
| 503 | monkeypatch.setattr(web_search_keyless, "_MAX_SEARXNG_BYTES", 512) |
| 504 | assert web_search_keyless._search_searxng("oversized", 5, base) == [] |
| 505 | |
| 506 | # 2. Non-UTF-8 byte in SearXNG JSON decoded with replacement, no UnicodeDecodeError. |
| 507 | items = web_search_keyless._search_searxng("latin1_json", 5, base) |
| 508 | assert len(items) == 1 |
| 509 | assert items[0]["url"] == "https://example.com/cafe" |
| 510 | assert items[0]["title"] == "Caf\ufffd" |
| 511 | |
| 512 | # 3. Non-UTF-8 byte in HTML fetched with http.get_text(..., decode_errors="replace"). |
| 513 | html_text = http.get_text( |
| 514 | f"{base}/latin1_html", retries=1, max_bytes=4096, decode_errors="replace", |
| 515 | ) |
| 516 | assert html_text is not None |
| 517 | parsed = web_search_keyless.parse_ddg(html_text, 5) |
| 518 | assert len(parsed) == 1 |
| 519 | assert parsed[0]["title"] == "Caf\ufffd Guide" |
| 520 | assert parsed[0]["snippet"] == "Best caf\ufffd spots" |
| 521 | |
| 522 | # 4. Hostile JSON shape degrades cleanly. |
| 523 | assert web_search_keyless._search_searxng("bad_shape", 5, base) == [] |
| 524 | |
| 525 | # 5. Even if a mocked transport raises UnicodeDecodeError or ValueError, |
| 526 | # _fetch_page and keyless_search never raise. |
| 527 | with patch.object( |
| 528 | web_search_keyless.http, |
| 529 | "get_text", |
| 530 | side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "bad byte"), |
| 531 | ): |
| 532 | items, artifact = web_search_keyless.keyless_search( |
| 533 | "topic", ("2026-10-01", "2026-11-01"), {} |
| 534 | ) |
| 535 | assert items == [] |
| 536 | assert artifact["reason"] == "keyless-search-unavailable" |
| 537 | assert artifact["keyless_rungs"]["ddg"] == web_search_keyless.ERROR |
| 538 | finally: |
| 539 | _stop_server(srv, thread) |
| 540 | |
| 541 | |
| 542 | def test_web_fetch_keyless_enforces_4mib_bound_and_replace_decoding(monkeypatch): |
| 543 | with patch.object(web_fetch_keyless.http, "get_text", return_value="# OK") as mock_get: |
| 544 | res = web_fetch_keyless.fetch_markdown("https://example.com/article") |
| 545 | assert res.ok is True |
| 546 | assert mock_get.call_args.kwargs.get("max_bytes") == 4 * 1024 * 1024 |
| 547 | assert mock_get.call_args.kwargs.get("decode_errors") == "replace" |
| 548 | |
| 549 | # Non-UTF-8 byte in Jina markdown decodes cleanly with replacement instead of crashing. |
| 550 | resp = MagicMock() |
| 551 | resp.__enter__.return_value = resp |
| 552 | resp.__exit__.return_value = False |
| 553 | resp.status = 200 |
| 554 | resp.headers = {} |
| 555 | resp.read.return_value = b"# Caf\xe9 Notes\n\nBody text." |
| 556 | with patch.object(web_fetch_keyless.http, "_open_request", return_value=resp): |
| 557 | res = web_fetch_keyless.fetch_markdown("https://example.com/cafe") |
| 558 | assert res.ok is True |
| 559 | assert "Caf\ufffd Notes" in res.markdown |
| 560 | |
| 561 | # Oversized reader response fails cleanly without raising. |
| 562 | monkeypatch.setattr(web_fetch_keyless, "_MAX_MARKDOWN_BYTES", 64) |
| 563 | big_resp = MagicMock() |
| 564 | big_resp.__enter__.return_value = big_resp |
| 565 | big_resp.__exit__.return_value = False |
| 566 | big_resp.status = 200 |
| 567 | big_resp.headers = {"Content-Length": "2048"} |
| 568 | big_resp.read.return_value = b"A" * 2048 |
| 569 | with patch.object(web_fetch_keyless.http, "_open_request", return_value=big_resp): |
| 570 | res = web_fetch_keyless.fetch_markdown("https://example.com/huge") |
| 571 | assert res.ok is False |
| 572 | assert res.reason == "fetch-failed" |
| 573 | |
| 574 | |
| 575 | # --------------------------------------------------------------------------- |
| 576 | # HIGH-205: Parallel MCP SSE slow-loris deadline, cancel, caps & DELETE cleanup |
| 577 | # --------------------------------------------------------------------------- |
| 578 | |
| 579 | |
| 580 | def test_parallel_mcp_sse_slow_loris_heartbeats_and_trickle_hit_wall_deadline(monkeypatch): |
| 581 | stop_server_writes = threading.Event() |
| 582 | |
| 583 | class SlowSSEHandler(BaseHTTPRequestHandler): |
| 584 | protocol_version = "HTTP/1.1" |
| 585 | |
| 586 | def log_message(self, *_args): |
| 587 | pass |
| 588 | |
| 589 | def do_POST(self): |
| 590 | self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 591 | self.send_response(200) |
| 592 | self.send_header("Content-Type", "text/event-stream") |
| 593 | self.send_header("Connection", "close") |
| 594 | self.end_headers() |
| 595 | chunk = b":\n" if "lines" in self.path else b":" |
| 596 | while not stop_server_writes.is_set(): |
| 597 | try: |
| 598 | self.wfile.write(chunk) |
| 599 | self.wfile.flush() |
| 600 | except OSError: |
| 601 | break |
| 602 | stop_server_writes.wait(0.04) |
| 603 | |
| 604 | srv, thread, base = _start_server(SlowSSEHandler) |
| 605 | try: |
| 606 | for mode in ("lines", "bytes"): |
| 607 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/{mode}") |
| 608 | started = time.monotonic() |
| 609 | with pytest.raises(http.DeadlineExceeded): |
| 610 | parallel_mcp._request( |
| 611 | {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, |
| 612 | None, |
| 613 | deadline_monotonic=started + 0.25, |
| 614 | ) |
| 615 | elapsed = time.monotonic() - started |
| 616 | assert elapsed < 1.0, f"slow-loris ({mode}) stalled for {elapsed:.2f}s" |
| 617 | finally: |
| 618 | stop_server_writes.set() |
| 619 | _stop_server(srv, thread) |
| 620 | |
| 621 | |
| 622 | def test_parallel_mcp_cancel_event_aborts_in_flight_sse_promptly(monkeypatch): |
| 623 | release = threading.Event() |
| 624 | |
| 625 | class HangingSSEHandler(BaseHTTPRequestHandler): |
| 626 | protocol_version = "HTTP/1.1" |
| 627 | |
| 628 | def log_message(self, *_args): |
| 629 | pass |
| 630 | |
| 631 | def do_POST(self): |
| 632 | self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 633 | self.send_response(200) |
| 634 | self.send_header("Content-Type", "text/event-stream") |
| 635 | self.send_header("Connection", "close") |
| 636 | self.end_headers() |
| 637 | self.wfile.write(b": heartbeat\n\n") |
| 638 | self.wfile.flush() |
| 639 | release.wait(10) |
| 640 | |
| 641 | srv, thread, base = _start_server(HangingSSEHandler) |
| 642 | try: |
| 643 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/mcp") |
| 644 | cancel = threading.Event() |
| 645 | threading.Timer(0.15, cancel.set).start() |
| 646 | started = time.monotonic() |
| 647 | with pytest.raises(http.DeadlineExceeded): |
| 648 | parallel_mcp.search( |
| 649 | "topic", |
| 650 | ("2026-10-01", "2026-11-01"), |
| 651 | deadline_monotonic=started + 10.0, |
| 652 | cancel=cancel, |
| 653 | ) |
| 654 | elapsed = time.monotonic() - started |
| 655 | assert elapsed < 1.0, f"cancel took {elapsed:.2f}s" |
| 656 | finally: |
| 657 | release.set() |
| 658 | _stop_server(srv, thread) |
| 659 | |
| 660 | |
| 661 | def test_parallel_mcp_sse_enforces_line_and_event_caps(monkeypatch): |
| 662 | class FakeSSEResp: |
| 663 | headers = {"Content-Type": "text/event-stream"} |
| 664 | |
| 665 | def __init__(self, raw: bytes): |
| 666 | self._bio = io.BytesIO(raw) |
| 667 | |
| 668 | def readline(self, size=-1): |
| 669 | return self._bio.readline(size) |
| 670 | |
| 671 | monkeypatch.setattr(parallel_mcp, "_MAX_SSE_LINES", 20) |
| 672 | with pytest.raises(RuntimeError, match="line limit"): |
| 673 | parallel_mcp._read_response(FakeSSEResp(b":\n" * 25), 3) |
| 674 | |
| 675 | monkeypatch.setattr(parallel_mcp, "_MAX_SSE_LINES", 500) |
| 676 | monkeypatch.setattr(parallel_mcp, "_MAX_SSE_EVENTS", 5) |
| 677 | notif = b'data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n' |
| 678 | with pytest.raises(RuntimeError, match="event limit"): |
| 679 | parallel_mcp._read_response(FakeSSEResp(notif * 10), 3) |
| 680 | |
| 681 | |
| 682 | def test_parallel_mcp_bounds_tools_list_pagination_and_total_requests(): |
| 683 | calls: list[dict | None] = [] |
| 684 | |
| 685 | def fake_request(message, _api_key, _session_id=None): |
| 686 | calls.append(message) |
| 687 | if message is None: |
| 688 | return {}, None |
| 689 | method = message.get("method") |
| 690 | if method == "initialize": |
| 691 | return {"result": {"protocolVersion": parallel_mcp._PROTOCOL_VERSION}}, "sess-1" |
| 692 | if method == "notifications/initialized": |
| 693 | return {}, "sess-1" |
| 694 | if method == "tools/list": |
| 695 | idx = len(calls) |
| 696 | return {"result": {"tools": [{"name": "other"}], "nextCursor": f"cursor-{idx}"}}, "sess-1" |
| 697 | raise AssertionError(f"unexpected method {method}") |
| 698 | |
| 699 | with patch.object(parallel_mcp, "_request", side_effect=fake_request): |
| 700 | with pytest.raises(RuntimeError, match="did not advertise web_search"): |
| 701 | parallel_mcp.search("topic", ("2026-10-01", "2026-11-01")) |
| 702 | |
| 703 | tools_list_calls = [m for m in calls if m is not None and m.get("method") == "tools/list"] |
| 704 | assert len(tools_list_calls) == parallel_mcp._MAX_TOOLS_LIST_PAGES |
| 705 | assert len(calls) <= parallel_mcp._MAX_SESSION_REQUESTS |
| 706 | assert calls[-1] is None # DELETE cleanup still ran within budget |
| 707 | |
| 708 | |
| 709 | def test_parallel_mcp_cleanup_delete_is_short_bounded_and_skipped_after_deadline(monkeypatch): |
| 710 | delete_seen: list[str] = [] |
| 711 | release_delete = threading.Event() |
| 712 | |
| 713 | class HangingDeleteHandler(BaseHTTPRequestHandler): |
| 714 | protocol_version = "HTTP/1.1" |
| 715 | |
| 716 | def log_message(self, *_args): |
| 717 | pass |
| 718 | |
| 719 | def do_POST(self): |
| 720 | body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) |
| 721 | method = body.get("method") |
| 722 | if method == "initialize": |
| 723 | reply = {"jsonrpc": "2.0", "id": body["id"], "result": {"protocolVersion": parallel_mcp._PROTOCOL_VERSION}} |
| 724 | raw = json.dumps(reply).encode() |
| 725 | self.send_response(200) |
| 726 | self.send_header("Content-Type", "application/json") |
| 727 | self.send_header("Mcp-Session-Id", "sess-hang") |
| 728 | self.send_header("Content-Length", str(len(raw))) |
| 729 | self.end_headers() |
| 730 | self.wfile.write(raw) |
| 731 | return |
| 732 | if method == "notifications/initialized": |
| 733 | self.send_response(202) |
| 734 | self.send_header("Content-Length", "0") |
| 735 | self.end_headers() |
| 736 | return |
| 737 | if method == "tools/list": |
| 738 | if "slow_tools" in self.path: |
| 739 | release_delete.wait(5) |
| 740 | return |
| 741 | reply = {"jsonrpc": "2.0", "id": body["id"], "error": {"message": "upstream boom"}} |
| 742 | raw = json.dumps(reply).encode() |
| 743 | self.send_response(200) |
| 744 | self.send_header("Content-Type", "application/json") |
| 745 | self.send_header("Content-Length", str(len(raw))) |
| 746 | self.end_headers() |
| 747 | self.wfile.write(raw) |
| 748 | return |
| 749 | |
| 750 | def do_DELETE(self): |
| 751 | delete_seen.append(self.path) |
| 752 | release_delete.wait(10) |
| 753 | |
| 754 | srv, thread, base = _start_server(HangingDeleteHandler) |
| 755 | try: |
| 756 | # Case 1: Upstream fails before deadline, DELETE hangs -> capped at _CLEANUP_TIMEOUT. |
| 757 | monkeypatch.setattr(parallel_mcp, "_CLEANUP_TIMEOUT", 0.25) |
| 758 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/fast_fail") |
| 759 | started = time.monotonic() |
| 760 | with pytest.raises(RuntimeError, match="upstream boom"): |
| 761 | parallel_mcp.search( |
| 762 | "topic", ("2026-10-01", "2026-11-01"), deadline_monotonic=started + 5.0, |
| 763 | ) |
| 764 | elapsed = time.monotonic() - started |
| 765 | assert elapsed < 1.0, f"hanging DELETE stalled for {elapsed:.2f}s" |
| 766 | assert len(delete_seen) == 1 |
| 767 | |
| 768 | # Case 2: Search itself exceeds deadline -> DELETE is skipped completely. |
| 769 | delete_seen.clear() |
| 770 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/slow_tools") |
| 771 | started = time.monotonic() |
| 772 | with pytest.raises(http.DeadlineExceeded): |
| 773 | parallel_mcp.search( |
| 774 | "topic", ("2026-10-01", "2026-11-01"), deadline_monotonic=started + 0.25, |
| 775 | ) |
| 776 | elapsed = time.monotonic() - started |
| 777 | assert elapsed < 1.0, f"expired deadline search stalled for {elapsed:.2f}s" |
| 778 | assert delete_seen == [] |
| 779 | finally: |
| 780 | release_delete.set() |
| 781 | _stop_server(srv, thread) |
| 782 | |
| 783 | |
| 784 | def test_parallel_mcp_scrubs_api_key_in_errors_and_rejects_bad_utf8_json(): |
| 785 | with pytest.raises(RuntimeError) as exc_info: |
| 786 | parallel_mcp._result( |
| 787 | {"error": {"message": "Invalid key secret-parallel-token-999"}}, |
| 788 | redactions=frozenset({"secret-parallel-token-999"}), |
| 789 | ) |
| 790 | assert "secret-parallel-token-999" not in str(exc_info.value) |
| 791 | assert "<redacted>" in str(exc_info.value) |
| 792 | |
| 793 | with pytest.raises(RuntimeError, match="invalid JSON-RPC response"): |
| 794 | parallel_mcp._matching_response(b"\xff\xfe", 1) |
| 795 | |
| 796 | |
| 797 | def test_parallel_mcp_cleanup_swallows_http_client_bad_status_line(): |
| 798 | responses = [ |
| 799 | ({"result": {"protocolVersion": parallel_mcp._PROTOCOL_VERSION}}, "sess-bad-delete"), |
| 800 | ({}, "sess-bad-delete"), |
| 801 | ({"result": {"tools": [{"name": "web_search"}]}}, "sess-bad-delete"), |
| 802 | ( |
| 803 | { |
| 804 | "result": { |
| 805 | "structuredContent": { |
| 806 | "results": [ |
| 807 | { |
| 808 | "url": "https://example.com/kept", |
| 809 | "title": "Kept Result", |
| 810 | "publish_date": "2026-10-15", |
| 811 | "excerpts": ["Still returned after DELETE BadStatusLine"], |
| 812 | } |
| 813 | ] |
| 814 | } |
| 815 | } |
| 816 | }, |
| 817 | "sess-bad-delete", |
| 818 | ), |
| 819 | http_client.BadStatusLine("MALFORMED-DELETE-REPLY"), |
| 820 | ] |
| 821 | with patch.object(parallel_mcp, "_request", side_effect=responses): |
| 822 | items, artifact = parallel_mcp.search("topic", ("2026-10-01", "2026-11-01")) |
| 823 | assert len(items) == 1 |
| 824 | assert items[0]["url"] == "https://example.com/kept" |
| 825 | assert artifact["resultCount"] == 1 |
| 826 | |
| 827 | |
| 828 | def test_parallel_mcp_cleanup_swallows_live_malformed_delete_response(monkeypatch): |
| 829 | class MalformedDeleteHandler(BaseHTTPRequestHandler): |
| 830 | protocol_version = "HTTP/1.1" |
| 831 | |
| 832 | def log_message(self, *_args): |
| 833 | pass |
| 834 | |
| 835 | def do_POST(self): |
| 836 | body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))) |
| 837 | method = body.get("method") |
| 838 | if method == "initialize": |
| 839 | reply = {"jsonrpc": "2.0", "id": body["id"], "result": {"protocolVersion": parallel_mcp._PROTOCOL_VERSION}} |
| 840 | raw = json.dumps(reply).encode() |
| 841 | self.send_response(200) |
| 842 | self.send_header("Content-Type", "application/json") |
| 843 | self.send_header("Mcp-Session-Id", "sess-live-bad") |
| 844 | self.send_header("Content-Length", str(len(raw))) |
| 845 | self.end_headers() |
| 846 | self.wfile.write(raw) |
| 847 | return |
| 848 | if method == "notifications/initialized": |
| 849 | self.send_response(202) |
| 850 | self.send_header("Content-Length", "0") |
| 851 | self.end_headers() |
| 852 | return |
| 853 | if method == "tools/list": |
| 854 | reply = {"jsonrpc": "2.0", "id": body["id"], "result": {"tools": [{"name": "web_search"}]}} |
| 855 | else: |
| 856 | reply = { |
| 857 | "jsonrpc": "2.0", |
| 858 | "id": body["id"], |
| 859 | "result": { |
| 860 | "structuredContent": { |
| 861 | "results": [ |
| 862 | { |
| 863 | "url": "https://example.com/live-kept", |
| 864 | "title": "Live Kept", |
| 865 | "publish_date": "2026-10-20", |
| 866 | "excerpts": ["Survives malformed DELETE"], |
| 867 | } |
| 868 | ] |
| 869 | } |
| 870 | }, |
| 871 | } |
| 872 | raw = json.dumps(reply).encode() |
| 873 | self.send_response(200) |
| 874 | self.send_header("Content-Type", "application/json") |
| 875 | self.send_header("Content-Length", str(len(raw))) |
| 876 | self.end_headers() |
| 877 | self.wfile.write(raw) |
| 878 | |
| 879 | def do_DELETE(self): |
| 880 | # Send invalid HTTP status line directly on the socket to trigger BadStatusLine. |
| 881 | self.wfile.write(b"NOT-AN-HTTP-STATUS-LINE\r\n\r\n") |
| 882 | self.wfile.flush() |
| 883 | self.close_connection = True |
| 884 | |
| 885 | srv, thread, base = _start_server(MalformedDeleteHandler) |
| 886 | try: |
| 887 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/mcp") |
| 888 | items, artifact = parallel_mcp.search("topic", ("2026-10-01", "2026-11-01")) |
| 889 | assert len(items) == 1 |
| 890 | assert items[0]["url"] == "https://example.com/live-kept" |
| 891 | assert artifact["resultCount"] == 1 |
| 892 | finally: |
| 893 | _stop_server(srv, thread) |
| 894 | |
| 895 | |
| 896 | def test_parallel_mcp_abort_handles_socket_without_shutdown_and_early_wake_jitter(): |
| 897 | class MinimalSock: |
| 898 | pass |
| 899 | |
| 900 | class CustomResp: |
| 901 | _sock = MinimalSock() |
| 902 | |
| 903 | # Must not raise AttributeError when _sock lacks shutdown(). |
| 904 | parallel_mcp._abort_response(CustomResp()) |
| 905 | |
| 906 | # Early timer wake within _DEADLINE_JITTER_SECONDS converts TimeoutError to DeadlineExceeded. |
| 907 | class EarlyTimeoutSSEResp: |
| 908 | headers = {"Content-Type": "text/event-stream"} |
| 909 | |
| 910 | def readline(self, _size=-1): |
| 911 | raise TimeoutError("timed out slightly early") |
| 912 | |
| 913 | deadline = time.monotonic() + 0.01 # 10ms remaining (< 50ms jitter tolerance) |
| 914 | with pytest.raises(http.DeadlineExceeded): |
| 915 | parallel_mcp._read_response(EarlyTimeoutSSEResp(), 1, deadline_monotonic=deadline) |
| 916 | |
| 917 | |
| 918 | def test_parallel_mcp_aborts_slow_stalled_headers_and_exits_worker_thread(monkeypatch): |
| 919 | stop_headers = threading.Event() |
| 920 | started_threads: list[threading.Thread] = [] |
| 921 | real_thread_cls = threading.Thread |
| 922 | |
| 923 | class TrackingThread(real_thread_cls): |
| 924 | def start(self): |
| 925 | if self.name == "parallel-mcp-request": |
| 926 | started_threads.append(self) |
| 927 | return super().start() |
| 928 | |
| 929 | class SlowHeadersHandler(BaseHTTPRequestHandler): |
| 930 | protocol_version = "HTTP/1.1" |
| 931 | |
| 932 | def log_message(self, *_args): |
| 933 | pass |
| 934 | |
| 935 | def do_POST(self): |
| 936 | self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 937 | # Send status line and drip partial headers without ever sending \r\n\r\n. |
| 938 | try: |
| 939 | self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n") |
| 940 | self.wfile.flush() |
| 941 | counter = 0 |
| 942 | while not stop_headers.is_set(): |
| 943 | counter += 1 |
| 944 | self.wfile.write(f"X-Slow-{counter}: 1\r\n".encode()) |
| 945 | self.wfile.flush() |
| 946 | stop_headers.wait(0.04) |
| 947 | except OSError: |
| 948 | pass |
| 949 | |
| 950 | srv, srv_thread, base = _start_server(SlowHeadersHandler) |
| 951 | try: |
| 952 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/slow-headers") |
| 953 | monkeypatch.setattr(parallel_mcp.threading, "Thread", TrackingThread) |
| 954 | started = time.monotonic() |
| 955 | with pytest.raises(http.DeadlineExceeded): |
| 956 | parallel_mcp.search( |
| 957 | "topic", |
| 958 | ("2026-10-01", "2026-11-01"), |
| 959 | deadline_monotonic=started + 0.25, |
| 960 | ) |
| 961 | elapsed = time.monotonic() - started |
| 962 | assert elapsed < 1.0, f"stalled headers took {elapsed:.2f}s" |
| 963 | assert len(started_threads) == 1 |
| 964 | started_threads[0].join(timeout=1.0) |
| 965 | assert started_threads[0].is_alive() is False, "worker thread leaked after stalled headers abort" |
| 966 | finally: |
| 967 | stop_headers.set() |
| 968 | _stop_server(srv, srv_thread) |
| 969 | |
| 970 | |
| 971 | def test_grounding_threads_deadline_and_cancel_to_parallel_mcp(monkeypatch): |
| 972 | seen_requests: list[object] = [] |
| 973 | |
| 974 | def fail_open(*_args, **_kwargs): |
| 975 | seen_requests.append(_args) |
| 976 | raise AssertionError("No HTTP requests should be issued when deadline expired or cancelled") |
| 977 | |
| 978 | monkeypatch.setattr(parallel_mcp.urllib.request.OpenerDirector, "open", fail_open) |
| 979 | |
| 980 | # 1. Expired deadline via pipeline config key `_research_deadline`. |
| 981 | with pytest.raises(http.DeadlineExceeded): |
| 982 | grounding.web_search( |
| 983 | "topic", |
| 984 | ("2026-10-01", "2026-11-01"), |
| 985 | {"PARALLEL_API_KEY": "secret-key-999", "_research_deadline": time.monotonic() - 1.0}, |
| 986 | backend="parallel-mcp", |
| 987 | ) |
| 988 | |
| 989 | # 2. Triggered cancel event via pipeline config key `_enrich_cancel`. |
| 990 | cancel = threading.Event() |
| 991 | cancel.set() |
| 992 | with pytest.raises(http.DeadlineExceeded): |
| 993 | grounding.web_search( |
| 994 | "topic", |
| 995 | ("2026-10-01", "2026-11-01"), |
| 996 | {"PARALLEL_API_KEY": "secret-key-999", "_enrich_cancel": cancel}, |
| 997 | backend="parallel-mcp", |
| 998 | ) |
| 999 | |
| 1000 | # 3. Direct keyword arguments on grounding.web_search(). |
| 1001 | with pytest.raises(http.DeadlineExceeded): |
| 1002 | grounding.web_search( |
| 1003 | "topic", |
| 1004 | ("2026-10-01", "2026-11-01"), |
| 1005 | {}, |
| 1006 | backend="parallel-mcp", |
| 1007 | deadline_monotonic=time.monotonic() - 1.0, |
| 1008 | ) |
| 1009 | |
| 1010 | assert seen_requests == [] |
| 1011 | |
| 1012 | |
| 1013 | def test_parallel_mcp_set_response_timeout_clamps_to_min_request_timeout_and_remaining(): |
| 1014 | class RecordingSock: |
| 1015 | def __init__(self): |
| 1016 | self.timeouts: list[float] = [] |
| 1017 | |
| 1018 | def settimeout(self, val): |
| 1019 | self.timeouts.append(val) |
| 1020 | |
| 1021 | class FakeResp: |
| 1022 | def __init__(self): |
| 1023 | self._sock = RecordingSock() |
| 1024 | |
| 1025 | resp = FakeResp() |
| 1026 | clamped = parallel_mcp._set_response_timeout(resp, 55.0, request_timeout=30.0) |
| 1027 | assert resp._sock.timeouts[-1] == 30.0 |
| 1028 | assert clamped is False |
| 1029 | |
| 1030 | clamped = parallel_mcp._set_response_timeout(resp, 5.0, request_timeout=30.0) |
| 1031 | assert resp._sock.timeouts[-1] == 5.0 |
| 1032 | assert clamped is True |
| 1033 | |
| 1034 | |
| 1035 | def test_parallel_mcp_sse_long_line_in_small_chunks_is_linear(): |
| 1036 | # 512 KiB single SSE data line arriving in 64-byte chunks (~8,192 chunks). |
| 1037 | # Quadratic buf.find(b"\n") rescanning would scan ~2 GiB; linear scan_pos scans 512 KiB. |
| 1038 | padding = "a" * (512 * 1024) |
| 1039 | line = ( |
| 1040 | b'data: {"jsonrpc":"2.0","id":7,"result":{"pad":"' |
| 1041 | + padding.encode("ascii") |
| 1042 | + b'"}}\n\n' |
| 1043 | ) |
| 1044 | |
| 1045 | class SmallChunkSSEResp: |
| 1046 | headers = {"Content-Type": "text/event-stream"} |
| 1047 | |
| 1048 | def __init__(self, raw: bytes, chunk_size: int = 64): |
| 1049 | self._raw = raw |
| 1050 | self._pos = 0 |
| 1051 | self._chunk_size = chunk_size |
| 1052 | |
| 1053 | def read1(self, size=-1): |
| 1054 | if self._pos >= len(self._raw): |
| 1055 | return b"" |
| 1056 | n = self._chunk_size if size < 0 else min(self._chunk_size, size) |
| 1057 | out = self._raw[self._pos:self._pos + n] |
| 1058 | self._pos += len(out) |
| 1059 | return out |
| 1060 | |
| 1061 | started = time.monotonic() |
| 1062 | result = parallel_mcp._read_response(SmallChunkSSEResp(line, chunk_size=64), 7) |
| 1063 | elapsed = time.monotonic() - started |
| 1064 | assert result["id"] == 7 |
| 1065 | assert len(result["result"]["pad"]) == len(padding) |
| 1066 | assert elapsed < 0.5, f"chunked long SSE line took {elapsed:.4f}s (possible O(N^2) rescan)" |
| 1067 | |
| 1068 | |
| 1069 | def test_parallel_mcp_scrubs_bearer_key_from_http_error_reason(monkeypatch): |
| 1070 | secret = "pl_live_super_secret_token_987654" |
| 1071 | |
| 1072 | class SecretEchoErrorHandler(BaseHTTPRequestHandler): |
| 1073 | protocol_version = "HTTP/1.1" |
| 1074 | |
| 1075 | def log_message(self, *_args): |
| 1076 | pass |
| 1077 | |
| 1078 | def do_POST(self): |
| 1079 | self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 1080 | status = 401 if "401" in self.path else 500 |
| 1081 | self.send_response( |
| 1082 | status, |
| 1083 | f"Rejected Bearer {secret} for key {secret} via https://u:{secret}@proxy.internal", |
| 1084 | ) |
| 1085 | self.send_header("Content-Length", "0") |
| 1086 | self.end_headers() |
| 1087 | |
| 1088 | srv, thread, base = _start_server(SecretEchoErrorHandler) |
| 1089 | try: |
| 1090 | for status in (401, 500): |
| 1091 | monkeypatch.setattr(parallel_mcp, "PARALLEL_MCP_URL", f"{base}/{status}") |
| 1092 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 1093 | parallel_mcp._request( |
| 1094 | {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}, |
| 1095 | secret, |
| 1096 | ) |
| 1097 | err = exc_info.value |
| 1098 | try: |
| 1099 | assert err.code == status |
| 1100 | assert secret not in str(err) |
| 1101 | assert secret not in str(err.reason) |
| 1102 | assert "<redacted>" in str(err.reason) |
| 1103 | finally: |
| 1104 | err.close() |
| 1105 | finally: |
| 1106 | _stop_server(srv, thread) |
| 1107 | |
| 1108 | |
| 1109 | def test_parallel_mcp_run_deadline_only_shortens_never_extends_60s_cap(): |
| 1110 | observed_deadlines: list[float] = [] |
| 1111 | |
| 1112 | def capture_budget(message, _api_key, _session_id=None): |
| 1113 | budget = parallel_mcp._REQUEST_BUDGET.get() |
| 1114 | assert budget is not None and budget[0] is not None |
| 1115 | observed_deadlines.append(budget[0]) |
| 1116 | if message is None: |
| 1117 | return {}, None |
| 1118 | method = message.get("method") |
| 1119 | if method == "initialize": |
| 1120 | return {"result": {"protocolVersion": parallel_mcp._PROTOCOL_VERSION}}, "sess-cap" |
| 1121 | if method == "notifications/initialized": |
| 1122 | return {}, "sess-cap" |
| 1123 | if method == "tools/list": |
| 1124 | return {"result": {"tools": [{"name": "web_search"}]}}, "sess-cap" |
| 1125 | if method == "tools/call": |
| 1126 | return {"result": {"structuredContent": {"results": []}}}, "sess-cap" |
| 1127 | raise AssertionError(f"unexpected method {method}") |
| 1128 | |
| 1129 | # Direct parallel_mcp.search() with 180s deadline must still cap at <= 60s. |
| 1130 | now = time.monotonic() |
| 1131 | with patch.object(parallel_mcp, "_request", side_effect=capture_budget): |
| 1132 | parallel_mcp.search( |
| 1133 | "topic", ("2026-10-01", "2026-11-01"), deadline_monotonic=now + 180.0, |
| 1134 | ) |
| 1135 | assert observed_deadlines |
| 1136 | assert observed_deadlines[0] <= time.monotonic() + parallel_mcp._DEFAULT_SEARCH_TIMEOUT + 1.0 |
| 1137 | assert observed_deadlines[0] < now + 100.0 |
| 1138 | |
| 1139 | # Via grounding.web_search() with 180s pipeline `_research_deadline`. |
| 1140 | observed_deadlines.clear() |
| 1141 | now = time.monotonic() |
| 1142 | with patch.object(parallel_mcp, "_request", side_effect=capture_budget): |
| 1143 | grounding.web_search( |
| 1144 | "topic", |
| 1145 | ("2026-10-01", "2026-11-01"), |
| 1146 | {"_research_deadline": now + 180.0}, |
| 1147 | backend="parallel-mcp", |
| 1148 | ) |
| 1149 | assert observed_deadlines |
| 1150 | assert observed_deadlines[0] <= time.monotonic() + parallel_mcp._DEFAULT_SEARCH_TIMEOUT + 1.0 |
| 1151 | assert observed_deadlines[0] < now + 100.0 |
| 1152 | |
| 1153 | # Shorter caller deadline (e.g. 5s) IS respected and shortens the 60s cap. |
| 1154 | observed_deadlines.clear() |
| 1155 | now = time.monotonic() |
| 1156 | short_deadline = now + 5.0 |
| 1157 | with patch.object(parallel_mcp, "_request", side_effect=capture_budget): |
| 1158 | parallel_mcp.search( |
| 1159 | "topic", ("2026-10-01", "2026-11-01"), deadline_monotonic=short_deadline, |
| 1160 | ) |
| 1161 | assert observed_deadlines |
| 1162 | assert abs(observed_deadlines[0] - short_deadline) < 0.01 |
| 1163 | |
| 1164 | |
| 1165 | def test_keyless_search_reports_timeout_when_cancelled_or_expired_and_keeps_found_results(): |
| 1166 | # (a1) Pre-cancelled keyless_search with 0 results reports timeout, not unavailable. |
| 1167 | cancel = threading.Event() |
| 1168 | cancel.set() |
| 1169 | with patch.object(web_search_keyless.http, "get_text") as mock_get: |
| 1170 | items, artifact = web_search_keyless.keyless_search( |
| 1171 | "topic", ("2026-10-01", "2026-11-01"), {}, cancel=cancel, |
| 1172 | ) |
| 1173 | assert items == [] |
| 1174 | mock_get.assert_not_called() |
| 1175 | assert artifact["reason"] == "keyless-search-timeout" |
| 1176 | assert artifact["reason"] != "keyless-search-unavailable" |
| 1177 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1178 | assert artifact["_source_outcome"]["attempted"] is False |
| 1179 | |
| 1180 | # (a2) Via grounding.web_search() with expired `_research_deadline`: pipeline maps to TIMEOUT. |
| 1181 | with patch.object(web_search_keyless.http, "get_text") as mock_get: |
| 1182 | items, artifact = grounding.web_search( |
| 1183 | "topic", |
| 1184 | ("2026-10-01", "2026-11-01"), |
| 1185 | {"_research_deadline": time.monotonic() - 1.0}, |
| 1186 | backend="keyless", |
| 1187 | ) |
| 1188 | assert items == [] |
| 1189 | mock_get.assert_not_called() |
| 1190 | assert artifact["reason"] == "keyless-search-timeout" |
| 1191 | resolved = pipeline._resolve_stream_outcome("grounding", artifact, []) |
| 1192 | assert resolved is not None |
| 1193 | assert resolved["state"] == health.TIMEOUT |
| 1194 | |
| 1195 | # (b) Cancellation after rung 1 already found results preserves rung 1's results. |
| 1196 | cancel_after_rung1 = threading.Event() |
| 1197 | ddg_html = ( |
| 1198 | '<a class="result__a" href="https://example.com/kept">Kept Title</a>' |
| 1199 | '<a class="result__snippet" href="//x">Kept snippet</a>' |
| 1200 | ) |
| 1201 | |
| 1202 | def ddg_then_cancel(url, *args, **kwargs): |
| 1203 | cancel_after_rung1.set() |
| 1204 | return ddg_html |
| 1205 | |
| 1206 | with patch.object(web_search_keyless.http, "get_text", side_effect=ddg_then_cancel): |
| 1207 | items, artifact = grounding.web_search( |
| 1208 | "topic", |
| 1209 | ("2026-10-01", "2026-11-01"), |
| 1210 | {"_enrich_cancel": cancel_after_rung1}, |
| 1211 | backend="keyless", |
| 1212 | ) |
| 1213 | assert len(items) == 1 |
| 1214 | assert items[0]["url"] == "https://example.com/kept" |
| 1215 | assert "reason" not in artifact |
| 1216 | assert "_source_outcome" not in artifact |
| 1217 | |
| 1218 | |
| 1219 | def test_grounding_enrich_reddit_items_forwards_deadline_and_preserves_items_on_timeout(): |
| 1220 | from lib import reddit_hydrate |
| 1221 | |
| 1222 | web_items = [ |
| 1223 | { |
| 1224 | "url": "https://www.reddit.com/r/python/comments/abc123/test_post/", |
| 1225 | "title": "Original Web Title", |
| 1226 | "snippet": "Original web snippet", |
| 1227 | }, |
| 1228 | { |
| 1229 | "url": "https://example.com/non-reddit", |
| 1230 | "title": "Example Article", |
| 1231 | "snippet": "Non-reddit snippet", |
| 1232 | }, |
| 1233 | ] |
| 1234 | seen_deadlines: list[float | None] = [] |
| 1235 | |
| 1236 | def timeout_hydrate(refs, **kwargs): |
| 1237 | seen_deadlines.append(kwargs.get("deadline")) |
| 1238 | raise http.DeadlineExceeded() |
| 1239 | |
| 1240 | deadline = time.monotonic() + 30.0 |
| 1241 | expected_enrich_deadline = deadline - grounding._REDDIT_ENRICH_HEADROOM_SECONDS |
| 1242 | with patch.object(reddit_hydrate, "hydrate", side_effect=timeout_hydrate): |
| 1243 | kept = grounding._enrich_reddit_items(list(web_items), deadline_monotonic=deadline) |
| 1244 | |
| 1245 | assert len(seen_deadlines) == 1 |
| 1246 | assert seen_deadlines[0] is not None |
| 1247 | assert seen_deadlines[0] <= expected_enrich_deadline |
| 1248 | assert seen_deadlines[0] == pytest.approx(expected_enrich_deadline) |
| 1249 | assert kept == web_items |
| 1250 | |
| 1251 | # Live path through grounding.web_search() forwards headroom-trimmed deadline into hydrate() |
| 1252 | # and keeps web results intact when optional Reddit enrichment times out. |
| 1253 | seen_deadlines.clear() |
| 1254 | with patch.object(web_search_keyless, "keyless_search", return_value=(list(web_items), {"keyless_backend": "ddg"})), \ |
| 1255 | patch.object(reddit_hydrate, "hydrate", side_effect=timeout_hydrate): |
| 1256 | items, artifact = grounding.web_search( |
| 1257 | "python", |
| 1258 | ("2026-10-01", "2026-11-01"), |
| 1259 | {"_research_deadline": deadline}, |
| 1260 | backend="keyless", |
| 1261 | ) |
| 1262 | assert len(seen_deadlines) == 1 |
| 1263 | assert seen_deadlines[0] is not None |
| 1264 | assert seen_deadlines[0] <= expected_enrich_deadline |
| 1265 | assert seen_deadlines[0] == pytest.approx(expected_enrich_deadline) |
| 1266 | assert items == web_items |
| 1267 | assert artifact["keyless_backend"] == "ddg" |
| 1268 | |
| 1269 | # When remaining run budget is within headroom (e.g. 1.0s < 3.0s), skip Reddit enrichment |
| 1270 | # completely and return the retrieved web items intact without calling hydrate(). |
| 1271 | tight_deadline = time.monotonic() + 1.0 |
| 1272 | with patch.object(web_search_keyless, "keyless_search", return_value=(list(web_items), {"keyless_backend": "ddg"})), \ |
| 1273 | patch.object(reddit_hydrate, "hydrate") as mock_hydrate: |
| 1274 | items, artifact = grounding.web_search( |
| 1275 | "python", |
| 1276 | ("2026-10-01", "2026-11-01"), |
| 1277 | {"_research_deadline": tight_deadline}, |
| 1278 | backend="keyless", |
| 1279 | ) |
| 1280 | mock_hydrate.assert_not_called() |
| 1281 | assert items == web_items |
| 1282 | assert artifact["keyless_backend"] == "ddg" |
| 1283 | |
| 1284 | # Direct _enrich_reddit_items() with tight deadline also skips hydrate() cleanly. |
| 1285 | with patch.object(reddit_hydrate, "hydrate") as mock_hydrate: |
| 1286 | kept_tight = grounding._enrich_reddit_items(list(web_items), deadline_monotonic=tight_deadline) |
| 1287 | mock_hydrate.assert_not_called() |
| 1288 | assert kept_tight == web_items |
| 1289 | |
| 1290 | |
| 1291 | def test_keyless_search_counts_searxng_attempt_when_html_rungs_skipped_and_searxng_times_out(): |
| 1292 | web_search_keyless.reset_rung_health() |
| 1293 | try: |
| 1294 | web_search_keyless.seed_rung_health({"ddg": "blocked", "startpage": "throttled"}) |
| 1295 | |
| 1296 | def searxng_timeout(*_args, **_kwargs): |
| 1297 | err = http.DeadlineExceeded() |
| 1298 | http._record_failure(err) |
| 1299 | raise err |
| 1300 | |
| 1301 | with patch.object(web_search_keyless.http, "get_text") as mock_get_text, \ |
| 1302 | patch.object(web_search_keyless.http, "get", side_effect=searxng_timeout) as mock_get: |
| 1303 | items, artifact = web_search_keyless.keyless_search( |
| 1304 | "topic", |
| 1305 | ("2026-10-01", "2026-11-01"), |
| 1306 | {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"}, |
| 1307 | deadline_monotonic=time.monotonic() + 5.0, |
| 1308 | ) |
| 1309 | mock_get_text.assert_not_called() |
| 1310 | mock_get.assert_called_once() |
| 1311 | assert items == [] |
| 1312 | assert artifact["keyless_backend"] == "searxng" |
| 1313 | assert artifact["keyless_rungs"] == {"ddg": "skipped", "startpage": "skipped"} |
| 1314 | assert artifact["reason"] == "keyless-search-timeout" |
| 1315 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1316 | assert artifact["_source_outcome"]["attempted"] is True |
| 1317 | finally: |
| 1318 | web_search_keyless.reset_rung_health() |
| 1319 | |
| 1320 | |
| 1321 | def test_rate_limiter_acquire_respects_deadline_and_cancel(): |
| 1322 | # Drained slow limiter (10s to refill): fails fast before deadline instead of sleeping 10s. |
| 1323 | limiter = http.RateLimiter(rate_per_sec=0.1, burst=1) |
| 1324 | limiter.acquire() # drain single token |
| 1325 | |
| 1326 | t0 = time.monotonic() |
| 1327 | with pytest.raises(http.DeadlineExceeded): |
| 1328 | limiter.acquire(deadline_monotonic=t0 + 0.2) |
| 1329 | elapsed = time.monotonic() - t0 |
| 1330 | assert elapsed < 0.5 |
| 1331 | assert limiter.waiting == 0 |
| 1332 | |
| 1333 | # Expired deadline raises without consuming an available token. |
| 1334 | fresh = http.RateLimiter(rate_per_sec=0.1, burst=1) |
| 1335 | with pytest.raises(http.DeadlineExceeded): |
| 1336 | fresh.acquire(deadline_monotonic=time.monotonic() - 0.01) |
| 1337 | assert fresh._tokens >= 1.0 |
| 1338 | assert fresh.waiting == 0 |
| 1339 | |
| 1340 | # Cancel event wakes a waiting acquirer promptly and cleans up waiting count. |
| 1341 | cancel = threading.Event() |
| 1342 | slow = http.RateLimiter(rate_per_sec=0.1, burst=1) |
| 1343 | slow.acquire() |
| 1344 | |
| 1345 | def trigger_cancel(): |
| 1346 | time.sleep(0.05) |
| 1347 | cancel.set() |
| 1348 | |
| 1349 | canceller = threading.Thread(target=trigger_cancel, daemon=True) |
| 1350 | canceller.start() |
| 1351 | t1 = time.monotonic() |
| 1352 | with pytest.raises(http.DeadlineExceeded): |
| 1353 | slow.acquire(deadline_monotonic=t1 + 20.0, cancel=cancel) |
| 1354 | elapsed_cancel = time.monotonic() - t1 |
| 1355 | canceller.join(1.0) |
| 1356 | assert elapsed_cancel < 1.0 |
| 1357 | assert slow.waiting == 0 |
| 1358 | |
| 1359 | |
| 1360 | def test_grounding_reddit_enrichment_stops_waiting_on_busy_limiter_before_deadline(): |
| 1361 | from lib import reddit_arctic, reddit_health |
| 1362 | |
| 1363 | web_items = [ |
| 1364 | { |
| 1365 | "url": "https://www.reddit.com/r/python/comments/abc123/test_post/", |
| 1366 | "title": "Original Web Title", |
| 1367 | "snippet": "Original web snippet", |
| 1368 | }, |
| 1369 | { |
| 1370 | "url": "https://example.com/non-reddit", |
| 1371 | "title": "Example Article", |
| 1372 | "snippet": "Non-reddit snippet", |
| 1373 | }, |
| 1374 | ] |
| 1375 | |
| 1376 | busy_limiter = http.RateLimiter(rate_per_sec=0.05, burst=1) # 20s per token |
| 1377 | busy_limiter.acquire() # drain bucket so next token is 20s away |
| 1378 | |
| 1379 | reddit_arctic.reset_memo() |
| 1380 | with patch.object(http, "REDDIT_KEYLESS_LIMITER", busy_limiter), \ |
| 1381 | patch.object(reddit_health, "skip_reason", return_value=None), \ |
| 1382 | patch.object(web_search_keyless, "keyless_search", return_value=(list(web_items), {"keyless_backend": "ddg"})), \ |
| 1383 | patch.object(reddit_arctic.http, "get", side_effect=AssertionError("should not send HTTP after limiter deadline")): |
| 1384 | t0 = time.monotonic() |
| 1385 | # 3.5s outer deadline => 0.5s enrichment budget after 3.0s headroom, well under 20s token wait. |
| 1386 | items, artifact = grounding.web_search( |
| 1387 | "python", |
| 1388 | ("2026-10-01", "2026-11-01"), |
| 1389 | {"_research_deadline": t0 + 3.5}, |
| 1390 | backend="keyless", |
| 1391 | ) |
| 1392 | elapsed = time.monotonic() - t0 |
| 1393 | |
| 1394 | assert elapsed < 1.0 |
| 1395 | assert items == web_items |
| 1396 | assert artifact["keyless_backend"] == "ddg" |
| 1397 | assert busy_limiter.waiting == 0 |
| 1398 | |
| 1399 | # Multi-batch fetch_posts_by_ids and fetch_comment_tree both fail fast on busy limiter. |
| 1400 | many_ids = [f"p{i:03d}" for i in range(150)] |
| 1401 | with patch.object(http, "REDDIT_KEYLESS_LIMITER", busy_limiter), \ |
| 1402 | patch.object(reddit_arctic.http, "get", side_effect=AssertionError("should not send HTTP")): |
| 1403 | t1 = time.monotonic() |
| 1404 | found, state = reddit_arctic.fetch_posts_by_ids(many_ids, deadline=t1 + 0.2) |
| 1405 | elapsed_ids = time.monotonic() - t1 |
| 1406 | assert elapsed_ids < 0.5 |
| 1407 | assert found == {} |
| 1408 | assert state == "down" |
| 1409 | |
| 1410 | t2 = time.monotonic() |
| 1411 | tree = reddit_arctic.fetch_comment_tree("abc123", deadline=t2 + 1.5) |
| 1412 | elapsed_tree = time.monotonic() - t2 |
| 1413 | assert elapsed_tree < 0.5 |
| 1414 | assert tree is None |
| 1415 | assert busy_limiter.waiting == 0 |
| 1416 | |
| 1417 | |
| 1418 | def test_http_ip_validator_and_local_bridge_mutually_exclusive_and_trailing_dot_preserved(): |
| 1419 | with pytest.raises(ValueError, match="mutually exclusive"): |
| 1420 | http.request( |
| 1421 | "GET", |
| 1422 | "http://127.0.0.1:8080/", |
| 1423 | local_bridge_only=True, |
| 1424 | ip_validator=lambda _ip: True, |
| 1425 | ) |
| 1426 | |
| 1427 | seen_hosts: list[str] = [] |
| 1428 | |
| 1429 | def fake_getaddrinfo(host, port, family=0, socktype=0): |
| 1430 | seen_hosts.append(host) |
| 1431 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("93.184.216.34", port))] |
| 1432 | |
| 1433 | with patch.object(http.socket, "getaddrinfo", side_effect=fake_getaddrinfo): |
| 1434 | verified = http._resolve_validated_addresses("searx.example.", 443, lambda _ip: True) |
| 1435 | assert seen_hosts == ["searx.example."] |
| 1436 | assert len(verified) == 1 |
| 1437 | |
| 1438 | |
| 1439 | def test_parallel_mcp_aborts_stalled_tls_handshake_and_worker_exits(): |
| 1440 | srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1441 | srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1442 | srv.bind(("127.0.0.1", 0)) |
| 1443 | srv.listen(4) |
| 1444 | port = srv.getsockname()[1] |
| 1445 | |
| 1446 | stop_srv = threading.Event() |
| 1447 | accepted_conns: list[socket.socket] = [] |
| 1448 | |
| 1449 | def accept_and_stall(): |
| 1450 | srv.settimeout(0.1) |
| 1451 | while not stop_srv.is_set(): |
| 1452 | try: |
| 1453 | conn, _ = srv.accept() |
| 1454 | except TimeoutError: |
| 1455 | continue |
| 1456 | except OSError: |
| 1457 | break |
| 1458 | accepted_conns.append(conn) |
| 1459 | # Accept TCP and never send TLS ServerHello; hold socket until test teardown. |
| 1460 | for conn in accepted_conns: |
| 1461 | try: |
| 1462 | conn.close() |
| 1463 | except OSError: |
| 1464 | pass |
| 1465 | |
| 1466 | srv_thread = threading.Thread(target=accept_and_stall, daemon=True) |
| 1467 | srv_thread.start() |
| 1468 | |
| 1469 | real_thread_cls = threading.Thread |
| 1470 | |
| 1471 | def run_with_worker_tracking(**kwargs): |
| 1472 | workers: list[threading.Thread] = [] |
| 1473 | |
| 1474 | def tracking_thread(*args, **t_kwargs): |
| 1475 | t = real_thread_cls(*args, **t_kwargs) |
| 1476 | if t_kwargs.get("name") == "parallel-mcp-request": |
| 1477 | workers.append(t) |
| 1478 | return t |
| 1479 | |
| 1480 | with patch.object(parallel_mcp, "PARALLEL_MCP_URL", f"https://127.0.0.1:{port}/mcp"), \ |
| 1481 | patch.object(parallel_mcp.threading, "Thread", side_effect=tracking_thread): |
| 1482 | t0 = time.monotonic() |
| 1483 | with pytest.raises(http.DeadlineExceeded): |
| 1484 | parallel_mcp.search( |
| 1485 | "tls stall", |
| 1486 | ("2026-10-01", "2026-11-01"), |
| 1487 | "test-key", |
| 1488 | **kwargs, |
| 1489 | ) |
| 1490 | elapsed = time.monotonic() - t0 |
| 1491 | assert workers, "expected at least one parallel-mcp-request worker thread" |
| 1492 | for worker in workers: |
| 1493 | worker.join(2.0) |
| 1494 | assert not worker.is_alive(), "worker thread stayed hung in stalled TLS handshake" |
| 1495 | return elapsed |
| 1496 | |
| 1497 | try: |
| 1498 | # 1) Deadline abort during stalled TLS handshake. |
| 1499 | elapsed_deadline = run_with_worker_tracking( |
| 1500 | deadline_monotonic=time.monotonic() + 0.25, |
| 1501 | ) |
| 1502 | assert elapsed_deadline < 1.5 |
| 1503 | |
| 1504 | # 2) Cancel abort during stalled TLS handshake. |
| 1505 | cancel = threading.Event() |
| 1506 | |
| 1507 | def trigger_cancel(): |
| 1508 | time.sleep(0.15) |
| 1509 | cancel.set() |
| 1510 | |
| 1511 | canceller = real_thread_cls(target=trigger_cancel, daemon=True) |
| 1512 | canceller.start() |
| 1513 | elapsed_cancel = run_with_worker_tracking( |
| 1514 | deadline_monotonic=time.monotonic() + 15.0, |
| 1515 | cancel=cancel, |
| 1516 | ) |
| 1517 | canceller.join(1.0) |
| 1518 | assert elapsed_cancel < 1.5 |
| 1519 | finally: |
| 1520 | stop_srv.set() |
| 1521 | try: |
| 1522 | srv.close() |
| 1523 | except OSError: |
| 1524 | pass |
| 1525 | srv_thread.join(2.0) |
| 1526 | |
| 1527 | |
| 1528 | def test_reddit_arctic_fetch_posts_by_ids_continues_after_per_batch_timeout_but_stops_on_overall_or_limiter_deadline(): |
| 1529 | from lib import reddit_arctic |
| 1530 | |
| 1531 | many_ids = [f"b{i:03d}" for i in range(150)] # 2 batches: 100 + 50 |
| 1532 | fast_limiter = http.RateLimiter(rate_per_sec=1000.0, burst=100) |
| 1533 | |
| 1534 | # (a) Batch 1 hits per-batch 15s DeadlineExceeded while overall end still has 30s left: |
| 1535 | # batch 2 MUST still run and return its posts. |
| 1536 | calls: list[str] = [] |
| 1537 | |
| 1538 | def batch1_timeout_batch2_ok(url, deadline, retry_422=True): |
| 1539 | calls.append(url) |
| 1540 | if len(calls) == 1: |
| 1541 | raise http.DeadlineExceeded() |
| 1542 | return { |
| 1543 | "data": [ |
| 1544 | { |
| 1545 | "id": "b100", |
| 1546 | "title": "Batch 2 survived", |
| 1547 | "subreddit": "python", |
| 1548 | "permalink": "/r/python/comments/b100/batch_2_survived/", |
| 1549 | "score": 42, |
| 1550 | "num_comments": 7, |
| 1551 | "created_utc": 1_760_000_000, |
| 1552 | } |
| 1553 | ] |
| 1554 | } |
| 1555 | |
| 1556 | with patch.object(http, "REDDIT_KEYLESS_LIMITER", fast_limiter), \ |
| 1557 | patch.object(reddit_arctic, "_fetch_search", side_effect=batch1_timeout_batch2_ok): |
| 1558 | found, state = reddit_arctic.fetch_posts_by_ids( |
| 1559 | many_ids, deadline=time.monotonic() + 30.0, |
| 1560 | ) |
| 1561 | assert len(calls) == 2 |
| 1562 | assert "b100" in found |
| 1563 | assert found["b100"]["title"] == "Batch 2 survived" |
| 1564 | assert state == "down" |
| 1565 | |
| 1566 | # (b) Batch 1 raises DeadlineExceeded AFTER overall deadline expired -> batch 2 skipped. |
| 1567 | calls.clear() |
| 1568 | fake_now = [100.0] |
| 1569 | |
| 1570 | def batch1_exhausts_overall(url, deadline, retry_422=True): |
| 1571 | calls.append(url) |
| 1572 | fake_now[0] = 105.0 # past end=101.0 |
| 1573 | raise http.DeadlineExceeded() |
| 1574 | |
| 1575 | with patch.object(http, "REDDIT_KEYLESS_LIMITER", fast_limiter), \ |
| 1576 | patch.object(reddit_arctic.time, "monotonic", side_effect=lambda: fake_now[0]), \ |
| 1577 | patch.object(reddit_arctic, "_fetch_search", side_effect=batch1_exhausts_overall): |
| 1578 | found2, state2 = reddit_arctic.fetch_posts_by_ids(many_ids, deadline=101.0) |
| 1579 | assert len(calls) == 1 |
| 1580 | assert found2 == {} |
| 1581 | assert state2 == "down" |
| 1582 | |
| 1583 | # (c) Limiter rejects before end -> batch 1 and batch 2 never invoke _fetch_search. |
| 1584 | slow_limiter = http.RateLimiter(rate_per_sec=0.05, burst=1) |
| 1585 | slow_limiter.acquire() |
| 1586 | calls.clear() |
| 1587 | with patch.object(http, "REDDIT_KEYLESS_LIMITER", slow_limiter), \ |
| 1588 | patch.object(reddit_arctic, "_fetch_search", side_effect=AssertionError("must not fetch")): |
| 1589 | t0 = time.monotonic() |
| 1590 | found3, state3 = reddit_arctic.fetch_posts_by_ids(many_ids, deadline=t0 + 0.2) |
| 1591 | assert time.monotonic() - t0 < 0.5 |
| 1592 | assert found3 == {} |
| 1593 | assert state3 == "down" |
| 1594 | |
| 1595 | |
| 1596 | def test_http_request_and_keyless_search_honor_cancel_during_retries_and_reads(): |
| 1597 | attempts = 0 |
| 1598 | |
| 1599 | class Retry503Handler(BaseHTTPRequestHandler): |
| 1600 | protocol_version = "HTTP/1.1" |
| 1601 | |
| 1602 | def log_message(self, *args): |
| 1603 | pass |
| 1604 | |
| 1605 | def do_GET(self): |
| 1606 | nonlocal attempts |
| 1607 | if self.path == "/flaky": |
| 1608 | attempts += 1 |
| 1609 | body = b"service unavailable" |
| 1610 | self.send_response(503) |
| 1611 | self.send_header("Content-Length", str(len(body))) |
| 1612 | self.end_headers() |
| 1613 | self.wfile.write(body) |
| 1614 | return |
| 1615 | if self.path == "/stream": |
| 1616 | self.send_response(200) |
| 1617 | self.send_header("Transfer-Encoding", "chunked") |
| 1618 | self.end_headers() |
| 1619 | chunk = b"X" * 4096 |
| 1620 | for _ in range(50): |
| 1621 | try: |
| 1622 | self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n") |
| 1623 | self.wfile.flush() |
| 1624 | except OSError: |
| 1625 | break |
| 1626 | time.sleep(0.05) |
| 1627 | try: |
| 1628 | self.wfile.write(b"0\r\n\r\n") |
| 1629 | except OSError: |
| 1630 | pass |
| 1631 | return |
| 1632 | self.send_response(404) |
| 1633 | self.end_headers() |
| 1634 | |
| 1635 | srv, thread, base = _start_server(Retry503Handler) |
| 1636 | try: |
| 1637 | # 1) Pre-set cancel aborts before making any attempt. |
| 1638 | pre_cancel = threading.Event() |
| 1639 | pre_cancel.set() |
| 1640 | with pytest.raises(http.DeadlineExceeded): |
| 1641 | http.request("GET", f"{base}/flaky", retries=3, raw=True, cancel=pre_cancel) |
| 1642 | assert attempts == 0 |
| 1643 | |
| 1644 | # 2) Cancel set shortly into retry backoff aborts immediately without sleeping 2s or retrying. |
| 1645 | retry_cancel = threading.Event() |
| 1646 | |
| 1647 | def set_soon(): |
| 1648 | time.sleep(0.08) |
| 1649 | retry_cancel.set() |
| 1650 | |
| 1651 | t_cancel = threading.Thread(target=set_soon, daemon=True) |
| 1652 | t_cancel.start() |
| 1653 | t0 = time.monotonic() |
| 1654 | with pytest.raises(http.DeadlineExceeded): |
| 1655 | http.request("GET", f"{base}/flaky", retries=3, raw=True, cancel=retry_cancel) |
| 1656 | elapsed = time.monotonic() - t0 |
| 1657 | t_cancel.join(1.0) |
| 1658 | assert attempts == 1 |
| 1659 | assert elapsed < 1.0 |
| 1660 | |
| 1661 | # 3) Cancel mid-stream interrupts _read_bounded / get_text promptly. |
| 1662 | stream_cancel = threading.Event() |
| 1663 | |
| 1664 | def set_stream_cancel(): |
| 1665 | time.sleep(0.12) |
| 1666 | stream_cancel.set() |
| 1667 | |
| 1668 | t_stream = threading.Thread(target=set_stream_cancel, daemon=True) |
| 1669 | t_stream.start() |
| 1670 | t1 = time.monotonic() |
| 1671 | with http.capture_failures() as failures: |
| 1672 | body = http.get_text(f"{base}/stream", retries=1, cancel=stream_cancel) |
| 1673 | elapsed_stream = time.monotonic() - t1 |
| 1674 | t_stream.join(1.0) |
| 1675 | assert body is None |
| 1676 | assert elapsed_stream < 1.0 |
| 1677 | assert any(isinstance(f, http.DeadlineExceeded) for f in failures) |
| 1678 | finally: |
| 1679 | _stop_server(srv, thread) |
| 1680 | |
| 1681 | # 4) keyless_search forwards cancel to http.get_text (HTML rungs) and http.get (SearXNG). |
| 1682 | ev = threading.Event() |
| 1683 | seen_get_text_cancels: list[object] = [] |
| 1684 | seen_get_cancels: list[object] = [] |
| 1685 | |
| 1686 | def fake_get_text(url, **kwargs): |
| 1687 | seen_get_text_cancels.append(kwargs.get("cancel")) |
| 1688 | return None |
| 1689 | |
| 1690 | def fake_get(url, **kwargs): |
| 1691 | seen_get_cancels.append(kwargs.get("cancel")) |
| 1692 | ev.set() |
| 1693 | err = http.DeadlineExceeded() |
| 1694 | http._record_failure(err) |
| 1695 | raise err |
| 1696 | |
| 1697 | web_search_keyless.reset_rung_health() |
| 1698 | try: |
| 1699 | with patch.object(web_search_keyless.http, "get_text", side_effect=fake_get_text), \ |
| 1700 | patch.object(web_search_keyless.http, "get", side_effect=fake_get): |
| 1701 | items, artifact = web_search_keyless.keyless_search( |
| 1702 | "topic", |
| 1703 | ("2026-10-01", "2026-11-01"), |
| 1704 | {"LAST30DAYS_SEARXNG_URL": "https://searxng.example"}, |
| 1705 | cancel=ev, |
| 1706 | ) |
| 1707 | assert items == [] |
| 1708 | assert seen_get_text_cancels == [ev, ev] |
| 1709 | assert seen_get_cancels == [ev] |
| 1710 | assert artifact["reason"] == "keyless-search-timeout" |
| 1711 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 1712 | finally: |
| 1713 | web_search_keyless.reset_rung_health() |
| 1714 | |
| 1715 | |
| 1716 | |
| 1717 | |
| 1718 | |
| 1719 | |
| 1720 |