Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(ghsnapshot): sweep head-mismatched and checks-watched PRs for wakeup reliability (MUL-10223) (#11592)

Jiayuan Zhang4b3be67ea591
diff --git a/server/internal/handler/chat_wakeup.go b/server/internal/handler/chat_wakeup.go
index 20c5d4bdd0..6dc7132c34 100644
--- a/server/internal/handler/chat_wakeup.go
+++ b/server/internal/handler/chat_wakeup.go
@@ -1,9 +1,11 @@
package handler
import (
+ "context"
"encoding/json"
"errors"
"net/http"
+ "strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -183,6 +185,7 @@ func (h *Handler) CreateChatTurnWakeup(w http.ResponseWriter, r *http.Request) {
chatWakeupError(w, err)
return
}
+ h.maybeRefreshPRForChatWakeup(r.Context(), created.WorkspaceID, created.Condition)
writeJSON(w, http.StatusCreated, chatWakeupToResponse(created))
}
@@ -209,9 +212,43 @@ func (h *Handler) UpdateChatTurnWakeup(w http.ResponseWriter, r *http.Request) {
chatWakeupError(w, err)
return
}
+ h.maybeRefreshPRForChatWakeup(r.Context(), updated.WorkspaceID, updated.Condition)
writeJSON(w, http.StatusOK, chatWakeupToResponse(updated))
}
+// maybeRefreshPRForChatWakeup kicks off a non-blocking snapshot refresh for an
+// open/draft GitHub PR when a chat wakeup watching its checks is saved and the
+// PR's snapshot is missing or stale.
+func (h *Handler) maybeRefreshPRForChatWakeup(ctx context.Context, workspaceID pgtype.UUID, rawCondition []byte) {
+ if !h.PRRefresh.Enabled() || len(rawCondition) == 0 {
+ return
+ }
+ var cond service.ChatWakeupCondition
+ if json.Unmarshal(rawCondition, &cond) != nil || cond.Type != "pull_request" || cond.Event != "checks_finished" {
+ return
+ }
+ owner, repo, ok := strings.Cut(cond.Repo, "/")
+ if !ok || owner == "" || repo == "" || cond.Number <= 0 {
+ return
+ }
+ row, err := h.Queries.GetGitHubPRForRefresh(ctx, db.GetGitHubPRForRefreshParams{
+ WorkspaceID: workspaceID,
+ RepoOwner: owner,
+ RepoName: repo,
+ PrNumber: cond.Number,
+ })
+ if err != nil || (row.State != "open" && row.State != "draft") {
+ return
+ }
+ h.PRRefresh.MaybeEnqueueOnView(
+ row.InstallationID, row.RepoOwner, row.RepoName, row.PrNumber,
+ row.SnapshotFetchedAt.Time,
+ row.SnapshotFetchedAt.Valid &&
+ row.SnapshotHeadSha != "" &&
+ row.SnapshotHeadSha == row.HeadSha,
+ )
+}
+
func (h *Handler) CancelChatTurnWakeup(w http.ResponseWriter, r *http.Request) {
task, id, ok := h.chatTurnWakeupID(w, r)
if !ok {
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 1aee65321c..a99ddad39f 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -1318,7 +1318,7 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {
h.handleInstallationEvent(ctx, body)
case "pull_request":
h.handlePullRequestEvent(ctx, body)
- case "check_suite", "check_run", "status":
+ case "check_suite", "check_run", "status", "workflow_run":
// CI events are pure triggers under Plan C (MUL-5265): their payload is
// never read for display. Each just asks the API pipeline to re-fetch
// the authoritative snapshot for the PR(s) it concerns.
@@ -1662,8 +1662,9 @@ func (h *Handler) resolvePRLinkPolicy(ctx context.Context, insts []db.GithubInst
}
// ghCIEventPayload captures the shared shape of the check_suite / check_run /
-// status webhooks — enough to resolve which PR to refresh. These events are
-// pure triggers under Plan C: their payload data is never read for display.
+// status / workflow_run webhooks — enough to resolve which PR to refresh. These
+// events are pure triggers under Plan C: their payload data is never read for
+// display.
type ghCIEventPayload struct {
Installation struct {
ID int64 `json:"id"`
@@ -1683,6 +1684,7 @@ type ghCIEventPayload struct {
} `json:"pull_requests"`
} `json:"check_suite"`
CheckRun struct {
+ HeadSHA string `json:"head_sha"`
PullRequests []struct {
Number int32 `json:"number"`
} `json:"pull_requests"`
@@ -1690,56 +1692,72 @@ type ghCIEventPayload struct {
HeadSHA string `json:"head_sha"`
} `json:"check_suite"`
} `json:"check_run"`
+ WorkflowRun struct {
+ HeadSHA string `json:"head_sha"`
+ PullRequests []struct {
+ Number int32 `json:"number"`
+ } `json:"pull_requests"`
+ } `json:"workflow_run"`
}
// triggerPRRefreshFromCIEvent enqueues an API refresh for the PR(s) a
-// check_suite / check_run / status webhook concerns. check_suite/check_run
-// carry the PR numbers directly; status events carry only a commit SHA, so we
-// map it back to the mirrored head_sha to find the PR(s).
-func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte) {
- if !h.PRRefresh.Enabled() {
- return
- }
+// check_suite / check_run / status / workflow_run webhook concerns. Check and
+// workflow events may carry the PR numbers directly; status events (and check
+// events with an empty pull_requests list) carry a commit SHA, which we map
+// back to the mirrored head_sha to find the PR(s).
+func parseCIEventTargets(body []byte) (installationID int64, owner, repo string, numbers []int32, headSHA string, ok bool) {
var p ghCIEventPayload
if err := json.Unmarshal(body, &p); err != nil {
- return
+ return 0, "", "", nil, "", false
}
if p.Installation.ID == 0 || p.Repository.Name == "" {
- return
+ return 0, "", "", nil, "", false
}
- owner, repo := p.Repository.Owner.Login, p.Repository.Name
-
seen := map[int32]struct{}{}
- enqueue := func(number int32) {
+ add := func(number int32) {
if number == 0 {
return
}
- if _, ok := seen[number]; ok {
+ if _, dup := seen[number]; dup {
return
}
seen[number] = struct{}{}
- h.PRRefresh.Enqueue(p.Installation.ID, owner, repo, number)
+ numbers = append(numbers, number)
}
for _, pr := range p.CheckSuite.PullRequests {
- enqueue(pr.Number)
+ add(pr.Number)
}
for _, pr := range p.CheckRun.PullRequests {
- enqueue(pr.Number)
+ add(pr.Number)
}
- if len(seen) > 0 {
+ for _, pr := range p.WorkflowRun.PullRequests {
+ add(pr.Number)
+ }
+ headSHA = firstNonEmpty(p.SHA, p.CheckSuite.HeadSHA, p.CheckRun.HeadSHA, p.CheckRun.CheckSuite.HeadSHA, p.WorkflowRun.HeadSHA)
+ return p.Installation.ID, p.Repository.Owner.Login, p.Repository.Name, numbers, headSHA, true
+}
+
+func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte) {
+ if !h.PRRefresh.Enabled() {
return
}
- // No PR number in the payload (status event, or a check event whose
- // pull_requests array was empty) — resolve by head SHA.
- sha := p.SHA
- if sha == "" {
- sha = coalesce(p.CheckSuite.HeadSHA, p.CheckRun.CheckSuite.HeadSHA)
+ installationID, owner, repo, numbers, sha, ok := parseCIEventTargets(body)
+ if !ok {
+ return
+ }
+ if len(numbers) > 0 {
+ for _, number := range numbers {
+ h.PRRefresh.Enqueue(installationID, owner, repo, number)
+ }
+ return
}
+ // No PR number in the payload (status event, or a check/workflow event whose
+ // pull_requests array was empty) — resolve by head SHA.
if sha == "" {
return
}
- numbers, err := h.Queries.ListGitHubPRNumbersByHeadSHA(ctx, db.ListGitHubPRNumbersByHeadSHAParams{
- InstallationID: p.Installation.ID,
+ resolved, err := h.Queries.ListGitHubPRNumbersByHeadSHA(ctx, db.ListGitHubPRNumbersByHeadSHAParams{
+ InstallationID: installationID,
RepoOwner: owner,
RepoName: repo,
HeadSha: sha,
@@ -1747,9 +1765,18 @@ func (h *Handler) triggerPRRefreshFromCIEvent(ctx context.Context, body []byte)
if err != nil {
return
}
- for _, number := range numbers {
- enqueue(number)
+ for _, number := range resolved {
+ h.PRRefresh.Enqueue(installationID, owner, repo, number)
+ }
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, v := range values {
+ if trimmed := strings.TrimSpace(v); trimmed != "" {
+ return trimmed
+ }
}
+ return ""
}
// mirrorPullRequestForWorkspace mirrors a pull_request webhook into a single
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index df9ed9d780..62b073ff80 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -3620,3 +3620,67 @@ func TestWebhook_UninstallDeletesAllBindings(t *testing.T) {
t.Errorf("deleted broadcasts must cover both workspaces; saw %v", seen)
}
}
+
+func TestParseCIEventTargets(t *testing.T) {
+ base := `"installation":{"id":42},"repository":{"name":"multica","owner":{"login":"multica-ai"}}`
+ for _, tc := range []struct {
+ name string
+ body string
+ wantNumbers []int32
+ wantSHA string
+ wantOK bool
+ }{
+ {
+ name: "check_run with head_sha and empty pull_requests",
+ body: `{` + base + `,"check_run":{"head_sha":"abc123","pull_requests":[]}}`,
+ wantSHA: "abc123",
+ wantOK: true,
+ },
+ {
+ name: "check_run falls back to check_suite head_sha",
+ body: `{` + base + `,"check_run":{"pull_requests":[],"check_suite":{"head_sha":"suite456"}}}`,
+ wantSHA: "suite456",
+ wantOK: true,
+ },
+ {
+ name: "workflow_run with pull_requests",
+ body: `{` + base + `,"workflow_run":{"head_sha":"wf789","pull_requests":[{"number":11563},{"number":11563}]}}`,
+ wantNumbers: []int32{11563},
+ wantSHA: "wf789",
+ wantOK: true,
+ },
+ {
+ name: "workflow_run with empty pull_requests falls back to head_sha",
+ body: `{` + base + `,"workflow_run":{"head_sha":"wf999","pull_requests":[]}}`,
+ wantSHA: "wf999",
+ wantOK: true,
+ },
+ {
+ name: "status event uses top-level sha",
+ body: `{` + base + `,"sha":"status111"}`,
+ wantSHA: "status111",
+ wantOK: true,
+ },
+ {
+ name: "missing installation is ignored",
+ body: `{"repository":{"name":"multica","owner":{"login":"multica-ai"}},"sha":"abc"}`,
+ wantOK: false,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ instID, owner, repo, numbers, sha, ok := parseCIEventTargets([]byte(tc.body))
+ if ok != tc.wantOK {
+ t.Fatalf("ok=%t, want %t", ok, tc.wantOK)
+ }
+ if !ok {
+ return
+ }
+ if instID != 42 || owner != "multica-ai" || repo != "multica" {
+ t.Fatalf("target=(%d,%s/%s), want (42,multica-ai/multica)", instID, owner, repo)
+ }
+ if !reflect.DeepEqual(numbers, tc.wantNumbers) || sha != tc.wantSHA {
+ t.Fatalf("numbers=%v sha=%q, want numbers=%v sha=%q", numbers, sha, tc.wantNumbers, tc.wantSHA)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/issue_wakeup.go b/server/internal/handler/issue_wakeup.go
index 50ebe06d32..5ce17579de 100644
--- a/server/internal/handler/issue_wakeup.go
+++ b/server/internal/handler/issue_wakeup.go
@@ -1,6 +1,7 @@
package handler
import (
+ "context"
"encoding/json"
"errors"
"net/http"
@@ -239,6 +240,7 @@ func (h *Handler) CreateIssueWakeup(w http.ResponseWriter, r *http.Request) {
wakeupError(w, err)
return
}
+ h.maybeRefreshPRsForIssueWakeup(r.Context(), issue.ID, result.Condition)
status := http.StatusCreated
if existingID.Valid {
status = http.StatusOK
@@ -307,9 +309,42 @@ func (h *Handler) EnableIssueWakeup(w http.ResponseWriter, r *http.Request) {
wakeupError(w, err)
return
}
+ h.maybeRefreshPRsForIssueWakeup(r.Context(), issue.ID, result.Condition)
writeJSON(w, 200, result)
}
+// maybeRefreshPRsForIssueWakeup kicks off a non-blocking snapshot refresh for
+// open/draft GitHub PRs linked to issue when a checks/conflicts wakeup is
+// created or re-enabled and the PR's snapshot is missing or stale.
+func (h *Handler) maybeRefreshPRsForIssueWakeup(ctx context.Context, issueID pgtype.UUID, rawCondition []byte) {
+ if !h.PRRefresh.Enabled() || len(rawCondition) == 0 {
+ return
+ }
+ var cond service.WakeupCondition
+ if json.Unmarshal(rawCondition, &cond) != nil || cond.Type != "pull_request" {
+ return
+ }
+ if cond.Event != "checks_finished" && cond.Event != "conflicts" {
+ return
+ }
+ rows, err := h.Queries.ListPullRequestsByIssue(ctx, issueID)
+ if err != nil {
+ return
+ }
+ for _, row := range rows {
+ if row.State != "open" && row.State != "draft" {
+ continue
+ }
+ h.PRRefresh.MaybeEnqueueOnView(
+ row.InstallationID, row.RepoOwner, row.RepoName, row.PrNumber,
+ row.SnapshotFetchedAt.Time,
+ row.SnapshotFetchedAt.Valid &&
+ row.SnapshotHeadSha != "" &&
+ row.SnapshotHeadSha == row.HeadSha,
+ )
+ }
+}
+
func (h *Handler) EditIssueWakeupInstruction(w http.ResponseWriter, r *http.Request) {
issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "id"))
if !ok {
diff --git a/server/internal/integrations/ghsnapshot/refresh.go b/server/internal/integrations/ghsnapshot/refresh.go
index ea2f28eed2..a19f55f631 100644
--- a/server/internal/integrations/ghsnapshot/refresh.go
+++ b/server/internal/integrations/ghsnapshot/refresh.go
@@ -43,6 +43,11 @@ var (
// PRs watched by a "wake on merge conflict" rule stay in the sweep even
// when decided, re-fetched once their snapshot is older than this.
defaultWatchTTL = 5 * time.Minute
+ // PRs watched by an active "wake on checks finished" rule (issue or chat)
+ // use a tighter TTL and sweep cadence so missed webhooks or rate-limit
+ // pauses never stall --until-pr checks for tens of minutes.
+ defaultChecksWatchTTL = 2 * time.Minute
+ defaultWatchInterval = time.Minute
// After a merge into a repository, GitHub recomputes the other PRs'
// mergeability asynchronously and may still answer with the old verdict
// at first, so watched PRs are fetched after each of these delays.
@@ -63,16 +68,18 @@ type Manager struct {
pool TxBeginner
onApplied func(ctx context.Context, prID pgtype.UUID)
- concurrency int
- viewTTL time.Duration
- sweepTTL time.Duration
- sweepInterval time.Duration
- sweepMaxRows int32
- watchTTL time.Duration
- mergeDelays []time.Duration
- chaseBackoff []time.Duration
- now func() time.Time
- jitter func() time.Duration
+ concurrency int
+ viewTTL time.Duration
+ sweepTTL time.Duration
+ sweepInterval time.Duration
+ sweepMaxRows int32
+ watchTTL time.Duration
+ checksWatchTTL time.Duration
+ watchInterval time.Duration
+ mergeDelays []time.Duration
+ chaseBackoff []time.Duration
+ now func() time.Time
+ jitter func() time.Duration
// fetch is the snapshot fetcher, a seam so tests can drive the queue /
// backoff without a live GitHub. Defaults to FetchPRSnapshot.
fetch func(ctx context.Context, c *Client, installationID int64, owner, repo string, number int32) (*PRSnapshot, error)
@@ -88,8 +95,9 @@ type Manager struct {
// this cursor and wraps, preventing a fixed first page from starving later
// installations when early addresses repeatedly fail.
sweepAfter address
- // The same rotation for the conflict-watch sweep.
- watchAfter address
+ // The same rotation for the conflict-watch and checks-watch sweeps.
+ watchAfter address
+ checksWatchAfter address
// Secondary rate limits are scoped to the installation whose token incurred
// them. One customer must never pause every other installation.
rateUntil map[int64]time.Time
@@ -103,28 +111,30 @@ type Manager struct {
// realtime PR update. Passing a nil client yields a disabled (no-op) manager.
func NewManager(client *Client, queries *db.Queries, pool TxBeginner, onApplied func(ctx context.Context, prID pgtype.UUID)) *Manager {
return &Manager{
- client: client,
- queries: queries,
- readSelector: dbreader.NewPrimaryOnly(queries),
- pool: pool,
- onApplied: onApplied,
- concurrency: defaultConcurrency,
- viewTTL: defaultViewTTL,
- sweepTTL: defaultSweepTTL,
- sweepInterval: defaultSweepInterval,
- sweepMaxRows: defaultSweepMaxRows,
- watchTTL: defaultWatchTTL,
- mergeDelays: defaultMergeWatchDelays,
- chaseBackoff: defaultChaseBackoff,
- now: time.Now,
- jitter: func() time.Duration { return time.Duration(rand.Int63n(int64(250 * time.Millisecond))) },
- fetch: FetchPRSnapshot,
- queue: make(chan address, queueBuffer),
- active: map[address]bool{},
- inFlight: map[address]bool{},
- trailing: map[address]bool{},
- attempts: map[address]int{},
- rateUntil: map[int64]time.Time{},
+ client: client,
+ queries: queries,
+ readSelector: dbreader.NewPrimaryOnly(queries),
+ pool: pool,
+ onApplied: onApplied,
+ concurrency: defaultConcurrency,
+ viewTTL: defaultViewTTL,
+ sweepTTL: defaultSweepTTL,
+ sweepInterval: defaultSweepInterval,
+ sweepMaxRows: defaultSweepMaxRows,
+ watchTTL: defaultWatchTTL,
+ checksWatchTTL: defaultChecksWatchTTL,
+ watchInterval: defaultWatchInterval,
+ mergeDelays: defaultMergeWatchDelays,
+ chaseBackoff: defaultChaseBackoff,
+ now: time.Now,
+ jitter: func() time.Duration { return time.Duration(rand.Int63n(int64(250 * time.Millisecond))) },
+ fetch: FetchPRSnapshot,
+ queue: make(chan address, queueBuffer),
+ active: map[address]bool{},
+ inFlight: map[address]bool{},
+ trailing: map[address]bool{},
+ attempts: map[address]int{},
+ rateUntil: map[int64]time.Time{},
}
}
@@ -159,6 +169,9 @@ func (m *Manager) Start(ctx context.Context) {
go m.worker(ctx)
}
go m.sweepLoop(ctx)
+ if m.watchInterval > 0 {
+ go m.watchSweepLoop(ctx)
+ }
}
// Enqueue schedules a refresh for a PR address. Repeated events coalesce, but
@@ -272,6 +285,7 @@ func (m *Manager) process(ctx context.Context, addr address) {
anyApplied := false
anyOpenApplied := false
+ anyOpenUnapplied := false
for _, row := range rows {
applied, err := m.applySnapshot(ctx, row.ID, snap)
if err != nil {
@@ -279,6 +293,9 @@ func (m *Manager) process(ctx context.Context, addr address) {
continue
}
if !applied {
+ if row.State == "open" || row.State == "draft" {
+ anyOpenUnapplied = true
+ }
continue
}
anyApplied = true
@@ -290,14 +307,14 @@ func (m *Manager) process(ctx context.Context, addr address) {
}
}
- // Chase only while the snapshot is undecided AND a write proved that an
- // open PR row still exists on this head. If the head advanced, its webhook
- // owns the next refresh; if the row was removed, nothing remains to refresh.
- // Replica lag can instead make rows empty; that omission is recovered by the
- // bounded TTL sweep for an open/draft PR or by a later page-view refresh, so
- // it must not start a chase without having observed current row state. A
- // logged write failure is likewise left to those later triggers.
- if anyApplied && anyOpenApplied && !snap.Decided() {
+ // Chase while the snapshot is undecided AND a write proved an open PR row
+ // still exists on this head. Also chase (bounded) when an open/draft PR row
+ // rejected the write due to a head-SHA mismatch and no trailing webhook
+ // refresh is already queued: right after pull_request.synchronize, GitHub's
+ // REST API can transiently return the previous head SHA, so without a chase
+ // the PR would wait for the next sweep. If the row was deleted or closed,
+ // the next fetch observes empty/closed rows and stops immediately.
+ if (anyApplied && anyOpenApplied && !snap.Decided()) || (!anyApplied && anyOpenUnapplied && !m.hasTrailing(addr)) {
m.scheduleChase(addr)
} else {
m.mu.Lock()
@@ -491,6 +508,12 @@ func (m *Manager) scheduleRetry(addr address, delay time.Duration) {
})
}
+func (m *Manager) hasTrailing(addr address) bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.trailing[addr]
+}
+
func (m *Manager) sweepLoop(ctx context.Context) {
ticker := time.NewTicker(m.sweepInterval)
defer ticker.Stop()
@@ -499,21 +522,46 @@ func (m *Manager) sweepLoop(ctx context.Context) {
case <-ctx.Done():
return
case <-ticker.C:
- m.sweepOnce(ctx)
+ m.sweepUndecided(ctx)
+ }
+ }
+}
+
+// watchSweepLoop runs on a tighter cadence than the platform-wide undecided
+// sweep so PRs watched by active wakeup rules (--until-pr checks / conflicts)
+// recover within minutes rather than waiting for the 10-minute general sweep.
+func (m *Manager) watchSweepLoop(ctx context.Context) {
+ ticker := time.NewTicker(m.watchInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ m.sweepWatchedOnce(ctx)
}
}
}
func (m *Manager) sweepOnce(ctx context.Context) {
m.sweepUndecided(ctx)
+ m.sweepWatchedOnce(ctx)
+}
+
+func (m *Manager) sweepWatchedOnce(ctx context.Context) {
m.sweepConflictWatched(ctx)
+ m.sweepChecksWatched(ctx)
}
-// sweepUndecided enqueues a refresh for every open PR whose snapshot is both
-// stale and undecided. Bounded by sweepMaxRows. This is the safety net for an
-// undecided PR whose base branch changes without a pull_request webhook, and
-// for any webhook that was dropped during a deploy.
+// sweepUndecided enqueues a refresh for every open PR whose snapshot is
+// missing for the current head or both stale and undecided. Bounded by
+// sweepMaxRows. This is the safety net for an undecided PR whose base branch
+// changes without a pull_request webhook, and for any webhook or refresh that
+// was dropped during a rate limit or deploy.
func (m *Manager) sweepUndecided(ctx context.Context) {
+ if m.queries == nil {
+ return
+ }
m.mu.Lock()
after := m.sweepAfter
m.mu.Unlock()
@@ -550,6 +598,9 @@ func (m *Manager) sweepUndecided(ctx context.Context) {
// fresh. A decided snapshot leaves the undecided sweep, yet a direct push to
// the base branch can make it conflicting with no event for the PR itself.
func (m *Manager) sweepConflictWatched(ctx context.Context) {
+ if m.queries == nil {
+ return
+ }
m.mu.Lock()
after := m.watchAfter
m.mu.Unlock()
@@ -577,6 +628,40 @@ func (m *Manager) sweepConflictWatched(ctx context.Context) {
}
}
+// sweepChecksWatched keeps the PRs watched by an active "checks finished"
+// wakeup (issue or chat) fresh on a tighter TTL, covering missed CI webhooks,
+// rate-limit pauses, zero-check initial snapshots, and same-head re-runs.
+func (m *Manager) sweepChecksWatched(ctx context.Context) {
+ if m.queries == nil {
+ return
+ }
+ m.mu.Lock()
+ after := m.checksWatchAfter
+ m.mu.Unlock()
+
+ rows, err := m.queries.ListStaleChecksWatchedGitHubPRs(ctx, db.ListStaleChecksWatchedGitHubPRsParams{
+ OlderThan: tsFromTime(m.now().Add(-m.checksWatchTTL)),
+ AfterInstallationID: after.InstallationID,
+ AfterRepoOwner: after.Owner,
+ AfterRepoName: after.Repo,
+ AfterPrNumber: after.Number,
+ MaxRows: m.sweepMaxRows,
+ })
+ if err != nil {
+ slog.Warn("ghsnapshot: checks-watch sweep query failed", "err", err.Error())
+ return
+ }
+ if len(rows) > 0 {
+ last := rows[len(rows)-1]
+ m.mu.Lock()
+ m.checksWatchAfter = address{InstallationID: last.InstallationID, Owner: last.RepoOwner, Repo: last.RepoName, Number: last.PrNumber}
+ m.mu.Unlock()
+ }
+ for _, r := range rows {
+ m.Enqueue(r.InstallationID, r.RepoOwner, r.RepoName, r.PrNumber)
+ }
+}
+
// RefreshConflictWatchers schedules refreshes for the open PRs in a repository
// that a "wake on merge conflict" rule watches, after the PR numbered merged
// merged there. That can move their base, which sends no event for them.
diff --git a/server/internal/integrations/ghsnapshot/refresh_db_test.go b/server/internal/integrations/ghsnapshot/refresh_db_test.go
index 4a1fc4cd8f..d5f9df75e2 100644
--- a/server/internal/integrations/ghsnapshot/refresh_db_test.go
+++ b/server/internal/integrations/ghsnapshot/refresh_db_test.go
@@ -388,8 +388,260 @@ func TestConflictWatchedGitHubPRQueries(t *testing.T) {
t.Fatalf("merge refreshed %v, want PRs 1 and 3 once each", got)
}
m.sweepOnce(ctx)
- if got := queued(); fmt.Sprint(got) != "[1 2]" && fmt.Sprint(got) != "[2 1]" {
- t.Fatalf("sweep refreshed %v, want stale watched PRs 1 and 2", got)
+ got := queued()
+ wantSwept := map[int32]bool{1: true, 2: true, 4: true}
+ if len(got) != len(wantSwept) {
+ t.Fatalf("sweep refreshed %v, want stale watched PRs 1, 2 (conflicts) and 4 (checks)", got)
+ }
+ for _, n := range got {
+ if !wantSwept[n] {
+ t.Fatalf("sweep refreshed unexpected PR %d in %v", n, got)
+ }
+ }
+}
+
+func TestListStaleUndecidedGitHubPRsIncludesHeadMismatch(t *testing.T) {
+ pool := testDBPool(t)
+ q := db.New(pool)
+ ctx := context.Background()
+ now := time.Unix(1_700_020_000, 0)
+ const installationID int64 = 7_313_000_003
+ repo := "head-mismatch-" + randHex(t)
+
+ // Open PR whose previous head had a settled snapshot fetched 30s ago, then
+ // pull_request.synchronize advanced head_sha to a new commit.
+ advanced := seedPRAt(t, pool, q, installationID, repo, 1, "new-head")
+ settled := seedPRAt(t, pool, q, installationID, repo, 2, "same-head")
+ closed := seedPRAt(t, pool, q, installationID, repo, 3, "new-closed")
+ prs := []db.GithubPullRequest{advanced, settled, closed}
+ t.Cleanup(func() {
+ for _, pr := range prs {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request_check_run WHERE pr_id=$1`, pr.ID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id=$1`, pr.ID)
+ }
+ })
+
+ for _, tc := range []struct {
+ pr db.GithubPullRequest
+ state string
+ snapshotHead string
+ fetchedAt time.Time
+ }{
+ {advanced, "open", "old-head", now.Add(-30 * time.Second)},
+ {settled, "open", "same-head", now.Add(-time.Hour)},
+ {closed, "closed", "old-head", now.Add(-time.Hour)},
+ } {
+ if _, err := pool.Exec(ctx, `
+ UPDATE github_pull_request
+ SET state=$2, snapshot_head_sha=$3, snapshot_fetched_at=$4,
+ api_mergeable='MERGEABLE', checks_rollup_state='FAILURE'
+ WHERE id=$1`,
+ tc.pr.ID, tc.state, tc.snapshotHead, tc.fetchedAt); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ rows, err := q.ListStaleUndecidedGitHubPRs(ctx, db.ListStaleUndecidedGitHubPRsParams{
+ OlderThan: tsFromTime(now.Add(-10 * time.Minute)),
+ MaxRows: 1000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []int32
+ for _, r := range rows {
+ if r.InstallationID == installationID && r.RepoName == repo {
+ got = append(got, r.PrNumber)
+ }
+ }
+ if fmt.Sprint(got) != "[1]" {
+ t.Fatalf("stale undecided sweep = %v, want [1] (head_sha != snapshot_head_sha)", got)
+ }
+
+ // Once the snapshot catches up to head_sha with a decided verdict, it leaves the sweep.
+ if _, err := pool.Exec(ctx, `
+ UPDATE github_pull_request
+ SET snapshot_head_sha=head_sha, snapshot_fetched_at=$2,
+ api_mergeable='MERGEABLE', checks_rollup_state='SUCCESS'
+ WHERE id=$1`, advanced.ID, now); err != nil {
+ t.Fatal(err)
+ }
+ rows, err = q.ListStaleUndecidedGitHubPRs(ctx, db.ListStaleUndecidedGitHubPRsParams{
+ OlderThan: tsFromTime(now.Add(-10 * time.Minute)),
+ MaxRows: 1000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, r := range rows {
+ if r.InstallationID == installationID && r.RepoName == repo {
+ t.Fatalf("caught-up decided PR remained in sweep: %+v", r)
+ }
+ }
+}
+
+func watchPRInChat(t *testing.T, pool *pgxpool.Pool, pr db.GithubPullRequest, repoOverride, event, status string) {
+ t.Helper()
+ ctx := context.Background()
+ repo := pr.RepoOwner + "/" + pr.RepoName
+ if repoOverride != "" {
+ repo = repoOverride
+ }
+ var id pgtype.UUID
+ if err := pool.QueryRow(ctx, `INSERT INTO chat_wakeup(
+ id, workspace_id, chat_session_id, agent_id, requester_id,
+ title, instruction, kind, condition, next_eval_at, expires_at, status
+ ) VALUES (
+ gen_random_uuid(), $1, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(),
+ 'watch checks', 'go', 'condition',
+ jsonb_build_object('type','pull_request','repo',$2::text,'number',$3::int,'event',$4::text),
+ now(), now() + interval '1 hour', $5
+ ) RETURNING id`, pr.WorkspaceID, repo, pr.PrNumber, event, status).Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_wakeup WHERE id=$1`, id)
+ })
+}
+
+func TestChecksWatchedGitHubPRQueriesAndRotation(t *testing.T) {
+ pool := testDBPool(t)
+ q := db.New(pool)
+ ctx := context.Background()
+ now := time.Now()
+ const installationID int64 = 7_313_000_004
+ repo := "checks-watch-" + randHex(t)
+
+ seed := func(number int32, state, head, snapshotHead string, fetchedAt time.Time) db.GithubPullRequest {
+ t.Helper()
+ pr := seedPRAt(t, pool, q, installationID, repo, number, head)
+ if _, err := pool.Exec(ctx, `UPDATE github_pull_request
+ SET state=$2, snapshot_head_sha=$3, snapshot_fetched_at=$4,
+ api_mergeable='MERGEABLE', checks_rollup_state='FAILURE'
+ WHERE id=$1`, pr.ID, state, snapshotHead, fetchedAt); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id=$1`, pr.ID) })
+ return pr
+ }
+
+ stale := now.Add(-5 * time.Minute)
+ openIssue := seed(1, "open", "h1", "h1", stale)
+ watchPR(t, pool, openIssue, "checks_finished", true)
+ draftIssue := seed(2, "draft", "h2", "h2", stale)
+ watchPR(t, pool, draftIssue, "checks_finished", true)
+ freshSameHead := seed(3, "open", "h3", "h3", now)
+ watchPR(t, pool, freshSameHead, "checks_finished", true)
+ freshMismatchedHead := seed(4, "open", "h4-new", "h4-old", now)
+ watchPR(t, pool, freshMismatchedHead, "checks_finished", true)
+ activeChat := seed(5, "open", "h5", "h5", stale)
+ watchPRInChat(t, pool, activeChat, "O/"+repo, "checks_finished", "active")
+ endedChat := seed(6, "open", "h6", "h6", stale)
+ watchPRInChat(t, pool, endedChat, "", "checks_finished", "fired")
+ disabledIssue := seed(7, "open", "h7", "h7", stale)
+ watchPR(t, pool, disabledIssue, "checks_finished", false)
+ conflictsOnly := seed(8, "open", "h8", "h8", stale)
+ watchPR(t, pool, conflictsOnly, "conflicts", true)
+ closedWatched := seed(9, "closed", "h9", "h9", stale)
+ watchPR(t, pool, closedWatched, "checks_finished", true)
+
+ rows, err := q.ListStaleChecksWatchedGitHubPRs(ctx, db.ListStaleChecksWatchedGitHubPRsParams{
+ OlderThan: tsFromTime(now.Add(-2 * time.Minute)),
+ MaxRows: 1000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := map[int32]bool{}
+ for _, r := range rows {
+ if r.InstallationID == installationID && r.RepoName == repo {
+ got[r.PrNumber] = true
+ }
+ }
+ want := map[int32]bool{1: true, 2: true, 4: true, 5: true}
+ if len(got) != len(want) {
+ t.Fatalf("checks-watched sweep = %v, want %v", got, want)
+ }
+ for n := range want {
+ if !got[n] {
+ t.Fatalf("checks-watched sweep missing PR %d: got %v", n, got)
+ }
+ }
+
+ // Cursor rotation: even when fetches never succeed, bounded sweeps still
+ // visit every watched address instead of pinning the first page.
+ m := NewManager(enabledClient(t), q, pool, nil)
+ m.sweepMaxRows = 1
+ seen := map[int32]bool{}
+ for sweep := 0; sweep < 50 && !(seen[1] && seen[2] && seen[4] && seen[5]); sweep++ {
+ m.sweepChecksWatched(ctx)
+ for len(m.queue) > 0 {
+ addr := <-m.queue
+ if addr.InstallationID == installationID && addr.Repo == repo {
+ seen[addr.Number] = true
+ }
+ m.mu.Lock()
+ delete(m.active, addr)
+ m.mu.Unlock()
+ }
+ }
+ for n := range want {
+ if !seen[n] {
+ t.Fatalf("bounded checks-watch sweeps visited %v, missing PR %d", seen, n)
+ }
+ }
+}
+
+// TestProcessHeadMismatchSchedulesBoundedChase covers the synchronize race
+// where GitHub's REST API transiently returns the previous head SHA after the
+// webhook already updated head_sha in DB (so no trailing edge exists).
+func TestProcessHeadMismatchSchedulesBoundedChase(t *testing.T) {
+ pool := testDBPool(t)
+ q := db.New(pool)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ pr := seedPRAt(t, pool, q, 7_313_000_005, "mismatch-chase-"+randHex(t), 11, "B")
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request_check_run WHERE pr_id=$1`, pr.ID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id=$1`, pr.ID)
+ })
+
+ applied := make(chan struct{}, 1)
+ var calls atomic.Int32
+ m := NewManager(enabledClient(t), q, pool, func(context.Context, pgtype.UUID) {
+ select {
+ case applied <- struct{}{}:
+ default:
+ }
+ })
+ m.concurrency = 1
+ m.sweepInterval = time.Hour
+ m.watchInterval = time.Hour
+ m.chaseBackoff = []time.Duration{5 * time.Millisecond}
+ m.jitter = func() time.Duration { return 0 }
+ m.fetch = func(context.Context, *Client, int64, string, string, int32) (*PRSnapshot, error) {
+ if calls.Add(1) == 1 {
+ // GitHub API transiently lags behind the synchronize webhook.
+ return &PRSnapshot{HeadSHA: "A", Mergeable: "MERGEABLE", MergeStateStatus: "CLEAN", HasChecks: true, RollupState: "FAILURE"}, nil
+ }
+ return &PRSnapshot{HeadSHA: "B", Mergeable: "MERGEABLE", MergeStateStatus: "CLEAN", HasChecks: true, RollupState: "SUCCESS"}, nil
+ }
+
+ m.Start(ctx)
+ m.Enqueue(pr.InstallationID, pr.RepoOwner, pr.RepoName, pr.PrNumber)
+
+ select {
+ case <-applied:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("head-mismatch chase did not retry and apply new head (fetch calls=%d)", calls.Load())
+ }
+ got, err := q.GetGitHubPullRequestByID(ctx, pr.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.SnapshotHeadSha != "B" || got.ChecksRollupState.String != "SUCCESS" {
+ t.Fatalf("snapshot after head-mismatch chase = %+v, want head B / SUCCESS", got)
}
}
diff --git a/server/internal/service/issue_wakeup_condition.go b/server/internal/service/issue_wakeup_condition.go
index 4f5b31bf8d..8d43ecfe99 100644
--- a/server/internal/service/issue_wakeup_condition.go
+++ b/server/internal/service/issue_wakeup_condition.go
@@ -296,8 +296,12 @@ func (s *IssueWakeupService) evaluateCondition(ctx context.Context, tx pgx.Tx, q
if !githubChecks {
continue
}
- missingSnapshot = missingSnapshot || head == ""
- if head != "" && slices.Contains([]string{"SUCCESS", "FAILURE", "ERROR"}, checks) {
+ // A snapshot from an older head says nothing about the pushed one.
+ if head == "" || (currentHead != "" && head != currentHead) {
+ missingSnapshot = true
+ continue
+ }
+ if slices.Contains([]string{"SUCCESS", "FAILURE", "ERROR"}, checks) {
keys = append(keys, fmt.Sprintf("%d@%s:%s", number, head, checks))
prs = append(prs, map[string]any{"number": number, "head_sha": head, "checks": strings.ToLower(checks)})
}
diff --git a/server/internal/service/issue_wakeup_condition_pr_test.go b/server/internal/service/issue_wakeup_condition_pr_test.go
index 88f860d699..13c833c79a 100644
--- a/server/internal/service/issue_wakeup_condition_pr_test.go
+++ b/server/internal/service/issue_wakeup_condition_pr_test.go
@@ -100,6 +100,8 @@ func TestWakeupConditionPREvaluation(t *testing.T) {
{"unlinked", "checks_finished", true, nil, errPRNotLinked, false},
{"unlinked merged", "merged", false, nil, errPRNotLinked, false},
{"no snapshot", "checks_finished", true, [][]any{row("open", "", "SUCCESS")}, errPRSnapshotPending, false},
+ {"checks verdict for an older head", "checks_finished", true, [][]any{{int32(1), "open", "old", "FAILURE", "head", "MERGEABLE", "p1"}}, errPRSnapshotPending, false},
+ {"checks legacy row with empty head_sha", "checks_finished", true, [][]any{{int32(1), "open", "old", "SUCCESS", "", "MERGEABLE", "p1"}}, nil, true},
{"pending", "checks_finished", true, [][]any{row("open", "head", "PENDING")}, nil, false},
{"no checks", "checks_finished", true, [][]any{row("open", "head", "")}, nil, false},
{"success", "checks_finished", true, [][]any{row("open", "head", "SUCCESS")}, nil, true},
diff --git a/server/internal/service/issue_wakeup_condition_test.go b/server/internal/service/issue_wakeup_condition_test.go
index 15e5c2e03a..4ccd60605c 100644
--- a/server/internal/service/issue_wakeup_condition_test.go
+++ b/server/internal/service/issue_wakeup_condition_test.go
@@ -467,6 +467,56 @@ func TestWakeupConditionPullRequestChecksWaitForNewResult(t *testing.T) {
}
}
+// When a push already advanced head_sha while snapshot_head_sha still holds
+// the old head's conclusion, checks_finished must report a pending snapshot
+// instead of baselining or firing on the outdated head.
+func TestWakeupConditionPullRequestChecksIgnoresStaleHeadSnapshot(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ s.Tasks.PRSnapshotsEnabled = true
+ ctx := context.Background()
+ pr := f.Insert(t, "github_pull_request", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "installation_id": 1,
+ "repo_owner": "fixture", "repo_name": "stale-head", "pr_number": 9,
+ "title": "PR", "state": "open", "html_url": "https://example.test/pr/9",
+ "pr_created_at": "2026-01-01T00:00:00Z", "pr_updated_at": "2026-01-01T00:00:00Z",
+ "head_sha": "new-sha", "snapshot_head_sha": "old-sha", "checks_rollup_state": "FAILURE",
+ })
+ f.Cleanup(t, "DELETE FROM issue_pull_request WHERE pull_request_id=$1", pr)
+ f.Exec(t, "INSERT INTO issue_pull_request(issue_id,pull_request_id) VALUES($1,$2)", issue, pr)
+
+ w := wakeCreate(t, f, s, issue, WakeupInput{AgentID: agent, Kind: "event", Instruction: "Check CI",
+ Condition: condition(t, map[string]any{"type": "pull_request", "event": "checks_finished"})})
+ if !w.LastError.Valid || w.LastError.String != conditionDiagnosticPrefix+errPRSnapshotPending.Error() {
+ t.Fatalf("expected pending snapshot diagnostic on stale head, got %+v", w.LastError)
+ }
+ if w.ConditionState != "" {
+ t.Fatalf("stale head must not populate condition_state, got %q", w.ConditionState)
+ }
+ if got := wakeTick(t, f, s, w.ID); wakeRuns(t, f, w.ID) != 0 || !got.LastError.Valid {
+ t.Fatalf("stale head must wait with diagnostic: runs=%d error=%+v", wakeRuns(t, f, w.ID), got.LastError)
+ }
+
+ // Snapshot catches up to new-sha while CI is still running → diagnostic clears.
+ f.Exec(t, "UPDATE github_pull_request SET snapshot_head_sha='new-sha', checks_rollup_state='PENDING' WHERE id=$1", pr)
+ if got := wakeTick(t, f, s, w.ID); wakeRuns(t, f, w.ID) != 0 || got.LastError.Valid {
+ t.Fatalf("pending checks on current head: runs=%d error=%+v", wakeRuns(t, f, w.ID), got.LastError)
+ }
+
+ // Checks finish on new-sha → fires once with current head evidence.
+ f.Exec(t, "UPDATE github_pull_request SET checks_rollup_state='SUCCESS' WHERE id=$1", pr)
+ got := wakeTick(t, f, s, w.ID)
+ if wakeRuns(t, f, w.ID) != 1 || got.Enabled || got.LastError.Valid {
+ t.Fatalf("finished checks on current head: runs=%d enabled=%t error=%+v", wakeRuns(t, f, w.ID), got.Enabled, got.LastError)
+ }
+ task, err := f.q.GetAgentTask(ctx, got.LastTaskID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(task.HandoffNote.String, `"head_sha":"new-sha"`) || !strings.Contains(task.HandoffNote.String, `"checks":"success"`) {
+ t.Fatalf("unexpected PR facts: %s", task.HandoffNote.String)
+ }
+}
+
func TestWakeupConditionValidation(t *testing.T) {
f, s, issue, agent := conditionFixture(t)
ctx := context.Background()
diff --git a/server/pkg/db/generated/github_snapshot.sql.go b/server/pkg/db/generated/github_snapshot.sql.go
index bfd9d118bd..a0bd26c5fc 100644
--- a/server/pkg/db/generated/github_snapshot.sql.go
+++ b/server/pkg/db/generated/github_snapshot.sql.go
@@ -22,6 +22,58 @@ func (q *Queries) DeleteGitHubPRCheckRuns(ctx context.Context, prID pgtype.UUID)
return err
}
+const getGitHubPRForRefresh = `-- name: GetGitHubPRForRefresh :one
+SELECT installation_id, repo_owner, repo_name, pr_number, state, head_sha, snapshot_head_sha, snapshot_fetched_at
+FROM github_pull_request
+WHERE workspace_id = $1
+ AND lower(repo_owner) = lower($3::text)
+ AND lower(repo_name) = lower($4::text)
+ AND pr_number = $2
+ORDER BY updated_at DESC
+LIMIT 1
+`
+
+type GetGitHubPRForRefreshParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PrNumber int32 `json:"pr_number"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+}
+
+type GetGitHubPRForRefreshRow struct {
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+ State string `json:"state"`
+ HeadSha string `json:"head_sha"`
+ SnapshotHeadSha string `json:"snapshot_head_sha"`
+ SnapshotFetchedAt pgtype.Timestamptz `json:"snapshot_fetched_at"`
+}
+
+// Looks up one mirrored PR by case-insensitive owner/repo and number so a
+// chat wakeup targeting a PR can kick off an immediate snapshot refresh.
+func (q *Queries) GetGitHubPRForRefresh(ctx context.Context, arg GetGitHubPRForRefreshParams) (GetGitHubPRForRefreshRow, error) {
+ row := q.db.QueryRow(ctx, getGitHubPRForRefresh,
+ arg.WorkspaceID,
+ arg.PrNumber,
+ arg.RepoOwner,
+ arg.RepoName,
+ )
+ var i GetGitHubPRForRefreshRow
+ err := row.Scan(
+ &i.InstallationID,
+ &i.RepoOwner,
+ &i.RepoName,
+ &i.PrNumber,
+ &i.State,
+ &i.HeadSha,
+ &i.SnapshotHeadSha,
+ &i.SnapshotFetchedAt,
+ )
+ return i, err
+}
+
const getGitHubPullRequestByID = `-- name: GetGitHubPullRequestByID :one
SELECT id, workspace_id, installation_id, repo_owner, repo_name, pr_number, title, state, html_url, branch, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, created_at, updated_at, head_sha, mergeable_state, additions, deletions, changed_files, api_mergeable, api_merge_state_status, checks_rollup_state, snapshot_head_sha, snapshot_fetched_at FROM github_pull_request WHERE id = $1
`
@@ -249,12 +301,126 @@ func (q *Queries) ListGitHubPRRowsByAddress(ctx context.Context, arg ListGitHubP
return items, nil
}
+const listStaleChecksWatchedGitHubPRs = `-- name: ListStaleChecksWatchedGitHubPRs :many
+WITH watched_issue_prs AS (
+ SELECT ipr.pull_request_id AS pr_id
+ FROM issue_wakeup AS w
+ JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+ WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'checks_finished'
+),
+watched_chat_prs AS (
+ SELECT pr.id AS pr_id
+ FROM chat_wakeup AS cw
+ JOIN github_pull_request AS pr
+ ON pr.workspace_id = cw.workspace_id
+ AND lower(pr.repo_owner) = lower(split_part(cw.condition->>'repo', '/', 1))
+ AND lower(pr.repo_name) = lower(split_part(cw.condition->>'repo', '/', 2))
+ AND pr.pr_number = CASE
+ WHEN COALESCE(cw.condition->>'number', '') ~ '^[0-9]{1,9}$' THEN (cw.condition->>'number')::INTEGER
+ END
+ WHERE cw.status = 'active'
+ AND cw.kind = 'condition'
+ AND cw.condition->>'type' = 'pull_request'
+ AND cw.condition->>'event' = 'checks_finished'
+),
+candidates AS (
+ SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+ FROM github_pull_request AS pr
+ WHERE pr.state IN ('open', 'draft')
+ AND (
+ pr.snapshot_fetched_at IS NULL
+ OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
+ OR pr.snapshot_fetched_at < $6
+ )
+ AND (
+ pr.id IN (SELECT pr_id FROM watched_issue_prs)
+ OR pr.id IN (SELECT pr_id FROM watched_chat_prs)
+ )
+ GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+)
+SELECT installation_id, repo_owner, repo_name, pr_number
+FROM candidates
+ORDER BY (
+ ROW(installation_id, repo_owner, repo_name, pr_number) >
+ ROW(
+ $1::BIGINT,
+ $2::TEXT,
+ $3::TEXT,
+ $4::INTEGER
+ )
+) DESC,
+installation_id, repo_owner, repo_name, pr_number
+LIMIT $5
+`
+
+type ListStaleChecksWatchedGitHubPRsParams struct {
+ AfterInstallationID int64 `json:"after_installation_id"`
+ AfterRepoOwner string `json:"after_repo_owner"`
+ AfterRepoName string `json:"after_repo_name"`
+ AfterPrNumber int32 `json:"after_pr_number"`
+ MaxRows int32 `json:"max_rows"`
+ OlderThan pgtype.Timestamptz `json:"older_than"`
+}
+
+type ListStaleChecksWatchedGitHubPRsRow struct {
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+}
+
+// Third sweep source: open/draft PRs watched by an enabled "checks finished"
+// wakeup (issue or chat). A PR can leave the undecided sweep while a checks
+// wakeup is still waiting (for example, an initial fetch right after
+// synchronize saw no checks yet, or jobs were re-run on the same head), or
+// webhook/chase refreshes may have been dropped during a rate limit or deploy.
+// Sweeping watched PRs on a shorter TTL keeps --until-pr checks responsive
+// without relying on a manual page visit. Rotates an address cursor like the
+// other sweeps.
+func (q *Queries) ListStaleChecksWatchedGitHubPRs(ctx context.Context, arg ListStaleChecksWatchedGitHubPRsParams) ([]ListStaleChecksWatchedGitHubPRsRow, error) {
+ rows, err := q.db.Query(ctx, listStaleChecksWatchedGitHubPRs,
+ arg.AfterInstallationID,
+ arg.AfterRepoOwner,
+ arg.AfterRepoName,
+ arg.AfterPrNumber,
+ arg.MaxRows,
+ arg.OlderThan,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListStaleChecksWatchedGitHubPRsRow{}
+ for rows.Next() {
+ var i ListStaleChecksWatchedGitHubPRsRow
+ if err := rows.Scan(
+ &i.InstallationID,
+ &i.RepoOwner,
+ &i.RepoName,
+ &i.PrNumber,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listStaleConflictWatchedGitHubPRs = `-- name: ListStaleConflictWatchedGitHubPRs :many
WITH candidates AS (
SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
FROM github_pull_request AS pr
WHERE pr.state IN ('open', 'draft')
- AND (pr.snapshot_fetched_at IS NULL OR pr.snapshot_fetched_at < $6)
+ AND (
+ pr.snapshot_fetched_at IS NULL
+ OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
+ OR pr.snapshot_fetched_at < $6
+ )
AND pr.id IN (
SELECT ipr.pull_request_id
FROM issue_wakeup AS w
@@ -340,9 +506,14 @@ WITH candidates AS (
SELECT installation_id, repo_owner, repo_name, pr_number
FROM github_pull_request AS pr
WHERE state IN ('open', 'draft')
- AND (snapshot_fetched_at IS NULL OR snapshot_fetched_at < $6)
AND (
snapshot_fetched_at IS NULL
+ OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
+ OR snapshot_fetched_at < $6
+ )
+ AND (
+ snapshot_fetched_at IS NULL
+ OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
OR api_mergeable IS NULL
OR api_mergeable = 'UNKNOWN'
OR checks_rollup_state IN ('PENDING', 'EXPECTED')
@@ -386,8 +557,10 @@ type ListStaleUndecidedGitHubPRsRow struct {
}
// TTL / safety-net sweep source. Returns distinct addresses of open/draft PRs
-// whose snapshot is both stale and undecided. A decided snapshot leaves the
-// periodic refresh set; later webhook or view activity can still refresh it.
+// whose snapshot is missing for the current head (never fetched or head_sha
+// advanced past snapshot_head_sha) or both stale and undecided. A decided
+// snapshot for the current head leaves the periodic refresh set; later webhook,
+// watched-wakeup, or view activity can still refresh it.
// The caller advances an address cursor after each bounded batch. Rows after
// the cursor sort first, followed by a wrap to the start, so even perpetually
// failing addresses cannot pin the same first LIMIT rows forever.
diff --git a/server/pkg/db/queries/github_snapshot.sql b/server/pkg/db/queries/github_snapshot.sql
index 94779e92a0..34c74e5903 100644
--- a/server/pkg/db/queries/github_snapshot.sql
+++ b/server/pkg/db/queries/github_snapshot.sql
@@ -45,8 +45,10 @@ INSERT INTO github_pull_request_check_run (
-- name: ListStaleUndecidedGitHubPRs :many
-- TTL / safety-net sweep source. Returns distinct addresses of open/draft PRs
--- whose snapshot is both stale and undecided. A decided snapshot leaves the
--- periodic refresh set; later webhook or view activity can still refresh it.
+-- whose snapshot is missing for the current head (never fetched or head_sha
+-- advanced past snapshot_head_sha) or both stale and undecided. A decided
+-- snapshot for the current head leaves the periodic refresh set; later webhook,
+-- watched-wakeup, or view activity can still refresh it.
-- The caller advances an address cursor after each bounded batch. Rows after
-- the cursor sort first, followed by a wrap to the start, so even perpetually
-- failing addresses cannot pin the same first LIMIT rows forever.
@@ -54,9 +56,14 @@ WITH candidates AS (
SELECT installation_id, repo_owner, repo_name, pr_number
FROM github_pull_request AS pr
WHERE state IN ('open', 'draft')
- AND (snapshot_fetched_at IS NULL OR snapshot_fetched_at < sqlc.arg('older_than'))
AND (
snapshot_fetched_at IS NULL
+ OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
+ OR snapshot_fetched_at < sqlc.arg('older_than')
+ )
+ AND (
+ snapshot_fetched_at IS NULL
+ OR (head_sha <> '' AND snapshot_head_sha <> head_sha)
OR api_mergeable IS NULL
OR api_mergeable = 'UNKNOWN'
OR checks_rollup_state IN ('PENDING', 'EXPECTED')
@@ -94,7 +101,11 @@ WITH candidates AS (
SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
FROM github_pull_request AS pr
WHERE pr.state IN ('open', 'draft')
- AND (pr.snapshot_fetched_at IS NULL OR pr.snapshot_fetched_at < sqlc.arg('older_than'))
+ AND (
+ pr.snapshot_fetched_at IS NULL
+ OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
+ OR pr.snapshot_fetched_at < sqlc.arg('older_than')
+ )
AND pr.id IN (
SELECT ipr.pull_request_id
FROM issue_wakeup AS w
@@ -119,6 +130,79 @@ ORDER BY (
installation_id, repo_owner, repo_name, pr_number
LIMIT sqlc.arg('max_rows');
+-- name: ListStaleChecksWatchedGitHubPRs :many
+-- Third sweep source: open/draft PRs watched by an enabled "checks finished"
+-- wakeup (issue or chat). A PR can leave the undecided sweep while a checks
+-- wakeup is still waiting (for example, an initial fetch right after
+-- synchronize saw no checks yet, or jobs were re-run on the same head), or
+-- webhook/chase refreshes may have been dropped during a rate limit or deploy.
+-- Sweeping watched PRs on a shorter TTL keeps --until-pr checks responsive
+-- without relying on a manual page visit. Rotates an address cursor like the
+-- other sweeps.
+WITH watched_issue_prs AS (
+ SELECT ipr.pull_request_id AS pr_id
+ FROM issue_wakeup AS w
+ JOIN issue_pull_request AS ipr ON ipr.issue_id = w.issue_id
+ WHERE w.enabled
+ AND w.condition->>'type' = 'pull_request'
+ AND w.condition->>'event' = 'checks_finished'
+),
+watched_chat_prs AS (
+ SELECT pr.id AS pr_id
+ FROM chat_wakeup AS cw
+ JOIN github_pull_request AS pr
+ ON pr.workspace_id = cw.workspace_id
+ AND lower(pr.repo_owner) = lower(split_part(cw.condition->>'repo', '/', 1))
+ AND lower(pr.repo_name) = lower(split_part(cw.condition->>'repo', '/', 2))
+ AND pr.pr_number = CASE
+ WHEN COALESCE(cw.condition->>'number', '') ~ '^[0-9]{1,9}$' THEN (cw.condition->>'number')::INTEGER
+ END
+ WHERE cw.status = 'active'
+ AND cw.kind = 'condition'
+ AND cw.condition->>'type' = 'pull_request'
+ AND cw.condition->>'event' = 'checks_finished'
+),
+candidates AS (
+ SELECT pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+ FROM github_pull_request AS pr
+ WHERE pr.state IN ('open', 'draft')
+ AND (
+ pr.snapshot_fetched_at IS NULL
+ OR (pr.head_sha <> '' AND pr.snapshot_head_sha <> pr.head_sha)
+ OR pr.snapshot_fetched_at < sqlc.arg('older_than')
+ )
+ AND (
+ pr.id IN (SELECT pr_id FROM watched_issue_prs)
+ OR pr.id IN (SELECT pr_id FROM watched_chat_prs)
+ )
+ GROUP BY pr.installation_id, pr.repo_owner, pr.repo_name, pr.pr_number
+)
+SELECT installation_id, repo_owner, repo_name, pr_number
+FROM candidates
+ORDER BY (
+ ROW(installation_id, repo_owner, repo_name, pr_number) >
+ ROW(
+ sqlc.arg('after_installation_id')::BIGINT,
+ sqlc.arg('after_repo_owner')::TEXT,
+ sqlc.arg('after_repo_name')::TEXT,
+ sqlc.arg('after_pr_number')::INTEGER
+ )
+) DESC,
+installation_id, repo_owner, repo_name, pr_number
+LIMIT sqlc.arg('max_rows');
+
+-- name: GetGitHubPRForRefresh :one
+-- Looks up one mirrored PR by case-insensitive owner/repo and number so a
+-- chat wakeup targeting a PR can kick off an immediate snapshot refresh.
+SELECT installation_id, repo_owner, repo_name, pr_number, state, head_sha, snapshot_head_sha, snapshot_fetched_at
+FROM github_pull_request
+WHERE workspace_id = $1
+ AND lower(repo_owner) = lower(sqlc.arg('repo_owner')::text)
+ AND lower(repo_name) = lower(sqlc.arg('repo_name')::text)
+ AND pr_number = $2
+ORDER BY updated_at DESC
+LIMIT 1;
+
-- name: ListConflictWatchedGitHubPRNumbersInRepo :many
-- Open/draft PRs in one repository that an enabled "wake on merge conflict"
-- rule watches. A merge into the repository can make them conflicting without