From 5c9d74e0198c02400a38769e2d234f93d71a3843 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Fri, 13 Nov 2026 13:13:31 +0200 Subject: [PATCH] perf(coderd/x/gitsync): poll merged PRs hourly (#31922) Merged PRs cannot reopen, so their diff-status rows do not need the two-minute TTL used for open and closed PRs. Use a one-hour TTL after successful diff-status refreshes of merged PRs while retaining periodic metadata updates. Workspace git reports still set `stale_at` to the past so merged diff-status rows remain eligible for the next worker tick. Refs CODAGT-1543 --- coderd/x/gitsync/gitsync.go | 16 +++- coderd/x/gitsync/gitsync_test.go | 134 ++++++++++++++++++++----------- coderd/x/gitsync/worker_test.go | 110 +++++++++++++++++++++++++ 3 files changed, 209 insertions(+), 51 deletions(-) diff --git a/coderd/x/gitsync/gitsync.go b/coderd/x/gitsync/gitsync.go index 60b6ccd9e12..922c7606fe8 100644 --- a/coderd/x/gitsync/gitsync.go +++ b/coderd/x/gitsync/gitsync.go @@ -20,10 +20,15 @@ import ( ) const ( - // DiffStatusTTL is how long a successfully refreshed - // diff status remains fresh before becoming stale again. + // DiffStatusTTL is the TTL after a successful diff-status refresh, + // unless the PR is merged. It is also the ordinary error backoff. DiffStatusTTL = 120 * time.Second + // MergedDiffStatusTTL is the TTL after a successful diff-status refresh + // of a merged PR. Merged PRs cannot reopen; periodic diff-status refreshes + // pick up metadata edits such as titles and reviews. + MergedDiffStatusTTL = time.Hour + // defaultConcurrency is the maximum number of HTTP calls // made in parallel during a single Refresh batch. defaultConcurrency = 10 @@ -341,6 +346,11 @@ func (r *Refresher) refreshOne( } } + ttl := DiffStatusTTL + if status.State == gitprovider.PRStateMerged { + ttl = MergedDiffStatusTTL + } + if status.PRNumber < math.MinInt32 || status.PRNumber > math.MaxInt32 { return nil, xerrors.Errorf("pull request number %d overflows int32", status.PRNumber) } @@ -370,7 +380,7 @@ func (r *Refresher) refreshOne( Approved: sql.NullBool{Bool: status.Approved, Valid: true}, ReviewerCount: sql.NullInt32{Int32: status.ReviewerCount, Valid: true}, RefreshedAt: now, - StaleAt: now.Add(DiffStatusTTL), + StaleAt: now.Add(ttl), } return params, nil diff --git a/coderd/x/gitsync/gitsync_test.go b/coderd/x/gitsync/gitsync_test.go index 8f0fbe150a6..d4f50ee03c6 100644 --- a/coderd/x/gitsync/gitsync_test.go +++ b/coderd/x/gitsync/gitsync_test.go @@ -499,58 +499,89 @@ func TestRefresher_BatchGroupsByOwnerAndOrigin(t *testing.T) { "TokenResolver should be called once per (owner, origin) group") } -func TestRefresher_UsesInjectedClock(t *testing.T) { +func TestRefresher_StaleAtByPRState(t *testing.T) { t.Parallel() - mClock := quartz.NewMock(t) - fixedTime := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC) - mClock.Set(fixedTime) - - mp := &mockProvider{ - parsePullRequestURL: func(raw string) (gitprovider.PRRef, bool) { - return gitprovider.PRRef{Owner: "org", Repo: "repo", Number: 42}, true + tests := []struct { + name string + // The fetched PR state determines the TTL, not the stored PR state. + storedState gitprovider.PRState + fetchedState gitprovider.PRState + wantTTL time.Duration + }{ + { + name: "open", + storedState: gitprovider.PRStateClosed, + fetchedState: gitprovider.PRStateOpen, + wantTTL: gitsync.DiffStatusTTL, }, - fetchPullRequestStatus: func(_ context.Context, _ string, _ gitprovider.PRRef) (*gitprovider.PRStatus, error) { - return &gitprovider.PRStatus{ - State: gitprovider.PRStateOpen, - DiffStats: gitprovider.DiffStats{ - Additions: 10, - Deletions: 5, - ChangedFiles: 3, + { + name: "open after merged", + storedState: gitprovider.PRStateMerged, + fetchedState: gitprovider.PRStateOpen, + wantTTL: gitsync.DiffStatusTTL, + }, + { + name: "closed", + storedState: gitprovider.PRStateClosed, + fetchedState: gitprovider.PRStateClosed, + wantTTL: gitsync.DiffStatusTTL, + }, + { + name: "merged", + storedState: gitprovider.PRStateOpen, + fetchedState: gitprovider.PRStateMerged, + wantTTL: gitsync.MergedDiffStatusTTL, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + mClock := quartz.NewMock(t) + fixedTime := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC) + mClock.Set(fixedTime) + + mp := &mockProvider{ + parsePullRequestURL: func(raw string) (gitprovider.PRRef, bool) { + return gitprovider.PRRef{Owner: "org", Repo: "repo", Number: 42}, true }, - }, nil - }, + fetchPullRequestStatus: func(_ context.Context, _ string, _ gitprovider.PRRef) (*gitprovider.PRStatus, error) { + return &gitprovider.PRStatus{State: tt.fetchedState}, nil + }, + } + + providers := func(_ context.Context, _ string) gitprovider.Provider { return mp } + tokens := func(_ context.Context, _ uuid.UUID, _ string) (*string, error) { + return new("test-token"), nil + } + + r := gitsync.NewRefresher(providers, tokens, slogtest.Make(t, nil), mClock) + + row := database.ChatDiffStatus{ + ChatID: uuid.New(), + Url: sql.NullString{String: "https://github.com/org/repo/pull/42", Valid: true}, + GitRemoteOrigin: "https://github.com/org/repo", + GitBranch: "feature", + PullRequestState: sql.NullString{String: string(tt.storedState), Valid: true}, + } + + results, err := r.Refresh(context.Background(), []gitsync.RefreshRequest{ + {Row: row, OwnerID: uuid.New()}, + }) + require.NoError(t, err) + require.Len(t, results, 1) + res := results[0] + + require.NoError(t, res.Error) + require.NotNil(t, res.Params) + + assert.Equal(t, string(tt.fetchedState), res.Params.PullRequestState.String) + assert.Equal(t, fixedTime, res.Params.RefreshedAt) + assert.Equal(t, fixedTime.Add(tt.wantTTL), res.Params.StaleAt) + }) } - - providers := func(_ context.Context, _ string) gitprovider.Provider { return mp } - tokens := func(_ context.Context, _ uuid.UUID, _ string) (*string, error) { - return new("test-token"), nil - } - - r := gitsync.NewRefresher(providers, tokens, slogtest.Make(t, nil), mClock) - - chatID := uuid.New() - row := database.ChatDiffStatus{ - ChatID: chatID, - Url: sql.NullString{String: "https://github.com/org/repo/pull/42", Valid: true}, - GitRemoteOrigin: "https://github.com/org/repo", - GitBranch: "feature", - } - - ownerID := uuid.New() - results, err := r.Refresh(context.Background(), []gitsync.RefreshRequest{ - {Row: row, OwnerID: ownerID}, - }) - require.NoError(t, err) - require.Len(t, results, 1) - res := results[0] - - require.NoError(t, res.Error) - require.NotNil(t, res.Params) - - // The mock clock is deterministic, so times must be exact. - assert.Equal(t, fixedTime, res.Params.RefreshedAt) - assert.Equal(t, fixedTime.Add(gitsync.DiffStatusTTL), res.Params.StaleAt) } func TestRefresher_RateLimitSkipsRemainingInGroup(t *testing.T) { @@ -825,6 +856,8 @@ func TestRefresher_ConcurrentProcessing(t *testing.T) { func TestRefresher_PRURLBranchMismatch(t *testing.T) { t.Parallel() + // PR 42 at the stored URL is merged; branch lookup returns open PR 43. + // wantTTL distinguishes their fetched PR states. tests := []struct { name string headBranch string @@ -832,6 +865,7 @@ func TestRefresher_PRURLBranchMismatch(t *testing.T) { wantURL string wantCleared bool wantResolve bool + wantTTL time.Duration }{ { name: "branch mismatch resolves current branch", @@ -839,6 +873,7 @@ func TestRefresher_PRURLBranchMismatch(t *testing.T) { resolveTo: &gitprovider.PRRef{Owner: "org", Repo: "repo", Number: 43}, wantURL: "https://github.com/org/repo/pull/43", wantResolve: true, + wantTTL: gitsync.DiffStatusTTL, }, { name: "branch mismatch without PR clears stale URL", @@ -853,12 +888,14 @@ func TestRefresher_PRURLBranchMismatch(t *testing.T) { headBranch: "feature-b", wantURL: "https://github.com/org/repo/pull/42", wantResolve: false, + wantTTL: gitsync.MergedDiffStatusTTL, }, { name: "empty head branch keeps stored URL", headBranch: "", wantURL: "https://github.com/org/repo/pull/42", wantResolve: false, + wantTTL: gitsync.MergedDiffStatusTTL, }, } @@ -883,7 +920,7 @@ func TestRefresher_PRURLBranchMismatch(t *testing.T) { switch ref.Number { case 42: return &gitprovider.PRStatus{ - State: gitprovider.PRStateOpen, + State: gitprovider.PRStateMerged, HeadBranch: tt.headBranch, Title: "Old PR", }, nil @@ -936,6 +973,7 @@ func TestRefresher_PRURLBranchMismatch(t *testing.T) { require.NotNil(t, res.Params) require.True(t, res.Params.Url.Valid) assert.Equal(t, tt.wantURL, res.Params.Url.String) + assert.Equal(t, clock.Now().Add(tt.wantTTL), res.Params.StaleAt) }) } } diff --git a/coderd/x/gitsync/worker_test.go b/coderd/x/gitsync/worker_test.go index ebbd8df28f1..ff53d0b6cf2 100644 --- a/coderd/x/gitsync/worker_test.go +++ b/coderd/x/gitsync/worker_test.go @@ -1247,6 +1247,116 @@ func TestWorker(t *testing.T) { assert.WithinDuration(t, expectedStaleAt, status.StaleAt, time.Second) } +func TestWorker_MarkStaleRefreshesMergedPR(t *testing.T) { + t.Parallel() + + db, _ := dbtestutil.NewDB(t) + user := dbgen.User(t, db, database.User{}) + org := dbgen.Organization(t, db, database.Organization{}) + modelCfg := dbgen.ChatModelConfig(t, db, database.ChatModelConfig{}) + + templateVersion := dbgen.TemplateVersion(t, db, database.TemplateVersion{ + OrganizationID: org.ID, + CreatedBy: user.ID, + }) + template := dbgen.Template(t, db, database.Template{ + CreatedBy: user.ID, + OrganizationID: org.ID, + ActiveVersionID: templateVersion.ID, + }) + + workspace := dbgen.Workspace(t, db, database.WorkspaceTable{ + OwnerID: user.ID, + OrganizationID: org.ID, + TemplateID: template.ID, + }) + + chat := dbgen.Chat(t, db, database.Chat{ + OrganizationID: org.ID, + OwnerID: user.ID, + WorkspaceID: uuid.NullUUID{UUID: workspace.ID, Valid: true}, + LastModelConfigID: modelCfg.ID, + }) + + ctx := testutil.Context(t, testutil.WaitLong) + + // PostgreSQL stores timestamps at microsecond precision. + wallNow := time.Now().UTC().Truncate(time.Microsecond) + + // Keep invalidation behind PostgreSQL NOW() despite small clock skew. + now := wallNow.Add(-time.Minute) + mClock := quartz.NewMock(t) + mClock.Set(now) + + prURL := "https://github.com/o/r/pull/1" + _, err := db.UpsertChatDiffStatus(ctx, database.UpsertChatDiffStatusParams{ + ChatID: chat.ID, + GitRemoteOrigin: "https://github.com/o/r", + GitBranch: "feature", + Url: sql.NullString{String: prURL, Valid: true}, + PullRequestState: sql.NullString{String: string(gitprovider.PRStateMerged), Valid: true}, + PullRequestTitle: "Original title", + RefreshedAt: now, + StaleAt: now.Add(gitsync.MergedDiffStatusTTL), + }) + require.NoError(t, err) + + acquired, err := db.AcquireStaleChatDiffStatuses(ctx, 1) + require.NoError(t, err) + require.Empty(t, acquired, "a fresh merged diff-status row must not be acquired") + + refresher := newTestRefresher(t, mClock, func(cfg *testRefresherCfg) { + cfg.fetchPRStatus = func(context.Context, string, gitprovider.PRRef) (*gitprovider.PRStatus, error) { + return &gitprovider.PRStatus{ + State: gitprovider.PRStateMerged, + HeadBranch: "feature", + Title: "Updated title", + }, nil + } + }) + + // MarkStale publishes once; the diff-status refresh publishes again. + const wantPublishes int32 = 2 + tickDone := make(chan struct{}) + var publishCount atomic.Int32 + pub := func(_ context.Context, chatID uuid.UUID, _ codersdk.DiffStatusRef) error { + assert.Equal(t, chat.ID, chatID) + if publishCount.Add(1) == wantPublishes { + close(tickDone) + } + return nil + } + logger := slogtest.Make(t, nil) + worker := gitsync.NewWorker(db, refresher, pub, mClock, logger) + + // MarkStale makes the merged diff-status row eligible immediately. + worker.MarkStale(ctx, gitsync.MarkStaleParams{ + WorkspaceID: workspace.ID, + ChatID: chat.ID, + Origin: "https://github.com/o/r", + Branch: "feature", + }) + + statuses, err := db.GetChatDiffStatusesByChatID(ctx, chat.ID) + require.NoError(t, err) + require.Len(t, statuses, 1) + require.True(t, statuses[0].StaleAt.Before(mClock.Now())) + assert.Equal(t, prURL, statuses[0].Url.String) + assert.Equal(t, string(gitprovider.PRStateMerged), statuses[0].PullRequestState.String) + require.Equal(t, int32(1), publishCount.Load()) + + // The next tick updates metadata and sets stale_at using the hourly TTL. + tickOnce(ctx, t, mClock, worker, tickDone) + + statuses, err = db.GetChatDiffStatusesByChatID(ctx, chat.ID) + require.NoError(t, err) + require.Len(t, statuses, 1) + assert.Equal(t, "Updated title", statuses[0].PullRequestTitle) + assert.Equal(t, mClock.Now(), statuses[0].RefreshedAt.Time.UTC()) + assert.Equal(t, mClock.Now().Add(gitsync.MergedDiffStatusTTL), statuses[0].StaleAt.UTC()) + require.Equal(t, wantPublishes, publishCount.Load()) +} + func TestWorker_RefreshDoesNotReorderPrimary(t *testing.T) { t.Parallel() ctx := testutil.Context(t, testutil.WaitLong)