From a11e6402305c78c86eadbb6021799337dad9ff87 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Sun, 29 Nov 2026 00:21:37 +0000 Subject: [PATCH] fix(passthrough): gate and bill passthrough requests by cost budget Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event. --- README.md | 12 +- events.go | 13 +- passthrough_sse_estimate_test.go | 163 ++++++++++++++ passthrough_unpriced_gate_test.go | 316 +++++++++++++++++++++++++++ passthrough_unpriced_refusal_test.go | 119 ++++++++++ routes_passthrough.go | 284 ++++++++++++++---------- routes_passthrough_test.go | 6 +- 7 files changed, 792 insertions(+), 121 deletions(-) create mode 100644 passthrough_sse_estimate_test.go create mode 100644 passthrough_unpriced_gate_test.go create mode 100644 passthrough_unpriced_refusal_test.go diff --git a/README.md b/README.md index 09d9fb6..028aaa5 100644 --- a/README.md +++ b/README.md @@ -412,7 +412,7 @@ config accepts them as YAML, which decodes to the same JSON shape. | `providers` | `map[string]ProviderConfig` | — | Required, at least one entry, or the plugin refuses to construct. | | `groups` | `map[string]GroupConfig` | `{}` | Optional. A user references one or more of these groups by name (`UserConfig.group`/`groups`); an unknown reference is a construction error. | | `pricing` | `map[string]ModelPricing` | `{}` | Per-model USD/1M-token overrides, keyed by model id (bare or `provider/model`). Merged over, not replacing, the built-in table (`pricing.go`). Every entry is validated at construction — see [Limits and accounting](#limits-and-accounting). | -| `allowUnpricedWithCostBudget` | `bool` | `false` | `false`: a request for a model with no known price — no `pricing` override, no built-in table entry, and no `modelMeta` entry marking it `free: true` — is refused with **402** whenever the caller's user or group has `costPerDayUSD`/`costPerMonthUSD` configured, since that budget could not otherwise be enforced. Applies to the unified routes and to native passthrough when the model is identifiable from the request body. `true` serves the request anyway, billing it as unpriced (cost `0`) — prefer adding the missing `pricing` entry instead. A caller with no cost budget configured is unaffected either way. | +| `allowUnpricedWithCostBudget` | `bool` | `false` | `false`: a request for a model with no known price — no `pricing` override, no built-in table entry, and no `modelMeta` entry marking it `free: true` — is refused with **402** whenever the caller's user or group has `costPerDayUSD`/`costPerMonthUSD` configured, since that budget could not otherwise be enforced. Applies to the unified routes and to native passthrough when the model is identifiable from the request body. Passthrough also refuses with **402** a JSON body whose top-level `model` is missing or repeated after the gateway has read the body up to the smaller of `maxRequestBytes` and the 32MiB passthrough cap (a body whose JSON object does not close within that bound gets **413**) because the first 64KiB did not settle it. A priced `model` placed after 64KiB is served. Two shapes are still not gated: a JSON body sent with a binary `Content-Type`, and Gemini passthrough, whose model is in the URL; both can reach an unpriced model at recorded cost `0`. `true` serves the request anyway, billing it as unpriced (cost `0`) — prefer adding the missing `pricing` entry instead. A caller with no cost budget configured is unaffected either way. | | `mcpServers` | `map[string]TargetConfig` | `{}` | MCP server registry; see [MCP/A2A](#mcp-and-a2a). | | `agents` | `map[string]AgentConfig` | `{}` | A2A agent registry; see [MCP/A2A](#mcp-and-a2a). | | `users` | `UsersConfig` | — | Inline and/or file-backed API-key holders. With none configured, every request is unauthenticated and gets 401. | @@ -1773,7 +1773,10 @@ model id) and per alias (`aliases[].modelMeta`) — see reports one — the request-body-size estimate (`ceil(request-bytes / 4)` prompt tokens, `estimated`) covers it instead, so a streamed or malformed passthrough response is never billed zero just for never - finishing cleanly. + finishing cleanly. A 2xx stream that delivered `data:` events but no + completion usage — no `include_usage`, or a client that hung up before + the final usage event — is also billed an estimated completion of one + token per `data:` event (capped at 1048576), marked `estimated`. - **Native passthrough request bodies are capped at 32MiB** (`maxPassthroughBytes`, `routes_passthrough.go`) — generous enough for a multimodal payload the unified routes' own narrower caps do not need @@ -1821,7 +1824,10 @@ released, so this never becomes a ceiling on total concurrent requests. memory, so there is nothing here for this limit to bound (the one exception, a bounded 64KiB peek for model-restricted groups, is already capped independently — see [Native passthrough model - authorization](#native-passthrough-model-authorization)). + authorization](#native-passthrough-model-authorization)). Under a cost + budget, when the first 64KiB does not settle the top-level `model`, + the gate buffers the body up to the smaller of `maxRequestBytes` (4MiB + by default) and this 32MiB cap, then restores it for forwarding.) ## Retry diff --git a/events.go b/events.go index bef047c..1373585 100644 --- a/events.go +++ b/events.go @@ -446,9 +446,16 @@ func (g *Gateway) recordUpstreamEvent(scopes []limitScope, model, provider, rout // apart in the feed (402 here, unset/0 there — a billed-0 event carries // no HTTP status of its own, since nothing was refused). func (g *Gateway) recordUnpricedRefusalEvent(scopes []limitScope, model, provider, route string) { + g.recordUnpricedRefusal(scopes, model, model, provider, route) +} + +// recordUnpricedRefusal is recordUnpricedRefusalEvent with the counter key +// and the displayed model split: counterModel names the per-model counter +// ("" for the total scope only), shownModel goes into the event. +func (g *Gateway) recordUnpricedRefusal(scopes []limitScope, counterModel, shownModel, provider, route string) { ev := gatewayEvent{ - Model: model, Provider: provider, Route: route, Kind: eventKindUnpriced, Status: http.StatusPaymentRequired, - Message: fmt.Sprintf("model %q refused: no configured price, so the cost budget that applies to this caller cannot be enforced", model), + Model: shownModel, Provider: provider, Route: route, Kind: eventKindUnpriced, Status: http.StatusPaymentRequired, + Message: fmt.Sprintf("model %q refused: no configured price, so the cost budget that applies to this caller cannot be enforced", shownModel), } applyScopeAttribution(&ev, scopes) g.recordEvent(ev) @@ -458,7 +465,7 @@ func (g *Gateway) recordUnpricedRefusalEvent(scopes []limitScope, model, provide // without touching either route file again. Fire-and-forget // (recordUnpriced402's own countAsync/l.spawn); no-op when admin // stats are off. - g.limiter.recordUnpriced402(model) + g.limiter.recordUnpriced402(counterModel) } // recordProxyEvent records an upstream event for a proxyUpstream result diff --git a/passthrough_sse_estimate_test.go b/passthrough_sse_estimate_test.go new file mode 100644 index 0000000..5f7cca7 --- /dev/null +++ b/passthrough_sse_estimate_test.go @@ -0,0 +1,163 @@ +package traefikllmgateway + +import ( + "bufio" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const sseTestChunk = "data: {\"id\":\"c1\",\"model\":\"gpt-5\",\"choices\":[{\"delta\":{\"content\":\"x\"}}]}\n\n" + +func newSSEEstimateGateway(t *testing.T, upstream http.HandlerFunc) *Gateway { + t.Helper() + srv := httptest.NewServer(upstream) + t.Cleanup(srv.Close) + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up"}} + cfg.Groups = map[string]*GroupConfig{"default": {}} + cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}} + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw") + if err != nil { + t.Fatalf("New: %v", err) + } + gw, ok := h.(*Gateway) + if !ok { + t.Fatal("handler is not *Gateway") + } + gw.limiter.spawn = func(f func()) { f() } + return gw +} + +func postSSE(gw *Gateway) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`)) + req.Header.Set("Authorization", "Bearer sk-alice") + rec := httptest.NewRecorder() + gw.ServeHTTP(rec, req) + return rec +} + +func tokOutOf(gw *Gateway) int64 { + v, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now()) + return v +} + +func TestPassthroughSSE_NoUsageChunkBillsEstimatedCompletion(t *testing.T) { + gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for i := 0; i < 30; i++ { + _, _ = io.WriteString(w, sseTestChunk) + } + }) + if rec := postSSE(gw); rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + got := tokOutOf(gw) + if got < 30 || got > 31 { + t.Errorf("tokout = %d, want 30..31 (one per data event)", got) + } + if cost, _ := gw.limiter.getCounter("user", "alice", metricCost, windowDay, time.Now()); cost <= 0 { + t.Errorf("cost = %d, want > 0", cost) + } +} + +func TestPassthroughSSE_ReportedUsageWins(t *testing.T) { + gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for i := 0; i < 30; i++ { + _, _ = io.WriteString(w, sseTestChunk) + } + _, _ = io.WriteString(w, "data: {\"id\":\"c1\",\"choices\":[],\"usage\":{\"prompt_tokens\":42,\"completion_tokens\":9}}\n\ndata: [DONE]\n\n") + }) + postSSE(gw) + if got := tokOutOf(gw); got != 9 { + t.Errorf("tokout = %d, want 9 (reported)", got) + } + if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 42 { + t.Errorf("tokin = %d, want 42 (reported)", got) + } +} + +func TestPassthroughSSE_HangupBeforeUsageBillsEstimate(t *testing.T) { + gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for i := 0; i < 5; i++ { + _, _ = io.WriteString(w, sseTestChunk) + w.(http.Flusher).Flush() + } + <-r.Context().Done() + }) + front := httptest.NewServer(gw) + defer front.Close() + + req, _ := http.NewRequest(http.MethodPost, front.URL+"/openai/v1/native-endpoint", strings.NewReader(`{"model":"gpt-5","stream":true,"messages":[]}`)) + req.Header.Set("Authorization", "Bearer sk-alice") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + rd := bufio.NewReader(resp.Body) + for i := 0; i < 5; i++ { + for { + line, rerr := rd.ReadString('\n') + if rerr != nil { + t.Fatalf("read: %v", rerr) + } + if line == "\n" { + break + } + } + } + _ = resp.Body.Close() + + deadline := time.Now().Add(3 * time.Second) + for tokOutOf(gw) == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := tokOutOf(gw); got < 1 || got > 6 { + t.Errorf("tokout = %d, want 1..6 after a client hang-up", got) + } +} + +func TestPassthroughJSON_NoUsageStaysNoOp(t *testing.T) { + gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"file-1","object":"file"}`) + }) + if rec := postSSE(gw); rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + if got := tokOutOf(gw); got != 0 { + t.Errorf("tokout = %d, want 0", got) + } + if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 0 { + t.Errorf("tokin = %d, want 0", got) + } +} + +func TestSSEAccountingBuffer_CountsDataEvents(t *testing.T) { + var b sseAccountingBuffer + _, _ = b.Write([]byte(sseTestChunk + sseTestChunk)) + _, _ = b.Write([]byte(": keepalive\n\n")) + _, _ = b.Write([]byte("data: [DONE]\n\n")) + if b.events != 3 { + t.Errorf("events = %d, want 3", b.events) + } +} + +func TestPassthroughSSE_ReportedPromptWithoutCompletionKeptWithoutRequestBody(t *testing.T) { + gw := newSSEEstimateGateway(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"model\":\"gpt-5\",\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":0}}\n\n") + }) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", nil) + req.Header.Set("Authorization", "Bearer sk-alice") + gw.ServeHTTP(httptest.NewRecorder(), req) + if got, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()); got != 7 { + t.Errorf("tokin = %d, want 7 (reported prompt usage must not be dropped)", got) + } +} diff --git a/passthrough_unpriced_gate_test.go b/passthrough_unpriced_gate_test.go new file mode 100644 index 0000000..f10f0dd --- /dev/null +++ b/passthrough_unpriced_gate_test.go @@ -0,0 +1,316 @@ +package traefikllmgateway + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +const gateUpstreamReply = `{"model":"gpt-5","usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}` + +// gateEnv is a gateway with a cost-budgeted user "alice" in front of an +// upstream that records how many requests reached it and how many body +// bytes it received. +type gateEnv struct { + gw *Gateway + h http.Handler + calls *int32 + lastBody *atomic.Value +} + +func newGateEnv(t *testing.T, mutate func(*Config)) *gateEnv { + t.Helper() + var calls int32 + var lastBody atomic.Value + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&calls, 1) + b, _ := io.ReadAll(r.Body) + lastBody.Store(string(b)) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, gateUpstreamReply) + })) + t.Cleanup(srv.Close) + + cfg := CreateConfig() + cfg.Admin = &AdminConfig{Enabled: true} + cfg.Providers = map[string]*ProviderConfig{ + "openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up", Models: []string{"cat-unpriced"}}, + } + cfg.Groups = map[string]*GroupConfig{"default": {}, "public": {Limits: &LimitsConfig{CostPerDayUSD: 5}}} + cfg.Users = &UsersConfig{ + AnonymousGroup: "public", + Inline: []*UserConfig{ + {Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}}, + {Name: "admin1", Group: "default", APIKey: "sk-admin1", Admin: true}, + }, + } + if mutate != nil { + mutate(cfg) + } + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw") + if err != nil { + t.Fatalf("New: %v", err) + } + gw, ok := h.(*Gateway) + if !ok { + t.Fatal("handler is not *Gateway") + } + gw.limiter.spawn = func(f func()) { f() } + return &gateEnv{gw: gw, h: h, calls: &calls, lastBody: &lastBody} +} + +func (e *gateEnv) post(body, key string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body)) + if key != "" { + req.Header.Set("Authorization", "Bearer "+key) + } + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + return rec +} + +func (e *gateEnv) upstreamCalls() int { return int(atomic.LoadInt32(e.calls)) } + +func (e *gateEnv) aliceTokOut() int64 { + v, _ := e.gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now()) + return v +} + +// padThenModel puts the model after more than maxModelPeekBytes of prompt. +func padThenModel(model string) string { + return `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}],"model":"` + model + `"}` +} + +func TestPassthroughCostGate_UnpricedModelBeyondPeekWindowRefused(t *testing.T) { + e := newGateEnv(t, nil) + rec := e.post(padThenModel("cat-unpriced"), "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } + if got := e.aliceTokOut(); got != 0 { + t.Errorf("tokout = %d, want 0", got) + } +} + +func TestPassthroughCostGate_PricedModelBeyondPeekWindowServedWithFullBody(t *testing.T) { + e := newGateEnv(t, nil) + body := padThenModel("gpt-5") + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String()) + } + if got, _ := e.lastBody.Load().(string); got != body { + t.Errorf("upstream body differs from the request body (got %d bytes, want %d)", len(got), len(body)) + } + if got := e.aliceTokOut(); got != 5 { + t.Errorf("tokout = %d, want 5", got) + } +} + +func TestPassthroughCostGate_LargeBodyWithoutModelRefused(t *testing.T) { + e := newGateEnv(t, nil) + body := `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}` + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_DuplicateModelKeyRefused(t *testing.T) { + e := newGateEnv(t, nil) + rec := e.post(`{"model":"gpt-5","model":"cat-unpriced"}`, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_DuplicateModelBeyondPeekWindowRefused(t *testing.T) { + e := newGateEnv(t, nil) + body := `{"model":"gpt-5","pad":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `","model":"cat-unpriced"}` + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_BodylessGetStillServed(t *testing.T) { + e := newGateEnv(t, nil) + req := httptest.NewRequest(http.MethodGet, "/openai/v1/models", nil) + req.Header.Set("Authorization", "Bearer sk-alice") + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String()) + } +} + +func TestPassthroughCostGate_ModelFirstPricedStillServed(t *testing.T) { + e := newGateEnv(t, nil) + body := `{"model":"gpt-5","messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}` + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String()) + } + if got := e.aliceTokOut(); got != 5 { + t.Errorf("tokout = %d, want 5", got) + } +} + +func TestPassthroughCostGate_AllowUnpricedOptInServesAllShapes(t *testing.T) { + e := newGateEnv(t, func(c *Config) { c.AllowUnpricedWithCostBudget = true }) + for name, body := range map[string]string{ + "padded": padThenModel("cat-unpriced"), + "duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`, + } { + if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK { + t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String()) + } + } +} + +func TestPassthroughCostGate_NoCostBudgetUnchanged(t *testing.T) { + e := newGateEnv(t, func(c *Config) { + c.Users.Inline[0].Limits = &LimitsConfig{} + }) + for name, body := range map[string]string{ + "padded": padThenModel("cat-unpriced"), + "duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`, + } { + if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK { + t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String()) + } + } +} + +func TestPassthroughCostGate_OverCapBodyIs413(t *testing.T) { + e := newGateEnv(t, nil) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(padThenModel("gpt-5"))) + req.ContentLength = maxPassthroughBytes + 1 + req.Header.Set("Authorization", "Bearer sk-alice") + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413", rec.Code) + } +} + +func TestPassthroughCostGate_ObjectUnclosedWithinBoundIs413(t *testing.T) { + e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 }) + body := `{"model":"gpt-5"` + strings.Repeat(" ", 1<<20) + `,"model":"cat-unpriced"}` + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413, body=%.200s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "maxRequestBytes") { + t.Errorf("body does not name maxRequestBytes: %.200s", rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_ChunkedOverCapBodyIs413(t *testing.T) { + e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = maxExplicitUnifiedRequestBytes }) + body := `{"pad":"` + strings.Repeat("a", maxPassthroughBytes) + `"}` + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body)) + req.ContentLength = -1 + req.Header.Set("Authorization", "Bearer sk-alice") + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413", rec.Code) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_HugeNonStringModelValueRefused(t *testing.T) { + e := newGateEnv(t, nil) + body := `{"model":[` + strings.Repeat("1,", 100_000) + `1],"x":1}` + body = strings.Replace(body, `"x":1`, `"pad":"`+strings.Repeat("a", maxModelPeekBytes)+`"`, 1) + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } +} + +func TestPassthroughCostGate_ModelBeyondMaxRequestBytesIs413(t *testing.T) { + e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 }) + body := `{"pad":"` + strings.Repeat("a", 2<<20) + `","model":"gpt-5"}` + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413", rec.Code) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func TestPassthroughCostGate_UnparseableObjectRefused(t *testing.T) { + for name, body := range map[string]string{ + "nan between duplicates": `{"model":"gpt-5","a":NaN,"model":"cat-unpriced"}`, + "truncated mid-object": `{"model":"gpt-5","messages":[{"role":"user"`, + } { + e := newGateEnv(t, nil) + rec := e.post(body, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Errorf("%s: status = %d, want 402, body=%.200s", name, rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("%s: upstream calls = %d, want 0", name, e.upstreamCalls()) + } + } +} + +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errors.New("client reset") } + +func TestPassthroughCostGate_WidenedReadErrorIs400(t *testing.T) { + e := newGateEnv(t, nil) + body := io.MultiReader(strings.NewReader(`{"pad":"`+strings.Repeat("a", maxModelPeekBytes+1024)), failingReader{}) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", body) + req.ContentLength = -1 + req.Header.Set("Authorization", "Bearer sk-alice") + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400, body=%.200s", rec.Code, rec.Body.String()) + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } +} + +func BenchmarkScanTopLevelModelLargeBody(b *testing.B) { + body := []byte(`{"messages":[` + strings.Repeat(`{"role":"user","content":"hello"},`, 1<<17) + `{}],"model":"gpt-5"}`) + b.SetBytes(int64(len(body))) + for i := 0; i < b.N; i++ { + if m, ok, _, _ := scanTopLevelModel(body); !ok || m != "gpt-5" { + b.Fatal("model not found") + } + } +} diff --git a/passthrough_unpriced_refusal_test.go b/passthrough_unpriced_refusal_test.go new file mode 100644 index 0000000..6fc6699 --- /dev/null +++ b/passthrough_unpriced_refusal_test.go @@ -0,0 +1,119 @@ +package traefikllmgateway + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +const refusalBoundBytes = 512 + +func (e *gateEnv) modelKeys() []string { + st := e.gw.limiter.fallback + st.mu.Lock() + defer st.mu.Unlock() + var keys []string + for k := range st.data { + if strings.HasPrefix(k, "llmgw:"+kindModel+":") { + keys = append(keys, k) + } + } + return keys +} + +func (e *gateEnv) totalR402() int64 { + v, _ := e.gw.limiter.getCounter(totalScopeKind, totalScopeID, metricR402, windowDay, time.Now()) + return v +} + +func longModelBody(i int) string { + return `{"model":"` + strings.Repeat("m", 60_000) + fmt.Sprint(i) + `"}` +} + +func testRefusalNoModelKeys(t *testing.T, key string) { + t.Helper() + e := newGateEnv(t, nil) + const n = 8 + for i := 0; i < n; i++ { + rec := e.post(longModelBody(i), key) + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("request %d: status = %d, want 402, body=%.200s", i, rec.Code, rec.Body.String()) + } + } + if e.upstreamCalls() != 0 { + t.Errorf("upstream calls = %d, want 0", e.upstreamCalls()) + } + if keys := e.modelKeys(); len(keys) != 0 { + t.Errorf("caller-named model counter keys minted: %d (first key length %d)", len(keys), len(keys[0])) + } + if got := e.totalR402(); got != n { + t.Errorf("total r402 = %d, want %d", got, n) + } +} + +func TestPassthroughUnpricedRefusal_NoModelKeysForUncataloguedNames(t *testing.T) { + testRefusalNoModelKeys(t, "sk-alice") +} + +func TestPassthroughUnpricedRefusal_AnonymousCaller(t *testing.T) { + testRefusalNoModelKeys(t, "") +} + +func TestPassthroughUnpricedRefusal_EventLogAndBodyAreBounded(t *testing.T) { + e := newGateEnv(t, nil) + cap := captureStderrStart() + rec := e.post(longModelBody(0), "sk-alice") + logged := captureStderrStop(cap) + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402", rec.Code) + } + if rec.Body.Len() > refusalBoundBytes { + t.Errorf("402 body = %d bytes, want <= %d", rec.Body.Len(), refusalBoundBytes) + } + if len(logged) > refusalBoundBytes { + t.Errorf("log output = %d bytes, want <= %d", len(logged), refusalBoundBytes) + } + events := e.gw.events.ring.snapshot(eventRingCap) + if len(events) == 0 { + t.Fatal("no refusal event recorded") + } + ev := events[0] + if ev.Kind != eventKindUnpriced || ev.Status != http.StatusPaymentRequired { + t.Fatalf("event = kind %q status %d, want unpriced/402", ev.Kind, ev.Status) + } + if len(ev.Model) > refusalBoundBytes || len(ev.Message) > refusalBoundBytes { + t.Errorf("event Model = %d bytes, Message = %d bytes, want each <= %d", len(ev.Model), len(ev.Message), refusalBoundBytes) + } +} + +func TestPassthroughUnpricedRefusal_CataloguedModelKeepsModelCounter(t *testing.T) { + e := newGateEnv(t, nil) + rec := e.post(`{"model":"cat-unpriced"}`, "sk-alice") + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + if got, _ := e.gw.limiter.getCounter(kindModel, "openai/cat-unpriced", metricR402, windowDay, time.Now()); got != 1 { + t.Errorf("model r402 counter = %d, want 1", got) + } +} + +func TestUnifiedUnpricedRefusal_Unchanged(t *testing.T) { + e := newGateEnv(t, nil) + req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", + map[string]any{"model": "cat-unpriced", "messages": []any{map[string]any{"role": "user", "content": "hi"}}}) + rec := httptest.NewRecorder() + e.h.ServeHTTP(rec, req) + if rec.Code != http.StatusPaymentRequired { + t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String()) + } + events := e.gw.events.ring.snapshot(eventRingCap) + if len(events) == 0 || events[0].Model != "openai/cat-unpriced" { + t.Fatalf("event model = %+v, want openai/cat-unpriced", events) + } + if got, _ := e.gw.limiter.getCounter(kindModel, "openai/cat-unpriced", metricR402, windowDay, time.Now()); got != 1 { + t.Errorf("model r402 counter = %d, want 1", got) + } +} diff --git a/routes_passthrough.go b/routes_passthrough.go index 3630443..98b9c64 100644 --- a/routes_passthrough.go +++ b/routes_passthrough.go @@ -50,6 +50,8 @@ const ( sseAccountingTailBytes = 64 << 10 ) +var sseDataMarker = []byte("data:") + // maxModelPeekBytes caps how much of a passthrough request body // peekPassthroughModel reads to find a top-level "model" field: 64KiB // (security review fix, 2026-08-22, round 2). This is deliberately far @@ -75,6 +77,23 @@ const ( // URL-independent "model" field those routes already require. const maxModelPeekBytes = 64 << 10 +// maxRefusedModelChars bounds caller-supplied model text in a refusal's +// log line, event and 402 body. +const maxRefusedModelChars = 128 + +// undeterminedModelLabel stands in for the model of a refusal whose body +// did not yield one. +const undeterminedModelLabel = "(undetermined)" + +// shortenRefusedText cuts caller-supplied text to maxRefusedModelChars +// bytes on a rune boundary, marking the cut. +func shortenRefusedText(s string) string { + if len(s) <= maxRefusedModelChars { + return s + } + return strings.ToValidUTF8(s[:maxRefusedModelChars], "") + "..." +} + // passthroughBinaryContentTypePrefixes lists Content-Type prefixes // peekPassthroughModel treats as genuinely binary and never reads at all // (security review fix, 2026-08-22, round 2): multipart uploads @@ -512,6 +531,10 @@ func (c *cappedAccountingBuffer) Write(p []byte) (int, error) { type sseAccountingBuffer struct { tail []byte head bytes.Buffer + // events counts "data:" markers across all writes, for a completion + // estimate when no usage arrives. A marker split across two writes is + // missed; that is acceptable for an estimate. + events int64 } // Write implements io.Writer. head fills once, like @@ -524,6 +547,7 @@ type sseAccountingBuffer struct { // Chosen over a circular-index ring buffer for simplicity. func (b *sseAccountingBuffer) Write(p []byte) (int, error) { n := len(p) + b.events += int64(bytes.Count(p, sseDataMarker)) if remaining := sseAccountingHeadBytes - b.head.Len(); remaining > 0 { head := p if len(head) > remaining { @@ -822,35 +846,35 @@ func parseSSEUsageChunk(typeName string, raw []byte) (usage, string) { // deadline) distinct from merely reaching the end of a body shorter than // the peek window — the caller maps err to the same 400 runUnified's own // body-read failure uses (routes_unified.go). -func peekPassthroughModel(r *http.Request) (model string, hasModel, truncated bool, err error) { +func peekPassthroughModel(r *http.Request) (string, bool, bool, error) { + model, hasModel, truncated, _, _, err := peekPassthroughModelUpTo(r, maxModelPeekBytes) + return model, hasModel, truncated, err +} + +// peekPassthroughModelUpTo is peekPassthroughModel with an explicit read +// limit. It also reports a duplicate top-level "model" key, and +// unparseable: the body opens a JSON object that the scan could not follow +// to its closing brace (malformed, or cut off by the limit). A later +// duplicate key could hide behind such a point, so the cost gate treats it +// as undeterminable. +func peekPassthroughModelUpTo(r *http.Request, limit int64) (string, bool, bool, bool, bool, error) { if r.Body == nil || isPassthroughBinaryContentType(r.Header.Get("Content-Type")) { - return "", false, false, nil + return "", false, false, false, false, nil } - head := make([]byte, maxModelPeekBytes) - n, readErr := io.ReadFull(r.Body, head) - capped := false - switch readErr { //nolint:errorlint // io.ReadFull returns these sentinels bare, never wrapped — see its own doc comment - case nil: - // Read exactly maxModelPeekBytes: the body has at least that much - // left unread on r.Body, restored below via io.MultiReader — a - // LATER "model" key beyond this window cannot be ruled out unless - // scanTopLevelModel confirms the object closed within it. - capped = true - case io.EOF, io.ErrUnexpectedEOF: - // Body was shorter than the peek window (io.EOF: empty; io. - // ErrUnexpectedEOF: 0 < n < len(head)) — head[:n] IS the whole - // body; r.Body is now exhausted, so appending it below is a - // harmless immediate EOF. No bytes exist beyond what was scanned, - // so "truncated" (in the hidden-duplicate sense) cannot apply. - default: - return "", false, false, readErr + head, readErr := io.ReadAll(io.LimitReader(r.Body, limit)) + if readErr != nil { + return "", false, false, false, false, readErr } - head = head[:n] + // A full read means the body has at least that much; a LATER "model" + // key beyond the window cannot be ruled out unless the scan confirms + // the object closed within it. A shorter read is the whole body. + capped := int64(len(head)) >= limit r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(head), r.Body)) - model, hasModel, closed := scanTopLevelModel(head) - return model, hasModel, capped && !closed, nil + model, hasModel, closed, duplicate := scanTopLevelModel(head) + unparseable := !closed && bytes.HasPrefix(bytes.TrimLeft(head, " \t\r\n"), []byte("{")) + return model, hasModel, capped && !closed, duplicate, unparseable, nil } // scanTopLevelModel walks head — a bounded, possibly-truncated PREFIX of @@ -882,59 +906,67 @@ func peekPassthroughModel(r *http.Request) (model string, hasModel, truncated bo // alone. peekPassthroughModel combines closed with its own knowledge of // whether the read actually hit the byte cap (there is more of r.Body // left unread) to decide whether a "found" model can be trusted. -func scanTopLevelModel(head []byte) (model string, found, closed bool) { +// +// duplicate is true only when a second top-level "model" key was seen: the +// model is then ambiguous, which is different from absent. +func scanTopLevelModel(head []byte) (string, bool, bool, bool) { + var model string + var found bool seenModel := false dec := json.NewDecoder(bytes.NewReader(head)) tok, err := dec.Token() if err != nil { - return "", false, false + return "", false, false, false } if d, ok := tok.(json.Delim); !ok || d != '{' { - return "", false, false + return "", false, false, false } for dec.More() { keyTok, keyErr := dec.Token() if keyErr != nil { - return model, found, false + return model, found, false, false } key, ok := keyTok.(string) if !ok { - return model, found, false // malformed: expected an object key + return model, found, false, false // malformed: expected an object key } - valTok, valErr := dec.Token() - if valErr != nil { - return model, found, false - } - if key == "model" { - // A DUPLICATE top-level "model" fails closed, matching - // extractMultipartModel's errDuplicateModelField rule - // (routes_media.go). Returning on the FIRST occurrence would be - // an authorization bypass: RFC 8259 permits duplicate names and - // every mainstream parser an upstream might use (Go's - // encoding/json, Python json.loads, Node JSON.parse, Ruby, PHP, - // Newtonsoft) resolves them LAST-wins, while this body is - // forwarded byte-for-byte unmodified — so a client could get - // {"model":"allowed","model":"expensive"} authorized against the - // first and executed as the second. Ambiguity is not - // resolvable here without rewriting the client's bytes, so the - // only safe answer is to refuse to answer. - if seenModel { - return "", false, false - } - seenModel = true - if s, isStr := valTok.(string); isStr && s != "" { - model = s - found = true + if key != "model" { + // Decode into RawMessage skips a whole value in one native call; + // stepping its tokens through the interpreter costs ~15x more CPU + // on a multi-MiB body. + var skipped json.RawMessage + if skipErr := dec.Decode(&skipped); skipErr != nil { + return model, found, false, false } continue } - if d, ok := valTok.(json.Delim); ok && (d == '{' || d == '[') { - if skipErr := skipJSONValue(dec); skipErr != nil { - return model, found, false + var rawModel json.RawMessage + if valErr := dec.Decode(&rawModel); valErr != nil { + return model, found, false, false + } + // A DUPLICATE top-level "model" fails closed, matching + // extractMultipartModel's errDuplicateModelField rule + // (routes_media.go). Returning on the FIRST occurrence would be + // an authorization bypass: RFC 8259 permits duplicate names and + // every mainstream parser an upstream might use (Go's + // encoding/json, Python json.loads, Node JSON.parse, Ruby, PHP, + // Newtonsoft) resolves them LAST-wins, while this body is + // forwarded byte-for-byte unmodified — so a client could get + // {"model":"allowed","model":"expensive"} authorized against the + // first and executed as the second. Ambiguity is not + // resolvable here without rewriting the client's bytes, so the + // only safe answer is to refuse to answer. + if seenModel { + return "", false, false, true + } + seenModel = true + if len(rawModel) > 0 && rawModel[0] == '"' { + var s string + if json.Unmarshal(rawModel, &s) == nil && s != "" { + model = s + found = true } } - // Otherwise valTok was a scalar (string/float64/bool/nil) other - // than "model" — nothing further to do; loop to the next key. } // dec.More() returned false above: either the object legitimately // closed, or the decoder simply ran out of bytes searching for the @@ -944,37 +976,12 @@ func scanTopLevelModel(head []byte) (model string, found, closed bool) { // within head. closeTok, err := dec.Token() if err != nil { - return model, found, false + return model, found, false, false } if d, ok := closeTok.(json.Delim); !ok || d != '}' { - return model, found, false + return model, found, false, false } - return model, found, true -} - -// skipJSONValue consumes the remainder of a nested JSON array/object -// value whose opening delimiter dec has already emitted, so -// scanTopLevelModel's own dec.More() call — which reports position in -// whatever object/array dec is CURRENTLY inside — correctly reports the -// outer top-level object's state again once this returns, rather than -// still appearing "inside" the value just skipped. -func skipJSONValue(dec *json.Decoder) error { - depth := 1 - for depth > 0 { - tok, err := dec.Token() - if err != nil { - return err - } - if d, ok := tok.(json.Delim); ok { - switch d { - case '{', '[': - depth++ - case '}', ']': - depth-- - } - } - } - return nil + return model, found, true, false } // allowsPassthroughModel reports whether grp's Models glob authorizes @@ -1275,34 +1282,74 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u // Finding 6 fix (review-routes.md): the same unpriced-model-under-a- // cost-budget refusal runMeteredCall applies to /v1/chat/completions - // (routes_unified.go's own F-1 gate) must also cover native - // passthrough, or a tenant whose cost budget is exhausted on the - // unified routes can keep spending without limit simply by calling - // the identical model through "/{provider}/...". Passthrough has no - // resolved canonical/upstream model id the way the unified route - // does — only whatever "model" the CLIENT's OWN request body names, - // peeked the same bounded way model authorization above already does - // — so this only ever fires when that model is actually determinable - // from the body; a request this gateway cannot price at all (Gemini - // passthrough, whose model id lives in the URL, never the body; a - // binary content type; or a body whose "model" sits beyond the peek - // window) is let through unpriced, exactly as before this fix, - // rather than fail-closed on a value it never had. peekPassthroughModel - // is called again here even when the model-restriction branches above - // already called it (a second bounded, cheap 64KiB re-peek — r.Body - // was already restored via io.MultiReader after that first call) so - // this check runs independently of whether the group restricts - // models at all. + // must cover native passthrough, or a tenant whose cost budget is + // exhausted on the unified routes can keep spending through + // "/{provider}/...". Only the model the client's own body names is + // known here. A first 64KiB peek settles it when the object closes + // there; otherwise the body is read up to min(maxRequestBytes, the + // passthrough cap) and the request is refused (402 missing or repeated + // model, 413 object not closed) rather than served unpriced. Still + // ungated: Gemini passthrough (model in the URL) and a binary content + // type, whose body is never read. var gatedModel string if !g.cfg.AllowUnpricedWithCostBudget && scopesHaveCostBudget(scopes) { - if model, hasModel, _, peekErr := peekPassthroughModel(r); peekErr == nil && hasModel { + model, hasModel, truncated, duplicate, unparseable, peekErr := peekPassthroughModelUpTo(r, maxModelPeekBytes) + widened := peekErr == nil && truncated + if widened { + // The first window cannot settle the model (a later key may add or + // repeat it): look at the rest of the body, up to the smaller of + // maxRequestBytes and the route cap. The body is restored for + // forwarding. + if r.ContentLength > maxPassthroughBytes { + writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request body exceeds the maximum allowed size") + return + } + bound := g.unifiedRequestBytes + if bound <= 0 || bound > maxPassthroughBytes { + bound = maxPassthroughBytes + } + // The scan allocates a few times the body, so it runs inside a + // body-admission slot like the unified routes' decode. + release, admitted := g.acquireBodyAdmission(&statusTrackingWriter{ResponseWriter: w}, writeOAIError) + if !admitted { + return + } + // One byte past the bound tells an over-cap body from one that ends at it. + model, hasModel, truncated, duplicate, unparseable, peekErr = peekPassthroughModelUpTo(r, bound+1) + release() + if peekErr != nil { + writeOAIError(w, http.StatusBadRequest, "invalid_request_error", "cannot read request body") + return + } + // An object that does not close within the bound may repeat the + // model past it, so the model cannot be settled. + if truncated { + writeOAIError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", + "request body exceeds maxRequestBytes before its top-level JSON object ends, so the model cannot be determined for the cost budget; send a smaller body or raise maxRequestBytes") + return + } + } + if peekErr == nil && (duplicate || unparseable || (!hasModel && widened)) { + g.logf("passthrough: refusing a request whose top-level model cannot be determined: a cost budget applies to this caller that cannot be enforced without it") + g.recordUnpricedRefusal(scopes, "", undeterminedModelLabel, providerName, routePassthrough) + writeOAIError(w, http.StatusPaymentRequired, "invalid_request_error", + "the model cannot be determined from the request body (missing or repeated top-level \"model\", or a malformed or unterminated JSON object), so the cost budget that applies to this request cannot be enforced; send the model once, or set allowUnpricedWithCostBudget to serve it unbounded") + return + } + if peekErr == nil && hasModel { canonical := providerName + "/" + model gatedModel = model if !priceKnown(canonical, model, g.cfg.Pricing, g.cfg.ModelMeta) { - g.logf("passthrough: refusing model %q: it has no configured price, and a cost budget applies to this caller that cannot be enforced without one", model) - g.recordUnpricedRefusalEvent(scopes, canonical, providerName, routePassthrough) // F3 hook 5 (item 5, this round) + shown := shortenRefusedText(model) + // Only ids the provider is known to serve may name a counter key. + counterModel := "" + if g.registry.providerHasModel(providerName, model) { + counterModel = canonical + } + g.logf("passthrough: refusing model %q: it has no configured price, and a cost budget applies to this caller that cannot be enforced without one", shown) + g.recordUnpricedRefusal(scopes, counterModel, shortenRefusedText(canonical), providerName, routePassthrough) // F3 hook 5 (item 5, this round) writeOAIError(w, http.StatusPaymentRequired, "invalid_request_error", - fmt.Sprintf("model %q has no configured price, so the cost budget that applies to this request cannot be enforced; add a \"pricing\" entry for it, or set allowUnpricedWithCostBudget to serve it unbounded", model)) + fmt.Sprintf("model %q has no configured price, so the cost budget that applies to this request cannot be enforced; add a \"pricing\" entry for it, or set allowUnpricedWithCostBudget to serve it unbounded", shown)) return } } @@ -1400,7 +1447,12 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u respUsage, respModel = extractPassthroughSSEUsage(adapter.typeName(), providerName, result.sseTee.head.Bytes(), result.sseTee.tailBytes()) } - if respUsage.total() == 0 { + is2xx := result.status >= 200 && result.status < 300 + // An SSE reply that delivered events but no completion usage (no + // include_usage, or a hang-up before the final usage event) must not + // record zero output tokens: one token per data event is the floor. + sseNoCompletion := is2xx && result.isSSE && respUsage.completion == 0 && result.sseTee.events > 0 + if respUsage.total() == 0 || sseNoCompletion { // Verify-core fix (round 4): the estimate below is only a valid // stand-in for real usage when the upstream actually accepted // the request (2xx) AND either the response is SSE (whose usage @@ -1416,17 +1468,25 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u // A 4xx/5xx JSON error body must never be estimated either: the // upstream billed nothing for a rejected request, so neither // should this gateway. - is2xx := result.status >= 200 && result.status < 300 copyAborted := !complete canEstimate := is2xx && (result.isSSE || (result.isJSON && (result.tee.truncated || copyAborted))) - if !canEstimate || result.requestBytes <= 0 { + if !canEstimate || (respUsage.prompt == 0 && result.requestBytes <= 0) { return } - respUsage = usage{prompt: estimatePromptTokens(int64(result.requestBytes)), estimated: true} + if respUsage.prompt == 0 { + respUsage.prompt = estimatePromptTokens(int64(result.requestBytes)) + } + if sseNoCompletion { + respUsage.completion = result.sseTee.events + if respUsage.completion > maxEstimatedPromptTokens { + respUsage.completion = maxEstimatedPromptTokens + } + } + respUsage.estimated = true if respModel == "" { respModel = "unknown/" + providerName } - g.logf("passthrough: usage for provider %q logged as estimated (%d prompt tokens derived from request body size, not the provider's reported usage)", providerName, respUsage.prompt) + g.logf("passthrough: usage for provider %q logged as estimated (%d prompt, %d completion tokens derived from request size and stream events, not the provider's reported usage)", providerName, respUsage.prompt, respUsage.completion) } canonical := providerName + "/" + respModel diff --git a/routes_passthrough_test.go b/routes_passthrough_test.go index 932f19f..a71789e 100644 --- a/routes_passthrough_test.go +++ b/routes_passthrough_test.go @@ -198,7 +198,7 @@ func TestScanTopLevelModel(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - gotModel, gotFound, _ := scanTopLevelModel([]byte(tt.head)) + gotModel, gotFound, _, _ := scanTopLevelModel([]byte(tt.head)) if gotFound != tt.wantFound { t.Errorf("found = %v, want %v", gotFound, tt.wantFound) } @@ -3077,7 +3077,7 @@ func TestScanTopLevelModel_DuplicateModelKeyFailsClosed(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - gotModel, gotFound, gotClosed := scanTopLevelModel([]byte(tc.body)) + gotModel, gotFound, gotClosed, _ := scanTopLevelModel([]byte(tc.body)) if gotModel != tc.wantModel || gotFound != tc.wantFound || gotClosed != tc.wantClosed { t.Fatalf("scanTopLevelModel(%s) = (%q, %v, %v), want (%q, %v, %v)", tc.body, gotModel, gotFound, gotClosed, tc.wantModel, tc.wantFound, tc.wantClosed) @@ -3105,7 +3105,7 @@ func TestScanTopLevelModel_ClosedTracksWindowTruncation(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - _, _, gotClosed := scanTopLevelModel([]byte(tc.body)) + _, _, gotClosed, _ := scanTopLevelModel([]byte(tc.body)) if gotClosed != tc.wantClosed { t.Errorf("scanTopLevelModel(%s) closed = %v, want %v", tc.body, gotClosed, tc.wantClosed) }