Skip to content

feat(ai-proxy): add configurable persistent API key affinity - #4128

Open
ran411285752 wants to merge 3 commits into
higress-group:mainfrom
ran411285752:feat/ai-proxy-anthropic-messages-affinity
Open

ran411285752 wants to merge 3 commits into
higress-group:mainfrom
ran411285752:feat/ai-proxy-anthropic-messages-affinity

Conversation

@ran411285752

@ran411285752 ran411285752 commented Jul 11, 2026 •

Copy link
Copy Markdown

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 更新分支。两个对应提交的代码树分别完全一致,未改代码、合并结构或签署信息。
  • 修复真实运行时暴露的竞态:等待 Redis 时使用 HeaderStopAllIterationAndWatermark,而不是只停止 headers 的 HeaderStopIteration,避免请求体抢先推进并带 provisional Key 到上游。
  • 补齐可复现的真实 Envoy/Redis 脚本、合成 RED/GREEN 结果、配置、脱敏日志片段、SHA256 清单和 release note。
  • 本轮产品源码与已经验证的 2.2.6 私有补丁保持一致;同步了上游新增的 SSE 测试修正,未引入跨 Provider 路由、账号池或套餐恢复检测。

Contract / compatibility

  1. 仅显式 apiKeyAffinity.enabled: true 时启用,需要配置 Redis;支持的部署组合必须同时开启现有 token failover。
  2. 无绑定首次沿用原选择算法,只有成功响应才建立绑定;绑定命中仍遵守当前可用 Key 池。
  3. 401/402/403/429 可在当前请求内尝试其他可用 Key;只有备用 Key 返回 2xx 才更新绑定。Key 恢复后不强制切回。
  4. 默认最多换 Key 3 次,从首次失败起共用 30 秒预算;绑定默认7天,达到80%按整天四舍五入的窗口后只在成功时续期。
  5. Redis异常降级不阻断上游请求,在已有 ai_log 记录 redis_degraded;不将亲和视为认证机制,消费者身份仍应来自前置认证插件。
  6. 保留原URI/请求体的内部重试需要配套 fallback-envoyfilter.yaml。缓存收益取决于供应商实际隔离域,不能泛称所有 prompt cache 都按 API Key 隔离;偏斜消费者可能造成 Key 负载偏斜,所以不默认开启。
  7. Claude protocol: original 的 /v1/messages 分类兼容修复、默认关闭、failover/重试预算等原有回归仍保留。
provider:
  failover:
    enabled: true
    cooldownDuration: 60000
  apiKeyAffinity:
    enabled: true
    redis:
      serviceName: redis.static
      servicePort: 6379
      database: 0
      timeout: 1000
    bindingTTLDays: 7
    maxRetries: 3
    retryTimeout: 30000

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

  • Bug fix
  • Feature or enhancement
  • Documentation or configuration only
  • Refactoring, tests, or maintenance

IV. Agent participation and issue-spec gate

  • No agent participation
  • Trivial agent-use exception
  • Verified maintainer/administrator exception
  • Material agent participation

Timed obligations (not retroactively asserted):

  • Before implementation began: approved Proposal and Design Issues and authorized implementation TASKs.
  • Before verification began: a maintainer-approved Design contained a Verification Plan.
  • Before requesting maintainer acceptance: canonical implementation/verification TASKs were completed with evidence.

Overall gate status:

  • Complete
  • Noncompliant: one or more obligations were not satisfied; explanation below.
  • Verified exception
  • N/A: human-only or trivial agent use

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:

cd plugins/wasm-go/extensions/ai-proxy
# New regression first failed with expected action4 / actual1 before the fix.
go test . -run '^TestApiKeyAffinityPausesRequestUntilRedisBindingIsLoaded$' -count=1
# After the fix:
go test . -run '^TestApiKeyAffinity' -count=1 -timeout 5m
go test ./provider ./config ./util -count=1
go test ./... -count=1 -timeout 30m
GOOS=wasip1 GOARCH=wasm go build -buildmode=c-shared -o /tmp/ai-proxy-fixed.wasm .
  • Full module verification passed (root package 539.767s; config/provider/util passed). This run occurred on the same product source before the final evidence/docs-only additions.
  • Final affinity regression and adjacent package verification passed again after evidence preparation.
  • The real Envoy procedure, pinned gateway image, build/rerun/cleanup instructions and assertions are in runtime-affinity/README.md.
  • git diff --check against 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:

  • Base: 0316bc904789ab25a9cd42db58eafca11f6a2205.
  • Pre-fix merged tree: 8236fc12603ea668d3c99dc24b9f6a3d3b59cb92 (original head cbb777a5 merged with that base).
  • Fixed source tree before evidence additions: 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.
  • Gateway: higress-registry.cn-hangzhou.cr.aliyuncs.com/higress/gateway@sha256:5d0618399fa98b9f4ad3c34b58f084b51624e3cc4eccdde72554b636d16b5da4.
  • Exact Envoy/plugin/Redis/retry configuration.

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:

  • Baseline Wasm SHA256: f98fbe08843884522f3ebc248e0630d4d13d0e9e550476ea2d8bb75851ecdbb5.
  • Fixed Wasm SHA256: c505ad6c0f42975148932b904221929127b6c8508fbe7a14c353b52f668fe864.
  • Evidence manifest contains source-file and result/config/log hashes and build metadata. Wasm binaries are intentionally not committed.

