Repository navigation
feat(ai-proxy): add configurable persistent API key affinity - #4128
ran411285752 wants to merge 3 commits into
Conversation
c20e34f to
a0d3c95
Compare
|
Hi @johnlanni, when you have a chance, could you please review this PR? It implements #4089. Thanks! |
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #4128 +/- ##
=======================================
Coverage ? 69.31%
=======================================
Files ? 170
Lines ? 33798
Branches ? 0
=======================================
Hits ? 23427
Misses ? 9524
Partials ? 847
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
| func isStatefulAPI(apiName string) bool { | ||
| // These APIs maintain session state and should be routed to the same provider consistently | ||
| statefulAPIs := map[string]bool{ | ||
| string(ApiNameAnthropicMessages): true, // Anthropic Messages - prompt cache keyed per API key |
There was a problem hiding this comment.
Agent: Review Agent
Agent Session ID: 019f6aac-4902-70d0-8004-5058a6f962e0
Agent Session Source: CODEX_THREAD_ID
Type: FINDING
ID: FINDING-001
Severity: P1
Status: open
Process: PROCESS-REQ-COMPAT
Spec: SPEC-001
Spec Comment: #4089 (comment)
这里把 Anthropic Messages 的 prompt cache 描述为 “keyed per API key”,但 Anthropic 当前官方文档说明 Claude API/Claude Platform on AWS/Microsoft Foundry 的缓存按 workspace 隔离,Bedrock/Google Cloud 按 organization 隔离,并非按 API key;vLLM 的 prefix-cache hash 也不包含鉴权 token。当前实现又仅按 API 名对所有原生 Messages provider 默认开启 affinity,会把现有随机均衡改成 consumer 桶化,却未必获得缓存收益;低基数或重流量 consumer 可能打热单个 key,增加 quota、429 和延迟风险。请先修正需求前提并明确产品边界:建议改成显式 opt-in,或至少按 provider/cache isolation domain 控制启用,同时补充负载倾斜评估及 release note。参考:https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-storage-and-sharing 以及 https://docs.vllm.ai/en/stable/design/prefix_caching/
There was a problem hiding this comment.
已按此意见调整:不再因 /v1/messages 对所有 Provider 默认开启。新增 apiKeyAffinity 配置,默认关闭,只有显式 enabled: true 且配置 Redis 才生效;未开启时保持原有随机/有状态选择行为。中英文 README 和 PR 的 Release note 已说明负载与启用边界。
| func isStatefulAPI(apiName string) bool { | ||
| // These APIs maintain session state and should be routed to the same provider consistently | ||
| statefulAPIs := map[string]bool{ | ||
| string(ApiNameAnthropicMessages): true, // Anthropic Messages - prompt cache keyed per API key |
There was a problem hiding this comment.
Agent: Review Agent
Agent Session ID: 019f6aac-4902-70d0-8004-5058a6f962e0
Agent Session Source: CODEX_THREAD_ID
Type: FINDING
ID: FINDING-002
Severity: P1
Status: open
Process: PROCESS-IMPL
Spec: SPEC-001
Spec Comment: #4089 (comment)
该 membership 在启用现有 apiToken failover 时不会生效:SetApiTokenInUse 在 failover.enabled=true 时直接调用 GetGlobalRandomToken,完全绕过 GetOrSetTokenWithContext → selectApiToken → isStatefulAPI。因此“多 token + /v1/messages + x-mse-consumer”仍会随机选 key,不满足 SPEC-001 无例外的 MUST。请让初次选择仍遵循 consumer affinity、只在失败后切换 token;或者在 SPEC/README 中明确排除 failover 并补充对应测试。绕过点:provider/failover.go:724-730。
There was a problem hiding this comment.
已处理 failover 绕过问题:亲和绑定在写上游认证头前读取;首次无绑定沿用现有选择算法,绑定命中只使用当前可用 Key,401/402/403/429 在当前请求内换 Key。failover 可用池并发清空时,内部重入本地返回 503,不会重新使用暂停 Key。已补 failover 正常切换、全部暂停和并发空池测试。
| func isStatefulAPI(apiName string) bool { | ||
| // These APIs maintain session state and should be routed to the same provider consistently | ||
| statefulAPIs := map[string]bool{ | ||
| string(ApiNameAnthropicMessages): true, // Anthropic Messages - prompt cache keyed per API key |
There was a problem hiding this comment.
Agent: Review Agent
Agent Session ID: 019f6aac-4902-70d0-8004-5058a6f962e0
Agent Session Source: CODEX_THREAD_ID
Type: FINDING
ID: FINDING-003
Severity: P1
Status: open
Process: PROCESS-IMPL
Spec: SPEC-001
Spec Comment: #4089 (comment)
Claude 的兼容配置 protocol: original 也不会命中这里:main.go:242-245 会用 provider-specific GetApiName 覆盖通用入站分类,而 claudeProvider.GetApiName 对真实 /v1/messages 返回 ApiNameChatCompletion(claude.go:1064-1067),所以仍走随机选择。这与 PR 描述中“claude 原生支持时生效”不一致。建议将用于 token affinity 的入站 API 分类与 provider 内部转换分类解耦,并增加 type=claude、protocol=original、多 token、同 consumer 的回归测试。
There was a problem hiding this comment.
已修复 Claude protocol: original:入站 /v1/messages 的 Anthropic 分类不会再被 claude provider 覆盖成 Chat Completions,其他 Provider 仍保留原专用分类语义。已补 helper 和 Host 回归测试。
|
|
||
| first := pick("consumer-anthropic") | ||
| second := pick("consumer-anthropic") | ||
| require.Equal(t, first, second, "same consumer should yield the same token across requests") |
There was a problem hiding this comment.
Agent: Review Agent
Agent Session ID: 019f6aac-4902-70d0-8004-5058a6f962e0
Agent Session Source: CODEX_THREAD_ID
Type: FINDING
ID: FINDING-004
Severity: P2
Status: open
Process: PROCESS-TEST-DOC
Spec: SPEC-001
Spec Comment: #4089 (comment)
这里仅比较两次结果相等,随机路径在 3 个 token 下仍有 1/3 概率误通过,且没有按 TASK-001 T3 要求断言结果等于 GetTokenWithConsumerAffinity/FNV-1a 的精确 token。后面的无 consumer 用例也只验证返回任一合法 token,无法证明确实走了随机 fallback。请改为断言精确 FNV 结果,并通过可控 RNG 或 selection spy 覆盖 header 缺失/空字符串的随机分支;同时补 ApiNameAnthropicComplete=false、failover 和 Claude original 场景。
There was a problem hiding this comment.
旧的“两次随机结果相等”验证已不再作为亲和成立依据。当前测试直接覆盖默认关闭、首次未绑定复用原选择路径、无 consumer 保留旧 retry、Redis 绑定命中、失败排除 Key、成功改绑、failover、Claude original、重试上限与共享预算;真实环境另验证了问题 Key 403 后同一请求内部重试并最终 200。
wydream
left a comment
There was a problem hiding this comment.
Review 结论
感谢提交。这个 PR 的最小实现思路清晰:在默认、未启用 failover、非 Claude original 的路径上,/v1/messages 可以正确进入既有 consumer affinity 逻辑;新增单测、Go/WASM Host 测试以及 CI 也都通过。
但当前仍有需求前提、功能覆盖和兼容性方面的 blocker,因此本轮结论为 Request changes,暂不建议 approve / merge。
Blocking findings
-
[P1] Cache scope 前提不准确,默认开启粘滞存在负载退化风险
当前注释及需求把 Anthropic prompt cache 描述为 “per API key”,但官方文档显示 Claude API 等按 workspace 隔离,Bedrock/Google Cloud 按 organization 隔离;vLLM prefix-cache key 也不包含鉴权 token。因此仅按 Messages API 名对所有 provider 默认开启 affinity,可能没有预期缓存收益,却会把随机均衡变成 consumer 桶化。低基数或重流量 consumer 可能打热单个 key,增加 quota、429 和延迟风险。
请先修正需求前提并明确产品边界。建议采用显式 opt-in,或按 provider/cache isolation domain 控制启用,并补充负载倾斜评估和 release note。
-
[P1] 启用现有
failover时功能完全失效SetApiTokenInUse在failover.enabled=true时直接调用GetGlobalRandomToken(),绕过本 PR 修改的 affinity 路径。同一 consumer 的 Messages 请求仍会随机选择 key,不满足 SPEC-001 当前无例外的 MUST。请让初次选择仍遵循 affinity、仅失败后切换 token;或者明确收缩 SPEC,并补充文档及测试。
-
[P1] Claude
protocol: original不会命中新增规则original 模式会使用 Claude provider 自己的 API 分类,而
/v1/messages被分类为ApiNameChatCompletion,不会命中新增的ApiNameAnthropicMessagesmembership。这与 PR 描述中“claude 原生支持时生效”不一致。建议将用于 token affinity 的入站 API 分类与 provider 内部转换分类解耦,并补 Claude original + multi-token 回归测试。
-
[P1] TASK-001 尚未完成
isStatefulAPI等注释仍把所有成员描述为 stateful,且 “per API key” 表述不准确;- README/README_EN 仍声明多 token 始终随机,没有披露 Messages 的行为变化;
- release note 未补;
- SPEC-001/TASK-001 仍为 draft,PR/Implement 链接和任务状态未同步。
Test follow-up
新增 wiring 测试可以捕获删除 membership 的回归,但当前“两次结果相等”的断言在随机路径下仍有 1/3 概率误通过;无 consumer 用例也无法证明确实走了随机 fallback。请断言精确 FNV token,并通过可控 RNG/selection spy 覆盖 header 缺失/空字符串,同时补 ApiNameAnthropicComplete=false、failover、Claude original 场景。
已验证
- Targeted provider tests:PASS
- Go/WASM
TestConsumerAffinity:PASS go test ./... -count=1 -timeout 8m:PASS- GitHub CI、changed-plugin、WASM e2e、lint、coverage:全部通过
- 微基准未发现新增内存分配;主要性能风险来自粘滞分流造成的负载倾斜,而不是这一行 map lookup 本身
请处理 3 个 P1 功能/设计 finding,并完成 TASK-001 的文档与 traceability 闭环。更新后我会基于新 head 重新 review。
65137d6 to
41b43dd
Compare
Signed-off-by: ran411285752 <411285752@qq.com>
46deb42 to
a6a30df
Compare
|
已基于本轮 review 将方案从“Messages 默认亲和”调整为“用户手动开启的持久 API Key 亲和”。 本轮主要修复: 亲和配置默认关闭,开启时 Redis 必填;未带 x-mse-consumer 完全保留旧行为。 还请基于新 head 重新 review。 Based on this round of review, the solution has been adjusted from "Messages default affinity" to "persistent API Key affinity manually enabled by the user". Main repairs this round: Affinity configuration is turned off by default, and Redis is required when turned on; without x-mse-consumer, the old behavior is completely retained. Please review again based on the new head. |
Merge the latest main and resolve conflicts in PR higress-group#4128 while retaining API Key affinity. Include upstream request-body size validation, streaming usage controls and provider updates. Validation recorded for this merge: go test ./... -count=1 passed in the ai-proxy module. The apiKeyAffinity feature remains disabled by default. Signed-off-by: ran411285752 <411285752@qq.com>
【原因】:: 同步最新 main 并消除 PR higress-group#4128 的合并冲突。 【变更】:: 保留 API Key 亲和逻辑,同时合入请求体大小校验、流式 usage 控制及最新 provider 变更。 【验证】:: 在 ai-proxy 模块执行 go test ./... -count=1,全部通过。 【影响】:: 仅更新功能分支合并基线,不改变 apiKeyAffinity 默认关闭的兼容行为。 Signed-off-by: ran411285752 <411285752@qq.com>
|
@johnlanni 您好,之前的 review 意见已经在最新版本中处理。本次又同步了最新 补充实际运行情况:这套机制在我们内部日均约 20 亿 token 的流量下持续使用,启用后用户没有再遇到限流问题。 麻烦您有空时帮忙复审一下,谢谢。 Hello @johnlanni, the previous review comments have been addressed in the latest version. This time, the latest Supplementary actual operation situation: This mechanism is continuously used under our internal daily average traffic of about 2 billion tokens. After being enabled, users no longer encounter current limiting problems. Please help me review it when you have time, thank you. |
Merge current main while preserving the original PR history and the opt-in Redis-backed API Key affinity implementation. Stop headers and body with HeaderStopAllIterationAndWatermark while awaiting the Redis binding. HeaderStopIteration allowed body processing to forward a provisional Key before the bound Key was applied. Add a reproducible real-Envoy/Redis harness, synthetic red/green evidence, configuration, log excerpts, file hashes and a release note. No deployment configuration, credentials, provider requests or Wasm binaries are included. Validation: - go test ./... -count=1 -timeout 30m: passed (root package 539.767s). - Final affinity tests and provider/config/util tests: passed. - Same real Envoy inputs with 100ms Redis delay: baseline reproduced Key changes; three fixed runs passed binding, 403 retry, body replay, rebinding, SSE and Redis-degradation assertions, with container/network cleanup. AI assistance: Codex participated in synchronization, regression diagnosis, test/evidence preparation and read-only review. This continues an in-flight PR; no retroactive maintainer approval or policy exemption is claimed. Signed-off-by: ran411285752 <411285752@qq.com>
1e013a4 to
5cef9fd
Compare
I. Summary
继续实现默认关闭的、单 Provider 内的持久 API Key 亲和:同一已认证消费者优先使用其 Redis 绑定的 Key;明确的 Key 失败可在当前请求内换 Key,备用 Key 成功后改绑。Redis 仅保存 Key 指纹,不保存明文 Key。没有消费者标识或未显式启用时,保留现有行为。
2026-11-15 update
main@0316bc904789ab25a9cd42db58eafca11f6a2205;最新提交为5cef9fd7b45d01e828949f4f40562112307e1f66。按作者明确授权,仅将历史合并提交cbb777a5的正文改为英文说明(新提交4cf5883d979a6ac53f879eef4f15d1a01be9cf2d),并相应更新后继 parent;已使用精确旧 SHA 的--force-with-lease更新分支。两个对应提交的代码树分别完全一致,未改代码、合并结构或签署信息。HeaderStopAllIterationAndWatermark,而不是只停止 headers 的HeaderStopIteration,避免请求体抢先推进并带 provisional Key 到上游。Contract / compatibility
apiKeyAffinity.enabled: true时启用,需要配置 Redis;支持的部署组合必须同时开启现有 tokenfailover。401/402/403/429可在当前请求内尝试其他可用 Key;只有备用 Key 返回2xx才更新绑定。Key 恢复后不强制切回。ai_log记录redis_degraded;不将亲和视为认证机制,消费者身份仍应来自前置认证插件。fallback-envoyfilter.yaml。缓存收益取决于供应商实际隔离域,不能泛称所有 prompt cache 都按 API Key 隔离;偏斜消费者可能造成 Key 负载偏斜,所以不默认开启。protocol: original的/v1/messages分类兼容修复、默认关闭、failover/重试预算等原有回归仍保留。II. Related issue
Closes #4089 (intended outcome, not a claim that its governance tasks are approved or complete).
The original discussion and review are historical context. This PR no longer changes all Anthropic Messages requests to default affinity; the current behavior is explicit opt-in as described above.
III. Change type
IV. Agent participation and issue-spec gate
Timed obligations (not retroactively asserted):
Overall gate status:
Gate-status explanation: This is an in-flight PR whose implementation/review began before the current agent-assisted contribution policy. It continues the existing scope with synchronization, a runtime regression fix and verification evidence. The issue still contains historical draft artifacts and the revised opt-in design discussion; no explicit current Proposal/Design approval for this implementation was located. No retroactive approval is fabricated. This update does not claim to satisfy the gate, waive maintainer review or obtain any exemption; maintainers decide acceptance and priority.
Trivial-exception explanation: N/A; assistance was material.
Verified maintainer/administrator exception evidence: N/A; no exception is claimed. Authenticated author is
ran411285752; querying canonical collaborator permission with token overrides unset returned403, so an eligible maintain/admin role could not be verified.Approved Proposal Issue URL: N/A; no explicitly approved current Proposal was established. Historical issue: #4089.
Approved Design Issue URL: N/A; the revised opt-in discussion remains at #4089 (comment), not a claimed approved Design.
Maintainer approval links: N/A; not located, not inferred from agent artifacts.
Authorized implementation TASK links: Historical draft only, not claimed current authorization: #4089 (comment). Historical draft SPEC: #4089 (comment).
Verification Plan and verification TASK/evidence links: There is no claimed maintainer-approved canonical verification TASK. Reproducible test procedure and actual synthetic evidence are linked below; they do not substitute for governance approval.
AI-assisted work summary: Codex assisted source synchronization, diagnosis of the Redis/header-body race, tests, evidence preparation and independent read-only review. Instructions were to update the existing patch PR to the verified 2.2.6 behavior, retain upstream fixes, use normal commits/push and exclude production data. No production configuration was changed during this PR refresh.
V. Testing and verification
Test and deterministic rerun commands:
539.767s; config/provider/util passed). This run occurred on the same product source before the final evidence/docs-only additions.git diff --checkagainst current upstream main passed. Older release notes imported by the merge contain baseline Markdown trailing whitespace; no unrelated cleanup was performed.Environment and configuration: Go1.26.4 windows/amd64 for host tests/builds; Linux amd64 Docker for real runtime comparison. The isolated test uses synthetic Keys/consumer, a mock OpenAI upstream, independent Redis and a100ms artificial Redis delay. Kubernetes/kind/k3s: N/A for this plugin-local runtime regression; the test runs the real proxy-Wasm path using a pinned release Envoy. This is not a claim that the whole control plane passed conformance.
Exact tested revision / image / manifests:
0316bc904789ab25a9cd42db58eafca11f6a2205.8236fc12603ea668d3c99dc24b9f6a3d3b59cb92(original headcbb777a5merged with that base).366ec44f5f92b082cbca2b06cbaa426e996d6fd8; product Go file hashes match the final commit and are recorded in the evidence manifest. The Wasm was built before the final merge commit, so embedded VCS metadata alone should not be used as the tested-code identity.higress-registry.cn-hangzhou.cr.aliyuncs.com/higress/gateway@sha256:5d0618399fa98b9f4ad3c34b58f084b51624e3cc4eccdde72554b636d16b5da4.Baseline reproduction evidence: baseline.json, expected exit1 with
consumer changed API Key, same input/configuration and100ms delay. No setup error is counted as RED.Fixed-version evidence: fixed-1.json, fixed-2.json, fixed-3.json. All three exit0: six stable requests, one-client-request403→replacement200, identical non-empty request-body hash/request ID across attempts, eventual Redis rebinding, subsequent reuse, SSE and Redis-stop degradation. Each reports no remaining test container; the test network is removed. Sanitized log excerpts are adjacent to the result files.
Wasm source / artifact hashes:
f98fbe08843884522f3ebc248e0630d4d13d0e9e550476ea2d8bb75851ecdbb5.c505ad6c0f42975148932b904221929127b6c8508fbe7a14c353b52f668fe864.VI. Special notes for reviewers