From 9115a6eb2c3366a3e2b766ae10ce1054ecf2236a Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 27 Nov 2026 14:45:30 -0400 Subject: [PATCH] fix(inference): report provider errors and cut-off cloud chat streams Co-Authored-By: Claude Sonnet 5.5 --- internal/inference/openai.go | 55 +++++++++++++++++-- .../inference/openai_stream_error_test.go | 50 +++++++++++++++++ 2 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 internal/inference/openai_stream_error_test.go diff --git a/internal/inference/openai.go b/internal/inference/openai.go index e1e6d123..5e7cc4d9 100644 --- a/internal/inference/openai.go +++ b/internal/inference/openai.go @@ -343,6 +343,7 @@ func (e *openAIEngine) handleStreamWithCacheUsage(body io.Reader, onToken TokenC scanner := bufio.NewScanner(body) var full strings.Builder reasoningOpen := false + sawData, finished := false, false for scanner.Scan() { line := scanner.Text() @@ -353,20 +354,29 @@ func (e *openAIEngine) handleStreamWithCacheUsage(body io.Reader, onToken TokenC if data == "" { continue } + sawData = true if data == "[DONE]" { - if reasoningOpen { - full.WriteString("") - onToken("") - } + finished = true break } + // Providers report failures after the 200 response as an error event. + if msg := openAIStreamErrorMessage(data); msg != "" { + return full.String(), fmt.Errorf("provider stream error: %s", msg) + } + var chatResp api.OpenAIChatResponse if err := json.Unmarshal([]byte(data), &chatResp); err != nil { continue } recordOpenAICacheUsage(collector, chatResp.Usage) reportOpenAIGenerationUsage(onUsage, chatResp.Usage) + // Some providers end the stream after finish_reason without sending [DONE]. + if len(chatResp.Choices) > 0 { + if reason := chatResp.Choices[0].FinishReason; reason != nil && *reason != "" { + finished = true + } + } if len(chatResp.Choices) == 0 || chatResp.Choices[0].Delta == nil { continue } @@ -393,7 +403,42 @@ func (e *openAIEngine) handleStreamWithCacheUsage(body io.Reader, onToken TokenC } } - return full.String(), scanner.Err() + if err := scanner.Err(); err != nil { + return full.String(), err + } + // A stream that started but never finished was cut off. + if sawData && !finished { + return full.String(), io.ErrUnexpectedEOF + } + if reasoningOpen { + full.WriteString("") + onToken("") + } + return full.String(), nil +} + +// openAIStreamErrorMessage returns the message carried by an in-stream error +// payload, or "" when data is a regular chunk. +func openAIStreamErrorMessage(data string) string { + var payload struct { + Error any `json:"error"` + } + if err := json.Unmarshal([]byte(data), &payload); err != nil { + return "" + } + switch v := payload.Error.(type) { + case string: + return v + case map[string]any: + if msg, ok := v["message"].(string); ok && msg != "" { + return msg + } + if len(v) > 0 { + raw, _ := json.Marshal(v) + return string(raw) + } + } + return "" } func (e *openAIEngine) handleJSONResponse(body io.Reader) (string, error) { diff --git a/internal/inference/openai_stream_error_test.go b/internal/inference/openai_stream_error_test.go new file mode 100644 index 00000000..f74f2267 --- /dev/null +++ b/internal/inference/openai_stream_error_test.go @@ -0,0 +1,50 @@ +package inference + +import ( + "errors" + "io" + "strings" + "testing" +) + +func TestOpenAIEngineStreamFailures(t *testing.T) { + const partial = "data: {\"choices\":[{\"delta\":{\"content\":\"hel\"}}]}\n\n" + tests := []struct { + name string + body string + wantErr string + }{ + {"error object", partial + "data: {\"error\":{\"message\":\"upstream overloaded\"}}\n\ndata: [DONE]\n\n", "upstream overloaded"}, + {"error string", "data: {\"error\":\"quota exceeded\"}\n\n", "quota exceeded"}, + {"cut connection", partial, io.ErrUnexpectedEOF.Error()}, + {"finish_reason without DONE", partial + "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", ""}, + {"finish_reason without delta", partial + "data: {\"choices\":[{\"finish_reason\":\"length\"}]}\n\n", ""}, + {"null error field", "data: {\"error\":null,\"choices\":[{\"delta\":{\"content\":\"hel\"}}]}\n\ndata: [DONE]\n\n", ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := &openAIEngine{} + _, err := e.handleStream(strings.NewReader(tt.body), func(string) {}) + if tt.wantErr == "" { + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("error = %v, want %q", err, tt.wantErr) + } + if tt.name == "cut connection" && !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("error = %v, want io.ErrUnexpectedEOF", err) + } + }) + } +} + +func TestOpenAIEngineStreamClosesThinkWithoutDone(t *testing.T) { + body := "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"hm\"},\"finish_reason\":\"length\"}]}\n\n" + got, err := (&openAIEngine{}).handleStream(strings.NewReader(body), func(string) {}) + if err != nil || got != "hm" { + t.Fatalf("got %q, %v", got, err) + } +}