Chat: never drop a Claude turn's lifecycle frames; end a runner turn whose end was lost
emit now waits (bounded) for a full watcher to accept step and resync frames instead of dropping them. The turn runner also ends its turn once a harness that tracks its turn state has reported idle for the settle period and its probe confirms, asking clients to resync. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// reportingChat is an observedChat that also reports its turn state without
|
||||
// I/O, as Claude Code does.
|
||||
type reportingChat struct {
|
||||
*observedChat
|
||||
rmu sync.Mutex
|
||||
running bool
|
||||
}
|
||||
|
||||
func (c *reportingChat) TurnRunning(string) bool {
|
||||
c.rmu.Lock()
|
||||
defer c.rmu.Unlock()
|
||||
return c.running
|
||||
}
|
||||
|
||||
// Prompt starts a turn, as Claude Code's does before it returns.
|
||||
func (c *reportingChat) Prompt(ctx context.Context, sessionID, text string) error {
|
||||
if err := c.observedChat.Prompt(ctx, sessionID, text); err != nil {
|
||||
return err
|
||||
}
|
||||
c.setRunning(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *reportingChat) setRunning(running bool) {
|
||||
c.rmu.Lock()
|
||||
c.running = running
|
||||
c.rmu.Unlock()
|
||||
}
|
||||
|
||||
// The live incident: a Claude turn's end frame was dropped on the way (a full
|
||||
// watcher buffer), so the room's own turn stayed "working" forever and every
|
||||
// later prompt queued behind it. Once the harness reports itself idle for the
|
||||
// settle period and its probe agrees, the turn is ended, the client told to
|
||||
// resync, and the queued prompt delivered. While it reports running, it waits.
|
||||
func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) {
|
||||
fastUnattended(t)
|
||||
fastStaleTurnSettle(t)
|
||||
t.Setenv("PIPELINES_NTFY_URL", "")
|
||||
store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db"))
|
||||
broker := &reportingChat{observedChat: newObservedChat()}
|
||||
server := startQueueServer(t, broker, store)
|
||||
conn := dialChatConn(t, server.ctx, server.srv)
|
||||
broker.setProbe(true)
|
||||
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"))
|
||||
waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_1")
|
||||
if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued {
|
||||
t.Fatalf("second prompt was not queued behind the running turn: %+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())
|
||||
}
|
||||
// The turn ends in the harness, but its end frame never arrives.
|
||||
broker.setRunning(false)
|
||||
broker.setProbe(false)
|
||||
sawResync := false
|
||||
for {
|
||||
message := readChatMessage(t, server.ctx, conn)
|
||||
if message.Type != protocol.ChatEvent || message.ChatEvent == nil {
|
||||
continue
|
||||
}
|
||||
if message.ChatEvent.Kind == protocol.ChatEventResync {
|
||||
sawResync = true
|
||||
}
|
||||
if step := message.ChatEvent.Step; step != nil && step.Status == protocol.ChatStepEnded && step.TurnID == "turn_1" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !sawResync {
|
||||
t.Fatal("the client was not told to resync after the lost end")
|
||||
}
|
||||
waitFor(t, "queued prompt delivered after the lost end", func() bool { return broker.promptCount() == 2 })
|
||||
if texts := broker.promptTexts(); texts[1] != "continue" {
|
||||
t.Fatalf("delivered = %v", texts)
|
||||
}
|
||||
}
|
||||
@@ -834,6 +834,20 @@ func (m *chatManager) TurnRunning(sessionID string) bool {
|
||||
return ok && reporter.TurnRunning(sessionID)
|
||||
}
|
||||
|
||||
// TracksTurnState reports whether the routed harness reports its own turn
|
||||
// state through TurnRunning (Claude Code does; OpenCode and Codex are probed).
|
||||
func (m *chatManager) TracksTurnState(sessionID string) bool {
|
||||
m.mu.Lock()
|
||||
backend := m.cache[sessionID]
|
||||
m.mu.Unlock()
|
||||
adapter := m.opencode
|
||||
if backend != "" && backend != "opencode" {
|
||||
adapter = m.attached(backend)
|
||||
}
|
||||
_, ok := adapter.(chatTurnReporter)
|
||||
return ok
|
||||
}
|
||||
|
||||
// ProbeTurn asks the session's own harness whether a turn is in flight. It is
|
||||
// the server-start probe (chat_unattended.go): a harness that can be asked
|
||||
// (OpenCode, Codex) is asked; otherwise its in-memory state is used, which for
|
||||
|
||||
@@ -190,6 +190,22 @@ func errChatQueueFull(sessionID string) error {
|
||||
return errors.New("session " + sessionID + " already has the maximum number of prompts queued")
|
||||
}
|
||||
|
||||
// chatTurnTracker is implemented by a broker that routes to several harnesses
|
||||
// and knows whether the one serving a session reports its own turn state.
|
||||
type chatTurnTracker interface {
|
||||
TracksTurnState(sessionID string) bool
|
||||
}
|
||||
|
||||
// brokerTracksTurns reports whether brokerTurnRunning's answer for sessionID
|
||||
// comes from a harness that tracks its turn, rather than a constant false.
|
||||
func brokerTracksTurns(broker chatBroker, sessionID string) bool {
|
||||
if tracker, ok := broker.(chatTurnTracker); ok {
|
||||
return tracker.TracksTurnState(sessionID)
|
||||
}
|
||||
_, ok := broker.(chatTurnReporter)
|
||||
return ok
|
||||
}
|
||||
|
||||
// brokerTurnRunning asks a harness that knows its own turn state without I/O.
|
||||
func brokerTurnRunning(broker chatBroker, sessionID string) bool {
|
||||
reporter, ok := broker.(chatTurnReporter)
|
||||
|
||||
@@ -925,10 +925,96 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{
|
||||
// Start the approval poller once, after the first ack, so a pending request
|
||||
// is surfaced after the prompt is acknowledged and shared with every client.
|
||||
h.startRoomPoller(room, broker)
|
||||
select {
|
||||
case <-done:
|
||||
case <-room.ctx.Done():
|
||||
h.awaitTurnEnd(room, broker, done)
|
||||
}
|
||||
|
||||
// awaitTurnEnd waits for the turn runner's turn to end. Its end normally
|
||||
// arrives as a step frame; the safety net covers an end that was lost on the
|
||||
// way (a full watcher buffer, a stream that reconnected): once a harness that
|
||||
// tracks its own turn state has reported itself idle for the settle period
|
||||
// (chatQueueStaleTurnSettle) and its own probe confirms no turn is in flight,
|
||||
// the turn is ended here and attached clients re-read the history. A harness
|
||||
// that cannot report or be probed is never second-guessed.
|
||||
func (h *chatHub) awaitTurnEnd(room *chatRoom, broker chatBroker, done chan struct{}) {
|
||||
prober, probes := broker.(chatTurnProber)
|
||||
if !probes || !brokerTracksTurns(broker, room.sessionID) {
|
||||
select {
|
||||
case <-done:
|
||||
case <-room.ctx.Done():
|
||||
}
|
||||
return
|
||||
}
|
||||
settle := h.unattended.staleTurn
|
||||
if settle <= 0 {
|
||||
settle = 10 * time.Second
|
||||
}
|
||||
ticker := time.NewTicker(min(chatQueueBusyPoll, settle/4))
|
||||
defer ticker.Stop()
|
||||
var idleSince time.Time
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-room.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
if brokerTurnRunning(broker, room.sessionID) {
|
||||
idleSince = time.Time{}
|
||||
continue
|
||||
}
|
||||
now := h.clock()
|
||||
if idleSince.IsZero() {
|
||||
idleSince = now
|
||||
}
|
||||
if now.Sub(idleSince) < settle {
|
||||
continue
|
||||
}
|
||||
probeCtx, cancel := context.WithTimeout(room.ctx, 5*time.Second)
|
||||
busy, err := prober.ProbeTurn(probeCtx, room.sessionID)
|
||||
cancel()
|
||||
if err != nil || busy {
|
||||
// Look again only after another settle period.
|
||||
idleSince = h.clock()
|
||||
continue
|
||||
}
|
||||
if h.endLostTurn(room, done, now.Sub(idleSince)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// endLostTurn ends the runner's turn whose end frame never arrived, exactly
|
||||
// as that frame would have, and asks attached clients to resync. It reports
|
||||
// false when the turn already ended (or the room was released) meanwhile.
|
||||
func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Duration) bool {
|
||||
h.mu.Lock()
|
||||
if h.rooms[room.sessionID] != room || room.ctx.Err() != nil || room.turnDone != done {
|
||||
h.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
log.Printf("chat session %s: the harness reports no turn running for %s but the turn %q never reported its end; ending it",
|
||||
room.sessionID, idle.Round(time.Second), room.nativeTurnID)
|
||||
end := protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: room.nativeTurnID, Kind: protocol.ChatEventStep,
|
||||
Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}}
|
||||
priorStep := h.turnLocked(room.sessionID).step
|
||||
h.applyLocked(end)
|
||||
h.noteTurnDiffLocked(room, end)
|
||||
h.noteReplyAttentionLocked(priorStep, end)
|
||||
h.finishTurnLocked(room)
|
||||
resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync}
|
||||
var slow []*chatSub
|
||||
for _, sub := range room.subs {
|
||||
if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) ||
|
||||
!enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) {
|
||||
slow = append(slow, sub)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, sub := range slow {
|
||||
sub.close()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// endRoomTurn releases the turn slot after a prompt that never entered flight,
|
||||
|
||||
Reference in New Issue
Block a user