VI. Special notes for reviewers

  • The default-off behavior, failover compatibility, Claude original protocol and previous i18n-independent behavior remain covered. Reviewer requests have not been dismissed or marked resolved on reviewers' behalf.
  • The real Envoy failure/replay test exercises403 and a roughly12KiB JSON body. Other eligible failure codes are host-tested; the1MiB replay boundary is not claimed as real-runtime tested here.
  • Public data is synthetic only. No production endpoint, consumer identity, API Key, Redis credential or production log body is included. Successful deployment feedback is not presented as independently verifiable upstream-provider fault injection or billing validation.
  • New-head CI must be evaluated separately; old-head CI success is not new-head proof. This PR update does not modify live deployment services.

@CLAassistant

CLAassistant commented Jul 11, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@ran411285752
ran411285752 force-pushed the feat/ai-proxy-anthropic-messages-affinity branch 3 times, most recently from c20e34f to a0d3c95 Compare July 11, 2026 10:37
@ran411285752

Copy link
Copy Markdown
Author

Hi @johnlanni, when you have a chance, could you please review this PR? It implements #4089. Thanks!

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@1547826). Learn more about missing BASE report.
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #4128   +/-   ##
=======================================
  Coverage        ?   69.31%           
=======================================
  Files           ?      170           
  Lines           ?    33798           
  Branches        ?        0           
=======================================
  Hits            ?    23427           
  Misses          ?     9524           
  Partials        ?      847           
Flag Coverage Δ
wasm-go-plugin-ai-proxy 81.50% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...s/wasm-go/extensions/ai-proxy/provider/provider.go 84.52% <100.00%> (ø)
...m-go/extensions/ai-proxy/test/consumer_affinity.go 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已按此意见调整:不再因 /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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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。

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已处理 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 的回归测试。

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复 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")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 场景。

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

旧的“两次随机结果相等”验证已不再作为亲和成立依据。当前测试直接覆盖默认关闭、首次未绑定复用原选择路径、无 consumer 保留旧 retry、Redis 绑定命中、失败排除 Key、成功改绑、failover、Claude original、重试上限与共享预算;真实环境另验证了问题 Key 403 后同一请求内部重试并最终 200。

@wydream wydream left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review 结论

感谢提交。这个 PR 的最小实现思路清晰:在默认、未启用 failover、非 Claude original 的路径上,/v1/messages 可以正确进入既有 consumer affinity 逻辑;新增单测、Go/WASM Host 测试以及 CI 也都通过。

但当前仍有需求前提、功能覆盖和兼容性方面的 blocker,因此本轮结论为 Request changes,暂不建议 approve / merge。

