Skip to content

feat(coderd): poll pull requests once per replica off the wake-up path - #363

Merged
ibetitsmike merged 12 commits into
mainfrom
mike/issue-296-pr-poller
Nov 16, 2026
Merged

ibetitsmike merged 12 commits into
mainfrom
mike/issue-296-pr-poller

Conversation

@ibetitsmike

@ibetitsmike ibetitsmike commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

Coder Agents opened this PR on behalf of @ibetitsmike.

Closes #296

What changed

  • New coderd/x/chatd/fork_pull_request_poller.go: one pull request poller per replica, started next to the waker in startForkLoops, so only with fork-chat-wakeups. Every 15 seconds it claims due pull_request watches (ClaimDuePullRequestWatches: undelivered, fired or not, active wake-up, unarchived chat, spec.next_poll_at due, not yet read through the expiry; FOR UPDATE SKIP LOCKED plus a 5 minute lease in next_poll_at). Rows are grouped by (pull request URL, chat owner) and each group is one read. When a claim batch is full, its last group is held back and joined to the next claim, so a group split by the row limit is still read once. Every claim of a pass takes the watches due at the pass start, so a pass never claims a watch it already read; the lease of each claim starts from the pass start plus the elapsed time. Within a group, watches that watch checks are read apart from those that do not, so a failed checks read does not hold back the others. At most 4 reads run at once, each with a 30 second deadline.
  • After a read, each watch gets its own text from the shared read (pullRequestWakeupText is now pure). New activity writes fired_at and fired_payload ({"text": ...}) with RecordPullRequestWatchPoll and pokes the waker for that chat. Every read moves spec.next_poll_at a minute on, capped at the expiry. A fired watch is read on until its delivery: each read with activity replaces fired_payload and keeps the first fired_at, and only the first fire pokes the waker. So a chat that stays busy gets the activity up to the last read, in one message. A failed read backs off in spec.next_poll_at (rate limit: RetryAfter, at least a minute; other errors: 5 minutes).
  • The delivery no longer reads GitHub. deliverEventsWakeup sends the stored text of a fired watch. ListDueChatWakeups now treats a fired pull_request watch as ready, like child_done. The final poll at the expiry waits (15 second retries, within pullRequestFinalRetryWindow) until the poller read through the expiry (spec.polled_at).
  • gitprovider.FetchPullRequestActivity takes a viewerLogin and skips GET /user when it is set, and returns ViewerLogin. The baseline read of wait_for_events stores it in spec.viewer_login, so polls do not read /user. coderd binds the stored value to the external auth link (<link updated_at>:<login>), so a relink or token refresh reads /user again. coderd also no longer validates an unexpired token on each read (that validation was another /user request per poll); an expired token is still refreshed.
  • Conditional requests: the GitHub provider already sends If-None-Match from its in-memory ETag cache. The poller keeps the request URLs stable (same since for a watch set), so an unchanged pull request answers 304 on every endpoint. The ETags live in replica memory, so the first poll after a restart reads in full.
  • ARCHITECTURE.md: the fork-owned pull request polling bullets now describe the poller in final prose, and the fork-owned sentences that put GitHub reads on the delivery path are corrected. No upstream line changed.

Tests

