Skip to content
Merged
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
11 changes: 9 additions & 2 deletions backend/crates/providers/openai/src/transport/client_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,8 +374,13 @@ impl CodexBackendClient {
connection_profile.push_str("\0peer:");
connection_profile.push_str(&hex::encode(Sha256::digest(route.as_bytes())));
}
let pool_key =
self.websocket_pool_key(request, context, pool_account_id, &connection_profile);
let pool_key = self.websocket_pool_key(
request,
context,
pool_account_id,
&connection_profile,
opening.connection.headers(),
);
let pool_log_context = pool_key.as_ref().map(WebSocketPoolLogContext::from_key);
let downstream_cancellation = context.response_control.and_then(
gateway_core::engine::response_control::ResponseControl::connection_cancellation,
Expand Down Expand Up @@ -702,6 +707,7 @@ impl CodexBackendClient {
context: CodexRequestContext<'_>,
pool_account_id: Option<&str>,
connection_profile: &str,
opening_headers: &[(String, String)],
) -> Option<CodexWebSocketPoolKey> {
let account_id = pool_account_id.or(context.account_id)?;
let conversation_id = request
Expand All @@ -712,6 +718,7 @@ impl CodexBackendClient {
.with_egress_key(&self.egress_key)
.with_outbound_proxy(self.outbound_proxy.as_ref())
.with_connection_profile(connection_profile)
.with_response_exclusions(opening_headers)
.with_fedramp_routing(self.fedramp_routing)
.with_installation_id(context.installation_id);
key = key.with_routing_affinity(self.routing_affinity.as_ref().map(|pin| pin.id()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub struct CodexWebSocketPoolKey {
account_id: String,
conversation_id: String,
connection_profile: String,
response_exclusions: Vec<String>,
installation_id: Option<String>,
routing_affinity_id: Option<Uuid>,
fedramp_routing: bool,
Expand All @@ -44,6 +45,7 @@ impl CodexWebSocketPoolKey {
account_id: account_id.into(),
conversation_id: conversation_id.into(),
connection_profile: String::new(),
response_exclusions: Vec::new(),
installation_id: None,
routing_affinity_id: None,
fedramp_routing: false,
Expand All @@ -65,6 +67,16 @@ impl CodexWebSocketPoolKey {
self
}

/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
self.response_exclusions = opening_headers
.iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
.map(|(_, value)| value.clone())
.collect();
self
}

/// 隔离同一逻辑会话中由不同下游 WebSocket 驱动的并发响应链
pub(crate) fn with_downstream_connection_id(
mut self,
Expand Down Expand Up @@ -111,7 +123,7 @@ impl CodexWebSocketPoolKey {
.routing_affinity_id
.map(|id| id.to_string())
.unwrap_or_default();
short_sha256([
let parts = [
self.base_url.as_str(),
self.account_id.as_str(),
self.conversation_id.as_str(),
Expand All @@ -121,7 +133,12 @@ impl CodexWebSocketPoolKey {
self.downstream_connection_id.as_str(),
self.egress_key.as_str(),
routing_affinity.as_str(),
])
];
short_sha256(
parts
.into_iter()
.chain(self.response_exclusions.iter().map(String::as_str)),
)
}

pub(super) fn same_logical_connection(&self, other: &Self) -> bool {
Expand All @@ -132,6 +149,7 @@ impl CodexWebSocketPoolKey {
&& self.egress_key == other.egress_key
&& self.routing_affinity_id == other.routing_affinity_id
&& self.fedramp_routing == other.fedramp_routing
&& self.response_exclusions == other.response_exclusions
}
}

Expand Down
103 changes: 103 additions & 0 deletions backend/crates/providers/openai/tests/transport/websocket_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2047,6 +2047,109 @@ async fn codex_backend_client_should_discard_pooled_websocket_after_unknown_resp
assert_eq!(accepted_connections.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
const EXCLUSIONS: &[&[&str]] = &[
&[],
&["tools,usage.attribution"],
&["tools"],
&["tools", "usage.attribution"],
&[""],
];
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let mut handlers = tokio::task::JoinSet::new();
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
let actual: Vec<_> = request
.headers()
.get_all("x-codex-exclude")
.iter()
.map(|value| value.to_str().unwrap())
.collect();
assert_eq!(actual, expected);
})
.await;
handlers.spawn(async move {
let mut turn = 0;
while let Some(Ok(Message::Text(_))) = socket.next().await {
let id = format!("resp_{index}_{turn}");
socket
.send(Message::Text(
completed_websocket_response(&id, 1, 1).into(),
))
.await
.unwrap();
turn += 1;
}
});
}
drop(listener);
while let Some(result) = handlers.join_next().await {
result.unwrap();
}
});
let pool = Arc::new(CodexWebSocketPool::new(Duration::from_mins(1)));
let backend = CodexBackendClient::new(
reqwest::Client::builder().no_proxy().build().unwrap(),
format!("http://{addr}"),
test_wire_profile(),
)
.with_websocket_pool(pool.clone());
let make_request = |values: &[&str]| {
let headers: Vec<_> = values
.iter()
.map(|&value| ("x-codex-exclude", value))
.collect();
let mut request = encode_request_with_headers(
codex_request_body("gpt-test", "be brief", vec![]),
&headers,
);
request.local_conversation_id = Some("shared-session".into());
request.use_websocket = true;
request
};
let context = request_context("req_exclusions", Some("account"));
for (index, &values) in EXCLUSIONS.iter().enumerate() {
let request = make_request(values);
for (turn, expected) in ["new", "reuse"].into_iter().enumerate() {
let response = backend.create_response(&request, context).await.unwrap();
assert_eq!(
response.websocket_pool_decision.unwrap().kind(),
expected,
"{values:?}"
);
assert!(response.body.contains(&format!("resp_{index}_{turn}")));
}
let continue_from_last_response = |mut request: CodexResponsesRequest| {
request.set_previous_response_id(Some(format!("resp_{index}_1")));
request.previous_response_scope = Some(PreviousResponseScope::ConnectionLocal);
request
};
let changed = make_request(EXCLUSIONS[(index + 1) % EXCLUSIONS.len()]);
let error = backend
.create_response(&continue_from_last_response(changed), context)
.await
.expect_err("changed exclusions must require replay");
assert!(matches!(
error,
CodexClientError::WebSocket(CodexWebSocketExchangeError::ContinuationUnavailable {
reason: PreviousResponseUnavailableReason::FreshConnectionRequired,
..
})
));
let response = backend
.create_response(&continue_from_last_response(request), context)
.await
.unwrap();
assert!(response.body.contains(&format!("resp_{index}_2")));
}
pool.shutdown().await;
server.await.unwrap();
}

#[tokio::test]
async fn guardian_header_should_open_a_distinct_websocket() {
assert_changed_handshake_opens_distinct_websocket("x-codex-guardian", "reviewer").await;
Expand Down
5 changes: 4 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,9 @@ Responses 的安装身份通过正文 `client_metadata` 及 turn metadata 发送
上述过滤描述原生转发;已信任插件的显式 header 改写可以覆盖账号与画像生成的默认头,
不按认证或会话字段名称拦截,边界见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)

Responses 透传客户端的 `x-codex-exclude`,由上游按请求省略响应字段。上游 WebSocket 只在握手时读取该头,
因此连接池按最终握手中的全部同名头值复用连接。头值变化时,依赖原连接的精确续接需要客户端重放完整历史

Responses 也不透传 `x-stainless-*`、`Origin`、`Referer`、`sec-ch-ua*` 和 `sec-fetch-*`
携带的下游 SDK/浏览器环境或页面来源。过滤规则适用于所有下游客户端,与 User-Agent 无关;
原始入站头仍供 CORS、鉴权和本地观测使用。
Expand Down Expand Up @@ -2315,7 +2318,7 @@ JSON 路径支持 `$`、`.成员`、`["带特殊字符的键"]`、`[索引]`、`

WebSocket 请求头在握手时发送。隐私规则改变握手头时,普通请求按对应连接身份选择连接,
处理结果稳定时可继续复用,不因每次执行删除动作而重连。
依赖原连接的精确续接保留原连接,规则变更不能撤回已有握手发送的值
依赖原连接的精确续接在响应排除项等连接归属条件仍匹配时保留原连接,规则变更不能撤回已有握手发送的值

例如,`turn_metadata` 范围的 `$.workspaces` 配合 `remove_field` 删除整个工作区映射;
`$.workspaces.*.associated_remote_urls.*` 配合 `remove_field` 和 `pattern: "private-org"` 只删除命中的远端;
Expand Down