From 3b66564b071c2750465f09e7bb9c2f4b505c2754 Mon Sep 17 00:00:00 2001 From: businessdeveloper69 Date: Sun, 22 Nov 2026 02:36:10 +0530 Subject: [PATCH] Split activity searches that exceed GitHub's result limit --- docs/use.md | 2 + github_activity/github_activity.py | 5 +- github_activity/graphql.py | 57 +++++++++++++--- tests/test_search_limit.py | 103 +++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 13 deletions(-) create mode 100644 tests/test_search_limit.py diff --git a/docs/use.md b/docs/use.md index 3a18192..e7f0126 100644 --- a/docs/use.md +++ b/docs/use.md @@ -70,6 +70,8 @@ Each of these accepts either: If no `-u` parameter is given, then all activity until today will be included. +GitHub returns at most 1,000 results per search. If an activity window exceeds that limit, `github-activity` searches smaller time ranges automatically. If more than 1,000 items were created or closed within the same second, it reports the affected range and stops. + (prefixes-and-tags)= ## Split PRs by tags and prefixes diff --git a/github_activity/github_activity.py b/github_activity/github_activity.py index d9edbfa..158fbd8 100644 --- a/github_activity/github_activity.py +++ b/github_activity/github_activity.py @@ -223,10 +223,9 @@ def get_activity( query_data = [] all_bot_users = set() for activity_type in ["created", "closed"]: - ii_search_query = ( - search_query + f" {activity_type}:{since_dt_str}..{until_dt_str}" + qu = GitHubGraphQlQuery( + search_query, auth=auth, window=(activity_type, since_dt_str, until_dt_str) ) - qu = GitHubGraphQlQuery(ii_search_query, auth=auth) qu.request() query_data.append(qu.data) # Collect bot users from each query diff --git a/github_activity/graphql.py b/github_activity/graphql.py index a3dd7f3..5ff9b5b 100644 --- a/github_activity/graphql.py +++ b/github_activity/graphql.py @@ -1,5 +1,7 @@ import os import sys +from datetime import datetime, timedelta +from itertools import count import numpy as np import pandas as pd @@ -127,7 +129,7 @@ # Define our query object that we'll re-use for github search class GitHubGraphQlQuery: - def __init__(self, query, display_progress=True, auth=None): + def __init__(self, query, display_progress=True, auth=None, *, window=None): """Run a GitHub GraphQL query and return the issue/PR data from it. Parameters @@ -140,8 +142,11 @@ def __init__(self, query, display_progress=True, auth=None): auth : string | None An authentication token for GitHub. If None, then the environment variable `GITHUB_ACCESS_TOKEN` will be tried. + window : tuple | None + A created or closed date qualifier and its inclusive UTC timestamps. """ self.query = query + self.window = window self.bot_users = set() # Store detected bot usernames # Authentication @@ -160,23 +165,36 @@ def __init__(self, query, display_progress=True, auth=None): self.gql_template = gql_template self.display_progress = display_progress - def request(self, n_pages=100, n_per_page=50): + def request(self, n_pages=None, n_per_page=50): """Make a request to the GitHub GraphQL API. This generates an attribute `self.data` with a pandas DataFrame of the issue / PR activity corresponding to - the query you ran. + the query you ran. An explicit n_pages limits the number of pages + fetched from the original search. """ + self.issues_and_or_prs = [] + self._request_pages(self.window, n_pages, n_per_page) + if not self.issues_and_or_prs: + self.data = pd.DataFrame() + return + self._build_dataframe() + + def _request_pages(self, window, n_pages, n_per_page): + query = self.query + if window: + field, start, end = window + query += f" {field}:{start}..{end}" # NOTE: This main search query has a type, but the query string also has a type. # ref ("search"): https://developer.github.com/v4/query/#connections # Collect paginated issues pageInfo = None - self.issues_and_or_prs = [] - for ii in range(n_pages): + pages = count() if n_pages is None else range(n_pages) + for ii in pages: github_search_query = [ f"first: {n_per_page}", - f'query: "{self.query}"', + f'query: "{query}"', "type: ISSUE", ] if ii != 0: @@ -237,13 +255,31 @@ def request(self, n_pages=100, n_per_page=50): if ii == 0: if json["issueCount"] == 0: print("Found no entries for query.", file=sys.stderr) - self.data = pd.DataFrame() return - n_pages = int(np.ceil(json["issueCount"] / n_per_page)) + if n_pages is None and json["issueCount"] > 1000: + if not window or start >= end: + raise ValueError( + f"GitHub search exceeds its 1,000-result limit for {query!r}. " + "Narrow the search to retrieve all results." + ) + first = datetime.fromisoformat(start.removesuffix("Z")) + last = datetime.fromisoformat(end.removesuffix("Z")) + middle = (first + (last - first) // 2).replace(microsecond=0) + # Both ends are inclusive and GitHub timestamps have second precision. + next_second = middle + timedelta(seconds=1) + self._request_pages( + (field, start, f"{middle.isoformat()}Z"), None, n_per_page + ) + self._request_pages( + (field, f"{next_second.isoformat()}Z", end), None, n_per_page + ) + return + + total_pages = int(np.ceil(json["issueCount"] / n_per_page)) print( "Found {} items, which will take {} pages".format( - json["issueCount"], n_pages + json["issueCount"], total_pages ), file=sys.stderr, ) @@ -251,7 +287,7 @@ def request(self, n_pages=100, n_per_page=50): total=json["issueCount"], desc="Downloading:", unit="issues", - disable=n_pages == 1 or not self.display_progress, + disable=total_pages == 1 or not self.display_progress, ) # Add the JSON to the raw data list @@ -264,6 +300,7 @@ def request(self, n_pages=100, n_per_page=50): if not pageInfo["hasNextPage"]: break + def _build_dataframe(self): # Extract bot users from raw data before DataFrame conversion def is_bot(user_dict): """Check if a GraphQL user object represents a bot account.""" diff --git a/tests/test_search_limit.py b/tests/test_search_limit.py new file mode 100644 index 0000000..7a93f4e --- /dev/null +++ b/tests/test_search_limit.py @@ -0,0 +1,103 @@ +import re +from datetime import datetime +from types import SimpleNamespace + +import pytest + +from github_activity import get_activity +from github_activity.graphql import GitHubGraphQlQuery + +START = "2020-01-01T00:00:00Z" +END = "2020-01-01T00:00:07Z" + + +def mock_search(monkeypatch, timestamps, activity): + """Serve GitHub's reported total, 1,000 accessible results, and real cursors.""" + calls = [] + nodes = [ + { + "id": str(number), + "number": number, + "url": f"https://github.com/org/repo/pull/{number}", + "createdAt": stamp if activity == "created" else "2019-01-01T00:00:00Z", + "closedAt": stamp if activity == "closed" else None, + "author": {"login": "contributor"}, + "mergedBy": None, + "reviews": None, + "commits": None, + "labels": {"edges": []}, + "reactions": {"totalCount": 0}, + } + for number, stamp in enumerate(timestamps, 1) + ] + + def post(url, json, auth): + query = json["query"] + kind, start, end = re.search( + r"(created|closed):([^ ]+)\.\.([^\"]+)", query + ).groups() + size = int(re.search(r"first: (\d+), query:", query)[1]) + cursor = re.search(r'after: "(\d+)"', query) + offset = int(cursor[1]) if cursor else 0 + calls.append((kind, start, end, offset)) + field = kind + "At" + matches = [row for row in nodes if row[field] and start <= row[field] <= end] + accessible = matches[:1000] + page = { + "issueCount": len(matches), + "nodes": accessible[offset : offset + size], + "pageInfo": { + "endCursor": str(offset + size), + "hasNextPage": offset + size < len(accessible), + }, + } + return SimpleNamespace(status_code=200, json=lambda: {"data": {"search": page}}) + + monkeypatch.setattr("github_activity.graphql.requests.post", post) + monkeypatch.setattr( + "github_activity.github_activity._validate_repository_exists", lambda *a: None + ) + monkeypatch.setattr( + "github_activity.github_activity._get_datetime_and_type", + lambda org, repo, date, auth: ( + datetime.fromisoformat(date.removesuffix("Z")), + False, + ), + ) + return calls + + +@pytest.mark.parametrize("activity", ["created", "closed"]) +def test_complete_large_window(monkeypatch, activity): + # The two occupied seconds fall into the same half twice before they split. + next_second = "2020-01-01T00:00:01Z" + calls = mock_search(monkeypatch, [START] * 500 + [next_second] * 501, activity) + data = get_activity("org/repo", since=START, until=END, kind="pr", auth="dummy") + assert sorted(data["number"]) == list(range(1, 1002)) + # Split on the first response; paging through a truncated parent wastes quota. + assert [c[3] for c in calls if c[:3] == (activity, START, END)] == [0] + other = "closed" if activity == "created" else "created" + assert [c for c in calls if c[0] == other] == [(other, START, END, 0)] + + +def test_exactly_1000_needs_no_split(monkeypatch): + calls = mock_search(monkeypatch, [START] * 1000, "created") + result = get_activity("org", since=START, until=START, kind="pr", auth="dummy") + assert len(result) == 1000 + assert [c[3] for c in calls if c[0] == "created"] == list(range(0, 1000, 50)) + + +def test_single_second_over_limit(monkeypatch): + mock_search(monkeypatch, [START] * 1001, "created") + with pytest.raises(ValueError, match="1,000|1000"): + get_activity("org/repo", since=START, until=START, kind="pr", auth="dummy") + + +def test_explicit_page_limit(monkeypatch): + calls = mock_search(monkeypatch, [START] * 1001, "created") + query = GitHubGraphQlQuery( + f"repo:org/repo type:pr created:{START}..{END}", auth="dummy" + ) + query.request(n_pages=2, n_per_page=10) + assert query.data["number"].tolist() == list(range(1, 21)) + assert [c[3] for c in calls] == [0, 10]