Files
coder/aibridge/intercept/messages/blocking.go
T
Yevhenii Shcherbina 93089d447f fix: resolve Bedrock application inference profile ARNs (#28877)
AWS recommends [application inference
profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/cost-mgmt-application-inference-profiles.html)
for attributing Bedrock spend to a team or workload, which requires
invoking Bedrock with the profile ARN as the `modelId`. AI Gateway used
the configured Bedrock model for both the invocation target and model
capability detection, and capability detection is substring matching
against model IDs. Application inference profile ARNs are opaque, so
they matched nothing.

Reproduced against a profile wrapping `anthropic.claude-opus-4-8`: the
client sent `thinking.type: "adaptive"`, the gateway rewrote it to
`enabled` + `budget_tokens` because the ARN did not look like an
adaptive-capable model, and Bedrock returned

```text
400 "thinking.type.enabled" is not supported for this model. Use "thinking.type.adaptive" and "output_config.effort" to control thinking behavior.
```

Models that accept both shapes, such as Sonnet 4.6, did not fail but had
adaptive thinking silently downgraded. The ARN was also recorded as the
interception model, so those requests never matched a price and may
appear in the weekly Missing AI Model Prices report.

The gateway now resolves application inference profile ARNs through
`GetInferenceProfile` and uses the model behind them for capability
detection, usage records, pricing, and metrics, while still invoking the
profile so AWS records the cost attribution. Resolution runs only for
`application-inference-profile` ARNs, so plain model IDs and
system-defined inference profile ARNs, which already carry the model ID,
cost no AWS call and need no new permission. Deployments that do
configure a profile must grant `bedrock:GetInferenceProfile` to the
identity the gateway already uses, including any assumed role.
Resolution failure fails provider construction, matching how other
misconfigured providers behave: the failure is logged and the provider
is reported as errored rather than serving requests it would shape
incorrectly.

## Concerns

**Every provider reload re-resolves every application inference
profile.**

Any provider create/update/delete publishes on
`AIProvidersChangedChannel`, and each subscriber responds by rebuilding
its whole snapshot: `Reload` fetches all providers and
`BuildProvidersFromProto` constructs every one of them from scratch
before `ReplaceProviders` swaps the snapshot in.

That rebuild used to be purely local work. This PR makes it hit the
network: a Bedrock provider configured with an AIP ARN now performs a
synchronous `GetInferenceProfile` call during construction,
sequentially, before the snapshot is published. So editing an unrelated
OpenAI provider re-resolves every AIP in the deployment. Consequences:

- Reload latency grows with the number of AIP-configured providers,
bounded by the 30s resolution timeout per provider.
- A transient AWS failure during an unrelated provider edit drops the
Bedrock provider from the new snapshot until the next reload, surfacing
as a 404 for a provider whose configuration never changed.

An ARN-keyed resolution cache would remove this: the Bedrock API has no
`UpdateInferenceProfile`, so a profile's underlying model is fixed at
creation and repointing requires a new ARN, hence a config change and a
reload. A process-lifetime cache is therefore sound with no invalidation
logic. Left out of this PR to keep it scoped.

## Improvement Options

1. Keep it as is.
2. Add a per-process in-memory cache that maps AIP ARNs to models.
3. Add a database-level cache for AIP-to-model resolution.
4. Move AIP resolution to the per-LLM-request path and cache the result
there.

My choice would be either 3 or 4. See the relevant P1s:
- https://github.com/coder/coder/pull/28877#discussion_r3936255218
- https://github.com/coder/coder/pull/28877#discussion_r3936255211

Closes https://linear.app/codercom/issue/AIGOV-488

Created by Coder Agents on behalf of @evgeniy-scherbina.
2026-09-07 21:01:39 -04:00

402 lines
14 KiB
Go

package messages
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/http"
"time"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/google/uuid"
mcplib "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/tidwall/sjson"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
aibcontext "github.com/coder/coder/v2/aibridge/context"
"github.com/coder/coder/v2/aibridge/intercept"
"github.com/coder/coder/v2/aibridge/intercept/eventstream"
"github.com/coder/coder/v2/aibridge/keypool"
"github.com/coder/coder/v2/aibridge/mcp"
"github.com/coder/coder/v2/aibridge/recorder"
"github.com/coder/coder/v2/aibridge/tracing"
)
type BlockingInterception struct {
interceptionBase
}
func NewBlockingInterceptor(
id uuid.UUID,
reqPayload RequestPayload,
cfg intercept.Config,
cred intercept.Credential,
bedrock *BedrockRuntime,
clientHeaders http.Header,
tracer trace.Tracer,
) *BlockingInterception {
return &BlockingInterception{interceptionBase: interceptionBase{
id: id,
reqPayload: reqPayload,
cfg: cfg,
cred: cred,
bedrock: bedrock,
clientHeaders: clientHeaders,
tracer: tracer,
isSmallFastModel: isSmallFastModel(reqPayload.model()),
}}
}
func (i *BlockingInterception) Setup(logger slog.Logger, rec recorder.Recorder, mcpProxy mcp.ServerProxier) {
i.interceptionBase.Setup(logger.Named("blocking"), rec, mcpProxy)
}
func (i *BlockingInterception) TraceAttributes(r *http.Request) []attribute.KeyValue {
return i.baseTraceAttributes(r, false)
}
func (*BlockingInterception) Streaming() bool {
return false
}
func (i *BlockingInterception) ProcessRequest(w http.ResponseWriter, r *http.Request) (outErr error) {
if len(i.reqPayload) == 0 {
return xerrors.New("developer error: request payload is empty")
}
ctx, span := i.tracer.Start(r.Context(), "Intercept.ProcessRequest", trace.WithAttributes(tracing.InterceptionAttributesFromContext(r.Context())...))
defer tracing.EndSpanErr(span, &outErr)
i.injectTools()
var prompt *string
promptText, promptFound, promptErr := i.reqPayload.lastUserPrompt()
if promptErr != nil {
i.logger.Warn(ctx, "failed to retrieve last user prompt", slog.Error(promptErr))
} else if promptFound {
prompt = &promptText
}
// TODO(ssncferreira): inject actor headers directly in the client-header
// middleware instead of using SDK options.
opts := []option.RequestOption{option.WithRequestTimeout(time.Second * 600)}
if actor := aibcontext.ActorFromContext(r.Context()); actor != nil && i.cfg.SendActorHeaders {
opts = append(opts, intercept.ActorHeadersAsAnthropicOpts(actor)...)
}
svc, err := i.newMessagesService(ctx, opts...)
if err != nil {
err = xerrors.Errorf("create anthropic client: %w", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
logger := i.logger.With(slog.F("model", i.Model()))
var resp *anthropic.Message
// Accumulate usage across the entire streaming interaction (including tool reinvocations).
var cumulativeUsage anthropic.Usage
// Sum the key attempts across all iterations and record once when the
// interception completes.
var totalKeyAttempts int
if cp, ok := intercept.AsCentralizedPool(i.cred); ok {
defer func() {
cp.Pool.RecordAttempts(totalKeyAttempts)
}()
}
for {
// TODO add outer loop span (https://github.com/coder/aibridge/issues/67)
// Rebuilt per iteration: i.reqPayload mutates when an agentic
// continuation appends tool results, so withBody must reflect
// the latest payload on every upstream call.
callOpts := []option.RequestOption{i.withBody()}
var keyAttempts int
resp, keyAttempts, err = i.newMessage(ctx, svc, callOpts)
totalKeyAttempts += keyAttempts
if err != nil {
if eventstream.IsConnError(err) {
// Can't write a response, just error out.
return xerrors.Errorf("upstream connection closed: %w", err)
}
// The failover loop may return a keypool exhaustion
// error. Check before the SDK-error path.
var keyPoolErr *keypool.Error
if errors.As(err, &keyPoolErr) {
i.writeUpstreamError(w, ResponseErrorFromKeyPool(keyPoolErr))
return xerrors.Errorf("key pool exhausted: %w", err)
}
if antErr := ResponseErrorFromAPIError(err); antErr != nil {
i.writeUpstreamError(w, antErr)
return xerrors.Errorf("anthropic API error: %w", err)
}
http.Error(w, "internal error", http.StatusInternalServerError)
return xerrors.Errorf("internal error: %w", err)
}
if prompt != nil {
_ = i.recorder.RecordPromptUsage(ctx, &recorder.PromptUsageRecord{
InterceptionID: i.ID().String(),
MsgID: resp.ID,
Prompt: *prompt,
})
prompt = nil
}
i.recordTokenUsage(ctx, resp.ID, resp.Usage)
accumulateUsage(&cumulativeUsage, resp.Usage)
// Capture any thinking blocks that were returned.
for _, t := range i.extractModelThoughts(resp) {
_ = i.recorder.RecordModelThought(ctx, &recorder.ModelThoughtRecord{
InterceptionID: i.ID().String(),
Content: t.Content,
Metadata: t.Metadata,
})
}
// Handle tool calls.
var pendingToolCalls []anthropic.ToolUseBlock
for _, c := range resp.Content {
toolUse := c.AsToolUse()
if toolUse.ID == "" {
continue
}
if i.mcpProxy != nil && i.mcpProxy.GetTool(toolUse.Name) != nil {
pendingToolCalls = append(pendingToolCalls, toolUse)
continue
}
// If tool is not injected, track it since the client will be handling it.
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
InterceptionID: i.ID().String(),
MsgID: resp.ID,
ToolCallID: toolUse.ID,
Tool: toolUse.Name,
Args: toolUse.Input,
Injected: false,
})
}
// If no injected tool calls, we're done.
if len(pendingToolCalls) == 0 {
break
}
var loopMessages []anthropic.MessageParam
loopMessages = append(loopMessages, resp.ToParam())
// Process each pending tool call.
for _, tc := range pendingToolCalls {
if i.mcpProxy == nil {
continue
}
tool := i.mcpProxy.GetTool(tc.Name)
if tool == nil {
logger.Warn(ctx, "tool not found in manager", slog.F("tool", tc.Name))
// Continue to next tool call, but still append an error tool_result
loopMessages = append(loopMessages,
anthropic.NewUserMessage(anthropic.NewToolResultBlock(tc.ID, fmt.Sprintf("Error: tool %s not found", tc.Name), true)),
)
continue
}
res, err := tool.Call(ctx, tc.Input, i.tracer)
_ = i.recorder.RecordToolUsage(ctx, &recorder.ToolUsageRecord{
InterceptionID: i.ID().String(),
MsgID: resp.ID,
ToolCallID: tc.ID,
ServerURL: &tool.ServerURL,
Tool: tool.Name,
Args: tc.Input,
Injected: true,
InvocationError: err,
})
if err != nil {
// Always provide a tool_result even if the tool call failed
loopMessages = append(loopMessages,
anthropic.NewUserMessage(anthropic.NewToolResultBlock(tc.ID, fmt.Sprintf("Error: calling tool: %v", err), true)),
)
continue
}
// Process tool result
toolResult := anthropic.ContentBlockParamUnion{
OfToolResult: &anthropic.ToolResultBlockParam{
ToolUseID: tc.ID,
IsError: anthropic.Bool(false),
},
}
var hasValidResult bool
for _, content := range res.Content {
switch cb := content.(type) {
case *mcplib.TextContent:
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: cb.Text,
},
})
hasValidResult = true
// TODO: is there a more correct way of handling these non-text content responses?
case *mcplib.EmbeddedResource:
resource := cb.Resource
switch {
case resource == nil:
i.logger.Warn(ctx, "embedded resource with no contents")
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: "Error: embedded resource with no contents",
},
})
toolResult.OfToolResult.IsError = anthropic.Bool(true)
hasValidResult = true
case resource.Blob != nil:
// The SDK decodes base64 during unmarshal; re-encode
// the bytes for model-facing text.
val := fmt.Sprintf("Binary resource (MIME: %s, URI: %s): %s",
resource.MIMEType, resource.URI, base64.StdEncoding.EncodeToString(resource.Blob))
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: val,
},
})
hasValidResult = true
default:
val := fmt.Sprintf("Binary resource (MIME: %s, URI: %s): %s",
resource.MIMEType, resource.URI, resource.Text)
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: val,
},
})
hasValidResult = true
}
default:
i.logger.Warn(ctx, "not handling non-text tool result", slog.F("type", fmt.Sprintf("%T", cb)))
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: "Error: unsupported tool result type",
},
})
toolResult.OfToolResult.IsError = anthropic.Bool(true)
hasValidResult = true
}
}
// If no content was processed, still add a tool_result
if !hasValidResult {
i.logger.Warn(ctx, "no tool result added", slog.F("content_len", len(res.Content)), slog.F("is_error", res.IsError))
toolResult.OfToolResult.Content = append(toolResult.OfToolResult.Content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{
Text: "Error: no valid tool result content",
},
})
toolResult.OfToolResult.IsError = anthropic.Bool(true)
}
if len(toolResult.OfToolResult.Content) > 0 {
loopMessages = append(loopMessages, anthropic.NewUserMessage(toolResult))
}
}
updatedPayload, rewriteErr := i.reqPayload.appendedMessages(loopMessages)
if rewriteErr != nil {
http.Error(w, rewriteErr.Error(), http.StatusInternalServerError)
return xerrors.Errorf("rewrite payload for agentic loop: %w", rewriteErr)
}
i.reqPayload = updatedPayload
}
if resp == nil {
return nil
}
// Overwrite response identifier since proxy obscures injected tool call invocations.
sj, err := sjson.Set(resp.RawJSON(), "id", i.ID().String())
if err != nil {
return xerrors.Errorf("marshal response id failed: %w", err)
}
// Overwrite the response's usage with the cumulative usage across any inner loops which invokes injected MCP tools.
sj, err = sjson.Set(sj, "usage", cumulativeUsage)
if err != nil {
return xerrors.Errorf("marshal response usage failed: %w", err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(sj))
return nil
}
// newMessage routes by credential type, returning the upstream message, the
// number of key attempts made for this call, and any error. A centralized key
// pool fails over across keys, while BYOK and Bedrock authenticate with a
// single, fixed credential baked into svc, so they make one attempt.
func (i *BlockingInterception) newMessage(ctx context.Context, svc anthropic.MessageService, opts []option.RequestOption) (*anthropic.Message, int, error) {
if cp, ok := intercept.AsCentralizedPool(i.cred); ok {
return i.newMessageWithKeyFailover(ctx, svc, cp, opts)
}
msg, err := i.newMessageWithKey(intercept.WithCredentialInfo(ctx, i.cred), svc, opts...)
return msg, 0, err
}
// newMessageWithKey performs a single upstream call.
func (i *BlockingInterception) newMessageWithKey(ctx context.Context, svc anthropic.MessageService, opts ...option.RequestOption) (_ *anthropic.Message, outErr error) {
_, span := i.tracer.Start(ctx, "Intercept.ProcessRequest.Upstream", trace.WithAttributes(tracing.InterceptionAttributesFromContext(ctx)...))
defer tracing.EndSpanErr(span, &outErr)
return svc.New(ctx, anthropic.MessageNewParams{}, opts...)
}
// newMessageWithKeyFailover walks the centralized key pool, trying each key
// until one succeeds or the pool is exhausted. Keys are marked temporary on
// 429 and permanent on 401/403. Errors that aren't key-specific don't trigger
// failover and are returned to the caller. It returns the upstream message,
// the number of key attempts made for this call, and any error.
func (i *BlockingInterception) newMessageWithKeyFailover(ctx context.Context, svc anthropic.MessageService, cp *intercept.CentralizedPool, opts []option.RequestOption) (*anthropic.Message, int, error) {
walker := cp.Pool.Walker()
for {
key, keyPoolErr := cp.NextKey(walker)
if keyPoolErr != nil {
return nil, walker.Attempts(), keyPoolErr
}
ctx = intercept.WithCredentialInfo(ctx, i.cred)
i.logger.Debug(ctx, "using centralized api key")
requestOpts := append([]option.RequestOption{}, opts...)
requestOpts = append(requestOpts,
option.WithAPIKey(key.Value()),
// Disable SDK retries because the failover loop
// handles retries via key rotation.
option.WithMaxRetries(0),
)
msg, err := i.newMessageWithKey(ctx, svc, requestOpts...)
// Key-specific failure: try the next key.
if i.markKeyOnError(ctx, key, err) {
continue
}
// Either success (msg, nil) or a non-key error (nil, err):
// nothing to retry, return as-is.
return msg, walker.Attempts(), err
}
}