diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index 0f73295..14c5f69 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -86,6 +86,54 @@ var errProxyUnavailable = errors.New("proxy unavailable") // proxyUnavailableError is an attempt error that asProxyUnavailable attributed // to the proxy route. It matches both errProxyUnavailable and the original // error under errors.Is and errors.As. +// timeoutStatus classifies an exhausted request budget for the client. +// +// A write-phase failure means the upstream never finished reading the request +// body: the payload is too large. 413 tells a client that can shrink the +// request (a harness that strips oversized inline images) to shrink it, instead +// of replaying the same oversized payload forever. +// +// Every other phase stays a 504: the upstream was slow to answer, or the model +// was thinking, and neither is the client's fault. +// +// The phase is read from the innermost phasedError, so a wrapped error (the +// key loop hands the attempt error back through its own wrapper) still +// classifies correctly. +func timeoutStatus(err error, budgetAlive bool) (int, string, string) { + if isPayloadTooLarge(err, budgetAlive) { + return http.StatusRequestEntityTooLarge, "request payload is too large for the upstream to accept", "payload_too_large" + } + return http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout" +} + +// isPayloadTooLarge reports whether the failure was caused by the request +// being too large for the upstream to accept. +// +// A write-phase attempt timeout means the upstream never finished reading the +// request body: the connection was established, but the body did not fit +// through it. A body that big is a payload-size problem, not a flaky network. +// +// Only the write phase counts. A header-phase timeout is the upstream being +// slow to answer, which is not the client's fault, and a first-event timeout +// is the model thinking, which is exactly what a long thinking turn does. +// +// The request budget must also still be alive (budgetAlive). The attempt +// timeout is short (15s) and the request budget is long (900s), so a write +// attempt that stalls for the whole attempt timeout while the request budget +// still has time is the upstream refusing the body. When the request budget is +// what expired, the whole request was too slow and the cause is not the +// payload. +func isPayloadTooLarge(err error, budgetAlive bool) bool { + if err == nil || !budgetAlive { + return false + } + var pe *phasedError + if !errors.As(err, &pe) || pe.phase != "write" { + return false + } + return errors.Is(err, errAttemptTimeout) || errors.Is(err, context.DeadlineExceeded) +} + type proxyUnavailableError struct { proxy string err error diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 860ada1..58ea342 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -271,7 +271,19 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return } if !g.catalog.Supported(model) { - wire.WriteError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + // A model the catalog has never heard of is a bad model NAME: 404 + // tells a client to pick a different model. A model the catalog + // knows but cannot serve is a capability or routing problem, and + // the old 400 phrasing ("the model uses an upstream protocol that + // opencode2api does not expose") is accurate for it. The old code + // returned that 400 for BOTH, so a request for a model the + // upstream retired (it answers 410 Gone) looked like a gateway + // capability bug and clients retried forever. + if g.catalog.Known(model) { + wire.WriteError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + } else { + wire.WriteError(w, external, http.StatusNotFound, fmt.Sprintf("model %q was not found in the upstream model catalog", model), "model_not_found", "model") + } return } route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) @@ -352,7 +364,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { // An exhausted request budget is a timeout, not a bad gateway: the // distinction matters to clients that retry on 502. if errors.Is(err, context.DeadlineExceeded) { - wire.WriteError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) + // A write-phase failure means the upstream never finished + // reading the request body: the payload is too large. Report + // it as 413 so a client that can shrink the request (a harness + // that strips oversized inline images) knows to shrink it + // instead of retrying the same oversized payload forever. A + // header- or first-event-phase failure is the upstream being + // slow, which is not the client's fault, and stays a 504. + status, message, code := timeoutStatus(err, requestCtx.Err() == nil) + wire.WriteError(w, external, status, message, code, ids.Request) return } // Every exit this request could use is under the free tier's IP @@ -479,7 +499,14 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { return } if !g.catalog.Supported(model) { - wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + // Same split as the chat path: a model the catalog has never heard of + // is a bad model NAME (404), a model it knows but cannot serve is a + // capability or routing problem (400). + if g.catalog.Known(model) { + wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") + } else { + wire.WriteError(w, wire.SystemOne, http.StatusNotFound, fmt.Sprintf("model %q was not found in the upstream model catalog", model), "model_not_found", "model") + } return } route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) @@ -545,7 +572,11 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body return } if errors.Is(err, context.DeadlineExceeded) { - wire.WriteError(w, wire.SystemOne, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) + // Same split as the chat path: a write-phase failure means the + // payload is too large (413), every other phase is a slow + // upstream (504). + status, message, code := timeoutStatus(err, requestCtx.Err() == nil) + wire.WriteError(w, wire.SystemOne, status, message, code, ids.Request) return } wire.WriteError(w, wire.SystemOne, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request) diff --git a/internal/gateway/interop_status_test.go b/internal/gateway/interop_status_test.go new file mode 100644 index 0000000..7a92d1d --- /dev/null +++ b/internal/gateway/interop_status_test.go @@ -0,0 +1,173 @@ +package gateway + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "opencode2api/internal/config" + modelcatalog "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" +) + +// An unknown model must be a 404 with a model_not_found code, so a client +// knows to pick a different model. The old code returned a 400 "the model +// uses an upstream protocol that opencode2api does not expose" for a bad +// model NAME as well, which made a model the upstream had retired (it answers +// 410 Gone) look like a gateway capability bug. +func TestUnknownModelReturns404ModelNotFound(t *testing.T) { + gw := gatewayWithCatalog(t, []string{"known-model"}) + + body := `{"model":"totally-unknown-model","stream":false,"messages":[{"role":"user","content":"hi"}]}` + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + rec := httptest.NewRecorder() + + telemetry.Middleware(telemetry.Monitor(), slog.New(slog.NewTextHandler(io.Discard, nil)), gw.Handler()).ServeHTTP(rec, req) + + if rec.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404 for an unknown model (body %q)", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "model_not_found") { + t.Errorf("response does not carry the model_not_found code: %q", rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "totally-unknown-model") { + t.Errorf("response does not name the missing model: %q", rec.Body.String()) + } +} + +// A model the catalog KNOWS but cannot serve keeps the 400: that is a +// capability or routing problem, and the old phrasing is accurate for it. +func TestKnownButUnservableModelKeeps400(t *testing.T) { + gw := gatewayWithCatalog(t, []string{"known-model"}) + // Mark the model as capability-unsupported on the Zen tier: the catalog + // knows it, but it cannot be served. + gw.catalog.ReplaceWithCapabilities( + []string{"known-model"}, nil, + map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}, + map[config.Tier]map[string]bool{config.TierZen: {"known-model": true}, config.TierGo: {}}, + map[config.Tier]map[string]modelcatalog.Metadata{config.TierZen: {}, config.TierGo: {}}, + ) + + body := `{"model":"known-model","stream":false,"messages":[{"role":"user","content":"hi"}]}` + req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-key") + rec := httptest.NewRecorder() + + telemetry.Middleware(telemetry.Monitor(), slog.New(slog.NewTextHandler(io.Discard, nil)), gw.Handler()).ServeHTTP(rec, req) + + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 for a known but unservable model (body %q)", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "upstream protocol") { + t.Errorf("response lost the capability explanation: %q", rec.Body.String()) + } +} + +// isPayloadTooLarge must only fire for a write-phase failure while the +// request budget is still alive. +func TestIsPayloadTooLargeClassification(t *testing.T) { + writeTimeout := &phasedError{err: errAttemptTimeout, phase: "write"} + headerTimeout := &phasedError{err: errAttemptTimeout, phase: "headers"} + firstEventTimeout := &phasedError{err: errFirstEventTimeout, phase: "first_event"} + dialTimeout := &phasedError{err: errAttemptTimeout, phase: "dial"} + + cases := []struct { + name string + err error + budgetAlive bool + want bool + }{ + {"write timeout with budget alive", writeTimeout, true, true}, + {"write timeout with budget expired", writeTimeout, false, false}, + {"header timeout", headerTimeout, true, false}, + {"first event timeout", firstEventTimeout, true, false}, + {"dial timeout", dialTimeout, true, false}, + {"nil error", nil, true, false}, + {"plain deadline", context.DeadlineExceeded, true, false}, + } + for _, tc := range cases { + if got := isPayloadTooLarge(tc.err, tc.budgetAlive); got != tc.want { + t.Errorf("%s: isPayloadTooLarge = %v, want %v", tc.name, got, tc.want) + } + } + if isPayloadTooLarge(errors.New("boom"), true) { + t.Errorf("an unrelated error must not be classified as payload-too-large") + } +} + +// The client-facing status for an exhausted budget: 413 when the upstream +// never finished reading the body, 504 for every other phase. +func TestTimeoutStatusClassification(t *testing.T) { + writeTimeout := &phasedError{err: errAttemptTimeout, phase: "write"} + headerTimeout := &phasedError{err: errAttemptTimeout, phase: "headers"} + firstEventTimeout := &phasedError{err: errFirstEventTimeout, phase: "first_event"} + + status, message, code := timeoutStatus(writeTimeout, true) + if status != http.StatusRequestEntityTooLarge { + t.Errorf("write-phase timeout status = %d, want 413", status) + } + if code != "payload_too_large" { + t.Errorf("write-phase timeout code = %q, want payload_too_large", code) + } + if !strings.Contains(message, "too large") { + t.Errorf("write-phase timeout message = %q, want it to name the size problem", message) + } + + // A header-phase failure is the upstream being slow: not the client's + // fault, so it stays a 504. + status, message, code = timeoutStatus(headerTimeout, true) + if status != http.StatusGatewayTimeout { + t.Errorf("header-phase timeout status = %d, want 504", status) + } + if code != "upstream_timeout" { + t.Errorf("header-phase timeout code = %q, want upstream_timeout", code) + } + if message != "upstream request timed out" { + t.Errorf("header-phase timeout message = %q", message) + } + + // A first-event timeout is the model thinking: also a 504. + if status, _, _ = timeoutStatus(firstEventTimeout, true); status != http.StatusGatewayTimeout { + t.Errorf("first-event timeout status = %d, want 504", status) + } + + // The request budget is what expired: the whole request was too slow, + // which is not a payload problem. + if status, _, _ = timeoutStatus(writeTimeout, false); status != http.StatusGatewayTimeout { + t.Errorf("write timeout with an expired budget = %d, want 504", status) + } +} + +// gatewayWithCatalog builds a gateway whose catalog knows exactly the given +// models. +func gatewayWithCatalog(t *testing.T, models []string) *Gateway { + t.Helper() + cfg := config.Config{ + ServerKeys: []string{"test-key"}, + ZenKeys: []string{"key-a"}, + Anonymous: false, + Prefer: config.TierZen, + Retry: config.RetryConfig{MaxAttempts: 1, TimeoutSeconds: 30}, + Performance: config.PerformanceConfig{ + ConnectTimeoutSeconds: 2, IdleConnTimeoutSeconds: 30, + MaxIdleConns: 64, MaxIdleConnsPerHost: 16, + }, + Upstream: config.UpstreamConfig{Zen: "http://127.0.0.1:1"}, + Models: config.ModelsConfig{RefreshSeconds: 300}, + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + monitor := telemetry.Monitor() + gw, err := New(cfg, logger, monitor) + if err != nil { + t.Fatalf("gateway New: %v", err) + } + gw.catalog.Replace(models, nil) + return gw +} diff --git a/internal/models/catalog.go b/internal/models/catalog.go index 483833b..07f9ace 100644 --- a/internal/models/catalog.go +++ b/internal/models/catalog.go @@ -559,6 +559,36 @@ func (c *ModelCatalog) Supported(model string) bool { return c.supportedLocked(model) } +// Known reports whether the catalog has ever heard of the model, regardless of +// whether it can currently be served. A model that is known but not servable +// (no tier advertises it, or the capability catalog marks it unsupported) is a +// DIFFERENT failure from a model the upstream has never offered: the first is +// a routing or capability problem, the second is a bad model name. +// +// The distinction matters for clients: a 404 "model not found" tells a harness +// to pick a different model, while a 400 "unsupported protocol" makes it retry +// the same impossible request forever. +func (c *ModelCatalog) Known(model string) bool { + c.mu.RLock() + defer c.mu.RUnlock() + if c.protocols[model] != "" { + return true + } + if c.zen[model] || c.goModels[model] { + return true + } + if c.nativeProtocols[config.TierZen][model] != "" || c.nativeProtocols[config.TierGo][model] != "" { + return true + } + if c.unsupported[config.TierZen][model] || c.unsupported[config.TierGo][model] { + return true + } + if c.modelMeta[config.TierZen][model].ContextWindow > 0 || c.modelMeta[config.TierGo][model].ContextWindow > 0 { + return true + } + return false +} + // MetadataForTier returns the rich per-model metadata (context window, // reasoning, tool call, modalities) captured from the OpenCode capability // catalog for the tier that will actually serve the request. Same-named models