New fork_pull_request_poller_internal_test.go runs a fake GitHub (TLS httptest, ETag and 304) through the real provider:

  • TestPullRequestPollerConditionalRequests: 3 polls of an unchanged PR send If-None-Match on all 4 endpoints and get 304; /user is requested once, by the baseline.
  • TestPullRequestPollerSharesReads: two chats of one owner watching one PR cost one request per endpoint per poll.
  • TestPullRequestPollerHangDoesNotDelayDelivery: with the waker at one delivery slot and a GitHub read hanging, an interval wake-up of another chat is delivered while the read still hangs.
  • TestPullRequestPollerSharesReadsAcrossClaims: 27 watches of one PR and owner (batch size 25 plus 2) cost one request per endpoint, and every watch is marked polled.
  • TestPullRequestPollerClaimsOncePerPass: 26 watches whose reads each advance the clock 2 minutes are each read once in one pass.
  • TestPullRequestPollerChecksFailureIsolated: a failed checks read backs off the checks watch, and the comment watch of the same pull request is still polled.
  • TestPullRequestPollerDeliversOncePerChat: a new comment sends exactly one message to each of two watching chats through the poke, with no clock advance; the next poll makes no requests.
  • TestWakeupPullRequestFiredTextStaysFresh: the watch fires on comment 1 while the chat runs. Comment 2 arrives and the PR merges, and the next poll reads again. When the chat waits, one message is sent with both comment URLs and state: merged, and no read follows the delivery.
  • TestWakeupPullRequestFinalPollWaitsForFiredRead: the watch fires while the chat is busy, and another comment arrives before the expiry. The waker runs after the expiry before the poller and sends nothing. After the poller reads through the expiry, one message has both comments.
  • TestClaimDuePullRequestWatchesPlan (forkdb): 10,000 chats with ended wake-ups (completed, canceled, paused) and undelivered watches, plus one live watch, then ANALYZE. The claim plan has no Seq Scan on chat_wakeups, chats or chat_wakeup_watches, and the claim returns only the live watch.
  • TestWakeupReadFits: no deadline fits, 2*processReadTimeout+1m fits, 2*processReadTimeout-1s does not, and 2*processReadTimeout <= wakeupDeliveryTimeout.

Claim plan from TestClaimDuePullRequestWatchesPlan (key lines). The existing partial indexes serve it, so no migration is needed:

CTE due
  ->  Limit -> LockRows -> Sort
        ->  Nested Loop
              ->  Nested Loop
                    ->  Index Scan using chat_wakeups_due_idx on chat_wakeups w
                          Filter: (status = 'active'::chat_wakeup_status)
                    ->  Index Scan using chat_wakeup_watches_open_wakeup_idx on chat_wakeup_watches x
                          Index Cond: (wakeup_id = w.id)
                          Filter: ((delivered_at IS NULL) AND (kind = 'pull_request') AND (next_poll_at due) AND (polled_at < w.expires_at))
              ->  Index Scan using chats_pkey on chats c
                    Index Cond: (id = x.chat_id)
                    Filter: (NOT archived)
CTE claimed
  ->  Update on chat_wakeup_watches -> Index Scan using chat_wakeup_watches_pkey

Existing pull request wake-up tests now run the poller and then the waker. TestWakeupPullRequestReadDeadline and TestWakeupPullRequestReadNearDeliveryDeadline are removed because the delivery no longer reads pull requests.

Commands run (all under flock ~/.fork-go.lock):

  • go test ./coderd/x/chatd/ ./coderd/externalauth/... ./coderd/database/forkdb/... -count=1: ok
  • go test ./coderd/database/dbauthz/ -run 'TestForkQuerier|TestMethodTestSuite' -count=1: ok
  • go test ./coderd/ -run PullRequest -count=1: ok
  • go test ./coderd/ -run 'PullRequest|ExternalAuth' -count=1 and go test ./coderd/externalauth/... -count=1 on b0f1eb2: ok. TestForkChatPullRequestActivityViewer: one /user and no validation across two reads of one link, a second /user after a relink.
  • ./coderd/database/forkdb/generate.sh after merging main: no drift.
  • go test ./coderd/x/chatd/ -count=1 on 51a4969: ok. -run TestPullRequestPollerClaimsOncePerPass -count=30: ok.
  • On 0ab3deb (after merging main 2de8654): generate.sh: no drift. go build ./coderd/...: ok. go test -count=1 ./coderd/x/chatd/ ./coderd/database/forkdb/... ./coderd/externalauth/gitprovider/: ok. dbauthz -run 'TestForkQuerier|TestMethodTestSuite': ok. ./coderd/ -run PullRequest: ok. golangci-lint run --fix=false ./coderd/x/chatd/...: nothing in changed lines.
  • On 7fccedd: go test -count=1 ./coderd/x/chatd/ ./coderd/database/forkdb/... ./coderd/externalauth/gitprovider/: ok. dbauthz -run 'TestForkQuerier|TestMethodTestSuite': ok. ./coderd/ -run PullRequest: ok. go test -race -count=10 ./coderd/x/chatd/ -run 'TestWakeupPullRequest|TestPullRequestPoller|TestWakeupReadFits': ok. generate.sh: no drift.
  • go vet on the changed packages, gofmt -l: clean. golangci-lint run --fix=false on the changed packages reports nothing in changed lines.

