fix(mcp): stop the progress watchdog cutting idle MCP event streams (#14)

MCP GET event streams (the server-to-client channel) now run without the progress watchdog and are ended by the client, the upstream or Gateway.DrainIdleStreams.
The standalone binary drains them on shutdown and when a config reload retires a gateway, so they do not hold either open.
This commit is contained in:
2026-11-26 20:20:43 +00:00
committed by GitHub
parent e667b6ec69
commit 04600a7bc9
10 changed files with 300 additions and 11 deletions
+8 -1
View File
@@ -1958,7 +1958,14 @@ Every provider adapter call and every native passthrough
aborted once this gateway observes no upstream read progress for the
configured duration, never simply because elapsed time crossed a fixed
deadline. The MCP/A2A target proxy (`/mcp/{name}/...`, `/a2a/{name}/...`)
shares the identical mechanism. The federated `/mcp` endpoint
shares the identical mechanism, with one exception: an MCP `GET` answered
with `text/event-stream` is the server-to-client message channel, which
stays silent until the server has something to send, so it runs without
the watchdog. It ends when the client disconnects or the server closes it.
The standalone binary also ends these streams when it shuts down or a
config reload replaces the gateway, so their clients reconnect elsewhere;
without that, one idle stream would hold a shutdown for its whole timeout.
The federated `/mcp` endpoint
(`mcp_federation.go`) does **not** — see the "Federated MCP" note below.
**Behavior change for every deployment, not an invisible bug fix.** Before
+5
View File
@@ -307,6 +307,11 @@ func run() error {
MaxHeaderBytes: defaultMaxHeaderBytes,
}
// Shutdown waits for open handlers, and an idle MCP event stream never
// ends by itself; ending those once the listener closes lets their
// clients reconnect to another replica.
srv.RegisterOnShutdown(sw.drainIdleStreams)
ready.Store(true)
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
+19
View File
@@ -51,6 +51,9 @@ func (g *generation) retire(maxWait time.Duration) {
if !g.markRetired() {
return
}
// Idle MCP event streams have no end of their own; ending them lets their
// clients reconnect to the new generation and this one close.
drainIdleStreams(g.h)
g.timer.Store(time.AfterFunc(maxWait, g.shut))
// A shut that ran before the Store could not stop the timer, so stop it here.
if g.shutDone.Load() {
@@ -113,6 +116,22 @@ func (s *swapHandler) swap(next *generation, drain time.Duration) {
s.cur.Swap(next).retire(drain)
}
// drainIdleStreams ends the serving gateway's idle MCP event streams. run
// calls it when the server shuts down, so those streams do not hold the
// shutdown for its whole timeout.
func (s *swapHandler) drainIdleStreams() {
if g := s.cur.Load(); g != nil {
drainIdleStreams(g.h)
}
}
// drainIdleStreams calls DrainIdleStreams when h is a gateway that has it.
func drainIdleStreams(h http.Handler) {
if d, ok := h.(interface{ DrainIdleStreams() }); ok {
d.DrainIdleStreams()
}
}
// closeCurrent closes the serving generation and turns away any request that arrives later.
// Call it only after the server stopped serving.
func (s *swapHandler) closeCurrent() {
+28
View File
@@ -372,3 +372,31 @@ func TestGatewayBuilderRejectsUnknownField(t *testing.T) {
}
var _ http.Handler = (*traefikllmgateway.Gateway)(nil)
// drainCounter is a gateway stand-in that counts DrainIdleStreams calls.
type drainCounter struct {
http.Handler
drains atomic.Int32
}
func (d *drainCounter) DrainIdleStreams() { d.drains.Add(1) }
func TestIdleStreamsDrainedOnRetireAndShutdown(t *testing.T) {
old := &drainCounter{Handler: okHandler()}
sw := &swapHandler{}
sw.cur.Store(newGeneration(old, func() {}))
g := sw.cur.Load()
g.enter() // a request is still running, so the close waits for it
sw.swap(newGeneration(okHandler(), func() {}), time.Hour)
if old.drains.Load() != 1 {
t.Errorf("retired gateway drains = %d, want 1: its idle MCP streams would hold it open", old.drains.Load())
}
g.leave()
cur := &drainCounter{Handler: okHandler()}
sw.cur.Store(newGeneration(cur, func() {}))
sw.drainIdleStreams()
if cur.drains.Load() != 1 {
t.Errorf("serving gateway drains = %d, want 1 on shutdown", cur.drains.Load())
}
}
+72
View File
@@ -0,0 +1,72 @@
package traefikllmgateway
import (
"context"
"sync"
)
// idleStreamSet tracks MCP server-to-client event streams. They may stay
// idle indefinitely, so they run without the progress watchdog, and a host
// that stops or swaps this gateway must end them explicitly. Methods are
// safe on a nil set, which tracks nothing.
type idleStreamSet struct {
cancels map[int64]context.CancelFunc
mu sync.Mutex
next int64
draining bool
}
func newIdleStreamSet() *idleStreamSet {
return &idleStreamSet{cancels: make(map[int64]context.CancelFunc)}
}
// add registers cancel and returns its id. It returns false when the set is
// draining; the caller then ends the stream at once.
func (s *idleStreamSet) add(cancel context.CancelFunc) (int64, bool) {
if s == nil {
return 0, true
}
s.mu.Lock()
defer s.mu.Unlock()
if s.draining {
return 0, false
}
s.next++
s.cancels[s.next] = cancel
return s.next, true
}
func (s *idleStreamSet) remove(id int64) {
if s == nil {
return
}
s.mu.Lock()
delete(s.cancels, id)
s.mu.Unlock()
}
// drain ends every tracked stream and every stream added afterwards.
func (s *idleStreamSet) drain() {
if s == nil {
return
}
s.mu.Lock()
s.draining = true
cancels := make([]context.CancelFunc, 0, len(s.cancels))
for id, cancel := range s.cancels {
cancels = append(cancels, cancel)
delete(s.cancels, id)
}
s.mu.Unlock()
for _, cancel := range cancels {
cancel()
}
}
// DrainIdleStreams ends the MCP server-to-client event streams this gateway
// serves, and any opened afterwards, so their clients reconnect elsewhere.
// The standalone binary calls it when its server shuts down or a config
// reload retires this gateway; those streams have no watchdog to end them.
func (g *Gateway) DrainIdleStreams() {
g.idleStreams.drain()
}
+135
View File
@@ -0,0 +1,135 @@
package traefikllmgateway
import (
"bufio"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// idleSSEUpstream answers every request with one event, an idle gap longer
// than the gateway's watchdog, then a second event.
func idleSSEUpstream(t *testing.T, gap time.Duration) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fl := w.(http.Flusher)
_, _ = w.Write([]byte("event: message\ndata: first\n\n"))
fl.Flush()
select {
case <-time.After(gap):
case <-r.Context().Done():
return
}
_, _ = w.Write([]byte("event: message\ndata: second\n\n"))
fl.Flush()
}))
t.Cleanup(srv.Close)
return srv
}
// newIdleStreamGateway builds a gateway with a 100ms target watchdog and one MCP target.
func newIdleStreamGateway(t *testing.T, targetURL string) *Gateway {
t.Helper()
cfg := CreateConfig()
cfg.RequestTimeout = "100ms"
cfg.Providers = map[string]*ProviderConfig{"p1": {Type: "openai", APIKey: "k", BaseURL: "http://127.0.0.1:1", Models: []string{"m"}}}
cfg.MCPServers = map[string]*TargetConfig{"notes": {URL: targetURL}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice"}}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
return h.(*Gateway)
}
// streamData serves one request through gw on a real listener and returns the data lines the client received.
func streamData(t *testing.T, gw *Gateway, method string, during func()) []string {
t.Helper()
front := httptest.NewServer(gw)
t.Cleanup(front.Close)
var body *strings.Reader
if method == http.MethodPost {
body = strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"ping"}`)
} else {
body = strings.NewReader("")
}
req, err := http.NewRequest(method, front.URL+"/mcp/notes", body)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Accept", "text/event-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request: %v", err)
}
defer resp.Body.Close()
var got []string
sc := bufio.NewScanner(resp.Body)
for sc.Scan() {
if line := sc.Text(); strings.HasPrefix(line, "data: ") {
got = append(got, strings.TrimPrefix(line, "data: "))
if len(got) == 1 && during != nil {
during()
}
}
}
return got
}
func TestTargetProxy_IdleStreamWatchdog(t *testing.T) {
tests := []struct {
name string
method string
want []string
}{
// An MCP GET event stream is the server-to-client channel and may idle for any time.
{"mcp GET event stream outlives the watchdog", http.MethodGet, []string{"first", "second"}},
// A POST response stream is a tool call in progress; a stall must still be cut.
{"mcp POST event stream keeps the watchdog", http.MethodPost, []string{"first"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gw := newIdleStreamGateway(t, idleSSEUpstream(t, 400*time.Millisecond).URL)
got := streamData(t, gw, tt.method, nil)
if strings.Join(got, ",") != strings.Join(tt.want, ",") {
t.Errorf("received %v, want %v", got, tt.want)
}
})
}
}
func TestDrainIdleStreams(t *testing.T) {
gw := newIdleStreamGateway(t, idleSSEUpstream(t, 30*time.Second).URL)
start := time.Now()
got := streamData(t, gw, http.MethodGet, gw.DrainIdleStreams)
if len(got) != 1 || got[0] != "first" {
t.Errorf("received %v, want only the event sent before the drain", got)
}
if d := time.Since(start); d > 5*time.Second {
t.Errorf("drained stream took %v to end, want it ended promptly", d)
}
// A stream opened after the drain ends at once instead of idling.
start = time.Now()
got = streamData(t, gw, http.MethodGet, nil)
if len(got) > 1 {
t.Errorf("stream opened after the drain received %v, want at most the first event", got)
}
if d := time.Since(start); d > 5*time.Second {
t.Errorf("stream opened after the drain took %v, want it ended at once", d)
}
}
func TestIdleStreamSetNilSafe(t *testing.T) {
var s *idleStreamSet
if _, ok := s.add(func() {}); !ok {
t.Error("nil set refused a stream")
}
s.remove(1)
s.drain()
}
+2 -1
View File
@@ -852,6 +852,7 @@ const maxExplicitBodyAdmissionCap = 10_000
type Gateway struct {
next http.Handler
events *eventLog
idleStreams *idleStreamSet
bodyAdmission chan struct{}
unifiedRequestBytes int64
teeBudget *teeBudget
@@ -1035,7 +1036,7 @@ func newGateway(ctx context.Context, next http.Handler, config *Config, name str
if err != nil {
return nil, err
}
g := &Gateway{next: next, name: name, cfg: config, auth: auth}
g := &Gateway{next: next, name: name, cfg: config, auth: auth, idleStreams: newIdleStreamSet()}
// replica/collectingWarnings (F4/F9/F10, v0.3 dashboard task): resolved
// immediately, before anything below can call warnf — every warnf
// call from here to this function's return is a construction-time
+1 -1
View File
@@ -243,7 +243,7 @@ func (g *Gateway) handleTargetProxy(w http.ResponseWriter, r *http.Request, u *u
// recordTargetProxyHealth's own doc comment for the exact
// success/failure rule.
start := time.Now()
result, ok := g.proxyUpstream(w, r, upstreamURL, g.targetClient, nil, nil, false, kind+" target (name "+name+")", g.targetTimeout)
result, ok := g.proxyUpstream(w, r, upstreamURL, g.targetClient, nil, nil, false, kind+" target (name "+name+")", g.targetTimeout, kind == targetKindMCP)
g.recordTargetProxyHealth(kind, name, targetURL, result, ok, time.Since(start))
g.recordProxyEvent(scopes, name, kind, result) // F3 hook 3 (v0.3 dashboard task)
}
+14 -2
View File
@@ -1356,7 +1356,7 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
}))
}
result, complete := g.proxyUpstream(w, r, upstreamURL, adapter.httpClient(), adapter.injectAuth, providerCredentialRetargetHeaders, true, "passthrough (provider "+providerName+")", adapter.requestTimeout())
result, complete := g.proxyUpstream(w, r, upstreamURL, adapter.httpClient(), adapter.injectAuth, providerCredentialRetargetHeaders, true, "passthrough (provider "+providerName+")", adapter.requestTimeout(), false)
defer result.tee.release()
g.recordProxyEvent(scopes, providerName, routePassthrough, result) // F3 hook 3 (v0.3 dashboard task)
@@ -1669,7 +1669,7 @@ func (c *cappedBodyReader) bytesRead() int64 {
// request instead of completing it against a silently truncated prefix
// (a multipart audio upload over the cap previously still parsed a
// valid, truncated body and got transcribed with no error at all).
func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstreamURL string, client *http.Client, injectAuth func(*http.Request), extraStrip map[string]bool, accountJSON bool, logPrefix string, timeout time.Duration) (result proxyResult, ok bool) {
func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstreamURL string, client *http.Client, injectAuth func(*http.Request), extraStrip map[string]bool, accountJSON bool, logPrefix string, timeout time.Duration, idleEventStreams bool) (result proxyResult, ok bool) {
if r.ContentLength > maxPassthroughBytes {
writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request body exceeds the maximum allowed size")
return proxyResult{}, false
@@ -1787,6 +1787,18 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
// (name ...)" — an MCP/A2A target is not a provider, and the watchdog
// error text must not claim it is (finding F9).
wb := newWatchdogBody(resp.Body, cancel, timeout, logPrefix, rec)
// An MCP server-to-client stream (a GET answered with text/event-stream) is
// silent until the server has something to send, so the progress watchdog
// would cut it. It runs unwatched and is ended by the client, the upstream,
// or DrainIdleStreams.
if idleEventStreams && r.Method == http.MethodGet && isEventStreamResponse(resp) {
wb.disarm()
id, tracked := g.idleStreams.add(cancel)
if !tracked {
cancel()
}
defer g.idleStreams.remove(id)
}
if latRec != nil {
wb.armLatency(start, isEventStreamResponse(resp), latRec)
}
+16 -6
View File
@@ -181,6 +181,8 @@ type watchdogBody struct {
timedOut int32
ttfbRecorded int32
latencyRecorded int32
// idle is set by disarm: the stream may stay silent indefinitely, so no read re-arms the timer.
idle int32
// done is set once Read observes a clean io.EOF (finding 11 fix,
// review-routes.md) — see Read's own doc comment for why the timer
// must be stopped THERE, not left armed until Close eventually calls
@@ -189,11 +191,11 @@ type watchdogBody struct {
// time.AfterFunc goroutine already started) still cannot record a
// spurious failure for an upstream that, in fact, just finished
// cleanly.
done int32
streaming bool
done int32
// sse feeds the first-byte guard for a stream, where a keep-alive comment is not a first byte.
sse sseDataDetector
fbDone bool
sse sseDataDetector
streaming bool
fbDone bool
}
// newWatchdogBody returns a watchdogBody wrapping rc, arming its watchdog
@@ -283,7 +285,7 @@ func (wb *watchdogBody) fire() {
// timer cannot be retracted once its goroutine has started, only
// prevented from starting via Stop) must not record a spurious
// provider failure for an upstream that, in fact, finished cleanly.
if atomic.LoadInt32(&wb.done) == 1 {
if atomic.LoadInt32(&wb.done) == 1 || atomic.LoadInt32(&wb.idle) == 1 {
return
}
atomic.StoreInt32(&wb.timedOut, 1)
@@ -376,12 +378,20 @@ func (wb *watchdogBody) Read(p []byte) (int, error) {
}
return n, err
}
if n > 0 {
if n > 0 && atomic.LoadInt32(&wb.idle) == 0 {
wb.timer.Reset(wb.timeout)
}
return n, nil
}
// disarm stops the progress watchdog for a stream that may legitimately stay
// idle, such as an MCP server-to-client event stream. The request context and
// Close still end it.
func (wb *watchdogBody) disarm() {
atomic.StoreInt32(&wb.idle, 1)
wb.timer.Stop()
}
// Close stops the watchdog timer (a harmless no-op if it already fired)
// and always calls cancel, so the derived request context this
// watchdogBody's cancel belongs to is released promptly — whether Close