Blocking findings

  1. [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。

  2. [P1] 启用现有 failover 时功能完全失效

    SetApiTokenInUse 在 failover.enabled=true 时直接调用 GetGlobalRandomToken(),绕过本 PR 修改的 affinity 路径。同一 consumer 的 Messages 请求仍会随机选择 key,不满足 SPEC-001 当前无例外的 MUST。

    请让初次选择仍遵循 affinity、仅失败后切换 token;或者明确收缩 SPEC,并补充文档及测试。

  3. [P1] Claude protocol: original 不会命中新增规则

    original 模式会使用 Claude provider 自己的 API 分类,而 /v1/messages 被分类为 ApiNameChatCompletion,不会命中新增的 ApiNameAnthropicMessages membership。这与 PR 描述中“claude 原生支持时生效”不一致。

    建议将用于 token affinity 的入站 API 分类与 provider 内部转换分类解耦,并补 Claude original + multi-token 回归测试。

  4. [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。

@ran411285752 ran411285752 changed the title feat(ai-proxy): support apikey affinity for anthropic messages feat(ai-proxy): add configurable persistent API key affinity Jul 26, 2026
@ran411285752
ran411285752 force-pushed the feat/ai-proxy-anthropic-messages-affinity branch from 65137d6 to 41b43dd Compare July 26, 2026 23:29
@ran411285752
ran411285752 requested a review from wydream July 28, 2026 07:35
Signed-off-by: ran411285752 <411285752@qq.com>
@ran411285752
ran411285752 force-pushed the feat/ai-proxy-anthropic-messages-affinity branch from 46deb42 to a6a30df Compare July 28, 2026 10:27
@ran411285752

ran411285752 commented Jul 28, 2026 •

Copy link
Copy Markdown
Author

@wydream

已基于本轮 review 将方案从“Messages 默认亲和”调整为“用户手动开启的持久 API Key 亲和”。

本轮主要修复:

亲和配置默认关闭,开启时 Redis 必填;未带 x-mse-consumer 完全保留旧行为。
首次沿用原 Key 选择算法,成功后写 Redis 指纹绑定。
401/402/403/429 当前请求内部换 Key,成功后改绑;最多 3 次,共用 30 秒预算。
failover 不再绕过亲和;全部 Key 暂停或重入前可用池被并发清空时,不会继续使用暂停 Key。
修复 Claude protocol: original 的 /v1/messages 分类。
internal redirect 保留请求体(1 MiB 上限),补齐中英文 README、Release note 和测试。
真实 Higress 环境已验证:预先绑定到一个直连稳定返回 403 usage limit 的 Key 后,单次客户端请求在同一 request ID 下先记录内部 299/retrying,随后最终 200,Redis 绑定同步切换到备用 Key。完整脱敏证据已写入 PR 描述。

还请基于新 head 重新 review。


@wydream

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.
The original Key selection algorithm will be used for the first time, and Redis fingerprint binding will be written after success.
401/402/403/429 is currently requesting internal key change, which will be changed after success; up to 3 times, sharing a 30-second budget.
Failover no longer bypasses affinity; when all Keys are suspended or the available pool is concurrently cleared before reentry, the suspended Key will not continue to be used.
Fix /v1/messages category for Claude protocol: original.
Internal redirect retains the request body (1 MiB upper limit) and completes Chinese and English README, Release note and testing.
The real Higress environment has been verified: after pre-binding to a directly connected Key that stably returns 403 usage limit, a single client request first records an internal 299/retrying under the same request ID, and then finally 200, and the Redis binding is synchronously switched to the backup Key. Complete evidence of desensitization has been written into the PR description.

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>
ran411285752 added a commit to ran411285752/higress that referenced this pull request Aug 16, 2026
【原因】:: 同步最新 main 并消除 PR higress-group#4128 的合并冲突。
【变更】:: 保留 API Key 亲和逻辑,同时合入请求体大小校验、流式 usage 控制及最新 provider 变更。
【验证】:: 在 ai-proxy 模块执行 go test ./... -count=1,全部通过。
【影响】:: 仅更新功能分支合并基线,不改变 apiKeyAffinity 默认关闭的兼容行为。

Signed-off-by: ran411285752 <411285752@qq.com>
@ran411285752

ran411285752 commented Aug 16, 2026 •

Copy link
Copy Markdown
Author

@johnlanni 您好,之前的 review 意见已经在最新版本中处理。本次又同步了最新 main(7fd8dd98),解决了 main.go 和 provider/provider.go 的冲突;plugins/wasm-go/extensions/ai-proxy 下执行 go test ./... -count=1 已全部通过,目前 PR 已无合并冲突。

补充实际运行情况:这套机制在我们内部日均约 20 亿 token 的流量下持续使用,启用后用户没有再遇到限流问题。

麻烦您有空时帮忙复审一下,谢谢。


Hello @johnlanni, the previous review comments have been addressed in the latest version. This time, the latest main (7fd8dd98) was synchronized, and the conflict between main.go and provider/provider.go was resolved; executing go test ./... -count=1 under plugins/wasm-go/extensions/ai-proxy has all passed, and there are currently no merge conflicts in the PR.

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>
@ran411285752
ran411285752 force-pushed the feat/ai-proxy-anthropic-messages-affinity branch from 1e013a4 to 5cef9fd Compare November 15, 2026 07:25

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants