From c62db5b2a39ed5a5b46692b7ef3976bde8b7b1a7 Mon Sep 17 00:00:00 2001 From: silverwind Date: Thu, 5 Nov 2026 21:58:17 +0000 Subject: [PATCH] perf: reduce git processes and queries on pull request view (#40224) Removes redundant work from the pull request conversation tab. - Base and head refs resolve through the `cat-file` batch of the git repos the callers already hold, instead of two `git rev-parse` processes, reducing the number of git processes from 9 to 7 per page, about 17 ms faster locally. - Sidebar reviewers are batch-loaded and code-review comments reuse their loaded poster, reducing the number of SQL queries from 387 to 358 on a PR with 169 timeline entries and 15 reviews. Also fixes the commit list of merged pull requests, which resolved the merge base as a branch name and returned 500. --------- Co-authored-by: wxiaoguang --- docs/guidelines-backend.md | 5 +++ models/issues/review.go | 16 ++++--- routers/api/v1/repo/pull.go | 38 +++++++++++----- routers/web/repo/compare.go | 9 +++- routers/web/repo/issue_page_meta.go | 12 +++-- routers/web/repo/issue_view.go | 10 ++--- routers/web/repo/pull.go | 9 +++- services/git/compare.go | 61 ++++++++++++++------------ services/pull/pull.go | 13 ++++-- tests/integration/pull_compare_test.go | 5 +++ 10 files changed, 116 insertions(+), 62 deletions(-) diff --git a/docs/guidelines-backend.md b/docs/guidelines-backend.md index 4c6421a838a..b3c3afd434f 100644 --- a/docs/guidelines-backend.md +++ b/docs/guidelines-backend.md @@ -88,6 +88,11 @@ conditional `UPDATE` or a lock. struct conditions and inserts of more than 1000 rows. - Paginated queries need a unique tiebreaker like `id` for a stable order. +### Git + +- Pass already opened repositories down or use `git.RepositoryFromContextOrOpen` + rather than reopening them or spawning extra `git` processes. + ## Dependencies Go dependencies are managed with [Go Modules](https://go.dev/ref/mod). diff --git a/models/issues/review.go b/models/issues/review.go index 7ac096f454d..eb3615ab58e 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -121,11 +121,15 @@ func (rt ReviewType) Icon() string { // Review represents collection of code comments giving feedback for a PR type Review struct { - ID int64 `xorm:"pk autoincr"` - Type ReviewType - Reviewer *user_model.User `xorm:"-"` - ReviewerID int64 `xorm:"index"` - ReviewerTeamID int64 `xorm:"NOT NULL DEFAULT 0"` + ID int64 `xorm:"pk autoincr"` + Type ReviewType + Reviewer *user_model.User `xorm:"-"` + + // HINT: REVIEWER-ID-NEGATIVE: ReviewerID and ReviewerTeamID must be positive at the moment, + // because the current template uses a trick "ItemID < 0" means "team id" + ReviewerID int64 `xorm:"index"` + ReviewerTeamID int64 `xorm:"NOT NULL DEFAULT 0"` + ReviewerTeam *organization.Team `xorm:"-"` OriginalAuthor string OriginalAuthorID int64 @@ -186,7 +190,7 @@ func (r *Review) LoadReviewerTeam(ctx context.Context) (err error) { return nil } - r.ReviewerTeam, err = organization.GetTeamByID(ctx, r.ReviewerTeamID) + r.ReviewerTeamID, r.ReviewerTeam, err = organization.GetPossibleTeamByID(ctx, r.ReviewerTeamID) return err } diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index eb522a28521..ebaf72d7901 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -1103,7 +1103,14 @@ func parseCompareInfo(ctx *context.APIContext, compareParam string) (result *git return nil, nil } - compareInfo, err := git_service.GetCompareInfo(ctx, baseRepo, headRepo, headGitRepo, baseRef, headRef, compareReq.DirectComparison(), false) + compareInfo, err := git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: baseRepo, + BaseGitRepo: ctx.Repo.GitRepo, + BaseRef: baseRef, + HeadRepo: headRepo, + HeadGitRepo: headGitRepo, + HeadRef: headRef, + }, compareReq.DirectComparison(), false) if err != nil { ctx.APIErrorInternal(err) return nil, nil @@ -1347,13 +1354,18 @@ func GetPullRequestCommits(ctx *context.APIContext) { } defer closer.Close() - var compareInfo git_service.CompareInfo + baseRef := git.RefNameFromBranch(pr.BaseBranch) if pr.HasMerged { - compareInfo, err = git_service.GetCompareInfo(ctx, pr.BaseRepo, pr.BaseRepo, baseGitRepo, git.RefName(pr.MergeBase), git.RefName(pr.GetGitHeadRefName()), false, false) - } else { - compareInfo, err = git_service.GetCompareInfo(ctx, pr.BaseRepo, pr.BaseRepo, baseGitRepo, git.RefNameFromBranch(pr.BaseBranch), git.RefName(pr.GetGitHeadRefName()), false, false) + baseRef = git.RefName(pr.MergeBase) } - + compareInfo, err := git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: pr.BaseRepo, + BaseGitRepo: baseGitRepo, + BaseRef: baseRef, + HeadRepo: pr.BaseRepo, + HeadGitRepo: baseGitRepo, + HeadRef: git.RefName(pr.GetGitHeadRefName()), + }, false, false) if gitcmd.IsStderr(err, gitcmd.StderrBadRevision) { ctx.APIError(http.StatusNotFound, "invalid base branch or revision") return @@ -1473,12 +1485,18 @@ func GetPullRequestFiles(ctx *context.APIContext) { baseGitRepo := ctx.Repo.GitRepo - var compareInfo git_service.CompareInfo + baseRef := git.RefNameFromBranch(pr.BaseBranch) if pr.HasMerged { - compareInfo, err = git_service.GetCompareInfo(ctx, pr.BaseRepo, pr.BaseRepo, baseGitRepo, git.RefName(pr.MergeBase), git.RefName(pr.GetGitHeadRefName()), false, false) - } else { - compareInfo, err = git_service.GetCompareInfo(ctx, pr.BaseRepo, pr.BaseRepo, baseGitRepo, git.RefNameFromBranch(pr.BaseBranch), git.RefName(pr.GetGitHeadRefName()), false, false) + baseRef = git.RefName(pr.MergeBase) } + compareInfo, err := git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: pr.BaseRepo, + BaseGitRepo: baseGitRepo, + BaseRef: baseRef, + HeadRepo: pr.BaseRepo, + HeadGitRepo: baseGitRepo, + HeadRef: git.RefName(pr.GetGitHeadRefName()), + }, false, false) if err != nil { ctx.APIErrorInternal(err) return diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index 604d861a6de..a874b39d514 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -296,7 +296,14 @@ func (cpi *comparePageInfoType) parseCompareInfo(ctx *context.Context, comparePa } } - compareInfo, err := git_service.GetCompareInfo(ctx, baseRepo, headRepo, headGitRepo, baseRef, headRef, compareReq.DirectComparison(), fileOnly) + compareInfo, err := git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: baseRepo, + BaseGitRepo: ctx.Repo.GitRepo, + BaseRef: baseRef, + HeadRepo: headRepo, + HeadGitRepo: headGitRepo, + HeadRef: headRef, + }, compareReq.DirectComparison(), fileOnly) if err != nil { return err } diff --git a/routers/web/repo/issue_page_meta.go b/routers/web/repo/issue_page_meta.go index abd97328443..36f6353a280 100644 --- a/routers/web/repo/issue_page_meta.go +++ b/routers/web/repo/issue_page_meta.go @@ -436,6 +436,7 @@ func (d *IssuePageMetaData) retrieveReviewersData(ctx *context.Context) { Review: review, ItemID: review.ReviewerID, } + // HINT: REVIEWER-ID-NEGATIVE: ItemID < 0 means "team id" if review.ReviewerTeamID > 0 { tmp.IsTeam = true tmp.ItemID = -review.ReviewerTeamID @@ -457,23 +458,20 @@ func (d *IssuePageMetaData) retrieveReviewersData(ctx *context.Context) { } if len(pullReviews) > 0 { - // Drop all non-existing users and teams from the reviews + if err := reviews.LoadReviewers(ctx); err != nil { + ctx.ServerError("LoadReviewers", err) + return + } currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews)) for _, item := range pullReviews { if item.Review.ReviewerID > 0 { if err := item.Review.LoadReviewer(ctx); err != nil { - if user_model.IsErrUserNotExist(err) { - continue - } ctx.ServerError("LoadReviewer", err) return } item.User = item.Review.Reviewer } else if item.Review.ReviewerTeamID > 0 { if err := item.Review.LoadReviewerTeam(ctx); err != nil { - if organization.IsErrTeamNotExist(err) { - continue - } ctx.ServerError("LoadReviewerTeam", err) return } diff --git a/routers/web/repo/issue_view.go b/routers/web/repo/issue_view.go index 75926782865..86c58d0cde4 100644 --- a/routers/web/repo/issue_view.go +++ b/routers/web/repo/issue_view.go @@ -753,12 +753,12 @@ func prepareIssueViewCommentsAndSidebarParticipants(ctx *context.Context, issue if comment.Review == nil { continue } + if comment.Poster.ID == comment.Review.ReviewerID { + comment.Review.Reviewer = comment.Poster + } if err = comment.Review.LoadAttributes(ctx); err != nil { - if !user_model.IsErrUserNotExist(err) { - ctx.ServerError("Review.LoadAttributes", err) - return - } - comment.Review.Reviewer = user_model.NewGhostUser() + ctx.ServerError("Review.LoadAttributes", err) + return } if err = comment.Review.LoadCodeComments(ctx); err != nil { ctx.ServerError("Review.LoadCodeComments", err) diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 7ee49f50ac3..cdb47fa3fd4 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -370,7 +370,14 @@ func (prInfo *pullRequestViewInfo) prepareViewFillInfo(ctx *context.Context, bas func (prInfo *pullRequestViewInfo) prepareViewFillCompareInfo(ctx *context.Context, baseRef git.RefName) { var err error pull := prInfo.issue.PullRequest - prInfo.CompareInfo, err = git_service.GetCompareInfo(ctx, ctx.Repo.Repository, ctx.Repo.Repository, ctx.Repo.GitRepo, baseRef, git.RefName(pull.GetGitHeadRefName()), false, false) + prInfo.CompareInfo, err = git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: ctx.Repo.Repository, + BaseGitRepo: ctx.Repo.GitRepo, + BaseRef: baseRef, + HeadRepo: ctx.Repo.Repository, + HeadGitRepo: ctx.Repo.GitRepo, + HeadRef: git.RefName(pull.GetGitHeadRefName()), + }, false, false) if err != nil { if !errors.Is(err, util.ErrNotExist) && !gitcmd.IsStderr(err, gitcmd.StderrNotValidObjectName) { log.Error("GetCompareInfo: %v", err) diff --git a/services/git/compare.go b/services/git/compare.go index 0bdebd09102..d87b332e1a0 100644 --- a/services/git/compare.go +++ b/services/git/compare.go @@ -13,14 +13,21 @@ import ( "gitea.dev/modules/util" ) +type CompareBaseHead struct { + BaseRepo *repo_model.Repository + BaseGitRepo *git.Repository + BaseRef git.RefName + + HeadRepo *repo_model.Repository + HeadGitRepo *git.Repository + HeadRef git.RefName +} + // CompareInfo represents needed information for comparing references. type CompareInfo struct { - BaseRepo *repo_model.Repository - BaseRef git.RefName + CompareBaseHead + BaseCommitID string - HeadRepo *repo_model.Repository - HeadGitRepo *git.Repository - HeadRef git.RefName HeadCommitID string CompareSeparator string @@ -51,45 +58,41 @@ func (ci *CompareInfo) DirectComparison() bool { // GetCompareInfo generates and returns compare information between base and head branches of repositories. // It does its best to fill the fields as many as it can. // MergeBase can be empty if the base and head are unrelated. -func GetCompareInfo(ctx context.Context, baseRepo, headRepo *repo_model.Repository, headGitRepo *git.Repository, baseRef, headRef git.RefName, directComparison, fileOnly bool) (compareInfo CompareInfo, err error) { - baseCommitID, err1 := git.GetFullCommitID(ctx, baseRepo, baseRef.String()) - headCommitID, err2 := git.GetFullCommitID(ctx, headRepo, headRef.String()) - compareInfo = CompareInfo{ - BaseRepo: baseRepo, - BaseRef: baseRef, +func GetCompareInfo(ctx context.Context, bh CompareBaseHead, directComparison, fileOnly bool) (ci CompareInfo, err error) { + baseCommitID, err1 := bh.BaseGitRepo.GetRefCommitID(ctx, bh.BaseRef.String()) + headCommitID, err2 := bh.HeadGitRepo.GetRefCommitID(ctx, bh.HeadRef.String()) + ci = CompareInfo{ + CompareBaseHead: bh, BaseCommitID: baseCommitID, - HeadRepo: headRepo, - HeadGitRepo: headGitRepo, - HeadRef: headRef, HeadCommitID: headCommitID, CompareSeparator: util.Iif(directComparison, "..", "..."), } if err1 != nil || err2 != nil { - return compareInfo, errors.Join(err1, err2) + return ci, errors.Join(err1, err2) } // if they are not the same repository, then we need to fetch the base commit into the head repository - // because we will use headGitRepo in the following code - if baseRepo.ID != headRepo.ID { - exist := headGitRepo.IsReferenceExist(ctx, compareInfo.BaseCommitID) + // because we will use the head repository in the following code + if bh.BaseRepo.ID != bh.HeadRepo.ID { + exist := bh.HeadGitRepo.IsReferenceExist(ctx, ci.BaseCommitID) if !exist { - if err := git.FetchRemoteTempCommit(ctx, headRepo, baseRepo, compareInfo.BaseCommitID); err != nil { - return compareInfo, fmt.Errorf("FetchRemoteTempCommit: %w", err) + if err := git.FetchRemoteTempCommit(ctx, bh.HeadRepo, bh.BaseRepo, ci.BaseCommitID); err != nil { + return ci, fmt.Errorf("FetchRemoteTempCommit: %w", err) } } } if !directComparison { - compareInfo.CompareBase, err = git.MergeBase(ctx, headRepo, compareInfo.BaseCommitID, compareInfo.HeadCommitID) + ci.CompareBase, err = git.MergeBase(ctx, bh.HeadRepo, ci.BaseCommitID, ci.HeadCommitID) if err != nil && !errors.Is(err, util.ErrNotExist) { - return compareInfo, fmt.Errorf("MergeBase: %w", err) + return ci, fmt.Errorf("MergeBase: %w", err) } } else { - compareInfo.CompareBase = compareInfo.BaseCommitID + ci.CompareBase = ci.BaseCommitID } - if compareInfo.CompareBase == "" { - return compareInfo, nil + if ci.CompareBase == "" { + return ci, nil } // We have a common base - therefore we know that ... should work @@ -98,15 +101,15 @@ func GetCompareInfo(ctx context.Context, baseRepo, headRepo *repo_model.Reposito // which is different from the meaning of "..." in git diff (where it implies diffing from the merge base). // For listing PR commits, we must use merge-base..head to include only the commits introduced by the head branch. // Otherwise, commits newly pushed to the base branch would also be included, which is incorrect. - compareInfo.Commits, err = headGitRepo.ShowPrettyFormatLogToList(ctx, compareInfo.CompareBase+".."+compareInfo.HeadCommitID) + ci.Commits, err = bh.HeadGitRepo.ShowPrettyFormatLogToList(ctx, ci.CompareBase+".."+ci.HeadCommitID) if err != nil { - return compareInfo, fmt.Errorf("ShowPrettyFormatLogToList: %w", err) + return ci, fmt.Errorf("ShowPrettyFormatLogToList: %w", err) } } // Count number of changed files. // TODO: This probably should be removed as we need to use shortstat elsewhere // Now there is git diff --shortstat but this appears to be slower than simply iterating with --nameonly - compareInfo.NumFiles, err = headGitRepo.GetDiffNumChangedFiles(ctx, compareInfo.BaseCommitID, compareInfo.HeadCommitID, directComparison) - return compareInfo, err + ci.NumFiles, err = bh.HeadGitRepo.GetDiffNumChangedFiles(ctx, ci.BaseCommitID, ci.HeadCommitID, directComparison) + return ci, err } diff --git a/services/pull/pull.go b/services/pull/pull.go index 3789d7f0b1c..0a68e4dbd21 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -1015,11 +1015,18 @@ func GetPullCommits(ctx context.Context, baseGitRepo *git.Repository, doer *user if err := pull.LoadBaseRepo(ctx); err != nil { return nil, "", err } - baseBranch := pull.BaseBranch + baseRef := git.RefNameFromBranch(pull.BaseBranch) if pull.HasMerged { - baseBranch = pull.MergeBase + baseRef = git.RefName(pull.MergeBase) } - compareInfo, err := git_service.GetCompareInfo(ctx, pull.BaseRepo, pull.BaseRepo, baseGitRepo, git.RefNameFromBranch(baseBranch), git.RefName(pull.GetGitHeadRefName()), false, false) + compareInfo, err := git_service.GetCompareInfo(ctx, git_service.CompareBaseHead{ + BaseRepo: pull.BaseRepo, + BaseGitRepo: baseGitRepo, + BaseRef: baseRef, + HeadRepo: pull.BaseRepo, + HeadGitRepo: baseGitRepo, + HeadRef: git.RefName(pull.GetGitHeadRefName()), + }, false, false) if err != nil { return nil, "", err } diff --git a/tests/integration/pull_compare_test.go b/tests/integration/pull_compare_test.go index 0d12c757da2..622d2b25df5 100644 --- a/tests/integration/pull_compare_test.go +++ b/tests/integration/pull_compare_test.go @@ -38,6 +38,11 @@ func TestListPullCommits(t *testing.T) { assert.Equal(t, "5c050d3b6d2db231ab1f64e324f1b6b9a0b181c2", pullCommitList.Commits[1].ID) assert.Equal(t, "4a357436d925b5c974181ff12a994538ddc5a269", pullCommitList.LastReviewCommitSha) + t.Run("MergedPull", func(t *testing.T) { + defer tests.PrintCurrentTest(t)() + session.MakeRequest(t, NewRequest(t, "GET", "/user2/repo1/pulls/2/commits/list"), http.StatusOK) + }) + t.Run("CommitBlobExcerpt", func(t *testing.T) { defer tests.PrintCurrentTest(t)() req = NewRequest(t, "GET", "/user2/repo1/blob_excerpt/985f0301dba5e7b34be866819cd15ad3d8f508ee?last_left=0&last_right=0&left=2&right=2&left_hunk_size=2&right_hunk_size=2&path=README.md&style=split&direction=up")