Chat and runs: tell a slow client to resync instead of dropping it silently; join queued deltas

A chat subscriber whose queue fills is detached and its writer ends the
stream with a resync frame (the app re-attaches and re-reads history); a run
subscriber gets a final runs_resync and the app subscribes again and
re-reads the Runs list and open detail. Consecutive text/reasoning deltas of
one part are joined in a chat subscriber's queue; joined numbered frames carry
seq_from and delta_lens so the app trims exactly the prefix a history page
already holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:39:38 +00:00
parent e649eced10
commit c316bc9bc8
20 changed files with 603 additions and 80 deletions
+13
View File
@@ -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<void> 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']) {
+1 -1
View File
@@ -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,
@@ -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'];
@@ -28,17 +28,21 @@ class ChatLiveFrames {
/// Stops recording for a read that will not be applied.
void abandon(List<JsonMap> 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 = <String, dynamic>{'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),
};
}
@@ -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<String, dynamic>;
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);
@@ -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<String, dynamic> 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<String, dynamic>.from(message as Map),
], replaced: (_) => true);
final parts = messages.single['parts'] as List;
expect((parts.single as Map)['text'], 'héllo wörld 😀!');
});
}
+10
View File
@@ -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
+7
View File
@@ -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.
+4
View File
@@ -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
+1 -1
View File
@@ -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)
+4 -4
View File
@@ -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()
}
}
}
+16 -16
View File
@@ -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)()
+5 -2
View File
@@ -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()
}
}
}
+1 -1
View File
@@ -388,7 +388,7 @@ func (h *chatHub) replayUsage(sub *chatSub) {
}
h.mu.Unlock()
if slow {
sub.close()
sub.overflow()
}
}
+180 -32
View File
@@ -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()
}
}
@@ -1012,7 +1160,7 @@ func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Dura
}
h.mu.Unlock()
for _, sub := range slow {
sub.close()
sub.overflow()
}
return true
}
+125
View File
@@ -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()
}
+1 -1
View File
@@ -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)
+7 -7
View File
@@ -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")
}
}
+33 -4
View File
@@ -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.
@@ -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)
}
}