| 1 | """Historical-window regressions through GitHub search and normalization.""" |
| 2 | |
| 3 | from urllib.parse import parse_qs, urlparse |
| 4 | from unittest.mock import patch |
| 5 | |
| 6 | import pytest |
| 7 | |
| 8 | from lib import github, pipeline, schema |
| 9 | |
| 10 | |
| 11 | @pytest.mark.parametrize("depth, count", [("quick", 15), ("default", 30), ("deep", 60)]) |
| 12 | @pytest.mark.parametrize("token", [None, "test-token"]) |
| 13 | def test_search_preserves_both_window_bounds_in_every_query(depth, count, token): |
| 14 | with patch.object(github, "_resolve_token", return_value=token), patch.object( |
| 15 | github, "_fetch_json", return_value={"items": []}, autospec=True |
| 16 | ) as fetch: |
| 17 | github.search_github( |
| 18 | "react created:>2025-01-01", "2024-02-01", "2024-02-29", depth=depth |
| 19 | ) |
| 20 | |
| 21 | expected_qualifiers = ["is:issue", "is:pull-request"] if token else [None] |
| 22 | assert fetch.call_count == len(expected_qualifiers) |
| 23 | for call, qualifier in zip(fetch.call_args_list, expected_qualifiers): |
| 24 | params = parse_qs(urlparse(call.args[0]).query) |
| 25 | expected_query = "is:public react created:2024-02-01..2024-02-29 in:title" |
| 26 | if qualifier: |
| 27 | expected_query += f" {qualifier}" |
| 28 | assert params["q"] == [expected_query] |
| 29 | expected_count = count if token else 10 |
| 30 | assert params["per_page"] == [str(expected_count)] |
| 31 | assert params["sort"] == ["reactions"] |
| 32 | assert params["order"] == ["desc"] |
| 33 | assert call.kwargs["token"] == token |
| 34 | |
| 35 | |
| 36 | @pytest.mark.parametrize("token", [None, "test-token"]) |
| 37 | def test_search_and_parse_include_full_boundary_days_and_exclude_adjacent_days(token): |
| 38 | timestamps = [ |
| 39 | "2024-01-31T23:59:59Z", |
| 40 | "2024-02-01T00:00:00Z", |
| 41 | "2024-02-29T23:59:59Z", |
| 42 | "2024-03-01T00:00:00Z", |
| 43 | ] |
| 44 | raw_items = [ |
| 45 | { |
| 46 | "id": index, |
| 47 | "html_url": f"https://github.com/example/react/issues/{index}", |
| 48 | "title": f"React issue {index}", |
| 49 | "created_at": timestamp, |
| 50 | "reactions": {"total_count": index}, |
| 51 | } |
| 52 | for index, timestamp in enumerate(timestamps, start=1) |
| 53 | ] |
| 54 | with patch.object(github, "_resolve_token", return_value=token), patch.object( |
| 55 | github, "_fetch_json", return_value={"items": raw_items}, autospec=True |
| 56 | ): |
| 57 | response = github.search_github("react", "2024-02-01", "2024-02-29") |
| 58 | |
| 59 | items = github.parse_github_response(response) |
| 60 | |
| 61 | assert {item["url"] for item in items} == { |
| 62 | "https://github.com/example/react/issues/2", |
| 63 | "https://github.com/example/react/issues/3", |
| 64 | } |
| 65 | assert {item["date"] for item in items} == {"2024-02-01", "2024-02-29"} |
| 66 | |
| 67 | |
| 68 | def test_search_github_title_only_false_omits_in_title(): |
| 69 | with patch.object(github, "_resolve_token", return_value="test-token"), patch.object( |
| 70 | github, "_fetch_json", return_value={"items": []}, autospec=True |
| 71 | ) as fetch: |
| 72 | github.search_github( |
| 73 | "Claude Code subagents worktrees release", |
| 74 | "2026-03-01", |
| 75 | "2026-03-31", |
| 76 | title_only=False, |
| 77 | ) |
| 78 | |
| 79 | assert fetch.call_count == 2 |
| 80 | for call in fetch.call_args_list: |
| 81 | params = parse_qs(urlparse(call.args[0]).query) |
| 82 | assert "in:title" not in params["q"][0] |
| 83 | |
| 84 | |
| 85 | def test_pipeline_github_retries_without_in_title_when_expanded_query_misses(): |
| 86 | calls = [] |
| 87 | |
| 88 | def _fake_search( |
| 89 | query, |
| 90 | from_date, |
| 91 | to_date, |
| 92 | depth="default", |
| 93 | token=None, |
| 94 | *, |
| 95 | title_only=True, |
| 96 | deadline=None, |
| 97 | stopped=None, |
| 98 | ): |
| 99 | calls.append((query, title_only, deadline, callable(stopped))) |
| 100 | if title_only: |
| 101 | return { |
| 102 | "items": [], |
| 103 | "context": {"core": query, "from_date": from_date, "to_date": to_date, "count": 30}, |
| 104 | } |
| 105 | return { |
| 106 | "items": [ |
| 107 | { |
| 108 | "id": 99, |
| 109 | "html_url": "https://github.com/anthropics/claude-code/issues/99", |
| 110 | "title": "Claude Code hooks stop firing", |
| 111 | "body": "Affects subagents worktrees release flow.", |
| 112 | "created_at": "2026-03-15T00:00:00Z", |
| 113 | "reactions": {"total_count": 25}, |
| 114 | } |
| 115 | ], |
| 116 | "context": {"core": query, "from_date": from_date, "to_date": to_date, "count": 30}, |
| 117 | } |
| 118 | |
| 119 | sq = schema.SubQuery( |
| 120 | label="primary", |
| 121 | search_query="Claude Code subagents worktrees release", |
| 122 | ranking_query="Claude Code", |
| 123 | sources=["github"], |
| 124 | ) |
| 125 | import time |
| 126 | future_deadline = time.monotonic() + 60.0 |
| 127 | with patch.object(github, "resolve_token", return_value=None), patch.object( |
| 128 | github, "search_github", side_effect=_fake_search |
| 129 | ): |
| 130 | items, _artifact = pipeline._retrieve_stream_impl( |
| 131 | topic="Claude Code", |
| 132 | subquery=sq, |
| 133 | source="github", |
| 134 | config={"_research_deadline": future_deadline}, |
| 135 | depth="default", |
| 136 | date_range=("2026-03-01", "2026-03-31"), |
| 137 | runtime=schema.ProviderRuntime( |
| 138 | reasoning_provider="local", |
| 139 | planner_model="local", |
| 140 | rerank_model="local", |
| 141 | ), |
| 142 | mock=False, |
| 143 | raw_topic="Claude Code", |
| 144 | ) |
| 145 | |
| 146 | assert calls == [ |
| 147 | ("Claude Code subagents worktrees release", True, future_deadline, True), |
| 148 | ("Claude Code subagents worktrees release", False, future_deadline, True), |
| 149 | ] |
| 150 | assert len(items) == 1 |
| 151 | assert items[0]["title"] == "Claude Code hooks stop firing" |
| 152 | |
| 153 | |
| 154 | def test_pipeline_github_does_not_retry_without_in_title_on_error(): |
| 155 | calls = [] |
| 156 | |
| 157 | def _fake_search( |
| 158 | query, |
| 159 | from_date, |
| 160 | to_date, |
| 161 | depth="default", |
| 162 | token=None, |
| 163 | *, |
| 164 | title_only=True, |
| 165 | deadline=None, |
| 166 | stopped=None, |
| 167 | ): |
| 168 | calls.append(title_only) |
| 169 | return { |
| 170 | "items": [], |
| 171 | "error": "rate limit exceeded", |
| 172 | "context": {"core": query, "from_date": from_date, "to_date": to_date, "count": 30}, |
| 173 | } |
| 174 | |
| 175 | sq = schema.SubQuery( |
| 176 | label="primary", |
| 177 | search_query="Claude Code subagents", |
| 178 | ranking_query="Claude Code", |
| 179 | sources=["github"], |
| 180 | ) |
| 181 | with patch.object(github, "resolve_token", return_value=None), patch.object( |
| 182 | github, "search_github", side_effect=_fake_search |
| 183 | ): |
| 184 | items, _artifact = pipeline._retrieve_stream_impl( |
| 185 | topic="Claude Code", |
| 186 | subquery=sq, |
| 187 | source="github", |
| 188 | config={}, |
| 189 | depth="default", |
| 190 | date_range=("2026-03-01", "2026-03-31"), |
| 191 | runtime=schema.ProviderRuntime( |
| 192 | reasoning_provider="local", |
| 193 | planner_model="local", |
| 194 | rerank_model="local", |
| 195 | ), |
| 196 | mock=False, |
| 197 | raw_topic="Claude Code", |
| 198 | ) |
| 199 | |
| 200 | assert calls == [True] |
| 201 | assert items == [] |
| 202 | |
| 203 | |
| 204 | def test_pipeline_github_skips_fallback_retry_when_cancelled_or_timed_out(): |
| 205 | import threading |
| 206 | import time |
| 207 | |
| 208 | for case in ("cancelled", "expired"): |
| 209 | calls = [] |
| 210 | cancel = threading.Event() |
| 211 | config = {"_enrich_cancel": cancel} |
| 212 | if case == "expired": |
| 213 | config["_research_deadline"] = time.monotonic() + 60.0 |
| 214 | |
| 215 | def _fake_search( |
| 216 | query, |
| 217 | from_date, |
| 218 | to_date, |
| 219 | depth="default", |
| 220 | token=None, |
| 221 | *, |
| 222 | title_only=True, |
| 223 | deadline=None, |
| 224 | stopped=None, |
| 225 | ): |
| 226 | calls.append(title_only) |
| 227 | if case == "cancelled": |
| 228 | cancel.set() |
| 229 | else: |
| 230 | config["_research_deadline"] = time.monotonic() - 1.0 |
| 231 | return { |
| 232 | "items": [], |
| 233 | "context": {"core": query, "from_date": from_date, "to_date": to_date, "count": 30}, |
| 234 | } |
| 235 | |
| 236 | sq = schema.SubQuery( |
| 237 | label="primary", |
| 238 | search_query="Claude Code subagents", |
| 239 | ranking_query="Claude Code", |
| 240 | sources=["github"], |
| 241 | ) |
| 242 | with patch.object(github, "resolve_token", return_value="tok"), patch.object( |
| 243 | github, "search_github", side_effect=_fake_search |
| 244 | ), patch.object(github, "enrich_with_comments") as enrich_mock: |
| 245 | items, _artifact = pipeline._retrieve_stream_impl( |
| 246 | topic="Claude Code", |
| 247 | subquery=sq, |
| 248 | source="github", |
| 249 | config=config, |
| 250 | depth="default", |
| 251 | date_range=("2026-03-01", "2026-03-31"), |
| 252 | runtime=schema.ProviderRuntime( |
| 253 | reasoning_provider="local", |
| 254 | planner_model="local", |
| 255 | rerank_model="local", |
| 256 | ), |
| 257 | mock=False, |
| 258 | raw_topic="Claude Code", |
| 259 | ) |
| 260 | |
| 261 | assert calls == [True], f"expected no fallback retry for {case}" |
| 262 | assert items == [] |
| 263 | enrich_mock.assert_not_called() |
| 264 | |
| 265 | |
| 266 | def test_search_github_clamps_timeout_and_stops_between_partitions(): |
| 267 | import time |
| 268 | |
| 269 | seen_timeouts = [] |
| 270 | stop_flag = {"stopped": False} |
| 271 | |
| 272 | def _fake_fetch(url, token=None, timeout=15, failure_out=None): |
| 273 | seen_timeouts.append(timeout) |
| 274 | stop_flag["stopped"] = True |
| 275 | return {"items": []} |
| 276 | |
| 277 | with patch.object(github, "_resolve_token", return_value="tok"), patch.object( |
| 278 | github, "_fetch_json", side_effect=_fake_fetch |
| 279 | ): |
| 280 | github.search_github( |
| 281 | "Claude Code", |
| 282 | "2026-03-01", |
| 283 | "2026-03-31", |
| 284 | token="tok", |
| 285 | title_only=False, |
| 286 | deadline=time.monotonic() + 2.5, |
| 287 | stopped=lambda: stop_flag["stopped"], |
| 288 | ) |
| 289 | |
| 290 | assert len(seen_timeouts) == 1 |
| 291 | assert 0 < seen_timeouts[0] <= 2.5 |
| 292 | |
| 293 | |
| 294 | def test_enrich_with_comments_respects_deadline_and_keeps_found_items(): |
| 295 | import threading |
| 296 | import time |
| 297 | |
| 298 | unblock = threading.Event() |
| 299 | seen_timeouts = [] |
| 300 | |
| 301 | def _slow_comments(issue_url, max_comments=5, timeout=15, *, as_of=None): |
| 302 | seen_timeouts.append(timeout) |
| 303 | unblock.wait(timeout=5.0) |
| 304 | return [{"score": 1, "excerpt": "late", "author": "bob"}] |
| 305 | |
| 306 | items = [ |
| 307 | { |
| 308 | "id": "GH1", |
| 309 | "title": "Claude Code hooks stop firing", |
| 310 | "url": "https://github.com/anthropics/claude-code/issues/99", |
| 311 | "score": 10, |
| 312 | "metadata": {}, |
| 313 | } |
| 314 | ] |
| 315 | start = time.monotonic() |
| 316 | try: |
| 317 | with patch.object(github, "_fetch_item_comments", side_effect=_slow_comments): |
| 318 | result = github.enrich_with_comments( |
| 319 | items, depth="default", deadline=start + 0.15 |
| 320 | ) |
| 321 | elapsed = time.monotonic() - start |
| 322 | finally: |
| 323 | unblock.set() |
| 324 | |
| 325 | assert len(result) == 1 |
| 326 | assert result[0]["title"] == "Claude Code hooks stop firing" |
| 327 | assert elapsed < 1.0 |
| 328 | assert seen_timeouts and 0 < seen_timeouts[0] <= 0.2 |
| 329 | |
| 330 | |
| 331 | def test_unauth_stopped_search_reports_timeout_not_rate_limit(): |
| 332 | import time |
| 333 | |
| 334 | with patch.object(github, "_resolve_token", return_value=None), patch.object( |
| 335 | github, "_fetch_json" |
| 336 | ) as fetch_mock: |
| 337 | env = github.search_github( |
| 338 | "Claude Code", |
| 339 | "2026-03-01", |
| 340 | "2026-03-31", |
| 341 | deadline=time.monotonic() - 1.0, |
| 342 | ) |
| 343 | |
| 344 | fetch_mock.assert_not_called() |
| 345 | assert env["stopped_reason"] == "deadline exceeded" |
| 346 | assert "GITHUB_TOKEN" not in env["error"] |
| 347 | assert "rate limit" not in env["error"] |
| 348 | |
| 349 | sq = schema.SubQuery( |
| 350 | label="primary", |
| 351 | search_query="Claude Code", |
| 352 | ranking_query="Claude Code", |
| 353 | sources=["github"], |
| 354 | ) |
| 355 | with patch.object(github, "resolve_token", return_value=None), patch.object( |
| 356 | github, "search_github", return_value=env |
| 357 | ): |
| 358 | items, artifact = pipeline._retrieve_stream_impl( |
| 359 | topic="Claude Code", |
| 360 | subquery=sq, |
| 361 | source="github", |
| 362 | config={"_research_deadline": time.monotonic() - 1.0}, |
| 363 | depth="default", |
| 364 | date_range=("2026-03-01", "2026-03-31"), |
| 365 | runtime=schema.ProviderRuntime( |
| 366 | reasoning_provider="local", |
| 367 | planner_model="local", |
| 368 | rerank_model="local", |
| 369 | ), |
| 370 | mock=False, |
| 371 | raw_topic="Claude Code", |
| 372 | ) |
| 373 | from lib import health |
| 374 | assert items == [] |
| 375 | assert artifact["_source_outcome"]["state"] == health.TIMEOUT |
| 376 | |
| 377 | |
| 378 | def test_pipeline_github_reserves_return_margin_for_comment_enrichment(): |
| 379 | import time |
| 380 | |
| 381 | deadline = time.monotonic() + 5.0 |
| 382 | captured = {} |
| 383 | |
| 384 | def _fake_enrich(items, depth="default", *, deadline=None, stopped=None, to_date=None): |
| 385 | captured["deadline"] = deadline |
| 386 | captured["to_date"] = to_date |
| 387 | return items |
| 388 | |
| 389 | sq = schema.SubQuery( |
| 390 | label="primary", |
| 391 | search_query="Claude Code", |
| 392 | ranking_query="Claude Code", |
| 393 | sources=["github"], |
| 394 | ) |
| 395 | response = { |
| 396 | "items": [ |
| 397 | { |
| 398 | "id": 99, |
| 399 | "html_url": "https://github.com/anthropics/claude-code/issues/99", |
| 400 | "title": "Claude Code hooks stop firing", |
| 401 | "body": "Body", |
| 402 | "created_at": "2026-03-15T00:00:00Z", |
| 403 | "reactions": {"total_count": 25}, |
| 404 | } |
| 405 | ], |
| 406 | "context": {"core": "Claude Code", "from_date": "2026-03-01", "to_date": "2026-03-31", "count": 30}, |
| 407 | } |
| 408 | with patch.object(github, "resolve_token", return_value="tok"), patch.object( |
| 409 | github, "search_github", return_value=response |
| 410 | ), patch.object(github, "enrich_with_comments", side_effect=_fake_enrich): |
| 411 | items, _artifact = pipeline._retrieve_stream_impl( |
| 412 | topic="Claude Code", |
| 413 | subquery=sq, |
| 414 | source="github", |
| 415 | config={"_research_deadline": deadline}, |
| 416 | depth="default", |
| 417 | date_range=("2026-03-01", "2026-03-31"), |
| 418 | runtime=schema.ProviderRuntime( |
| 419 | reasoning_provider="local", |
| 420 | planner_model="local", |
| 421 | rerank_model="local", |
| 422 | ), |
| 423 | mock=False, |
| 424 | raw_topic="Claude Code", |
| 425 | ) |
| 426 | |
| 427 | assert len(items) == 1 |
| 428 | assert captured["deadline"] == deadline - 1.0 |
| 429 | assert captured["to_date"] == "2026-03-31" |
| 430 | |
| 431 | |
| 432 | @pytest.mark.parametrize(("names", "expected", "kept"), [ |
| 433 | (["future"], "no-results", []), |
| 434 | (["timeout"], "timeout", []), |
| 435 | (["json-schema"], "unreachable", []), |
| 436 | (["usable", "timeout"], "partial", ["acme/usable"]), |
| 437 | (["release-timeout"], "partial", ["acme/release-timeout"]), |
| 438 | ]) |
| 439 | def test_pinned_project_lookup_preserves_transport_failures_and_valid_siblings(monkeypatch, names, expected, kept): |
| 440 | import io |
| 441 | import json |
| 442 | from urllib.error import URLError |
| 443 | |
| 444 | def open_request(request, timeout): |
| 445 | path = urlparse(request.full_url).path |
| 446 | if path in ("/repos/acme/timeout", "/repos/acme/release-timeout/releases"): |
| 447 | raise URLError(TimeoutError("TLS handshake timed out")) |
| 448 | if path == "/repos/acme/json-schema": |
| 449 | raise URLError(ConnectionRefusedError("connection refused")) |
| 450 | if path.endswith("/releases"): |
| 451 | result = [{"tag_name": "v1", "published_at": "2024-03-28"}] |
| 452 | elif path.startswith("/repos/acme/"): |
| 453 | result = {"visibility": "public", "created_at": "2024-04-01" if path.endswith("/future") else "2024-01-01"} |
| 454 | elif path == "/search/issues": |
| 455 | result = {"total_count": 0, "items": []} |
| 456 | else: |
| 457 | pytest.fail(f"Unexpected GitHub request {path}") |
| 458 | return io.BytesIO(json.dumps(result).encode()) |
| 459 | |
| 460 | monkeypatch.setattr(github.http, "open_request", open_request) |
| 461 | monkeypatch.setattr(github, "_fetch_readme_snippet", lambda *a, **kw: None) |
| 462 | plan = {"intent": "product", "freshness_mode": "balanced_recent", "cluster_mode": "none", |
| 463 | "subqueries": [{"label": "primary", "search_query": "acme", "ranking_query": "acme", "sources": ["github"]}]} |
| 464 | report = pipeline.run( |
| 465 | topic="acme", config={"GITHUB_TOKEN": "dummy-token"}, depth="quick", |
| 466 | requested_sources=["github"], mock=False, web_backend="none", external_plan=plan, |
| 467 | github_repos=[f"acme/{name}" for name in names], as_of_date="2024-03-31", |
| 468 | ) |
| 469 | outcome = report.source_status["github"] |
| 470 | assert outcome.state == expected and outcome.attempted |
| 471 | assert [i.container for i in report.items_by_source.get("github", [])] == kept |
| 472 | if expected == "unreachable": |
| 473 | assert "connection refused" in outcome.detail and "acme/json-schema" in outcome.detail |
| 474 | elif expected != "no-results": |
| 475 | assert "timed out" in outcome.detail and "acme/" in outcome.detail |
| 476 |