Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions backend/internal/storage/sqlite/gen/conversations.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions backend/internal/storage/sqlite/queries/conversations.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1679,6 +1679,25 @@ SELECT * FROM conversation_activities
WHERE conversation_id = ? AND provider_item_id = ?
LIMIT 1;

-- A question reaches the store with only its request id, and the chat host
-- replays pending requests after a reconnect. Matching on the request id is
-- what keeps that replay on the row AO already stored: the
-- (conversation_id, request_id) index forbids a second row, and failing the
-- insert stops the whole projection with the turn still running (#7944).
-- Only an in-flight row is refreshed. A settled row stays settled: a replay
-- must not reopen a question the user answered (resolved) or one
-- settleOrphanedWork already failed with its turn - revived, it would sit
-- pending on a failed turn, where the dock never shows it.
-- name: SelectConversationActivityByRequest :one
SELECT * FROM conversation_activities
WHERE conversation_id = ? AND request_id = ?
LIMIT 1;

-- name: SettleConversationActivityByRequest :exec
UPDATE conversation_activities
SET status = ?, summary = ?, detail_json = ?, revision = revision + 1, updated_at = ?
WHERE conversation_id = ? AND request_id = ? AND status IN ('pending', 'running');

-- name: SelectConversationContextResetSequence :one
SELECT CAST(COALESCE(MAX(sequence), 0) AS INTEGER) AS sequence
FROM conversation_activities
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1997,3 +1997,103 @@ func TestAppendUserMessagePersistsContinuation(t *testing.T) {
t.Fatalf("continuation by message = %v, want only the continue marked", continuation)
}
}

// The chat host replays a pending question after a reconnect, and a question
// reaches the store with only its request id. The replay must land on the row
// AO already stored rather than tripping the (conversation_id, request_id)
// index and stopping the whole projection with the turn still running (#7944).
func TestUpsertActivityReplayRefreshesTheStoredQuestionInsteadOfColliding(t *testing.T) {
s, _, conversation := conversationFixture(t)
ctx := context.Background()
activity := domain.ConversationActivity{
ID: "question", Kind: domain.ActivityKindUserInput, Status: domain.ActivityStatusPending,
Summary: "Questions", RequestID: "replayed-request",
Detail: []byte(`{"inputMode":"form","message":"Questions"}`),
}
if err := s.UpsertActivity(ctx, conversation, "", activity, histClock); err != nil {
t.Fatalf("UpsertActivity: %v", err)
}

replay := activity
replay.ID = "question-replay"
if err := s.UpsertActivity(ctx, conversation, "", replay, histClock.Add(time.Minute)); err != nil {
t.Fatalf("replayed UpsertActivity: %v", err)
}

snapshot, err := s.LoadConversationSnapshot(ctx, conversation)
if err != nil {
t.Fatalf("LoadConversationSnapshot: %v", err)
}
rows, status := questionRowsByRequest(snapshot, "replayed-request")
if rows != 1 || status != domain.ActivityStatusPending {
t.Fatalf("after replay: rows=%d status=%q, want one pending row", rows, status)
}

// A question the user answered is not reopened by a late replay.
if err := s.ResolveApproval(ctx, conversation, "replayed-request",
`{"resolvedBy":"user"}`, histClock.Add(2*time.Minute)); err != nil {
t.Fatalf("ResolveApproval: %v", err)
}
late := activity
late.ID = "question-late-replay"
if err := s.UpsertActivity(ctx, conversation, "", late, histClock.Add(3*time.Minute)); err != nil {
t.Fatalf("late replayed UpsertActivity: %v", err)
}
snapshot, err = s.LoadConversationSnapshot(ctx, conversation)
if err != nil {
t.Fatalf("LoadConversationSnapshot after late replay: %v", err)
}
rows, status = questionRowsByRequest(snapshot, "replayed-request")
if rows != 1 || status != domain.ActivityStatusResolved {
t.Fatalf("after late replay: rows=%d status=%q, want the one resolved row kept", rows, status)
}
}

