Files
coder/coderd/x/chatd/configcache.go
T
Ethan 088cb3d04f refactor(coderd): remove chatd's unreachable AI provider cache (#32836)
Relates to WI-97

chatd kept a 10 second cache of every enabled AI provider, with a pubsub
subscription to invalidate it. The only way to reach it was calling
`resolveUserProviderAPIKeys` with a `uuid.Nil` provider ID, and nothing
can pass one. Every caller either goes through
`resolveNormalizedProviderForModelConfig`, which requires a valid
provider ID, reads its model configs from a query that inner joins
`ai_providers`, or passes the ID of a provider it just fetched.

This PR just deletes the cache, its subscription, the `uuid.Nil` branch
and the helpers that only that branch used, i.e. `aiProviderConfigs`,
`ensureUniqueConfiguredProviderTypes`,
`chatprovider.PruneDisabledProviderKeys` and `Config.ProviderAPIKeys`.
Most of the added lines are `newInternalTestServer` call sites losing
their keys argument.

I don't think we want to make the cache reachable again, or add a new
one. By the top of this stack the AI provider read is one query per
generation step, about 2% of what a step runs, so a cache would save
very little and could serve a stale provider. The larger costs are chatd
loading the chat row again to authorise each of its own queries, and
building the turn's environment on steps that never call the model. I
think fixing those is the better long term solution, since neither needs
a cache, and that's tracked in CODAGT-1657.

For now, #32840, further up the stack, consolidates the reads chatd
repeats when it builds a turn's environment, which takes a plain turn to
58 queries (`main` was at 94 when I measured it).

To check that nothing relied on the cache, I ran a live chat on the top
of the stack and, between turns, disabled and re-enabled its provider,
swapped the provider's key for an invalid one and back, and deleted the
provider. Each change applied to the very next turn, the same as on a
local `main` build.

I came across this whilst working on #32811, which takes
`ai_provider:read_secret` away from chatd. The cache holds full provider
rows, base URL and settings included, which chatd can't load without
that permission. Keeping it would've meant rebuilding it on the
summaries from #32837, for a path nothing reaches, so I've deleted it
and split the deletions out of #32811 to be reviewed on their own. This
is on top of #32899 in the stack.
2026-12-04 12:20:13 +11:00

250 lines
6.6 KiB
Go

