Compare commits

..
7 Commits
Author SHA1 Message Date
ZyyandCodex 45a4d580c7 chore: bump version to 3.54.5
Co-authored-by: Codex <noreply@openai.com>
2026-11-24 11:51:08 +08:00
ZyyandCodex 8075487f57 fix(openai): align spend limits and WebSocket logging with Codex 0.172
Co-authored-by: Codex <noreply@openai.com>
2026-11-24 11:49:02 +08:00
ZyyandCodex 037cbcd605 fix(deps): upgrade cookie to 0.18.3
Raise the OpenAI provider dependency floor and lock the patched release for RUSTSEC-2026-0594.

Co-authored-by: Codex <noreply@openai.com>
2026-11-23 18:12:40 +08:00
ZyyandCodex 89362e54b2 test(store): allow idle rounds while verifying analytics reset progress
Wait for a committed reset batch under lock contention and verify the injected cursor-write error before checking rollback.

Co-authored-by: Codex <noreply@openai.com>
2026-11-23 18:09:33 +08:00
ZyyandCodex f46fe43bf3 fix(openai): honor parent account affinity for Guardian review models
Check the bound parent against the authorized direct-model candidates before switching a descendant review. Keep the original model when the parent is outside that scope.

Co-authored-by: Codex <noreply@openai.com>
2026-11-23 18:09:33 +08:00
ZyyandCodex 000107597e fix(accounts): preserve quota across OAuth reauthorization
Keep the last quota observation when the upstream identity is unchanged. Include disabled OAuth accounts in quota maintenance while keeping them out of request selection.

