Chat turns, manual titles, automatic titles and turn status labels each created a debug run on a detached, time-bounded context, rebuilt the run context from the row, and finalized the run by hand. This PR adds `chatdebug.Service.BeginRun` and `StartRun` and routes all four through them. It deletes `prepareQuickgenDebugCandidate`, `shortTextCandidate`, `chatdebugRunContext`, `debugCreateRunTimeout` and a literal 5 second insert timeout. - `BeginRun` inserts the run on a context that ignores the caller's cancellation, with a 5 second limit, and builds the `RunContext` from its parameters. Chat turns call it and still finalize in `runnerDebugTurn`. - `StartRun` wraps `BeginRun` for one model call and returns a context that carries the run plus a function that finalizes it from the call's error. Titles and status labels use it. - New `TestService_StartRun` covers a finalized run, a failed insert and a failed finalize with a mock store, including the seed summary that each finalize keeps and the warning that each failure logs. **Why it is safe:** #30933 pins the insert parameters, the run context, the finalize status and summary, and the failed insert for all four call sites. Those tests and the other debug-run, title and quickgen tests pass before and after. `CreateRun` stores its parameters unchanged, so a `RunContext` built from the parameters equals one built from the row. A repo-wide search finds no reference to the deleted symbols. Of 14 mutants of `BeginRun` and `StartRun`, 13 fail `TestService_StartRun`. They drop either failure warning, report a failed insert as success, let the insert inherit the caller's cancellation or lose its deadline, drop the parent chat or the history tip from the run context, drop the seed summary from the insert or the finalize, ignore the call error or the finalize timeout, leave the run out of the returned context, or finalize the wrong run. The survivor shortens the insert limit from 5 seconds to 1. **Review focus:** log output. Create and finalize failures now log through the chatdebug logger as `failed to create debug run` and `failed to finalize debug run`. Before, each call site used its own logger and message. Compaction still creates its debug run by hand, because #30766 changes that code; it can move to `StartRun` after that PR merges. **Moved onto the deletion stack:** a merge commit moved this layer onto the updated #30933 without a force push. It carries one forced change: #30989 removed the `database/sql` import from `chatdebug/service_test.go` with the last test that used it, and `TestService_StartRun` here still uses `sql.NullString`, so the merge adds the import back. The rest of the diff is unchanged. Validation: - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run '^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$'`: the same 25 tests pass before and after, and again after the move. - `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/chatdebug/...` passes. - `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/... ./coderd/x/chatd/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack deletes the stale debug-run sweep, then simplifies the chatdebug debug-run, stream wrapper and step numbering code, drops the indexes the sweep used, and last deletes a runner debug field that lost its only reader with the heartbeats. The debug-run and stream wrapper refactors each sit on a test-only layer that pins the behavior they keep. 1. #30988 Delete the chat debug run and step heartbeats 2. #30989 Delete `FinalizeStale` and the stale threshold 3. #30995 Delete the `FinalizeStaleChatDebugRows` query 4. #30933 Pin the debug runs that turns, titles and status labels record 5. This PR: Create and finalize debug runs through one helper 6. #30980 Table the stream wrapper tests and cover their status rules 7. #30981 Share one finalize-once lifecycle between the stream wrappers 8. #31007 Number chat debug steps in the database 9. #31008 Delete the process-global step counters 10. #31009 Drop the chat debug stale-sweep indexes 11. #31010 Drop the unused `runnerCtx` from the runner debug turn > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description.
268 lines
7.2 KiB
Go
268 lines
7.2 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/mcpclient"
|
|
)
|
|
|
|
type runnerDebugTurn struct {
|
|
runnerCtx context.Context
|
|
logger slog.Logger
|
|
|
|
mu sync.Mutex
|
|
|
|
runContext chatdebug.RunContext
|
|
seedSummary map[string]any
|
|
service *chatdebug.Service
|
|
|
|
created bool
|
|
disabled bool
|
|
finalized bool
|
|
|
|
status chatdebug.Status
|
|
statusSet bool
|
|
}
|
|
|
|
func newRunnerDebugTurn(runnerCtx context.Context, logger slog.Logger) *runnerDebugTurn {
|
|
return &runnerDebugTurn{
|
|
runnerCtx: runnerCtx,
|
|
logger: logger,
|
|
}
|
|
}
|
|
|
|
func (d *runnerDebugTurn) Ensure(
|
|
ctx context.Context,
|
|
chat database.Chat,
|
|
debug *generationDebug,
|
|
) context.Context {
|
|
if d == nil {
|
|
return ctx
|
|
}
|
|
|
|
d.mu.Lock()
|
|
defer d.mu.Unlock()
|
|
return d.ensureLocked(ctx, chat, debug)
|
|
}
|
|
|
|
func (d *runnerDebugTurn) ensureLocked(
|
|
ctx context.Context,
|
|
chat database.Chat,
|
|
debug *generationDebug,
|
|
) context.Context {
|
|
// Check finalized/disabled before created: once the turn is
|
|
// finalized, new contexts must not be attributed to the
|
|
// finalized run, even if it was created earlier.
|
|
if d.disabled || d.finalized {
|
|
return ctx
|
|
}
|
|
if d.created {
|
|
return d.contextLocked(ctx)
|
|
}
|
|
if debug == nil || !debug.Enabled || debug.Service == nil ||
|
|
chat.ID == uuid.Nil || debug.TriggerMessageID == 0 {
|
|
d.disabled = true
|
|
return ctx
|
|
}
|
|
|
|
seedSummary := chatdebug.SeedSummary(
|
|
chatdebug.TruncateLabel(debug.TriggerLabel, chatdebug.MaxLabelLength),
|
|
)
|
|
// Carry per-server MCP connect outcomes (and their dropped
|
|
// count) stashed by RecordMCPConnectSummaries before the run
|
|
// existed, so slow or failing servers appear in the run instead
|
|
// of as a silent gap before the first step. Seeded keys survive
|
|
// FinalizeRun's summary aggregation.
|
|
for key, stashed := range d.seedSummary {
|
|
if seedSummary == nil {
|
|
seedSummary = make(map[string]any, len(d.seedSummary))
|
|
}
|
|
seedSummary[key] = stashed
|
|
}
|
|
rootChatID := uuid.Nil
|
|
if chat.RootChatID.Valid {
|
|
rootChatID = chat.RootChatID.UUID
|
|
}
|
|
parentChatID := uuid.Nil
|
|
if chat.ParentChatID.Valid {
|
|
parentChatID = chat.ParentChatID.UUID
|
|
}
|
|
|
|
runContext, ok := debug.Service.BeginRun(ctx, chatdebug.CreateRunParams{
|
|
ChatID: chat.ID,
|
|
RootChatID: rootChatID,
|
|
ParentChatID: parentChatID,
|
|
ModelConfigID: debug.ModelConfig.ID,
|
|
TriggerMessageID: debug.TriggerMessageID,
|
|
HistoryTipMessageID: debug.HistoryTipMessageID,
|
|
Kind: chatdebug.KindChatTurn,
|
|
Status: chatdebug.StatusInProgress,
|
|
Provider: debug.Provider,
|
|
Model: debug.Model,
|
|
Summary: seedSummary,
|
|
})
|
|
if !ok {
|
|
d.disabled = true
|
|
return ctx
|
|
}
|
|
|
|
d.service = debug.Service
|
|
d.runContext = runContext
|
|
d.seedSummary = seedSummary
|
|
d.created = true
|
|
return d.contextLocked(ctx)
|
|
}
|
|
|
|
func (d *runnerDebugTurn) Context(ctx context.Context) context.Context {
|
|
if d == nil {
|
|
return ctx
|
|
}
|
|
d.mu.Lock()
|
|
defer d.mu.Unlock()
|
|
return d.contextLocked(ctx)
|
|
}
|
|
|
|
// RecordMCPConnectSummaries merges one preparation's per-server MCP
|
|
// connect outcomes into the mcp_connect summary key, creating the
|
|
// debug run if it does not exist yet. Preparation invokes it as soon
|
|
// as its MCP connect phase completes, so every attempt is recorded:
|
|
// preparations that fail after connecting, decision errors, and
|
|
// actions that never reach Ensure (local tool execution,
|
|
// requires-action, turn finishing). Creating the run here matters
|
|
// when the first preparation connects and then fails: no model or
|
|
// compaction action ever runs Ensure, and Finalize discards the
|
|
// stash of a never-created run.
|
|
func (d *runnerDebugTurn) RecordMCPConnectSummaries(
|
|
ctx context.Context,
|
|
chat database.Chat,
|
|
debug *generationDebug,
|
|
summaries []mcpclient.ConnectSummary,
|
|
) {
|
|
if d == nil || len(summaries) == 0 {
|
|
return
|
|
}
|
|
d.mu.Lock()
|
|
defer d.mu.Unlock()
|
|
if d.disabled || d.finalized {
|
|
return
|
|
}
|
|
// Merge before ensuring so the outcomes ride the seed summary
|
|
// when this call is the one that creates the run.
|
|
d.mergeMCPConnectSummariesLocked(summaries)
|
|
d.ensureLocked(ctx, chat, debug)
|
|
}
|
|
|
|
// maxMCPConnectSummaryEntries bounds the retained per-preparation MCP
|
|
// connect outcomes. A turn may run up to 1,200 generation steps, each
|
|
// reconnecting to every selected server, so unbounded retention could
|
|
// grow one run summary to megabytes of database and API payload. The
|
|
// newest entries win because the tail of the history is what shows a
|
|
// server that degraded mid-turn; the mcp_connect_dropped count keeps
|
|
// the truncation visible.
|
|
const maxMCPConnectSummaryEntries = 100
|
|
|
|
// mergeMCPConnectSummariesLocked appends a preparation's per-server
|
|
// MCP connect outcomes to the mcp_connect summary key. chatd
|
|
// reconnects to every configured MCP server on each generation step
|
|
// while the run is created only once, so without this merge only
|
|
// one preparation's outcomes would survive to the finalized run and
|
|
// a server that degrades mid-turn would still be reported as
|
|
// connected.
|
|
func (d *runnerDebugTurn) mergeMCPConnectSummariesLocked(summaries []mcpclient.ConnectSummary) {
|
|
if len(summaries) == 0 {
|
|
return
|
|
}
|
|
if d.seedSummary == nil {
|
|
d.seedSummary = make(map[string]any, 1)
|
|
}
|
|
existing, _ := d.seedSummary["mcp_connect"].([]mcpclient.ConnectSummary)
|
|
existing = append(existing, summaries...)
|
|
if over := len(existing) - maxMCPConnectSummaryEntries; over > 0 {
|
|
existing = existing[over:]
|
|
dropped, _ := d.seedSummary["mcp_connect_dropped"].(int)
|
|
d.seedSummary["mcp_connect_dropped"] = dropped + over
|
|
}
|
|
d.seedSummary["mcp_connect"] = existing
|
|
}
|
|
|
|
func (d *runnerDebugTurn) contextLocked(ctx context.Context) context.Context {
|
|
if !d.created || d.runContext.RunID == uuid.Nil {
|
|
return ctx
|
|
}
|
|
runContext := d.runContext
|
|
return chatdebug.ContextWithRun(ctx, &runContext)
|
|
}
|
|
|
|
func (d *runnerDebugTurn) RecordOutcome(status chatdebug.Status) {
|
|
if d == nil || debugTurnOutcomePriority(status) == 0 {
|
|
return
|
|
}
|
|
d.mu.Lock()
|
|
defer d.mu.Unlock()
|
|
if d.finalized {
|
|
return
|
|
}
|
|
if !d.statusSet || debugTurnOutcomePriority(status) > debugTurnOutcomePriority(d.status) {
|
|
d.status = status
|
|
d.statusSet = true
|
|
}
|
|
}
|
|
|
|
func (d *runnerDebugTurn) Finalize(ctx context.Context) {
|
|
if d == nil {
|
|
return
|
|
}
|
|
|
|
d.mu.Lock()
|
|
if d.finalized {
|
|
d.mu.Unlock()
|
|
return
|
|
}
|
|
d.finalized = true
|
|
if !d.created || d.service == nil || d.runContext.RunID == uuid.Nil {
|
|
d.mu.Unlock()
|
|
return
|
|
}
|
|
service := d.service
|
|
runContext := d.runContext
|
|
seedSummary := d.seedSummary
|
|
status := chatdebug.StatusInterrupted
|
|
if d.statusSet {
|
|
status = d.status
|
|
}
|
|
logger := d.logger
|
|
d.mu.Unlock()
|
|
|
|
if finalizeErr := service.FinalizeRun(ctx, chatdebug.FinalizeRunParams{
|
|
RunID: runContext.RunID,
|
|
ChatID: runContext.ChatID,
|
|
Status: status,
|
|
SeedSummary: seedSummary,
|
|
}); finalizeErr != nil {
|
|
logger.Warn(ctx, "failed to finalize chat debug run",
|
|
slog.F("chat_id", runContext.ChatID),
|
|
slog.F("run_id", runContext.RunID),
|
|
slog.Error(finalizeErr),
|
|
)
|
|
}
|
|
}
|
|
|
|
func debugTurnOutcomePriority(status chatdebug.Status) int {
|
|
switch status {
|
|
case chatdebug.StatusCompleted:
|
|
return 1
|
|
case chatdebug.StatusInterrupted:
|
|
return 2
|
|
case chatdebug.StatusError:
|
|
return 3
|
|
default:
|
|
return 0
|
|
}
|
|
}
|