From e02fee7a7887eee8103313685e32df04d9831e8f Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:36:55 -0800 Subject: [PATCH 01/19] fix(auth): persist explicit session affinity across restarts and reloads --- sdk/cliproxy/auth/conductor.go | 6 + sdk/cliproxy/auth/conductor_lifecycle.go | 22 +- sdk/cliproxy/auth/conductor_selection.go | 8 + sdk/cliproxy/auth/selector.go | 81 +++- sdk/cliproxy/auth/session_cache.go | 91 +++- sdk/cliproxy/auth/session_persistence.go | 425 ++++++++++++++++++ sdk/cliproxy/auth/session_persistence_test.go | 322 +++++++++++++ .../auth/session_restart_regression_test.go | 47 ++ sdk/cliproxy/kv_store.go | 10 +- .../service_affinity_persistence_test.go | 90 ++++ 10 files changed, 1066 insertions(+), 36 deletions(-) create mode 100644 sdk/cliproxy/auth/session_persistence.go create mode 100644 sdk/cliproxy/auth/session_persistence_test.go create mode 100644 sdk/cliproxy/auth/session_restart_regression_test.go create mode 100644 sdk/cliproxy/service_affinity_persistence_test.go diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 2a0dc84e4d8..bde6b7a563f 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -182,6 +182,7 @@ type Manager struct { pendingCooldownStateStore CooldownStateStore executors map[string]ProviderExecutor selector Selector + affinityPersistence *sessionAffinityPersistence hook Hook resultPolicy atomic.Pointer[resultPolicyHolder] mu sync.RWMutex @@ -277,6 +278,11 @@ func NewManager(store Store, selector Selector, hook Hook) *Manager { providerOffsets: make(map[string]int), modelPoolOffsets: make(map[string]int), } + if affinity, ok := selector.(*SessionAffinitySelector); ok { + manager.affinityPersistence = affinity.persistence + affinity.persistenceManaged = true + affinity.authCandidates = manager.List + } // atomic.Value requires non-nil initial value. manager.runtimeConfig.Store(&internalconfig.Config{}) manager.apiKeyModelRouting.Store(&apiKeyModelRoutingSnapshot{config: &internalconfig.Config{}}) diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index d4c28141e0a..1cb678abdb3 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -661,10 +661,19 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo executorKeyFromAuth(existingBeforeSave) != executorKeyFromAuth(authClone) forgetEpoch := authClone.RegistrationEpoch forgetGen := authClone.Generation + if shouldForgetWeighted && m.affinityPersistence != nil { + m.affinityPersistence.retireAuth(authClone.ID, forgetEpoch, forgetGen) + } m.mu.Unlock() _ = schedulerSnapshot if shouldForgetWeighted { m.forgetWeightedAuthUpTo(authClone.ID, forgetEpoch, forgetGen) + // Keep the live binding observable for the supported disabled/never + // contract, while removing it from durable restart state. + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.flush() } return auth.Clone(), true, cooldownStateChanged, nil } @@ -717,6 +726,9 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) return false } provider := strings.TrimSpace(existing.Provider) + if m.affinityPersistence != nil { + m.affinityPersistence.retireAuth(id, existing.RegistrationEpoch, ^uint64(0)) + } delete(m.auths, id) m.notifyAuthChangeLocked(id) if m.modelPoolOffsets != nil { @@ -741,6 +753,11 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) tombstoneEpoch := m.authEpochs[id] m.mu.Unlock() m.forgetWeightedAuthUpTo(id, tombstoneEpoch, ^uint64(0)) + m.invalidateSessionAffinity(id) + ForgetQuotaWindows(id) + ForgetScopedWeeklyWindows(id) + ForgetShortWindowUsage(id) + ObserveAuthPlan(id, "") releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { @@ -751,7 +768,6 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) } m.structuralEpoch.Add(1) m.queueRefreshUnschedule(id) - m.invalidateSessionAffinity(id) if provider != "" { if exec, ok := m.Executor(provider); ok && exec != nil { @@ -770,6 +786,10 @@ func (m *Manager) invalidateSessionAffinity(authID string) { if m == nil || authID == "" { return } + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.invalidateAuth(authID) sel := m.Selector() if invalidator, ok := sel.(interface{ InvalidateAuth(string) }); ok && invalidator != nil { invalidator.InvalidateAuth(authID) diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index bcffcc36d50..a2eb5a4474b 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -748,6 +748,14 @@ func (m *Manager) SetSelector(selector Selector) { m.mu.Unlock() return } + if affinity, ok := selector.(*SessionAffinitySelector); ok { + if m.affinityPersistence == nil { + m.affinityPersistence = affinity.persistence + } + affinity.persistence = m.affinityPersistence + affinity.persistenceManaged = true + affinity.authCandidates = m.List + } m.selector = selector m.mu.Unlock() diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index 70131c26b94..fcd1d665494 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -1411,12 +1411,15 @@ func availabilityBlock(unavailable, quotaExceeded bool, nextRetryAfter, nextReco // It extracts session ID from multiple sources and maintains session-to-auth // mappings with automatic failover when the bound auth becomes unavailable. type SessionAffinitySelector struct { - fallback Selector - cache *SessionCache - matcher *cliproxysession.MerklePrefixMatcher - subagentAffinity bool - rebindOnQuotaOnly bool - rebindOnNever bool + fallback Selector + cache *SessionCache + persistence *sessionAffinityPersistence + persistenceManaged bool + authCandidates func() []*Auth + matcher *cliproxysession.MerklePrefixMatcher + subagentAffinity bool + rebindOnQuotaOnly bool + rebindOnNever bool } const ( @@ -1608,6 +1611,7 @@ func NewSessionAffinitySelectorWithConfig(cfg SessionAffinityConfig) *SessionAff return &SessionAffinitySelector{ fallback: cfg.Fallback, cache: NewSessionCache(cfg.TTL), + persistence: newSessionAffinityPersistence(), matcher: cliproxysession.NewMerklePrefixMatcher(cfg.TTL), subagentAffinity: subagentAffinity, rebindOnQuotaOnly: rebindMode == SessionAffinityRebindOnQuota, @@ -1648,6 +1652,11 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if opts.Metadata == nil { opts.Metadata = make(map[string]any) } + if cliproxyexecutor.DownstreamWebsocket(ctx) { + opts.Metadata[affinityTransportMetadataKey] = "ws" + } else { + delete(opts.Metadata, affinityTransportMetadataKey) + } opts.Metadata[cliproxyexecutor.SessionAffinityProviderMetadataKey] = provider opts.Metadata[cliproxyexecutor.SessionAffinityModelMetadataKey] = model @@ -1713,7 +1722,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri fallbackAuths := highestPriorityAuths(available) modelKey := canonicalModelKey(model) - cacheKey := providerAffinityNamespace(provider, opts.Metadata) + "::" + primaryID + "::" + modelKey + cacheKey := affinityRequestNamespace(provider, opts.Metadata) + "::" + primaryID + "::" + modelKey isFork := false if opts.Metadata != nil { if forkFlag, ok := opts.Metadata[cliproxyexecutor.IsForkMetadataKey].(bool); ok && forkFlag { @@ -1723,13 +1732,25 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri isSubagent := !isFork && isSubagentSession(primaryID, fallbackID) fallbackKey := "" if fallbackID != "" && fallbackID != primaryID { - fallbackKey = providerAffinityNamespace(provider, opts.Metadata) + "::" + fallbackID + "::" + modelKey + fallbackKey = affinityRequestNamespace(provider, opts.Metadata) + "::" + fallbackID + "::" + modelKey } bind := func(authID string, recordSelection bool) { keys := []string{cacheKey} if fallbackKey != "" && !isSubagent && !isFork { keys = append(keys, fallbackKey) } + if explicitID != "" { + bindingCandidates := auths + if !recordSelection && s.authCandidates != nil { + bindingCandidates = s.authCandidates() + } + for _, candidate := range bindingCandidates { + if candidate != nil && candidate.ID == authID { + s.persistence.bind(candidate, s.cache.ttl, affinityPersistenceKeys(keys, opts.Metadata)...) + break + } + } + } if !recordSelection { s.cache.SetAliases(authID, keys...) return @@ -1743,9 +1764,15 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri break } } - s.cache.setSessionAliases(authID, bindingProvider, primaryID, keys...) + s.cache.setAliases(authID, sessionBinding{provider: bindingProvider, sessionID: primaryID, scope: affinityRequestScope(opts.Metadata), model: modelKey}, keys...) } + if explicitID != "" { + s.restoreExplicitBinding(cacheKey, auths, opts.Metadata) + if fallbackKey != "" { + s.restoreExplicitBinding(fallbackKey, auths, opts.Metadata) + } + } if cachedAuthID, ok := s.cache.GetAndRefresh(cacheKey); ok { for _, auth := range available { if auth.ID == cachedAuthID { @@ -1793,7 +1820,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri providers[candidateProvider] = struct{}{} } } - if parentAuthID := s.cache.latestSessionAuth(fallbackID, providers); parentAuthID != "" { + if parentAuthID := s.cache.latestSessionAuth(fallbackID, providers, affinityRequestScope(opts.Metadata)); parentAuthID != "" { for _, auth := range available { if auth.ID == parentAuthID { bind(auth.ID, true) @@ -2138,6 +2165,11 @@ func (s *SessionAffinitySelector) Stop() { if s == nil { return } + if s.persistenceManaged { + s.persistence.flush() + } else { + s.persistence.close() + } if s.cache != nil { s.cache.Stop() } @@ -2152,6 +2184,7 @@ func (s *SessionAffinitySelector) InvalidateAuth(authID string) { if s == nil { return } + s.persistence.invalidateAuth(authID) if s.cache != nil { s.cache.InvalidateAuth(authID) } @@ -2244,6 +2277,11 @@ func (s *SessionAffinitySelector) LookupAffinity(provider, model, sessionID stri } foundAuths[authID] = struct{}{} } + for _, authID := range s.cache.lookupScopedSessionAuths(candProvider, modelKey, bounded) { + if authFilter == nil || authFilter(authID) { + foundAuths[authID] = struct{}{} + } + } } } @@ -2374,19 +2412,28 @@ func (s *SessionAffinitySelector) OnResult(res Result) { fallbackID = cliproxysession.BoundSessionIdentity(fallbackID) } - cacheKey := providerAffinityNamespace(ns, res.Options.Metadata) + "::" + primaryID + "::" + nsModel + cacheKey := affinityRequestNamespace(ns, res.Options.Metadata) + "::" + primaryID + "::" + nsModel var fallbackKey string if fallbackID != "" && fallbackID != primaryID && !isSubagentSession(primaryID, fallbackID) { - fallbackKey = providerAffinityNamespace(ns, res.Options.Metadata) + "::" + fallbackID + "::" + nsModel + fallbackKey = affinityRequestNamespace(ns, res.Options.Metadata) + "::" + fallbackID + "::" + nsModel } if res.Success { - s.cache.Touch(cacheKey, res.AuthID) + if s.cache.Touch(cacheKey, res.AuthID) && explicitID != "" { + s.persistence.touch(res.AuthID, s.cache.ttl, affinityPersistenceKey(cacheKey, res.Options.Metadata)) + } if fallbackKey != "" { - s.cache.Touch(fallbackKey, res.AuthID) + if s.cache.Touch(fallbackKey, res.AuthID) && explicitID != "" { + s.persistence.touch(res.AuthID, s.cache.ttl, affinityPersistenceKey(fallbackKey, res.Options.Metadata)) + } } return } - + if explicitID != "" { + s.persistence.remove(res.AuthID, affinityPersistenceKey(cacheKey, res.Options.Metadata)) + if fallbackKey != "" { + s.persistence.remove(res.AuthID, affinityPersistenceKey(fallbackKey, res.Options.Metadata)) + } + } s.cache.CompareAndDelete(cacheKey, res.AuthID) if fallbackKey != "" { s.cache.CompareAndDelete(fallbackKey, res.AuthID) @@ -2447,14 +2494,14 @@ func (s *SessionAffinitySelector) boundAuthForRequest(providers []string, model if primaryID != "" { for _, candProvider := range candidateProviders { - if authID, ok := s.cache.Get(providerAffinityNamespace(candProvider, opts.Metadata) + "::" + primaryID + "::" + modelKey); ok && authID != "" { + if authID, ok := s.cache.Get(affinityRequestNamespace(candProvider, opts.Metadata) + "::" + primaryID + "::" + modelKey); ok && authID != "" { return authID, true } } } if fallbackID != "" && fallbackID != primaryID && !isSubagent && !isFork { for _, candProvider := range candidateProviders { - if authID, ok := s.cache.Get(providerAffinityNamespace(candProvider, opts.Metadata) + "::" + fallbackID + "::" + modelKey); ok && authID != "" { + if authID, ok := s.cache.Get(affinityRequestNamespace(candProvider, opts.Metadata) + "::" + fallbackID + "::" + modelKey); ok && authID != "" { return authID, true } } diff --git a/sdk/cliproxy/auth/session_cache.go b/sdk/cliproxy/auth/session_cache.go index eb3482550da..fc7501e078f 100644 --- a/sdk/cliproxy/auth/session_cache.go +++ b/sdk/cliproxy/auth/session_cache.go @@ -17,12 +17,15 @@ type sessionBinding struct { sessionID string provider string sequence uint64 + scope string + model string } // sessionEntry stores an auth binding, its identifier aliases, and expiration. type sessionEntry struct { authID string expiresAt time.Time + touchedAt time.Time aliases []string binding sessionBinding } @@ -40,6 +43,14 @@ type SessionCache struct { stopOnce sync.Once sessionGroups map[string]map[string]struct{} bindingSequence uint64 + nowFunc func() time.Time +} + +func (c *SessionCache) now() time.Time { + if c.nowFunc != nil { + return c.nowFunc() + } + return time.Now() } // NewSessionCache creates a cache with the specified TTL. @@ -94,7 +105,7 @@ func (c *SessionCache) Get(sessionID string) (string, bool) { return "", false } c.mu.RLock() - now := time.Now() + now := c.now() entry, ok := c.entries[sessionID] if ok && now.Before(entry.expiresAt) { c.mu.RUnlock() @@ -112,7 +123,7 @@ func (c *SessionCache) Get(sessionID string) (string, bool) { if !ok { return "", false } - if time.Now().Before(entry.expiresAt) { + if c.now().Before(entry.expiresAt) { return entry.authID, true } c.removeAliasGroupLocked(entry) @@ -132,7 +143,7 @@ func (c *SessionCache) GetAndRefresh(sessionID string) (string, bool) { if !ok { return "", false } - now := time.Now() + now := c.now() if !now.Before(entry.expiresAt) { c.removeAliasGroupLocked(entry) return "", false @@ -170,7 +181,7 @@ func (c *SessionCache) setAliases(authID string, binding sessionBinding, session c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() - now := time.Now() + now := c.now() aliases := mergeSessionAliases(nil, sessionIDs...) previousGroups := make([]sessionEntry, 0, len(sessionIDs)) @@ -214,13 +225,13 @@ func (c *SessionCache) replaceAliasGroupsLocked(authID string, expiresAt time.Ti if existing, ok := c.groups[primaryKey]; ok { c.removeAliasGroupLocked(existing) } - entry := sessionEntry{authID: authID, expiresAt: expiresAt, aliases: append([]string(nil), aliases...), binding: binding} + entry := sessionEntry{authID: authID, expiresAt: expiresAt, touchedAt: expiresAt.Add(-c.ttl), aliases: append([]string(nil), aliases...), binding: binding} c.groups[primaryKey] = entry - if binding.sequence != 0 { - if c.sessionGroups[binding.sessionID] == nil { - c.sessionGroups[binding.sessionID] = make(map[string]struct{}) + for _, sessionID := range indexedSessionIDs(entry) { + if c.sessionGroups[sessionID] == nil { + c.sessionGroups[sessionID] = make(map[string]struct{}) } - c.sessionGroups[binding.sessionID][primaryKey] = struct{}{} + c.sessionGroups[sessionID][primaryKey] = struct{}{} } for _, alias := range aliases { c.entries[alias] = entry @@ -255,10 +266,12 @@ func (c *SessionCache) removeAliasGroupLocked(entry sessionEntry) { primaryKey := entry.aliases[0] if currentGroup, ok := c.groups[primaryKey]; ok && sameSessionEntryGroup(currentGroup, entry) { delete(c.groups, primaryKey) - if groups := c.sessionGroups[entry.binding.sessionID]; groups != nil { - delete(groups, primaryKey) - if len(groups) == 0 { - delete(c.sessionGroups, entry.binding.sessionID) + for _, sessionID := range indexedSessionIDs(entry) { + if groups := c.sessionGroups[sessionID]; groups != nil { + delete(groups, primaryKey) + if len(groups) == 0 { + delete(c.sessionGroups, sessionID) + } } } if elem, ok := c.evictionElements[primaryKey]; ok { @@ -356,16 +369,19 @@ func mergeSessionAliases(existing []string, candidates ...string) []string { // latestSessionAuth observes the newest live selection on the requested real providers. // It does not refresh TTL or eviction order and visits only this session's groups. -func (c *SessionCache) latestSessionAuth(sessionID string, providers map[string]struct{}) string { +func (c *SessionCache) latestSessionAuth(sessionID string, providers map[string]struct{}, scopes ...string) string { if c == nil || sessionID == "" || len(providers) == 0 { return "" } c.mu.RLock() defer c.mu.RUnlock() - now := time.Now() + now := c.now() var latest sessionEntry for key := range c.sessionGroups[sessionID] { entry := c.groups[key] + if len(scopes) > 0 && entry.binding.scope != scopes[0] { + continue + } if _, ok := providers[entry.binding.provider]; !ok || !now.Before(entry.expiresAt) { continue } @@ -384,7 +400,7 @@ func (c *SessionCache) Touch(sessionID, expectedAuthID string) bool { c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() - now := time.Now() + now := c.now() entry, ok := c.entries[sessionID] if !ok || entry.authID != expectedAuthID || !now.Before(entry.expiresAt) { return false @@ -502,7 +518,7 @@ func (c *SessionCache) Len() int { } func (c *SessionCache) cleanup() { - now := time.Now() + now := c.now() c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() @@ -512,3 +528,44 @@ func (c *SessionCache) cleanup() { } } } + +// indexedSessionIDs indexes explicit aliases for read-only lookup without +// putting raw identifiers into the separate persistent cache. +func indexedSessionIDs(entry sessionEntry) []string { + ids := []string{entry.binding.sessionID} + for _, alias := range entry.aliases { + _, rest, ok := strings.Cut(alias, "::") + if !ok { + continue + } + if entry.binding.sequence != 0 { + if id, okSuffix := strings.CutSuffix(rest, "::"+entry.binding.model); okSuffix { + ids = append(ids, id) + } + } else if last := strings.LastIndex(rest, "::"); last >= 0 { + ids = append(ids, rest[:last]) + } + } + return mergeSessionAliases(nil, ids...) +} + +func (c *SessionCache) lookupScopedSessionAuths(provider, model, sessionID string) []string { + c.mu.RLock() + defer c.mu.RUnlock() + var authIDs []string + suffix := "::" + sessionID + "::" + model + for key := range c.sessionGroups[sessionID] { + entry := c.groups[key] + if !c.now().Before(entry.expiresAt) { + continue + } + for _, alias := range entry.aliases { + namespace, _, _ := strings.Cut(alias, "::") + if strings.HasPrefix(namespace, provider+"/request/") && strings.HasSuffix(alias, suffix) { + authIDs = append(authIDs, entry.authID) + break + } + } + } + return authIDs +} diff --git a/sdk/cliproxy/auth/session_persistence.go b/sdk/cliproxy/auth/session_persistence.go new file mode 100644 index 00000000000..2574a639954 --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence.go @@ -0,0 +1,425 @@ +package auth + +import ( + "context" + "strconv" + "sync" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" +) + +const affinitySnapshotKey = "session-affinity:v1" + +// sessionAffinityPersistence is shared by a manager's selectors, including while +// affinity is disabled. Only explicit identities enter this bounded cache. Keys +// and credential IDs are hashed before entering it, so snapshots contain neither +// session text nor caller keys. The local KV store remains optional. +type sessionAffinityPersistence struct { + mu sync.Mutex + flushMu sync.Mutex + cache *SessionCache + client *kvstore.BoltStore + dirty bool + now func() time.Time + stop chan struct{} + done chan struct{} + closed bool + suspended bool + nextRefresh time.Time + flushInterval time.Duration + retired map[string]affinityAuthVersion +} + +func newSessionAffinityPersistence() *sessionAffinityPersistence { + p := &sessionAffinityPersistence{now: time.Now, flushInterval: time.Second, retired: make(map[string]affinityAuthVersion)} + p.cache = &SessionCache{maxEntries: defaultMaxSessionEntries, nowFunc: func() time.Time { return p.now() }} + p.cache.ensureInitializedLocked() + return p +} + +// localLocked loads once per local store instance. Home owns its routing state. +func (p *sessionAffinityPersistence) localLocked() bool { + client, _, errClient := kvstore.CurrentKVClient() + local, ok := client.(*kvstore.BoltStore) + if errClient != nil || !ok || p.closed || p.suspended { + return false + } + if local == p.client { + return true + } + raw, found, errGet := local.KVGet(context.Background(), affinitySnapshotKey) + if errGet != nil { + log.WithError(errGet).Warn("session-affinity: load local bindings") + return false + } + p.client = local + previous := p.cache.groups + p.cache = &SessionCache{maxEntries: defaultMaxSessionEntries, nowFunc: func() time.Time { return p.now() }} + p.cache.ensureInitializedLocked() + p.dirty = false + if found { + root := ojson.ParseBytes(raw) + for _, item := range root.Get("groups").Array() { + expires := time.Unix(0, item.Get("expires").Int()) + touched := time.Unix(0, item.Get("touched").Int()) + authHash := item.Get("auth").String() + aliases := []string{} + for _, alias := range item.Get("aliases").Array() { + aliases = append(aliases, alias.String()) + } + if _, retired := p.retired[authHash]; retired { + continue + } + if !p.now().Before(expires) || touched.After(p.now()) || authHash == "" || len(aliases) == 0 { + continue + } + p.cache.replaceAliasGroupsLocked(authHash, expires, compactSessionAliases(aliases), sessionBinding{}) + entry := p.cache.groups[aliases[0]] + entry.touchedAt = touched + p.cache.groups[aliases[0]] = entry + for _, alias := range entry.aliases { + p.cache.entries[alias] = entry + } + } + } + // Runtime bindings can be newer than this store's last snapshot, including + // bindings made with disk persistence disabled. + for _, entry := range previous { + if !p.now().Before(entry.expiresAt) { + continue + } + conflicts := []sessionEntry{} + for _, alias := range entry.aliases { + if existing, ok := p.cache.entries[alias]; ok { + conflicts = append(conflicts, existing) + } + } + p.cache.replaceAliasGroupsLocked(entry.authID, entry.expiresAt, entry.aliases, sessionBinding{}, conflicts...) + p.cache.groups[entry.aliases[0]] = entry + for _, alias := range entry.aliases { + p.cache.entries[alias] = entry + } + p.dirty = true + } + if p.stop == nil { + p.stop, p.done = make(chan struct{}), make(chan struct{}) + go p.run() + } + return true +} + +func (p *sessionAffinityPersistence) run() { + defer close(p.done) + ticker := time.NewTicker(p.flushInterval) + defer ticker.Stop() + for { + select { + case <-p.stop: + return + case <-ticker.C: + p.flush() + } + } +} + +func persistedAffinityKey(key string) string { + prefix := "session:" + if isLocalPromptCacheSessionAlias(key) { + prefix = "pck:" + } + return prefix + kvstore.HashKeyPart(key) +} + +func (p *sessionAffinityPersistence) get(key string, ttl time.Duration, candidates []*Auth) (string, time.Time, bool) { + if p == nil { + return "", time.Time{}, false + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return "", time.Time{}, false + } + p.localLocked() + key = persistedAffinityKey(key) + entry, ok := p.cache.entries[key] + now := p.now() + if !ok || !now.Before(entry.expiresAt) || !now.Before(entry.touchedAt.Add(ttl)) { + return "", time.Time{}, false + } + for _, auth := range candidates { + if auth != nil && !auth.Disabled && auth.Status != StatusDisabled && kvstore.HashKeyPart(auth.ID) == entry.authID { + return auth.ID, minAffinityExpiry(entry, ttl), true + } + } + return "", time.Time{}, false +} + +func (p *sessionAffinityPersistence) bind(auth *Auth, ttl time.Duration, keys ...string) { + if p == nil || auth == nil || auth.Disabled || auth.Status == StatusDisabled { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + authHash := kvstore.HashKeyPart(auth.ID) + if version, retired := p.retired[authHash]; retired && (auth.RegistrationEpoch < version.epoch || (auth.RegistrationEpoch == version.epoch && auth.Generation <= version.generation)) { + return + } + aliases := make([]string, 0, len(keys)) + for _, key := range keys { + aliases = append(aliases, persistedAffinityKey(key)) + } + changed := false + for _, alias := range aliases { + previous, ok := p.cache.entries[alias] + if !ok || previous.authID != authHash { + changed = true + break + } + } + p.cache.ttl = ttl + p.cache.SetAliases(authHash, aliases...) + p.markDirtyLocked(ttl, changed) +} + +func (p *sessionAffinityPersistence) remove(authID string, keys ...string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + for _, key := range keys { + if p.cache.CompareAndDelete(persistedAffinityKey(key), kvstore.HashKeyPart(authID)) { + p.dirty = true + } + } +} + +func (p *sessionAffinityPersistence) invalidateAuth(authID string) { + if p == nil { + return + } + p.mu.Lock() + p.localLocked() + p.cache.InvalidateAuth(kvstore.HashKeyPart(authID)) + p.dirty = true + p.mu.Unlock() + // Credential removal is administrative. Commit the deletion before returning, + // serialized with earlier snapshots so an in-flight write cannot restore it. + p.flush() +} + +func (p *sessionAffinityPersistence) flush() { + if p == nil { + return + } + p.flushMu.Lock() + defer p.flushMu.Unlock() + p.mu.Lock() + current, _, _ := kvstore.CurrentKVClient() + if !p.dirty || p.client == nil || current != p.client || p.suspended { + p.mu.Unlock() + return + } + p.cache.cleanup() + groups := make([]map[string]any, 0, len(p.cache.groups)) + var expiresAt time.Time + for _, entry := range p.cache.groups { + groups = append(groups, map[string]any{"auth": entry.authID, "expires": entry.expiresAt.UnixNano(), "touched": entry.touchedAt.UnixNano(), "aliases": entry.aliases}) + if entry.expiresAt.After(expiresAt) { + expiresAt = entry.expiresAt + } + } + client := p.client + p.dirty = false + p.nextRefresh = p.now().Add(min(p.cache.ttl/4, time.Minute)) + p.mu.Unlock() + var errWrite error + if len(groups) == 0 { + _, errWrite = client.KVDel(context.Background(), affinitySnapshotKey) + } else { + doc := ojson.NewDocString(`{}`) + errWrite = doc.Set("groups", groups) + if errWrite == nil { + ttl := expiresAt.Sub(p.now()) + if ttl > 0 { + _, errWrite = client.KVSet(context.Background(), affinitySnapshotKey, doc.Bytes(), kvstore.KVSetOptions{PX: ttl}) + } + } + } + if errWrite != nil { + p.mu.Lock() + p.dirty = true + p.mu.Unlock() + log.WithError(errWrite).Warn("session-affinity: persist local bindings") + } +} + +func (p *sessionAffinityPersistence) close() { + if p == nil { + return + } + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + p.closed = true + p.dirty = p.dirty || len(p.cache.groups) > 0 + stop, done := p.stop, p.done + p.mu.Unlock() + if stop != nil { + close(stop) + <-done + } + p.flush() +} + +// affinityRequestNamespace scopes explicit bindings just as tightly in memory +// as on disk. Empty legacy metadata retains its existing namespace. +func affinityRequestNamespace(provider string, metadata map[string]any) string { + namespace := providerAffinityNamespace(provider, metadata) + if scope := affinityRequestScope(metadata); scope != "" { + return namespace + "/request/" + scope + } + return namespace +} + +func affinityRequestScope(metadata map[string]any) string { + caller := sessionMetadataString(metadata, cliproxyexecutor.CallerScopeMetadataKey) + tier := sessionMetadataString(metadata, cliproxyexecutor.ServiceTierMetadataKey) + if caller == "" && tier == "" { + return "" + } + return kvstore.HashKeyPart(strconv.Quote(caller) + strconv.Quote(tier)) +} + +const affinityTransportMetadataKey = "session_affinity_transport" + +func (p *sessionAffinityPersistence) touch(authID string, ttl time.Duration, key string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + p.cache.ttl = ttl + if p.cache.Touch(persistedAffinityKey(key), kvstore.HashKeyPart(authID)) { + p.markDirtyLocked(ttl, false) + } +} + +type affinityAuthVersion struct{ epoch, generation uint64 } + +func (p *sessionAffinityPersistence) retireAuth(authID string, epoch, generation uint64) { + p.mu.Lock() + defer p.mu.Unlock() + p.retired[kvstore.HashKeyPart(authID)] = affinityAuthVersion{epoch: epoch, generation: generation} + p.localLocked() + p.cache.InvalidateAuth(kvstore.HashKeyPart(authID)) + p.dirty = true +} + +func (s *SessionAffinitySelector) restoreExplicitBinding(key string, candidates []*Auth, metadata map[string]any) { + if _, ok := s.cache.Get(key); ok { + return + } + if s.authCandidates != nil { + candidates = s.authCandidates() + } + if authID, expiresAt, ok := s.persistence.get(affinityPersistenceKey(key, metadata), s.cache.ttl, candidates); ok { + s.cache.mu.Lock() + s.cache.ensureInitializedLocked() + // A concurrent request may already have installed a newer binding. + if entry, exists := s.cache.entries[key]; !exists || !s.cache.now().Before(entry.expiresAt) { + s.cache.replaceAliasGroupsLocked(authID, expiresAt, []string{key}, sessionBinding{}) + } + s.cache.mu.Unlock() + } +} + +// CloseSessionAffinityPersistence flushes pending local bindings during shutdown. +func (m *Manager) CloseSessionAffinityPersistence() { + if m == nil { + return + } + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.close() +} + +func affinityPersistenceKey(key string, metadata map[string]any) string { + return key + "\x00transport=" + sessionMetadataString(metadata, affinityTransportMetadataKey) +} + +func affinityPersistenceKeys(keys []string, metadata map[string]any) []string { + scoped := make([]string, 0, len(keys)) + for _, key := range keys { + scoped = append(scoped, affinityPersistenceKey(key, metadata)) + } + return scoped +} + +func minAffinityExpiry(entry sessionEntry, ttl time.Duration) time.Time { + if limit := entry.touchedAt.Add(ttl); limit.Before(entry.expiresAt) { + return limit + } + return entry.expiresAt +} + +func (p *sessionAffinityPersistence) markDirtyLocked(ttl time.Duration, changed bool) { + if changed || !p.now().Before(p.nextRefresh) { + p.dirty = true + p.nextRefresh = p.now().Add(min(ttl/4, time.Minute)) + } +} + +// SetSessionAffinityPersistenceEnabled keeps memory affinity available while +// local storage is disabled. Clear old snapshots when disabling so removals +// during that interval cannot revive old bindings in a later process. +func (m *Manager) SetSessionAffinityPersistenceEnabled(enabled bool) { + if m == nil { + return + } + m.mu.Lock() + if m.affinityPersistence == nil { + m.affinityPersistence = newSessionAffinityPersistence() + } + p := m.affinityPersistence + m.mu.Unlock() + p.flushMu.Lock() + defer p.flushMu.Unlock() + p.mu.Lock() + if enabled { + p.suspended = false + if p.client != nil || len(p.cache.groups) > 0 { + p.localLocked() + } + p.mu.Unlock() + return + } + p.localLocked() + p.suspended = true + client := p.client + p.mu.Unlock() + if client != nil { + if _, errDelete := client.KVDel(context.Background(), affinitySnapshotKey); errDelete != nil { + log.WithError(errDelete).Warn("session-affinity: clear disabled persistence") + } + } +} diff --git a/sdk/cliproxy/auth/session_persistence_test.go b/sdk/cliproxy/auth/session_persistence_test.go new file mode 100644 index 00000000000..074899e919c --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence_test.go @@ -0,0 +1,322 @@ +package auth + +import ( + "bytes" + "context" + "net/http" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +func affinityKV(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "kv.db") + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := kvstore.ShutdownLocal(); err != nil { + t.Error(err) + } + }) + return path +} + +func persistentSelector(t *testing.T, ttl time.Duration) *SessionAffinitySelector { + t.Helper() + selector := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: ttl, Fallback: &FillFirstSelector{}}) + selector.persistence.flushInterval = time.Hour // Flush explicitly for deterministic crash/restart boundaries. + t.Cleanup(selector.Stop) + return selector +} + +func affinityOptions() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"private-session-text"}}, + OriginalRequest: []byte(`{"messages":[{"role":"user","content":"private-prompt-text"}]}`), + Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "private-caller-key", cliproxyexecutor.ServiceTierMetadataKey: "default"}} +} + +func expectAffinityPick(t *testing.T, selector *SessionAffinitySelector, ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, want string) { + t.Helper() + got, err := selector.Pick(ctx, provider, model, opts, auths) + if err != nil || got == nil || got.ID != want { + t.Fatalf("Pick() = %v, %v, want %s", got, err, want) + } +} + +func TestPersistentAffinityRestartAndIsolation(t *testing.T) { + path := affinityKV(t) + a, b := &Auth{ID: "a", Provider: "claude"}, &Auth{ID: "b-private-auth", Provider: "claude"} + original := persistentSelector(t, time.Hour) + expectAffinityPick(t, original, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, b.ID) + original.Stop() // A graceful stop commits queued writes. + client, _, _ := kvstore.CurrentKVClient() + raw, found, err := client.KVGet(context.Background(), affinitySnapshotKey) + if err != nil || !found { + t.Fatalf("missing snapshot: %v", err) + } + for _, private := range []string{"private-session-text", "private-prompt-text", "private-caller-key", b.ID} { + if bytes.Contains(raw, []byte(private)) { + t.Fatalf("snapshot contains %q", private) + } + } + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + for _, name := range []string{"same", "caller", "model", "provider", "tier", "transport", "provider-scope"} { + t.Run(name, func(t *testing.T) { + restored := persistentSelector(t, time.Hour) + opts := affinityOptions() + ctx, provider, model, want := context.Background(), "claude", "model", "a" + switch name { + case "same": + want = b.ID + case "caller": + opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey] = "other-caller" + case "model": + model = "other-model" + case "provider": + provider = "other-provider" + case "tier": + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = "priority" + case "transport": + ctx = cliproxyexecutor.WithDownstreamWebsocket(ctx) + case "provider-scope": + opts.Metadata[cliproxyexecutor.ProviderScopeMetadataKey] = "restricted" + } + expectAffinityPick(t, restored, ctx, provider, model, opts, []*Auth{a, b}, want) + }) + } +} + +func TestPersistentAffinityReloadBeforeFlushAndRemoval(t *testing.T) { + affinityKV(t) + first := persistentSelector(t, time.Hour) + manager := NewManager(nil, first, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + a, err := manager.Register(context.Background(), &Auth{ID: "a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + b, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := affinityOptions() + expectAffinityPick(t, first, context.Background(), "claude", "model", opts, []*Auth{b}, "b") + second := persistentSelector(t, time.Hour) + manager.SetSelector(second) + if second.persistence != first.persistence { + t.Fatal("reload did not retain pending bindings") + } + expectAffinityPick(t, second, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, b}, "b") + // Removal while session affinity is disabled must still invalidate snapshots + // which the next selector has not loaded into its own session cache. + manager.SetSelector(&FillFirstSelector{}) + manager.Remove(context.Background(), "b") + // An already-running selection cannot write the removed incarnation back. + first.persistence.bind(b, time.Hour, "delayed-selection") + third := persistentSelector(t, time.Hour) + manager.SetSelector(third) + readded, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + expectAffinityPick(t, third, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, readded}, "a") + third.persistence.mu.Lock() + _, resurrected := third.persistence.cache.Get(persistedAffinityKey("delayed-selection")) + third.persistence.mu.Unlock() + if resurrected { + t.Fatal("delayed selection resurrected removed auth") + } + // The deletion must also survive a fresh process with no in-memory tombstones. + third.persistence.flush() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, readded}, "a") +} + +func TestPersistentAffinityTTLAndSlidingRefresh(t *testing.T) { + affinityKV(t) + var clock atomic.Int64 + clock.Store(time.Now().UnixNano()) + now := func() time.Time { return time.Unix(0, clock.Load()) } + p := newSessionAffinityPersistence() + p.now, p.flushInterval = now, time.Hour + t.Cleanup(p.close) + auth := &Auth{ID: "auth"} + p.bind(auth, time.Hour, "route") + clock.Add(int64(40 * time.Minute)) + p.touch(auth.ID, time.Hour, "route") + p.flush() + fresh := newSessionAffinityPersistence() + fresh.now, fresh.flushInterval = now, time.Hour + t.Cleanup(fresh.close) + clock.Add(int64(40 * time.Minute)) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{auth}); !ok { + t.Fatal("sliding refresh lost across restart") + } + if _, _, ok := fresh.get("route", 30*time.Minute, []*Auth{auth}); ok { + t.Fatal("shorter reload TTL reused an expired binding") + } + clock.Add(int64(20 * time.Minute)) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{auth}); ok { + t.Fatal("binding survived its exact expiration") + } +} + +func TestPersistentAffinityAliasRebindAndResultInvalidation(t *testing.T) { + affinityKV(t) + p := newSessionAffinityPersistence() + p.flushInterval = time.Hour + t.Cleanup(p.close) + a, b := &Auth{ID: "a"}, &Auth{ID: "b"} + p.bind(a, time.Hour, "conversation", "pck:old") + p.bind(b, time.Hour, "conversation", "pck:new") + // An older result must not delete the new account's alias. + p.remove(a.ID, "conversation") + p.flush() + fresh := newSessionAffinityPersistence() + fresh.flushInterval = time.Hour + t.Cleanup(fresh.close) + for _, key := range []string{"conversation", "pck:new"} { + if got, _, ok := fresh.get(key, time.Hour, []*Auth{a, b}); !ok || got != b.ID { + t.Fatalf("%s = %s, %t", key, got, ok) + } + } + if _, _, ok := fresh.get("pck:old", time.Hour, []*Auth{a, b}); ok { + t.Fatal("obsolete prompt alias resurrected") + } + fresh.remove(b.ID, "conversation", "pck:new") + fresh.flush() + restarted := newSessionAffinityPersistence() + restarted.flushInterval = time.Hour + t.Cleanup(restarted.close) + if _, _, ok := restarted.get("conversation", time.Hour, []*Auth{a, b}); ok { + t.Fatal("failed binding resurrected") + } +} + +func TestPersistentAffinityDisabledCredentialAndOptionalStore(t *testing.T) { + affinityKV(t) + selector := persistentSelector(t, time.Hour) + manager := NewManager(nil, selector, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + b, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + expectAffinityPick(t, selector, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, "b") + disabled := b.Clone() + disabled.Disabled = true + if _, err := manager.Update(context.Background(), disabled); err != nil { + t.Fatal(err) + } + selector.persistence.flush() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "a"}, b}, "a") + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + memory := persistentSelector(t, time.Hour) + expectAffinityPick(t, memory, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, "b") + expectAffinityPick(t, memory, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "a"}, b}, "b") + if memory.persistence.client != nil || memory.persistence.stop != nil { + t.Fatal("disabled storage started persistence") + } +} + +func TestPersistentAffinityDoesNotWriteOnPick(t *testing.T) { + affinityKV(t) + selector := persistentSelector(t, time.Hour) + expectAffinityPick(t, selector, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "b"}}, "b") + client, _, _ := kvstore.CurrentKVClient() + if _, found, err := client.KVGet(context.Background(), affinitySnapshotKey); err != nil || found { + t.Fatalf("Pick wrote disk: %t, %v", found, err) + } + selector.persistence.flush() + if _, found, err := client.KVGet(context.Background(), affinitySnapshotKey); err != nil || !found { + t.Fatalf("flush failed: %t, %v", found, err) + } +} + +func TestPersistentAffinityConcurrentRemovalCannotResurrect(t *testing.T) { + affinityKV(t) + p := newSessionAffinityPersistence() + p.flushInterval = time.Hour + t.Cleanup(p.close) + old := &Auth{ID: "removed", RegistrationEpoch: 1, Generation: 1} + p.bind(old, time.Hour, "route") + p.flush() + // Both asynchronous work and old in-flight selections compete with removal. + start := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + <-start + for range 50 { + p.bind(old, time.Hour, "route") + p.flush() + } + }() + close(start) + p.retireAuth(old.ID, old.RegistrationEpoch, ^uint64(0)) + p.invalidateAuth(old.ID) + <-done + p.flush() + fresh := newSessionAffinityPersistence() + fresh.flushInterval = time.Hour + t.Cleanup(fresh.close) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{{ID: old.ID, RegistrationEpoch: 3}}); ok { + t.Fatal("concurrent stale selection revived removed binding") + } +} + +func TestPersistentAffinityRefreshWritesAreThrottled(t *testing.T) { + affinityKV(t) + var timestamp atomic.Int64 + timestamp.Store(time.Now().UnixNano()) + p := newSessionAffinityPersistence() + p.now = func() time.Time { return time.Unix(0, timestamp.Load()) } + p.flushInterval = time.Hour + t.Cleanup(p.close) + auth := &Auth{ID: "auth"} + p.bind(auth, time.Hour, "route") + p.flush() + timestamp.Add(int64(30 * time.Second)) + p.bind(auth, time.Hour, "route") + p.touch(auth.ID, time.Hour, "route") + p.mu.Lock() + dirty := p.dirty + p.mu.Unlock() + if dirty { + t.Fatal("unchanged binding scheduled another snapshot inside refresh throttle") + } + timestamp.Add(int64(30 * time.Second)) + p.touch(auth.ID, time.Hour, "route") + p.mu.Lock() + dirty = p.dirty + p.mu.Unlock() + if !dirty { + t.Fatal("due TTL refresh did not schedule persistence") + } +} + +func TestSessionAffinityScopedLookupAndGuardianIsolation(t *testing.T) { + selector := persistentSelector(t, time.Hour) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"main-thread"}}, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-a"}} + expectAffinityPick(t, selector, context.Background(), "codex", "team::model", opts, []*Auth{b}, "b") + if authID, status := selector.LookupAffinity("codex", "team::model", "main-thread"); authID != "b" || status != "bound" { + t.Fatalf("scoped lookup = %s, %s", authID, status) + } + child := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"main-thread:agent:child"}, "X-Openai-Subagent": {"guardian"}}, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-b"}} + expectAffinityPick(t, selector, context.Background(), "codex", "review", child, []*Auth{a, b}, "a") +} diff --git a/sdk/cliproxy/auth/session_restart_regression_test.go b/sdk/cliproxy/auth/session_restart_regression_test.go new file mode 100644 index 00000000000..006b3e30c18 --- /dev/null +++ b/sdk/cliproxy/auth/session_restart_regression_test.go @@ -0,0 +1,47 @@ +package auth + +import ( + "context" + "net/http" + "path/filepath" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +// This public-entry regression also runs against the audit baseline using a Go +// source overlay. It needs no persistence implementation details. +func TestSessionAffinityPublicRestartRegression(t *testing.T) { + path := filepath.Join(t.TempDir(), "kv.db") + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := kvstore.ShutdownLocal(); err != nil { + t.Error(err) + } + }) + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"restart-regression"}}} + cfg := SessionAffinityConfig{TTL: time.Hour, Fallback: &FillFirstSelector{}} + first := NewSessionAffinitySelectorWithConfig(cfg) + a, b := &Auth{ID: "a"}, &Auth{ID: "b"} + got, err := first.Pick(context.Background(), "claude", "model", opts, []*Auth{b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("first Pick = %v, %v", got, err) + } + first.Stop() + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + restarted := NewSessionAffinitySelectorWithConfig(cfg) + t.Cleanup(restarted.Stop) + got, err = restarted.Pick(context.Background(), "claude", "model", opts, []*Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("restart changed warm account: Pick = %v, %v, want b", got, err) + } +} diff --git a/sdk/cliproxy/kv_store.go b/sdk/cliproxy/kv_store.go index e6874620574..93014b42a72 100644 --- a/sdk/cliproxy/kv_store.go +++ b/sdk/cliproxy/kv_store.go @@ -16,18 +16,26 @@ func (s *Service) applyKVStoreConfig(cfg *config.Config) { } s.kvStoreManaged.Store(true) if cfg == nil || cfg.Home.Enabled || home.Current() != nil || cfg.KVStore.Disabled { + if s.coreManager != nil { + s.coreManager.SetSessionAffinityPersistenceEnabled(false) + } if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { log.Errorf("failed to shutdown local kv store: %v", errShutdown) } return } - _ = kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()) + if errConfigure := kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()); errConfigure == nil && s.coreManager != nil { + s.coreManager.SetSessionAffinityPersistenceEnabled(true) + } } func (s *Service) shutdownKVStore() error { if s == nil { return nil } + if s.coreManager != nil { + s.coreManager.CloseSessionAffinityPersistence() + } s.kvStoreManaged.Store(false) return kvstore.ShutdownLocal() } diff --git a/sdk/cliproxy/service_affinity_persistence_test.go b/sdk/cliproxy/service_affinity_persistence_test.go new file mode 100644 index 00000000000..608ba10c605 --- /dev/null +++ b/sdk/cliproxy/service_affinity_persistence_test.go @@ -0,0 +1,90 @@ +package cliproxy + +import ( + "context" + "net/http" + "path/filepath" + + "github.com/rune-oai/t3code-proxy/internal/kvstore" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/config" + coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +func TestServiceRoutingReloadPreservesExplicitAffinity(t *testing.T) { + cfg := &config.Config{Routing: config.RoutingConfig{Strategy: "fill-first", SessionAffinity: true, SessionAffinityTTL: "1h"}} + selector := newRoutingSelector(normalizedRoutingRuntimeState(cfg)) + manager := coreauth.NewManager(nil, selector, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + service := &Service{coreManager: manager, cfg: cfg} + a, err := manager.Register(context.Background(), &coreauth.Auth{ID: "a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + b, err := manager.Register(context.Background(), &coreauth.Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"service-reload-session"}}} + if _, err := selector.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{b}); err != nil { + t.Fatal(err) + } + next := *cfg + next.Routing.SessionAffinityRebindOn = "quota" + if !service.applyManagerConfig(context.Background(), configCommit{cfg: &next, sequence: 1}) { + t.Fatal("routing reload failed") + } + replacement := manager.Selector() + if replacement == selector { + t.Fatal("test did not replace selector") + } + t.Cleanup(func() { + if stoppable, ok := replacement.(coreauth.StoppableSelector); ok { + stoppable.Stop() + } + }) + got, err := replacement.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("reload changed warm account: %v, %v", got, err) + } +} + +func TestServiceAffinityStorageDisableDoesNotResurrectRemovedCredential(t *testing.T) { + cfg := &config.Config{KVStore: config.KVStoreConfig{Path: filepath.Join(t.TempDir(), "kv.db")}} + first := coreauth.NewSessionAffinitySelector(&coreauth.FillFirstSelector{}) + manager := coreauth.NewManager(nil, first, nil) + service := &Service{coreManager: manager} + service.applyKVStoreConfig(cfg) + t.Cleanup(func() { + first.Stop() + if err := service.shutdownKVStore(); err != nil { + t.Error(err) + } + }) + b, err := manager.Register(context.Background(), &coreauth.Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"disable-storage-session"}}} + if _, err := first.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{b}); err != nil { + t.Fatal(err) + } + first.Stop() // Flush while the initial store is still enabled. + disabled := *cfg + disabled.KVStore.Disabled = true + service.applyKVStoreConfig(&disabled) + manager.Remove(context.Background(), b.ID) + service.applyKVStoreConfig(cfg) + // A new manager simulates a new process with no runtime removal tombstones. + fresh := coreauth.NewSessionAffinitySelector(&coreauth.FillFirstSelector{}) + t.Cleanup(fresh.Stop) + got, err := fresh.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{{ID: "a"}, b}) + if err != nil || got == nil || got.ID != "a" { + t.Fatalf("disabled storage revived removed binding: %v, %v", got, err) + } + if _, enabled, err := kvstore.CurrentKVClient(); err != nil || !enabled { + t.Fatalf("KV did not re-enable: %t, %v", enabled, err) + } +} From be2aea13d4bd4be68e7a2a9f111fc978502d535f Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:36:55 -0800 Subject: [PATCH 02/19] fix(quota): restore safe persisted routing readings before polling --- internal/quotahistory/recorder.go | 31 +++- internal/quotahistory/restore.go | 95 ++++++++++++ internal/quotahistory/restore_test.go | 213 ++++++++++++++++++++++++++ internal/quotahistory/store.go | 5 + 4 files changed, 339 insertions(+), 5 deletions(-) create mode 100644 internal/quotahistory/restore.go create mode 100644 internal/quotahistory/restore_test.go diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index ddba0d3e806..c65d08e0d32 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -211,6 +211,9 @@ func (r *Recorder) Apply(s Settings) error { coreauth.ObserveAuthPlan(auth.ID, plan) } } + if errRestore := r.restoreRouting(store, s); errRestore != nil { + log.WithError(errRestore).Warn("quota-history: restore routing readings") + } r.wg.Add(1) go r.run(r.ctx, store, s) log.Infof("quota-history: recording every %s to %s (retention %s)", s.Interval, s.Path, s.Retention) @@ -416,6 +419,16 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { } rec.Windows = windows rec.Plan = plan + rec.RoutingVersion = 1 + rec.RoutingScopes = make(map[string][]string) + for key, window := range windows { + if len(window.modelScope) > 0 { + rec.RoutingScopes[key] = window.modelScope + } + if window.estimated { + rec.EstimatedWindows = append(rec.EstimatedWindows, key) + } + } if plan != "" { r.setPlan(auth.Index, plan) } @@ -424,7 +437,14 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { if providerOf(auth) == "mistral" { return rec } - r.publishRouting(auth, plan, windows, time.UnixMilli(rec.T)) + r.publishWindows(auth, plan, windows, time.UnixMilli(rec.T)) + return rec +} + +// publishWindows is shared by live polls and startup restoration. Observation +// timestamps always identify the original provider sample. +func (r *Recorder) publishWindows(auth *coreauth.Auth, plan string, windows map[string]Window, observedAt time.Time) { + r.publishRouting(auth, plan, windows, observedAt) observations := make([]coreauth.QuotaWindow, 0, len(windows)) for key, window := range windows { // A usage figure the parser had to assume is charted but does not steer routing. @@ -438,11 +458,10 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { observations = append(observations, coreauth.QuotaWindow{Key: key, UsedPercent: window.UsedPercent, ResetAt: time.UnixMilli(*window.ResetsAt), Period: time.Duration(window.PeriodHours * float64(time.Hour)), ModelScope: scope}) } - coreauth.ObserveQuotaWindows(auth.ID, time.UnixMilli(rec.T), observations) + coreauth.ObserveQuotaWindows(auth.ID, observedAt, observations) if providerOf(auth) == "claude" { - coreauth.ObserveScopedWeeklyWindows(auth.ID, time.UnixMilli(rec.T), scopedWeeklyWindows(windows)) + coreauth.ObserveScopedWeeklyWindows(auth.ID, observedAt, scopedWeeklyWindows(windows)) } - return rec } // publishRouting hands routing the plan and 5-hour reading of one account, so @@ -752,7 +771,9 @@ func (r *Recorder) forgetUntracked(enabled bool) { // The last plugin list keeps plugin-provider accounts tracked across a // settings change; trackable applies the new allowlist to them. for _, auth := range r.trackable(r.pluginProviders(context.Background(), false)) { - tracked[auth.ID] = true + if !isDisabled(auth) { + tracked[auth.ID] = true + } } } for _, auth := range r.deps.ListAuths() { diff --git a/internal/quotahistory/restore.go b/internal/quotahistory/restore.go new file mode 100644 index 00000000000..5e0fdeda381 --- /dev/null +++ b/internal/quotahistory/restore.go @@ -0,0 +1,95 @@ +package quotahistory + +import ( + "context" + "math" + "time" +) + +// restoreRouting reuses the latest successful sample, like a live poll failure +// which leaves the preceding reading intact. A newer successful empty sample +// supersedes earlier windows. Removed, disabled and untracked accounts are ignored. +func (r *Recorder) restoreRouting(store *Store, settings Settings) error { + now := r.now() + latest := make(map[string]record) + tracked := r.trackable(r.pluginProviders(context.Background(), false)) + wanted := make(map[string]bool, len(tracked)) + for _, auth := range tracked { + if !isDisabled(auth) { + wanted[auth.Index] = true + } + } + if errScan := store.scan(now.Add(-settings.Retention).UnixMilli(), now.UnixMilli(), func(rec record) { + if wanted[rec.AuthIndex] && rec.Error == "" { + latest[rec.AuthIndex] = rec + } + }); errScan != nil { + return errScan + } + for _, auth := range tracked { + rec, found := latest[auth.Index] + if !found || isDisabled(auth) || providerOf(auth) == "mistral" { + continue + } + // Re-read after the history scan. A removed or replaced credential + // must not receive an older incarnation's reading. + current := r.current(auth.ID) + if current == nil || isDisabled(current) || current.Index != rec.AuthIndex || providerOf(current) != providerOf(auth) { + continue + } + auth = current + observedAt := time.UnixMilli(rec.T) + if rec.T <= 0 || observedAt.After(now) || (!auth.CreatedAt.IsZero() && auth.CreatedAt.UnixMilli() > rec.T) { + continue + } + windows := make(map[string]Window) + for key, window := range rec.Windows { + if rec.RoutingVersion == 0 { + // Claude's legacy parser always read utilization and has recoverable + // weekly family scopes. Codex's assumed 100% was indistinguishable from + // a measured exhausted window. Other providers may have lost arbitrary model scopes. + switch providerOf(auth) { + case "claude": + case "codex": + if window.UsedPercent == 100 { + continue + } + default: + continue + } + } else if rec.RoutingVersion == 1 { + window.modelScope = rec.RoutingScopes[key] + for _, estimated := range rec.EstimatedWindows { + if estimated == key { + window.estimated = true + break + } + } + } else { + continue + } + if !restorableWindow(window, observedAt, now) { + continue + } + windows[key] = window + } + // Use the already restored plan. A historical reading must not overwrite + // a plan learned more recently in this recorder's lifetime. + r.publishWindows(auth, r.plan(auth.Index), windows, observedAt) + } + return nil +} + +func restorableWindow(window Window, observedAt, now time.Time) bool { + if window.estimated || window.ResetsAt == nil || *window.ResetsAt <= 0 || + window.PeriodHours <= 0 || math.IsNaN(window.PeriodHours) || math.IsInf(window.PeriodHours, 0) || + math.IsNaN(window.UsedPercent) || math.IsInf(window.UsedPercent, 0) || window.UsedPercent < 0 { + return false + } + // Match routing's period-plus-one-day tolerance without overflowing a + // duration from malformed history. A passed reset is never rolled forward. + maxAge := (window.PeriodHours + 24) * float64(time.Hour) + reset := time.UnixMilli(*window.ResetsAt) + return reset.After(now) && !observedAt.After(now) && + float64(now.Sub(observedAt)) <= maxAge && float64(reset.Sub(observedAt)) <= maxAge +} diff --git a/internal/quotahistory/restore_test.go b/internal/quotahistory/restore_test.go new file mode 100644 index 00000000000..7a29ed3ec94 --- /dev/null +++ b/internal/quotahistory/restore_test.go @@ -0,0 +1,213 @@ +package quotahistory + +import ( + "context" + "sync/atomic" + "testing" + "time" + + coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +func forgetRouting(t *testing.T, auths ...*coreauth.Auth) { + t.Helper() + clear := func() { + for _, auth := range auths { + coreauth.ForgetQuotaWindows(auth.ID) + coreauth.ForgetScopedWeeklyWindows(auth.ID) + coreauth.ForgetShortWindowUsage(auth.ID) + coreauth.ObserveAuthPlan(auth.ID, "") + } + } + clear() + t.Cleanup(clear) +} + +func historyWindow(now time.Time, after time.Duration, used, period float64) Window { + reset := now.Add(after).UnixMilli() + return Window{UsedPercent: used, PeriodHours: period, ResetsAt: &reset} +} + +func seedHistory(t *testing.T, settings Settings, records ...record) { + t.Helper() + store, err := OpenStore(settings.Path) + if err != nil { + t.Fatal(err) + } + for _, rec := range records { + if err := store.put(rec); err != nil { + t.Fatal(err) + } + } + if err := store.Close(); err != nil { + t.Fatal(err) + } +} + +func TestRecorderRestoresRoutingBeforeInitialPoll(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + observed := now.Add(-2 * time.Minute) + a := &coreauth.Auth{ID: "restore-a", Index: "restore-a", Provider: "codex"} + b := &coreauth.Auth{ID: "restore-b", Index: "restore-b", Provider: "codex"} + forgetRouting(t, a, b) + settings := enabledSettings(t) + seedHistory(t, settings, + record{Sample: Sample{T: observed.UnixMilli(), AuthIndex: a.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 4*24*time.Hour, 20, 168)}}}, + record{Sample: Sample{T: observed.UnixMilli(), AuthIndex: b.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 20, 168)}}}, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: b.Index, Error: "HTTP 503"}}, + ) + var requests atomic.Int64 + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{a, b} }, Do: func(context.Context, *coreauth.Auth, string, string, map[string]string) (int, []byte, error) { + requests.Add(1) + return 500, nil, nil + }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + for _, auth := range []*coreauth.Auth{a, b} { + got, windows := coreauth.ObservedQuotaWindows(auth.ID) + if !got.Equal(observed) || len(windows) != 1 { + t.Fatalf("%s reading = %v, %+v", auth.ID, got, windows) + } + } + selector := &coreauth.SoonestResetFirstSelector{} + got, err := selector.Pick(context.Background(), "codex", "gpt-5", cliproxyexecutor.Options{}, []*coreauth.Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("restored Pick = %v, %v, want %s", got, err, b.ID) + } + if requests.Load() != 0 { + t.Fatal("startup performed an upstream poll") + } + // Reconfiguration must preserve a live observation newer than the snapshot. + newer := now.Add(-time.Second) + coreauth.ObserveQuotaWindows(b.ID, newer, []coreauth.QuotaWindow{{Key: "new", UsedPercent: 30, ResetAt: now.Add(48 * time.Hour), Period: 168 * time.Hour}}) + settings.Interval += time.Minute + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if ts, windows := coreauth.ObservedQuotaWindows(b.ID); !ts.Equal(newer) || len(windows) != 1 || windows[0].Key != "new" { + t.Fatalf("reload replaced newer reading: %v, %+v", ts, windows) + } +} + +func TestRecorderRestoreRejectsUnsafeHistory(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + for _, name := range []string{"expired", "stale", "future-observation", "far-reset", "missing-reset", "estimated", "legacy-codex-estimate", "disabled", "removed", "api-key", "untracked", "unknown-version", "replaced"} { + t.Run(name, func(t *testing.T) { + auth := &coreauth.Auth{ID: "restore-unsafe-" + name, Index: "restore-unsafe-" + name, Provider: "codex"} + forgetRouting(t, auth) + settings := enabledSettings(t) + rec := record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 100, 168)}}, RoutingVersion: 1} + auths := []*coreauth.Auth{auth} + switch name { + case "expired": + rec.Windows[WindowSevenDay] = historyWindow(now, 0, 100, 168) + case "stale": + rec.T = now.Add(-9 * 24 * time.Hour).UnixMilli() + case "future-observation": + rec.T = now.Add(time.Millisecond).UnixMilli() + case "far-reset": + rec.Windows[WindowSevenDay] = historyWindow(now, 30*24*time.Hour, 100, 168) + case "missing-reset": + rec.Windows[WindowSevenDay] = Window{UsedPercent: 100, PeriodHours: 168} + case "estimated": + rec.EstimatedWindows = []string{WindowSevenDay} + case "legacy-codex-estimate": + rec.RoutingVersion = 0 + case "disabled": + auth.Disabled = true + case "removed": + auths = nil + case "api-key": + auth.Attributes = map[string]string{"api_key": "synthetic-key"} + case "untracked": + settings.Providers = "claude" + case "unknown-version": + rec.RoutingVersion = 99 + case "replaced": + auth.CreatedAt = now + } + seedHistory(t, settings, rec) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return auths }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if _, windows := coreauth.ObservedQuotaWindows(auth.ID); len(windows) != 0 { + t.Fatalf("unsafe history restored: %+v", windows) + } + }) + } +} + +func TestRecorderPersistsParserSafetyMetadata(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + auth := &coreauth.Auth{ID: "restore-parser", Index: "restore-parser", Provider: "codex"} + forgetRouting(t, auth) + source := NewRecorder(Deps{Do: func(context.Context, *coreauth.Auth, string, string, map[string]string) (int, []byte, error) { + return 200, []byte(`{"rate_limit":{"limit_reached":true,"primary_window":{"limit_window_seconds":18000,"reset_after_seconds":3600},"secondary_window":{"used_percent":20,"limit_window_seconds":604800,"reset_after_seconds":86400}}}`), nil + }}) + source.now = func() time.Time { return now.Add(-time.Minute) } + rec := source.sample(context.Background(), auth) + if rec.Error != "" || len(rec.EstimatedWindows) != 1 { + t.Fatalf("sample = %+v", rec) + } + // A provider-specific model scope must survive storage even though Window's + // internal modelScope field is absent from the public history API. + rec.RoutingScopes = map[string][]string{WindowSevenDay: {"gpt-5-*"}} + settings := enabledSettings(t) + seedHistory(t, settings, rec) + coreauth.ForgetQuotaWindows(auth.ID) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{auth} }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + ts, windows := coreauth.ObservedQuotaWindows(auth.ID) + if !ts.Equal(time.UnixMilli(rec.T)) || len(windows) != 1 || windows[0].Key != WindowSevenDay || len(windows[0].ModelScope) != 1 || windows[0].ModelScope[0] != "gpt-5-*" { + t.Fatalf("restored = %v, %+v", ts, windows) + } +} + +func TestRecorderRestoreScopedCapsAndEmptySuccess(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + auth := &coreauth.Auth{ID: "restore-scoped", Index: "restore-scoped", Provider: "claude"} + other := &coreauth.Auth{ID: "restore-scoped-other", Index: "restore-scoped-other", Provider: "claude"} + forgetRouting(t, auth, other) + settings := enabledSettings(t) + seedHistory(t, settings, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 10, 168), WindowSevenDayFable: historyWindow(now, 48*time.Hour, 100, 168)}}}, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: other.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 72*time.Hour, 10, 168)}}}, + ) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{auth, other} }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ model, want string }{{"claude-fable-5", other.ID}, {"claude-sonnet-5", auth.ID}} { + got, err := (&coreauth.SoonestResetFirstSelector{}).Pick(context.Background(), "claude", tc.model, cliproxyexecutor.Options{}, []*coreauth.Auth{auth, other}) + if err != nil || got == nil || got.ID != tc.want { + t.Fatalf("Pick(%s)=%v,%v,want %s", tc.model, got, err, tc.want) + } + } + r.Close() + seedHistory(t, settings, record{Sample: Sample{T: now.UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{}}}) + coreauth.ForgetQuotaWindows(auth.ID) + coreauth.ForgetScopedWeeklyWindows(auth.ID) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if _, windows := coreauth.ObservedQuotaWindows(auth.ID); len(windows) != 0 { + t.Fatalf("empty success revived old windows: %+v", windows) + } +} diff --git a/internal/quotahistory/store.go b/internal/quotahistory/store.go index 2772d08aad9..567b0fff619 100644 --- a/internal/quotahistory/store.go +++ b/internal/quotahistory/store.go @@ -32,6 +32,11 @@ type Sample struct { type record struct { Sample Plan string `json:"plan,omitempty"` + // Routing metadata was absent in older history. Persist the parser's safety + // information separately so the management sample shape stays stable. + RoutingVersion int `json:"routing_version,omitempty"` + RoutingScopes map[string][]string `json:"routing_scopes,omitempty"` + EstimatedWindows []string `json:"estimated_windows,omitempty"` } // Store persists samples in bbolt. Keys are an 8-byte big-endian unix-ms From 3e890a318834e25fdf79554e45392d3430d39640 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:47:48 -0800 Subject: [PATCH 03/19] fix(codex): observe HTTP SSE quota events before filtering --- .../executor/codex_executor_execute.go | 1 + .../runtime/executor/codex_executor_stream.go | 2 + .../codex_http_quota_observation_test.go | 74 +++++++++++++++++++ .../runtime/executor/helps/codex_quota.go | 8 ++ .../runtime/executor/helps/logging_helpers.go | 2 +- 5 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 internal/runtime/executor/codex_http_quota_observation_test.go diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index f208015a7c4..5f2c602aea0 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -272,6 +272,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re } eventData := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, eventData) eventData = helps.RestoreCodexMultiAgentV2Response(eventData, optimizeMultiAgentV2) reporter.ObserveResponseModel(eventData) eventType := ojson.GetBytesNoCopy(eventData, "type").String() diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index 6b6bfe5eea7..fa353611767 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -269,6 +269,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au isHandshake = true } else if bytes.HasPrefix(line, dataTag) { data := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, data) data = helps.RestoreCodexMultiAgentV2Response(data, optimizeMultiAgentV2) observeCodexTokenEvent(reporter, data) translatedLine = append([]byte("data: "), data...) @@ -469,6 +470,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au translatedLine = transformed } else if bytes.HasPrefix(line, dataTag) { data := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, data) data = helps.RestoreCodexMultiAgentV2Response(data, optimizeMultiAgentV2) observeCodexTokenEvent(reporter, data) translatedLine = append([]byte("data: "), data...) diff --git a/internal/runtime/executor/codex_http_quota_observation_test.go b/internal/runtime/executor/codex_http_quota_observation_test.go new file mode 100644 index 00000000000..d476ba4b7ba --- /dev/null +++ b/internal/runtime/executor/codex_http_quota_observation_test.go @@ -0,0 +1,74 @@ +package executor + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/registry" + cliproxyauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + sdktranslator "github.com/rune-oai/t3code-proxy/sdk/translator" +) + +func TestCodexHTTPQuotaEventsReachCredentialWithoutHeaderPassthrough(t *testing.T) { + for _, mode := range []string{"buffered", "stream", "bootstrap-stream"} { + t.Run(mode, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("X-Codex-Turn-State", "opaque-continuation") + for _, event := range []string{ + codexCreatedEvent, + `{"type":"codex.rate_limits","rate_limits":{"primary":{"used_percent":42,"window_minutes":300,"reset_at":1893456000}},"metered_limit_name":"codex","headers":{"X-Codex-Turn-State":"opaque-event"}}`, + codexCompletedEventBody, + } { + _, _ = fmt.Fprint(w, "data: "+event+"\n\n") + } + })) + defer server.Close() + cfg := codexBufferingConfig(mode == "bootstrap-stream") + cfg.PassthroughHeaders = false + cfg.RequestLog = false + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(NewCodexExecutor(cfg)) + auth := codexAPIKeyTestAuth(server.URL) + auth.ID = "http-quota-" + mode + auth.Status = cliproxyauth.StatusActive + const model = "gpt-5.6-terra" + registry.GetGlobalRegistry().RegisterClient(auth.ID, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + ctx := context.Background() + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatal(err) + } + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"model":"gpt-5.6-terra","input":"hello"}`)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString("openai-response"), Stream: mode != "buffered"} + if opts.Stream { + result, err := manager.ExecuteStream(ctx, []string{"codex"}, req, opts) + if err != nil { + t.Fatal(err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, err := manager.Execute(ctx, []string{"codex"}, req, opts); err != nil { + t.Fatal(err) + } + updated, ok := manager.GetByID(auth.ID) + if !ok { + t.Fatal("selected credential missing") + } + if updated.Quota.Signals["X-Codex-Primary-Used-Percent"] != "42" || updated.Quota.Signals["X-Codex-Active-Limit"] != "codex" { + t.Fatalf("SSE quota event did not reach selected credential: %+v", updated.Quota.Signals) + } + if _, exists := updated.Quota.Signals["X-Codex-Turn-State"]; exists { + t.Fatal("opaque continuation state reached quota diagnostics") + } + }) + } +} diff --git a/internal/runtime/executor/helps/codex_quota.go b/internal/runtime/executor/helps/codex_quota.go index aa96f8f5e7c..0b14a6a7b4a 100644 --- a/internal/runtime/executor/helps/codex_quota.go +++ b/internal/runtime/executor/helps/codex_quota.go @@ -1,13 +1,21 @@ package helps import ( + "context" "net/http" "strings" "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/logging" "github.com/rune-oai/t3code-proxy/internal/util" ) +// ObserveCodexQuotaEvent records quota data before transport-specific event +// filtering, independently of request logging and downstream header passthrough. +func ObserveCodexQuotaEvent(ctx context.Context, payload []byte) { + logging.MergeResponseHeaders(ctx, ParseCodexQuotaEventHeaders(payload)) +} + const ( codexRateLimitsEventType = "codex.rate_limits" codexQuotaAdditionalHeaderKey = "X-Codex-Additional-" diff --git a/internal/runtime/executor/helps/logging_helpers.go b/internal/runtime/executor/helps/logging_helpers.go index e5b5bb3d6ec..e02e5d63ef6 100644 --- a/internal/runtime/executor/helps/logging_helpers.go +++ b/internal/runtime/executor/helps/logging_helpers.go @@ -539,7 +539,7 @@ func AppendAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload // AppendCodexAPIWebsocketResponse stores a codex upstream websocket response frame and merges any // quota event headers carried by the frame into the request log. func AppendCodexAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload []byte) { - logging.MergeResponseHeaders(ctx, ParseCodexQuotaEventHeaders(payload)) + ObserveCodexQuotaEvent(ctx, payload) AppendAPIWebsocketResponse(ctx, cfg, payload) } From a0b8f717a1e4327c13cd61e4f80a7f7ac92a5d32 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:58:16 -0800 Subject: [PATCH 04/19] fix(auth): preserve affinity across tier and transport changes --- sdk/cliproxy/auth/selector.go | 19 ++--- sdk/cliproxy/auth/session_persistence.go | 28 +++----- sdk/cliproxy/auth/session_persistence_test.go | 72 +++++++++++++++++++ .../service_affinity_persistence_test.go | 16 ++++- 4 files changed, 101 insertions(+), 34 deletions(-) diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index fcd1d665494..a4c8c7427c4 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -1652,11 +1652,6 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if opts.Metadata == nil { opts.Metadata = make(map[string]any) } - if cliproxyexecutor.DownstreamWebsocket(ctx) { - opts.Metadata[affinityTransportMetadataKey] = "ws" - } else { - delete(opts.Metadata, affinityTransportMetadataKey) - } opts.Metadata[cliproxyexecutor.SessionAffinityProviderMetadataKey] = provider opts.Metadata[cliproxyexecutor.SessionAffinityModelMetadataKey] = model @@ -1746,7 +1741,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri } for _, candidate := range bindingCandidates { if candidate != nil && candidate.ID == authID { - s.persistence.bind(candidate, s.cache.ttl, affinityPersistenceKeys(keys, opts.Metadata)...) + s.persistence.bind(candidate, s.cache.ttl, keys...) break } } @@ -1768,9 +1763,9 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri } if explicitID != "" { - s.restoreExplicitBinding(cacheKey, auths, opts.Metadata) + s.restoreExplicitBinding(cacheKey, auths) if fallbackKey != "" { - s.restoreExplicitBinding(fallbackKey, auths, opts.Metadata) + s.restoreExplicitBinding(fallbackKey, auths) } } if cachedAuthID, ok := s.cache.GetAndRefresh(cacheKey); ok { @@ -2419,19 +2414,19 @@ func (s *SessionAffinitySelector) OnResult(res Result) { } if res.Success { if s.cache.Touch(cacheKey, res.AuthID) && explicitID != "" { - s.persistence.touch(res.AuthID, s.cache.ttl, affinityPersistenceKey(cacheKey, res.Options.Metadata)) + s.persistence.touch(res.AuthID, s.cache.ttl, cacheKey) } if fallbackKey != "" { if s.cache.Touch(fallbackKey, res.AuthID) && explicitID != "" { - s.persistence.touch(res.AuthID, s.cache.ttl, affinityPersistenceKey(fallbackKey, res.Options.Metadata)) + s.persistence.touch(res.AuthID, s.cache.ttl, fallbackKey) } } return } if explicitID != "" { - s.persistence.remove(res.AuthID, affinityPersistenceKey(cacheKey, res.Options.Metadata)) + s.persistence.remove(res.AuthID, cacheKey) if fallbackKey != "" { - s.persistence.remove(res.AuthID, affinityPersistenceKey(fallbackKey, res.Options.Metadata)) + s.persistence.remove(res.AuthID, fallbackKey) } } s.cache.CompareAndDelete(cacheKey, res.AuthID) diff --git a/sdk/cliproxy/auth/session_persistence.go b/sdk/cliproxy/auth/session_persistence.go index 2574a639954..5c3b194f16e 100644 --- a/sdk/cliproxy/auth/session_persistence.go +++ b/sdk/cliproxy/auth/session_persistence.go @@ -2,7 +2,6 @@ package auth import ( "context" - "strconv" "sync" "time" @@ -298,15 +297,12 @@ func affinityRequestNamespace(provider string, metadata map[string]any) string { func affinityRequestScope(metadata map[string]any) string { caller := sessionMetadataString(metadata, cliproxyexecutor.CallerScopeMetadataKey) - tier := sessionMetadataString(metadata, cliproxyexecutor.ServiceTierMetadataKey) - if caller == "" && tier == "" { + if caller == "" { return "" } - return kvstore.HashKeyPart(strconv.Quote(caller) + strconv.Quote(tier)) + return kvstore.HashKeyPart(caller) } -const affinityTransportMetadataKey = "session_affinity_transport" - func (p *sessionAffinityPersistence) touch(authID string, ttl time.Duration, key string) { if p == nil { return @@ -334,14 +330,14 @@ func (p *sessionAffinityPersistence) retireAuth(authID string, epoch, generation p.dirty = true } -func (s *SessionAffinitySelector) restoreExplicitBinding(key string, candidates []*Auth, metadata map[string]any) { +func (s *SessionAffinitySelector) restoreExplicitBinding(key string, candidates []*Auth) { if _, ok := s.cache.Get(key); ok { return } if s.authCandidates != nil { candidates = s.authCandidates() } - if authID, expiresAt, ok := s.persistence.get(affinityPersistenceKey(key, metadata), s.cache.ttl, candidates); ok { + if authID, expiresAt, ok := s.persistence.get(key, s.cache.ttl, candidates); ok { s.cache.mu.Lock() s.cache.ensureInitializedLocked() // A concurrent request may already have installed a newer binding. @@ -363,18 +359,6 @@ func (m *Manager) CloseSessionAffinityPersistence() { persistence.close() } -func affinityPersistenceKey(key string, metadata map[string]any) string { - return key + "\x00transport=" + sessionMetadataString(metadata, affinityTransportMetadataKey) -} - -func affinityPersistenceKeys(keys []string, metadata map[string]any) []string { - scoped := make([]string, 0, len(keys)) - for _, key := range keys { - scoped = append(scoped, affinityPersistenceKey(key, metadata)) - } - return scoped -} - func minAffinityExpiry(entry sessionEntry, ttl time.Duration) time.Time { if limit := entry.touchedAt.Add(ttl); limit.Before(entry.expiresAt) { return limit @@ -413,6 +397,10 @@ func (m *Manager) SetSessionAffinityPersistenceEnabled(enabled bool) { p.mu.Unlock() return } + if p.suspended { + p.mu.Unlock() + return + } p.localLocked() p.suspended = true client := p.client diff --git a/sdk/cliproxy/auth/session_persistence_test.go b/sdk/cliproxy/auth/session_persistence_test.go index 074899e919c..d0234f13c99 100644 --- a/sdk/cliproxy/auth/session_persistence_test.go +++ b/sdk/cliproxy/auth/session_persistence_test.go @@ -87,8 +87,10 @@ func TestPersistentAffinityRestartAndIsolation(t *testing.T) { provider = "other-provider" case "tier": opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = "priority" + want = b.ID case "transport": ctx = cliproxyexecutor.WithDownstreamWebsocket(ctx) + want = b.ID case "provider-scope": opts.Metadata[cliproxyexecutor.ProviderScopeMetadataKey] = "restricted" } @@ -97,6 +99,76 @@ func TestPersistentAffinityRestartAndIsolation(t *testing.T) { } } +func TestSessionAffinityLiveTierToggleKeepsBinding(t *testing.T) { + selector := persistentSelector(t, time.Hour) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + opts := affinityOptions() + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = "auto" + expectAffinityPick(t, selector, context.Background(), "codex", "model", opts, []*Auth{b}, b.ID) + for _, tier := range []string{"priority", "auto", "", "default", "priority"} { + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = tier + expectAffinityPick(t, selector, context.Background(), "codex", "model", opts, []*Auth{a, b}, b.ID) + if got, ok := selector.boundAuthForRequest([]string{"codex"}, "model", opts); !ok || got != b.ID { + t.Fatalf("tier %q lost bound request lookup: %s, %t", tier, got, ok) + } + } + // Results use the same tier-independent key as selection. + selector.OnResult(Result{AuthID: b.ID, Provider: "codex", Model: "model", Options: opts}) + expectAffinityPick(t, selector, context.Background(), "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) +} + +func TestPersistentAffinityTransportSwitchRestoresLatestBinding(t *testing.T) { + for _, firstTransport := range []string{"http", "ws"} { + t.Run(firstTransport, func(t *testing.T) { + path := affinityKV(t) + httpCtx := context.Background() + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(httpCtx) + firstCtx, secondCtx := httpCtx, wsCtx + if firstTransport == "ws" { + firstCtx, secondCtx = wsCtx, httpCtx + } + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + original := persistentSelector(t, time.Hour) + firstOpts, secondOpts := affinityOptions(), affinityOptions() + expectAffinityPick(t, original, firstCtx, "codex", "model", firstOpts, []*Auth{a}, a.ID) + expectAffinityPick(t, original, secondCtx, "codex", "model", secondOpts, []*Auth{b}, b.ID) + // An older transport's delayed failure cannot delete the newer binding. + original.OnResult(Result{AuthID: a.ID, Provider: "codex", Model: "model", Options: firstOpts}) + original.Stop() + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + restored := persistentSelector(t, time.Hour) + expectAffinityPick(t, restored, firstCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, b.ID) + // A result on the original transport invalidates the shared durable binding. + restored.OnResult(Result{AuthID: b.ID, Provider: "codex", Model: "model", Options: affinityOptions()}) + restored.Stop() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, secondCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) + }) + } +} + +func TestPersistentAffinityTransportRestoreRespectsEligibleCandidates(t *testing.T) { + affinityKV(t) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + original := persistentSelector(t, time.Hour) + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(context.Background()) + expectAffinityPick(t, original, wsCtx, "codex", "model", affinityOptions(), []*Auth{b}, b.ID) + original.Stop() + restored := persistentSelector(t, time.Hour) + // Managers expose all registered credentials for restoration, while the + // request's candidates have already passed provider/model/caller eligibility. + restored.authCandidates = func() []*Auth { return []*Auth{a, b} } + expectAffinityPick(t, restored, context.Background(), "codex", "model", affinityOptions(), []*Auth{a}, a.ID) + restored.Stop() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, wsCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) +} + func TestPersistentAffinityReloadBeforeFlushAndRemoval(t *testing.T) { affinityKV(t) first := persistentSelector(t, time.Hour) diff --git a/sdk/cliproxy/service_affinity_persistence_test.go b/sdk/cliproxy/service_affinity_persistence_test.go index 608ba10c605..72600c5d5d1 100644 --- a/sdk/cliproxy/service_affinity_persistence_test.go +++ b/sdk/cliproxy/service_affinity_persistence_test.go @@ -4,13 +4,14 @@ import ( "context" "net/http" "path/filepath" - - "github.com/rune-oai/t3code-proxy/internal/kvstore" "testing" "github.com/rune-oai/t3code-proxy/internal/config" + "github.com/rune-oai/t3code-proxy/internal/kvstore" coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" ) func TestServiceRoutingReloadPreservesExplicitAffinity(t *testing.T) { @@ -75,6 +76,17 @@ func TestServiceAffinityStorageDisableDoesNotResurrectRemovedCredential(t *testi disabled := *cfg disabled.KVStore.Disabled = true service.applyKVStoreConfig(&disabled) + previousHooks := log.StandardLogger().Hooks + hook := logtest.NewLocal(log.StandardLogger()) + t.Cleanup(func() { log.StandardLogger().ReplaceHooks(previousHooks) }) + for range 3 { + service.applyKVStoreConfig(&disabled) + } + for _, entry := range hook.AllEntries() { + if entry.Message == "session-affinity: clear disabled persistence" { + t.Fatal("disabled reload tried to clear a closed KV store") + } + } manager.Remove(context.Background(), b.ID) service.applyKVStoreConfig(cfg) // A new manager simulates a new process with no runtime removal tombstones. From 38d3bee62af7af0e18c3b496f13cffe05295f39c Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:31:07 -0800 Subject: [PATCH 05/19] fix(auth): serialize affinity publication with credential retirement --- sdk/cliproxy/auth/selector.go | 34 ++++---- sdk/cliproxy/auth/session_persistence.go | 23 ++++- .../session_persistence_lifecycle_test.go | 87 +++++++++++++++++++ sdk/cliproxy/auth/session_persistence_test.go | 16 ++-- 4 files changed, 134 insertions(+), 26 deletions(-) create mode 100644 sdk/cliproxy/auth/session_persistence_lifecycle_test.go diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index a4c8c7427c4..f67db587309 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -1734,32 +1734,36 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if fallbackKey != "" && !isSubagent && !isFork { keys = append(keys, fallbackKey) } - if explicitID != "" { - bindingCandidates := auths - if !recordSelection && s.authCandidates != nil { - bindingCandidates = s.authCandidates() + publish := func() { + if !recordSelection { + s.cache.SetAliases(authID, keys...) + return } - for _, candidate := range bindingCandidates { + bindingProvider := canonicalSchedulingProvider(provider) + for _, candidate := range auths { if candidate != nil && candidate.ID == authID { - s.persistence.bind(candidate, s.cache.ttl, keys...) + if candidateProvider := canonicalSchedulingProvider(executorKeyFromAuth(candidate)); candidateProvider != "" { + bindingProvider = candidateProvider + } break } } + s.cache.setAliases(authID, sessionBinding{provider: bindingProvider, sessionID: primaryID, scope: affinityRequestScope(opts.Metadata), model: modelKey}, keys...) } - if !recordSelection { - s.cache.SetAliases(authID, keys...) + if explicitID == "" { + publish() return } - bindingProvider := canonicalSchedulingProvider(provider) - for _, candidate := range auths { + bindingCandidates := auths + if !recordSelection && s.authCandidates != nil { + bindingCandidates = s.authCandidates() + } + for _, candidate := range bindingCandidates { if candidate != nil && candidate.ID == authID { - if candidateProvider := canonicalSchedulingProvider(executorKeyFromAuth(candidate)); candidateProvider != "" { - bindingProvider = candidateProvider - } - break + s.persistence.bind(candidate, s.cache.ttl, publish, keys...) + return } } - s.cache.setAliases(authID, sessionBinding{provider: bindingProvider, sessionID: primaryID, scope: affinityRequestScope(opts.Metadata), model: modelKey}, keys...) } if explicitID != "" { diff --git a/sdk/cliproxy/auth/session_persistence.go b/sdk/cliproxy/auth/session_persistence.go index 5c3b194f16e..5e6f86bfcec 100644 --- a/sdk/cliproxy/auth/session_persistence.go +++ b/sdk/cliproxy/auth/session_persistence.go @@ -139,6 +139,11 @@ func (p *sessionAffinityPersistence) get(key string, ttl time.Duration, candidat } p.mu.Lock() defer p.mu.Unlock() + return p.getLocked(key, ttl, candidates) +} + +// getLocked allows restoration to publish into the live cache before retirement. +func (p *sessionAffinityPersistence) getLocked(key string, ttl time.Duration, candidates []*Auth) (string, time.Time, bool) { if p.closed { return "", time.Time{}, false } @@ -157,8 +162,10 @@ func (p *sessionAffinityPersistence) get(key string, ttl time.Duration, candidat return "", time.Time{}, false } -func (p *sessionAffinityPersistence) bind(auth *Auth, ttl time.Duration, keys ...string) { - if p == nil || auth == nil || auth.Disabled || auth.Status == StatusDisabled { +// bind publishes live and durable state under the retirement lock. Publication +// must only touch the selector cache; manager lookups must happen before this call. +func (p *sessionAffinityPersistence) bind(auth *Auth, ttl time.Duration, publish func(), keys ...string) { + if p == nil || auth == nil { return } p.mu.Lock() @@ -171,6 +178,12 @@ func (p *sessionAffinityPersistence) bind(auth *Auth, ttl time.Duration, keys .. if version, retired := p.retired[authHash]; retired && (auth.RegistrationEpoch < version.epoch || (auth.RegistrationEpoch == version.epoch && auth.Generation <= version.generation)) { return } + if publish != nil { + publish() + } + if auth.Disabled || auth.Status == StatusDisabled { + return + } aliases := make([]string, 0, len(keys)) for _, key := range keys { aliases = append(aliases, persistedAffinityKey(key)) @@ -337,7 +350,11 @@ func (s *SessionAffinitySelector) restoreExplicitBinding(key string, candidates if s.authCandidates != nil { candidates = s.authCandidates() } - if authID, expiresAt, ok := s.persistence.get(key, s.cache.ttl, candidates); ok { + // Match bind's lock order so a retired snapshot cannot be published after + // removal has already invalidated the live cache. + s.persistence.mu.Lock() + defer s.persistence.mu.Unlock() + if authID, expiresAt, ok := s.persistence.getLocked(key, s.cache.ttl, candidates); ok { s.cache.mu.Lock() s.cache.ensureInitializedLocked() // A concurrent request may already have installed a newer binding. diff --git a/sdk/cliproxy/auth/session_persistence_lifecycle_test.go b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go new file mode 100644 index 00000000000..8f68b57a3d7 --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go @@ -0,0 +1,87 @@ +package auth + +import ( + "context" + "net/http" + "sync/atomic" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/registry" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +type lifecycleBlockingFallback struct { + entered chan struct{} + release chan struct{} + calls atomic.Int32 +} + +func (f *lifecycleBlockingFallback) Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (*Auth, error) { + if f.calls.Add(1) == 1 { + close(f.entered) + <-f.release + } + return (&FillFirstSelector{}).Pick(ctx, provider, model, opts, auths) +} + +func TestRemovedIncarnationCannotBecomeDurableThroughLiveCache(t *testing.T) { + affinityKV(t) + f := &lifecycleBlockingFallback{entered: make(chan struct{}), release: make(chan struct{})} + s := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: time.Hour, Fallback: f}) + t.Cleanup(s.Stop) + m := NewManager(nil, s, nil) + t.Cleanup(m.CloseSessionAffinityPersistence) + m.RegisterExecutor(schedulerProviderTestExecutor{provider: "claude"}) + b, err := m.Register(t.Context(), &Auth{ID: "sol-removed-b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + const model = "sol-lifecycle-model" + reg := registry.GetGlobalRegistry() + registerModel := func(id string) { reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) } + registerModel(b.ID) + t.Cleanup(func() { reg.UnregisterClient(b.ID); reg.UnregisterClient("sol-a") }) + options := func() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"sol-remove-session"}}} + } + done := make(chan error, 1) + go func() { _, errPick := m.SelectAuth(t.Context(), "claude", model, options()); done <- errPick }() + <-f.entered + m.Remove(t.Context(), b.ID) + close(f.release) + if errPick := <-done; errPick != nil { + t.Fatal(errPick) + } + s.persistence.mu.Lock() + durableImmediatelyAfterRemoval := len(s.persistence.cache.entries) + s.persistence.mu.Unlock() + if durableImmediatelyAfterRemoval != 0 { + t.Fatalf("stale selection directly persisted %d aliases", durableImmediatelyAfterRemoval) + } + // Administrative removal has finished before the old selection installs + // its live binding. Its direct durable write is correctly tombstoned. + a, err := m.Register(t.Context(), &Auth{ID: "sol-a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + registerModel(a.ID) + replacement, err := m.Register(t.Context(), &Auth{ID: b.ID, Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + registerModel(replacement.ID) + got, err := m.SelectAuth(t.Context(), "claude", model, options()) + if err != nil { + t.Fatal(err) + } + s.persistence.flush() + fresh := persistentSelector(t, time.Hour) + restored, err := fresh.Pick(t.Context(), "claude", model, options(), []*Auth{a, replacement}) + if err != nil { + t.Fatal(err) + } + if got.ID != a.ID || restored.ID != a.ID { + t.Fatalf("removed incarnation's session revived: live=%s restarted=%s, want fresh selection %s", got.ID, restored.ID, a.ID) + } +} diff --git a/sdk/cliproxy/auth/session_persistence_test.go b/sdk/cliproxy/auth/session_persistence_test.go index d0234f13c99..22c2de9cdcf 100644 --- a/sdk/cliproxy/auth/session_persistence_test.go +++ b/sdk/cliproxy/auth/session_persistence_test.go @@ -195,7 +195,7 @@ func TestPersistentAffinityReloadBeforeFlushAndRemoval(t *testing.T) { manager.SetSelector(&FillFirstSelector{}) manager.Remove(context.Background(), "b") // An already-running selection cannot write the removed incarnation back. - first.persistence.bind(b, time.Hour, "delayed-selection") + first.persistence.bind(b, time.Hour, nil, "delayed-selection") third := persistentSelector(t, time.Hour) manager.SetSelector(third) readded, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) @@ -224,7 +224,7 @@ func TestPersistentAffinityTTLAndSlidingRefresh(t *testing.T) { p.now, p.flushInterval = now, time.Hour t.Cleanup(p.close) auth := &Auth{ID: "auth"} - p.bind(auth, time.Hour, "route") + p.bind(auth, time.Hour, nil, "route") clock.Add(int64(40 * time.Minute)) p.touch(auth.ID, time.Hour, "route") p.flush() @@ -250,8 +250,8 @@ func TestPersistentAffinityAliasRebindAndResultInvalidation(t *testing.T) { p.flushInterval = time.Hour t.Cleanup(p.close) a, b := &Auth{ID: "a"}, &Auth{ID: "b"} - p.bind(a, time.Hour, "conversation", "pck:old") - p.bind(b, time.Hour, "conversation", "pck:new") + p.bind(a, time.Hour, nil, "conversation", "pck:old") + p.bind(b, time.Hour, nil, "conversation", "pck:new") // An older result must not delete the new account's alias. p.remove(a.ID, "conversation") p.flush() @@ -325,7 +325,7 @@ func TestPersistentAffinityConcurrentRemovalCannotResurrect(t *testing.T) { p.flushInterval = time.Hour t.Cleanup(p.close) old := &Auth{ID: "removed", RegistrationEpoch: 1, Generation: 1} - p.bind(old, time.Hour, "route") + p.bind(old, time.Hour, nil, "route") p.flush() // Both asynchronous work and old in-flight selections compete with removal. start := make(chan struct{}) @@ -334,7 +334,7 @@ func TestPersistentAffinityConcurrentRemovalCannotResurrect(t *testing.T) { defer close(done) <-start for range 50 { - p.bind(old, time.Hour, "route") + p.bind(old, time.Hour, nil, "route") p.flush() } }() @@ -360,10 +360,10 @@ func TestPersistentAffinityRefreshWritesAreThrottled(t *testing.T) { p.flushInterval = time.Hour t.Cleanup(p.close) auth := &Auth{ID: "auth"} - p.bind(auth, time.Hour, "route") + p.bind(auth, time.Hour, nil, "route") p.flush() timestamp.Add(int64(30 * time.Second)) - p.bind(auth, time.Hour, "route") + p.bind(auth, time.Hour, nil, "route") p.touch(auth.ID, time.Hour, "route") p.mu.Lock() dirty := p.dirty From a2175f85fef41bd13ac0f63200366c290ff7f73f Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-oai@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:42:29 -0800 Subject: [PATCH 06/19] fix(auth): preserve observed credential epochs during failover --- sdk/cliproxy/auth/selector.go | 10 +++- .../session_persistence_lifecycle_test.go | 55 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index f67db587309..f33d9422c80 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -1729,6 +1729,12 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri if fallbackID != "" && fallbackID != primaryID { fallbackKey = affinityRequestNamespace(provider, opts.Metadata) + "::" + fallbackID + "::" + modelKey } + // Capture incarnations before reading any binding. A later preservation must + // not adopt a replacement registration that appeared while fallback waited. + preservedCandidates := auths + if explicitID != "" && s.authCandidates != nil { + preservedCandidates = s.authCandidates() + } bind := func(authID string, recordSelection bool) { keys := []string{cacheKey} if fallbackKey != "" && !isSubagent && !isFork { @@ -1755,8 +1761,8 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri return } bindingCandidates := auths - if !recordSelection && s.authCandidates != nil { - bindingCandidates = s.authCandidates() + if !recordSelection { + bindingCandidates = preservedCandidates } for _, candidate := range bindingCandidates { if candidate != nil && candidate.ID == authID { diff --git a/sdk/cliproxy/auth/session_persistence_lifecycle_test.go b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go index 8f68b57a3d7..abddd586ab2 100644 --- a/sdk/cliproxy/auth/session_persistence_lifecycle_test.go +++ b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go @@ -85,3 +85,58 @@ func TestRemovedIncarnationCannotBecomeDurableThroughLiveCache(t *testing.T) { t.Fatalf("removed incarnation's session revived: live=%s restarted=%s, want fresh selection %s", got.ID, restored.ID, a.ID) } } + +func TestDelayedPreserveCannotReviveRemovedIncarnation(t *testing.T) { + affinityKV(t) + f := &lifecycleBlockingFallback{entered: make(chan struct{}), release: make(chan struct{})} + f.calls.Store(1) + s := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: time.Hour, Fallback: f, RebindOn: SessionAffinityRebindOnQuota}) + t.Cleanup(s.Stop) + m := NewManager(nil, s, nil) + t.Cleanup(m.CloseSessionAffinityPersistence) + m.RegisterExecutor(schedulerProviderTestExecutor{provider: "claude"}) + const model = "review-delayed-preserve-model" + reg := registry.GetGlobalRegistry() + register := func(id string) *Auth { + t.Helper() + a, err := m.Register(t.Context(), &Auth{ID: id, Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + return a + } + b := register("review-b") + options := func() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"review-preserve-session"}}} + } + if got, err := m.SelectAuth(t.Context(), "claude", model, options()); err != nil || got.ID != b.ID { + t.Fatalf("seed %v %v", got, err) + } + a := register("review-a") + m.MarkResult(t.Context(), Result{AuthID: b.ID, Provider: "claude", Model: model, Error: &Error{HTTPStatus: 502, Message: "overloaded"}, Options: options()}) + f.calls.Store(0) + done := make(chan error, 1) + go func() { _, err := m.SelectAuth(t.Context(), "claude", model, options()); done <- err }() + <-f.entered + m.Remove(t.Context(), b.ID) + replacement := register(b.ID) + close(f.release) + if err := <-done; err != nil { + t.Fatal(err) + } + got, err := m.SelectAuth(t.Context(), "claude", model, options()) + if err != nil { + t.Fatal(err) + } + s.persistence.flush() + fresh := persistentSelector(t, time.Hour) + restored, err := fresh.Pick(t.Context(), "claude", model, options(), []*Auth{a, replacement}) + if err != nil { + t.Fatal(err) + } + if got.ID != a.ID || restored.ID != a.ID { + t.Fatalf("retired binding revived: live=%s restarted=%s want=%s", got.ID, restored.ID, a.ID) + } +} From 6314e0fa2d59b39bba8172dcc293c96c64198f6a Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:38:50 -0800 Subject: [PATCH 07/19] fix(claude): stop replay after accepted responses are interrupted --- .../executor/claude_executor_execute.go | 12 +- .../executor/claude_executor_stream.go | 35 +-- .../claude_executor_truncation_test.go | 239 ++++++++++++++++++ .../runtime/executor/helps/response_decode.go | 9 + .../auth/conductor_request_scoped_errors.go | 3 +- 5 files changed, 279 insertions(+), 19 deletions(-) create mode 100644 internal/runtime/executor/claude_executor_truncation_test.go diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 1b094a5693d..ce4136134e0 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -358,7 +358,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } - return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, &helps.AcceptedResponseError{Err: err}) } defer func() { if errClose := decodedBody.Close(); errClose != nil { @@ -369,7 +369,15 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) - return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + var responseErr error = &helps.AcceptedResponseError{Err: err} + if upstreamStream { + // A complete vendor error event remains authoritative even if the + // decoder subsequently fails while reading the response trailer. + if vendorErr, ok := validateClaudeStreamingResponse(data).(statusErr); ok && !vendorErr.streamTruncated { + responseErr = vendorErr + } + } + return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, responseErr) } var streamUsage helps.StreamUsageBuffer threadMessageID := "" diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 0a51f523a5a..5fb010fef60 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -352,7 +352,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } - return nil, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + return nil, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, &helps.AcceptedResponseError{Err: err}) } out := make(chan cliproxyexecutor.StreamChunk, 1) go func() { @@ -454,12 +454,12 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if emitCancellation(scanner.Err()) { return } - errScan := scanner.Err() - if errScan == nil { - errScan = upstreamStreamErr + errScan := upstreamStreamErr + if errScan == nil && scanner.Err() != nil { + errScan = &helps.AcceptedResponseError{Err: scanner.Err()} } if errScan == nil && ctx.Err() == nil { - errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop"} + errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop", streamTruncated: true} } if errScan != nil { errScan = wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errScan) @@ -557,12 +557,12 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if emitCancellation(scanner.Err()) { return } - errScan := scanner.Err() - if errScan == nil { - errScan = upstreamStreamErr + errScan := upstreamStreamErr + if errScan == nil && scanner.Err() != nil { + errScan = &helps.AcceptedResponseError{Err: scanner.Err()} } if errScan == nil && ctx.Err() == nil { - errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop"} + errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop", streamTruncated: true} } if errScan != nil { errScan = wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errScan) @@ -594,6 +594,7 @@ func validateClaudeStreamingResponse(data []byte) error { hasData := false hasMessageStart := false hasMessageDelta := false + hasMessageStop := false for scanner.Scan() { line := bytes.TrimSpace(scanner.Bytes()) @@ -606,7 +607,7 @@ func validateClaudeStreamingResponse(data []byte) error { } hasData = true if !ojson.ValidBytes(payload) { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned malformed stream data"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned malformed stream data", streamTruncated: true} } root := util.ParseGJSONBytesNoCopy(payload) @@ -623,24 +624,26 @@ func validateClaudeStreamingResponse(data []byte) error { case "message_start": message := root.Get("message") if strings.TrimSpace(message.Get("id").String()) == "" || strings.TrimSpace(message.Get("model").String()) == "" { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream message_start is missing id or model"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream message_start is missing id or model", streamTruncated: true} } hasMessageStart = true case "message_delta": hasMessageDelta = true + case "message_stop": + hasMessageStop = true } } if errScan := scanner.Err(); errScan != nil { - return errScan + return &helps.AcceptedResponseError{Err: errScan} } if !hasData { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned empty stream response"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned empty stream response", streamTruncated: true} } if !hasMessageStart { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response is missing message_start"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response is missing message_start", streamTruncated: true} } - if !hasMessageDelta { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response ended before message completion"} + if !hasMessageDelta || !hasMessageStop { + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response ended before message completion", streamTruncated: true} } return nil } diff --git a/internal/runtime/executor/claude_executor_truncation_test.go b/internal/runtime/executor/claude_executor_truncation_test.go new file mode 100644 index 00000000000..43ecc857f16 --- /dev/null +++ b/internal/runtime/executor/claude_executor_truncation_test.go @@ -0,0 +1,239 @@ +package executor + +import ( + "bytes" + "compress/gzip" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/config" + "github.com/rune-oai/t3code-proxy/internal/registry" + "github.com/rune-oai/t3code-proxy/internal/runtime/executor/helps" + cliproxyauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + sdktranslator "github.com/rune-oai/t3code-proxy/sdk/translator" +) + +func TestClaudeExecutorManagerPrematureEOFKeepsCredentialWithoutReplay(t *testing.T) { + const model = "claude-sonnet-4-5" + const start = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_partial\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4-5\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n" + const delta = "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n" + const stop = "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + for _, failure := range []string{"message_start", "message_delta", "gzip-trailer", "gzip-header", "incomplete-json"} { + for _, rule := range []string{"none", "miss", "continue-and-cooldown"} { + for _, mode := range []string{"nonstream", "stream-claude", "stream-openai"} { + t.Run(failure+"/rule="+rule+"/"+mode, func(t *testing.T) { + var truncated atomic.Bool + var hits atomic.Int32 + accounts := make(chan string, 16) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + hits.Add(1) + accounts <- r.Header.Get("Authorization") + w.Header().Set("Content-Type", "text/event-stream") + payload := []byte(start) + if failure != "message_start" || !truncated.Load() { + payload = append(payload, delta...) + } + if !truncated.Load() { + payload = append(payload, stop...) + } else if failure == "incomplete-json" { + payload = append(payload, `data: {"type":"content_block_delta","delta":{"text":"unfinished`...) + } + if failure == "gzip-trailer" || failure == "gzip-header" { + var compressed bytes.Buffer + writer := gzip.NewWriter(&compressed) + _, _ = writer.Write(payload) + _ = writer.Close() + payload = compressed.Bytes() + if truncated.Load() { + if failure == "gzip-header" { + payload = payload[:5] + } else { + payload = payload[:len(payload)-5] + } + } + w.Header().Set("Content-Encoding", "gzip") + } + _, _ = w.Write(payload) + w.(http.Flusher).Flush() + })) + t.Cleanup(server.Close) + t.Cleanup(helps.ResetProxyTransports) + cfg := &config.Config{} + if rule != "none" { + pattern := ".+" + if rule == "miss" { + pattern = "never-match-this-upstream-error" + } + cfg.OAuthRequestScopedErrors = map[string][]config.RequestScopedErrorRule{ + "claude": {{Status: http.StatusBadGateway, MatchRegexr: []string{pattern}, Action: cliproxyauth.RequestScopedActionContinueAndCooldown}}, + } + } + + selector := cliproxyauth.NewSessionAffinitySelector(&cliproxyauth.RoundRobinSelector{}) + t.Cleanup(selector.Stop) + manager := cliproxyauth.NewManager(nil, selector, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(3, 0, 0) + manager.RegisterExecutor(NewClaudeExecutor(cfg)) + for _, name := range []string{"one.json", "two.json"} { + id := t.Name() + "/" + name + auth := &cliproxyauth.Auth{ + ID: id, FileName: name, Provider: "claude", ProxyURL: "direct", + Metadata: map[string]any{"access_token": "sk-ant-oat-test-" + name, "refresh_token": "refresh-" + name, "account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"}, + Attributes: map[string]string{"base_url": server.URL}, + } + if _, errRegister := manager.Register(t.Context(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + } + payload := []byte(`{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: payload, Headers: http.Header{"X-Claude-Code-Session-Id": []string{t.Name()}}, + } + if mode == "stream-claude" { + opts.ResponseFormat = sdktranslator.FormatClaude + } + request := cliproxyexecutor.Request{Model: model, Payload: payload} + run := func() error { + if mode == "nonstream" { + _, errExecute := manager.Execute(t.Context(), []string{"claude"}, request, opts) + return errExecute + } + result, errStream := manager.ExecuteStream(t.Context(), []string{"claude"}, request, opts) + if errStream != nil { + return errStream + } + var chunkErr error + var sawPayload bool + for chunk := range result.Chunks { + if len(chunk.Payload) > 0 { + sawPayload = true + } + if chunk.Err != nil { + chunkErr = chunk.Err + } + } + if !sawPayload && !(failure == "gzip-header" && truncated.Load()) { + t.Fatal("stream did not deliver accepted message_start") + } + return chunkErr + } + if errWarm := run(); errWarm != nil { + t.Fatal(errWarm) + } + firstAccount := <-accounts + if firstAccount == "" { + t.Fatal("request did not carry the selected OAuth credential") + } + truncated.Store(true) + errPartial := run() + var truncErr cliproxyexecutor.StreamTruncatedError + if !errors.As(errPartial, &truncErr) || !truncErr.IsStreamTruncated() { + t.Fatalf("error = %T (%v), want typed stream truncation", errPartial, errPartial) + } + if (failure == "gzip-header" || failure == "gzip-trailer") && mode == "nonstream" && !errors.Is(errPartial, io.ErrUnexpectedEOF) { + t.Fatalf("decoder cause lost: %v", errPartial) + } + if hits.Load() != 2 { + t.Fatalf("requests = %d, want 2 including warm-up", hits.Load()) + } + for _, name := range []string{"one.json", "two.json"} { + auth, _ := manager.GetByID(t.Name() + "/" + name) + if auth.Unavailable || auth.Quota.Exceeded || !auth.NextRetryAfter.IsZero() { + t.Fatalf("credential %s cooled after accepted partial response: %s", name, auth.StatusMessage) + } + for _, state := range auth.ModelStates { + if state.Unavailable || state.Quota.Exceeded || !state.NextRetryAfter.IsZero() { + t.Fatalf("model cooled after accepted partial response: %+v", state) + } + } + } + truncated.Store(false) + if errNext := run(); errNext != nil { + t.Fatal(errNext) + } + if hits.Load() != 3 || <-accounts != firstAccount || <-accounts != firstAccount { + t.Fatal("accepted partial response replayed or rebound the session") + } + }) + } + } + } +} + +func TestClaudeExecutorPreservesExplicitVendorErrors(t *testing.T) { + for _, failure := range []string{"http-status", "sse-error", "sse-error-gzip-cutoff"} { + for _, mode := range []string{"nonstream", "stream-claude", "stream-openai"} { + t.Run(failure+"/"+mode, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + if failure == "http-status" { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"explicit vendor rejection"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + payload := []byte("event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"explicit vendor rejection\"}}\n\n") + if failure == "sse-error-gzip-cutoff" { + var compressed bytes.Buffer + writer := gzip.NewWriter(&compressed) + _, _ = writer.Write(payload) + _ = writer.Close() + payload = compressed.Bytes()[:compressed.Len()-5] + w.Header().Set("Content-Encoding", "gzip") + } + _, _ = w.Write(payload) + })) + t.Cleanup(server.Close) + t.Cleanup(helps.ResetProxyTransports) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, ProxyURL: "direct"} + payload := []byte(`{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + request := cliproxyexecutor.Request{Model: "claude-sonnet-4-5", Payload: payload} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatOpenAI, OriginalRequest: payload} + if mode == "stream-claude" { + opts.ResponseFormat = sdktranslator.FormatClaude + } + var responseErr error + if mode == "nonstream" { + _, responseErr = executor.Execute(t.Context(), auth, request, opts) + } else { + var result *cliproxyexecutor.StreamResult + result, responseErr = executor.ExecuteStream(t.Context(), auth, request, opts) + if responseErr == nil { + for chunk := range result.Chunks { + if chunk.Err != nil { + responseErr = chunk.Err + } + } + } + } + if responseErr == nil || !strings.Contains(responseErr.Error(), "explicit vendor rejection") { + t.Fatalf("vendor error lost: %v", responseErr) + } + var truncated cliproxyexecutor.StreamTruncatedError + if errors.As(responseErr, &truncated) && truncated.IsStreamTruncated() { + t.Fatalf("vendor error classified as response interruption: %v", responseErr) + } + var status interface{ StatusCode() int } + want := http.StatusBadGateway + if failure == "http-status" { + want = http.StatusTooManyRequests + } + if !errors.As(responseErr, &status) || status.StatusCode() != want { + t.Fatalf("vendor status lost: %v", responseErr) + } + }) + } + } +} diff --git a/internal/runtime/executor/helps/response_decode.go b/internal/runtime/executor/helps/response_decode.go index 6f1419cc719..4cedc3ef934 100644 --- a/internal/runtime/executor/helps/response_decode.go +++ b/internal/runtime/executor/helps/response_decode.go @@ -16,6 +16,15 @@ import ( log "github.com/sirupsen/logrus" ) +// AcceptedResponseError marks a read or decoding failure after upstream acceptance. +// The generation may have run, so it must not be replayed or cool the credential. +type AcceptedResponseError struct{ Err error } + +func (e *AcceptedResponseError) Error() string { return e.Err.Error() } +func (e *AcceptedResponseError) Unwrap() error { return e.Err } +func (e *AcceptedResponseError) IsStreamTruncated() bool { return true } +func (e *AcceptedResponseError) StatusCode() int { return http.StatusBadGateway } + type compositeReadCloser struct { io.Reader closers []func() error diff --git a/sdk/cliproxy/auth/conductor_request_scoped_errors.go b/sdk/cliproxy/auth/conductor_request_scoped_errors.go index 4a01ee709ef..fb52a5131d1 100644 --- a/sdk/cliproxy/auth/conductor_request_scoped_errors.go +++ b/sdk/cliproxy/auth/conductor_request_scoped_errors.go @@ -194,7 +194,8 @@ func ResolveRequestScopedErrorRules(auth *Auth, cfg *internalconfig.Config) []in // MatchRequestScopedErrorRules evaluates an error against a pre-resolved rule list. func MatchRequestScopedErrorRules(rules []internalconfig.RequestScopedErrorRule, err error) (string, bool) { - if err == nil || len(rules) == 0 || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { + // A locally truncated response already reached the provider and must not be retried. + if err == nil || len(rules) == 0 || isStreamTruncatedError(err) || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { return "", false } From 327e0d317f8839dba5677cba40572cccab819f6c Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:39:35 -0800 Subject: [PATCH 08/19] fix(logging): synchronize deferred request capture finalization --- internal/api/middleware/request_logging.go | 55 ++++++++++++------- .../api/middleware/request_logging_test.go | 37 +++++++++++++ internal/api/middleware/response_writer.go | 2 +- 3 files changed, 74 insertions(+), 20 deletions(-) diff --git a/internal/api/middleware/request_logging.go b/internal/api/middleware/request_logging.go index d109250b50f..dabba1bbe5e 100644 --- a/internal/api/middleware/request_logging.go +++ b/internal/api/middleware/request_logging.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "strings" + "sync" "time" "github.com/gin-gonic/gin" @@ -76,7 +77,7 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc { deferredCapture := attachDeferredRequestBodyCapture(c.Request, logger, requestInfo, false, false) if captureBody { c.Set(authenticatedRequestBodyCapturerContextKey, func() { - if deferredCapture != nil && deferredCapture.bytesRead == 0 { + if deferredCapture != nil && !deferredCapture.hasRead() { c.Request.Body = deferredCapture.body requestInfo.deferredBodyCapture = nil deferredCapture.Cleanup() @@ -147,6 +148,7 @@ func CaptureAuthenticatedRequestBody(c *gin.Context) { } type deferredRequestBodyCapture struct { + mu sync.Mutex body io.ReadCloser factory fileBodySourceFactory memBuf bytes.Buffer @@ -184,7 +186,13 @@ func (c *deferredRequestBodyCapture) Read(payload []byte) (int, error) { if c == nil || c.body == nil { return 0, io.EOF } + // Close must be able to unblock the underlying read. n, errRead := c.body.Read(payload) + c.mu.Lock() + defer c.mu.Unlock() + if c.finished { + return n, errRead + } if errRead == io.EOF { c.sawEOF = true } @@ -192,7 +200,7 @@ func (c *deferredRequestBodyCapture) Read(payload []byte) (int, error) { return n, errRead } c.bytesRead += int64(n) - if c.skipCapture || c.captureErr != nil || c.finished { + if c.skipCapture || c.captureErr != nil { return n, errRead } @@ -269,17 +277,16 @@ func (c *deferredRequestBodyCapture) Close() error { if c == nil { return nil } - _ = c.Finish() + c.mu.Lock() + _ = c.finishLocked() + c.mu.Unlock() if c.body == nil { return nil } return c.body.Close() } -func (c *deferredRequestBodyCapture) Finish() error { - if c == nil { - return nil - } +func (c *deferredRequestBodyCapture) finishLocked() error { if c.finished { return c.captureErr } @@ -297,7 +304,9 @@ func (c *deferredRequestBodyCapture) Bytes() ([]byte, string, error) { if c == nil || c.skipCapture { return nil, "", nil } - if errFinish := c.Finish(); errFinish != nil { + c.mu.Lock() + defer c.mu.Unlock() + if errFinish := c.finishLocked(); errFinish != nil { return nil, "", errFinish } if c.source != nil { @@ -305,31 +314,37 @@ func (c *deferredRequestBodyCapture) Bytes() ([]byte, string, error) { if errBytes != nil { return nil, "", errBytes } - return body, c.statusMarker(), nil + return body, c.statusMarkerLocked(), nil } var body []byte if c.memBuf.Len() > 0 { body = bytes.Clone(c.memBuf.Bytes()) } - return body, c.statusMarker(), nil + return body, c.statusMarkerLocked(), nil } func (c *deferredRequestBodyCapture) isComplete() bool { - if c == nil { - return true - } + c.mu.Lock() + defer c.mu.Unlock() + return c.isCompleteLocked() +} + +func (c *deferredRequestBodyCapture) hasRead() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.bytesRead > 0 +} + +func (c *deferredRequestBodyCapture) isCompleteLocked() bool { return c.sawEOF || (c.contentLength >= 0 && c.bytesRead >= c.contentLength) } -func (c *deferredRequestBodyCapture) statusMarker() string { - if c == nil { - return "" - } +func (c *deferredRequestBodyCapture) statusMarkerLocked() string { var markers []string if c.truncated { markers = append(markers, fmt.Sprintf("[REQUEST BODY TRUNCATED: captured first %d bytes]", c.bytesCaptured)) } - if !c.isComplete() { + if !c.isCompleteLocked() { if c.contentLength >= 0 { markers = append(markers, fmt.Sprintf("[REQUEST BODY CAPTURE INCOMPLETE: consumed %d of %d bytes]", c.bytesRead, c.contentLength)) } else { @@ -343,7 +358,9 @@ func (c *deferredRequestBodyCapture) Cleanup() { if c == nil { return } - if errFinish := c.Finish(); errFinish != nil { + c.mu.Lock() + defer c.mu.Unlock() + if errFinish := c.finishLocked(); errFinish != nil { log.WithError(errFinish).Warn("failed to finish deferred request body capture") } c.memBuf.Reset() diff --git a/internal/api/middleware/request_logging_test.go b/internal/api/middleware/request_logging_test.go index 3e9eb0793a3..e41a16d3ce7 100644 --- a/internal/api/middleware/request_logging_test.go +++ b/internal/api/middleware/request_logging_test.go @@ -1620,3 +1620,40 @@ func TestRequestLoggingMiddlewareIsolatesDeferredResponseAcrossStreamCancelAndGi } }) } + +type blockedCaptureBody struct { + started chan struct{} + closed chan struct{} +} + +func (b *blockedCaptureBody) Read(p []byte) (int, error) { + close(b.started) + <-b.closed + return copy(p, "late bytes"), io.EOF +} + +func (b *blockedCaptureBody) Close() error { + close(b.closed) + return nil +} + +func TestDeferredRequestBodyCaptureCloseDuringBlockedRead(t *testing.T) { + body := &blockedCaptureBody{started: make(chan struct{}), closed: make(chan struct{})} + capture := &deferredRequestBodyCapture{body: body, contentLength: -1} + done := make(chan string, 1) + go func() { + payload := make([]byte, 32) + n, _ := capture.Read(payload) + done <- string(payload[:n]) + }() + <-body.started + if errClose := capture.Close(); errClose != nil { + t.Fatal(errClose) + } + if got := <-done; got != "late bytes" { + t.Fatalf("reader got %q", got) + } + if payload, _, errRead := capture.Bytes(); errRead != nil || len(payload) != 0 || capture.hasRead() || capture.isComplete() { + t.Fatalf("late read changed the finalized capture: %q, %v", payload, errRead) + } +} diff --git a/internal/api/middleware/response_writer.go b/internal/api/middleware/response_writer.go index e28fe90baa9..9eebc0ed081 100644 --- a/internal/api/middleware/response_writer.go +++ b/internal/api/middleware/response_writer.go @@ -326,7 +326,7 @@ func (w *ResponseWriterWrapper) currentCapturedRequestBody() []byte { if len(w.requestInfo.Body) > 0 { return w.requestInfo.Body } - if w.requestInfo.deferredBodyCapture == nil || w.requestInfo.deferredBodyCapture.bytesRead == 0 { + if w.requestInfo.deferredBodyCapture == nil || !w.requestInfo.deferredBodyCapture.hasRead() { return nil } body, _, errRead := w.requestInfo.deferredBodyCapture.Bytes() From fba00ea40bcd2ab9c63bfabc89c7a8c970f5b614 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:41:24 -0800 Subject: [PATCH 09/19] fix(claude): preserve Fast response decoding error status --- internal/runtime/executor/helps/response_decode.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/runtime/executor/helps/response_decode.go b/internal/runtime/executor/helps/response_decode.go index 4cedc3ef934..1465164e313 100644 --- a/internal/runtime/executor/helps/response_decode.go +++ b/internal/runtime/executor/helps/response_decode.go @@ -23,7 +23,6 @@ type AcceptedResponseError struct{ Err error } func (e *AcceptedResponseError) Error() string { return e.Err.Error() } func (e *AcceptedResponseError) Unwrap() error { return e.Err } func (e *AcceptedResponseError) IsStreamTruncated() bool { return true } -func (e *AcceptedResponseError) StatusCode() int { return http.StatusBadGateway } type compositeReadCloser struct { io.Reader From 5589fc9f3ed66d3037dd165374a9738ffa20209e Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:40:06 +0000 Subject: [PATCH 10/19] fix(mistral): give Mistral models their real reasoning levels Configured OpenAI-compatible models without a thinking block all got low/medium/high. For Mistral that is wrong for most models: GLM-5.3 takes low/high/max and rejects medium, Magistral and Mistral Small take none/high, and Codestral, Ministral and Large 2512 reject reasoning_effort entirely. The hub then rewrote "none" to "low" (rejected upstream or silently run with reasoning on), passed "medium" through to a 400, and advertised the wrong levels in the OpenCode catalog. Models on a mistral.ai base URL now take their levels from a table probed against the API. Known models without reasoning get no thinking support, so the hub strips reasoning_effort for them. An explicit thinking block in the config still wins, and unknown models keep the old default. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 566ac95fd48718898ff98c6620bfae5dc1465390) --- internal/registry/mistral_thinking.go | 76 +++++++++++++++++++ internal/registry/mistral_thinking_test.go | 63 +++++++++++++++ .../runtime/executor/helps/mistral_request.go | 10 +-- internal/thinking/mistral_levels_test.go | 46 +++++++++++ .../auth/api_key_model_capabilities.go | 6 +- .../openai_compat_config_models_test.go | 40 ++++++++++ sdk/cliproxy/service_models.go | 2 +- 7 files changed, 231 insertions(+), 12 deletions(-) create mode 100644 internal/registry/mistral_thinking.go create mode 100644 internal/registry/mistral_thinking_test.go create mode 100644 internal/thinking/mistral_levels_test.go diff --git a/internal/registry/mistral_thinking.go b/internal/registry/mistral_thinking.go new file mode 100644 index 00000000000..6a4b37e24ab --- /dev/null +++ b/internal/registry/mistral_thinking.go @@ -0,0 +1,76 @@ +package registry + +import ( + "net/url" + "strings" +) + +// mistralThinkingRule maps a Mistral model name prefix to the reasoning_effort +// values Mistral's chat completions API accepts for it. A nil Levels means the +// model rejects reasoning_effort altogether ("reasoning_effort is not enabled +// for this model"). +type mistralThinkingRule struct { + prefix string + levels []string +} + +// mistralThinkingRules lists the reasoning levels Mistral reports for each model +// family, probed against the API on 2026-11-29. The first matching prefix wins, +// so more specific prefixes come first. +var mistralThinkingRules = []mistralThinkingRule{ + {prefix: "codestral"}, + {prefix: "ministral"}, + {prefix: "mistral-code"}, + {prefix: "mistral-large-2512"}, + {prefix: "mistral-large", levels: []string{"low", "medium", "high"}}, + {prefix: "magistral", levels: []string{"none", "high"}}, + {prefix: "mistral-small", levels: []string{"none", "high"}}, + {prefix: "mistral-medium", levels: []string{"none", "high"}}, + {prefix: "mistral-vibe-cli", levels: []string{"none", "high"}}, + {prefix: "zai-glm-5-2", levels: []string{"low", "medium", "high"}}, + {prefix: "glm-5-2", levels: []string{"low", "medium", "high"}}, + {prefix: "zai-glm", levels: []string{"low", "high", "max"}}, + {prefix: "deepseek-v4", levels: []string{"none", "low", "high", "xhigh", "max"}}, +} + +// MistralThinkingSupport returns the thinking capability Mistral's API has for +// modelName (any "/" is ignored). known is false for a model the table +// does not cover; support is nil for a known model without reasoning. +func MistralThinkingSupport(modelName string) (support *ThinkingSupport, known bool) { + name := lastPathSegment(strings.TrimSpace(modelName)) + if name == "" { + return nil, false + } + for _, rule := range mistralThinkingRules { + if !strings.HasPrefix(name, rule.prefix) { + continue + } + if rule.levels == nil { + return nil, true + } + return &ThinkingSupport{Levels: append([]string(nil), rule.levels...)}, true + } + return nil, false +} + +// IsMistralBaseURL reports whether baseURL points at Mistral's API. +func IsMistralBaseURL(baseURL string) bool { + parsed, err := url.Parse(strings.TrimSpace(baseURL)) + if err != nil { + return false + } + host := strings.ToLower(parsed.Hostname()) + return host == "mistral.ai" || strings.HasSuffix(host, ".mistral.ai") +} + +// OpenAICompatThinkingSupport returns the thinking capability of a configured +// OpenAI-compatible model that has no explicit thinking block: the real levels +// for a known Mistral model, else the generic low/medium/high default. +func OpenAICompatThinkingSupport(baseURL, modelName string) *ThinkingSupport { + if IsMistralBaseURL(baseURL) { + if support, known := MistralThinkingSupport(modelName); known { + return support + } + } + return &ThinkingSupport{Levels: []string{"low", "medium", "high"}} +} diff --git a/internal/registry/mistral_thinking_test.go b/internal/registry/mistral_thinking_test.go new file mode 100644 index 00000000000..aadc98ddba4 --- /dev/null +++ b/internal/registry/mistral_thinking_test.go @@ -0,0 +1,63 @@ +package registry + +import ( + "slices" + "testing" +) + +func TestMistralThinkingSupport(t *testing.T) { + tests := []struct { + model string + known bool + levels []string // nil: the model takes no reasoning_effort + }{ + {model: "zai-glm-5-3-flash", known: true, levels: []string{"low", "high", "max"}}, + {model: "vibe/zai-glm-5-3-flash", known: true, levels: []string{"low", "high", "max"}}, + {model: "zai-glm-latest", known: true, levels: []string{"low", "high", "max"}}, + {model: "zai-glm-5-2", known: true, levels: []string{"low", "medium", "high"}}, + {model: "glm-5-2", known: true, levels: []string{"low", "medium", "high"}}, + {model: "magistral-small-latest", known: true, levels: []string{"none", "high"}}, + {model: "mistral-small-2603", known: true, levels: []string{"none", "high"}}, + {model: "mistral-medium-3.5", known: true, levels: []string{"none", "high"}}, + {model: "mistral-vibe-cli-fast", known: true, levels: []string{"none", "high"}}, + {model: "mistral-large-4", known: true, levels: []string{"low", "medium", "high"}}, + {model: "mistral-large-latest", known: true, levels: []string{"low", "medium", "high"}}, + {model: "deepseek-v4-1-flash-1017", known: true, levels: []string{"none", "low", "high", "xhigh", "max"}}, + {model: "mistral-large-2512", known: true}, + {model: "codestral-2508", known: true}, + {model: "mistral-code-latest", known: true}, + {model: "ministral-8b-latest", known: true}, + {model: "voxtral-small-latest"}, + {model: ""}, + } + for _, tc := range tests { + support, known := MistralThinkingSupport(tc.model) + if known != tc.known { + t.Fatalf("%q: known = %v, want %v", tc.model, known, tc.known) + } + var got []string + if support != nil { + got = support.Levels + } + if !slices.Equal(got, tc.levels) { + t.Fatalf("%q: levels = %v, want %v", tc.model, got, tc.levels) + } + } +} + +func TestOpenAICompatThinkingSupport(t *testing.T) { + if got := OpenAICompatThinkingSupport("https://api.mistral.ai/v1", "zai-glm-5-3-flash"); got == nil || !slices.Equal(got.Levels, []string{"low", "high", "max"}) { + t.Fatalf("mistral GLM support = %+v, want low/high/max", got) + } + if got := OpenAICompatThinkingSupport("https://api.mistral.ai/v1", "codestral-2508"); got != nil { + t.Fatalf("mistral codestral support = %+v, want nil", got) + } + defaultLevels := []string{"low", "medium", "high"} + if got := OpenAICompatThinkingSupport("https://api.mistral.ai/v1", "voxtral-small-latest"); got == nil || !slices.Equal(got.Levels, defaultLevels) { + t.Fatalf("unknown mistral model support = %+v, want the default", got) + } + // The table only describes Mistral's API; other hosts keep the default. + if got := OpenAICompatThinkingSupport("https://example.com/v1", "zai-glm-5-3-flash"); got == nil || !slices.Equal(got.Levels, defaultLevels) { + t.Fatalf("non-mistral support = %+v, want the default", got) + } +} diff --git a/internal/runtime/executor/helps/mistral_request.go b/internal/runtime/executor/helps/mistral_request.go index 29da6a3d982..98dfceae649 100644 --- a/internal/runtime/executor/helps/mistral_request.go +++ b/internal/runtime/executor/helps/mistral_request.go @@ -2,10 +2,9 @@ package helps import ( "fmt" - "net/url" - "strings" "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/registry" ) // mistralEchoedReasoningKeys are the reasoning fields OpenAI-compatible @@ -23,12 +22,7 @@ var mistralEchoedReasoningKeys = []string{ // IsMistralBaseURL reports whether baseURL points at Mistral's API. func IsMistralBaseURL(baseURL string) bool { - parsed, err := url.Parse(strings.TrimSpace(baseURL)) - if err != nil { - return false - } - host := strings.ToLower(parsed.Hostname()) - return host == "mistral.ai" || strings.HasSuffix(host, ".mistral.ai") + return registry.IsMistralBaseURL(baseURL) } // StripMistralEchoedReasoningDoc removes echoed reasoning fields from every diff --git a/internal/thinking/mistral_levels_test.go b/internal/thinking/mistral_levels_test.go new file mode 100644 index 00000000000..0f149fcba0f --- /dev/null +++ b/internal/thinking/mistral_levels_test.go @@ -0,0 +1,46 @@ +package thinking_test + +import ( + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/modelconfig" + "github.com/rune-oai/t3code-proxy/internal/registry" + "github.com/rune-oai/t3code-proxy/internal/thinking" + _ "github.com/rune-oai/t3code-proxy/internal/thinking/provider/openai" +) + +// Mistral models carry their real reasoning levels, so "none" reaches a model +// that can turn reasoning off and the field is dropped for one that takes none. +func TestApplyThinkingMistralLevels(t *testing.T) { + tests := []struct { + model string + effort string + want string // "" means reasoning_effort is removed + }{ + {model: "magistral-small-latest", effort: "none", want: "none"}, + {model: "mistral-small-2603", effort: "high", want: "high"}, + {model: "zai-glm-5-3-flash", effort: "max", want: "max"}, + {model: "zai-glm-5-3-flash", effort: "low", want: "low"}, + {model: "codestral-2508", effort: "high", want: ""}, + } + for _, tc := range tests { + support := registry.OpenAICompatThinkingSupport("https://api.mistral.ai/v1", tc.model) + info := modelconfig.ResolveModelInfo(tc.model, "openai-compatibility", support) + body := []byte(`{"model":"` + tc.model + `","reasoning_effort":"` + tc.effort + `"}`) + out, err := thinking.ApplyThinkingWithModelInfo(body, body, tc.model, "openai", "openai", "mistral", info) + if err != nil { + t.Fatalf("%s/%s: error = %v", tc.model, tc.effort, err) + } + got := ojson.GetBytes(out, "reasoning_effort") + if tc.want == "" { + if got.Exists() { + t.Fatalf("%s/%s: reasoning_effort = %q, want it removed; body=%s", tc.model, tc.effort, got.String(), out) + } + continue + } + if got.String() != tc.want { + t.Fatalf("%s/%s: reasoning_effort = %q, want %q; body=%s", tc.model, tc.effort, got.String(), tc.want, out) + } + } +} diff --git a/sdk/cliproxy/auth/api_key_model_capabilities.go b/sdk/cliproxy/auth/api_key_model_capabilities.go index 59806d54bb1..8bb44f4405f 100644 --- a/sdk/cliproxy/auth/api_key_model_capabilities.go +++ b/sdk/cliproxy/auth/api_key_model_capabilities.go @@ -413,7 +413,7 @@ func compileAPIKeyModelCapabilitiesForAuth(cfg *internalconfig.Config, auth *Aut compatName = strings.TrimSpace(auth.Attributes["compat_name"]) } if entry := resolveOpenAICompatConfigForAuth(cfg, auth, providerKey, compatName); entry != nil { - compileOpenAICompatibleModelCapabilities(out, entry.Models) + compileOpenAICompatibleModelCapabilities(out, entry.BaseURL, entry.Models) } } if len(out) == 0 { @@ -436,11 +436,11 @@ func compileConfiguredModelCapabilities[T interface { } } -func compileOpenAICompatibleModelCapabilities(out map[string][]apiKeyModelCapabilityRoute, models []internalconfig.OpenAICompatibilityModel) { +func compileOpenAICompatibleModelCapabilities(out map[string][]apiKeyModelCapabilityRoute, baseURL string, models []internalconfig.OpenAICompatibilityModel) { for i := range models { support := models[i].Thinking if support == nil && !models[i].Image { - support = ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}} + support = registry.OpenAICompatThinkingSupport(baseURL, models[i].Name) } addConfiguredModelCapability(out, models[i].Name, models[i].Alias, "openai-compatibility", support, models[i].IsCompat) } diff --git a/sdk/cliproxy/openai_compat_config_models_test.go b/sdk/cliproxy/openai_compat_config_models_test.go index fe1303f1f2b..923b315e589 100644 --- a/sdk/cliproxy/openai_compat_config_models_test.go +++ b/sdk/cliproxy/openai_compat_config_models_test.go @@ -76,3 +76,43 @@ func joinModalities(modalities []string) string { } return out } + +func TestBuildOpenAICompatibilityConfigModels_MistralThinkingLevels(t *testing.T) { + compat := &config.OpenAICompatibility{ + Name: "mistral-vibe", + Prefix: "vibe", + BaseURL: "https://api.mistral.ai/v1", + Models: []config.OpenAICompatibilityModel{ + {Name: "zai-glm-5-3-flash", Alias: "zai-glm-5-3-flash"}, + {Name: "magistral-small-latest", Alias: "magistral-small-latest"}, + {Name: "codestral-2508", Alias: "codestral-2508"}, + {Name: "mistral-medium-3-5", Alias: "mistral-medium-3-5", Thinking: ®istry.ThinkingSupport{Levels: []string{"high"}}}, + }, + } + want := map[string]string{ + "zai-glm-5-3-flash": "low,high,max", + "magistral-small-latest": "none,high", + "codestral-2508": "", + "mistral-medium-3-5": "high", // an explicit thinking block wins + } + for _, model := range buildOpenAICompatibilityConfigModels(compat) { + expected, ok := want[model.ID] + if !ok { + t.Fatalf("unexpected model %q", model.ID) + } + got := "" + if model.Thinking != nil { + got = joinModalities(model.Thinking.Levels) + } + if got != expected { + t.Fatalf("%s levels = %q, want %q", model.ID, got, expected) + } + if model.ID == "magistral-small-latest" && !model.Thinking.ZeroAllowed { + t.Fatalf("magistral-small-latest must allow turning reasoning off") + } + delete(want, model.ID) + } + if len(want) != 0 { + t.Fatalf("missing models: %v", want) + } +} diff --git a/sdk/cliproxy/service_models.go b/sdk/cliproxy/service_models.go index 2f5259e3be4..a3635416cb3 100644 --- a/sdk/cliproxy/service_models.go +++ b/sdk/cliproxy/service_models.go @@ -812,7 +812,7 @@ func buildOpenAICompatibilityConfigModels(compat *config.OpenAICompatibility) [] } thinkingSupport := model.Thinking if thinkingSupport == nil && !model.Image { - thinkingSupport = ®istry.ThinkingSupport{Levels: []string{"low", "medium", "high"}} + thinkingSupport = registry.OpenAICompatThinkingSupport(compat.BaseURL, model.Name) } if model.Thinking != nil { info.ExplicitThinking = true From dfbb8b993b9751582765210564510338c505dfd1 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:07:51 -0800 Subject: [PATCH 11/19] feat(auth): let auth files opt proxied transports into connection pooling A file-backed OAuth credential with a proxy_url built a fresh transport on every request, so each request paid a new TCP, SOCKS and TLS handshake to the proxy. Only credentials defined in config could carry the connection-pool block that enables reuse. Auth files now accept the same block as proxy_connection_pool (true, false, or an object with enabled, idle-conn-timeout and max-idle-conns-per-host). Both file loaders, the plugin auth path and PATCH auth-files/fields apply it. Co-Authored-By: Claude Opus 5.5 --- .../handlers/management/auth_files_fields.go | 4 ++ .../auth_files_patch_fields_test.go | 49 +++++++++++++ internal/pluginhost/auth_callbacks.go | 2 + .../helps/proxy_pool_override_test.go | 28 ++++++++ internal/watcher/synthesizer/file.go | 2 + internal/watcher/synthesizer/file_test.go | 33 +++++++++ sdk/auth/filestore.go | 2 + sdk/auth/filestore_proxy_test.go | 34 +++++++++ sdk/cliproxy/auth/proxy_pool_metadata.go | 69 +++++++++++++++++++ sdk/cliproxy/auth/proxy_pool_metadata_test.go | 66 ++++++++++++++++++ 10 files changed, 289 insertions(+) create mode 100644 sdk/cliproxy/auth/proxy_pool_metadata.go create mode 100644 sdk/cliproxy/auth/proxy_pool_metadata_test.go diff --git a/internal/api/handlers/management/auth_files_fields.go b/internal/api/handlers/management/auth_files_fields.go index 1627b145cf1..00e6940d77e 100644 --- a/internal/api/handlers/management/auth_files_fields.go +++ b/internal/api/handlers/management/auth_files_fields.go @@ -662,6 +662,10 @@ func syncAuthFileMetadataFields(auth *coreauth.Auth, touchedRoots map[string]str auth.ProxyURL = strings.TrimSpace(proxyURL) } } + if _, ok := touchedRoots[coreauth.ProxyConnectionPoolMetadataKey]; ok { + auth.ProxyConnectionPool = nil + coreauth.ApplyProxyConnectionPoolMetadata(auth, auth.Metadata) + } if _, ok := touchedRoots["headers"]; ok { syncAuthFileHeaderAttributes(auth) } diff --git a/internal/api/handlers/management/auth_files_patch_fields_test.go b/internal/api/handlers/management/auth_files_patch_fields_test.go index 5978a002225..007b4746e19 100644 --- a/internal/api/handlers/management/auth_files_patch_fields_test.go +++ b/internal/api/handlers/management/auth_files_patch_fields_test.go @@ -1512,3 +1512,52 @@ func mustGetAuthByID(t *testing.T, manager *coreauth.Manager, id string) *coreau } return got } + +func TestPatchAuthFileFields_ProxyConnectionPool(t *testing.T) { + t.Setenv("MANAGEMENT_PASSWORD", "") + + store := &memoryAuthStore{} + manager := coreauth.NewManager(store, nil, nil) + record := &coreauth.Auth{ + ID: "xai.json", + FileName: "xai.json", + Provider: "xai", + Attributes: map[string]string{"path": "/tmp/xai.json"}, + Metadata: map[string]any{"type": "xai"}, + } + if _, errRegister := manager.Register(context.Background(), record); errRegister != nil { + t.Fatalf("failed to register auth record: %v", errRegister) + } + h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager) + + patch := func(body string) *coreauth.Auth { + t.Helper() + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + ctx.Request = req + h.PatchAuthFileFields(ctx) + if rec.Code != http.StatusOK { + t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String()) + } + updated, ok := manager.GetByID("xai.json") + if !ok || updated == nil { + t.Fatal("expected auth record to exist after patch") + } + return updated + } + + updated := patch(`{"name":"xai.json","proxy_url":"socks5://user:pass@127.0.0.1:1080","proxy_connection_pool":{"max-idle-conns-per-host":4}}`) + if updated.ProxyConnectionPool == nil || updated.ProxyConnectionPool.MaxIdleConnsPerHost == nil || *updated.ProxyConnectionPool.MaxIdleConnsPerHost != 4 { + t.Fatalf("ProxyConnectionPool = %+v, want max-idle-conns-per-host 4", updated.ProxyConnectionPool) + } + + updated = patch(`{"name":"xai.json","proxy_connection_pool":null}`) + if updated.ProxyConnectionPool != nil { + t.Fatalf("ProxyConnectionPool = %+v, want nil after removing the field", updated.ProxyConnectionPool) + } + if updated.ProxyURL != "socks5://user:pass@127.0.0.1:1080" { + t.Fatalf("ProxyURL = %q, want it untouched", updated.ProxyURL) + } +} diff --git a/internal/pluginhost/auth_callbacks.go b/internal/pluginhost/auth_callbacks.go index d90325c152b..8a74c3c0ccb 100644 --- a/internal/pluginhost/auth_callbacks.go +++ b/internal/pluginhost/auth_callbacks.go @@ -496,6 +496,7 @@ func (h *Host) buildAuthsFromFileData(ctx context.Context, path string, data []b } } coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) if existing := h.findExistingAuthForSave(auth.ID, path, len(out) == 1); existing != nil { preserveExistingAuthState(auth, existing) } @@ -545,6 +546,7 @@ func (h *Host) buildAuthsFromFileData(ctx context.Context, path string, data []b } coreauth.ApplyAuthPriorityMetadata(auth, metadata) coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) return []*coreauth.Auth{auth}, nil } diff --git a/internal/runtime/executor/helps/proxy_pool_override_test.go b/internal/runtime/executor/helps/proxy_pool_override_test.go index e4e717b8b67..01bd2a0ccc1 100644 --- a/internal/runtime/executor/helps/proxy_pool_override_test.go +++ b/internal/runtime/executor/helps/proxy_pool_override_test.go @@ -143,3 +143,31 @@ func TestProxyPoolCredentialOptInWithoutProxyURL(t *testing.T) { } } } + +// TestProxyPoolFileCredentialMetadataOptIn pins the auth-file opt-in: an OAuth +// credential whose file carries proxy_connection_pool reuses one SOCKS5 transport +// instead of dialing the proxy again for every request. +func TestProxyPoolFileCredentialMetadataOptIn(t *testing.T) { + ResetProxyTransports() + t.Cleanup(ResetProxyTransports) + + const proxyURL = "socks5://user:pass@127.0.0.1:1080" + metadata := map[string]any{"proxy_url": proxyURL, cliproxyauth.ProxyConnectionPoolMetadataKey: true} + auth := &cliproxyauth.Auth{ID: "xai.json", Provider: "xai", ProxyURL: proxyURL, Metadata: metadata} + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) + + first := NewProxyAwareHTTPClient(context.Background(), testConfig(), auth, 0) + second := NewProxyAwareHTTPClient(context.Background(), testConfig(), auth, 0) + firstTransport, ok := first.Transport.(*http.Transport) + if !ok || firstTransport == nil { + t.Fatalf("first transport = %T, want *http.Transport", first.Transport) + } + if second.Transport != first.Transport { + t.Fatal("opted-in file credential did not reuse its proxied transport") + } + + plain := &cliproxyauth.Auth{ID: "xai-plain.json", Provider: "xai", ProxyURL: proxyURL} + if NewProxyAwareHTTPClient(context.Background(), testConfig(), plain, 0).Transport == NewProxyAwareHTTPClient(context.Background(), testConfig(), plain, 0).Transport { + t.Fatal("file credential without the field must keep a per-request transport") + } +} diff --git a/internal/watcher/synthesizer/file.go b/internal/watcher/synthesizer/file.go index 410a57d0942..ff05372c07e 100644 --- a/internal/watcher/synthesizer/file.go +++ b/internal/watcher/synthesizer/file.go @@ -203,6 +203,7 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([ applyVertexOpenAPISettingsAttribute(auth, metadata) ApplyAuthExcludedModelsMeta(auth, perAccountExcluded, "oauth") coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) applyFingerprintProfileAttribute(auth, metadata) auth.BindFileSnapshot(fullPath, data) } @@ -281,6 +282,7 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([ } } coreauth.ApplyCustomHeadersFromMetadata(a) + coreauth.ApplyProxyConnectionPoolMetadata(a, metadata) coreauth.SetOAuthModelAliasesAttribute(a, perAccountModelAliases) applyOpenAPIModelsAttribute(a, metadata) applyVertexOpenAPISettingsAttribute(a, metadata) diff --git a/internal/watcher/synthesizer/file_test.go b/internal/watcher/synthesizer/file_test.go index e9f87a1efdd..1a9cca79091 100644 --- a/internal/watcher/synthesizer/file_test.go +++ b/internal/watcher/synthesizer/file_test.go @@ -1244,3 +1244,36 @@ func TestFileSynthesizerRecordsIncompleteFiles(t *testing.T) { } }) } + +func TestFileSynthesizer_Synthesize_ProxyConnectionPool(t *testing.T) { + tempDir := t.TempDir() + authData := map[string]any{ + "type": "xai", + "email": "test@example.com", + "proxy_url": "socks5://user:pass@127.0.0.1:1080", + "proxy_connection_pool": true, + } + data, _ := json.Marshal(authData) + if err := os.WriteFile(filepath.Join(tempDir, "xai-auth.json"), data, 0o600); err != nil { + t.Fatalf("failed to write auth file: %v", err) + } + + synth := NewFileSynthesizer() + ctx := &SynthesisContext{ + Config: &config.Config{}, + AuthDir: tempDir, + Now: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC), + IDGenerator: NewStableIDGenerator(), + } + auths, err := synth.Synthesize(ctx) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(auths) != 1 { + t.Fatalf("expected 1 auth, got %d", len(auths)) + } + pool := auths[0].ProxyConnectionPool + if pool == nil || pool.Enabled == nil || !*pool.Enabled { + t.Fatalf("ProxyConnectionPool = %+v, want enabled", pool) + } +} diff --git a/sdk/auth/filestore.go b/sdk/auth/filestore.go index 7dcf8f731d8..5984a9b435e 100644 --- a/sdk/auth/filestore.go +++ b/sdk/auth/filestore.go @@ -311,6 +311,7 @@ func (s *FileTokenStore) readAuthFiles(path, baseDir string) ([]*cliproxyauth.Au } } cliproxyauth.ApplyCustomHeadersFromMetadata(auth) + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) } return auths, nil } @@ -364,6 +365,7 @@ func (s *FileTokenStore) readAuthFiles(path, baseDir string) ([]*cliproxyauth.Au auth.Attributes["email"] = email } cliproxyauth.ApplyCustomHeadersFromMetadata(auth) + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) return []*cliproxyauth.Auth{auth}, nil } diff --git a/sdk/auth/filestore_proxy_test.go b/sdk/auth/filestore_proxy_test.go index 03c13c1cea9..96ef2ef9736 100644 --- a/sdk/auth/filestore_proxy_test.go +++ b/sdk/auth/filestore_proxy_test.go @@ -92,3 +92,37 @@ func TestFileTokenStoreList_DoesNotBlockColdStartWithUnproxiedNetworkRequest(t * t.Fatalf("List took %v, expected < 2s (should not perform blocking network calls during file load)", elapsed) } } + +// TestFileTokenStoreList_LoadsProxyConnectionPool verifies that an auth file can opt +// its proxied transport into connection pooling, which config-only credentials could +// do before. +func TestFileTokenStoreList_LoadsProxyConnectionPool(t *testing.T) { + dir := t.TempDir() + store := NewFileTokenStore() + store.SetBaseDir(dir) + + content := []byte(`{ + "type": "xai", + "proxy_url": "socks5://user:pass@127.0.0.1:1080", + "proxy_connection_pool": {"idle-conn-timeout": "120s"}, + "access_token": "test-token" + }`) + if err := os.WriteFile(filepath.Join(dir, "xai.json"), content, 0o600); err != nil { + t.Fatalf("failed to write test file: %v", err) + } + + auths, err := store.List(context.Background()) + if err != nil { + t.Fatalf("List error: %v", err) + } + if len(auths) != 1 { + t.Fatalf("got %d auths, want 1", len(auths)) + } + pool := auths[0].ProxyConnectionPool + if pool == nil { + t.Fatal("ProxyConnectionPool = nil, want the file's block") + } + if pool.IdleConnTimeout != "120s" { + t.Fatalf("IdleConnTimeout = %q, want 120s", pool.IdleConnTimeout) + } +} diff --git a/sdk/cliproxy/auth/proxy_pool_metadata.go b/sdk/cliproxy/auth/proxy_pool_metadata.go new file mode 100644 index 00000000000..5d69bcd76ec --- /dev/null +++ b/sdk/cliproxy/auth/proxy_pool_metadata.go @@ -0,0 +1,69 @@ +package auth + +import ( + "encoding/json" + "strings" +) + +// ProxyConnectionPoolMetadataKey is the auth-file field that opts a file-backed +// credential into a pooled upstream transport, mirroring the per-api-key +// `connection-pool` config block. Without it, a credential with a proxy_url gets a +// fresh transport, and so a fresh proxied TCP and TLS handshake, on every request. +const ProxyConnectionPoolMetadataKey = "proxy_connection_pool" + +// ApplyProxyConnectionPoolMetadata sets auth.ProxyConnectionPool from the +// credential metadata. The value is either a boolean (true asks for the pool +// defaults, false keeps the historical per-request transport) or an object with +// the config block's fields: enabled, idle-conn-timeout and +// max-idle-conns-per-host. An absent field leaves the override untouched; an +// unrecognized value clears it. +func ApplyProxyConnectionPoolMetadata(auth *Auth, metadata map[string]any) { + if auth == nil { + return + } + raw, ok := metadata[ProxyConnectionPoolMetadataKey] + if !ok { + return + } + auth.ProxyConnectionPool = proxyConnectionPoolFromMetadata(raw) +} + +func proxyConnectionPoolFromMetadata(raw any) *ProxyConnectionPoolOverride { + switch value := raw.(type) { + case bool: + return &ProxyConnectionPoolOverride{Enabled: &value} + case map[string]any: + // An empty object is still the opt-in, matching `connection-pool: {}`. + out := &ProxyConnectionPoolOverride{} + if enabled, ok := value["enabled"].(bool); ok { + out.Enabled = &enabled + } + if idle, ok := value["idle-conn-timeout"].(string); ok { + out.IdleConnTimeout = strings.TrimSpace(idle) + } + if maxIdle, ok := metadataInt(value["max-idle-conns-per-host"]); ok { + out.MaxIdleConnsPerHost = &maxIdle + } + return out + default: + return nil + } +} + +// metadataInt reads an integer from file-decoded (float64) or management-decoded +// (json.Number) metadata. +func metadataInt(raw any) (int, bool) { + switch value := raw.(type) { + case float64: + return int(value), true + case int: + return value, true + case int64: + return int(value), true + case json.Number: + n, err := value.Int64() + return int(n), err == nil + default: + return 0, false + } +} diff --git a/sdk/cliproxy/auth/proxy_pool_metadata_test.go b/sdk/cliproxy/auth/proxy_pool_metadata_test.go new file mode 100644 index 00000000000..eb4347881ed --- /dev/null +++ b/sdk/cliproxy/auth/proxy_pool_metadata_test.go @@ -0,0 +1,66 @@ +package auth + +import ( + "encoding/json" + "testing" +) + +func TestApplyProxyConnectionPoolMetadata(t *testing.T) { + existing := func() *ProxyConnectionPoolOverride { + enabled := true + return &ProxyConnectionPoolOverride{Enabled: &enabled, IdleConnTimeout: "9s"} + } + tests := []struct { + name string + raw string + wantNil bool + wantEnabled *bool + wantIdle string + wantMax *int + }{ + {name: "absent keeps existing", raw: `{}`, wantEnabled: boolValue(true), wantIdle: "9s"}, + {name: "true asks for defaults", raw: `{"proxy_connection_pool": true}`, wantEnabled: boolValue(true)}, + {name: "false opts out", raw: `{"proxy_connection_pool": false}`, wantEnabled: boolValue(false)}, + {name: "empty object is the opt-in", raw: `{"proxy_connection_pool": {}}`}, + {name: "object fields", raw: `{"proxy_connection_pool": {"enabled": true, "idle-conn-timeout": " 120s ", "max-idle-conns-per-host": 4}}`, wantEnabled: boolValue(true), wantIdle: "120s", wantMax: intValue(4)}, + {name: "unrecognized value clears", raw: `{"proxy_connection_pool": "yes"}`, wantNil: true}, + {name: "null clears", raw: `{"proxy_connection_pool": null}`, wantNil: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var metadata map[string]any + if err := json.Unmarshal([]byte(tt.raw), &metadata); err != nil { + t.Fatalf("unmarshal: %v", err) + } + auth := &Auth{ProxyConnectionPool: existing()} + ApplyProxyConnectionPoolMetadata(auth, metadata) + got := auth.ProxyConnectionPool + if tt.wantNil { + if got != nil { + t.Fatalf("ProxyConnectionPool = %+v, want nil", got) + } + return + } + if got == nil { + t.Fatal("ProxyConnectionPool = nil, want an override") + } + if (got.Enabled == nil) != (tt.wantEnabled == nil) || (got.Enabled != nil && *got.Enabled != *tt.wantEnabled) { + t.Fatalf("Enabled = %v, want %v", got.Enabled, tt.wantEnabled) + } + if got.IdleConnTimeout != tt.wantIdle { + t.Fatalf("IdleConnTimeout = %q, want %q", got.IdleConnTimeout, tt.wantIdle) + } + if (got.MaxIdleConnsPerHost == nil) != (tt.wantMax == nil) || (got.MaxIdleConnsPerHost != nil && *got.MaxIdleConnsPerHost != *tt.wantMax) { + t.Fatalf("MaxIdleConnsPerHost = %v, want %v", got.MaxIdleConnsPerHost, tt.wantMax) + } + }) + } +} + +func TestApplyProxyConnectionPoolMetadataNilAuth(t *testing.T) { + ApplyProxyConnectionPoolMetadata(nil, map[string]any{ProxyConnectionPoolMetadataKey: true}) +} + +func boolValue(v bool) *bool { return &v } + +func intValue(v int) *int { return &v } From 4cec7ddb0ab9d246ba6e0b44c024699ad4a28aaa Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:10:55 +0000 Subject: [PATCH 12/19] fix(auth): answer 404 when every account rejects the model Anthropic answers not_found_error "model: " for a model the subscription cannot use. The hub suspends that model on the account for 12 hours, so the first request returned the upstream 404 and every later one returned 503 auth_unavailable "no auth available". Claude Code shows that as a temporary server problem and keeps retrying (seen with claude-mythos-5-2, including during context compaction). When every enabled candidate is suspended for the model by a 404, the selector now returns a non-retryable 404 model_not_found that keeps the upstream error as its cause. If any candidate is blocked for another reason, the retryable error stays. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + sdk/cliproxy/auth/conductor_selection.go | 3 + sdk/cliproxy/auth/model_not_found_status.go | 39 +++++++ .../auth/model_not_found_status_test.go | 104 ++++++++++++++++++ sdk/cliproxy/auth/scheduler.go | 27 +++++ 5 files changed, 179 insertions(+) create mode 100644 sdk/cliproxy/auth/model_not_found_status.go create mode 100644 sdk/cliproxy/auth/model_not_found_status_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index b019b2180ad..fe845da8a24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,12 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- A model that every account's upstream rejects as unknown (Anthropic `not_found_error`, for + example `claude-mythos-5-2`) now keeps answering `404 model_not_found`. Before, only the first + request got the 404. Later requests got `503 auth_unavailable: no auth available`, which Claude + Code shows as a temporary server problem and retries, including during context compaction. + If only some accounts reject the model, the hub still answers with the retryable error. + - Multi-turn conversations with reasoning models on Mistral (GLM, DeepSeek, Magistral) no longer fail on their second turn with `422 extra_forbidden`. OpenAI-compatible clients such as OpenCode echo earlier reasoning back as `reasoning_content` and similar fields, and the hub adds diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index a2eb5a4474b..c3096d5ccbc 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -942,6 +942,9 @@ func (m *Manager) availableAuthsForRouteModelForRequest(ctx context.Context, aut HTTPStatus: http.StatusServiceUnavailable, }, terminalCause) } + if candidatesRejectedModel(auths, func(candidate *Auth) string { return m.selectionModelForAuth(candidate, routeModel) }) { + return nil, newModelRejectedError(routeModel, lastCandidateErr) + } return nil, newAuthUnavailableErrorWithCause(earliest, now, lastCandidateErr) } diff --git a/sdk/cliproxy/auth/model_not_found_status.go b/sdk/cliproxy/auth/model_not_found_status.go new file mode 100644 index 00000000000..a17671bb182 --- /dev/null +++ b/sdk/cliproxy/auth/model_not_found_status.go @@ -0,0 +1,39 @@ +package auth + +import ( + "fmt" + "net/http" + "strings" +) + +// candidatesRejectedModel reports whether every enabled candidate is blocked for +// the model because its upstream answered 404 for it (for Claude: +// not_found_error "model: "). MarkResult suspends such a model for 12 hours, +// so callers should get a 404 rather than a retryable 503 "no auth available". +func candidatesRejectedModel(auths []*Auth, modelFor func(*Auth) string) bool { + found := false + for _, candidate := range auths { + if candidate == nil || candidate.Disabled || candidate.Status == StatusDisabled { + continue + } + model := modelFor(candidate) + state := existingModelState(candidate, model) + if state == nil || !state.Unavailable || state.LastError == nil || state.LastError.HTTPStatus != http.StatusNotFound { + return false + } + found = true + } + return found +} + +// newModelRejectedError builds the non-retryable 404 returned once every +// candidate's upstream has rejected the model as unknown. +func newModelRejectedError(model string, cause error) error { + model = strings.TrimSpace(model) + return WithCause(&Error{ + Code: "model_not_found", + Message: fmt.Sprintf("model %s was not found on any configured account; its provider does not serve it to these credentials", model), + Retryable: false, + HTTPStatus: http.StatusNotFound, + }, cause) +} diff --git a/sdk/cliproxy/auth/model_not_found_status_test.go b/sdk/cliproxy/auth/model_not_found_status_test.go new file mode 100644 index 00000000000..3ce6c4f128e --- /dev/null +++ b/sdk/cliproxy/auth/model_not_found_status_test.go @@ -0,0 +1,104 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/registry" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +// A model every account's upstream rejects as unknown must keep answering 404 +// on later requests, not 503 "no auth available", which clients show as a +// temporary server problem and retry. +func TestManager_Execute_ModelNotFoundOnEveryAuthStays404(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "claude-missing-model-404" + notFound := func() error { + return &Error{ + HTTPStatus: http.StatusNotFound, + Message: `{"type":"error","error":{"type":"not_found_error","message":"model: ` + model + `"}}`, + } + } + executor := &authFallbackExecutor{ + id: "claude", + executeErrors: map[string]error{ + "mnf-auth-a": notFound(), + "mnf-auth-b": notFound(), + }, + } + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + reg := registry.GetGlobalRegistry() + for _, id := range []string{"mnf-auth-a", "mnf-auth-b"} { + auth := &Auth{ID: id, Provider: "claude"} + reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + if _, err := m.Register(context.Background(), auth); err != nil { + t.Fatalf("register %s: %v", id, err) + } + } + + for attempt := 1; attempt <= 3; attempt++ { + _, err := m.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if err == nil { + t.Fatalf("attempt %d: expected an error", attempt) + } + if got := statusCodeFromError(err); got != http.StatusNotFound { + t.Fatalf("attempt %d: status = %d (%v), want 404", attempt, got, err) + } + var authErr *Error + if errors.As(err, &authErr) && authErr.Retryable { + t.Fatalf("attempt %d: error is retryable: %v", attempt, err) + } + } +} + +// When only some accounts reject the model, the others may recover, so the +// error must stay a retryable unavailability rather than a 404. +func TestManager_Execute_ModelNotFoundOnSomeAuthsIsNot404(t *testing.T) { + previous := quotaCooldownDisabled.Load() + quotaCooldownDisabled.Store(false) + t.Cleanup(func() { quotaCooldownDisabled.Store(previous) }) + + model := "claude-partly-missing-model-404" + executor := &authFallbackExecutor{ + id: "claude", + executeErrors: map[string]error{ + "pmnf-auth-a": &Error{ + HTTPStatus: http.StatusNotFound, + Message: `{"type":"error","error":{"type":"not_found_error","message":"model: ` + model + `"}}`, + }, + "pmnf-auth-b": &Error{ + HTTPStatus: http.StatusServiceUnavailable, + Message: `{"type":"error","error":{"type":"api_error","message":"upstream unavailable"}}`, + }, + }, + } + m := NewManager(nil, nil, nil) + m.RegisterExecutor(executor) + reg := registry.GetGlobalRegistry() + for _, id := range []string{"pmnf-auth-a", "pmnf-auth-b"} { + auth := &Auth{ID: id, Provider: "claude"} + reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + if _, err := m.Register(context.Background(), auth); err != nil { + t.Fatalf("register %s: %v", id, err) + } + } + + for attempt := 1; attempt <= 2; attempt++ { + _, err := m.Execute(context.Background(), []string{"claude"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{}) + if err == nil { + t.Fatalf("attempt %d: expected an error", attempt) + } + if attempt == 2 && statusCodeFromError(err) == http.StatusNotFound { + t.Fatalf("attempt %d: got 404 although one account did not reject the model: %v", attempt, err) + } + } +} diff --git a/sdk/cliproxy/auth/scheduler.go b/sdk/cliproxy/auth/scheduler.go index 9394c42b681..05808b9f84a 100644 --- a/sdk/cliproxy/auth/scheduler.go +++ b/sdk/cliproxy/auth/scheduler.go @@ -830,6 +830,15 @@ func (s *authScheduler) mixedUnavailableErrorLocked(providers []string, model st HTTPStatus: http.StatusServiceUnavailable, }, terminalCause) } + var candidates []*Auth + for _, providerKey := range providers { + if providerState := s.providers[providerKey]; providerState != nil { + candidates = append(candidates, providerState.ensureModelLocked(canonicalModelLookupKey(model), now).candidateAuthsLocked(predicate)...) + } + } + if candidatesRejectedModel(candidates, func(*Auth) string { return model }) { + return newModelRejectedError(model, lastCandidateErr) + } return newAuthUnavailableErrorWithCause(earliest, now, lastCandidateErr) } @@ -1582,9 +1591,27 @@ func (m *modelScheduler) unavailableErrorLocked(provider, model string, predicat HTTPStatus: http.StatusServiceUnavailable, }, terminalCause) } + if candidatesRejectedModel(m.candidateAuthsLocked(predicate), func(*Auth) string { return model }) { + return newModelRejectedError(model, lastCandidateErr) + } return newAuthUnavailableErrorWithCause(earliest, now, lastCandidateErr) } +// candidateAuthsLocked returns the auths of the shard entries that pass predicate. +func (m *modelScheduler) candidateAuthsLocked(predicate func(*scheduledAuth) bool) []*Auth { + if m == nil { + return nil + } + auths := make([]*Auth, 0, len(m.entries)) + for _, entry := range m.entries { + if entry == nil || entry.auth == nil || (predicate != nil && !predicate(entry)) { + continue + } + auths = append(auths, entry.auth) + } + return auths +} + func (m *modelScheduler) latestCandidateErrorWithTimeLocked(model string, predicate func(*scheduledAuth) bool) (error, time.Time, string) { modelErr, modelTime, modelAuthID, authErr, authTime, authAuthID := m.candidateErrorsLocked(model, predicate) if modelErr != nil { From 751fe62258ddd866745eed4fbc048a508bcfa129 Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:34:29 +0000 Subject: [PATCH 13/19] fix(quota): lift quota cooldowns when a usage poll shows allowance again A Codex usage_limit_reached rejection cools the account down until the reset time it carries. When OpenAI renewed both accounts early, the hub kept refusing every Codex model for up to four more days, because no request reaches a cooling account and the quota-history poll that read 0% used only fed routing order. When a Claude or Codex usage poll shows allowance in every window, the recorder now clears quota cooldowns recorded before that poll, the same local reset as POST /v0/management/reset-quota. Cooldowns that are not about quota, such as a model the account rejects, stay in place, and nothing is sent upstream. Co-Authored-By: Claude Opus 5.5 --- .../api/handlers/management/quota_history.go | 21 ++++ internal/quotahistory/recorder.go | 24 ++++ internal/quotahistory/recover_test.go | 69 +++++++++++ sdk/cliproxy/auth/conductor_cooldown.go | 89 ++++++++++++-- sdk/cliproxy/auth/quota_recover_usage_test.go | 112 ++++++++++++++++++ 5 files changed, 304 insertions(+), 11 deletions(-) create mode 100644 internal/quotahistory/recover_test.go create mode 100644 sdk/cliproxy/auth/quota_recover_usage_test.go diff --git a/internal/api/handlers/management/quota_history.go b/internal/api/handlers/management/quota_history.go index 849d22d59bd..f8c40a14810 100644 --- a/internal/api/handlers/management/quota_history.go +++ b/internal/api/handlers/management/quota_history.go @@ -43,6 +43,7 @@ func (h *Handler) quotaHistoryRecorder() *quotahistory.Recorder { PluginProviders: h.quotaHistoryPluginProviders, FetchPlugin: h.quotaHistoryPlugin, Label: authEmail, + RecoverQuota: h.quotaHistoryRecover, }) }) return h.quotaHistory.rec @@ -85,6 +86,26 @@ func (h *Handler) quotaHistoryAuths() []*coreauth.Auth { return manager.List() } +// quotaHistoryRecover clears a quota cooldown that a usage poll showed has +// renewed early. It only changes the hub's routing state. +func (h *Handler) quotaHistoryRecover(ctx context.Context, auth *coreauth.Auth, observedAt time.Time) { + h.mu.Lock() + manager := h.authManager + h.mu.Unlock() + if manager == nil || auth == nil { + return + } + // The poll's deadline may be nearly spent; persisting must still finish. + updated, models, errRecover := manager.RecoverQuotaFromUsage(context.WithoutCancel(ctx), auth.ID, observedAt) + if errRecover != nil { + log.WithError(errRecover).Warnf("quota-history: clear renewed quota cooldown for %s auth %s", auth.Provider, auth.Index) + return + } + if updated != nil { + log.Infof("quota-history: %s auth %s has allowance again; cleared its quota cooldown for %d models", auth.Provider, auth.Index, len(models)) + } +} + // quotaHistoryDo sends one request with the credential's token, using the same // token resolution and proxy selection as APICall. func (h *Handler) quotaHistoryDo(ctx context.Context, auth *coreauth.Auth, method, url string, header map[string]string) (int, []byte, error) { diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index c65d08e0d32..2be8b4ce03c 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -81,6 +81,9 @@ type Deps struct { FetchPlugin func(context.Context, *coreauth.Auth) ([]byte, error) // Label returns the display label of a credential (optional). Label func(*coreauth.Auth) string + // RecoverQuota clears the account's quota cooldown after a poll observed + // at the given time showed allowance left in every window (optional). + RecoverQuota func(context.Context, *coreauth.Auth, time.Time) } // Account describes one tracked credential. @@ -438,6 +441,9 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { return rec } r.publishWindows(auth, plan, windows, time.UnixMilli(rec.T)) + if r.deps.RecoverQuota != nil && showsAllowance(auth, windows) { + r.deps.RecoverQuota(ctx, auth, time.UnixMilli(rec.T)) + } return rec } @@ -464,6 +470,24 @@ func (r *Recorder) publishWindows(auth *coreauth.Auth, plan string, windows map[ } } +// showsAllowance reports whether a Claude or Codex reading has allowance left +// in every window. Their usage endpoints report the same allowance that the +// quota rejection enforced, so an early renewal shows up here first. +func showsAllowance(auth *coreauth.Auth, observations []coreauth.QuotaWindow) bool { + if provider := providerOf(auth); provider != "claude" && provider != "codex" { + return false + } + if len(observations) == 0 { + return false + } + for _, window := range observations { + if window.UsedPercent >= 100 { + return false + } + } + return true +} + // publishRouting hands routing the plan and 5-hour reading of one account, so // plan weights and the headroom guard use what the recorder already fetched. func (r *Recorder) publishRouting(auth *coreauth.Auth, plan string, windows map[string]Window, observedAt time.Time) { diff --git a/internal/quotahistory/recover_test.go b/internal/quotahistory/recover_test.go new file mode 100644 index 00000000000..9a15ba00d29 --- /dev/null +++ b/internal/quotahistory/recover_test.go @@ -0,0 +1,69 @@ +package quotahistory + +import ( + "context" + "net/http" + "testing" + "time" + + coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" +) + +// A Codex account rejected with usage_limit_reached cools down until the reset +// time from the rejection. When the provider renews the allowance early, the +// next usage poll must clear that cooldown; a poll that still reads a spent +// window must not. +func TestPollWithAllowanceClearsEarlyRenewedCodexCooldown(t *testing.T) { + coreauth.SetQuotaCooldownDisabled(false) + ctx := context.Background() + for _, tc := range []struct { + name string + usedPercent string + wantCleared bool + }{ + {name: "renewed early", usedPercent: "0", wantCleared: true}, + {name: "still spent", usedPercent: "100", wantCleared: false}, + } { + t.Run(tc.name, func(t *testing.T) { + auth := &coreauth.Auth{ID: "qh-recover-" + tc.usedPercent, Index: "qh-recover-" + tc.usedPercent, Provider: "codex", Status: coreauth.StatusActive, Metadata: map[string]any{"access_token": "a"}} + t.Cleanup(func() { coreauth.ForgetQuotaWindows(auth.ID) }) + manager := coreauth.NewManager(nil, nil, nil) + if _, errRegister := manager.Register(ctx, auth); errRegister != nil { + t.Fatal(errRegister) + } + retry := 39 * time.Hour + manager.MarkResult(ctx, coreauth.Result{AuthID: auth.ID, Provider: "codex", Model: "gpt-test", + Error: &coreauth.Error{HTTPStatus: http.StatusTooManyRequests, Code: "usage_limit_reached", Message: "The usage limit has been reached"}, + RetryAfter: &retry, CredentialScope: true}) + if blocked, _ := manager.GetByID(auth.ID); !blocked.ModelStates["gpt-test"].Quota.Exceeded { + t.Fatal("setup: want a quota cooldown") + } + + usage := `{"plan_type":"pro","rate_limit":{"primary_window":{"used_percent":` + tc.usedPercent + `,"limit_window_seconds":18000,"reset_after_seconds":3600},"secondary_window":{"used_percent":` + tc.usedPercent + `,"limit_window_seconds":604800,"reset_after_seconds":140000}}}` + request := func(_ context.Context, _ *coreauth.Auth, _, url string, _ map[string]string, _ []byte) (int, []byte, error) { + if url == CodexUsageURL { + return 200, []byte(usage), nil + } + return 404, nil, nil + } + recover := func(ctx context.Context, auth *coreauth.Auth, observedAt time.Time) { + if _, _, errRecover := manager.RecoverQuotaFromUsage(ctx, auth.ID, observedAt); errRecover != nil { + t.Errorf("RecoverQuotaFromUsage: %v", errRecover) + } + } + r := NewRecorder(Deps{DoRequest: request, RecoverQuota: recover, ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{auth} }}) + // The poll runs after the rejection. + r.now = func() time.Time { return time.Now().Add(time.Second) } + if rec := r.sample(ctx, auth); rec.Error != "" { + t.Fatalf("sample: %s", rec.Error) + } + + after, _ := manager.GetByID(auth.ID) + state := after.ModelStates["gpt-test"] + cleared := !state.Quota.Exceeded && !state.Unavailable && !after.Quota.Exceeded + if cleared != tc.wantCleared { + t.Fatalf("cooldown cleared = %v, want %v (model %+v, account quota %+v)", cleared, tc.wantCleared, state, after.Quota) + } + }) + } +} diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index ff5d9c17e3c..ac6f8af1fa8 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -1059,9 +1059,51 @@ func dedupeStrings(values []string) []string { // ResetQuota clears quota/cooldown state for an auth and resumes registry routing. func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []string, error) { + return m.resetQuota(ctx, authID, time.Time{}) +} + +// RecoverQuotaFromUsage clears an account's quota cooldown when a usage poll +// observed at observedAt shows allowance left in every window. Providers can +// renew a window before the reset time sent with the rejection, and no request +// reaches a cooling account to notice it. Only quota cooldowns recorded at or +// before observedAt are cleared; other model cooldowns stay. It returns nil +// when there was nothing to recover. +func (m *Manager) RecoverQuotaFromUsage(ctx context.Context, authID string, observedAt time.Time) (*Auth, []string, error) { + if observedAt.IsZero() { + return nil, nil, nil + } + return m.resetQuota(ctx, authID, observedAt) +} + +// isQuotaModelCooldown reports whether a model state carries a quota cooldown, +// its own or one propagated from the credential. +func isQuotaModelCooldown(state *ModelState) bool { + return state != nil && (state.Quota.Exceeded || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated) +} + +// quotaCooldownRecoverable reports whether auth has an active quota cooldown +// and none recorded after observedAt, which a usage poll at observedAt could not see. +func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { + active := auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now) + for _, state := range auth.ModelStates { + if !isQuotaModelCooldown(state) || !isModelStateActiveCooldown(state, now) { + continue + } + if state.UpdatedAt.After(observedAt) { + return false + } + active = true + } + return active +} + +// resetQuota clears quota cooldowns. A zero recoverObservedAt is a manual reset +// of every cooldown; otherwise it recovers quota cooldowns from a usage poll. +func (m *Manager) resetQuota(ctx context.Context, authID string, recoverObservedAt time.Time) (*Auth, []string, error) { if m == nil { return nil, nil, nil } + recovering := !recoverObservedAt.IsZero() authID = strings.TrimSpace(authID) if authID == "" { return nil, nil, fmt.Errorf("auth id is required") @@ -1081,11 +1123,18 @@ func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []strin m.mu.Unlock() return nil, nil, nil } - // A manual reset also drops recorded "spent" readings, so routing does not - // keep avoiding the account until the next poll. - ForgetQuotaWindows(authID) - ForgetScopedWeeklyWindows(authID) - ForgetShortWindowUsage(authID) + if recovering && !quotaCooldownRecoverable(auth, recoverObservedAt, now) { + m.mu.Unlock() + return nil, nil, nil + } + if !recovering { + // A manual reset also drops recorded "spent" readings, so routing does not + // keep avoiding the account until the next poll. A recovery keeps the + // fresh reading that showed the allowance. + ForgetQuotaWindows(authID) + ForgetScopedWeeklyWindows(authID) + ForgetShortWindowUsage(authID) + } var cooldownRecordsBefore []CooldownStateRecord trackCooldownState := m.cooldownStore != nil @@ -1093,24 +1142,42 @@ func (m *Manager) ResetQuota(ctx context.Context, authID string) (*Auth, []strin cooldownRecordsBefore = m.cooldownStateRecordsForAuthLocked(auth, now) } + // A recovery keeps cooldowns that are not about quota, such as a model the + // account rejects. + kept := make(map[string]*ModelState) for modelKey, state := range auth.ModelStates { if strings.TrimSpace(modelKey) == "" { continue } + if recovering && state != nil { + if !isQuotaModelCooldown(state) && isModelStateActiveCooldown(state, now) { + kept[modelKey] = state.Clone() + continue + } + // A credential quota wrapped over the model's own failure: drop + // the quota layer and reinstate the failure beneath it. + if shadow := state.credentialQuotaShadow; shadow != nil && !shadow.Quota.Exceeded && isModelStateActiveCooldown(shadow, now) { + independent := shadow.cloneShallow() + independent.credentialQuotaShadow = nil + independent.credentialQuotaPropagated = false + kept[modelKey] = independent + continue + } + } models = append(models, modelKey) if state != nil { resetModelState(state, now) } } - if clearCooldownStateForAuth(auth, now) { - if len(models) == 0 { - models = append(models, registeredModels...) - } - } else if len(auth.ModelStates) > 0 { + cleared := clearCooldownStateForAuth(auth, now) + for modelKey, state := range kept { + auth.ModelStates[modelKey] = state + } + if (!cleared || len(kept) > 0) && len(auth.ModelStates) > 0 { updateAggregatedAvailability(auth, now) } - if len(models) == 0 { + if len(models) == 0 && len(kept) == 0 { models = append(models, registeredModels...) } models = dedupeStrings(models) diff --git a/sdk/cliproxy/auth/quota_recover_usage_test.go b/sdk/cliproxy/auth/quota_recover_usage_test.go new file mode 100644 index 00000000000..ede1600171c --- /dev/null +++ b/sdk/cliproxy/auth/quota_recover_usage_test.go @@ -0,0 +1,112 @@ +package auth + +import ( + "context" + "net/http" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/registry" +) + +// A Codex account that hit usage_limit_reached stays in cooldown until the +// reset time from the rejection. When the provider renews the allowance early, +// a usage poll showing headroom must clear that cooldown, also after a restart. +func TestRecoverQuotaFromUsageClearsEarlyRenewedCodexCooldown(t *testing.T) { + withQuotaCooldownEnabled(t) + ctx := context.Background() + dir := t.TempDir() + m := NewManager(nil, nil, nil) + m.SetCooldownStateStore(NewFileCooldownStateStore(dir)) + r := registry.GetGlobalRegistry() + authID := "recover-usage-codex" + models := []*registry.ModelInfo{{ID: "recover-astra"}, {ID: "recover-luna"}, {ID: "recover-rejected"}} + if _, err := m.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusActive}); err != nil { + t.Fatal(err) + } + r.RegisterClient(authID, "codex", models) + t.Cleanup(func() { r.UnregisterClient(authID) }) + for _, model := range models { + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: model.ID, Success: true}) + } + // The account does not serve this model; that cooldown is not about quota. + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-rejected", + Error: &Error{HTTPStatus: http.StatusNotFound, Code: "model_not_found", Message: "model not found"}}) + rejectedAuth, _ := m.GetByID(authID) + rejectedBefore := rejectedAuth.ModelStates["recover-rejected"].Clone() + retry := 39 * time.Hour + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-astra", + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Code: "usage_limit_reached", Message: "The usage limit has been reached"}, + RetryAfter: &retry, CredentialScope: true}) + + before, _ := m.GetByID(authID) + for _, id := range []string{"recover-astra", "recover-luna"} { + if state := before.ModelStates[id]; state == nil || !state.Quota.Exceeded || !isModelStateActiveCooldown(state, time.Now()) { + t.Fatalf("model %s: want active quota cooldown before recovery, got %+v", id, state) + } + } + if !rejectedBefore.Unavailable { + t.Fatalf("rejected model: want an active cooldown before recovery, got %+v", rejectedBefore) + } + + // A poll that started before the cooldown cannot have seen the rejection. + if updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, time.Now().Add(-time.Hour)); err != nil || updated != nil { + t.Fatalf("stale poll: got updated=%v err=%v, want no recovery", updated != nil, err) + } + + updated, recovered, err := m.RecoverQuotaFromUsage(ctx, authID, time.Now().Add(time.Second)) + if err != nil || updated == nil { + t.Fatalf("RecoverQuotaFromUsage: updated=%v err=%v", updated != nil, err) + } + if len(recovered) != 2 { + t.Fatalf("recovered models = %v, want the two quota-cooled models", recovered) + } + check := func(label string, auth *Auth) { + t.Helper() + now := time.Now() + for _, id := range []string{"recover-astra", "recover-luna"} { + if state := auth.ModelStates[id]; state == nil || state.Quota.Exceeded || isModelStateActiveCooldown(state, now) { + t.Fatalf("%s: model %s still cooling down: %+v", label, id, state) + } + } + if auth.Quota.Exceeded || (auth.Unavailable && auth.NextRetryAfter.After(now.Add(time.Hour))) { + t.Fatalf("%s: account still blocked: unavailable=%v next=%v quota=%+v", label, auth.Unavailable, auth.NextRetryAfter, auth.Quota) + } + rejected := auth.ModelStates["recover-rejected"] + if rejected == nil || !rejected.Unavailable || !rejected.NextRetryAfter.Equal(rejectedBefore.NextRetryAfter) { + t.Fatalf("%s: rejected model cooldown changed: %+v, want %+v", label, rejected, rejectedBefore) + } + } + check("live", updated) + if count := r.GetModelCount("recover-astra"); count != 1 { + t.Fatalf("registry count for recover-astra = %d, want 1", count) + } + + // The persisted cooldown must not bring the block back after a restart. + restarted := NewManager(nil, nil, nil) + restarted.SetCooldownStateStore(NewFileCooldownStateStore(dir)) + if _, err := restarted.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusActive}); err != nil { + t.Fatal(err) + } + if err := restarted.RestoreCooldownStates(ctx); err != nil { + t.Fatal(err) + } + restored, _ := restarted.GetByID(authID) + for _, id := range []string{"recover-astra", "recover-luna"} { + if state := restored.ModelStates[id]; state != nil && isModelStateActiveCooldown(state, time.Now()) { + t.Fatalf("restart: model %s cooldown came back: %+v", id, state) + } + } +} + +func TestRecoverQuotaFromUsageIgnoresAccountWithoutQuotaCooldown(t *testing.T) { + ctx := context.Background() + m := NewManager(nil, nil, nil) + authID := "recover-usage-idle" + if _, err := m.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusActive}); err != nil { + t.Fatal(err) + } + if updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, time.Now()); err != nil || updated != nil { + t.Fatalf("got updated=%v err=%v, want no change", updated != nil, err) + } +} From a46eb66f35bca71bae2b5e15e9a57ad69e0b5bd1 Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:44:06 +0000 Subject: [PATCH 14/19] fix(quota): judge renewal from every reported window and skip non-quota blocks Co-Authored-By: Claude Opus 5.5 --- internal/quotahistory/recorder.go | 11 ++++++----- internal/quotahistory/recover_test.go | 17 +++++++++++------ sdk/cliproxy/auth/conductor_cooldown.go | 18 ++++++++++++------ sdk/cliproxy/auth/quota_recover_usage_test.go | 17 +++++++++++++++-- 4 files changed, 44 insertions(+), 19 deletions(-) diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index 2be8b4ce03c..3c35ddeb592 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -471,16 +471,17 @@ func (r *Recorder) publishWindows(auth *coreauth.Auth, plan string, windows map[ } // showsAllowance reports whether a Claude or Codex reading has allowance left -// in every window. Their usage endpoints report the same allowance that the -// quota rejection enforced, so an early renewal shows up here first. -func showsAllowance(auth *coreauth.Auth, observations []coreauth.QuotaWindow) bool { +// in every window it reported, including windows routing does not use. Their +// usage endpoints report the same allowance that the quota rejection +// enforced, so an early renewal shows up here first. +func showsAllowance(auth *coreauth.Auth, windows map[string]Window) bool { if provider := providerOf(auth); provider != "claude" && provider != "codex" { return false } - if len(observations) == 0 { + if len(windows) == 0 { return false } - for _, window := range observations { + for _, window := range windows { if window.UsedPercent >= 100 { return false } diff --git a/internal/quotahistory/recover_test.go b/internal/quotahistory/recover_test.go index 9a15ba00d29..30f6d236133 100644 --- a/internal/quotahistory/recover_test.go +++ b/internal/quotahistory/recover_test.go @@ -2,6 +2,7 @@ package quotahistory import ( "context" + "fmt" "net/http" "testing" "time" @@ -16,16 +17,21 @@ import ( func TestPollWithAllowanceClearsEarlyRenewedCodexCooldown(t *testing.T) { coreauth.SetQuotaCooldownDisabled(false) ctx := context.Background() + window := func(used string, seconds int) string { + return fmt.Sprintf(`{"used_percent":%s,"limit_window_seconds":%d,"reset_after_seconds":3600}`, used, seconds) + } for _, tc := range []struct { name string - usedPercent string + usage string wantCleared bool }{ - {name: "renewed early", usedPercent: "0", wantCleared: true}, - {name: "still spent", usedPercent: "100", wantCleared: false}, + {name: "renewed early", usage: `{"rate_limit":{"primary_window":` + window("0", 18000) + `,"secondary_window":` + window("0", 604800) + `}}`, wantCleared: true}, + {name: "still spent", usage: `{"rate_limit":{"primary_window":` + window("100", 18000) + `,"secondary_window":` + window("100", 604800) + `}}`, wantCleared: false}, + // A spent window stated only through limit_reached still blocks. + {name: "limit reached without percentage", usage: `{"rate_limit":{"limit_reached":true,"primary_window":{"limit_window_seconds":18000},"secondary_window":` + window("0", 604800) + `}}`, wantCleared: false}, } { t.Run(tc.name, func(t *testing.T) { - auth := &coreauth.Auth{ID: "qh-recover-" + tc.usedPercent, Index: "qh-recover-" + tc.usedPercent, Provider: "codex", Status: coreauth.StatusActive, Metadata: map[string]any{"access_token": "a"}} + auth := &coreauth.Auth{ID: "qh-recover-" + tc.name, Index: "qh-recover-" + tc.name, Provider: "codex", Status: coreauth.StatusActive, Metadata: map[string]any{"access_token": "a"}} t.Cleanup(func() { coreauth.ForgetQuotaWindows(auth.ID) }) manager := coreauth.NewManager(nil, nil, nil) if _, errRegister := manager.Register(ctx, auth); errRegister != nil { @@ -39,10 +45,9 @@ func TestPollWithAllowanceClearsEarlyRenewedCodexCooldown(t *testing.T) { t.Fatal("setup: want a quota cooldown") } - usage := `{"plan_type":"pro","rate_limit":{"primary_window":{"used_percent":` + tc.usedPercent + `,"limit_window_seconds":18000,"reset_after_seconds":3600},"secondary_window":{"used_percent":` + tc.usedPercent + `,"limit_window_seconds":604800,"reset_after_seconds":140000}}}` request := func(_ context.Context, _ *coreauth.Auth, _, url string, _ map[string]string, _ []byte) (int, []byte, error) { if url == CodexUsageURL { - return 200, []byte(usage), nil + return 200, []byte(tc.usage), nil } return 404, nil, nil } diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index ac6f8af1fa8..ecbbda13a6d 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -1075,16 +1075,22 @@ func (m *Manager) RecoverQuotaFromUsage(ctx context.Context, authID string, obse return m.resetQuota(ctx, authID, observedAt) } +// isQuotaReason reports whether a quota state records a usage quota, not +// another block such as a Cloudflare challenge. +func isQuotaReason(quota QuotaState) bool { + return quota.Exceeded && (quota.Reason == "quota" || quota.Reason == "credential_quota") +} + // isQuotaModelCooldown reports whether a model state carries a quota cooldown, // its own or one propagated from the credential. func isQuotaModelCooldown(state *ModelState) bool { - return state != nil && (state.Quota.Exceeded || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated) + return state != nil && (isQuotaReason(state.Quota) || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated) } // quotaCooldownRecoverable reports whether auth has an active quota cooldown // and none recorded after observedAt, which a usage poll at observedAt could not see. func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { - active := auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now) + active := isQuotaReason(auth.Quota) && auth.Quota.NextRecoverAt.After(now) for _, state := range auth.ModelStates { if !isQuotaModelCooldown(state) || !isModelStateActiveCooldown(state, now) { continue @@ -1142,21 +1148,21 @@ func (m *Manager) resetQuota(ctx context.Context, authID string, recoverObserved cooldownRecordsBefore = m.cooldownStateRecordsForAuthLocked(auth, now) } - // A recovery keeps cooldowns that are not about quota, such as a model the - // account rejects. + // A recovery leaves model states without a quota cooldown as they are, + // including other cooldowns such as a model the account rejects. kept := make(map[string]*ModelState) for modelKey, state := range auth.ModelStates { if strings.TrimSpace(modelKey) == "" { continue } if recovering && state != nil { - if !isQuotaModelCooldown(state) && isModelStateActiveCooldown(state, now) { + if !isQuotaModelCooldown(state) { kept[modelKey] = state.Clone() continue } // A credential quota wrapped over the model's own failure: drop // the quota layer and reinstate the failure beneath it. - if shadow := state.credentialQuotaShadow; shadow != nil && !shadow.Quota.Exceeded && isModelStateActiveCooldown(shadow, now) { + if shadow := state.credentialQuotaShadow; shadow != nil && !isQuotaReason(shadow.Quota) && isModelStateActiveCooldown(shadow, now) { independent := shadow.cloneShallow() independent.credentialQuotaShadow = nil independent.credentialQuotaPropagated = false diff --git a/sdk/cliproxy/auth/quota_recover_usage_test.go b/sdk/cliproxy/auth/quota_recover_usage_test.go index ede1600171c..486606f9b88 100644 --- a/sdk/cliproxy/auth/quota_recover_usage_test.go +++ b/sdk/cliproxy/auth/quota_recover_usage_test.go @@ -20,7 +20,7 @@ func TestRecoverQuotaFromUsageClearsEarlyRenewedCodexCooldown(t *testing.T) { m.SetCooldownStateStore(NewFileCooldownStateStore(dir)) r := registry.GetGlobalRegistry() authID := "recover-usage-codex" - models := []*registry.ModelInfo{{ID: "recover-astra"}, {ID: "recover-luna"}, {ID: "recover-rejected"}} + models := []*registry.ModelInfo{{ID: "recover-astra"}, {ID: "recover-luna"}, {ID: "recover-rejected"}, {ID: "recover-challenged"}} if _, err := m.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusActive}); err != nil { t.Fatal(err) } @@ -32,8 +32,15 @@ func TestRecoverQuotaFromUsageClearsEarlyRenewedCodexCooldown(t *testing.T) { // The account does not serve this model; that cooldown is not about quota. m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-rejected", Error: &Error{HTTPStatus: http.StatusNotFound, Code: "model_not_found", Message: "model not found"}}) + // A Cloudflare challenge also sets Quota.Exceeded but is not a usage quota. + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-challenged", + Error: &Error{HTTPStatus: http.StatusForbidden, Message: "cloudflare challenge"}}) rejectedAuth, _ := m.GetByID(authID) rejectedBefore := rejectedAuth.ModelStates["recover-rejected"].Clone() + challengedBefore := rejectedAuth.ModelStates["recover-challenged"].Clone() + if !challengedBefore.Quota.Exceeded || challengedBefore.Quota.Reason != "cloudflare challenge" || !challengedBefore.Unavailable { + t.Fatalf("setup: want a Cloudflare challenge cooldown, got %+v", challengedBefore) + } retry := 39 * time.Hour m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-astra", Error: &Error{HTTPStatus: http.StatusTooManyRequests, Code: "usage_limit_reached", Message: "The usage limit has been reached"}, @@ -69,13 +76,19 @@ func TestRecoverQuotaFromUsageClearsEarlyRenewedCodexCooldown(t *testing.T) { t.Fatalf("%s: model %s still cooling down: %+v", label, id, state) } } - if auth.Quota.Exceeded || (auth.Unavailable && auth.NextRetryAfter.After(now.Add(time.Hour))) { + // The kept short Cloudflare cooldown may still aggregate onto the + // account; the 39-hour usage quota must not. + if (auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now.Add(time.Hour))) || (auth.Unavailable && auth.NextRetryAfter.After(now.Add(time.Hour))) { t.Fatalf("%s: account still blocked: unavailable=%v next=%v quota=%+v", label, auth.Unavailable, auth.NextRetryAfter, auth.Quota) } rejected := auth.ModelStates["recover-rejected"] if rejected == nil || !rejected.Unavailable || !rejected.NextRetryAfter.Equal(rejectedBefore.NextRetryAfter) { t.Fatalf("%s: rejected model cooldown changed: %+v, want %+v", label, rejected, rejectedBefore) } + challenged := auth.ModelStates["recover-challenged"] + if challenged == nil || !challenged.Unavailable || !challenged.NextRetryAfter.Equal(challengedBefore.NextRetryAfter) || challenged.Quota.Reason != "cloudflare challenge" { + t.Fatalf("%s: Cloudflare challenge cooldown changed: %+v, want %+v", label, challenged, challengedBefore) + } } check("live", updated) if count := r.GetModelCount("recover-astra"); count != 1 { From 8f43d1468edac480372524ea966e46522c86f589 Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:50:52 +0000 Subject: [PATCH 15/19] fix(quota): keep cooldowns a renewal poll cannot vouch for Codex limit_reached now blocks recovery even when the parsed windows have room, a lapsed quota left on a model's own live failure no longer hides it, and the account-level quota is only judged on its own when no model state carries it. Co-Authored-By: Claude Opus 5.5 --- internal/quotahistory/parse.go | 5 +++- internal/quotahistory/recorder.go | 2 +- internal/quotahistory/recover_test.go | 2 ++ sdk/cliproxy/auth/conductor_cooldown.go | 19 ++++++++++-- sdk/cliproxy/auth/quota_recover_usage_test.go | 30 +++++++++++++++++++ 5 files changed, 53 insertions(+), 5 deletions(-) diff --git a/internal/quotahistory/parse.go b/internal/quotahistory/parse.go index 0c2c5e19eaa..322bae98cd9 100644 --- a/internal/quotahistory/parse.go +++ b/internal/quotahistory/parse.go @@ -35,6 +35,9 @@ type Window struct { modelScope []string // estimated marks a used percent the payload did not state. estimated bool + // denied marks a reading whose payload said requests are refused, which + // can come from a limit the parsed windows do not show. + denied bool } var errEmptyPayload = errors.New("empty or invalid usage payload") @@ -221,7 +224,7 @@ func ParseCodexUsage(body []byte, now time.Time) (map[string]Window, string, err reset = &ms } } - windows[id] = Window{UsedPercent: used, ResetsAt: reset, PeriodHours: seconds / 3600, estimated: estimated} + windows[id] = Window{UsedPercent: used, ResetsAt: reset, PeriodHours: seconds / 3600, estimated: estimated, denied: limitReached} } return windows, plan, nil } diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index 3c35ddeb592..ec9c82b48c1 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -482,7 +482,7 @@ func showsAllowance(auth *coreauth.Auth, windows map[string]Window) bool { return false } for _, window := range windows { - if window.UsedPercent >= 100 { + if window.UsedPercent >= 100 || window.denied { return false } } diff --git a/internal/quotahistory/recover_test.go b/internal/quotahistory/recover_test.go index 30f6d236133..0a007c7239b 100644 --- a/internal/quotahistory/recover_test.go +++ b/internal/quotahistory/recover_test.go @@ -28,6 +28,8 @@ func TestPollWithAllowanceClearsEarlyRenewedCodexCooldown(t *testing.T) { {name: "renewed early", usage: `{"rate_limit":{"primary_window":` + window("0", 18000) + `,"secondary_window":` + window("0", 604800) + `}}`, wantCleared: true}, {name: "still spent", usage: `{"rate_limit":{"primary_window":` + window("100", 18000) + `,"secondary_window":` + window("100", 604800) + `}}`, wantCleared: false}, // A spent window stated only through limit_reached still blocks. + // limit_reached can come from a limit outside the parsed windows. + {name: "limit reached with room in parsed windows", usage: `{"rate_limit":{"limit_reached":true,"primary_window":` + window("0", 18000) + `,"secondary_window":` + window("0", 604800) + `}}`, wantCleared: false}, {name: "limit reached without percentage", usage: `{"rate_limit":{"limit_reached":true,"primary_window":{"limit_window_seconds":18000},"secondary_window":` + window("0", 604800) + `}}`, wantCleared: false}, } { t.Run(tc.name, func(t *testing.T) { diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index ecbbda13a6d..3af66759ae2 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -1081,6 +1081,12 @@ func isQuotaReason(quota QuotaState) bool { return quota.Exceeded && (quota.Reason == "quota" || quota.Reason == "credential_quota") } +// hasActiveQuota reports whether a usage quota is still in force; a lapsed one +// left in the fields does not explain a live cooldown. +func hasActiveQuota(quota QuotaState, now time.Time) bool { + return isQuotaReason(quota) && (quota.NextRecoverAt.IsZero() || quota.NextRecoverAt.After(now)) +} + // isQuotaModelCooldown reports whether a model state carries a quota cooldown, // its own or one propagated from the credential. func isQuotaModelCooldown(state *ModelState) bool { @@ -1090,7 +1096,11 @@ func isQuotaModelCooldown(state *ModelState) bool { // quotaCooldownRecoverable reports whether auth has an active quota cooldown // and none recorded after observedAt, which a usage poll at observedAt could not see. func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { - active := isQuotaReason(auth.Quota) && auth.Quota.NextRecoverAt.After(now) + if len(auth.ModelStates) == 0 { + return isQuotaReason(auth.Quota) && auth.Quota.NextRecoverAt.After(now) && !auth.UpdatedAt.After(observedAt) + } + // With model states, the account-level quota is aggregated from them. + active := false for _, state := range auth.ModelStates { if !isQuotaModelCooldown(state) || !isModelStateActiveCooldown(state, now) { continue @@ -1155,14 +1165,17 @@ func (m *Manager) resetQuota(ctx context.Context, authID string, recoverObserved if strings.TrimSpace(modelKey) == "" { continue } - if recovering && state != nil { + if recovering { + if state == nil { + continue + } if !isQuotaModelCooldown(state) { kept[modelKey] = state.Clone() continue } // A credential quota wrapped over the model's own failure: drop // the quota layer and reinstate the failure beneath it. - if shadow := state.credentialQuotaShadow; shadow != nil && !isQuotaReason(shadow.Quota) && isModelStateActiveCooldown(shadow, now) { + if shadow := state.credentialQuotaShadow; shadow != nil && !hasActiveQuota(shadow.Quota, now) && isModelStateActiveCooldown(shadow, now) { independent := shadow.cloneShallow() independent.credentialQuotaShadow = nil independent.credentialQuotaPropagated = false diff --git a/sdk/cliproxy/auth/quota_recover_usage_test.go b/sdk/cliproxy/auth/quota_recover_usage_test.go index 486606f9b88..c829d39a7a2 100644 --- a/sdk/cliproxy/auth/quota_recover_usage_test.go +++ b/sdk/cliproxy/auth/quota_recover_usage_test.go @@ -123,3 +123,33 @@ func TestRecoverQuotaFromUsageIgnoresAccountWithoutQuotaCooldown(t *testing.T) { t.Fatalf("got updated=%v err=%v, want no change", updated != nil, err) } } + +// A model's own live failure kept beneath a propagated credential quota is +// reinstated even when it still carries the fields of an earlier, lapsed 429. +func TestRecoverQuotaFromUsageKeepsLiveFailureUnderLapsedQuotaFields(t *testing.T) { + ctx := context.Background() + now := time.Now() + failureUntil := now.Add(12 * time.Hour) + quotaUntil := now.Add(39 * time.Hour) + credentialQuota := QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: quotaUntil} + m := NewManager(nil, nil, nil) + authID := "recover-usage-lapsed-shadow" + if _, err := m.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusError, Unavailable: true, NextRetryAfter: quotaUntil, Quota: credentialQuota, + ModelStates: map[string]*ModelState{"recover-rejected": { + Status: StatusError, Unavailable: true, NextRetryAfter: quotaUntil, Quota: credentialQuota, UpdatedAt: now.Add(-time.Minute), + credentialQuotaPropagated: true, + credentialQuotaShadow: &ModelState{Status: StatusError, Unavailable: true, NextRetryAfter: failureUntil, + LastError: &Error{HTTPStatus: http.StatusNotFound, Code: "model_not_found", Message: "model not found"}, + Quota: QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: now.Add(-time.Hour)}}, + }}}); err != nil { + t.Fatal(err) + } + updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, now) + if err != nil || updated == nil { + t.Fatalf("RecoverQuotaFromUsage: updated=%v err=%v", updated != nil, err) + } + state := updated.ModelStates["recover-rejected"] + if state == nil || !state.Unavailable || !state.NextRetryAfter.Equal(failureUntil) || state.LastError == nil { + t.Fatalf("live 404 cooldown not reinstated: %+v", state) + } +} From f1545a47b80c4eb5f06756a5f9a3b8ec2d325e83 Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:56:05 +0000 Subject: [PATCH 16/19] fix(quota): judge only live quota and account-only 429s against the poll time Co-Authored-By: Claude Opus 5.5 --- sdk/cliproxy/auth/conductor_cooldown.go | 24 ++++++++++++------- sdk/cliproxy/auth/quota_recover_usage_test.go | 10 +++++++- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index 3af66759ae2..931480eaf2d 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -1089,20 +1089,24 @@ func hasActiveQuota(quota QuotaState, now time.Time) bool { // isQuotaModelCooldown reports whether a model state carries a quota cooldown, // its own or one propagated from the credential. -func isQuotaModelCooldown(state *ModelState) bool { - return state != nil && (isQuotaReason(state.Quota) || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated) +func isQuotaModelCooldown(state *ModelState, now time.Time) bool { + return state != nil && (hasActiveQuota(state.Quota, now) || state.credentialQuotaShadow != nil || state.credentialQuotaPropagated) } // quotaCooldownRecoverable reports whether auth has an active quota cooldown // and none recorded after observedAt, which a usage poll at observedAt could not see. func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { - if len(auth.ModelStates) == 0 { - return isQuotaReason(auth.Quota) && auth.Quota.NextRecoverAt.After(now) && !auth.UpdatedAt.After(observedAt) + // A credential quota recorded without a model key only touches the account. + if hasActiveQuota(auth.Quota, now) && auth.UpdatedAt.After(observedAt) { + return false } - // With model states, the account-level quota is aggregated from them. - active := false + active, hasStates := false, false for _, state := range auth.ModelStates { - if !isQuotaModelCooldown(state) || !isModelStateActiveCooldown(state, now) { + if state == nil { + continue + } + hasStates = true + if !isQuotaModelCooldown(state, now) || !isModelStateActiveCooldown(state, now) { continue } if state.UpdatedAt.After(observedAt) { @@ -1110,6 +1114,10 @@ func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { } active = true } + if !hasStates { + return isQuotaReason(auth.Quota) && auth.Quota.NextRecoverAt.After(now) + } + // With model states, the account-level quota is aggregated from them. return active } @@ -1169,7 +1177,7 @@ func (m *Manager) resetQuota(ctx context.Context, authID string, recoverObserved if state == nil { continue } - if !isQuotaModelCooldown(state) { + if !isQuotaModelCooldown(state, now) { kept[modelKey] = state.Clone() continue } diff --git a/sdk/cliproxy/auth/quota_recover_usage_test.go b/sdk/cliproxy/auth/quota_recover_usage_test.go index c829d39a7a2..9bbb8442656 100644 --- a/sdk/cliproxy/auth/quota_recover_usage_test.go +++ b/sdk/cliproxy/auth/quota_recover_usage_test.go @@ -144,7 +144,7 @@ func TestRecoverQuotaFromUsageKeepsLiveFailureUnderLapsedQuotaFields(t *testing. }}}); err != nil { t.Fatal(err) } - updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, now) + updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, time.Now().Add(time.Second)) if err != nil || updated == nil { t.Fatalf("RecoverQuotaFromUsage: updated=%v err=%v", updated != nil, err) } @@ -152,4 +152,12 @@ func TestRecoverQuotaFromUsageKeepsLiveFailureUnderLapsedQuotaFields(t *testing. if state == nil || !state.Unavailable || !state.NextRetryAfter.Equal(failureUntil) || state.LastError == nil { t.Fatalf("live 404 cooldown not reinstated: %+v", state) } + // The next poll finds no quota left to recover and keeps the 404. + if again, _, errAgain := m.RecoverQuotaFromUsage(ctx, authID, now.Add(10*time.Minute)); errAgain != nil || again != nil { + t.Fatalf("second poll: updated=%v err=%v, want no change", again != nil, errAgain) + } + after, _ := m.GetByID(authID) + if state := after.ModelStates["recover-rejected"]; state == nil || !state.NextRetryAfter.Equal(failureUntil) { + t.Fatalf("second poll cleared the live 404: %+v", state) + } } From 3ec412adeb92d82d7483418e21c3c1b65acd68fe Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:01:32 +0000 Subject: [PATCH 17/19] fix(quota): let traffic on other models not delay a model quota recovery Co-Authored-By: Claude Opus 5.5 --- sdk/cliproxy/auth/conductor_cooldown.go | 4 ++- sdk/cliproxy/auth/quota_recover_usage_test.go | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/sdk/cliproxy/auth/conductor_cooldown.go b/sdk/cliproxy/auth/conductor_cooldown.go index 931480eaf2d..89d52781f21 100644 --- a/sdk/cliproxy/auth/conductor_cooldown.go +++ b/sdk/cliproxy/auth/conductor_cooldown.go @@ -1097,7 +1097,9 @@ func isQuotaModelCooldown(state *ModelState, now time.Time) bool { // and none recorded after observedAt, which a usage poll at observedAt could not see. func quotaCooldownRecoverable(auth *Auth, observedAt, now time.Time) bool { // A credential quota recorded without a model key only touches the account. - if hasActiveQuota(auth.Quota, now) && auth.UpdatedAt.After(observedAt) { + // It blocks every model, so no later traffic moves this timestamp; an + // account quota aggregated from model states is judged by those states. + if auth.Quota.Reason == "credential_quota" && hasActiveQuota(auth.Quota, now) && auth.UpdatedAt.After(observedAt) { return false } active, hasStates := false, false diff --git a/sdk/cliproxy/auth/quota_recover_usage_test.go b/sdk/cliproxy/auth/quota_recover_usage_test.go index 9bbb8442656..876dc41a715 100644 --- a/sdk/cliproxy/auth/quota_recover_usage_test.go +++ b/sdk/cliproxy/auth/quota_recover_usage_test.go @@ -161,3 +161,29 @@ func TestRecoverQuotaFromUsageKeepsLiveFailureUnderLapsedQuotaFields(t *testing. t.Fatalf("second poll cleared the live 404: %+v", state) } } + +// Traffic on another model after the poll started must not hold back the +// recovery of an older model quota. +func TestRecoverQuotaFromUsageIgnoresLaterTrafficOnOtherModels(t *testing.T) { + withQuotaCooldownEnabled(t) + ctx := context.Background() + m := NewManager(nil, nil, nil) + authID := "recover-usage-busy" + if _, err := m.Register(ctx, &Auth{ID: authID, Provider: "codex", Status: StatusActive}); err != nil { + t.Fatal(err) + } + retry := 39 * time.Hour + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-spent", + Error: &Error{HTTPStatus: http.StatusTooManyRequests, Code: "usage_limit_reached", Message: "The usage limit has been reached"}, + RetryAfter: &retry}) + // The poll starts between the rejection and the later success. + pollAt := time.Now() + m.MarkResult(ctx, Result{AuthID: authID, Provider: "codex", Model: "recover-busy", Success: true}) + updated, _, err := m.RecoverQuotaFromUsage(ctx, authID, pollAt) + if err != nil || updated == nil { + t.Fatalf("RecoverQuotaFromUsage: updated=%v err=%v, want recovery", updated != nil, err) + } + if state := updated.ModelStates["recover-spent"]; state == nil || state.Quota.Exceeded || state.Unavailable { + t.Fatalf("model quota not cleared: %+v", state) + } +} From 2411ed38f71e51d2f312e01caff4acec1f4f8183 Mon Sep 17 00:00:00 2001 From: Daniel <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 08:24:33 +0000 Subject: [PATCH 18/19] fix(opencode): restrict catalog and routing to selected providers (cherry picked from commit 21a3be7dec03a2e5332d0c08076117c63d887570) --- config.example.yaml | 6 +++ docs/t3code.md | 25 +++++++++++- internal/api/opencode_catalog.go | 55 ++++++++++++++++++++++----- internal/api/opencode_catalog_test.go | 47 +++++++++++++++++++++++ internal/api/opencode_upstream.go | 31 +++++++++++++++ internal/api/provider_routes.go | 16 +++++--- internal/api/server.go | 12 +++++- internal/config/sdk_config.go | 12 +++++- internal/registry/model_adoption.go | 7 +++- sdk/config/config.go | 1 + 10 files changed, 190 insertions(+), 22 deletions(-) diff --git a/config.example.yaml b/config.example.yaml index 3209c103826..f9ab77e558b 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -420,6 +420,12 @@ requests: # Client-facing compatibility settings apply to both OAuth and API-key routes. client: + # Optional OpenCode allowlist. Keys are /provider route names, values are picker labels. + # With this section enabled, OpenCode uses scoped routes and its own free models. + # opencode: + # providers: + # mistral: Mistral API + # mistral-vibe: Mistral Vibe codex: # When false (default), only models that natively declare freeform apply_patch advertise it. # When true, non-template and bridged models supported by every routing executor also advertise "freeform". diff --git a/docs/t3code.md b/docs/t3code.md index 5e7927c300e..948e9ccd68f 100644 --- a/docs/t3code.md +++ b/docs/t3code.md @@ -140,7 +140,7 @@ Clearing the binary path returns to T3 Code's bundled runtime and its fixed Gemi ## OpenCode -OpenCode takes its model catalog from a models.dev-style URL. The hub serves its own catalog at +By default, OpenCode takes its model catalog from a models.dev-style URL. The hub serves its own catalog at `https:///opencode//api.json`: every model the hub serves, under one provider called `t3code-proxy`, refreshed by OpenCode every few minutes. Claude models use the Anthropic Messages API, Codex models the Responses API, and the rest OpenAI chat completions, all on the hub. @@ -167,6 +167,29 @@ in its logs. 3. Pick a `t3code-proxy/` or `opencode/` model in the thread. The instance lists only those; your own OpenCode setup outside T3 Code is unchanged. +To give OpenCode just the two Mistral budgets and OpenCode's free models, configure the hub: + +```yaml +client: + opencode: + providers: + mistral: Mistral API + mistral-vibe: Mistral Vibe +``` + +The keys match the names in `/provider//v1`. The catalog then lists each allowed +provider under its own label and scoped URL, and includes only explicitly free, zero-priced +OpenCode offerings. An empty `providers: {}` allows only those free offerings. The hub +returns HTTP 403 when a recognized OpenCode client uses the general API or another provider. +It identifies the client by its OpenCode headers. A shared hub key still grants its normal +access to other clients. + +For OpenCode profiles with locally configured providers, remove any general hub provider +and its `provider.use` allowance from each active config, including `OPENCODE_CONFIG_DIR`. +Check any scheduled catalog refresh for writes that could recreate it. Keep the two scoped +Mistral base URLs, set their provider names to the labels above, then run `opencode reload` +and check `opencode models` in the same profile as T3 Code. + The standalone hub reserves its Claude subscription credentials for Claude Code and its Google Antigravity logins for the Antigravity CLI. OpenCode lists a model when an eligible credential supplies it, such as an Anthropic or Gemini API key or an upstream with `reserved-for: opencode`. diff --git a/internal/api/opencode_catalog.go b/internal/api/opencode_catalog.go index 89fe8262878..27d49253b37 100644 --- a/internal/api/opencode_catalog.go +++ b/internal/api/opencode_catalog.go @@ -2,10 +2,12 @@ package api import ( "net/http" + "net/url" "strings" "time" "github.com/gin-gonic/gin" + "github.com/rune-oai/t3code-proxy/internal/config" "github.com/rune-oai/t3code-proxy/internal/registry" ) @@ -45,17 +47,50 @@ func openCodePathKeyToHeader(c *gin.Context) { func (s *Server) openCodeCatalogHandler(c *gin.Context) { c.Header("Cache-Control", "no-store") - hub := buildOpenCodeCatalog(requestBaseURL(c.Request)+"/v1", registry.GetGlobalRegistry().OpenCodeModels()) - catalog := make(map[string]any, len(hub)+1) - for id, provider := range hub { - catalog[id] = provider + base := requestBaseURL(c.Request) + reg := registry.GetGlobalRegistry() + policy := s.getConfig().Client.OpenCode + catalog := make(map[string]any) + if policy == nil { + catalog[openCodeProviderID] = buildOpenCodeProvider(openCodeProviderID, openCodeProviderID, base+"/v1", reg.OpenCodeModels()) + } else { + for route, label := range policy.Providers { + scope := resolveProviderKey(route) + models := reg.OpenCodeProviderModels(scope) + if len(models) == 0 { + continue + } + id := openCodeProviderID + "-" + route + catalog[id] = buildOpenCodeProvider(id, label, base+"/provider/"+url.PathEscape(route)+"/v1", models) + } } if upstream := openCodeUpstream.Provider(openCodeUpstreamFirstWait); upstream != nil { - catalog[openCodeUpstreamProviderID] = upstream + if policy != nil { + upstream = freeOpenCodeProvider(upstream) + } + if upstream != nil { + catalog[openCodeUpstreamProviderID] = upstream + } } c.JSON(http.StatusOK, catalog) } +// A stale catch-all profile must not spend another provider's allowance. +func openCodeRouteAllowed(c *gin.Context, policy *config.OpenCodeClientConfig) bool { + switch c.FullPath() { + case "/healthz", "/opencode/:key/api.json": + return true + case "/provider/:provider/v1/models", "/provider/:provider/v1/models/*model", + "/provider/:provider/v1/chat/completions", "/provider/:provider/v1/completions", + "/provider/:provider/v1/responses", "/provider/:provider/v1/responses/compact", + "/provider/:provider/v1/messages", "/provider/:provider/v1/messages/count_tokens", + "/provider/:provider/v1beta/models", "/provider/:provider/v1beta/models/*action": + _, allowed := policy.Providers[c.Param("provider")] + return allowed + } + return false +} + // isOpenCodeRequest recognizes OpenCode, which may use credentials reserved for it // (reserved-for: opencode). OpenCode 2.x sends a User-Agent such as // "opencode/latest/2.3.0/cli" and x-opencode-* headers on its model requests. @@ -130,14 +165,14 @@ type openCodeModelProviderAPI struct { API string `json:"api"` } -// buildOpenCodeCatalog renders the hub's text models as one models.dev +// buildOpenCodeProvider renders the hub's text models as one models.dev // provider. Each model names the API shape that serves it best: Claude models // the Anthropic Messages API, Codex models the Responses API, and the rest // OpenAI chat completions. -func buildOpenCodeCatalog(apiBase string, models []registry.RegisteredModel) map[string]openCodeProvider { +func buildOpenCodeProvider(id, label, apiBase string, models []registry.RegisteredModel) openCodeProvider { provider := openCodeProvider{ - ID: openCodeProviderID, - Name: "t3code-proxy", + ID: id, + Name: label, Env: []string{openCodeAPIKeyEnv}, NPM: openCodeNPMOpenAICompatible, API: apiBase, @@ -157,7 +192,7 @@ func buildOpenCodeCatalog(apiBase string, models []registry.RegisteredModel) map entry.Name = registry.CatalogDisplayName(entry.Name, id, names[entry.Name]) provider.Models[id] = entry } - return map[string]openCodeProvider{openCodeProviderID: provider} + return provider } func openCodeModelFor(info *registry.ModelInfo, providers []string, apiBase string) openCodeModel { diff --git a/internal/api/opencode_catalog_test.go b/internal/api/opencode_catalog_test.go index 012766396ba..8119b8128f8 100644 --- a/internal/api/opencode_catalog_test.go +++ b/internal/api/opencode_catalog_test.go @@ -9,7 +9,9 @@ import ( "strings" "testing" + "github.com/MoeForge/moego/ojson" claudemodels "github.com/rune-oai/t3code-proxy/internal/client/claude/models" + "github.com/rune-oai/t3code-proxy/internal/config" "github.com/rune-oai/t3code-proxy/internal/registry" "github.com/rune-oai/t3code-proxy/internal/util" "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" @@ -138,6 +140,50 @@ func TestOpenCodeCatalogListsHubModelsInModelsDevFormat(t *testing.T) { } } +func TestRestrictedOpenCodeCatalogAndDispatch(t *testing.T) { + stubOpenCodeUpstream(t, func(context.Context, string) ([]byte, error) { + return []byte(`{"opencode":{"models":{ + "example-free":{"id":"example-free","cost":{"input":0,"output":0}}, + "paid":{"id":"paid","cost":{"input":1,"output":2}}, + "unknown-free":{"id":"unknown-free"}, + "cache-free":{"id":"cache-free","cost":{"input":0,"output":0,"cache_read":1}} + }}}`), nil + }) + server, executors := newProviderScopeServer(t) + cfg := *server.getConfig() + cfg.Client.OpenCode = &config.OpenCodeClientConfig{Providers: map[string]string{"mistral": "Mistral API"}} + server.UpdateClients(&cfg) + headers := map[string]string{"X-Opencode-Client": "cli"} + resp := scopedRequest(server, http.MethodGet, "/opencode/test-key/api.json", "", nil) + catalog := ojson.ParseBytes(resp.Body.Bytes()).Map() + allowed := catalog["t3code-proxy-mistral"] + if resp.Code != 200 || len(catalog) != 2 || allowed.Get("name").String() != "Mistral API" || + !strings.HasSuffix(allowed.Get("api").String(), "/provider/mistral/v1") || + len(allowed.Get("models").Map()) != 1 || allowed.Get("models").Map()[scopedSharedModel].Get("name").String() != "mistral shared" { + t.Fatalf("scoped catalog = %s", resp.Body.String()) + } + if models := catalog["opencode"].Get("models").Map(); len(models) != 1 || !models["example-free"].Exists() { + t.Fatalf("free models = %v", models) + } + body := `{"model":"` + scopedSharedModel + `","messages":[{"role":"user","content":"test"}]}` + for _, path := range []string{"/v1/chat/completions", "/provider/claude/v1/chat/completions", "/backend-api/codex/responses"} { + if got := scopedRequest(server, http.MethodPost, path, body, headers); got.Code != http.StatusForbidden { + t.Fatalf("%s = %d", path, got.Code) + } + } + for _, agent := range []string{"opencode", "opencode/2.3"} { + if got := scopedRequest(server, http.MethodGet, "/v1/models", "", map[string]string{"User-Agent": agent}); got.Code != http.StatusForbidden { + t.Fatalf("unscoped catalog for %s = %d", agent, got.Code) + } + } + if got := scopedRequest(server, http.MethodPost, "/provider/mistral/v1/chat/completions", body, headers); got.Code != 200 || len(executors["mistral"].authIDs) != 1 || len(executors["claude"].authIDs) != 0 { + t.Fatalf("allowed dispatch = %d, %s", got.Code, got.Body.String()) + } + if got := scopedRequest(server, http.MethodGet, "/v1/models", "", nil); got.Code != 200 || !strings.Contains(got.Body.String(), scopedOutsideModel) { + t.Fatalf("other client's catalog = %d, %s", got.Code, got.Body.String()) + } +} + func TestOpenCodeCatalogRequiresAnAccessKey(t *testing.T) { server := newTestServer(t) for _, path := range []string{"/opencode/wrong-key/api.json", "/opencode//api.json"} { @@ -347,6 +393,7 @@ func TestReservedForOpenCodeServesOnlyOpenCode(t *testing.T) { {"/opencode/test-key/api.json", nil, true}, {"/v1/models", openCode, true}, {"/v1/models", openCodeHeaderOnly, true}, + {"/v1/models", map[string]string{"User-Agent": "opencode"}, false}, {"/v1/models", vibe, false}, {"/v1/models", claudeCode, false}, {"/v1/models", map[string]string{"User-Agent": testAntigravityCLIUA}, false}, diff --git a/internal/api/opencode_upstream.go b/internal/api/opencode_upstream.go index 65c0bfc7ff2..3185ac62fac 100644 --- a/internal/api/opencode_upstream.go +++ b/internal/api/opencode_upstream.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "strings" "sync" "time" @@ -100,6 +101,36 @@ func (u *openCodeUpstreamCatalog) load() (json.RawMessage, error) { return json.RawMessage(provider.Raw), nil } +// Free offerings must have a free ID and explicit zero token prices. Unknown +// or tiered pricing is excluded from the restricted catalog. +func freeOpenCodeProvider(provider json.RawMessage) json.RawMessage { + doc := ojson.NewDoc(provider) + free := make(map[string]json.RawMessage) + for id, model := range doc.Get("models").Map() { + if id != "big-pickle" && !strings.HasSuffix(id, "-free") { + continue + } + cost := model.Get("cost").Map() + if model.Get("id").String() != id || cost["input"].Type != ojson.Number || cost["output"].Type != ojson.Number { + continue + } + zero := true + for _, price := range cost { + if price.Type != ojson.Number || price.Num != 0 { + zero = false + break + } + } + if zero { + free[id] = json.RawMessage(model.Raw) + } + } + if err := doc.Set("models", free); err != nil { + return nil + } + return doc.Bytes() +} + func fetchOpenCodeUpstreamCatalog(ctx context.Context, url string) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { diff --git a/internal/api/provider_routes.go b/internal/api/provider_routes.go index 580bd8064ac..40015c08ecc 100644 --- a/internal/api/provider_routes.go +++ b/internal/api/provider_routes.go @@ -17,15 +17,19 @@ import ( "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" ) +func resolveProviderKey(provider string) string { + provider = strings.ToLower(strings.TrimSpace(provider)) + if registry.GetGlobalRegistry().HasProvider(provider) { + return provider + } + return util.OpenAICompatibleProviderKey(provider) +} + func (s *Server) setupProviderRoutes(openaiHandler *openai.OpenAIAPIHandler, claudeHandler *claude.ClaudeCodeAPIHandler, responsesHandler *openai.OpenAIResponsesAPIHandler, geminiHandler *gemini.GeminiAPIHandler) { group := s.engine.Group("/provider/:provider", AuthMiddleware(s.accessManager)) group.Use(func(c *gin.Context) { - provider := strings.ToLower(strings.TrimSpace(c.Param("provider"))) - modelRegistry := registry.GetGlobalRegistry() - if !modelRegistry.HasProvider(provider) { - provider = util.OpenAICompatibleProviderKey(provider) - } - if !modelRegistry.HasProvider(provider) { + provider := resolveProviderKey(c.Param("provider")) + if !registry.GetGlobalRegistry().HasProvider(provider) { message := fmt.Sprintf("unknown provider %q", c.Param("provider")) errMsg := &interfaces.ErrorMessage{StatusCode: http.StatusNotFound, Error: errors.New(message)} switch { diff --git a/internal/api/server.go b/internal/api/server.go index 4a5774127d7..ad21f009f26 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -275,7 +275,7 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk // Home heartbeat gate: when home is enabled, block all endpoints with 503 until the // subscribe-config heartbeat connection is healthy. - engine.Use(subscriptionClientMiddleware) + engine.Use(s.subscriptionClientMiddleware) engine.Use(s.homeHeartbeatMiddleware()) engine.Use(s.exampleAPIKeySafeModeMiddleware()) @@ -536,7 +536,7 @@ func (s *Server) Stop(ctx context.Context) error { // reservations: the standalone Antigravity CLI may use the Google Antigravity logins, // OpenCode the credentials reserved for it, and everyone else no reserved credential. // The Claude handler upgrades a verified Claude Code request to the Claude subscriptions. -func subscriptionClientMiddleware(c *gin.Context) { +func (s *Server) subscriptionClientMiddleware(c *gin.Context) { client := "" switch { case antigravitycli.IsAntigravityCLIUserAgent(c.GetHeader("User-Agent")): @@ -544,5 +544,13 @@ func subscriptionClientMiddleware(c *gin.Context) { case isOpenCodeRequest(c.Request): client = registry.ReservedForOpenCode } + // A bare OpenCode user agent is subject to the route restriction, but does + // not establish eligibility for reserved credentials. + if client == registry.ReservedForOpenCode || strings.EqualFold(strings.TrimSpace(c.Request.UserAgent()), "opencode") { + if policy := s.getConfig().Client.OpenCode; policy != nil && !openCodeRouteAllowed(c, policy) { + c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "OpenCode requires an allowed provider-scoped route"}) + return + } + } c.Request = c.Request.WithContext(auth.WithSubscriptionClient(c.Request.Context(), client)) } diff --git a/internal/config/sdk_config.go b/internal/config/sdk_config.go index a2df0a43462..aa05ca7c756 100644 --- a/internal/config/sdk_config.go +++ b/internal/config/sdk_config.go @@ -127,8 +127,16 @@ func (c *SDKConfig) TLSHandshakeTimeout() time.Duration { // ClientConfig configures client-facing compatibility behavior. type ClientConfig struct { - Codex CodexClientConfig `yaml:"codex" json:"codex"` - Claude ClaudeClientConfig `yaml:"claude" json:"claude"` + // OpenCode, when present, opts into a provider-scoped catalog and routing. + OpenCode *OpenCodeClientConfig `yaml:"opencode,omitempty" json:"opencode,omitempty"` + Codex CodexClientConfig `yaml:"codex" json:"codex"` + Claude ClaudeClientConfig `yaml:"claude" json:"claude"` +} + +// OpenCodeClientConfig maps allowed /provider route names to their picker labels. +// An empty map exposes only OpenCode's own free models. +type OpenCodeClientConfig struct { + Providers map[string]string `yaml:"providers" json:"providers"` } // ClaudeClientConfig controls client-facing Claude protocol compatibility. diff --git a/internal/registry/model_adoption.go b/internal/registry/model_adoption.go index 7f9e4a772ac..1c3599e31cf 100644 --- a/internal/registry/model_adoption.go +++ b/internal/registry/model_adoption.go @@ -233,7 +233,12 @@ func (r *ModelRegistry) ClientCatalog(scope, client string) []RegisteredModel { // OpenCodeModels includes cooling credentials and those reserved for OpenCode, but // excludes credentials reserved for other clients. func (r *ModelRegistry) OpenCodeModels() []RegisteredModel { - return r.clientCatalog("", ReservedForOpenCode, true) + return r.OpenCodeProviderModels("") +} + +// OpenCodeProviderModels includes only credentials eligible within the given provider. +func (r *ModelRegistry) OpenCodeProviderModels(scope string) []RegisteredModel { + return r.clientCatalog(scope, ReservedForOpenCode, true) } // Project each registration onto eligible credentials before resolving availability, diff --git a/sdk/config/config.go b/sdk/config/config.go index aae13ff96c5..e7a43b1bf76 100644 --- a/sdk/config/config.go +++ b/sdk/config/config.go @@ -13,6 +13,7 @@ type Config = internalconfig.Config type ModelCatalogs = internalconfig.ModelCatalogs type ClientConfig = internalconfig.ClientConfig +type OpenCodeClientConfig = internalconfig.OpenCodeClientConfig type ClaudeClientConfig = internalconfig.ClaudeClientConfig type CodexClientConfig = internalconfig.CodexClientConfig type CodexWebSearchResultCacheConfig = internalconfig.CodexWebSearchResultCacheConfig From a3e45d3a860a2f053aa685409622ba60691cee32 Mon Sep 17 00:00:00 2001 From: rune-oai <157205701+rune-gh@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:10:20 -0800 Subject: [PATCH 19/19] feat(web): draw each quota window as its own line, drop drain rate and 5-hour charts Pool cards no longer switch between windows. Every window a provider reports (Claude weekly and Fable weekly, Antigravity's model groups, Mistral's two budgets, ...) is a separately coloured line on one chart, with a compact per-window table for remaining, pool-empty, first-empty, next reset and burn. Single-window providers keep the large headline. Sub-day windows (5-hour) no longer get a chart line unless a provider reports nothing longer; the account table still shows each account's 5-hour meter. The Remaining/Drain rate toggle is gone. Co-Authored-By: Claude Opus 5.5 --- web/src/features/quota/QuotaPage.tsx | 20 +- .../quota/components/PoolChart.module.scss | 32 +- .../features/quota/components/PoolChart.tsx | 304 +++++++------ .../components/QuotaPoolCard.module.scss | 87 +++- .../quota/components/QuotaPoolCard.tsx | 418 +++++++++--------- .../quota/components/QuotaPoolToolbar.tsx | 20 +- web/src/features/quota/poolModel.ts | 32 +- web/src/i18n/locales/en.json | 14 +- web/tests/quotaPoolModel.test.ts | 33 +- 9 files changed, 539 insertions(+), 421 deletions(-) diff --git a/web/src/features/quota/QuotaPage.tsx b/web/src/features/quota/QuotaPage.tsx index 6b970a97129..389ac2f3531 100644 --- a/web/src/features/quota/QuotaPage.tsx +++ b/web/src/features/quota/QuotaPage.tsx @@ -47,24 +47,21 @@ import { RESETS_FILTER_ALL } from './resetCalendarModel'; import { UseResetDialog, type UseResetTarget } from './components/UseResetDialog'; import { QuotaPoolCard } from './components/QuotaPoolCard'; import { QuotaPoolToolbar, type BurnWindowHours } from './components/QuotaPoolToolbar'; -import type { PoolChartMode } from './components/PoolChart'; import { LIVE_POOL_PROVIDERS, defaultPoolSpan, historyFromLiveSnapshots, isLivePoolProvider, mergeLiveHistory, + poolChartWindows, poolProvidersFromHistory, - poolWindowChoices, providerWindowLabels, providerWindows, - resolvePoolWindow, shiftPoolSpan, type FutureUsage, type LiveAccountInput, type PoolProvider, type PoolSpan, - type PoolWindowChoice, } from './poolModel'; import { formatPlanName, formatWeight } from './poolPrefs'; import { liveReadFor, type LiveRead } from './liveWindows'; @@ -278,12 +275,9 @@ export function QuotaPage() { // null = follow today (Now a quarter into a 14-day span). const [pinnedSpan, setPinnedSpan] = useState(null); const span = pinnedSpan ?? defaultPoolSpan(now); - const [chartMode, setChartMode] = useState('remaining'); const [burnWindow, setBurnWindow] = useState(3); const [futureUsage, setFutureUsage] = useState('same'); const [showAccounts, setShowAccounts] = useState(false); - // Only choices the user made; each card falls back to its provider default. - const [poolWindows, setPoolWindows] = useState>({}); const planWeights = usePlanWeights(!disableControls); // Also without credential files: the hub may record API-key upstreams (Mistral) only. @@ -915,8 +909,6 @@ export function QuotaPage() { {showViews && view === 'pools' && ( <> entry.type === provider); const rows = rowsByProvider[provider] ?? []; const lastReadAt = historyReady ? latestReadingAt(rows) : null; - const windowChoice = resolvePoolWindow(provider, poolHistory, poolWindows[provider]); const windows = isLivePoolProvider(provider) ? [] : providerWindows(poolHistory, provider); @@ -993,19 +984,14 @@ export function QuotaPage() { key={provider} provider={provider} history={poolHistory} - window={windowChoice ?? ''} - windowChoices={poolWindowChoices(provider, poolHistory)} + windows={poolChartWindows(provider, poolHistory)} windowLabels={windowLabels} - onWindowChange={(choice) => - setPoolWindows((previous) => ({ ...previous, [provider]: choice })) - } weights={planWeights.effectiveFor(provider)} defaultWeights={planWeights.defaultsFor(provider)} configuredWeights={planWeights.configuredFor(provider)} weightsMode={planWeights.mode} weightsError={planWeights.error} onSaveWeights={(changes) => handleSaveWeights(provider, changes)} - mode={chartMode} showAccounts={showAccounts} spanStart={span.start} spanEnd={span.end} @@ -1018,7 +1004,7 @@ export function QuotaPage() { loading={poolLoading} lastReadAt={lastReadAt} stale={isReadingStale(lastReadAt, now, historyIntervalSeconds)} - headlineHint={windowChoice ? budgetHint(rows, windowChoice) : undefined} + headlineHint={(window) => budgetHint(rows, window)} bankedResets={ provider === 'codex' ? totalBankedCredits( diff --git a/web/src/features/quota/components/PoolChart.module.scss b/web/src/features/quota/components/PoolChart.module.scss index 4d60af48b01..857dfde2a01 100644 --- a/web/src/features/quota/components/PoolChart.module.scss +++ b/web/src/features/quota/components/PoolChart.module.scss @@ -1,4 +1,4 @@ -/* Pool chart: series colour comes from the panel's --pool-color; the rest is neutral. */ +/* Pool chart: each line sets --series-color (the first is the panel's --pool-color); the rest is neutral. */ .wrap { position: relative; @@ -15,7 +15,7 @@ .areaRecorded, .areaProjected { - fill: var(--pool-color); + fill: var(--series-color, var(--pool-color)); stroke: none; } @@ -46,7 +46,7 @@ .line { fill: none; - stroke: var(--pool-color); + stroke: var(--series-color, var(--pool-color)); stroke-width: 1.75; stroke-linejoin: round; stroke-linecap: round; @@ -59,7 +59,7 @@ .accountLine { fill: none; - stroke: var(--pool-color); + stroke: var(--series-color, var(--pool-color)); stroke-opacity: 0.4; stroke-width: 1; stroke-linejoin: round; @@ -88,7 +88,7 @@ .nowDot, .hoverDot { - fill: var(--pool-color); + fill: var(--series-color, var(--pool-color)); stroke: var(--card); stroke-width: 2; } @@ -108,6 +108,14 @@ stroke-width: 1.5; } +.emptyRingSeries { + stroke: var(--series-color); +} + +.jumpLabelSeries { + fill: var(--series-color); +} + .tooltip { position: absolute; z-index: 2; @@ -123,3 +131,17 @@ pointer-events: none; box-shadow: var(--shadow-popover); } + +.tooltipRow { + display: flex; + align-items: center; + gap: var(--space-2); +} + +.tooltipSwatch { + display: inline-block; + width: 10px; + height: 2px; + border-radius: 1px; + background: var(--series-color); +} diff --git a/web/src/features/quota/components/PoolChart.tsx b/web/src/features/quota/components/PoolChart.tsx index 838a65665d9..fa07497c271 100644 --- a/web/src/features/quota/components/PoolChart.tsx +++ b/web/src/features/quota/components/PoolChart.tsx @@ -1,29 +1,37 @@ /** - * Pool chart: recorded (solid line, flat area) and projected (dashed) pooled - * quota over the span, with reset-jump annotations, a Now rule, an "Empty" - * marker, optional per-account lines, and a hover crosshair. + * Pool chart: one line per window (Weekly, Fable weekly, Gemini Models, ...), + * each in its own colour, recorded solid and projected dashed, with reset-jump + * annotations, a Now rule, "Empty" markers, optional per-account lines and a + * hover crosshair that reads every line at once. * * Plain SVG in pixel space (width measured with ResizeObserver) so text and * strokes never distort. */ -import { useEffect, useId, useMemo, useRef, useState, type PointerEvent } from 'react'; +import { + useEffect, + useId, + useMemo, + useRef, + useState, + type CSSProperties, + type PointerEvent, +} from 'react'; import { useTranslation } from 'react-i18next'; import { dayStarts, type PoolView, type SeriesPoint } from '../poolModel'; -import { - formatDayTick, - formatWeekdayTime, - niceCeil, - POOL_UNITS, - type PoolUnits, -} from '../poolFormat'; +import { formatDayTick, formatWeekdayTime, POOL_UNITS, type PoolUnits } from '../poolFormat'; import styles from './PoolChart.module.scss'; -export type PoolChartMode = 'remaining' | 'drain'; +export interface PoolChartSeries { + key: string; + label: string; + /** CSS colour for this line (the first series uses the provider colour). */ + color: string; + view: PoolView; +} export interface PoolChartProps { - view: PoolView; - mode: PoolChartMode; + series: readonly PoolChartSeries[]; showAccounts: boolean; spanStart: number; spanEnd: number; @@ -79,9 +87,10 @@ function valueAt(points: readonly SeriesPoint[], t: number, interpolate: boolean return a.value + ((b.value - a.value) * (t - a.t)) / (b.t - a.t); } +const seriesStyle = (color: string) => ({ '--series-color': color }) as CSSProperties; + export function PoolChart({ - view, - mode, + series, showAccounts, spanStart, spanEnd, @@ -105,10 +114,6 @@ export function PoolChart({ return () => observer.disconnect(); }, []); - const drain = mode === 'drain'; - const recordedSeries = drain ? view.recordedRate : view.recorded; - const projectedSeries = drain ? view.projectedRate : view.projected; - const height = width < COMPACT_WIDTH ? COMPACT_HEIGHT : HEIGHT; const compact = width < COMPACT_WIDTH; const plotLeft = MARGIN.left; @@ -116,23 +121,18 @@ export function PoolChart({ const plotTop = MARGIN.top; const plotBottom = height - MARGIN.bottom; const span = Math.max(1, spanEnd - spanStart); + // One line keeps its filled area; several lines would muddy each other. + const single = series.length === 1; const yMax = useMemo(() => { - if (!drain) return view.max > 0 ? view.max : 100; - const peak = Math.max( - 0, - ...recordedSeries.map((p) => p.value), - ...projectedSeries.map((p) => p.value) - ); - return niceCeil(Math.max(1, peak * 1.15)); - }, [drain, projectedSeries, recordedSeries, view.max]); + const max = Math.max(0, ...series.map((line) => line.view.max)); + return max > 0 ? max : 100; + }, [series]); const x = (time: number) => plotLeft + ((time - spanStart) / span) * (plotRight - plotLeft); const y = (value: number) => plotBottom - (Math.min(Math.max(value, 0), yMax) / yMax) * (plotBottom - plotTop); - const formatValue = (value: number) => (drain ? units.rate(value) : units.value(value)); - const days = useMemo(() => dayStarts(spanStart, spanEnd), [spanStart, spanEnd]); const dayLabels = useMemo(() => { const bounds = [spanStart, ...days.filter((d) => d > spanStart), spanEnd]; @@ -151,13 +151,14 @@ export function PoolChart({ return labels.filter((_, index) => index % step === 0); }, [days, locale, spanEnd, spanStart, width]); - // Jump annotations, greedily thinned so labels never overlap. + // Jump annotations over every line, greedily thinned so labels never overlap. const jumpLabels = useMemo(() => { - if (drain || compact) return []; - const out: { x: number; y: number; label: string; projected: boolean }[] = []; - [...view.jumps] - .sort((a, b) => a.t - b.t) - .forEach((jump) => { + if (compact) return []; + const out: { x: number; y: number; label: string; color: string }[] = []; + series + .flatMap((line) => line.view.jumps.map((jump) => ({ jump, color: line.color }))) + .sort((a, b) => a.jump.t - b.jump.t) + .forEach(({ jump, color }) => { const jx = plotLeft + ((jump.t - spanStart) / span) * (plotRight - plotLeft); const jy = plotBottom - (Math.min(Math.max(jump.value, 0), yMax) / yMax) * (plotBottom - plotTop); @@ -166,46 +167,32 @@ export function PoolChart({ (other) => Math.abs(other.x - jx) < LABEL_MIN_GAP_X && Math.abs(other.y - labelY) < 14 ); if (clash || jx < plotLeft || jx > plotRight) return; - out.push({ - x: jx, - y: labelY, - label: units.signed(jump.amount), - projected: jump.projected, - }); + out.push({ x: jx, y: labelY, label: units.signed(jump.amount), color }); }); return out; - }, [ - compact, - drain, - plotBottom, - plotLeft, - plotRight, - plotTop, - span, - spanStart, - units, - view.jumps, - yMax, - ]); + }, [compact, plotBottom, plotLeft, plotRight, plotTop, series, span, spanStart, units, yMax]); const nowVisible = now >= spanStart && now <= spanEnd; const nowX = x(now); - const nowValue = drain - ? (recordedSeries[recordedSeries.length - 1]?.value ?? view.burnRate) - : view.current; - const emptyAt = !drain ? view.poolEmptyAt : null; - // Hover lookup. + // "Empty" markers, stacked upward so two lines emptying close together stay legible. + const empties = series + .map((line) => ({ line, at: line.view.poolEmptyAt })) + .filter((item): item is { line: PoolChartSeries; at: number } => item.at !== null); + + // Hover lookup: every line's value at the hovered time. const hover = useMemo(() => { if (hoverX === null) return null; const time = spanStart + ((hoverX - plotLeft) / (plotRight - plotLeft)) * span; const projected = time > now; - const value = projected - ? valueAt(projectedSeries, time, true) - : valueAt(recordedSeries, time, false); - if (value === null) return { time, value: null, projected }; - return { time, value, projected }; - }, [hoverX, now, plotLeft, plotRight, projectedSeries, recordedSeries, span, spanStart]); + const values = series.map((line) => ({ + line, + value: projected + ? valueAt(line.view.projected, time, true) + : valueAt(line.view.recorded, time, false), + })); + return { time, projected, values }; + }, [hoverX, now, plotLeft, plotRight, series, span, spanStart]); const onPointerMove = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); @@ -214,22 +201,19 @@ export function PoolChart({ }; const yTicks = [0, yMax / 2, yMax]; - const recordedLine = linePath(recordedSeries, x, y); - const projectedLine = linePath(projectedSeries, x, y); - const recordedArea = areaPath(recordedSeries, x, y, plotBottom); - const projectedArea = areaPath(projectedSeries, x, y, plotBottom); - - const summary = drain - ? t('quota_pool.chart_summary_drain', { - defaultValue: 'Drain rate over time; currently {{rate}}.', - rate: units.rate(view.burnRate), + + const summary = series + .map((line) => + t('quota_pool.chart_summary_series', { + defaultValue: '{{label}}: {{current}} of {{max}} left', + label: line.label, + current: units.value(line.view.current), + max: units.value(line.view.max), }) - : t('quota_pool.chart_summary', { - defaultValue: 'Pooled quota over time: {{current}} of {{max}} left.', - current: units.value(view.current), - max: units.value(view.max), - }); + ) + .join('; '); + const hoverValues = hover?.values.filter((item) => item.value !== null) ?? []; const tooltipFlip = hoverX !== null && hoverX > width / 2; return ( @@ -284,7 +268,7 @@ export function PoolChart({ textAnchor="end" dy="0.32em" > - {formatValue(tick)} + {units.value(tick)} ))} @@ -302,34 +286,53 @@ export function PoolChart({ ))} - {projectedArea && } - {recordedArea && } - - {showAccounts && - view.accounts.map((account) => { - const rec = drain ? account.recordedRate : account.recorded; - const proj = drain ? account.projectedRate : account.projected; + {single && + series.map((line) => { + const projectedArea = areaPath(line.view.projected, x, y, plotBottom); + const recordedArea = areaPath(line.view.recorded, x, y, plotBottom); return ( - - - + + {projectedArea && } + {recordedArea && } ); })} - {projectedLine && ( - - )} - {recordedLine && } + {showAccounts && + series.map((line) => ( + + {line.view.accounts.map((account) => ( + + + + + ))} + + ))} + + {/* Later series first so the provider's own line draws on top. */} + {[...series].reverse().map((line) => { + const projectedLine = linePath(line.view.projected, x, y); + const recordedLine = linePath(line.view.recorded, x, y); + return ( + + {projectedLine && ( + + )} + {recordedLine && } + + ); + })} {jumpLabels.map((label) => ( {t('quota_pool.now', { defaultValue: 'Now' })} - {recordedSeries.length > 0 && ( - - )} + {series + .filter((line) => line.view.recorded.length > 0) + .map((line) => ( + + ))} )} - {emptyAt !== null && ( - + {empties.map(({ line, at }, index) => ( + - {t('quota_pool.empty_at', { - defaultValue: 'Empty {{time}}', - time: formatWeekdayTime(emptyAt, locale), - })} + {single + ? t('quota_pool.empty_at', { + defaultValue: 'Empty {{time}}', + time: formatWeekdayTime(at, locale), + }) + : t('quota_pool.empty_at_series', { + defaultValue: '{{label}} empty {{time}}', + label: line.label, + time: formatWeekdayTime(at, locale), + })} - + - )} + ))} {hover && hoverX !== null && ( @@ -376,14 +401,21 @@ export function PoolChart({ y1={plotTop} y2={plotBottom} /> - {hover.value !== null && ( - - )} + {hoverValues.map(({ line, value }) => ( + + ))} )} - {hover && hoverX !== null && hover.value !== null && ( + {hover && hoverX !== null && hoverValues.length > 0 && (
- {formatWeekdayTime(hover.time, locale)} - {' · '} - {drain - ? units.rate(hover.value) - : t('quota_pool.tooltip_left', { - defaultValue: '{{value}} left', - value: units.value(hover.value), - })} - {' · '} - {hover.projected - ? t('quota_pool.projected_lower', { defaultValue: 'projected' }) - : t('quota_pool.recorded_lower', { defaultValue: 'recorded' })} +
+ {formatWeekdayTime(hover.time, locale)} + {' · '} + {hover.projected + ? t('quota_pool.projected_lower', { defaultValue: 'projected' }) + : t('quota_pool.recorded_lower', { defaultValue: 'recorded' })} +
+ {hoverValues.map(({ line, value }) => ( +
+ {!single && ( +
+ ))}
)} diff --git a/web/src/features/quota/components/QuotaPoolCard.module.scss b/web/src/features/quota/components/QuotaPoolCard.module.scss index 13e288ac808..b133ce17007 100644 --- a/web/src/features/quota/components/QuotaPoolCard.module.scss +++ b/web/src/features/quota/components/QuotaPoolCard.module.scss @@ -35,11 +35,6 @@ max-width: 100%; } -.windowSelect { - min-width: 0; - max-width: 220px; -} - /* ---------- plan weights popover ---------- */ .weightsAnchor { @@ -125,6 +120,11 @@ .panel { --pool-color: #c96442; + /* Further lines on a multi-window chart, chosen to stay apart from every provider colour. */ + --pool-series-1: #7c4ddb; + --pool-series-2: #0f9d76; + --pool-series-3: #c2417e; + --pool-series-4: #8a7a12; display: flex; flex-direction: column; @@ -142,6 +142,10 @@ :global([data-theme='dark']) .panel { --pool-color: #d97757; + --pool-series-1: #a98bf5; + --pool-series-2: #3ccf9f; + --pool-series-3: #f07ab3; + --pool-series-4: #d8c552; &[data-provider='codex'] { --pool-color: #7aa2f7; @@ -193,6 +197,79 @@ text-align: center; } +/* ---------- per-window summary (several lines) ---------- */ + +.seriesTableWrap { + display: flex; + flex-direction: column; + gap: var(--space-3); + min-width: 0; + overflow-x: auto; +} + +.seriesTable { + width: 100%; + border-collapse: collapse; + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; + + th, + td { + padding: var(--space-2) var(--space-4) var(--space-2) 0; + text-align: left; + vertical-align: baseline; + white-space: nowrap; + } + + thead th { + padding-top: 0; + color: var(--muted-foreground); + font-weight: 400; + } + + tbody tr + tr > * { + border-top: 1px solid var(--border); + } + + tbody th { + font-weight: 500; + color: var(--foreground); + } + + td { + color: var(--foreground); + } +} + +.seriesName { + display: inline-flex; + align-items: center; + gap: var(--space-2); +} + +.seriesSwatch { + display: inline-block; + width: 16px; + height: 0; + border-top: 2px solid var(--series-color); +} + +.seriesValue { + font-size: var(--text-lg); + font-weight: 600; +} + +.seriesMax { + margin-left: var(--space-1); + color: var(--muted-foreground); +} + +.seriesHint { + display: block; + color: var(--muted-foreground); + font-size: var(--text-xs); +} + /* ---------- legend ---------- */ .legend { diff --git a/web/src/features/quota/components/QuotaPoolCard.tsx b/web/src/features/quota/components/QuotaPoolCard.tsx index 59768e636ee..02583469f80 100644 --- a/web/src/features/quota/components/QuotaPoolCard.tsx +++ b/web/src/features/quota/components/QuotaPoolCard.tsx @@ -1,7 +1,8 @@ /** - * One provider's pooled quota: a section with the window picker, a panel - * holding the headline, projection stats, chart and legend, then the - * per-account table. All numbers come from the pure pool model (poolModel.ts). + * One provider's pooled quota: a section holding the headline (or, with + * several windows, one stats row per window), the chart with one coloured + * line per window, the legend, then the per-account table. All numbers come + * from the pure pool model (poolModel.ts). * * Pools are capacity-weighted by plan and read in percent of the heaviest plan * in the pool: with a Max 5x and a Pro account, Max 5x is 100% and Pro 20%, so @@ -27,8 +28,6 @@ import { IconSlidersHorizontal } from '@/components/ui/icons'; import { Section } from '@/components/ui/Section'; import { Skeleton } from '@/components/ui/Skeleton'; import { Stat } from '@/components/ui/Stat'; -import { Select } from '@/components/ui/Select'; -import { SegmentedControl } from '@/components/ui/Tabs'; import type { QuotaHistory } from '@/services/api'; import type { ResolvedTheme } from '@/types'; import { getAuthFileIcon, getTypeColor, getTypeLabel } from '@/features/authFiles/constants'; @@ -39,24 +38,23 @@ import { type FutureUsage, type PlanWeights, type PoolProvider, + type PoolView, type PoolWindowChoice, } from '../poolModel'; import { formatDuration, formatMonthDay, formatWeekdayTime, POOL_UNITS } from '../poolFormat'; import { formatPlanName, formatWeight, planKey } from '../poolPrefs'; -import { groupWindowChoices, windowLabel } from '../poolWindowLabels'; +import { windowLabel } from '../poolWindowLabels'; import type { PlanWeightsMode } from '../hooks/usePlanWeights'; -import { PoolChart, type PoolChartMode } from './PoolChart'; +import { PoolChart, type PoolChartSeries } from './PoolChart'; import styles from './QuotaPoolCard.module.scss'; export interface QuotaPoolCardProps { provider: PoolProvider; history: QuotaHistory; - window: PoolWindowChoice; - /** Choices for the window picker; hidden when there is only one. */ - windowChoices: readonly PoolWindowChoice[]; + /** Windows drawn as lines, the provider's main window first. */ + windows: readonly PoolWindowChoice[]; /** Names the provider gives its own windows, by window key. */ windowLabels?: Record; - onWindowChange: (window: PoolWindowChoice) => void; /** Effective plan weights (plan → weight). */ weights: PlanWeights; /** Hub defaults per plan; empty when the hub does not report them. */ @@ -68,7 +66,6 @@ export interface QuotaPoolCardProps { weightsError?: string; /** Save edits: a weight, or null to go back to the default. Rejects on failure. */ onSaveWeights: (changes: Record) => Promise; - mode: PoolChartMode; showAccounts: boolean; spanStart: number; spanEnd: number; @@ -84,8 +81,8 @@ export interface QuotaPoolCardProps { /** Newest recorded reading; null hides the line (live-only view). */ lastReadAt?: number | null; stale?: boolean; - /** A line under the headline, e.g. money spent in a window with a budget. */ - headlineHint?: string; + /** A line under a window's figure, e.g. money spent in a window with a budget. */ + headlineHint?: (window: PoolWindowChoice) => string | undefined; /** Codex: banked resets over all accounts; null while unknown. */ bankedResets?: number | null; /** Per-account table. */ @@ -96,8 +93,11 @@ export interface QuotaPoolCardProps { reading?: boolean; } -/** More window choices than this switch the picker to a menu so it fits narrow screens. */ -const MAX_SEGMENTED_WINDOWS = 3; +/** Line colour by position: the provider colour first, then the panel's series palette. */ +const seriesColor = (index: number) => + index === 0 ? 'var(--pool-color)' : `var(--pool-series-${Math.min(index, 4)})`; + +type StatItem = { key: string; label: string; value: ReactNode }; const formatClock = (ms: number, locale: string) => new Date(ms).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }); @@ -106,17 +106,14 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const { provider, history, - window: windowChoice, - windowChoices, + windows, windowLabels, - onWindowChange, weights, defaultWeights = {}, configuredWeights = {}, weightsMode, weightsError = '', onSaveWeights, - mode, showAccounts, spanStart, spanEnd, @@ -142,11 +139,12 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const [saveError, setSaveError] = useState(''); const weightsRef = useRef(null); - const view = useMemo( - () => - buildPoolView(history, { + const lines = useMemo(() => { + const built = windows.map((window) => ({ + window, + view: buildPoolView(history, { provider, - window: windowChoice, + window, weights, now, spanStart, @@ -154,18 +152,11 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { burnWindowHours, futureUsage, }), - [ - burnWindowHours, - futureUsage, - history, - now, - provider, - spanEnd, - spanStart, - weights, - windowChoice, - ] - ); + })); + // A window no account draws on (Fable on a Pro-only pool) gets no line. + const drawn = built.filter((line) => line.view.tracks.length > 0); + return drawn.length > 0 ? drawn : built.slice(0, 1); + }, [burnWindowHours, futureUsage, history, now, provider, spanEnd, spanStart, weights, windows]); const plans = useMemo(() => { const set = new Set(); @@ -176,7 +167,14 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { }, [history.accounts, provider]); const units = POOL_UNITS; - const single = view.tracks.length === 1; + const series: PoolChartSeries[] = lines.map((line, index) => ({ + key: line.window, + label: windowLabel(t, line.window, windowLabels), + color: seriesColor(index), + view: line.view, + })); + const primary = series[0]; + const multi = series.length > 1; const currentWeight = (plan: string) => weights[plan] ?? defaultWeights[plan] ?? 1; const openWeights = () => { @@ -244,98 +242,81 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const providerLabel = getTypeLabel(t, provider); const notBy = t('quota_pool.not_by', { date: formatMonthDay(spanEnd, locale) }); - const hasData = view.tracks.length > 0; - const firstEmptyValue = view.firstEmpty ? ( - <> - - {view.firstEmpty.label} - {' '} - {view.firstEmpty.at <= now - ? t('quota_pool.empty_now') - : t('quota_pool.in_duration', { duration: formatDuration(view.firstEmpty.at - now) })} - - ) : ( - notBy - ); + const hasData = series.some((line) => line.view.tracks.length > 0); + const firstEmptyValue = (view: PoolView): ReactNode => + view.firstEmpty ? ( + <> + + {view.firstEmpty.label} + {' '} + {view.firstEmpty.at <= now + ? t('quota_pool.empty_now') + : t('quota_pool.in_duration', { duration: formatDuration(view.firstEmpty.at - now) })} + + ) : ( + notBy + ); - const currentWindowLabel = windowLabel(t, windowChoice, windowLabels); - // Many scoped windows (Antigravity): a group picker plus short period tabs. - const windowGroups = groupWindowChoices(t, windowChoices, windowLabels); - const currentItem = windowGroups?.items.find((item) => item.choice === windowChoice); - const currentGroup = currentItem?.group ?? windowGroups?.groups[0] ?? ''; - const groupItems = windowGroups - ? windowGroups.items.filter((item) => (item.group ?? '') === currentGroup) - : []; - const selectGroup = (group: string) => { - if (!windowGroups) return; - const inGroup = windowGroups.items.filter((item) => (item.group ?? '') === group); - // Keep the period the user is looking at when the new group has it. - const same = inGroup.find((item) => item.period === currentItem?.period); - const next = same ?? inGroup[0]; - if (next) onWindowChange(next.choice); + // Labels follow the main window; every line uses the same burn window. + const limited = primary?.view.burnEstimate.confidence === 'limited'; + const statsFor = (view: PoolView): StatItem[] => { + const hasTracks = view.tracks.length > 0; + const collecting = !view.burnEstimate.ready && futureUsage !== 'none'; + return [ + { + key: 'pool-empty', + label: t(limited ? 'quota_pool.stat_pool_empty_limited' : 'quota_pool.stat_pool_empty'), + value: !hasTracks + ? '—' + : collecting + ? t('quota_pool.collecting_data') + : view.poolEmptyAt !== null + ? formatWeekdayTime(view.poolEmptyAt, locale) + : notBy, + }, + { + key: 'first-empty', + label: t('quota_pool.stat_first_empty'), + // With one account the first account to run dry is the pool itself. + value: + view.tracks.length < 2 + ? '—' + : collecting + ? t('quota_pool.collecting_data') + : firstEmptyValue(view), + }, + { + key: 'next-reset', + label: t('quota_pool.stat_next_reset'), + value: view.nextReset + ? `${units.signed(view.nextReset.amount)}, ${formatWeekdayTime(view.nextReset.at, locale)}` + : '—', + }, + { + key: 'burn', + label: t(limited ? 'quota_pool.stat_burn_limited' : 'quota_pool.stat_burn', { + hours: Number((primary?.view.burnEstimate.windowHours ?? burnWindowHours).toFixed(1)), + }), + value: !hasTracks + ? '—' + : view.burnEstimate.ready + ? units.rate(view.burnRate) + : t('quota_pool.collecting_data'), + }, + ]; }; - const stats: { key: string; label: string; value: ReactNode }[] = [ - { - key: 'pool-empty', - label: t( - view.burnEstimate.confidence === 'limited' - ? 'quota_pool.stat_pool_empty_limited' - : 'quota_pool.stat_pool_empty' - ), - value: !hasData - ? '—' - : !view.burnEstimate.ready && futureUsage !== 'none' - ? t('quota_pool.collecting_data') - : view.poolEmptyAt !== null - ? formatWeekdayTime(view.poolEmptyAt, locale) - : notBy, - }, - { - key: 'first-empty', - label: t('quota_pool.stat_first_empty'), - value: !hasData - ? '—' - : !view.burnEstimate.ready && futureUsage !== 'none' - ? t('quota_pool.collecting_data') - : firstEmptyValue, - }, - { - key: 'next-reset', - label: t('quota_pool.stat_next_reset'), - value: view.nextReset - ? `${units.signed(view.nextReset.amount)}, ${formatWeekdayTime(view.nextReset.at, locale)}` - : '—', - }, - { - key: 'burn', - label: t( - view.burnEstimate.confidence === 'limited' - ? 'quota_pool.stat_burn_limited' - : 'quota_pool.stat_burn', - { - hours: Number(view.burnEstimate.windowHours.toFixed(1)), - } - ), - value: !hasData - ? '—' - : view.burnEstimate.ready - ? units.rate(view.burnRate) - : t('quota_pool.collecting_data'), - }, - ]; - // With one account the first account to run dry is the pool itself. - if (single) - stats.splice( - stats.findIndex((stat) => stat.key === 'first-empty'), - 1 - ); - if (bankedResets !== undefined) { - stats.push({ - key: 'banked', - label: t('quota_pool.stat_banked'), - value: bankedResets === null ? '—' : String(bankedResets), - }); - } + // The first-empty stat only means something when a line pools several accounts. + const showFirstEmpty = series.some((line) => line.view.tracks.length > 1); + const shownStats = (view: PoolView) => + statsFor(view).filter((stat) => stat.key !== 'first-empty' || showFirstEmpty); + const banked: StatItem | null = + bankedResets === undefined + ? null + : { + key: 'banked', + label: t('quota_pool.stat_banked'), + value: bankedResets === null ? '—' : String(bankedResets), + }; const description = ( @@ -351,6 +332,93 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { ); + let summary: ReactNode = null; + if (loading) { + summary = ( +
+ } + /> +
+ ); + } else if (hasData && primary && !multi) { + summary = ( +
+ +
+ {[...shownStats(primary.view), ...(banked ? [banked] : [])].map((stat) => ( + + ))} +
+
+ ); + } else if (hasData && primary) { + summary = ( +
+ + + + + + {shownStats(primary.view).map((stat) => ( + + ))} + + + + {series.map((line) => { + const hint = headlineHint?.(line.key); + return ( + + + + {shownStats(line.view).map((stat) => ( + + ))} + + ); + })} + +
{t('quota_pool.series_window')}{t('quota_pool.series_left')} + {stat.label} +
+ + + + {units.value(line.view.current)} + {line.view.tracks.length > 1 && ( + + {t('quota_pool.of_max', { max: units.value(line.view.max) })} + + )} + {hint && {hint}} + {stat.value}
+ {banked && ( +
+ +
+ )} +
+ ); + } + return (
- {windowGroups ? ( - <> - ({ - value: choice, - label: windowLabel(t, choice, windowLabels), - }))} - onChange={onWindowChange} - /> - ) : windowChoices.length > 1 ? ( - ({ - value: choice, - label: windowLabel(t, choice, windowLabels), - }))} - value={windowChoice} - onChange={onWindowChange} - /> - ) : null}
{/* Nothing read yet: the empty-state panel alone, no row of dashes. */} - {(hasData || loading) && ( -
- - ) : hasData ? ( - units.value(view.current) - ) : ( - '—' - ) - } - unit={ - // One account: "38%" says it all; "of 100%" adds nothing. - !hasData || single - ? undefined - : t('quota_pool.of_max', { max: units.value(view.max) }) - } - hint={hasData && !loading ? headlineHint : undefined} - /> -
- {stats.map((stat) => ( - - ))} -
-
- )} + {summary} {loading ? ( @@ -589,8 +574,7 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
) : (
  • {showAccounts && (
  • diff --git a/web/src/features/quota/components/QuotaPoolToolbar.tsx b/web/src/features/quota/components/QuotaPoolToolbar.tsx index 8c22f13509d..f579eb5e849 100644 --- a/web/src/features/quota/components/QuotaPoolToolbar.tsx +++ b/web/src/features/quota/components/QuotaPoolToolbar.tsx @@ -1,6 +1,6 @@ /** - * Pool chart toolbar: chart value and date range up front; the rarely - * changed burn window, future usage and per-account lines sit in a menu. + * Pool chart toolbar: the date range up front; the rarely changed burn + * window, future usage and per-account lines sit in a menu. */ import { useTranslation } from 'react-i18next'; @@ -11,10 +11,8 @@ import { DropdownMenuSeparator, } from '@/components/ui/DropdownMenu'; import { IconSlidersHorizontal } from '@/components/ui/icons'; -import { SegmentedControl } from '@/components/ui/Tabs'; import { Toolbar } from '@/components/ui/Toolbar'; import type { FutureUsage } from '../poolModel'; -import type { PoolChartMode } from './PoolChart'; import { SpanNav } from './SpanNav'; import styles from './QuotaPoolToolbar.module.scss'; @@ -28,8 +26,6 @@ const FUTURE_OPTIONS: { value: FutureUsage; key: string }[] = [ ]; export interface QuotaPoolToolbarProps { - mode: PoolChartMode; - onModeChange: (mode: PoolChartMode) => void; burnWindow: BurnWindowHours; onBurnWindowChange: (hours: BurnWindowHours) => void; futureUsage: FutureUsage; @@ -46,8 +42,6 @@ export interface QuotaPoolToolbarProps { export function QuotaPoolToolbar(props: QuotaPoolToolbarProps) { const { - mode, - onModeChange, burnWindow, onBurnWindowChange, futureUsage, @@ -114,16 +108,6 @@ export function QuotaPoolToolbar(props: QuotaPoolToolbarProps) { } > - choice !== 'five_hour') + : (() => { + const windows = history ? providerWindows(history, provider) : []; + const long = windows.filter( + (window) => window.periodHours === null || window.periodHours >= SHORT_WINDOW_HOURS + ); + return (long.length > 0 ? long : windows).map((window) => window.key); + })(); + const first = defaultPoolWindow(provider, history); + return first && choices.includes(first) + ? [first, ...choices.filter((choice) => choice !== first)] + : choices; } /* --------------------------------------------------------------------------- diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 7a7cdb235b3..ba6cf3006a9 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -1743,9 +1743,11 @@ "tooltip_left": "{{value}} left", "projected_lower": "projected", "recorded_lower": "recorded", - "chart_summary": "Pooled quota over time: {{current}} of {{max}} left.", - "chart_summary_drain": "Drain rate over time; currently {{rate}}.", - "window_label": "Quota window", + "chart_summary_series": "{{label}}: {{current}} of {{max}} left", + "empty_at_series": "{{label}} empty {{time}}", + "tooltip_series_left": "{{label}}: {{value}} left", + "series_window": "Window", + "series_left": "Left", "window_weekly": "Weekly", "window_fable": "Fable weekly", "window_five_hour": "5-hour", @@ -1757,7 +1759,6 @@ "window_span_month": "{{count}}-month", "window_scoped": "{{scope}} {{window}}", "window_unknown": "Quota window", - "window_group_label": "Quota group", "window_group_account": "Whole account", "plan_weights": "Plan weights", "plan_weights_for": "{{provider}} plan weights", @@ -1795,9 +1796,6 @@ "legend_recorded": "Recorded", "legend_projected": "Projected", "legend_accounts": "Accounts", - "mode_label": "Chart value", - "mode_remaining": "Remaining", - "mode_drain": "Drain rate", "burn_rate": "Burn rate", "future_usage": "Future usage", "future_same": "Same as now", @@ -1817,8 +1815,6 @@ "burn_window_option": "Last {{count}} hours", "range_label": "Date range", "legend_label": "Chart legend", - "legend_recorded_drain": "Recorded drain", - "legend_projected_drain": "Projected drain", "last_reading": "Last reading {{time}}", "stale": "Stale, {{duration}} old", "stale_hint": "The hub has not recorded a new reading recently. Refresh to take one.", diff --git a/web/tests/quotaPoolModel.test.ts b/web/tests/quotaPoolModel.test.ts index c7e7d671a34..5c6092f8f69 100644 --- a/web/tests/quotaPoolModel.test.ts +++ b/web/tests/quotaPoolModel.test.ts @@ -29,7 +29,7 @@ import { poolWindowChoices, providerWindowLabels, providerWindows, - resolvePoolWindow, + poolChartWindows, pooledAt, poolMax, remainingAt, @@ -568,8 +568,11 @@ describe('pools for every provider', () => { })] ); expect(defaultPoolWindow('antigravity', h)).toBe('group_gemini_models_gemini_weekly'); - expect(resolvePoolWindow('antigravity', h, 'group_claude_and_gpt_models_3p_weekly')) - .toBe('group_claude_and_gpt_models_3p_weekly'); + // One line per weekly group, Gemini first; the 5-hour window gets no line. + expect(poolChartWindows('antigravity', h)).toEqual([ + 'group_gemini_models_gemini_weekly', + 'group_claude_and_gpt_models_3p_weekly', + ]); }); test('Gemini falls back to an available window when its own models are absent', () => { @@ -589,12 +592,20 @@ describe('pools for every provider', () => { expect(defaultPoolWindow('codex')).toBe('weekly'); }); - test('a remembered choice that is no longer offered falls back to the default', () => { + test('chart lines leave out 5-hour windows and lead with the default window', () => { const h = multi(); - expect(resolvePoolWindow('xai', h, 'seven_day')).toBe('seven_day'); - expect(resolvePoolWindow('xai', h, 'fable')).toBe('monthly'); - expect(resolvePoolWindow('xai', h, undefined)).toBe('monthly'); - expect(resolvePoolWindow('claude', h, undefined)).toBe('weekly'); + expect(poolChartWindows('xai', h)).toEqual(['monthly', 'seven_day']); + expect(poolChartWindows('claude', h)).toEqual(['weekly', 'fable']); + expect(poolChartWindows('codex')).toEqual(['weekly']); + expect(poolChartWindows('antigravity', h)).toEqual(['seven_day_gemini_pro', 'image_gen']); + }); + + test('a provider that reports only a short window still gets its line', () => { + const h = history( + [{ id: 's', provider: 'muse' }], + [sample(NOW, 's', { five_hour: { used: 10, period: 5 } })] + ); + expect(poolChartWindows('muse', h)).toEqual(['five_hour']); }); test('xAI pools by the weight the hub reports per account', () => { @@ -896,7 +907,7 @@ describe('percent of the heaviest plan (owner pools)', () => { }; const view = buildPoolView(h, { provider: 'mistral', - window: resolvePoolWindow('mistral', h, undefined) as string, + window: poolChartWindows('mistral', h)[0], now: NOW, spanStart: NOW - 3 * 24 * H, spanEnd: NOW + 11 * 24 * H, @@ -1033,9 +1044,7 @@ describe('retired windows', () => { 'group_gemini_models_gemini_weekly', ]); expect(poolWindowChoices('antigravity', h)).toEqual(['group_gemini_models_gemini_weekly']); - expect( - resolvePoolWindow('antigravity', h, 'group_gemini_4_argon_gemini_argon_wtu_weekly') - ).toBe('group_gemini_models_gemini_weekly'); + expect(poolChartWindows('antigravity', h)).toEqual(['group_gemini_models_gemini_weekly']); }); test('partial reads and failed polls within six hours keep a window', () => {