From 932b459257c6d0a1de18a9c43f1a0803314af9bb Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Sun, 29 Nov 2026 00:21:35 +0000 Subject: [PATCH] fix(billing): estimate completion when a stream ends before its usage A streaming unified request that failed after output reached the client recorded zero completion tokens. The gateway now estimates them from the forwarded output bytes and marks the usage as estimated. Streams that report usage, and streams that end cleanly, are unchanged. --- README.md | 9 +- messages_stream.go | 4 +- provider_anthropic.go | 4 +- provider_openai.go | 55 +++++++++- routes_unified.go | 11 ++ stream_hangup_billing_test.go | 190 ++++++++++++++++++++++++++++++++++ translate_anthropic.go | 19 ++++ 7 files changed, 283 insertions(+), 9 deletions(-) create mode 100644 stream_hangup_billing_test.go diff --git a/README.md b/README.md index 028aaa5..062ab18 100644 --- a/README.md +++ b/README.md @@ -1645,9 +1645,12 @@ model id) and per alias (`aliases[].modelMeta`) — see `ceil(request-body-bytes / 4)` counted as prompt tokens, no completion estimate — and marks it `estimated`. Estimated usage therefore lands entirely in the `tokin` counter below; `tokout` never moves for an - estimated request. A **streaming** unified-route response with no usage - is logged and the request itself is still counted, but no token - estimate is applied. + estimated request. A **streaming** unified-route response that ends + cleanly with no usage is logged and the request itself is still counted, + but no token estimate is applied. A streaming response that fails or is + cancelled after output reached the client, and reports no completion + usage, records an estimated `tokout` of `ceil(forwarded-output-bytes / 4)` + (text, reasoning and tool-call argument bytes) and is marked `estimated`. - **Tokens are tracked in two directions**: every prompt token increments a `tokin` counter, every completion token a separate `tokout` counter — the same split the admin usage API and usage-history API both expose diff --git a/messages_stream.go b/messages_stream.go index 3d2800e..004ab68 100644 --- a/messages_stream.go +++ b/messages_stream.go @@ -400,9 +400,9 @@ func relayAnthropicMessagesStream(w http.ResponseWriter, body io.Reader, model s return st.usage(), nil } if relayed { - return st.usage(), fmt.Errorf("%w: %w", errStreamErrorRelayed, err) + return st.usageOnAbort(), fmt.Errorf("%w: %w", errStreamErrorRelayed, err) } - return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err) + return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, err) } // writeEvent writes one frame with an "event:" line ahead of the data, the diff --git a/provider_anthropic.go b/provider_anthropic.go index 660d180..876179a 100644 --- a/provider_anthropic.go +++ b/provider_anthropic.go @@ -224,11 +224,11 @@ func (a *anthropicAdapter) forwardStream(w http.ResponseWriter, body io.Reader, return terr }) if err != nil { - return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, err) + return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, err) } if clientAskedUsage { if werr := sw.writeData(st.usageChunk()); werr != nil { - return st.usage(), fmt.Errorf("%w: stream: %w", errUpstream, werr) + return st.usageOnAbort(), fmt.Errorf("%w: stream: %w", errUpstream, werr) } } sw.writeDone() diff --git a/provider_openai.go b/provider_openai.go index d766e2e..7712ebb 100644 --- a/provider_openai.go +++ b/provider_openai.go @@ -133,8 +133,53 @@ type promptTokenDetails struct { // chatCompletion's streaming path needs: whether it carries content // (Choices non-empty) and, on the final chunk, its usage totals. type chatStreamChunk struct { - Usage *chatStreamUsage `json:"usage"` - Choices []json.RawMessage `json:"choices"` + Usage *chatStreamUsage `json:"usage"` + Choices []chatStreamChoice `json:"choices"` +} + +// chatStreamChoice carries only the delta fields forwardStream sizes for an +// abort-time completion estimate. +type chatStreamChoice struct { + Delta chatStreamDelta `json:"delta"` +} + +// chatStreamDelta holds raw JSON so a non-string value cannot fail the +// decode and drop the chunk's usage. +type chatStreamDelta struct { + Content json.RawMessage `json:"content"` + ReasoningContent json.RawMessage `json:"reasoning_content"` + Reasoning json.RawMessage `json:"reasoning"` + ToolCalls []chatStreamToolDelta `json:"tool_calls"` +} + +type chatStreamToolDelta struct { + Function chatStreamToolFunction `json:"function"` +} + +type chatStreamToolFunction struct { + Arguments json.RawMessage `json:"arguments"` +} + +// rawTextLen is the byte length of a raw JSON string value without its quotes; 0 for null or absent. +func rawTextLen(raw json.RawMessage) int64 { + n := int64(len(raw)) + if n < 3 || raw[0] != '"' { + return 0 + } + return n - 2 +} + +// chunkOutputBytes sums the forwarded output text of every choice in c. +func chunkOutputBytes(c *chatStreamChunk) int64 { + var n int64 + for i := range c.Choices { + d := &c.Choices[i].Delta + n += rawTextLen(d.Content) + rawTextLen(d.ReasoningContent) + rawTextLen(d.Reasoning) + for j := range d.ToolCalls { + n += rawTextLen(d.ToolCalls[j].Function.Arguments) + } + } + return n } // chatCompletion implements providerAdapter. @@ -287,6 +332,7 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli var u usage finish := "" hasOutput := false + var outBytes int64 sawDone := false @@ -305,6 +351,7 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli var chunk chatStreamChunk hasUsage := json.Unmarshal(ev.data, &chunk) == nil && chunk.Usage != nil + outBytes += chunkOutputBytes(&chunk) if hasUsage { u.prompt = chunk.Usage.PromptTokens u.completion = chunk.Usage.CompletionTokens @@ -324,6 +371,10 @@ func (a *openaiAdapter) forwardStream(w http.ResponseWriter, body io.Reader, cli // u carries whatever usage was already captured before the stream // broke — a usage chunk that arrived, then a dropped connection, // must not report as zero and get treated as an unbilled request. + if u.completion == 0 && outBytes > 0 { + u.completion = estimateCompletionTokens(outBytes) + u.estimated = true + } return u, fmt.Errorf("%w: stream: %w", errUpstream, err) } return withAnswerFlags(u, finish, hasOutput), nil diff --git a/routes_unified.go b/routes_unified.go index 4d60461..f33b767 100644 --- a/routes_unified.go +++ b/routes_unified.go @@ -715,6 +715,11 @@ func (g *Gateway) runMeteredCall(sw *statusTrackingWriter, r *http.Request, scop // only when it is genuinely zero (a non-streaming failure), never // skipped, so a later successful candidate's real usage is never // silently doubled with a phantom first entry either. + if streaming && callErr != nil && sw.wroteHeader && result.prompt == 0 && result.total() != 0 { + // An estimated completion must not suppress the prompt estimate. + result.prompt = estimatePromptTokens(int64(len(body))) + result.estimated = true + } if result.total() == 0 { switch { case streaming && callErr != nil && sw.wroteHeader: @@ -1576,6 +1581,12 @@ func reserveTokensFor(bodyBytes int64) int64 { // window would legitimately hold. const maxEstimatedPromptTokens = 1 << 20 +// estimateCompletionTokens estimates completion tokens from forwarded output +// bytes, with the same rule and cap as estimatePromptTokens. +func estimateCompletionTokens(outBytes int64) int64 { + return estimatePromptTokens(outBytes) +} + // estimatePromptTokens estimates prompt tokens as one per four body bytes, // rounded up and capped at maxEstimatedPromptTokens. func estimatePromptTokens(bodyBytes int64) int64 { diff --git a/stream_hangup_billing_test.go b/stream_hangup_billing_test.go new file mode 100644 index 0000000..e9c8b10 --- /dev/null +++ b/stream_hangup_billing_test.go @@ -0,0 +1,190 @@ +package traefikllmgateway + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// hangupServer writes frames, flushes, then closes the connection without a terminator. +func hangupServer(t *testing.T, contentType string, frames []string) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + w.WriteHeader(http.StatusOK) + fl, ok := w.(http.Flusher) + if !ok { + t.Error("upstream writer cannot flush") + return + } + for _, f := range frames { + _, _ = w.Write([]byte(f)) + fl.Flush() + } + hj, ok := w.(http.Hijacker) + if !ok { + t.Error("upstream writer cannot hijack") + return + } + if conn, _, err := hj.Hijack(); err == nil { + _ = conn.Close() + } + })) +} + +func newStreamBillingGateway(t *testing.T, providerType, baseURL, model string) *Gateway { + t.Helper() + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{ + "up": {Type: providerType, BaseURL: baseURL, APIKey: "k", Models: []string{model}}, + } + 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") + } + return gw +} + +func aliceTokens(gw *Gateway) (int64, int64) { + in, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now()) + out, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now()) + return in, out +} + +func openAIContentFrames(n int) []string { + frames := make([]string, 0, n) + for i := 0; i < n; i++ { + frames = append(frames, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"delta":{"content":"hello world, this is a chunk of text "}}]}`+"\n\n") + } + return frames +} + +func anthropicFrames(deltas int, withMessageDelta bool) []string { + frames := []string{ + "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"usage\":{\"input_tokens\":100}}}\n\n", + "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n", + } + for i := 0; i < deltas; i++ { + frames = append(frames, "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hello world, this is a chunk of text \"}}\n\n") + } + if withMessageDelta { + frames = append(frames, + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5000}}\n\n", + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n") + } + return frames +} + +func TestOpenAIStreamHangup_BillsEstimatedCompletion(t *testing.T) { + srv := hangupServer(t, "text/event-stream", openAIContentFrames(12)) + defer srv.Close() + gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test") + body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + in, out := aliceTokens(gw) + if in <= 0 || out <= 0 { + t.Fatalf("tokin/tokout = %d/%d, want both > 0 after a hang-up that followed forwarded output", in, out) + } +} + +func TestOpenAIStreamFullRead_BillsReportedUsage(t *testing.T) { + frames := append(openAIContentFrames(3), + `data: {"id":"c1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":3000}}`+"\n\n", + "data: [DONE]\n\n") + srv := hangupServer(t, "text/event-stream", frames) + defer srv.Close() + gw := newStreamBillingGateway(t, providerTypeOpenAI, srv.URL, "gpt-test") + body := map[string]any{"model": "gpt-test", "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + if in, out := aliceTokens(gw); in != 9 || out != 3000 { + t.Fatalf("tokin/tokout = %d/%d, want 9/3000", in, out) + } +} + +func TestAnthropicChatStreamHangup_BillsEstimatedCompletion(t *testing.T) { + srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false)) + defer srv.Close() + gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test") + body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + in, out := aliceTokens(gw) + if in != 100 || out <= 0 { + t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out) + } +} + +func TestAnthropicMessagesRelayHangup_BillsEstimatedCompletion(t *testing.T) { + srv := hangupServer(t, "text/event-stream", anthropicFrames(20, false)) + defer srv.Close() + gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test") + body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + gw.ServeHTTP(httptest.NewRecorder(), newMessagesRequest(t, body, "x-api-key", "sk-alice")) + in, out := aliceTokens(gw) + if in != 100 || out <= 0 { + t.Fatalf("tokin/tokout = %d/%d, want 100 / >0", in, out) + } +} + +func TestAnthropicStreamFullRead_BillsReportedUsage(t *testing.T) { + srv := hangupServer(t, "text/event-stream", anthropicFrames(3, true)) + defer srv.Close() + gw := newStreamBillingGateway(t, providerTypeAnthropic, srv.URL, "claude-test") + body := map[string]any{"model": "claude-test", "stream": true, "max_tokens": 100, "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + gw.ServeHTTP(newRecordingWriter(), newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body)) + if in, out := aliceTokens(gw); in != 100 || out != 5000 { + t.Fatalf("tokin/tokout = %d/%d, want 100/5000", in, out) + } +} + +func TestAnthropicStreamState_UsageOnAbortKeepsReportedCompletion(t *testing.T) { + st := newAnthropicStreamState("m", 1) + for _, ev := range []sseEvent{ + {event: "message_start", data: []byte(`{"message":{"id":"x","usage":{"input_tokens":10}}}`)}, + {event: "content_block_delta", data: []byte(`{"index":0,"delta":{"type":"text_delta","text":"abcdefgh"}}`)}, + } { + if _, err := st.translate(ev); err != nil { + t.Fatal(err) + } + } + if u := st.usageOnAbort(); u.completion != 2 || !u.estimated { + t.Fatalf("before message_delta: completion=%d estimated=%v, want 2/true", u.completion, u.estimated) + } + if _, err := st.translate(sseEvent{event: "message_delta", data: []byte(`{"delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":77}}`)}); err != nil { + t.Fatal(err) + } + if u := st.usageOnAbort(); u.completion != 77 || u.estimated { + t.Fatalf("after message_delta: completion=%d estimated=%v, want 77/false", u.completion, u.estimated) + } +} + +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { return 0, errors.New("hang-up") } + +// Pin only: Gemini reports usageMetadata on every chunk, so an abort keeps the last one. +func TestGeminiStreamHangup_PinsLastUsageMetadata(t *testing.T) { + a, err := newGeminiAdapter("p1", "http://unused", "k") + if err != nil { + t.Fatal(err) + } + frame := fmt.Sprintf("data: %s\n\n", `{"candidates":[{"content":{"role":"model","parts":[{"text":"hello there"}]}}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":4}}`) + u, err := a.forwardStream(httptest.NewRecorder(), io.MultiReader(strings.NewReader(frame), failingReader{}), "g", false) + if err == nil { + t.Fatal("want a stream error") + } + if u.prompt != 10 || u.completion != 4 { + t.Fatalf("usage = %d/%d, want 10/4 (report to integrator if completion is 0)", u.prompt, u.completion) + } +} diff --git a/translate_anthropic.go b/translate_anthropic.go index ae46c34..b385c79 100644 --- a/translate_anthropic.go +++ b/translate_anthropic.go @@ -745,6 +745,8 @@ type anthropicStreamState struct { created int64 nextToolOrdinal int hasOutput bool + // outBytes counts forwarded delta text, for the estimate when the stream aborts before message_delta. + outBytes int64 } // newAnthropicStreamState returns an anthropicStreamState for one @@ -763,6 +765,17 @@ func (st *anthropicStreamState) usage() usage { return withAnswerFlags(st.u, st.finish, st.hasOutput) } +// usageOnAbort is usage() for a stream that ended in an error: with no +// reported completion it estimates one from the output already forwarded. +func (st *anthropicStreamState) usageOnAbort() usage { + u := st.usage() + if u.completion == 0 && st.outBytes > 0 { + u.completion = estimateCompletionTokens(st.outBytes) + u.estimated = true + } + return u +} + // chunk builds one OpenAI-shaped "chat.completion.chunk" payload carrying // delta, and finishReason as its choices[0].finish_reason — nil for the // JSON null every non-terminal chunk carries. @@ -940,6 +953,7 @@ type anthropicContentBlockDeltaPayload struct { Type string `json:"type"` Text string `json:"text"` PartialJSON string `json:"partial_json"` + Thinking string `json:"thinking"` } `json:"delta"` Index int `json:"index"` } @@ -1033,11 +1047,16 @@ func (st *anthropicStreamState) translate(ev sseEvent) ([][]byte, error) { } switch p.Delta.Type { case "text_delta": + st.outBytes += int64(len(p.Delta.Text)) if p.Delta.Text != "" { st.hasOutput = true } return [][]byte{st.content.build(p.Delta.Text)}, nil + case "thinking_delta": + st.outBytes += int64(len(p.Delta.Thinking)) + return nil, nil case "input_json_delta": + st.outBytes += int64(len(p.Delta.PartialJSON)) ordinal, ok := st.toolOrdinals[p.Index] if !ok { // Defensive: an input_json_delta for a content-block index