| 1 | import io |
| 2 | import json |
| 3 | import threading |
| 4 | import unittest |
| 5 | import urllib.error |
| 6 | from contextlib import contextmanager |
| 7 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 8 | from datetime import datetime, timedelta, timezone |
| 9 | from unittest.mock import patch |
| 10 | |
| 11 | from lib import grounding, parallel_mcp |
| 12 | |
| 13 | |
| 14 | class BraveSearchTests(unittest.TestCase): |
| 15 | def test_brave_search_applies_freshness_and_filters_to_in_range_dated_items(self): |
| 16 | mock_response = { |
| 17 | "web": { |
| 18 | "results": [ |
| 19 | { |
| 20 | "title": "Test Article", |
| 21 | "url": "https://example.com/article", |
| 22 | "description": "A test snippet", |
| 23 | "page_age": "2026-03-10T00:00:00", |
| 24 | }, |
| 25 | { |
| 26 | "title": "Old Article", |
| 27 | "url": "https://example.com/old", |
| 28 | "description": "Should be filtered", |
| 29 | "page_age": "2025-12-10T00:00:00", |
| 30 | }, |
| 31 | { |
| 32 | "title": "Undated Article", |
| 33 | "url": "https://example.com/undated", |
| 34 | "description": "Kept because date is unknown", |
| 35 | } |
| 36 | ] |
| 37 | } |
| 38 | } |
| 39 | with patch("lib.grounding.http.request", return_value=mock_response) as mock_req: |
| 40 | items, artifact = grounding.brave_search("test", ("2026-02-25", "2026-03-27"), "fake-key") |
| 41 | self.assertEqual(2, len(items)) |
| 42 | self.assertEqual("Test Article", items[0]["title"]) |
| 43 | self.assertEqual("https://example.com/article", items[0]["url"]) |
| 44 | self.assertEqual("2026-03-10", items[0]["date"]) |
| 45 | self.assertEqual("Undated Article", items[1]["title"]) |
| 46 | self.assertIsNone(items[1]["date"]) |
| 47 | self.assertEqual("brave", artifact["label"]) |
| 48 | call_url = mock_req.call_args.args[1] |
| 49 | self.assertIn("freshness=2026-02-25to2026-03-27", call_url) |
| 50 | |
| 51 | |
| 52 | class SerperSearchTests(unittest.TestCase): |
| 53 | def test_serper_search_filters_to_in_range_dated_items(self): |
| 54 | mock_response = { |
| 55 | "organic": [ |
| 56 | { |
| 57 | "title": "Serper Result", |
| 58 | "link": "https://example.com/serper", |
| 59 | "snippet": "A serper snippet", |
| 60 | "date": "Mar 15, 2026", |
| 61 | }, |
| 62 | { |
| 63 | "title": "Old Result", |
| 64 | "link": "https://example.com/old", |
| 65 | "snippet": "Should be filtered", |
| 66 | "date": "Jan 15, 2026", |
| 67 | }, |
| 68 | { |
| 69 | "title": "Undated Result", |
| 70 | "link": "https://example.com/undated", |
| 71 | "snippet": "Kept because date is unknown", |
| 72 | } |
| 73 | ] |
| 74 | } |
| 75 | with patch("lib.grounding.http.request", return_value=mock_response): |
| 76 | items, artifact = grounding.serper_search("test", ("2026-02-25", "2026-03-27"), "fake-key") |
| 77 | self.assertEqual(2, len(items)) |
| 78 | self.assertEqual("Serper Result", items[0]["title"]) |
| 79 | self.assertEqual("2026-03-15", items[0]["date"]) |
| 80 | self.assertEqual("Undated Result", items[1]["title"]) |
| 81 | self.assertIsNone(items[1]["date"]) |
| 82 | self.assertEqual("serper", artifact["label"]) |
| 83 | |
| 84 | def test_serper_search_keeps_relative_dates(self): |
| 85 | """Google renders recent results with a relative date, not an absolute one. |
| 86 | |
| 87 | Before these were parsed, every fresh result failed the in-range check |
| 88 | and the web lane came back empty on short windows. |
| 89 | """ |
| 90 | mock_response = { |
| 91 | "organic": [ |
| 92 | { |
| 93 | "title": "Two Hours Old", |
| 94 | "link": "https://example.com/hours", |
| 95 | "snippet": "Fresh enough that Google shows an hour count", |
| 96 | "date": "2 hours ago", |
| 97 | }, |
| 98 | { |
| 99 | "title": "One Day Old", |
| 100 | "link": "https://example.com/day", |
| 101 | "snippet": "Yesterday, relative to the window end", |
| 102 | "date": "1 day ago", |
| 103 | }, |
| 104 | { |
| 105 | "title": "Too Old", |
| 106 | "link": "https://example.com/stale", |
| 107 | "snippet": "Resolves before the window start", |
| 108 | "date": "3 weeks ago", |
| 109 | }, |
| 110 | ] |
| 111 | } |
| 112 | with patch("lib.grounding.http.request", return_value=mock_response), \ |
| 113 | patch("lib.grounding._now", return_value=datetime(2026, 3, 27, 12, 0)): |
| 114 | items, _ = grounding.serper_search("test", ("2026-03-26", "2026-03-27"), "fake-key") |
| 115 | self.assertEqual(2, len(items)) |
| 116 | self.assertEqual("Two Hours Old", items[0]["title"]) |
| 117 | self.assertEqual("2026-03-27", items[0]["date"]) |
| 118 | self.assertEqual("One Day Old", items[1]["title"]) |
| 119 | self.assertEqual("2026-03-26", items[1]["date"]) |
| 120 | |
| 121 | |
| 122 | def test_serper_search_keeps_valid_result_after_overlong_relative_age(self): |
| 123 | response = { |
| 124 | "organic": [ |
| 125 | {"title": "Malformed", "link": "https://example.com/bad", |
| 126 | "date": "9" * 5000 + " days ago"}, |
| 127 | {"title": "Valid", "link": "https://example.com/good", |
| 128 | "date": "1 day ago"}, |
| 129 | ] |
| 130 | } |
| 131 | with patch("lib.grounding.http.request", return_value=response), \ |
| 132 | patch("lib.grounding._now", return_value=datetime(2026, 3, 27, 12, 0)): |
| 133 | items, artifact = grounding.serper_search( |
| 134 | "test", ("2026-03-26", "2026-03-27"), "fake-key" |
| 135 | ) |
| 136 | self.assertEqual(["https://example.com/good"], [item["url"] for item in items]) |
| 137 | self.assertEqual("2026-03-26", items[0]["date"]) |
| 138 | self.assertEqual(1, artifact["resultCount"]) |
| 139 | |
| 140 | |
| 141 | class WebNewsTests(unittest.TestCase): |
| 142 | def test_research_stream_keeps_dated_news_and_web_results_in_one_request(self): |
| 143 | from lib import pipeline, schema |
| 144 | |
| 145 | query = schema.SubQuery(label="primary", search_query="metro opening", ranking_query="metro opening", |
| 146 | sources=["grounding"], weight=1.0) |
| 147 | runtime = schema.ProviderRuntime(reasoning_provider="local", planner_model="local", rerank_model="local") |
| 148 | root = "https://example.com/" |
| 149 | now = datetime(2026, 3, 27, 0, 30, tzinfo=timezone.utc) |
| 150 | for backend in ("brave", "serper"): |
| 151 | brave = backend == "brave" |
| 152 | url = "url" if brave else "link" |
| 153 | date = "page_age" if brave else "date" |
| 154 | snippet = "description" if brave else "snippet" |
| 155 | web = [ |
| 156 | {"title": "Transit agency", url: root + "agency"}, |
| 157 | {"title": "Earlier copy of the opening", url: root + "opening?utm_source=web", snippet: "Route details"}, |
| 158 | {"title": "Timetable", url: root + "hours"}, |
| 159 | {"title": "Network map", url: root + "map"}, |
| 160 | ] |
| 161 | news = [ |
| 162 | {"title": "Old story", url: root + "old", date: "2025-03-25"}, |
| 163 | {"title": "Missing date", url: root + "unknown"}, |
| 164 | {"title": "Metro opening", url: root + "opening", date: "2026-03-25"}, |
| 165 | {"title": "Same story", url: root + "opening#share", date: "2026-03-25"}, |
| 166 | {"title": "Ridership at launch", url: root + "ridership", |
| 167 | "age" if brave else "date": "2 hours ago"}, |
| 168 | {"title": "Outside the window", url: root + "after", date: "2026-03-27"}, |
| 169 | ] |
| 170 | response = {"web": {"results": web}, "news": {"results": news}} if brave else { |
| 171 | "organic": web, "topStories": news, |
| 172 | } |
| 173 | config = {f"{backend.upper()}_API_KEY": "fake-key", "EXCLUDE_SOURCES": "reddit"} |
| 174 | for mode in ("strict_recent", "balanced_recent", "evergreen_ok"): |
| 175 | with self.subTest(backend=backend, mode=mode), \ |
| 176 | patch.object(grounding.http, "request", return_value=response) as request, \ |
| 177 | patch.object(grounding, "_now", return_value=now): |
| 178 | items, artifact = pipeline._retrieve_stream_impl( |
| 179 | topic=query.search_query, subquery=query, source="grounding", config=config, depth="quick", |
| 180 | date_range=("2026-03-25", "2026-03-26"), runtime=runtime, mock=False, freshness_mode=mode, |
| 181 | ) |
| 182 | request.assert_called_once() |
| 183 | self.assertEqual(artifact["resultCount"], len(items)) |
| 184 | if mode == "strict_recent": |
| 185 | self.assertEqual([i["url"] for i in items], [root + suffix for suffix in |
| 186 | ("opening", "agency", "ridership", "hours", "map")]) |
| 187 | self.assertEqual((items[0]["date"], items[0]["snippet"]), ("2026-03-25", "Route details")) |
| 188 | self.assertEqual(items[2]["date"], "2026-03-26") |
| 189 | self.assertEqual(items[2]["metadata"]["web_result_type"], "news") |
| 190 | self.assertEqual(len({i["id"] for i in items}), len(items)) |
| 191 | else: |
| 192 | self.assertEqual([i["url"] for i in items], [entry[url] for entry in web]) |
| 193 | |
| 194 | def test_incomplete_news_sections_leave_valid_web_results_available(self): |
| 195 | web = {"title": "Transit agency", "url": "https://example.com/agency"} |
| 196 | for block in (None, "pending", {"results": [None, {"url": 7, "page_age": 12}]}): |
| 197 | with self.subTest(block=block), patch.object(grounding.http, "request", return_value={ |
| 198 | "web": {"results": [web]}, "news": block, |
| 199 | }): |
| 200 | items, artifact = grounding.brave_search( |
| 201 | "transit", ("2026-03-01", "2026-03-31"), "fake-key", include_news=True, |
| 202 | ) |
| 203 | self.assertEqual([item["url"] for item in items], [web["url"]]) |
| 204 | self.assertEqual(artifact["resultCount"], 1) |
| 205 | |
| 206 | def test_news_only_reply_fills_the_requested_limit_and_obeys_historical_cutoff(self): |
| 207 | now = datetime(2026, 3, 28, tzinfo=timezone.utc) |
| 208 | news = [{"title": f"Article {i}", "link": f"https://example.com/{i}", "date": f"{i} days ago"} |
| 209 | for i in range(1, 7)] |
| 210 | with patch.object(grounding.http, "request", return_value={"topStories": news}), \ |
| 211 | patch.object(grounding, "_now", return_value=now): |
| 212 | items, artifact = grounding.serper_search( |
| 213 | "transit", ("2026-03-21", "2026-03-25"), "fake-key", count=2, include_news=True, |
| 214 | ) |
| 215 | self.assertEqual([item["date"] for item in items], ["2026-03-25", "2026-03-24"]) |
| 216 | self.assertEqual(artifact["resultCount"], 2) |
| 217 | |
| 218 | def test_story_budget_reaches_headlines_that_name_the_subject(self): |
| 219 | from lib import pipeline, render, schema |
| 220 | |
| 221 | topic = "Alex Rivera" |
| 222 | article = "https://press.example/alex-rivera" |
| 223 | news = [{"title": title, "link": f"https://press.example/{index}", "date": "2026-03-25"} |
| 224 | for index, title in enumerate(("Rivera opens exhibition", "Arts fair", "Rivera visits museum"))] |
| 225 | news.append({"title": "Alex Rivera exhibits new work", "link": article, "date": "2026-03-25"}) |
| 226 | web = [{"title": f"{topic} gallery", "link": "https://museum.example/gallery"}, |
| 227 | {"title": f"{topic} profile", "link": "https://museum.example/profile"}] |
| 228 | plan = {"intent": "breaking_news", "freshness_mode": "strict_recent", "cluster_mode": "story", |
| 229 | "subqueries": [{"label": "primary", "search_query": topic, "ranking_query": topic, |
| 230 | "sources": ["grounding"]}]} |
| 231 | with patch.object(grounding.http, "request", return_value={"topStories": news, "organic": web}) as request: |
| 232 | report = pipeline.run( |
| 233 | topic=topic, depth="quick", requested_sources=["grounding"], external_plan=plan, |
| 234 | config={"SERPER_API_KEY": "fake-key", "EXCLUDE_SOURCES": "reddit"}, |
| 235 | web_backend="serper", as_of_date="2026-03-26", |
| 236 | ) |
| 237 | request.assert_called_once() |
| 238 | self.assertIn(article, {r["url"] for r in schema.to_agent_export(report)["results"]}) |
| 239 | self.assertIn(article, render.render_compact(report)) |
| 240 | |
| 241 | |
| 242 | class SerperRelativeDateTests(unittest.TestCase): |
| 243 | NOON = datetime(2026, 3, 27, 12, 0) |
| 244 | |
| 245 | def test_absolute_formats_are_unchanged(self): |
| 246 | for raw, expected in ( |
| 247 | ("Mar 15, 2026", "2026-03-15"), |
| 248 | ("March 15, 2026", "2026-03-15"), |
| 249 | ("2026-03-15", "2026-03-15"), |
| 250 | ): |
| 251 | with self.subTest(raw=raw): |
| 252 | self.assertEqual(expected, grounding._parse_serper_date(raw, self.NOON)) |
| 253 | |
| 254 | def test_relative_units_resolve_against_query_time(self): |
| 255 | for raw, expected in ( |
| 256 | ("45 minutes ago", "2026-03-27"), |
| 257 | ("2 hours ago", "2026-03-27"), |
| 258 | ("1 day ago", "2026-03-26"), |
| 259 | ("5 days ago", "2026-03-22"), |
| 260 | ("2 weeks ago", "2026-03-13"), |
| 261 | ("3 months ago", "2025-12-27"), |
| 262 | ("about 2 days ago", "2026-03-25"), |
| 263 | ("today", "2026-03-27"), |
| 264 | ("yesterday", "2026-03-26"), |
| 265 | ): |
| 266 | with self.subTest(raw=raw): |
| 267 | self.assertEqual(expected, grounding._parse_serper_date(raw, self.NOON)) |
| 268 | |
| 269 | def test_historical_window_dates_against_query_time(self): |
| 270 | """A relative label describes age at query time, not age at the window end. |
| 271 | |
| 272 | Searching a past window with --as-of still runs today, so Serper labels a |
| 273 | result from the window with its age as of today. Anchoring to the window |
| 274 | end would place it before the window and discard it. |
| 275 | """ |
| 276 | self.assertEqual( |
| 277 | "2026-03-15", |
| 278 | grounding._parse_serper_date("12 days ago", now=datetime(2026, 3, 27, 12, 0)), |
| 279 | ) |
| 280 | |
| 281 | def test_unparseable_and_missing_dates_still_return_none(self): |
| 282 | for raw in ("", "sometime last spring", "ago 2 days", "many hours ago"): |
| 283 | with self.subTest(raw=raw): |
| 284 | self.assertIsNone(grounding._parse_serper_date(raw, self.NOON)) |
| 285 | |
| 286 | def test_defaults_to_the_current_clock(self): |
| 287 | with patch("lib.grounding._now", return_value=datetime(2026, 3, 27, 12, 0)): |
| 288 | self.assertEqual("2026-03-26", grounding._parse_serper_date("1 day ago")) |
| 289 | |
| 290 | def test_sub_day_labels_cross_the_midnight_boundary(self): |
| 291 | """A sub-day age is exact, so it must not be rounded up to the query date. |
| 292 | |
| 293 | Just after midnight, "23 hours ago" names yesterday. Stamping it with |
| 294 | today's date both misreports the publication date downstream and lets a |
| 295 | one-day window admit a result that falls outside it. |
| 296 | """ |
| 297 | just_after_midnight = datetime(2026, 3, 27, 0, 30) |
| 298 | for raw, expected in ( |
| 299 | ("23 hours ago", "2026-03-26"), |
| 300 | ("20 minutes ago", "2026-03-27"), |
| 301 | ("2 hours ago", "2026-03-26"), |
| 302 | ): |
| 303 | with self.subTest(raw=raw): |
| 304 | self.assertEqual( |
| 305 | expected, grounding._parse_serper_date(raw, just_after_midnight) |
| 306 | ) |
| 307 | |
| 308 | def test_absurd_ages_are_unparseable_rather_than_fatal(self): |
| 309 | """One malformed label must not take the whole web lane down with it. |
| 310 | |
| 311 | The amount is unbounded, and a large enough one overflows `timedelta` or |
| 312 | runs off the end of `date`. That has to read as an unparseable date, the |
| 313 | same as any other junk value, not as an exception escaping the result |
| 314 | loop in `serper_search`. |
| 315 | """ |
| 316 | for raw in ("999999999 years ago", "3000000 days ago", "99999999999 hours ago"): |
| 317 | with self.subTest(raw=raw): |
| 318 | self.assertIsNone(grounding._parse_serper_date(raw, self.NOON)) |
| 319 | |
| 320 | def test_long_zero_padded_age_is_still_parseable(self): |
| 321 | self.assertEqual( |
| 322 | "2026-03-26", |
| 323 | grounding._parse_serper_date("0" * 5000 + "1 day ago", self.NOON), |
| 324 | ) |
| 325 | |
| 326 | |
| 327 | class ExaSearchTests(unittest.TestCase): |
| 328 | def test_exa_search_filters_to_in_range_dated_items(self): |
| 329 | mock_response = { |
| 330 | "results": [ |
| 331 | { |
| 332 | "title": "Exa Result", |
| 333 | "url": "https://example.com/exa", |
| 334 | "text": "An exa snippet about AI trends", |
| 335 | "publishedDate": "2026-03-15T00:00:00.000Z", |
| 336 | "score": 0.85, |
| 337 | }, |
| 338 | { |
| 339 | "title": "Old Exa Result", |
| 340 | "url": "https://example.com/old-exa", |
| 341 | "text": "Should be filtered out", |
| 342 | "publishedDate": "2025-12-01T00:00:00.000Z", |
| 343 | "score": 0.7, |
| 344 | }, |
| 345 | { |
| 346 | "title": "Undated Exa Result", |
| 347 | "url": "https://example.com/undated-exa", |
| 348 | "text": "Kept because date is unknown", |
| 349 | }, |
| 350 | ] |
| 351 | } |
| 352 | with patch("lib.grounding.http.request", return_value=mock_response) as mock_req: |
| 353 | items, artifact = grounding.exa_search("test", ("2026-02-25", "2026-03-27"), "fake-exa-key") |
| 354 | self.assertEqual(2, len(items)) |
| 355 | self.assertEqual("Exa Result", items[0]["title"]) |
| 356 | self.assertEqual("https://example.com/exa", items[0]["url"]) |
| 357 | self.assertEqual("2026-03-15", items[0]["date"]) |
| 358 | self.assertEqual("Undated Exa Result", items[1]["title"]) |
| 359 | self.assertIsNone(items[1]["date"]) |
| 360 | self.assertTrue(items[0]["id"].startswith("WE")) |
| 361 | self.assertEqual("exa", artifact["label"]) |
| 362 | self.assertEqual(2, artifact["resultCount"]) |
| 363 | # Verify API call |
| 364 | call_args = mock_req.call_args |
| 365 | self.assertEqual("POST", call_args.args[0]) |
| 366 | self.assertEqual("https://api.exa.ai/search", call_args.args[1]) |
| 367 | self.assertEqual("fake-exa-key", call_args.kwargs["headers"]["x-api-key"]) |
| 368 | body = call_args.kwargs["json_data"] |
| 369 | self.assertEqual({"highlights": True}, body["contents"]) |
| 370 | self.assertEqual("auto", body["type"]) |
| 371 | self.assertIn("startPublishedDate", body) |
| 372 | self.assertIn("endPublishedDate", body) |
| 373 | |
| 374 | def test_exa_search_prefers_highlights_and_falls_back_to_text(self): |
| 375 | mock_response = { |
| 376 | "results": [ |
| 377 | { |
| 378 | "title": "Highlighted", |
| 379 | "url": "https://example.com/highlights", |
| 380 | "highlights": ["First relevant passage.", "Second passage."], |
| 381 | "text": "Unused full text", |
| 382 | "publishedDate": "2026-03-15T00:00:00.000Z", |
| 383 | }, |
| 384 | { |
| 385 | "title": "String highlight", |
| 386 | "url": "https://example.com/string", |
| 387 | "highlights": "A single highlight string", |
| 388 | "text": "Unused", |
| 389 | }, |
| 390 | { |
| 391 | "title": "Empty highlights", |
| 392 | "url": "https://example.com/empty", |
| 393 | "highlights": ["", None, 1], |
| 394 | "text": "Text after empty highlights", |
| 395 | }, |
| 396 | { |
| 397 | "title": "Text only", |
| 398 | "url": "https://example.com/text", |
| 399 | "text": "Legacy text extract", |
| 400 | "publishedDate": "2026-03-16T00:00:00.000Z", |
| 401 | }, |
| 402 | "not a dict", |
| 403 | {"title": "No URL", "text": "dropped"}, |
| 404 | ] |
| 405 | } |
| 406 | with patch("lib.grounding.http.request", return_value=mock_response): |
| 407 | items, _artifact = grounding.exa_search( |
| 408 | "test", ("2026-02-25", "2026-03-27"), "fake-exa-key", |
| 409 | ) |
| 410 | snippets = [item["snippet"] for item in items] |
| 411 | self.assertEqual( |
| 412 | [ |
| 413 | "First relevant passage. Second passage.", |
| 414 | "A single highlight string", |
| 415 | "Text after empty highlights", |
| 416 | "Legacy text extract", |
| 417 | ], |
| 418 | snippets, |
| 419 | ) |
| 420 | |
| 421 | def test_exa_company_search_omits_publication_dates(self): |
| 422 | with patch("lib.grounding.http.request", return_value={"results": []}) as mock_req: |
| 423 | grounding.exa_company_search( |
| 424 | "companies developing payments APIs", "key", |
| 425 | objective="Find competing companies", |
| 426 | ) |
| 427 | body = mock_req.call_args.kwargs["json_data"] |
| 428 | self.assertEqual("company", body["category"]) |
| 429 | self.assertEqual("Find competing companies", body["objective"]) |
| 430 | self.assertNotIn("startPublishedDate", body) |
| 431 | self.assertNotIn("endPublishedDate", body) |
| 432 | self.assertNotIn("excludeDomains", body) |
| 433 | self.assertEqual({"highlights": True}, body["contents"]) |
| 434 | |
| 435 | def test_exa_people_search_omits_dates_and_exclude_domains(self): |
| 436 | with patch("lib.grounding.http.request", return_value={"results": []}) as mock_req: |
| 437 | grounding.exa_people_search("Patrick Collison Stripe", "key") |
| 438 | body = mock_req.call_args.kwargs["json_data"] |
| 439 | self.assertEqual("people", body["category"]) |
| 440 | self.assertNotIn("startPublishedDate", body) |
| 441 | self.assertNotIn("endPublishedDate", body) |
| 442 | self.assertNotIn("excludeDomains", body) |
| 443 | |
| 444 | def test_exa_search_drops_dates_even_if_a_range_is_passed_for_company(self): |
| 445 | """category=company must not send dates: Exa returns HTTP 400.""" |
| 446 | with patch("lib.grounding.http.request", return_value={"results": []}) as mock_req: |
| 447 | grounding.exa_search( |
| 448 | "Stripe", ("2026-02-25", "2026-03-27"), "key", category="company", |
| 449 | ) |
| 450 | body = mock_req.call_args.kwargs["json_data"] |
| 451 | self.assertNotIn("startPublishedDate", body) |
| 452 | self.assertNotIn("endPublishedDate", body) |
| 453 | |
| 454 | def test_exa_search_returns_empty_for_no_results(self): |
| 455 | with patch("lib.grounding.http.request", return_value={"results": []}): |
| 456 | items, artifact = grounding.exa_search("test", ("2026-02-25", "2026-03-27"), "key") |
| 457 | self.assertEqual([], items) |
| 458 | self.assertEqual(0, artifact["resultCount"]) |
| 459 | |
| 460 | |
| 461 | class ParallelSearchTests(unittest.TestCase): |
| 462 | def test_parallel_search_filters_to_in_range_dated_items(self): |
| 463 | today = datetime.now(timezone.utc).date() |
| 464 | date_range = ((today - timedelta(days=30)).isoformat(), today.isoformat()) |
| 465 | mock_response = { |
| 466 | "results": [ |
| 467 | { |
| 468 | "title": "Parallel Result", |
| 469 | "url": "https://example.com/parallel", |
| 470 | "snippet": "A parallel snippet", |
| 471 | "publish_date": f"{today.isoformat()}T00:00:00Z", |
| 472 | }, |
| 473 | { |
| 474 | "title": "Old Parallel Result", |
| 475 | "url": "https://example.com/old-parallel", |
| 476 | "snippet": "Should be filtered", |
| 477 | "publish_date": "2025-12-01T00:00:00Z", |
| 478 | }, |
| 479 | { |
| 480 | "title": "Undated Parallel Result", |
| 481 | "url": "https://example.com/undated-parallel", |
| 482 | "snippet": "Kept because date is unknown", |
| 483 | }, |
| 484 | ] |
| 485 | } |
| 486 | with patch("lib.grounding.http.request", return_value=mock_response) as mock_req: |
| 487 | items, artifact = grounding.parallel_search( |
| 488 | "test", date_range, "fake-parallel-key" |
| 489 | ) |
| 490 | self.assertEqual(2, len(items)) |
| 491 | self.assertEqual("Parallel Result", items[0]["title"]) |
| 492 | self.assertEqual("https://example.com/parallel", items[0]["url"]) |
| 493 | self.assertEqual(today.isoformat(), items[0]["date"]) |
| 494 | self.assertEqual("Undated Parallel Result", items[1]["title"]) |
| 495 | self.assertIsNone(items[1]["date"]) |
| 496 | self.assertTrue(items[0]["id"].startswith("WP")) |
| 497 | self.assertEqual("parallel", artifact["label"]) |
| 498 | self.assertEqual(2, artifact["resultCount"]) |
| 499 | self.assertEqual("POST", mock_req.call_args.args[0]) |
| 500 | self.assertEqual("https://api.parallel.ai/v1/search", mock_req.call_args.args[1]) |
| 501 | self.assertEqual("fake-parallel-key", mock_req.call_args.kwargs["headers"]["x-api-key"]) |
| 502 | |
| 503 | def test_parallel_search_returns_empty_for_no_results(self): |
| 504 | with patch("lib.grounding.http.request", return_value={"results": []}): |
| 505 | items, artifact = grounding.parallel_search("test", ("2026-02-25", "2026-03-27"), "key") |
| 506 | self.assertEqual([], items) |
| 507 | self.assertEqual(0, artifact["resultCount"]) |
| 508 | |
| 509 | |
| 510 | class WebSearchDispatchTests(unittest.TestCase): |
| 511 | def test_auto_selects_brave_when_key_present(self): |
| 512 | config = {"BRAVE_API_KEY": "test-key"} |
| 513 | with patch("lib.grounding.brave_search", return_value=([], {})) as mock: |
| 514 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 515 | mock.assert_called_once() |
| 516 | |
| 517 | def test_auto_selects_exa_when_only_exa_key(self): |
| 518 | config = {"EXA_API_KEY": "test-key"} |
| 519 | with patch("lib.grounding.exa_search", return_value=([], {})) as mock: |
| 520 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 521 | mock.assert_called_once() |
| 522 | |
| 523 | def test_auto_selects_serper_when_only_serper_key(self): |
| 524 | config = {"SERPER_API_KEY": "test-key"} |
| 525 | with patch("lib.grounding.serper_search", return_value=([], {})) as mock: |
| 526 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 527 | mock.assert_called_once() |
| 528 | |
| 529 | def test_auto_selects_parallel_when_only_parallel_key(self): |
| 530 | config = {"PARALLEL_API_KEY": "test-key"} |
| 531 | with patch("lib.grounding.parallel_search", return_value=([], {})) as mock: |
| 532 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 533 | mock.assert_called_once() |
| 534 | |
| 535 | def test_auto_returns_empty_when_no_keys_and_native_search(self): |
| 536 | # On a native-search host (signal set) with no paid key, the engine |
| 537 | # leaves general web to the model's own search and returns nothing. |
| 538 | config = {"LAST30DAYS_NATIVE_SEARCH": "1"} |
| 539 | items, artifact = grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 540 | self.assertEqual([], items) |
| 541 | self.assertEqual({}, artifact) |
| 542 | |
| 543 | def test_auto_falls_to_keyless_when_no_keys_and_no_native_search(self): |
| 544 | # No paid key and no native search -> keyless floor is used. |
| 545 | with patch("lib.grounding.web_search_keyless.keyless_search", |
| 546 | return_value=([], {"label": "keyless"})) as mock_keyless: |
| 547 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="auto") |
| 548 | mock_keyless.assert_called_once() |
| 549 | |
| 550 | def test_explicit_keyless_backend_invokes_keyless(self): |
| 551 | with patch("lib.grounding.web_search_keyless.keyless_search", |
| 552 | return_value=([], {"label": "keyless"})) as mock_keyless: |
| 553 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="keyless") |
| 554 | mock_keyless.assert_called_once() |
| 555 | |
| 556 | def test_none_returns_empty(self): |
| 557 | config = {"BRAVE_API_KEY": "test-key"} |
| 558 | items, artifact = grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="none") |
| 559 | self.assertEqual([], items) |
| 560 | |
| 561 | def test_auto_prefers_brave_over_exa(self): |
| 562 | config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key"} |
| 563 | with patch("lib.grounding.brave_search", return_value=([], {})) as mock_brave, \ |
| 564 | patch("lib.grounding.exa_search", return_value=([], {})) as mock_exa: |
| 565 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 566 | mock_brave.assert_called_once() |
| 567 | mock_exa.assert_not_called() |
| 568 | |
| 569 | def test_auto_prefers_exa_over_serper(self): |
| 570 | config = {"EXA_API_KEY": "exa-key", "SERPER_API_KEY": "serper-key"} |
| 571 | with patch("lib.grounding.exa_search", return_value=([], {})) as mock_exa, \ |
| 572 | patch("lib.grounding.serper_search", return_value=([], {})) as mock_serper: |
| 573 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 574 | mock_exa.assert_called_once() |
| 575 | mock_serper.assert_not_called() |
| 576 | |
| 577 | def test_auto_prefers_serper_over_parallel(self): |
| 578 | config = {"SERPER_API_KEY": "serper-key", "PARALLEL_API_KEY": "parallel-key"} |
| 579 | with patch("lib.grounding.serper_search", return_value=([], {})) as mock_serper, \ |
| 580 | patch("lib.grounding.parallel_search", return_value=([], {})) as mock_parallel: |
| 581 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 582 | mock_serper.assert_called_once() |
| 583 | mock_parallel.assert_not_called() |
| 584 | |
| 585 | def test_auto_prefers_brave_when_all_keys_present(self): |
| 586 | config = {"BRAVE_API_KEY": "brave-key", "EXA_API_KEY": "exa-key", "SERPER_API_KEY": "serper-key"} |
| 587 | with patch("lib.grounding.brave_search", return_value=([], {})) as mock_brave, \ |
| 588 | patch("lib.grounding.exa_search", return_value=([], {})) as mock_exa, \ |
| 589 | patch("lib.grounding.serper_search", return_value=([], {})) as mock_serper: |
| 590 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 591 | mock_brave.assert_called_once() |
| 592 | mock_exa.assert_not_called() |
| 593 | mock_serper.assert_not_called() |
| 594 | |
| 595 | def test_explicit_exa_without_key_raises(self): |
| 596 | with self.assertRaises(RuntimeError): |
| 597 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="exa") |
| 598 | |
| 599 | def test_explicit_brave_without_key_raises(self): |
| 600 | with self.assertRaises(RuntimeError): |
| 601 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="brave") |
| 602 | |
| 603 | def test_explicit_parallel_without_key_raises(self): |
| 604 | with self.assertRaises(RuntimeError): |
| 605 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="parallel") |
| 606 | |
| 607 | def test_unsupported_backend_raises(self): |
| 608 | with self.assertRaises(ValueError): |
| 609 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), {}, backend="google") |
| 610 | |
| 611 | |
| 612 | class RedditEnrichmentGateTests(unittest.TestCase): |
| 613 | """EXCLUDE_SOURCES=reddit must suppress the web-search Reddit enrichment. |
| 614 | |
| 615 | Otherwise a user who explicitly excluded Reddit would still get Reddit |
| 616 | content smuggled back in via web-search URLs that happen to point at |
| 617 | reddit.com threads. |
| 618 | """ |
| 619 | |
| 620 | def test_reddit_excluded_via_exclude_sources_skips_enrichment(self): |
| 621 | config = {"BRAVE_API_KEY": "k", "EXCLUDE_SOURCES": "reddit"} |
| 622 | items = [{"url": "https://www.reddit.com/r/python/comments/abc/title/", "snippet": "original"}] |
| 623 | with patch("lib.grounding.brave_search", return_value=(items, {})), \ |
| 624 | patch("lib.grounding._enrich_reddit_items") as enrich_mock: |
| 625 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 626 | enrich_mock.assert_not_called() |
| 627 | |
| 628 | def test_reddit_excluded_case_insensitive(self): |
| 629 | for value in ("REDDIT", "Reddit", " reddit ", "x,reddit,y"): |
| 630 | config = {"BRAVE_API_KEY": "k", "EXCLUDE_SOURCES": value} |
| 631 | self.assertTrue( |
| 632 | grounding._reddit_excluded(config), |
| 633 | msg=f"_reddit_excluded should be True for EXCLUDE_SOURCES={value!r}", |
| 634 | ) |
| 635 | |
| 636 | def test_reddit_not_excluded_when_other_sources_listed(self): |
| 637 | config = {"EXCLUDE_SOURCES": "tiktok,instagram"} |
| 638 | self.assertFalse(grounding._reddit_excluded(config)) |
| 639 | |
| 640 | def test_enrichment_runs_when_reddit_not_excluded(self): |
| 641 | config = {"BRAVE_API_KEY": "k"} |
| 642 | items = [{"url": "https://www.reddit.com/r/python/comments/abc/title/", "snippet": "original"}] |
| 643 | with patch("lib.grounding.brave_search", return_value=(items, {})), \ |
| 644 | patch("lib.grounding._enrich_reddit_items", return_value=items) as enrich_mock: |
| 645 | grounding.web_search("test", ("2026-02-25", "2026-03-27"), config, backend="auto") |
| 646 | enrich_mock.assert_called_once() |
| 647 | |
| 648 | |
| 649 | class RedditEnrichItemsTests(unittest.TestCase): |
| 650 | """Direct tests for `_enrich_reddit_items`: Reddit web results are filled |
| 651 | through the Reddit hydrator (Arctic Shift), and a result the archive could |
| 652 | not fill stays as the search gave it. |
| 653 | """ |
| 654 | |
| 655 | def test_throttled_archive_leaves_results_unchanged(self): |
| 656 | from lib import reddit_arctic |
| 657 | |
| 658 | item1 = {"url": "https://www.reddit.com/r/python/comments/aaa/x/", "snippet": "a"} |
| 659 | item2 = {"url": "https://www.reddit.com/r/python/comments/bbb/y/", "snippet": "b"} |
| 660 | with patch.object(reddit_arctic, "fetch_posts_by_ids", return_value=({}, "throttled")) as ids, \ |
| 661 | patch.object(reddit_arctic, "fetch_comment_tree") as tree: |
| 662 | result = grounding._enrich_reddit_items([item1, item2]) |
| 663 | ids.assert_called_once() |
| 664 | tree.assert_not_called() |
| 665 | self.assertEqual(["a", "b"], [r["snippet"] for r in result]) |
| 666 | self.assertFalse(any("enriched_via" in r for r in result)) |
| 667 | |
| 668 | class RedditEnrichmentIsolationTests(unittest.TestCase): |
| 669 | def test_enrichment_http_failure_does_not_poison_web_source(self): |
| 670 | """A reddit.com enrichment fetch failure (e.g. a 403 on a datacenter IP) |
| 671 | is a secondary operation on already-retrieved web results; it must not be |
| 672 | attributed to the web/grounding source and discard those results.""" |
| 673 | from lib import http |
| 674 | |
| 675 | retrieved = [ |
| 676 | {"url": "https://www.reddit.com/r/x/comments/1/abc/", "title": "T", "snippet": "s"}, |
| 677 | ] |
| 678 | |
| 679 | def fake_enrich(items): |
| 680 | # The enricher swallows the error, but the http layer records the |
| 681 | # terminal failure into whatever capture sink is currently active. |
| 682 | http._record_failure(http.HTTPError("Blocked", status_code=403)) |
| 683 | return items |
| 684 | |
| 685 | with http.capture_failures() as source_sink: |
| 686 | with patch.object(grounding, "web_search_keyless") as wsk, \ |
| 687 | patch.object(grounding, "_enrich_reddit_items", side_effect=fake_enrich): |
| 688 | wsk.keyless_search.return_value = (list(retrieved), {"keyless_backend": "startpage"}) |
| 689 | items, _ = grounding.web_search( |
| 690 | "q", ("2026-02-25", "2026-03-27"), {}, backend="keyless") |
| 691 | |
| 692 | self.assertEqual(len(items), 1) |
| 693 | # The enrichment 403 is isolated in its own sink; the source's sink is clean. |
| 694 | self.assertEqual(source_sink, []) |
| 695 | |
| 696 | |
| 697 | class ParallelMCPRuntimeTests(unittest.TestCase): |
| 698 | class _Response: |
| 699 | def __init__(self, payload, session=None, content_type="application/json"): |
| 700 | raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode() if payload is not None else b"" |
| 701 | self.body = io.BytesIO(raw) |
| 702 | self.headers = {"Content-Type": content_type} |
| 703 | if session: |
| 704 | self.headers["Mcp-Session-Id"] = session |
| 705 | def __enter__(self): |
| 706 | return self |
| 707 | def __exit__(self, *_args): |
| 708 | return False |
| 709 | def read(self, size=-1): |
| 710 | return self.body.read(size) |
| 711 | def readline(self, size=-1): |
| 712 | return self.body.readline(size) |
| 713 | |
| 714 | def test_explicit_parallel_mcp_discovers_invokes_and_maps_anonymous_result(self): |
| 715 | responses = iter([ |
| 716 | self._Response({"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-03-26"}}, "session-1"), |
| 717 | self._Response(None), |
| 718 | self._Response({"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "web_search"}, {"name": "web_fetch"}]}}), |
| 719 | self._Response({"jsonrpc": "2.0", "id": 3, "result": {"structuredContent": {"results": [{"url": "https://example.com/evidence", "title": None, "publish_date": "2026-08-01", "excerpts": ["Useful evidence"]}]}}}), |
| 720 | self._Response(None), |
| 721 | ]) |
| 722 | requests = [] |
| 723 | def open_response(request, timeout): |
| 724 | requests.append(request) |
| 725 | return next(responses) |
| 726 | with patch("lib.parallel_mcp.urllib.request.OpenerDirector.open", side_effect=open_response): |
| 727 | items, artifact = grounding.web_search( |
| 728 | "agent runtimes", ("2026-07-27", "2026-08-26"), {}, backend="parallel-mcp" |
| 729 | ) |
| 730 | self.assertEqual("https://example.com/evidence", items[0]["url"]) |
| 731 | self.assertEqual("Useful evidence", items[0]["snippet"]) |
| 732 | self.assertEqual("2026-08-01", items[0]["date"]) |
| 733 | self.assertEqual("parallel-mcp", artifact["label"]) |
| 734 | self.assertTrue(all(request.get_header("Authorization") is None for request in requests)) |
| 735 | self.assertTrue(all(request.get_header("Mcp-session-id") == "session-1" for request in requests[1:])) |
| 736 | self.assertTrue(all(request.get_header("Mcp-protocol-version") == "2025-03-26" for request in requests[1:])) |
| 737 | self.assertEqual("DELETE", requests[-1].method) |
| 738 | messages = [json.loads(request.data) for request in requests if request.data] |
| 739 | self.assertEqual(["initialize", "notifications/initialized", "tools/list", "tools/call"], [message["method"] for message in messages]) |
| 740 | self.assertEqual("web_search", messages[-1]["params"]["name"]) |
| 741 | self.assertEqual(["agent runtimes"], messages[-1]["params"]["arguments"]["search_queries"]) |
| 742 | self.assertNotIn("max_results", messages[-1]["params"]["arguments"]) |
| 743 | |
| 744 | def test_parallel_mcp_rejects_oversized_response(self): |
| 745 | class OversizedResponse(self._Response): |
| 746 | def read(self, size=-1): |
| 747 | self.requested_size = size |
| 748 | return b"x" * size |
| 749 | response = OversizedResponse(None) |
| 750 | with patch("lib.parallel_mcp.urllib.request.OpenerDirector.open", return_value=response): |
| 751 | with self.assertRaisesRegex(RuntimeError, "exceeded 4 MiB"): |
| 752 | grounding.web_search( |
| 753 | "test", ("2026-07-27", "2026-08-26"), {}, backend="parallel-mcp" |
| 754 | ) |
| 755 | self.assertEqual(4 * 1024 * 1024 + 1, response.requested_size) |
| 756 | |
| 757 | def test_auto_without_opt_in_does_not_contact_parallel_mcp(self): |
| 758 | with patch("lib.grounding.parallel_mcp.search") as mcp_search, \ |
| 759 | patch("lib.grounding.web_search_keyless.keyless_search", return_value=([], {})): |
| 760 | grounding.web_search("test", ("2026-07-27", "2026-08-26"), {}, backend="auto") |
| 761 | mcp_search.assert_not_called() |
| 762 | |
| 763 | def test_explicit_parallel_mcp_preserves_optional_bearer_auth(self): |
| 764 | with patch("lib.grounding.parallel_mcp.search", return_value=([], {})) as mcp_search: |
| 765 | grounding.web_search( |
| 766 | "test", ("2026-07-27", "2026-08-26"), |
| 767 | {"PARALLEL_API_KEY": "test-key"}, backend="parallel-mcp", |
| 768 | ) |
| 769 | mcp_search.assert_called_once_with("test", ("2026-07-27", "2026-08-26"), "test-key") |
| 770 | |
| 771 | @contextmanager |
| 772 | def _server(self, handler): |
| 773 | server = ThreadingHTTPServer(("127.0.0.1", 0), handler) |
| 774 | thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) |
| 775 | thread.start() |
| 776 | try: |
| 777 | yield f"http://127.0.0.1:{server.server_port}" |
| 778 | finally: |
| 779 | server.shutdown() |
| 780 | server.server_close() |
| 781 | thread.join() |
| 782 | |
| 783 | def test_redirects_never_forward_auth_session_or_search_data(self): |
| 784 | target_requests = [] |
| 785 | original_requests = [] |
| 786 | |
| 787 | class Target(BaseHTTPRequestHandler): |
| 788 | def do_GET(self): |
| 789 | target_requests.append(dict(self.headers)) |
| 790 | self.send_response(200) |
| 791 | self.end_headers() |
| 792 | do_POST = do_GET |
| 793 | def log_message(self, *_args): |
| 794 | pass |
| 795 | |
| 796 | class Redirect(Target): |
| 797 | def do_POST(self): |
| 798 | original_requests.append(dict(self.headers)) |
| 799 | self.rfile.read(int(self.headers.get("Content-Length", 0))) |
| 800 | self.send_response(int(self.path.strip("/"))) |
| 801 | self.send_header("Location", target_url) |
| 802 | self.end_headers() |
| 803 | |
| 804 | with self._server(Target) as target_url, self._server(Redirect) as source_url: |
| 805 | for status in (301, 302, 303, 307, 308): |
| 806 | with self.subTest(status=status), patch.object(parallel_mcp, "PARALLEL_MCP_URL", f"{source_url}/{status}"): |
| 807 | with self.assertRaises(urllib.error.HTTPError) as raised: |
| 808 | parallel_mcp._request( |
| 809 | {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, |
| 810 | "test-key", "test-session", |
| 811 | ) |
| 812 | self.assertEqual(status, raised.exception.code) |
| 813 | raised.exception.close() |
| 814 | self.assertEqual([], target_requests) |
| 815 | self.assertEqual(5, len(original_requests)) |
| 816 | self.assertTrue(all(headers["Authorization"] == "Bearer test-key" for headers in original_requests)) |
| 817 | self.assertTrue(all(headers["Mcp-Session-Id"] == "test-session" for headers in original_requests)) |
| 818 | |
| 819 | def test_sse_matches_request_and_returns_without_waiting_for_eof(self): |
| 820 | class OpenStream(self._Response): |
| 821 | def read(self, size=-1): |
| 822 | raise AssertionError("SSE must not wait for the whole body") |
| 823 | def readline(self, size=-1): |
| 824 | line = super().readline(size) |
| 825 | if not line: |
| 826 | raise AssertionError("SSE must stop at the matching response") |
| 827 | return line |
| 828 | |
| 829 | response = OpenStream( |
| 830 | b': heartbeat\r\n\r\n' |
| 831 | b'data: {"jsonrpc":"2.0","method":"notifications/progress"}\r\n\r\n' |
| 832 | b'data: {"jsonrpc":"2.0","id":99,"result":{}}\r\n\r\n' |
| 833 | b'event: message\r\ndata: {"jsonrpc":"2.0",\r\ndata: "id":3,"result":{"content":[]}}\r\n\r\n', |
| 834 | content_type="text/event-stream; charset=utf-8", |
| 835 | ) |
| 836 | self.assertEqual({"content": []}, parallel_mcp._read_response(response, 3)["result"]) |
| 837 | |
| 838 | def test_sse_supports_batched_messages(self): |
| 839 | payload = b'data: [{"jsonrpc":"2.0","method":"notifications/progress"},{"jsonrpc":"2.0","id":3,"result":{}}]\n\n' |
| 840 | response = self._Response(payload, content_type="text/event-stream") |
| 841 | self.assertEqual(3, parallel_mcp._read_response(response, 3)["id"]) |
| 842 | |
| 843 | def test_sse_response_cap_includes_heartbeats_and_all_events(self): |
| 844 | for payload in (b":" + b"x" * 80, b": heartbeat\n\n" * 10): |
| 845 | with self.subTest(payload=payload), patch.object(parallel_mcp, "_MAX_RESPONSE_BYTES", 64): |
| 846 | response = self._Response(payload, content_type="text/event-stream") |
| 847 | with self.assertRaisesRegex(RuntimeError, "exceeded 4 MiB"): |
| 848 | parallel_mcp._read_response(response, 3) |
| 849 | |
| 850 | def test_rejects_missing_or_mismatched_rpc_response(self): |
| 851 | for payload, content_type in ( |
| 852 | ({"jsonrpc": "2.0", "id": 99, "result": {}}, "application/json"), |
| 853 | (None, "application/json"), |
| 854 | (b'data: {"jsonrpc":"2.0","method":"notifications/progress"}\n\n', "text/event-stream"), |
| 855 | ): |
| 856 | with self.subTest(payload=payload): |
| 857 | with self.assertRaisesRegex(RuntimeError, "missing the requested"): |
| 858 | parallel_mcp._read_response(self._Response(payload, content_type=content_type), 3) |
| 859 | |
| 860 | def test_filters_dates_and_invalid_urls_before_applying_result_limit(self): |
| 861 | rows = [ |
| 862 | {"url": "https://example.com/old", "publish_date": "2026-07-26"}, |
| 863 | {"url": "https://example.com/future", "publish_date": "2026-08-27"}, |
| 864 | {"url": "https://example.com/undated"}, |
| 865 | {"url": "https://example.com/invalid-date", "publish_date": "not-a-date"}, |
| 866 | {"url": "https:///missing-host", "publish_date": "2026-08-01"}, |
| 867 | {"url": "https://[invalid", "publish_date": "2026-08-01"}, |
| 868 | {"url": "https://example.com/start", "publish_date": "2026-07-27T12:00:00Z", "excerpts": "Start evidence"}, |
| 869 | {"url": "https://example.com/end", "publish_date": "2026-08-26", "excerpts": ["End evidence"]}, |
| 870 | {"url": "https://example.com/extra", "publish_date": "2026-08-01"}, |
| 871 | ] |
| 872 | responses = [ |
| 873 | ({"result": {"protocolVersion": "2025-03-26"}}, None), |
| 874 | ({}, None), |
| 875 | ({"result": {"tools": [{"name": "web_search"}]}}, None), |
| 876 | ({"result": {"content": [{"type": "text", "text": json.dumps({"results": rows})}]}}, None), |
| 877 | ] |
| 878 | with patch.object(parallel_mcp, "_request", side_effect=responses): |
| 879 | items, artifact = parallel_mcp.search("test", ("2026-07-27", "2026-08-26"), count=2) |
| 880 | self.assertEqual(["2026-07-27", "2026-08-26"], [item["date"] for item in items]) |
| 881 | self.assertEqual(["Start evidence", "End evidence"], [item["snippet"] for item in items]) |
| 882 | self.assertEqual(2, artifact["resultCount"]) |
| 883 | |
| 884 | def test_empty_results_are_distinct_from_malformed_payloads(self): |
| 885 | self.assertEqual([], parallel_mcp._search_rows({"structuredContent": {"results": []}})) |
| 886 | for value in (42, "invalid", {"results": 42}): |
| 887 | with self.subTest(value=value), self.assertRaisesRegex(RuntimeError, "no results array"): |
| 888 | parallel_mcp._search_rows({"structuredContent": value}) |
| 889 | |
| 890 | def test_discovers_web_search_on_later_page_and_cleanup_failure_is_nonfatal(self): |
| 891 | responses = [ |
| 892 | ({"result": {"protocolVersion": "2025-03-26"}}, "session-1"), |
| 893 | ({}, "session-1"), |
| 894 | ({"result": {"tools": [{"name": "web_fetch"}], "nextCursor": "page-2"}}, "session-1"), |
| 895 | ({"result": {"tools": [{"name": "web_search"}]}}, "session-1"), |
| 896 | ({"result": {"structuredContent": {"results": []}}}, "session-1"), |
| 897 | urllib.error.HTTPError(parallel_mcp.PARALLEL_MCP_URL, 405, "Not allowed", {}, None), |
| 898 | ] |
| 899 | with patch.object(parallel_mcp, "_request", side_effect=responses) as request: |
| 900 | items, _ = parallel_mcp.search("test", ("2026-07-27", "2026-08-26")) |
| 901 | self.assertEqual([], items) |
| 902 | self.assertEqual({"cursor": "page-2"}, request.call_args_list[3].args[0]["params"]) |
| 903 | self.assertEqual(4, request.call_args_list[4].args[0]["id"]) |
| 904 | self.assertEqual((None, None, "session-1"), request.call_args_list[-1].args) |
| 905 | |
| 906 | def test_failed_discovery_still_terminates_session_and_preserves_error(self): |
| 907 | responses = [ |
| 908 | ({"result": {"protocolVersion": "2025-03-26"}}, "session-1"), |
| 909 | ({}, "session-1"), |
| 910 | ({"error": {"message": "Discovery failed"}}, "session-1"), |
| 911 | OSError("Cleanup failed"), |
| 912 | ] |
| 913 | with patch.object(parallel_mcp, "_request", side_effect=responses) as request: |
| 914 | with self.assertRaisesRegex(RuntimeError, "Discovery failed"): |
| 915 | parallel_mcp.search("test", ("2026-07-27", "2026-08-26")) |
| 916 | self.assertIsNone(request.call_args.args[0]) |
| 917 | |
| 918 | def test_unsupported_protocol_is_rejected_before_search(self): |
| 919 | responses = [({"result": {"protocolVersion": "unsupported"}}, "session-1"), ({}, None)] |
| 920 | with patch.object(parallel_mcp, "_request", side_effect=responses) as request: |
| 921 | with self.assertRaisesRegex(RuntimeError, "unsupported protocol version"): |
| 922 | parallel_mcp.search("test", ("2026-07-27", "2026-08-26")) |
| 923 | self.assertEqual(2, request.call_count) |
| 924 | self.assertIsNone(request.call_args.args[0]) |
| 925 | |
| 926 | |
| 927 | if __name__ == "__main__": |
| 928 | unittest.main() |
| 929 |