**TL;DR:** Wraps each prompt in a `chat_turn` root span with every lifecycle stage parented under it. The span records one outcome per turn (`completed`, `interrupted`, `error`, `abandoned`), and the new `coderd_chatd_turn_outcomes_total` counter counts those outcomes. Turns stay correct when tasks are canceled, replaced, or retried. Each prompt runs inside a `chat_turn` root span owned by the runner (`runnerTurnSpan`). The generation step, prepare, MCP connect, stream, TTFT, provider attempt, commit, thinking, tool call, compaction, and retry backoff stages are parented under it, activating the stages from #29770. `chat_turn` spans are standalone roots: the turn runs on a worker, often on another replica, and no trace context is persisted. **Lifecycle** - **Start.** Each generation loop iteration calls `Ensure`, which opens the turn if none is open and returns a `turnToken`. The span is backdated to the trigger: the latest of the last user prompt, a dynamic tool's result message after it, and a pending compaction request. An `acquisition` stage covers trigger to pickup. - **Stale trigger / takeover.** A trigger at or before the previous anchor opens the turn at now with no `acquisition` and counts `stale_anchor`. A runner that took the chat over from an owner with a stale heartbeat (`TakenOver`, from acquisition) opens its first turn at now with no `acquisition`, so the dead owner's run is not reported as pickup delay. - **Newer prompt.** `Ensure` on the current turn with a newer trigger closes it and opens a new one. The closed turn is `abandoned` unless the task that ran it records an outcome before releasing it. - **Finish.** After `FinishTurn` or `EnterRequiresAction` commits, the step calls `Complete`; `Settle` closes the span after the step's own stage ends, so the finishing step is inside the turn. A chat waiting in `requires_action` is outside any turn; the generation resumed by its tool results opens a new one. - **Emission.** Closing a turn fixes its end time; its span is emitted once every task that joined it (`Ensure` takes the task ID) has called `Release`, which `runTask` does after the task returns. A finishing task whose `FinishTurn` promoted a queued prompt therefore still counts its turn as `completed` even when the promoted task's `Ensure` runs before its `Complete`. `End` at runner exit emits whatever is left. - **Failure.** A step that commits `FinishError`, or fails closed, invalidates the turn as `error` after the commit. Errors the task runner retries, including task timeouts, keep the same turn open; an expected, non-retryable exit records no outcome and leaves the turn open until the interrupt task, a newer prompt, or runner exit closes it. A canceled generation task records no outcome and cannot obtain a turn token, so a replaced task never touches its successor's turn. - **Interrupt.** The interrupt task marks the open turn `interrupted` before `FinishInterruption` commits and closes it after. Only a stop (by the user or a parent agent) is `interrupted`; it ends with unset span status, since error status is reserved for `error` turns. runner shutdown, loss of ownership, and message edits close the turn as `abandoned` with unset status. - **Promotion.** Every promoting transition (`FinishTurn`, `FinishInterruption`, a send to an errored chat, `PromoteQueued`) returns the promoted message's queued time in its result, and one `recordQueueWait` helper records a standalone `queue_wait` to the promotion. The promoted turn opens at the promotion time. `chat_turn` is observed on `coderd_chatd_stage_duration_seconds` only for completed turns, so the histogram is completed-turn latency; every turn still emits its span. `coderd_chatd_turn_outcomes_total{outcome, chat_kind}` counts every closed turn exactly once (`completed`, `interrupted`, `error`, `abandoned`), matching the span's `turn_outcome`, under the `chat-stage-metrics` experiment. Turn time accounting is in draft #29772. **Stages and identity** - `tool_call` is a live stage around each local tool call in `chatloop`; the tool runs on its context, and it ends errored only when the tool fails to execute. Calls that never run (inactive, unknown, or rejected by policy) record no stage. - `mcp_connect` carries connected and failed server counts and ends errored only when servers were configured and none connected. - The compaction stage carries the model that runs the summary. - `withStageIdentity` puts scope and chat kind on the turn context. Detached background work runs in `background` scope as its own trace roots. - The `advisor` tool's nested model call appears only as its enclosing `tool_call`. ARCHITECTURE.md gains a "Lifecycle tracing" section. <details> <summary>Review decisions</summary> - Turn identity stays timestamp-based with targeted fixes (clamped acquisition, rotation on a newer trigger, invalidate after commit, fail-closed invalidation, settle closing invalidated turns) plus a takeover flag; keying turns on message IDs would not detect takeover and cannot express interrupted/abandoned outcomes. - Outcome classification: the interrupt task owns `interrupted`, and cancellation or a fence mismatch alone never records an outcome, so shutdown, ownership loss, and edits are `abandoned`. Only `error` turns set error span status. Remaining ordering races between a step and an interrupt are documented as known limitations in ARCHITECTURE.md. - Turns are emitted after the tasks that ran them return, not when they close, so an outcome a replaced task records while unwinding reaches its own turn; the successor task is not delayed. Chosen over an after-commit, pre-publish hook on `ChatMachine.Update`, which would fix only the `FinishTurn` ordering. - `requires_action` ends the turn rather than pausing it, so `chat_turn` measures chatd time; a prompt with client tools counts as several turns. - Promoted turns anchor at promotion time and `queue_wait` is always standalone, so `chat_turn` never includes time spent queued behind another turn. - The former `capacity_wait` stage (#29805) was dropped: it was a per-worker lower bound, excluded from accounting, and needed its own SQL and bookkeeping. #29805's remaining helpers are folded into this PR. </details> Supersedes #28972, #28973, and #29805. 🤖 This PR was generated by Coder Agents on behalf of @jscottmiller.
348 lines
9.0 KiB
Go
348 lines
9.0 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)
|
|
})
|
|
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
|
|
}
|
|
// Interrupting and requires-action chats bypass capacity so their runners
|
|
// can finish work or enforce the action deadline.
|
|
isSubagent := row.ParentChatID.Valid
|
|
if row.Status == database.ChatStatusRunning &&
|
|
((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
|
|
}
|
|
_, 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
|
|
}
|
|
|
|
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
|
|
}
|