Repository navigation
Description
Filed by Xum (an AI coding agent) on behalf of @ibetitsmike. Part of #311. Line numbers are at 607a95b.
Summary
Chat wake-ups are delivered by a loop that runs in every chatd worker of every replica: every 15 s it claims up to 20 due rows with a 2 minute lease, then handles them one at a time. The chat state machine is never consulted. Results:
- A wake-up whose chat just became idle, or whose watched child just finished, waits up to 15 s plus the time the tick takes.
- The loop handles at most 20 rows per tick per replica. With many waiting wake-ups, latency grows linearly and scheduled wake-ups queue behind waiting ones.
- One slow row blocks the rest of the batch.
- Idle cost is proportional to the number of waiting wake-ups (see the tracking issue: 56 round trips and 8 row updates per waiting wake-up per minute).
Replace the loop with a waker that is poked by the state machine, by a timer for the next scheduled row, and by a slow sweep. Drop the lease.
Evidence
The loop:
fork_wakeups.go:28-30:wakeupPollInterval = 15 s,wakeupLease = 2 min,wakeupClaimBatch = 20.worker.go:94andfork_wakeups.go:36-63: started in every worker; the ticker is stopped during a pass and reset after it, so the period is 15 s plus the pass duration.fork_wakeups.go:88-106: the claimed rows are delivered sequentially.
No signal from the state machine:
- Every committed transition already publishes
chat:update:{chat_id}with the new status (machine.go:147-206). Nothing in the wake-up code subscribes to it, and there is no in-process hook. - A busy chat keeps its wake-up due and is retried on a later tick:
fork_wakeups.go:143-151,fork_wakeups.go:222-226.
Head-of-line blocking:
- Process reads are bounded at 30 s (
fork_process_events.go:37-40), with a 30 s dial timeout for an offline agent (fork_process_events.go:182-183,defaultDialTimeoutatchatd.go:73). Pull request reads are bounded at 30 s (fork_pull_request_events.go:40-42). - The guard at
fork_wait_for_events.go:432-438andfork_wait_for_events.go:458-460stops starting such reads once less than 60 s of the lease is left, and releases the remaining rows unhandled. So one replica completes about 2 slow reads per tick, and every other row in the batch, including plain interval wake-ups, waits for the next tick. - A wake-up that watches a process on an unreachable agent comes back every 60 s (
processErrorRetry,fork_process_events.go:41-43) and costs 30 s each time. Two such wake-ups saturate a replica.
Scan cost of rows that cannot be delivered:
- Rows of busy chats stay
activewith an oldnext_run_at. The claim's index scan walks all of them every tick before it reaches a deliverable row. On the seeded database, 3,045 such rows cost 15,204 buffer hits per claim (plan in the tracking issue).
What the lease is for (TLA+ result, tracking issue): at-most-once delivery comes from the idempotency record written in the message transaction, and still holds with the lease check removed. The lease only makes a committed pause or cancel win over a delivery in flight. A status = 'active' check under the wake-up row lock gives the same guarantee.
Proposed design
All new code in coderd/x/chatd/fork_waker.go. Hooks into upstream files are one line each.
1. The waker
One forkWaker per chatd Server, not per worker.
type forkWaker struct {
pokes chan uuid.UUID // chat to re-check; uuid.Nil means "everything"
...
}
func (w *forkWaker) Poke(chatID uuid.UUID) // never blocks; coalescesIts goroutine waits on three sources and runs reconcile(scope):
| Source | When | Scope |
|---|---|---|
| Poke | see table below | one chat |
| Timer | at min(next_run_at) over active rows with next_run_at > now(); re-armed after every pass and after a poke from a wake-up write |
everything |
| Sweep | at start, then every 60 s | everything |
reconcile runs the due query, then delivers each row in a bounded pool (8 concurrent deliveries per replica), each delivery with its own deadline.
2. Pokes
In-process only. The replica that commits pokes its own waker after the commit.
| Event | Hook | Chats poked |
|---|---|---|
A transition leaves a chat in a status other than running or interrupting, or archives it |
one fork hook on ChatMachine called after buffer.Flush() in Update (machine.go:205), and at the two other flush sites (CreateChat, SetFamilyArchived) |
the chat and its parent_chat_id |
| A wake-up is created, resumed or rescheduled | after the write in createChatWakeup and the wake-up control handlers |
the wake-up's chat, plus re-arm the timer |
| A watch fires (process or pull request) | the writer of fired_at (#295, #296) |
the watch's chat |
chatstate must not import chatd. Add a field forkAfterCommit func(database.Chat) on ChatMachine, set where chatd constructs machines; chatstate/fork_notice.go is the precedent for fork code in that package.
No pubsub channel is added. A poke lost because the process died after the commit is recovered by the sweep of any replica. TLC shows this combination never loses a wake-up, and shows the counterexamples for "poke on child done only" and for "pokes with no sweep" (tracking issue, configurations B, E, G).
3. The due query
One statement for both kinds of due row, scoped to one chat when a poke carries one:
-- name: ListDueChatWakeups :many
SELECT w.id
FROM chat_wakeups w
JOIN chats c ON c.id = w.chat_id
WHERE w.status = 'active'
AND (sqlc.narg('chat_id')::uuid IS NULL OR w.chat_id = sqlc.narg('chat_id')::uuid)
AND (c.archived -- archived: cancel
OR (c.status NOT IN ('running', 'interrupting', 'requires_action', 'paused')
AND NOT (c.status = 'error' AND EXISTS (SELECT 1 FROM chat_queued_messages q WHERE q.chat_id = c.id))))
AND (w.next_run_at <= now()
OR EXISTS (/* a ready watch of w, the predicate of ListReadyChatWakeupWatches in #293 */))
ORDER BY w.next_run_at NULLS LAST, w.id
LIMIT sqlc.arg('limit_count')::int;It is a plain SELECT. It takes no lock and writes nothing.
4. Delivery in one transaction
Keep the existing SendMessage path with forkAdmit (fork_wakeups.go:259-303). Inside forkAdmit, under the chat lock:
SELECT ... FROM chat_wakeups WHERE id = $1 AND status = 'active' FOR UPDATE SKIP LOCKED. No row means another replica is delivering it or it was paused or canceled: roll back.- Re-check that the row is still due (timer:
next_run_at <= now(); events: pick the first ready watch withdelivered_at IS NULL). Nothing due: roll back. - Write the idempotency record (advance
next_run_at, or setdelivered_aton the watch), updaterun_countandlast_run_at, and the cap counter of chatd: wake-up caps run five aggregates per delivery, one over a day of organization chat messages #297.
Lock order is chat row, then wake-up row, everywhere (delivery, archive cascade). The pause and cancel handlers lock only the wake-up row.
5. Removed
wakeupLoop,wakeupOnce,ClaimDueChatWakeups,FinishChatWakeupClaim,GetChatWakeupByIDForUpdateas a fencing step,errWakeupClaimLost.- Column
chat_wakeups.lease_expires_at. - The "stays due" release path: a busy chat's row is simply not returned by the due query, and the chat's next idle transition pokes.
- The 15 s reschedule of
eventswake-ups (eventsWakeupRunAt).
6. Schedules
next_run_at for interval and cron rows is computed as today (fork_wakeups.go:337-370). With the timer they fire at the scheduled time instead of up to one tick late.
Expected cost
| Today | After | |
|---|---|---|
Idle, N waiting events wake-ups, one replica |
4 claims + 56 N round trips and 8 N row updates per minute | 1 SELECT per minute |
| Child finishes, parent idle | up to 15 s + tick time, more when over 20 rows are waiting | one scoped SELECT and one delivery transaction, right after the child's commit |
| Chat becomes idle with a due wake-up | up to 15 s + tick time | same as above |
| One unreachable agent | blocks the batch for 30 s per row | not on this path (#295) |
Acceptance criteria
- With quartz, a test creates a
wait_for_eventswake-up, finishes the child, and asserts the parent receives the message with no clock advance. - A test makes a chat busy across a due interval slot, ends the turn, and asserts delivery with no clock advance.
- A test drops every poke (waker with a nil poke channel) and asserts delivery after one sweep interval.
- A test runs two wakers against one database, both reconcile the same due row, and exactly one message is stored.
- A test pauses a wake-up between the due query and the delivery transaction and asserts no message is stored.
- A test counts store calls over 10 sweep intervals with 50 waiting wake-ups and nothing to deliver: 10 statements.
git grep -n 'wakeupPollInterval\|lease_expires_at\|ClaimDueChatWakeups'returns nothing outside migrations.coderd/x/chatd/ARCHITECTURE.mdgets TODO notes in the sections that describe wake-up delivery (the human author rewrites them).
Depends on
#293 for the watch predicate. The timer, pokes, single-transaction delivery and lease removal can land first for delay, interval and cron wake-ups.
Activity
ibetitsmike commentedon Nov 15, 2026
Delegated to a workstream agent (chat b9396e7f) on 2026-11-15 about 15:28Z. Target branch
mike/issue-294-waker, with a stackedmike/issue-294-waker-eventsif the change needs two PRs. The brief reusesListReadyChatWakeupWatchesfrom #339 and #340, forbids migrations that cancel or delete wake-ups, and asks for real ARCHITECTURE.md text. The PR goes through fork-ci, Codex and the merge gates.fix(chatd): do not poke the waker after a busy wake-up delivery
feat(chatd): deliver chat wake-ups from a state-driven waker (#344)
ibetitsmike commentedon Nov 15, 2026
Bottom PR #344 (waker, timer, sweep, pokes, single-transaction delivery) merged as 7c10f9f. Top PR #345 (events through the due query, lease column drop, ARCHITECTURE.md) is next after it is retargeted to main and passes the gates. Review follow-ups are in #347.
feat(chatd): make events wake-ups due when a watched child is done (#345
ibetitsmike commentedon Nov 15, 2026
Done. #344 (7c10f9f) and #345 (344810f) are merged. The waker now delivers wake-ups on state changes, and events wake-ups become due when a watched child finishes. #345 drops
chat_wakeups.lease_expires_at, so a rollback must restore the database snapshot. Review follow-ups are tracked in #347.