Co-authored-by: Codex <noreply@openai.com>
2026-11-23 17:08:45 +08:00
github-actions[bot] a2c46e0dc7 chore(release): update release channels to 3.54.4 2026-11-23 04:37:46 +00:00
44 changed files with 714 additions and 133 deletions
+4 -4
View File
@@ -1004,9 +1004,9 @@ dependencies = [
[[package]]
name = "cookie"
version = "0.18.2"
version = "0.18.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
dependencies = [
"percent-encoding",
"time",
@@ -4787,7 +4787,7 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.28.0"
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7447c427513cfe685f236e1ac0513c4ea3dd9c0b#7447c427513cfe685f236e1ac0513c4ea3dd9c0b"
source = "git+https://github.com/openai-oss-forks/tokio-tungstenite?rev=7a920470d62138955446b64220c7609e46ad770e#7a920470d62138955446b64220c7609e46ad770e"
dependencies = [
"futures-util",
"log",
@@ -4996,7 +4996,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.27.0"
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=bc589d684755a8c02da0fc7e58d0861cbfc306f1#bc589d684755a8c02da0fc7e58d0861cbfc306f1"
source = "git+https://github.com/openai-oss-forks/tungstenite-rs?rev=e19950ef7828cb311e6d51a6bedcebf0192e055c#e19950ef7828cb311e6d51a6bedcebf0192e055c"
dependencies = [
"bytes",
"data-encoding",
@@ -63,7 +63,10 @@ pub(super) fn observe_account_quotas(
continue;
}
};
if !account.enabled || &account.provider_kind != provider.provider_kind() {
if &account.provider_kind != provider.provider_kind()
|| (!account.enabled
&& provider.supports_peer_connection(&account.authentication_kind))
{
continue;
}
// 后台查询与手动刷新共用认证能力分派,互联协议由 Admin 解释
@@ -209,7 +209,7 @@ impl PeerInfoService {
if context.cancellation().is_cancelled() {
break;
}
let accounts = match self.accounts.list_for_provider(provider).await {
let accounts = match self.accounts.list_for_provider(provider, false).await {
Ok(accounts) => accounts,
Err(error) => {
failure.get_or_insert(error);
@@ -26,14 +26,17 @@ use super::super::{
async fn imported_peer_accounts_should_start_observation_without_waiting_for_network() {
let events = events();
let provider = FakeProviderAdmin::new("openai", events.clone());
provider.set_import_account_ids(&["acct_first", "acct_second"]);
provider.set_import_account_ids(&["acct_disabled", "acct_first", "acct_second"]);
let mut first = account_record("openai");
first.id = "acct_first".into();
first.authentication_kind = "api_key".into();
let mut second = first.clone();
second.id = "acct_second".into();
let store = FakeAccountStore::with_account(first.clone(), events);
store.set_accounts(vec![first, second]);
let mut disabled = first.clone();
disabled.id = "acct_disabled".into();
disabled.enabled = false;
store.set_accounts(vec![disabled, first, second]);
let peer = Arc::new(PendingPeer::default());
let services = AdminHarness::new()
.provider(provider.clone())
@@ -59,8 +62,8 @@ async fn imported_peer_accounts_should_start_observation_without_waiting_for_net
.expect("import must not wait for peer response")
.expect("import committed");
peer.wait_for_requests(1).await;
assert_eq!(peer.changed.lock().unwrap().len(), 2);
assert_eq!(result.credential_ids.len(), 2);
assert_eq!(peer.changed.lock().unwrap().len(), 3);
assert_eq!(result.credential_ids.len(), 3);
assert!(provider.quota_requests().is_empty());
peer.gate.add_permits(2);
peer.wait_for_requests(2).await;
@@ -72,11 +75,13 @@ async fn imported_peer_accounts_should_start_observation_without_waiting_for_net
}
#[tokio::test]
async fn native_import_should_use_provider_quota_when_peer_service_is_available() {
async fn disabled_native_account_should_observe_quota_when_peer_service_is_available() {
let events = events();
let provider = FakeProviderAdmin::new("openai", events.clone());
provider.set_import_account_ids(&["acct_test"]);
let store = FakeAccountStore::new("openai", events);
let mut account = account_record("openai");
account.enabled = false;
let store = FakeAccountStore::with_account(account, events);
let peer = Arc::new(PendingPeer::default());
let services = AdminHarness::new()
.provider(provider.clone())
@@ -467,6 +467,7 @@ impl ProviderAccountStore for TestAccounts {
async fn list_for_provider(
&self,
provider: &ProviderKind,
include_disabled: bool,
) -> Result<Vec<ProviderAccount>, StoreError> {
if Some(provider.as_str()) == self.failed_provider {
return Err(StoreError::new(StoreErrorKind::Unavailable));
@@ -476,7 +477,9 @@ impl ProviderAccountStore for TestAccounts {
.lock()
.unwrap()
.iter()
.filter(|account| account.provider() == provider)
.filter(|account| {
account.provider() == provider && (include_disabled || account.enabled())
})
.cloned()
.collect())
}
@@ -88,9 +88,11 @@ pub trait ProviderAccountStore: Send + Sync {
async fn list_accounts(&self) -> Result<Vec<ProviderAccount>, StoreError>;
/// 额度维护可包含停用账号,请求调度只读取已启用账号
async fn list_for_provider(
&self,
provider: &ProviderKind,
include_disabled: bool,
) -> Result<Vec<ProviderAccount>, StoreError>;
/// 只读取指定 Provider 冻结范围内的已启用账号,空范围直接返回空池
@@ -637,17 +637,17 @@ impl DefaultExecutionService {
)?;
middleware.as_ref()
.is_none_or(|plan| plan.preserves_model_bindings(extension_route, kind, &model))
.then(|| (kind.clone(), model))
.then(|| (kind.clone(), provider, model))
});
if let Some((kind, model)) = direct {
if let Some((kind, provider, model)) = direct {
let account_scope = match authorization.required_account.as_ref() {
Some(id) => Arc::new(account_scope.restricted_to(&Default::default(), &[id.clone()].into())),
None => account_scope,
};
request.client.snapshot.plan_with_direct_account_model(
let plan = request.client.snapshot.plan_with_direct_account_model(
&target_model,
&request.operation,
account_scope,
Arc::clone(&account_scope),
&target_context,
DirectAccountModel {
provider: &kind,
@@ -658,6 +658,30 @@ impl DefaultExecutionService {
plan.uses_native_upstream(extension_route, &kind, account)
}),
)
.map_err(map_routing_error)?;
// 原生续接已校验固定账号,新请求只在实际选择专用模型时复核父会话
if pin.is_none()
&& let Some(candidate) = plan.candidates().first()
&& candidate.requires_direct_authentication()
&& !provider
.allows_direct_model_scope(
&request.operation,
request.client.policy.key_id(),
candidate.account_scope(),
plan.account_selection_policy(),
)
.await
.map_err(|error| GatewayError::from_provider(&error))?
{
request.client.snapshot.plan(
&target_model,
&request.operation,
account_scope,
&target_context,
)
} else {
Ok(plan)
}
} else {
request.client.snapshot.plan(
&target_model,
@@ -1185,6 +1185,17 @@ pub trait Provider: Send + Sync {
None
}
/// 自动替换模型前校验必须跟随的会话账号是否在候选范围内
async fn allows_direct_model_scope(
&self,
_operation: &Operation,
_client_key: &ClientApiKeyId,
_scope: &crate::routing::FrozenAccountScope,
_policy: crate::account::AccountSelectionPolicy,
) -> Result<bool, ProviderError> {
Ok(true)
}
/// Provider 解释自己的隐私规则,Core 仅冻结编译结果
fn compile_privacy_policy(
&self,
@@ -305,6 +305,149 @@ fn request_observation_is_stable_across_candidate_order_and_respects_session_own
}
}
struct DirectModelProvider {
parent: ProviderAccountId,
}
#[async_trait]
impl Provider for DirectModelProvider {
fn name(&self) -> &'static str {
"openai"
}
fn catalog_generation(&self) -> ProviderCatalogGeneration {
ProviderCatalogGeneration::default()
}
async fn query_model_capabilities(
&self,
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
Ok(Vec::new())
}
fn direct_account_model(
&self,
_: &PublicModelId,
_: &Operation,
_: Option<&gateway_core::operation::ProviderSessionState>,
_: &gateway_core::settings::SettingsValues,
) -> Option<UpstreamModelId> {
Some(UpstreamModelId::new("review").unwrap())
}
async fn allows_direct_model_scope(
&self,
_: &Operation,
_: &ClientApiKeyId,
scope: &FrozenAccountScope,
_: gateway_core::account::AccountSelectionPolicy,
) -> Result<bool, ProviderError> {
Ok(scope.allows(&self.parent))
}
async fn execute(
self: Arc<Self>,
request: ProviderRequest,
_: AttemptContext,
) -> Result<ProviderStream, ProviderError> {
let candidate = request.candidate();
assert!(candidate.account_scope().allows(&self.parent));
let model = candidate.upstream_model().unwrap();
let metadata = ProviderCallMetadata::new(
candidate.provider().clone(),
model.clone(),
self.parent.clone(),
UpstreamTransport::new("websocket").unwrap(),
);
let response = ResponseMeta::new("resp_direct_model", model.as_str());
Ok(ProviderStream::new(
metadata,
futures::stream::iter([
Ok(GatewayEvent::Started(response.clone()).into()),
Ok(GatewayEvent::Completed(response).into()),
]),
(),
))
}
}
#[test]
fn direct_model_uses_the_original_route_when_the_parent_is_outside_its_scope() {
block_on(async {
let kind = ProviderKind::new("openai").unwrap();
let key = ProviderAccountId::new("acct_api_key").unwrap();
let oauth = ProviderAccountId::new("acct_oauth").unwrap();
let scope = FrozenAccountScope::new(
Arc::new(RuntimeAccountDirectory::new(
[
(
key.clone(),
RuntimeAccount::new(kind.clone(), BTreeSet::new()),
),
(
oauth.clone(),
RuntimeAccount::new(kind.clone(), BTreeSet::new())
.with_direct_authentication_kind(Some("oauth".into())),
),
]
.into(),
)),
ClientRoutingScope::all_accounts(),
);
let snapshot = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
gateway_core::settings::SettingsValues::new(1, "smart", Default::default(), None, None),
vec![kind.clone()],
["gpt-start", "review"]
.map(|model| {
ProviderModel::new(
kind.clone(),
UpstreamModelId::new(model).unwrap(),
ModelCapabilities::new([OperationKind::Generate].into(), None)
.with_upstream_feature_validation(),
)
})
.into(),
vec![ClientPolicy::new(
ClientApiKeyId::new("key_start_test").unwrap(),
PlaintextClientApiKey::new("sk_start_test").unwrap(),
Arc::new(scope),
true,
RateLimits::unlimited(),
)],
)
.unwrap();
let snapshots = RuntimeSnapshotHandle::new(snapshot);
for (parent, expected) in [(key, "gpt-start"), (oauth, "review")] {
let store = Arc::new(TrackingExecutionStore::default());
let service = DefaultExecutionService::new(
snapshots.clone(),
store.clone(),
ProviderRegistry::new([
Arc::new(DirectModelProvider { parent }) as Arc<dyn Provider>
])
.unwrap(),
Arc::new(Admissions::default()),
Arc::new(UnusedContinuation),
Arc::new(RecordingClientApiKeyUsage::default()),
Arc::new(crate::RecordingDiagnostics::default()),
);
let mut started = service
.start(request(&service, ClientTransport::WebSocket))
.await
.unwrap();
assert!(started.session.next_event().await.unwrap().is_some());
started.session.detach_finalize().await;
let attempts = store.attempts.lock().unwrap();
assert_eq!(attempts.len(), 1);
assert_eq!(
attempts[0].upstream_model_id.as_ref().unwrap().as_str(),
expected
);
}
});
}
struct SessionObservationProvider(&'static str);
#[async_trait]
@@ -112,8 +112,9 @@ impl ProviderAccountStore for PgProviderAccountRepository {
async fn list_for_provider(
&self,
provider: &ProviderKind,
include_disabled: bool,
) -> Result<Vec<CoreProviderAccount>, CoreStoreError> {
self.list_provider_accounts(Some(provider.as_str()), false)
self.list_provider_accounts(Some(provider.as_str()), include_disabled)
.await
.map_err(core_store_error)?
.into_iter()
@@ -854,9 +854,11 @@ pub(crate) async fn rotate_provider_account_in_transaction(
profile: &UpdateProviderAccount,
replacement_identity: Option<&ProviderAccountIdentity>,
update: &ProviderCredentialUpdate,
preserve_name: bool,
reauthorization: bool,
) -> StoreResult<Revision> {
let replace_identity = replacement_identity.is_some();
// 同身份重新授权会更新账号资料,额度及本周期的预热进度仍属于该身份
let preserve_quota = !replace_identity && (reauthorization || update.preserve_profile);
let upstream_user_id = replacement_identity.map(ProviderAccountIdentity::upstream_user_id);
let upstream_account_id =
replacement_identity.and_then(ProviderAccountIdentity::upstream_account_id);
@@ -866,8 +868,11 @@ pub(crate) async fn rotate_provider_account_in_transaction(
set name = case when $14 or $16 then name else $4 end,
email = case when $14 then email else $5 end,
plan_type = case when $14 then plan_type else $6 end,
quota_warmup_state = case when $14 then quota_warmup_state else '{}'::jsonb end, quota_warmup_revision = provider_accounts.quota_warmup_revision + 1, provider_quota_json = case when $14 then provider_quota_json else null end, quota_paused = case when $14 then quota_paused else false end,
quota_observed_at = case when $14 then quota_observed_at else null end,
quota_warmup_state = case when $18 then quota_warmup_state else '{}'::jsonb end,
quota_warmup_revision = provider_accounts.quota_warmup_revision + 1,
provider_quota_json = case when $18 then provider_quota_json else null end,
quota_paused = case when $18 then quota_paused else false end,
quota_observed_at = case when $18 then quota_observed_at else null end,
quota_access_state = case when $11 then 'unknown' else quota_access_state end,
quota_evidence = case when $11 then null else quota_evidence end,
quota_access_observed_at = case when $11 then null else quota_access_observed_at end,
@@ -910,8 +915,9 @@ pub(crate) async fn rotate_provider_account_in_transaction(
.bind(upstream_account_id)
.bind(update.preserve_profile)
.bind(update.preserve_credential_state)
.bind(preserve_name)
.bind(reauthorization)
.bind(update.preserve_access_token_expiry)
.bind(preserve_quota)
.fetch_optional(&mut **transaction)
.await
.map_err(|error| {
@@ -1180,7 +1186,7 @@ pub(super) async fn import_provider_accounts_in_transaction(
pub(super) async fn rotate_provider_account_admin_in_transaction(
transaction: &mut Transaction<'_, Postgres>,
command: RotateProviderAccount,
preserve_name: bool,
reauthorization: bool,
) -> StoreResult<ProviderAccountAdminRotation> {
command.scope.validate()?;
require_nonempty(ENTITY, "account_id", &command.profile.id)?;
@@ -1209,7 +1215,7 @@ pub(super) async fn rotate_provider_account_admin_in_transaction(
&command.profile,
command.replacement_identity.as_ref(),
&command.credential,
preserve_name,
reauthorization,
)
.await?;
// 凭据 CAS、普通设置和审计共享事务,任何设置失败都回滚凭据更新
@@ -4,9 +4,36 @@ use super::{
TestDatabase, analytics::seed, drain_analytics, observability_query_budget,
observability_repository,
};
use std::time::Duration;
use chrono::{TimeDelta, Utc};
use gateway_store::postgres::{ObservabilityRange, PgRequestAnalyticsRepository};
async fn next_reset_batch(worker: &PgRequestAnalyticsRepository) -> gateway_store::StoreResult<()> {
// 维护锁被占用时 Worker 会返回空轮,测试按已提交批次核对游标
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let batch = worker.maintain(2).await?;
if batch.reset_progress {
return Ok(());
}
assert_eq!(
(
batch.projected_requests,
batch.rebuilt_buckets,
batch.advanced_buckets,
batch.backfilled_requests
),
(0, 0, 0, 0),
"ordinary maintenance ran during a version reset"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("analytics reset batch did not acquire the maintenance lock")
}
#[tokio::test]
async fn version_reset_persists_primary_keys_atomically_and_resumes_after_table_rewrite() {
let Some(database) = TestDatabase::create("analytics_reset_cursor").await else {
@@ -34,13 +61,26 @@ async fn version_reset_persists_primary_keys_atomically_and_resumes_after_table_
.execute(&database.pool).await.unwrap();
let worker =
PgRequestAnalyticsRepository::new(database.pool.clone(), observability_query_budget());
assert!(worker.maintain(2).await.is_err());
let error = next_reset_batch(&worker).await.unwrap_err();
let gateway_store::StoreError::Unavailable {
source: Some(source),
..
} = error
else {
panic!("expected the reset cursor trigger to reject the update");
};
let database_error = source
.downcast_ref::<sqlx::Error>()
.unwrap()
.as_database_error()
.unwrap();
assert_eq!(database_error.message(), "test reset progress failure");
let unchanged: (i64, i16, bool) = sqlx::query_as("select (select count(*) from request_analytics_facts),reset_phase,reset_cursor is null from request_analytics_build_state")
.fetch_one(&database.pool).await.unwrap();
assert_eq!(unchanged, (5, 0, true));
sqlx::raw_sql("drop trigger reject_reset_cursor on request_analytics_build_state; drop function reject_reset_cursor();")
.execute(&database.pool).await.unwrap();
assert!(worker.maintain(2).await.unwrap().reset_progress);
next_reset_batch(&worker).await.unwrap();
let cursor: serde_json::Value =
sqlx::query_scalar("select reset_cursor from request_analytics_build_state")
.fetch_one(&database.pool)
@@ -84,7 +124,7 @@ async fn version_reset_persists_primary_keys_atomically_and_resumes_after_table_
// 每轮创建新实例,所有推进事实必须来自数据库而非 Worker 内存
let worker =
PgRequestAnalyticsRepository::new(database.pool.clone(), observability_query_budget());
assert!(worker.maintain(2).await.unwrap().reset_progress);
next_reset_batch(&worker).await.unwrap();
let after: (i16, Option<serde_json::Value>) =
sqlx::query_as("select reset_phase,reset_cursor from request_analytics_build_state")
.fetch_one(&database.pool)
@@ -1,5 +1,6 @@
//! 验证账号授权回执的并发幂等、事务回滚与过期清理
use chrono::SubsecRound;
use gateway_admin::model::provider_credentials::{
AuthorizationReceiptKey, PreparedCredentialRotationFacts,
};
@@ -281,28 +282,21 @@ async fn expired_receipts_are_unreadable_and_reclaimed_without_removing_accounts
database.close().await;
}
#[tokio::test]
async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_edits() {
let Some(database) = TestDatabase::create("reauthorization_receipt").await else {
return;
};
let store = admin_account_store(&database.pool);
let (seed, context) = command(credential("acct_reauthorize", "reauthorize-user"));
let receipt = store.commit_authorization(seed, &context).await.unwrap();
let id = receipt.result.account_id.clone();
let command = AuthorizationCommit {
key: AuthorizationReceiptKey::new(
ProviderKind::new("openai").unwrap(),
"reauthorize-flow",
&context,
)
.unwrap(),
fn reauthorization(
id: &ProviderAccountId,
context: &MutationContext,
flow_id: &str,
replacement_identity: Option<ProviderAccountIdentity>,
) -> AuthorizationCommit {
AuthorizationCommit {
key: AuthorizationReceiptKey::new(ProviderKind::new("openai").unwrap(), flow_id, context)
.unwrap(),
pending: PendingAuthorizationMutation::new(
ProviderKind::new("openai").unwrap(),
AuthorizationMutationTarget::Reauthorize {
account_id: id.clone(),
},
AuthorizationOwnerBinding::from_context(&context),
AuthorizationOwnerBinding::from_context(context),
),
settings: None,
credential: AuthorizationCredentialCommit::Reauthorize(Box::new(
@@ -310,10 +304,7 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
account_id: id.clone(),
provider_kind: ProviderKind::new("openai").unwrap(),
expected_credential_revision: gateway_admin::model::Revision::new(1).unwrap(),
replacement_identity: Some(ProviderAccountIdentity::new(
"new-user".into(),
Some("new-workspace".into()),
)),
replacement_identity,
name: "remote profile".into(),
email: Some("new@example.com".into()),
plan_type: Some("plus".into()),
@@ -331,7 +322,109 @@ async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_e
next_refresh_at: None,
},
)),
}
}
#[tokio::test]
async fn reauthorization_keeps_disabled_account_quota_only_for_the_same_identity() {
let Some(database) = TestDatabase::create("reauthorization_quota").await else {
return;
};
let store = admin_account_store(&database.pool);
let repository = PgProviderAccountRepository::new(database.pool.clone());
for (slot, replacement) in [
("acct_same", None),
(
"acct_rebound",
Some(ProviderAccountIdentity::new(
"new-user".into(),
Some("new-workspace".into()),
)),
),
] {
let mut input = credential(slot, slot);
input.enabled = false;
let (seed, context) = command(input);
let id = store
.commit_authorization(seed, &context)
.await
.unwrap()
.result
.account_id;
let observed_at = SystemTime::from(Utc::now().round_subsecs(6));
let reset_at = Utc::now() + TimeDelta::days(2);
let weekly = json!({"rate_limit":{"secondary_window":{
"used_percent":42, "limit_window_seconds":604800, "reset_at":reset_at.timestamp()
}}});
let observation = QuotaObservation {
account_id: id.clone(),
expected_revision: CredentialRevision::new(1).unwrap(),
quota: OpaqueProviderData::new(weekly.as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
expected_connection: None,
quota_pause: None,
plan_type: None,
};
assert_eq!(
repository
.compare_and_swap_quota(observation.clone())
.await
.unwrap(),
QuotaWriteOutcome::Updated
);
let same_identity = replacement.is_none();
store
.commit_authorization(reauthorization(&id, &context, slot, replacement), &context)
.await
.unwrap();
let account = repository.get_account(&id).await.unwrap().unwrap();
assert!(!account.enabled());
assert_eq!(account.email(), Some("new@example.com"));
assert_eq!(
repository
.compare_and_swap_quota(observation.clone())
.await
.unwrap(),
QuotaWriteOutcome::Conflict
);
let mut snapshots = repository
.get_quotas(std::slice::from_ref(&id))
.await
.unwrap();
if same_identity {
let current = snapshots
.pop()
.expect("same quota window after reauthorization");
assert_eq!(current.expected_revision, account.revision());
assert_eq!(current.observed_at, observed_at);
assert_eq!(current.quota, observation.quota);
} else {
assert!(snapshots.is_empty());
assert_eq!(account.quota(), QuotaState::unknown());
}
}
database.close().await;
}
#[tokio::test]
async fn reauthorization_replay_keeps_the_committed_revision_and_later_profile_edits() {
let Some(database) = TestDatabase::create("reauthorization_receipt").await else {
return;
};
let store = admin_account_store(&database.pool);
let (seed, context) = command(credential("acct_reauthorize", "reauthorize-user"));
let receipt = store.commit_authorization(seed, &context).await.unwrap();
let id = receipt.result.account_id.clone();
let command = reauthorization(
&id,
&context,
"reauthorize-flow",
Some(ProviderAccountIdentity::new(
"new-user".into(),
Some("new-workspace".into()),
)),
);
let rename = UpdateAccount {
account_id: id.to_string(),
name: Some("renamed team".to_owned()),
@@ -62,7 +62,7 @@ async fn scoped_account_list_filters_ids_provider_and_live_enabled_state() {
["acct_scope_a", "acct_scope_z"]
);
let full_pool = repository
.list_for_provider(&provider)
.list_for_provider(&provider, false)
.await
.expect("load full provider pool");
assert_eq!(
@@ -72,6 +72,22 @@ async fn scoped_account_list_filters_ids_provider_and_live_enabled_state() {
.collect::<Vec<_>>(),
["acct_scope_a", "acct_scope_outside", "acct_scope_z"]
);
let maintenance = repository
.list_for_provider(&provider, true)
.await
.expect("load provider accounts for maintenance");
assert_eq!(
maintenance
.iter()
.map(|account| account.id().as_str())
.collect::<Vec<_>>(),
[
"acct_scope_a",
"acct_scope_disabled",
"acct_scope_outside",
"acct_scope_z"
]
);
let all = repository
.list_provider_accounts(None, true)
.await
@@ -272,7 +272,7 @@ async fn disabled_proxy_projects_direct_while_preserving_bindings_and_credential
projected.push(accounts.get_account(&id).await.unwrap().unwrap());
projected.push(accounts.load_current_credential(&id).await.unwrap().account);
let kind = ProviderKind::new(provider).unwrap();
projected.extend(accounts.list_for_provider(&kind).await.unwrap());
projected.extend(accounts.list_for_provider(&kind, false).await.unwrap());
let now = SystemTime::now();
projected.extend(
accounts
+3 -3
View File
@@ -14,7 +14,7 @@ base64 = "0.23.0"
bytes = "1.11.1"
chrono = { version = "0.4.45", features = ["clock", "serde"] }
chrono-tz = { version = "0.10", features = ["serde"] }
cookie = "0.18.1"
cookie = "0.18.3"
crc32fast = "1.5.0"
futures = "0.3.32"
flate2 = "1.1.9"
@@ -60,9 +60,9 @@ tokio-util = { version = "0.7.18", features = ["rt"] }
tower-service = "0.3.3"
tower-layer = "0.3.3"
# 官方 fork 支持代理连接和分帧消息的 permessage-deflate,两个提交须配套
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7447c427513cfe685f236e1ac0513c4ea3dd9c0b", features = ["proxy", "rustls-tls-native-roots"] }
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "7a920470d62138955446b64220c7609e46ad770e", features = ["proxy", "rustls-tls-native-roots"] }
tracing = "0.1.44"
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "bc589d684755a8c02da0fc7e58d0861cbfc306f1", features = ["deflate", "proxy"] }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "e19950ef7828cb311e6d51a6bedcebf0192e055c", features = ["deflate", "proxy"] }
url = "2.5.8"
uuid = { version = "1.23.3", features = ["v4", "v7"] }
# 静态链接 XZ 解码器,不要求部署环境安装 liblzma。
@@ -138,14 +138,24 @@ pub(crate) fn derive_codex_session_affinity(
request: &CodexResponsesRequest,
client_api_key_id: &ClientApiKeyId,
) -> Option<CodexSessionAffinity> {
let session_id = non_empty(request.client_account_session_id.as_deref())?;
root_session_affinity(
request.client_account_session_id.as_deref(),
client_api_key_id,
)
.map(|affinity| affinity.with_follow_only(request.client_account_follow_only))
}
pub(crate) fn root_session_affinity(
session_id: Option<&str>,
client_api_key_id: &ClientApiKeyId,
) -> Option<CodexSessionAffinity> {
let session_id = non_empty(session_id)?;
session_affinity(
"root-session",
session_id,
Some(session_id),
client_api_key_id,
)
.map(|affinity| affinity.with_follow_only(request.client_account_follow_only))
}
/// Messages 的会话只参与账号绑定,不解释为 OpenAI 轮次或原生续接身份
@@ -243,7 +243,7 @@ impl CodexCredentialCatalogService {
}
let revision = self.state_revision()?;
let now = SystemTime::now();
let accounts = self.repository.list_for_provider().await?;
let accounts = self.repository.list_for_provider(false).await?;
let current: BTreeMap<_, _> = accounts
.into_iter()
.filter(|a| eligible_catalog_account(a, now))
@@ -23,7 +23,7 @@ pub(crate) use affinity::{
derive_codex_endpoint_session_affinity, derive_codex_session_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,
derive_previous_response_id_hash, derive_turn_alias, root_session_affinity,
};
pub(crate) use eligibility::CodexSelectionModel;
pub(crate) use oauth::oauth_owner_ref;
@@ -137,7 +137,7 @@ impl CodexCredentialQuotaService {
now: DateTime<Utc>,
) -> Result<CodexWarmupSummary, CodexCredentialQuotaError> {
let mut summary = CodexWarmupSummary::default();
for account in self.repository.list_for_provider().await? {
for account in self.repository.list_for_provider(false).await? {
if !warmup::warmup_account_is_available(&account)
|| !account.quota_settings().has_warmup()
{
@@ -336,7 +336,7 @@ fn quota_refresh_candidate(
snapshot: Option<&CodexAccountQuotaSnapshot>,
now: SystemTime,
) -> Option<(ProviderAccount, Option<SystemTime>)> {
if !eligible_periodic_quota_refresh(&account, now) {
if !access_token_is_current(&account, now) {
return None;
}
if account.quota().is_exhausted() {
@@ -428,14 +428,9 @@ fn insert_projection_entry(
);
}
fn eligible_periodic_quota_refresh(account: &ProviderAccount, now: SystemTime) -> bool {
account.enabled() && access_token_is_current(account, now)
}
fn eligible_initial_quota_sync(account: &ProviderAccount, now: SystemTime) -> bool {
// 首次观察只兜底刚入库、尚无 quota 快照的账号
// 已耗尽等运行时状态必须由
// periodic 路径处理,才能保留同一账号的最小复核间隔
account.credential_state() == CredentialState::Ready
&& eligible_periodic_quota_refresh(account, now)
account.credential_state() == CredentialState::Ready && access_token_is_current(account, now)
}
@@ -131,7 +131,7 @@ impl CodexCredentialQuotaService {
&self,
now: SystemTime,
) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> {
let mut accounts = self.repository.list_for_provider().await?;
let mut accounts = self.repository.list_for_provider(true).await?;
accounts.retain(|account| {
account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
});
@@ -121,7 +121,7 @@ impl CodexCredentialQuotaService {
&self,
model: &str,
) -> Result<CodexWarmupSummary, CodexCredentialQuotaError> {
let mut accounts = self.repository.list_for_provider().await?;
let mut accounts = self.repository.list_for_provider(false).await?;
accounts.retain(warmup_account_is_available);
let mut summary = CodexWarmupSummary::default();
if accounts.is_empty() {
@@ -136,12 +136,13 @@ impl CodexCredentialRepository {
pub async fn list_for_provider(
&self,
include_disabled: bool,
) -> Result<Vec<ProviderAccount>, CredentialRepositoryError> {
let provider = ProviderKind::new(PROVIDER_NAME).map_err(|source| {
CredentialRepositoryError::InvalidCredentialData(Some(ErrorSource::new(source)))
})?;
self.store
.list_for_provider(&provider)
.list_for_provider(&provider, include_disabled)
.await
.map_err(Into::into)
}
@@ -74,6 +74,8 @@ pub enum CodexAccountFailure {
Banned,
/// 账号信用额度已耗尽
QuotaExhausted,
/// 当前凭据被上游支出上限拒绝,其他凭据的归属未知
SpendLimitExceeded,
/// 当前用量窗口已耗尽;到重置时间后可自动恢复
UsageLimitExhausted {
/// 上游返回的窗口绝对重置时刻
@@ -594,7 +596,7 @@ impl CodexCredentialSelector {
.collect());
}
if diagnostic {
return Ok(self.repository.list_for_provider().await?);
return Ok(self.repository.list_for_provider(false).await?);
}
let account_ids: Vec<_> = attempt
.account_scope()
@@ -1701,7 +1703,7 @@ impl CodexCredentialSelector {
.map(|alias| alias.map(|alias| CodexSessionAffinity::from_turn_alias(turn.clone(), alias)))
}
async fn lookup_session_affinity(
pub(crate) async fn lookup_session_affinity(
&self,
key: &ProviderSessionAffinityKey,
) -> Result<Option<ProviderSessionBinding>, CredentialSelectionError> {
@@ -1988,6 +1990,11 @@ impl CodexCredentialSelector {
.record_confirmed_exhaustion(account, QuotaEvidence::PaymentRequired, None, now)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::SpendLimitExceeded => self
.quota
.record_confirmed_exhaustion(account, QuotaEvidence::ProviderDenied, None, now)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source))),
CodexAccountFailure::UsageLimitExhausted { reset_at } => self
.quota
.record_confirmed_exhaustion(
@@ -358,7 +358,11 @@ pub(super) async fn apply_failure(
}
let needs_authoritative_quota_refresh = matches!(
failure.account_failure,
Some(CodexAccountFailure::QuotaExhausted | CodexAccountFailure::UsageLimitExhausted { .. })
Some(
CodexAccountFailure::QuotaExhausted
| CodexAccountFailure::SpendLimitExceeded
| CodexAccountFailure::UsageLimitExhausted { .. }
)
);
if failure.cyber_policy_failure {
context
@@ -1695,6 +1699,9 @@ fn upstream_failure_summary(
CodexFailureCategory::QuotaExhausted => {
(ProviderErrorKind::QuotaExhausted, "上游账号额度已用完")
}
CodexFailureCategory::SpendLimitExceeded => {
(ProviderErrorKind::QuotaExhausted, "已达到上游 API 支出上限")
}
CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"),
CodexFailureCategory::TurnRateLimited => {
(ProviderErrorKind::RateLimited, "当前对话轮次受到限流")
@@ -1767,6 +1774,7 @@ pub(super) fn account_failure(
retry_after: retry_after_seconds.map(Duration::from_secs),
}),
CodexFailureCategory::QuotaExhausted => Some(CodexAccountFailure::QuotaExhausted),
CodexFailureCategory::SpendLimitExceeded => Some(CodexAccountFailure::SpendLimitExceeded),
CodexFailureCategory::CloudflareChallenge => {
Some(CodexAccountFailure::CloudflareChallenge {
retry_after: retry_after_seconds.map(Duration::from_secs),
@@ -432,6 +432,40 @@ impl Provider for CodexProvider {
)
}
async fn allows_direct_model_scope(
&self,
operation: &Operation,
client_key: &gateway_core::policy::ClientApiKeyId,
scope: &gateway_core::routing::FrozenAccountScope,
policy: gateway_core::account::AccountSelectionPolicy,
) -> Result<bool, ProviderError> {
let Operation::Generate(generate) = operation else {
return Ok(true);
};
let payload = generate.protocol_payload();
if policy.openai_account_affinity() != AccountAffinity::Strict
|| !crate::request_identity::follows_session_with_headers(
payload.body(),
payload.context(),
&[],
)
{
return Ok(true);
}
let session = account_session_with_headers(payload.body(), payload.context(), &[]);
let Some(affinity) =
crate::credential::root_session_affinity(session.as_deref(), client_key)
else {
return Ok(true);
};
let binding = self
.selector
.lookup_session_affinity(affinity.key())
.await
.map_err(map_selection_error)?;
Ok(binding.is_none_or(|binding| scope.allows(binding.account_id())))
}
fn compile_privacy_policy(
&self,
policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
@@ -50,6 +50,8 @@ pub enum CodexFailureCategory {
RateLimited,
/// 当前 turn 的限流交给客户端等待,不据此推导账号级冷却
TurnRateLimited,
/// 上游 API 支出已达上限,本次请求终止,作用范围由原始错误码标识
SpendLimitExceeded,
QuotaExhausted,
CloudflareChallenge,
CloudflarePathBlocked,
@@ -467,6 +469,18 @@ fn classify_upstream_failure(
if code == "turn_rate_limit_exceeded" {
return CodexFailureCategory::TurnRateLimited;
}
if matches!(status, None | Some(StatusCode::TOO_MANY_REQUESTS))
&& matches!(
fields.code.as_deref(),
Some(
"api_key_spend_limit_exceeded"
| "project_spend_limit_exceeded"
| "organization_spend_limit_exceeded"
)
)
{
return CodexFailureCategory::SpendLimitExceeded;
}
// 容量拒绝可能带 400/429/503;仅用结构化错误字段识别,不能扫描任意正文
if is_capacity_error(
@@ -72,9 +72,9 @@ fn local_service(
}
#[tokio::test]
async fn zero_initial_delay_keeps_immediate_first_observation() {
async fn disabled_account_without_quota_is_observed_when_initial_delay_expires() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_initial_zero").await;
create_account_with_enabled(&store, "acct_initial_zero", false).await;
let server = MockServer::start().await;
mount_usage(&server, 200).await;
let service = local_service(&store, &server, zero_delays());
@@ -278,10 +278,10 @@ async fn exhausted_reset_refreshes_quickly_then_backs_off_and_recovers_from_usag
}
#[tokio::test]
async fn allowed_account_with_expired_window_synchronizes_at_reset_grace() {
async fn disabled_account_with_expired_window_synchronizes_at_reset_grace() {
let mut now = SystemTime::now();
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_allowed_expired_window").await;
create_account_with_enabled(&store, "acct_allowed_expired_window", false).await;
let account = store
.account("acct_allowed_expired_window")
.expect("account");
@@ -143,6 +143,88 @@ async fn guardian_model_matches_structured_reviewer_and_any_original_model() {
}
}
#[tokio::test]
async fn guardian_direct_model_respects_the_strict_parent_account() {
let store = Arc::new(MemoryAccountStore::default());
let affinity = Arc::new(MemorySessionAffinity::default());
let provider = provider_with_affinity(&store, affinity.clone());
let kind = ProviderKind::new("openai").unwrap();
let key = ClientApiKeyId::new("key_openai_contract").unwrap();
let oauth = ProviderAccountId::new("acct_oauth").unwrap();
let api_key = ProviderAccountId::new("acct_api_key").unwrap();
let root = super::session_binding::turn_request("root", "root-turn");
let hash = provider
.request_observation(&root, &key)
.continuation
.affinity_hash
.unwrap();
let body = json!({
"model": FUTURE, "input": [],
"client_metadata": {
"x-openai-subagent": "guardian",
"x-codex-turn-metadata": json!({
"thread_source": "guardian_review", "session_id": "root", "thread_id": "child"
}).to_string()
}
});
let reviewer = Operation::Generate(GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
));
let scope = FrozenAccountScope::new(
Arc::new(RuntimeAccountDirectory::new(
[(
oauth.clone(),
RuntimeAccount::new(kind.clone(), BTreeSet::new())
.with_direct_authentication_kind(Some("oauth".into())),
)]
.into(),
)),
ClientRoutingScope::all_accounts(),
);
let strict = crate::support::account_policy();
assert!(
provider
.allows_direct_model_scope(&reviewer, &key, &scope, strict)
.await
.unwrap()
);
affinity.seed_binding(&kind, &hash, api_key);
assert!(
!provider
.allows_direct_model_scope(&reviewer, &key, &scope, strict)
.await
.unwrap()
);
assert!(
provider
.allows_direct_model_scope(&root, &key, &scope, strict)
.await
.unwrap()
);
let other_key = ClientApiKeyId::new("key_other").unwrap();
assert!(
provider
.allows_direct_model_scope(&reviewer, &other_key, &scope, strict)
.await
.unwrap()
);
let preferred =
strict.with_openai_account_affinity(gateway_core::account::AccountAffinity::Preferred);
assert!(
provider
.allows_direct_model_scope(&reviewer, &key, &scope, preferred)
.await
.unwrap()
);
affinity.seed_binding(&kind, &hash, oauth);
assert!(
provider
.allows_direct_model_scope(&reviewer, &key, &scope, strict)
.await
.unwrap()
);
}
#[tokio::test]
async fn guardian_model_rejects_unknown_or_changed_continuations_before_account_selection() {
let store = Arc::new(MemoryAccountStore::default());
@@ -9228,27 +9228,62 @@ async fn capacity_http_and_websocket_opening_rejections_use_bounded_business_ret
#[tokio::test]
async fn request_rejections_should_not_retry_or_cool_down_accounts() {
use gateway_core::provider_ports::ProviderCooldownPort as _;
for (use_websocket, (code, expected_kind)) in [false, true].into_iter().flat_map(|websocket| {
[
("flex_unavailable", ProviderErrorKind::Unavailable),
("turn_rate_limit_exceeded", ProviderErrorKind::RateLimited),
]
.map(|case| (websocket, case))
}) {
use provider_openai::credential::ResponsesTransport;
for (use_websocket, (code, error_type, expected_kind)) in
[false, true].into_iter().flat_map(|websocket| {
[
(
"flex_unavailable",
"resource_unavailable",
ProviderErrorKind::Unavailable,
),
(
"turn_rate_limit_exceeded",
"rate_limit_error",
ProviderErrorKind::RateLimited,
),
(
"api_key_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
(
"project_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
(
"organization_spend_limit_exceeded",
"insufficient_quota",
ProviderErrorKind::QuotaExhausted,
),
]
.map(|case| (websocket, case))
})
{
let store = Arc::new(MemoryAccountStore::default());
let account_id = "acct_provider_contract";
create_account(&store, account_id).await;
let cooldowns = Arc::new(MemoryCooldownPort::new());
let server = MockServer::start().await;
let error_type = if code == "turn_rate_limit_exceeded" {
"rate_limit_error"
let spend_limit = expected_kind == ProviderErrorKind::QuotaExhausted;
let endpoint = if spend_limit {
let transport = if use_websocket {
ResponsesTransport::PreferWebsocket
} else {
ResponsesTransport::Http
};
store
.seed_api_key(account_id, server.uri(), transport)
.await;
"/responses"
} else {
"resource_unavailable"
create_account(&store, account_id).await;
"/codex/responses"
};
let body =
json!({"error":{"type":error_type,"code":code,"message":"Retry this request later."}});
Mock::given(method(if use_websocket { "GET" } else { "POST" }))
.and(path("/codex/responses"))
.and(path(endpoint))
.respond_with(
ResponseTemplate::new(429)
.insert_header("retry-after", "300")
@@ -9296,7 +9331,14 @@ async fn request_rejections_should_not_retry_or_cool_down_accounts() {
);
let account = store.account(account_id).unwrap();
assert_eq!(account.credential_state(), CredentialState::Ready);
assert_eq!(account.quota().access(), QuotaAccessState::Unknown);
assert_eq!(
account.quota().access(),
if spend_limit {
QuotaAccessState::Exhausted
} else {
QuotaAccessState::Unknown
}
);
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
}
}
@@ -9576,6 +9618,18 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
ProviderErrorKind::RateLimited,
false,
),
(
"project_spend_limit_exceeded",
"Project spending limit reached.",
ProviderErrorKind::QuotaExhausted,
false,
),
(
"organization_spend_limit_exceeded",
"Organization spending limit reached.",
ProviderErrorKind::QuotaExhausted,
false,
),
(
"unsupported_parameter",
"Hosted tool 'web_search' requires authorization and metering that are not supported by rustponsesapi.",
@@ -9620,7 +9674,9 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
"type":"invalid_request_error","code":code,"message":message,"param":"tools"
}});
}
if code == "turn_rate_limit_exceeded" {
if code == "organization_spend_limit_exceeded" {
original = json!({"type":"error","error":{"code":code,"message":message,"headers":{"retry-after":"7"}}});
} else if code == "turn_rate_limit_exceeded" || expected_kind == ProviderErrorKind::QuotaExhausted {
original["response"]["error"]["headers"] = json!({"retry-after": "7"});
}
let expected_status = original["status"]
@@ -9702,10 +9758,13 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
);
assert_eq!(error.replay_is_safe(), capacity && !semantic_output);
assert_eq!(error.upstream_status(), expected_status);
if code == "turn_rate_limit_exceeded" {
if code == "turn_rate_limit_exceeded" || expected_kind == ProviderErrorKind::QuotaExhausted {
assert!(error.retry_is_prohibited());
assert_eq!(error.retry_after(), Some(Duration::from_secs(7)));
}
if expected_kind == ProviderErrorKind::QuotaExhausted {
assert_eq!(store.account("acct_provider_contract").unwrap().quota().access(), QuotaAccessState::Exhausted);
}
assert_eq!(
error.pre_delivery_retry().is_some(),
capacity && !semantic_output
@@ -12418,6 +12477,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
for use_websocket in [false, true] {
for (status, code, projects_replay) in [
(429, "usage_limit_reached", true),
(429, "project_spend_limit_exceeded", false),
(402, "insufficient_quota", true),
(429, "quota_exceeded", false),
(429, "rate_limit_exceeded", false),
@@ -474,6 +474,7 @@ impl ProviderAccountStore for MemoryAccountStore {
async fn list_for_provider(
&self,
provider: &ProviderKind,
include_disabled: bool,
) -> Result<Vec<ProviderAccount>, StoreError> {
self.provider_list_reads.fetch_add(1, Ordering::SeqCst);
if self.fail_provider_listing.load(Ordering::SeqCst) {
@@ -485,13 +486,15 @@ impl ProviderAccountStore for MemoryAccountStore {
),
));
}
// 与 Postgres 实现的调度列表语义一致:停用账号不进入常规候选
Ok(self
.accounts
.lock()
.expect("account store lock")
.values()
.filter(|stored| stored.account.provider() == provider && stored.account.enabled())
.filter(|stored| {
stored.account.provider() == provider
&& (include_disabled || stored.account.enabled())
})
.map(|stored| stored.account.clone())
.collect())
}
@@ -469,6 +469,16 @@ fn openai_account_failure_matrix_is_preserved() {
r#"{"error":{"type":"usage_limit_reached","message":"quota window reached"}}"#,
CodexFailureCategory::UsageLimitExhausted,
),
(
429,
r#"{"error":{"type":"project_spend_limit_exceeded"}}"#,
CodexFailureCategory::RateLimited,
),
(
401,
r#"{"error":{"code":"project_spend_limit_exceeded"}}"#,
CodexFailureCategory::CredentialExpired,
),
(
529,
r#"{"error":{"type":"server_error","message":"overloaded"}}"#,
@@ -413,11 +413,10 @@ impl GrokCredentialQuotaService {
.load_current(account_id)
.await
.map_err(map_quota_repository_error)?;
if !loaded.account.enabled()
|| loaded
.account
.access_token_expires_at()
.is_none_or(|expires_at| expires_at <= SystemTime::now())
if loaded
.account
.access_token_expires_at()
.is_none_or(|expires_at| expires_at <= SystemTime::now())
{
return Err(GrokQuotaError::AccountUnavailable);
}
@@ -513,7 +513,7 @@ impl GrokCredentialRepository {
})?;
let accounts = self
.store
.list_for_provider(&provider)
.list_for_provider(&provider, false)
.await
.map_err(map_store_error)?;
let mut loaded = Vec::with_capacity(accounts.len());
@@ -535,7 +535,7 @@ impl GrokCredentialRepository {
})?;
let accounts = self
.store
.list_for_provider(&provider)
.list_for_provider(&provider, false)
.await
.map_err(map_store_error)?;
for account in &accounts {
@@ -150,7 +150,7 @@ impl ScheduledTask for XaiQuotaCatalogTask {
Box::pin(async move {
let accounts = self
.accounts
.list_for_provider(&self.provider_kind)
.list_for_provider(&self.provider_kind, true)
.await
.map_err(|source| WorkerTaskError::safe("账号列表读取失败").with_source(source))?;
let mut failures = QuotaCatalogFailure::default();
@@ -243,10 +243,9 @@ impl XaiQuotaCatalogTask {
}
pub(super) fn eligible_quota_worker_account(account: &ProviderAccount, now: SystemTime) -> bool {
account.enabled()
&& account
.access_token_expires_at()
.is_some_and(|expires_at| expires_at > now)
account
.access_token_expires_at()
.is_some_and(|expires_at| expires_at > now)
&& account
.quota()
.exhaustion_refresh_due(now, EXHAUSTED_QUOTA_FALLBACK_RECHECK_INTERVAL)
+2 -1
View File
@@ -219,7 +219,8 @@ async fn xai_quota_catalog_worker_retains_both_failure_stages_and_finishes_the_b
for refresh_due in [true, false] {
let store = MemoryProviderAccountStore::shared();
for suffix in ["broken_one", "broken_two"] {
let input = create_input(suffix, "synthetic-subject");
let mut input = create_input(suffix, "synthetic-subject");
input.enabled = suffix == "broken_one";
let mut account = crate::support::prepare_input(&input).unwrap();
// 模拟历史持久化凭据损坏,额度与目录读取均应保留各自的失败分类
account.credential = gateway_core::account::PlaintextCredential::new(Map::new());
@@ -709,21 +709,20 @@ async fn quota_read_rejects_corrupt_provider_document() {
}
#[tokio::test]
async fn disabled_account_quota_refresh_never_calls_upstream() {
async fn disabled_account_refreshes_quota_without_enabling_scheduling() {
let (store, repository) =
repository_with_accounts(&[("disabled-quota", "subject-disabled")]).await;
let id = account_id("disabled-quota");
store
.set_enabled(&account_id("disabled-quota"), false)
.set_enabled(&id, false)
.await
.expect("disable account");
let transport = QueueBillingTransport::success(br#"{"config":null}"#);
let service = crate::support::grok_quota_service(repository, transport.clone());
let transport = QueueBillingTransport::success(br#"{"config":{"creditUsagePercent":37.5}}"#);
let service = crate::support::grok_quota_service(repository, transport);
assert!(matches!(
service.refresh_account(&account_id("disabled-quota")).await,
Err(GrokQuotaError::AccountUnavailable)
));
assert_eq!(transport.calls.load(Ordering::SeqCst), 0);
let snapshot = service.refresh_account(&id).await.expect("refresh quota");
assert_eq!(snapshot.billing().used_percent(), Some(37.5));
assert!(!store.account(&id).expect("account").enabled());
}
#[tokio::test]
@@ -356,14 +356,17 @@ impl ProviderAccountStore for MemoryProviderAccountStore {
async fn list_for_provider(
&self,
provider: &ProviderKind,
include_disabled: bool,
) -> Result<Vec<ProviderAccount>, StoreError> {
if self.fail_provider_listing.load(Ordering::SeqCst) {
return Err(invalid());
}
// 与 Postgres 实现的调度列表语义一致:停用账号不进入常规候选
Ok(lock(&self.accounts)
.values()
.filter(|stored| stored.account.provider() == provider && stored.account.enabled())
.filter(|stored| {
stored.account.provider() == provider
&& (include_disabled || stored.account.enabled())
})
.map(|stored| stored.account.clone())
.collect())
}
+12 -5
View File
@@ -598,7 +598,8 @@ API Key 登录通常选择 `gpt-5.6-luna`,ChatGPT 登录选择 `codex-auto-rev
“系统设置 → 上游配置”中的“专用审核模型”默认开启。关闭后沿用客户端模型。开启时,网关按当前请求的
Guardian 身份识别同步审核和审核预热,优先选择允许 `codex-auto-review` 的原生 OAuth 账号。
入站审核模型可以是任意名称。普通请求、后台分类和会话整理沿用原模型。
缺少合格账号时,网关按客户端模型正常选路。管理员显式模型映射、别名与已绑定的适配器和中间件优先。
缺少合格账号时,网关按客户端模型正常选路。严格会话亲和下,如果父账号不在专用模型候选中,子审核沿用客户端模型并跟随父账号。
管理员显式模型映射、别名与已绑定的适配器和中间件优先。
已有续接沿用绑定账号及已记录的审核模型;无法确认模型兼容性时要求客户端重放。执行开始后的重试保持已选模型
发往 Codex OAuth 的同步 `codex-auto-review` 审核带 `x-codex-guardian: reviewer`,
@@ -877,7 +878,12 @@ headers 中移除,避免客户端再次等待旧账号;关联 ID 等其他
#### 额度耗尽与续写
明确额度耗尽触发账号隔离与安全换号,包括 WebSocket 握手返回的 429;不会因其长 `Retry-After` 而转入同账号传输恢复等待
OpenAI Responses 在 HTTP 429、WebSocket 握手 429 或流内错误(无状态码或 429)中返回
`api_key_spend_limit_exceeded`、`project_spend_limit_exceeded` 或 `organization_spend_limit_exceeded` 时,
网关保留原码并终止本次请求,包括原生续写。仅本次选中的上游账号记为额度耗尽,`Retry-After` 不触发重试或临时冷却。
调整上游预算后,可在管理端对已启用的 API Key 账号执行强制恢复
其他明确额度耗尽触发账号隔离与安全换号,包括 WebSocket 握手返回的 429;不会因其长 `Retry-After` 而转入同账号传输恢复等待
Client Key 日周预算超限返回 `429`,`error.type` 为官方额度耗尽类型 `usage_limit_reached`,
`error.code` 分别保留 `key_daily_budget_exceeded` 与 `key_weekly_budget_exceeded`,`Retry-After` 指向预算重置边界。
@@ -1795,7 +1801,8 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
`refreshToken`。刷新响应中的三个 token 字段均按官方语义独立轮换:返回新值时替换,省略时分别保留
现值。回调地址只承载 `code`/`state`,不以 host/path 形式作为拒绝条件
- OpenAI 重新授权允许登录另一个上游账号。保留本地账号 ID、名称和调度设置,按新授权更新令牌、
上游用户与工作区 ID、邮箱和套餐。换号时清除旧账号的额度快照和耗尽状态,新额度由后台重新查询。
上游用户与工作区 ID、邮箱和套餐。同一用户和工作区保留最近的额度快照,后台查询成功后按上游窗口更新。
用户或工作区变更时清除原身份的额度快照和耗尽状态。
无法识别新用户或新身份已绑定其他记录时,原账号保持不变
- OAuth 账号文件导入和 OAuth complete(包括重新授权)在 credential 提交后后台尝试一次额度观测,不等待
观测完成才返回成功。观测失败只记录告警,不回滚已提交的账号;手工或后台 RT 刷新只更新 token,
@@ -1813,8 +1820,8 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
本次耗尽之后的已记录窗口 reset 全部到期后,新查询明确 `allowed=true` 可解除限制,即使用量仍为
100%。未知 reset 或再次拒绝后残留的旧 reset 仍走原规则,不复用旧边界解封;时间到期本身不会
解除限制,也不会将展示用量归零
- 账号 `enabled` 控制是否参与请求调度,不控制 OAuth 凭据续期。OpenAI 与 xAI 的停用账号仍按各自刷新
策略维护 Token;刷新结果更新凭据状态,但不会启用调度。无 refresh token 或凭据已进入失效、无效、
- 停用的 OpenAI 与 xAI OAuth 账号退出客户端请求调度,仍按各自策略续期 Token、查询额度。
成功刷新后账号保持停用。无 refresh token 或凭据已进入失效、无效、
封禁状态的账号不参加后台自动续期
- `POST /api/admin/accounts/recover` 对停用账号只将 `enabled` 改为 `true`,保留已有额度快照、凭据、错误和 Redis
cooldown;启用后仍按这些事实投影状态,不会把已有错误或耗尽改成正常。对已启用账号则执行强制恢复:
+2 -1
View File
@@ -999,8 +999,9 @@ credential 与 quota 是两组独立事实:credential refresh 不等于 quota
团队身份不推断为 Free,订阅查询失败不影响额度观测
普通 Token 续期与刷新退避保留提交时的账号资料及额度快照,显式凭据轮换仍按原子提交合同失效旧观测。
xAI Provider 在缺少可展示上游额度时投影本地 24 小时滚动统计,Admin 按该窗口展示日用量,额度预测使用完整周/月窗口
- 账号导入和 OAuth complete(包括重新授权)在 credential 提交、Provider 事实失效及快照发布后,
- 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后,
由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。
同身份重新授权在事务内保留额度观测和按桶预热进度,旧凭据版本的在途观测无法覆盖新版本。
手工和后台 credential refresh 仍不隐式刷新 quota
- quota refresh、正常推理返回的 rate-limit headers 和后台健康任务汇入同一额度事实;Provider 使用套餐
事实进行展示、目录 cache 隔离和请求资格检查,不创建套餐专属状态机。
+7 -6
View File
@@ -1,9 +1,10 @@
# v3.54.4
# v3.54.5
## 问题修复
- OpenAI Responses 经 WebSocket 上传长会话时,若上游在首条响应文本前因请求过大关闭连接,允许回退的请求会通过同一账号改走 HTTP/SSE
- Codex 切换 `x-codex-exclude` 响应字段设置后,WebSocket 按新设置选择连接,依赖旧连接的续接会提示客户端重放完整历史
- 严格账号亲和下,聊天主账号缺少生图资格时,主会话和子会话可临时借用有权限的账号生成或编辑图片,后续聊天继续使用原账号
- 导入 OpenAI API 密钥账号时,只需在账号设置中填写一次名称,手动导入时留空会使用「密钥账号」
- 将后端 `url` 依赖升级至 2.5.9,修复安全公告 `RUSTSEC-2026-0592` 所列问题
- 兼容 Codex 0.172 的支出上限错误,保留 API Key、项目和组织的原始错误码,停止本次请求的自动重试
- WebSocket 出站帧的 TRACE 日志仅记录帧类型、结束标志和长度
- 严格会话亲和下,父账号不支持专用审核模型时,Guardian 子审核沿用客户端模型并跟随父账号
- OpenAI OAuth 对同一用户和工作区重新授权时,保留最近的额度快照及耗尽状态
- 停用的 OpenAI 与 xAI OAuth 账号仍会在后台查询额度
- 将后端 `cookie` 依赖升级至 0.18.3,修复 `RUSTSEC-2026-0594`
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.54.4
version: 3.54.5
published:
'3':
stable: 3.54.3
rc: 3.54.3
beta: 3.54.3
alpha: 3.54.3
stable: 3.54.4
rc: 3.54.4
beta: 3.54.4
alpha: 3.54.4