Negative controls (each reverted afterwards):

  • Poller passes "" as viewer login: ConditionalRequests and SharesReads fail (/user per poll).
  • Group per watch ID instead of (URL, owner): SharesReads fails (8 requests instead of 4).
  • Poller reads since now instead of the baseline: ConditionalRequests fails (comments endpoint not conditional), DeliversOncePerChat fails.
  • Carry disabled (a full batch is processed alone): SharesReadsAcrossClaims fails (requests repeated for the split group).
  • Viewer key not bound to the link: ForkChatPullRequestActivityViewer fails (1 /user read instead of 2 after a relink).
  • RefreshToken called for an unexpired token: ForkChatPullRequestActivityViewer fails (2 validations instead of 0).
  • Claims select by the elapsed time instead of the pass start: ClaimsOncePerPass fails (the pass re-claims read watches until cancelled).
  • One read for watches with and without checks: ChecksFailureIsolated fails (the comment watch is not polled).
  • Claim restored to fired_at IS NULL: FiredTextStaysFresh fails (the fired watch is not read again).
  • fired_payload kept from the first fire: FiredTextStaysFresh fails (comment 2 is missing from the message).
  • Claim without w.status = 'active': ClaimDuePullRequestWatchesPlan fails (Seq Scans on chats, chat_wakeup_watches and chat_wakeups).
  • Fired delivery without the wait for the read through the expiry: FinalPollWaitsForFiredRead fails (the waker sends the old text).

Review answers (P2)

  • Lease for a carried group: the comment on pullRequestPollerBatch now says a batch and its carried group read well within the lease unless most reads hit pullRequestReadTimeout. A read past the lease can be repeated by another replica. That costs requests only: fired_at is kept by COALESCE, the poke fires only on the first fire, and delivery is guarded by the deliveries row, so no second message is sent.
  • viewer_login after a GitHub login rename with a non-expiring token: accepted. /user is read again on a relink or token refresh. Until then the stale login only affects the filter of the user's own activity.
  • Invalid spec reclaimed every 5 minutes until the waker pauses it: accepted. Each reclaim is one row update and no GitHub read.
  • Final retry every 15 seconds for up to 1 hour, where main retried every 5 minutes: the 15 second retry is a database check of spec.polled_at by the waker, with no GitHub read. The poller still reads at most once a minute, and backs off on failures.
  • wakeupReadFits coverage: restored by TestWakeupReadFits.
  • Claim scan growth: the claim joins only active wake-ups, and TestClaimDuePullRequestWatchesPlan pins the index plan above.
  • Stale fired text: fixed, see TestWakeupPullRequestFiredTextStaysFresh.
  • Fired watch delivered at the expiry before the final read (Codex): fixed, the final poll waits for the read through the expiry within pullRequestFinalRetryWindow. See TestWakeupPullRequestFinalPollWaitsForFiredRead.
  • Two replicas split one owner's group of more than 25 watches on one pull request (Codex): dropped. It costs one extra conditional read and no second message, and every watch was read on its own before this PR.
  • A fired delivery that races a read in flight sends the text of the last finished read (Codex): dropped. That equals a delivery a moment before the read started, and is no regression. The final poll waits for polled_at past the expiry, written in the same update as the text.

Not verified

  • No run against real GitHub or a deployed server.
  • No test checks the lease of each claim batch directly.
  • A final read that starts in the last 15 seconds of the one hour retry window after the expiry can be lost when the waker completes the wake-up during it (Codex P2, dropped: same effect as a slightly shorter window).
  • A group reads comments since its oldest baseline. Over 1,000 comments in that window would truncate the read for a newer watch (Codex P2, dropped: the same 10-page cap applied per watch before).
  • A revoked but unexpired token is no longer caught by validation before the read; the read itself fails and backs off.
  • The plan test pins the plan at one data shape (10,000 ended wake-ups). It does not prove the plan at other table sizes.

A pull request poller per replica claims the due pull_request watches,
reads each pull request once per chat owner with conditional requests,
keeps the token's login in the watch spec, and fires watches with their
message so the waker only sends stored text.

