Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions changelog/unreleased/cache-affinity-resilience.md
Original file line number Diff line number Diff line change
@@ -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 前缀抖动还是首条消息变了。
9 changes: 9 additions & 0 deletions changelog/unreleased/prompt-cache-tools-and-escape.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Normalize the tools array before hashing the session seed, so a client that rebuilds its tool list in a different order no longer scatters one conversation across accounts. `CLI2API_TOOLS_NORMALIZE=1` additionally normalizes the outbound payload order and protects the upstream cached prefix; the default keeps the payload byte-identical.
- Escape a sticky provider binding when every account of that provider is cooling for a real reason (quota, or a retry hint of two minutes or more) and another provider family can serve the model, instead of answering `429` while a healthy supplier sits idle. Shorter cooldowns still return a Retry-After so the chat keeps its warm cache.

### 中文

- 计算会话指纹前先归一化 tools 数组顺序,客户端每轮重建工具列表不再把同一段对话打散到多个账号。设置 `CLI2API_TOOLS_NORMALIZE=1` 会同时归一化发往上游的 payload 顺序,进一步保护上游的缓存前缀;默认保持 payload 字节不变。
- 当某供应商所有账号都在因为真实原因冷却(额度耗尽,或上游给出两分钟以上的重试提示),而另一供应商家族还能服务该模型时,允许脱离 sticky 绑定改走可用供应商,不再一边返回 `429` 一边让健康账号闲置。更短的冷却仍然返回 Retry-After,让对话保住已预热的缓存。
64 changes: 34 additions & 30 deletions internal/accounts/request_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"`
Expand Down
Loading
Loading