diff --git a/app/lib/application/app_session.dart b/app/lib/application/app_session.dart index eae45388..5edbde6e 100644 --- a/app/lib/application/app_session.dart +++ b/app/lib/application/app_session.dart @@ -53,6 +53,7 @@ class AppSession extends ChangeNotifier { bool _subscribed = false, _disposed = false; bool _everConnected; int _connectionEpoch = 0; + int _runsResyncs = 0; RunSubscriptionState _subscription = RunSubscriptionState.pending; String _subscriptionError = ''; String? _subscribeRequest; @@ -79,6 +80,11 @@ class AppSession extends ChangeNotifier { /// detail without remounting the screen or losing its selection. int get connectionEpoch => _connectionEpoch; + /// Advances on every connected transition and whenever the server detached + /// this connection's run watch for falling behind (`runs_resync`). The Runs + /// screen keys its re-read with this: frames were discarded either way. + int get runsEpoch => _connectionEpoch + _runsResyncs; + /// Connects the shared socket. A missing endpoint is a configuration state, /// so this is a no-op rather than a guessed endpoint. Future start() async { @@ -140,6 +146,13 @@ class AppSession extends ChangeNotifier { void _onFrame(JsonMap frame) { if (_disposed) return; + if (frame['type'] == 'runs_resync') { + // The server dropped this watch because the connection fell behind and + // discarded the frames it still held: watch again and re-read the runs. + _runsResyncs++; + resubscribe(); + return; + } final id = frame['id']; if (id is! String || id != _subscribeRequest) return; switch (frame['type']) { diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index 6dffbe39..8f56fc4b 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -103,7 +103,7 @@ class RunsDestination extends StatelessWidget { initialStageKey: initialStageKey, initialVisit: initialVisit, initialDecide: initialDecide, - syncToken: session.connectionEpoch, + syncToken: session.runsEpoch, listRefreshToken: listRefreshToken, notifications: notifications, attention: attention, diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index b4a6d6c9..7b002faa 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -439,9 +439,10 @@ class ChatThreadController extends ChangeNotifier { return; } // A delta a history page already included is not added again. - if (!_live.admit(body)) return; + final admitted = _live.admit(body); + if (admitted == null) return; final current = _thread; - final next = applyChatEvent(current, body); + final next = applyChatEvent(current, admitted); if (identical(next, current)) return; // A frame for a cached message is fresh state the next read must not drop. final changed = body['message_id']; diff --git a/app/lib/features/chat/domain/chat_live_frames.dart b/app/lib/features/chat/domain/chat_live_frames.dart index d62aa7b1..6212f34d 100644 --- a/app/lib/features/chat/domain/chat_live_frames.dart +++ b/app/lib/features/chat/domain/chat_live_frames.dart @@ -28,17 +28,21 @@ class ChatLiveFrames { /// Stops recording for a read that will not be applied. void abandon(List frames) => _reads.remove(frames); - /// Whether [frame] should be folded into the held transcript, recording it - /// for every read in flight. A frame with no number is always folded. - bool admit(JsonMap frame) { + /// The part of [frame] to fold into the held transcript, recording it for + /// every read in flight, or null when a page already included all of it. A + /// frame with no number is always folded whole; a joined frame whose first + /// deltas were already included is trimmed to the rest. + JsonMap? admit(JsonMap frame) { final seq = frame['seq']; - if (seq is! int) return true; - if (seq <= _included) return false; + if (seq is! int) return frame; + if (seq <= _included) return null; + final admitted = chatDeltasAfter(frame, _included); + if (admitted == null) return null; _included = seq; for (final read in _reads) { - read.add(frame); + read.add(admitted); } - return true; + return admitted; } /// [messages] after applying [page]: frames recorded during the read that @@ -65,9 +69,11 @@ class ChatLiveFrames { }; } var thread = {'messages': messages}; - for (final frame in frames) { - final seq = frame['seq']; + for (final recorded in frames) { + final seq = recorded['seq']; if (seq is! int || seq <= liveSeq) continue; + final frame = chatDeltasAfter(recorded, liveSeq); + if (frame == null) continue; final messageId = frame['message_id']; if (!replaced(messageId)) continue; final part = frame['part']; @@ -82,3 +88,35 @@ class ChatLiveFrames { return chatMessageList(thread['messages']); } } + +/// [frame] without the numbered deltas up to [included]. +/// +/// A server joins consecutive deltas of one part while a slow client's queue +/// is backed up: the joined frame's `seq_from`..`seq` names the deltas it holds +/// and `delta_lens` each one's length in UTF-16 code units. When a history page +/// already holds a prefix of them, only the rest is new. A plain frame (or one +/// wholly past [included]) is returned unchanged; null means nothing in it is +/// new. +JsonMap? chatDeltasAfter(JsonMap frame, int included) { + final seq = frame['seq']; + if (seq is! int) return frame; + if (seq <= included) return null; + final from = frame['seq_from']; + final lens = frame['delta_lens']; + if (from is! int || from > included || lens is! List) return frame; + final delta = frame['delta']; + if (delta is! String || lens.length != seq - from + 1) return frame; + var cut = 0; + for (var i = 0; i <= included - from; i++) { + final length = lens[i]; + if (length is! int || length < 0) return frame; + cut += length; + } + if (cut >= delta.length) return null; + return { + ...frame, + 'delta': delta.substring(cut), + 'seq_from': included + 1, + 'delta_lens': lens.sublist(included - from + 1), + }; +} diff --git a/app/test/application/app_session_test.dart b/app/test/application/app_session_test.dart index 28233da0..a6c7dd00 100644 --- a/app/test/application/app_session_test.dart +++ b/app/test/application/app_session_test.dart @@ -140,6 +140,37 @@ void main() { expect(session.subscriptionError, contains('too many run subscriptions')); }); + test('runs_resync watches again and advances the runs epoch', () async { + // The server detached this connection's run watch because it fell behind + // and discarded the frames it held; without a new subscribe the Runs + // list and detail froze until the next reconnect. + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + final subscribe = + jsonDecode(channel.outgoing.single as String) as Map; + channel.incoming.add( + jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}), + ); + await flush(); + final epoch = session.runsEpoch; + final connection = session.connectionEpoch; + + channel.incoming.add(jsonEncode({'type': 'runs_resync'})); + await flush(); + expect(types(channel), ['subscribe', 'subscribe']); + expect(session.runsEpoch, greaterThan(epoch)); + expect(session.connectionEpoch, connection); + expect(session.subscription, RunSubscriptionState.pending); + }); + test('dispose drops the watch and releases the client', () async { final channel = FakeChannel()..readyCompleter.complete(); final client = PipelinesClient(channelFactory: (_) => channel); diff --git a/app/test/features/chat/domain/chat_live_frames_test.dart b/app/test/features/chat/domain/chat_live_frames_test.dart new file mode 100644 index 00000000..00dfd674 --- /dev/null +++ b/app/test/features/chat/domain/chat_live_frames_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_live_frames.dart'; + +/// A frame the server joined from deltas 10..12 ("héllo ", "wörld ", "😀!") +/// while this client's queue was backed up. +Map joined() => { + 'session_id': 's', + 'message_id': 'm', + 'kind': 'text', + 'part': {'type': 'text', 'id': 'm-text-0'}, + 'delta': 'héllo wörld 😀!', + 'seq_from': 10, + 'seq': 12, + 'delta_lens': [6, 6, 3], +}; + +void main() { + test('a joined frame drops exactly the deltas a page already holds', () { + expect(chatDeltasAfter(joined(), 9)?['delta'], 'héllo wörld 😀!'); + final rest = chatDeltasAfter(joined(), 10)!; + expect(rest['delta'], 'wörld 😀!'); + expect(rest['seq_from'], 11); + expect(rest['delta_lens'], [6, 3]); + expect(chatDeltasAfter(joined(), 11)?['delta'], '😀!'); + expect(chatDeltasAfter(joined(), 12), isNull); + }); + + test('a plain numbered delta is folded whole or not at all', () { + final plain = {'kind': 'text', 'delta': 'x', 'seq': 5}; + expect(chatDeltasAfter(plain, 4), same(plain)); + expect(chatDeltasAfter(plain, 5), isNull); + }); + + test('admit trims a joined frame overlapping what was included', () { + final live = ChatLiveFrames(); + final first = {'kind': 'text', 'delta': 'héllo ', 'seq': 10}; + expect(live.admit(first), same(first)); + // The rest arrives joined with the delta already shown. + expect(live.admit(joined())?['delta'], 'wörld 😀!'); + expect(live.admit(joined()), isNull); + }); + + test('settle folds back only the part of a joined frame past the page', () { + final live = ChatLiveFrames(); + final read = live.beginRead(); + live.admit(joined()); + final page = { + 'liveSeq': 11, + 'liveParts': ['m-text-0'], + 'messages': [ + { + 'id': 'm', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'id': 'm-text-0', 'text': 'héllo wörld '}, + ], + }, + ], + }; + final messages = live.settle(read, page, [ + for (final message in page['messages'] as List) + Map.from(message as Map), + ], replaced: (_) => true); + final parts = messages.single['parts'] as List; + expect((parts.single as Map)['text'], 'héllo wörld 😀!'); + }); +} diff --git a/docs/cli.md b/docs/cli.md index 0bab3de4..c413128d 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -480,6 +480,16 @@ history refresh without inventing text deltas or ending a queued prompt. Native step markers may include `step.turn_id`; a terminal marker for an older turn must not clear a newer turn's Stop control or release its queue slot. +A client that falls too far behind its chat stream (64 queued frames) is +detached; its last frame is `chat_event.kind="resync"`, so it must send +`chat_subscribe` again before re-reading history. Consecutive text or reasoning +deltas of one part are joined while queued: a joined numbered frame carries +`seq` (its last delta), `seq_from` (its first) and `delta_lens` (each delta's +length in UTF-16 code units), so a client whose history page's `liveSeq` +falls inside the range drops exactly the prefix the page already holds. A run +subscriber that falls behind likewise receives a final `{"type":"runs_resync"}` +and must send `subscribe` again for a fresh snapshot. + Native context compaction is reported as `chat_event.kind="compaction"`, with `compaction: {status: "running" | "completed" | "failed", id?: string}`. Optional `native_turn_id` scopes the activity to its real harness turn; ignore diff --git a/internal/claude/claude.go b/internal/claude/claude.go index 6ef01238..59b66db1 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -474,14 +474,39 @@ func (s *session) emit(frame protocol.ChatEventFrame) { targets = append(targets, ch) } s.mu.Unlock() + lifecycle := frameIsLifecycle(frame) for _, ch := range targets { select { case ch <- frame: + continue default: } + if !lifecycle { + continue + } + // A full watcher may lose a delta (the hub repairs text from + // history), but never a step start or end: a lost end leaves the + // turn "working" forever. Wait, bounded, for the watcher to drain. + timer := time.NewTimer(lifecycleDeliveryTimeout) + select { + case ch <- frame: + case <-timer.C: + log.Printf("claude session %s: a watcher did not accept the %s frame within %s; it was dropped", s.id, frame.Kind, lifecycleDeliveryTimeout) + } + timer.Stop() } } +// lifecycleDeliveryTimeout bounds how long emit waits for a full watcher to +// accept a turn lifecycle frame before it gives up on that watcher. +var lifecycleDeliveryTimeout = 5 * time.Second + +// frameIsLifecycle reports whether a frame changes the turn's state, so it +// must reach every watcher even when that watcher's buffer is full. +func frameIsLifecycle(frame protocol.ChatEventFrame) bool { + return frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventResync +} + func (s *session) subscribe() chan protocol.ChatEventFrame { ch := make(chan protocol.ChatEventFrame, 256) s.mu.Lock() diff --git a/internal/claude/emit_lifecycle_test.go b/internal/claude/emit_lifecycle_test.go new file mode 100644 index 00000000..6577e5c3 --- /dev/null +++ b/internal/claude/emit_lifecycle_test.go @@ -0,0 +1,61 @@ +package claude + +import ( + "context" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A watcher whose buffer is full of streamed text may lose a delta, but never +// the turn's end: a lost end left the chat "working" forever. +func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) { + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_full", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + emitted := make(chan struct{}) + go func() { + defer close(emitted) + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + }() + // The watcher is slow, not gone: it drains only after the end was emitted. + time.Sleep(100 * time.Millisecond) + deadline := time.After(3 * time.Second) + for { + select { + case frame := <-ch: + if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded { + <-emitted + return + } + case <-deadline: + t.Fatal("the turn end never reached the full watcher") + } + } +} + +// A watcher that never drains does not hold the CLI reader forever. +func TestEmitGivesUpOnAStuckWatcher(t *testing.T) { + prior := lifecycleDeliveryTimeout + lifecycleDeliveryTimeout = 50 * time.Millisecond + t.Cleanup(func() { lifecycleDeliveryTimeout = prior }) + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_stuck", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + start := time.Now() + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + if waited := time.Since(start); waited > 2*time.Second { + t.Fatalf("emit blocked %s on a stuck watcher", waited) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index e5433ea3..f8252115 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -758,6 +758,13 @@ type ChatEventFrame struct { // Seq numbers a text or reasoning delta within its session, increasing; // see ChatHistoryPage.LiveSeq. Zero when the harness does not number them. Seq int64 `json:"seq,omitempty"` + // SeqFrom and DeltaLens are set on a frame joining consecutive numbered + // deltas of one part (a slow client's queue coalesced them, see + // chatSub): SeqFrom is the first joined delta's Seq (Seq the last), and + // DeltaLens each joined delta's length in UTF-16 code units, so a client + // whose history page already holds a prefix (LiveSeq) drops exactly it. + SeqFrom int64 `json:"seq_from,omitempty"` + DeltaLens []int `json:"delta_lens,omitempty"` } // ChatCompaction is session activity, never a transcript message or tool. diff --git a/internal/protocol/runevents.go b/internal/protocol/runevents.go index d5915216..9689e3e1 100644 --- a/internal/protocol/runevents.go +++ b/internal/protocol/runevents.go @@ -11,6 +11,10 @@ const ( Subscribe = "subscribe" Unsubscribe = "unsubscribe" RunEvent = "run_event" + // RunsResync is the last frame of a subscription the server detached + // because its client fell too far behind: the client must send subscribe + // again and re-read the runs it shows, since frames were discarded. + RunsResync = "runs_resync" ) // RunEventFrame is the server-pushed run_event delta. It carries only the values diff --git a/internal/server/chat_activity_test.go b/internal/server/chat_activity_test.go index 5fa6f2d2..44b7445f 100644 --- a/internal/server/chat_activity_test.go +++ b/internal/server/chat_activity_test.go @@ -173,7 +173,7 @@ func TestChatBackgroundTasksKeepUnattendedRoom(t *testing.T) { if tasks > 0 { h.turnLocked(id).applyShell(&protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning}) } - sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() h.detach(id, sub) diff --git a/internal/server/chat_compaction.go b/internal/server/chat_compaction.go index 6b16a9b0..3079c7b3 100644 --- a/internal/server/chat_compaction.go +++ b/internal/server/chat_compaction.go @@ -35,7 +35,7 @@ func (h *chatHub) replayCompaction(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } @@ -56,9 +56,9 @@ func (h *chatHub) clearCompactionLocked(room *chatRoom) { } for _, sub := range room.subs { if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}) { - // close detaches under h.mu; never block the folding lock. A full - // queue must reconnect rather than silently miss terminal cleanup. - go sub.close() + // overflow detaches under h.mu; never block the folding lock. A + // full queue must resync rather than silently miss terminal cleanup. + go sub.overflow() } } } diff --git a/internal/server/chat_compaction_test.go b/internal/server/chat_compaction_test.go index 63ddcab7..64943e87 100644 --- a/internal/server/chat_compaction_test.go +++ b/internal/server/chat_compaction_test.go @@ -14,63 +14,63 @@ func TestCompactionRetainedReplayIsolationAndTerminalClear(t *testing.T) { room.running, room.nativeTurnID = true, "turn_new" room.turnDone = make(chan struct{}) h.rooms[room.sessionID] = room - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})} room.subs[sub.clientID] = sub emit := func(id, status, nativeID string) { h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: nativeID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{ID: id, Status: status}}) } emit("old", "running", "turn_old") - if len(sub.ch) != 0 { + if sub.queued() != 0 { t.Fatal("old native turn surfaced") } emit("first", "running", "turn_new") - <-sub.ch + sub.take() if got := h.snapshot(room.sessionID); len(got) != 0 { t.Fatalf("fake message: %+v", got) } h.replayCompaction(sub) - if f := (<-sub.ch).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" { + if f := (sub.take()).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" { t.Fatalf("replay without assistant: %+v", f) } other := newChatRoom(context.Background(), "ses_other") defer other.cancel() h.rooms[other.sessionID] = other - otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})} + otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})} other.subs[otherSub.clientID] = otherSub h.replayCompaction(otherSub) - if len(otherSub.ch) != 0 { + if otherSub.queued() != 0 { t.Fatal("foreign-session replay") } resetOld := h.compactionReset(room.sessionID) emit("second", "running", "turn_new") - <-sub.ch + sub.take() resetOld() emit("first", "completed", "turn_new") - if len(sub.ch) != 0 || h.turns[room.sessionID].compaction.ID != "second" { + if sub.queued() != 0 || h.turns[room.sessionID].compaction.ID != "second" { t.Fatal("old lifecycle cleared newer compaction") } h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Intermediate: true}}) - <-sub.ch + sub.take() if h.turns[room.sessionID].compaction == nil || !room.running { t.Fatal("provider step settled compaction or turn") } emit("second", "completed", "turn_new") - <-sub.ch + sub.take() if !room.running { t.Fatal("compaction completion released turn queue") } emit("third", "running", "turn_new") - <-sub.ch + sub.take() h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_new"}}) - if f := (<-sub.ch).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" { + if f := (sub.take()).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" { t.Fatalf("terminal cleanup: %+v", f) } - <-sub.ch // authoritative step completion + sub.take() // authoritative step completion if room.running || h.turns[room.sessionID].compaction != nil { t.Fatal("terminal state stuck") } emit("third", "running", "turn_new") - if len(sub.ch) != 0 { + if sub.queued() != 0 { t.Fatal("late old-turn activity revived label") } } @@ -83,10 +83,10 @@ func TestCompactionTransportLossAndInterruptClearDoNotReleaseTurn(t *testing.T) defer room.cancel() h.rooms[room.sessionID] = room room.running = true - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 8), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 8, done: make(chan struct{})} room.subs[sub.clientID] = sub h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running", ID: "compact"}}) - <-sub.ch + sub.take() switch mode { case "interrupt": h.compactionReset(room.sessionID)() diff --git a/internal/server/chat_detach.go b/internal/server/chat_detach.go index f6ea4e47..5dc0f852 100644 --- a/internal/server/chat_detach.go +++ b/internal/server/chat_detach.go @@ -294,8 +294,11 @@ func (h *chatHub) endObservedTurnLocked(room *chatRoom) { 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}) + if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) || + !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) { + // overflow detaches under h.mu: never from inside the fold lock. + go sub.overflow() + } } } diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index c2359e82..d9455868 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -391,7 +391,7 @@ func (h *chatHub) replayUsage(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } diff --git a/internal/server/chat_lost_end_test.go b/internal/server/chat_lost_end_test.go new file mode 100644 index 00000000..99db772e --- /dev/null +++ b/internal/server/chat_lost_end_test.go @@ -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) + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 533d5d9a..d5340735 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -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 diff --git a/internal/server/chat_multiclient_test.go b/internal/server/chat_multiclient_test.go index 53890952..3bf6fd6b 100644 --- a/internal/server/chat_multiclient_test.go +++ b/internal/server/chat_multiclient_test.go @@ -313,8 +313,9 @@ func TestChatFanoutToSeveralClients(t *testing.T) { name string conn *websocket.Conn }{{"phone", phone}, {"tablet", tablet}} { + // Deltas still queued for a client may arrive joined into one frame. var text strings.Builder - for i := 0; i < 2; i++ { + for i := 0; text.Len() < len("hello"); i++ { frame := nextEvent(t, ctx, client.conn) if frame.Kind != protocol.ChatEventText { t.Fatalf("%s frame %d = %+v, want text", client.name, i, frame) diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 2f5d26a6..1a266e7c 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -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) diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 85a69615..9e518d21 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -46,17 +46,29 @@ const ( // chatSub is one client's attachment to a session's shared stream. Frames reach // it through a dedicated writer goroutine so a slow or broken client never stalls -// the turn or the other subscribers; the buffered channel bounds how far behind -// it may fall. +// the turn or the other subscribers; the bounded queue limits how far behind it +// may fall. Consecutive text or reasoning deltas of one part are joined in the +// queue, so a streaming burst takes one slot. A client that still falls behind +// is detached, and its writer ends the stream with a resync frame so the client +// re-attaches and re-reads the authoritative history instead of silently +// missing frames. type chatSub struct { hub *chatHub room *chatRoom clientID string label string - ch chan protocol.Message done chan struct{} once sync.Once write func(protocol.Message) error + + // qmu guards the queue. It is taken under h.mu (enqueue) and never + // takes h.mu itself. + qmu sync.Mutex + queue []protocol.Message + limit int // 0 means chatRoomSubscriberBuffer + ready chan struct{} // signalled when the queue gains a frame + overflowed bool + overOnce sync.Once } func (s *chatSub) run() { @@ -64,28 +76,118 @@ func (s *chatSub) run() { select { case <-s.done: return - case msg := <-s.ch: - if err := s.write(msg); err != nil { - s.close() + default: + } + msg, ok, overflowed := s.next() + if overflowed { + // The terminal frame: everything still queued was discarded, so + // the client must re-attach and re-read the history. + resync := protocol.ChatEventFrame{SessionID: s.room.sessionID, Kind: protocol.ChatEventResync} + _ = s.write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) + s.close() + return + } + if !ok { + select { + case <-s.done: return + case <-s.ready: } + continue + } + if err := s.write(msg); err != nil { + s.close() + return } } } -func (s *chatSub) send(msg protocol.Message) { +// next pops the oldest queued frame, or reports that the subscription +// overflowed. +func (s *chatSub) next() (protocol.Message, bool, bool) { + s.qmu.Lock() + defer s.qmu.Unlock() + if s.overflowed { + return protocol.Message{}, false, true + } + if len(s.queue) == 0 { + return protocol.Message{}, false, false + } + msg := s.queue[0] + s.queue[0] = protocol.Message{} + s.queue = s.queue[1:] + return msg, true, false +} + +// queued is the number of frames waiting for the writer. +func (s *chatSub) queued() int { + s.qmu.Lock() + defer s.qmu.Unlock() + return len(s.queue) +} + +// enqueue queues msg without blocking, joining it to the previous delta of the +// same part. It reports false when the queue is full; the caller must then +// call overflow, outside h.mu. It never detaches, so it may run under h.mu. +func (s *chatSub) enqueue(msg protocol.Message) bool { select { case <-s.done: - return + return true default: } - select { - case s.ch <- msg: - default: - // The client is not draining: drop it rather than block the fan-out. Its - // next attach re-syncs from history. - s.close() + s.qmu.Lock() + defer s.qmu.Unlock() + if s.overflowed { + return true // discarded: the client is told to resync } + if n := len(s.queue); n > 0 { + if joined, ok := joinChatDeltas(s.queue[n-1], msg); ok { + s.queue[n-1] = joined + return true + } + } + limit := s.limit + if limit <= 0 { + limit = chatRoomSubscriberBuffer + } + if len(s.queue) >= limit { + return false + } + s.queue = append(s.queue, msg) + if s.ready != nil { + select { + case s.ready <- struct{}{}: + default: + } + } + return true +} + +func (s *chatSub) send(msg protocol.Message) { + if !s.enqueue(msg) { + // The client is not draining: detach it rather than block the + // fan-out. Its writer tells it to resync. + s.overflow() + } +} + +// overflow detaches a subscription whose client fell too far behind and lets +// its writer end the stream with a resync frame. Callers must not hold h.mu. +func (s *chatSub) overflow() { + s.overOnce.Do(func() { + s.qmu.Lock() + s.overflowed = true + s.queue = nil + if s.ready != nil { + select { + case s.ready <- struct{}{}: + default: + } + } + s.qmu.Unlock() + log.Printf("chat session %s: client %s fell %d frames behind; it is told to resync", s.room.sessionID, s.clientID, chatRoomSubscriberBuffer) + s.hub.detach(s.room.sessionID, s) + }) } // close detaches the subscription and stops its writer goroutine exactly once. @@ -96,6 +198,61 @@ func (s *chatSub) close() { }) } +// joinChatDeltas joins next onto last when both are plain text or reasoning +// deltas of the same part, so a burst takes one queue slot. Numbered deltas +// join only when consecutive; the joined frame names its first delta +// (SeqFrom) and each delta's length, so a client whose history page already +// holds a prefix can drop exactly that prefix. +func joinChatDeltas(last, next protocol.Message) (protocol.Message, bool) { + a, b := last.ChatEvent, next.ChatEvent + if last.Type != protocol.ChatEvent || next.Type != protocol.ChatEvent || a == nil || b == nil || last.ID != "" || next.ID != "" { + return last, false + } + if !plainChatDelta(a) || !plainChatDelta(b) || a.Kind != b.Kind || a.SessionID != b.SessionID || a.MessageID != b.MessageID || + a.NativeTurnID != b.NativeTurnID || a.MessageKind != b.MessageKind || a.Part.ID != b.Part.ID || a.Part.Type != b.Part.Type { + return last, false + } + if (a.Seq == 0) != (b.Seq == 0) || (a.Seq != 0 && b.Seq != a.Seq+1) { + return last, false + } + joined := *a + part := *a.Part + joined.Part = &part + joined.Delta = a.Delta + b.Delta + if a.Seq != 0 { + lens := a.DeltaLens + if a.SeqFrom == 0 { + joined.SeqFrom = a.Seq + lens = []int{utf16Len(a.Delta)} + } + joined.DeltaLens = append(slices.Clip(lens), utf16Len(b.Delta)) + joined.Seq = b.Seq + } + last.ChatEvent = &joined + return last, true +} + +// plainChatDelta reports whether f carries only a text or reasoning delta. +func plainChatDelta(f *protocol.ChatEventFrame) bool { + return (f.Kind == protocol.ChatEventText || f.Kind == protocol.ChatEventReasoning) && f.Delta != "" && f.Part != nil && + f.Part.Text == "" && f.Step == nil && f.Usage == nil && f.Shell == nil && f.Form == nil && f.Compaction == nil && + len(f.Attachments) == 0 && f.Client == "" && f.OperationID == "" +} + +// utf16Len is the length of s in UTF-16 code units, the unit a Dart client +// indexes strings by. +func utf16Len(s string) int { + n := 0 + for _, r := range s { + if r >= 0x10000 { + n += 2 + } else { + n++ + } + } + return n +} + // chatQueuedPrompt is one prompt waiting for the session's in-flight turn to // finish. acked marks a prompt the handler already acknowledged as queued, so the // turn runner does not send a second (success) acknowledgement for the same @@ -316,7 +473,7 @@ func (h *chatHub) attach(sessionID, clientID, label string, broker chatBroker, w room: room, clientID: clientID, label: label, - ch: make(chan protocol.Message, chatRoomSubscriberBuffer), + ready: make(chan struct{}, 1), done: make(chan struct{}), write: write, } @@ -396,7 +553,7 @@ func (h *chatHub) roomBacklog(sessionID string) int { most := 0 if room := h.rooms[sessionID]; room != nil { for _, sub := range room.subs { - most = max(most, len(sub.ch)) + most = max(most, sub.queued()) } } return most @@ -529,7 +686,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) { } h.mu.Unlock() for _, sub := range slow { - sub.close() + sub.overflow() } return } @@ -543,19 +700,10 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) { } } -// enqueueChatLocked never blocks or calls detach under the hub mutex. +// enqueueChatLocked never blocks or calls detach under the hub mutex. A false +// result means the client overflowed: call sub.overflow once h.mu is released. func enqueueChatLocked(sub *chatSub, msg protocol.Message) bool { - select { - case <-sub.done: - return true - default: - } - select { - case sub.ch <- msg: - return true - default: - return false - } + return sub.enqueue(msg) } func (h *chatHub) replayShells(sub *chatSub) { @@ -574,7 +722,7 @@ func (h *chatHub) replayShells(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } @@ -661,7 +809,7 @@ func (h *chatHub) flushBuffered(sessionID string) { } h.mu.Unlock() for _, sub := range slow { - sub.close() + sub.overflow() } } @@ -925,10 +1073,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.overflow() + } + return true } // endRoomTurn releases the turn slot after a prompt that never entered flight, diff --git a/internal/server/chat_sub_overflow_test.go b/internal/server/chat_sub_overflow_test.go new file mode 100644 index 00000000..8e515ab7 --- /dev/null +++ b/internal/server/chat_sub_overflow_test.go @@ -0,0 +1,125 @@ +package server + +import ( + "strings" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// take pops the oldest queued frame (the zero Message when none is queued). +func (s *chatSub) take() protocol.Message { + msg, _, _ := s.next() + return msg +} + +func deltaMessage(seq int64, delta string) protocol.Message { + frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: delta, Seq: seq, + Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1-text-0"}} + return protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame} +} + +// A streaming burst must not overflow a client that is merely a little slow: +// consecutive deltas of one part take one queue slot, and the joined frame +// says which numbered deltas it holds and how long each one is. +func TestChatSubJoinsConsecutiveDeltasOfOnePart(t *testing.T) { + sub := &chatSub{limit: 2, done: make(chan struct{})} + pieces := []string{"héllo ", "wörld ", "😀!"} + for i, piece := range pieces { + if !sub.enqueue(deltaMessage(int64(10+i), piece)) { + t.Fatalf("delta %d overflowed a two-slot queue", i) + } + } + if sub.queued() != 1 { + t.Fatalf("queued = %d, want the burst joined into one frame", sub.queued()) + } + // A frame of another kind is never joined. + step := protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}} + if !sub.enqueue(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &step}) { + t.Fatal("step frame refused") + } + if sub.enqueue(deltaMessage(13, "late")) { + t.Fatal("a delta after the step joined across it") + } + joined := sub.take().ChatEvent + if joined.Delta != strings.Join(pieces, "") || joined.SeqFrom != 10 || joined.Seq != 12 { + t.Fatalf("joined = %+v", joined) + } + if want := []int{6, 6, 3}; len(joined.DeltaLens) != 3 || joined.DeltaLens[0] != want[0] || joined.DeltaLens[1] != want[1] || joined.DeltaLens[2] != want[2] { + t.Fatalf("delta lengths = %v, want %v (UTF-16 units)", joined.DeltaLens, want) + } + // A gap in the numbering is never joined over. + sub2 := &chatSub{limit: 4, done: make(chan struct{})} + sub2.enqueue(deltaMessage(1, "a")) + sub2.enqueue(deltaMessage(3, "c")) + if sub2.queued() != 2 { + t.Fatal("deltas with a numbering gap were joined") + } +} + +// The frame a delta came from is shared by every subscriber, so joining for +// one slow client must not change what another client is sent. +func TestChatSubJoinDoesNotMutateSharedFrames(t *testing.T) { + sub := &chatSub{limit: 4, done: make(chan struct{})} + first := deltaMessage(1, "a") + sub.enqueue(first) + sub.enqueue(deltaMessage(2, "b")) + if first.ChatEvent.Delta != "a" || first.ChatEvent.Seq != 1 || first.ChatEvent.SeqFrom != 0 { + t.Fatalf("shared frame mutated: %+v", first.ChatEvent) + } +} + +// The live incident: a slow client's 64-frame buffer filled and the server +// silently dropped its subscription, so the app kept showing a frozen +// transcript until the next reconnect. Now the client's last frame is a +// resync, which makes the app re-attach and re-read the history. +func TestChatSubOverflowEndsWithAResyncFrame(t *testing.T) { + h := newChatHub() + h.mu.Lock() + room := h.roomLocked("ses_1") + h.mu.Unlock() + defer room.cancel() + release := make(chan struct{}) + var mu sync.Mutex + var written []protocol.Message + write := func(msg protocol.Message) error { + <-release // the client does not read until the burst is over + mu.Lock() + written = append(written, msg) + mu.Unlock() + return nil + } + sub := h.attach("ses_1", "slow", "Phone", nil, write) + for i := range chatRoomSubscriberBuffer + 8 { + // Tool frames never join, so the queue fills. + frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, + Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "tool", Name: strings.Repeat("x", i%3+1)}} + h.fanout("ses_1", protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}, "") + } + h.mu.Lock() + attached := room.subs["slow"] == sub + h.mu.Unlock() + if attached { + t.Fatal("an overflowed client stayed attached") + } + close(release) + select { + case <-sub.done: + case <-time.After(5 * time.Second): + t.Fatal("the overflowed subscription never closed") + } + mu.Lock() + defer mu.Unlock() + last := written[len(written)-1] + if last.Type != protocol.ChatEvent || last.ChatEvent == nil || last.ChatEvent.Kind != protocol.ChatEventResync || last.ChatEvent.SessionID != "ses_1" { + t.Fatalf("the overflowed client's last frame was %+v, want a resync", last) + } + // The client re-attaches with its own subscribe: a fresh subscription. + again := h.attach("ses_1", "slow", "Phone", nil, func(protocol.Message) error { return nil }) + if again == nil || again == sub { + t.Fatal("re-attaching after an overflow did not create a fresh subscription") + } + again.close() +} diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index 5b6513c4..3a03d262 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -549,10 +549,12 @@ func TestChatPromptStreamsEvents(t *testing.T) { t.Fatalf("ack = %+v", ack) } frames := readChatTurn(t, ctx, conn) - if len(frames) != 4 { - t.Fatalf("got %d frames, want 4", len(frames)) + // The two text deltas may arrive joined into one frame. + if len(frames) != 4 && len(frames) != 3 { + t.Fatalf("got %d frames, want 4 (or 3 with the deltas joined)", len(frames)) } sawText, sawStep := false, false + var text strings.Builder for _, frame := range frames { if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" { t.Fatalf("frame missing stable ids: %+v", frame) @@ -560,6 +562,7 @@ func TestChatPromptStreamsEvents(t *testing.T) { switch frame.Kind { case protocol.ChatEventText: sawText = true + text.WriteString(frame.Delta) case protocol.ChatEventStep: sawStep = true if frame.Step == nil || frame.Step.Status != protocol.ChatStepEnded { @@ -567,8 +570,8 @@ func TestChatPromptStreamsEvents(t *testing.T) { } } } - if !sawText || !sawStep { - t.Fatalf("missing text or step frame: %+v", frames) + if !sawText || !sawStep || text.String() != "hello world" { + t.Fatalf("missing text or step frame (text %q): %+v", text.String(), frames) } if prompts, _, _ := broker.counts(); prompts != 1 { t.Fatalf("prompt forwarded %d times, want 1", prompts) diff --git a/internal/server/chat_unattended_test.go b/internal/server/chat_unattended_test.go index d6d2e23d..0c5f1fbc 100644 --- a/internal/server/chat_unattended_test.go +++ b/internal/server/chat_unattended_test.go @@ -337,7 +337,7 @@ func TestChatUnattendedRoomsAreBounded(t *testing.T) { h.mu.Lock() room := h.roomLocked(id) room.running = true - sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() h.detach(id, sub) diff --git a/internal/server/chat_usage_test.go b/internal/server/chat_usage_test.go index b72105f2..31d99707 100644 --- a/internal/server/chat_usage_test.go +++ b/internal/server/chat_usage_test.go @@ -15,20 +15,20 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing. room.nativeTurnID = "turn_keep" room.turnDone = make(chan struct{}) h.rooms[room.sessionID] = room - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})} room.subs[sub.clientID] = sub h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}}) for _, n := range []int64{123, 123, 0, 5} { total := n u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total} h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u}) - live := (<-sub.ch).ChatEvent + live := (sub.take()).ChatEvent if live.MessageID != "" || *live.Usage.TotalTokens != n { t.Fatalf("live=%+v", live) } total = 999 // producer-owned data must not mutate retained state h.replayUsage(sub) - frame := (<-sub.ch).ChatEvent + frame := (sub.take()).ChatEvent if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n { t.Fatalf("replay=%+v", frame) } @@ -47,18 +47,18 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing. } // A full snapshot may legitimately reset every unknown field to nil. h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}}) - <-sub.ch + sub.take() h.replayUsage(sub) - if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil { + if f := (sub.take()).ChatEvent; f.Usage.TotalTokens != nil { t.Fatal("unknown snapshot accumulated old counter") } other := newChatRoom(context.Background(), "ses_other") defer other.cancel() h.rooms[other.sessionID] = other - otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})} + otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})} other.subs[otherSub.clientID] = otherSub h.replayUsage(otherSub) - if len(otherSub.ch) != 0 { + if otherSub.queued() != 0 { t.Fatal("foreign usage replayed") } } diff --git a/internal/server/run_reattach_test.go b/internal/server/run_reattach_test.go index 047170ca..1f330347 100644 --- a/internal/server/run_reattach_test.go +++ b/internal/server/run_reattach_test.go @@ -194,6 +194,40 @@ func TestStageRunWithHarnessGoneFallsBackWithReason(t *testing.T) { } } +// TestUninterruptibleStageSessionInterruptsOnlyItsRun: one stage session that +// start-up cannot confirm stopped (a crashed Pi owner, a missing Claude +// evidence directory) used to fail the whole runner, disabling every run. +// Now only its run is interrupted, naming why, and the runner starts. +func TestUninterruptibleStageSessionInterruptsOnlyItsRun(t *testing.T) { + seamRestartRecovery(t, nil) + interruptRecoveredSession = func(context.Context, pipeline.SessionOwner) error { + return fmt.Errorf("retained Pi owner: %w", stage.ErrStageCleanup) + } + f := stopMidStage(t, func(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) { + if err := s.RunSession(context.Background(), id, 1, "ses_pi", true, "pi", "/nonexistent/pi-ref"); err != nil { + return stage.Result{}, err + } + <-ctx.Done() + return stage.Result{}, stage.ErrDetached + }) + r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { + t.Error("an interrupted run executed again") + return stage.Result{}, nil + }) + r.reattachRuns() + r.wg.Wait() + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be confirmed stopped") || !strings.Contains(d.Diagnostic, "ses_pi") { + t.Fatalf("uninterruptible session's run lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic) + } + if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { + t.Fatalf("the interrupted run's session still blocks recovery at the next start: %+v", owners) + } +} + // TestStageNotYetAdmittedStartsAgainAfterRestart: a visit the stopped server // had begun but not handed to any session is started again, nothing replayed. func TestStageNotYetAdmittedStartsAgainAfterRestart(t *testing.T) { diff --git a/internal/server/runevents.go b/internal/server/runevents.go index ddf8bfd8..bd4e4e3c 100644 --- a/internal/server/runevents.go +++ b/internal/server/runevents.go @@ -1,6 +1,7 @@ package server import ( + "log" "sync" "time" @@ -90,6 +91,11 @@ type runSubscription struct { mu sync.Mutex snapshotting bool pending []protocol.Message + + // overflowed is closed once the subscriber fell too far behind: it is + // already detached, and its writer ends the stream with runs_resync. + overflowed chan struct{} + overOnce sync.Once } func newRunEventHub() *runEventHub { @@ -129,6 +135,7 @@ func (h *runEventHub) subscribe(clientID, workspace string, runIDs []int64, writ workspace: workspace, ch: make(chan protocol.Message, runEventSubscriberBuffer), done: make(chan struct{}), + overflowed: make(chan struct{}), write: write, snapshotting: true, } @@ -378,9 +385,19 @@ func (s *runSubscription) matches(workspace string, runID int64) bool { func (s *runSubscription) run() { for { + select { + case <-s.overflowed: + // The terminal frame: the frames still queued are discarded, so + // the client must subscribe again and re-read the runs. + _ = s.write(protocol.Message{Type: protocol.RunsResync}) + s.close() + return + default: + } select { case <-s.done: return + case <-s.overflowed: case msg := <-s.ch: if err := s.write(msg); err != nil { s.close() @@ -450,7 +467,7 @@ func (s *runSubscription) sendMessage(msg protocol.Message) { // the snapshot and the ack are written directly by the subscriber. if len(s.pending) >= runEventSubscriberBuffer { s.mu.Unlock() - s.close() + s.overflow() return } s.pending = append(s.pending, msg) @@ -461,12 +478,24 @@ func (s *runSubscription) sendMessage(msg protocol.Message) { select { case s.ch <- msg: default: - // The subscriber is not draining: drop it rather than block the - // producer. Its next subscribe re-syncs from a fresh snapshot. - s.close() + // The subscriber is not draining: detach it rather than block the + // producer. Its writer tells it to subscribe again for a fresh + // snapshot. + s.overflow() } } +// overflow detaches a subscriber that fell too far behind and lets its writer +// (started by ready, if the snapshot is still being written) end the stream +// with runs_resync. +func (s *runSubscription) overflow() { + s.overOnce.Do(func() { + close(s.overflowed) + log.Printf("run events: client %s fell %d frames behind; it is told to resync", s.clientID, runEventSubscriberBuffer) + s.hub.remove(s) + }) +} + // close unregisters the subscription and stops its writer goroutine exactly // once. It is safe to call from the writer goroutine, from unsubscribe and from // the disconnect path. diff --git a/internal/server/runevents_overflow_test.go b/internal/server/runevents_overflow_test.go new file mode 100644 index 00000000..2b65e2b8 --- /dev/null +++ b/internal/server/runevents_overflow_test.go @@ -0,0 +1,47 @@ +package server + +import ( + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A run subscriber that falls behind used to be dropped silently: the app's +// run list and open detail froze until the next reconnect. Now it is detached +// and its last frame is runs_resync, which makes the app subscribe again. +func TestRunSubscriptionOverflowEndsWithRunsResync(t *testing.T) { + h := newRunEventHub() + release := make(chan struct{}) + var mu sync.Mutex + var written []protocol.Message + sub := h.subscribe("conn", "", nil, func(msg protocol.Message) error { + <-release + mu.Lock() + written = append(written, msg) + mu.Unlock() + return nil + }) + sub.ready() + for i := range runEventSubscriberBuffer + 4 { + sub.send(protocol.RunEventFrame{RunID: int64(i + 1), Status: protocol.RunStatusRunning}) + } + h.mu.Lock() + _, attached := h.subs[sub] + h.mu.Unlock() + if attached { + t.Fatal("an overflowed run subscriber stayed attached") + } + close(release) + select { + case <-sub.done: + case <-time.After(5 * time.Second): + t.Fatal("the overflowed subscription never closed") + } + mu.Lock() + defer mu.Unlock() + if last := written[len(written)-1]; last.Type != protocol.RunsResync { + t.Fatalf("the overflowed client's last frame was %q, want %q", last.Type, protocol.RunsResync) + } +} diff --git a/internal/server/runner.go b/internal/server/runner.go index 8206e3ab..50e44374 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -152,7 +152,15 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot cancel() } if err != nil { - return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err) + // One session that cannot be confirmed stopped must not disable + // every run: interrupt only its run, saying why, and go on. + reason := fmt.Sprintf("its previous %s stage agent (session %s) could not be confirmed stopped (%v); check for a leftover agent process before reusing the workspace", owner.Backend, owner.ID, err) + if prior := reasons[owner.RunID]; prior != "" { + reason = prior + "; " + reason + } + reasons[owner.RunID] = reason + log.Printf("run %d: cannot interrupt previously active agent %s: %v; the run is marked interrupted", owner.RunID, owner.ID, err) + continue } if err := s.ConfirmRecoveredSession(ctx, owner); err != nil { return nil, err diff --git a/internal/stage/pi.go b/internal/stage/pi.go index 7f05b3e8..4adc94dd 100644 --- a/internal/stage/pi.go +++ b/internal/stage/pi.go @@ -608,7 +608,9 @@ func piResult(data []byte) (string, error) { } // InterruptPi expires the retained lease. The explicit extension aborts tools and -// marks quiescence before shutting down; without that receipt recovery fails closed. +// marks quiescence before shutting down. An owner whose process and process +// group are both gone (a crash, a reboot) has nothing left to stop, so it +// counts as interrupted without that receipt; otherwise recovery fails closed. func InterruptPi(ctx context.Context, reference string) error { if !filepath.IsAbs(reference) { return fmt.Errorf("invalid retained Pi reference") @@ -623,6 +625,12 @@ func InterruptPi(ctx context.Context, reference string) error { if json.Unmarshal(data, &owner) != nil || owner.PID <= 1 { return errors.Join(fmt.Errorf("invalid retained Pi owner"), ErrStageCleanup) } + gone := func() bool { + return errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) + } + if gone() { + return nil + } old := time.Unix(0, 0) if err := os.Chtimes(filepath.Join(reference, "lease"), old, old); err != nil { return err @@ -630,7 +638,9 @@ func InterruptPi(ctx context.Context, reference string) error { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { - if data, err := os.ReadFile(filepath.Join(reference, "quiescent")); err == nil && string(data) == "quiescent" && errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) { + // The receipt is written just before a clean exit; a process that + // died without it is still gone. + if gone() { return nil } select { diff --git a/internal/stage/pi_cleanup_test.go b/internal/stage/pi_cleanup_test.go index 9f22cc59..e9ec181d 100644 --- a/internal/stage/pi_cleanup_test.go +++ b/internal/stage/pi_cleanup_test.go @@ -42,3 +42,31 @@ func TestPiReceiptRequiresProcessExit(t *testing.T) { t.Fatal("confirmed process exit not accepted", err) } } + +// A Pi owner that crashed never wrote its quiescence receipt; with its process +// and process group gone there is nothing left to stop, so recovery must not +// wait out its timeout and fail. +func TestPiOwnerGoneWithoutReceiptCountsAsInterrupted(t *testing.T) { + cmd := exec.Command("sleep", "5") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + pid := cmd.Process.Pid + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + cmd.Wait() + dir := t.TempDir() + owner, _ := json.Marshal(map[string]any{"pid": pid}) + for name, data := range map[string][]byte{"owner.json": owner, "lease": []byte("lease")} { + if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := InterruptPi(ctx, dir); err != nil { + t.Fatal("a crashed owner was not accepted as gone:", err) + } +}