diff --git a/internal/api/middleware/request_logging_test.go b/internal/api/middleware/request_logging_test.go index 12ab0d5cad..9e3a3c380b 100644 --- a/internal/api/middleware/request_logging_test.go +++ b/internal/api/middleware/request_logging_test.go @@ -956,3 +956,32 @@ func TestDecodeCapturedZstdRefusesAnOversizedWindow(t *testing.T) { t.Fatalf("an oversized window must leave the raw bytes, got %q", got) } } + +func TestResponseWriterLogOnErrorOnlyCapsSingleLargeWrite(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader("{}")) + + logger := logging.NewFileRequestLogger(false, t.TempDir(), "", 10) + wrapper := NewResponseWriterWrapper(c.Writer, logger, &RequestInfo{ + URL: "/v1/messages", + Method: http.MethodPost, + }) + wrapper.logOnErrorOnly = true + + largePayload := bytes.Repeat([]byte("a"), 4<<20) // 4 MiB + if _, err := wrapper.Write(largePayload); err != nil { + t.Fatalf("Write failed: %v", err) + } + if wrapper.body.Len() != maxDeferredErrorStreamBodyBytes { + t.Fatalf("wrapper.body.Len() = %d, want %d", wrapper.body.Len(), maxDeferredErrorStreamBodyBytes) + } + + if _, err := wrapper.WriteString("extra"); err != nil { + t.Fatalf("WriteString failed: %v", err) + } + if wrapper.body.Len() != maxDeferredErrorStreamBodyBytes { + t.Fatalf("wrapper.body.Len() after WriteString = %d, want %d", wrapper.body.Len(), maxDeferredErrorStreamBodyBytes) + } +} diff --git a/internal/api/middleware/response_writer.go b/internal/api/middleware/response_writer.go index aa4a336f78..d934a7f33b 100644 --- a/internal/api/middleware/response_writer.go +++ b/internal/api/middleware/response_writer.go @@ -119,9 +119,7 @@ func (w *ResponseWriterWrapper) Write(data []byte) (int, error) { return n, err } - if w.shouldBufferResponseBody() { - w.body.Write(data) - } + w.bufferResponseBodyBytes(data) return n, err } @@ -163,6 +161,8 @@ func (w *ResponseWriterWrapper) closeConnectionIfRequestBodyUnconsumed(statusCod } } +const maxDeferredErrorStreamBodyBytes = 256 << 10 // 256 KiB + func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool { if w.logger != nil && w.logger.IsEnabled() { return true @@ -177,10 +177,53 @@ func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool { if status >= http.StatusBadRequest { return true } - const maxDeferredErrorStreamBodyBytes = 256 << 10 // 256 KiB return w.body != nil && w.body.Len() < maxDeferredErrorStreamBodyBytes } +func (w *ResponseWriterWrapper) bufferResponseBodyBytes(data []byte) { + if len(data) == 0 || w.body == nil || !w.shouldBufferResponseBody() { + return + } + if w.logger != nil && w.logger.IsEnabled() { + w.body.Write(data) + return + } + if w.effectiveStatusCode() >= http.StatusBadRequest { + w.body.Write(data) + return + } + remaining := maxDeferredErrorStreamBodyBytes - w.body.Len() + if remaining <= 0 { + return + } + if len(data) > remaining { + data = data[:remaining] + } + w.body.Write(data) +} + +func (w *ResponseWriterWrapper) bufferResponseBodyString(data string) { + if len(data) == 0 || w.body == nil || !w.shouldBufferResponseBody() { + return + } + if w.logger != nil && w.logger.IsEnabled() { + w.body.WriteString(data) + return + } + if w.effectiveStatusCode() >= http.StatusBadRequest { + w.body.WriteString(data) + return + } + remaining := maxDeferredErrorStreamBodyBytes - w.body.Len() + if remaining <= 0 { + return + } + if len(data) > remaining { + data = data[:remaining] + } + w.body.WriteString(data) +} + // WriteString wraps the underlying ResponseWriter's WriteString method to capture response data. // Some handlers (and fmt/io helpers) write via io.StringWriter; without this override, those writes // bypass Write() and would be missing from request logs. @@ -204,9 +247,7 @@ func (w *ResponseWriterWrapper) WriteString(data string) (int, error) { return n, err } - if w.shouldBufferResponseBody() { - w.body.WriteString(data) - } + w.bufferResponseBodyString(data) return n, err } diff --git a/internal/runtime/executor/claude_executor_fast_error.go b/internal/runtime/executor/claude_executor_fast_error.go index 53a6855695..a37feea8e0 100644 --- a/internal/runtime/executor/claude_executor_fast_error.go +++ b/internal/runtime/executor/claude_executor_fast_error.go @@ -38,7 +38,16 @@ func (e *claudeFastRequestError) Unwrap() error { } func (e *claudeFastRequestError) StatusCode() int { - if e == nil || (e.status >= http.StatusOK && e.status < http.StatusMultipleChoices) { + if e == nil { + return 0 + } + if e.status <= 0 || (e.status >= http.StatusOK && e.status < http.StatusMultipleChoices) { + var statusCoder interface{ StatusCode() int } + if errors.As(e.cause, &statusCoder) && statusCoder != nil { + if code := statusCoder.StatusCode(); code > 0 { + return code + } + } return 0 } return e.status diff --git a/internal/runtime/executor/claude_executor_stop_reasons_test.go b/internal/runtime/executor/claude_executor_stop_reasons_test.go index 912d331933..da36e40f5e 100644 --- a/internal/runtime/executor/claude_executor_stop_reasons_test.go +++ b/internal/runtime/executor/claude_executor_stop_reasons_test.go @@ -2,6 +2,7 @@ package executor import ( "context" + "errors" "io" "net/http" "net/http/httptest" @@ -181,3 +182,15 @@ func TestClaudeExecutorChatRefusalStaysSuccessful(t *testing.T) { t.Fatalf("finish_reason = %q: %s", got, resp.Payload) } } + +func TestWrapClaudeFastRequestErrorPreservesClassifiedStatusCode(t *testing.T) { + inner := statusErr{code: http.StatusBadRequest, msg: "claude refusal (cyber): blocked"} + wrapped := wrapClaudeFastRequestError(true, http.StatusOK, inner) + var statusCoder interface{ StatusCode() int } + if !errors.As(wrapped, &statusCoder) || statusCoder == nil { + t.Fatalf("expected wrapped error to implement StatusCode()") + } + if got := statusCoder.StatusCode(); got != http.StatusBadRequest { + t.Fatalf("statusCoder.StatusCode() = %d, want %d", got, http.StatusBadRequest) + } +}