Compare commits

..
Author SHA1 Message Date
ZyyandCodex 09f3b39bbc chore: bump version to 3.61.1-rc.4
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:37:01 +08:00
7591845f74 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>
2026-12-04 11:27:41 +08:00
ZyyandCodex 67ac8fd067 fix(deps): update DOMPurify to 3.5.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:14:27 +08:00
b232e367fc fix(openai): defer failed account catalog refresh with per-scope backoff (#839)
* fix(openai): defer failed account catalog refresh with per-scope backoff

* style: cargo fmt refresh.rs

* fix(openai): keep stale-catalog accounts probeable during refresh backoff

* fix(openai): schedule account catalog retries independently

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-04 11:02:02 +08:00
ZyyandCodex 0bdaa29907 fix(ui): clarify update actions and align dashboard empty state
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 21:13:07 +08:00
github-actions[bot] cc798e33a1 chore(release): update release channels to 3.61.1-rc.3 2026-12-03 18:48:31 +08:00
30 changed files with 706 additions and 357 deletions
@@ -341,6 +341,11 @@ pub(super) fn map_catalog_error(error: CodexCredentialCatalogError) -> ProviderA
.with_public_message(message)
.with_source(source);
}
Error::Store(source) => {
return provider_admin_error(Kind::Unavailable)
.with_public_message("模型目录存储暂不可用")
.with_source(source);
}
Error::InvalidEtag => (Kind::Invalid, "模型目录版本无效,请重新查询"),
Error::NoEligibleCredential => (Kind::NotFound, "没有可查询模型的账号"),
Error::ConcurrentUpdate => (Kind::Conflict, "模型目录正在更新,请稍后重试"),
@@ -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))
})
}
@@ -13,6 +13,7 @@ use gateway_core::account::AccountCatalogObservation;
use gateway_core::account::{
CredentialRevision, CredentialState, OpaqueProviderData, ProviderAccount, ProviderAccountId,
};
use gateway_core::error::{StoreError, StoreErrorKind};
use gateway_core::provider_ports::{
ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCatalogScope,
ProviderRuntimePolicyPort,
@@ -39,6 +40,8 @@ const CATALOG_REFRESH_AFTER: Duration = Duration::from_hours(1);
const MAX_ACCOUNT_CATALOG_MODELS: usize = 2_048;
const MODEL_CATALOG_TIMEOUT: Duration = Duration::from_secs(15);
const CATALOG_FAILURE_BACKOFF_BASE: Duration = Duration::from_secs(60);
const CATALOG_FAILURE_BACKOFF_MAX: Duration = Duration::from_hours(1);
const REFRESH_CONCURRENCY: usize = 32;
// 同时到期或导入大量账号时也限制起始速率,不能把连接并发上限当作请求速率上限
const REFRESH_SPACING: Duration = Duration::from_millis(10);
@@ -272,6 +275,8 @@ pub enum CodexCredentialCatalogError {
Credential(#[from] CredentialRepositoryError),
#[error("Codex model catalog upstream query failed: {detail}")]
Upstream { detail: String },
#[error("Codex model catalog storage is unavailable")]
Store(#[from] StoreError),
#[error("Codex model catalog cache is unavailable")]
Cache,
#[error("Codex model catalog ETag is invalid")]
@@ -282,13 +287,34 @@ pub enum CodexCredentialCatalogError {
Profile(#[source] gateway_core::error::ErrorSource),
}
impl CodexCredentialCatalogError {
fn is_account_failure(&self) -> bool {
matches!(
self,
Self::Upstream { .. }
| Self::Credential(CredentialRepositoryError::InvalidCredentialData(_))
)
}
}
#[derive(Default)]
struct AccountCatalogRefresh {
etag: Option<String>,
retry: Option<CatalogRetry>,
}
struct CatalogRetry {
at: tokio::time::Instant,
delay: Duration,
}
#[derive(Default)]
struct CatalogCacheState {
restored: bool,
revision: u64,
generation: u64,
snapshot: Option<Arc<CodexCredentialCatalogSnapshot>>,
pending: BTreeMap<CodexCatalogScope, String>,
refreshes: BTreeMap<CodexCatalogScope, AccountCatalogRefresh>,
}
#[derive(Clone)]
@@ -301,6 +327,7 @@ pub struct CodexCredentialCatalogService {
runtime_policy: Arc<dyn ProviderRuntimePolicyPort>,
cache: Arc<RwLock<CatalogCacheState>>,
refresh_notification: Arc<Notify>,
retry_changed: Arc<Notify>,
refresh_lock: Arc<tokio::sync::Mutex<()>>,
publication: Arc<std::sync::Mutex<()>>,
}
@@ -323,6 +350,7 @@ impl CodexCredentialCatalogService {
runtime_policy,
cache: Arc::new(RwLock::new(CatalogCacheState::default())),
refresh_notification: Arc::new(Notify::new()),
retry_changed: Arc::new(Notify::new()),
refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
publication: Default::default(),
}
@@ -601,8 +629,7 @@ impl CodexCredentialCatalogService {
.repository
.store()
.save_account_catalog(&observed, &fetched.document)
.await
.map_err(|_| CodexCredentialCatalogError::Cache)?
.await?
{
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
}
@@ -702,43 +729,51 @@ impl CodexCredentialCatalogService {
client: &CodexBackendClient,
account: &ProviderAccount,
) -> Result<CodexModelCatalogSnapshot, CodexCredentialCatalogError> {
tokio::time::timeout(MODEL_CATALOG_TIMEOUT, async {
let credential = self.repository.load_runtime_credential(account).await?;
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
let authorization = credential
.authentication
.authorization_header()
.map_err(CredentialRepositoryError::from)?;
let mut client = credential
.authentication
.model_client_for_account(client, account)
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})?;
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
{
client = client.with_messages_api_base_url(&auth.configuration.base_url);
}
let result = client
.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
None,
)
.await;
result.map_err(|error| CodexCredentialCatalogError::Upstream {
let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT;
let credential =
tokio::time::timeout_at(deadline, self.repository.load_runtime_credential(account))
.await
.map_err(|error| {
CredentialRepositoryError::Store(StoreError::caused_by(
StoreErrorKind::Unavailable,
error,
))
})??;
let request_id = format!("catalog_{}", Uuid::now_v7().simple());
let authorization = credential
.authentication
.authorization_header()
.map_err(CredentialRepositoryError::from)?;
let mut client = credential
.authentication
.model_client_for_account(client, account)
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
})
})?;
if let super::CodexRuntimeAuthentication::ApiKey(auth) = &credential.authentication
&& auth.configuration.protocol == super::ApiKeyProtocol::Messages
{
client = client.with_messages_api_base_url(&auth.configuration.base_url);
}
tokio::time::timeout_at(
deadline,
client.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
None,
),
)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
}
}
@@ -12,8 +12,7 @@ impl CodexCredentialCatalogService {
.repository
.store()
.load_account_catalogs(&provider)
.await
.map_err(|_| CodexCredentialCatalogError::Cache)?;
.await?;
let mut entries = Entries::new();
for group in groups {
let decoded =
@@ -91,7 +90,7 @@ impl CodexCredentialCatalogService {
.map_err(|_| CodexCredentialCatalogError::Cache)?;
cache.revision = cache.revision.wrapping_add(1);
cache
.pending
.refreshes
.retain(|scope, _| !ids.contains(&scope.account_id) || current.contains(scope));
cache.revision
};
@@ -120,8 +119,11 @@ impl CodexCredentialCatalogService {
.cache
.write()
.map_err(|_| CodexCredentialCatalogError::Cache)?;
let pending = state.pending.get(&scope);
if pending.is_some_and(|tag| tag == etag) {
let pending = state
.refreshes
.get(&scope)
.and_then(|work| work.etag.as_deref());
if pending == Some(etag) {
return Ok(false);
}
if let Some(entry) = state.snapshot.as_ref().and_then(|s| s.entries.get(&scope))
@@ -129,17 +131,22 @@ impl CodexCredentialCatalogService {
{
// 已收到变更时,迟到的旧标记不能覆盖待刷新版本
if pending.is_none() && entry.etag.as_deref() == Some(etag) {
let mut confirmed_at = entry
*entry
.etag_confirmed_at
.lock()
.map_err(|_| CodexCredentialCatalogError::Cache)?;
*confirmed_at = Some(tokio::time::Instant::now());
.map_err(|_| CodexCredentialCatalogError::Cache)? =
Some(tokio::time::Instant::now());
if state.refreshes.remove(&scope).is_some() {
self.retry_changed.notify_one();
}
}
return Ok(false);
}
state.pending.insert(scope, etag.to_owned());
drop(state);
self.refresh_notification.notify_one();
let work = state.refreshes.entry(scope).or_default();
work.etag = Some(etag.to_owned());
if work.retry.is_none() {
self.schedule_refresh();
}
Ok(true)
}
@@ -148,7 +155,30 @@ impl CodexCredentialCatalogService {
}
pub async fn wait_for_refresh(&self) {
self.refresh_notification.notified().await;
loop {
// 周期任务可能正在批量登记失败,等本轮结束再读取最早期限
let deadline = {
let _scan = self.refresh_lock.lock().await;
self.cache
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.refreshes
.values()
.filter_map(|work| work.retry.as_ref().map(|retry| retry.at))
.min()
};
let timer = async {
match deadline {
Some(at) => tokio::time::sleep_until(at).await,
None => std::future::pending().await,
}
};
tokio::select! {
() = self.refresh_notification.notified() => return,
() = timer => return,
() = self.retry_changed.notified() => {},
}
}
}
/// 只合并成功的账号;手动刷新和后台任务同时完成时,保留较新的观测
@@ -176,15 +206,10 @@ impl CodexCredentialCatalogService {
entries.insert(scope, Arc::new(entry));
}
}
self.publish(revision, entries)?;
Ok(())
self.publish(revision, entries)
}
fn publish(
&self,
revision: u64,
entries: Entries,
) -> Result<Option<Arc<CodexCredentialCatalogSnapshot>>, CodexCredentialCatalogError> {
fn publish(&self, revision: u64, entries: Entries) -> Result<(), CodexCredentialCatalogError> {
let next =
(!entries.is_empty()).then(|| Arc::new(CodexCredentialCatalogSnapshot::new(entries)));
let old = self.cached()?;
@@ -207,29 +232,40 @@ impl CodexCredentialCatalogService {
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
}
if let Some(snapshot) = &next {
cache.pending.retain(|scope, tag| {
cache.refreshes.retain(|scope, work| {
let Some(entry) = snapshot.entries.get(scope) else {
return true;
};
// 发布其他账号时保留通知,只有该账号更新的观测才能确认 ETag
!entry.recognizes_etag(tag)
|| old
.as_ref()
.and_then(|s| s.entries.get(scope))
.is_some_and(|previous| previous.observed_at >= entry.observed_at)
if old
.as_ref()
.and_then(|s| s.entries.get(scope))
.is_some_and(|previous| previous.observed_at >= entry.observed_at)
{
return true;
}
// 只有该账号更新的观测能解除退避,期间到达的新 ETag 仍需对账
let pending = work
.etag
.as_deref()
.is_some_and(|tag| !entry.recognizes_etag(tag));
if work.retry.take().is_some() {
self.retry_changed.notify_one();
}
if pending {
self.schedule_refresh();
}
pending
});
}
cache.snapshot = next.clone();
cache.snapshot = next;
if changed {
cache.generation = cache.generation.wrapping_add(1);
}
Ok(next)
Ok(())
}
/// 一次对账只探测缺失、过期或有新 ETag 的账号;成功逐批发布,失败不更新观测时间
pub async fn refresh_catalogs(
&self,
) -> Result<Arc<CodexCredentialCatalogSnapshot>, CodexCredentialCatalogError> {
/// 对到期账号限速探测,逐批发布成功结果并按账号安排重试
pub async fn refresh_catalogs(&self) -> Result<(), CodexCredentialCatalogError> {
let _writer = self.refresh_lock.lock().await;
// 启动时数据库暂不可用,应先重试恢复,不能把整池误判为没有历史
if !self
@@ -248,14 +284,6 @@ impl CodexCredentialCatalogService {
.filter(|a| eligible_catalog_account(a, now))
.map(|a| (CodexCatalogScope::for_account(&a), a))
.collect();
let pending = {
let mut cache = self
.cache
.write()
.map_err(|_| CodexCredentialCatalogError::Cache)?;
cache.pending.retain(|scope, _| current.contains_key(scope));
cache.pending.clone()
};
let previous = self.cached()?;
let mut entries = previous
.as_ref()
@@ -281,17 +309,32 @@ impl CodexCredentialCatalogService {
.values()
.map(|e| (e.content.digest, e.content.clone()))
.collect();
let due = current
.into_iter()
.filter(|(scope, _)| {
pending.contains_key(scope)
|| !entries.get(scope).is_some_and(|entry| entry.is_fresh(now))
})
.collect::<Vec<_>>();
let due = {
let mut cache = self
.cache
.write()
.map_err(|_| CodexCredentialCatalogError::Cache)?;
if cache.revision != revision {
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
}
cache
.refreshes
.retain(|scope, _| current.contains_key(scope));
let instant = tokio::time::Instant::now();
current
.into_iter()
.filter_map(|(scope, account)| {
let work = cache.refreshes.get(&scope);
let due = match work {
Some(work) => work.retry.as_ref().is_none_or(|retry| retry.at <= instant),
None => !entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)),
};
due.then(|| (scope, account, work.and_then(|work| work.etag.clone())))
})
.collect::<Vec<_>>()
};
if due.is_empty() {
return self
.cached()?
.ok_or(CodexCredentialCatalogError::NoEligibleCredential);
return Ok(());
}
let client = self.discovery_client().await?;
let mut pace = tokio::time::interval(REFRESH_SPACING);
@@ -302,25 +345,21 @@ impl CodexCredentialCatalogService {
});
let fetches = stream::iter(due)
.zip(starts)
.map(|((scope, account), ())| {
.map(|((scope, account, etag), ())| {
let client = &client;
let etag = pending.get(&scope).cloned();
async move {
let (_, entry) = self
.fetch_observation(client, &account, &scope, etag.clone())
.await?;
Ok((scope, entry))
let result = self.fetch_observation(client, &account, &scope, etag).await;
(scope, result)
}
})
.buffer_unordered(REFRESH_CONCURRENCY);
tokio::pin!(fetches);
let mut batch = Vec::with_capacity(PUBLICATION_BATCH);
let mut completed = 0_usize;
let mut failures = 0_usize;
let mut last_error = None;
while let Some(result) = fetches.next().await {
let mut cycle_error = None;
while let Some((scope, result)) = fetches.next().await {
match result {
Ok((scope, mut entry)) => {
Ok((_, mut entry)) => {
entry.content = contents
.entry(entry.content.digest)
.or_insert_with(|| entry.content.clone())
@@ -331,27 +370,59 @@ impl CodexCredentialCatalogService {
self.merge_observations(revision, std::mem::take(&mut batch))?;
}
}
Err(error) if error.is_account_failure() => {
self.defer_account(revision, &scope, &entries, &error)?;
}
Err(error) => {
failures += 1;
last_error = Some(error);
cycle_error = Some(error);
}
}
}
if !batch.is_empty() {
self.merge_observations(revision, batch)?;
}
if let Some(error) = &last_error {
tracing::warn!(successes=completed,failures,%error,"OpenAI account catalog refresh incomplete");
cycle_error.map_or(Ok(()), Err)
}
fn defer_account(
&self,
revision: u64,
scope: &CodexCatalogScope,
previous: &Entries,
error: &CodexCredentialCatalogError,
) -> Result<(), CodexCredentialCatalogError> {
let mut cache = self
.cache
.write()
.map_err(|_| CodexCredentialCatalogError::Cache)?;
if cache.revision != revision {
return Err(CodexCredentialCatalogError::ConcurrentUpdate);
}
if pending
.keys()
.any(|k| self.cache.read().is_ok_and(|c| c.pending.contains_key(k)))
&& let Some(error) = last_error.clone()
// 手动刷新可能在后台请求期间发布了新目录,迟到的失败不能恢复旧退避
let latest = cache.snapshot.as_ref().and_then(|s| s.entries.get(scope));
if latest.map(|e| e.observed_at) != previous.get(scope).map(|e| e.observed_at) {
return Ok(());
}
// 普通响应也能在探测期间确认旧目录仍有效
if !cache.refreshes.contains_key(scope)
&& latest.is_some_and(|entry| entry.is_fresh(SystemTime::now()))
{
self.refresh_notification.notify_one();
return Err(error);
return Ok(());
}
self.cached()?
.ok_or(last_error.unwrap_or(CodexCredentialCatalogError::NoEligibleCredential))
let work = cache.refreshes.entry(scope.clone()).or_default();
let delay = work
.retry
.as_ref()
.map_or(CATALOG_FAILURE_BACKOFF_BASE, |retry| {
(retry.delay * 2).min(CATALOG_FAILURE_BACKOFF_MAX)
});
work.retry = Some(CatalogRetry {
at: tokio::time::Instant::now() + delay,
delay,
});
drop(cache);
self.retry_changed.notify_one();
tracing::warn!(account_id = %scope.account_id, retry_after_secs = delay.as_secs(), %error, "OpenAI account catalog refresh deferred");
Ok(())
}
}
@@ -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,
}
}
}
@@ -57,15 +57,15 @@ use uuid::Uuid;
use crate::billing::normalize_service_tier;
use crate::credential::{
CodexAccountFailure, CodexCredentialCatalogError, CodexCredentialCatalogService,
CodexCredentialLease, CodexCredentialQuotaService, CodexCredentialRefreshOutcome,
CodexCredentialRefreshService, CodexCredentialRepository, CodexCredentialSelector,
CodexCyberPolicyScope, CodexQuotaRefreshPolicy, CodexSessionAffinity, CredentialSelectionError,
RuntimeCodexCookie, SelectCodexCredential, SelectCodexProviderEndpointCredential,
derive_cache_preference, derive_codex_cyber_policy_session_key,
derive_codex_endpoint_session_affinity, derive_codex_session_affinity,
derive_codex_transport_key, derive_endpoint_affinity_with_headers,
derive_live_session_affinity, derive_previous_response_id_hash, derive_turn_alias,
CodexAccountFailure, CodexCredentialCatalogService, CodexCredentialLease,
CodexCredentialQuotaService, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
CodexCredentialRepository, CodexCredentialSelector, CodexCyberPolicyScope,
CodexQuotaRefreshPolicy, CodexSessionAffinity, CredentialSelectionError, RuntimeCodexCookie,
SelectCodexCredential, SelectCodexProviderEndpointCredential, derive_cache_preference,
derive_codex_cyber_policy_session_key, derive_codex_endpoint_session_affinity,
derive_codex_session_affinity, derive_codex_transport_key,
derive_endpoint_affinity_with_headers, derive_live_session_affinity,
derive_previous_response_id_hash, derive_turn_alias,
};
use crate::profile::{APPCAST_POLL_INTERVAL, CodexDesktopReleaseService, CodexWireProfileState};
use crate::request_identity::{account_session_with_headers, turn_id_with_headers};
@@ -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()
@@ -298,31 +298,22 @@ impl ScheduledTask for OpenAiQuotaTask {
impl ScheduledTask for OpenAiCatalogTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move {
let Some(catalogs) = context
let Some(result) = context
.cancellation()
.run_until_cancelled(self.catalog.refresh_catalogs())
.await
else {
return Ok(());
};
let result = match catalogs {
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => Ok(()),
Err(error) => Err(WorkerTaskError::safe("模型目录同步失败").with_source(error)),
};
// 成功周期尾部追加 [0, 20%) 单侧随机抖动,打破固定周期轮询特征;
// 放在周期尾部避免延迟冷启动首轮刷新,失败路径交给宿主退避不叠加。
// 抖动期间 leader lease 由宿主监督循环并发续租,不会超时。
if result.is_ok() {
let jitter = crate::jitter::catalog_refresh_jitter(
crate::jitter::random_u64(),
self.interval,
);
tokio::select! {
() = context.cancellation().cancelled() => {},
() = tokio::time::sleep(jitter) => {},
}
}
result
result.map_err(|error| WorkerTaskError::safe("模型目录同步失败").with_source(error))?;
// 成功周期尾部追加抖动,首轮刷新和失败重试不额外等待
let jitter =
crate::jitter::catalog_refresh_jitter(crate::jitter::random_u64(), self.interval);
context
.cancellation()
.run_until_cancelled(tokio::time::sleep(jitter))
.await;
Ok(())
})
}
}
@@ -340,12 +331,9 @@ impl DaemonTask for OpenAiCatalogEtagTask {
()=cancellation.cancelled()=>return Ok(()),
result=self.catalog.refresh_catalogs()=>result,
};
match result {
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => {}
Err(error) => {
self.catalog.schedule_refresh();
return Err(WorkerTaskError::safe("模型目录刷新失败").with_source(error));
}
if let Err(error) = result {
self.catalog.schedule_refresh();
return Err(WorkerTaskError::safe("模型目录刷新失败").with_source(error));
}
context.succeeded();
}
@@ -266,7 +266,7 @@ async fn failed_client_catalog_never_falls_back_to_an_out_of_scope_account_or_ca
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let scope = client_scope(&[allowed]);
assert!(service.refresh_catalogs().await.is_err());
service.refresh_catalogs().await.unwrap();
for _ in 0..2 {
assert!(
service
@@ -313,18 +313,11 @@ fn catalog_starts_without_a_snapshot_or_generation() {
}
#[tokio::test]
async fn catalog_without_openai_accounts_fails_before_network_io() {
async fn empty_account_pool_has_no_published_catalog() {
let store = Arc::new(MemoryAccountStore::default());
let error = service(&store)
.refresh_catalogs()
.await
.expect_err("empty account set");
assert!(matches!(
error,
CodexCredentialCatalogError::NoEligibleCredential
));
let service = service(&store);
service.refresh_catalogs().await.unwrap();
assert!(service.cached().unwrap().is_none());
}
#[tokio::test]
@@ -437,9 +430,11 @@ async fn service_tier_changes_should_replace_cached_metadata_and_advance_generat
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let initial = service.refresh_catalogs().await.expect("initial catalog");
service.refresh_catalogs().await.expect("initial catalog");
let initial = service.cached().unwrap().unwrap();
let generation = service.catalog_generation().get();
let cached = service.refresh_catalogs().await.expect("cached catalog");
service.refresh_catalogs().await.expect("cached catalog");
let cached = service.cached().unwrap().unwrap();
assert_eq!(cached.models(), initial.models());
assert_eq!(
cached.models()[0].metadata().service_tiers(),
@@ -454,17 +449,10 @@ async fn service_tier_changes_should_replace_cached_metadata_and_advance_generat
service
.observe_response_etag(&store.account("acct_service_tiers").unwrap(), "new")
.unwrap();
let refreshed = service.refresh_catalogs().await.expect("updated catalog");
service.refresh_catalogs().await.expect("updated catalog");
let refreshed = service.cached().unwrap().unwrap();
assert!(refreshed.models()[0].metadata().service_tiers().is_empty());
assert_eq!(service.catalog_generation().get(), generation + 1);
assert_eq!(
service
.cached()
.expect("cache read")
.expect("cached snapshot")
.models(),
refreshed.models()
);
}
#[tokio::test]
@@ -529,10 +517,11 @@ async fn cross_plan_presentation_drift_unions_on_the_first_seen_model() {
}
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let snapshot = service
service
.refresh_catalogs()
.await
.expect("presentation drift must not wedge the union");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(snapshot.models().len(), 1);
assert_eq!(snapshot.models()[0].display_name(), "GPT-5.4 Plus");
@@ -559,10 +548,11 @@ async fn cross_plan_supported_in_api_drift_unions_on_the_first_seen_model() {
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let snapshot = service
service
.refresh_catalogs()
.await
.expect("supported_in_api drift must not block catalog publication");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(snapshot.models().len(), 1);
server.verify().await;
@@ -595,10 +585,11 @@ async fn account_entitlements_keep_the_discovering_account_across_plans() {
}
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let snapshot = service
service
.refresh_catalogs()
.await
.expect("mixed-plan catalog");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(snapshot.models().len(), 2);
assert_eq!(
@@ -623,7 +614,8 @@ async fn account_entitlements_keep_the_discovering_account_across_plans() {
);
let restarted = service_with_catalog_cache(&store, server.uri(), catalog_cache());
restarted.restore().await.unwrap();
let restored = restarted.refresh_catalogs().await.unwrap();
restarted.refresh_catalogs().await.unwrap();
let restored = restarted.cached().unwrap().unwrap();
assert_eq!(
restored.model_catalog_accounts(),
snapshot.model_catalog_accounts()
@@ -797,7 +789,7 @@ async fn api_key_client_catalog_distinguishes_filtered_empty_from_fetch_failure(
.mount(&upstream)
.await;
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
assert_eq!(service.refresh_catalogs().await.is_ok(), status == 200);
service.refresh_catalogs().await.unwrap();
let result = service
.client_model_catalog(
&client_scope(&[store.account("acct_api").unwrap()]),
@@ -1033,7 +1025,8 @@ async fn api_key_catalog_hides_only_known_specialized_models_in_codex_picker() {
.mount(&upstream)
.await;
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
let snapshot = service.refresh_catalogs().await.expect("standard API IDs");
service.refresh_catalogs().await.expect("standard API IDs");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(
snapshot
.models()
@@ -1078,7 +1071,6 @@ async fn api_key_catalog_rejects_invalid_ids_and_duplicates() {
store
.seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http)
.await;
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
for invalid in [
String::new(),
"__reserved".to_owned(),
@@ -1093,13 +1085,16 @@ async fn api_key_catalog_rejects_invalid_ids_and_duplicates() {
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"data": [{"id":"valid-model"}, {"id":invalid}]
})))
.expect(1)
.mount(&upstream)
.await;
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
service.refresh_catalogs().await.unwrap();
assert!(
service.refresh_catalogs().await.is_err(),
service.cached().unwrap().is_none(),
"invalid entry accepted: {invalid:?}"
);
assert!(service.cached().expect("cache").is_none());
upstream.verify().await;
}
}
@@ -1119,7 +1114,8 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() {
}]})))
.mount(&oauth).await;
let service = service_with_catalog_cache(&store, oauth.uri(), catalog_cache());
let before = service.refresh_catalogs().await.expect("OAuth directory");
service.refresh_catalogs().await.expect("OAuth directory");
let before = service.cached().unwrap().unwrap();
store
.seed_api_key("acct_api", upstream.uri(), ResponsesTransport::Http)
.await;
@@ -1132,7 +1128,8 @@ async fn api_key_catalog_does_not_replace_native_metadata_for_shared_models() {
.mount(&upstream)
.await;
let after = service.refresh_catalogs().await.expect("mixed directory");
service.refresh_catalogs().await.expect("mixed directory");
let after = service.cached().unwrap().unwrap();
assert_eq!(
after.models(),
before.models(),
@@ -1199,10 +1196,11 @@ async fn account_catalog_documents_keep_native_objects_of_the_account_plan() {
.await;
}
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let snapshot = service
service
.refresh_catalogs()
.await
.expect("shared union snapshot");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(snapshot.models().len(), 3);
assert_eq!(snapshot.models()[1].display_name(), "Plus");
@@ -1284,10 +1282,12 @@ async fn catalog_account_membership_changes_advance_generation_without_model_cha
.mount(&server)
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let initial = service.refresh_catalogs().await.unwrap();
service.refresh_catalogs().await.unwrap();
let initial = service.cached().unwrap().unwrap();
let generation = service.catalog_generation();
let second = seed_account(&store, "acct_source_b").await;
let refreshed = service.refresh_catalogs().await.unwrap();
service.refresh_catalogs().await.unwrap();
let refreshed = service.cached().unwrap().unwrap();
assert_eq!(initial.models(), refreshed.models());
assert!(service.catalog_generation() > generation);
assert_eq!(
@@ -152,14 +152,12 @@ async fn simultaneous_periodic_refreshes_share_the_completed_scan() {
.mount(&server)
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let (first, second, third) = tokio::join!(
tokio::try_join!(
service.refresh_catalogs(),
service.refresh_catalogs(),
service.refresh_catalogs(),
);
let first = first.expect("first refresh");
assert_eq!(first.models(), second.expect("shared refresh").models());
assert_eq!(first.models(), third.expect("shared refresh").models());
)
.unwrap();
server.verify().await;
}
@@ -199,10 +197,11 @@ async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_en
.mount(&upstream)
.await;
let service = service_with_catalog_cache(&store, upstream.uri(), catalog_cache());
let snapshot = service
service
.refresh_catalogs()
.await
.expect("native background directory");
let snapshot = service.cached().unwrap().unwrap();
assert_eq!(
snapshot.models()[0].capabilities().reasoning(),
CodexCatalogCapabilityEvidence::Unknown
@@ -234,3 +233,133 @@ async fn api_key_background_catalog_preserves_negotiated_reasoning_levels_and_en
}
upstream.verify().await;
}
#[tokio::test]
async fn failed_catalog_write_keeps_the_snapshot_and_retries_without_account_backoff() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_write").await;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/codex/models"))
.respond_with(SequencedCatalogResponder {
calls: Arc::new(AtomicUsize::new(0)),
bodies: [
br#"{"models":[{"slug":"before","display_name":"Before"}]}"#,
br#"{"models":[{"slug":"after","display_name":"After"}]}"#,
],
})
.expect(3)
.mount(&server)
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
service.refresh_catalogs().await.unwrap();
service.observe_response_etag(&account, "updated").unwrap();
store.fail_catalog_write.store(true, Ordering::SeqCst);
assert!(matches!(
service.refresh_catalogs().await,
Err(CodexCredentialCatalogError::Store(_))
));
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["before"]
);
store.fail_catalog_write.store(false, Ordering::SeqCst);
service.refresh_catalogs().await.unwrap();
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["after"]
);
server.verify().await;
}
#[tokio::test]
async fn manual_catalog_recovery_releases_backoff_and_keeps_a_newer_etag() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_manual").await;
let healthy = seed_account(&store, "acct_healthy").await;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/codex/models"))
.and(header("chatgpt-account-id", "chatgpt-acct_manual"))
.respond_with(ResponseTemplate::new(503))
.up_to_n_times(1)
.with_priority(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/codex/models"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("etag", r#""v1""#)
.set_body_raw(OFFICIAL_FIXTURE, "application/json"),
)
.expect(4)
.mount(&server)
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
service.refresh_catalogs().await.unwrap();
assert!(service.observe_response_etag(&account, "v2").unwrap());
assert!(
service
.observe_response_etag(&healthy, "healthy-change")
.unwrap()
);
service.wait_for_refresh().await;
service.refresh_catalogs().await.unwrap();
assert_eq!(server.received_requests().await.unwrap().len(), 3);
assert!(service.cached_account_models(&account).unwrap().is_none());
service.refresh_account_catalog(account.id()).await.unwrap();
tokio::time::timeout(
std::time::Duration::from_secs(1),
service.wait_for_refresh(),
)
.await
.unwrap();
service.refresh_catalogs().await.unwrap();
assert!(!service.observe_response_etag(&account, "v2").unwrap());
server.verify().await;
}
#[tokio::test]
async fn periodic_failure_arms_an_idle_catalog_worker_without_an_etag() {
use std::time::Duration;
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_periodic").await;
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/codex/models"))
.respond_with(ResponseTemplate::new(503))
.up_to_n_times(1)
.with_priority(1)
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/codex/models"))
.respond_with(ResponseTemplate::new(200).set_body_raw(OFFICIAL_FIXTURE, "application/json"))
.expect(1)
.mount(&server)
.await;
let service = service_with_catalog_cache(&store, server.uri(), catalog_cache());
let wake = service.wait_for_refresh();
tokio::pin!(wake);
tokio::select! {
biased;
() = &mut wake => panic!("idle worker woke without a due account"),
result = service.refresh_catalogs() => result.unwrap(),
}
tokio::time::pause();
assert!(
tokio::time::timeout(Duration::from_secs(59), &mut wake)
.await
.is_err()
);
tokio::time::timeout(Duration::from_secs(2), wake)
.await
.expect("periodic failure must arm the retry");
tokio::time::resume();
service.refresh_catalogs().await.unwrap();
assert!(service.cached_account_models(&account).unwrap().is_some());
server.verify().await;
}
@@ -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:?}"
@@ -507,6 +507,9 @@ async fn selection_uses_the_last_catalog_for_the_same_account_identity() {
.expect(1)
.mount(&api)
.await;
tokio::time::pause();
tokio::time::advance(Duration::from_mins(1)).await;
tokio::time::resume();
catalog.refresh_catalogs().await.unwrap();
}
let mut stream = execute().await.unwrap();
@@ -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,4 +1,4 @@
//! 验证 OpenAI 目录 ETag worker 的失败交接、重启恢复与取消
//! 验证 OpenAI 目录 ETag worker 的账号退避、到期恢复与取消
use std::sync::Arc;
use std::time::Duration;
@@ -20,7 +20,7 @@ use crate::admin::{
use crate::support::{MemoryAccountStore, profile, secret};
#[tokio::test]
async fn catalog_etag_failure_returns_to_supervisor_and_recovers_pending_refresh() {
async fn catalog_etag_worker_retries_a_cold_account_without_restarting() {
let account_id = "acct_catalog_etag_worker";
let store = Arc::new(MemoryAccountStore::default());
store
@@ -104,42 +104,35 @@ async fn catalog_etag_failure_returns_to_supervisor_and_recovers_pending_refresh
panic!("catalog ETag worker must be a daemon");
};
for expected_requests in 1..=2 {
let context = WorkerDaemonContext::new(CancellationToken::new());
let result = timeout(Duration::from_secs(2), task.run(context.clone())).await;
let requests = server.received_requests().await.unwrap();
let paths: Vec<_> = requests.iter().map(|request| request.url.path()).collect();
assert!(
result.is_ok(),
"failed refresh must return control to the supervisor: {paths:?}, completed={}",
context.completed_cycles()
);
let error = result.unwrap().expect_err("catalog unavailable");
assert!(
error.error_details().is_some(),
"preserve the failure cause"
);
assert_eq!(context.completed_cycles(), 0);
assert_eq!(
requests
.iter()
.filter(|request| request.url.path() == "/codex/models")
.count(),
expected_requests,
"each run must perform only one failed refresh"
);
}
let context = WorkerDaemonContext::new(CancellationToken::new());
let run = task.run(context.clone());
tokio::pin!(run);
tokio::select! {
result = &mut run => panic!("daemon exited before recovery: {result:?}"),
result = timeout(Duration::from_secs(2), context.progress_since(0)) => {
result.expect("pending ETag must survive failed runs");
for (completed, delay_secs) in [0, 60, 120].into_iter().enumerate() {
if delay_secs > 0 {
tokio::time::pause();
tokio::select! {
result = &mut run => panic!("daemon exited during backoff: {result:?}"),
() = context.progress_since(completed as u64) => panic!("retried before deadline"),
() = tokio::time::sleep(Duration::from_secs(delay_secs - 1)) => {},
}
tokio::time::advance(Duration::from_secs(1)).await;
tokio::time::resume();
}
tokio::select! {
result = &mut run => panic!("daemon exited before cancellation: {result:?}"),
result = timeout(Duration::from_secs(2), context.progress_since(completed as u64)) => {
result.expect("catalog refresh must run when due");
}
}
let requests = server.received_requests().await.unwrap();
assert_eq!(
requests
.iter()
.filter(|r| r.url.path() == "/codex/models")
.count(),
completed + 1
);
}
assert_eq!(context.completed_cycles(), 1);
context.cancellation().cancel();
timeout(Duration::from_secs(2), run)
.await
@@ -81,6 +81,7 @@ pub(crate) struct MemoryAccountStore {
next_quota_read: Mutex<Option<(oneshot::Sender<()>, oneshot::Receiver<()>)>>,
largest_quota_read: AtomicUsize,
fail_provider_listing: AtomicBool,
pub(crate) fail_catalog_write: AtomicBool,
pending_account_reads: bool,
credential_load_hook: Mutex<Option<Arc<CredentialLoadHook>>>,
credential_loads: AtomicUsize,
@@ -425,6 +426,9 @@ impl ProviderAccountStore for MemoryAccountStore {
observation: &gateway_core::account::AccountCatalogObservation,
document: &[u8],
) -> Result<bool, StoreError> {
if self.fail_catalog_write.load(Ordering::SeqCst) {
return Err(store_error(StoreErrorKind::Unavailable));
}
let rows = self.accounts.lock().unwrap();
if !rows.get(&observation.account_id).is_some_and(|a| {
a.account.revision() == observation.revision
+3 -3
View File
@@ -1003,10 +1003,10 @@ alpha、beta、rc、exp 在 GitHub 标记为 Pre-release,不覆盖 GitHub Late
在线更新要求官方构建且起始版本不低于 **v3.18.1**,版本选择遵循上述规则;源码等非官方构建返回不支持原因,不提供可用更新。
不满足在线更新条件时,使用完整发行包或镜像[手动部署](#镜像升级与源码构建)。
点击「下载更新」后,操作日志显示下载、校验与安装过程,完成后显示「待重启」及待生效版本。点击「重启服务」并确认后才使用新程序。
检查到可用版本后,右侧的「检查更新」切换为「下载更新」。操作日志显示下载、校验与安装过程,完成后显示待生效版本,点击右侧「重启服务」后生效。重启前检查目标版本和插件兼容性,目标变化或有不兼容插件时需要确认。
「当前版本」表示正在运行的版本,「通道最新」显示所选通道已发布的版本。通道版本较低时仍显示其版本号,并提示无可用更新
启用在线重启的部署,在没有更新时也可点击「检查更新」左侧的「重启服务」。确认框提示请求中断影响,有不兼容插件时同时展示清单;取消不执行重启。服务恢复后页面自动刷新,未启用在线重启时按钮不可用
没有待生效版本时,可点击「重启服务」并确认。重启会中断正在进行的请求,服务恢复后页面自动刷新。未启用在线重启时按钮不可用
手动更换镜像或程序后,更新器会核对安装文件并校准历史状态,不以旧成功记录推断需要重启。
运行期间检测到外部文件变动或文件缺失时会报告异常,需要核对完整发行包并重启服务后再检查。
@@ -1025,7 +1025,7 @@ host:
```
`executable_path` 为可选项:未指定时,服务在启动时解析并固定当前程序路径;
显式配置时,将示例改为实际程序的绝对路径。`self_restart_enabled` 控制管理端的「立即重启」操作;
显式配置时,将示例改为实际程序的绝对路径。`self_restart_enabled` 控制管理端的在线重启;
修改配置后需手动重启当前服务一次才会生效。
以上三个字段也可分别通过 `CPR_DEPLOYMENT_MODE`、`CPR_ENABLE_SELF_RESTART` 和 `CPR_UPDATE_EXE_PATH` 设置,
YAML 中显式配置的值优先于对应环境变量
+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`,否则按上游模型、开头的指令和首条用户消息的文本匹配。
后续消息及工具列表不参与匹配。优先模式允许临时分流;严格模式沿用根请求的等待与迁移规则,启用账号排队时等待繁忙的绑定账号,关闭排队或账号失效时允许重新选号并迁移绑定。
+2 -2
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 个候选,同范围读取合并,不同范围独立
健康绑定每次重读目标账号及其冷却、运行状态和凭据,容量观测复用完整投影,最终准入由原子租约裁决
目标失效、租约争用或凭据版本冲突触发完整刷新,策略插件和受管适配器使用完整候选评估
@@ -1108,7 +1108,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
刷新期间及失败后继续使用上次成功的目录。凭据或套餐变化后重新发现模型。
账号上游查询失败后按凭据版本和套餐独立退避,从 1 分钟倍增至最多 1 小时,到期由目录任务重试。手动刷新可立即查询,成功发布后解除该账号的退避。刷新期间继续使用上次成功的目录,凭据或套餐变化后重新发现模型。
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再读取本地账号状态核对凭据版本。同一份正文可以复用,但不会把一个账号的模型授予同套餐的其他账号。客户端版本和 Key 身份不触发额外发现
+4 -4
View File
@@ -1882,8 +1882,8 @@ packages:
resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
dompurify@3.4.17:
resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==}
dompurify@3.5.1:
resolution: {integrity: sha512-9fRTM0QJhaSDzR2y4Ym59AW3J3wvNIsQrFQmDilCsExEA/Daks2t5UXh75tE38PB7v8S2/3+JP1UT89Zo9YvEg==}
dunder-proto@1.0.1:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
@@ -3568,7 +3568,7 @@ snapshots:
'@vueuse/core': 15.1.0(vue@3.5.46(typescript@6.0.3))
'@vueuse/integrations': 15.1.0(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(sortablejs@1.15.7)(vue@3.5.46(typescript@6.0.3))
dayjs: 1.11.23
dompurify: 3.4.17
dompurify: 3.5.1
es-toolkit: 1.53.2
gsap: 3.15.1
marked: 18.1.0
@@ -4760,7 +4760,7 @@ snapshots:
diff-sequences@29.6.3: {}
dompurify@3.4.17:
dompurify@3.5.1:
optionalDependencies:
'@types/trusted-types': 2.0.7
@@ -33,7 +33,6 @@
},
"errors": {
"preRestartCheck": "Pre-restart check failed",
"restart": "Restart failed, please check again",
"unconfirmed": "Update task has not been confirmed, check its status and try again",
"updateFailed": "Update failed",
"startTimeout": "Timed out waiting for v{version} to restart. Refresh the page to check the running version.",
@@ -52,6 +51,7 @@
"restarting": "Restarting",
"checking": "Checking",
"restartRequired": "Restart required",
"pendingVersion": "Restart for v{version}",
"available": "Update available",
"upToDate": "No updates available",
"notChecked": "Not checked",
@@ -33,7 +33,6 @@
},
"errors": {
"preRestartCheck": "重启前检查失败",
"restart": "重启失败,请重新检查",
"unconfirmed": "尚未确认更新任务,请检查状态后重试",
"updateFailed": "更新失败",
"startTimeout": "等待 v{version} 重启确认超时,请刷新页面查看运行版本",
@@ -52,6 +51,7 @@
"restarting": "重启中",
"checking": "检查中",
"restartRequired": "待重启",
"pendingVersion": "待重启 · v{version}",
"available": "有可用更新",
"upToDate": "无可用更新",
"notChecked": "未检查",
@@ -33,7 +33,6 @@
},
"errors": {
"preRestartCheck": "重啓前檢查失敗",
"restart": "重啓失敗,請重新檢查",
"unconfirmed": "尚未確認更新任務,請檢查狀態後重試",
"updateFailed": "更新失敗",
"startTimeout": "等待 v{version} 重新啟動確認逾時,請重新整理頁面查看執行版本",
@@ -52,6 +51,7 @@
"restarting": "重啓中",
"checking": "檢查中",
"restartRequired": "待重啓",
"pendingVersion": "待重啓 · v{version}",
"available": "有可用更新",
"upToDate": "無可用更新",
"notChecked": "未檢查",
@@ -20,9 +20,10 @@ import { storeToRefs } from 'pinia'
import { computed, nextTick, shallowRef, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { checkSystemRestart } from '@/api'
import { useRequestState } from '@/composables/useRequestState'
import { systemUpdateChannelLabels } from '@/layout/constants/system-update-channels'
import { notification as ZNotification } from '@/plugins/notification'
import { useSystemUpdateStore } from '@/stores/modules/system-update'
import { normalizeSystemVersion, useSystemUpdateStore } from '@/stores/modules/system-update'
import { errorMessage } from '@/utils/operation'
import {
resolveSystemUpdateLogClasses,
@@ -48,6 +49,7 @@ const {
updateError,
lastFailedOperation,
needRestart,
pendingVersion,
updateLogs,
updateStreaming,
updateStreamError,
@@ -57,9 +59,15 @@ const {
} = storeToRefs(systemUpdateStore)
const { loadSystem, checkUpdates, changeChannel, updateNow, restartNow } = systemUpdateStore
const updateDialog = useTemplateRef<InstanceType<typeof ZDialog>>('updateDialog')
const updateLogScrollbar = useTemplateRef<InstanceType<typeof ZScrollbar>>('updateLogScrollbar')
const restartButton = useTemplateRef<InstanceType<typeof ZButton>>('restartButton')
const checkingRestart = shallowRef(false)
const restartCheck = useRequestState((error) => {
ZNotification.error({
message: errorMessage(error, t('systemUpdate.errors.preRestartCheck')),
})
})
const { loading: checkingRestart } = restartCheck
const restartConfirmOpen = shallowRef(false)
const restartPlan = shallowRef<SystemRestartPlan | null>(null)
@@ -68,10 +76,11 @@ const presentation = computed(() => resolveSystemUpdatePresentation({
updateInfo: updateInfo.value,
loading: loading.value,
checking: checking.value || changingChannel.value,
restarting: restarting.value,
restarting: restarting.value && !restartConfirmOpen.value,
updating: updating.value,
updateError: updateError.value,
needRestart: needRestart.value,
pendingVersion: pendingVersion.value,
hasUpdate: hasUpdate.value,
updateStreaming: updateStreaming.value,
updateStreamError: updateStreamError.value,
@@ -169,48 +178,57 @@ async function handleUpdateRequest() {
}
async function handleRestart() {
if (checkingRestart.value || !canRestart.value)
if (checkingRestart.value || restartConfirmOpen.value || !canRestart.value)
return
checkingRestart.value = true
const activationVersion = pendingVersion.value
const requestId = restartCheck.start()
// 按钮在检查期间禁用,焦点留在弹窗内才能继续用 Escape 取消
updateDialog.value?.focus()
let plan: SystemRestartPlan
try {
restartPlan.value = await checkSystemRestart({ silent: true })
if (!open.value)
return
checkingRestart.value = false
await nextTick()
// 检查期间按钮暂时禁用,恢复焦点后再让确认框记录返回位置
restartButton.value?.focus()
restartConfirmOpen.value = true
plan = await checkSystemRestart({ silent: true, signal: restartCheck.signal })
}
catch (error: unknown) {
ZNotification.error({
message: errorMessage(error, t('systemUpdate.errors.preRestartCheck')),
})
restartCheck.fail(requestId, error)
return
}
finally {
checkingRestart.value = false
restartCheck.finish(requestId)
}
if (!open.value || !restartCheck.isCurrent(requestId) || !canRestart.value)
return
// 只有检查结果与点击时的待生效版本一致,才可直接继续升级
if (activationVersion && activationVersion === pendingVersion.value
&& activationVersion === normalizeSystemVersion(plan.targetVersion) && !plan.incompatiblePlugins.length) {
await restartNow(plan).catch(() => undefined)
return
}
restartPlan.value = plan
await nextTick()
if (!open.value || !restartCheck.isCurrent(requestId))
return
// 检查期间按钮暂时禁用,恢复焦点后再让确认框记录返回位置
restartButton.value?.focus()
restartConfirmOpen.value = true
}
async function handleConfirmRestart() {
if (!restartPlan.value)
return
try {
await restartNow(restartPlan.value)
restartConfirmOpen.value = false
}
catch (error: unknown) {
restartConfirmOpen.value = false
ZNotification.error({
message: errorMessage(error, t('systemUpdate.errors.restart')),
})
}
await restartNow(restartPlan.value).catch(() => undefined)
restartConfirmOpen.value = false
}
watch(open, (visible) => {
if (visible) {
void loadSystem(false).catch(() => undefined)
}
else {
restartCheck.invalidate()
restartConfirmOpen.value = false
}
})
watch(
@@ -227,6 +245,7 @@ watch(
<template>
<ZDialog
ref="updateDialog"
v-model="open"
:title="t('systemUpdate.title')"
:description="t('systemUpdate.description')"
@@ -434,7 +453,7 @@ watch(
:options="channelOptions"
:aria-label="t('systemUpdate.channels.label')"
size="small"
:disabled="!canChangeChannel"
:disabled="!canChangeChannel || checkingRestart"
@update:model-value="handleChannelChange"
/>
<ZPopover placement="top-start">
@@ -459,7 +478,9 @@ watch(
<span class="inline-flex" :tabindex="version?.restartSupported === false ? 0 : undefined">
<ZButton
ref="restartButton"
:disabled="!canRestart || checkingRestart"
:type="needRestart ? 'primary' : 'default'"
:loading="checkingRestart || (restarting && !restartConfirmOpen)"
:disabled="!canRestart"
@click="handleRestart"
>
<template #icon>
@@ -474,8 +495,21 @@ watch(
</p>
</ZPopover>
<ZButton
v-if="!needRestart && !checking && (hasUpdate || updating)"
type="primary"
:loading="updating"
:disabled="!canUpdate || checkingRestart"
@click="handleUpdateRequest"
>
<template #icon>
<Download class="size-4" />
</template>
{{ updating ? t('systemUpdate.status.updating') : t('systemUpdate.actions.install') }}
</ZButton>
<ZButton
v-else-if="!needRestart"
:loading="checking"
:disabled="loading || updating || restarting || changingChannel"
:disabled="loading || restarting || changingChannel || checkingRestart"
@click="handleCheckUpdates(true)"
>
<template #loading>
@@ -486,18 +520,6 @@ watch(
</template>
{{ t('systemUpdate.actions.check') }}
</ZButton>
<ZButton
v-if="!needRestart && (hasUpdate || updating)"
type="primary"
:loading="updating"
:disabled="!canUpdate"
@click="handleUpdateRequest"
>
<template #icon>
<Download class="size-4" />
</template>
{{ updating ? t('systemUpdate.status.updating') : t('systemUpdate.actions.install') }}
</ZButton>
</template>
</ZDialog>
@@ -11,6 +11,7 @@ interface SystemUpdatePresentationInput {
updating: boolean
updateError: string
needRestart: boolean
pendingVersion: string
hasUpdate: boolean
updateStreaming: boolean
updateStreamError: string
@@ -74,7 +75,9 @@ function resolveStatus(input: SystemUpdatePresentationInput) {
if (input.needRestart || input.hasUpdate || input.updateInfo) {
return {
label: input.needRestart
? t('systemUpdate.status.restartRequired')
? input.pendingVersion
? t('systemUpdate.status.pendingVersion', { version: input.pendingVersion })
: t('systemUpdate.status.restartRequired')
: input.hasUpdate
? t('systemUpdate.status.available')
: t('systemUpdate.status.upToDate'),
@@ -107,6 +107,9 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
})
const needRestart = computed(() => Boolean(updateStatus.value?.needRestart))
const pendingVersion = computed(() => needRestart.value
? normalizeSystemVersion(updateStatus.value?.currentVersion)
: '')
const canRestart = computed(() => version.value?.restartSupported === true
&& statusAvailable.value && !UPDATE_BUSY_PHASES.has(phaseKind.value))
const selectedChannel = computed(() => policy.value?.channel ?? 'stable')
@@ -446,6 +449,8 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
updateStreamError.value = t('systemUpdate.status.confirmingStart')
return null
}
if (error instanceof ApiError && error.status === 409)
updateInfo.value = null
updateError.value = errorMessage(error)
setPhase({ kind: 'failed' })
disconnectUpdateEvents()
@@ -539,6 +544,7 @@ export const useSystemUpdateStore = defineStore('system-update', () => {
updateError,
lastFailedOperation,
needRestart,
pendingVersion,
updateLogs,
updateStreaming,
updateStreamError,
@@ -276,7 +276,7 @@ const statusBars = computed(() => {
v-if="accounts.length === 0"
:title="t('dashboard.activeAccounts.empty')"
surface="inset"
class="min-h-40 place-content-center xl:h-full"
class="min-h-40 place-content-center xl:min-h-82.5"
/>
<TransitionGroup
v-else
+9 -9
View File
@@ -1,12 +1,12 @@
# v3.61.1-rc.3
## 优化改进
- Antigravity 自动核验对应平台的官方发布包,版本和构建号一同生效,核验失败时沿用当前画像
- 仪表盘更新指标和账号排序时平滑过渡,订阅标识与账号页统一,窄卡片下账号信息分行显示
# v3.61.1-rc.4
## 问题修复
- Google 明确要求验证时,Antigravity 将对应账号标记为待验证并停止调度,避免反复使用同一账号(#836)
- Antigravity 保留 Google 结构化拒绝的状态、错误原因和重试时间,原生流已输出内容时以 SSE 错误帧结束
- 停止或重启服务时优先收尾后台任务,超出收尾预算时在日志中标明任务名称
- OpenAI Chat Completions 选号时识别会话与线程,修复严格模式下已有可用账号却返回 503 的问题。根请求因模型限制迁移账号后,子线程跟随新账号(#841)
- OpenAI 账号的模型目录刷新失败后,从 1 分钟起逐次延长重试间隔,最长 1 小时。其他账号照常刷新,失败账号仍可手动重试(#838)
## 优化改进
- 系统更新弹窗按进度显示「检查更新」「下载更新」或「重启服务」,安装后显示待生效版本,目标版本一致且插件兼容时点击重启即可生效
- 仪表盘在宽屏下对齐账号概览的空状态
- 管理端内容清理依赖 DOMPurify 升级至 3.5.1
+4 -4
View File
@@ -1,7 +1,7 @@
version: 3.61.1-rc.3
version: 3.61.1-rc.4
published:
'3':
stable: 3.61.0
rc: 3.61.1-rc.2
beta: 3.61.1-rc.2
alpha: 3.61.1-rc.2
rc: 3.61.1-rc.3
beta: 3.61.1-rc.3
alpha: 3.61.1-rc.3