diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index 94ea859eaf2..7cb41108081 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -2975,14 +2975,6 @@ func (q *querier) FetchVolumesResourceMonitorsUpdatedAfter(ctx context.Context, return q.db.FetchVolumesResourceMonitorsUpdatedAfter(ctx, updatedAt) } -func (q *querier) FinalizeStaleChatDebugRows(ctx context.Context, updatedBefore database.FinalizeStaleChatDebugRowsParams) (database.FinalizeStaleChatDebugRowsRow, error) { - // Background sweep operates across all chats. - if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceChat); err != nil { - return database.FinalizeStaleChatDebugRowsRow{}, err - } - return q.db.FinalizeStaleChatDebugRows(ctx, updatedBefore) -} - func (q *querier) FindMatchingPresetID(ctx context.Context, arg database.FindMatchingPresetIDParams) (uuid.UUID, error) { _, err := q.GetTemplateVersionByID(ctx, arg.TemplateVersionID) if err != nil { diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index bc72054fa34..29c2b31c243 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -973,16 +973,6 @@ func (s *MethodTestSuite) TestChats() { dbm.EXPECT().DeleteChatDebugDataByChatID(gomock.Any(), arg).Return(int64(1), nil).AnyTimes() check.Args(arg).Asserts(chat, policy.ActionUpdate).Returns(int64(1)) })) - s.Run("FinalizeStaleChatDebugRows", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { - now := dbtime.Now() - arg := database.FinalizeStaleChatDebugRowsParams{ - Now: now, - UpdatedBefore: now.Add(-5 * time.Minute), - } - row := database.FinalizeStaleChatDebugRowsRow{RunsFinalized: 1, StepsFinalized: 2} - dbm.EXPECT().FinalizeStaleChatDebugRows(gomock.Any(), arg).Return(row, nil).AnyTimes() - check.Args(arg).Asserts(rbac.ResourceChat, policy.ActionUpdate).Returns(row) - })) s.Run("GetChatDebugLoggingAllowUsers", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { dbm.EXPECT().GetChatDebugLoggingAllowUsers(gomock.Any()).Return(true, nil).AnyTimes() check.Args().Asserts().Returns(true) diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 670537ff4f8..41ebc3d7e7b 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -1152,14 +1152,6 @@ func (m queryMetricsStore) FetchVolumesResourceMonitorsUpdatedAfter(ctx context. return r0, r1 } -func (m queryMetricsStore) FinalizeStaleChatDebugRows(ctx context.Context, updatedBefore database.FinalizeStaleChatDebugRowsParams) (database.FinalizeStaleChatDebugRowsRow, error) { - start := time.Now() - r0, r1 := m.s.FinalizeStaleChatDebugRows(ctx, updatedBefore) - m.queryLatencies.WithLabelValues("FinalizeStaleChatDebugRows").Observe(time.Since(start).Seconds()) - m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "FinalizeStaleChatDebugRows").Inc() - return r0, r1 -} - func (m queryMetricsStore) FindMatchingPresetID(ctx context.Context, arg database.FindMatchingPresetIDParams) (uuid.UUID, error) { start := time.Now() r0, r1 := m.s.FindMatchingPresetID(ctx, arg) diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index e43794b67cb..4c2a1c99a10 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -2004,21 +2004,6 @@ func (mr *MockStoreMockRecorder) FetchVolumesResourceMonitorsUpdatedAfter(ctx, u return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FetchVolumesResourceMonitorsUpdatedAfter", reflect.TypeOf((*MockStore)(nil).FetchVolumesResourceMonitorsUpdatedAfter), ctx, updatedAt) } -// FinalizeStaleChatDebugRows mocks base method. -func (m *MockStore) FinalizeStaleChatDebugRows(ctx context.Context, arg database.FinalizeStaleChatDebugRowsParams) (database.FinalizeStaleChatDebugRowsRow, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FinalizeStaleChatDebugRows", ctx, arg) - ret0, _ := ret[0].(database.FinalizeStaleChatDebugRowsRow) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// FinalizeStaleChatDebugRows indicates an expected call of FinalizeStaleChatDebugRows. -func (mr *MockStoreMockRecorder) FinalizeStaleChatDebugRows(ctx, arg any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FinalizeStaleChatDebugRows", reflect.TypeOf((*MockStore)(nil).FinalizeStaleChatDebugRows), ctx, arg) -} - // FindMatchingPresetID mocks base method. func (m *MockStore) FindMatchingPresetID(ctx context.Context, arg database.FindMatchingPresetIDParams) (uuid.UUID, error) { m.ctrl.T.Helper() diff --git a/coderd/database/querier.go b/coderd/database/querier.go index be578e07a07..3ac0e5ebf65 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -305,19 +305,6 @@ type sqlcQuerier interface { FetchNewMessageMetadata(ctx context.Context, arg FetchNewMessageMetadataParams) (FetchNewMessageMetadataRow, error) FetchVolumesResourceMonitorsByAgentID(ctx context.Context, agentID uuid.UUID) ([]WorkspaceAgentVolumeResourceMonitor, error) FetchVolumesResourceMonitorsUpdatedAfter(ctx context.Context, updatedAt time.Time) ([]WorkspaceAgentVolumeResourceMonitor, error) - // Marks orphaned in-progress rows as interrupted so they do not stay - // in a non-terminal state forever. The NOT IN list must match the - // terminal statuses defined by ChatDebugStatus in codersdk/chats.go. - // - // The steps CTE also catches steps whose parent run was just finalized - // (via run_id IN), because PostgreSQL data-modifying CTEs share the - // same snapshot and cannot see each other's row updates. Without this, - // a step with a recent updated_at would survive its run's finalization - // and remain in 'in_progress' state permanently. - // - // @now is the caller's clock timestamp so that mock-clock tests stay - // consistent with the @updated_before cutoff. - FinalizeStaleChatDebugRows(ctx context.Context, arg FinalizeStaleChatDebugRowsParams) (FinalizeStaleChatDebugRowsRow, error) // FindMatchingPresetID finds a preset ID that is the largest exact subset of the provided parameters. // It returns the preset ID if a match is found, or NULL if no match is found. // The query finds presets where all preset parameters are present in the provided parameters, diff --git a/coderd/database/querier_test.go b/coderd/database/querier_test.go index fc9177e2a21..f0a8cfad829 100644 --- a/coderd/database/querier_test.go +++ b/coderd/database/querier_test.go @@ -16717,443 +16717,6 @@ func TestDeleteChatDebugDataAfterMessageIDStepLevelFieldBoundariesAndNulls(t *te require.Len(t, remaining, 4) } -func TestFinalizeStaleChatDebugRows(t *testing.T) { - t.Parallel() - - store, _ := dbtestutil.NewDB(t) - ctx := testutil.Context(t, testutil.WaitMedium) - - org := dbgen.Organization(t, store, database.Organization{}) - user := dbgen.User(t, store, database.User{}) - - providerName := "openai" - modelName := "debug-model-finalize-" + uuid.NewString() - - dbgen.ChatProvider(t, store, database.ChatProvider{ - Provider: providerName, - DisplayName: "Debug Provider", - APIKey: "test-key", - Enabled: true, - CentralApiKeyEnabled: true, - }) - - modelCfg, err := insertChatModelConfigForTest(ctx, t, store, providerName, database.InsertChatModelConfigParams{ - Model: modelName, - DisplayName: "Debug Model", - CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true}, - UpdatedBy: uuid.NullUUID{UUID: user.ID, Valid: true}, - Enabled: true, - IsDefault: true, - ContextLimit: 128000, - CompressionThreshold: 80, - Options: json.RawMessage(`{}`), - }) - require.NoError(t, err) - - chat, err := store.InsertChat(ctx, database.InsertChatParams{ - OrganizationID: org.ID, - Status: database.ChatStatusWaiting, - ClientType: database.ChatClientTypeUi, - OwnerID: user.ID, - LastModelConfigID: modelCfg.ID, - Title: "chat-finalize-" + uuid.NewString(), - }) - require.NoError(t, err) - - // staleTime is well before the threshold so rows stamped with it - // are considered stale. The threshold sits between staleTime and - // NOW(), letting us create rows that are stale-by-age and rows - // that are fresh-by-age in the same test. - staleTime := time.Now().Add(-2 * time.Hour) - staleThreshold := time.Now().Add(-1 * time.Hour) - - // preExistingError is attached to staleStep so we can verify - // that finalization preserves pre-existing error JSON rather - // than clearing or overwriting it. - preExistingError := json.RawMessage(`{"code":"timeout","message":"upstream deadline exceeded"}`) - - // --- staleRun: in_progress run with no finished_at --- should be - // finalized. - staleRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 1, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 1, Valid: true}, - Kind: "chat_turn", - Status: "in_progress", - Provider: sql.NullString{String: providerName, Valid: true}, - Model: sql.NullString{String: modelName, Valid: true}, - UpdatedAt: sql.NullTime{Time: staleTime, Valid: true}, - }) - require.NoError(t, err) - - // staleStep: in_progress step attached to staleRun with a - // pre-existing error JSON payload. - staleStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: staleRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "in_progress", - UpdatedAt: sql.NullTime{Time: staleTime, Valid: true}, - Error: pqtype.NullRawMessage{ - RawMessage: preExistingError, - Valid: true, - }, - }) - require.NoError(t, err) - require.True(t, staleStep.Error.Valid, - "precondition: error must be stored at insertion") - - // --- orphanStep: in_progress step whose run is already completed --- - // Its own updated_at is old, so it should be finalized directly. - // The step must be inserted while the run is still open because - // InsertChatDebugStep requires finished_at IS NULL on the parent - // run (atomic guard against appending steps to finalized runs). - completedRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 2, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 2, Valid: true}, - Kind: "chat_turn", - Status: "completed", - }) - require.NoError(t, err) - - // Insert the step while the run is still open (finished_at IS NULL). - orphanStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: completedRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "in_progress", - UpdatedAt: sql.NullTime{Time: staleTime, Valid: true}, - }) - require.NoError(t, err) - - // Now mark the run as completed with a finished_at timestamp, - // leaving the step orphaned in in_progress state. - _, err = store.UpdateChatDebugRun(ctx, database.UpdateChatDebugRunParams{ - ID: completedRun.ID, - ChatID: completedRun.ChatID, - Status: sql.NullString{String: "completed", Valid: true}, - FinishedAt: sql.NullTime{ - Time: time.Now(), - Valid: true, - }, - Now: time.Now(), - }) - require.NoError(t, err) - - // --- cascadeRun: stale in_progress run with a FRESH step --- - // The run's updated_at is old so the run itself is finalized by - // age. The step's updated_at is recent (default NOW()), so it is - // NOT caught by the age predicate. It must be finalized solely - // via the cascade CTE clause: run_id IN (SELECT id FROM - // finalized_runs). Removing that clause would leave this step - // stuck in 'in_progress'. - cascadeRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 10, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 10, Valid: true}, - Kind: "chat_turn", - Status: "in_progress", - Provider: sql.NullString{String: providerName, Valid: true}, - Model: sql.NullString{String: modelName, Valid: true}, - UpdatedAt: sql.NullTime{Time: staleTime, Valid: true}, - }) - require.NoError(t, err) - - // cascadeStep: recent updated_at (default NOW()), so only the - // cascade path can finalize it. - cascadeStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: cascadeRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "in_progress", - }) - require.NoError(t, err) - - // The InsertChatDebugStep CTE atomically bumps the parent run's - // updated_at to NOW(). Reset it back to staleTime so the run is - // still caught by the age predicate in FinalizeStaleChatDebugRows. - _, err = store.UpdateChatDebugRun(ctx, database.UpdateChatDebugRunParams{ - ID: cascadeRun.ID, - ChatID: chat.ID, - Now: staleTime, - }) - require.NoError(t, err) - - // --- alreadyDone: completed run/step --- should NOT be touched. - doneRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 3, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 3, Valid: true}, - Kind: "chat_turn", - Status: "completed", - }) - require.NoError(t, err) - - // Insert step while run is still open. - doneStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: doneRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "completed", - }) - require.NoError(t, err) - - // Now finalize both run and step. - _, err = store.UpdateChatDebugRun(ctx, database.UpdateChatDebugRunParams{ - ID: doneRun.ID, - ChatID: doneRun.ChatID, - Status: sql.NullString{String: "completed", Valid: true}, - FinishedAt: sql.NullTime{ - Time: time.Now(), - Valid: true, - }, - Now: time.Now(), - }) - require.NoError(t, err) - - _, err = store.UpdateChatDebugStep(ctx, database.UpdateChatDebugStepParams{ - ID: doneStep.ID, - ChatID: chat.ID, - Status: sql.NullString{String: "completed", Valid: true}, - FinishedAt: sql.NullTime{ - Time: time.Now(), - Valid: true, - }, - Now: time.Now(), - }) - require.NoError(t, err) - - // --- errorRun: error run/step --- should NOT be touched either, - // exercising the 'error' branch of the NOT IN clause. - errorRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 4, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 4, Valid: true}, - Kind: "chat_turn", - Status: "error", - }) - require.NoError(t, err) - - // Insert step while run is still open. - errorStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: errorRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "error", - }) - require.NoError(t, err) - - // Now finalize both run and step. - _, err = store.UpdateChatDebugRun(ctx, database.UpdateChatDebugRunParams{ - ID: errorRun.ID, - ChatID: errorRun.ChatID, - Status: sql.NullString{String: "error", Valid: true}, - FinishedAt: sql.NullTime{ - Time: time.Now(), - Valid: true, - }, - Now: time.Now(), - }) - require.NoError(t, err) - - _, err = store.UpdateChatDebugStep(ctx, database.UpdateChatDebugStepParams{ - ID: errorStep.ID, - ChatID: chat.ID, - Status: sql.NullString{String: "error", Valid: true}, - FinishedAt: sql.NullTime{ - Time: time.Now(), - Valid: true, - }, - Now: time.Now(), - }) - require.NoError(t, err) - - // --- freshRun: recent in_progress run with current timestamp --- - // should NOT be finalized because its updated_at is after the - // threshold, exercising the age predicate (not just terminal - // status) as the survival reason. - freshRun, err := store.InsertChatDebugRun(ctx, database.InsertChatDebugRunParams{ - ChatID: chat.ID, - ModelConfigID: uuid.NullUUID{UUID: modelCfg.ID, Valid: true}, - TriggerMessageID: sql.NullInt64{Int64: 20, Valid: true}, - HistoryTipMessageID: sql.NullInt64{Int64: 20, Valid: true}, - Kind: "chat_turn", - Status: "in_progress", - Provider: sql.NullString{String: providerName, Valid: true}, - Model: sql.NullString{String: modelName, Valid: true}, - // UpdatedAt defaults to NOW(), which is after staleThreshold. - }) - require.NoError(t, err) - - freshStep, err := store.InsertChatDebugStep(ctx, database.InsertChatDebugStepParams{ - RunID: freshRun.ID, - ChatID: chat.ID, - StepNumber: 1, - Operation: "stream", - Status: "in_progress", - // UpdatedAt defaults to NOW(). - }) - require.NoError(t, err) - - // --- Execute the finalization sweep. --- - // Capture the @now timestamp so we can verify finalized rows - // received exactly this value for updated_at and finished_at. - nowParam := time.Now().Truncate(time.Microsecond) - result, err := store.FinalizeStaleChatDebugRows(ctx, database.FinalizeStaleChatDebugRowsParams{ - Now: nowParam, - UpdatedBefore: staleThreshold, - }) - require.NoError(t, err) - - // staleRun + cascadeRun were finalized; completedRun and doneRun - // were already terminal, and freshRun survives because its - // updated_at is after the threshold — so only 2 runs are expected. - assert.EqualValues(t, 2, result.RunsFinalized, - "stale + cascade in_progress runs should be finalized") - // staleStep (age), orphanStep (age), cascadeStep (cascade only) - // should all be finalized. - assert.EqualValues(t, 3, result.StepsFinalized, - "stale step + orphan step + cascade step should all be finalized") - - // Verify the stale run was set to interrupted with correct - // timestamps matching the @now parameter. - updatedStaleRun, err := store.GetChatDebugRunByID(ctx, staleRun.ID) - require.NoError(t, err) - assert.Equal(t, "interrupted", updatedStaleRun.Status) - assert.True(t, updatedStaleRun.FinishedAt.Valid, - "finalized run should have a finished_at timestamp") - assert.WithinDuration(t, nowParam, updatedStaleRun.FinishedAt.Time, time.Microsecond, - "finished_at should match the @now parameter") - assert.WithinDuration(t, nowParam, updatedStaleRun.UpdatedAt, time.Microsecond, - "updated_at should match the @now parameter") - - // Verify the stale step was set to interrupted and its - // pre-existing error JSON was preserved. - staleSteps, err := store.GetChatDebugStepsByRunID(ctx, staleRun.ID) - require.NoError(t, err) - require.Len(t, staleSteps, 1) - assert.Equal(t, staleStep.ID, staleSteps[0].ID) - assert.Equal(t, "interrupted", staleSteps[0].Status) - assert.True(t, staleSteps[0].FinishedAt.Valid, - "finalized step should have a finished_at timestamp") - assert.WithinDuration(t, nowParam, staleSteps[0].FinishedAt.Time, time.Microsecond, - "step finished_at should match the @now parameter") - assert.WithinDuration(t, nowParam, staleSteps[0].UpdatedAt, time.Microsecond, - "step updated_at should match the @now parameter") - // The error JSON that was set at insertion time must survive - // finalization. The query does not touch the error column, so - // this proves the JSONB payload is preserved. - assert.True(t, staleSteps[0].Error.Valid, - "pre-existing error JSON must be preserved after finalization") - assert.JSONEq(t, string(preExistingError), string(staleSteps[0].Error.RawMessage), - "error JSON content must match the value set at insertion") - - // Verify the orphan step was also finalized with correct timestamps. - orphanSteps, err := store.GetChatDebugStepsByRunID(ctx, completedRun.ID) - require.NoError(t, err) - require.Len(t, orphanSteps, 1) - assert.Equal(t, orphanStep.ID, orphanSteps[0].ID) - assert.Equal(t, "interrupted", orphanSteps[0].Status) - assert.True(t, orphanSteps[0].FinishedAt.Valid, - "orphan step should have a finished_at timestamp") - assert.WithinDuration(t, nowParam, orphanSteps[0].FinishedAt.Time, time.Microsecond, - "orphan step finished_at should match the @now parameter") - assert.WithinDuration(t, nowParam, orphanSteps[0].UpdatedAt, time.Microsecond, - "orphan step updated_at should match the @now parameter") - // The orphan step had no error set; verify it remains null. - assert.False(t, orphanSteps[0].Error.Valid, - "step without pre-existing error should remain null after finalization") - - // Verify the cascade run was finalized with correct timestamps. - updatedCascadeRun, err := store.GetChatDebugRunByID(ctx, cascadeRun.ID) - require.NoError(t, err) - assert.Equal(t, "interrupted", updatedCascadeRun.Status) - assert.True(t, updatedCascadeRun.FinishedAt.Valid, - "cascade run should have a finished_at timestamp") - assert.WithinDuration(t, nowParam, updatedCascadeRun.FinishedAt.Time, time.Microsecond, - "cascade run finished_at should match the @now parameter") - assert.WithinDuration(t, nowParam, updatedCascadeRun.UpdatedAt, time.Microsecond, - "cascade run updated_at should match the @now parameter") - - // Verify the cascade step was finalized despite its recent - // updated_at, proving the cascade CTE clause is required. - cascadeSteps, err := store.GetChatDebugStepsByRunID(ctx, cascadeRun.ID) - require.NoError(t, err) - require.Len(t, cascadeSteps, 1) - assert.Equal(t, cascadeStep.ID, cascadeSteps[0].ID) - assert.Equal(t, "interrupted", cascadeSteps[0].Status, - "fresh step should be finalized via cascade, not age") - assert.True(t, cascadeSteps[0].FinishedAt.Valid, - "cascade step should have a finished_at timestamp") - assert.WithinDuration(t, nowParam, cascadeSteps[0].FinishedAt.Time, time.Microsecond, - "cascade step finished_at should match the @now parameter") - assert.WithinDuration(t, nowParam, cascadeSteps[0].UpdatedAt, time.Microsecond, - "cascade step updated_at should match the @now parameter") - // The cascade step also had no error set. - assert.False(t, cascadeSteps[0].Error.Valid, - "cascade step without pre-existing error should remain null") - - // Verify the completed run/step are untouched. - unchangedRun, err := store.GetChatDebugRunByID(ctx, doneRun.ID) - require.NoError(t, err) - assert.Equal(t, "completed", unchangedRun.Status) - - doneSteps, err := store.GetChatDebugStepsByRunID(ctx, doneRun.ID) - require.NoError(t, err) - require.Len(t, doneSteps, 1) - assert.Equal(t, "completed", doneSteps[0].Status) - - // Verify the error run/step are untouched. - unchangedErrorRun, err := store.GetChatDebugRunByID(ctx, errorRun.ID) - require.NoError(t, err) - assert.Equal(t, "error", unchangedErrorRun.Status) - - errorSteps, err := store.GetChatDebugStepsByRunID(ctx, errorRun.ID) - require.NoError(t, err) - require.Len(t, errorSteps, 1) - assert.Equal(t, "error", errorSteps[0].Status) - - // Verify the fresh in_progress run survived due to recency, - // not terminal status — its updated_at is after the threshold. - unchangedFreshRun, err := store.GetChatDebugRunByID(ctx, freshRun.ID) - require.NoError(t, err) - assert.Equal(t, "in_progress", unchangedFreshRun.Status, - "fresh in_progress run must survive due to recency") - assert.False(t, unchangedFreshRun.FinishedAt.Valid, - "fresh run should not have a finished_at timestamp") - - freshSteps, err := store.GetChatDebugStepsByRunID(ctx, freshRun.ID) - require.NoError(t, err) - require.Len(t, freshSteps, 1) - assert.Equal(t, freshStep.ID, freshSteps[0].ID) - assert.Equal(t, "in_progress", freshSteps[0].Status, - "fresh in_progress step must survive due to recency") - assert.False(t, freshSteps[0].FinishedAt.Valid, - "fresh step should not have a finished_at timestamp") - - // A second sweep should be a no-op. - result2, err := store.FinalizeStaleChatDebugRows(ctx, database.FinalizeStaleChatDebugRowsParams{ - Now: time.Now(), - UpdatedBefore: staleThreshold, - }) - require.NoError(t, err) - assert.EqualValues(t, 0, result2.RunsFinalized, - "second sweep should find nothing to finalize") - assert.EqualValues(t, 0, result2.StepsFinalized, - "second sweep should find nothing to finalize") -} - func TestChatDebugSQLGuards(t *testing.T) { t.Parallel() diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 85e25f3ed15..751fad2fb10 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -5580,65 +5580,6 @@ func (q *sqlQuerier) DeleteOldChatDebugRuns(ctx context.Context, arg DeleteOldCh return result.RowsAffected() } -const finalizeStaleChatDebugRows = `-- name: FinalizeStaleChatDebugRows :one -WITH finalized_runs AS ( - UPDATE chat_debug_runs - SET - status = 'interrupted', - updated_at = $1::timestamptz, - finished_at = $1::timestamptz - WHERE updated_at < $2::timestamptz - AND finished_at IS NULL - AND status NOT IN ('completed', 'error', 'interrupted') - RETURNING id -), finalized_steps AS ( - UPDATE chat_debug_steps - SET - status = 'interrupted', - updated_at = $1::timestamptz, - finished_at = $1::timestamptz - WHERE ( - updated_at < $2::timestamptz - OR run_id IN (SELECT id FROM finalized_runs) - ) - AND finished_at IS NULL - AND status NOT IN ('completed', 'error', 'interrupted') - RETURNING 1 -) -SELECT - (SELECT COUNT(*) FROM finalized_runs)::bigint AS runs_finalized, - (SELECT COUNT(*) FROM finalized_steps)::bigint AS steps_finalized -` - -type FinalizeStaleChatDebugRowsParams struct { - Now time.Time `db:"now" json:"now"` - UpdatedBefore time.Time `db:"updated_before" json:"updated_before"` -} - -type FinalizeStaleChatDebugRowsRow struct { - RunsFinalized int64 `db:"runs_finalized" json:"runs_finalized"` - StepsFinalized int64 `db:"steps_finalized" json:"steps_finalized"` -} - -// Marks orphaned in-progress rows as interrupted so they do not stay -// in a non-terminal state forever. The NOT IN list must match the -// terminal statuses defined by ChatDebugStatus in codersdk/chats.go. -// -// The steps CTE also catches steps whose parent run was just finalized -// (via run_id IN), because PostgreSQL data-modifying CTEs share the -// same snapshot and cannot see each other's row updates. Without this, -// a step with a recent updated_at would survive its run's finalization -// and remain in 'in_progress' state permanently. -// -// @now is the caller's clock timestamp so that mock-clock tests stay -// consistent with the @updated_before cutoff. -func (q *sqlQuerier) FinalizeStaleChatDebugRows(ctx context.Context, arg FinalizeStaleChatDebugRowsParams) (FinalizeStaleChatDebugRowsRow, error) { - row := q.db.QueryRowContext(ctx, finalizeStaleChatDebugRows, arg.Now, arg.UpdatedBefore) - var i FinalizeStaleChatDebugRowsRow - err := row.Scan(&i.RunsFinalized, &i.StepsFinalized) - return i, err -} - const getChatDebugRunByID = `-- name: GetChatDebugRunByID :one SELECT id, chat_id, root_chat_id, parent_chat_id, model_config_id, trigger_message_id, history_tip_message_id, kind, status, provider, model, summary, started_at, updated_at, finished_at FROM chat_debug_runs diff --git a/coderd/database/queries/chatdebug.sql b/coderd/database/queries/chatdebug.sql index eff4f9b7323..8beb6d630a9 100644 --- a/coderd/database/queries/chatdebug.sql +++ b/coderd/database/queries/chatdebug.sql @@ -219,44 +219,3 @@ DELETE FROM chat_debug_runs USING deletable WHERE chat_debug_runs.id = deletable.id AND chat_debug_runs.chat_id = deletable.chat_id; - --- name: FinalizeStaleChatDebugRows :one --- Marks orphaned in-progress rows as interrupted so they do not stay --- in a non-terminal state forever. The NOT IN list must match the --- terminal statuses defined by ChatDebugStatus in codersdk/chats.go. --- --- The steps CTE also catches steps whose parent run was just finalized --- (via run_id IN), because PostgreSQL data-modifying CTEs share the --- same snapshot and cannot see each other's row updates. Without this, --- a step with a recent updated_at would survive its run's finalization --- and remain in 'in_progress' state permanently. --- --- @now is the caller's clock timestamp so that mock-clock tests stay --- consistent with the @updated_before cutoff. -WITH finalized_runs AS ( - UPDATE chat_debug_runs - SET - status = 'interrupted', - updated_at = @now::timestamptz, - finished_at = @now::timestamptz - WHERE updated_at < @updated_before::timestamptz - AND finished_at IS NULL - AND status NOT IN ('completed', 'error', 'interrupted') - RETURNING id -), finalized_steps AS ( - UPDATE chat_debug_steps - SET - status = 'interrupted', - updated_at = @now::timestamptz, - finished_at = @now::timestamptz - WHERE ( - updated_at < @updated_before::timestamptz - OR run_id IN (SELECT id FROM finalized_runs) - ) - AND finished_at IS NULL - AND status NOT IN ('completed', 'error', 'interrupted') - RETURNING 1 -) -SELECT - (SELECT COUNT(*) FROM finalized_runs)::bigint AS runs_finalized, - (SELECT COUNT(*) FROM finalized_steps)::bigint AS steps_finalized; diff --git a/codersdk/chats.go b/codersdk/chats.go index 2dd553b029b..cef15e0d262 100644 --- a/codersdk/chats.go +++ b/codersdk/chats.go @@ -1357,7 +1357,7 @@ type UpdateUserChatDebugLoggingRequest struct { // ChatDebugStatus enumerates the lifecycle states shared by debug // runs and steps. These values must match the literals used in -// FinalizeStaleChatDebugRows and all insert/update callers. +// insert/update callers. type ChatDebugStatus string const (