From 364e0cb3c9d7a219260d0e5f8b3541ca86ca8acc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 1 Dec 2026 00:56:34 +0000 Subject: [PATCH] Chat queue: wake the runner when a scheduled head is unqueued; end a stale observed turn once the harness is idle A prompt queued behind a scheduled prompt (the app's auto-continue at a usage limit's reset) stayed queued after that head was removed: unqueue never woke the runner, which slept until the removed prompt's send_at. unqueue now wakes it, and the runner re-checks a scheduled head at least every 30 s. Safety net: a due prompt held by a turn the room only observed (its end lost, or a reattach watcher that gave up) is delivered once the harness reports itself idle for a settle period and its probe confirms it. Co-Authored-By: Claude Opus 5.5 --- internal/claude/hosted_test.go | 30 +++++ internal/server/chat_detach.go | 81 +++++++++++-- internal/server/chat_detach_test.go | 6 - internal/server/chat_queue.go | 15 +++ internal/server/chat_queue_stuck_test.go | 144 +++++++++++++++++++++++ internal/server/chat_room.go | 16 ++- internal/server/chat_unattended.go | 5 +- 7 files changed, 280 insertions(+), 17 deletions(-) create mode 100644 internal/server/chat_queue_stuck_test.go diff --git a/internal/claude/hosted_test.go b/internal/claude/hosted_test.go index ce86188b..704713a4 100644 --- a/internal/claude/hosted_test.go +++ b/internal/claude/hosted_test.go @@ -247,6 +247,36 @@ func TestInterruptAfterRestart(t *testing.T) { } } +// A chat whose last turn before a restart was refused for a usage limit is +// idle after the restart: the reattached host reports no turn running, so a +// prompt queued for it is not held, and the next prompt runs on the same CLI. +func TestRefusedLastTurnIsIdleAfterRestart(t *testing.T) { + fixture := hostedSetup(t) + first := hostedChat(t) + session := newCreatedChat(t, first) + frames := subscribe(t, first, session.ID) + if err := first.Prompt(context.Background(), session.ID, "usage-limit"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + second := restart(t, first) + if running, err := second.ProbeTurn(context.Background(), session.ID); err != nil || running { + t.Fatalf("the refused turn must not be running after the restart: running=%t err=%v", running, err) + } + if second.TurnRunning(session.ID) { + t.Fatal("TurnRunning must report the refused chat idle after the restart") + } + frames = subscribe(t, second, session.ID) + if err := second.Prompt(context.Background(), session.ID, "continue"); err != nil { + t.Fatal(err) + } + waitFrame(t, frames, "the next turn's text", textFrame("Hello")) + waitStepEnded(t, frames) + if spawns := readArgs(t, fixture.logPath); len(spawns) != 1 { + t.Fatalf("the CLI must not be restarted, spawns: %+v", spawns) + } +} + func TestModelAndBackgroundTaskSurviveRestart(t *testing.T) { fixture := hostedSetup(t) first := hostedChat(t) diff --git a/internal/server/chat_detach.go b/internal/server/chat_detach.go index 4849b774..4a8fafc1 100644 --- a/internal/server/chat_detach.go +++ b/internal/server/chat_detach.go @@ -206,6 +206,7 @@ func (h *chatHub) reattachSession(ctx context.Context, broker chatBroker, sessio room.nativeTurnID = session.NativeTurnID } room.observedTurn = true + room.observedIdleSince = time.Time{} h.mu.Unlock() go h.awaitReattachedTurn(room, broker, session) } @@ -216,7 +217,11 @@ func (h *chatHub) reattachSession(ctx context.Context, broker chatBroker, sessio func (h *chatHub) awaitReattachedTurn(room *chatRoom, broker chatBroker, session pipeline.ChatLiveSession) { prober, _ := broker.(chatTurnProber) started := h.clock() - ticker := time.NewTicker(chatReattachPoll) + poll := h.unattended.reattachPoll + if poll <= 0 { + poll = 2 * time.Second + } + ticker := time.NewTicker(poll) defer ticker.Stop() for { select { @@ -257,14 +262,7 @@ func (h *chatHub) foldEndedTurn(ctx context.Context, broker chatBroker, session h.mu.Lock() defer h.mu.Unlock() if room != nil && h.rooms[id] == room && room.observedTurn { - end := protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}} - h.applyLocked(end) - h.finishTurnLocked(room) - resync := protocol.ChatEventFrame{SessionID: id, Kind: protocol.ChatEventResync} - for _, sub := range room.subs { - enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) - enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) - } + h.endObservedTurnLocked(room) if room.watching && len(room.subs) == 0 && len(room.queue) == 0 && !h.keepUnattendedLocked(room, false, false) { room.watching = false h.releaseRoomLocked(room) @@ -287,6 +285,71 @@ func (h *chatHub) foldEndedTurn(ctx context.Context, broker chatBroker, session h.startChatAttention(chatAttention{sessionID: id, reply: true, body: body, id: chatNotificationID(id, "reply", key)}) } +// endObservedTurnLocked ends a turn the room observed but whose end event it +// never received: the turn slot is released (so queued prompts are delivered) +// and attached clients re-read the authoritative history. Callers hold h.mu. +func (h *chatHub) endObservedTurnLocked(room *chatRoom) { + end := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}} + h.applyLocked(end) + h.finishTurnLocked(room) + resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync} + for _, sub := range room.subs { + enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) + enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) + } +} + +// settleStaleObservedTurn is the queue's safety net for a turn the room only +// observed (announced by the stream, or reattached after a restart) whose end +// was lost: a replayed or silent result, an end carrying another turn id, or +// a reattach watcher that gave up. The runner calls it, without h.mu, while a +// due prompt waits behind such a turn. Once the harness has reported itself +// idle (TurnRunning false) for the settle period (chatQueueStaleTurnSettle) and its own probe +// confirms no turn is in flight, the observed turn is ended and it reports +// true so the queue proceeds. A harness that cannot be probed is never +// second-guessed. +func (h *chatHub) settleStaleObservedTurn(room *chatRoom, broker chatBroker) bool { + if brokerTurnRunning(broker, room.sessionID) { + h.mu.Lock() + room.observedIdleSince = time.Time{} + h.mu.Unlock() + return false + } + h.mu.Lock() + now := h.clock() + if room.observedIdleSince.IsZero() { + room.observedIdleSince = now + } + idle := now.Sub(room.observedIdleSince) + h.mu.Unlock() + prober, ok := broker.(chatTurnProber) + settle := h.unattended.staleTurn + if settle <= 0 { + settle = 10 * time.Second + } + if !ok || idle < settle { + return false + } + probeCtx, cancel := context.WithTimeout(room.ctx, 5*time.Second) + busy, err := prober.ProbeTurn(probeCtx, room.sessionID) + cancel() + h.mu.Lock() + defer h.mu.Unlock() + if err != nil || busy || room.observedIdleSince.IsZero() { + // Busy, unknown, or a new turn started meanwhile: look again only + // after another settle period (one probe per period). + room.observedIdleSince = h.clock() + return false + } + if h.rooms[room.sessionID] != room || room.ctx.Err() != nil || !room.observedTurn || room.running { + return false + } + log.Printf("chat session %s: the harness reports no turn running for %s; ending the observed turn %q that never reported its end, so the queued prompt is delivered", + room.sessionID, idle.Round(time.Second), room.nativeTurnID) + h.endObservedTurnLocked(room) + return true +} + // lastReply returns the id and bounded text of the assistant reply that ends // a history page (messages after the last user message), or "" when the page // ends with the user's own message. diff --git a/internal/server/chat_detach_test.go b/internal/server/chat_detach_test.go index 9298272d..9dca1d6e 100644 --- a/internal/server/chat_detach_test.go +++ b/internal/server/chat_detach_test.go @@ -30,12 +30,6 @@ func (c *restartChat) Messages(context.Context, string, int, string) (protocol.C return protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage(nil), c.history...)}, nil } -func (c *restartChat) setProbe(running bool) { - c.smu.Lock() - c.probe["ses_1"] = running - c.smu.Unlock() -} - // chatRestartServer is one server process over a shared database. type chatRestartServer struct { ctx context.Context diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 4f1ce48b..fbf5b099 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -37,6 +37,18 @@ var chatQueueBusyPoll = time.Second // through its stream. var chatQueueRecoverySettle = 1500 * time.Millisecond +// chatQueueScheduleRecheck bounds how long the runner sleeps on a scheduled +// head before it looks at the queue again, so a head that changed without a +// wake (it was removed, or a restart reordered nothing) never holds the +// prompts behind it until the old send_at. +var chatQueueScheduleRecheck = 30 * time.Second + +// chatQueueStaleTurnSettle is how long a due queue head waits behind a turn +// the room only observed (one it did not start) while the harness reports +// itself idle, before that turn is treated as ended (its end event was lost) +// and the queue proceeds. +var chatQueueStaleTurnSettle = 10 * time.Second + // chatRecentOpsLimit bounds the remembered accepted operation ids used to // refuse a duplicate delivery of a client retry. const chatRecentOpsLimit = 256 @@ -299,6 +311,9 @@ func (h *chatHub) unqueue(ctx context.Context, sessionID, operationID string) (b if p.acked && p.operationID == operationID { removed = p room.queue = append(room.queue[:i:i], room.queue[i+1:]...) + // The runner may be asleep until the removed prompt's send_at; + // the new head (often one due now) must not wait for it. + signalWake(room.wake) break } } diff --git a/internal/server/chat_queue_stuck_test.go b/internal/server/chat_queue_stuck_test.go new file mode 100644 index 00000000..1fbb4007 --- /dev/null +++ b/internal/server/chat_queue_stuck_test.go @@ -0,0 +1,144 @@ +package server + +import ( + "context" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/coder/websocket" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// fastStaleTurnSettle shortens the queue's stale observed-turn settle period. +func fastStaleTurnSettle(t *testing.T) { + t.Helper() + settle := chatQueueStaleTurnSettle + chatQueueStaleTurnSettle = 150 * time.Millisecond + t.Cleanup(func() { chatQueueStaleTurnSettle = settle }) +} + +func (c *observedChat) setProbe(running bool) { + c.smu.Lock() + c.probe["ses_1"] = running + c.smu.Unlock() +} + +// waitStepFrame reads conn until the stream delivers the step frame for turn. +func waitStepFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, status, turn string) { + t.Helper() + for { + message := readChatMessage(t, ctx, conn) + if message.Type == protocol.ChatEvent && message.ChatEvent != nil && message.ChatEvent.Step != nil && + message.ChatEvent.Step.Status == status && message.ChatEvent.Step.TurnID == turn { + return + } + } +} + +// The live incident: a chat's last turn before a restart was refused for a +// usage limit, so the app scheduled its auto-continue prompt for the limit's +// reset, an hour away. After the restart the operator switched accounts and +// sent "continue", which queued behind that scheduled head; then the +// scheduled prompt was removed. The runner was asleep until the removed +// prompt's send_at, so "continue" (due now, harness idle) sat in the queue +// until the next restart. Removing the head must wake the runner. +func TestChatPromptBehindAnUnqueuedScheduledHeadRunsAfterRestart(t *testing.T) { + fastReattach(t) + path := restartChatDB(t) + + first := newRestartChat() + server := startChatRestartServer(t, first, path) + conn := dialChatConn(t, server.ctx, server.srv) + sendPrompt(t, server.ctx, conn, "p1", "keep going", "op-1") + waitFor(t, "first prompt", func() bool { return first.promptCount() == 1 }) + // The turn is refused for a usage limit: it ends at once. + first.push(stepFrameFor(protocol.ChatStepStarted, "turn_refused")) + first.push(stepFrameFor(protocol.ChatStepEnded, "turn_refused")) + waitStepFrame(t, server.ctx, conn, protocol.ChatStepEnded, "turn_refused") + reset := time.Now().Add(time.Hour) + writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "auto", ChatPrompt: &protocol.ChatPromptRequest{ + SessionID: "ses_1", Text: "keep going", OperationID: "auto-continue-refusal-1", Client: "Phone", SendAt: reset.UnixMilli()}}) + if ack := readUntil(t, server.ctx, conn, protocol.ChatPrompt); !ack.ChatQueued { + t.Fatalf("auto-continue was not scheduled: %+v", ack) + } + server.shutdown() + + second := newRestartChat() + server = startChatRestartServer(t, second, path) + conn = dialChatConn(t, server.ctx, server.srv) + if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-continue"); !ack.ChatQueued { + t.Fatalf("continue was not queued behind the scheduled head: %+v", ack) + } + writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: "auto-continue-refusal-1"}}) + if removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue); removed.ChatQueue == nil || removed.ChatQueue.Removed != "auto-continue-refusal-1" { + t.Fatalf("unqueue reply = %+v", removed.ChatQueue) + } + waitFor(t, "continue delivered once the scheduled head is gone", func() bool { return second.promptCount() == 1 }) + if texts := second.promptTexts(); !slices.Equal(texts, []string{"continue"}) { + t.Fatalf("delivered = %v", texts) + } +} + +// A turn the room only observed (the harness started it on its own) whose +// end event is lost must not hold a due prompt forever: once the harness +// reports itself idle for the settle period, the stale turn is ended and the +// prompt delivered. While the harness reports the turn running, it waits. +func TestChatQueueEndsAStaleObservedTurnOnceTheHarnessIsIdle(t *testing.T) { + fastUnattended(t) + fastStaleTurnSettle(t) + t.Setenv("PIPELINES_NTFY_URL", "") + store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) + broker := newObservedChat() + server := startQueueServer(t, broker, store) + conn := dialChatConn(t, server.ctx, server.srv) + sendPrompt(t, server.ctx, conn, "p1", "build it", "op-1") + waitFor(t, "first prompt", func() bool { return broker.promptCount() == 1 }) + broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1")) + broker.push(stepFrameFor(protocol.ChatStepEnded, "turn_1")) + // The harness starts a turn of its own (a background task finished); + // its end never reaches the room. + broker.setProbe(true) + broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_cli")) + waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_cli") + if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued { + t.Fatalf("prompt behind the harness's own turn was not queued: %+v", ack) + } + time.Sleep(4 * chatQueueStaleTurnSettle) + if n := broker.promptCount(); n != 1 { + t.Fatalf("prompt delivered while the harness reports its turn running: %v", broker.promptTexts()) + } + broker.setProbe(false) + waitFor(t, "prompt delivered after the harness went idle", func() bool { return broker.promptCount() == 2 }) + if texts := broker.promptTexts(); texts[1] != "continue" { + t.Fatalf("delivered = %v", texts) + } +} + +// A reattached turn whose watcher gave up (its turn limit passed while the +// harness still reported it running) left the room's observed turn set: once +// the harness is idle, the queued prompt must still be delivered. +func TestChatQueuedPromptRunsAfterAReattachedTurnWatcherGaveUp(t *testing.T) { + fastReattach(t) + fastStaleTurnSettle(t) + limit := chatUnattendedTurnLimit + chatUnattendedTurnLimit = 100 * time.Millisecond + t.Cleanup(func() { chatUnattendedTurnLimit = limit }) + path := restartChatDB(t) + startTurnThenRestart(t, path, true) + second := newRestartChat() + second.setProbe(true) + startChatRestartServer(t, second, path) + waitFor(t, "reattached stream", func() bool { active, _ := second.streams(); return active >= 1 }) + time.Sleep(3 * chatUnattendedTurnLimit) // the reattach watcher gives up + if second.promptCount() != 0 { + t.Fatalf("queued prompt delivered into a turn still running: %v", second.promptTexts()) + } + second.setProbe(false) + waitFor(t, "queued prompt delivered", func() bool { return second.promptCount() == 1 }) + if texts := second.promptTexts(); texts[0] != "then ship it" { + t.Fatalf("wrong prompt delivered after restart: %v", texts) + } +} diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 004edb0a..37513763 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -149,6 +149,10 @@ type chatRoom struct { // attach) and cleared when the turn ends, so a later subscriber is told the // turn is running even though no prompt of this room started it. observedTurn bool + // observedIdleSince is when the runner, holding a due prompt behind an + // observed turn, first saw the harness report itself idle (zero while it + // reports a turn running). See settleStaleObservedTurn. + observedIdleSince time.Time // observing is non-nil while one caller is attaching the shared broker // stream. It prevents concurrent subscribers from opening duplicate global // event streams before streaming can be published. @@ -473,6 +477,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) { } if room != nil && frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepStarted && !frame.Step.Intermediate { room.observedTurn = true + room.observedIdleSince = time.Time{} } var priorStep *protocol.ChatStep if frame.Kind == protocol.ChatEventStep && frame.SessionID != "" { @@ -603,6 +608,7 @@ func (h *chatHub) finishTurnLocked(room *chatRoom) { h.clearCompactionLocked(room) room.running = false room.observedTurn = false + room.observedIdleSince = time.Time{} room.nativeTurnID = "" if room.turnDone != nil { close(room.turnDone) @@ -800,9 +806,17 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{}, case room.queue[0].sendAt.After(now): // A scheduled head waits for its time; the queue is FIFO, so // later prompts wait behind it. A timer wakes the runner then. - wait = room.queue[0].sendAt.Sub(now) + wait = min(room.queue[0].sendAt.Sub(now), chatQueueScheduleRecheck) case room.observedTurn: wait = chatQueueBusyPoll + if !room.running { + broker := room.broker + h.mu.Unlock() + if h.settleStaleObservedTurn(room, broker) { + continue + } + h.mu.Lock() + } case time.Until(room.notBefore) > 0: wait = time.Until(room.notBefore) default: diff --git a/internal/server/chat_unattended.go b/internal/server/chat_unattended.go index d6da33e6..3819ad09 100644 --- a/internal/server/chat_unattended.go +++ b/internal/server/chat_unattended.go @@ -49,10 +49,13 @@ var ( // hub is built so its goroutines never read the package variables. type chatUnattendedTimings struct { check, turnLimit, settle, window time.Duration + // reattachPoll is chatReattachPoll; staleTurn is chatQueueStaleTurnSettle. + reattachPoll, staleTurn time.Duration } func currentChatUnattendedTimings() chatUnattendedTimings { - return chatUnattendedTimings{check: chatUnattendedCheck, turnLimit: chatUnattendedTurnLimit, settle: chatUnattendedRecoverSettle, window: chatRecoverWindow} + return chatUnattendedTimings{check: chatUnattendedCheck, turnLimit: chatUnattendedTurnLimit, settle: chatUnattendedRecoverSettle, window: chatRecoverWindow, + reattachPoll: chatReattachPoll, staleTurn: chatQueueStaleTurnSettle} } // chatTurnProber is implemented by a broker that can ask the harness itself,