package chatd
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/ammario/tlru"
"github.com/google/uuid"
"tailscale.com/util/singleflight"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/quartz"
)
const (
chatConfigUserPromptTTL = 5 * time.Second
chatConfigAdvisorConfigTTL = 10 * time.Second
// Bound user-prompt cache cardinality so one-shot users do not
// accumulate forever in long-lived chatd processes.
chatConfigUserPromptEntryLimit = 64 * 1024
)
type advisorRuntimeConfig struct {
MaxUsesPerRun int `json:"max_uses_per_run"`
MaxOutputTokens int64 `json:"max_output_tokens"`
}
type cachedAdvisorConfig struct {
config advisorRuntimeConfig
expiresAt time.Time
}
type chatConfigCache struct {
db database.Store
clock quartz.Clock
// ctx is the server-scoped context used for all DB fills.
// Cache fills run inside singleflight.Do where one caller
// becomes the leader for all coalesced waiters. Using a
// per-request context would mean the leader's cancellation
// (timeout, user disconnect) fans the error to every waiter.
// Storing the server context here makes that impossible by
// construction — callers cannot pass a request context into
// the shared fill path.
ctx context.Context
mu sync.RWMutex
// User custom prompts (keyed by user ID).
userPromptEpoch uint64
userPrompts *tlru.Cache[uuid.UUID, string]
userPromptFetches singleflight.Group[string, string]
// Advisor configuration (singleton).
advisorConfig *cachedAdvisorConfig
advisorConfigGeneration uint64
advisorConfigFetches singleflight.Group[string, advisorRuntimeConfig]
}
func newChatConfigCache(ctx context.Context, db database.Store, clock quartz.Clock) *chatConfigCache {
return &chatConfigCache{
db: db,
clock: clock,
ctx: ctx,
userPrompts: tlru.New[uuid.UUID](
tlru.ConstantCost[string],
chatConfigUserPromptEntryLimit,
),
}
}
// singleflightDoChan wraps a singleflight group's DoChan method,
// allowing the caller to abandon the wait if their context is
// canceled while the shared fill continues running to completion.
// This separates two lifetimes: the fill runs under the server-scoped
// context, while each caller waits under its own request-scoped context.
func singleflightDoChan[K comparable, V any](
ctx context.Context,
group *singleflight.Group[K, V],
key K,
fn func() (V, error),
) (V, error) {
ch := group.DoChan(key, fn)
select {
case <-ctx.Done():
var zero V
return zero, ctx.Err()
case res := <-ch:
return res.Val, res.Err
}
}
func (c *chatConfigCache) UserPrompt(ctx context.Context, userID uuid.UUID) (string, error) {
if prompt, ok := c.cachedUserPrompt(userID); ok {
return prompt, nil
}
epoch := c.currentUserPromptEpoch()
prompt, err := singleflightDoChan(ctx, &c.userPromptFetches, fmt.Sprintf("%d:%s", epoch, userID), func() (string, error) {
if cached, ok := c.cachedUserPrompt(userID); ok {
return cached, nil
}
fetched, err := c.db.GetUserChatCustomPrompt(c.ctx, userID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
c.storeUserPrompt(epoch, userID, "")
return "", nil
}
return "", err
}
c.storeUserPrompt(epoch, userID, fetched)
return fetched, nil
})
if err != nil {
return "", err
}
return prompt, nil
}
func (c *chatConfigCache) cachedUserPrompt(userID uuid.UUID) (string, bool) {
prompt, _, ok := c.userPrompts.Get(userID)
if !ok {
return "", false
}
return prompt, true
}
func (c *chatConfigCache) currentUserPromptEpoch() uint64 {
c.mu.RLock()
epoch := c.userPromptEpoch
c.mu.RUnlock()
return epoch
}
func (c *chatConfigCache) storeUserPrompt(epoch uint64, userID uuid.UUID, prompt string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.userPromptEpoch != epoch {
return
}
c.userPrompts.Set(userID, prompt, chatConfigUserPromptTTL)
}
func (c *chatConfigCache) InvalidateUserPrompt(userID uuid.UUID) {
c.mu.Lock()
c.userPrompts.Delete(userID)
c.userPromptEpoch++
c.mu.Unlock()
}
// InvalidateAdvisorConfig drops the cached advisor configuration so the
// next AdvisorConfig call re-fetches from the database. Called from the
// ChatConfigEvent subscriber after an admin writes
// PUT /api/v2/chats/config/advisor; without this the cache could serve
// stale limits for up to chatConfigAdvisorConfigTTL. Bumping the
// generation counter also discards any in-flight fill started before the
// invalidation, so a stale DB read cannot re-cache the pre-update value.
func (c *chatConfigCache) InvalidateAdvisorConfig() {
c.mu.Lock()
c.advisorConfig = nil
c.advisorConfigGeneration++
c.mu.Unlock()
}
// AdvisorConfig returns the deployment-wide advisor configuration. The
// underlying site-config row changes on the order of hours or days, so
// this cache saves a per-turn DB round trip on chats that reference the
// advisor. Parse errors and lookup errors are surfaced to the caller.
func (c *chatConfigCache) AdvisorConfig(ctx context.Context) (advisorRuntimeConfig, error) {
if config, ok := c.cachedAdvisorConfig(); ok {
return config, nil
}
generation := c.advisorConfigGenerationSnapshot()
config, err := singleflightDoChan(
ctx,
&c.advisorConfigFetches,
fmt.Sprintf("%d:advisor", generation),
func() (advisorRuntimeConfig, error) {
if cached, ok := c.cachedAdvisorConfig(); ok {
return cached, nil
}
raw, err := c.db.GetChatAdvisorConfig(c.ctx)
if err != nil {
return advisorRuntimeConfig{}, err
}
var cfg advisorRuntimeConfig
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
return advisorRuntimeConfig{}, err
}
c.storeAdvisorConfig(generation, cfg)
return cfg, nil
},
)
if err != nil {
return advisorRuntimeConfig{}, err
}
return config, nil
}
func (c *chatConfigCache) cachedAdvisorConfig() (advisorRuntimeConfig, bool) {
c.mu.RLock()
entry := c.advisorConfig
c.mu.RUnlock()
if entry == nil {
return advisorRuntimeConfig{}, false
}
if c.clock.Now().Before(entry.expiresAt) {
return entry.config, true
}
c.mu.Lock()
if current := c.advisorConfig; current != nil && !c.clock.Now().Before(current.expiresAt) {
c.advisorConfig = nil
}
c.mu.Unlock()
return advisorRuntimeConfig{}, false
}
func (c *chatConfigCache) advisorConfigGenerationSnapshot() uint64 {
c.mu.RLock()
generation := c.advisorConfigGeneration
c.mu.RUnlock()
return generation
}
func (c *chatConfigCache) storeAdvisorConfig(generation uint64, config advisorRuntimeConfig) {
c.mu.Lock()
defer c.mu.Unlock()
if c.advisorConfigGeneration != generation {
return
}
c.advisorConfig = &cachedAdvisorConfig{
config: config,
expiresAt: c.clock.Now().Add(chatConfigAdvisorConfigTTL),
}
}