diff --git a/coderd/database/lock.go b/coderd/database/lock.go index ca824f69154..a2a94c426c9 100644 --- a/coderd/database/lock.go +++ b/coderd/database/lock.go @@ -44,6 +44,12 @@ func LockIDChatOrganizationSystemPrompt(organizationID uuid.UUID) int64 { return GenLockID("chat_organization_system_prompt:" + organizationID.String()) } +// LockIDChatDebugRunSteps returns the advisory lock ID that serializes +// step numbering within one chat debug run. +func LockIDChatDebugRunSteps(runID uuid.UUID) int64 { + return GenLockID("chat_debug_run_steps:" + runID.String()) +} + // GenLockID generates a unique and consistent lock ID from a given string. func GenLockID(name string) int64 { hash := fnv.New64() diff --git a/coderd/database/querier.go b/coderd/database/querier.go index 3ac0e5ebf65..7d11ed44362 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -1221,6 +1221,11 @@ type sqlcQuerier interface { // finished, the UPDATE returns zero rows, the INSERT gets no source // rows, and sql.ErrNoRows is returned. The UPDATE also serializes // with a concurrent run finalization under READ COMMITTED isolation. + // A zero @step_number numbers the step after the run's highest step. + // The row lock does not make that number unique, because the statement + // snapshot predates the lock wait. Callers hold LockIDChatDebugRunSteps + // from an earlier statement of the same transaction, so the snapshot + // includes every committed step. InsertChatDebugStep(ctx context.Context, arg InsertChatDebugStepParams) (ChatDebugStep, error) InsertChatFile(ctx context.Context, arg InsertChatFileParams) (InsertChatFileRow, error) // Returns the inserted rows in input array order. Ids are allocated before the diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 751fad2fb10..2d30569baeb 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -5834,7 +5834,10 @@ INSERT INTO chat_debug_steps ( SELECT $1::uuid, locked_run.chat_id, - $2::int, + COALESCE( + NULLIF($2::int, 0), + (SELECT COALESCE(MAX(s.step_number), 0) + 1 FROM chat_debug_steps s WHERE s.run_id = $1::uuid) + ), $3::text, $4::text, $5::bigint, @@ -5876,6 +5879,11 @@ type InsertChatDebugStepParams struct { // finished, the UPDATE returns zero rows, the INSERT gets no source // rows, and sql.ErrNoRows is returned. The UPDATE also serializes // with a concurrent run finalization under READ COMMITTED isolation. +// A zero @step_number numbers the step after the run's highest step. +// The row lock does not make that number unique, because the statement +// snapshot predates the lock wait. Callers hold LockIDChatDebugRunSteps +// from an earlier statement of the same transaction, so the snapshot +// includes every committed step. func (q *sqlQuerier) InsertChatDebugStep(ctx context.Context, arg InsertChatDebugStepParams) (ChatDebugStep, error) { row := q.db.QueryRowContext(ctx, insertChatDebugStep, arg.RunID, diff --git a/coderd/database/queries/chatdebug.sql b/coderd/database/queries/chatdebug.sql index 8beb6d630a9..400086e9498 100644 --- a/coderd/database/queries/chatdebug.sql +++ b/coderd/database/queries/chatdebug.sql @@ -73,6 +73,11 @@ RETURNING *; -- finished, the UPDATE returns zero rows, the INSERT gets no source -- rows, and sql.ErrNoRows is returned. The UPDATE also serializes -- with a concurrent run finalization under READ COMMITTED isolation. +-- A zero @step_number numbers the step after the run's highest step. +-- The row lock does not make that number unique, because the statement +-- snapshot predates the lock wait. Callers hold LockIDChatDebugRunSteps +-- from an earlier statement of the same transaction, so the snapshot +-- includes every committed step. WITH locked_run AS ( UPDATE chat_debug_runs SET updated_at = COALESCE(sqlc.narg('updated_at')::timestamptz, NOW()) @@ -102,7 +107,10 @@ INSERT INTO chat_debug_steps ( SELECT @run_id::uuid, locked_run.chat_id, - @step_number::int, + COALESCE( + NULLIF(@step_number::int, 0), + (SELECT COALESCE(MAX(s.step_number), 0) + 1 FROM chat_debug_steps s WHERE s.run_id = @run_id::uuid) + ), @operation::text, @status::text, sqlc.narg('history_tip_message_id')::bigint, diff --git a/coderd/x/chatd/chatdebug/bench_internal_test.go b/coderd/x/chatd/chatdebug/bench_internal_test.go index be4176d7a8b..cd29af68c0d 100644 --- a/coderd/x/chatd/chatdebug/bench_internal_test.go +++ b/coderd/x/chatd/chatdebug/bench_internal_test.go @@ -61,12 +61,12 @@ func (noopStore) UpdateChatDebugStep( }, nil } -// GetChatDebugStepsByRunID isn't on the hot path these benchmarks -// exercise (step retry-collision handling), but overriding it avoids -// a nil-dereference panic if a future benchmark configuration change -// reaches it through the embedded nil database.Store. -func (noopStore) GetChatDebugStepsByRunID(context.Context, uuid.UUID) ([]database.ChatDebugStep, error) { - return nil, nil +func (s noopStore) InTx(fn func(database.Store) error, _ *database.TxOptions) error { + return fn(s) +} + +func (noopStore) AcquireLock(context.Context, int64) error { + return nil } var _ database.Store = noopStore{} diff --git a/coderd/x/chatd/chatdebug/model_internal_test.go b/coderd/x/chatd/chatdebug/model_internal_test.go index e56abac903c..635d5845cd1 100644 --- a/coderd/x/chatd/chatdebug/model_internal_test.go +++ b/coderd/x/chatd/chatdebug/model_internal_test.go @@ -40,12 +40,11 @@ func expectDebugLoggingEnabled( db.EXPECT().GetUserChatDebugLoggingEnabled(gomock.Any(), ownerID).Return(true, nil) } -func expectCreateStepNumberWithRequestValidity( +func expectCreateStepWithRequestValidity( t *testing.T, db *dbmock.MockStore, runID uuid.UUID, chatID uuid.UUID, - stepNumber int32, op Operation, normalizedRequestValid bool, ) uuid.UUID { @@ -53,50 +52,31 @@ func expectCreateStepNumberWithRequestValidity( stepID := uuid.New() + db.EXPECT().InTx(gomock.Any(), gomock.Any()).DoAndReturn( + func(f func(database.Store) error, _ *database.TxOptions) error { return f(db) }) + db.EXPECT().AcquireLock(gomock.Any(), database.LockIDChatDebugRunSteps(runID)).Return(nil) db.EXPECT(). InsertChatDebugStep(gomock.Any(), gomock.AssignableToTypeOf(database.InsertChatDebugStepParams{})). DoAndReturn(func(_ context.Context, params database.InsertChatDebugStepParams) (database.ChatDebugStep, error) { require.Equal(t, runID, params.RunID) require.Equal(t, chatID, params.ChatID) - require.Equal(t, stepNumber, params.StepNumber) + require.Zero(t, params.StepNumber, "the database numbers the step") require.Equal(t, string(op), params.Operation) require.Equal(t, string(StatusInProgress), params.Status) require.Equal(t, normalizedRequestValid, params.NormalizedRequest.Valid) return database.ChatDebugStep{ - ID: stepID, - RunID: runID, - ChatID: chatID, - StepNumber: params.StepNumber, - Operation: params.Operation, - Status: params.Status, + ID: stepID, + RunID: runID, + ChatID: chatID, + Operation: params.Operation, + Status: params.Status, }, nil }) return stepID } -func expectCreateStepNumber( - t *testing.T, - db *dbmock.MockStore, - runID uuid.UUID, - chatID uuid.UUID, - stepNumber int32, - op Operation, -) uuid.UUID { - t.Helper() - - return expectCreateStepNumberWithRequestValidity( - t, - db, - runID, - chatID, - stepNumber, - op, - true, - ) -} - func expectCreateStep( t *testing.T, db *dbmock.MockStore, @@ -106,7 +86,7 @@ func expectCreateStep( ) uuid.UUID { t.Helper() - return expectCreateStepNumber(t, db, runID, chatID, 1, op) + return expectCreateStepWithRequestValidity(t, db, runID, chatID, op, true) } func expectUpdateStep( diff --git a/coderd/x/chatd/chatdebug/recorder.go b/coderd/x/chatd/chatdebug/recorder.go index c8b07ff50c3..1a6909245ff 100644 --- a/coderd/x/chatd/chatdebug/recorder.go +++ b/coderd/x/chatd/chatdebug/recorder.go @@ -237,11 +237,9 @@ func beginStep( } } - stepNum := nextStepNumber(rc.RunID) step, err := svc.CreateStep(ctx, CreateStepParams{ RunID: rc.RunID, ChatID: chatID, - StepNumber: stepNum, Operation: op, Status: StatusInProgress, HistoryTipMessageID: rc.HistoryTipMessageID, @@ -257,8 +255,6 @@ func beginStep( return nil, ctx } - syncStepCounter(rc.RunID, step.StepNumber) - sc := &StepContext{ StepID: step.ID, RunID: rc.RunID, diff --git a/coderd/x/chatd/chatdebug/recorder_internal_test.go b/coderd/x/chatd/chatdebug/recorder_internal_test.go index 2dbbe116b6a..ba6befd3d46 100644 --- a/coderd/x/chatd/chatdebug/recorder_internal_test.go +++ b/coderd/x/chatd/chatdebug/recorder_internal_test.go @@ -152,7 +152,7 @@ func TestBeginStep_FallsBackToRunChatID(t *testing.T) { runChatID := uuid.New() ownerID := uuid.New() expectDebugLoggingEnabled(t, db, ownerID) - expectCreateStepNumberWithRequestValidity(t, db, runID, runChatID, 1, OperationGenerate, false) + expectCreateStepWithRequestValidity(t, db, runID, runChatID, OperationGenerate, false) ctx := ContextWithRun(context.Background(), &RunContext{RunID: runID, ChatID: runChatID}) svc := NewService(db, testutil.Logger(t), nil) diff --git a/coderd/x/chatd/chatdebug/reuse_step_internal_test.go b/coderd/x/chatd/chatdebug/reuse_step_internal_test.go index 5feb1ac6224..90319c07a70 100644 --- a/coderd/x/chatd/chatdebug/reuse_step_internal_test.go +++ b/coderd/x/chatd/chatdebug/reuse_step_internal_test.go @@ -26,15 +26,7 @@ func TestBeginStepReuseStep(t *testing.T) { ctrl := gomock.NewController(t) db := dbmock.NewMockStore(ctrl) expectDebugLoggingEnabled(t, db, ownerID) - expectCreateStepNumberWithRequestValidity( - t, - db, - runID, - chatID, - 1, - OperationStream, - false, - ) + expectCreateStepWithRequestValidity(t, db, runID, chatID, OperationStream, false) expectDebugLoggingEnabled(t, db, ownerID) svc := NewService(db, testutil.Logger(t), nil) @@ -67,25 +59,9 @@ func TestBeginStepReuseStep(t *testing.T) { ctrl := gomock.NewController(t) db := dbmock.NewMockStore(ctrl) expectDebugLoggingEnabled(t, db, ownerID) - expectCreateStepNumberWithRequestValidity( - t, - db, - runID, - chatID, - 1, - OperationStream, - false, - ) + expectCreateStepWithRequestValidity(t, db, runID, chatID, OperationStream, false) expectDebugLoggingEnabled(t, db, ownerID) - expectCreateStepNumberWithRequestValidity( - t, - db, - runID, - chatID, - 2, - OperationStream, - false, - ) + expectCreateStepWithRequestValidity(t, db, runID, chatID, OperationStream, false) svc := NewService(db, testutil.Logger(t), nil) ctx := ContextWithRun(context.Background(), &RunContext{RunID: runID, ChatID: chatID}) diff --git a/coderd/x/chatd/chatdebug/service.go b/coderd/x/chatd/chatdebug/service.go index e6dc0555c30..1ef47f028bf 100644 --- a/coderd/x/chatd/chatdebug/service.go +++ b/coderd/x/chatd/chatdebug/service.go @@ -73,7 +73,6 @@ type UpdateRunParams struct { type CreateStepParams struct { RunID uuid.UUID ChatID uuid.UUID - StepNumber int32 Operation Operation Status Status HistoryTipMessageID int64 @@ -341,7 +340,7 @@ func (s *Service) CreateStep( now := s.clock.Now() insert := database.InsertChatDebugStepParams{ RunID: params.RunID, - StepNumber: params.StepNumber, + StepNumber: 0, // Zero lets the database number the step. Operation: string(params.Operation), Status: string(params.Status), HistoryTipMessageID: nullInt64(params.HistoryTipMessageID), @@ -358,52 +357,34 @@ func (s *Service) CreateStep( ChatID: params.ChatID, } - // Cap retry attempts to prevent infinite loops under - // pathological concurrency. Each iteration performs two DB - // round-trips (insert + list), so 10 retries is generous. - const maxCreateStepRetries = 10 - - for range maxCreateStepRetries { - if err := ctx.Err(); err != nil { - return database.ChatDebugStep{}, err + // The insert numbers the step from its statement snapshot, which it + // takes before it waits on the run row. Holding the run's step lock + // from an earlier statement makes that snapshot include every step + // that the previous holder committed. + var step database.ChatDebugStep + err := s.db.InTx(func(tx database.Store) error { + if err := tx.AcquireLock(chatdContext(ctx), database.LockIDChatDebugRunSteps(params.RunID)); err != nil { + return xerrors.Errorf("lock debug run steps: %w", err) } - - step, err := s.db.InsertChatDebugStep(chatdContext(ctx), insert) - if err == nil { - // The INSERT CTE atomically bumps the parent run's - // updated_at, so no separate touch call is needed. - s.publishEvent(ctx, step.ChatID, EventKindStepUpdate, step.RunID, step.ID) - return step, nil - } - // The INSERT's locked_run CTE filters on id, chat_id, and - // finished_at IS NULL, so sql.ErrNoRows can mean "run not - // found", "chat_id mismatch", or "already finalized." Look - // the run up to disambiguate instead of conflating - // caller-side data bugs with the legitimate terminal case. - if errors.Is(err, sql.ErrNoRows) { - return database.ChatDebugStep{}, s.classifyMissingRun(ctx, params) - } - if !database.IsUniqueViolation(err, database.UniqueIndexChatDebugStepsRunStep) { - return database.ChatDebugStep{}, err - } - - steps, listErr := s.db.GetChatDebugStepsByRunID(chatdContext(ctx), params.RunID) - if listErr != nil { - return database.ChatDebugStep{}, listErr - } - nextStepNumber := insert.StepNumber + 1 - for _, existing := range steps { - if existing.StepNumber >= nextStepNumber { - nextStepNumber = existing.StepNumber + 1 - } - } - insert.StepNumber = nextStepNumber + var err error + step, err = tx.InsertChatDebugStep(chatdContext(ctx), insert) + return err + }, nil) + // The INSERT's locked_run CTE filters on id, chat_id, and + // finished_at IS NULL, so sql.ErrNoRows can mean "run not + // found", "chat_id mismatch", or "already finalized." Look + // the run up to disambiguate instead of conflating + // caller-side data bugs with the legitimate terminal case. + if errors.Is(err, sql.ErrNoRows) { + return database.ChatDebugStep{}, s.classifyMissingRun(ctx, params) } - - return database.ChatDebugStep{}, xerrors.Errorf( - "chatdebug: failed to create step after %d retries (run %s)", - maxCreateStepRetries, params.RunID, - ) + if err != nil { + return database.ChatDebugStep{}, err + } + // The INSERT CTE atomically bumps the parent run's + // updated_at, so no separate touch call is needed. + s.publishEvent(ctx, step.ChatID, EventKindStepUpdate, step.RunID, step.ID) + return step, nil } // classifyMissingRun disambiguates the sql.ErrNoRows returned by diff --git a/coderd/x/chatd/chatdebug/service_test.go b/coderd/x/chatd/chatdebug/service_test.go index 69a5c557b53..a872933edd1 100644 --- a/coderd/x/chatd/chatdebug/service_test.go +++ b/coderd/x/chatd/chatdebug/service_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/google/uuid" - "github.com/lib/pq" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "golang.org/x/xerrors" @@ -28,6 +27,7 @@ import ( type testFixture struct { ctx context.Context db database.Store + sqlDB *sql.DB svc *chatdebug.Service org database.Organization owner database.User @@ -288,7 +288,6 @@ func TestService_CreateStep(t *testing.T) { step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ RunID: run.ID, ChatID: fixture.chat.ID, - StepNumber: 1, Operation: chatdebug.OperationStream, Status: chatdebug.StatusInProgress, HistoryTipMessageID: historyTipMsg.ID, @@ -312,60 +311,81 @@ func TestService_CreateStep(t *testing.T) { require.Equal(t, step.ID, steps[0].ID) } -func TestService_CreateStep_RetriesDuplicateStepNumbers(t *testing.T) { +func TestService_CreateStep_NumbersStepsPerRun(t *testing.T) { + t.Parallel() + + fixture := newFixture(t) + first := createRun(t, fixture) + second := createRun(t, fixture) + + for _, tc := range []struct { + runID uuid.UUID + want int32 + }{{first.ID, 1}, {second.ID, 1}, {first.ID, 2}} { + step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ + RunID: tc.runID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, + }) + require.NoError(t, err) + require.Equal(t, tc.want, step.StepNumber) + } +} + +// Creates that wait on a locked run all start before any step exists. +// Each must still get its own number, however many of them there are. +func TestService_CreateStep_NumbersConcurrentSteps(t *testing.T) { t.Parallel() fixture := newFixture(t) run := createRun(t, fixture) - first, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, - }) + tx, err := fixture.sqlDB.BeginTx(fixture.ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + _, err = tx.ExecContext(fixture.ctx, "SELECT 1 FROM chat_debug_runs WHERE id = $1 FOR UPDATE", run.ID) require.NoError(t, err) - second, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationGenerate, - Status: chatdebug.StatusInProgress, - }) + const creates = 20 + errs := make(chan error, creates) + for range creates { + go func() { + _, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, + }) + errs <- err + }() + } + // Release the run only after every create waits on a lock. + require.Eventually(t, func() bool { + if len(errs) > 0 { + return true + } + var waiting int + err := fixture.sqlDB.QueryRowContext(fixture.ctx, `SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&waiting) + return err == nil && waiting == creates + }, testutil.WaitShort, testutil.IntervalFast) + require.NoError(t, tx.Commit()) + + for range creates { + require.NoError(t, testutil.RequireReceive(fixture.ctx, t, errs)) + } + steps, err := fixture.db.GetChatDebugStepsByRunID(fixture.ctx, run.ID) require.NoError(t, err) - require.EqualValues(t, 1, first.StepNumber) - require.EqualValues(t, 2, second.StepNumber) -} - -func TestService_CreateStep_ListRetryErrorWins(t *testing.T) { - t.Parallel() - - ctrl := gomock.NewController(t) - db := dbmock.NewMockStore(ctrl) - svc := chatdebug.NewService(db, testutil.Logger(t), nil) - runID := uuid.New() - chatID := uuid.New() - listErr := xerrors.New("list chat debug steps") - - db.EXPECT().InsertChatDebugStep( - gomock.Any(), - gomock.AssignableToTypeOf(database.InsertChatDebugStepParams{}), - ).Return(database.ChatDebugStep{}, &pq.Error{ - Code: pq.ErrorCode("23505"), - Constraint: string(database.UniqueIndexChatDebugStepsRunStep), - }) - db.EXPECT().GetChatDebugStepsByRunID(gomock.Any(), runID).Return(nil, listErr) - - _, err := svc.CreateStep(context.Background(), chatdebug.CreateStepParams{ - RunID: runID, - ChatID: chatID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, - }) - require.ErrorIs(t, err, listErr) + got := make([]int32, 0, len(steps)) + for _, step := range steps { + got = append(got, step.StepNumber) + } + want := make([]int32, 0, creates) + for n := range int32(creates) { + want = append(want, n+1) + } + require.Equal(t, want, got) } func TestService_CreateStep_RejectsFinalizedRun(t *testing.T) { @@ -385,11 +405,10 @@ func TestService_CreateStep_RejectsFinalizedRun(t *testing.T) { // Creating a step on the finalized run must fail. _, err = fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.Error(t, err) require.ErrorContains(t, err, "already finalized") @@ -404,11 +423,10 @@ func TestService_CreateStep_MissingRunReportsNotFound(t *testing.T) { // returns zero rows, which must be classified as "not found" // instead of being conflated with the already-finalized case. _, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: uuid.New(), - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: uuid.New(), + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.Error(t, err) require.ErrorContains(t, err, "not found", @@ -430,11 +448,10 @@ func TestService_CreateStep_ChatIDMismatchReportsNotFound(t *testing.T) { fixture.owner.ID, fixture.model.ID) _, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: otherChat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: otherChat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.Error(t, err) require.ErrorContains(t, err, "not found", @@ -448,11 +465,10 @@ func TestService_UpdateStep(t *testing.T) { fixture := newFixture(t) run := createRun(t, fixture) step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) @@ -504,11 +520,10 @@ func TestService_UpdateStep_AutoFillsFinishedAtOnTerminalStatus(t *testing.T) { fixture := newFixture(t) run := createRun(t, fixture) step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) @@ -536,11 +551,10 @@ func TestService_UpdateStep_TypedNilAttemptsPreserveExistingValue(t *testing.T) fixture := newFixture(t) run := createRun(t, fixture) step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationStream, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationStream, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) @@ -574,11 +588,10 @@ func TestService_DeleteByChatID(t *testing.T) { fixture := newFixture(t) run := createRun(t, fixture) _, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: run.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationGenerate, - Status: chatdebug.StatusInProgress, + RunID: run.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationGenerate, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) @@ -611,11 +624,10 @@ func TestService_DeleteAfterMessageID(t *testing.T) { runKeep := createRun(t, fixture) stepKeep, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: runKeep.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationGenerate, - Status: chatdebug.StatusInProgress, + RunID: runKeep.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationGenerate, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) _, err = fixture.svc.UpdateStep(fixture.ctx, chatdebug.UpdateStepParams{ @@ -627,11 +639,10 @@ func TestService_DeleteAfterMessageID(t *testing.T) { runDelete := createRun(t, fixture) stepDelete, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: runDelete.ID, - ChatID: fixture.chat.ID, - StepNumber: 1, - Operation: chatdebug.OperationGenerate, - Status: chatdebug.StatusInProgress, + RunID: runDelete.ID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationGenerate, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) _, err = fixture.svc.UpdateStep(fixture.ctx, chatdebug.UpdateStepParams{ @@ -990,13 +1001,14 @@ func newFixture(t *testing.T) testFixture { t.Helper() ctx := testutil.Context(t, testutil.WaitLong) - db, _ := dbtestutil.NewDB(t) + db, _, sqlDB := dbtestutil.NewDBWithSQLDB(t) org, owner, chat, model := seedChat(t, db) prov, err := db.GetAIProviderByID(ctx, model.AIProviderID.UUID) require.NoError(t, err) return testFixture{ ctx: ctx, db: db, + sqlDB: sqlDB, svc: chatdebug.NewService(db, testutil.Logger(t), nil), org: org, owner: owner, diff --git a/coderd/x/chatd/chatdebug/summary_test.go b/coderd/x/chatd/chatdebug/summary_test.go index fc329ae0a95..d3c3c84f9d9 100644 --- a/coderd/x/chatd/chatdebug/summary_test.go +++ b/coderd/x/chatd/chatdebug/summary_test.go @@ -183,7 +183,7 @@ func TestService_AggregateRunSummary(t *testing.T) { }) require.NoError(t, err) - step2 := createTestStepN(t, fixture, run.ID, 2) + step2 := createTestStep(t, fixture, run.ID) _, err = fixture.svc.UpdateStep(fixture.ctx, chatdebug.UpdateStepParams{ ID: step2.ID, ChatID: fixture.chat.ID, @@ -259,7 +259,7 @@ func TestService_AggregateRunSummary(t *testing.T) { step1 := createTestStep(t, fixture, run.ID) updateTestStepWithUsage(t, fixture, step1.ID, 10, 5, 2, 3) - step2 := createTestStepN(t, fixture, run.ID, 2) + step2 := createTestStep(t, fixture, run.ID) updateTestStepWithUsage(t, fixture, step2.ID, 15, 7, 1, 4) got, err := fixture.svc.AggregateRunSummary(fixture.ctx, run.ID, nil) @@ -281,7 +281,7 @@ func TestService_AggregateRunSummary(t *testing.T) { updateTestStepWithUsage(t, fixture, step1.ID, 10, 5, 0, 0) // Step without usage (just complete it, no usage). - step2 := createTestStepN(t, fixture, run.ID, 2) + step2 := createTestStep(t, fixture, run.ID) _, err := fixture.svc.UpdateStep(fixture.ctx, chatdebug.UpdateStepParams{ ID: step2.ID, ChatID: fixture.chat.ID, @@ -323,7 +323,7 @@ func TestService_AggregateRunSummary(t *testing.T) { step1 := createTestStep(t, fixture, run.ID) updateTestStepWithFullUsage(t, fixture, step1.ID, 10, 5, 20, 0, 0) - step2 := createTestStepN(t, fixture, run.ID, 2) + step2 := createTestStep(t, fixture, run.ID) updateTestStepWithFullUsage(t, fixture, step2.ID, 15, 7, 30, 0, 0) got, err := fixture.svc.AggregateRunSummary(fixture.ctx, run.ID, nil) @@ -364,7 +364,7 @@ func TestService_AggregateRunSummary(t *testing.T) { // expected). Write directly through the store so the jsonb // cast succeeds while the Go unmarshal fails, exercising the // "skipping malformed step usage JSON" log-and-continue path. - step2 := createTestStepN(t, fixture, run.ID, 2) + step2 := createTestStep(t, fixture, run.ID) _, err := fixture.db.UpdateChatDebugStep(fixture.ctx, database.UpdateChatDebugStepParams{ ID: step2.ID, ChatID: fixture.chat.ID, @@ -387,31 +387,18 @@ func TestService_AggregateRunSummary(t *testing.T) { }) } -// createTestStep is a thin helper that creates a debug step with -// step number 1 for the given run. +// createTestStep creates the run's next debug step. func createTestStep( t *testing.T, fixture testFixture, runID uuid.UUID, -) database.ChatDebugStep { - t.Helper() - return createTestStepN(t, fixture, runID, 1) -} - -// createTestStepN creates a debug step with the given step number. -func createTestStepN( - t *testing.T, - fixture testFixture, - runID uuid.UUID, - stepNumber int32, ) database.ChatDebugStep { t.Helper() step, err := fixture.svc.CreateStep(fixture.ctx, chatdebug.CreateStepParams{ - RunID: runID, - ChatID: fixture.chat.ID, - StepNumber: stepNumber, - Operation: chatdebug.OperationGenerate, - Status: chatdebug.StatusInProgress, + RunID: runID, + ChatID: fixture.chat.ID, + Operation: chatdebug.OperationGenerate, + Status: chatdebug.StatusInProgress, }) require.NoError(t, err) return step