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.
259 lines
8.5 KiB
Go
259 lines
8.5 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sync/atomic"
|
|
"testing"
|
|
"testing/synctest"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/stretchr/testify/require"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3/sloggers/slogtest"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/messagepartbuffer"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
"github.com/coder/coder/v2/testutil"
|
|
"github.com/coder/quartz"
|
|
)
|
|
|
|
type fakeDialError struct {
|
|
unrecoverable bool
|
|
}
|
|
|
|
func (fakeDialError) Error() string { return "fake dial error" }
|
|
func (e fakeDialError) IsUnrecoverable() bool { return e.unrecoverable }
|
|
|
|
func TestStreamPartsDialUnrecoverable(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
require.False(t, streamPartsDialUnrecoverable(nil))
|
|
require.False(t, streamPartsDialUnrecoverable(xerrors.New("plain error")))
|
|
require.False(t, streamPartsDialUnrecoverable(fakeDialError{unrecoverable: false}))
|
|
require.True(t, streamPartsDialUnrecoverable(fakeDialError{unrecoverable: true}))
|
|
require.True(t, streamPartsDialUnrecoverable(xerrors.Errorf("wrapped: %w", fakeDialError{unrecoverable: true})))
|
|
}
|
|
|
|
// TestStreamRelayForwarderDeliversPartsAfterStall stops reading relay.Parts()
|
|
// for longer than the send timeout on an open episode, then expects every part
|
|
// in order over the first connection.
|
|
func TestStreamRelayForwarderDeliversPartsAfterStall(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
synctest.Test(t, func(t *testing.T) {
|
|
// The pipe, session and relay part channels hold 128 parts each, fewer
|
|
// than episodeParts, so the buffer's send blocks.
|
|
const (
|
|
episodeParts = 1000
|
|
sendTimeout = 10 * time.Second
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
buffer := messagepartbuffer.New(messagepartbuffer.Options{
|
|
Clock: clock,
|
|
SubscriberSendTimeout: sendTimeout,
|
|
})
|
|
defer buffer.Close()
|
|
chatID := uuid.New()
|
|
key := messagepartbuffer.Key{ChatID: chatID, HistoryVersion: 1, GenerationAttempt: 1}
|
|
require.NoError(t, buffer.CreateEpisode(key))
|
|
for i := range episodeParts {
|
|
require.NoError(t, buffer.AddPart(key, codersdk.ChatMessageRoleAssistant, codersdk.ChatMessageText(fmt.Sprintf("part %d", i+1))))
|
|
}
|
|
|
|
logger := slogtest.Make(t, nil)
|
|
local := NewLocalStreamPartsDialer(LocalStreamPartsDialerConfig{Buffer: buffer, Logger: logger})
|
|
var dials atomic.Int32
|
|
dialer := func(ctx context.Context, input StreamPartsDialInput) (StreamPartsSession, error) {
|
|
dials.Add(1)
|
|
return local(ctx, input)
|
|
}
|
|
relay := newStreamRelayForwarder(chatID, nil, dialer, clock, logger)
|
|
defer relay.Close()
|
|
relay.Configure(ctx, streamRelayTarget{
|
|
workerID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
|
|
historyVersion: key.HistoryVersion,
|
|
generationAttempt: key.GenerationAttempt,
|
|
})
|
|
|
|
// drain reads until every goroutine blocks. A replay from seq 1 fails
|
|
// its order check.
|
|
var lastSeq int64
|
|
drain := func() {
|
|
for {
|
|
synctest.Wait()
|
|
select {
|
|
case part := <-relay.Parts():
|
|
require.Equal(t, lastSeq+1, part.Seq, "message part out of order")
|
|
lastSeq = part.Seq
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
synctest.Wait()
|
|
require.Equal(t, cap(relay.parts), len(relay.parts), "relay.parts did not fill")
|
|
clock.Advance(sendTimeout).MustWait(ctx)
|
|
drain()
|
|
require.NoError(t, buffer.AddPart(key, codersdk.ChatMessageRoleAssistant, codersdk.ChatMessageText("live")))
|
|
drain()
|
|
require.Equal(t, int64(episodeParts+1), lastSeq, "the live part did not reach relay.Parts()")
|
|
require.Equal(t, int32(1), dials.Load(), "the relay forwarder reconnected")
|
|
})
|
|
}
|
|
|
|
type selectCountingSession struct {
|
|
StreamPartsSession
|
|
selects *atomic.Int32
|
|
}
|
|
|
|
func (s selectCountingSession) SelectEpisode(ctx context.Context, historyVersion, generationAttempt int64) error {
|
|
s.selects.Add(1)
|
|
return s.StreamPartsSession.SelectEpisode(ctx, historyVersion, generationAttempt)
|
|
}
|
|
|
|
// TestStreamRelayForwarderSelectsOnlyChangedTargets configures the same
|
|
// target repeatedly and expects one selection and one copy of the episode,
|
|
// then one more selection when the target changes.
|
|
func TestStreamRelayForwarderSelectsOnlyChangedTargets(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
synctest.Test(t, func(t *testing.T) {
|
|
const (
|
|
episodeParts = 200
|
|
reconfigures = 10
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
buffer := messagepartbuffer.New(messagepartbuffer.Options{Clock: clock})
|
|
defer buffer.Close()
|
|
chatID := uuid.New()
|
|
workerID := uuid.NullUUID{UUID: uuid.New(), Valid: true}
|
|
createEpisode := func(historyVersion int64) streamRelayTarget {
|
|
key := messagepartbuffer.Key{ChatID: chatID, HistoryVersion: historyVersion, GenerationAttempt: 1}
|
|
require.NoError(t, buffer.CreateEpisode(key))
|
|
for i := range episodeParts {
|
|
require.NoError(t, buffer.AddPart(key, codersdk.ChatMessageRoleAssistant, codersdk.ChatMessageText(fmt.Sprintf("part %d", i+1))))
|
|
}
|
|
return streamRelayTarget{workerID: workerID, historyVersion: historyVersion, generationAttempt: 1}
|
|
}
|
|
|
|
logger := slogtest.Make(t, nil)
|
|
local := NewLocalStreamPartsDialer(LocalStreamPartsDialerConfig{Buffer: buffer, Logger: logger})
|
|
var selects atomic.Int32
|
|
dialer := func(ctx context.Context, input StreamPartsDialInput) (StreamPartsSession, error) {
|
|
session, err := local(ctx, input)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return selectCountingSession{StreamPartsSession: session, selects: &selects}, nil
|
|
}
|
|
relay := newStreamRelayForwarder(chatID, nil, dialer, clock, logger)
|
|
defer relay.Close()
|
|
|
|
// received reads relay.Parts() until every goroutine blocks.
|
|
received := func() int {
|
|
n := 0
|
|
for {
|
|
synctest.Wait()
|
|
select {
|
|
case <-relay.Parts():
|
|
n++
|
|
default:
|
|
return n
|
|
}
|
|
}
|
|
}
|
|
|
|
target := createEpisode(1)
|
|
parts := 0
|
|
for range reconfigures {
|
|
relay.Configure(ctx, target)
|
|
parts += received()
|
|
}
|
|
require.Equal(t, int32(1), selects.Load())
|
|
require.Equal(t, episodeParts, parts)
|
|
|
|
relay.Configure(ctx, createEpisode(2))
|
|
require.Equal(t, episodeParts, received())
|
|
require.Equal(t, int32(2), selects.Load())
|
|
})
|
|
}
|
|
|
|
// TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures
|
|
// stalls the stream loop until the buffers between the parts endpoint and
|
|
// relay.Parts() are full, configures the same episode many times while it
|
|
// reads at most one part each time, then resumes reading and expects a new
|
|
// part of the episode to arrive.
|
|
func TestStreamRelayForwarderDeliversLivePartsAfterSameEpisodeReconfigures(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
synctest.Test(t, func(t *testing.T) {
|
|
const (
|
|
// The pipe, session and relay part channels hold 128 parts
|
|
// each, fewer than episodeParts.
|
|
episodeParts = 1000
|
|
reconfigures = 1000
|
|
)
|
|
ctx := testutil.Context(t, testutil.WaitLong)
|
|
clock := quartz.NewMock(t).WithLogger(quartz.NoOpLogger)
|
|
buffer := messagepartbuffer.New(messagepartbuffer.Options{Clock: clock})
|
|
defer buffer.Close()
|
|
chatID := uuid.New()
|
|
key := messagepartbuffer.Key{ChatID: chatID, HistoryVersion: 1, GenerationAttempt: 1}
|
|
require.NoError(t, buffer.CreateEpisode(key))
|
|
for i := range episodeParts {
|
|
require.NoError(t, buffer.AddPart(key, codersdk.ChatMessageRoleAssistant, codersdk.ChatMessageText(fmt.Sprintf("part %d", i+1))))
|
|
}
|
|
|
|
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true})
|
|
dialer := NewLocalStreamPartsDialer(LocalStreamPartsDialerConfig{Buffer: buffer, Logger: logger})
|
|
relay := newStreamRelayForwarder(chatID, nil, dialer, clock, logger)
|
|
defer relay.Close()
|
|
target := streamRelayTarget{
|
|
workerID: uuid.NullUUID{UUID: uuid.New(), Valid: true},
|
|
historyVersion: key.HistoryVersion,
|
|
generationAttempt: key.GenerationAttempt,
|
|
}
|
|
relay.Configure(ctx, target)
|
|
synctest.Wait()
|
|
require.Equal(t, cap(relay.parts), len(relay.parts), "relay.parts did not fill")
|
|
|
|
// readOne lets the forwarder run once, so it can take the pending
|
|
// configuration.
|
|
readOne := func() {
|
|
select {
|
|
case <-relay.Parts():
|
|
default:
|
|
}
|
|
synctest.Wait()
|
|
}
|
|
for range reconfigures {
|
|
relay.Configure(ctx, target)
|
|
readOne()
|
|
}
|
|
|
|
// Read until every goroutine blocks, then add a live part and read
|
|
// again.
|
|
var lastSeq int64
|
|
drain := func() {
|
|
for {
|
|
synctest.Wait()
|
|
select {
|
|
case part := <-relay.Parts():
|
|
lastSeq = part.Seq
|
|
default:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
drain()
|
|
require.NoError(t, buffer.AddPart(key, codersdk.ChatMessageRoleAssistant, codersdk.ChatMessageText("live")))
|
|
drain()
|
|
require.Equal(t, int64(episodeParts+1), lastSeq, "the live part did not reach relay.Parts()")
|
|
})
|
|
}
|