fix(openai): honor chat session affinity during account selection (#842)

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-12-04 11:27:41 +08:00
committed by GitHub
co-authored by Zyy Codex
parent 67ac8fd067
commit 7591845f74
10 changed files with 162 additions and 72 deletions
@@ -256,20 +256,7 @@ pub(crate) fn derive_endpoint_affinity_with_headers(
if let Some(session) = body.get(body_session_field).cloned() {
body.entry("session_id").or_insert(session);
}
let session_id = account_session_with_headers(&body, payload.context(), headers)?;
session_affinity(
"root-session",
&session_id,
Some(&session_id),
client_api_key_id,
)
.map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(
&body,
payload.context(),
headers,
))
})
session_affinity_with_headers(&body, payload.context(), headers, client_api_key_id)
}
pub(crate) fn derive_live_session_affinity(
@@ -292,19 +279,18 @@ pub(crate) fn derive_live_session_affinity(
}),
);
// x-session-id 是实时通话身份,不代表根对话;只消费官方发送的 session-id
let session_id = account_session_with_headers(&Map::new(), &Map::new(), &effective)?;
session_affinity(
"root-session",
&session_id,
Some(&session_id),
client_api_key_id,
)
.map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(
&Map::new(),
&Map::new(),
&effective,
))
session_affinity_with_headers(&Map::new(), &Map::new(), &effective, client_api_key_id)
}
pub(crate) fn session_affinity_with_headers(
body: &Map<String, Value>,
context: &Map<String, Value>,
headers: &[gateway_core::engine::middleware::MiddlewareHeader],
client_api_key_id: &ClientApiKeyId,
) -> Option<CodexSessionAffinity> {
let session = account_session_with_headers(body, context, headers)?;
root_session_affinity(Some(&session), client_api_key_id).map(|affinity| {
affinity.with_follow_only(follows_session_with_headers(body, context, headers))
})
}
@@ -3,8 +3,30 @@
use gateway_core::account::scope::FrozenAccountScope;
use gateway_core::account::{ProviderAccount, ProviderAccountId};
use super::api_key::ApiKeyProtocol;
use super::types::CODEX_AUTHENTICATION_KIND_OAUTH;
// 原生资格在账号边界检查,显式插件适配拥有自己的输入协议
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum NativeProtocol {
Fixed(ApiKeyProtocol),
Chat,
Unsupported,
}
impl NativeProtocol {
pub(super) fn for_source(protocol: &str) -> Self {
match protocol {
gateway_protocol::openai::OPENAI_PROTOCOL => Self::Fixed(ApiKeyProtocol::Responses),
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL | "token-count" => {
Self::Fixed(ApiKeyProtocol::Messages)
}
gateway_protocol::chat_completions::CHAT_PROTOCOL => Self::Chat,
_ => Self::Unsupported,
}
}
}
/// 选号使用的模型与端点类别,原生 Images 和 Search 允许模型未知
#[derive(Clone, Copy)]
pub(crate) enum CodexSelectionModel<'a> {
@@ -24,6 +24,7 @@ pub(crate) use affinity::{
derive_codex_transport_key, derive_endpoint_affinity_with_headers,
derive_live_session_affinity, derive_messages_session_affinity,
derive_previous_response_id_hash, derive_turn_alias, root_session_affinity,
session_affinity_with_headers,
};
pub(crate) use eligibility::CodexSelectionModel;
pub(crate) use oauth::oauth_owner_ref;
@@ -10,6 +10,8 @@ use gateway_core::policy::ClientApiKeyId;
use gateway_core::provider_ports::ProviderConcurrencyPool;
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
use super::eligibility::NativeProtocol;
const PROJECTION_TTL: Duration = Duration::from_millis(200);
const MAX_PROJECTIONS: usize = 32;
const MAX_CACHED_CANDIDATES: usize = 8192;
@@ -19,6 +21,7 @@ pub(super) struct SchedulingProjectionKey {
pub client_key: ClientApiKeyId,
pub scope: Arc<FrozenAccountScope>,
pub model: String,
pub native_protocol: NativeProtocol,
pub policy: AccountSelectionPolicy,
pub requires_websocket: bool,
pub concurrency_pool: ProviderConcurrencyPool,
@@ -40,7 +40,7 @@ use super::affinity::CodexSessionAffinity;
use super::catalog::CodexCredentialCatalogService;
use super::codec::CodexRuntimeAuthentication;
use super::cookie::CodexCookiePolicy;
use super::eligibility::CodexSelectionModel;
use super::eligibility::{CodexSelectionModel, NativeProtocol};
use super::quota::CodexCredentialQuotaService;
use super::refresh::refresh_recovery_deadline;
use super::repository::{CodexCredentialRepository, CredentialRepositoryError};
@@ -816,6 +816,7 @@ impl CodexCredentialSelector {
client_key: request.attempt.client_api_key_ref().clone(),
scope: Arc::clone(scope),
model: model.to_owned(),
native_protocol: request.native_protocol,
policy: request.attempt.account_selection_policy(),
requires_websocket: request.requires_websocket,
concurrency_pool,
@@ -2540,24 +2541,3 @@ fn minimum_duration(current: Option<Duration>, candidate: Option<Duration>) -> O
(None, candidate) => candidate,
}
}
// 原生资格在账号边界检查,显式插件适配拥有自己的输入协议
#[derive(Clone, Copy)]
enum NativeProtocol {
Fixed(ApiKeyProtocol),
Chat,
Unsupported,
}
impl NativeProtocol {
fn for_source(protocol: &str) -> Self {
match protocol {
gateway_protocol::openai::OPENAI_PROTOCOL => Self::Fixed(ApiKeyProtocol::Responses),
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL | "token-count" => {
Self::Fixed(ApiKeyProtocol::Messages)
}
gateway_protocol::chat_completions::CHAT_PROTOCOL => Self::Chat,
_ => Self::Unsupported,
}
}
}
@@ -745,11 +745,6 @@ impl Provider for CodexProvider {
requires_websocket,
)
});
let messages_affinity = crate::credential::derive_messages_session_affinity(
generate.protocol_payload(),
&[],
context.client_api_key_ref(),
);
if let ContinuationAttempt::RotateForClientReplay(trigger) = context.continuation_attempt()
&& (selection_session_affinity.is_none()
|| (trigger == ClientReplayTrigger::UpstreamCapacity
@@ -762,11 +757,28 @@ impl Provider for CodexProvider {
UpstreamSendState::NotSent,
));
}
// Messages 身份与内容亲和仅交给选号器,不建立 OpenAI 轮次或原生续接关联
let payload = generate.protocol_payload();
// Chat 转换保留入站会话头,正文中的 Responses 专用字段不会进入转换结果
let protocol_affinity = if !adapted
&& payload.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL
{
crate::credential::session_affinity_with_headers(
&Map::new(),
payload.context(),
&[],
context.client_api_key_ref(),
)
} else {
crate::credential::derive_messages_session_affinity(
payload,
&[],
context.client_api_key_ref(),
)
};
let account_affinity = selection_session_affinity
.as_ref()
.or(cache_preference.as_ref())
.or(messages_affinity.as_ref());
.or(protocol_affinity.as_ref());
let selection_started_at = Instant::now();
let selection = async {
self.selector
@@ -852,7 +864,6 @@ impl Provider for CodexProvider {
.map_err(|_| provider_error(ProviderErrorKind::Protocol, UpstreamSendState::NotSent))?;
let account_id = lease.account_id().clone();
// 账号确定后再判断强制档位,避免借用其他账号的同名模型;attempt 可以继续改写正文
let payload = generate.protocol_payload();
let mut operation = Operation::Generate(generate.clone());
if payload.protocol() == OPENAI_PROTOCOL
&& !(adapter.is_none()
@@ -141,8 +141,8 @@ async fn changed_owner_and_lease_contention_refresh_the_complete_pool() {
}
#[tokio::test]
async fn projection_is_isolated_by_client_scope_model_and_account_policy() {
for changed in ["client", "scope", "model", "concurrency"] {
async fn projection_is_isolated_by_client_scope_model_protocol_and_account_policy() {
for changed in ["client", "scope", "model", "protocol", "concurrency"] {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_first", "test-first");
create_account(&store, "acct_second", "test-second");
@@ -173,18 +173,24 @@ async fn projection_is_isolated_by_client_scope_model_and_account_policy() {
scope,
policy,
);
let error = select(
&selector,
&attempt,
&key,
if changed == "model" {
"gpt-5.5"
} else {
"gpt-5.4"
},
)
.await
.unwrap_err();
let error = selector
.select(&SelectCodexCredential {
protocol: if changed == "protocol" {
gateway_protocol::chat_completions::CHAT_PROTOCOL
} else {
gateway_protocol::openai::OPENAI_PROTOCOL
},
upstream_model: if changed == "model" {
"gpt-5.5"
} else {
"gpt-5.4"
},
request_url: &Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
attempt: &attempt,
session_affinity_key: Some(&key),
})
.await
.unwrap_err();
assert!(
matches!(error, CredentialSelectionError::Store(_)),
"{changed}: {error:?}"
@@ -197,6 +197,86 @@ async fn cyber_policy_session_exclusion_has_actionable_non_retryable_error() {
);
}
#[tokio::test]
async fn chat_session_follows_the_bound_account_and_only_the_root_migrates_on_model_denial() {
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode};
use gateway_core::concurrency::ConcurrencyQueuePolicy;
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/codex/responses"))
.respond_with(
ResponseTemplate::new(200).set_body_raw(CAPTURE_COMPLETED_SSE, "text/event-stream"),
)
.expect(3)
.mount(&server)
.await;
let store = Arc::new(MemoryAccountStore::default());
let mut accounts = BTreeMap::new();
for (id, denied) in [
("acct_subagent_a", "model-b"),
("acct_subagent_b", "model-a"),
] {
create_account(&store, id).await;
let access =
AccountModelAccess::new(AccountModelAccessMode::Denylist, vec![denied.to_owned()])
.unwrap();
accounts.insert(
ProviderAccountId::new(id).unwrap(),
RuntimeAccount::new(ProviderKind::new("openai").unwrap(), BTreeSet::new())
.with_model_access(access),
);
}
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(RuntimeAccountDirectory::new(accounts)),
ClientRoutingScope::all_accounts(),
));
let provider = provider_with_affinity_and_base_url(&store, Arc::default(), server.uri());
let policy = account_policy().with_queue(ConcurrencyQueuePolicy {
max_waiting: 1,
timeout: Duration::from_millis(50),
});
for (thread, model, expected) in [
("root", "model-a", Some("acct_subagent_a")),
("child", "model-b", None),
("root", "model-b", Some("acct_subagent_b")),
("child", "shared-model", Some("acct_subagent_b")),
] {
let metadata = json!({"session_id":"root","thread_id":thread}).to_string();
let payload = ProtocolPayload::json_object(
gateway_protocol::chat_completions::CHAT_PROTOCOL,
json!({"model":model,"messages":[{"role":"user","content":"hello"}],"stream":true})
.as_object()
.unwrap()
.clone(),
)
.unwrap()
.with_context(Map::from_iter([("turn_metadata".into(), json!(metadata))]));
let request = planned_request_for_model(
"openai",
Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
model,
);
let attempt = context_with_affinity_policy("req_chat_session", scope.clone(), policy)
.with_transport(AttemptTransport::Fallback);
let result = provider.clone().execute(request, attempt).await;
if let Some(expected) = expected {
let mut stream = result.unwrap();
assert_eq!(stream.metadata().provider_account_id().as_str(), expected);
while let Some(event) = stream.next().await {
event.unwrap();
}
} else {
let error = result
.err()
.expect("child must wait for the root to migrate");
assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
}
}
server.verify().await;
}
#[derive(Debug)]
struct ChangeTurnMetadata(&'static [u8]);
+1
View File
@@ -2655,6 +2655,7 @@ OpenAI 在上述模式下还保留以下协议规则,包括带明确 Claude Co
插件显式选号及原生续写的状态归属约束在三种模式下仍然生效
Chat Completions 使用原生 OpenAI Provider 时,选号会读取 `x-codex-turn-metadata` 中的会话与线程身份,也支持显式会话头 `session-id` 或 `session_id`。严格模式下,根请求可在绑定账号受模型限制时迁移,后代线程跟随根请求的账号。
Chat Completions 和 Responses 通过原生 OpenAI Provider 选号时,缺少显式会话 ID 的请求会在同一 Client Key 下匹配账号亲和。
网关先匹配客户端传入的 `prompt_cache_key`,否则按上游模型、开头的指令和首条用户消息的文本匹配。
后续消息及工具列表不参与匹配。优先模式允许临时分流;严格模式沿用根请求的等待与迁移规则,启用账号排队时等待繁忙的绑定账号,关闭排队或账号失效时允许重新选号并迁移绑定。
+1 -1
View File
@@ -852,7 +852,7 @@ OpenAI Provider 解释官方逻辑 `session_id` 与 `thread_id`,按 Client Key
插件显式选号由 Core 复核账号资格并取得租约,native continuation 受独立的状态 owner 与安全重放边界约束
OpenAI 固定归属请求直接读取目标账号,其余请求按冻结的账号 ID 范围查询 Store
原生会话的完整候选投影由 Provider 短时持有,按 Client Key、冻结范围、模型、调度策略、传输和容量池隔离
原生会话的完整候选投影由 Provider 短时持有,按 Client Key、冻结范围、模型、原生协议资格、调度策略、传输和容量池隔离
投影从读取开始保留 200ms,最多 32 项且合计 8,192 个候选,同范围读取合并,不同范围独立
健康绑定每次重读目标账号及其冷却、运行状态和凭据,容量观测复用完整投影,最终准入由原子租约裁决
目标失效、租约争用或凭据版本冲突触发完整刷新,策略插件和受管适配器使用完整候选评估