Skip to content

Add pagination handling for Gitea provider API endpoints - #2147

Closed
naorpeled with Copilot wants to merge 3 commits into
mainfrom
copilot/fix-pagination-in-gitea-api
Closed

naorpeled with Copilot wants to merge 3 commits into
mainfrom
copilot/fix-pagination-in-gitea-api

Conversation

Copilot AI commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor

Gitea provider's get_change_file_pull_request() and get_pr_commits() methods only fetched the first page of results (default 30 items), causing incomplete data for PRs with many files or commits.

Changes

  • Added _fetch_paginated() helper in RepoApi class - iterates through all pages using page/limit params, returns accumulated results, handles errors gracefully with partial result recovery
  • Refactored get_change_file_pull_request() to use pagination helper
  • Refactored get_pr_commits() to use pagination helper
  • Added 10 unit tests covering single/multi-page responses, empty responses, error handling, and partial result recovery

Example

Before: PRs with >30 files would silently return truncated results.

After: All pages are fetched automatically:

def get_change_file_pull_request(self, owner: str, repo: str, pr_number: int):
    """Get changed files in the pull request"""
    base_url = f'/repos/{owner}/{repo}/pulls/{pr_number}/files'
    return self._fetch_paginated(base_url, "changed files")
Original prompt

This section details on the original issue you should resolve

<issue_title>Missing Pagination Handling in Gitea Provider API Wrappers</issue_title>
<issue_description>### Git provider

Other

System Info

Gitea: 1.23.6
Docker image: codiumai/pr-agent:0.31-gitea_app

Bug details

Description

Some Python API wrapper methods in the Gitea provider do not handle pagination correctly. As a result, when fetching data related to a pull request, only the first page of results is returned (default limit: 30 items), causing incomplete data retrieval for PRs with more items.

This impacts pull requests that contain more than 30 files or commits.

Affected Endpoints

The following API wrappers are affected:

  • get_change_file_pull_request(): repos/{owner}/{repo}/pulls/{pr_number}/files
  • get_pr_commits(): /repos/{owner}/{repo}/pulls/{pr_number}/commits

Current Behavior

Only the first page of results is fetched.
Pagination parameters (e.g. page, limit) are not iterated.
PRs with more than 30 files or commits return incomplete data.

Expected Behavior

All pages should be fetched until no more results are returned.
The full list of files and commits for a pull request should be available, regardless of size.</issue_description>

<agent_instructions>Make sure to update/create relevant tests.</agent_instructions>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 2 commits January 3, 2026 22:00
- Implement _fetch_paginated helper method in RepoApi class
- Update get_change_file_pull_request to use pagination
- Update get_pr_commits to use pagination
- Add comprehensive unit tests for pagination functionality

Fixes issue where PRs with more than 30 files or commits
would return incomplete data due to missing pagination handling.

Co-authored-by: naorpeled <6171622+naorpeled@users.noreply.github.com>
Address code review feedback by removing redundant
conditional expressions in error handlers.

Co-authored-by: naorpeled <6171622+naorpeled@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix pagination handling in Gitea provider API wrappers Add pagination handling for Gitea provider API endpoints Jan 3, 2026
Copilot AI requested a review from naorpeled January 3, 2026 22:02
@jong47

jong47 commented Feb 1, 2026

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2138 - Partially compliant

Compliant requirements:

  • Fix Gitea provider API wrappers so they correctly handle pagination when fetching PR-related data.
  • Ensure get_change_file_pull_request() fetches all pages for repos/{owner}/{repo}/pulls/{pr_number}/files.
  • Ensure get_pr_commits() fetches all pages for /repos/{owner}/{repo}/pulls/{pr_number}/commits.
  • Continue fetching pages until no more results are returned (avoid truncation at default page size ~30).
  • The full list of files and commits should be available for large PRs (>30 files/commits).

Non-compliant requirements:

Requires further human verification:

  • Verify against a real Gitea 1.23.6 instance that page/limit query params are honored for these endpoints and that limit=50 is acceptable for the deployed configuration.
  • Verify real giteapy call_api response shapes match the parsing logic (response.data.read() vs tuple response) across versions/configurations.
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 Security concerns

Sensitive information exposure:
the code appends the auth token as a token query parameter in the request URL (e.g., ...?token=...&page=...). Query strings are commonly logged by proxies, servers, and observability tooling, and can leak credentials more easily than headers. If Gitea supports header-based auth for these calls via the configured client, prefer using the Authorization header rather than placing the token in the URL.

⚡ Recommended focus areas for review

Robustness

_fetch_paginated() manually constructs URLs with query strings; if base_url ever already contains query params (now or in future refactors), this will produce invalid URLs (double ? / missing &). Consider using a query builder (or passing query_params to the API client if supported) to avoid subtle URL bugs.

def _fetch_paginated(self, base_url: str, error_context: str) -> list:
    """Fetch all pages of a paginated API endpoint.

    Args:
        base_url: The base API URL (without pagination params)
        error_context: Description for error logging (e.g., "changed files")

    Returns:
        List of all items from all pages
    """
    all_items = []
    page = 1
    limit = 50  # Gitea's default max is usually 50

    try:
        token = self.api_client.configuration.api_key.get('Authorization', '').replace('token ', '')

        while True:
            # Build URL with pagination parameters
            if token:
                url = f'{base_url}?token={token}&page={page}&limit={limit}'
            else:
                url = f'{base_url}?page={page}&limit={limit}'
Data parsing

The response parsing branches on hasattr(response, 'data') vs isinstance(response, tuple) and then reads/decodes bytes. If the API client returns other common shapes (e.g., (data, status, headers) tuples, or already-decoded Python objects), this may break or mis-handle pagination. Consider normalizing/parsing response in one place (and/or validating the expected type) to prevent silent failures.

page_items = []
if hasattr(response, 'data'):
    raw_data = response.data.read()
    page_items = json.loads(raw_data.decode('utf-8'))
elif isinstance(response, tuple):
    raw_data = response[0].read()
    page_items = json.loads(raw_data.decode('utf-8'))
Failure mode

On ApiException, _fetch_paginated() logs and returns partial results, which can mask upstream outages/permission issues and lead to incomplete PR analysis without an explicit signal. Consider whether callers need an explicit indicator (e.g., raising, returning a structured result, or logging with stronger context including endpoint/page) so truncation due to errors is observable.

except ApiException as e:
    self.logger.error(f"Error getting {error_context}: {e}")
    return all_items
except Exception as e:
    self.logger.error(f"Unexpected error: {e}")
    return all_items

@IsmaelMartinez IsmaelMartinez left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three things worth addressing before this can land.

The branch predates the move to header auth. main now passes auth_settings=['AuthorizationHeaderToken'] on every call and no longer puts the token in the URL, so this would reintroduce credentials in query strings, where they end up in server logs and proxies. That is also most of the conflict.

The termination check can still truncate. limit is hardcoded to 50 and the loop stops when a page returns fewer than 50 items, but Gitea's max page size is configurable and often lower. On a server capped at 30, asking for 50 returns 30, the loop breaks after one page, and the original bug is back. Looping until an empty page avoids the assumption.

Both except branches return all_items, so a failure halfway through pagination yields a silently truncated list. That is the same silent truncation this PR is fixing, just moved.

Happy to open a rebased version with these addressed if that is easier than reviving this one.

@naorpeled naorpeled closed this Aug 29, 2026
@naorpeled
naorpeled deleted the copilot/fix-pagination-in-gitea-api branch August 29, 2026 20:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing Pagination Handling in Gitea Provider API Wrappers

4 participants