Compaction summaries asked the provider for 1.5 times the model's configured output cap. When an admin adds a known model, the form fills `max_output_tokens` with the provider maximum, 128,000 for `claude-opus-5-5`, so each summary request sent `max_tokens: 192000`. Anthropic rejected it with HTTP 400 (`max_tokens: 192000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5`), so compaction failed and the chat could not shrink its context. `compactionSummaryCall` now keeps the chat call's cap. The 50% headroom came from #28886, which accepted the overshoot for caps set at a provider ceiling as a tradeoff. With catalog defaults, that case is the common one. `GenerateCompaction` still lowers the cap to the remaining context window when that is smaller. Closes [CODAGT-1428](https://linear.app/codercom/issue/CODAGT-1428). The ticket also shows "Your input exceeds the context window" on a summary request. That is a separate failure, which #30766 handles (merged after the ticket was filed), so this PR does not change it. **Tests** - New `TestActiveServer_ManualCompaction/summary keeps the configured output cap`: a 128,000 cap reaches both the chat turn and the summary request unchanged. On the old code it fails with `expected: 128000 actual: 192000`. - `TestBuildTurnEnvironmentClampsRequestedReasoningEffortToMax` and the compaction hook tests now expect the unchanged default cap (32,000 instead of 48,000). #30942 rewrites the first test and keeps a `3 * defaultChatMaxOutputTokens / 2` expectation, so whichever PR merges second drops that factor. **Validation** - `go test ./coderd/x/chatd/ ./coderd/x/chatd/chatloop/ -count=1`: passes - `make pre-commit`: passes - Remote dogfood UAT against `claude-opus-5-5` with a 128,000 cap: on `main`, manual, automatic, and compaction-model-override summaries asked for 192,000 tokens and failed with the 400 above. On this branch, all 16 summary requests (the same flows plus an unset cap and a small context window) succeeded, and none asked for more than its configured cap. Chat turn `max_tokens` was the same on both. UAT ran on `9230a6e9fa1`; the head `3633adef53e` only adds a comment edit. - No new dependencies. The polish pass and the test audit changed no files. - Codex review on `3633adef53e`: no findings. > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description.
259 lines
8.9 KiB
Go
259 lines
8.9 KiB
Go
package chatd
|
|
|
|
import (
|
|
"context"
|
|
"sync/atomic"
|
|
|
|
"charm.land/fantasy"
|
|
"golang.org/x/xerrors"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbauthz"
|
|
"github.com/coder/coder/v2/coderd/util/ptr"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatdebug"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatloop"
|
|
"github.com/coder/coder/v2/coderd/x/chatd/chatprovider"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
const defaultChatMaxOutputTokens = int64(32_000)
|
|
|
|
// fixedModelCall selects a provider/model pair that has no config row of its
|
|
// own (computer use).
|
|
type fixedModelCall struct {
|
|
providerType string
|
|
modelName string
|
|
callConfig codersdk.ChatModelCallConfig
|
|
}
|
|
|
|
type modelCallSpec struct {
|
|
// purpose labels resolver logs only; it does not affect call behavior.
|
|
purpose string
|
|
chat database.Chat
|
|
explicitConfig *database.ChatModelConfig
|
|
fixedModel *fixedModelCall
|
|
// requestedEffort overrides the config's default reasoning effort,
|
|
// clamped to the config's max.
|
|
requestedEffort *string
|
|
// maxOutputTokens overrides the config's output-token cap and the
|
|
// package default.
|
|
maxOutputTokens *int64
|
|
// chatdScopedRoute resolves the route with chatd scope. Deployment-wide
|
|
// override models must route for user-owned chats regardless of the
|
|
// caller's actor.
|
|
chatdScopedRoute bool
|
|
buildOptions modelBuildOptions
|
|
}
|
|
|
|
func chatRequestedEffort(chat database.Chat) *string {
|
|
if !chat.LastReasoningEffort.Valid {
|
|
return nil
|
|
}
|
|
return new(string(chat.LastReasoningEffort.ChatReasoningEffort))
|
|
}
|
|
|
|
// modelCallConfigParseError lets the advisor distinguish malformed options
|
|
// from route and client failures when deciding whether to fall back.
|
|
type modelCallConfigParseError struct{ err error }
|
|
|
|
func (e modelCallConfigParseError) Error() string {
|
|
return "parse model call config: " + e.err.Error()
|
|
}
|
|
|
|
func (e modelCallConfigParseError) Unwrap() error { return e.err }
|
|
|
|
type resolvedModelCall struct {
|
|
model chatprovider.Model
|
|
dbConfig database.ChatModelConfig
|
|
callConfig codersdk.ChatModelCallConfig
|
|
providerOptions fantasy.ProviderOptions
|
|
resolvedProvider string
|
|
resolvedModel string
|
|
resolvedEffort string
|
|
route aiGatewayModelRoute
|
|
debugEnabled bool
|
|
// reasoningRejected reports whether the provider rejected encrypted
|
|
// reasoning replayed into a call to model.
|
|
reasoningRejected *atomic.Bool
|
|
}
|
|
|
|
// stageModel uses the configured provider type rather than
|
|
// resolvedProvider, which is inferred from the model name for types such
|
|
// as copilot.
|
|
func (r resolvedModelCall) stageModel() chatloop.StageModel {
|
|
stageModel := chatloop.StageModel{
|
|
ProviderType: string(r.route.Provider.Type),
|
|
Model: r.resolvedModel,
|
|
Effort: r.resolvedEffort,
|
|
}
|
|
if r.model.Valid() {
|
|
stageModel.Provider = r.model.Provider()
|
|
}
|
|
return stageModel
|
|
}
|
|
|
|
// resolveModelCall is the single pipeline from a spec to a ready model
|
|
// client plus the call metadata flows need.
|
|
func (p *Server) resolveModelCall(ctx context.Context, spec modelCallSpec) (resolvedModelCall, error) {
|
|
out := resolvedModelCall{}
|
|
|
|
var modelName string
|
|
var configOptions []byte
|
|
switch {
|
|
case spec.fixedModel != nil:
|
|
modelName = spec.fixedModel.modelName
|
|
case spec.explicitConfig != nil:
|
|
out.dbConfig = *spec.explicitConfig
|
|
modelName = out.dbConfig.Model
|
|
configOptions = out.dbConfig.Options
|
|
default:
|
|
dbConfig, err := p.resolveModelConfig(ctx, spec.chat)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("resolve model config: %w", err)
|
|
}
|
|
if !dbConfig.Enabled {
|
|
return resolvedModelCall{}, xerrors.Errorf("chat model config %s is disabled", dbConfig.ID)
|
|
}
|
|
out.dbConfig = dbConfig
|
|
modelName = dbConfig.Model
|
|
configOptions = dbConfig.Options
|
|
}
|
|
|
|
// clientCallConfig drives client construction; out.callConfig drives
|
|
// per-call option derivation and comes from the chat model for computer
|
|
// use, whose fixed model has no config of its own.
|
|
clientCallConfig, err := parseModelConfigOptions(configOptions)
|
|
if err != nil {
|
|
return resolvedModelCall{}, modelCallConfigParseError{err: err}
|
|
}
|
|
if spec.fixedModel != nil {
|
|
out.callConfig = spec.fixedModel.callConfig
|
|
} else {
|
|
out.callConfig = clientCallConfig
|
|
}
|
|
switch {
|
|
case spec.maxOutputTokens != nil:
|
|
out.callConfig.MaxOutputTokens = spec.maxOutputTokens
|
|
case out.callConfig.MaxOutputTokens == nil:
|
|
out.callConfig.MaxOutputTokens = ptr.Ref(defaultChatMaxOutputTokens)
|
|
}
|
|
|
|
routeCtx := ctx
|
|
if spec.chatdScopedRoute {
|
|
//nolint:gocritic // Deployment-wide override models need chatd-scoped provider reads for user-owned chats.
|
|
routeCtx = dbauthz.AsChatd(ctx)
|
|
}
|
|
if spec.fixedModel != nil {
|
|
out.route, err = p.resolveModelRouteForProviderType(routeCtx, spec.chat.OwnerID, spec.fixedModel.providerType)
|
|
} else {
|
|
out.route, err = p.resolveModelRouteForConfig(routeCtx, spec.chat.OwnerID, out.dbConfig)
|
|
}
|
|
if err != nil {
|
|
return resolvedModelCall{}, err
|
|
}
|
|
|
|
// The resolved identity feeds metadata, logs, and debug labels. The
|
|
// client is constructed with the configured model string so gateway
|
|
// validation sees the name exactly as configured.
|
|
out.resolvedProvider, out.resolvedModel, err = chatprovider.ResolveModelWithProviderHint(
|
|
modelName,
|
|
out.route.ModelProviderHint,
|
|
)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("resolve model metadata: %w", err)
|
|
}
|
|
|
|
debugSvc := p.debugService()
|
|
out.debugEnabled = debugSvc != nil && debugSvc.IsEnabled(ctx, spec.chat.ID, spec.chat.OwnerID)
|
|
|
|
// Coder-scale effort, before provider mapping can change or drop it.
|
|
if effectiveEffort := chatprovider.ResolveReasoningEffort(spec.requestedEffort, out.callConfig.ReasoningEffort); effectiveEffort != nil {
|
|
out.resolvedEffort = *effectiveEffort
|
|
}
|
|
|
|
buildOpts := spec.buildOptions
|
|
buildOpts.RecordHTTP = out.debugEnabled
|
|
buildOpts.StageModel = out.stageModel()
|
|
model, err := p.newModel(ctx, modelClientRequest{
|
|
Chat: spec.chat,
|
|
ModelName: modelName,
|
|
UserAgent: chatprovider.UserAgent(),
|
|
ExtraHeaders: chatprovider.CoderHeaders(spec.chat),
|
|
CallConfig: clientCallConfig,
|
|
}, out.route, buildOpts)
|
|
if err != nil {
|
|
return resolvedModelCall{}, xerrors.Errorf("create model: %w", err)
|
|
}
|
|
model = p.withThinkingDropBlock(model, out.route.Provider.ID, clientCallConfig, spec.chat.ID)
|
|
out.reasoningRejected = &atomic.Bool{}
|
|
model = p.withEncryptedReasoningFallback(model, spec.chat.ID, out.reasoningRejected)
|
|
|
|
if out.debugEnabled {
|
|
model = model.WithLanguageModel(chatdebug.WrapModel(model.LanguageModel(), debugSvc, chatdebug.RecorderOptions{
|
|
ChatID: spec.chat.ID,
|
|
OwnerID: spec.chat.OwnerID,
|
|
}))
|
|
}
|
|
out.model = model
|
|
|
|
// Only the derived provider options see the coerced config: callConfig
|
|
// stays as configured so provider substitution (computer use rerouting
|
|
// to direct OpenAI) starts from the original value.
|
|
out.providerOptions = chatprovider.ProviderOptionsForCall(
|
|
out.model,
|
|
coerceBedrockReasoningSummary(out.route.Provider.Type, modelName, out.callConfig),
|
|
spec.requestedEffort,
|
|
)
|
|
|
|
p.logger.Debug(ctx, "resolved model call",
|
|
slog.F("purpose", spec.purpose),
|
|
slog.F("chat_id", spec.chat.ID),
|
|
slog.F("provider", out.resolvedProvider),
|
|
slog.F("model", out.resolvedModel),
|
|
slog.F("reasoning_effort", out.resolvedEffort),
|
|
slog.F("debug_enabled", out.debugEnabled),
|
|
)
|
|
return out, nil
|
|
}
|
|
|
|
func (r resolvedModelCall) newCall() fantasy.Call {
|
|
return fantasy.Call{
|
|
ProviderOptions: r.providerOptions,
|
|
MaxOutputTokens: r.callConfig.MaxOutputTokens,
|
|
Temperature: r.callConfig.Temperature,
|
|
TopP: r.callConfig.TopP,
|
|
TopK: r.callConfig.TopK,
|
|
PresencePenalty: r.callConfig.PresencePenalty,
|
|
FrequencyPenalty: r.callConfig.FrequencyPenalty,
|
|
}
|
|
}
|
|
|
|
// compactionSummaryCall follows the resolved call template, except summaries
|
|
// must not call tools. Streaming avoids the Anthropic SDK's non-streaming
|
|
// duration limit, while the explicit cap prevents adaptive thinking from
|
|
// exhausting fantasy's smaller provider default before producing summary text.
|
|
// The cap is not raised: the configured cap is the provider ceiling chatd
|
|
// knows, and providers reject a larger one. GenerateCompaction can only
|
|
// lower it, to the remaining context window.
|
|
func compactionSummaryCall(resolved resolvedModelCall) fantasy.Call {
|
|
call := resolved.newCall()
|
|
toolChoiceNone := fantasy.ToolChoiceNone
|
|
call.ToolChoice = &toolChoiceNone
|
|
return call
|
|
}
|
|
|
|
func (r resolvedModelCall) newObjectCall(schemaName, schemaDescription string, maxOutputTokens int64) fantasy.ObjectCall {
|
|
return fantasy.ObjectCall{
|
|
SchemaName: schemaName,
|
|
SchemaDescription: schemaDescription,
|
|
MaxOutputTokens: ptr.Ref(maxOutputTokens),
|
|
Temperature: r.callConfig.Temperature,
|
|
TopP: r.callConfig.TopP,
|
|
TopK: r.callConfig.TopK,
|
|
PresencePenalty: r.callConfig.PresencePenalty,
|
|
FrequencyPenalty: r.callConfig.FrequencyPenalty,
|
|
ProviderOptions: r.providerOptions,
|
|
}
|
|
}
|