Merge branch 'main' into worktree-agent-a7c8c1a6937e97e84

Resolve chat_room.go: keep main's bounded chatSub queue (ready channel, no ch) in attachSub; the subscribe live-turn marker is still queued at attach under h.mu through enqueueChatLocked, and an existing subscriber whose queue is full is overflowed (resync) after the hub lock is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 01:11:11 +00:00
150 changed files with 7656 additions and 901 deletions
+276 -38
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
@@ -320,7 +477,6 @@ func (h *chatHub) attachSub(sessionID, clientID, label string, broker chatBroker
return nil, false
}
h.mu.Lock()
defer h.mu.Unlock()
room := h.roomLocked(sessionID)
if room.broker == nil {
room.broker = broker
@@ -336,21 +492,26 @@ func (h *chatHub) attachSub(sessionID, clientID, label string, broker chatBroker
room: room,
clientID: clientID,
label: label,
ch: make(chan protocol.Message, chatRoomSubscriberBuffer),
ready: make(chan struct{}, 1),
done: make(chan struct{}),
write: write,
}
room.subs[clientID] = sub
}
full := false
if replayTurn && (room.running || room.observedTurn || busy) {
// A fresh channel has room; an existing subscriber that cannot take
// it is already being dropped.
_ = enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
// A fresh queue always has room; an existing subscriber that cannot
// take it has fallen behind and is told to resync.
full = !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &protocol.ChatEventFrame{
SessionID: sessionID,
Kind: protocol.ChatEventStep,
Step: &protocol.ChatStep{Status: protocol.ChatStepStarted},
}})
}
h.mu.Unlock()
if full {
sub.overflow()
}
return sub, !ok
}
@@ -424,7 +585,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
@@ -557,7 +718,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) {
}
h.mu.Unlock()
for _, sub := range slow {
sub.close()
sub.overflow()
}
return
}
@@ -571,19 +732,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) {
@@ -602,7 +754,7 @@ func (h *chatHub) replayShells(sub *chatSub) {
}
h.mu.Unlock()
if slow {
sub.close()
sub.overflow()
}
}
@@ -689,7 +841,7 @@ func (h *chatHub) flushBuffered(sessionID string) {
}
h.mu.Unlock()
for _, sub := range slow {
sub.close()
sub.overflow()
}
}
@@ -934,10 +1086,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,