Files
coder/coderd/x/chatd/worker.go
T
Thomas Kosiewski 8620361fcc feat(coderd): run chat automation schedules (#30160)
Part of CODAGT-1211. Part of CODAGT-1135.

> Stack: PR 7a of "Automations for Coder Agents", on top of 1210 5b
(#30134, `tk/codagt-1210b-automations-new-chat`). Run now (`POST
.../runs`) is split into PR 7b (#30166) on top of this one, which closes
CODAGT-1211.

Schedule automations now run. Every coderd instance scans for due
schedules at start and every 30 seconds, and publishes each occurrence
through the existing `Publish` paths (existing_chat `SendMessage(queue)`
and new_chat `Create`, with their `AdmitInTx` callbacks). There is no
second admission path.

## How a scan works

1. An unlocked read returns enabled schedule automations whose cursor
(`schedule_next_run_at`) is due, in pages of 500 by (cursor, id) until a
short page. It leaves out inactive or deleted owners and existing_chat
targets that are gone or archived.
2. The `chat-automations` experiment is evaluated once per owner per
tick, outside any callback. Owners with it off are dropped without a
cursor write. `Publish` checks the experiment for the owner again before
the transaction (webhooks map that refusal to 404, like the handler's
own check).
3. A cursor more than 60 seconds (the grace window) old is missed: a
guarded write moves it to the next future time, nothing is published,
and nothing is replayed.
4. Otherwise `Publish` runs (up to eight occurrences at once, so one
slow hook or lock wait does not hold back the rest) with the observed
revision and cursor. The pre-check refuses a stale or expired occurrence
before any hook runs. Under the chat and automation locks, the callback
requires the same revision and cursor, reads the clock after the locks,
requires the occurrence to be due and within grace, and moves the cursor
to the first cron time after that read in the same transaction.
5. A busy chat with `skip`, a full queue or automation share, a hook
denial, lost permission, or an occurrence that expired while waiting for
a lock skips the occurrence with the same guarded write and an info log.
A stale, disabled, or deleted automation is left alone. Other errors
keep the cursor, so the next scan retries within grace. That includes an
experiment-off refusal from `Publish`, because the evaluator also
reports a failed read as off.

New chats created by a schedule are titled with the occurrence's
scheduled time in the schedule's time zone, for example `Tokyo digest
2026-09-30 08:14 JST` (the ticket says acceptance time; the two differ
by at most the grace window, and the scheduled time cannot drift across
a minute while hooks or locks run). Webhook titles stay in UTC. Each
such chat gets an audit entry as created by the automation owner, with
the automation and input ids, like the chats the webhook endpoint
creates.

## Decisions reviewers should check

- **Clock (deviates from the ticket's "fresh database clock").** The
callback reads the injected quartz clock after the chat and automation
locks are held, not transaction-start `now()`. The ticket also requires
fake-clock tests, and the lower layers already read the clock after
locks. Exactly-once rests on the revision and cursor tuple, not on time.
Inter-instance clock skew cannot cause a double acceptance or a replay:
an acceptance commits only together with the conditional cursor write
under the automation lock, and every cursor write moves the cursor
strictly forward (`advanceAutomationSchedule` refuses a next run at or
before the cursor). A clock that is off by `d` only shifts the
acceptance window to `[cursor-d, cursor+grace+d]` in true time; a clock
that runs ahead can skip occurrences within `d`. See the comment on
`checkAutomationOccurrence` and the `CursorOnlyMovesForward` test.
Swapping in `clock_timestamp()` later is a one-line change.
- **Authorization of the cursor write.**
`AdvanceChatAutomationScheduleCursor` follows the object pattern of
`ConsumeChatAutomationWebhookByID` and `UpdateChatAutomationByID`: the
dbauthz wrapper loads the automation and authorizes `update` on it. The
scanner and the callback call it as chatd, so the chatd subject gains
`update` on `chat_automation` (it already had `read`). This is the
smallest grant; chatd still cannot create or delete automations (pinned
in `TestAsChatd`), and owner-only changes stay in the chatd automation
service. No 1207 migration is touched.
- **Narrow write.** The query sets only `schedule_next_run_at` and
`updated_at`, guarded by `id`, `kind = 'schedule'`, `enabled`, the
observed `schedule_revision`, and the observed cursor. It never touches
owner-controlled fields or the revision.
- **Known limitation (CODAGT-1234).** Two replicas that read the same
due row can both reach the `user_prompt_submit` hook before one loses
under the lock; only one message or chat commits. This matches the lower
layer's best-effort unlocked pre-check for webhooks. A claim-first
cursor move would break the ticket's retry-within-grace rule or the
forward-only cursor, so a lease column is proposed as a follow-up.
- The schedule tests run their servers through dbauthz, so they use the
chatd subject's real permissions (they fail without the grant).

## Tests

`coderd/x/chatd/automation_schedules_internal_test.go` uses a mock
clock, real Postgres, and a second connection that holds row locks
(waiting on `pg_stat_activity`): two instances accept one occurrence
(existing_chat, and new_chat with no orphan chat); busy `skip`,
automation share full, and queue full each advance the cursor once; a
cron edit rolls back an in-flight acceptance; restart after missed
intervals publishes nothing, restart within grace accepts once; previews
match accepted runs; an occurrence that expires while waiting for a lock
is not accepted; a DST change keeps 09:00 wall-clock time; the
experiment off gets no run (scan and Publish); the cursor only moves
forward; the loop scans at start.

Dogfood UAT ran on a real dev instance through Coder Agents and passed:
a one-minute schedule delivered one message per minute with no browser
open, a busy chat skipped its occurrence, disable stopped runs and
re-enable did not replay, new_chat titles used Asia/Tokyo, two coderd
instances produced no duplicates, and downtime was not replayed.

## Size

About 994 hand-written lines (about 560 of them tests). Generated:
`queries.sql.go`, `querier.go`, `dbmetrics`, `dbmock` (181 lines).

ARCHITECTURE.md prose was drafted by an agent at the user's request; the
user will review it.

---
_Generated with [`xum`](https://github.com/coder/xum) • Model:
`anthropic:claude-opus-5-5` • Thinking: `high`_
2026-10-02 15:54:52 +00:00

384 lines
10 KiB
Go

package chatd
import (
"context"
"database/sql"
"errors"
"sync"
"time"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
coderdpubsub "github.com/coder/coder/v2/coderd/pubsub"
"github.com/coder/coder/v2/coderd/x/chatd/chatstate"
)
// chatWorker owns chat acquisition and runner lifecycle for one process.
type chatWorker struct {
server *Server
opts chatWorkerOptions
mu sync.Mutex
started bool
ctx context.Context
cancel context.CancelFunc
manager *runnerManager
unsubscribe func()
wakeCh chan struct{}
wg sync.WaitGroup
}
// newChatWorker constructs a chat worker. The worker is idle until Start is
// called.
func newChatWorker(server *Server, opts chatWorkerOptions) (*chatWorker, error) {
if server == nil {
return nil, xerrors.New("chatworker: server is required")
}
withDefaults, err := opts.withDefaults()
if err != nil {
return nil, err
}
return &chatWorker{server: server, opts: withDefaults}, nil
}
// Start starts the acquisition and runner manager loops.
func (w *chatWorker) Start(ctx context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.started {
return xerrors.New("chatworker: worker already started")
}
workerID := w.opts.WorkerID
workerCtx, cancel := context.WithCancel(ctx)
manager := newRunnerManager(workerCtx, w.server, w.opts)
if manager.opts.TaskStarter == nil {
starter, err := newTaskStarter(manager.server, manager.opts, manager.RouteStateHint, manager.requestCleanup)
if err != nil {
cancel()
return err
}
manager.opts.TaskStarter = starter
}
wakeCh := make(chan struct{}, w.opts.AcquisitionWakeChannelSize)
unsubscribe, err := w.opts.Pubsub.SubscribeWithErr(
coderdpubsub.ChatStateOwnershipChannel,
coderdpubsub.HandleChatStateOwnership(func(ctx context.Context, _ coderdpubsub.ChatStateOwnershipMessage, err error) {
if err != nil {
w.opts.Logger.Warn(ctx, "chatworker ownership hint decode failed", slogError(err))
return
}
wake(wakeCh)
}),
)
if err != nil {
cancel()
return xerrors.Errorf("subscribe ownership hints: %w", err)
}
w.started = true
w.ctx = workerCtx
w.cancel = cancel
w.manager = manager
w.unsubscribe = unsubscribe
w.wakeCh = wakeCh
manager.start()
w.wg.Go(func() {
w.acquisitionLoop(workerCtx, workerID, manager, wakeCh)
})
w.wg.Go(func() {
w.archiveLoop(workerCtx)
})
w.wg.Go(func() {
w.automationScheduleLoop(workerCtx)
})
if w.opts.CapacityMetrics != nil {
w.wg.Go(func() {
w.capacityMetricsLoop(workerCtx)
})
}
wake(wakeCh)
return nil
}
// Wake requests an immediate acquisition pass.
func (w *chatWorker) Wake() {
w.mu.Lock()
wakeCh := w.wakeCh
w.mu.Unlock()
if wakeCh != nil {
wake(wakeCh)
}
}
// WaitIdle waits until the worker has no active or cleaning runners.
func (w *chatWorker) WaitIdle(ctx context.Context) error {
for {
w.mu.Lock()
manager := w.manager
w.mu.Unlock()
if manager == nil || manager.idle() {
return nil
}
timer := w.opts.Clock.NewTimer(10*time.Millisecond, "chatworker", "wait-idle")
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
timer.Stop()
}
}
// Close stops the worker and waits for its loops to exit.
func (w *chatWorker) Close() error {
w.mu.Lock()
if !w.started {
w.mu.Unlock()
return nil
}
cancel := w.cancel
unsubscribe := w.unsubscribe
manager := w.manager
w.started = false
w.cancel = nil
w.unsubscribe = nil
w.manager = nil
w.wakeCh = nil
w.mu.Unlock()
if unsubscribe != nil {
unsubscribe()
}
cancel()
w.wg.Wait()
if manager != nil {
manager.wait()
}
return nil
}
func wake(ch chan<- struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
func (w *chatWorker) acquisitionLoop(
ctx context.Context,
workerID uuid.UUID,
manager *runnerManager,
wakeCh <-chan struct{},
) {
ticker := w.opts.Clock.NewTicker(w.opts.AcquisitionInterval, "chatworker", "acquisition")
defer ticker.Stop()
for {
select {
case <-wakeCh:
w.acquireOnce(ctx, workerID, manager)
case <-ticker.C:
w.acquireOnce(ctx, workerID, manager)
case <-ctx.Done():
return
}
}
}
func (w *chatWorker) acquireOnce(ctx context.Context, workerID uuid.UUID, manager *runnerManager) {
// Fetch twice the budget so one full pool cannot hide candidates in the other.
rows, err := w.opts.Store.GetChatWorkerAcquisitionCandidates(ctx, database.GetChatWorkerAcquisitionCandidatesParams{
StaleSeconds: w.opts.HeartbeatStaleSeconds,
LimitCount: w.opts.AcquisitionBatchSize * 2,
})
if err != nil {
if ctx.Err() == nil {
w.opts.Logger.Warn(ctx, "chatworker acquisition query failed", slogError(err))
}
return
}
acquired := int32(0)
rootPoolRefused := false
subagentPoolRefused := false
for _, row := range rows {
if acquired >= w.opts.AcquisitionBatchSize {
return
}
// Every runnable status needs admission, so a refusal applies to
// the rest of the pool's candidates in this batch.
isSubagent := row.ParentChatID.Valid
if (isSubagent && subagentPoolRefused) || (!isSubagent && rootPoolRefused) {
continue
}
candidateAcquired, err := w.acquireCandidateSafely(ctx, workerID, manager, row.ID)
if errors.Is(err, errCapacityRefused) {
if isSubagent {
subagentPoolRefused = true
} else {
rootPoolRefused = true
}
continue
}
if err != nil {
if ctx.Err() != nil {
return
}
w.opts.Logger.Warn(ctx, "chatworker acquisition candidate failed", slogError(err))
continue
}
if candidateAcquired {
acquired++
}
}
}
var (
errSkipAcquire = xerrors.New("skip acquire")
errCapacityRefused = xerrors.New("capacity refused")
)
func (w *chatWorker) acquireCandidateSafely(
ctx context.Context,
workerID uuid.UUID,
manager *runnerManager,
chatID uuid.UUID,
) (acquired bool, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = xerrors.Errorf("chatworker acquisition panic: %v", recovered)
}
}()
return w.acquireCandidate(ctx, workerID, manager, chatID)
}
func (w *chatWorker) acquireCandidate(
ctx context.Context,
workerID uuid.UUID,
manager *runnerManager,
chatID uuid.UUID,
) (bool, error) {
runnerID := uuid.New()
var takenOver bool
machine := chatstate.NewChatMachine(w.opts.Store, w.opts.Pubsub, chatID)
err := machine.Update(ctx, func(tx *chatstate.Tx, store database.Store) error {
chat, err := store.GetChatByID(ctx, chatID)
if errors.Is(err, sql.ErrNoRows) {
return errSkipAcquire
}
if err != nil {
return xerrors.Errorf("load chat: %w", err)
}
queueCount, err := store.CountChatQueuedMessages(ctx, chatID)
if err != nil {
return xerrors.Errorf("count queue: %w", err)
}
if !chatstate.ClassifyExecutionState(chat, queueCount > 0, true).IsRunnable() || chat.Archived {
return errSkipAcquire
}
if chat.WorkerID.Valid && chat.RunnerID.Valid {
stale, err := store.IsChatHeartbeatStale(ctx, database.IsChatHeartbeatStaleParams{
ChatID: chat.ID,
RunnerID: chat.RunnerID.UUID,
StaleSeconds: w.opts.HeartbeatStaleSeconds,
})
if err != nil {
return xerrors.Errorf("check heartbeat stale: %w", err)
}
if !stale {
return errSkipAcquire
}
takenOver = true
}
admitted, err := w.opts.AgentCapacityLimiter.Admit(ctx, store, chat)
if err != nil {
return xerrors.Errorf("agent admission: %w", err)
}
if !admitted {
// Roll back to suppress the ownership hint, which would wake every
// worker into an immediate retry of this unowned chat.
return errCapacityRefused
}
if takenOver {
// The lease was read before the admission lock, which heartbeat
// renewal also takes. A renewal that held the lock may have
// extended the lease since, so recheck it under the lock.
stillStale, err := w.leaseStaleUnderAdmissionLock(ctx, store, chat)
if err != nil {
return err
}
if !stillStale {
return errSkipAcquire
}
}
_, err = tx.Acquire(chatstate.AcquireInput{WorkerID: workerID, RunnerID: runnerID})
return err
})
if errors.Is(err, errCapacityRefused) {
return false, errCapacityRefused
}
if errors.Is(err, errSkipAcquire) || errors.Is(err, chatstate.ErrChatNotFound) {
return false, nil
}
if err != nil {
return false, err
}
if err := manager.Spawn(ctx, spawnRunnerRequest{ChatID: chatID, WorkerID: workerID, RunnerID: runnerID, TakenOver: takenOver}); err != nil {
if errAbandon := w.abandonAcquiredChat(ctx, workerID, runnerID, chatID); errAbandon != nil {
return false, errors.Join(err, errAbandon)
}
return false, err
}
return true, nil
}
// leaseStaleUnderAdmissionLock rechecks a takeover candidate's lease while
// holding the capacity admission lock. Admit already holds the lock when
// capacity is capped; advisory locks are reentrant, so taking it again is
// harmless and also covers uncapped deployments.
func (w *chatWorker) leaseStaleUnderAdmissionLock(ctx context.Context, store database.Store, chat database.Chat) (bool, error) {
if err := store.SetTransactionLockTimeout(ctx, admissionLockTimeout.Milliseconds()); err != nil {
return false, xerrors.Errorf("set lock timeout: %w", err)
}
if err := store.AcquireLock(ctx, database.LockIDChatCapacityAdmission); err != nil {
return false, xerrors.Errorf("acquire capacity admission lock: %w", err)
}
stale, err := store.IsChatHeartbeatStale(ctx, database.IsChatHeartbeatStaleParams{
ChatID: chat.ID,
RunnerID: chat.RunnerID.UUID,
StaleSeconds: w.opts.HeartbeatStaleSeconds,
})
if err != nil {
return false, xerrors.Errorf("recheck heartbeat stale: %w", err)
}
return stale, nil
}
func (w *chatWorker) abandonAcquiredChat(ctx context.Context, workerID uuid.UUID, runnerID uuid.UUID, chatID uuid.UUID) error {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownCleanupTimeout)
defer cancel()
machine := chatstate.NewChatMachine(w.opts.Store, w.opts.Pubsub, chatID)
err := machine.Update(cleanupCtx, func(tx *chatstate.Tx, store database.Store) error {
chat, err := store.GetChatByID(cleanupCtx, chatID)
if errors.Is(err, sql.ErrNoRows) {
return errSkipAcquire
}
if err != nil {
return xerrors.Errorf("load chat: %w", err)
}
if !chat.WorkerID.Valid || chat.WorkerID.UUID != workerID || !chat.RunnerID.Valid || chat.RunnerID.UUID != runnerID {
return errSkipAcquire
}
_, err = tx.Abandon(chatstate.AbandonInput{})
return err
})
if errors.Is(err, errSkipAcquire) || errors.Is(err, chatstate.ErrChatNotFound) {
return nil
}
return err
}