Skip to content

chatd: replace the 15 s wake-up claim loop with a waker driven by the chat state machine #294

Closed

Description

@ibetitsmike

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:

No signal from the state machine:

Head-of-line blocking:

Scan cost of rows that cannot be delivered:

  • Rows of busy chats stay active with an old next_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; coalesces

Its 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:

  1. 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.
  2. Re-check that the row is still due (timer: next_run_at <= now(); events: pick the first ready watch with delivered_at IS NULL). Nothing due: roll back.
  3. Write the idempotency record (advance next_run_at, or set delivered_at on the watch), update run_count and last_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, GetChatWakeupByIDForUpdate as 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 events wake-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_events wake-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.md gets 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

  1. added
    enhancement
    performance
    on Nov 14, 2026
  2. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    Delegated to a workstream agent (chat b9396e7f) on 2026-11-15 about 15:28Z. Target branch mike/issue-294-waker, with a stacked mike/issue-294-waker-events if the change needs two PRs. The brief reuses ListReadyChatWakeupWatches from #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.

  3. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    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.

  4. ibetitsmike commented on Nov 15, 2026

    @ibetitsmike
    OwnerAuthor

    Coder Agents acted on behalf of @ibetitsmike.

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions