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.
206 lines
7.9 KiB
Go
206 lines
7.9 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"testing"
|
|
|
|
"charm.land/fantasy"
|
|
"github.com/google/uuid"
|
|
"github.com/sqlc-dev/pqtype"
|
|
"github.com/stretchr/testify/require"
|
|
"go.uber.org/mock/gomock"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3/sloggers/slogtest"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbmock"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chattest"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/testutil"
|
|
)
|
|
|
|
func TestQuickgenDebugRun(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const prompt = "fix the flaky heartbeat test"
|
|
chat := database.Chat{
|
|
ID: uuid.New(),
|
|
OwnerID: uuid.New(),
|
|
Title: "Fix the flaky heartbeat test",
|
|
TitleSource: database.ChatTitleSourceFallback,
|
|
}
|
|
hidden := mustChatMessage(t, database.ChatMessageRoleUser, database.ChatMessageVisibilityModel, codersdk.ChatMessageText("model context"))
|
|
hidden.ID = 3
|
|
user := mustChatMessage(t, database.ChatMessageRoleUser, database.ChatMessageVisibilityBoth, codersdk.ChatMessageText(prompt))
|
|
user.ID = 5
|
|
tip := hidden
|
|
tip.ID = 8
|
|
messages := []database.ChatMessage{hidden, user, tip}
|
|
|
|
generators := []struct {
|
|
name string
|
|
kind chatdebug.RunKind
|
|
trigger int64
|
|
historyTip int64
|
|
provider string
|
|
model string
|
|
label string
|
|
object map[string]any
|
|
generate func(ctx context.Context, t *testing.T, db *dbmock.MockStore, svc *chatdebug.Service, resolved resolvedModelCall) bool
|
|
}{
|
|
{
|
|
name: "TitleGeneration",
|
|
kind: chatdebug.KindTitleGeneration,
|
|
trigger: user.ID,
|
|
historyTip: tip.ID,
|
|
provider: string(database.AIProviderTypeOpenaiCompat),
|
|
model: "configured-model",
|
|
label: prompt,
|
|
object: map[string]any{"title": "Flaky heartbeat test"},
|
|
generate: func(ctx context.Context, t *testing.T, db *dbmock.MockStore, svc *chatdebug.Service, resolved resolvedModelCall) bool {
|
|
db.EXPECT().UpdateChatTitleByID(gomock.Any(), gomock.Any()).
|
|
Return(chatWithGeneratedTitle(chat, "Flaky heartbeat test"), nil).AnyTimes()
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
generated := &generatedChatTitle{}
|
|
titleOverrideTestServer(db, logger).maybeGenerateChatTitle(ctx, chat, messages, nil, resolved, generated, logger, svc)
|
|
_, ok := generated.Load()
|
|
return ok
|
|
},
|
|
},
|
|
{
|
|
name: "TurnStatusLabel",
|
|
kind: chatdebug.KindQuickgen,
|
|
trigger: 21,
|
|
historyTip: 34,
|
|
provider: "resolved-provider",
|
|
model: "resolved-model",
|
|
label: "Turn status label",
|
|
object: map[string]any{"label": "Fixed flaky test"},
|
|
generate: func(ctx context.Context, t *testing.T, _ *dbmock.MockStore, svc *chatdebug.Service, resolved resolvedModelCall) bool {
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
return generateTurnStatusLabel(ctx, chat, database.ChatStatusWaiting, "All tests pass.", resolved, codersdk.DefaultChatMaxGenerationRetries, logger, svc, 21, 34) != ""
|
|
},
|
|
},
|
|
}
|
|
outcomes := []struct {
|
|
name string
|
|
createErr error
|
|
modelErr error
|
|
wantStatus chatdebug.Status
|
|
}{
|
|
{name: "Completed", wantStatus: chatdebug.StatusCompleted},
|
|
{name: "ModelFails", modelErr: xerrors.New("model failed"), wantStatus: chatdebug.StatusError},
|
|
{name: "CreateFails", createErr: xerrors.New("insert failed")},
|
|
}
|
|
|
|
for _, gen := range generators {
|
|
for _, outcome := range outcomes {
|
|
t.Run(gen.name+"/"+outcome.name, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
db := dbmock.NewMockStore(gomock.NewController(t))
|
|
svc := chatdebug.NewService(db, testutil.Logger(t), nil, chatdebug.WithAlwaysEnable(true))
|
|
runID := uuid.New()
|
|
|
|
db.EXPECT().InsertChatDebugRun(gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, params database.InsertChatDebugRunParams) (database.ChatDebugRun, error) {
|
|
params.StartedAt, params.UpdatedAt = sql.NullTime{}, sql.NullTime{}
|
|
require.Equal(t, database.InsertChatDebugRunParams{
|
|
ChatID: chat.ID,
|
|
TriggerMessageID: sql.NullInt64{Int64: gen.trigger, Valid: true},
|
|
HistoryTipMessageID: sql.NullInt64{Int64: gen.historyTip, Valid: true},
|
|
Kind: string(gen.kind),
|
|
Status: string(chatdebug.StatusInProgress),
|
|
Provider: sql.NullString{String: gen.provider, Valid: true},
|
|
Model: sql.NullString{String: gen.model, Valid: true},
|
|
Summary: pqtype.NullRawMessage{RawMessage: json.RawMessage(`{"first_message":"` + gen.label + `"}`), Valid: true},
|
|
}, params)
|
|
if outcome.createErr != nil {
|
|
return database.ChatDebugRun{}, outcome.createErr
|
|
}
|
|
return database.ChatDebugRun{
|
|
ID: runID,
|
|
ChatID: params.ChatID,
|
|
TriggerMessageID: params.TriggerMessageID,
|
|
HistoryTipMessageID: params.HistoryTipMessageID,
|
|
Kind: params.Kind,
|
|
Status: params.Status,
|
|
Provider: params.Provider,
|
|
Model: params.Model,
|
|
}, nil
|
|
}).Times(1)
|
|
if outcome.createErr == nil {
|
|
db.EXPECT().GetChatDebugStepsByRunID(gomock.Any(), runID).Return(nil, nil).Times(1)
|
|
db.EXPECT().UpdateChatDebugRun(gomock.Any(), gomock.Any()).
|
|
DoAndReturn(func(_ context.Context, params database.UpdateChatDebugRunParams) (database.ChatDebugRun, error) {
|
|
require.Equal(t, runID, params.ID)
|
|
require.Equal(t, chat.ID, params.ChatID)
|
|
require.Equal(t, sql.NullString{String: string(outcome.wantStatus), Valid: true}, params.Status)
|
|
var summary map[string]any
|
|
require.NoError(t, json.Unmarshal(params.Summary.RawMessage, &summary))
|
|
require.Equal(t, gen.label, summary["first_message"])
|
|
return database.ChatDebugRun{ID: runID, ChatID: chat.ID}, nil
|
|
}).Times(1)
|
|
}
|
|
|
|
var runs []*chatdebug.RunContext
|
|
model := &chattest.FakeModel{
|
|
GenerateObjectFn: func(ctx context.Context, _ fantasy.ObjectCall) (*fantasy.ObjectResponse, error) {
|
|
if run, ok := chatdebug.RunFromContext(ctx); ok {
|
|
runs = append(runs, run)
|
|
}
|
|
if outcome.modelErr != nil {
|
|
return nil, outcome.modelErr
|
|
}
|
|
return &fantasy.ObjectResponse{Object: gen.object}, nil
|
|
},
|
|
}
|
|
resolved := resolvedModelCall{
|
|
model: chatprovider.NewModel(model, nil),
|
|
dbConfig: database.ChatModelConfig{ID: uuid.New(), Model: "configured-model"},
|
|
resolvedProvider: "resolved-provider",
|
|
resolvedModel: "resolved-model",
|
|
route: aiGatewayModelRoute{Provider: database.AIProvider{Type: database.AIProviderTypeOpenaiCompat}},
|
|
}
|
|
|
|
require.Equal(t, outcome.modelErr == nil, gen.generate(ctx, t, db, svc, resolved))
|
|
if outcome.createErr != nil {
|
|
require.Empty(t, runs)
|
|
return
|
|
}
|
|
require.NotEmpty(t, runs)
|
|
for _, run := range runs {
|
|
require.Equal(t, chatdebug.RunContext{
|
|
RunID: runID,
|
|
ChatID: chat.ID,
|
|
TriggerMessageID: gen.trigger,
|
|
HistoryTipMessageID: gen.historyTip,
|
|
Provider: gen.provider,
|
|
Model: gen.model,
|
|
}, *run)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestPrepareManualTitleDebugRunCreateFailure(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
db := dbmock.NewMockStore(gomock.NewController(t))
|
|
db.EXPECT().InsertChatDebugRun(gomock.Any(), gomock.Any()).
|
|
Return(database.ChatDebugRun{}, xerrors.New("insert failed")).Times(1)
|
|
|
|
ctx, finish := prepareManualTitleDebugRun(testutil.Context(t, testutil.WaitLong),
|
|
chatdebug.NewService(db, testutil.Logger(t), nil), database.Chat{ID: uuid.New()}, resolvedModelCall{}, nil)
|
|
_, ok := chatdebug.RunFromContext(ctx)
|
|
require.False(t, ok)
|
|
// The mock expects no finalize calls.
|
|
finish(nil)
|
|
}
|