**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.
319 lines
8.2 KiB
Go
319 lines
8.2 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"maps"
|
|
"slices"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatloop"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// turnToken identifies one turn, so a stale holder cannot act on a
|
|
// replacement turn. The zero token matches no turn.
|
|
type turnToken uint64
|
|
|
|
// runnerTurnSpan owns the sequential chat_turn spans of one runner.
|
|
//
|
|
// Closing a turn fixes its end time, but the span is emitted only once
|
|
// every holder has called Release, so an unwinding task can still
|
|
// record the outcome.
|
|
type runnerTurnSpan struct {
|
|
stages *chatloop.StageTracer
|
|
|
|
mu sync.Mutex
|
|
// turns holds every turn not yet emitted.
|
|
turns map[turnToken]*turnState
|
|
current turnToken
|
|
lastToken turnToken
|
|
shutDown bool
|
|
// lastAnchorAt keeps a future trigger even though its span starts
|
|
// at now.
|
|
lastAnchorAt time.Time
|
|
// takenOver is cleared once the first turn opens.
|
|
takenOver bool
|
|
}
|
|
|
|
// turnState is guarded by runnerTurnSpan.mu.
|
|
type turnState struct {
|
|
token turnToken
|
|
span *chatloop.StageSpan
|
|
spanCtx trace.SpanContext
|
|
chatKind chatloop.ChatKind
|
|
// triggerAt is unadjusted, unlike the span's anchor.
|
|
triggerAt time.Time
|
|
finished bool
|
|
outcome chatloop.TurnOutcome
|
|
invalidErr error
|
|
closed bool
|
|
endAt time.Time
|
|
closeErr error
|
|
holders map[uuid.UUID]struct{}
|
|
}
|
|
|
|
func newRunnerTurnSpan(stages *chatloop.StageTracer, takenOver bool) *runnerTurnSpan {
|
|
return &runnerTurnSpan{
|
|
stages: stages,
|
|
turns: map[turnToken]*turnState{},
|
|
takenOver: takenOver,
|
|
}
|
|
}
|
|
|
|
// Ensure joins taskID to the current turn, or starts one anchored at
|
|
// triggerAt. A newer triggerAt replaces the current turn. A canceled
|
|
// ctx gets the zero token so it cannot act on a replacement turn.
|
|
func (t *runnerTurnSpan) Ensure(ctx context.Context, taskID uuid.UUID, chat database.Chat, triggerAt time.Time) (context.Context, turnToken) {
|
|
if t == nil {
|
|
return ctx, 0
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if t.shutDown || ctx.Err() != nil {
|
|
return ctx, 0
|
|
}
|
|
if turn := t.turns[t.current]; turn != nil {
|
|
switch {
|
|
case turn.finished || turn.outcome != "":
|
|
t.closeLocked(turn, nil)
|
|
case !triggerAt.After(turn.triggerAt):
|
|
turn.hold(taskID)
|
|
return turn.context(ctx), turn.token
|
|
default:
|
|
t.closeLocked(turn, nil)
|
|
}
|
|
}
|
|
|
|
anchorAt := triggerAt
|
|
switch {
|
|
case t.takenOver:
|
|
anchorAt = time.Time{}
|
|
case !triggerAt.IsZero() && !t.lastAnchorAt.IsZero() && !triggerAt.After(t.lastAnchorAt):
|
|
anchorAt = time.Time{}
|
|
t.stages.RecordAnomaly(chatloop.StageAnomalyStaleAnchor)
|
|
}
|
|
t.takenOver = false
|
|
turn := t.startLocked(ctx, chat, triggerAt, anchorAt)
|
|
turn.hold(taskID)
|
|
return turn.context(ctx), turn.token
|
|
}
|
|
|
|
// startLocked anchors at now, with no acquisition, when startAt is zero.
|
|
func (t *runnerTurnSpan) startLocked(ctx context.Context, chat database.Chat, triggerAt, startAt time.Time) *turnState {
|
|
anchored := !startAt.IsZero()
|
|
if !anchored {
|
|
startAt = t.stages.Now()
|
|
}
|
|
t.lastToken++
|
|
turn := &turnState{
|
|
token: t.lastToken,
|
|
chatKind: chatKind(chat),
|
|
triggerAt: triggerAt,
|
|
holders: map[uuid.UUID]struct{}{},
|
|
}
|
|
t.turns[turn.token] = turn
|
|
t.current = turn.token
|
|
t.lastAnchorAt = startAt
|
|
|
|
chatID := attribute.String(chatloop.AttrChatID, chat.ID.String())
|
|
turnCtx, span := t.stages.StartRootAt(turn.context(ctx), chatloop.StageChatTurn, startAt, chatID)
|
|
turn.span = span
|
|
turn.spanCtx = span.SpanContext()
|
|
if anchored {
|
|
t.stages.Record(turnCtx, chatloop.StageAcquisition, chatloop.StageModel{},
|
|
startAt, t.stages.Now(), nil, chatID)
|
|
}
|
|
return turn
|
|
}
|
|
|
|
func (turn *turnState) hold(taskID uuid.UUID) {
|
|
if taskID != uuid.Nil {
|
|
turn.holders[taskID] = struct{}{}
|
|
}
|
|
}
|
|
|
|
func (turn *turnState) context(ctx context.Context) context.Context {
|
|
// Stage identity is needed even when tracing is not recording.
|
|
ctx = withStageIdentity(ctx, chatloop.ScopeTurn, turn.chatKind)
|
|
if !turn.spanCtx.IsValid() {
|
|
return ctx
|
|
}
|
|
return trace.ContextWithSpanContext(ctx, turn.spanCtx)
|
|
}
|
|
|
|
// Complete marks the turn finished; it stays open until Settle so
|
|
// in-flight stages end inside it.
|
|
func (t *runnerTurnSpan) Complete(token turnToken) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if turn := t.turns[token]; turn != nil {
|
|
turn.finished = true
|
|
}
|
|
}
|
|
|
|
// Invalidate is ignored after Complete, since the finishing transition
|
|
// has already committed. Only the first call is kept.
|
|
func (t *runnerTurnSpan) Invalidate(token turnToken, outcome chatloop.TurnOutcome, err error) {
|
|
if t == nil || outcome == "" {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
turn := t.turns[token]
|
|
if turn == nil || turn.finished || turn.outcome != "" {
|
|
return
|
|
}
|
|
turn.outcome = outcome
|
|
turn.invalidErr = err
|
|
}
|
|
|
|
// Settle closes the turn only if it was completed or invalidated.
|
|
func (t *runnerTurnSpan) Settle(token turnToken) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
turn := t.turns[token]
|
|
if turn == nil || (!turn.finished && turn.outcome == "") {
|
|
return
|
|
}
|
|
t.closeLocked(turn, nil)
|
|
}
|
|
|
|
// Release must be called after the task returns so its stages have
|
|
// ended before the turn is emitted.
|
|
func (t *runnerTurnSpan) Release(taskID uuid.UUID) {
|
|
if t == nil || taskID == uuid.Nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
for _, turn := range t.pendingLocked() {
|
|
delete(turn.holders, taskID)
|
|
t.emitIfReleasedLocked(turn)
|
|
}
|
|
}
|
|
|
|
// OpenToken returns the zero token when ctx is done.
|
|
func (t *runnerTurnSpan) OpenToken(ctx context.Context) turnToken {
|
|
if t == nil {
|
|
return 0
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if ctx.Err() != nil {
|
|
return 0
|
|
}
|
|
return t.current
|
|
}
|
|
|
|
// End emits every pending turn regardless of holders. No turn opens
|
|
// afterwards.
|
|
func (t *runnerTurnSpan) End(err error) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
if t.shutDown {
|
|
return
|
|
}
|
|
t.shutDown = true
|
|
if turn := t.turns[t.current]; turn != nil {
|
|
t.closeLocked(turn, err)
|
|
}
|
|
for _, turn := range t.pendingLocked() {
|
|
t.closeLocked(turn, err)
|
|
clear(turn.holders)
|
|
t.emitIfReleasedLocked(turn)
|
|
}
|
|
}
|
|
|
|
func (t *runnerTurnSpan) pendingLocked() []*turnState {
|
|
tokens := slices.Sorted(maps.Keys(t.turns))
|
|
turns := make([]*turnState, 0, len(tokens))
|
|
for _, token := range tokens {
|
|
turns = append(turns, t.turns[token])
|
|
}
|
|
return turns
|
|
}
|
|
|
|
func (t *runnerTurnSpan) closeLocked(turn *turnState, err error) {
|
|
if turn.closed {
|
|
return
|
|
}
|
|
turn.closed = true
|
|
turn.endAt = t.stages.Now()
|
|
turn.closeErr = err
|
|
if t.current == turn.token {
|
|
t.current = 0
|
|
}
|
|
t.emitIfReleasedLocked(turn)
|
|
}
|
|
|
|
func (t *runnerTurnSpan) emitIfReleasedLocked(turn *turnState) {
|
|
if !turn.closed || len(turn.holders) > 0 {
|
|
return
|
|
}
|
|
outcome, err := turn.outcome, turn.closeErr
|
|
switch {
|
|
case outcome != "":
|
|
err = turn.invalidErr
|
|
case turn.finished:
|
|
outcome = chatloop.TurnOutcomeCompleted
|
|
default:
|
|
outcome = chatloop.TurnOutcomeAbandoned
|
|
}
|
|
turn.span.EndTurn(outcome, err, turn.endAt)
|
|
delete(t.turns, turn.token)
|
|
}
|
|
|
|
// triggerMessageTime also counts dynamic tool results, which the client
|
|
// submits to resume a chat from requires_action.
|
|
func triggerMessageTime(messages []database.ChatMessage, dynamicTools map[string]bool) time.Time {
|
|
var triggerAt time.Time
|
|
start := 0
|
|
if index := lastUserPromptIndex(messages); index != -1 {
|
|
triggerAt = messages[index].CreatedAt
|
|
start = index + 1
|
|
}
|
|
if len(dynamicTools) == 0 {
|
|
return triggerAt
|
|
}
|
|
for _, msg := range messages[start:] {
|
|
if msg.Deleted || msg.Compressed || msg.Role != database.ChatMessageRoleTool || !msg.CreatedAt.After(triggerAt) {
|
|
continue
|
|
}
|
|
parts, err := chatprompt.ParseContent(msg)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, part := range parts {
|
|
if part.Type == codersdk.ChatMessagePartTypeToolResult && dynamicTools[part.ToolName] {
|
|
triggerAt = msg.CreatedAt
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return triggerAt
|
|
}
|
|
|
|
func turnTriggerTime(chat database.Chat, messages []database.ChatMessage) time.Time {
|
|
triggerAt := triggerMessageTime(messages, dynamicToolNamesFromChat(chat))
|
|
if chat.CompactionRequestedAt.Valid && chat.CompactionRequestedAt.Time.After(triggerAt) {
|
|
triggerAt = chat.CompactionRequestedAt.Time
|
|
}
|
|
return triggerAt
|
|
}
|