Files
coder/coderd/database/chatfiles.go
T
Michael Suchacz 57f38b5c24 fix: keep chat attachments while a linking chat exists
Fixes https://linear.app/codercom/issue/CODAGT-616/keep-chat-attachments-while-chats-remain-unarchived

Chat attachments could disappear even though the chat was still available. This happened when a message was saved without recording which attachments it used, or when cleanup deleted attachments before an archived chat itself was removed.

Creating a chat, sending or queuing a message, and editing a message now record both the message and which attachments it uses as one operation. If the chat is already at the 50-attachment limit, the chat change fails without being partially saved.

Concurrent attachment writes serialize the 50-file cap per chat. Cleanup locks candidates and checks again for new links before deleting. If a file becomes unavailable after input validation, create, send, and edit return a clear client error and roll back the chat change.

An attachment stays available while any chat that uses it still exists. After an archived chat reaches the end of its retention period and is deleted, an old attachment that no remaining chat uses can be cleaned up. The retention guide and unavailable-attachment UI text document this lifecycle. This change cannot restore attachments that were already deleted.

The database migration adds two indexes so attachment cleanup stays fast as attachments accumulate.

> This PR was authored by Mux (AI) on Mike's behalf.
2026-08-11 13:53:15 +02:00

60 lines
1.5 KiB
Go

package database
import (
"context"
"golang.org/x/xerrors"
)
type (
DeleteOldChatFilesParams = GetOldUnlinkedChatFileIDsParams
LinkChatFilesParams = LinkChatFilesAfterLockParams
)
func (q *sqlQuerier) LinkChatFiles(ctx context.Context, arg LinkChatFilesParams) (int32, error) {
var rejected int32
err := q.InTx(func(tx Store) error {
if _, err := tx.LockChatByID(ctx, arg.ChatID); err != nil {
return xerrors.Errorf("lock chat: %w", err)
}
var err error
rejected, err = tx.LinkChatFilesAfterLock(ctx, arg)
if err != nil {
return xerrors.Errorf("link chat files after lock: %w", err)
}
return nil
}, DefaultTXOptions().WithID("link_chat_files"))
if err != nil {
return 0, err
}
return rejected, nil
}
func (q *sqlQuerier) DeleteOldChatFiles(ctx context.Context, arg DeleteOldChatFilesParams) (int64, error) {
// Recheck candidates because links may commit during row-lock waits.
var deleted int64
err := q.InTx(func(tx Store) error {
ids, err := tx.GetOldUnlinkedChatFileIDs(ctx, arg)
if err != nil {
return xerrors.Errorf("get old unlinked chat files: %w", err)
}
if len(ids) == 0 {
return nil
}
deleted, err = tx.DeleteUnlinkedChatFilesByIDs(ctx, DeleteUnlinkedChatFilesByIDsParams{
IDs: ids,
BeforeTime: arg.BeforeTime,
})
if err != nil {
return xerrors.Errorf("delete old unlinked chat files: %w", err)
}
return nil
}, DefaultTXOptions().WithID("delete_old_chat_files"))
if err != nil {
return 0, err
}
return deleted, nil
}