From cf7267e9701ee382a5ff59b8fd89d981bbefd45c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Banaszewski?= Date: Thu, 26 Nov 2026 17:15:23 +0100 Subject: [PATCH] feat: add response processing to AI Gateway proxy mode for Anthropic (#32628) Add recording for blocking Anthropic Messages responses in AI Gateway proxy mode. Response facts and interception completion are recorded asynchronously under a shared timeout. Shutdown waits for recording to finish. Upstream error responses are classified and recorded in the interception end record. Restored early cancellation replies for stalled HTTP/1 requests that were removed by mistake. > Generated with Coder Agents. --- aibridge/extractors/extractors.go | 50 +++ aibridge/extractors/messages.go | 214 +++++++++- aibridge/extractors/messages_internal_test.go | 71 ---- aibridge/extractors/messages_test.go | 388 ++++++++++++++++++ .../integrationtest/bridge_internal_test.go | 176 ++++++-- .../interception_error_internal_test.go | 16 +- .../internal/integrationtest/setupbridge.go | 10 +- aibridge/provider/anthropic.go | 2 +- aibridge/x/proxy/handler.go | 175 ++++++-- aibridge/x/proxy/handler_internal_test.go | 117 +++++- aibridge/x/proxy/outcomes_internal_test.go | 64 +-- enterprise/coderd/aibridge_test.go | 110 +++++ 12 files changed, 1166 insertions(+), 227 deletions(-) delete mode 100644 aibridge/extractors/messages_internal_test.go create mode 100644 aibridge/extractors/messages_test.go diff --git a/aibridge/extractors/extractors.go b/aibridge/extractors/extractors.go index 5ae27e9dec2..4871d8f5f21 100644 --- a/aibridge/extractors/extractors.go +++ b/aibridge/extractors/extractors.go @@ -3,11 +3,61 @@ package extractors import ( + "context" + "mime" + "net/http" + "strings" + + "golang.org/x/xerrors" + "github.com/coder/coder/v2/aibridge/recorder" ) // Extractor provides a way to extract facts from a request and response body. +// It is request-scoped. Each phase runs at most once, request first. type Extractor interface { // ExtractRequest adds Model and CorrelatingToolCallID to the start record. ExtractRequest(reqBody []byte, start *recorder.InterceptionRecord) error + // ExtractResponse returns the recording facts of the final upstream + // response. body is the completed capture, partial if capture failed, and + // nil if no response was received, which yields an empty result. On error, + // the result holds the facts extracted before the failure. + ExtractResponse(ctx context.Context, statusCode int, header http.Header, body []byte) (ResponseResult, error) +} + +// ResponseResult holds the facts extracted from a response. The caller stamps +// records with the interception ID and creation time. +type ResponseResult struct { + // Prompt is nil when the request had no prompt or the response has no + // message ID. + Prompt *recorder.PromptUsageRecord + Tokens []recorder.TokenUsageRecord + Tools []recorder.ToolUsageRecord + Thoughts []recorder.ModelThoughtRecord + + // ResponseError is a failure reported by the response or detected in its + // protocol. It is not an extraction or persistence failure. + ResponseError error +} + +// streamingFromContentType reports whether the response content type declares +// a streamed (SSE) or blocking (JSON) response. It returns an error when the +// content type is missing, malformed, or unsupported. +func streamingFromContentType(header http.Header) (streaming bool, err error) { + contentType := header.Get("Content-Type") + if contentType == "" { + return false, xerrors.New("missing response content type") + } + mediaType, _, err := mime.ParseMediaType(contentType) + if err != nil { + return false, xerrors.Errorf("parse response content type %q: %w", contentType, err) + } + switch { + case mediaType == "text/event-stream": + return true, nil + case mediaType == "application/json", strings.HasSuffix(mediaType, "+json"): + return false, nil + default: + return false, xerrors.Errorf("unsupported response content type %q", contentType) + } } diff --git a/aibridge/extractors/messages.go b/aibridge/extractors/messages.go index ce20650cc96..52709a5b75a 100644 --- a/aibridge/extractors/messages.go +++ b/aibridge/extractors/messages.go @@ -1,15 +1,61 @@ package extractors import ( + "context" + "encoding/json" + "errors" + "net/http" + "strconv" + + "github.com/anthropics/anthropic-sdk-go" + "github.com/anthropics/anthropic-sdk-go/shared/constant" + "github.com/tidwall/gjson" "golang.org/x/xerrors" + "cdr.dev/slog/v3" "github.com/coder/coder/v2/aibridge/intercept/messages" "github.com/coder/coder/v2/aibridge/recorder" ) +const ( + messagesRespPathID = "id" + messagesRespPathModel = "model" + messagesRespPathContent = "content" + messagesRespPathUsage = "usage" + + // Fields relative to a content block. + messagesRespFieldID = "id" + messagesRespFieldType = "type" + messagesRespFieldName = "name" + messagesRespFieldInput = "input" + messagesRespFieldThinking = "thinking" + + // Paths relative to the usage object. + messagesUsagePathInputTokens = "input_tokens" + messagesUsagePathOutputTokens = "output_tokens" + messagesUsagePathCacheReadInputTokens = "cache_read_input_tokens" + messagesUsagePathCacheWriteInputTokens = "cache_creation_input_tokens" + messagesUsagePathServiceTier = "service_tier" + messagesUsagePathServerToolUse = "server_tool_use" + messagesUsagePathCacheCreation = "cache_creation" + messagesUsagePathWebSearchRequests = "server_tool_use.web_search_requests" + messagesUsagePathEphemeral1hInput = "cache_creation.ephemeral_1h_input_tokens" + messagesUsagePathEphemeral5mInput = "cache_creation.ephemeral_5m_input_tokens" +) + +// Content block types. +var ( + messagesRespTypeThinking = string(constant.ValueOf[constant.Thinking]()) + messagesRespTypeToolUse = string(constant.ValueOf[constant.ToolUse]()) + messagesRespTypeServerToolUse = string(constant.ValueOf[constant.ServerToolUse]()) + messagesRespTypeMCPToolUse = string(constant.ValueOf[constant.MCPToolUse]()) +) + // messagesExtractor extracts recording facts from Anthropic Messages API // traffic. type messagesExtractor struct { + logger slog.Logger + // prompt is the last user prompt in the request, nil when absent. It is // recorded once response message ID is known (PromptUsageRecord.MsgID). prompt *string @@ -19,8 +65,8 @@ type messagesExtractor struct { } // NewMessages returns an [Extractor] for one Anthropic Messages API request. -func NewMessages() Extractor { - return &messagesExtractor{} +func NewMessages(logger slog.Logger) Extractor { + return &messagesExtractor{logger: logger} } func (e *messagesExtractor) ExtractRequest(reqBody []byte, start *recorder.InterceptionRecord) error { @@ -41,3 +87,167 @@ func (e *messagesExtractor) ExtractRequest(reqBody []byte, start *recorder.Inter } return nil } + +func (e *messagesExtractor) ExtractResponse(ctx context.Context, statusCode int, header http.Header, body []byte) (ResponseResult, error) { + // No upstream response was accepted, so there is nothing to extract. + if body == nil { + return ResponseResult{}, nil + } + // Error responses carry an error envelope whatever the request asked for. + if statusCode >= http.StatusBadRequest { + return ResponseResult{ResponseError: decodeMessagesError(statusCode, body)}, nil + } + // The response content type takes precedence over the request's stream + // flag. + streaming, err := streamingFromContentType(header) + if err != nil { + e.logger.Debug(ctx, "failed to determine response format; using request stream flag", slog.F("content_type", header.Get("Content-Type")), slog.Error(err)) + streaming = e.streaming + } + if streaming { + // TODO: extract streamed responses. https://linear.app/codercom/issue/AIGOV-616 + return ResponseResult{}, nil + } + return e.extractBlocking(body) +} + +// extractBlocking extracts facts from a JSON Message response. +func (e *messagesExtractor) extractBlocking(body []byte) (ResponseResult, error) { + if !json.Valid(body) { + return ResponseResult{}, xerrors.New("decode messages response: invalid JSON") + } + msg := gjson.ParseBytes(body) + if !msg.IsObject() { + return ResponseResult{}, xerrors.New("decode messages response: expected response object") + } + + msgID, idErr := messagesStringField(msg, messagesRespPathID) + providerModel, modelErr := messagesStringField(msg, messagesRespPathModel) + extractErr := errors.Join(idErr, modelErr) + var result ResponseResult + if e.prompt != nil && msgID != "" { + result.Prompt = &recorder.PromptUsageRecord{MsgID: msgID, Prompt: *e.prompt} + } + usage, usageErr := messagesTokenUsage(msgID, providerModel, msg.Get(messagesRespPathUsage)) + result.Tokens = []recorder.TokenUsageRecord{usage} + extractErr = errors.Join(extractErr, usageErr) + + content := msg.Get(messagesRespPathContent) + if content.Type != gjson.Null && !content.IsArray() { + return result, errors.Join(extractErr, xerrors.Errorf("unexpected content type: %s", content.Type)) + } + for index, block := range content.Array() { + if !block.IsObject() { + extractErr = errors.Join(extractErr, xerrors.Errorf("unexpected content block at index %d: expected object", index)) + continue + } + blockType, typeErr := messagesStringField(block, messagesRespFieldType) + if typeErr != nil { + extractErr = errors.Join(extractErr, typeErr) + continue + } + switch blockType { + case messagesRespTypeThinking: + thinking, thinkingErr := messagesStringField(block, messagesRespFieldThinking) + extractErr = errors.Join(extractErr, thinkingErr) + if thinking != "" { + result.Thoughts = append(result.Thoughts, recorder.ModelThoughtRecord{ + Content: thinking, + Metadata: recorder.Metadata{"source": recorder.ThoughtSourceThinking}, + }) + } + case messagesRespTypeToolUse, messagesRespTypeServerToolUse, messagesRespTypeMCPToolUse: + toolCallID, idErr := messagesStringField(block, messagesRespFieldID) + toolName, nameErr := messagesStringField(block, messagesRespFieldName) + extractErr = errors.Join(extractErr, idErr, nameErr) + if idErr != nil || nameErr != nil || toolCallID == "" { + continue + } + var args json.RawMessage + if input := block.Get(messagesRespFieldInput); input.Type != gjson.Null { + args = json.RawMessage(input.Raw) + } + result.Tools = append(result.Tools, recorder.ToolUsageRecord{ + MsgID: msgID, + ToolCallID: toolCallID, + Tool: toolName, + Args: args, + }) + } + } + return result, extractErr +} + +func messagesStringField(parent gjson.Result, path string) (string, error) { + field := parent.Get(path) + if field.Type != gjson.Null && field.Type != gjson.String { + return "", xerrors.Errorf("unexpected %s type: %s", path, field.Type) + } + return field.Str, nil +} + +// messagesTokenUsage converts usage reported for message msgID to a token +// record, matching the record interception mode writes. +func messagesTokenUsage(msgID, providerModel string, usage gjson.Result) (recorder.TokenUsageRecord, error) { + record := recorder.TokenUsageRecord{MsgID: msgID, ProviderModel: providerModel} + if usage.Type != gjson.Null && !usage.IsObject() { + return record, xerrors.Errorf("unexpected usage type: %s", usage.Type) + } + var usageErr error + for _, path := range []string{messagesUsagePathServerToolUse, messagesUsagePathCacheCreation} { + field := usage.Get(path) + if field.Type != gjson.Null && !field.IsObject() { + usageErr = errors.Join(usageErr, xerrors.Errorf("unexpected %s type: %s", path, field.Type)) + } + } + readInt := func(path string) int64 { + field := usage.Get(path) + if field.Type == gjson.Null { + return 0 + } + if field.Type != gjson.Number { + usageErr = errors.Join(usageErr, xerrors.Errorf("unexpected %s type: %s", path, field.Type)) + return 0 + } + value, err := strconv.ParseInt(field.Raw, 10, 64) + if err != nil { + usageErr = errors.Join(usageErr, xerrors.Errorf("invalid integer in %s", path)) + return 0 + } + return value + } + record.Input = readInt(messagesUsagePathInputTokens) + record.Output = readInt(messagesUsagePathOutputTokens) + record.CacheReadInputTokens = readInt(messagesUsagePathCacheReadInputTokens) + record.CacheWriteInputTokens = readInt(messagesUsagePathCacheWriteInputTokens) + serviceTier, tierErr := messagesStringField(usage, messagesUsagePathServiceTier) + usageErr = errors.Join(usageErr, tierErr) + if serviceTier != "" { + record.Metadata = recorder.Metadata{recorder.MetadataKeyServiceTier: serviceTier} + } + extra := make(map[string]int64) + if count := readInt(messagesUsagePathWebSearchRequests); count != 0 { + extra["web_search_requests"] = count + } + if count := readInt(messagesUsagePathEphemeral1hInput); count != 0 { + extra["cache_ephemeral_1h_input"] = count + } + if count := readInt(messagesUsagePathEphemeral5mInput); count != 0 { + extra["cache_ephemeral_5m_input"] = count + } + if len(extra) > 0 { + record.ExtraTokenTypes = extra + } + return record, usageErr +} + +// decodeMessagesError decodes the Messages API error envelope of an HTTP +// error response. It returns nil when body has no error message, which leaves +// classification to the response status and raw body. +func decodeMessagesError(statusCode int, body []byte) error { + var envelope anthropic.ErrorResponse + if err := json.Unmarshal(body, &envelope); err != nil || envelope.Error.Message == "" { + return nil + } + return &messages.ResponseError{ErrorResponse: &envelope, StatusCode: statusCode} +} diff --git a/aibridge/extractors/messages_internal_test.go b/aibridge/extractors/messages_internal_test.go deleted file mode 100644 index f9dc194b32c..00000000000 --- a/aibridge/extractors/messages_internal_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package extractors - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/coder/coder/v2/aibridge/recorder" -) - -func TestMessagesExtractRequest(t *testing.T) { - t.Parallel() - for _, tc := range []struct { - name string - body string - wantErr string - wantModel string - wantToolCallID *string - wantPrompt *string - wantStreaming bool - }{ - { - name: "AllFields", - body: `{"model":"claude-test","stream":true,"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"hi"}]}]}`, - wantModel: "claude-test", - wantToolCallID: new("toolu_1"), - wantPrompt: new("hi"), - wantStreaming: true, - }, - { - name: "NoPrompt", - body: `{"model":"claude-test","messages":[]}`, - wantModel: "claude-test", - }, - { - name: "EmptyPrompt", - body: `{"model":"claude-test","messages":[{"role":"user","content":""}]}`, - wantModel: "claude-test", - wantPrompt: new(""), - }, - { - name: "PromptError", - body: `{"model":"claude-test","messages":{}}`, - wantErr: "read last user prompt", - wantModel: "claude-test", - }, - { - name: "InvalidBody", - body: `not JSON`, - wantErr: "parse messages request", - }, - } { - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - start := &recorder.InterceptionRecord{} - e, ok := NewMessages().(*messagesExtractor) - require.True(t, ok) - - err := e.ExtractRequest([]byte(tc.body), start) - if tc.wantErr != "" { - require.ErrorContains(t, err, tc.wantErr) - } else { - require.NoError(t, err) - } - require.Equal(t, tc.wantModel, start.Model) - require.Equal(t, tc.wantToolCallID, start.CorrelatingToolCallID) - require.Equal(t, tc.wantPrompt, e.prompt) - require.Equal(t, tc.wantStreaming, e.streaming) - }) - } -} diff --git a/aibridge/extractors/messages_test.go b/aibridge/extractors/messages_test.go new file mode 100644 index 00000000000..15173717767 --- /dev/null +++ b/aibridge/extractors/messages_test.go @@ -0,0 +1,388 @@ +package extractors_test + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "slices" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/sjson" + + "cdr.dev/slog/v3" + "github.com/coder/coder/v2/aibridge/extractors" + "github.com/coder/coder/v2/aibridge/intercept/messages" + "github.com/coder/coder/v2/aibridge/recorder" + "github.com/coder/coder/v2/testutil" +) + +func TestMessagesExtractRequest(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + body string + wantErr string + wantModel string + wantToolCallID *string + // wantPrompt is the prompt recorded with the response message ID. + wantPrompt *string + }{ + { + name: "AllFields", + body: `{"model":"claude-test","messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"hi"}]}]}`, + wantModel: "claude-test", + wantToolCallID: new("toolu_1"), + wantPrompt: new("hi"), + }, + { + name: "NoPrompt", + body: `{"model":"claude-test","messages":[]}`, + wantModel: "claude-test", + }, + { + name: "EmptyPrompt", + body: `{"model":"claude-test","messages":[{"role":"user","content":""}]}`, + wantModel: "claude-test", + wantPrompt: new(""), + }, + { + name: "PromptError", + body: `{"model":"claude-test","messages":{}}`, + wantErr: "read last user prompt", + wantModel: "claude-test", + }, + { + name: "InvalidBody", + body: `not JSON`, + wantErr: "parse messages request", + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + e := extractors.NewMessages(slog.Make()) + start := &recorder.InterceptionRecord{} + err := e.ExtractRequest([]byte(tc.body), start) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.wantModel, start.Model) + require.Equal(t, tc.wantToolCallID, start.CorrelatingToolCallID) + + header := http.Header{"Content-Type": {"application/json"}} + got, err := e.ExtractResponse(t.Context(), http.StatusOK, header, []byte(`{"id":"msg_1"}`)) + require.NoError(t, err) + var wantPrompt *recorder.PromptUsageRecord + if tc.wantPrompt != nil { + wantPrompt = &recorder.PromptUsageRecord{MsgID: "msg_1", Prompt: *tc.wantPrompt} + } + require.Equal(t, wantPrompt, got.Prompt) + }) + } +} + +func TestMessagesExtractResponse(t *testing.T) { + t.Parallel() + const message = `{"id":"msg_1","model":"claude-test-1","content":[` + + `{"type":"thinking","thinking":"pondering","signature":"sig"},` + + `{"type":"redacted_thinking","data":"secret"},` + + `{"type":"text","text":"reading"},` + + `{"type":"tool_use","id":"toolu_1","name":"Read","input":{"path":"/a"}}],` + + `"usage":{"input_tokens":1,"output_tokens":2,"cache_read_input_tokens":3,"cache_creation_input_tokens":4,` + + `"cache_creation":{"ephemeral_1h_input_tokens":5,"ephemeral_5m_input_tokens":6},` + + `"server_tool_use":{"web_search_requests":7},"service_tier":"priority"}}` + extracted := extractors.ResponseResult{ + Prompt: &recorder.PromptUsageRecord{MsgID: "msg_1", Prompt: "hi"}, + Tokens: []recorder.TokenUsageRecord{{ + MsgID: "msg_1", + ProviderModel: "claude-test-1", + Input: 1, + Output: 2, + CacheReadInputTokens: 3, + CacheWriteInputTokens: 4, + ExtraTokenTypes: map[string]int64{ + "cache_ephemeral_1h_input": 5, + "cache_ephemeral_5m_input": 6, + "web_search_requests": 7, + }, + Metadata: recorder.Metadata{recorder.MetadataKeyServiceTier: "priority"}, + }}, + Tools: []recorder.ToolUsageRecord{{ + MsgID: "msg_1", + ToolCallID: "toolu_1", + Tool: "Read", + Args: json.RawMessage(`{"path":"/a"}`), + }}, + Thoughts: []recorder.ModelThoughtRecord{{ + Content: "pondering", + Metadata: recorder.Metadata{"source": recorder.ThoughtSourceThinking}, + }}, + } + + var response struct { + Content []json.RawMessage `json:"content"` + } + require.NoError(t, json.Unmarshal([]byte(message), &response)) + + withoutToolInput := extracted + withoutToolInput.Tools = slices.Clone(extracted.Tools) + withoutToolInput.Tools[0].Args = json.RawMessage(nil) + + partialUsage := extracted + partialUsage.Tokens = slices.Clone(extracted.Tokens) + partialUsage.Tokens[0].Output = 0 + + for _, tc := range []struct { + name string + // streaming is the request's stream flag. + streaming bool + status int + contentType string + body []byte // Nil uses the default Message response. + // noResponse passes a nil body, as when no upstream response was + // accepted. + noResponse bool + setFields map[string]any + deleteFields []string + want extractors.ResponseResult + wantErr string + wantLogErr string + // wantErrorStatus and wantErrorMessage describe the decoded error + // response. Zero wantErrorStatus means none. + wantErrorStatus int + wantErrorMessage string + }{ + { + name: "JSON", + status: http.StatusOK, + contentType: "application/json", + want: extracted, + }, + { + name: "MixedToolCallTypes", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{ + "content": append([]json.RawMessage{ + json.RawMessage(`{"type":"server_tool_use","id":"srvtoolu_1","name":"web_search","input":{"query":"q"}}`), + json.RawMessage(`{"type":"mcp_tool_use","id":"mcptoolu_1","name":"list_issues","server_name":"github","input":{"repo":"r"}}`), + json.RawMessage(`{"type":"future_block","id":"future_1"}`), + }, response.Content...), + }, + want: extractors.ResponseResult{ + Prompt: extracted.Prompt, + Tokens: extracted.Tokens, + Thoughts: extracted.Thoughts, + Tools: []recorder.ToolUsageRecord{ + { + MsgID: "msg_1", + ToolCallID: "srvtoolu_1", + Tool: "web_search", + Args: json.RawMessage(`{"query":"q"}`), + }, + { + MsgID: "msg_1", + ToolCallID: "mcptoolu_1", + Tool: "list_issues", + Args: json.RawMessage(`{"repo":"r"}`), + }, + extracted.Tools[0], + }, + }, + }, + { + name: "MissingToolInput", + status: http.StatusOK, + contentType: "application/json", + deleteFields: []string{"content.3.input"}, + want: withoutToolInput, + }, + { + name: "NonObjectResponse", + status: http.StatusOK, + contentType: "application/json", + body: []byte("[]"), + wantErr: "expected response object", + }, + { + name: "InvalidUsageTokenType", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{"usage.output_tokens": true}, + want: partialUsage, + wantErr: "unexpected output_tokens type", + }, + { + name: "InvalidUsageTokenValue", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{"usage.output_tokens": 1.5}, + want: partialUsage, + wantErr: "invalid integer in output_tokens", + }, + { + name: "InvalidToolIDType", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{"content.3.id": 42}, + want: extractors.ResponseResult{ + Prompt: extracted.Prompt, + Tokens: extracted.Tokens, + Thoughts: extracted.Thoughts, + }, + wantErr: "unexpected id type", + }, + { + name: "InvalidContentBlock", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{ + "content": append([]json.RawMessage{json.RawMessage("42")}, response.Content...), + }, + want: extracted, + wantErr: "unexpected content block at index 0", + }, + { + name: "InvalidContentShape", + status: http.StatusOK, + contentType: "application/json", + setFields: map[string]any{"content": map[string]any{"items": response.Content}}, + want: extractors.ResponseResult{ + Prompt: extracted.Prompt, + Tokens: extracted.Tokens, + }, + wantErr: "unexpected content type", + }, + { + // The response content type takes precedence over the request. + name: "JSONToStreamingRequest", + streaming: true, + status: http.StatusOK, + contentType: "application/json; charset=utf-8", + want: extracted, + }, + { + name: "MissingContentType", + status: http.StatusOK, + want: extracted, + wantLogErr: "missing response content type", + }, + { + // TODO: extract streamed responses. https://linear.app/codercom/issue/AIGOV-616 + name: "MissingContentTypeStreamingRequest", + streaming: true, + status: http.StatusOK, + wantLogErr: "missing response content type", + }, + { + name: "MalformedContentType", + status: http.StatusOK, + contentType: "application/json; charset", + want: extracted, + wantLogErr: "mime: invalid media parameter", + }, + { + name: "UnsupportedContentTypeStreamingRequest", + streaming: true, + status: http.StatusOK, + contentType: "text/plain", + wantLogErr: `unsupported response content type "text/plain"`, + }, + { + // TODO: extract streamed responses. https://linear.app/codercom/issue/AIGOV-616 + name: "EventStream", + status: http.StatusOK, + contentType: "text/event-stream", + }, + { + name: "InvalidJSON", + status: http.StatusOK, + contentType: "application/json", + body: []byte("{"), + wantErr: "decode messages response", + }, + { + name: "NoResponse", + noResponse: true, + }, + { + // Error responses carry an error envelope whatever the request + // asked for. + name: "ErrorResponse", + streaming: true, + status: 529, + contentType: "text/event-stream", + body: []byte(`{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`), + wantErrorStatus: 529, + wantErrorMessage: "Overloaded", + }, + { + // Without an envelope, the response status classifies the error. + name: "ErrorWithoutEnvelope", + status: http.StatusBadGateway, + contentType: "text/html", + body: []byte("bad gateway"), + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + sink := testutil.NewFakeSink(t) + e := extractors.NewMessages(sink.Logger()) + request := fmt.Sprintf(`{"model":"claude-test","stream":%t,"messages":[{"role":"user","content":"hi"}]}`, tc.streaming) + require.NoError(t, e.ExtractRequest([]byte(request), &recorder.InterceptionRecord{})) + + header := http.Header{} + if tc.contentType != "" { + header.Set("Content-Type", tc.contentType) + } + body := tc.body + if body == nil { + body = []byte(message) + } + for path, value := range tc.setFields { + var err error + body, err = sjson.SetBytes(body, path, value) + require.NoError(t, err) + } + for _, path := range tc.deleteFields { + var err error + body, err = sjson.DeleteBytes(body, path) + require.NoError(t, err) + } + if tc.noResponse { + body = nil + } + got, err := e.ExtractResponse(t.Context(), tc.status, header, body) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + } else { + require.NoError(t, err) + } + if tc.wantErrorStatus != 0 { + var responseErr *messages.ResponseError + require.True(t, errors.As(got.ResponseError, &responseErr), "unexpected response error: %v", got.ResponseError) + require.Equal(t, tc.wantErrorStatus, responseErr.StatusCode) + require.Equal(t, tc.wantErrorMessage, responseErr.Error()) + got.ResponseError = nil + } + require.Equal(t, tc.want, got) + entries := sink.Entries() + if tc.wantLogErr != "" { + require.Len(t, entries, 1) + require.Equal(t, slog.LevelDebug, entries[0].Level) + var loggedErr error + for _, field := range entries[0].Fields { + if field.Name == "error" { + loggedErr, _ = field.Value.(error) + } + } + require.ErrorContains(t, loggedErr, tc.wantLogErr) + } else { + require.Empty(t, entries) + } + }) + } +} diff --git a/aibridge/internal/integrationtest/bridge_internal_test.go b/aibridge/internal/integrationtest/bridge_internal_test.go index 80bdc5e82cf..ab9c0197204 100644 --- a/aibridge/internal/integrationtest/bridge_internal_test.go +++ b/aibridge/internal/integrationtest/bridge_internal_test.go @@ -62,6 +62,7 @@ func TestAnthropicMessages(t *testing.T) { cases := []struct { name string streaming bool + proxy bool expectedInputTokens int expectedOutputTokens int expectedCacheReadInputTokens int @@ -86,6 +87,15 @@ func TestAnthropicMessages(t *testing.T) { expectedCacheWriteInputTokens: 0, expectedToolCallID: "toolu_01AusGgY5aKFhzWrFBv9JfHq", }, + { + name: "non-streaming/proxy", + proxy: true, + expectedInputTokens: 5, + expectedOutputTokens: 84, + expectedCacheReadInputTokens: 23490, + expectedCacheWriteInputTokens: 0, + expectedToolCallID: "toolu_01AusGgY5aKFhzWrFBv9JfHq", + }, } for _, tc := range cases { @@ -98,7 +108,7 @@ func TestAnthropicMessages(t *testing.T) { fix := fixtures.Parse(t, fixtures.AntSingleBuiltinTool) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL) + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, withProxyMode(tc.proxy)) // Make API call to aibridge for Anthropic /v1/messages reqBody, err := sjson.SetBytes(fix.Request(), "stream", tc.streaming) @@ -116,7 +126,11 @@ func TestAnthropicMessages(t *testing.T) { // Ensure the message starts and completes, at a minimum. assert.Contains(t, sp.AllEvents(), "message_start") assert.Contains(t, sp.AllEvents(), "message_stop") + } else { + _, err = io.ReadAll(resp.Body) + require.NoError(t, err) } + bridgeServer.awaitRecordings(t) expectedTokenRecordings := 1 if tc.streaming { @@ -388,6 +402,7 @@ func TestAnthropicMessagesModelThoughts(t *testing.T) { cases := []struct { name string streaming bool + proxy bool fixture []byte expectedThoughts []recorder.ModelThoughtRecord // nil means no model thoughts expected }{ @@ -451,6 +466,39 @@ func TestAnthropicMessagesModelThoughts(t *testing.T) { fixture: fixtures.AntSingleInjectedTool, expectedThoughts: nil, }, + { + name: "single thinking block/blocking/proxy", + proxy: true, + fixture: fixtures.AntSingleBuiltinTool, + expectedThoughts: []recorder.ModelThoughtRecord{newModelThought("The user wants me to read", recorder.ThoughtSourceThinking)}, + }, + { + name: "multiple thinking blocks/blocking/proxy", + proxy: true, + fixture: fixtures.AntMultiThinkingBuiltinTool, + expectedThoughts: []recorder.ModelThoughtRecord{ + newModelThought("The user wants me to read", recorder.ThoughtSourceThinking), + newModelThought("I should use the Read tool", recorder.ThoughtSourceThinking), + }, + }, + { + name: "parallel tool calls/blocking/proxy", + proxy: true, + fixture: fixtures.AntSingleBuiltinToolParallel, + expectedThoughts: []recorder.ModelThoughtRecord{newModelThought("The user wants me to read two files", recorder.ThoughtSourceThinking)}, + }, + { + name: "thoughts without tool calls/blocking/proxy", + proxy: true, + fixture: fixtures.AntSimple, + expectedThoughts: []recorder.ModelThoughtRecord{newModelThought("This is a classic philosophical question about medieval scholasticism", recorder.ThoughtSourceThinking)}, + }, + { + name: "no thoughts captured/proxy", + proxy: true, + fixture: fixtures.AntSingleInjectedTool, + expectedThoughts: nil, + }, } for _, tc := range cases { @@ -463,7 +511,7 @@ func TestAnthropicMessagesModelThoughts(t *testing.T) { fix := fixtures.Parse(t, tc.fixture) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL) + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, withProxyMode(tc.proxy)) reqBody, err := sjson.SetBytes(fix.Request(), "stream", tc.streaming) require.NoError(t, err) @@ -477,7 +525,11 @@ func TestAnthropicMessagesModelThoughts(t *testing.T) { require.NoError(t, sp.Parse(resp.Body)) assert.Contains(t, sp.AllEvents(), "message_start") assert.Contains(t, sp.AllEvents(), "message_stop") + } else { + _, err = io.ReadAll(resp.Body) + require.NoError(t, err) } + bridgeServer.awaitRecordings(t) bridgeServer.Recorder.VerifyModelThoughtsRecorded(t, tc.expectedThoughts) bridgeServer.Recorder.VerifyAllInterceptionsEnded(t) @@ -1589,6 +1641,7 @@ func TestSimple(t *testing.T) { expectedMsgID string userAgent string expectedClient aibclient.Type + proxy bool }{ { name: config.ProviderAnthropic, @@ -1656,6 +1709,40 @@ func TestSimple(t *testing.T) { userAgent: "Zed/0.219.4+stable.119.abc123 (macos; aarch64)", expectedClient: aibclient.Zed, }, + { + name: config.ProviderAnthropic + "/proxy", + proxy: true, + fixture: fixtures.AntSimple, + expectedPath: "/v1/messages", + getResponseIDFunc: getAnthropicResponseID, + path: pathAnthropicMessages, + expectedMsgID: "msg_01Pvyf26bY17RcjmWfJsXGBn", + userAgent: "claude-cli/2.0.67 (external, cli)", + expectedClient: aibclient.ClaudeCode, + }, + { + name: config.ProviderAnthropic + "_haiku_prompt_capture/proxy", + proxy: true, + fixture: fixtures.AntHaikuSimple, + expectedPath: "/v1/messages", + getResponseIDFunc: getAnthropicResponseID, + path: pathAnthropicMessages, + expectedMsgID: "msg_01Pvyf26bY17RcjmWfJsXGBn", + userAgent: "claude-cli/2.0.67 (external, cli)", + expectedClient: aibclient.ClaudeCode, + }, + { + name: config.ProviderAnthropic + "_baseURL_path/proxy", + proxy: true, + fixture: fixtures.AntSimple, + basePath: "/api", + expectedPath: "/api/v1/messages", + getResponseIDFunc: getAnthropicResponseID, + path: pathAnthropicMessages, + expectedMsgID: "msg_01Pvyf26bY17RcjmWfJsXGBn", + userAgent: "GitHubCopilotChat/0.37.2026011603", + expectedClient: aibclient.CopilotVSC, + }, } for _, tc := range testCases { @@ -1664,6 +1751,10 @@ func TestSimple(t *testing.T) { for _, streaming := range []bool{true, false} { t.Run(fmt.Sprintf("streaming=%v", streaming), func(t *testing.T) { + if tc.proxy && streaming { + // TODO: record streamed responses in proxy mode. https://linear.app/codercom/issue/AIGOV-616 + t.Skip("AIGOV-616: proxy mode does not record streamed responses yet") + } t.Parallel() ctx, cancel := context.WithTimeout(t.Context(), testutil.WaitLong) @@ -1672,7 +1763,7 @@ func TestSimple(t *testing.T) { fix := fixtures.Parse(t, tc.fixture) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL+tc.basePath) + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL+tc.basePath, withProxyMode(tc.proxy)) // When: calling the "API server" with the fixture's request body. reqBody, err := sjson.SetBytes(fix.Request(), "stream", streaming) @@ -1691,6 +1782,7 @@ func TestSimple(t *testing.T) { bodyBytes, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.NotEmpty(t, bodyBytes, "should have received response body") + bridgeServer.awaitRecordings(t) // Reset the body after being read. resp.Body = io.NopCloser(bytes.NewReader(bodyBytes)) @@ -1700,12 +1792,17 @@ func TestSimple(t *testing.T) { require.NotEmpty(t, promptUsages, "no prompts tracked") assert.Contains(t, promptUsages[0].Prompt, "how many angels can dance on the head of a pin") - // Validate that responses have their IDs overridden with a interception ID rather than the original ID from the upstream provider. - // The reason for this is that Bridge may make multiple upstream requests (i.e. to invoke injected tools), and clients will not be expecting - // multiple messages in response to a single request. id, err := tc.getResponseIDFunc(streaming, resp) require.NoError(t, err, "failed to retrieve response ID") - require.Nilf(t, uuid.Validate(id), "%s is not a valid UUID", id) + if tc.proxy { + // Proxy mode forwards the upstream response unchanged. + require.Equal(t, tc.expectedMsgID, id) + } else { + // Validate that responses have their IDs overridden with a interception ID rather than the original ID from the upstream provider. + // The reason for this is that Bridge may make multiple upstream requests (i.e. to invoke injected tools), and clients will not be expecting + // multiple messages in response to a single request. + require.Nilf(t, uuid.Validate(id), "%s is not a valid UUID", id) + } tokenUsages := bridgeServer.Recorder.RecordedTokenUsages() require.GreaterOrEqual(t, len(tokenUsages), 1) @@ -1714,7 +1811,9 @@ func TestSimple(t *testing.T) { // Validate user agent and client have been recorded. interceptions := bridgeServer.Recorder.RecordedInterceptions() require.Len(t, interceptions, 1, "expected exactly one interception, got: %v", interceptions) - assert.Equal(t, id, interceptions[0].ID) + if !tc.proxy { + assert.Equal(t, id, interceptions[0].ID) + } assert.Equal(t, tc.userAgent, interceptions[0].UserAgent) assert.Equal(t, string(tc.expectedClient), interceptions[0].Client) @@ -1801,11 +1900,7 @@ func TestSessionIDTracking(t *testing.T) { fix := fixtures.Parse(t, tc.fixture) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - opts := []bridgeOption{withProvider(config.ProviderAnthropic)} - if tc.proxyMode { - opts = append(opts, withProxyMode()) - } - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, opts...) + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, withProvider(config.ProviderAnthropic), withProxyMode(tc.proxyMode)) reqBody := fix.Request() if tc.metadataSessionID != "" { @@ -2301,24 +2396,39 @@ func TestErrorHandling(t *testing.T) { t.Run("non-stream error", func(t *testing.T) { t.Parallel() + anthropicResponseHandler := func(resp *http.Response) { + require.Equal(t, http.StatusBadRequest, resp.StatusCode) + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equal(t, "error", gjson.GetBytes(body, "type").Str) + require.Equal(t, "invalid_request_error", gjson.GetBytes(body, "error.type").Str) + require.Contains(t, gjson.GetBytes(body, "error.message").Str, "prompt is too long") + } + cases := []struct { - name string - fixture []byte - path string - responseHandlerFn func(resp *http.Response) + name string + fixture []byte + path string + responseHandlerFn func(resp *http.Response) + proxy bool + expectedErrorType recorder.ErrorType + expectedErrorMessage string }{ { - name: config.ProviderAnthropic, - fixture: fixtures.AntNonStreamError, - path: pathAnthropicMessages, - responseHandlerFn: func(resp *http.Response) { - require.Equal(t, http.StatusBadRequest, resp.StatusCode) - body, err := io.ReadAll(resp.Body) - require.NoError(t, err) - require.Equal(t, "error", gjson.GetBytes(body, "type").Str) - require.Equal(t, "invalid_request_error", gjson.GetBytes(body, "error.type").Str) - require.Contains(t, gjson.GetBytes(body, "error.message").Str, "prompt is too long") - }, + name: config.ProviderAnthropic, + fixture: fixtures.AntNonStreamError, + path: pathAnthropicMessages, + responseHandlerFn: anthropicResponseHandler, + }, + { + name: config.ProviderAnthropic + "/proxy", + proxy: true, + fixture: fixtures.AntNonStreamError, + path: pathAnthropicMessages, + responseHandlerFn: anthropicResponseHandler, + // The decoded error message, not the whole envelope. + expectedErrorType: recorder.ErrorTypeBadRequest, + expectedErrorMessage: "prompt is too long: 205429 tokens > 200000 maximum", }, { name: config.ProviderOpenAI, @@ -2351,7 +2461,7 @@ func TestErrorHandling(t *testing.T) { fix := fixtures.Parse(t, tc.fixture) upstream := testutil.NewMockUpstream(ctx, t, testutil.NewFixtureResponse(fix)) - bridgeServer := newBridgeTestServer(ctx, t, upstream.URL) + bridgeServer := newBridgeTestServer(ctx, t, upstream.URL, withProxyMode(tc.proxy)) // Add the stream param to the request. reqBody, err := sjson.SetBytes(fix.Request(), "stream", streaming) @@ -2362,7 +2472,15 @@ func TestErrorHandling(t *testing.T) { defer resp.Body.Close() tc.responseHandlerFn(resp) + bridgeServer.awaitRecordings(t) bridgeServer.Recorder.VerifyAllInterceptionsEnded(t) + if tc.proxy { + intcs := bridgeServer.Recorder.RecordedInterceptions() + require.Len(t, intcs, 1) + ended := bridgeServer.Recorder.RecordedInterceptionEnd(intcs[0].ID) + require.Equal(t, tc.expectedErrorType, ended.ErrorType) + require.Equal(t, tc.expectedErrorMessage, ended.ErrorMessage) + } }) } }) diff --git a/aibridge/internal/integrationtest/interception_error_internal_test.go b/aibridge/internal/integrationtest/interception_error_internal_test.go index 1975c64833d..d625a508bbc 100644 --- a/aibridge/internal/integrationtest/interception_error_internal_test.go +++ b/aibridge/internal/integrationtest/interception_error_internal_test.go @@ -31,11 +31,16 @@ func TestInterceptionUpstreamErrorRecorded(t *testing.T) { path string streaming bool wantType recorder.ErrorType + // proxy selects reverse-proxy mode, where the key pool failure takes + // precedence over the error response it writes. + proxy bool }{ - {"anthropic_blocking", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, false, recorder.ErrorTypeUnauthorized}, - {"anthropic_streaming", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, true, recorder.ErrorTypeUnauthorized}, - {"openai_blocking", config.ProviderOpenAI, fixtures.OaiChatSimple, pathOpenAIChatCompletions, false, recorder.ErrorTypeUnauthorized}, - {"openai_streaming", config.ProviderOpenAI, fixtures.OaiChatSimple, pathOpenAIChatCompletions, true, recorder.ErrorTypeUnauthorized}, + {"anthropic_blocking", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, false, recorder.ErrorTypeUnauthorized, false}, + {"anthropic_streaming", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, true, recorder.ErrorTypeUnauthorized, false}, + {"anthropic_blocking/proxy", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, false, recorder.ErrorTypeUnauthorized, true}, + {"anthropic_streaming/proxy", config.ProviderAnthropic, fixtures.AntSimple, pathAnthropicMessages, true, recorder.ErrorTypeUnauthorized, true}, + {"openai_blocking", config.ProviderOpenAI, fixtures.OaiChatSimple, pathOpenAIChatCompletions, false, recorder.ErrorTypeUnauthorized, false}, + {"openai_streaming", config.ProviderOpenAI, fixtures.OaiChatSimple, pathOpenAIChatCompletions, true, recorder.ErrorTypeUnauthorized, false}, } for _, tc := range cases { @@ -48,7 +53,7 @@ func TestInterceptionUpstreamErrorRecorded(t *testing.T) { ) upstream.AllowOverflow = true - bridgeServer := newBridgeTestServer(t.Context(), t, upstream.URL, withProvider(tc.provider)) + bridgeServer := newBridgeTestServer(t.Context(), t, upstream.URL, withProvider(tc.provider), withProxyMode(tc.proxy)) reqBody, err := sjson.SetBytes(fix.Request(), "stream", tc.streaming) require.NoError(t, err) @@ -57,6 +62,7 @@ func TestInterceptionUpstreamErrorRecorded(t *testing.T) { require.NoError(t, err) _, _ = io.Copy(io.Discard, resp.Body) require.NoError(t, resp.Body.Close()) + bridgeServer.awaitRecordings(t) intcs := bridgeServer.Recorder.RecordedInterceptions() require.Len(t, intcs, 1) diff --git a/aibridge/internal/integrationtest/setupbridge.go b/aibridge/internal/integrationtest/setupbridge.go index b6a549d0d06..e154bf2c382 100644 --- a/aibridge/internal/integrationtest/setupbridge.go +++ b/aibridge/internal/integrationtest/setupbridge.go @@ -145,10 +145,10 @@ func withCustomProvider(p aibridge.Provider) bridgeOption { } } -// withProxyMode serves [proxy.NewRouter] instead of the default -// [aibridge.NewRequestBridge]. -func withProxyMode() bridgeOption { - return func(c *bridgeConfig) { c.proxyMode = true } +// withProxyMode serves [proxy.NewRouter] when enabled, and the default +// [aibridge.NewRequestBridge] otherwise. +func withProxyMode(enabled bool) bridgeOption { + return func(c *bridgeConfig) { c.proxyMode = enabled } } // withMetrics sets the Prometheus metrics for the bridge. @@ -173,7 +173,7 @@ func withActor(id uuid.UUID, username string) bridgeOption { // newBridgeTestServer creates a fully configured test server running // a RequestBridge with sensible defaults: -// - interception mode (unless withProxyMode) +// - interception mode (unless withProxyMode(true)) // - All standard providers (unless withProvider / withCustomProvider) // - NoopMCPManager (unless withMCP) // - slogtest debug logger diff --git a/aibridge/provider/anthropic.go b/aibridge/provider/anthropic.go index 33dc94a34bc..fa235eaa3e3 100644 --- a/aibridge/provider/anthropic.go +++ b/aibridge/provider/anthropic.go @@ -194,7 +194,7 @@ func (p *Anthropic) CreateInterceptor(_ http.ResponseWriter, r *http.Request, tr // CreateExtractor serves the messages route. func (p *Anthropic) CreateExtractor(path string) extractors.Extractor { if path == p.RoutePrefix()+routeMessages { - return extractors.NewMessages() + return extractors.NewMessages(p.cfg.Logger) } return nil } diff --git a/aibridge/x/proxy/handler.go b/aibridge/x/proxy/handler.go index 214be71a876..06a53ecae97 100644 --- a/aibridge/x/proxy/handler.go +++ b/aibridge/x/proxy/handler.go @@ -10,6 +10,7 @@ import ( "net/http/httputil" "net/url" "strings" + "sync" "time" "github.com/google/uuid" @@ -53,20 +54,20 @@ type forwardingHandler struct { } // errForwardingAborted marks forwarding that ended without returning, such as -// a panic that aborts the response copy. endRecord replaces it with the real -// cause when one is known. +// a panic that aborts the response copy. forwardingError replaces it with the +// real cause when one is known. var errForwardingAborted = xerrors.New("forwarding aborted") // forwardedRequest tracks single bridged request type forwardedRequest struct { handler *forwardingHandler - // logger, cred, and record are set by start after the request passes - // validation and its interception start is recorded. record is nil - // otherwise. - logger slog.Logger - cred credential.Credential - record *recorder.InterceptionRecord + // logger is the request logger, set by start. cred and startRecord are + // set by start after the request passes validation and its interception + // start is recorded. startRecord is nil otherwise. + logger slog.Logger + cred credential.Credential + startRecord *recorder.InterceptionRecord // extractor derives recording facts for the route, set by start. Nil when // the route has no extractor yet. extractor extractors.Extractor @@ -81,6 +82,8 @@ type forwardedRequest struct { // status is the final upstream response status, set by forward. // Zero when no upstream response was accepted. status int + // header is the final upstream response header, set with status. + header http.Header // responseBody captures the final upstream response body, set by forward. // Nil when no upstream response was accepted. responseBody *replaybody.TeeBuffer @@ -160,7 +163,7 @@ func (fr *forwardedRequest) serve(w http.ResponseWriter, r *http.Request) { return } // Set the sentinel in case forwarding panics and breaker.Execute does not return. - // fr.endRecord replaces it with the real cause when one is known. + // fr.forwardingError replaces it with the real cause when one is known. fr.err = errForwardingAborted // Defer ordering: finish, then cleanup, then span.End. @@ -168,8 +171,9 @@ func (fr *forwardedRequest) serve(w http.ResponseWriter, r *http.Request) { defer span.End() ctx, cleanup := fr.handler.inflight.RequestContext(ctx) defer cleanup() - // finish needs to run before cleanup cancels the ctx. - defer fr.finish(ctx, release) + // finish needs to run before cleanup cancels the ctx. It reads ctx when it + // runs, so it sees the interception ID added below. + defer func() { fr.finish(ctx, release) }() defer func() { if fr.requestBody != nil { _ = fr.requestBody.Close() @@ -179,6 +183,10 @@ func (fr *forwardedRequest) serve(w http.ResponseWriter, r *http.Request) { if !fr.start(ctx, w, r) { return } + // Later logs belong to the recorded interception, including those of the + // extractor, the recorder, and the upstream transport. + ctx = slog.With(ctx, slog.F("interception_id", fr.startRecord.ID)) + fr.outbound = fr.outbound.WithContext(ctx) route := strings.TrimPrefix(r.URL.Path, "/"+fr.handler.provider.Name()) fr.err = fr.handler.breaker.Execute(route, "", w, fr.forward) @@ -197,6 +205,12 @@ func (fr *forwardedRequest) start(ctx context.Context, w http.ResponseWriter, r return false } + // Without full duplex, an HTTP/1 reply written before the body is fully + // read, such as a cancellation, waits for the server to drain the rest of + // the body. Writers that cannot enable it keep the default drain. + if err := http.NewResponseController(w).EnableFullDuplex(); err != nil { + logger.Debug(ctx, "full duplex unavailable, early replies drain the request body first", slog.Error(err)) + } if !fr.readRequest(ctx, w, r) { return false } @@ -220,7 +234,8 @@ func (fr *forwardedRequest) start(ctx context.Context, w http.ResponseWriter, r http.Error(w, "failed to record interception", http.StatusInternalServerError) return false } - fr.cred, fr.record = cred, record + fr.cred = cred + fr.startRecord = record return true } @@ -262,25 +277,31 @@ func (fr *forwardedRequest) readRequest(ctx context.Context, w http.ResponseWrit } _ = outbound.Body.Close() outbound.Body = replay - fr.outbound, fr.requestBody = outbound, capture + fr.outbound = outbound + fr.requestBody = capture return true } -// finish records how the interception ended, then releases in-flight -// admission. It must run before cleanup cancels ctx. +// finish records the response facts and how the interception ended, then +// releases in-flight admission. It must run before cleanup cancels ctx. func (fr *forwardedRequest) finish(ctx context.Context, release func()) { // No start record means the request was not forwarded, do not record an end. - if fr.record == nil { + if fr.startRecord == nil { release() return } - ended := fr.endRecord(ctx) + // Snapshot the outcome now: cleanup cancels ctx once finish returns, and + // forwardingError reads its cancellation cause. + endedAt := time.Now().UTC() + forwardErr := fr.forwardingError(ctx) // Record asynchronously so the response finishes without waiting for the recorder. - go fr.recordEnd(ctx, ended, release) + go fr.recordFacts(ctx, endedAt, forwardErr, release) } -// endRecord describes how forwarding ended. -func (fr *forwardedRequest) endRecord(ctx context.Context) *recorder.InterceptionRecordEnded { +// forwardingError returns why forwarding failed: the transport, capture, +// cancellation, key pool, or circuit breaker failure. Nil when the upstream +// response was delivered, even an HTTP error response. +func (fr *forwardedRequest) forwardingError(ctx context.Context) error { // fr.err is what breaker.Execute returned, or errForwardingAborted if // forwarding panicked. A nil error still needs the response capture and // status to tell success from failure. @@ -291,14 +312,12 @@ func (fr *forwardedRequest) endRecord(ctx context.Context) *recorder.Interceptio err = canceled } - var body []byte if fr.responseBody != nil { // fr.forward has closed the capture, so it has finished. readErr := fr.responseBody.Err() if errors.Is(readErr, replaybody.ErrCaptureInProgress) { - fr.logger.Warn(ctx, "response capture still in progress when recording interception end", slog.F("interception_id", fr.record.ID)) + fr.logger.Warn(ctx, "response capture still in progress when recording interception end") } - body = fr.responseBody.Bytes() // Errors from the circuit breaker, reverse proxy, or cancellation are left // unchanged. A nil err, or the errForwardingAborted sentinel, takes the // capture's read error. The sentinel stays only if the capture completed but @@ -307,44 +326,119 @@ func (fr *forwardedRequest) endRecord(ctx context.Context) *recorder.Interceptio err = readErr } } + return err +} +// recordFacts extracts the response facts, then records them and the end +// record concurrently, and finally releases in-flight admission. endedAt and +// forwardErr are snapshots taken when forwarding completed. Each write has its +// own recorder.DefaultAsyncTimeout. +func (fr *forwardedRequest) recordFacts(ctx context.Context, endedAt time.Time, forwardErr error, release func()) { + // Release in-flight gate admission after recording. + defer release() + // Do not propagate cancellation to the recorder. + ctx = context.WithoutCancel(ctx) + + // The end record depends on the error the response reported, so + // extraction must finish before either write starts. The result stays + // empty when the route has no extractor. + var result extractors.ResponseResult + if fr.extractor != nil { + var body []byte + if fr.responseBody != nil { + body = fr.responseBody.Bytes() + } + var err error + result, err = fr.extractor.ExtractResponse(ctx, fr.status, fr.header, body) + if err != nil { + // Extraction failures only lose recording facts, they do not change + // the outcome. A failed forward leaves a partial capture, which is + // expected not to parse. + if forwardErr != nil { + fr.logger.Debug(ctx, "failed to extract response facts", slog.F("forward_error", forwardErr.Error()), slog.Error(err)) + } else { + fr.logger.Warn(ctx, "failed to extract response facts", slog.Error(err)) + } + } + } + + var wg sync.WaitGroup + wg.Go(func() { fr.recordResponseFacts(ctx, endedAt, result) }) + wg.Go(func() { fr.recordEnd(ctx, endedAt, forwardErr, result.ResponseError) }) + wg.Wait() +} + +// recordResponseFacts stores the extracted response facts, created at endedAt, +// and returns once every write finishes. The writes run concurrently, so a +// response with many facts does not exhaust a shared timeout. AsyncRecorder +// returns no errors; the handler's recorder chain logs write failures. +func (fr *forwardedRequest) recordResponseFacts(ctx context.Context, endedAt time.Time, result extractors.ResponseResult) { + id := fr.startRecord.ID + rec := recorder.NewAsyncRecorder(fr.handler.recorder, recorder.DefaultAsyncTimeout) + defer rec.Wait() + if prompt := result.Prompt; prompt != nil { + prompt.InterceptionID = id + prompt.CreatedAt = endedAt + _ = rec.RecordPromptUsage(ctx, prompt) //nolint:errcheck // AsyncRecorder always returns nil. + } + for i := range result.Tokens { + tokens := &result.Tokens[i] + tokens.InterceptionID = id + tokens.CreatedAt = endedAt + _ = rec.RecordTokenUsage(ctx, tokens) //nolint:errcheck // AsyncRecorder always returns nil. + } + for i := range result.Tools { + tool := &result.Tools[i] + tool.InterceptionID = id + tool.CreatedAt = endedAt + _ = rec.RecordToolUsage(ctx, tool) //nolint:errcheck // AsyncRecorder always returns nil. + } + for i := range result.Thoughts { + thought := &result.Thoughts[i] + thought.InterceptionID = id + thought.CreatedAt = endedAt + _ = rec.RecordModelThought(ctx, thought) //nolint:errcheck // AsyncRecorder always returns nil. + } +} + +// recordEnd stores how the interception ended within +// recorder.DefaultAsyncTimeout. forwardErr takes precedence over responseErr, +// the failure the response reported. An HTTP error response without either is +// classified by its status. The handler's recorder chain logs a write failure. +func (fr *forwardedRequest) recordEnd(ctx context.Context, endedAt time.Time, forwardErr, responseErr error) { + err := forwardErr + if err == nil { + err = responseErr + } // Categorize Go errors first, HTTP error responses may have no Go error. errType, errMsg := interceptionerror.Categorize(fr.handler.provider, err) if err == nil && fr.status >= http.StatusBadRequest { // TODO: provide SDK error to Categorize // https://linear.app/codercom/issue/AIGOV-811 errType = recorder.ErrorTypeFromStatus(fr.status) - errMsg = interceptionerror.TruncateMessage(string(body)) + if fr.responseBody != nil { + errMsg = interceptionerror.TruncateMessage(string(fr.responseBody.Bytes())) + } if errMsg == "" { errMsg = http.StatusText(fr.status) } } // Keep the initial hint for BYOK, or use the last attempted pooled key. - hint := fr.record.CredentialHint + hint := fr.startRecord.CredentialHint if fr.credentialHint != "" { hint = fr.credentialHint } - return &recorder.InterceptionRecordEnded{ - ID: fr.record.ID, - EndedAt: time.Now().UTC(), + record := &recorder.InterceptionRecordEnded{ + ID: fr.startRecord.ID, + EndedAt: endedAt, CredentialHint: hint, ErrorType: errType, ErrorMessage: errMsg, } -} - -// recordEnd stores the end record, then releases in-flight admission. -func (fr *forwardedRequest) recordEnd(ctx context.Context, ended *recorder.InterceptionRecordEnded, release func()) { - // Release in-flight gate admission after recording. - defer release() - - // Do not propagate cancellation to the recorder. - ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recorder.DefaultAsyncTimeout) + ctx, cancel := context.WithTimeout(ctx, recorder.DefaultAsyncTimeout) defer cancel() - if err := fr.handler.recorder.RecordInterceptionEnded(ctx, ended); err != nil { - fr.handler.logger.Warn(ctx, "failed to record interception end", slog.F("interception_id", ended.ID), slog.Error(err)) - } + _ = fr.handler.recorder.RecordInterceptionEnded(ctx, record) //nolint:errcheck // The recorder chain logs failures. } // checkRequest validates a bridged request without reading its body. On rejection @@ -468,6 +562,7 @@ func (fr *forwardedRequest) forward(w http.ResponseWriter) (err error) { return xerrors.New("upstream protocol upgrades are not supported") } fr.status = resp.StatusCode + fr.header = resp.Header.Clone() fr.responseBody = replaybody.NewResponse(resp) return nil }, diff --git a/aibridge/x/proxy/handler_internal_test.go b/aibridge/x/proxy/handler_internal_test.go index 6fb27144c97..d41be3483e2 100644 --- a/aibridge/x/proxy/handler_internal_test.go +++ b/aibridge/x/proxy/handler_internal_test.go @@ -787,22 +787,83 @@ func newMessagesRequest(t *testing.T, prov provider.Provider, body io.Reader) *h } // Routes with an extractor read the request before recording its start, then -// forward the same bytes. Extraction failures only lose facts. -func TestForwardingExtractsRequest(t *testing.T) { +// forward the same bytes. Response facts are recorded with the interception ID +// and end time, and a decoded error response classifies the end. Extraction +// failures only lose facts. +func TestForwardingExtraction(t *testing.T) { t.Parallel() + const blockingRequest = `{"model":"claude-test","messages":[{"role":"user","content":"hi"}]}` for _, tc := range []struct { - name string - body string - wantModel string + name string + body string + // status, contentType, and response describe the upstream response. + // upstreamErr, when set, fails the upstream body after response. + status int + contentType string + response string + upstreamErr error + wantModel string + wantPrompts []recorder.PromptUsageRecord + wantTokens []recorder.TokenUsageRecord + wantError recorder.ErrorType + wantMessage string }{ { name: "Messages", body: `{"model":"claude-test","stream":true,"messages":[{"role":"user","content":"hi"}]}`, + status: http.StatusOK, wantModel: "claude-test", }, { - name: "InvalidJSON", - body: `not JSON`, + name: "InvalidJSON", + body: `not JSON`, + status: http.StatusOK, + }, + { + name: "BlockingResponse", + body: blockingRequest, + status: http.StatusOK, + contentType: "application/json", + response: `{"id":"msg_1","model":"claude-test-1","usage":{"input_tokens":3,"output_tokens":5}}`, + wantModel: "claude-test", + wantPrompts: []recorder.PromptUsageRecord{{MsgID: "msg_1", Prompt: "hi"}}, + wantTokens: []recorder.TokenUsageRecord{{MsgID: "msg_1", ProviderModel: "claude-test-1", Input: 3, Output: 5}}, + }, + { + name: "Overloaded", + body: blockingRequest, + status: 529, + contentType: "application/json", + response: `{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}`, + wantModel: "claude-test", + wantError: recorder.ErrorTypeOverloaded, + wantMessage: "Overloaded", + }, + { + // JSON without the Messages error envelope is classified by status + // and recorded raw. + name: "ErrorWithoutEnvelope", + body: blockingRequest, + status: http.StatusBadGateway, + contentType: "application/json", + response: `{"detail":"bad gateway"}`, + wantModel: "claude-test", + wantError: recorder.ErrorTypeServerError, + wantMessage: `{"detail":"bad gateway"}`, + }, + { + // An upstream failure partway through the body leaves a partial + // capture: no facts are recorded and the end keeps the forward + // error. + name: "PartialResponse", + body: blockingRequest, + status: http.StatusOK, + contentType: "application/json", + response: `{"id":"msg_1","model":"claude-test-1","usage":{"input_tokens":3`, + upstreamErr: io.ErrUnexpectedEOF, + wantModel: "claude-test", + wantError: recorder.ErrorTypeUnknown, + wantMessage: io.ErrUnexpectedEOF.Error(), }, } { t.Run(tc.name, func(t *testing.T) { @@ -818,21 +879,51 @@ func TestForwardingExtractsRequest(t *testing.T) { payload, err := io.ReadAll(r.Body) assert.NoError(t, err) forwarded = append(forwarded, string(payload)) - return &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: http.NoBody}, nil + header := http.Header{} + if tc.contentType != "" { + header.Set("Content-Type", tc.contentType) + } + var upstream io.Reader = strings.NewReader(tc.response) + if tc.upstreamErr != nil { + upstream = io.MultiReader(upstream, readerFunc(func([]byte) (int, error) { return 0, tc.upstreamErr })) + } + return &http.Response{StatusCode: tc.status, Header: header, Body: io.NopCloser(upstream)}, nil }) req := newMessagesRequest(t, prov, strings.NewReader(tc.body)) response := httptest.NewRecorder() h.ServeHTTP(response, req) require.NoError(t, h.inflight.Shutdown(codertestutil.Context(t, codertestutil.WaitLong))) - require.Equal(t, http.StatusOK, response.Code) + require.Equal(t, tc.status, response.Code) + require.Equal(t, tc.response, response.Body.String(), "extraction must not alter the forwarded response") require.Equal(t, []string{tc.body}, forwarded, "extraction must not alter the forwarded bytes") starts := rec.RecordedInterceptions() require.Len(t, starts, 1) require.Equal(t, tc.wantModel, starts[0].Model) end := rec.RecordedInterceptionEnd(starts[0].ID) require.NotNil(t, end) - require.Empty(t, end.ErrorType) + require.Equal(t, tc.wantError, end.ErrorType) + require.Equal(t, tc.wantMessage, end.ErrorMessage) + + // Response records are stamped with the interception and its end. + var prompts []recorder.PromptUsageRecord + for _, prompt := range rec.RecordedPromptUsages() { + require.Equal(t, starts[0].ID, prompt.InterceptionID) + require.Equal(t, end.EndedAt, prompt.CreatedAt) + prompt.InterceptionID = "" + prompt.CreatedAt = time.Time{} + prompts = append(prompts, *prompt) + } + require.Equal(t, tc.wantPrompts, prompts) + var tokens []recorder.TokenUsageRecord + for _, usage := range rec.RecordedTokenUsages() { + require.Equal(t, starts[0].ID, usage.InterceptionID) + require.Equal(t, end.EndedAt, usage.CreatedAt) + usage.InterceptionID = "" + usage.CreatedAt = time.Time{} + tokens = append(tokens, *usage) + } + require.Equal(t, tc.wantTokens, tokens) }) } } @@ -1085,9 +1176,11 @@ func TestForwardingRecordsInterception(t *testing.T) { require.NoError(t, err) require.NotEqual(t, uuid.Nil, id) require.WithinRange(t, start.StartedAt, before, time.Now()) - wantKind, wantStartHint := credential.KindBYOK, utils.MaskSecret(userSecretKey) + wantKind := credential.KindBYOK + wantStartHint := utils.MaskSecret(userSecretKey) if tc.pooled { - wantKind, wantStartHint = credential.KindCentralized, credential.HintFailoverKey + wantKind = credential.KindCentralized + wantStartHint = credential.HintFailoverKey } require.Equal(t, &recorder.InterceptionRecord{ ID: start.ID, diff --git a/aibridge/x/proxy/outcomes_internal_test.go b/aibridge/x/proxy/outcomes_internal_test.go index 6e87efc6e61..fe12d0ed9ef 100644 --- a/aibridge/x/proxy/outcomes_internal_test.go +++ b/aibridge/x/proxy/outcomes_internal_test.go @@ -7,7 +7,6 @@ import ( "net/http" "net/http/httptest" "strings" - "sync" "sync/atomic" "testing" "time" @@ -248,66 +247,6 @@ func TestForwardingBodyFailures(t *testing.T) { } } -// signalReadBody closes read once the first bytes arrive from the client. -type signalReadBody struct { - io.ReadCloser - read chan struct{} - once sync.Once -} - -func (b *signalReadBody) Read(p []byte) (int, error) { - n, err := b.ReadCloser.Read(p) - if n > 0 { - b.once.Do(func() { close(b.read) }) - } - return n, err -} - -// Closing the inflight gate unblocks a request whose body stalls mid-read, so -// shutdown does not wait for the client to finish sending. -func TestForwardingStalledBodyShutdown(t *testing.T) { - t.Parallel() - h := newTestForwardingHandler(t, provider.NewOpenAI(config.OpenAI{BaseURL: "https://upstream.example.test"}), nil) - rec := &testutil.MockRecorder{} - h.recorder = rec - h.transport = roundTripFunc(func(*http.Request) (*http.Response, error) { - t.Error("stalled requests must not call upstream") - return nil, io.ErrUnexpectedEOF - }) - reading, served := make(chan struct{}), make(chan struct{}) - // The handler response is recorded here, the stalled client cannot read it. - response := httptest.NewRecorder() - gateway := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { - defer close(served) - r.Body = &signalReadBody{ReadCloser: r.Body, read: reading} - ctx := aibcontext.AsActor(r.Context(), aibcontext.Actor{ID: uuid.New(), APIKeyID: uuid.NewString()}) - h.ServeHTTP(response, r.WithContext(ctx)) - })) - t.Cleanup(gateway.Close) - // The client sends one byte, then stalls until cleanup ends the body. - body, stall := io.Pipe() - t.Cleanup(func() { _ = stall.Close() }) - req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, gateway.URL+"/openai/v1/chat/completions", body) - require.NoError(t, err) - req.Header.Set("Authorization", "Bearer "+userSecretKey) - go func() { - resp, err := gateway.Client().Do(req) - if err == nil { - _ = resp.Body.Close() - } - }() - _, err = stall.Write([]byte("{")) - require.NoError(t, err) - - ctx := codertestutil.Context(t, codertestutil.WaitShort) - codertestutil.TryReceive(ctx, t, reading) - h.inflight.Close() - require.NoError(t, h.inflight.Shutdown(ctx), "a stalled body must not hold admission after close") - codertestutil.TryReceive(ctx, t, served) - require.Equal(t, http.StatusServiceUnavailable, response.Code, "cancellation is not a client error") - require.Empty(t, rec.RecordedInterceptions(), "canceled requests must not record a start") -} - // Key failover retries with the next pooled key, and an exhausted pool returns // its error response. func TestForwardingKeyOutcomes(t *testing.T) { @@ -427,7 +366,8 @@ func TestForwardingBYOKOutcomes(t *testing.T) { func TestForwardingStreamsAndCancels(t *testing.T) { t.Parallel() - canceled, forwarded := make(chan struct{}), make(chan struct{}) + canceled := make(chan struct{}) + forwarded := make(chan struct{}) release := make(chan struct{}) defer close(release) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/enterprise/coderd/aibridge_test.go b/enterprise/coderd/aibridge_test.go index fd9865877f3..04ebd66e36f 100644 --- a/enterprise/coderd/aibridge_test.go +++ b/enterprise/coderd/aibridge_test.go @@ -17,11 +17,13 @@ import ( "time" "github.com/google/uuid" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" aibclient "github.com/coder/coder/v2/aibridge/client" "github.com/coder/coder/v2/aibridge/fixtures" + "github.com/coder/coder/v2/cli" agplaibridge "github.com/coder/coder/v2/coderd/aibridge" aibridgedtest "github.com/coder/coder/v2/coderd/aibridgedtest" "github.com/coder/coder/v2/coderd/audit" @@ -1937,6 +1939,114 @@ func TestAIBridgeRouting(t *testing.T) { } } +// signalReadBody closes read once the first bytes arrive from the client. +type signalReadBody struct { + io.ReadCloser + read chan struct{} + once sync.Once +} + +func (b *signalReadBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + if n > 0 { + b.once.Do(func() { close(b.read) }) + } + return n, err +} + +// Forced gateway shutdown cancels a proxy request whose body stalls mid-read, +// and the stalled HTTP/1 client receives the rejection through the coderd +// router without first sending the rest of its body. +func TestAIGatewayProxyStalledBodyShutdown(t *testing.T) { + t.Parallel() + + ctx := testutil.Context(t, testutil.WaitLong) + upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + t.Error("stalled requests must not reach upstream") + })) + t.Cleanup(upstream.Close) + + dv := coderdtest.DeploymentValues(t) + dv.AI.BridgeConfig.Enabled = serpent.Bool(true) + dv.Experiments = []string{string(codersdk.ExperimentAIGatewayReverseProxy)} + db, ps := dbtestutil.NewDB(t) + client, _, api, firstUser := coderdenttest.NewWithAPI(t, &coderdenttest.Options{ + Options: &coderdtest.Options{DeploymentValues: dv, Database: db, Pubsub: ps}, + LicenseOptions: &coderdenttest.LicenseOptions{ + Features: license.Features{codersdk.FeatureAIBridge: 1}, + }, + }) + //nolint:gocritic // Owner role is needed for provider management. + _, err := client.CreateAIProvider(ctx, codersdk.CreateAIProviderRequest{ + Type: codersdk.AIProviderTypeOpenAI, + Name: "openai", + Enabled: true, + BaseURL: upstream.URL, + APIKeys: []string{"sk-embedded"}, + }) + require.NoError(t, err) + + srv, unsubscribe, err := cli.NewAIBridgeDaemon(ctx, cli.AIBridgeDaemonOptions{ + API: api.AGPL, + Config: api.DeploymentValues.AI.BridgeConfig, + Registerer: prometheus.NewRegistry(), + }) + require.NoError(t, err) + t.Cleanup(unsubscribe) + t.Cleanup(func() { _ = srv.Close() }) + // Only the request body is wrapped, behind the coderd middleware chain, so + // the gateway replies through the production ResponseWriter. + reading := make(chan struct{}) + api.AGPL.RegisterInMemoryAIBridgedHTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = &signalReadBody{ReadCloser: r.Body, read: reading} + srv.ServeHTTP(w, r) + })) + // The proxy backend is selected before the daemon reports ready. + require.Eventually(t, srv.Ready, testutil.WaitShort, testutil.IntervalFast) + + userClient, _ := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID) + // The client sends one byte, then stalls until cleanup ends the body. + body, stall := io.Pipe() + t.Cleanup(func() { _ = stall.Close() }) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, userClient.URL.String()+"/api/v2/ai-gateway/openai/v1/chat/completions", body) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+userClient.SessionToken()) + type reply struct { + status int + body string + } + replies := make(chan reply, 1) + go func() { + resp, err := (&http.Client{}).Do(req) + if !assert.NoError(t, err, "client must receive the rejection") { + replies <- reply{} + return + } + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + assert.NoError(t, err) + replies <- reply{status: resp.StatusCode, body: string(respBody)} + }() + _, err = stall.Write([]byte("{")) + require.NoError(t, err) + testutil.TryReceive(ctx, t, reading) + + // A done context forces shutdown, canceling admitted requests instead of + // waiting for them to drain. + forced, cancel := context.WithCancel(ctx) + cancel() + require.ErrorIs(t, srv.Shutdown(forced), context.Canceled) + + // Full duplex lets the reply reach the client without draining the + // stalled body first. + got := testutil.TryReceive(testutil.Context(t, testutil.WaitShort), t, replies) + require.Equal(t, http.StatusServiceUnavailable, got.status, "cancellation is not a client error") + require.Equal(t, "request canceled\n", got.body, "the reply must come from the canceled body read") + interceptions, err := db.GetAIBridgeInterceptions(ctx) + require.NoError(t, err) + require.Empty(t, interceptions, "canceled requests must not record a start") +} + func TestAIBridgeActorHeaderNames(t *testing.T) { t.Parallel()