Closes #296
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T09:13:35.787252Z 0ab3deb Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fb58857985

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/ARCHITECTURE.md Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a65683d91

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62d68ea19a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 62d68ea19a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_wait_for_events.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 51a4969744

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: c5e488833a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The poller sets the retry from the claim time, which is the pass start plus the elapsed time. Postgres rounds that to the microsecond, so a pass of half a microsecond or more put the retry just past wantNext and the poll at wantNext read nothing.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 871024e58d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

A fired watch whose wake-up is not delivered yet stays claimable. Each
read replaces fired_payload and keeps fired_at, so a chat that stays busy
gets the activity up to the last read, and the waker is poked only on the
first fire.

The claim already skips watches of ended wake-ups. A test seeds 10,000
ended wake-ups and checks that EXPLAIN uses the partial indexes and no
sequential scan.

Add TestWakeupReadFits for the delivery read budget.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7fccedd7ee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_wait_for_events.go Resolved
…very

A fired pull request watch is read on until its delivery, so a final poll
that sends its stored text before the poller read through the expiry
could drop the activity since the read before. The final poll now waits
for that read, fired or not, within pullRequestFinalRetryWindow.
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0ab3deb38c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coderd/x/chatd/fork_wait_for_events.go Resolved
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 0ab3deb38c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@ibetitsmike
ibetitsmike merged commit 3a63653 into main Nov 16, 2026
11 checks passed
@ibetitsmike
ibetitsmike deleted the mike/issue-296-pr-poller branch November 16, 2026 09:36
@ibetitsmike

Copy link
Copy Markdown
Owner Author

Coder Agents acted on behalf of @ibetitsmike.

Merged at head 0ab3deb38c26ec1e945b7f09b0c40f3e61615d1a as 3a63653, on main 2de86545dc785a54d62b85d27e74b1324bf4a1fc, with the server running that main.

Gates on this exact head:

  1. The head matched the SHA I verified (--match-head-commit).
  2. Every check run passed. fork-ci run 43835038223 passed on this head.
  3. Codex receipt for this head: feat(coderd): poll pull requests once per replica off the wake-up path #363 (comment) ("Didn't find any major issues"). Two Codex P2s were declined on the PR with reasons.
  4. No unresolved review thread.
  5. 0 commits behind main.
  6. I ran the tests below on this exact head.

Tests I ran on 0ab3deb38c (detached worktree, under flock ~/.fork-go.lock, Postgres 16 at 127.0.0.1:5432):

  • go test -count=1 -v ./coderd/x/chatd/: 2601 PASS, 0 FAIL.
  • go test -count=10 -race -run 'TestWakeupPullRequest|TestPullRequestPoller|TestWakeupReadFits' ./coderd/x/chatd/: ok.
  • go test -count=1 -v ./coderd/database/forkdb/... ./coderd/externalauth/gitprovider/: 282 PASS, 0 FAIL.
  • go test -count=1 -v -run 'TestForkQuerier|TestMethodTestSuite' ./coderd/database/dbauthz/: 5423 PASS, 0 FAIL.
  • go test -count=1 -v -run PullRequest ./coderd/: 2 PASS, 0 FAIL.
  • Negative control 1: with RecordPullRequestWatchPoll keeping the first fired payload (COALESCE(fired_payload, $3)), TestWakeupPullRequestFiredTextStaysFresh and TestWakeupPullRequestFinalPollWaitsForFiredRead fail.
  • Negative control 2: with the final poll delivering a fired watch before the read through the expiry (the (!unread || !canWait) guard forced true), TestWakeupPullRequestFinalPollWaitsForFiredRead fails.
  • On the earlier head 871024e, a control that broke the grouping of reads failed TestPullRequestPollerSharesReads and TestPullRequestPollerSharesReadsAcrossClaims. The source was restored after every control.

Review notes: an independent Opus review of 871024e found no P1. Its two regression P2s (stale fired text, a final poll that could send before the last read) were fixed in 7fccedd and a00c0a8, and the controls above cover both. I read the delta 871024e..0ab3deb: the claim no longer skips fired watches, the poll record keeps the first fired_at and replaces the text, and the waker is poked only on the first fire.

Not exercised: a running server with real GitHub pull requests, several replicas sharing one claim, and GitHub rate limits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chatd: one shared pull request poller with conditional requests, off the wake-up delivery path

1 participant