diff --git a/README.md b/README.md index c8658d8..b1ef24a 100644 --- a/README.md +++ b/README.md @@ -317,7 +317,7 @@ Comment markers are `#`, `;`, and `//` at the start of a line or after whitespac | --------------------------------------- | ------- | ------------------------------------------------------ | | `retry.max_attempts` | `3` | Attempts per authenticated tier, including the first. | | `retry.timeout_seconds` | `300` | Total inference timeout, including stream consumption. | -| `performance.attempt_timeout_seconds` | `0` | Header wait per attempt; 0 uses the request timeout. | +| `performance.attempt_timeout_seconds` | `0` | Whole-attempt bound; 0 uses the request timeout. | | `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. | | `performance.failure_cooldown_seconds` | `15` | Base failure cooldown. | | `performance.max_idle_conns` | `2048` | Idle connection limit per proxy transport. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 3cf2d6a..5a695a7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -312,7 +312,7 @@ direct | --------------------------------------- | ------ | ------------------------------------------------ | | `retry.max_attempts` | `3` | 每个认证 Tier 的尝试次数,包含首次请求。 | | `retry.timeout_seconds` | `300` | 推理请求总超时,包含流式响应读取。 | -| `performance.attempt_timeout_seconds` | `0` | 每次尝试等待响应头的超时;0 表示使用请求总超时。 | +| `performance.attempt_timeout_seconds` | `0` | 单次尝试的总超时;0 表示使用请求总超时。 | | `performance.connect_timeout_seconds` | `5` | 建立连接的超时。 | | `performance.failure_cooldown_seconds` | `15` | 失败冷却基数。 | | `performance.max_idle_conns` | `2048` | 每个代理 Transport 的空闲连接上限。 | diff --git a/internal/config/config.go b/internal/config/config.go index ebdc935..2675fe8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -102,14 +102,16 @@ type PerformanceConfig struct { // AttemptTimeout bounds how long a single upstream attempt may wait for // response headers before it is abandoned and the next node is tried. Values // <= 0 keep the historical behavior of using the request-level retry timeout, -// so existing configs are unaffected. The result never exceeds requestTimeout, -// and only the header wait is bounded: an established stream keeps flowing -// under the request-level timeout. +// so existing configs are unaffected. The result never exceeds requestTimeout. +// It bounds the whole attempt up to the response being released (dial, request +// write, headers and, when enabled, the first SSE event); an established +// stream keeps flowing under the request-level timeout. // -// The bound is installed on the shared transports, so it covers every attempt -// in both the anonymous and the authenticated loops. Without it, one hung exit -// can consume the entire request budget by itself, and the attempts that follow -// are fired against an already-expired context. +// The bound is installed on the shared transports as the header wait and on +// each attempt's context, so it covers every attempt in both the anonymous and +// the authenticated loops. Without it, one hung exit can consume the entire +// request budget by itself, and the attempts that follow are fired against an +// already-expired context. func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.Duration { if cfg.AttemptTimeoutSeconds > 0 { attempt := time.Duration(cfg.AttemptTimeoutSeconds) * time.Second diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index e7e80c2..77947e9 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -8,11 +8,87 @@ import ( "fmt" "io" "net/http" + "net/http/httptrace" "strings" + "sync" + "sync/atomic" "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. +// The callbacks run on transport goroutines, so the flags are atomic. +type attemptTrace struct { + gotConn atomic.Bool + wroteRequest atomic.Bool + gotFirstByte atomic.Bool +} + +func (t *attemptTrace) phase() string { + switch { + case !t.gotConn.Load(): + return "dial" + case !t.wroteRequest.Load(): + return "write" + case !t.gotFirstByte.Load(): + return "headers" + default: + return "first_event" + } +} + +func (t *attemptTrace) clientTrace() *httptrace.ClientTrace { + return &httptrace.ClientTrace{ + GotConn: func(httptrace.GotConnInfo) { t.gotConn.Store(true) }, + WroteRequest: func(httptrace.WroteRequestInfo) { t.wroteRequest.Store(true) }, + GotFirstResponseByte: func() { t.gotFirstByte.Store(true) }, + } +} + +// upstreamAccepted reports whether an attempt died after the upstream had +// already answered with headers. Such a timeout is slow generation, not a +// broken proxy, so it must not evict the exit. +func upstreamAccepted(err error) bool { + var pe *phasedError + return errors.As(err, &pe) && pe.phase == "first_event" +} + +// 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 +104,77 @@ 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 && attemptTimeout <= 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)) - if err != nil { - cancel(nil) - return resp, err + 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) + } + }) } - if resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") { + // 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, &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 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 +182,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 diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a5e376d..88bda9e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -27,6 +27,16 @@ const maxRequestBody = 32 << 20 const anonymousZenKey = "public" +// attemptDeadline is the per-attempt context deadline. It is armed only when +// attempt_timeout_seconds is set: otherwise the request-level budget already +// bounds the single attempt it would cover. +func attemptDeadline(cfg config.Config) time.Duration { + if cfg.Performance.AttemptTimeoutSeconds <= 0 { + return 0 + } + return cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds) * time.Second) +} + // statusClientClosedRequest is nginx's 499: the client went away before the // gateway could answer, so the failure is neither upstream nor ours. const statusClientClosedRequest = 499 @@ -42,6 +52,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) { @@ -66,15 +79,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: attemptDeadline(cfg), }, nil } diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 93d074c..ebaff23 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -245,7 +245,7 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans // route is unavailable. HTTP responses and unrelated transport/protocol errors // must not evict a proxy. func isProxyFailure(err error) bool { - if errors.Is(err, errFirstEventTimeout) { + if errors.Is(err, errFirstEventTimeout) || upstreamAccepted(err) { return false // The upstream accepted HTTP; slow generation is not a broken proxy. } if err == nil { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 19f71ed..86116af 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -304,7 +304,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 @@ -650,7 +650,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 { @@ -719,7 +719,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 @@ -843,11 +843,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) }