Stacked on #31196, which must merge first. When a chat's worker runs on the same replica as the stream, the chat stream relay can deadlock with the in-process parts endpoint. Live model output then stops on that stream until the client reconnects, while saved messages, status and queue updates keep arriving. The stream loop configures the relay forwarder after every newer snapshot, and queueing a message, deleting or promoting a queued one, interrupting, and recording a retry keep the episode. The forwarder sent a selection each time, and the endpoint answers each one by sending the episode again from `seq` 1, so K updates on an N-part episode moved about K times N parts. While the stream loop reads slowly, the resent parts fill the buffers and the endpoint's serve loop waits to send. Three unread selections fill the pipe's one-slot channel, the endpoint's selection reader and its one-slot channel to the serve loop, and the forwarder's next `WriteControl` never returns. - The forwarder sends a selection only on a new connection or when the target changes. Before #31196, only a repeated selection restarted live output after the part buffer dropped a slow subscriber. - The endpoint's selection reader replaces an unread selection instead of waiting, so the endpoint does not depend on how a client sends selections. After the first change the forwarder cannot practically reach the cycle, since it drops other episodes' parts without waiting. Dropping one loses nothing, because every selection starts again from `seq` 1. <details> <summary>Investigation and decision log</summary> ### Evidence `TestStreamRelayForwarderSelectsOnlyChangedTargets` configures one 200-part episode 10 times: before the forwarder change it sees 10 selections and 2000 parts, after it 1 selection and 200 parts. `TestStreamPartsEndpointLatestSelectionWinsWhileBlocked` fails in 10 of 10 runs without the reader change and with a 15-slot queue that replaces nothing. `TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures` stalls the stream loop until the buffers fill, configures the same episode 1000 times, then requires a new part to arrive; it fails in 20 of 20 runs with both changes reverted and passes with either one alone. All three pass with `-race -count=20`. A goroutine dump taken with the world stopped, from a test that used the real forwarder, local dialer and part buffer with a 2000-part episode, shows the four goroutines at the waits described above and every buffer full. The deadlock formed in 20 of 20 runs under `-race`, after 4 to 384 same-episode selections. After the test read every buffered part, added live parts, configured the relay 11 more times (once for a new episode) and fired the buffer's send timeout, no part arrived. ``` F goroutine 73 [select]: streamPartsChannelClientTransport.WriteControl stream_parts_transport.go:142 <- (*streamRelayForwarder).loop.func4 stream_relay.go:148 <- loop stream_relay.go:207 R goroutine 74 [select]: streamPartsEndpoint.serve.func1() stream_parts.go:84 E goroutine 83 [select]: streamPartsChannelServerTransport.WriteEvents stream_parts_transport.go:120 <- streamPartsEndpoint.serve stream_parts.go:169 L goroutine 84 [select]: (*streamPartsTransportSession).readLoop stream_parts_transport.go:236 f.parts=128/128 s.parts=128/128 eventsCh=128/128 controlCh=1/1 SelectEpisode started=13 returned=12 ``` A test goroutine in place of the stream loop dropped repeated parts and spent a fixed sync time on each hint before it selected the same episode again (200 hints, 3 runs per row, real clock): | Sync time per hint | Hint interval | Deadlock formed | |--------------------|---------------|-----------------| | 1 ms | 1 ms | 1 of 3 | | 5 ms | 5 ms | 1 of 3 | | 1 ms | 2 ms or 5 ms | 0 of 6 | | 5 ms | 10 ms | 0 of 3 | The deadlock formed only when selections arrived about as fast as the stream loop handled them. How often that happens in production is not measured. Selecting a new episode every time under the same pressure did not deadlock in 300 of 300 iterations, because the forwarder drops parts of other episodes without waiting for the stream loop. Over the WebSocket transport with the pipeline full, 1263 selections over 2999 iterations all returned; when the stream loop then stopped reading, the server heartbeat closed the parts connection about 35 seconds after it opened, and the forwarder dialed again once the stream loop read again. ### Decisions - `WriteControl` keeps its waiting send: the reader no longer waits after reading the pipe, so the send returns, and replacing there changed no test result. - Replaced `TestStreamRelayLivePartsAfterSameEpisodeReselects`, which waited for full buffers before every selection and so relied on the replays the forwarder change removes, with a test that fills the buffers once by stalling the stream loop. - Rejected: having the serve loop read selections while it waits in `WriteEvents`. The serve loop would have to abandon a send in progress and drop its part, a larger change with the same result. </details> > 🤖 This PR was created with the help of Coder Agents.
254 lines
6.1 KiB
Go
254 lines
6.1 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/quartz"
|
|
)
|
|
|
|
const (
|
|
streamRelayRetryInitialBackoff = 100 * time.Millisecond
|
|
streamRelayRetryMaxBackoff = 5 * time.Second
|
|
)
|
|
|
|
type streamRelayForwarder struct {
|
|
chatID uuid.UUID
|
|
requestHeader http.Header
|
|
dialer StreamPartsDialer
|
|
clock quartz.Clock
|
|
logger slog.Logger
|
|
|
|
parts chan StreamPart
|
|
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
done chan struct{}
|
|
|
|
configure chan streamRelayTarget
|
|
closeOnce sync.Once
|
|
}
|
|
|
|
func newStreamRelayForwarder(
|
|
chatID uuid.UUID,
|
|
requestHeader http.Header,
|
|
dialer StreamPartsDialer,
|
|
clock quartz.Clock,
|
|
logger slog.Logger,
|
|
) *streamRelayForwarder {
|
|
if clock == nil {
|
|
clock = quartz.NewReal()
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
f := &streamRelayForwarder{
|
|
chatID: chatID,
|
|
requestHeader: cloneHeader(requestHeader),
|
|
dialer: dialer,
|
|
clock: clock,
|
|
logger: logger,
|
|
parts: make(chan StreamPart, 128),
|
|
ctx: ctx,
|
|
cancel: cancel,
|
|
done: make(chan struct{}),
|
|
configure: make(chan streamRelayTarget, 1),
|
|
}
|
|
go f.loop()
|
|
return f
|
|
}
|
|
|
|
func (f *streamRelayForwarder) Parts() <-chan StreamPart {
|
|
return f.parts
|
|
}
|
|
|
|
func (f *streamRelayForwarder) Configure(ctx context.Context, target streamRelayTarget) {
|
|
if f == nil {
|
|
return
|
|
}
|
|
// Drop any pending target so the buffered channel always holds the most
|
|
// recent configuration.
|
|
select {
|
|
case <-f.configure:
|
|
default:
|
|
}
|
|
select {
|
|
case f.configure <- target:
|
|
case <-f.ctx.Done():
|
|
case <-ctx.Done():
|
|
}
|
|
}
|
|
|
|
func (f *streamRelayForwarder) Close() {
|
|
if f == nil {
|
|
return
|
|
}
|
|
f.closeOnce.Do(func() {
|
|
f.cancel()
|
|
<-f.done
|
|
})
|
|
}
|
|
|
|
func (f *streamRelayForwarder) loop() {
|
|
defer close(f.done)
|
|
defer close(f.parts)
|
|
var (
|
|
target streamRelayTarget
|
|
connected streamRelayTarget
|
|
session StreamPartsSession
|
|
sessionParts <-chan StreamPart
|
|
retryTimer *quartz.Timer
|
|
retryC <-chan time.Time
|
|
retryBackoff = streamRelayRetryInitialBackoff
|
|
)
|
|
stopRetry := func() {
|
|
if retryTimer != nil {
|
|
retryTimer.Stop()
|
|
retryTimer = nil
|
|
retryC = nil
|
|
}
|
|
}
|
|
defer stopRetry()
|
|
closeSession := func() {
|
|
if session != nil {
|
|
_ = session.Close()
|
|
}
|
|
session = nil
|
|
sessionParts = nil
|
|
connected = streamRelayTarget{}
|
|
}
|
|
defer closeSession()
|
|
scheduleRetry := func() {
|
|
if !target.needsRelay() || f.dialer == nil || retryTimer != nil {
|
|
return
|
|
}
|
|
retryTimer = f.clock.NewTimer(retryBackoff, "chatd", "stream-relay-retry")
|
|
retryC = retryTimer.C
|
|
if retryBackoff < streamRelayRetryMaxBackoff {
|
|
retryBackoff *= 2
|
|
if retryBackoff > streamRelayRetryMaxBackoff {
|
|
retryBackoff = streamRelayRetryMaxBackoff
|
|
}
|
|
}
|
|
}
|
|
connect := func(ctx context.Context) {
|
|
stopRetry()
|
|
if !target.needsRelay() {
|
|
closeSession()
|
|
return
|
|
}
|
|
if f.dialer == nil {
|
|
return
|
|
}
|
|
if session != nil && connected.workerID.Valid && sameNullUUID(connected.workerID, target.workerID) {
|
|
// runStreamSync configures after every newer snapshot; a selection resends
|
|
// from seq 1. Skipping relies on messagepartbuffer keeping open-episode subscribers.
|
|
if connected.sameEpisode(target) {
|
|
return
|
|
}
|
|
if err := session.SelectEpisode(ctx, target.historyVersion, target.generationAttempt); err != nil {
|
|
f.logger.Warn(ctx, "failed to select stream parts episode",
|
|
slog.F("chat_id", f.chatID),
|
|
slog.F("history_version", target.historyVersion),
|
|
slog.F("generation_attempt", target.generationAttempt),
|
|
slog.Error(err),
|
|
)
|
|
closeSession()
|
|
scheduleRetry()
|
|
return
|
|
}
|
|
connected = target
|
|
retryBackoff = streamRelayRetryInitialBackoff
|
|
return
|
|
}
|
|
closeSession()
|
|
newSession, err := f.dialer(ctx, StreamPartsDialInput{
|
|
ChatID: f.chatID,
|
|
WorkerID: target.workerID.UUID,
|
|
RequestHeader: cloneHeader(f.requestHeader),
|
|
})
|
|
if err != nil {
|
|
f.logger.Warn(ctx, "failed to dial stream parts relay",
|
|
slog.F("chat_id", f.chatID),
|
|
slog.F("worker_id", target.workerID.UUID),
|
|
slog.Error(err),
|
|
)
|
|
// Unrecoverable dial errors (e.g. auth failures) will not
|
|
// succeed on retry with the same inputs, so wait for the next
|
|
// configuration instead of scheduling a retry.
|
|
if !streamPartsDialUnrecoverable(err) {
|
|
scheduleRetry()
|
|
}
|
|
return
|
|
}
|
|
session = newSession
|
|
sessionParts = newSession.Parts()
|
|
connected = streamRelayTarget{workerID: target.workerID}
|
|
if err := session.SelectEpisode(ctx, target.historyVersion, target.generationAttempt); err != nil {
|
|
f.logger.Warn(ctx, "failed to select stream parts episode",
|
|
slog.F("chat_id", f.chatID),
|
|
slog.F("history_version", target.historyVersion),
|
|
slog.F("generation_attempt", target.generationAttempt),
|
|
slog.Error(err),
|
|
)
|
|
closeSession()
|
|
scheduleRetry()
|
|
return
|
|
}
|
|
connected = target
|
|
retryBackoff = streamRelayRetryInitialBackoff
|
|
}
|
|
|
|
for {
|
|
select {
|
|
case <-f.ctx.Done():
|
|
return
|
|
case nextTarget := <-f.configure:
|
|
target = nextTarget
|
|
connect(f.ctx)
|
|
case <-retryC:
|
|
retryTimer = nil
|
|
retryC = nil
|
|
connect(f.ctx)
|
|
case part, ok := <-sessionParts:
|
|
if !ok {
|
|
closeSession()
|
|
scheduleRetry()
|
|
continue
|
|
}
|
|
if !connected.sameEpisode(target) ||
|
|
part.HistoryVersion != target.historyVersion ||
|
|
part.GenerationAttempt != target.generationAttempt {
|
|
continue
|
|
}
|
|
select {
|
|
case f.parts <- part:
|
|
case <-f.ctx.Done():
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (t streamRelayTarget) needsRelay() bool {
|
|
return t.workerID.Valid && t.generationAttempt > 0
|
|
}
|
|
|
|
// streamPartsDialUnrecoverable reports whether a dial error signals that
|
|
// retrying with the same inputs is futile, such as an auth failure. Dialers
|
|
// opt in by returning errors that implement IsUnrecoverable.
|
|
func streamPartsDialUnrecoverable(err error) bool {
|
|
var unrecoverable interface{ IsUnrecoverable() bool }
|
|
return errors.As(err, &unrecoverable) && unrecoverable.IsUnrecoverable()
|
|
}
|
|
|
|
func (t streamRelayTarget) sameEpisode(other streamRelayTarget) bool {
|
|
return sameNullUUID(t.workerID, other.workerID) &&
|
|
t.historyVersion == other.historyVersion &&
|
|
t.generationAttempt == other.generationAttempt
|
|
}
|