func questionRowsByRequest(
snapshot store.ConversationSnapshot, requestID string,
) (int, domain.ActivityStatus) {
rows := 0
status := domain.ActivityStatus("")
for _, activity := range snapshot.Activities {
if activity.RequestID == requestID {
rows++
status = activity.Status
}
}
return rows, status
}

// settleOrphanedWork fails a pending question and its turn in the same pass,
// so a replay that reopened it would leave a pending question on a failed
// turn — one the dock never shows, because latestPendingInteraction only
// docks a question linked to the running turn. A failed row stays failed.
func TestUpsertActivityReplayDoesNotReopenAFailedQuestion(t *testing.T) {
s, _, conversation := conversationFixture(t)
ctx := context.Background()
activity := domain.ConversationActivity{
ID: "question", Kind: domain.ActivityKindUserInput, Status: domain.ActivityStatusPending,
Summary: "Questions", RequestID: "replayed-request",
Detail: []byte(`{"inputMode":"form","message":"Questions"}`),
}
if err := s.UpsertActivity(ctx, conversation, "", activity, histClock); err != nil {
t.Fatalf("UpsertActivity: %v", err)
}
if err := s.FailPendingInputs(ctx, conversation, histClock.Add(time.Minute)); err != nil {
t.Fatalf("FailPendingInputs: %v", err)
}

replay := activity
replay.ID = "question-replay"
if err := s.UpsertActivity(ctx, conversation, "", replay, histClock.Add(2*time.Minute)); err != nil {
t.Fatalf("replayed UpsertActivity: %v", err)
}

snapshot, err := s.LoadConversationSnapshot(ctx, conversation)
if err != nil {
t.Fatalf("LoadConversationSnapshot: %v", err)
}
rows, status := questionRowsByRequest(snapshot, "replayed-request")
if rows != 1 || status != domain.ActivityStatusFailed {
t.Fatalf("after replay: rows=%d status=%q, want the one failed row kept", rows, status)
}
}
34 changes: 34 additions & 0 deletions backend/internal/storage/sqlite/store/conversation_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3266,6 +3266,40 @@ func (s *Store) UpsertActivity(
}
}

// A pending interaction that carries no provider item — an elicited
// question — can still be one AO already stored: the chat host replays the
// pending request after a reconnect. Refresh that row rather than inserting
// a duplicate the (conversation_id, request_id) index would refuse; a failed
// insert here is a fatal projection error and would leave the turn running
// with no recoverable controller (#7944). Only an in-flight row is
// refreshed: a row the user answered stays untouched so a late replay
// cannot reopen it, and so does a row a dead controller failed —
// settleOrphanedWork fails that question together with its turn, and
// revived it would sit pending on a failed turn, where the dock never
// shows it.
if activity.RequestID != "" {
if _, err := q.SelectConversationActivityByRequest(ctx,
gen.SelectConversationActivityByRequestParams{
ConversationID: conversationID,
RequestID: activity.RequestID,
}); err == nil {
if settleErr := q.SettleConversationActivityByRequest(ctx,
gen.SettleConversationActivityByRequestParams{
Status: activity.Status,
Summary: activity.Summary,
DetailJson: detail,
UpdatedAt: now,
ConversationID: conversationID,
RequestID: activity.RequestID,
}); settleErr != nil {
return fmt.Errorf("settle activity %s: %w", activity.RequestID, settleErr)
}
return nil
} else if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("lookup activity %s: %w", activity.RequestID, err)
}
}

turnID := s.turnIDFor(ctx, conversationID, providerTurnID)
return s.inTx(ctx, "insert activity", func(q *gen.Queries) error {
sequence, seqErr := q.NextConversationSequence(ctx, gen.NextConversationSequenceParams{
Expand Down
Loading