package traefikllmgateway import ( "context" "net/http" "net/http/httptest" "strings" "testing" "time" ) // cancelAfterWriter cancels the request context once it has received n writes, as a client hanging up mid-stream does. type cancelAfterWriter struct { *recordingWriter cancel context.CancelFunc n int } func (c *cancelAfterWriter) Write(b []byte) (int, error) { n, err := c.recordingWriter.Write(b) if len(c.events) >= c.n { c.cancel() } return n, err } func TestOpenAIStreamClientCancel_BillsEstimatedCompletion(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") w.WriteHeader(http.StatusOK) fl, _ := w.(http.Flusher) for _, f := range openAIContentFrames(200) { if _, err := w.Write([]byte(f)); err != nil { return } fl.Flush() select { case <-r.Context().Done(): return case <-time.After(5 * time.Millisecond): } } })) 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"}}} ctx, cancel := context.WithCancel(context.Background()) defer cancel() req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice", body).WithContext(ctx) w := &cancelAfterWriter{recordingWriter: newRecordingWriter(), n: 6, cancel: cancel} out := captureStderr(t, func() { gw.ServeHTTP(w, req) }) in, tokOut := aliceTokens(gw) if in <= 0 || tokOut <= 0 { t.Fatalf("tokin/tokout = %d/%d, want both > 0 after a client cancel that followed forwarded output", in, tokOut) } if !strings.Contains(out, "logged as estimated (prompt tokens derived from request body size, completion tokens from streamed output size") { t.Errorf("the estimated flag did not reach the accounting step; log = %q", out) } }