From bfc71b75180e7f0d196b18a7a2afb8322687cb6a Mon Sep 17 00:00:00 2001 From: gerarecipe Date: Wed, 18 Nov 2026 21:32:42 +0100 Subject: [PATCH] fix(gateway): bound reading an upstream error body in time and size doInferenceAttempt returned a non-2xx response at its headers. Its body was then read by classification (peekResponseBody), retry buffering (bufferRetryResponse) and the error copied to the client (copyErrorResponse), none with a deadline of their own. An upstream or exit that sends error headers and then stalls held the retry and fallback loop until the whole request budget was gone. Read at most 1 MiB of a non-2xx body inside doInferenceAttempt under an absolute 2 s limit (the attempt timer stays armed), close without draining, and hand the buffered bytes on with status and headers intact, so 403/429/5xx classification and retries are unchanged. /systemone keeps skipping the optional deadlines but gets the same bound. Retry buffering keeps the same cap instead of truncating at 64 KiB, and DrainAndClose no longer does an untimed speculative read before closing. Co-Authored-By: Claude Opus 5.5 --- internal/gateway/abuse.go | 13 ++++++++--- internal/gateway/first_event.go | 41 +++++++++++++++++++++++++++++---- internal/httpx/body.go | 11 +++++---- 3 files changed, 53 insertions(+), 12 deletions(-) diff --git a/internal/gateway/abuse.go b/internal/gateway/abuse.go index 3bd724ff..c5907653 100644 --- a/internal/gateway/abuse.go +++ b/internal/gateway/abuse.go @@ -94,15 +94,22 @@ func peekResponseBody(resp *http.Response) []byte { return prefix } -// bufferRetryResponse releases a response's transport before the next attempt, -// retaining at most 64 KiB of its body, including any prefix read before an error. +// bufferRetryResponse retains an error response across later attempts. +// doInferenceAttempt has already bounded and buffered non-2xx bodies under the +// error-body deadline, so this read is memory-only. Keep the same size cap: a +// second, smaller cap would truncate otherwise valid error JSON on a retry. func bufferRetryResponse(resp *http.Response) { if resp == nil || resp.Body == nil { return } - body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes)) _ = resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(body)) + resp.ContentLength = int64(len(body)) + resp.Header.Del("Content-Length") + resp.Header.Del("Transfer-Encoding") + resp.TransferEncoding = nil + resp.Trailer = nil } // replaceRetryResponse keeps the latest HTTP response across transport failures diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index ea1b57a4..c3217df8 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -199,6 +199,15 @@ func (b *attemptBody) Close() error { return b.body.Close() } +// Non-2xx bodies are buffered before classification or forwarding; see +// doInferenceAttempt. The time cap applies even when the optional attempt +// deadline is disabled; cancellation interrupts the transport read without a +// background reader. +const ( + maxErrorBodyBytes = 1 << 20 + errorBodyTimeout = 2 * time.Second +) + // doInferenceAttempt sends one upstream attempt through client under two // optional deadlines. It passes straight through to client.Do when both // timeouts are zero or negative, and for the /systemone path. @@ -221,8 +230,10 @@ func (b *attemptBody) Close() error { // errFirstEventTimeout as the error when that deadline caused the failure, and // closing the returned body also releases the attempt's context. func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeout, attemptTimeout time.Duration) (*http.Response, error) { - if (firstEventTimeout <= 0 && attemptTimeout <= 0) || strings.HasSuffix(req.URL.Path, "/systemone") { - return client.Do(req) + // /systemone skips the optional deadlines, but its error bodies are still + // bounded below like every other attempt's. + if strings.HasSuffix(req.URL.Path, "/systemone") { + firstEventTimeout, attemptTimeout = 0, 0 } trace := &attemptTrace{} ctx, cancel := context.WithCancelCause(req.Context()) @@ -273,8 +284,30 @@ func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeou cancel(nil) return resp, &phasedError{err: err, phase: trace.phase()} } - // Without a first-event wait the attempt is done once headers arrive. - if firstEventTimeout <= 0 || resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") { + if resp.StatusCode/100 != 2 { + // Error bodies are read by classification, retries and the error copied + // to the client, all after this function returns and without a deadline + // of their own: a peer that sends headers and then stalls would hold the + // retry loop until the request budget is gone. Read at most + // maxErrorBodyBytes here under an absolute errorBodyTimeout (not reset + // by a peer trickling bytes; the attempt timer also stays armed), then + // close without draining. Status, headers and whatever bytes arrived are + // kept, so 403/429/5xx classification and retries are unchanged. + bodyTimer := time.AfterFunc(errorBodyTimeout, func() { cancel(context.DeadlineExceeded) }) + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes)) + bodyTimer.Stop() + _ = resp.Body.Close() + cancel(nil) + resp.Body = io.NopCloser(bytes.NewReader(body)) + resp.ContentLength = int64(len(body)) + resp.Header.Del("Content-Length") + resp.Header.Del("Transfer-Encoding") + resp.TransferEncoding = nil + resp.Trailer = nil + return resp, nil + } + // Without a first-event wait a successful attempt commits at headers. + if firstEventTimeout <= 0 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") { if attemptTimer != nil { if cause := commitDeadline(); cause != nil { cancel(nil) diff --git a/internal/httpx/body.go b/internal/httpx/body.go index beebaa3c..ff16257e 100644 --- a/internal/httpx/body.go +++ b/internal/httpx/body.go @@ -4,14 +4,15 @@ import ( "io" ) -// DrainAndClose discards up to 64 KiB of body and closes it, so the -// connection can be reused. A nil body is ignored. The bound keeps a small -// response fully drained while a large or endless one cannot hold the caller -// for more than that amount of data. +// DrainAndClose closes body without speculative reads. A byte-limited drain +// is not time-limited: even one unread byte can stall the caller forever. +// Callers that want connection reuse must consume the body under their own +// deadline first; the regular and Bun transports already reuse a connection +// after a clean EOF. Closing an unread body only gives up reuse. The name is +// kept for existing callers. A nil body is ignored. func DrainAndClose(body io.ReadCloser) { if body == nil { return } - _, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10)) _ = body.Close() }