OpenAI Responses chats default to `store=false`, and chatd only replayed reasoning as an `item_reference`, which needs provider-side storage. Reasoning was therefore dropped between tool steps and turns, so reasoning models lost their chain of thought mid-task. This pins coder/fantasy `coder_2_33` at 6ba8681, which includes fantasy #63 (and #64, #65, and #66). #63 captures each completed reasoning item (ID, `encrypted_content`, summary) and replays it in full regardless of `store`. In chatd: - Every Responses call requests `reasoning.encrypted_content`. The `store` default and configured includes are unchanged, and Chat Completions requests are untouched. - Prompt rebuilds keep reasoning parts without visible text when they carry finalized encrypted state, so reasoning survives durable history and coderd restarts. - The provider-switch sanitizer also strips OpenAI reasoning from history produced by a different or unknown provider instance, since reasoning IDs and encrypted content only resolve where they were issued. - A compaction model override on a different provider instance, or with a different model, gets a compaction prompt without the chat's OpenAI reasoning. - Each saved reasoning part records the provider instance, model, and credential (the deployment's or the user's personal API key) that produced it, and the sanitizer keeps it only when all three match the current turn, because another model, or the organization behind another credential, can reject the encrypted content. Switching models, adding or removing a personal key, or editing a config's model or provider drops the earlier reasoning; switching back restores it. The record is never returned by the API. Reasoning saved before this change has no record and follows its model config. - If OpenAI rejects replayed reasoning it cannot decrypt (`invalid_encrypted_content`), for example after the deployment's key is replaced with one from another organization, the request is retried once without reasoning, and the reasoning that step produces is saved with the provider's next rejection epoch. Epochs are kept separately for each provider, model, and credential. Later steps and turns leave out reasoning from earlier epochs, on any replica and after restarts, so only the first request after the change is rejected and newer reasoning keeps replaying. A retried step that returns no reasoning saves its epoch on its first part. The advisor's prompt never includes OpenAI reasoning, as on `main`. ## Testing Rebased onto main at98332c739bas 5735acb36ed (same tree as merging the pre-rebase head a378071862a with main; older SHAs below refer to the pre-rebase history). 3c17d807a33 then adds the model to the reasoning record, 21156b2b32e pins Fantasy d55a867, which treats a response that echoes `store: false` as unstored, bf795daa923 adds the retry and the advisor change, 7eb8b1d029a moves the pin to 88cffb5 (`coder_2_33` merged into #63; its OpenAI provider code is identical to d55a867), and f4f40734a41 pins `coder_2_33` at 6ba8681 once #63 merged. That adds fantasy #66, which replays the Responses message phase on assistant text. abccede81f7 makes the retry remember rejected reasoning in the process. The branch was then rebased onto main atabc2faed60, so every SHA above refers to the pre-rebase history.5fb3ce1689replaces that memory with the credential and a rejection epoch saved on each reasoning part, and62b5cb532akeeps epochs per provider, model, and credential and saves the epoch when the retried step returns no reasoning.1057beb327hides the four internal fields from the Swagger spec and API reference, and29a705e099merges main atd68b2c8b25. Its only conflicts were the fantasy pin (kept at 6ba8681, whose `coder_2_33` history includes main's 3510552) and test imports. - Tests in `chatprompt`, `chatprovider`, `chatsanitize`, the provider-switch sanitizer, and `integration_responses_test.go` cover tool-step and durable replay, legacy and incomplete metadata, provider switches, and a web search chat switching from `store=false` to `store=true`. Integration tests also cover the retry, a later tool step after it, the next turn on a fresh server against the same database (with and without reasoning in the retried step), a personal key added mid-chat, and the advisor prompt. Red-green verified, including a config whose model is edited in place. The compaction override's model check has unit tests and UAT coverage but no integration test. `go vet`, targeted race tests, and the pre-commit hook (gen, fmt, lint, build) pass. Local pre-push hooks were skipped; CI covers them. - Remote UAT on dogfood with real gpt-5-mini and gpt-5.4 behind a logging proxy that checks every request body. Rounds 1 and 2 failed on dangling item references (both fixed). Rounds 3 to 5 passed (ee3c0bf3d60, 0580870b5ff, a378071862a): tool-step and durable replay, restarts, interrupts, provider switches and config repoints, web search history, and compaction overrides. Both test providers shared one upstream account, so cross-provider checks cover request shape, not a real rejection. Round 6 at 21156b2b32e (model record) with gpt-5-mini and gpt-5-nano: PASS. 151 Responses requests, all 200; no request carried reasoning from a different model except an older, unrecorded part that follows its config by design. Same-model config switches, switching back, edits to a config's model, a mid-turn switch, restarts, and a same-provider compaction override with a different model all behaved as described. Round 7 at bf795daa923 (retry and advisor): PASS. Through AI Gateway, a corrupted saved blob is rejected with HTTP 400 `invalid_encrypted_content`. All 14 rejected requests were retried once without reasoning and returned 200, a different 400 was not retried, and advisor requests on the chat model, a same-provider override, and another provider carried no reasoning. - f4f40734a41 changes only the pin. Its new OpenAI code is fantasy #66, which UAT rounds 1 to 7 did not run. A live check of fantasy 6ba8681 through AI Gateway, two turns with tool calls on gpt-5.5 and gpt-5-mini with `store` false and true: all 18 requests returned 200, and the gpt-5.5 requests replayed encrypted reasoning followed by assistant messages with the `commentary` and `final_answer` phases. `go test ./coderd/x/chatd/... ./codersdk/` passes (21 packages) on the same fantasy tree. - UAT round 8 at abccede81f7 (remembered rejection, and fantasy #66 through chatd) with gpt-5.5, gpt-5-mini, and gpt-5-nano: PASS. 110 requests; the 6 rejections were 5 corrupted saved blobs, each retried once without reasoning and answered 200, and one unrelated `temperature` error that was not retried. After the first rejection, later steps and turns in that chat were never rejected again and replayed newer reasoning. A coderd restart cost one more rejection, which also dropped reasoning saved after the first one, and a second chat was unaffected. gpt-5.5 requests replayed assistant messages with the phases the model returned, with `store` false and true. - UAT round 9 at62b5cb532a(saved rejection epoch, personal key switch) with gpt-5.5, gpt-5-mini, and gpt-5-nano: PASS. 158 Responses and 7 Chat Completions requests; the 6 rejections were corrupted saved blobs, each retried once without reasoning and answered 200, and an unrelated `temperature` error was not retried. After a coderd restart, and on a second coderd against the same database, the chat was not rejected again and kept replaying the reasoning saved after the rejection. Adding a personal key left out the deployment key's reasoning before sending, and removing it brought that reasoning back. A retried step without reasoning, two chats rejected at once, compaction, a model switch after a rejection, and a switch to Chat Completions and back all behaved as described. ## Review record - Independent full-branch test audit atbbe1a1b27a: PASS. - Codex through a378071862: compaction overrides kept foreign reasoning and configs could be repointed to another provider (both fixed); a request for documentation TODOs and two behaviors that already exist on `main` (declined). - Codex on 5735acb36e: two findings. Reasoning replayed after a same-provider model switch: fixed in 3c17d807a33. A provider's base URL edited in place keeps its reasoning: covered by the retry in bf795daa923. - Codex on 21156b2b32, bf795daa92, and 7eb8b1d029: no major issues. Codex on f4f40734a4: rejected reasoning stayed in the chat's history, so each later request in that chat was rejected and retried again without any reasoning. Fixed in abccede81f7. Codex on abccede81f: that memory was lost on a restart or another replica, where the next rejection also dropped newer reasoning, and it grew without bound. Fixed in5fb3ce1689. Codex on5fb3ce1689: a rejection advanced the epoch for every model and credential on the provider, and a retried step without reasoning lost the new epoch. Both fixed in62b5cb532a. Codex on62b5cb532a: keep reasoning out of a config switched from Responses to Chat Completions (declined: the Chat Completions converter already skips reasoning parts, confirmed with a probe test). Codex on29a705e099: no major issues. - ethanndickson: retry without reasoning on `invalid_encrypted_content`, and keep OpenAI reasoning out of the advisor prompt. Both fixed in bf795daa923. Then: in-process memory is not enough because dogfood restarts on every merge and runs several replicas. Fixed in5fb3ce1689with his proposed rejection epoch in chat history, plus the credential record, and tested with the next turn on a fresh server. Then: hide the internal fields from Swagger, fixed in1057beb327. Approved on62b5cb532a. - coder/fantasy#63 review: honoring an echoed `store: false` is fixed in d55a867; replaying web searches that had no preceding reasoning is a pre-existing gap, tracked in #30528. - CI on 5735acb36ed: green after rerunning two failures outside this change (a `cli` `TestSSH` data race, and a `test-go-pg` job timeout that also fails on `main`). CI on 21156b2b32e: all checks pass. CI on bf795daa923: all checks pass. CI on 7eb8b1d029a: all checks pass. CI on f4f40734a41: all checks pass. CI on abccede81f7 did not run, because the branch conflicted with `main` (#30492 changed the provider-switch sanitizer to return database errors). CI on62b5cb532a: all checks pass. CI on29a705e099: all checks pass. > Xum, an AI coding agent, implemented, tested, and opened this PR on behalf of @ibetitsmike.
265 lines
9.2 KiB
Go
265 lines
9.2 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 gets 50% headroom because the summary must fit reasoning plus
|
|
// summary text in one response; a low configured chat cap could otherwise
|
|
// truncate the summary that replaces pruned history. The headroom stays
|
|
// modest because a cap configured at a provider's output ceiling overshoots
|
|
// it; that residual overshoot is an accepted tradeoff. GenerateCompaction
|
|
// bounds the increased cap by the remaining context window at trigger time.
|
|
func compactionSummaryCall(resolved resolvedModelCall) fantasy.Call {
|
|
call := resolved.newCall()
|
|
toolChoiceNone := fantasy.ToolChoiceNone
|
|
call.ToolChoice = &toolChoiceNone
|
|
if call.MaxOutputTokens != nil {
|
|
call.MaxOutputTokens = ptr.Ref(*call.MaxOutputTokens * 3 / 2)
|
|
}
|
|
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,
|
|
}
|
|
}
|