BFE AI 协议路径改写向后兼容验证:未配置 ProtocolPaths 时 openai/anthropic 请求的逐字节透传(TC-05)
BFE AI 协议路径改写向后兼容验证:未配置 ProtocolPaths 时 openai/anthropic 请求的逐字节透传(TC-05)
本文是 BFE(Baidu Front End)SC17「AI 协议路径改写(AIConf.ProtocolPaths)」场景中 TC-05 用例的深度解析:当 cluster 未注入 AIConf(即未配置 ProtocolPaths)时,openai 与 anthropic 协议请求的路径必须逐字节透传,与特性上线前行为完全一致。文章将从用例设计出发,深入 ai_path_rewrite.go 与 reverseproxy.go 的源码实现,并结合集成测试代码,说明该用例如何验证 AI 协议路径改写特性对存量部署的零影响,帮助读者理解 BFE 在引入路径改写后如何守住向后兼容底线。
一、用例定位:SC17 场景中的“零配置基线”
BFE 的 AI 协议路径改写特性允许通过 cluster 的 AIConf.ProtocolPaths 为不同 model provider 声明上游 API 基路径(即该协议 SDK base_url 的 path 部分),把客户端的标准入口路径(openai 的 /v1/chat/completions、anthropic 的 /v1/messages)改写到 provider 特有的前缀下(如百炼 /compatible-mode/v1、/apps/anthropic,Kimi Code /coding/v1、/coding,火山 /api/v3 等)。SC17 场景共设计 8 个测试例(TC-01 至 TC-08),完整覆盖改写、双协议独立改写、fallback 重算与各类透传分支,其全景与运行方式见 场景说明.md。
TC-05「未配置透传」是其中唯一以“完全不配置”为条件的用例:cluster_primary 的 AIConf 为 nil,AIConfs 映射中根本没有该 cluster。它的存在不是为了验证一个新行为,而是为了证明一个“没有发生任何变化”的事实——路径改写特性对未启用它的存量部署必须零影响,这正是向后兼容性验证的基线(baseline)用例。
二、测试目的与运行模式
2.1 测试目的
验证未配置 ProtocolPaths(cluster 无 AIConf)时,openai 与 anthropic 请求的路径逐字节透传——与特性上线前行为完全一致,证明该特性对存量部署零影响(向后兼容)。
逐字节透传(byte-for-byte passthrough)意味着后端收到的路径与客户端发来的路径字符串完全一致,不含任何前缀增删或改写痕迹。该用例对照 TC-01(openai 改写为 /compatible-mode/v1/chat/completions)与 TC-02(anthropic 改写为 /apps/anthropic/v1/messages),形成“配置即改写、不配置即透传”的对称验证。
2.2 运行模式
单组件模式:仅启动真实 bfe 进程。与仓库其他集成测试一致,测试不引入 ai-gateway-api 与 conf-agent 等外部组件;AIConf 由测试代码经 BFEConfigBuilder 直接写入运行时生成的 cluster_conf.data(不经控制面),mock AI 后端通过 mock_backend.go 中的 common.MockBackend 启动,并新增 URLPaths() 观测点记录后端实际收到的请求路径序列。
三、前置条件与配置构造
3.1 前置条件
cluster_primary不注入AIConf(AIConfs映射中无该 cluster,即primaryAIConf传 nil);- 路由与认证方式同 TC-01/TC-02:apikey
ak_user_a命中default_t()规则 →cluster_primary,fallback 至cluster_fallback; cluster_primary/cluster_fallback均不配置ProtocolPaths,后端均返回 200。
需要说明的是,在 SC17 场景中除 TC-05/TC-08 外,其他用例的 cluster_primary / cluster_fallback 均声明 ModelProtocols: <a href="https://link.gitcode.com/i/ea88e13858b2b59cf24ba44ec8d4b3ca" target="_blank">"openai", "anthropic"](否则 anthropic 请求会在协议匹配处被 PROVIDER_PROTOCOL_MISMATCH 拒绝)。TC-05 因 AIConf 为 nil,协议匹配检查 cluster.AIConf != nil && !clusterSupportsAuthStyle(...) 直接短路跳过(见 [reverseproxy.go),因此无需声明 ModelProtocols。
3.2 配置构造(源码级)
集成测试实现中,newTestEnv 通过两个 *cluster_conf.AIConf 参数控制注入:
aiConfs := map[string]*cluster_conf.AIConf{}
if primaryAIConf != nil {
aiConfs[clusterPrimary] = primaryAIConf
}
if fallbackAIConf != nil {
aiConfs[clusterFallback] = fallbackAIConf
}
TC-05 调用 newTestEnv(t, http.StatusOK, http.StatusOK, nil, nil)——两个 AIConf 参数均为 nil,因此生成的 cluster_conf.data 中 cluster_primary 与 cluster_fallback 都不含 AIConf 节点,这正对应文档前置条件中的“AIConfs 映射中无该 cluster”。
AIConf 结构与 ProtocolPaths 字段的定义位于 cluster_conf_load.go:
type AIConf struct {
Type int // type of LLM service, reserved for future use. should be 0 now.
ModelMapping *map[string]string // model mapping, key is model name in req, value is model name in backend
Provider string // provider name in model_prices
Keys []AIKey // multiple API keys; empty means no key injection
KeyPolicy *AIKeyPolicy // key selection & retry policy
ModelTable *ModelTable // pricing table, auto-filled by InnerAPI
MatchPrefix string // provider/model prefix this cluster matches
StripPrefix bool
ModelProtocols []string // protocols supported by the cluster's provider
ProtocolPaths map[string]string // protocol -> upstream base path, nil means disabled
}
源码注释明确:ProtocolPaths 为 empty/nil 时特性禁用,请求按其原始路径转发("empty/nil means disabled (requests are forwarded with their original path)")——这与 TC-05 的透传断言在语义上严格对应。
四、BFE 请求构造
按序发送 2 次 POST 请求(Host 均为 api.example.org):
| 序号 | 路径 | 认证头 |
|---|---|---|
| 1 | /v1/chat/completions |
Authorization: Bearer ak_user_a |
| 2 | /v1/messages |
x-api-key: ak_user_a |
两个请求分别代表 openai 与 anthropic 两种协议风格:Authorization: Bearer 触发 openai 协议识别,x-api-key 触发 anthropic 协议识别(参见 detect.go 的 DetectProtocolAndKey,以及 request_ai_basic.go 中 AuthStyleOpenAI = "openai"、AuthStyleAnthropic = "anthropic" 的定义)。请求体与真实 SDK 调用一致:openai 请求体为 {"model":"test-model","messages":[...]},anthropic 请求体额外携带 "max_tokens":1。
apikey 级路由由 ai_route.data 配置:ak_user_a 绑定 apikey_ak_user_a 路由表,命中 default_t() 规则,target 为 cluster_primary(Weight 100),fallback 为 cluster_fallback。
五、改写计算:nil 分支在第一行拦截
TC-05 的改写计算在文档中只有一句话:cluster.AIConf == nil → rewriteUpstreamPath 直接返回原路径(第一分支拦截),透传。对应 ai_path_rewrite.go 中 rewriteUpstreamPath 的完整逻辑:
func rewriteUpstreamPath(reqPath string, authStyle string, aiConf *cluster_conf.AIConf) string {
if aiConf == nil {
return reqPath // 第一分支:AIConf 为 nil,直接透传
}
base, ok := aiConf.ProtocolPaths[authStyle]
if !ok {
return reqPath // 第二分支:该协议未配置基路径,透传
}
if authStyle == bfe_basic.AuthStyleAnthropic {
if !isStandardV1Prefix(reqPath) {
return reqPath
}
return base + reqPath // anthropic: base + /v1/messages
}
// openai: 去 /v1 前缀后追加 base(仅限标准端点)
if reqPath == "/v1" || reqPath == "/v1/" {
return base
}
rest := bfe_basic.StripV1Prefix(reqPath)
if !bfe_basic.IsOpenAIEndpoint(rest) {
return reqPath
}
return base + rest
}
TC-05 的两次请求都命中第一分支:cluster.AIConf == nil,函数在第 40 行直接返回 reqPath 原值,后续的协议分支(anthropic 的 isStandardV1Prefix 判定、openai 的 StripV1Prefix 与 IsOpenAIEndpoint 端点识别)根本不会执行。
这种“nil 优先”的分支设计有明确的语义:ProtocolPaths 是可选能力,未配置时改写逻辑完全旁路,请求走与特性上线前完全相同的代码路径。换言之,TC-05 验证的不是“改写被正确跳过”这一中间状态,而是整个改写链路对请求不可见。
六、私有 URL 拷贝:透传的工程保障
透传不仅要求 rewriteUpstreamPath 返回原路径,还要求改写过程绝不触碰入站请求。这一点由 applyAIProtocolPathRewrite 保证(ai_path_rewrite.go):
func applyAIProtocolPathRewrite(outreq *bfe_http.Request, authStyle string, aiConf *cluster_conf.AIConf) {
if outreq == nil || outreq.URL == nil {
return
}
newPath := rewriteUpstreamPath(outreq.URL.Path, authStyle, aiConf)
if newPath == outreq.URL.Path {
return // 改写结果与原路径相同,直接返回,保持共享 URL 指针
}
u := *outreq.URL // 改写才创建私有 URL 拷贝
u.Path = newPath
u.RawPath = ""
outreq.URL = &u
}
两个关键点:
- 无改写时保持共享指针:
newPath == outreq.URL.Path时函数提前返回,outreq.URL仍指向入站请求的原始 URL。TC-05 场景下每次 attempt 的outreq与入站请求共享同一个 URL 对象,行为与特性上线前逐字节一致。 - 有改写时才拷贝:只有实际发生改写才创建
u := *outreq.URL私有拷贝,改写结果写入副本,入站请求路径永不修改。这一设计同时支撑了 TC-04「fallback 路径重算」:route 级 fallback 切换 cluster 时,第二次 attempt 从原始客户端路径按 fallback cluster 自身配置重算,而非继承第一次 attempt 的改写结果。
对应的单元测试 ai_path_rewrite_test.go 专门断言了共享指针语义:
t.Run("no rewrite keeps shared URL pointer", func(t *testing.T) {
outreq := newReq("/v1/messages")
inboundURL := outreq.URL
applyAIProtocolPathRewrite(outreq, bfe_basic.AuthStyleAnthropic, &cluster_conf.AIConf{})
applyAIProtocolPathRewrite(outreq, bfe_basic.AuthStyleAnthropic, nil)
if outreq.URL != inboundURL {
t.Error("expected shared URL pointer preserved when no rewrite applies")
}
...
})
TestRewriteUpstreamPath 的用例表中同样有 {"nil aiConf passthrough", "/v1/messages", AuthStyleAnthropic, nil, "/v1/messages"} 与 {"nil protocol paths passthrough", "/v1/messages", AuthStyleAnthropic, &cluster_conf.AIConf{}, "/v1/messages"} 两条基线用例,分别覆盖「AIConf 为 nil」与「AIConf 存在但 ProtocolPaths 为 nil/空」两种未配置形态(ai_path_rewrite_test.go)。
七、doSingleAIForward 调用链中的透传
改写发生的位置在 ReverseProxy.doSingleAIForward(reverseproxy.go):
// prepare out request to downstream RS backend
outreq := new(bfe_http.Request)
*outreq = *req // includes shallow copies of maps, but okay
basicReq.OutRequest = outreq
// Rewrite upstream path per provider protocol config (AIConf.ProtocolPaths):
// standard /v1/... entry paths are mapped to the provider-specific base path
// of the detected protocol. The rewrite goes to a private URL copy, so the
// inbound request path stays original and every cluster attempt (including
// route-level fallback) recomputes from it.
applyAIProtocolPathRewrite(outreq, aiMeta.AuthStyle, cluster.AIConf)
每次 cluster attempt 都会执行 *outreq = *req 浅拷贝入站请求得到新的 outreq,然后调用 applyAIProtocolPathRewrite。在 TC-05 中,cluster.AIConf 为 nil,rewriteUpstreamPath 返回原路径,newPath == outreq.URL.Path 成立,函数在拷贝 URL 之前就返回——outreq.URL 与原请求共享指针,后端收到的路径与客户端发送的完全相同。
此外,协议检测发生在改写之前:aiMeta.AuthStyle 未知时由 DetectAuthStyle 识别(openai/anthropic/gemini/unknown,见 request_ai_basic.go)。TC-05 的两次请求分别识别为 openai 与 anthropic,但无论识别结果如何,aiConf == nil 的第一分支都会拦截并透传。
八、预期结果与断言
| 断言 | 预期 |
|---|---|
| 两次响应状态码 | 200 |
cluster_primary 后端收到的路径序列 |
[/v1/chat/completions, /v1/messages](原样) |
cluster_fallback 命中数 |
0 |
断言通过 MockBackend.URLPaths() 与 Hits() 观测点实现(mock_backend.go):URLPaths() 按到达顺序返回后端记录的所有请求路径,Hits() 返回命中次数。断言要求 cluster_primary 收到的路径序列按序为 [/v1/chat/completions, /v1/messages],既验证了路径逐字节不变,也验证了两次请求均落在主 cluster;cluster_fallback 命中数为 0 则确认无 fallback 发生,整个转发链路完全在主 cluster 内完成。
九、集成测试实现对照
TC-05 的 Go 集成测试实现为 TestTC05_NoRewritePassthrough(sc17_ai_protocol_paths_rewrite_test.go):
// TC05: without ProtocolPaths the request path is forwarded unchanged.
func TestTC05_NoRewritePassthrough(t *testing.T) {
e := newTestEnv(t, http.StatusOK, http.StatusOK, nil, nil)
defer e.Close()
resp, respBody, err := e.sendOpenAI(openAIBody())
...
assertStatus(t, e, resp, respBody, http.StatusOK)
resp, respBody, err = e.sendAnthropic(anthropicBody())
...
assertStatus(t, e, resp, respBody, http.StatusOK)
assertPaths(t, e.backends[clusterPrimary],
[]string{"/v1/chat/completions", "/v1/messages"})
}
测试流程与文档完全一致:newTestEnv 的两个 AIConf 参数均为 nil(不注入任何 AIConf);sendOpenAI 发送 POST /v1/chat/completions(Authorization 头携带 apikey),sendAnthropic 发送 POST /v1/messages(x-api-key 头携带 apikey);两次均断言 200;最终 assertPaths 断言 cluster_primary 收到的路径序列为 [/v1/chat/completions, /v1/messages]。assertPaths 使用 reflect.DeepEqual 进行序列级精确比较,任何顺序颠倒或路径变形都会导致测试失败。
十、与兄弟用例的对照:透传是全场景的公共底线
TC-05 不是唯一的透传用例,将它与 SC17 场景的其他用例并置,可以更完整地理解“透传”的边界:
| 用例 | 配置 | 请求路径 | 后端路径 | 语义 |
|---|---|---|---|---|
| TC-05 未配置透传 | 无 AIConf | /v1/chat/completions、/v1/messages |
原样 | 零配置基线:特性对存量部署零影响 |
| TC-06 非标准入口透传 | 配置 openai /api/v3 |
/compatible-mode/v1/chat/completions、/v10/xxx |
原样 | 即使配置了改写,非标准入口也永不改写 |
| TC-07 无 /v1 入口改写(issue #1379) | 配置 openai /compatible-mode/v1 |
/chat/completions、/v1/chat/completions |
均为 /compatible-mode/v1/chat/completions |
带不带 /v1 入口改写结果相同 |
| TC-08 无 /v1 入口未配置透传(issue #1379) | 无 AIConf | /chat/completions、/v1/chat/completions |
原样 | 无配置时两种入口均逐字节透传 |
TC-08 是 TC-05 在 issue #1379(兼容 Trae 等直连 base_url 的客户端)场景下的延伸:未配置 ProtocolPaths 时,不带 /v1 的入口 /chat/completions 与带 /v1 的入口 /v1/chat/completions 均原样透传,对应实现 TestTC08_NoV1EntryPassthrough(sc17_ai_protocol_paths_rewrite_test.go)。TC-06 则证明“配置了也不乱改”:openai 基路径配置为 /api/v3 时,provider 原生全路径与 /v10/xxx 仍因不满足标准入口判定(IsOpenAIEndpoint、isStandardV1Prefix)而透传(单元测试见 ai_path_rewrite_test.go)。
透传分支的统一工程语义是:改写只作用于“配置的协议 + 标准入口”的交集,交集之外的任何请求——无论配置与否——都保持原路径。TC-05 验证的是交集的空集情形,是这条规则最纯粹的表达。
十一、配置校验与透传的边界保证
ProtocolPaths 的合法值范围由配置校验函数保证(cluster_conf_load.go):
AIProtocolPathsCheck:键仅允许openai与anthropic(其他协议如gemini直接报错);nil/空 map 合法(即允许不配置)。checkUpstreamBasePath:基路径必须以/开头、不以/结尾、不含?/#/..、长度 ≤ 128。
校验与透传语义的配合点在于:合法配置只影响标准入口,非法配置在加载期即被拒绝——绝不会出现“配置写错导致存量请求被意外改写”的情况,这是 TC-05 所验证的“零影响”在配置维度上的另一层保障。校验规则的完整正反用例见 cluster_conf_load_test.go。
十二、运行方式
在仓库根目录执行集成测试(参见 tests/integration/README.md):
# 运行 SC17 整个场景
go test ./tests/integration/implementation/scenario-SC17-ai-protocol-paths-rewrite/ -v
# 仅运行 TC-05(未配置透传)
go test ./tests/integration/implementation/scenario-SC17-ai-protocol-paths-rewrite/ -run TestTC05 -v
首次运行会自动编译 bfe 二进制并缓存到 bfe/tests/integration/.integration-test-bin/(注意:缓存二进制按 git 版本键控,修改源码后需重新编译)。测试启动真实 bfe 进程与三个 mock 后端(cluster_primary、cluster_fallback、cluster_default),通过真实 HTTP 请求驱动,并在结束时输出 exception.log 辅助排障。
十三、总结:为什么要专门测试“什么都不做”
TC-05 表面上是“什么都不发生”的用例,但它在特性演进中承担着不可替代的职责:
- 向后兼容基线:AI 协议路径改写是新增能力,存量部署在未配置
ProtocolPaths时必须保持行为不变。TC-05 用两条真实协议请求(openai + anthropic)验证路径逐字节透传,把“零影响”从口头承诺变成可重复、可断言的工程事实。 - 共享指针语义的可观测证明:源码层通过“无改写时保持共享 URL 指针”实现零开销透传,TC-05 与单元测试
TestApplyAIProtocolPathRewrite共同确保该语义不被后续改动破坏。 - 与改写用例形成完整矩阵:TC-01/TC-02(改写生效)、TC-03(双协议独立改写)、TC-04(fallback 重算)、TC-06(非标准入口透传)、TC-07/TC-08(issue #1379 无 /v1 入口)与 TC-05 一起,覆盖了「配置 × 协议 × 入口形态」的所有组合,其中 TC-05 是判定改写正确性的对照基线——没有它,改写用例的断言就失去参照系。
对于在生产环境运行 BFE 的团队,TC-05 的结论可以直接转化为升级策略依据:只要不在 AIConf 中配置 ProtocolPaths,AI 请求转发路径就不会有任何变化,可以放心随版本升级;而启用该特性时,也只需按 ProtocolPaths 的键(openai/anthropic)与标准入口(/v1/...)规则配置,透传兜底会保证配置之外的请求始终安全。