One of the main costs in terms of DB load from chats is extra round trips during transactions. This results in locks being held for longer periods of time -> an increase in lock waits for chats related queries. One of the opportunities for reducing some of the round trips is to eliminate extra chat row reads after we have just read the row in order to lock it. In this PR `ChatMachine.Update` now seeds the transaction struct with the row returned by `LockChatAndBumpSnapshotVersion`, plus a queue count taken right after it. We can then pass it into `Update` as an optional parameter validate against it, so neither re-reads the chat row from the database while the row lock is held. `updateChat` (send, edit, promote, tool results, interrupt, compact, clear, reconcile), hook failure, family archive, and the worker's generation and task transitions use it instead of reloading the chat under the lock. This PR relative to main: |measurement | main | this PR | percent change | |-- | -- | -- | -- | | Round trips under lock | 180.9 | 142.0 | -39% | | Statements under lock | 86.1 | 66.6 | -23% | | GetChatByID under lock | 54.1 | 35.8 | -34% | | GetChatByID total | 75.5 | 57.1 | -25% | | Statements | 235.8 | 216.2 | -8% | Generated by Coder Agents on behalf of @cstyan.
2138 lines
75 KiB
Go
2138 lines
75 KiB
Go
package chatstate
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/sqlc-dev/pqtype"
|
|
"golang.org/x/xerrors"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
coderdpubsub "github.com/coder/coder/v2/coderd/pubsub"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprompt"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
// CreateChatInput configures [CreateChat].
|
|
type CreateChatInput struct {
|
|
OrganizationID uuid.UUID
|
|
OwnerID uuid.UUID
|
|
ProjectID uuid.NullUUID
|
|
WorkspaceID uuid.NullUUID
|
|
BuildID uuid.NullUUID
|
|
AgentID uuid.NullUUID
|
|
ParentChatID uuid.NullUUID
|
|
RootChatID uuid.NullUUID
|
|
LastModelConfigID uuid.UUID
|
|
Title string
|
|
// TitleSource defaults to fallback.
|
|
TitleSource database.ChatTitleSource
|
|
Mode database.NullChatMode
|
|
PlanMode database.NullChatPlanMode
|
|
MCPServerIDs []uuid.UUID
|
|
InlineMCPServers []codersdk.InlineMCPServerRequest
|
|
Labels pqtype.NullRawMessage
|
|
DynamicTools pqtype.NullRawMessage
|
|
ClientType database.ChatClientType
|
|
InitialMessages []Message
|
|
// FileIDs are linked atomically with the initial messages.
|
|
FileIDs []uuid.UUID
|
|
// InitialStatus selects the chat's starting execution state:
|
|
// `running` (R0) when the initial history ends with a user turn
|
|
// the worker should process, or `waiting` (W) when the chat is
|
|
// created idle with no initial user message. Empty defaults to
|
|
// `running`.
|
|
InitialStatus database.ChatStatus
|
|
// MaxFileLinks is the maximum number of files linked to the chat. It
|
|
// must be positive when FileIDs is not empty.
|
|
MaxFileLinks int
|
|
}
|
|
|
|
// CreateChatResult is the value returned by [CreateChat]. It carries
|
|
// the new chat row and the inserted initial history.
|
|
type CreateChatResult struct {
|
|
Chat database.Chat
|
|
InitialMessages []database.ChatMessage
|
|
}
|
|
|
|
// CreateChat creates a brand new chat with initial history in a single
|
|
// transaction. It is package-level rather than a method on [ChatMachine]
|
|
// because no chat-scoped machine can exist before the chat row is written.
|
|
//
|
|
// Validation:
|
|
// - InitialMessages must be non-empty.
|
|
// - InitialStatus must be `waiting`, `running`, or empty (`running`).
|
|
// - When RootChatID is set, the root chat must exist and must not be
|
|
// archived; otherwise CreateChat returns [ErrChatNotFound] or
|
|
// [ErrChatFamilyArchived].
|
|
//
|
|
// After commit CreateChat publishes a `chat:update` message describing
|
|
// the new chat snapshot. When the new chat is runnable (`running`),
|
|
// CreateChat also publishes an ownership hint so workers can race to
|
|
// acquire it. A `waiting` chat is idle, so no ownership hint is
|
|
// published until a later transition makes it runnable.
|
|
func CreateChat(
|
|
ctx context.Context,
|
|
store database.Store,
|
|
publisher Publisher,
|
|
input CreateChatInput,
|
|
) (CreateChatResult, error) {
|
|
return insertChat(ctx, store, publisher, uuid.NullUUID{}, input)
|
|
}
|
|
|
|
// CreateChatWithID creates a chat using a caller-minted ID so
|
|
// admission-time work can reference the chat before it exists.
|
|
func CreateChatWithID(
|
|
ctx context.Context,
|
|
store database.Store,
|
|
publisher Publisher,
|
|
chatID uuid.UUID,
|
|
input CreateChatInput,
|
|
) (CreateChatResult, error) {
|
|
if chatID == uuid.Nil {
|
|
return CreateChatResult{}, xerrors.New("chatstate: CreateChatWithID called with nil chat ID")
|
|
}
|
|
return insertChat(ctx, store, publisher, uuid.NullUUID{UUID: chatID, Valid: true}, input)
|
|
}
|
|
|
|
func insertChat(
|
|
ctx context.Context,
|
|
store database.Store,
|
|
publisher Publisher,
|
|
chatID uuid.NullUUID,
|
|
input CreateChatInput,
|
|
) (CreateChatResult, error) {
|
|
if store == nil {
|
|
return CreateChatResult{}, xerrors.New("chatstate: CreateChat called with nil store")
|
|
}
|
|
if publisher == nil {
|
|
return CreateChatResult{}, xerrors.New("chatstate: CreateChat called with nil publisher")
|
|
}
|
|
if len(input.InitialMessages) == 0 {
|
|
return CreateChatResult{}, newTransitionError(
|
|
TransitionCreateChat, StateN,
|
|
"initial messages must include at least one message",
|
|
)
|
|
}
|
|
initialStatus := cmp.Or(input.InitialStatus, database.ChatStatusRunning)
|
|
if initialStatus != database.ChatStatusWaiting && initialStatus != database.ChatStatusRunning {
|
|
return CreateChatResult{}, newTransitionError(
|
|
TransitionCreateChat, StateN,
|
|
"initial status must be waiting or running",
|
|
)
|
|
}
|
|
var result CreateChatResult
|
|
buffer := NewPublishBuffer(publisher)
|
|
defer buffer.Discard()
|
|
err := store.InTx(func(store database.Store) error {
|
|
if input.RootChatID.Valid {
|
|
// Lock the family root before inserting the child so this
|
|
// transaction serializes with SetFamilyArchived, which also
|
|
// locks the root first and then writes the members. FOR
|
|
// SHARE conflicts with that FOR UPDATE lock and with the
|
|
// row lock of any plain UPDATE on the root, so the archived
|
|
// flag read here holds until commit. Concurrent child
|
|
// creations under the same root still run in parallel.
|
|
root, err := store.GetChatByIDForShare(ctx, input.RootChatID.UUID)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return ErrChatNotFound
|
|
}
|
|
return xerrors.Errorf("lock root chat: %w", err)
|
|
}
|
|
if root.Archived {
|
|
return ErrChatFamilyArchived
|
|
}
|
|
}
|
|
chat, err := store.InsertChat(ctx, database.InsertChatParams{
|
|
ID: chatID,
|
|
OrganizationID: input.OrganizationID,
|
|
OwnerID: input.OwnerID,
|
|
ProjectID: input.ProjectID,
|
|
WorkspaceID: input.WorkspaceID,
|
|
BuildID: input.BuildID,
|
|
AgentID: input.AgentID,
|
|
ParentChatID: input.ParentChatID,
|
|
RootChatID: input.RootChatID,
|
|
LastModelConfigID: input.LastModelConfigID,
|
|
Title: input.Title,
|
|
TitleSource: database.NullChatTitleSource{ChatTitleSource: input.TitleSource, Valid: input.TitleSource != ""},
|
|
Mode: input.Mode,
|
|
PlanMode: input.PlanMode,
|
|
Status: initialStatus,
|
|
MCPServerIDs: input.MCPServerIDs,
|
|
Labels: input.Labels,
|
|
DynamicTools: input.DynamicTools,
|
|
ClientType: input.ClientType,
|
|
})
|
|
if err != nil {
|
|
return xerrors.Errorf("insert chat: %w", err)
|
|
}
|
|
// Insert the initial history under the new chat row. The
|
|
// message revision trigger advances `history_version` to the
|
|
// current `snapshot_version` (which is 1 for a brand new chat).
|
|
inserted, err := store.InsertChatMessages(ctx, toInsertParams(chat.ID, input.InitialMessages))
|
|
if err != nil {
|
|
return xerrors.Errorf("insert initial messages: %w", err)
|
|
}
|
|
if err := LinkFiles(ctx, store, chat.ID, input.FileIDs, input.MaxFileLinks); err != nil {
|
|
return err
|
|
}
|
|
if len(input.InlineMCPServers) > 0 {
|
|
if err := ReplaceInlineMCPServers(ctx, store, chat.ID, input.InlineMCPServers); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
refreshed, err := store.GetChatByID(ctx, chat.ID)
|
|
if err != nil {
|
|
return xerrors.Errorf("reload chat after initial messages: %w", err)
|
|
}
|
|
result = CreateChatResult{
|
|
Chat: refreshed,
|
|
InitialMessages: fromInsertedRows(inserted),
|
|
}
|
|
if err := buffer.Publish(
|
|
coderdpubsub.ChatStateUpdateChannel(refreshed.ID),
|
|
buildChatUpdateMessage(refreshed),
|
|
); err != nil {
|
|
return xerrors.Errorf("buffer chat update: %w", err)
|
|
}
|
|
if ClassifyExecutionState(refreshed, QueueState{}, true).IsRunnable() {
|
|
if err := buffer.Publish(
|
|
coderdpubsub.ChatStateOwnershipChannel,
|
|
buildChatOwnershipMessage(refreshed),
|
|
); err != nil {
|
|
return xerrors.Errorf("buffer ownership hint: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}, nil)
|
|
if err != nil {
|
|
return CreateChatResult{}, err
|
|
}
|
|
if err := buffer.Flush(); err != nil {
|
|
return result, err
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// applyExecutionStateUpdate is a small adapter so transition methods
|
|
// do not have to repeat the UpdateChatExecutionState boilerplate.
|
|
// The state machine writes status, archived, last_error, ownership
|
|
// identifiers, the requires-action deadline, and the manual
|
|
// compaction request marker as one atomic update.
|
|
//
|
|
// CompactionRequestedAt is one-shot by construction: leaving it at
|
|
// its zero value clears any pending manual compaction request, so a
|
|
// stale request can never replay on a later turn. Transitions that
|
|
// must keep a pending request alive (archive toggles, ownership
|
|
// changes, queue appends) explicitly carry the current value forward.
|
|
type executionStateUpdate struct {
|
|
Status database.ChatStatus
|
|
Archived bool
|
|
WorkerID uuid.NullUUID
|
|
RunnerID uuid.NullUUID
|
|
LastError pqtype.NullRawMessage
|
|
RequiresActionDeadlineAt sql.NullTime
|
|
CompactionRequestedAt sql.NullTime
|
|
GrantHistoryEpoch bool
|
|
}
|
|
|
|
func (tx *Tx) applyExecutionState(u executionStateUpdate) (database.Chat, error) {
|
|
return tx.store.UpdateChatExecutionState(tx.ctx, database.UpdateChatExecutionStateParams{
|
|
ID: tx.chatID,
|
|
Status: u.Status,
|
|
Archived: u.Archived,
|
|
WorkerID: u.WorkerID,
|
|
RunnerID: u.RunnerID,
|
|
LastError: u.LastError,
|
|
RequiresActionDeadlineAt: u.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: u.CompactionRequestedAt,
|
|
GrantHistoryEpoch: u.GrantHistoryEpoch,
|
|
})
|
|
}
|
|
|
|
// insertMessages inserts the given Message batch under the current
|
|
// chat.
|
|
func (tx *Tx) insertMessages(messages []Message) ([]database.ChatMessage, error) {
|
|
if len(messages) == 0 {
|
|
return nil, nil
|
|
}
|
|
inserted, err := tx.store.InsertChatMessages(tx.ctx, toInsertParams(tx.chatID, messages))
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("insert messages: %w", err)
|
|
}
|
|
return fromInsertedRows(inserted), nil
|
|
}
|
|
|
|
// clearQueue deletes all queued messages on the chat and returns the
|
|
// IDs that were deleted in queue order.
|
|
func (tx *Tx) clearQueue() ([]int64, error) {
|
|
queued, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("get queued for clear: %w", err)
|
|
}
|
|
if len(queued) == 0 {
|
|
return nil, nil
|
|
}
|
|
if _, err := tx.store.DeleteAllChatQueuedMessagesReturningCount(tx.ctx, tx.chatID); err != nil {
|
|
return nil, xerrors.Errorf("delete queued: %w", err)
|
|
}
|
|
ids := make([]int64, len(queued))
|
|
for i, q := range queued {
|
|
ids[i] = q.ID
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
func (tx *Tx) insertQueuedMessage(ownerFallback uuid.UUID, m Message, busyBehavior database.ChatBusyBehavior) (database.ChatQueuedMessage, error) {
|
|
createdBy := ownerFallback
|
|
if m.CreatedBy.Valid {
|
|
createdBy = m.CreatedBy.UUID
|
|
}
|
|
rawContent := m.Content.RawMessage
|
|
if !m.Content.Valid || len(rawContent) == 0 {
|
|
rawContent = json.RawMessage("null")
|
|
}
|
|
return tx.store.InsertChatQueuedMessageWithCreator(tx.ctx, database.InsertChatQueuedMessageWithCreatorParams{
|
|
ChatID: tx.chatID,
|
|
Content: rawContent,
|
|
ModelConfigID: m.ModelConfigID,
|
|
ReasoningEffort: m.ReasoningEffort,
|
|
CreatedBy: createdBy,
|
|
BusyBehavior: busyBehavior,
|
|
})
|
|
}
|
|
|
|
// steerLane returns the steer rows that the next delivery moves into
|
|
// history. A steer row under edit holds the whole lane, so it returns
|
|
// none while any steer row is under edit. queued must be in delivery
|
|
// order, with all steer rows first.
|
|
func steerLane(queued []database.ChatQueuedMessage) []database.ChatQueuedMessage {
|
|
n := 0
|
|
for n < len(queued) && queued[n].BusyBehavior == database.ChatBusyBehaviorSteer {
|
|
if queuePaused(queued[n]) {
|
|
return nil
|
|
}
|
|
n++
|
|
}
|
|
return queued[:n]
|
|
}
|
|
|
|
// nextDelivery returns the rows that the next delivery moves into
|
|
// history: the steer lane when steer rows exist, otherwise the queue
|
|
// head. It returns none when the queue is empty, a steer row is under
|
|
// edit, or the queue head is under edit. queued must be in delivery
|
|
// order.
|
|
func nextDelivery(queued []database.ChatQueuedMessage) []database.ChatQueuedMessage {
|
|
if len(queued) == 0 {
|
|
return nil
|
|
}
|
|
if queued[0].BusyBehavior == database.ChatBusyBehaviorSteer {
|
|
return steerLane(queued)
|
|
}
|
|
if queuePaused(queued[0]) {
|
|
return nil
|
|
}
|
|
return queued[:1]
|
|
}
|
|
|
|
type queuedDelivery struct {
|
|
// inserted holds the messages inserted ahead of the delivered rows,
|
|
// then one message for each delivered row.
|
|
inserted []database.ChatMessage
|
|
// delivered is the tail of inserted that holds the delivered rows.
|
|
delivered []database.ChatMessage
|
|
// queuedAt is the enqueue time of the first delivered row, or zero.
|
|
queuedAt time.Time
|
|
}
|
|
|
|
func (tx *Tx) deliverQueuedRows(
|
|
chat database.Chat,
|
|
before []Message,
|
|
rows []database.ChatQueuedMessage,
|
|
) (queuedDelivery, error) {
|
|
messages := make([]Message, 0, len(before)+len(rows))
|
|
messages = append(messages, before...)
|
|
for _, row := range rows {
|
|
m, err := tx.messageFromQueuedRow(chat, row)
|
|
if err != nil {
|
|
return queuedDelivery{}, xerrors.Errorf("resolve queued message %d: %w", row.ID, err)
|
|
}
|
|
messages = append(messages, m)
|
|
}
|
|
inserted, err := tx.insertMessages(messages)
|
|
if err != nil {
|
|
return queuedDelivery{}, xerrors.Errorf("insert delivered messages: %w", err)
|
|
}
|
|
if len(inserted) != len(messages) {
|
|
return queuedDelivery{}, xerrors.Errorf(
|
|
"insert delivered messages: expected %d rows, got %d",
|
|
len(messages), len(inserted),
|
|
)
|
|
}
|
|
for _, row := range rows {
|
|
if err := tx.deletePromotedQueuedMessage(row.ID); err != nil {
|
|
return queuedDelivery{}, xerrors.Errorf("delete delivered queued message: %w", err)
|
|
}
|
|
}
|
|
d := queuedDelivery{
|
|
inserted: inserted,
|
|
delivered: inserted[len(inserted)-len(rows):],
|
|
}
|
|
if len(rows) > 0 {
|
|
d.queuedAt = rows[0].CreatedAt
|
|
}
|
|
return d, nil
|
|
}
|
|
|
|
func (tx *Tx) messageFromQueuedRow(chat database.Chat, queued database.ChatQueuedMessage) (Message, error) {
|
|
modelConfigID, err := tx.resolveQueuedMessageModelConfigID(chat, queued)
|
|
if err != nil {
|
|
return Message{}, err
|
|
}
|
|
return Message{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: pqtype.NullRawMessage{RawMessage: queued.Content, Valid: queued.Content != nil},
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
ModelConfigID: modelConfigID,
|
|
ReasoningEffort: queued.ReasoningEffort,
|
|
CreatedBy: uuid.NullUUID{UUID: queued.CreatedBy, Valid: true},
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
QueuedMessageID: sql.NullInt64{Int64: queued.ID, Valid: true},
|
|
}, nil
|
|
}
|
|
|
|
// deletePromotedQueuedMessage deletes the queue row a promotion just
|
|
// copied into history. The row was read under the chat row lock, so any
|
|
// count other than one means the queue changed underneath the lock; the
|
|
// error rolls back the promotion instead of leaving a duplicate or a
|
|
// message linked to a row that was never removed.
|
|
func (tx *Tx) deletePromotedQueuedMessage(id int64) error {
|
|
rows, err := tx.store.DeleteChatQueuedMessageReturningCount(tx.ctx, database.DeleteChatQueuedMessageReturningCountParams{
|
|
ID: id,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if rows != 1 {
|
|
return xerrors.Errorf("promoted queued message %d: deleted %d rows, want 1", id, rows)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveQueuedMessageModelConfigID returns the first of the queued row's
|
|
// model and the chat's last model that is enabled, has an enabled
|
|
// provider, and belongs to the chat's organization, else the organization
|
|
// default. A lookup error other than sql.ErrNoRows is returned without
|
|
// trying the next candidate.
|
|
func (tx *Tx) resolveQueuedMessageModelConfigID(
|
|
chat database.Chat,
|
|
queued database.ChatQueuedMessage,
|
|
) (uuid.NullUUID, error) {
|
|
//nolint:gocritic // Queue promotion needs daemon access to deployment model configuration.
|
|
ctx := dbauthz.AsChatd(tx.ctx)
|
|
candidates := []uuid.NullUUID{
|
|
queued.ModelConfigID,
|
|
{UUID: chat.LastModelConfigID, Valid: true},
|
|
}
|
|
for _, candidate := range candidates {
|
|
if !candidate.Valid {
|
|
continue
|
|
}
|
|
config, err := tx.store.GetEnabledChatModelConfigByID(ctx, candidate.UUID)
|
|
if err == nil && config.OrganizationID == chat.OrganizationID {
|
|
return candidate, nil
|
|
}
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return uuid.NullUUID{}, xerrors.Errorf(
|
|
"get chat model config %s: %w",
|
|
candidate.UUID,
|
|
err,
|
|
)
|
|
}
|
|
}
|
|
|
|
configs, err := tx.store.GetEnabledChatModelConfigsByOrganization(ctx, chat.OrganizationID)
|
|
if err != nil {
|
|
return uuid.NullUUID{}, xerrors.Errorf("get default chat model config: %w", err)
|
|
}
|
|
for _, config := range configs {
|
|
if config.ChatModelConfig.IsDefault {
|
|
return uuid.NullUUID{UUID: config.ChatModelConfig.ID, Valid: true}, nil
|
|
}
|
|
}
|
|
return uuid.NullUUID{}, ErrNoDefaultChatModelConfig
|
|
}
|
|
|
|
// SetArchivedInput configures [Tx.SetArchived].
|
|
type SetArchivedInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Archived bool
|
|
}
|
|
|
|
// SetArchivedResult is returned by [Tx.SetArchived].
|
|
type SetArchivedResult struct{}
|
|
|
|
// SetArchived sets or clears the chat's archived marker.
|
|
func (tx *Tx) SetArchived(input SetArchivedInput) (SetArchivedResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionSetArchived, input.Snapshot)
|
|
if err != nil {
|
|
return SetArchivedResult{}, err
|
|
}
|
|
if input.Archived == chat.Archived {
|
|
// The matrix only allows SetArchived(true) from W/E0/E1/E1P and
|
|
// SetArchived(false) from XW/XE0/XE1/XE1P. A request whose
|
|
// Archived field already matches the chat's current archived
|
|
// flag is the wrong direction (or a no-op) and must be rejected
|
|
// so we do not silently roll the snapshot or publish a
|
|
// chat:update.
|
|
return SetArchivedResult{}, newTransitionError(
|
|
TransitionSetArchived, from,
|
|
"SetArchived input matches the current archived flag",
|
|
)
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: chat.Status,
|
|
Archived: input.Archived,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: chat.CompactionRequestedAt,
|
|
}); err != nil {
|
|
return SetArchivedResult{}, xerrors.Errorf("update archive: %w", err)
|
|
}
|
|
return SetArchivedResult{}, nil
|
|
}
|
|
|
|
// SetProjectInput configures [Tx.SetProject]. A NULL ProjectID removes
|
|
// the chat from its project.
|
|
type SetProjectInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
ProjectID uuid.NullUUID
|
|
}
|
|
|
|
// SetProjectResult is returned by [Tx.SetProject].
|
|
type SetProjectResult struct {
|
|
// Chat is the row after the move.
|
|
Chat database.Chat
|
|
}
|
|
|
|
// SetProject sets or clears the chat's project. It runs only from W, E0,
|
|
// E1, E1P and P, so no step of the chat runs during a move.
|
|
func (tx *Tx) SetProject(input SetProjectInput) (SetProjectResult, error) {
|
|
chat, _, err := tx.requireFromAllowed(TransitionSetProject, input.Snapshot)
|
|
if err != nil {
|
|
return SetProjectResult{}, err
|
|
}
|
|
if input.ProjectID == chat.ProjectID {
|
|
return SetProjectResult{Chat: chat}, nil
|
|
}
|
|
if err := tx.store.UpdateChatProjectIDByID(tx.ctx, database.UpdateChatProjectIDByIDParams{
|
|
ID: chat.ID,
|
|
ProjectID: input.ProjectID,
|
|
}); err != nil {
|
|
return SetProjectResult{}, xerrors.Errorf("update project: %w", err)
|
|
}
|
|
chat.ProjectID = input.ProjectID
|
|
return SetProjectResult{Chat: chat}, nil
|
|
}
|
|
|
|
// BusyBehavior selects the delivery lane for messages sent to a busy chat.
|
|
type BusyBehavior string
|
|
|
|
const (
|
|
// BusyBehaviorQueue stores the message in the queue lane. It is
|
|
// delivered when a turn or an interruption ends and the steer lane
|
|
// is empty.
|
|
BusyBehaviorQueue BusyBehavior = "queue"
|
|
// BusyBehaviorSteer stores the message in the steer lane. It is
|
|
// delivered before the next assistant model call, or when a turn
|
|
// or an interruption ends.
|
|
BusyBehaviorSteer BusyBehavior = "steer"
|
|
)
|
|
|
|
// SendMessageInput configures [Tx.SendMessage].
|
|
type SendMessageInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Message Message
|
|
BusyBehavior BusyBehavior
|
|
// MaxQueueSize is the maximum number of messages that can be queued
|
|
// in the chat. It must be positive when the send can make the queue
|
|
// longer.
|
|
MaxQueueSize int
|
|
// FileIDs are linked to the chat by [LinkFiles], which caps the
|
|
// chat at MaxFileLinks files.
|
|
FileIDs []uuid.UUID
|
|
MaxFileLinks int
|
|
}
|
|
|
|
// SendMessageResult is returned by [Tx.SendMessage].
|
|
type SendMessageResult struct {
|
|
InsertedMessages []database.ChatMessage
|
|
QueuedMessage *database.ChatQueuedMessage
|
|
// PromotedQueuedAt is zero when no queued message was delivered.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// SendMessage inserts directly in idle states and queues by lane in busy
|
|
// states. From E1, E1P, or P, it queues the message and resumes with the
|
|
// steer lane, or the queue head if no steer messages exist, unless a
|
|
// message under edit blocks the delivery. MaxQueueSize applies only to
|
|
// sends that can make the queue longer.
|
|
func (tx *Tx) SendMessage(input SendMessageInput) (SendMessageResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionSendMessage, input.Snapshot)
|
|
if err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
if input.Message.Role != database.ChatMessageRoleUser {
|
|
return SendMessageResult{}, newTransitionError(
|
|
TransitionSendMessage, from,
|
|
"SendMessage requires a user message",
|
|
)
|
|
}
|
|
switch input.BusyBehavior {
|
|
case BusyBehaviorQueue, BusyBehaviorSteer:
|
|
// ok
|
|
default:
|
|
// Callers must choose a lane explicitly, even when the chat is idle.
|
|
return SendMessageResult{}, newTransitionError(
|
|
TransitionSendMessage, from,
|
|
"invalid BusyBehavior",
|
|
)
|
|
}
|
|
queuedCount, err := tx.store.CountChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("count queued messages: %w", err)
|
|
}
|
|
queue, err := tx.queueState(input.Snapshot)
|
|
if err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
if err := sendMessageQueueCapacityError(from, queue, input.BusyBehavior, queuedCount, input.MaxQueueSize); err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
if err := LinkFiles(tx.ctx, tx.store, tx.chatID, input.FileIDs, input.MaxFileLinks); err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
switch from {
|
|
case StateW, StateE0:
|
|
return tx.sendMessageDirect(chat, input)
|
|
|
|
// Error or paused: queue the message, deliver the steer lane or
|
|
// the queue head into history, clear last_error. A message under
|
|
// edit that holds the delivery keeps the status.
|
|
case StateE1, StateE1P, StateP:
|
|
return tx.sendMessageE1(chat, input)
|
|
|
|
case StateR0, StateR1, StateR1P, StateI0, StateI1, StateI1P, StateA0, StateA1, StateA1P:
|
|
return tx.queueMessage(chat, input)
|
|
}
|
|
return SendMessageResult{}, newTransitionError(TransitionSendMessage, from, "unhandled state in SendMessage")
|
|
}
|
|
|
|
// sendMessageGrowsQueue reports whether SendMessage from the state can
|
|
// make the queue longer. W and E0 insert the message into history. E1
|
|
// queues the message, but it also delivers at least one queued message
|
|
// in the same transaction. In E1P and P a message under edit holds the
|
|
// queue. A queue send waits. A steer send waits only when a steer
|
|
// message is under edit; when the queue head is under edit, the steer
|
|
// lane holds only the new message, which is delivered at once.
|
|
func sendMessageGrowsQueue(from ExecutionState, queue QueueState, busy BusyBehavior) bool {
|
|
switch from {
|
|
case StateW, StateE0, StateE1:
|
|
return false
|
|
case StateE1P, StateP:
|
|
return busy != BusyBehaviorSteer || queue.HeadSteer
|
|
default:
|
|
return true
|
|
}
|
|
}
|
|
|
|
// CheckSendMessageQueueCapacity returns a *MessageQueueFullError when
|
|
// SendMessage from chat, with the given queue state, busy behavior, and
|
|
// queuedCount queued messages, would add to a full queue.
|
|
// [Tx.SendMessage] runs the same check under the row lock; callers
|
|
// outside a transaction can call it first to reject a send early.
|
|
func CheckSendMessageQueueCapacity(chat database.Chat, queue QueueState, busy BusyBehavior, queuedCount int64, maxQueueSize int) error {
|
|
return sendMessageQueueCapacityError(ClassifyExecutionState(chat, queue, true), queue, busy, queuedCount, maxQueueSize)
|
|
}
|
|
|
|
func sendMessageQueueCapacityError(from ExecutionState, queue QueueState, busy BusyBehavior, queuedCount int64, maxQueueSize int) error {
|
|
if !sendMessageGrowsQueue(from, queue, busy) {
|
|
return nil
|
|
}
|
|
if maxQueueSize <= 0 {
|
|
return xerrors.Errorf("max queue size must be positive, got %d", maxQueueSize)
|
|
}
|
|
if queuedCount >= int64(maxQueueSize) {
|
|
return &MessageQueueFullError{Max: int64(maxQueueSize)}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (tx *Tx) sendMessageDirect(chat database.Chat, input SendMessageInput) (SendMessageResult, error) {
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, "Tool execution interrupted by new user message", false)
|
|
if err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
inserted, err := tx.insertMessages(append(cancels, input.Message))
|
|
if err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("insert direct user message: %w", err)
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: pqtype.NullRawMessage{},
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return SendMessageResult{
|
|
InsertedMessages: inserted,
|
|
}, nil
|
|
}
|
|
|
|
// sendMessageE1 queues the message from E1, E1P, or P. A non-empty
|
|
// next delivery moves into history and the chat runs with last_error
|
|
// cleared. Otherwise a message under edit holds the delivery and the
|
|
// chat keeps its status.
|
|
func (tx *Tx) sendMessageE1(chat database.Chat, input SendMessageInput) (SendMessageResult, error) {
|
|
queued, err := tx.insertQueuedMessage(chat.OwnerID, input.Message, database.ChatBusyBehavior(input.BusyBehavior))
|
|
if err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("insert queued: %w", err)
|
|
}
|
|
queue, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("get queued messages: %w", err)
|
|
}
|
|
rows := nextDelivery(queue)
|
|
if len(rows) == 0 {
|
|
if err := tx.keepStatusAfterQueue(chat); err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
return SendMessageResult{QueuedMessage: &queued}, nil
|
|
}
|
|
_, d, err := tx.promoteQueuedRows(chat, rows)
|
|
if err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
result := SendMessageResult{
|
|
InsertedMessages: d.inserted,
|
|
PromotedQueuedAt: d.queuedAt,
|
|
}
|
|
if !slices.ContainsFunc(d.delivered, func(m database.ChatMessage) bool {
|
|
return m.QueuedMessageID.Int64 == queued.ID
|
|
}) {
|
|
result.QueuedMessage = &queued
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func (tx *Tx) queueMessage(chat database.Chat, input SendMessageInput) (SendMessageResult, error) {
|
|
queued, err := tx.insertQueuedMessage(chat.OwnerID, input.Message, database.ChatBusyBehavior(input.BusyBehavior))
|
|
if err != nil {
|
|
return SendMessageResult{}, xerrors.Errorf("insert queued: %w", err)
|
|
}
|
|
if err := tx.keepStatusAfterQueue(chat); err != nil {
|
|
return SendMessageResult{}, err
|
|
}
|
|
return SendMessageResult{
|
|
QueuedMessage: &queued,
|
|
}, nil
|
|
}
|
|
|
|
// keepStatusAfterQueue writes the chat's execution state back unchanged
|
|
// after a send queues a message.
|
|
func (tx *Tx) keepStatusAfterQueue(chat database.Chat) error {
|
|
// Queueing does not start a new turn, so a pending manual
|
|
// compaction request stays live: the in-flight compaction
|
|
// commits first and the queued message is promoted afterwards.
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: chat.Status,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: chat.CompactionRequestedAt,
|
|
}); err != nil {
|
|
return xerrors.Errorf("update status: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// EditMessageInput configures [Tx.EditMessage].
|
|
type EditMessageInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
MessageID int64
|
|
// SuffixMessages are inserted after the replacement message in the
|
|
// same transaction, so a later edit's suffix truncation cleans them
|
|
// up together with the rest of the discarded turn.
|
|
SuffixMessages []Message
|
|
CreatedBy uuid.UUID
|
|
Content pqtype.NullRawMessage
|
|
ModelConfigIDOverride uuid.NullUUID
|
|
ReasoningEffortOverride database.NullChatReasoningEffort
|
|
// FileIDs are linked to the chat by [LinkFiles], which caps the
|
|
// chat at MaxFileLinks files.
|
|
FileIDs []uuid.UUID
|
|
MaxFileLinks int
|
|
}
|
|
|
|
// EditMessageResult is returned by [Tx.EditMessage].
|
|
type EditMessageResult struct {
|
|
ReplacementMessage database.ChatMessage
|
|
DeletedMessageIDs []int64
|
|
DeletedQueuedMessageIDs []int64
|
|
CancellationMessages []database.ChatMessage
|
|
SuffixMessages []database.ChatMessage
|
|
}
|
|
|
|
// EditMessage replaces an earlier user message and discards the
|
|
// active-history suffix that followed it.
|
|
func (tx *Tx) EditMessage(input EditMessageInput) (EditMessageResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionEditMessage, input.Snapshot)
|
|
if err != nil {
|
|
return EditMessageResult{}, err
|
|
}
|
|
target, err := tx.store.GetChatMessageByID(tx.ctx, input.MessageID)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return EditMessageResult{}, ErrMessageNotFound
|
|
}
|
|
return EditMessageResult{}, xerrors.Errorf("get target message: %w", err)
|
|
}
|
|
if target.ChatID != tx.chatID {
|
|
return EditMessageResult{}, ErrMessageNotFound
|
|
}
|
|
if target.Deleted {
|
|
return EditMessageResult{}, ErrMessageNotFound
|
|
}
|
|
if target.Role != database.ChatMessageRoleUser {
|
|
return EditMessageResult{}, newTransitionErrorWithCause(
|
|
TransitionEditMessage, from,
|
|
ErrEditedMessageNotUser,
|
|
"only user messages can be edited",
|
|
)
|
|
}
|
|
if err := LinkFiles(tx.ctx, tx.store, tx.chatID, input.FileIDs, input.MaxFileLinks); err != nil {
|
|
return EditMessageResult{}, err
|
|
}
|
|
|
|
suffix, err := tx.store.GetChatMessagesByChatID(tx.ctx, database.GetChatMessagesByChatIDParams{
|
|
ChatID: tx.chatID,
|
|
AfterID: target.ID - 1, // include target and everything after
|
|
})
|
|
if err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("get suffix messages: %w", err)
|
|
}
|
|
deletedIDs := make([]int64, 0, len(suffix))
|
|
for _, m := range suffix {
|
|
if !m.Deleted {
|
|
deletedIDs = append(deletedIDs, m.ID)
|
|
}
|
|
}
|
|
|
|
if err := tx.store.SoftDeleteChatMessagesAfterID(tx.ctx, database.SoftDeleteChatMessagesAfterIDParams{
|
|
ChatID: tx.chatID,
|
|
AfterID: target.ID - 1, // AfterID is exclusive; - 1 includes target.
|
|
}); err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("soft-delete suffix: %w", err)
|
|
}
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, "Tool execution interrupted by message edit", false)
|
|
if err != nil {
|
|
return EditMessageResult{}, err
|
|
}
|
|
cancellationMessages, err := tx.insertMessages(cancels)
|
|
if err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("insert message edit cancellations: %w", err)
|
|
}
|
|
|
|
modelConfig := target.ModelConfigID
|
|
if input.ModelConfigIDOverride.Valid {
|
|
modelConfig = input.ModelConfigIDOverride
|
|
}
|
|
reasoningEffort := target.ReasoningEffort
|
|
if input.ReasoningEffortOverride.Valid {
|
|
reasoningEffort = input.ReasoningEffortOverride
|
|
}
|
|
replacement := Message{
|
|
Role: database.ChatMessageRoleUser,
|
|
Content: input.Content,
|
|
Visibility: target.Visibility,
|
|
ModelConfigID: modelConfig,
|
|
ReasoningEffort: reasoningEffort,
|
|
CreatedBy: uuid.NullUUID{UUID: input.CreatedBy, Valid: true},
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
}
|
|
insertedReplacement, err := tx.insertMessages([]Message{replacement})
|
|
if err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("insert replacement message: %w", err)
|
|
}
|
|
var replacementRow database.ChatMessage
|
|
if len(insertedReplacement) == 1 {
|
|
replacementRow = insertedReplacement[0]
|
|
}
|
|
insertedSuffix, err := tx.insertMessages(input.SuffixMessages)
|
|
if err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("insert edit suffix messages: %w", err)
|
|
}
|
|
|
|
deletedQueuedIDs, err := tx.clearQueue()
|
|
if err != nil {
|
|
return EditMessageResult{}, err
|
|
}
|
|
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: pqtype.NullRawMessage{},
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return EditMessageResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return EditMessageResult{
|
|
ReplacementMessage: replacementRow,
|
|
DeletedMessageIDs: deletedIDs,
|
|
DeletedQueuedMessageIDs: deletedQueuedIDs,
|
|
CancellationMessages: cancellationMessages,
|
|
SuffixMessages: insertedSuffix,
|
|
}, nil
|
|
}
|
|
|
|
// RequestCompactionInput configures [Tx.RequestCompaction]. The
|
|
// compaction turn derives AI Gateway attribution from the owner's
|
|
// synthetic API key, so the request carries no caller input.
|
|
type RequestCompactionInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// RequestCompactionResult is returned by [Tx.RequestCompaction].
|
|
type RequestCompactionResult struct {
|
|
Chat database.Chat
|
|
}
|
|
|
|
// RequestCompaction records a manual compaction request, clears any
|
|
// prior error, and hands ownership off to a worker. The transition
|
|
// changes no history, so the previous runner cannot detect the work
|
|
// from its existing running snapshot. Clearing ownership makes
|
|
// ChatMachine.Update publish an ownership hint for worker acquisition.
|
|
//
|
|
// The compaction turn gets the same fresh history epoch a history
|
|
// change would grant: a full retry budget regardless of how the
|
|
// previous turn spent its own, and message part episode keys that
|
|
// cannot collide with episodes the failed turn's replica retains.
|
|
func (tx *Tx) RequestCompaction(input RequestCompactionInput) (RequestCompactionResult, error) {
|
|
_, _, err := tx.requireFromAllowed(TransitionRequestCompaction, input.Snapshot)
|
|
if err != nil {
|
|
return RequestCompactionResult{}, err
|
|
}
|
|
now, err := tx.store.GetDatabaseNow(tx.ctx)
|
|
if err != nil {
|
|
return RequestCompactionResult{}, xerrors.Errorf("get db now: %w", err)
|
|
}
|
|
updated, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: uuid.NullUUID{},
|
|
RunnerID: uuid.NullUUID{},
|
|
LastError: pqtype.NullRawMessage{},
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
CompactionRequestedAt: sql.NullTime{Time: now, Valid: true},
|
|
GrantHistoryEpoch: true,
|
|
})
|
|
if err != nil {
|
|
return RequestCompactionResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return RequestCompactionResult{Chat: updated}, nil
|
|
}
|
|
|
|
// ClearContextInput configures [Tx.ClearContext]. Messages carries
|
|
// the boundary rows built by chatd; chatstate requires a non-empty
|
|
// batch so the insert trigger grants the fresh history epoch.
|
|
type ClearContextInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Messages []Message
|
|
}
|
|
|
|
// ClearContextResult is returned by [Tx.ClearContext].
|
|
type ClearContextResult struct {
|
|
Chat database.Chat
|
|
InsertedMessages []database.ChatMessage
|
|
}
|
|
|
|
// ClearContext commits a synchronous context reset: it inserts the
|
|
// caller-built boundary rows, clears any stored error and pending
|
|
// compaction request, preserves ownership, and lands in waiting. No
|
|
// worker turn is needed; the message insert trigger advances
|
|
// history_version and resets the retry budget.
|
|
func (tx *Tx) ClearContext(input ClearContextInput) (ClearContextResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionClearContext, input.Snapshot)
|
|
if err != nil {
|
|
return ClearContextResult{}, err
|
|
}
|
|
if len(input.Messages) == 0 {
|
|
return ClearContextResult{}, newTransitionError(
|
|
TransitionClearContext, from,
|
|
"ClearContext requires boundary messages",
|
|
)
|
|
}
|
|
inserted, err := tx.insertMessages(input.Messages)
|
|
if err != nil {
|
|
return ClearContextResult{}, xerrors.Errorf("insert clear boundary messages: %w", err)
|
|
}
|
|
updated, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusWaiting,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: pqtype.NullRawMessage{},
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
})
|
|
if err != nil {
|
|
return ClearContextResult{}, xerrors.Errorf("set waiting: %w", err)
|
|
}
|
|
return ClearContextResult{Chat: updated, InsertedMessages: inserted}, nil
|
|
}
|
|
|
|
// requireQueuedMessageTransition is requireFromAllowed for a transition
|
|
// on one queued message. When t is refused and the message does not
|
|
// exist, it returns ErrQueuedMessageNotFound.
|
|
func (tx *Tx) requireQueuedMessageTransition(t Transition, snapshot *ChatSnapshot, id int64) (database.Chat, ExecutionState, error) {
|
|
chat, from, err := tx.requireFromAllowed(t, snapshot)
|
|
if !errors.Is(err, ErrTransitionNotAllowed) {
|
|
return chat, from, err
|
|
}
|
|
_, lookupErr := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
|
ID: id,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if errors.Is(lookupErr, sql.ErrNoRows) {
|
|
return chat, from, ErrQueuedMessageNotFound
|
|
}
|
|
if lookupErr != nil {
|
|
return chat, from, xerrors.Errorf("get queued: %w", lookupErr)
|
|
}
|
|
return chat, from, err
|
|
}
|
|
|
|
// DeleteQueuedMessageInput configures [Tx.DeleteQueuedMessage].
|
|
type DeleteQueuedMessageInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
QueuedMessageID int64
|
|
}
|
|
|
|
// DeleteQueuedMessageResult is returned by [Tx.DeleteQueuedMessage].
|
|
type DeleteQueuedMessageResult struct {
|
|
DeletedQueuedMessage database.ChatQueuedMessage
|
|
// Chat is the updated chat when the transition left P, else nil.
|
|
Chat *database.Chat
|
|
// PromotedQueuedAt is zero when no queue head was promoted.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// DeleteQueuedMessage removes a single queued user message. From P it
|
|
// leaves paused once the head is ready or the queue is empty (see
|
|
// leavePaused).
|
|
func (tx *Tx) DeleteQueuedMessage(input DeleteQueuedMessageInput) (DeleteQueuedMessageResult, error) {
|
|
chat, from, err := tx.requireQueuedMessageTransition(TransitionDeleteQueuedMessage, input.Snapshot, input.QueuedMessageID)
|
|
if err != nil {
|
|
return DeleteQueuedMessageResult{}, err
|
|
}
|
|
target, err := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
|
ID: input.QueuedMessageID,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return DeleteQueuedMessageResult{}, ErrQueuedMessageNotFound
|
|
}
|
|
if err != nil {
|
|
return DeleteQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err)
|
|
}
|
|
rows, err := tx.store.DeleteChatQueuedMessageReturningCount(tx.ctx, database.DeleteChatQueuedMessageReturningCountParams{
|
|
ID: input.QueuedMessageID,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if err != nil {
|
|
return DeleteQueuedMessageResult{}, xerrors.Errorf("delete queued: %w", err)
|
|
}
|
|
if rows == 0 {
|
|
return DeleteQueuedMessageResult{}, ErrQueuedMessageNotFound
|
|
}
|
|
result := DeleteQueuedMessageResult{DeletedQueuedMessage: target}
|
|
if from == StateP {
|
|
result.Chat, result.PromotedQueuedAt, err = tx.leavePaused(chat)
|
|
if err != nil {
|
|
return DeleteQueuedMessageResult{}, err
|
|
}
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// EditQueuedMessageInput configures [Tx.EditQueuedMessage]. Nil fields
|
|
// leave the corresponding column untouched.
|
|
type EditQueuedMessageInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
QueuedMessageID int64
|
|
// Content is the chatprompt.MarshalParts encoding of the message parts.
|
|
Content json.RawMessage
|
|
// ModelConfigIDOverride, ReasoningEffortOverride, and FileIDs apply
|
|
// only together with Content. FileIDs are linked to the chat by
|
|
// [LinkFiles], which caps the chat at MaxFileLinks files.
|
|
ModelConfigIDOverride uuid.NullUUID
|
|
ReasoningEffortOverride database.NullChatReasoningEffort
|
|
FileIDs []uuid.UUID
|
|
MaxFileLinks int
|
|
// Editing begins (true) or ends (false) the row's edit.
|
|
Editing *bool
|
|
}
|
|
|
|
// EditQueuedMessageResult is returned by [Tx.EditQueuedMessage].
|
|
type EditQueuedMessageResult struct {
|
|
QueuedMessage database.ChatQueuedMessage
|
|
// Chat is the updated chat when the transition left P, else nil.
|
|
Chat *database.Chat
|
|
// PromotedQueuedAt is zero when no queue head was promoted.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// EditQueuedMessage changes a queued row's content, edit marker, or
|
|
// both. Beginning an edit on a row ends any other row's edit. From P,
|
|
// ending the edit that holds the queue leaves paused (see leavePaused);
|
|
// beginning an edit on a different row is refused with
|
|
// [ErrPausedQueuedHeadUnderEdit].
|
|
func (tx *Tx) EditQueuedMessage(input EditQueuedMessageInput) (EditQueuedMessageResult, error) {
|
|
chat, from, err := tx.requireQueuedMessageTransition(TransitionEditQueuedMessage, input.Snapshot, input.QueuedMessageID)
|
|
if err != nil {
|
|
return EditQueuedMessageResult{}, err
|
|
}
|
|
if input.Content == nil && input.Editing == nil {
|
|
return EditQueuedMessageResult{}, newTransitionError(
|
|
TransitionEditQueuedMessage, from,
|
|
"EditQueuedMessage requires content or editing",
|
|
)
|
|
}
|
|
row, err := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
|
ID: input.QueuedMessageID,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return EditQueuedMessageResult{}, ErrQueuedMessageNotFound
|
|
}
|
|
if err != nil {
|
|
return EditQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err)
|
|
}
|
|
if from == StateP && input.Editing != nil && *input.Editing && !row.EditingSince.Valid {
|
|
return EditQueuedMessageResult{}, ErrPausedQueuedHeadUnderEdit
|
|
}
|
|
var result EditQueuedMessageResult
|
|
if input.Content != nil {
|
|
modelConfig := row.ModelConfigID
|
|
if input.ModelConfigIDOverride.Valid {
|
|
modelConfig = input.ModelConfigIDOverride
|
|
}
|
|
reasoningEffort := row.ReasoningEffort
|
|
if input.ReasoningEffortOverride.Valid {
|
|
reasoningEffort = input.ReasoningEffortOverride
|
|
}
|
|
row, err = tx.store.UpdateChatQueuedMessageContent(tx.ctx, database.UpdateChatQueuedMessageContentParams{
|
|
ID: row.ID,
|
|
ChatID: tx.chatID,
|
|
Content: input.Content,
|
|
ModelConfigID: modelConfig,
|
|
ReasoningEffort: reasoningEffort,
|
|
})
|
|
if err != nil {
|
|
return EditQueuedMessageResult{}, xerrors.Errorf("update queued content: %w", err)
|
|
}
|
|
if err := LinkFiles(tx.ctx, tx.store, tx.chatID, input.FileIDs, input.MaxFileLinks); err != nil {
|
|
return EditQueuedMessageResult{}, err
|
|
}
|
|
}
|
|
if input.Editing != nil {
|
|
if *input.Editing && !row.EditingSince.Valid {
|
|
if err := tx.endOtherEdit(row.ID); err != nil {
|
|
return EditQueuedMessageResult{}, err
|
|
}
|
|
}
|
|
row, err = tx.store.UpdateChatQueuedMessageEditing(tx.ctx, database.UpdateChatQueuedMessageEditingParams{
|
|
ID: row.ID,
|
|
ChatID: tx.chatID,
|
|
Editing: *input.Editing,
|
|
})
|
|
if err != nil {
|
|
return EditQueuedMessageResult{}, xerrors.Errorf("update queued editing: %w", err)
|
|
}
|
|
if from == StateP && !*input.Editing {
|
|
result.Chat, result.PromotedQueuedAt, err = tx.leavePaused(chat)
|
|
if err != nil {
|
|
return EditQueuedMessageResult{}, err
|
|
}
|
|
}
|
|
}
|
|
result.QueuedMessage = row
|
|
return result, nil
|
|
}
|
|
|
|
// endOtherEdit clears editing_since on the chat's row under edit if it
|
|
// is not exceptID.
|
|
func (tx *Tx) endOtherEdit(exceptID int64) error {
|
|
queue, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return xerrors.Errorf("get queued messages: %w", err)
|
|
}
|
|
for _, other := range queue {
|
|
if !other.EditingSince.Valid || other.ID == exceptID {
|
|
continue
|
|
}
|
|
if _, err := tx.store.UpdateChatQueuedMessageEditing(tx.ctx, database.UpdateChatQueuedMessageEditingParams{
|
|
ID: other.ID,
|
|
ChatID: tx.chatID,
|
|
Editing: false,
|
|
}); err != nil {
|
|
return xerrors.Errorf("end other row's edit: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// leavePaused runs advanceQueue for a chat in P. It returns the updated
|
|
// chat, or nil when the chat stays in P, and the promoted head's queued
|
|
// time, or zero when nothing was promoted.
|
|
func (tx *Tx) leavePaused(chat database.Chat) (*database.Chat, time.Time, error) {
|
|
updated, d, err := tx.advanceQueue(chat)
|
|
if err != nil || updated.Status == chat.Status {
|
|
return nil, time.Time{}, err
|
|
}
|
|
return &updated, d.queuedAt, nil
|
|
}
|
|
|
|
// advanceQueue moves the chat on by its queue when a turn or an
|
|
// interruption ends, or when P may resume: an empty queue sets W, a
|
|
// held delivery sets P, and a non-empty next delivery is promoted and
|
|
// the chat runs. A chat already in the resulting status is
|
|
// not written.
|
|
func (tx *Tx) advanceQueue(chat database.Chat) (database.Chat, queuedDelivery, error) {
|
|
queued, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return database.Chat{}, queuedDelivery{}, xerrors.Errorf("get queued messages: %w", err)
|
|
}
|
|
if rows := nextDelivery(queued); len(rows) > 0 {
|
|
return tx.promoteQueuedRows(chat, rows)
|
|
}
|
|
status := database.ChatStatusWaiting
|
|
if len(queued) > 0 {
|
|
status = database.ChatStatusPaused
|
|
}
|
|
if chat.Status == status {
|
|
return chat, queuedDelivery{}, nil
|
|
}
|
|
updated, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: status,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, queuedDelivery{}, xerrors.Errorf("set %s: %w", status, err)
|
|
}
|
|
return updated, queuedDelivery{}, nil
|
|
}
|
|
|
|
// promoteQueuedRows pops rows out of the queue into active history and
|
|
// sets the chat running with last_error cleared. Every outstanding tool
|
|
// call, dynamic or not, is closed first so the LLM history stays valid.
|
|
func (tx *Tx) promoteQueuedRows(chat database.Chat, rows []database.ChatQueuedMessage) (database.Chat, queuedDelivery, error) {
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, "Tool execution interrupted by queued message promotion", false)
|
|
if err != nil {
|
|
return database.Chat{}, queuedDelivery{}, err
|
|
}
|
|
d, err := tx.deliverQueuedRows(chat, cancels, rows)
|
|
if err != nil {
|
|
return database.Chat{}, queuedDelivery{}, err
|
|
}
|
|
updated, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: pqtype.NullRawMessage{},
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
})
|
|
if err != nil {
|
|
return database.Chat{}, queuedDelivery{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return updated, d, nil
|
|
}
|
|
|
|
// SteerQueuedMessageInput configures [Tx.SteerQueuedMessage].
|
|
type SteerQueuedMessageInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
QueuedMessageID int64
|
|
}
|
|
|
|
// SteerQueuedMessageResult is returned by [Tx.SteerQueuedMessage].
|
|
type SteerQueuedMessageResult struct {
|
|
// InsertedMessages holds the tool call cancellations and then the
|
|
// delivered steer rows. Only E1, E1P, and P deliver; every other
|
|
// state leaves it empty.
|
|
InsertedMessages []database.ChatMessage
|
|
// PromotedQueuedAt is zero when no queued message was delivered.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// SteerQueuedMessage ends the target's edit, if any, then moves a queue
|
|
// row behind existing steer rows, without reordering an existing steer
|
|
// row. From E1, E1P, or P, a non-empty next delivery moves into history
|
|
// and the chat runs with last_error cleared. Otherwise the chat keeps its
|
|
// status.
|
|
func (tx *Tx) SteerQueuedMessage(input SteerQueuedMessageInput) (SteerQueuedMessageResult, error) {
|
|
chat, from, err := tx.requireQueuedMessageTransition(TransitionSteerQueuedMessage, input.Snapshot, input.QueuedMessageID)
|
|
if err != nil {
|
|
return SteerQueuedMessageResult{}, err
|
|
}
|
|
target, err := tx.store.GetChatQueuedMessageByID(tx.ctx, database.GetChatQueuedMessageByIDParams{
|
|
ID: input.QueuedMessageID,
|
|
ChatID: tx.chatID,
|
|
})
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return SteerQueuedMessageResult{}, ErrQueuedMessageNotFound
|
|
}
|
|
if err != nil {
|
|
return SteerQueuedMessageResult{}, xerrors.Errorf("get queued: %w", err)
|
|
}
|
|
if target.EditingSince.Valid {
|
|
if _, err := tx.store.UpdateChatQueuedMessageEditing(tx.ctx, database.UpdateChatQueuedMessageEditingParams{
|
|
ID: target.ID,
|
|
ChatID: tx.chatID,
|
|
Editing: false,
|
|
}); err != nil {
|
|
return SteerQueuedMessageResult{}, xerrors.Errorf("end queued edit: %w", err)
|
|
}
|
|
}
|
|
if target.BusyBehavior == database.ChatBusyBehaviorQueue {
|
|
if _, err := tx.store.SteerChatQueuedMessage(tx.ctx, database.SteerChatQueuedMessageParams{
|
|
ID: target.ID,
|
|
ChatID: tx.chatID,
|
|
}); err != nil {
|
|
return SteerQueuedMessageResult{}, xerrors.Errorf("steer queued: %w", err)
|
|
}
|
|
}
|
|
if from != StateE1 && from != StateE1P && from != StateP {
|
|
return SteerQueuedMessageResult{}, nil
|
|
}
|
|
queue, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return SteerQueuedMessageResult{}, xerrors.Errorf("get queued messages: %w", err)
|
|
}
|
|
rows := nextDelivery(queue)
|
|
if len(rows) == 0 {
|
|
return SteerQueuedMessageResult{}, nil
|
|
}
|
|
_, d, err := tx.promoteQueuedRows(chat, rows)
|
|
if err != nil {
|
|
return SteerQueuedMessageResult{}, err
|
|
}
|
|
return SteerQueuedMessageResult{
|
|
InsertedMessages: d.inserted,
|
|
PromotedQueuedAt: d.queuedAt,
|
|
}, nil
|
|
}
|
|
|
|
// InterruptInput configures [Tx.Interrupt].
|
|
type InterruptInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Reason string
|
|
}
|
|
|
|
// InterruptResult is returned by [Tx.Interrupt].
|
|
type InterruptResult struct {
|
|
// Interrupted is false when the chat had nothing to interrupt and
|
|
// the call left it unchanged.
|
|
Interrupted bool
|
|
CancellationMessages []database.ChatMessage
|
|
// PromotedQueuedAt is zero when no queue head was promoted.
|
|
PromotedQueuedAt time.Time
|
|
// FinishedInterruption reports that the call also applied
|
|
// FinishInterruption because no worker owns the chat.
|
|
FinishedInterruption bool
|
|
}
|
|
|
|
// Interrupt requests interruption of an active or requires-action
|
|
// chat. It also finishes the pending interruption of an unowned
|
|
// interrupting chat. An idle or errored chat, or an interrupting chat
|
|
// that its runner is already finishing, has nothing to interrupt, so
|
|
// the call succeeds without changing it.
|
|
func (tx *Tx) Interrupt(input InterruptInput) (InterruptResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionInterrupt, input.Snapshot)
|
|
if err != nil {
|
|
return InterruptResult{}, err
|
|
}
|
|
reason := input.Reason
|
|
if reason == "" {
|
|
reason = "Tool execution interrupted by user"
|
|
}
|
|
switch from {
|
|
case StateW, StateE0, StateE1, StateE1P, StateP:
|
|
return InterruptResult{}, nil
|
|
case StateI0, StateI1, StateI1P:
|
|
if chat.WorkerID.Valid {
|
|
return InterruptResult{}, nil
|
|
}
|
|
// An unowned interrupting chat has no runner, and a worker would
|
|
// need a capacity slot to finish it, so finish it here instead.
|
|
finished, err := tx.finishUnownedInterruption(chat, reason)
|
|
if err != nil {
|
|
return InterruptResult{}, err
|
|
}
|
|
return InterruptResult{
|
|
Interrupted: true,
|
|
CancellationMessages: finished.cancellations,
|
|
PromotedQueuedAt: finished.PromotedQueuedAt,
|
|
FinishedInterruption: true,
|
|
}, nil
|
|
case StateR0, StateR1, StateR1P:
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusInterrupting,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
}); err != nil {
|
|
return InterruptResult{}, xerrors.Errorf("set interrupting: %w", err)
|
|
}
|
|
if chat.WorkerID.Valid {
|
|
return InterruptResult{Interrupted: true}, nil
|
|
}
|
|
finished, err := tx.finishUnownedInterruption(chat, reason)
|
|
if err != nil {
|
|
return InterruptResult{}, err
|
|
}
|
|
return InterruptResult{
|
|
Interrupted: true,
|
|
CancellationMessages: finished.cancellations,
|
|
PromotedQueuedAt: finished.PromotedQueuedAt,
|
|
FinishedInterruption: true,
|
|
}, nil
|
|
case StateA0, StateA1, StateA1P:
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, reason, true)
|
|
if err != nil {
|
|
return InterruptResult{}, err
|
|
}
|
|
inserted, err := tx.insertMessages(cancels)
|
|
if err != nil {
|
|
return InterruptResult{}, xerrors.Errorf("insert interrupt cancellations: %w", err)
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return InterruptResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return InterruptResult{
|
|
Interrupted: true,
|
|
CancellationMessages: inserted,
|
|
}, nil
|
|
default:
|
|
return InterruptResult{}, newTransitionError(TransitionInterrupt, from, "unhandled state in Interrupt")
|
|
}
|
|
}
|
|
|
|
type unownedInterruption struct {
|
|
FinishInterruptionResult
|
|
cancellations []database.ChatMessage
|
|
}
|
|
|
|
// Finish inline so a full worker pool cannot block interruption cleanup.
|
|
// The chat stays unowned; its next turn still needs capacity admission.
|
|
func (tx *Tx) finishUnownedInterruption(chat database.Chat, reason string) (unownedInterruption, error) {
|
|
if chat.WorkerID.Valid {
|
|
return unownedInterruption{}, xerrors.New("finish unowned interruption: chat is owned")
|
|
}
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, reason, false)
|
|
if err != nil {
|
|
return unownedInterruption{}, err
|
|
}
|
|
finished, err := tx.FinishInterruption(FinishInterruptionInput{PartialMessages: cancels})
|
|
if err != nil {
|
|
return unownedInterruption{}, xerrors.Errorf("finish unowned interruption: %w", err)
|
|
}
|
|
if len(finished.InsertedMessages) < len(cancels) {
|
|
return unownedInterruption{}, xerrors.Errorf(
|
|
"finish unowned interruption: inserted %d messages, want at least %d",
|
|
len(finished.InsertedMessages), len(cancels),
|
|
)
|
|
}
|
|
return unownedInterruption{
|
|
FinishInterruptionResult: finished,
|
|
cancellations: finished.InsertedMessages[:len(cancels)],
|
|
}, nil
|
|
}
|
|
|
|
// ToolResultInput is one submitted dynamic-tool result.
|
|
type ToolResultInput struct {
|
|
ToolCallID string
|
|
Output json.RawMessage
|
|
IsError bool
|
|
}
|
|
|
|
// CompleteRequiresActionInput configures [Tx.CompleteRequiresAction].
|
|
type CompleteRequiresActionInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
CreatedBy uuid.UUID
|
|
ModelConfigID uuid.UUID
|
|
Results []ToolResultInput
|
|
SuffixMessages []Message
|
|
}
|
|
|
|
// CompleteRequiresActionResult is returned by [Tx.CompleteRequiresAction].
|
|
type CompleteRequiresActionResult struct {
|
|
InsertedMessages []database.ChatMessage
|
|
}
|
|
|
|
// CompleteRequiresAction validates and stores user-submitted tool
|
|
// results that satisfy the chat's pending dynamic tool calls, then
|
|
// returns the chat to running.
|
|
func (tx *Tx) CompleteRequiresAction(input CompleteRequiresActionInput) (CompleteRequiresActionResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionCompleteRequiresAction, input.Snapshot)
|
|
if err != nil {
|
|
return CompleteRequiresActionResult{}, err
|
|
}
|
|
pending, err := pendingDynamicToolCallIDs(tx.ctx, tx.store, chat)
|
|
if err != nil {
|
|
return CompleteRequiresActionResult{}, err
|
|
}
|
|
if invalid := ValidateToolResults(input.Results, pending); invalid != nil {
|
|
return CompleteRequiresActionResult{}, newTransitionErrorWithCause(
|
|
TransitionCompleteRequiresAction, from, invalid,
|
|
toolResultTransitionMessage(invalid.Cause),
|
|
)
|
|
}
|
|
messages := make([]Message, 0, len(input.Results))
|
|
for _, r := range input.Results {
|
|
part := codersdk.ChatMessagePart{
|
|
Type: codersdk.ChatMessagePartTypeToolResult,
|
|
ToolCallID: r.ToolCallID,
|
|
ToolName: pending[r.ToolCallID],
|
|
Result: r.Output,
|
|
IsError: r.IsError,
|
|
}
|
|
raw, err := chatprompt.MarshalParts([]codersdk.ChatMessagePart{part})
|
|
if err != nil {
|
|
return CompleteRequiresActionResult{}, xerrors.Errorf("marshal tool result: %w", err)
|
|
}
|
|
messages = append(messages, Message{
|
|
Role: database.ChatMessageRoleTool,
|
|
Content: raw,
|
|
Visibility: database.ChatMessageVisibilityBoth,
|
|
CreatedBy: uuid.NullUUID{UUID: input.CreatedBy, Valid: true},
|
|
ModelConfigID: uuid.NullUUID{UUID: input.ModelConfigID, Valid: true},
|
|
ContentVersion: chatprompt.CurrentContentVersion,
|
|
})
|
|
}
|
|
inserted, err := tx.insertMessages(append(messages, input.SuffixMessages...))
|
|
if err != nil {
|
|
return CompleteRequiresActionResult{}, xerrors.Errorf("insert tool results: %w", err)
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return CompleteRequiresActionResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return CompleteRequiresActionResult{
|
|
InsertedMessages: inserted,
|
|
}, nil
|
|
}
|
|
|
|
func toolResultTransitionMessage(cause error) string {
|
|
switch {
|
|
case errors.Is(cause, ErrToolResultDuplicate):
|
|
return "duplicate tool_call_id submitted"
|
|
case errors.Is(cause, ErrToolResultInvalidJSON):
|
|
return "tool result output is not valid JSON"
|
|
case errors.Is(cause, ErrToolResultMissing):
|
|
return "submitted tool results do not match pending tool calls"
|
|
case errors.Is(cause, ErrToolResultUnexpected):
|
|
return "submitted tool_call_id does not match a pending dynamic tool call"
|
|
default:
|
|
return "submitted tool results are invalid"
|
|
}
|
|
}
|
|
|
|
// AcquireInput configures [Tx.Acquire].
|
|
type AcquireInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
WorkerID uuid.UUID
|
|
RunnerID uuid.UUID
|
|
}
|
|
|
|
// AcquireResult is returned by [Tx.Acquire].
|
|
type AcquireResult struct{}
|
|
|
|
// Acquire claims the chat for a worker/runner pair. Execution state
|
|
// is preserved.
|
|
//
|
|
// Acquire never inspects the chat's current ownership: it simply
|
|
// overwrites worker_id/runner_id with the supplied identifiers and
|
|
// upserts a fresh heartbeat. Detecting and recovering from stale
|
|
// leases is a worker-side fence concern outside the state machine.
|
|
// Callers that need to coordinate takeovers with the previous owner
|
|
// must arrange that out-of-band before calling Acquire.
|
|
func (tx *Tx) Acquire(input AcquireInput) (AcquireResult, error) {
|
|
chat, _, err := tx.loadState(input.Snapshot)
|
|
if err != nil {
|
|
return AcquireResult{}, err
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: chat.Status,
|
|
Archived: chat.Archived,
|
|
WorkerID: uuid.NullUUID{UUID: input.WorkerID, Valid: true},
|
|
RunnerID: uuid.NullUUID{UUID: input.RunnerID, Valid: true},
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: chat.CompactionRequestedAt,
|
|
}); err != nil {
|
|
return AcquireResult{}, xerrors.Errorf("set ownership: %w", err)
|
|
}
|
|
if err := tx.store.UpsertChatHeartbeat(tx.ctx, database.UpsertChatHeartbeatParams{
|
|
ChatID: tx.chatID,
|
|
RunnerID: input.RunnerID,
|
|
}); err != nil {
|
|
return AcquireResult{}, xerrors.Errorf("upsert heartbeat: %w", err)
|
|
}
|
|
// Acquire writes a fresh heartbeat itself, so the post-commit
|
|
// ownership-hint logic in Update will evaluate the heartbeat as
|
|
// fresh and skip publishing a `chat:ownership` hint.
|
|
return AcquireResult{}, nil
|
|
}
|
|
|
|
// AbandonInput configures [Tx.Abandon]. Ownership-fence checks belong
|
|
// outside the transition, in caller code that compares the snapshot's
|
|
// worker_id and runner_id before invoking Abandon.
|
|
type AbandonInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// AbandonResult is returned by [Tx.Abandon].
|
|
type AbandonResult struct{}
|
|
|
|
// Abandon clears worker_id and runner_id from the locked chat row. It
|
|
// rejects calls when the chat is not currently owned (worker_id IS NULL).
|
|
// Callers that need to verify their own identity before abandoning should
|
|
// compare the snapshot's worker_id and runner_id, then pass the snapshot
|
|
// in [AbandonInput].
|
|
func (tx *Tx) Abandon(input AbandonInput) (AbandonResult, error) {
|
|
chat, from, err := tx.loadState(input.Snapshot)
|
|
if err != nil {
|
|
return AbandonResult{}, err
|
|
}
|
|
if !chat.WorkerID.Valid {
|
|
return AbandonResult{}, newTransitionError(TransitionAbandon, from, "chat is not owned")
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: chat.Status,
|
|
Archived: chat.Archived,
|
|
WorkerID: uuid.NullUUID{},
|
|
RunnerID: uuid.NullUUID{},
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: chat.CompactionRequestedAt,
|
|
}); err != nil {
|
|
return AbandonResult{}, xerrors.Errorf("clear ownership: %w", err)
|
|
}
|
|
return AbandonResult{}, nil
|
|
}
|
|
|
|
// RecordGenerationAttemptInput configures [Tx.RecordGenerationAttempt].
|
|
type RecordGenerationAttemptInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// RecordGenerationAttemptResult is returned by [Tx.RecordGenerationAttempt].
|
|
type RecordGenerationAttemptResult struct {
|
|
GenerationAttempt int64
|
|
}
|
|
|
|
// RecordGenerationAttempt durably records that the worker is
|
|
// attempting another generation under the current history version.
|
|
func (tx *Tx) RecordGenerationAttempt(input RecordGenerationAttemptInput) (RecordGenerationAttemptResult, error) {
|
|
_, _, err := tx.requireFromAllowed(TransitionRecordGenerationAttempt, input.Snapshot)
|
|
if err != nil {
|
|
return RecordGenerationAttemptResult{}, err
|
|
}
|
|
value, err := tx.store.IncrementChatGenerationAttempt(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return RecordGenerationAttemptResult{}, xerrors.Errorf("increment generation attempt: %w", err)
|
|
}
|
|
return RecordGenerationAttemptResult{
|
|
GenerationAttempt: value,
|
|
}, nil
|
|
}
|
|
|
|
// DeliverSteerMessagesInput configures [Tx.DeliverSteerMessages].
|
|
type DeliverSteerMessagesInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// DeliverSteerMessagesResult is returned by [Tx.DeliverSteerMessages].
|
|
type DeliverSteerMessagesResult struct {
|
|
// DeliveredMessages contains steer messages in position order.
|
|
DeliveredMessages []database.ChatMessage
|
|
// PromotedQueuedAt is the enqueue time of the first delivered
|
|
// message. It is zero when no message was delivered.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// DeliverSteerMessages moves the steer lane into history in position
|
|
// order at a step boundary of a running turn. A steer row under edit
|
|
// holds the whole lane. Queue rows stay queued and the status does not
|
|
// change.
|
|
func (tx *Tx) DeliverSteerMessages(input DeliverSteerMessagesInput) (DeliverSteerMessagesResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionDeliverSteerMessages, input.Snapshot)
|
|
if err != nil {
|
|
return DeliverSteerMessagesResult{}, err
|
|
}
|
|
if from == StateR0 {
|
|
return DeliverSteerMessagesResult{}, nil
|
|
}
|
|
queued, err := tx.store.GetChatQueuedMessages(tx.ctx, tx.chatID)
|
|
if err != nil {
|
|
return DeliverSteerMessagesResult{}, xerrors.Errorf("get queued messages: %w", err)
|
|
}
|
|
rows := steerLane(queued)
|
|
if len(rows) == 0 {
|
|
return DeliverSteerMessagesResult{}, nil
|
|
}
|
|
outstanding, err := outstandingToolCalls(tx.ctx, tx.store, chat, false)
|
|
if err != nil {
|
|
return DeliverSteerMessagesResult{}, err
|
|
}
|
|
if len(outstanding) > 0 {
|
|
return DeliverSteerMessagesResult{}, newTransitionError(
|
|
TransitionDeliverSteerMessages, from,
|
|
"outstanding tool calls block steer delivery",
|
|
)
|
|
}
|
|
d, err := tx.deliverQueuedRows(chat, nil, rows)
|
|
if err != nil {
|
|
return DeliverSteerMessagesResult{}, err
|
|
}
|
|
return DeliverSteerMessagesResult{
|
|
DeliveredMessages: d.delivered,
|
|
PromotedQueuedAt: d.queuedAt,
|
|
}, nil
|
|
}
|
|
|
|
// RecordRetryStateInput configures [Tx.RecordRetryState].
|
|
type RecordRetryStateInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
RetryState pqtype.NullRawMessage
|
|
}
|
|
|
|
// RecordRetryStateResult is returned by [Tx.RecordRetryState].
|
|
type RecordRetryStateResult struct {
|
|
Chat database.Chat
|
|
}
|
|
|
|
// RecordRetryState stores the client-visible retry payload for the
|
|
// current generation attempt.
|
|
func (tx *Tx) RecordRetryState(input RecordRetryStateInput) (RecordRetryStateResult, error) {
|
|
_, from, err := tx.requireFromAllowed(TransitionRecordRetryState, input.Snapshot)
|
|
if err != nil {
|
|
return RecordRetryStateResult{}, err
|
|
}
|
|
if !input.RetryState.Valid || len(input.RetryState.RawMessage) == 0 {
|
|
return RecordRetryStateResult{}, newTransitionError(
|
|
TransitionRecordRetryState, from,
|
|
"RecordRetryState requires a retry payload",
|
|
)
|
|
}
|
|
if !json.Valid(input.RetryState.RawMessage) {
|
|
return RecordRetryStateResult{}, newTransitionError(
|
|
TransitionRecordRetryState, from,
|
|
"retry payload is not valid JSON",
|
|
)
|
|
}
|
|
chat, err := tx.store.UpdateChatRetryState(tx.ctx, database.UpdateChatRetryStateParams{
|
|
ID: tx.chatID,
|
|
RetryState: input.RetryState.RawMessage,
|
|
})
|
|
if err != nil {
|
|
return RecordRetryStateResult{}, xerrors.Errorf("update retry state: %w", err)
|
|
}
|
|
return RecordRetryStateResult{Chat: chat}, nil
|
|
}
|
|
|
|
// CommitStepInput configures [Tx.CommitStep].
|
|
type CommitStepInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Messages []Message
|
|
// ConsumeCompactionRequest clears the one-shot manual compaction
|
|
// marker atomically with the committed step. Compaction commits
|
|
// set this so a request is consumed exactly once and never
|
|
// replays on a later turn.
|
|
ConsumeCompactionRequest bool
|
|
}
|
|
|
|
// CommitStepResult is returned by [Tx.CommitStep].
|
|
type CommitStepResult struct {
|
|
InsertedMessages []database.ChatMessage
|
|
}
|
|
|
|
// CommitStep stores one durable message suffix while remaining
|
|
// running.
|
|
func (tx *Tx) CommitStep(input CommitStepInput) (CommitStepResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionCommitStep, input.Snapshot)
|
|
if err != nil {
|
|
return CommitStepResult{}, err
|
|
}
|
|
if len(input.Messages) == 0 {
|
|
return CommitStepResult{}, newTransitionError(
|
|
TransitionCommitStep, from,
|
|
"CommitStep requires at least one message",
|
|
)
|
|
}
|
|
inserted, err := tx.insertMessages(input.Messages)
|
|
if err != nil {
|
|
return CommitStepResult{}, xerrors.Errorf("insert commit step messages: %w", err)
|
|
}
|
|
if input.ConsumeCompactionRequest && chat.CompactionRequestedAt.Valid {
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: chat.Status,
|
|
Archived: chat.Archived,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: chat.RequiresActionDeadlineAt,
|
|
CompactionRequestedAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return CommitStepResult{}, xerrors.Errorf("consume compaction request: %w", err)
|
|
}
|
|
}
|
|
return CommitStepResult{
|
|
InsertedMessages: inserted,
|
|
}, nil
|
|
}
|
|
|
|
// requiresActionTimeout is the time allowed for a client to submit
|
|
// required dynamic tool results before follow-up logic may consider
|
|
// the requires-action state expired.
|
|
const requiresActionTimeout = 5 * time.Minute
|
|
|
|
// EnterRequiresActionInput configures [Tx.EnterRequiresAction].
|
|
type EnterRequiresActionInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// EnterRequiresActionResult is returned by [Tx.EnterRequiresAction].
|
|
type EnterRequiresActionResult struct {
|
|
RequiresActionDeadlineAt sql.NullTime
|
|
}
|
|
|
|
// EnterRequiresAction parks the chat in requires_action with a
|
|
// database-time deadline of now() + requiresActionTimeout.
|
|
func (tx *Tx) EnterRequiresAction(input EnterRequiresActionInput) (EnterRequiresActionResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionEnterRequiresAction, input.Snapshot)
|
|
if err != nil {
|
|
return EnterRequiresActionResult{}, err
|
|
}
|
|
pending, err := pendingDynamicToolCallIDs(tx.ctx, tx.store, chat)
|
|
if err != nil {
|
|
return EnterRequiresActionResult{}, err
|
|
}
|
|
if len(pending) == 0 {
|
|
return EnterRequiresActionResult{}, newTransitionError(
|
|
TransitionEnterRequiresAction, from,
|
|
"no pending dynamic tool calls",
|
|
)
|
|
}
|
|
now, err := tx.store.GetDatabaseNow(tx.ctx)
|
|
if err != nil {
|
|
return EnterRequiresActionResult{}, xerrors.Errorf("get db now: %w", err)
|
|
}
|
|
deadline := sql.NullTime{Time: now.Add(requiresActionTimeout), Valid: true}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRequiresAction,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: deadline,
|
|
}); err != nil {
|
|
return EnterRequiresActionResult{}, xerrors.Errorf("set requires_action: %w", err)
|
|
}
|
|
return EnterRequiresActionResult{
|
|
RequiresActionDeadlineAt: deadline,
|
|
}, nil
|
|
}
|
|
|
|
// FinishInterruptionInput configures [Tx.FinishInterruption].
|
|
type FinishInterruptionInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
PartialMessages []Message
|
|
}
|
|
|
|
// FinishInterruptionResult is returned by [Tx.FinishInterruption].
|
|
type FinishInterruptionResult struct {
|
|
InsertedMessages []database.ChatMessage
|
|
// PromotedMessages contains delivered queue entries in insertion order.
|
|
PromotedMessages []database.ChatMessage
|
|
// PromotedQueuedAt is zero when no queued message was promoted.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// FinishInterruption commits an optional partial assistant/tool suffix
|
|
// and moves the chat to waiting (I0), running (I1), or paused (I1P).
|
|
// From I1 it promotes the steer lane when it is not empty, otherwise
|
|
// the queue head.
|
|
func (tx *Tx) FinishInterruption(input FinishInterruptionInput) (FinishInterruptionResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionFinishInterruption, input.Snapshot)
|
|
if err != nil {
|
|
return FinishInterruptionResult{}, err
|
|
}
|
|
insertedPartial, err := tx.insertMessages(input.PartialMessages)
|
|
if err != nil {
|
|
return FinishInterruptionResult{}, xerrors.Errorf("insert interruption partial messages: %w", err)
|
|
}
|
|
// Any outstanding call, dynamic or not, would leave invalid LLM history.
|
|
outstanding, err := outstandingToolCalls(tx.ctx, tx.store, chat, false)
|
|
if err != nil {
|
|
return FinishInterruptionResult{}, err
|
|
}
|
|
if len(outstanding) > 0 {
|
|
return FinishInterruptionResult{}, newTransitionError(
|
|
TransitionFinishInterruption, from,
|
|
"outstanding tool calls remain after partial commit",
|
|
)
|
|
}
|
|
|
|
_, d, err := tx.advanceQueue(chat)
|
|
if err != nil {
|
|
return FinishInterruptionResult{}, err
|
|
}
|
|
return FinishInterruptionResult{
|
|
InsertedMessages: append(insertedPartial, d.inserted...),
|
|
PromotedMessages: d.delivered,
|
|
PromotedQueuedAt: d.queuedAt,
|
|
}, nil
|
|
}
|
|
|
|
// FinishTurnInput configures [Tx.FinishTurn].
|
|
type FinishTurnInput struct {
|
|
Snapshot *ChatSnapshot
|
|
}
|
|
|
|
// FinishTurnResult is returned by [Tx.FinishTurn].
|
|
type FinishTurnResult struct {
|
|
Chat database.Chat
|
|
// PromotedMessages contains delivered queue entries in insertion order.
|
|
PromotedMessages []database.ChatMessage
|
|
// PromotedQueuedAt is zero when no queued message was promoted.
|
|
PromotedQueuedAt time.Time
|
|
}
|
|
|
|
// FinishTurn completes a running turn: waiting (R0), running (R1), or
|
|
// paused (R1P). From R1 it starts a new turn with the steer lane when it
|
|
// is not empty, otherwise with the queue head.
|
|
func (tx *Tx) FinishTurn(input FinishTurnInput) (FinishTurnResult, error) {
|
|
chat, _, err := tx.requireFromAllowed(TransitionFinishTurn, input.Snapshot)
|
|
if err != nil {
|
|
return FinishTurnResult{}, err
|
|
}
|
|
updated, d, err := tx.advanceQueue(chat)
|
|
if err != nil {
|
|
return FinishTurnResult{}, err
|
|
}
|
|
return FinishTurnResult{
|
|
Chat: updated,
|
|
PromotedMessages: d.delivered,
|
|
PromotedQueuedAt: d.queuedAt,
|
|
}, nil
|
|
}
|
|
|
|
// FinishErrorInput configures [Tx.FinishError].
|
|
type FinishErrorInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
LastError pqtype.NullRawMessage
|
|
}
|
|
|
|
// FinishErrorResult is returned by [Tx.FinishError].
|
|
type FinishErrorResult struct{}
|
|
|
|
// FinishError parks the chat in error with the supplied last_error.
|
|
// It is allowed when an unarchived chat is waiting or running.
|
|
func (tx *Tx) FinishError(input FinishErrorInput) (FinishErrorResult, error) {
|
|
chat, _, err := tx.requireFromAllowed(TransitionFinishError, input.Snapshot)
|
|
if err != nil {
|
|
return FinishErrorResult{}, err
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusError,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: input.LastError,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return FinishErrorResult{}, xerrors.Errorf("set error: %w", err)
|
|
}
|
|
return FinishErrorResult{}, nil
|
|
}
|
|
|
|
// CancelRequiresActionInput configures [Tx.CancelRequiresAction].
|
|
type CancelRequiresActionInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
Reason string
|
|
}
|
|
|
|
// CancelRequiresActionResult is returned by [Tx.CancelRequiresAction].
|
|
type CancelRequiresActionResult struct {
|
|
CancellationMessages []database.ChatMessage
|
|
}
|
|
|
|
// CancelRequiresAction synthesizes cancellation results for every
|
|
// pending dynamic tool call and returns the chat to running.
|
|
func (tx *Tx) CancelRequiresAction(input CancelRequiresActionInput) (CancelRequiresActionResult, error) {
|
|
chat, from, err := tx.requireFromAllowed(TransitionCancelRequiresAction, input.Snapshot)
|
|
if err != nil {
|
|
return CancelRequiresActionResult{}, err
|
|
}
|
|
reason := input.Reason
|
|
if reason == "" {
|
|
reason = "Tool execution timed out"
|
|
}
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, reason, true)
|
|
if err != nil {
|
|
return CancelRequiresActionResult{}, err
|
|
}
|
|
if len(cancels) == 0 {
|
|
return CancelRequiresActionResult{}, newTransitionError(
|
|
TransitionCancelRequiresAction, from,
|
|
"no pending dynamic tool calls to cancel",
|
|
)
|
|
}
|
|
inserted, err := tx.insertMessages(cancels)
|
|
if err != nil {
|
|
return CancelRequiresActionResult{}, xerrors.Errorf("insert requires-action cancellations: %w", err)
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusRunning,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: chat.LastError,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return CancelRequiresActionResult{}, xerrors.Errorf("set running: %w", err)
|
|
}
|
|
return CancelRequiresActionResult{
|
|
CancellationMessages: inserted,
|
|
}, nil
|
|
}
|
|
|
|
// ReconcileInvalidStateInput configures [Tx.ReconcileInvalidState].
|
|
type ReconcileInvalidStateInput struct {
|
|
Snapshot *ChatSnapshot
|
|
|
|
LastError pqtype.NullRawMessage
|
|
CancellationReason string
|
|
}
|
|
|
|
// ReconcileInvalidStateResult is returned by [Tx.ReconcileInvalidState].
|
|
type ReconcileInvalidStateResult struct {
|
|
CancellationMessages []database.ChatMessage
|
|
}
|
|
|
|
// ReconcileInvalidState moves an invalid execution-state combination
|
|
// into a valid error state. Queued messages are preserved; pending
|
|
// dynamic-tool calls are closed with synthetic cancellation results.
|
|
func (tx *Tx) ReconcileInvalidState(input ReconcileInvalidStateInput) (ReconcileInvalidStateResult, error) {
|
|
chat, from, err := tx.loadState(input.Snapshot)
|
|
if err != nil {
|
|
return ReconcileInvalidStateResult{}, err
|
|
}
|
|
if from != StateInvalid {
|
|
return ReconcileInvalidStateResult{}, newTransitionError(
|
|
TransitionReconcileInvalidState, from,
|
|
"reconcile is only valid for invalid states",
|
|
)
|
|
}
|
|
reason := input.CancellationReason
|
|
if reason == "" {
|
|
reason = "Tool execution canceled due to invalid chat state"
|
|
}
|
|
cancels, err := synthesizePendingToolCancellations(tx.ctx, tx.store, chat, reason, true)
|
|
if err != nil {
|
|
return ReconcileInvalidStateResult{}, err
|
|
}
|
|
var inserted []database.ChatMessage
|
|
if len(cancels) > 0 {
|
|
inserted, err = tx.insertMessages(cancels)
|
|
if err != nil {
|
|
return ReconcileInvalidStateResult{}, xerrors.Errorf("insert invalid-state cancellations: %w", err)
|
|
}
|
|
}
|
|
lastErr := input.LastError
|
|
if !lastErr.Valid {
|
|
lastErr = pqtype.NullRawMessage{
|
|
RawMessage: json.RawMessage(`{"message":"chat was in an invalid state; send a new message or edit history to continue"}`),
|
|
Valid: true,
|
|
}
|
|
}
|
|
if _, err := tx.applyExecutionState(executionStateUpdate{
|
|
Status: database.ChatStatusError,
|
|
Archived: false,
|
|
WorkerID: chat.WorkerID,
|
|
RunnerID: chat.RunnerID,
|
|
LastError: lastErr,
|
|
RequiresActionDeadlineAt: sql.NullTime{},
|
|
}); err != nil {
|
|
return ReconcileInvalidStateResult{}, xerrors.Errorf("set error: %w", err)
|
|
}
|
|
return ReconcileInvalidStateResult{
|
|
CancellationMessages: inserted,
|
|
}, nil
|
|
}
|