Skip to content

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

Go

fix(github): surface in-flight CI on PR cards (MUL-2392) (#2887)

Jiayuan Zhang41586f14997a
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index a835ed2424..cc24676983 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -849,6 +849,13 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {
return
}
+ // Drain any check_suite events that arrived before this PR row was
+ // mirrored (out-of-order webhook delivery). Each drained row is
+ // replayed through the same upsert path used by live check_suite
+ // events; the DrainPending… query removes them atomically so a
+ // concurrent PR upsert can't double-apply.
+ h.replayPendingCheckSuitesForPR(ctx, pr, inst.WorkspaceID)
+
workspaceID := uuidToString(inst.WorkspaceID)
resp := githubPullRequestToResponse(pr)
@@ -982,26 +989,23 @@ type ghCheckSuitePayload struct {
}
// handleCheckSuiteEvent records the CI suite state for each PR the suite
-// references. MVP only persists terminal events (`completed`); GitHub sends
-// `requested`/`rerequested` for some apps but those carry no useful
-// conclusion and the RFC restricts us to suite-level aggregation.
+// references. We persist all non-terminal actions (`requested`, `rerequested`)
+// as well as `completed`: a `requested`/`rerequested` event has status
+// `queued`/`in_progress` and an empty conclusion, which the aggregation query
+// counts as pending. Without persisting them, the per-PR `checks_pending`
+// count stays at 0 while CI is mid-run and the PR card falls through to
+// "checks not reported yet" until the first suite finishes.
//
// The suite payload may reference multiple PRs (e.g. the same head SHA is
// open against several base branches), so we iterate. A reference whose PR
-// hasn't been mirrored locally is logged and skipped — auto-backfill from
-// GitHub's REST API is a v2 enhancement.
+// hasn't been mirrored locally is stashed in `github_pending_check_suite`
+// and replayed when the matching `pull_request` event upserts the PR row.
func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
var p ghCheckSuitePayload
if err := json.Unmarshal(body, &p); err != nil {
slog.Warn("github: bad check_suite payload", "err", err)
return
}
- if p.Action != "completed" {
- // MVP scope: only completed suites carry a conclusion we can
- // surface. queued / in_progress events would feed a future
- // "real pending" display path.
- return
- }
if p.Installation.ID == 0 {
return
}
@@ -1040,12 +1044,28 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
if err != nil {
if !errors.Is(err, pgx.ErrNoRows) {
slog.Warn("github: lookup pr for check_suite failed", "err", err)
+ continue
+ }
+ // Out-of-order delivery: the suite reached us before the
+ // `pull_request` webhook that mirrors the PR row. Stash the
+ // event keyed by (workspace, repo, pr_number, suite_id); the
+ // PR upsert path will drain and replay it.
+ if err := h.Queries.UpsertPendingCheckSuite(ctx, db.UpsertPendingCheckSuiteParams{
+ WorkspaceID: inst.WorkspaceID,
+ InstallationID: p.Installation.ID,
+ RepoOwner: p.Repository.Owner.Login,
+ RepoName: p.Repository.Name,
+ PrNumber: prRef.Number,
+ SuiteID: p.CheckSuite.ID,
+ HeadSha: p.CheckSuite.HeadSHA,
+ AppID: p.CheckSuite.App.ID,
+ Conclusion: strToText(p.CheckSuite.Conclusion),
+ Status: p.CheckSuite.Status,
+ SuiteUpdatedAt: updatedAt,
+ }); err != nil {
+ slog.Warn("github: stash pending check_suite failed",
+ "err", err, "suite_id", p.CheckSuite.ID)
}
- slog.Info("github: check_suite for unknown PR — skipping",
- "repo", p.Repository.Owner.Login+"/"+p.Repository.Name,
- "pr", prRef.Number,
- "suite_id", p.CheckSuite.ID,
- )
continue
}
if err := h.Queries.UpsertPullRequestCheckSuite(ctx, db.UpsertPullRequestCheckSuiteParams{
@@ -1084,6 +1104,41 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
}
}
+// replayPendingCheckSuitesForPR drains the stash table for one PR (any
+// rows left there by a check_suite event that arrived before the PR row
+// was mirrored) and re-applies each event through the normal upsert
+// path. Safe to call on every PR upsert: the drain is a single
+// DELETE … RETURNING, so when there is nothing to replay the helper is
+// a no-op round-trip.
+func (h *Handler) replayPendingCheckSuitesForPR(ctx context.Context, pr db.GithubPullRequest, workspaceID pgtype.UUID) {
+ pending, err := h.Queries.DrainPendingCheckSuitesForPR(ctx, db.DrainPendingCheckSuitesForPRParams{
+ WorkspaceID: workspaceID,
+ RepoOwner: pr.RepoOwner,
+ RepoName: pr.RepoName,
+ PrNumber: pr.PrNumber,
+ })
+ if err != nil {
+ slog.Warn("github: drain pending check_suites failed",
+ "err", err, "pr_id", uuidToString(pr.ID))
+ return
+ }
+ for _, row := range pending {
+ if err := h.Queries.UpsertPullRequestCheckSuite(ctx, db.UpsertPullRequestCheckSuiteParams{
+ PrID: pr.ID,
+ SuiteID: row.SuiteID,
+ HeadSha: row.HeadSha,
+ AppID: row.AppID,
+ Conclusion: row.Conclusion,
+ Status: row.Status,
+ UpdatedAt: row.SuiteUpdatedAt,
+ }); err != nil {
+ slog.Warn("github: replay pending check_suite failed",
+ "err", err, "pr_id", uuidToString(pr.ID),
+ "suite_id", row.SuiteID)
+ }
+ }
+}
+
// derivePRMergeableState resolves the upsert behaviour for the PR row's
// mergeable_state column on a `pull_request` webhook. It returns three
// states encoded as (value, clear):
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index bdecdd5973..09288421d2 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -1360,17 +1360,27 @@ func firePullRequestWebhookWithHead(t *testing.T, secret, identifier string, ins
}
func fireCheckSuiteWebhook(t *testing.T, secret string, installationID int64, repo string, prNumbers []int32, suiteID, appID int64, headSHA, conclusion, updatedAt string) {
+ t.Helper()
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, repo, prNumbers,
+ suiteID, appID, headSHA, "completed", "completed", conclusion, updatedAt)
+}
+
+// fireCheckSuiteWebhookWithStatus is the parametric form of
+// fireCheckSuiteWebhook. Tests covering the `requested`/`rerequested` and
+// `queued`/`in_progress` matrix use it directly; the legacy completed-only
+// helper above wraps it for existing call sites.
+func fireCheckSuiteWebhookWithStatus(t *testing.T, secret string, installationID int64, repo string, prNumbers []int32, suiteID, appID int64, headSHA, action, status, conclusion, updatedAt string) {
t.Helper()
prRefs := make([]map[string]any, 0, len(prNumbers))
for _, n := range prNumbers {
prRefs = append(prRefs, map[string]any{"number": n})
}
payload := map[string]any{
- "action": "completed",
+ "action": action,
"check_suite": map[string]any{
"id": suiteID,
"head_sha": headSHA,
- "status": "completed",
+ "status": status,
"conclusion": conclusion,
"updated_at": updatedAt,
"app": map[string]any{"id": appID},
@@ -1415,6 +1425,7 @@ func setupPRTestIssue(t *testing.T, ctx context.Context, secret string) (IssueRe
installationID := int64(33445566) + int64(time.Now().UnixNano()%1000000)
t.Cleanup(func() {
testPool.Exec(ctx, `DELETE FROM github_pull_request_check_suite WHERE pr_id IN (SELECT id FROM github_pull_request WHERE workspace_id = $1)`, testWorkspaceID)
+ testPool.Exec(ctx, `DELETE FROM github_pending_check_suite WHERE workspace_id = $1`, testWorkspaceID)
testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)
testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)
testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
@@ -1538,6 +1549,153 @@ func TestWebhook_CheckSuite_LateOlderEventIgnored(t *testing.T) {
}
}
+// TestWebhook_CheckSuite_QueuedCountsAsPending covers the "CI 跑到一半" path:
+// GitHub fires `check_suite.requested` with status `queued` and an empty
+// conclusion while CI is still spinning up. The handler must persist these
+// non-terminal events so the per-PR `checks_pending` count reflects work in
+// progress; otherwise the frontend falls through to the "checks not
+// reported yet" placeholder until the first completed suite arrives.
+func TestWebhook_CheckSuite_QueuedCountsAsPending(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ const secret = "ci-pending-secret"
+ created, installationID := setupPRTestIssue(t, ctx, secret)
+
+ head := "pending1234567"
+ firePullRequestWebhookWithHead(t, secret, created.Identifier, installationID, "ci-repo-pending", 55, "opened", head, "")
+ // CI just kicked off — `requested` action, status=queued, no conclusion.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-pending", []int32{55}, 4001, 6001, head, "requested", "queued", "", "2026-05-01T00:00:00Z")
+ // A second app's suite starts a moment later with status=in_progress.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-pending", []int32{55}, 4002, 6002, head, "requested", "in_progress", "", "2026-05-01T00:00:30Z")
+
+ rows, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("expected 1 PR row, got %d", len(rows))
+ }
+ if rows[0].ChecksPending != 2 || rows[0].ChecksTotal != 2 ||
+ rows[0].ChecksFailed != 0 || rows[0].ChecksPassed != 0 {
+ t.Fatalf("expected pending=2 total=2 failed=0 passed=0, got pending=%d total=%d failed=%d passed=%d",
+ rows[0].ChecksPending, rows[0].ChecksTotal, rows[0].ChecksFailed, rows[0].ChecksPassed)
+ }
+ got := aggregateChecksConclusion(rows[0].ChecksFailed, rows[0].ChecksPassed, rows[0].ChecksPending, rows[0].ChecksTotal)
+ if got == nil || *got != "pending" {
+ t.Errorf("expected aggregate pending while CI is running, got %v", got)
+ }
+
+ // Now one app completes successfully — pending count drops to 1 and the
+ // aggregate stays pending until the second app finishes.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-pending", []int32{55}, 4001, 6001, head, "completed", "completed", "success", "2026-05-01T00:05:00Z")
+ rows, err = testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ }
+ if rows[0].ChecksPending != 1 || rows[0].ChecksPassed != 1 || rows[0].ChecksTotal != 2 {
+ t.Fatalf("expected pending=1 passed=1 total=2 after one suite completes, got pending=%d passed=%d total=%d",
+ rows[0].ChecksPending, rows[0].ChecksPassed, rows[0].ChecksTotal)
+ }
+}
+
+// TestWebhook_CheckSuite_OutOfOrderReplaysOnPRUpsert covers the out-of-order
+// path: a `check_suite` event arrives before the matching `pull_request`
+// row has been mirrored locally (e.g. webhook reordering, or the PR was
+// linked to an installation that was suspended/resumed). The handler must
+// stash the suite and replay it when the PR upsert arrives, otherwise the
+// PR's first observed suite is silently lost and `checks_pending` stays at
+// 0 until the next suite ships.
+func TestWebhook_CheckSuite_OutOfOrderReplaysOnPRUpsert(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ const secret = "ci-oooreplay-secret"
+ created, installationID := setupPRTestIssue(t, ctx, secret)
+
+ head := "oo01234567890"
+ // Suite event lands FIRST — the PR row does not exist yet.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-ooo", []int32{66}, 5001, 7501, head, "requested", "in_progress", "", "2026-05-01T00:00:00Z")
+
+ // Verify nothing landed on the PR table yet (no PR row to land on).
+ if rows, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID)); err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ } else if len(rows) != 0 {
+ t.Fatalf("expected 0 PR rows before PR webhook, got %d", len(rows))
+ }
+
+ // Now the pull_request webhook arrives. The handler must drain the
+ // pending stash and replay it onto this PR.
+ firePullRequestWebhookWithHead(t, secret, created.Identifier, installationID, "ci-repo-ooo", 66, "opened", head, "")
+
+ rows, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("expected 1 PR row after PR webhook, got %d", len(rows))
+ }
+ if rows[0].ChecksPending != 1 || rows[0].ChecksTotal != 1 {
+ t.Fatalf("expected pending=1 total=1 after replay, got pending=%d total=%d",
+ rows[0].ChecksPending, rows[0].ChecksTotal)
+ }
+
+ // The next PR upsert (a no-op metadata edit) must NOT re-apply or fail
+ // — the drain is one-shot, so the second pull_request webhook drains
+ // an empty pending list.
+ firePullRequestWebhookWithHead(t, secret, created.Identifier, installationID, "ci-repo-ooo", 66, "edited", head, "")
+ rows, err = testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ }
+ if rows[0].ChecksPending != 1 || rows[0].ChecksTotal != 1 {
+ t.Fatalf("expected pending=1 total=1 after no-op edit, got pending=%d total=%d",
+ rows[0].ChecksPending, rows[0].ChecksTotal)
+ }
+}
+
+// TestWebhook_CheckSuite_OutOfOrderStashKeepsNewer guards the pending
+// stash against the same out-of-order trap the live table already
+// handles: while the PR row is still missing, an older event for the
+// same suite_id must not overwrite a newer payload that was stashed
+// first. Without the suite_updated_at guard on UpsertPendingCheckSuite,
+// a late `requested/in_progress` arriving after `completed/success`
+// would roll the stash back to pending; the subsequent PR upsert would
+// then replay the stale state and the PR card would stay stuck on
+// "pending" until the next suite shipped.
+func TestWebhook_CheckSuite_OutOfOrderStashKeepsNewer(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ const secret = "ci-stash-order-secret"
+ created, installationID := setupPRTestIssue(t, ctx, secret)
+
+ head := "stash01234567"
+ // Newer event lands FIRST while the PR row does not exist yet.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-stash", []int32{77}, 6001, 8001, head, "completed", "completed", "success", "2026-05-01T00:05:00Z")
+ // Older event for the SAME suite arrives later (webhook reorder). The
+ // pending stash must keep the newer payload.
+ fireCheckSuiteWebhookWithStatus(t, secret, installationID, "ci-repo-stash", []int32{77}, 6001, 8001, head, "requested", "in_progress", "", "2026-05-01T00:00:00Z")
+
+ // PR webhook arrives — drain replays the (still newer) stash.
+ firePullRequestWebhookWithHead(t, secret, created.Identifier, installationID, "ci-repo-stash", 77, "opened", head, "")
+
+ rows, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("ListPullRequestsByIssue: %v", err)
+ }
+ if len(rows) != 1 {
+ t.Fatalf("expected 1 PR row after PR webhook, got %d", len(rows))
+ }
+ if rows[0].ChecksPassed != 1 || rows[0].ChecksPending != 0 || rows[0].ChecksTotal != 1 {
+ t.Fatalf("expected passed=1 pending=0 total=1 (newer stash preserved), got passed=%d pending=%d total=%d",
+ rows[0].ChecksPassed, rows[0].ChecksPending, rows[0].ChecksTotal)
+ }
+}
+
// TestWebhook_PullRequest_SynchronizeClearsMergeable verifies that
// `synchronize` sets mergeable_state to NULL even when the payload still
// carries the previous "clean" verdict — the old answer no longer applies
diff --git a/server/migrations/096_pending_check_suite.down.sql b/server/migrations/096_pending_check_suite.down.sql
new file mode 100644
index 0000000000..a7ec98ae2d
--- /dev/null
+++ b/server/migrations/096_pending_check_suite.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_github_pending_check_suite_received_at;
+DROP TABLE IF EXISTS github_pending_check_suite;
diff --git a/server/migrations/096_pending_check_suite.up.sql b/server/migrations/096_pending_check_suite.up.sql
new file mode 100644
index 0000000000..9220951ab9
--- /dev/null
+++ b/server/migrations/096_pending_check_suite.up.sql
@@ -0,0 +1,28 @@
+-- Stash for check_suite webhook events that arrive before the matching PR
+-- row has been mirrored (the `pull_request` and `check_suite` webhooks are
+-- delivered independently and GitHub does not guarantee order). When the
+-- corresponding `pull_request` event upserts the PR row, the handler drains
+-- this table for that (workspace, repo, pr_number) and replays each row
+-- through the normal check_suite upsert path, then deletes the pending row.
+--
+-- We key by (workspace_id, repo_owner, repo_name, pr_number, suite_id) so
+-- repeated deliveries of the same suite while the PR is still missing are
+-- idempotent — the newer payload simply overwrites the older.
+CREATE TABLE github_pending_check_suite (
+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ installation_id BIGINT NOT NULL,
+ repo_owner TEXT NOT NULL,
+ repo_name TEXT NOT NULL,
+ pr_number INTEGER NOT NULL,
+ suite_id BIGINT NOT NULL,
+ head_sha TEXT NOT NULL,
+ app_id BIGINT NOT NULL,
+ conclusion TEXT,
+ status TEXT NOT NULL,
+ suite_updated_at TIMESTAMPTZ NOT NULL,
+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (workspace_id, repo_owner, repo_name, pr_number, suite_id)
+);
+
+CREATE INDEX idx_github_pending_check_suite_received_at
+ ON github_pending_check_suite(received_at);
diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.go
index 4a74d7685d..19d134b569 100644
--- a/server/pkg/db/generated/github.sql.go
+++ b/server/pkg/db/generated/github.sql.go
@@ -100,6 +100,67 @@ func (q *Queries) DeletePendingGitHubInstallation(ctx context.Context, installat
return err
}
+const drainPendingCheckSuitesForPR = `-- name: DrainPendingCheckSuitesForPR :many
+DELETE FROM github_pending_check_suite
+WHERE workspace_id = $1
+ AND repo_owner = $2
+ AND repo_name = $3
+ AND pr_number = $4
+RETURNING suite_id, head_sha, app_id, conclusion, status, suite_updated_at
+`
+
+type DrainPendingCheckSuitesForPRParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+}
+
+type DrainPendingCheckSuitesForPRRow struct {
+ SuiteID int64 `json:"suite_id"`
+ HeadSha string `json:"head_sha"`
+ AppID int64 `json:"app_id"`
+ Conclusion pgtype.Text `json:"conclusion"`
+ Status string `json:"status"`
+ SuiteUpdatedAt pgtype.Timestamptz `json:"suite_updated_at"`
+}
+
+// Atomically reads + deletes all pending suites for the given PR address.
+// Caller replays each row through UpsertPullRequestCheckSuite. RETURNING
+// gives us the payloads we need without a separate SELECT, so two parallel
+// handlers racing on the same PR can't double-apply the same row.
+func (q *Queries) DrainPendingCheckSuitesForPR(ctx context.Context, arg DrainPendingCheckSuitesForPRParams) ([]DrainPendingCheckSuitesForPRRow, error) {
+ rows, err := q.db.Query(ctx, drainPendingCheckSuitesForPR,
+ arg.WorkspaceID,
+ arg.RepoOwner,
+ arg.RepoName,
+ arg.PrNumber,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []DrainPendingCheckSuitesForPRRow{}
+ for rows.Next() {
+ var i DrainPendingCheckSuitesForPRRow
+ if err := rows.Scan(
+ &i.SuiteID,
+ &i.HeadSha,
+ &i.AppID,
+ &i.Conclusion,
+ &i.Status,
+ &i.SuiteUpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const getGitHubInstallationByID = `-- name: GetGitHubInstallationByID :one
SELECT id, workspace_id, installation_id, account_login, account_type, account_avatar_url, connected_by_id, created_at, updated_at FROM github_installation
WHERE id = $1
@@ -626,6 +687,67 @@ func (q *Queries) UpsertGitHubPullRequest(ctx context.Context, arg UpsertGitHubP
return i, err
}
+const upsertPendingCheckSuite = `-- name: UpsertPendingCheckSuite :exec
+
+INSERT INTO github_pending_check_suite (
+ workspace_id, installation_id, repo_owner, repo_name, pr_number,
+ suite_id, head_sha, app_id, conclusion, status, suite_updated_at
+) VALUES (
+ $1, $2, $3, $4, $5,
+ $6, $7, $8, $11, $9, $10
+)
+ON CONFLICT (workspace_id, repo_owner, repo_name, pr_number, suite_id) DO UPDATE SET
+ installation_id = EXCLUDED.installation_id,
+ head_sha = EXCLUDED.head_sha,
+ app_id = EXCLUDED.app_id,
+ conclusion = EXCLUDED.conclusion,
+ status = EXCLUDED.status,
+ suite_updated_at = EXCLUDED.suite_updated_at,
+ received_at = now()
+WHERE EXCLUDED.suite_updated_at >= github_pending_check_suite.suite_updated_at
+`
+
+type UpsertPendingCheckSuiteParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+ SuiteID int64 `json:"suite_id"`
+ HeadSha string `json:"head_sha"`
+ AppID int64 `json:"app_id"`
+ Status string `json:"status"`
+ SuiteUpdatedAt pgtype.Timestamptz `json:"suite_updated_at"`
+ Conclusion pgtype.Text `json:"conclusion"`
+}
+
+// =====================
+// GitHub pending check_suite (out-of-order arrival stash)
+// =====================
+// Stashes a check_suite event whose PR row is not yet mirrored. Replayed
+// (and deleted) by DrainPendingCheckSuitesForPR once the matching
+// `pull_request` webhook lands. ON CONFLICT keeps the newest payload
+// for the same (workspace, repo, pr_number, suite_id) — repeated
+// deliveries while the PR is still missing are idempotent. The
+// suite_updated_at guard mirrors UpsertPullRequestCheckSuite so an older
+// event arriving after a newer one cannot overwrite the newer payload.
+func (q *Queries) UpsertPendingCheckSuite(ctx context.Context, arg UpsertPendingCheckSuiteParams) error {
+ _, err := q.db.Exec(ctx, upsertPendingCheckSuite,
+ arg.WorkspaceID,
+ arg.InstallationID,
+ arg.RepoOwner,
+ arg.RepoName,
+ arg.PrNumber,
+ arg.SuiteID,
+ arg.HeadSha,
+ arg.AppID,
+ arg.Status,
+ arg.SuiteUpdatedAt,
+ arg.Conclusion,
+ )
+ return err
+}
+
const upsertPendingGitHubInstallation = `-- name: UpsertPendingGitHubInstallation :one
INSERT INTO github_pending_installation (
installation_id, account_login, account_type, account_avatar_url
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 9df248898d..78489f197f 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -280,6 +280,21 @@ type GithubInstallation struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type GithubPendingCheckSuite struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InstallationID int64 `json:"installation_id"`
+ RepoOwner string `json:"repo_owner"`
+ RepoName string `json:"repo_name"`
+ PrNumber int32 `json:"pr_number"`
+ SuiteID int64 `json:"suite_id"`
+ HeadSha string `json:"head_sha"`
+ AppID int64 `json:"app_id"`
+ Conclusion pgtype.Text `json:"conclusion"`
+ Status string `json:"status"`
+ SuiteUpdatedAt pgtype.Timestamptz `json:"suite_updated_at"`
+ ReceivedAt pgtype.Timestamptz `json:"received_at"`
+}
+
type GithubPendingInstallation struct {
InstallationID int64 `json:"installation_id"`
AccountLogin string `json:"account_login"`
diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sql
index 2f0b46270e..62afe1f91b 100644
--- a/server/pkg/db/queries/github.sql
+++ b/server/pkg/db/queries/github.sql
@@ -211,6 +211,47 @@ ON CONFLICT (pr_id, suite_id) DO UPDATE SET
updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.updated_at >= github_pull_request_check_suite.updated_at;
+-- =====================
+-- GitHub pending check_suite (out-of-order arrival stash)
+-- =====================
+
+-- name: UpsertPendingCheckSuite :exec
+-- Stashes a check_suite event whose PR row is not yet mirrored. Replayed
+-- (and deleted) by DrainPendingCheckSuitesForPR once the matching
+-- `pull_request` webhook lands. ON CONFLICT keeps the newest payload
+-- for the same (workspace, repo, pr_number, suite_id) — repeated
+-- deliveries while the PR is still missing are idempotent. The
+-- suite_updated_at guard mirrors UpsertPullRequestCheckSuite so an older
+-- event arriving after a newer one cannot overwrite the newer payload.
+INSERT INTO github_pending_check_suite (
+ workspace_id, installation_id, repo_owner, repo_name, pr_number,
+ suite_id, head_sha, app_id, conclusion, status, suite_updated_at
+) VALUES (
+ $1, $2, $3, $4, $5,
+ $6, $7, $8, sqlc.narg('conclusion'), $9, $10
+)
+ON CONFLICT (workspace_id, repo_owner, repo_name, pr_number, suite_id) DO UPDATE SET
+ installation_id = EXCLUDED.installation_id,
+ head_sha = EXCLUDED.head_sha,
+ app_id = EXCLUDED.app_id,
+ conclusion = EXCLUDED.conclusion,
+ status = EXCLUDED.status,
+ suite_updated_at = EXCLUDED.suite_updated_at,
+ received_at = now()
+WHERE EXCLUDED.suite_updated_at >= github_pending_check_suite.suite_updated_at;
+
+-- name: DrainPendingCheckSuitesForPR :many
+-- Atomically reads + deletes all pending suites for the given PR address.
+-- Caller replays each row through UpsertPullRequestCheckSuite. RETURNING
+-- gives us the payloads we need without a separate SELECT, so two parallel
+-- handlers racing on the same PR can't double-apply the same row.
+DELETE FROM github_pending_check_suite
+WHERE workspace_id = $1
+ AND repo_owner = $2
+ AND repo_name = $3
+ AND pr_number = $4
+RETURNING suite_id, head_sha, app_id, conclusion, status, suite_updated_at;
+
-- =====================
-- Issue ↔ Pull Request link
-- =====================