Cap the commits the compare API returns to unauthenticated callers

What does this MR do and why?

Unauthenticated callers of GET /projects/:id/repository/compare now receive at most MergeRequestDiff::COMMITS_SAFE_SIZE (100) commits per response, the most recent ones, matching Projects::CompareController#gitaly_commits_limit on the web compare page. Authenticated callers are unchanged. This is behind the compare_api_anonymous_commits_limit feature flag, off by default.

The entity memoizes the commit list so commit and commits share one ListCommits RPC when a limit is set, and the limit is part of the response cache key so capped and uncapped responses never share an entry.

Rollback: disable compare_api_anonymous_commits_limit.

References

Detailed context for reviewers and AI agents

Shape

  • compare_commits_limit returns COMMITS_SAFE_SIZE for anonymous callers when the flag is enabled, nil otherwise. It is passed to the entity as commits_limit: and appended to the cache key.
  • API::Entities::Compare#commit_collection memoizes compare.commits(limit:), mirroring the existing diff_collection memoization. Compare#commits(limit:) is not memoized itself.
  • Gitlab::Git::Commit.between(limit:) returns the newest N commits reordered chronologically, so commits.last is still the head commit.

Choices to confirm

  • 100, not 101. The web controller asks for COMMITS_SAFE_SIZE + 1 only to detect overflow for its "100+" label. The API has no such field, so it returns exactly 100.
  • Anonymous only. Extending the cap to signed-in callers is a product decision and needs coordination with Code Review, whose Duo re-reviews call this route (https://gitlab.com/gitlab-org/gitlab/-/work_items/634800). Recorded as Phase 2 on the issue.
  • Flag actor is the project, matching commit_stats_failure_handling.

Docs

doc/api/repositories.md: history entry, flag note, prose, and the commits response table row.

How to set up and validate locally

  1. In the Rails console, enable the flag:

    Feature.enable(:compare_api_anonymous_commits_limit)
  2. Pick a public project with a branch more than 100 commits ahead of another ref.

  3. Request the comparison without a token:

    curl --url "http://gdk.test:3000/api/v4/projects/<project id>/repository/compare?from=<base>&to=<head>" | jq '.commits | length'

    The result is 100, and .commit.id equals the last entry in .commits.

  4. Repeat with --header "PRIVATE-TOKEN: <token>". All commits are returned.

  5. Disable the flag and repeat the unauthenticated request. All commits are returned.

MR acceptance checklist

Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Gavin Hinfey

Merge request reports

Loading
Loading