fix(openai): keep slow model catalog refreshes alive (#846)

Use a 30-second idle timeout for account retries and manual refreshes while keeping ordinary discovery bounded. Let the admin UI wait for these refreshes until completion or cancellation.

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
authored and GitHub committed 2026-12-04 17:49:30 +08:00
1 parent 7d6e4cc4e7
commit 21cf139c96
12 files changed
+238 -46

No files matched your search

@@ -308,6 +308,12 @@ struct CatalogRetry {
delay: Duration,
}
#[derive(Clone, Copy)]
enum CatalogFetchMode {
Discovery,
Recovery,
}
#[derive(Default)]
struct CatalogCacheState {
restored: bool,
@@ -576,13 +582,23 @@ impl CodexCredentialCatalogService {
if let Some(catalog) = self.read_account_catalog(account).await? {
return Ok(catalog);
}
self.refresh_account_catalog(account.id()).await
self.query_account_catalog(account.id(), CatalogFetchMode::Discovery)
.await
}
/// 实时刷新指定账号的模型集合,包括管理员显式查询的停用账号
pub async fn refresh_account_catalog(
&self,
account_id: &ProviderAccountId,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
self.query_account_catalog(account_id, CatalogFetchMode::Recovery)
.await
}
async fn query_account_catalog(
&self,
account_id: &ProviderAccountId,
mode: CatalogFetchMode,
) -> Result<CodexAccountCatalog, CodexCredentialCatalogError> {
let account = self
.repository
@@ -596,7 +612,7 @@ impl CodexCredentialCatalogService {
let client = self.discovery_client().await?;
let revision = self.state_revision()?;
let (catalog, entry) = self
.fetch_observation(&client, &account, &scope, None)
.fetch_observation(&client, &account, &scope, None, mode)
.await?;
if eligible_catalog_account(&account, SystemTime::now())
&& let Err(error) = self.merge_observations(revision, vec![(scope, entry)])
@@ -615,9 +631,10 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
scope: &CodexCatalogScope,
etag: Option<String>,
mode: CatalogFetchMode,
) -> Result<(CodexAccountCatalog, AccountEntry), CodexCredentialCatalogError> {
let observed_at = SystemTime::now();
let mut fetched = self.fetch_account_models(client, account).await?;
let mut fetched = self.fetch_account_models(client, account, mode).await?;
let observed = AccountCatalogObservation {
account_id: account.id().clone(),
revision: account.revision(),
@@ -664,7 +681,9 @@ impl CodexCredentialCatalogService {
account: &ProviderAccount,
) -> Result<(Vec<CodexCatalogModel>, SystemTime), CodexCredentialCatalogError> {
let client = self.discovery_client().await?;
let fetched = self.fetch_account_models(&client, account).await?;
let fetched = self
.fetch_account_models(&client, account, CatalogFetchMode::Discovery)
.await?;
if fetched.models.is_empty() {
return Err(CodexCredentialCatalogError::NoEligibleCredential);
}
@@ -728,6 +747,7 @@ impl CodexCredentialCatalogService {
&self,
client: &CodexBackendClient,
account: &ProviderAccount,
mode: CatalogFetchMode,
) -> Result<CodexModelCatalogSnapshot, CodexCredentialCatalogError> {
let deadline = tokio::time::Instant::now() + MODEL_CATALOG_TIMEOUT;
let credential =
@@ -755,22 +775,25 @@ impl CodexCredentialCatalogService {
{
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,
),
let fetch = client.fetch_models_with_context(
CodexRequestContext::auxiliary(
authorization.expose_secret(),
account.upstream_account_id(),
&request_id,
None,
),
)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
None,
);
match mode {
CatalogFetchMode::Discovery => {
tokio::time::timeout_at(deadline, fetch)
.await
.map_err(|_| CodexCredentialCatalogError::Upstream {
detail: "model catalog timed out".to_owned(),
})?
}
CatalogFetchMode::Recovery => fetch.await,
}
.map_err(|error| CodexCredentialCatalogError::Upstream {
detail: error.to_string(),
})
@@ -325,11 +325,17 @@ impl CodexCredentialCatalogService {
.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)),
let mode = match work {
Some(AccountCatalogRefresh {
retry: Some(retry), ..
}) => (retry.at <= instant).then_some(CatalogFetchMode::Recovery)?,
None if entries.get(&scope).is_some_and(|entry| entry.is_fresh(now)) => {
return None;
}
_ => CatalogFetchMode::Discovery,
};
due.then(|| (scope, account, work.and_then(|work| work.etag.clone())))
let etag = work.and_then(|work| work.etag.clone());
Some((scope, account, etag, mode))
})
.collect::<Vec<_>>()
};
@@ -345,10 +351,12 @@ impl CodexCredentialCatalogService {
});
let fetches = stream::iter(due)
.zip(starts)
.map(|((scope, account, etag), ())| {
.map(|((scope, account, etag, mode), ())| {
let client = &client;
async move {
let result = self.fetch_observation(client, &account, &scope, etag).await;
let result = self
.fetch_observation(client, &account, &scope, etag, mode)
.await;
(scope, result)
}
})
@@ -1,7 +1,12 @@
//! 上游模型目录读取;Codex 版本协商与 Messages 分页各自遵循原生合同
use crate::profile::CodexWireProfile;
use std::time::Duration;
use bytes::BytesMut;
use gateway_protocol::openai::events::retry_after_seconds_from_body;
use tokio::time::{Instant, timeout, timeout_at};
use crate::profile::CodexWireProfile;
use super::backend::{
CodexBackendClient, CodexBackendTransport, CodexClientError, CodexClientResult,
@@ -15,6 +20,8 @@ use super::super::{
response_meta,
};
const CATALOG_READ_IDLE: Duration = Duration::from_secs(30);
impl CodexBackendClient {
/// 目录优先使用显式协商版本,否则沿用调用方冻结的画像版本
pub async fn fetch_models_with_context(
@@ -112,7 +119,12 @@ impl CodexBackendClient {
.headers_mut()
.insert(gateway_protocol::peer::ROUTE_HEADER, route.clone());
}
let response = self.client.execute(request).await?;
let idle_timeout = |_| CodexClientError::StreamIdleTimeout {
timeout: CATALOG_READ_IDLE,
};
let mut response = timeout(CATALOG_READ_IDLE, self.client.execute(request))
.await
.map_err(idle_timeout)??;
let status = response.status();
let diagnostics = response_meta::diagnostics(Some(status.as_u16()), response.headers())
.with_response_origin(Some(response.url().clone()));
@@ -123,7 +135,17 @@ impl CodexBackendClient {
.then(|| catalog_etag(response.headers()))
.transpose()?
.flatten();
let body = response.bytes().await?;
let mut body = BytesMut::new();
let mut deadline = Instant::now() + CATALOG_READ_IDLE;
while let Some(chunk) = timeout_at(deadline, response.chunk())
.await
.map_err(idle_timeout)??
{
if !chunk.is_empty() {
body.extend_from_slice(&chunk);
deadline = Instant::now() + CATALOG_READ_IDLE;
}
}
if !status.is_success() {
let body = String::from_utf8_lossy(&body).into_owned();
return Err(CodexClientError::Upstream {
@@ -140,7 +162,7 @@ impl CodexBackendClient {
send_phase: CodexUpstreamSendPhase::AfterPayload,
});
}
Ok((body, etag))
Ok((body.freeze(), etag))
}
}
@@ -2,6 +2,9 @@
use super::*;
use gateway_protocol::openai::OPENAI_PROTOCOL;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
#[tokio::test]
async fn invalidation_queues_background_refresh_without_an_upstream_etag() {
@@ -363,3 +366,131 @@ async fn periodic_failure_arms_an_idle_catalog_worker_without_an_etag() {
assert!(service.cached_account_models(&account).unwrap().is_some());
server.verify().await;
}
async fn accept_catalog_request(listener: &TcpListener) -> TcpStream {
let (socket, _) = tokio::time::timeout(Duration::from_secs(5), listener.accept())
.await
.expect("expected an upstream catalog request")
.unwrap();
let mut reader = BufReader::new(socket);
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();
assert!(line.starts_with("GET /codex/models?"));
loop {
line.clear();
assert_ne!(reader.read_line(&mut line).await.unwrap(), 0);
if line == "\r\n" {
return reader.into_inner();
}
}
}
const PARTIAL_CATALOG: &[u8] = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{";
async fn stalled_catalog<T>(
listener: &TcpListener,
request: impl Future<Output = T>,
partial_body: bool,
) -> (T, u64) {
tokio::pin!(request);
let mut socket = tokio::select! {
_ = &mut request => panic!("catalog request ended before reaching the upstream"),
socket = accept_catalog_request(listener) => socket,
};
if partial_body {
socket.write_all(PARTIAL_CATALOG).await.unwrap();
}
tokio::time::pause();
let start = tokio::time::Instant::now();
let result = tokio::time::timeout(Duration::from_secs(35), request)
.await
.expect("stalled catalog request must release the connection");
let elapsed = start.elapsed().as_secs();
tokio::time::resume();
(result, elapsed)
}
async fn send_slow_catalog(listener: &TcpListener) {
let mut socket = accept_catalog_request(listener).await;
socket.write_all(PARTIAL_CATALOG).await.unwrap();
for chunk in [
br#""models":"#.as_slice(),
b"[",
br#"{"slug":"#,
br#""slow","#,
br#""display_name":"#,
br#""Slow"}"#,
b"]}",
] {
tokio::time::pause();
tokio::time::sleep(Duration::from_secs(20)).await;
tokio::time::resume();
socket.write_all(chunk).await.unwrap();
}
}
#[tokio::test]
async fn discovery_times_out_but_a_due_retry_can_publish_a_slow_catalog() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_slow_retry").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let service = service_with_catalog_cache(&store, url, catalog_cache());
let (scan, elapsed) = stalled_catalog(&listener, service.refresh_catalogs(), true).await;
scan.unwrap();
assert!((14..=15).contains(&elapsed));
assert!(service.cached_account_models(&account).unwrap().is_none());
tokio::time::pause();
tokio::time::advance(Duration::from_secs(61)).await;
tokio::time::resume();
let (retry, ()) = tokio::join!(service.refresh_catalogs(), send_slow_catalog(&listener));
retry.unwrap();
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["slow"]
);
}
#[tokio::test]
async fn manual_refresh_tracks_body_progress_and_keeps_the_catalog_on_stall() {
let store = Arc::new(MemoryAccountStore::default());
let account = seed_account(&store, "acct_slow_manual").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let service = service_with_catalog_cache(&store, url, catalog_cache());
let (miss, elapsed) = stalled_catalog(
&listener,
service.cached_or_refresh_account_catalog(&account),
true,
)
.await;
assert!(matches!(
miss,
Err(CodexCredentialCatalogError::Upstream { .. })
));
assert!((14..=15).contains(&elapsed));
let (refresh, ()) = tokio::join!(
service.refresh_account_catalog(account.id()),
send_slow_catalog(&listener)
);
assert_eq!(refresh.unwrap().models(), ["slow"]);
for partial_body in [false, true] {
let (refresh, elapsed) = stalled_catalog(
&listener,
service.refresh_account_catalog(account.id()),
partial_body,
)
.await;
assert!(matches!(
refresh,
Err(CodexCredentialCatalogError::Upstream { .. })
));
assert!((29..=30).contains(&elapsed));
assert_eq!(
service.cached_account_models(&account).unwrap().unwrap(),
["slow"]
);
}
}
+1
View File
@@ -1115,6 +1115,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
账号上游查询失败后按凭据版本和套餐独立退避,从 1 分钟倍增至最多 1 小时,到期由目录任务重试。手动刷新可立即查询,成功发布后解除该账号的退避。刷新期间继续使用上次成功的目录,凭据或套餐变化后重新发现模型。
常规目录拉取共用 15 秒的凭据加载与上游查询预算。退避到期重试和手动刷新时,凭据加载仍限 15 秒,每页最多等待响应头 30 秒,读取正文后每收到新字节重新计时,连续 30 秒没有正文进展才超时。
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
OpenAI 从账号目录生成原生列表;先按冻结政策选择来源,再读取本地账号状态核对凭据版本。同一份正文可以复用,但不会把一个账号的模型授予同套餐的其他账号。客户端版本和 Key 身份不触发额外发现
+6 -2
View File
@@ -33,11 +33,15 @@ export function getAccountModelCatalog(data: AccountIdParam, options: RequestOpt
})
}
export function refreshAccountModels(data: AccountIdParam, options: RequestOptions = {}) {
export function refreshAccountModels({ accountId, provider }: AccountIdParam & { provider?: string }, options: RequestOptions = {}) {
return request<AccountModelsResponse>({
url: '/api/admin/accounts/models/refresh',
method: 'POST',
data,
data: { accountId },
// OpenAI 由上游正文进度决定超时,弹窗通过 signal 取消等待
timeout: provider === 'openai'
? 0
: undefined,
...options,
})
}
@@ -14,6 +14,7 @@ import { accountModelAccessError, accountModelIdError } from './validation'
const props = withDefaults(defineProps<{
accountId?: string
provider?: string
groupId?: string | null
disabled?: boolean
allowPreserve?: boolean
@@ -206,7 +207,9 @@ async function load(refresh = false) {
catalog.value = result.models
}
else {
const result = await (refresh ? refreshAccountModels : getAccountModels)({ accountId: id }, options)
const result = refresh
? await refreshAccountModels({ accountId: id, provider: props.provider }, options)
: await getAccountModels({ accountId: id }, options)
if (request.isCurrent(requestId)) {
catalog.value = result.models
catalogObservedAtDisplay.value = result.observedAt ? result.observedAtDisplay : undefined
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { AccountGroupRef, AccountModelAccess } from '@/api'
import type { Account, AccountGroupRef, AccountModelAccess } from '@/api'
import { ZButton, ZDialog, ZForm, ZFormItem, ZSegmented } from '@codex-proxy/ui'
@@ -10,7 +10,7 @@ import AccountSettingsFields from './AccountSettingsFields.vue'
const props = defineProps<{
selectedCount: number
catalogAccountId?: string
catalogAccount?: Pick<Account, 'id' | 'provider'>
provider?: string
groups: AccountGroupRef[]
groupsLoading: boolean
@@ -96,7 +96,7 @@ const schedulingMode = computed({
v-model:proxy-id="proxyId"
preserve-model-access
:model-account-id="catalogAccountId"
:model-account="catalogAccount"
:provider="provider"
:groups="groups"
:groups-loading="groupsLoading"
@@ -1,5 +1,5 @@
<script setup lang="ts">
import type { AccountGroupRef, AccountModelAccess } from '@/api'
import type { Account, AccountGroupRef, AccountModelAccess } from '@/api'
import { ZFormItem, ZInput, ZSegmented, ZTextarea } from '@codex-proxy/ui'
import { computed } from 'vue'
@@ -18,7 +18,7 @@ withDefaults(defineProps<{
endpoint?: string | null
accountId?: string
provider?: string
modelAccountId?: string
modelAccount?: Pick<Account, 'id' | 'provider'>
preserveProxy?: boolean
preserveModelAccess?: boolean
showScheduling?: boolean
@@ -102,7 +102,7 @@ const schedulingMode = computed({
</ZFormItem>
</div>
<AccountModelAccessField v-model="modelAccess" class="sm:col-span-2" form-prop="modelAccess" :account-id="modelAccountId ?? accountId" :image-model-presets="providerAccounts(provider)?.imageModelPresets" :disabled="disabled" :allow-preserve="preserveModelAccess" />
<AccountModelAccessField v-model="modelAccess" class="sm:col-span-2" form-prop="modelAccess" :account-id="modelAccount?.id ?? accountId" :provider="modelAccount?.provider ?? provider" :image-model-presets="providerAccounts(provider)?.imageModelPresets" :disabled="disabled" :allow-preserve="preserveModelAccess" />
<ZFormItem class="sm:col-span-2" :label="t('accounts.scheduling.groupLabel')">
<AccountGroupCheckboxGrid
@@ -22,7 +22,7 @@ export function useAccountBatchEditor(options: {
const weight = shallowRef('1')
const modelAccess = ref<AccountModelAccess | undefined>()
const editedFields = ref(new Set<'concurrencyLimit' | 'weight' | 'groupIds'>())
const catalogAccountId = shallowRef<string>()
const catalogAccount = shallowRef<Pick<Account, 'id' | 'provider'>>()
const provider = shallowRef<string>()
const proxyMode = shallowRef('preserve')
const proxyId = shallowRef('')
@@ -49,7 +49,7 @@ export function useAccountBatchEditor(options: {
editingCount.value = accounts.length
modelAccess.value = undefined
editedFields.value.clear()
catalogAccountId.value = accounts[0]?.id
catalogAccount.value = accounts[0]
provider.value = accounts.every(account => account.provider === accounts[0]?.provider)
? accounts[0]?.provider
: undefined
@@ -145,7 +145,7 @@ export function useAccountBatchEditor(options: {
weight,
modelAccess,
editedFields,
catalogAccountId,
catalogAccount,
provider,
proxyMode,
proxyId,
@@ -420,10 +420,10 @@ export function useAccountConnectionTest(options: { reload: () => Promise<unknow
modelsRequestMode.value = refresh ? 'refresh' : 'load'
connectionTestError.value = ''
try {
const result = await (refresh ? refreshAccountModels : getAccountModels)(
{ accountId: account.id },
{ signal: modelsRequest.signal },
)
const requestOptions = { signal: modelsRequest.signal }
const result = refresh
? await refreshAccountModels({ accountId: account.id, provider: account.provider }, requestOptions)
: await getAccountModels({ accountId: account.id }, requestOptions)
if (!modelsRequest.isCurrent(requestId))
return
applyConnectionTestModels(result.models, account, refresh)
+2 -2
View File
@@ -172,7 +172,7 @@ const {
weight: batchWeight,
modelAccess: batchModelAccess,
editedFields: batchEditedFields,
catalogAccountId: batchCatalogAccountId,
catalogAccount: batchCatalogAccount,
provider: batchProvider,
editingCount: batchEditingCount,
proxyMode: batchProxyMode,
@@ -465,7 +465,7 @@ const {
v-model:proxy-mode="batchProxyMode"
v-model:proxy-id="batchProxyId"
v-model:selected-group-ids="batchGroupIds"
:catalog-account-id="batchCatalogAccountId"
:catalog-account="batchCatalogAccount"
:provider="batchProvider"
:edited-fields="batchEditedFields"
:selected-count="batchEditingCount"