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:
+180
-32
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user