From 04600a7bc9f42e955a7118cec8f39c8b7a76a657 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 20:20:43 +0000 Subject: [PATCH] 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. --- README.md | 9 ++- cmd/gateway/main.go | 5 ++ cmd/gateway/reload.go | 19 ++++++ cmd/gateway/reload_test.go | 28 ++++++++ idle_streams.go | 72 ++++++++++++++++++++ idle_streams_test.go | 135 +++++++++++++++++++++++++++++++++++++ llmgateway.go | 3 +- mcp_a2a.go | 2 +- routes_passthrough.go | 16 ++++- timeout.go | 22 ++++-- 10 files changed, 300 insertions(+), 11 deletions(-) create mode 100644 idle_streams.go create mode 100644 idle_streams_test.go diff --git a/README.md b/README.md index de03d27..e163aae 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go index 8658bb1..1fe1362 100644 --- a/cmd/gateway/main.go +++ b/cmd/gateway/main.go @@ -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() }() diff --git a/cmd/gateway/reload.go b/cmd/gateway/reload.go index 2703a63..8650e26 100644 --- a/cmd/gateway/reload.go +++ b/cmd/gateway/reload.go @@ -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() { diff --git a/cmd/gateway/reload_test.go b/cmd/gateway/reload_test.go index ac752f6..a3b470f 100644 --- a/cmd/gateway/reload_test.go +++ b/cmd/gateway/reload_test.go @@ -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()) + } +} diff --git a/idle_streams.go b/idle_streams.go new file mode 100644 index 0000000..df6a611 --- /dev/null +++ b/idle_streams.go @@ -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() +} diff --git a/idle_streams_test.go b/idle_streams_test.go new file mode 100644 index 0000000..b52887e --- /dev/null +++ b/idle_streams_test.go @@ -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() +} diff --git a/llmgateway.go b/llmgateway.go index f095609..0ead12b 100644 --- a/llmgateway.go +++ b/llmgateway.go @@ -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 diff --git a/mcp_a2a.go b/mcp_a2a.go index b87e8ed..73dff22 100644 --- a/mcp_a2a.go +++ b/mcp_a2a.go @@ -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) } diff --git a/routes_passthrough.go b/routes_passthrough.go index 353413a..f2d6d59 100644 --- a/routes_passthrough.go +++ b/routes_passthrough.go @@ -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) } diff --git a/timeout.go b/timeout.go index e6481f8..97b1e48 100644 --- a/timeout.go +++ b/timeout.go @@ -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