diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index af44ea04862..68660189a78 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -3146,6 +3146,13 @@ func (q *querier) GetAuthorizationUserRoles(ctx context.Context, userID uuid.UUI return q.db.GetAuthorizationUserRoles(ctx, userID) } +func (q *querier) GetAutoArchiveInactiveChatCandidateByID(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidateByIDParams) (database.GetAutoArchiveInactiveChatCandidateByIDRow, error) { + if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceChat); err != nil { + return database.GetAutoArchiveInactiveChatCandidateByIDRow{}, err + } + return q.db.GetAutoArchiveInactiveChatCandidateByID(ctx, arg) +} + func (q *querier) GetAutoArchiveInactiveChatCandidates(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidatesParams) ([]database.GetAutoArchiveInactiveChatCandidatesRow, error) { if err := q.authorizeContext(ctx, policy.ActionUpdate, rbac.ResourceChat); err != nil { return nil, err diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index 4de1d41072e..f53071fa0e3 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -1188,6 +1188,11 @@ func (s *MethodTestSuite) TestChats() { dbm.EXPECT().GetAutoArchiveInactiveChatCandidates(gomock.Any(), arg).Return([]database.GetAutoArchiveInactiveChatCandidatesRow{}, nil).AnyTimes() check.Args(arg).Asserts(rbac.ResourceChat, policy.ActionUpdate).Returns([]database.GetAutoArchiveInactiveChatCandidatesRow{}) })) + s.Run("GetAutoArchiveInactiveChatCandidateByID", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) { + arg := database.GetAutoArchiveInactiveChatCandidateByIDParams{ID: uuid.New()} + dbm.EXPECT().GetAutoArchiveInactiveChatCandidateByID(gomock.Any(), arg).Return(database.GetAutoArchiveInactiveChatCandidateByIDRow{}, nil).AnyTimes() + check.Args(arg).Asserts(rbac.ResourceChat, policy.ActionUpdate).Returns(database.GetAutoArchiveInactiveChatCandidateByIDRow{}) + })) s.Run("GetChatMessageByID", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { chat := testutil.Fake(s.T(), faker, database.Chat{}) msg := testutil.Fake(s.T(), faker, database.ChatMessage{ChatID: chat.ID}) diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 8fe8c607237..19413063f49 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -1424,6 +1424,14 @@ func (m queryMetricsStore) GetAuthorizationUserRoles(ctx context.Context, userID return r0, r1 } +func (m queryMetricsStore) GetAutoArchiveInactiveChatCandidateByID(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidateByIDParams) (database.GetAutoArchiveInactiveChatCandidateByIDRow, error) { + start := time.Now() + r0, r1 := m.s.GetAutoArchiveInactiveChatCandidateByID(ctx, arg) + m.queryLatencies.WithLabelValues("GetAutoArchiveInactiveChatCandidateByID").Observe(time.Since(start).Seconds()) + m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "GetAutoArchiveInactiveChatCandidateByID").Inc() + return r0, r1 +} + func (m queryMetricsStore) GetAutoArchiveInactiveChatCandidates(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidatesParams) ([]database.GetAutoArchiveInactiveChatCandidatesRow, error) { start := time.Now() r0, r1 := m.s.GetAutoArchiveInactiveChatCandidates(ctx, arg) diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index 2ab651f857d..0622c4bddc1 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -2668,6 +2668,21 @@ func (mr *MockStoreMockRecorder) GetAuthorizedWorkspacesAndAgentsByOwnerID(ctx, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAuthorizedWorkspacesAndAgentsByOwnerID", reflect.TypeOf((*MockStore)(nil).GetAuthorizedWorkspacesAndAgentsByOwnerID), ctx, ownerID, prepared) } +// GetAutoArchiveInactiveChatCandidateByID mocks base method. +func (m *MockStore) GetAutoArchiveInactiveChatCandidateByID(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidateByIDParams) (database.GetAutoArchiveInactiveChatCandidateByIDRow, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAutoArchiveInactiveChatCandidateByID", ctx, arg) + ret0, _ := ret[0].(database.GetAutoArchiveInactiveChatCandidateByIDRow) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAutoArchiveInactiveChatCandidateByID indicates an expected call of GetAutoArchiveInactiveChatCandidateByID. +func (mr *MockStoreMockRecorder) GetAutoArchiveInactiveChatCandidateByID(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAutoArchiveInactiveChatCandidateByID", reflect.TypeOf((*MockStore)(nil).GetAutoArchiveInactiveChatCandidateByID), ctx, arg) +} + // GetAutoArchiveInactiveChatCandidates mocks base method. func (m *MockStore) GetAutoArchiveInactiveChatCandidates(ctx context.Context, arg database.GetAutoArchiveInactiveChatCandidatesParams) ([]database.GetAutoArchiveInactiveChatCandidatesRow, error) { m.ctrl.T.Helper() diff --git a/coderd/database/querier.go b/coderd/database/querier.go index 8d5f6152a86..1ac00b1b691 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -429,6 +429,13 @@ type sqlcQuerier interface { // (implied member roles, org default roles, groups); // TestGetActiveUsersAuthorizationRolesParity enforces this. GetAuthorizationUserRoles(ctx context.Context, userID uuid.UUID) (GetAuthorizationUserRolesRow, error) + // Rechecks one root chat against the GetAutoArchiveInactiveChatCandidates + // filters. Auto-archive calls it inside the archive transaction after the + // family rows are locked, so activity that landed after the unlocked + // candidate read is observed. Returns no rows when the chat no longer + // qualifies. Keep the filters in sync with + // GetAutoArchiveInactiveChatCandidates. + GetAutoArchiveInactiveChatCandidateByID(ctx context.Context, arg GetAutoArchiveInactiveChatCandidateByIDParams) (GetAutoArchiveInactiveChatCandidateByIDRow, error) // Returns read-only root chat candidates for state-machine-backed // auto-archive. Activity is computed across the root family. The query // limits roots, not total family members. diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 76bccefefc0..c786578460b 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -8387,6 +8387,150 @@ func (q *sqlQuerier) GetActiveChatsByAgentID(ctx context.Context, agentID uuid.U return items, nil } +const getAutoArchiveInactiveChatCandidateByID = `-- name: GetAutoArchiveInactiveChatCandidateByID :one +SELECT + chats_expanded.id, chats_expanded.owner_id, chats_expanded.workspace_id, chats_expanded.title, chats_expanded.status, chats_expanded.worker_id, chats_expanded.started_at, chats_expanded.heartbeat_at, chats_expanded.created_at, chats_expanded.updated_at, chats_expanded.parent_chat_id, chats_expanded.root_chat_id, chats_expanded.last_model_config_id, chats_expanded.last_reasoning_effort, chats_expanded.archived, chats_expanded.last_error, chats_expanded.mode, chats_expanded.mcp_server_ids, chats_expanded.labels, chats_expanded.build_id, chats_expanded.agent_id, chats_expanded.pin_order, chats_expanded.last_read_message_id, chats_expanded.dynamic_tools, chats_expanded.organization_id, chats_expanded.plan_mode, chats_expanded.client_type, chats_expanded.last_turn_summary, chats_expanded.summary, chats_expanded.summary_generated_at, chats_expanded.snapshot_version, chats_expanded.history_version, chats_expanded.queue_version, chats_expanded.generation_attempt, chats_expanded.retry_state, chats_expanded.retry_state_version, chats_expanded.runner_id, chats_expanded.requires_action_deadline_at, chats_expanded.user_acl, chats_expanded.group_acl, chats_expanded.owner_username, chats_expanded.owner_name, chats_expanded.context_aggregate_hash, chats_expanded.context_dirty_since, chats_expanded.context_dirty_resources, chats_expanded.context_error, chats_expanded.compaction_requested_at, + COALESCE(activity.last_activity_at, chats_expanded.created_at)::timestamptz AS last_activity_at +FROM chats_expanded +LEFT JOIN LATERAL ( + SELECT MAX(chat_messages.created_at) AS last_activity_at + FROM chat_messages + JOIN chats family_chat ON family_chat.id = chat_messages.chat_id + WHERE (family_chat.id = chats_expanded.id OR family_chat.root_chat_id = chats_expanded.id) + AND chat_messages.deleted = false +) activity ON TRUE +WHERE + chats_expanded.id = $1::uuid + AND chats_expanded.archived = false + AND chats_expanded.pin_order = 0 + AND chats_expanded.parent_chat_id IS NULL + AND chats_expanded.created_at < $2::timestamptz + AND chats_expanded.status NOT IN ( + 'running'::chat_status, + 'interrupting'::chat_status, + 'requires_action'::chat_status + ) + AND COALESCE(activity.last_activity_at, chats_expanded.created_at) < $2::timestamptz +` + +type GetAutoArchiveInactiveChatCandidateByIDParams struct { + ID uuid.UUID `db:"id" json:"id"` + ArchiveCutoff time.Time `db:"archive_cutoff" json:"archive_cutoff"` +} + +type GetAutoArchiveInactiveChatCandidateByIDRow struct { + ID uuid.UUID `db:"id" json:"id"` + OwnerID uuid.UUID `db:"owner_id" json:"owner_id"` + WorkspaceID uuid.NullUUID `db:"workspace_id" json:"workspace_id"` + Title string `db:"title" json:"title"` + Status ChatStatus `db:"status" json:"status"` + WorkerID uuid.NullUUID `db:"worker_id" json:"worker_id"` + StartedAt sql.NullTime `db:"started_at" json:"started_at"` + HeartbeatAt sql.NullTime `db:"heartbeat_at" json:"heartbeat_at"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + UpdatedAt time.Time `db:"updated_at" json:"updated_at"` + ParentChatID uuid.NullUUID `db:"parent_chat_id" json:"parent_chat_id"` + RootChatID uuid.NullUUID `db:"root_chat_id" json:"root_chat_id"` + LastModelConfigID uuid.UUID `db:"last_model_config_id" json:"last_model_config_id"` + LastReasoningEffort NullChatReasoningEffort `db:"last_reasoning_effort" json:"last_reasoning_effort"` + Archived bool `db:"archived" json:"archived"` + LastError pqtype.NullRawMessage `db:"last_error" json:"last_error"` + Mode NullChatMode `db:"mode" json:"mode"` + MCPServerIDs []uuid.UUID `db:"mcp_server_ids" json:"mcp_server_ids"` + Labels StringMap `db:"labels" json:"labels"` + BuildID uuid.NullUUID `db:"build_id" json:"build_id"` + AgentID uuid.NullUUID `db:"agent_id" json:"agent_id"` + PinOrder int32 `db:"pin_order" json:"pin_order"` + LastReadMessageID sql.NullInt64 `db:"last_read_message_id" json:"last_read_message_id"` + DynamicTools pqtype.NullRawMessage `db:"dynamic_tools" json:"dynamic_tools"` + OrganizationID uuid.UUID `db:"organization_id" json:"organization_id"` + PlanMode NullChatPlanMode `db:"plan_mode" json:"plan_mode"` + ClientType ChatClientType `db:"client_type" json:"client_type"` + LastTurnSummary sql.NullString `db:"last_turn_summary" json:"last_turn_summary"` + Summary sql.NullString `db:"summary" json:"summary"` + SummaryGeneratedAt sql.NullTime `db:"summary_generated_at" json:"summary_generated_at"` + SnapshotVersion int64 `db:"snapshot_version" json:"snapshot_version"` + HistoryVersion int64 `db:"history_version" json:"history_version"` + QueueVersion int64 `db:"queue_version" json:"queue_version"` + GenerationAttempt int64 `db:"generation_attempt" json:"generation_attempt"` + RetryState pqtype.NullRawMessage `db:"retry_state" json:"retry_state"` + RetryStateVersion int64 `db:"retry_state_version" json:"retry_state_version"` + RunnerID uuid.NullUUID `db:"runner_id" json:"runner_id"` + RequiresActionDeadlineAt sql.NullTime `db:"requires_action_deadline_at" json:"requires_action_deadline_at"` + UserACL ChatACL `db:"user_acl" json:"user_acl"` + GroupACL ChatACL `db:"group_acl" json:"group_acl"` + OwnerUsername string `db:"owner_username" json:"owner_username"` + OwnerName string `db:"owner_name" json:"owner_name"` + ContextAggregateHash []byte `db:"context_aggregate_hash" json:"context_aggregate_hash"` + ContextDirtySince sql.NullTime `db:"context_dirty_since" json:"context_dirty_since"` + ContextDirtyResources pqtype.NullRawMessage `db:"context_dirty_resources" json:"context_dirty_resources"` + ContextError string `db:"context_error" json:"context_error"` + CompactionRequestedAt sql.NullTime `db:"compaction_requested_at" json:"compaction_requested_at"` + LastActivityAt time.Time `db:"last_activity_at" json:"last_activity_at"` +} + +// Rechecks one root chat against the GetAutoArchiveInactiveChatCandidates +// filters. Auto-archive calls it inside the archive transaction after the +// family rows are locked, so activity that landed after the unlocked +// candidate read is observed. Returns no rows when the chat no longer +// qualifies. Keep the filters in sync with +// GetAutoArchiveInactiveChatCandidates. +func (q *sqlQuerier) GetAutoArchiveInactiveChatCandidateByID(ctx context.Context, arg GetAutoArchiveInactiveChatCandidateByIDParams) (GetAutoArchiveInactiveChatCandidateByIDRow, error) { + row := q.db.QueryRowContext(ctx, getAutoArchiveInactiveChatCandidateByID, arg.ID, arg.ArchiveCutoff) + var i GetAutoArchiveInactiveChatCandidateByIDRow + err := row.Scan( + &i.ID, + &i.OwnerID, + &i.WorkspaceID, + &i.Title, + &i.Status, + &i.WorkerID, + &i.StartedAt, + &i.HeartbeatAt, + &i.CreatedAt, + &i.UpdatedAt, + &i.ParentChatID, + &i.RootChatID, + &i.LastModelConfigID, + &i.LastReasoningEffort, + &i.Archived, + &i.LastError, + &i.Mode, + pq.Array(&i.MCPServerIDs), + &i.Labels, + &i.BuildID, + &i.AgentID, + &i.PinOrder, + &i.LastReadMessageID, + &i.DynamicTools, + &i.OrganizationID, + &i.PlanMode, + &i.ClientType, + &i.LastTurnSummary, + &i.Summary, + &i.SummaryGeneratedAt, + &i.SnapshotVersion, + &i.HistoryVersion, + &i.QueueVersion, + &i.GenerationAttempt, + &i.RetryState, + &i.RetryStateVersion, + &i.RunnerID, + &i.RequiresActionDeadlineAt, + &i.UserACL, + &i.GroupACL, + &i.OwnerUsername, + &i.OwnerName, + &i.ContextAggregateHash, + &i.ContextDirtySince, + &i.ContextDirtyResources, + &i.ContextError, + &i.CompactionRequestedAt, + &i.LastActivityAt, + ) + return i, err +} + const getAutoArchiveInactiveChatCandidates = `-- name: GetAutoArchiveInactiveChatCandidates :many SELECT chats_expanded.id, chats_expanded.owner_id, chats_expanded.workspace_id, chats_expanded.title, chats_expanded.status, chats_expanded.worker_id, chats_expanded.started_at, chats_expanded.heartbeat_at, chats_expanded.created_at, chats_expanded.updated_at, chats_expanded.parent_chat_id, chats_expanded.root_chat_id, chats_expanded.last_model_config_id, chats_expanded.last_reasoning_effort, chats_expanded.archived, chats_expanded.last_error, chats_expanded.mode, chats_expanded.mcp_server_ids, chats_expanded.labels, chats_expanded.build_id, chats_expanded.agent_id, chats_expanded.pin_order, chats_expanded.last_read_message_id, chats_expanded.dynamic_tools, chats_expanded.organization_id, chats_expanded.plan_mode, chats_expanded.client_type, chats_expanded.last_turn_summary, chats_expanded.summary, chats_expanded.summary_generated_at, chats_expanded.snapshot_version, chats_expanded.history_version, chats_expanded.queue_version, chats_expanded.generation_attempt, chats_expanded.retry_state, chats_expanded.retry_state_version, chats_expanded.runner_id, chats_expanded.requires_action_deadline_at, chats_expanded.user_acl, chats_expanded.group_acl, chats_expanded.owner_username, chats_expanded.owner_name, chats_expanded.context_aggregate_hash, chats_expanded.context_dirty_since, chats_expanded.context_dirty_resources, chats_expanded.context_error, chats_expanded.compaction_requested_at, diff --git a/coderd/database/queries/chats.sql b/coderd/database/queries/chats.sql index c4cbb654f16..a0ef7ae8bfd 100644 --- a/coderd/database/queries/chats.sql +++ b/coderd/database/queries/chats.sql @@ -2591,6 +2591,37 @@ WHERE ORDER BY chats_expanded.created_at ASC LIMIT @limit_count::int; +-- name: GetAutoArchiveInactiveChatCandidateByID :one +-- Rechecks one root chat against the GetAutoArchiveInactiveChatCandidates +-- filters. Auto-archive calls it inside the archive transaction after the +-- family rows are locked, so activity that landed after the unlocked +-- candidate read is observed. Returns no rows when the chat no longer +-- qualifies. Keep the filters in sync with +-- GetAutoArchiveInactiveChatCandidates. +SELECT + chats_expanded.*, + COALESCE(activity.last_activity_at, chats_expanded.created_at)::timestamptz AS last_activity_at +FROM chats_expanded +LEFT JOIN LATERAL ( + SELECT MAX(chat_messages.created_at) AS last_activity_at + FROM chat_messages + JOIN chats family_chat ON family_chat.id = chat_messages.chat_id + WHERE (family_chat.id = chats_expanded.id OR family_chat.root_chat_id = chats_expanded.id) + AND chat_messages.deleted = false +) activity ON TRUE +WHERE + chats_expanded.id = @id::uuid + AND chats_expanded.archived = false + AND chats_expanded.pin_order = 0 + AND chats_expanded.parent_chat_id IS NULL + AND chats_expanded.created_at < @archive_cutoff::timestamptz + AND chats_expanded.status NOT IN ( + 'running'::chat_status, + 'interrupting'::chat_status, + 'requires_action'::chat_status + ) + AND COALESCE(activity.last_activity_at, chats_expanded.created_at) < @archive_cutoff::timestamptz; + -- name: LockChatAndBumpSnapshotVersion :one -- Locks the chat row with FOR UPDATE and atomically increments its diff --git a/coderd/x/chatd/ARCHITECTURE.md b/coderd/x/chatd/ARCHITECTURE.md index 45be1e49e0b..939a32f0ed5 100644 --- a/coderd/x/chatd/ARCHITECTURE.md +++ b/coderd/x/chatd/ARCHITECTURE.md @@ -1095,6 +1095,10 @@ By default, chatd runs up to five top-level chats and ten subagent chats at once The worker periodically archives old, unused chats. +Each tick reads a batch of candidate root chats without holding locks. A candidate is unarchived, unpinned, not `running`, `interrupting` or `requires_action`, created before the cutoff, and the newest non-deleted message in its family is older than the cutoff. The cutoff is 00:00 UTC of the current day minus the configured number of auto-archive days. + +Each candidate is archived the same way as an archive through `PATCH /api/v2/chats/{chat}`: `SetArchived(true)` applies to the root and all descendants in one transaction. Before any chat changes, that transaction locks the root and then every descendant, and rechecks the candidate conditions. A chat that no longer qualifies, for example because a message arrived after the candidate read, is skipped. Only messages count as activity, so a chat that is unarchived without a new message is archived again on the next tick. + ## Manual compaction Compaction reduces the LLM prompt size by summarizing older history into a compressed boundary. It normally runs automatically: while preparing a generation, the worker compares the latest known token usage against the model's compaction threshold, and when the threshold is exceeded it makes a non-streaming LLM call to produce a summary and commits it as a compressed message triplet (a hidden model-only summary boundary, a visible `chat_summarized` tool call, and its tool result). Prompt queries prune history at the newest boundary. diff --git a/coderd/x/chatd/auto_archive.go b/coderd/x/chatd/auto_archive.go index ac460f74a33..542430f407d 100644 --- a/coderd/x/chatd/auto_archive.go +++ b/coderd/x/chatd/auto_archive.go @@ -27,6 +27,11 @@ import ( const chatAutoArchiveDigestMaxChats = 25 +// errAutoArchiveCandidateIneligible reports that a candidate stopped +// qualifying for auto-archive between the unlocked candidate read and +// the locked recheck, for example because a new message landed. +var errAutoArchiveCandidateIneligible = xerrors.New("chat no longer qualifies for auto-archive") + type autoArchivedChat struct { Chat database.Chat LastActivityAt time.Time @@ -92,7 +97,7 @@ func (w *chatWorker) archiveOnce(ctx context.Context, start time.Time) { archived := make([]autoArchivedChat, 0, len(rows)) for _, row := range rows { - family, err := w.archiveCandidateSafely(ctx, row) + family, err := w.archiveCandidateSafely(ctx, row, archiveCutoff) if err != nil { if ctx.Err() != nil { return @@ -124,22 +129,43 @@ func (w *chatWorker) archiveOnce(ctx context.Context, start time.Time) { func (w *chatWorker) archiveCandidateSafely( ctx context.Context, row database.GetAutoArchiveInactiveChatCandidatesRow, + archiveCutoff time.Time, ) (family []autoArchivedChat, err error) { defer func() { if recovered := recover(); recovered != nil { err = xerrors.Errorf("chatworker auto-archive panic: %v", recovered) } }() - return w.archiveCandidate(ctx, row) + return w.archiveCandidate(ctx, row, archiveCutoff) } func (w *chatWorker) archiveCandidate( ctx context.Context, row database.GetAutoArchiveInactiveChatCandidatesRow, + archiveCutoff time.Time, ) ([]autoArchivedChat, error) { + lastActivityAt := row.LastActivityAt familyChats, err := chatstate.SetFamilyArchived(ctx, w.opts.Store, w.opts.Pubsub, chatstate.SetFamilyArchivedInput{ RootID: row.ID, Archived: true, + // The candidate list is read without locks, so recheck the + // candidate filters once the family rows are locked. Activity + // that committed after the candidate read, such as a new + // message in the root or a child, makes the chat skip this tick. + Precondition: func(ctx context.Context, tx database.Store) error { + current, err := tx.GetAutoArchiveInactiveChatCandidateByID(ctx, database.GetAutoArchiveInactiveChatCandidateByIDParams{ + ID: row.ID, + ArchiveCutoff: archiveCutoff, + }) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return errAutoArchiveCandidateIneligible + } + return xerrors.Errorf("recheck auto-archive candidate: %w", err) + } + lastActivityAt = current.LastActivityAt + return nil + }, }) if err != nil { return nil, err @@ -152,13 +178,13 @@ func (w *chatWorker) archiveCandidate( archived := make([]autoArchivedChat, 0, len(familyChats)) for _, chat := range familyChats { - lastActivityAt := row.LastActivityAt - if lastActivityAt.IsZero() { - lastActivityAt = chat.CreatedAt + chatLastActivityAt := lastActivityAt + if chatLastActivityAt.IsZero() { + chatLastActivityAt = chat.CreatedAt } archived = append(archived, autoArchivedChat{ Chat: chat, - LastActivityAt: lastActivityAt, + LastActivityAt: chatLastActivityAt, }) } return archived, nil @@ -166,6 +192,7 @@ func (w *chatWorker) archiveCandidate( func isExpectedAutoArchiveError(err error) bool { return errors.Is(err, sql.ErrNoRows) || + errors.Is(err, errAutoArchiveCandidateIneligible) || errors.Is(err, chatstate.ErrChatNotFound) || errors.Is(err, chatstate.ErrChatNotRoot) || errors.Is(err, chatstate.ErrInvalidState) || diff --git a/coderd/x/chatd/auto_archive_internal_test.go b/coderd/x/chatd/auto_archive_internal_test.go index e08709ae15a..10f94e980f8 100644 --- a/coderd/x/chatd/auto_archive_internal_test.go +++ b/coderd/x/chatd/auto_archive_internal_test.go @@ -770,6 +770,7 @@ func TestIsExpectedAutoArchiveError(t *testing.T) { chatstate.ErrChatNotRoot, chatstate.ErrInvalidState, chatstate.ErrTransitionNotAllowed, + errAutoArchiveCandidateIneligible, } for _, err := range expected { require.True(t, isExpectedAutoArchiveError(err), "%v should be classified as expected", err) diff --git a/coderd/x/chatd/auto_archive_recheck_internal_test.go b/coderd/x/chatd/auto_archive_recheck_internal_test.go new file mode 100644 index 00000000000..7816b9d6a64 --- /dev/null +++ b/coderd/x/chatd/auto_archive_recheck_internal_test.go @@ -0,0 +1,268 @@ +package chatd + +import ( + "context" + "database/sql" + "testing" + "time" + + "github.com/google/uuid" + "github.com/stretchr/testify/require" + + "github.com/coder/coder/v2/coderd/database" + "github.com/coder/coder/v2/coderd/database/dbtime" + "github.com/coder/coder/v2/coderd/x/chatd/chatstate" + "github.com/coder/coder/v2/testutil" +) + +// staleAutoArchiveCandidate returns the candidate row that archiveOnce +// would read for chatID, together with the cutoff it used. Tests change +// the chat after this read to model activity that lands before +// archiveCandidate runs. +func staleAutoArchiveCandidate(t *testing.T, f *workerTestFixture, now time.Time) (database.GetAutoArchiveInactiveChatCandidatesRow, time.Time) { + t.Helper() + ctx := testutil.Context(t, testutil.WaitShort) + cutoff := dbtime.StartOfDay(now).Add(-90 * 24 * time.Hour) + rows, err := f.db.GetAutoArchiveInactiveChatCandidates(ctx, database.GetAutoArchiveInactiveChatCandidatesParams{ + ArchiveCutoff: cutoff, + LimitCount: 10, + }) + require.NoError(t, err) + require.Len(t, rows, 1) + return rows[0], cutoff +} + +// TestWorker_AutoArchiveRechecksCandidateActivity covers activity that +// lands between the unlocked candidate read and the archive. The chat +// must stay unarchived because its last message is newer than the cutoff. +func TestWorker_AutoArchiveRechecksCandidateActivity(t *testing.T) { + t.Parallel() + f := newWorkerTestFixture(t) + ctx := testutil.Context(t, testutil.WaitShort) + now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC) + chat := f.createArchiveCandidate(t, now.Add(-120*24*time.Hour)) + insertArchiveMessage(t, f, chat.ID, now.Add(-100*24*time.Hour)) + require.NoError(t, f.db.UpsertChatAutoArchiveDays(ctx, 90)) + worker := f.newArchiveWorker(t, nil, nil, nil) + + row, cutoff := staleAutoArchiveCandidate(t, f, now) + // Fresh activity lands before archiveCandidate runs for this row. + insertArchiveMessage(t, f, chat.ID, now) + + family, err := worker.archiveCandidate(ctx, row, cutoff) + require.ErrorIs(t, err, errAutoArchiveCandidateIneligible) + require.True(t, isExpectedAutoArchiveError(err)) + require.Empty(t, family) + require.False(t, f.archived(t, chat.ID), + "chat %s was auto-archived although its last message (%s) is newer than the cutoff (%s)", + chat.ID, now, cutoff) +} + +func TestWorker_AutoArchiveRechecksCandidatePin(t *testing.T) { + t.Parallel() + f := newWorkerTestFixture(t) + ctx := testutil.Context(t, testutil.WaitShort) + now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC) + chat := f.createArchiveCandidate(t, now.Add(-120*24*time.Hour)) + require.NoError(t, f.db.UpsertChatAutoArchiveDays(ctx, 90)) + worker := f.newArchiveWorker(t, nil, nil, nil) + + row, cutoff := staleAutoArchiveCandidate(t, f, now) + f.setPinOrder(t, chat.ID, 1) + + _, err := worker.archiveCandidate(ctx, row, cutoff) + require.ErrorIs(t, err, errAutoArchiveCandidateIneligible) + require.False(t, f.archived(t, chat.ID), "chat pinned after the candidate read must not be auto-archived") +} + +// TestWorker_AutoArchiveRechecksChildActivityUnderLock holds a child row +// lock while archiveCandidate runs, commits fresh child activity once the +// archive is blocked on that lock, and then releases it. The recheck runs +// after every family row is locked, so it must observe the new activity. +func TestWorker_AutoArchiveRechecksChildActivityUnderLock(t *testing.T) { + t.Parallel() + f := newWorkerTestFixture(t) + ctx := testutil.Context(t, testutil.WaitLong) + now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC) + root := f.createArchiveCandidate(t, now.Add(-120*24*time.Hour)) + child := f.createArchiveCandidate(t, now.Add(-120*24*time.Hour)) + f.linkChild(t, root.ID, child.ID) + insertArchiveMessage(t, f, child.ID, now.Add(-100*24*time.Hour)) + // Stage a fresh child message as deleted so it does not count as + // activity yet. Undeleting it under the child lock models a child + // turn that commits a message while the archive waits. + insertArchiveMessage(t, f, child.ID, now) + _, err := f.sqlDB.ExecContext(ctx, "UPDATE chat_messages SET deleted = true WHERE chat_id = $1 AND created_at >= $2", child.ID, now) + require.NoError(t, err) + require.NoError(t, f.db.UpsertChatAutoArchiveDays(ctx, 90)) + worker := f.newArchiveWorker(t, nil, nil, nil) + + row, cutoff := staleAutoArchiveCandidate(t, f, now) + + conn, err := f.sqlDB.Conn(ctx) + require.NoError(t, err) + defer conn.Close() + lockTx, err := conn.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = lockTx.Rollback() }() + var lockPID int + require.NoError(t, lockTx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&lockPID)) + _, err = lockTx.ExecContext(ctx, "SELECT id FROM chats WHERE id = $1 FOR UPDATE", child.ID) + require.NoError(t, err) + + type result struct { + family []autoArchivedChat + err error + } + done := make(chan result, 1) + go func() { + family, err := worker.archiveCandidate(ctx, row, cutoff) + done <- result{family: family, err: err} + }() + + // Wait until the archive transaction is blocked on the child lock. + testutil.Eventually(ctx, t, func(ctx context.Context) bool { + var blocked bool + err := f.sqlDB.QueryRowContext(ctx, + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE $1::int = ANY(pg_blocking_pids(pid)))", + lockPID, + ).Scan(&blocked) + return err == nil && blocked + }, testutil.IntervalFast, "archive transaction never blocked on the child row lock") + + _, err = lockTx.ExecContext(ctx, "UPDATE chat_messages SET deleted = false WHERE chat_id = $1", child.ID) + require.NoError(t, err) + require.NoError(t, lockTx.Commit()) + + res := testutil.RequireReceive(ctx, t, done) + require.ErrorIs(t, res.err, errAutoArchiveCandidateIneligible) + require.Empty(t, res.family) + require.False(t, f.archived(t, root.ID), "child activity committed under the child lock must keep the root alive") + require.False(t, f.archived(t, child.ID)) +} + +// TestWorker_AutoArchiveRearchivesUnarchivedChatWithoutMessages pins the +// documented behavior that unarchiving alone is not activity: only +// messages count, so the next tick archives the chat again. +func TestWorker_AutoArchiveRearchivesUnarchivedChatWithoutMessages(t *testing.T) { + t.Parallel() + f := newWorkerTestFixture(t) + ctx := testutil.Context(t, testutil.WaitShort) + now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC) + chat := f.createArchiveCandidate(t, now.Add(-120*24*time.Hour)) + require.NoError(t, f.db.UpsertChatAutoArchiveDays(ctx, 90)) + worker := f.newArchiveWorker(t, nil, nil, nil) + + worker.archiveOnce(ctx, now) + require.True(t, f.archived(t, chat.ID)) + + _, err := chatstate.SetFamilyArchived(ctx, f.db, f.pubsub, chatstate.SetFamilyArchivedInput{ + RootID: chat.ID, + Archived: false, + }) + require.NoError(t, err) + require.False(t, f.archived(t, chat.ID)) + + worker.archiveOnce(ctx, now) + require.True(t, f.archived(t, chat.ID), "unarchive without a message must not count as activity") +} + +// TestAutoArchiveCandidateQueriesAgree guards the "keep the filters in +// sync" contract between GetAutoArchiveInactiveChatCandidates and +// GetAutoArchiveInactiveChatCandidateByID: for every fixture chat, +// appearing in the batch result must equal the by-ID recheck returning +// a row. Each fixture also pins its expected eligibility so that both +// queries drifting the same way still fails. +func TestAutoArchiveCandidateQueriesAgree(t *testing.T) { + t.Parallel() + f := newWorkerTestFixture(t) + ctx := testutil.Context(t, testutil.WaitLong) + now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC) + cutoff := dbtime.StartOfDay(now).Add(-90 * 24 * time.Hour) + old := now.Add(-120 * 24 * time.Hour) + + type fixture struct { + name string + chatID uuid.UUID + eligible bool + } + var fixtures []fixture + add := func(name string, chat database.Chat, eligible bool) { + fixtures = append(fixtures, fixture{name: name, chatID: chat.ID, eligible: eligible}) + } + + add("eligible without messages", f.createArchiveCandidate(t, old), true) + + oldMessage := f.createArchiveCandidate(t, old) + insertArchiveMessage(t, f, oldMessage.ID, now.Add(-100*24*time.Hour)) + add("eligible with old message", oldMessage, true) + + errored := f.createArchiveCandidate(t, old) + forceExecutionState(t, f, errored.ID, database.ChatStatusError, false) + add("eligible in error status", errored, true) + + archived := f.createArchiveCandidate(t, old) + forceExecutionState(t, f, archived.ID, database.ChatStatusWaiting, true) + add("archived", archived, false) + + pinned := f.createArchiveCandidate(t, old) + f.setPinOrder(t, pinned.ID, 1) + add("pinned", pinned, false) + + parent := f.createArchiveCandidate(t, old) + child := f.createArchiveCandidate(t, old) + f.linkChild(t, parent.ID, child.ID) + add("root of idle child", parent, true) + add("non-root child", child, false) + + add("created after cutoff", f.createArchiveCandidate(t, now.Add(-10*24*time.Hour)), false) + + for _, status := range []database.ChatStatus{ + database.ChatStatusRunning, + database.ChatStatusInterrupting, + database.ChatStatusRequiresAction, + } { + chat := f.createArchiveCandidate(t, old) + forceExecutionState(t, f, chat.ID, status, false) + add("status "+string(status), chat, false) + } + + recent := f.createArchiveCandidate(t, old) + insertArchiveMessage(t, f, recent.ID, now.Add(-5*24*time.Hour)) + add("recent message", recent, false) + + activeFamily := f.createArchiveCandidate(t, old) + activeChild := f.createArchiveCandidate(t, old) + f.linkChild(t, activeFamily.ID, activeChild.ID) + insertArchiveMessage(t, f, activeChild.ID, now.Add(-5*24*time.Hour)) + add("recent child message", activeFamily, false) + + softDeleted := f.createArchiveCandidate(t, old) + insertArchiveMessage(t, f, softDeleted.ID, now.Add(-5*24*time.Hour)) + f.softDeleteMessages(t, softDeleted.ID) + add("soft-deleted recent message", softDeleted, true) + + rows, err := f.db.GetAutoArchiveInactiveChatCandidates(ctx, database.GetAutoArchiveInactiveChatCandidatesParams{ + ArchiveCutoff: cutoff, + LimitCount: 1000, + }) + require.NoError(t, err) + require.Less(t, len(rows), 1000, "batch limit must not truncate the fixtures") + inBatch := make(map[uuid.UUID]bool, len(rows)) + for _, row := range rows { + inBatch[row.ID] = true + } + + for _, fx := range fixtures { + _, err := f.db.GetAutoArchiveInactiveChatCandidateByID(ctx, database.GetAutoArchiveInactiveChatCandidateByIDParams{ + ID: fx.chatID, + ArchiveCutoff: cutoff, + }) + byID := err == nil + if !byID { + require.ErrorIs(t, err, sql.ErrNoRows, fx.name) + } + require.Equal(t, inBatch[fx.chatID], byID, "%s: batch and by-ID queries disagree", fx.name) + require.Equal(t, fx.eligible, byID, "%s: unexpected eligibility", fx.name) + } +} diff --git a/coderd/x/chatd/chatstate/family.go b/coderd/x/chatd/chatstate/family.go index fb22e05bae9..42ef532f22f 100644 --- a/coderd/x/chatd/chatstate/family.go +++ b/coderd/x/chatd/chatstate/family.go @@ -22,6 +22,14 @@ type SetFamilyArchivedInput struct { // Archived is the desired post-call archived value for every // family member. Archived bool + // Precondition, when set, runs inside the transaction after the + // root and every family member row are locked (root first, then + // children in GetChatFamilyIDsByRootID order) and before any + // member is updated. A non-nil error aborts the call and rolls + // back the transaction. Reads issued through tx observe every + // change committed before the locks were acquired, and writers + // that lock a family row cannot commit until this call finishes. + Precondition func(ctx context.Context, tx database.Store) error } // SetFamilyArchived runs Update for every chat in the root chat's @@ -84,6 +92,21 @@ func SetFamilyArchived( if len(ids) == 0 { return ErrChatNotFound } + if input.Precondition != nil { + // Lock the remaining members in the same order the update + // loop below uses, so the precondition sees a stable family. + for _, id := range ids { + if id == input.RootID { + continue + } + if _, err := tx.GetChatByIDForUpdate(ctx, id); err != nil { + return xerrors.Errorf("lock family chat for archive: %w", err) + } + } + if err := input.Precondition(ctx, tx); err != nil { + return err + } + } familyChats = make([]database.Chat, 0, len(ids)) for _, id := range ids { var chat database.Chat