fix: bound each upstream attempt by the full attempt deadline

performance.attempt_timeout_seconds only maps to
http.Transport.ResponseHeaderTimeout, which starts after the request
body is written and stops at the response headers. An exit that wedges
during dial or request-write hangs with no timer running and can consume
the entire request budget on its own; the attempts that follow are then
fired against an already-expired context.

Wrap every attempt in a context deadline covering dial + request write +
response headers + first event. Release it atomically the moment a
response is committed so the deadline can never cut an established
stream (a stop-the-timer race at the first-event boundary is closed by
deciding "deadline fired" vs "commit response" under one lock).

Also tag each failed attempt with the phase it died in (dial / write /
headers / first_event) so a hung exit is attributable from the request
log alone, and classify the attempt timeout as its own leg instead of
the generic transport bucket.

Adds unit tests for the deadline cut, the release-after-first-event
boundary, the phase classification and error unwrapping.
This commit is contained in:
mcheiyue committed 2026-10-11 19:42:51 +08:00
1 parent 1e2702f6e0
commit 5076226ac2
4 files changed
+276 -27

No files matched your search

+136 -10
View File
@@ -8,11 +8,77 @@ import (
"fmt"
"io"
"net/http"
"net/http/httptrace"
"strings"
"sync"
"time"
)
var errFirstEventTimeout = fmt.Errorf("upstream first SSE event timed out: %w", context.DeadlineExceeded)
var (
errFirstEventTimeout = fmt.Errorf("upstream first SSE event timed out: %w", context.DeadlineExceeded)
errAttemptTimeout = fmt.Errorf("upstream attempt timed out: %w", context.DeadlineExceeded)
)
// attemptTrace records how far a single attempt got before it failed. The
// shared ResponseHeaderTimeout only covers the header wait; this probe tells
// apart the phases it cannot see (dial, request write) from the ones it can.
type attemptTrace struct {
gotConn bool
wroteRequest bool
gotFirstByte bool
}
func (t *attemptTrace) phase() string {
switch {
case !t.gotConn:
return "dial"
case !t.wroteRequest:
return "write"
case !t.gotFirstByte:
return "headers"
default:
return "first_event"
}
}
func (t *attemptTrace) clientTrace() *httptrace.ClientTrace {
return &httptrace.ClientTrace{
GotConn: func(httptrace.GotConnInfo) { t.gotConn = true },
WroteRequest: func(httptrace.WroteRequestInfo) { t.wroteRequest = true },
GotFirstResponseByte: func() { t.gotFirstByte = true },
}
}
// phasedError carries the phase an attempt died in. Unwrap keeps the original
// error, so existing errors.Is checks keep working.
type phasedError struct {
err error
phase string
}
func (e *phasedError) Error() string { return fmt.Sprintf("%s [phase=%s]", e.err.Error(), e.phase) }
func (e *phasedError) Unwrap() error { return e.err }
// classifyAttemptError renders a leg token for the request log. The phase is
// appended for the attempt-deadline and transport cases so a hung exit can be
// attributed without grepping logs.
func classifyAttemptError(err error) string {
var pe *phasedError
phase := ""
if errors.As(err, &pe) {
phase = "_" + pe.phase
}
switch {
case errors.Is(err, errAttemptTimeout):
return "attempt_timeout" + phase
case errors.Is(err, errFirstEventTimeout):
return "first_event"
case errors.Is(err, context.DeadlineExceeded):
return "timeout" + phase
default:
return "transport" + phase
}
}
type attemptBody struct {
io.Reader
@@ -28,21 +94,76 @@ func (b *attemptBody) Close() error {
// Wait before returning a successful SSE response to the retry loop, while
// nothing has been committed downstream. Keep every byte for native forwarding.
// Comments and incomplete frames do not count as the first event.
func doInferenceAttempt(client *http.Client, req *http.Request, timeout time.Duration) (*http.Response, error) {
if timeout <= 0 || strings.HasSuffix(req.URL.Path, "/systemone") {
//
// attemptTimeout bounds the whole attempt (dial + request write + response
// headers + first event). ResponseHeaderTimeout only covers the header wait,
// so a wedged exit can otherwise hang in the write or dial phase until the
// request-level budget is gone.
func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeout, attemptTimeout time.Duration) (*http.Response, error) {
if firstEventTimeout <= 0 || strings.HasSuffix(req.URL.Path, "/systemone") {
return client.Do(req)
}
trace := &attemptTrace{}
ctx, cancel := context.WithCancelCause(req.Context())
resp, err := client.Do(req.Clone(ctx))
req = req.Clone(httptrace.WithClientTrace(ctx, trace.clientTrace()))
var (
deadlineMu sync.Mutex
committed bool
attemptTimer *time.Timer
)
if attemptTimeout > 0 {
attemptTimer = time.AfterFunc(attemptTimeout, func() {
deadlineMu.Lock()
defer deadlineMu.Unlock()
if !committed {
cancel(errAttemptTimeout)
}
})
}
// commitDeadline decides success against the attempt deadline atomically:
// either the deadline already fired (cause returned) or the response is
// committed and the timer can no longer cut an established stream.
commitDeadline := func() error {
if attemptTimer == nil {
return context.Cause(ctx)
}
deadlineMu.Lock()
defer deadlineMu.Unlock()
if cause := context.Cause(ctx); cause != nil {
return cause
}
committed = true
attemptTimer.Stop()
return nil
}
defer func() {
deadlineMu.Lock()
committed = true
deadlineMu.Unlock()
if attemptTimer != nil {
attemptTimer.Stop()
}
}()
resp, err := client.Do(req)
if err != nil {
if cause := context.Cause(ctx); cause != nil && errors.Is(cause, errAttemptTimeout) {
err = cause
}
cancel(nil)
return resp, err
return resp, &phasedError{err: err, phase: trace.phase()}
}
if resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
if attemptTimer != nil {
if cause := commitDeadline(); cause != nil {
cancel(nil)
resp.Body.Close()
return nil, &phasedError{err: cause, phase: trace.phase()}
}
}
resp.Body = &attemptBody{Reader: resp.Body, body: resp.Body, cancel: cancel}
return resp, nil
}
timer := time.AfterFunc(timeout, func() { cancel(errFirstEventTimeout) })
timer := time.AfterFunc(firstEventTimeout, func() { cancel(errFirstEventTimeout) })
reader := bufio.NewReader(resp.Body)
prefix, err := readFirstEvent(reader)
stopped := timer.Stop()
@@ -50,13 +171,18 @@ func doInferenceAttempt(client *http.Client, req *http.Request, timeout time.Dur
// Stop(false) means the callback may still be about to run.
cancel(errFirstEventTimeout)
}
if cause := context.Cause(ctx); cause != nil {
err = cause
}
if err != nil {
if cause := context.Cause(ctx); cause != nil {
err = cause
}
cancel(nil)
resp.Body.Close()
return nil, err
return nil, &phasedError{err: err, phase: trace.phase()}
}
if cause := commitDeadline(); cause != nil {
cancel(nil)
resp.Body.Close()
return nil, &phasedError{err: cause, phase: trace.phase()}
}
resp.Body = &attemptBody{Reader: io.MultiReader(bytes.NewReader(prefix), reader), body: resp.Body, cancel: cancel}
return resp, nil
+123
View File
@@ -0,0 +1,123 @@
package gateway
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestAttemptDeadlineCutsHungHeaders(t *testing.T) {
block := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-block
}))
defer srv.Close()
defer close(block)
req, err := http.NewRequest(http.MethodPost, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
start := time.Now()
_, err = doInferenceAttempt(srv.Client(), req, 5*time.Second, 200*time.Millisecond)
elapsed := time.Since(start)
if err == nil {
t.Fatal("expected an attempt timeout, got nil error")
}
if !errors.Is(err, errAttemptTimeout) {
t.Fatalf("expected errAttemptTimeout, got %v", err)
}
if got := classifyAttemptError(err); got != "attempt_timeout_headers" {
t.Fatalf("classify = %q, want attempt_timeout_headers", got)
}
if elapsed > time.Second {
t.Fatalf("attempt deadline did not cut a hung exit in time: %v", elapsed)
}
}
// The attempt deadline guards only the wait for the first event; it must never
// leak into the established stream that follows.
func TestAttemptDeadlineReleasesAfterFirstEvent(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("data: {\"x\":1}\n\n"))
w.(http.Flusher).Flush()
<-release
}))
defer srv.Close()
defer close(release)
req, err := http.NewRequest(http.MethodPost, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
start := time.Now()
resp, err := doInferenceAttempt(srv.Client(), req, 5*time.Second, 300*time.Millisecond)
elapsed := time.Since(start)
if err != nil {
t.Fatalf("first event arrived, expected success, got %v", err)
}
if resp == nil {
t.Fatal("expected a response")
}
defer resp.Body.Close()
if elapsed > 2*time.Second {
t.Fatalf("attempt deadline leaked into the established stream: %v", elapsed)
}
}
func TestClassifyAttemptError(t *testing.T) {
cases := []struct {
name string
err error
want string
}{
{"attempt timeout in write phase", &phasedError{err: errAttemptTimeout, phase: "write"}, "attempt_timeout_write"},
{"attempt timeout in dial phase", &phasedError{err: errAttemptTimeout, phase: "dial"}, "attempt_timeout_dial"},
{"first event timeout", &phasedError{err: errFirstEventTimeout, phase: "first_event"}, "first_event"},
{"request deadline with headers phase", &phasedError{err: context.DeadlineExceeded, phase: "headers"}, "timeout_headers"},
{"plain transport error", &phasedError{err: errors.New("connection reset"), phase: "dial"}, "transport_dial"},
{"bare context deadline", context.DeadlineExceeded, "timeout"},
}
for _, tc := range cases {
if got := classifyAttemptError(tc.err); got != tc.want {
t.Errorf("%s: classifyAttemptError() = %q, want %q", tc.name, got, tc.want)
}
}
}
func TestPhasedErrorUnwrapKeepsIs(t *testing.T) {
err := &phasedError{err: errAttemptTimeout, phase: "write"}
if !errors.Is(err, errAttemptTimeout) {
t.Fatal("phasedError must unwrap to errAttemptTimeout")
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatal("errAttemptTimeout must remain a DeadlineExceeded for the retry loop")
}
}
func TestAttemptTracePhase(t *testing.T) {
var trace attemptTrace
if got := trace.phase(); got != "dial" {
t.Fatalf("fresh trace phase = %q, want dial", got)
}
trace.gotConn = true
if got := trace.phase(); got != "write" {
t.Fatalf("after GotConn phase = %q, want write", got)
}
trace.wroteRequest = true
if got := trace.phase(); got != "headers" {
t.Fatalf("after WroteRequest phase = %q, want headers", got)
}
trace.gotFirstByte = true
if got := trace.phase(); got != "first_event" {
t.Fatalf("after GotFirstResponseByte phase = %q, want first_event", got)
}
}
+13 -9
View File
@@ -38,6 +38,9 @@ type Gateway struct {
catalog *models.Catalog
monitor *telemetry.Monitor
availability *models.AvailabilityStore
// attemptTimeout bounds a whole upstream attempt (dial + write + headers +
// first event), not just the header wait. Zero keeps the legacy behavior.
attemptTimeout time.Duration
}
func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) {
@@ -62,15 +65,16 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*G
catalog := models.NewCatalog(cfg.Prefer, cfg.Models.Protocols)
catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second)
return &Gateway{
cfg: cfg,
rotation: rotationManager,
logger: logger,
transports: transports,
zenNodes: zenNodes,
goNodes: goNodes,
anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown),
catalog: catalog,
monitor: monitor,
cfg: cfg,
rotation: rotationManager,
logger: logger,
transports: transports,
zenNodes: zenNodes,
goNodes: goNodes,
anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown),
catalog: catalog,
monitor: monitor,
attemptTimeout: cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds) * time.Second),
}, nil
}
+4 -8
View File
@@ -302,7 +302,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy)
started := time.Now()
resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
duration := time.Since(started)
if ctx.Err() != nil {
// The parent budget expired while this attempt was in flight. Its
@@ -578,7 +578,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
return nil, err, 0
}
started := time.Now()
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
duration := time.Since(started)
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration)
if err != nil {
@@ -647,7 +647,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
keyID := config.KeyDisplayID(node.key)
setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy)
attemptStarted := time.Now()
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
attemptDuration := time.Since(attemptStarted)
if ctx.Err() != nil {
// The request budget expired while this attempt was in flight. A
@@ -771,11 +771,7 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
}
leg := label + ":"
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
leg += "timeout"
} else {
leg += "transport"
}
leg += classifyAttemptError(err)
} else {
leg += strconv.Itoa(status)
}