Files
coder/coderd/x/chatd/chatd_debug.go
T
Michael Suchacz 9168dbf4d3 refactor(coderd/x/chatd): unify LLM model-call construction behind a resolver (#28145)
Centralizes every LLM client build in chatd behind one resolver and
makes all model calls behave the same, instead of preserving per-flow
quirks.

## Why

`chatd` built LLM clients in five places (standard turn, compaction
override, quickgen, title override, advisor), each repeating config
parsing, route resolution, client construction, and debug wrapping with
slightly different behavior. An earlier iteration of this PR centralized
construction but preserved every historical quirk behind
purpose-specific spec constructors and policy flags. Review concluded
the quirks themselves were the problem.

## What changed

- `Server.resolveModelCall` (`modelcall.go`) is the single pipeline from
a `modelCallSpec` to a ready client plus call metadata. Callers build
spec literals inline; the only spec fields are data: model source (chat
config, explicit config row, or fixed provider/model pair for computer
use), requested reasoning effort, chatd-scoped routing, and build
options.
- Uniform behavior for every call:
- Provider options are always derived. Whole-chat summaries, turn status
labels, and chat-model compaction summaries previously sent none; they
now follow the config like everything else.
- `MaxOutputTokens` always defaults to 32k when the config leaves it
unset. The compaction summary call nulls the cap after copying the
template because it is non-streaming and the Anthropic SDK rejects
non-streaming requests whose cap implies a completion over ten minutes.
- Debug recording always wraps the client when chat debug is enabled,
labeled with the resolved provider/model. The debug-rebuild paths
(`manualTitleDebugSpec`, `quickgenDebugSpec`) are deleted; debug helpers
now only create and finalize run records, since run association flows
through the generate context, not the model.
- Clients are always constructed with the configured model string and
unmutated route, so AI Gateway validation sees the name exactly as
configured. The resolved identity feeds metadata, logs, and debug labels
only.
- `resolvedModelCall.newCall` / `newObjectCall` are the only production
constructors of `fantasy.Call` / `fantasy.ObjectCall`; object calls now
carry the config's sampling parameters.
- Net: -240 lines.

## Validation

- Full `./coderd/x/chatd/...` suite green (PostgreSQL-backed).
- Red-green toggles verified for the three key unifications (option
derivation, token default, summary cap removal).
- ARCHITECTURE.md: prose the refactor made stale is deleted; no new
resolver documentation is added.

> Mux acted on Mike's behalf for this PR.
2026-08-20 20:54:52 +00:00

112 lines
3.2 KiB
Go

package chatd
import (
"context"
"time"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
)
const (
debugCleanupRetryDelay = 500 * time.Millisecond
debugCleanupAttempts = 3
debugCleanupTimeout = 5 * time.Second
// debugCreateRunTimeout caps how long a CreateRun insert can
// block the caller's critical path. Debug persistence is
// best-effort, so the turn proceeds without debug rows if the
// DB is slow or locked. Matches the manual-title budget.
debugCreateRunTimeout = 5 * time.Second
// debugFinalizeTimeout caps best-effort debug run finalization
// outside the runner's canceled context.
debugFinalizeTimeout = 5 * time.Second
// debugCleanupClockSkew gives cleanup cutoffs tolerance for cross-
// replica clock drift. The cutoff is sampled from the DB
// (updated_at returned by the status transition), and
// chat_debug_runs.started_at is stamped by whatever replica
// processes the replacement turn. If that replica's clock lags
// the DB, its started_at can land behind a commit-time cutoff
// even though the insert physically happened after commit.
// Subtracting this buffer ensures the fast retry path cannot
// delete replacement rows when clocks drift by up to this
// amount; rows within the buffer survive the fast cleanup but
// are still finalized (and eligible for stale-sweep cleanup) by
// the existing FinalizeStale background loop.
debugCleanupClockSkew = 30 * time.Second
)
func (p *Server) debugService() *chatdebug.Service {
if p == nil {
return nil
}
if p.debugSvcFactory == nil {
return p.debugSvc
}
p.debugSvcInit.Do(func() {
p.debugSvc = p.debugSvcFactory()
p.debugSvcReady.Store(p.debugSvc != nil)
})
return p.debugSvc
}
func (p *Server) existingDebugService() *chatdebug.Service {
if p == nil {
return nil
}
if p.debugSvcFactory == nil {
return p.debugSvc
}
if !p.debugSvcReady.Load() {
return nil
}
return p.debugSvc
}
func (p *Server) scheduleDebugCleanup(
ctx context.Context,
logMessage string,
fields []slog.Field,
cleanup func(context.Context, *chatdebug.Service) error,
) {
debugSvc := p.debugService()
if debugSvc == nil {
return
}
cleanupCtx, stopCleanupCtx := p.inflightContext(ctx)
if err := p.goInflight(func() {
defer stopCleanupCtx()
for attempt := 0; attempt < debugCleanupAttempts; attempt++ {
if attempt > 0 {
timer := p.clock.NewTimer(debugCleanupRetryDelay, "chatd", "debug_cleanup")
defer timer.Stop()
select {
case <-timer.C:
case <-cleanupCtx.Done():
timer.Stop()
return
}
}
passCtx, cancel := context.WithTimeout(cleanupCtx, debugCleanupTimeout)
err := cleanup(passCtx, debugSvc)
cancel()
if err == nil {
return
}
logFields := append([]slog.Field{
slog.F("attempt", attempt+1),
slog.F("max_attempts", debugCleanupAttempts),
}, fields...)
logFields = append(logFields, slog.Error(err))
p.logger.Warn(cleanupCtx, logMessage, logFields...)
}
}); err != nil {
stopCleanupCtx()
logFields := append([]slog.Field{slog.F("cleanup", logMessage)}, fields...)
logFields = append(logFields, slog.Error(err))
p.logger.Error(context.WithoutCancel(ctx), "failed to schedule chat debug cleanup", logFields...)
}
}