From a7bda20caad21efbd3c294b2f54258e043a10bae Mon Sep 17 00:00:00 2001 From: guyu233 Date: Tue, 24 Nov 2026 18:01:10 +0800 Subject: [PATCH] fix(executor): retry transient failures in place and keep cache anchors Routing stability for cache affinity: - Retry a transient upstream hiccup once on the same account before spending a failover hop. An empty stream, a first-byte timeout, or a stream that dies before the first event usually recovers on the same worker, and switching accounts throws away the prompt cache. The retry has its own per-request budget, keeps the in-flight slot, and skips any non-transient failure. - Stop the exponential ladder from multiplying a cooldown the upstream declared itself. Transient failures are capped at 60s; a quota reset reported in the response body is used verbatim (>=1m, <=24h) instead of being clamped to the 10-minute rate-limit window, which would have retried a dead account every ten minutes. Durable failures (auth, unhinted rate limits) still escalate. - Keep a session binding through a short cooldown: failover no longer clears the anchor when the account is only cooling, and bindSession/CommitSession leave the anchor alone while its remaining cooldown is 5 minutes or less, so the next turn returns to the cache-warm account. - Default session-affinity TTL 1h -> 4h, with CLI2API_AFFINITY_TTL and CLI2API_AFFINITY_CAPACITY overrides (48h / 1M bindings hard caps). - Classify exhausted routing (503 no_accounts) and undecodable upstream bodies (502 upstream_decode_error) instead of leaking a bare 502 upstream_error. Observability, so the change can be measured: - SessionAffinityStats gains miss_reasons / escape_reasons distributions alongside the existing last-value fields. - RequestUsageTotals gains cache_hit_rate (hit / (hit + miss)), nil when no cache accounting was reported. - SeedComponents reports per-component session-seed hashes; Prepare logs them under CLI2API_AFFINITY_DEBUG so a chat that re-anchors every turn can be traced to a volatile system prefix or a changed first message. --- .../unreleased/cache-affinity-resilience.md | 17 + internal/accounts/request_logs.go | 64 +-- internal/executor/cache_affinity_test.go | 375 ++++++++++++++++++ internal/executor/chat.go | 194 +++++++-- internal/executor/chat_test.go | 2 +- internal/executor/classify.go | 68 +++- internal/executor/error.go | 9 +- internal/executor/pool.go | 19 +- internal/executor/prepare.go | 5 + internal/executor/session_affinity.go | 107 ++++- internal/store/request_logs.go | 4 + internal/store/request_logs_test.go | 40 ++ internal/translate/seed_components_test.go | 58 +++ internal/translate/session_seed.go | 43 +- 14 files changed, 933 insertions(+), 72 deletions(-) create mode 100644 changelog/unreleased/cache-affinity-resilience.md create mode 100644 internal/executor/cache_affinity_test.go create mode 100644 internal/translate/seed_components_test.go diff --git a/changelog/unreleased/cache-affinity-resilience.md b/changelog/unreleased/cache-affinity-resilience.md new file mode 100644 index 00000000..2c875325 --- /dev/null +++ b/changelog/unreleased/cache-affinity-resilience.md @@ -0,0 +1,17 @@ +### English + +- Retry a transient upstream failure once on the same account before failing over: a stream that dies before its first event or returns an empty body usually recovers on the same worker, and switching accounts throws away the whole prompt cache. +- Stop the local backoff ladder from multiplying a cooldown the upstream declared itself. Transient failures are capped at 60s, and a quota reset reported in the response body is used verbatim (bounded to 24h) instead of being clamped to the 10-minute rate-limit window or scaled up the exponential ladder. +- Keep a session anchor through a short cooldown: a failover whose anchor account is still ready and cooling for five minutes or less no longer clears the binding, so the next turn returns to the cache-warm account instead of walking the pool. +- Raise the default session-affinity TTL from 1h to 4h and expose `CLI2API_AFFINITY_TTL` / `CLI2API_AFFINITY_CAPACITY` (48h and one million bindings are the hard caps). +- Answer a request with no usable account, and an upstream body that cannot be decoded, with `503 no_accounts` / `502 upstream_decode_error` instead of an unclassified `502 upstream_error`. +- Report cache-hit and miss reason distributions (`SessionAffinityStats.miss_reasons` / `escape_reasons`), a per-total `cache_hit_rate`, and per-component session-seed hashes in the affinity debug log, so a chat that silently re-anchors every turn can be traced to a volatile system prefix or a changed first message. + +### 中文 + +- 上游瞬时失败先在同一账号重试一次再切号:首个事件之前就断流或返回空 body 的请求通常在同一 worker 上就能恢复,而换号会把整个 prompt 缓存丢掉。 +- 本地指数退避不再放大上游自己给出的冷却时间。瞬时失败封顶 60 秒;响应体里上报的 quota 重置时间按原值使用(上限 24 小时),既不被 10 分钟的限流窗口截断,也不被指数阶梯成倍放大。 +- 短冷却期间保留会话锚点:failover 时若原账号仍然 Ready 且冷却不超过 5 分钟,不再清空绑定,下一轮直接回到缓存已预热的账号,而不是重新在池子里轮转。 +- 会话亲和默认 TTL 从 1 小时提升到 4 小时,并新增 `CLI2API_AFFINITY_TTL` / `CLI2API_AFFINITY_CAPACITY`(硬上限 48 小时、一百万条绑定)。 +- 没有可用账号的请求、以及上游返回无法解码的响应体,分别返回 `503 no_accounts` 和 `502 upstream_decode_error`,不再落到未分类的 `502 upstream_error`。 +- 上报缓存命中的 miss/escape 原因分布(`SessionAffinityStats.miss_reasons` / `escape_reasons`)、按总量计算的 `cache_hit_rate`,并在亲和调试日志中输出会话指纹的分量哈希,这样"每轮都在悄悄换号"的对话可以直接定位到是 system 前缀抖动还是首条消息变了。 diff --git a/internal/accounts/request_logs.go b/internal/accounts/request_logs.go index fd074356..d2469daa 100644 --- a/internal/accounts/request_logs.go +++ b/internal/accounts/request_logs.go @@ -25,31 +25,31 @@ const ( var ErrRequestLogNotFound = errors.New("request log not found") type RequestLog struct { - ID string `json:"id"` - CreatedAt time.Time `json:"created_at"` - FinishedAt *time.Time `json:"finished_at,omitempty"` - Stream bool `json:"stream"` - Status string `json:"status"` - RequestedModel string `json:"requested_model"` - MappedModel string `json:"mapped_model,omitempty"` - RequestedReasoning string `json:"requested_reasoning,omitempty"` - ResolvedReasoning string `json:"resolved_reasoning,omitempty"` - AccountID string `json:"account_id,omitempty"` - APIKeyID string `json:"api_key_id,omitempty"` // console API key id; "" for console-key traffic and legacy rows - Provider string `json:"provider,omitempty"` - Routing string `json:"routing,omitempty"` - PromptTokens *int `json:"prompt_tokens,omitempty"` - CompletionTokens *int `json:"completion_tokens,omitempty"` - CacheReadTokens *int `json:"cache_read_tokens,omitempty"` - CacheWriteTokens *int `json:"cache_write_tokens,omitempty"` - UsageSource string `json:"usage_source,omitempty"` - Credits *float64 `json:"credits,omitempty"` - LatencyMs *int `json:"latency_ms,omitempty"` - TTFBMs *int `json:"ttfb_ms,omitempty"` - ErrorKind string `json:"error_kind,omitempty"` - ErrorCode string `json:"error_code,omitempty"` - ErrorMessage string `json:"error_message,omitempty"` - AttemptCount int `json:"attempt_count"` + ID string `json:"id"` + CreatedAt time.Time `json:"created_at"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + Stream bool `json:"stream"` + Status string `json:"status"` + RequestedModel string `json:"requested_model"` + MappedModel string `json:"mapped_model,omitempty"` + RequestedReasoning string `json:"requested_reasoning,omitempty"` + ResolvedReasoning string `json:"resolved_reasoning,omitempty"` + AccountID string `json:"account_id,omitempty"` + APIKeyID string `json:"api_key_id,omitempty"` // console API key id; "" for console-key traffic and legacy rows + Provider string `json:"provider,omitempty"` + Routing string `json:"routing,omitempty"` + PromptTokens *int `json:"prompt_tokens,omitempty"` + CompletionTokens *int `json:"completion_tokens,omitempty"` + CacheReadTokens *int `json:"cache_read_tokens,omitempty"` + CacheWriteTokens *int `json:"cache_write_tokens,omitempty"` + UsageSource string `json:"usage_source,omitempty"` + Credits *float64 `json:"credits,omitempty"` + LatencyMs *int `json:"latency_ms,omitempty"` + TTFBMs *int `json:"ttfb_ms,omitempty"` + ErrorKind string `json:"error_kind,omitempty"` + ErrorCode string `json:"error_code,omitempty"` + ErrorMessage string `json:"error_message,omitempty"` + AttemptCount int `json:"attempt_count"` // DetailExpired marks a log whose detail rows and detail-only columns were // cleared by retention. The aggregate columns (tokens, credits, latency, // status, model) are still present, so usage totals stay exact; only the @@ -276,11 +276,15 @@ type RequestUsage struct { } type RequestUsageTotals struct { - TotalTokens int64 `json:"total_tokens"` - PromptTokens int64 `json:"prompt_tokens"` - CompletionTokens int64 `json:"completion_tokens"` - CacheHitTokens int64 `json:"cache_hit_tokens"` - CacheMissTokens int64 `json:"cache_miss_tokens"` + TotalTokens int64 `json:"total_tokens"` + PromptTokens int64 `json:"prompt_tokens"` + CompletionTokens int64 `json:"completion_tokens"` + CacheHitTokens int64 `json:"cache_hit_tokens"` + CacheMissTokens int64 `json:"cache_miss_tokens"` + // CacheHitRate is CacheHitTokens / (CacheHitTokens + CacheMissTokens). Nil + // when no cache accounting was reported in the window, so a fresh install + // reads as "no data" instead of a 0% hit rate. + CacheHitRate *float64 `json:"cache_hit_rate,omitempty"` Requests int `json:"requests"` Errors int `json:"errors"` AvgLatencyMs *int `json:"avg_latency_ms,omitempty"` diff --git a/internal/executor/cache_affinity_test.go b/internal/executor/cache_affinity_test.go new file mode 100644 index 00000000..16f3fe48 --- /dev/null +++ b/internal/executor/cache_affinity_test.go @@ -0,0 +1,375 @@ +package executor + +import ( + "context" + "errors" + "net/http" + "sync" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/auth" + "github.com/caigee-cmd/cli2api/internal/providers" + "github.com/caigee-cmd/cli2api/internal/translate" +) + +// scriptedChat fails or succeeds per call index so a test can express +// "first attempt hiccups, second succeeds" without a real upstream. +type scriptedChat struct { + mu sync.Mutex + calls int + fn func(call int) (providers.ChatOutcome, error) +} + +func (s *scriptedChat) ChatNonStream(_ context.Context, _ string, req translate.ChatRequest) (providers.ChatOutcome, error) { + s.mu.Lock() + s.calls++ + call := s.calls + s.mu.Unlock() + return s.fn(call) +} + +func (s *scriptedChat) ChatStream(context.Context, string, translate.ChatRequest) (*http.Response, providers.ResolvedChat, error) { + return nil, providers.ResolvedChat{}, errors.New("stream not scripted") +} + +func (s *scriptedChat) Calls() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.calls +} + +func inProcessExecutor(t *testing.T, chat providers.ProviderChat, items ...Item) ChatExecutor { + t.Helper() + pool := NewPool(nil, nil) + for _, item := range items { + if item.Provider == "" { + item.Provider = "workbuddy" + } + if item.Region == "" { + item.Region = "cn" + } + if item.Runtime == "" { + item.Runtime = string(providers.RuntimeInProcess) + } + pool.Upsert(item) + } + registry := providers.NewRegistry() + registry.Register(providers.Adapter{ID: "workbuddy", Chat: chat}) + ex := NewChatExecutor(pool, "") + ex.Providers = registry + return ex +} + +func okOutcome(req translate.ChatRequest) (providers.ChatOutcome, error) { + return providers.ChatOutcome{Model: req.Model, Content: "ok", FinishReason: "stop"}, nil +} + +func emptyStreamErr() error { + return &providers.Error{ + Kind: accounts.KindUnavailable, Status: 200, + Message: "upstream answered 200 but the stream was empty", Code: "upstream_empty", + } +} + +func TestTransientFailureRetriesSameAccountBeforeFailover(t *testing.T) { + chat := &scriptedChat{fn: func(call int) (providers.ChatOutcome, error) { + if call == 1 { + return providers.ChatOutcome{}, emptyStreamErr() + } + return providers.ChatOutcome{Model: "glm-5.2", Content: "ok", FinishReason: "stop"}, nil + }} + ex := inProcessExecutor(t, chat, Item{ID: "wb1"}) + + ctx := WithSessionKey(context.Background(), "retry-session") + result, err := ex.ChatNonStream(ctx, translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err != nil { + t.Fatalf("err = %v", err) + } + if result.AccountID != "wb1" { + t.Fatalf("account = %q, want wb1", result.AccountID) + } + // The retry must not consume the failover budget: this request had exactly + // one candidate account. + if result.AttemptCount != 1 { + t.Fatalf("attempt count = %d, want 1", result.AttemptCount) + } + if chat.Calls() != 2 { + t.Fatalf("adapter calls = %d, want 2", chat.Calls()) + } + if bound, ok := ex.SessionAffinity.Get("retry-session"); !ok || bound != "wb1" { + t.Fatalf("binding = %q ok=%v, want wb1", bound, ok) + } +} + +func TestRateLimitIsNotRetriedOnSameAccount(t *testing.T) { + chat := &scriptedChat{fn: func(int) (providers.ChatOutcome, error) { + return providers.ChatOutcome{}, &providers.Error{ + Kind: accounts.KindRateLimit, Status: 429, + Message: "too many requests", Code: "rate_limit", RetryAfter: time.Minute, + } + }} + ex := inProcessExecutor(t, chat, Item{ID: "wb1"}) + + _, err := ex.ChatNonStream(context.Background(), translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err == nil { + t.Fatal("expected rate limit error") + } + if chat.Calls() != 1 { + t.Fatalf("adapter calls = %d, want 1 (no same-account retry for 429)", chat.Calls()) + } +} + +func TestTransientFailureDoesNotEscalateBackoff(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "a"}) + ex := NewChatExecutor(pool, "") + + for i := 0; i < 4; i++ { + ex.markClassified("a", Classified{ + Kind: accounts.KindUnavailable, Cooldown: 10 * time.Second, Transient: true, + }, "") + } + item, ok := pool.ByID("a") + if !ok { + t.Fatal("account missing") + } + if item.BackoffLevel != 0 { + t.Fatalf("backoff level = %d, want 0 for transient failures", item.BackoffLevel) + } + if remaining := time.Until(item.DownUntil); remaining > 15*time.Second { + t.Fatalf("cooldown = %s, want the classifier window, not an escalated one", remaining) + } +} + +func TestExactResetIsNotMultiplied(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "a"}) + ex := NewChatExecutor(pool, "") + + for i := 0; i < 4; i++ { + ex.markClassified("a", Classified{ + Kind: accounts.KindQuota, Cooldown: 15 * time.Minute, ExactReset: true, + }, "") + } + item, ok := pool.ByID("a") + if !ok { + t.Fatal("account missing") + } + if item.BackoffLevel != 0 { + t.Fatalf("backoff level = %d, want 0 for an authoritative reset", item.BackoffLevel) + } + if remaining := time.Until(item.DownUntil); remaining > 16*time.Minute { + t.Fatalf("cooldown = %s, want the upstream reset window", remaining) + } +} + +func TestDurableAuthFailureStillEscalates(t *testing.T) { + pool := NewPool(nil, nil) + pool.Upsert(Item{ID: "a"}) + ex := NewChatExecutor(pool, "") + + for i := 0; i < 4; i++ { + ex.markClassified("a", Classified{Kind: accounts.KindAuth, Cooldown: 30 * time.Second}, "") + } + item, ok := pool.ByID("a") + if !ok { + t.Fatal("account missing") + } + if remaining := time.Until(item.DownUntil); remaining <= 30*time.Second { + t.Fatalf("cooldown = %s, want escalation above the base window", remaining) + } +} + +func TestShortCooldownKeepsAnchorAndReturnsToOriginal(t *testing.T) { + chat := &scriptedChat{fn: func(int) (providers.ChatOutcome, error) { + return providers.ChatOutcome{Model: "glm-5.2", Content: "ok", FinishReason: "stop"}, nil + }} + ex := inProcessExecutor(t, chat, Item{ID: "a"}, Item{ID: "b"}) + ex.SessionAffinity.Bind("cache-session", "a") + // A short cooling window keeps a's prompt cache plausibly warm. + ex.Pool.MarkClassified("a", Classified{Kind: accounts.KindRateLimit, Cooldown: 30 * time.Second, Model: "glm-5.2"}) + + ctx := WithSessionKey(context.Background(), "cache-session") + first, err := ex.ChatNonStream(ctx, translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err != nil { + t.Fatalf("err = %v", err) + } + if first.AccountID != "b" { + t.Fatalf("served by %q, want the healthy sibling b", first.AccountID) + } + if bound, ok := ex.SessionAffinity.Get("cache-session"); !ok || bound != "a" { + t.Fatalf("binding = %q ok=%v, want the original anchor a", bound, ok) + } + + // Once the cooldown lifts, the chat returns to its original account. + ex.Pool.MarkOK("a", "glm-5.2") + second, err := ex.ChatNonStream(ctx, translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err != nil { + t.Fatalf("err = %v", err) + } + if second.AccountID != "a" || second.Routing != routingSticky { + t.Fatalf("second = %+v, want sticky back on a", second) + } +} + +func TestLongCooldownReanchorsToServingAccount(t *testing.T) { + chat := &scriptedChat{fn: func(int) (providers.ChatOutcome, error) { + return providers.ChatOutcome{Model: "glm-5.2", Content: "ok", FinishReason: "stop"}, nil + }} + ex := inProcessExecutor(t, chat, Item{ID: "a"}, Item{ID: "b"}) + ex.SessionAffinity.Bind("long-session", "a") + ex.Pool.MarkClassified("a", Classified{Kind: accounts.KindAuth, Cooldown: time.Hour}) + + _, err := ex.ChatNonStream(WithSessionKey(context.Background(), "long-session"), translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err != nil { + t.Fatalf("err = %v", err) + } + // A one-hour wait outlives the cached prefix, so the chat follows the + // account that actually served it. + if bound, ok := ex.SessionAffinity.Get("long-session"); !ok || bound != "b" { + t.Fatalf("binding = %q ok=%v, want b", bound, ok) + } +} + +func TestZeroCooldownFailoverStillForgets(t *testing.T) { + chat := &scriptedChat{fn: func(call int) (providers.ChatOutcome, error) { + if call <= 2 { + return providers.ChatOutcome{}, emptyStreamErr() + } + return providers.ChatOutcome{Model: "glm-5.2", Content: "ok", FinishReason: "stop"}, nil + }} + // Both accounts share one adapter, so account a fails on its retry and + // then the failover to b succeeds. + ex := inProcessExecutor(t, chat, Item{ID: "a"}, Item{ID: "b"}) + ex.SessionAffinity.Bind("cold-stream", "a") + + result, err := ex.ChatNonStream(WithSessionKey(context.Background(), "cold-stream"), translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }, "", "") + if err != nil { + t.Fatalf("err = %v", err) + } + if result.AccountID != "b" { + t.Fatalf("account = %q, want b", result.AccountID) + } + if bound, ok := ex.SessionAffinity.Get("cold-stream"); !ok || bound != "b" { + t.Fatalf("binding = %q ok=%v, want b after a zero-cooldown failure", bound, ok) + } +} + +func TestQuotaResetHintIsNotClampedToRateLimitWindow(t *testing.T) { + body := `{"error":{"message":"insufficient_quota","code":"insufficient_quota"},"resets_in_seconds":7200}` + classified := Classify(429, body, "", "", "") + if classified.Kind != accounts.KindQuota { + t.Fatalf("kind = %q, want quota", classified.Kind) + } + if classified.Cooldown < 90*time.Minute { + t.Fatalf("cooldown = %s, want the full upstream reset window", classified.Cooldown) + } + if !classified.ExactReset { + t.Fatal("quota reset from upstream must be marked ExactReset") + } +} + +func TestQuotaWithoutHintFallsBackToLocalMidnight(t *testing.T) { + classified := Classify(429, `{"error":{"message":"insufficient_quota","code":"insufficient_quota"}}`, "", "", "") + if classified.Kind != accounts.KindQuota { + t.Fatalf("kind = %q, want quota", classified.Kind) + } + if classified.Cooldown <= 0 { + t.Fatalf("cooldown = %s, want the local-midnight fallback", classified.Cooldown) + } + if classified.ExactReset { + t.Fatal("a guessed midnight fallback must not claim an exact reset") + } +} + +func TestSessionAffinityReportsReasonDistributions(t *testing.T) { + affinity := NewSessionAffinity(time.Minute, 32) + affinity.Bind("one", "a") + if _, ok := affinity.Get("one"); !ok { + t.Fatal("expected a hit") + } + affinity.Get("missing") + // Shrink the TTL before binding so the next binding is already expiring. + affinity.ttl = time.Millisecond + affinity.Bind("short", "a") + time.Sleep(5 * time.Millisecond) + affinity.Get("short") + affinity.RecordEscape("provider_cooldown") + affinity.RecordEscape("provider_cooldown") + affinity.RecordEscape("concurrency_saturated") + + stats := affinity.Stats() + if stats.MissReasons["not_found"] != 1 || stats.MissReasons["expired"] != 1 { + t.Fatalf("miss reasons = %v", stats.MissReasons) + } + if stats.EscapeReasons["provider_cooldown"] != 2 || stats.EscapeReasons["concurrency_saturated"] != 1 { + t.Fatalf("escape reasons = %v", stats.EscapeReasons) + } + if stats.Hits != 1 || stats.Misses != 2 || stats.Escapes != 3 { + t.Fatalf("counters = hits %d misses %d escapes %d", stats.Hits, stats.Misses, stats.Escapes) + } +} + +func TestPeekDoesNotCountAsHit(t *testing.T) { + affinity := NewSessionAffinity(time.Minute, 8) + affinity.Bind("s", "a") + if anchor, ok := affinity.Peek("s"); !ok || anchor != "a" { + t.Fatalf("peek = %q ok=%v", anchor, ok) + } + if stats := affinity.Stats(); stats.Hits != 0 && stats.Misses != 0 { + t.Fatalf("peek changed routing counters: %+v", stats) + } +} + +func TestResolveSessionAffinityConfigDefaultsAndOverrides(t *testing.T) { + t.Setenv("CLI2API_AFFINITY_TTL", "") + t.Setenv("CLI2API_AFFINITY_CAPACITY", "") + ttl, capacity := ResolveSessionAffinityConfig() + if ttl != 4*time.Hour || capacity != 10_000 { + t.Fatalf("defaults = %s/%d", ttl, capacity) + } + + t.Setenv("CLI2API_AFFINITY_TTL", "90m") + t.Setenv("CLI2API_AFFINITY_CAPACITY", "2048") + ttl, capacity = ResolveSessionAffinityConfig() + if ttl != 90*time.Minute || capacity != 2048 { + t.Fatalf("override = %s/%d", ttl, capacity) + } + + // Bare seconds stay supported, invalid values fall back, and the ceiling + // keeps a typo from making bindings effectively permanent. + t.Setenv("CLI2API_AFFINITY_TTL", "7200") + if ttl, _ = ResolveSessionAffinityConfig(); ttl != 2*time.Hour { + t.Fatalf("seconds override = %s", ttl) + } + t.Setenv("CLI2API_AFFINITY_TTL", "not-a-duration") + if ttl, _ = ResolveSessionAffinityConfig(); ttl != 4*time.Hour { + t.Fatalf("invalid override = %s", ttl) + } + t.Setenv("CLI2API_AFFINITY_TTL", "720h") + if ttl, _ = ResolveSessionAffinityConfig(); ttl != maxSessionAffinityTTL { + t.Fatalf("ceiling = %s", ttl) + } +} + +func TestKeyedIdentityStillIsolatesBindings(t *testing.T) { + if got := SessionKeyFor("h", auth.ConsoleIdentity(), translate.ChatRequest{ + Model: "glm-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, + }); got == "" { + t.Fatal("empty session key") + } +} diff --git a/internal/executor/chat.go b/internal/executor/chat.go index 47f7f475..ac33794c 100644 --- a/internal/executor/chat.go +++ b/internal/executor/chat.go @@ -173,15 +173,64 @@ type routingPlan struct { SessionKey string BoundAccount string PublicModel string + // Aggregate marks a request routed through a logical (virtual) model. + // Escaping such a request changes the concrete upstream model, so the + // session must follow the member that answered rather than snap back to + // a member that is merely cooling. + Aggregate bool } func (e ChatExecutor) bindSession(plan routingPlan, accountID string) { if plan.Source == routingPin || plan.SessionKey == "" || e.SessionAffinity == nil { return } + if plan.Source == routingStickyEscape && e.keepAnchorOnEscape(plan, accountID) { + return + } e.SessionAffinity.Bind(plan.SessionKey, accountID) } +// keepAnchorMaxCooldown is how long a bound account may stay unavailable +// before an escape stops preserving the anchor. Upstream prompt caches are +// measured in minutes: below this window the original account's prefix is +// still warm and returning to it is cheaper than re-anchoring, above it the +// cache is gone and the chat should follow the account that actually serves. +const keepAnchorMaxCooldown = 5 * time.Minute + +// keepAnchorOnEscape reports whether a sticky-escape should leave the existing +// binding intact. Keeping it lets the next turn return to the original account +// — and its warm prompt cache — as soon as a short cooldown lifts. A binding +// that would be wrong to keep: +// - the account is gone, disabled, or the request is aggregated (escaping +// swaps the concrete model, so the session must follow the answerer); +// - the cooldown is long enough that the cached prefix has expired anyway. +func (e ChatExecutor) keepAnchorOnEscape(plan routingPlan, accountID string) bool { + if e.SessionAffinity == nil || e.Pool == nil || plan.Aggregate { + return false + } + anchor, ok := e.SessionAffinity.Peek(plan.SessionKey) + if !ok || anchor == "" || anchor == accountID { + return false + } + item, ok := e.Pool.ByID(anchor) + if !ok { + return false + } + if item.Ready != nil && !*item.Ready { + return false + } + // Only a short, known cooldown keeps the anchor: the original account's + // prompt cache is still warm, so returning there is cheaper than + // re-anchoring. An unknown window (concurrency saturation has no resume + // time) or a long quota wait means the cached prefix is gone and the chat + // should follow the account that actually serves it. + remaining := e.Pool.RetryAfter(item, plan.PublicModel) + if remaining <= 0 || remaining > keepAnchorMaxCooldown { + return false + } + return true +} + func (e ChatExecutor) observeRouting(plan *routingPlan, accountID string) { if plan == nil || plan.Source != routingSticky || plan.BoundAccount == "" { return @@ -228,7 +277,12 @@ func (e ChatExecutor) CommitSession(ctx context.Context, req translate.ChatReque if routing == routingPin || e.SessionAffinity == nil { return } - e.SessionAffinity.Bind(resolveSessionKey(ctx, req), accountID) + key := resolveSessionKey(ctx, req) + plan := routingPlan{Source: routing, SessionKey: key, PublicModel: req.Model} + if routing == routingStickyEscape && e.keepAnchorOnEscape(plan, accountID) { + return + } + e.SessionAffinity.Bind(key, accountID) } func itemProvider(item Item) string { @@ -258,10 +312,10 @@ func (e ChatExecutor) prepareRouting(ctx context.Context, prefer, providerFilter providerFilter = strings.ToLower(strings.TrimSpace(providerFilter)) publicModel := req.Model if prefer != "" { - return prefer, providerFilter, "", routingPlan{Source: routingPin, PublicModel: publicModel} + return prefer, providerFilter, "", routingPlan{Source: routingPin, PublicModel: publicModel, Aggregate: plan != nil} } - planRoute := routingPlan{Source: routingPool, SessionKey: resolveSessionKey(ctx, req), PublicModel: publicModel} + planRoute := routingPlan{Source: routingPool, SessionKey: resolveSessionKey(ctx, req), PublicModel: publicModel, Aggregate: plan != nil} if planRoute.SessionKey == "" || e.SessionAffinity == nil || e.Pool == nil { return "", providerFilter, "", planRoute } @@ -294,6 +348,7 @@ func (e ChatExecutor) prepareRouting(ctx context.Context, prefer, providerFilter } return item.ID, itemProvider(item), accounts.NormalizeRegion(item.Region), routingPlan{ Source: routingSticky, SessionKey: planRoute.SessionKey, BoundAccount: item.ID, PublicModel: publicModel, + Aggregate: plan != nil, } } @@ -301,11 +356,12 @@ func NewChatExecutor(pool *Pool, workerKey string) ChatExecutor { if pool == nil { pool = NewPool(nil, nil) } + affinityTTL, affinityCapacity := ResolveSessionAffinityConfig() return ChatExecutor{ Pool: pool, WorkerKey: strings.TrimSpace(workerKey), MaxAttempts: 4, - SessionAffinity: NewSessionAffinity(defaultSessionAffinityTTL, defaultSessionAffinityCapacity), + SessionAffinity: NewSessionAffinity(affinityTTL, affinityCapacity), HTTPClient: &http.Client{ Timeout: 120 * time.Second, }, @@ -961,8 +1017,19 @@ type routeLoop struct { // excluded. tierAttempts map[int]int tierBudget int + // sameAccountRetries counts how many transient same-account retries this + // request has already spent. It is a separate budget from attempts: a + // retry on the same account must not consume a failover hop, because + // attemptsFor already caps attempts at the number of candidate accounts. + sameAccountRetries int } +// maxSameAccountRetries bounds same-account retries per request. One is enough: +// the transient cases are empty/heartbeat-only streams and a first-byte +// timeout, where a second identical attempt almost always succeeds, and +// more retries would stack latency ahead of a real failover. +const maxSameAccountRetries = 1 + func (e ChatExecutor) newRouteLoop(ctx context.Context, prefer, providerFilter string, req translate.ChatRequest) routeLoop { aggPlan := aggregatePlanFrom(ctx) prefer, providerFilter, regionFilter, routing := e.prepareRouting(ctx, prefer, providerFilter, req, aggPlan) @@ -989,10 +1056,10 @@ func (e ChatExecutor) newRouteLoop(ctx context.Context, prefer, providerFilter s } } prefer = "" - routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model} + routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model, Aggregate: true} default: prefer = "" - routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model} + routing = routingPlan{Source: routingPool, SessionKey: routing.SessionKey, PublicModel: req.Model, Aggregate: true} } } // A model-name region prefix (e.g. "workbuddy-cn/model") sets an explicit @@ -1145,6 +1212,23 @@ func (l routeLoop) canFailover(classified Classified) bool { return classified.Failover && l.index < l.attempts } +// canSameAccountRetry reports whether this failure may be retried once on the +// account that produced it. Only transient upstream hiccups qualify, and only +// while the caller is still connected: retrying after the client left would +// burn an upstream slot for nothing. +func (l *routeLoop) canSameAccountRetry(ctx context.Context, classified Classified) bool { + if l.sameAccountRetries >= maxSameAccountRetries { + return false + } + if !classified.Transient { + return false + } + if ctx != nil && ctx.Err() != nil { + return false + } + return true +} + func (l *routeLoop) exclude(item Item) { l.excluded[item.ID] = struct{}{} // A cross-provider route (no explicit provider filter) must be able to @@ -1166,20 +1250,27 @@ func (l *routeLoop) exclude(item Item) { // next pick can leave the first supplier's region. Provider-scoped routes keep // their region pin. // -// A sticky binding is invalidated on failover (401/429/5xx and other -// failover-classified failures), including after a sticky escape. The next -// request then rebinds to a healthy account instead of retrying the dead one -// first; a successfully retried request rebinds through bindSession. This -// mirrors mature gateways' session affinity: sticky on the cache-hit path, -// failover invalidates the binding. -func (l *routeLoop) failover(e ChatExecutor, item Item) { +// The session binding survives a cooldown-carrying failure: the account is +// parked, not dead, and the next request should fall through to a sibling and +// then return to the original account (and its warm prompt cache). A failure +// that leaves no cooldown invalidates the binding instead, because retrying +// that account first next turn would fail identically. +func (l *routeLoop) failover(e ChatExecutor, item Item, classified Classified) { l.exclude(item) l.noteTierFailure(e, item) // Any non-pin route that already carries a session key can have a stale // binding (including a sticky-escape that started on another account). - // Invalidate it so the next turn does not retry the failed account first. + // + // A cooling account is only temporarily unavailable. Keep the binding so + // the next turn's PreferAccount falls through to a healthy sibling now and + // returns to the original account — and its warm prompt cache — once the + // cooldown lifts. Only a failure that leaves no cooldown (a cold upstream + // or a model this account does not serve) invalidates the anchor, because + // retrying it first next turn would just fail the same way. if l.routing.Source != routingPin && l.routing.SessionKey != "" && e.SessionAffinity != nil { - e.SessionAffinity.Forget(l.routing.SessionKey) + if classified.Cooldown <= 0 { + e.SessionAffinity.Forget(l.routing.SessionKey) + } } } @@ -1296,7 +1387,23 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque } release := func() { e.releaseInFlight(loop.requestID, poolID) } if isInProcessItem(item) || e.qoderDirect(item) { - result, classified, err := e.chatInProcessNonStreamAttempt(ctx, item, loop.dispatchRequest(item, req), i) + // Retry a transient upstream hiccup once on the same account before + // spending a failover hop. The prompt cache is still warm here, so a + // same-account retry usually succeeds and keeps the turn on the + // account the session is anchored to. + dispatch := loop.dispatchRequest(item, req) + var result ChatResult + var classified Classified + var err error + for { + result, classified, err = e.chatInProcessNonStreamAttempt(ctx, item, dispatch, i) + if err == nil || !loop.canSameAccountRetry(ctx, classified) { + break + } + loop.sameAccountRetries++ + log.Printf("chat same-account retry request_id=%q account=%q code=%q kind=%q retry=%d", + loop.requestID, poolID, classified.Code, classified.Kind, loop.sameAccountRetries) + } if err == nil { result.AttemptCount = i + 1 e.observeRouting(&loop.routing, poolID) @@ -1314,7 +1421,7 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque } if loop.canFailover(classified) { release() - loop.failover(e, item) + loop.failover(e, item, classified) continue } release() @@ -1352,7 +1459,7 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque Status: accounts.AttemptStatusFailover, ErrorKind: classified.Kind, ErrorMessage: loop.lastErr.Error(), LatencyMs: &latency, }) release() - loop.failover(e, item) + loop.failover(e, item, classified) continue } // Non-stream worker responses are buffered whole; cap them so a @@ -1377,7 +1484,7 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque status := accounts.AttemptStatusError if loop.canFailover(classified) { status = accounts.AttemptStatusFailover - loop.failover(e, poolItem) + loop.failover(e, poolItem, classified) e.recordAttempt(ctx, accounts.RequestAttempt{ AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, @@ -1396,13 +1503,23 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque } result, err := decodeChatResult(req, body) if err != nil { + // A body this account answered with but this gateway cannot decode is + // an upstream protocol failure, not a routing miss. Classify it here + // so the HTTP layer does not fall back to a bare 502 "upstream_error" + // for a problem that is already understood. + classified := Classified{ + Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, + Code: "upstream_decode_error", Type: "api_error", Message: err.Error(), + } + loop.lastErr = NewExecutionError(classified, err) + e.markClassified(poolID, classified, loop.attemptModel(item, req)) e.recordAttempt(ctx, accounts.RequestAttempt{ AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, Status: accounts.AttemptStatusError, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: accounts.KindUnavailable, ErrorMessage: truncateErr(err.Error()), LatencyMs: &latency, }) release() - return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, err + return ChatResult{AttemptCount: i + 1, AccountID: item.ID, Provider: loop.resultProvider(item)}, loop.lastErr } result.AccountID = item.ID result.Provider = loop.resultProvider(item) @@ -1424,7 +1541,11 @@ func (e ChatExecutor) ChatNonStream(ctx context.Context, req translate.ChatReque return result, nil } if loop.lastErr == nil { - loop.lastErr = fmt.Errorf("no worker accounts available") + // Exhausting the loop without a selected account is a routing outcome, + // not an origin outage. Report it with the routing taxonomy (503 + + // Retry-After) instead of handing the HTTP layer a bare error it would + // render as 502 upstream_error. + loop.lastErr = noAccountsError("no worker accounts available") } return ChatResult{AttemptCount: loop.attempts}, loop.lastErr } @@ -1808,7 +1929,22 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq } release := func() { e.releaseInFlight(loop.requestID, poolID) } if isInProcessItem(item) || (e.qoderDirect(item) && !(preferNativeResponses && native != nil)) { - result, classified, err := e.chatInProcessStreamAttempt(ctx, item, loop.dispatchRequest(item, req), native, i, preferNativeResponses) + dispatch := loop.dispatchRequest(item, req) + var result StreamResult + var classified Classified + var err error + for { + result, classified, err = e.chatInProcessStreamAttempt(ctx, item, dispatch, native, i, preferNativeResponses) + if err == nil || !loop.canSameAccountRetry(ctx, classified) { + break + } + // Nothing has been relayed to the client: the attempt failed + // before the first meaningful event, so a same-account retry is + // both safe and cache-warm. + loop.sameAccountRetries++ + log.Printf("chat stream same-account retry request_id=%q account=%q code=%q kind=%q retry=%d", + loop.requestID, poolID, classified.Code, classified.Kind, loop.sameAccountRetries) + } if err == nil { result.AttemptCount = i + 1 @@ -1829,7 +1965,7 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq } if loop.canFailover(classified) { release() - loop.failover(e, item) + loop.failover(e, item, classified) continue } release() @@ -1867,7 +2003,7 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq Status: accounts.AttemptStatusFailover, ErrorKind: classified.Kind, ErrorMessage: loop.lastErr.Error(), LatencyMs: &latency, }) release() - loop.failover(e, item) + loop.failover(e, item, classified) continue } if account := resp.Header.Get("X-Qoder-Account"); account != "" { @@ -1891,7 +2027,7 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq status := accounts.AttemptStatusError if loop.canFailover(classified) { status = accounts.AttemptStatusFailover - loop.failover(e, poolItem) + loop.failover(e, poolItem, classified) e.recordAttempt(ctx, accounts.RequestAttempt{ AttemptIndex: i, AccountID: item.ID, StartedAt: started, FinishedAt: &finished, Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, @@ -1938,7 +2074,7 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq Status: status, HTTPStatus: ptrInt(resp.StatusCode), ErrorKind: classified.Kind, ErrorMessage: truncateErr(probeErr.Error()), LatencyMs: &latency, }) - loop.failover(e, poolItem) + loop.failover(e, poolItem, classified) release() continue } @@ -1976,7 +2112,11 @@ func (e ChatExecutor) chatStreamProxy(ctx context.Context, req translate.ChatReq }, nil } if loop.lastErr == nil { - loop.lastErr = fmt.Errorf("no worker accounts available") + // Exhausting the loop without a selected account is a routing outcome, + // not an origin outage. Report it with the routing taxonomy (503 + + // Retry-After) instead of handing the HTTP layer a bare error it would + // render as 502 upstream_error. + loop.lastErr = noAccountsError("no worker accounts available") } return StreamResult{AttemptCount: loop.attempts}, loop.lastErr } diff --git a/internal/executor/chat_test.go b/internal/executor/chat_test.go index a2ae876f..e28bd1cc 100644 --- a/internal/executor/chat_test.go +++ b/internal/executor/chat_test.go @@ -289,7 +289,7 @@ func TestRouteFailoverKeepsAttemptBudgetAndCrossesRegion(t *testing.T) { t.Fatalf("attempt budget shrank after region pin: %d", loop.attempts) } - loop.failover(e, first) + loop.failover(e, first, Classified{Kind: "unavailable"}) second, _, err := loop.pickNext(e, "shared") if err != nil { t.Fatalf("failover pick: %v", err) diff --git a/internal/executor/classify.go b/internal/executor/classify.go index 6104f1c0..6ceaf70c 100644 --- a/internal/executor/classify.go +++ b/internal/executor/classify.go @@ -25,6 +25,17 @@ type Classified struct { // Model scopes the cooldown to one public model. When set, only that // model is cooled; the account keeps serving everything else. Model string + // Transient marks an upstream hiccup that says nothing about the account's + // credential, quota, or rate limit: an empty stream, a stream that died + // mid-body, or a first-byte timeout. A transient failure may be retried on + // the same account, and it must never escalate the cooldown ladder — one + // flaky turn would otherwise park a healthy account for minutes. + Transient bool + // ExactReset marks a cooldown taken verbatim from an upstream hint + // (Retry-After header/body or a quota reset time). The exponential ladder + // must not multiply it: the upstream already said when it recovers, and + // doubling that parks the account past the real reset. + ExactReset bool } // backoffFloor and backoffCeiling bound the exponential backoff applied to @@ -34,6 +45,11 @@ const ( backoffFloor = 30 * time.Second backoffCeiling = 6 * time.Hour backoffMaxLevel = BackoffMaxLevel + // transientCooldownCap bounds how long a transient upstream hiccup may + // park an account. The classifier's own window (10s for a first-byte + // timeout) is the intent; this cap only guards against a caller handing a + // transient classification a wider window by mistake. + transientCooldownCap = 60 * time.Second ) func nextBackoffCooldown(base time.Duration, level int) (time.Duration, int) { @@ -62,14 +78,35 @@ func ParseRetryAfter(raw string, fallback time.Duration) time.Duration { } func ParseRetryAfterHint(body, header string, fallback time.Duration) time.Duration { + if hint, ok := parseUpstreamRetryHint(body, header); ok { + return hint + } + return clampRetryAfter(fallback) +} + +// parseUpstreamRetryHint returns only a hint the upstream actually sent. +// Unlike ParseRetryAfterHint it never substitutes a local fallback, so callers +// can tell "the upstream told us when it recovers" from "we guessed". +func parseUpstreamRetryHint(body, header string) (time.Duration, bool) { + raw, ok := parseUpstreamRetryHintRaw(body, header) + if !ok { + return 0, false + } + return clampRetryAfter(raw), true +} + +// parseUpstreamRetryHintRaw is parseUpstreamRetryHint without the general +// retry-after ceiling. Quota resets are legitimately hours away and must not be +// shortened to a rate-limit window. +func parseUpstreamRetryHintRaw(body, header string) (time.Duration, bool) { now := time.Now() if parsed := parseRetryAfterValue(header, now); parsed > 0 { - return clampRetryAfter(parsed) + return parsed, true } if parsed := retryAfterFromBody(body, now); parsed > 0 { - return clampRetryAfter(parsed) + return parsed, true } - return clampRetryAfter(fallback) + return 0, false } func parseRetryAfterValue(raw string, now time.Time) time.Duration { @@ -200,6 +237,12 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class } out := Classified{Kind: kind, Message: strings.TrimSpace(msg), Code: firstNonEmpty(code, kind), Type: firstNonEmpty(typ, "api_error")} + // A hint the upstream actually sent is authoritative: use it verbatim and + // never let the local backoff ladder multiply it. + _, hasHint := parseUpstreamRetryHint(body, retryAfter) + if hasHint { + out.ExactReset = true + } switch kind { case KindQuota: out.Status = 429 @@ -208,7 +251,22 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class // When every account is exhausted the route itself stops with // insufficient_quota (see quotaBlockedMessage / coolingPickError). out.Failover = true - out.Cooldown = NextLocalMidnightCooldown() + // A parsed upstream reset beats the local-midnight fallback, but only + // when it is long enough to be a real reset window. The generic hint + // path clamps at maxRetryAfter (10m) for rate limits; applying that cap + // to a multi-hour quota reset would retry a dead account every ten + // minutes. A short hint (a transient blip reported as quota) falls back + // to the local rollover, which is the safer park. + if raw, ok := parseUpstreamRetryHintRaw(body, retryAfter); ok && raw >= time.Minute { + if raw > 24*time.Hour { + raw = 24 * time.Hour + } + out.Cooldown = raw + out.ExactReset = true + } else { + out.Cooldown = NextLocalMidnightCooldown() + out.ExactReset = false + } out.Code = firstNonEmpty(code, "insufficient_quota") out.Type = "insufficient_quota" case KindRateLimit: @@ -222,12 +280,14 @@ func Classify(status int, body, retryAfter, kindHint, failoverHint string) Class out.Failover = false out.Cooldown = 0 out.RetryAfter = ParseRetryAfterHint(body, retryAfter, 0) + out.ExactReset = false break } out.Failover = true out.Cooldown = ParseRetryAfterHint(body, retryAfter, 60*time.Second) if out.Cooldown > 0 && out.Cooldown < minRateLimitCooldown { out.Cooldown = minRateLimitCooldown + out.ExactReset = false } case KindAuth: if status == 401 { diff --git a/internal/executor/error.go b/internal/executor/error.go index d9d3247c..10466af3 100644 --- a/internal/executor/error.go +++ b/internal/executor/error.go @@ -78,6 +78,9 @@ func newUnavailableStreamError(code, message string, status int, cause error) er classified.Message = message classified.Status = status classified.Type = "api_error" + // A stream that ended without [DONE] or broke mid-read is an upstream + // hiccup, not proof that this account's credential or quota is broken. + classified.Transient = true return NewExecutionError(classified, cause) } @@ -98,7 +101,7 @@ func ClassifyError(err error) Classified { return Classified{ Kind: accounts.KindUnavailable, Status: http.StatusBadGateway, Failover: true, Cooldown: 10 * time.Second, RetryAfter: 10 * time.Second, - Code: "first_byte_timeout", Message: err.Error(), + Code: "first_byte_timeout", Message: err.Error(), Transient: true, } } if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { @@ -179,6 +182,7 @@ func ClassifyError(err error) Classified { // another account serves the turn, but never cool this one down. classified.Failover = true classified.Cooldown = 0 + classified.Transient = true } switch classified.Kind { case accounts.KindRateLimit: @@ -187,8 +191,10 @@ func ClassifyError(err error) Classified { classified.Cooldown = 5 * time.Minute case providerErr.RetryAfter > 0: classified.Cooldown = providerErr.RetryAfter + classified.ExactReset = true if classified.Cooldown < 30*time.Second { classified.Cooldown = 30 * time.Second + classified.ExactReset = false } } case accounts.KindQuota: @@ -196,6 +202,7 @@ func ClassifyError(err error) Classified { // Quota stays account-wide; Classify already marks it for failover. if providerErr.RetryAfter > 0 { classified.Cooldown = providerErr.RetryAfter + classified.ExactReset = true } } classified.RetryAfter = classified.Cooldown diff --git a/internal/executor/pool.go b/internal/executor/pool.go index 91330ea2..c3ed17fe 100644 --- a/internal/executor/pool.go +++ b/internal/executor/pool.go @@ -1266,8 +1266,14 @@ func (p *Pool) MarkClassified(id string, c Classified) { // interval. A new failure kind starts the ladder over. Backoff is // tracked per model when the cooldown is model-scoped, so one // model's repeat failures don't inflate another model's ladder. + // Escalation is only for failures that say something durable about + // the account. A transient upstream hiccup (empty stream, first-byte + // timeout) and an upstream-supplied reset time are already accurate, + // so multiplying them parks a healthy account well past recovery. + escalate := !c.Transient && !c.ExactReset && c.Kind != KindInvalidRequest level := 0 - if prevKind == c.Kind && c.Kind != KindInvalidRequest { + switch { + case prevKind == c.Kind && escalate: if model != "" { if p.items[i].ModelBackoff == nil { p.items[i].ModelBackoff = map[string]int{} @@ -1282,7 +1288,11 @@ func (p *Pool) MarkClassified(id string, c Classified) { } level = p.items[i].BackoffLevel } - } else { + case !escalate: + // Leave the ladder untouched. Resetting it on a transient blip + // would erase an earned level for the durable failure that + // follows, and bumping it would punish a healthy account. + default: // New kind: reset that ladder so it starts over. if model != "" { if p.items[i].ModelBackoff == nil { @@ -1294,7 +1304,10 @@ func (p *Pool) MarkClassified(id string, c Classified) { } } cooldown := c.Cooldown - if level > 1 { + if c.Transient && cooldown > transientCooldownCap { + cooldown = transientCooldownCap + } + if escalate && level > 1 { cooldown, _ = nextBackoffCooldown(c.Cooldown, level-1) } until := time.Now().Add(cooldown) diff --git a/internal/executor/prepare.go b/internal/executor/prepare.go index d1af9da2..5fe80cef 100644 --- a/internal/executor/prepare.go +++ b/internal/executor/prepare.go @@ -223,8 +223,13 @@ func (e ChatExecutor) Prepare(in PrepareInput) (PreparedRequest, error) { } else if sessionKeyFor("", "", in.Identity, request) == "" && MessageStatShards() > 0 { source = "shard" } + // The component hashes answer the question a bare key cannot: when a + // chat re-anchors every turn, which part of the request moved? + parts := translate.SeedComponents(request) log.Printf("session affinity request_id=%q source=%q key=%q model=%q tools=%t msgs=%d", requestID, source, shortSessionKey(sessionKey), request.Model, len(request.Tools) > 0, len(request.Messages)) + log.Printf("session affinity components request_id=%q key=%q model_hash=%q tools_hash=%q prefix_hash=%q first_user_hash=%q", + requestID, shortSessionKey(sessionKey), parts.Model, parts.Tools, parts.Prefix, parts.FirstUser) } return PreparedRequest{ Context: ctx, diff --git a/internal/executor/session_affinity.go b/internal/executor/session_affinity.go index a4152b38..d0d7eec9 100644 --- a/internal/executor/session_affinity.go +++ b/internal/executor/session_affinity.go @@ -5,6 +5,8 @@ import ( "context" "crypto/sha256" "encoding/hex" + "os" + "strconv" "strings" "sync" "time" @@ -13,8 +15,16 @@ import ( ) const ( - defaultSessionAffinityTTL = time.Hour + // defaultSessionAffinityTTL bounds how long a chat stays pinned to one + // account. A working session routinely idles longer than an hour between + // turns, and every expired binding costs one full prompt-cache rebuild, so + // the default matches a working half-day rather than a coffee break. + defaultSessionAffinityTTL = 4 * time.Hour defaultSessionAffinityCapacity = 10_000 + // maxSessionAffinityTTL keeps an operator override from turning the LRU + // into durable account state by accident. + maxSessionAffinityTTL = 48 * time.Hour + maxSessionAffinityCapacity = 1_000_000 ) type sessionKeyContextKey struct{} @@ -67,6 +77,13 @@ type SessionAffinityStats struct { LastEscapeAt string `json:"last_escape_at,omitempty"` LastEscapeReason string `json:"last_escape_reason,omitempty"` LastMissReason string `json:"last_miss_reason,omitempty"` + // MissReasons and EscapeReasons are distributions, not single samples. + // A cache-hit regression is diagnosed by which reason dominates: a rising + // "expired" count is a TTL problem, "account_missing"/"model_unavailable" + // is a pool problem, and "upstream_failover" is the failover path eating + // affinity. The last-value fields above stay for older console builds. + MissReasons map[string]int `json:"miss_reasons,omitempty"` + EscapeReasons map[string]int `json:"escape_reasons,omitempty"` } // SessionAffinity is a bounded process-local LRU. Session bindings are a @@ -85,6 +102,8 @@ type SessionAffinity struct { lastEscapeAt time.Time lastEscapeReason string lastMissReason string + missReasons map[string]int + escapeReasons map[string]int } func NewSessionAffinity(ttl time.Duration, capacity int) *SessionAffinity { @@ -95,13 +114,50 @@ func NewSessionAffinity(ttl time.Duration, capacity int) *SessionAffinity { capacity = defaultSessionAffinityCapacity } return &SessionAffinity{ - ttl: ttl, - capacity: capacity, - entries: make(map[string]*list.Element, capacity), - lru: list.New(), + ttl: ttl, + capacity: capacity, + entries: make(map[string]*list.Element, capacity), + lru: list.New(), + missReasons: map[string]int{}, + escapeReasons: map[string]int{}, } } +// ResolveSessionAffinityConfig reads the optional operator overrides. Both +// knobs are deliberately env-only: they describe host capacity, not per-route +// behaviour, and a wrong value must never be persisted into a shared store. +func ResolveSessionAffinityConfig() (time.Duration, int) { + ttl := defaultSessionAffinityTTL + if raw := strings.TrimSpace(os.Getenv("CLI2API_AFFINITY_TTL")); raw != "" { + parsed, err := time.ParseDuration(raw) + if err != nil { + // A bare integer is accepted as seconds so `CLI2API_AFFINITY_TTL=14400` + // does not silently fall back to the default. + if seconds, convErr := strconv.Atoi(raw); convErr == nil { + parsed = time.Duration(seconds) * time.Second + } else { + parsed = 0 + } + } + if parsed > 0 { + if parsed > maxSessionAffinityTTL { + parsed = maxSessionAffinityTTL + } + ttl = parsed + } + } + capacity := defaultSessionAffinityCapacity + if raw := strings.TrimSpace(os.Getenv("CLI2API_AFFINITY_CAPACITY")); raw != "" { + if n, err := strconv.Atoi(raw); err == nil && n > 0 { + if n > maxSessionAffinityCapacity { + n = maxSessionAffinityCapacity + } + capacity = n + } + } + return ttl, capacity +} + func (a *SessionAffinity) Get(key string) (string, bool) { if a == nil { return "", false @@ -116,6 +172,7 @@ func (a *SessionAffinity) Get(key string) (string, bool) { if !ok { a.misses++ a.lastMissReason = "not_found" + a.missReasons["not_found"]++ return "", false } binding := element.Value.(sessionBinding) @@ -123,6 +180,7 @@ func (a *SessionAffinity) Get(key string) (string, bool) { a.remove(element) a.misses++ a.lastMissReason = "expired" + a.missReasons["expired"]++ return "", false } a.hits++ @@ -130,6 +188,31 @@ func (a *SessionAffinity) Get(key string) (string, bool) { return binding.accountID, true } +// Peek reads a binding without counting a hit. Callers that only ask "who is +// this session anchored to?" (bind-time decisions) must not inflate the hit +// rate, which is a routing-quality signal. +func (a *SessionAffinity) Peek(key string) (string, bool) { + if a == nil { + return "", false + } + key = strings.TrimSpace(key) + if key == "" { + return "", false + } + a.mu.Lock() + defer a.mu.Unlock() + element, ok := a.entries[key] + if !ok { + return "", false + } + binding := element.Value.(sessionBinding) + if !binding.expiresAt.After(time.Now()) { + a.remove(element) + return "", false + } + return binding.accountID, true +} + func (a *SessionAffinity) Bind(key, accountID string) { if a == nil { return @@ -165,6 +248,7 @@ func (a *SessionAffinity) RecordEscape(reason string) { a.escapes++ a.lastEscapeAt = time.Now().UTC() a.lastEscapeReason = strings.TrimSpace(reason) + a.escapeReasons[strings.TrimSpace(reason)]++ a.mu.Unlock() } @@ -184,7 +268,20 @@ func (a *SessionAffinity) Stats() SessionAffinityStats { Escapes: a.escapes, Rebindings: a.rebindings, LastEscapeAt: lastAt, LastEscapeReason: a.lastEscapeReason, LastMissReason: a.lastMissReason, + MissReasons: cloneReasonCounts(a.missReasons), + EscapeReasons: cloneReasonCounts(a.escapeReasons), + } +} + +func cloneReasonCounts(src map[string]int) map[string]int { + if len(src) == 0 { + return nil + } + dst := make(map[string]int, len(src)) + for reason, count := range src { + dst[reason] = count } + return dst } func (a *SessionAffinity) Forget(key string) { diff --git a/internal/store/request_logs.go b/internal/store/request_logs.go index c249b678..08f99d03 100644 --- a/internal/store/request_logs.go +++ b/internal/store/request_logs.go @@ -250,6 +250,10 @@ FROM request_logs`+where, args...) if usage.Totals.CacheMissTokens < 0 { usage.Totals.CacheMissTokens = 0 } + if cacheTokens := usage.Totals.CacheHitTokens + usage.Totals.CacheMissTokens; cacheTokens > 0 { + rate := float64(usage.Totals.CacheHitTokens) / float64(cacheTokens) + usage.Totals.CacheHitRate = &rate + } usage.Totals.AvgLatencyMs = roundedNullInt(avgLatency) if usage.Totals.Requests > 0 { usage.Totals.SuccessRate = float64(usage.Totals.Requests-usage.Totals.Errors) / float64(usage.Totals.Requests) diff --git a/internal/store/request_logs_test.go b/internal/store/request_logs_test.go index bfc3bdcc..e2dfd30d 100644 --- a/internal/store/request_logs_test.go +++ b/internal/store/request_logs_test.go @@ -890,3 +890,43 @@ func TestSummarizeModelCostsUsesServedModel(t *testing.T) { }) } } + +func TestSummarizeRequestUsageReportsCacheHitRate(t *testing.T) { + ctx := context.Background() + store, err := OpenStore(filepath.Join(t.TempDir(), "qoder.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + + base := time.Date(2026, 10, 2, 12, 0, 0, 0, time.UTC) + iptr := func(v int) *int { return &v } + insert := func(id string, at time.Time, prompt, cacheRead int) { + t.Helper() + if err := store.InsertRequestLog(ctx, accounts.RequestLog{ + ID: id, CreatedAt: at, Status: accounts.RequestStatusOK, + RequestedModel: "glm", PromptTokens: iptr(prompt), CacheReadTokens: iptr(cacheRead), + }); err != nil { + t.Fatal(err) + } + } + insert("req_hit", base, 1000, 900) + insert("req_miss", base.Add(time.Minute), 1000, 0) + + usage, err := store.SummarizeRequestUsage(ctx, base.Add(-time.Minute), base.Add(time.Hour), "") + if err != nil { + t.Fatal(err) + } + if usage.Totals.CacheHitRate == nil { + t.Fatal("cache hit rate missing") + } + if got := *usage.Totals.CacheHitRate; got < 0.44 || got > 0.46 { + t.Fatalf("cache hit rate = %v, want 0.45", got) + } + if usage.Totals.CacheHitTokens != 900 || usage.Totals.CacheMissTokens != 1100 { + t.Fatalf("hit/miss = %d/%d", usage.Totals.CacheHitTokens, usage.Totals.CacheMissTokens) + } + if usage.Totals.CacheHitRate != nil && (usage.Totals.Requests != 2) { + t.Fatalf("requests = %d", usage.Totals.Requests) + } +} diff --git a/internal/translate/seed_components_test.go b/internal/translate/seed_components_test.go new file mode 100644 index 00000000..574c3c02 --- /dev/null +++ b/internal/translate/seed_components_test.go @@ -0,0 +1,58 @@ +package translate + +import "testing" + +// TestSeedComponentsExposePerComponentHash pins the diagnostic split used by +// the affinity debug log: each seed component must move independently, so an +// operator can tell a volatile system prefix from a changed model or a new +// first message. Tool reorder invariance is covered where the tools order is +// normalized, not here. +func TestSeedComponentsExposePerComponentHash(t *testing.T) { + base := ChatRequest{ + Model: "glm-5.2", + Messages: []ChatMessage{ + {Role: "system", Content: "stable prefix"}, + {Role: "user", Content: "first question"}, + }, + } + baseParts := SeedComponents(base) + if baseParts.Model == "" || baseParts.Prefix == "" || baseParts.FirstUser == "" { + t.Fatalf("components missing: %+v", baseParts) + } + + otherModel := base + otherModel.Model = "deepseek-v4.1-flash" + got := SeedComponents(otherModel) + if got.Model == baseParts.Model { + t.Fatal("model change did not move the model component") + } + if got.Prefix != baseParts.Prefix || got.FirstUser != baseParts.FirstUser { + t.Fatalf("model change moved unrelated components: %+v", got) + } + + volatilePrefix := base + volatilePrefix.Messages = []ChatMessage{ + {Role: "system", Content: "today is 2026-11-24 17:45:03"}, + {Role: "user", Content: "first question"}, + } + got = SeedComponents(volatilePrefix) + if got.Prefix == baseParts.Prefix { + t.Fatal("prefix change did not move the prefix component") + } + if got.FirstUser != baseParts.FirstUser { + t.Fatalf("prefix change moved the first-user component: %+v", got) + } +} + +// TestSeedComponentsMissingWithoutUserAnchor keeps the "no user message means +// no session key" invariant visible: reporting all-zero components matches an +// empty ContentSessionSeed. +func TestSeedComponentsMissingWithoutUserAnchor(t *testing.T) { + parts := SeedComponents(ChatRequest{ + Model: "glm-5.2", + Messages: []ChatMessage{{Role: "system", Content: "only a prefix"}}, + }) + if parts != (SessionSeedComponents{}) { + t.Fatalf("components = %+v, want zero value", parts) + } +} diff --git a/internal/translate/session_seed.go b/internal/translate/session_seed.go index e22599fb..a1ac90d2 100644 --- a/internal/translate/session_seed.go +++ b/internal/translate/session_seed.go @@ -261,7 +261,6 @@ func compactSessionJSON(raw json.RawMessage) string { return compact.String() } - // PrefixSessionSeed is the cache-affine part of ContentSessionSeed: model, // tools and the leading system/developer prefix only. It deliberately excludes // the first user message so workbuddy2api-hub-style sharding does not scatter @@ -287,3 +286,45 @@ func PrefixSessionSeed(req ChatRequest) string { sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]) } + +// SessionSeedComponents exposes the per-component hashes behind +// ContentSessionSeed. Routing only needs the combined hash; diagnostics need +// this split to answer "which part of the request moved", because a chat that +// silently re-anchors every turn is usually carrying a volatile timestamp in +// its system prefix or reordering its tool list. +type SessionSeedComponents struct { + Model string `json:"model"` + Tools string `json:"tools"` + Prefix string `json:"prefix"` + FirstUser string `json:"first_user"` +} + +// SeedComponents returns short component hashes. Zero values mean the component +// is absent (for example no system prefix at all). +func SeedComponents(req ChatRequest) SessionSeedComponents { + fingerprint, ok := buildContentSessionFingerprint(req) + if !ok { + return SessionSeedComponents{} + } + out := SessionSeedComponents{ + Model: shortHash(fingerprint.Model), + Tools: shortHash(fingerprint.Tools), + } + if len(fingerprint.Prefix) > 0 { + if raw, err := json.Marshal(fingerprint.Prefix); err == nil { + out.Prefix = shortHash(string(raw)) + } + } + if raw, err := json.Marshal(fingerprint.FirstUser); err == nil { + out.FirstUser = shortHash(string(raw)) + } + return out +} + +func shortHash(value string) string { + if strings.TrimSpace(value) == "" { + return "" + } + sum := sha256.Sum256([]byte(value)) + return hex.EncodeToString(sum[:4]) +}