mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
fix(openai): recover native continuations after account queue timeouts
This commit is contained in:
@@ -22,10 +22,10 @@ use crate::engine::probe::AccountProbeTarget;
|
||||
use crate::engine::provider::{Provider, ProviderCallMetadata, ProviderRequest, ProviderStream};
|
||||
use crate::engine::{
|
||||
AccountAttemptContext, AttemptContext, AttemptRecord, AttemptTransport, AttemptTrigger,
|
||||
CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError, ExecutionOutcome,
|
||||
ExecutionStore, GatewayEngine, IntermediateFailure, ModelRequestFailureObservation,
|
||||
ModelRequestFinalization, ModelRequestId, NewModelRequest, ProviderAccountStateOwner,
|
||||
RequestAttemptContext, UpstreamSendState,
|
||||
ClientReplayTrigger, CommitRequirement, ContinuationAttempt, CoordinatedEvent, EngineError,
|
||||
ExecutionOutcome, ExecutionStore, GatewayEngine, IntermediateFailure,
|
||||
ModelRequestFailureObservation, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||
ProviderAccountStateOwner, RequestAttemptContext, UpstreamSendState,
|
||||
};
|
||||
use crate::error::{
|
||||
ContinuationRecoveryDisposition, GatewayError, GatewayErrorKind, ProviderError,
|
||||
@@ -1474,9 +1474,11 @@ where
|
||||
attempt_trace: &TraceContext,
|
||||
) -> Result<PullOutcome, EngineError> {
|
||||
attempt_trace.record_provider_failure(&error);
|
||||
if self.continuation_attempt == ContinuationAttempt::RotateForClientReplay
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
if matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
) && error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
&& let Some(original) = self.last_retryable_failure.take()
|
||||
{
|
||||
// 迁移只改变客户端恢复指令;失败分类、发送事实与运维正文仍属于原请求
|
||||
@@ -1563,6 +1565,15 @@ where
|
||||
.expect("pending connection rotation");
|
||||
self.excluded_accounts.remove(&recovery.account);
|
||||
self.pending_retry = Some(recovery);
|
||||
} else if continuation_retry
|
||||
&& matches!(
|
||||
self.continuation_attempt,
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
)
|
||||
{
|
||||
// 只有替代账号准入成功后才投影重放信号,空池仍返回原排队错误
|
||||
self.last_retryable_failure_events.clear();
|
||||
self.last_retryable_failure = Some(error);
|
||||
} else if candidate_retry {
|
||||
// 原账号只属于原 Provider,跨候选后不能拿旧钉选作恢复兜底
|
||||
self.connection_rotation = None;
|
||||
@@ -2261,7 +2272,9 @@ where
|
||||
&& !error.retry_is_prohibited()
|
||||
&& self.has_account_rotation_budget() =>
|
||||
{
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay;
|
||||
self.continuation_attempt = ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::UpstreamCapacity,
|
||||
);
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
@@ -2301,27 +2314,23 @@ where
|
||||
self.excluded_accounts
|
||||
.insert(current.metadata.provider_account_id().clone());
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => return false,
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// 原生续写的原账号在本地调度阶段已不可用时,交给 Provider 执行跨账号恢复
|
||||
///
|
||||
/// 这不是强制 Smart:下一次 attempt 仍使用请求配置的调度策略
|
||||
/// 只有网关持有
|
||||
/// 对应 Provider 的会话状态时才进入恢复;是否保留 native handle、执行 probe
|
||||
/// 或使用完整 transcript,由 Provider 自己的协议边界决定
|
||||
/// 仅恢复网关持有的会话状态,沿用冻结的调度策略和换号预算
|
||||
/// Provider 决定能否恢复原生状态,或仅允许客户端带完整历史重发
|
||||
fn prepare_unavailable_native_continuation_replay(&mut self, error: &ProviderError) -> bool {
|
||||
if self.account_selection.required_account().is_some()
|
||||
|| self.continuation_attempt != ContinuationAttempt::Native
|
||||
|| self.current_send_state() != UpstreamSendState::NotSent
|
||||
|| !matches!(
|
||||
error.kind(),
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted
|
||||
)
|
||||
|| self.replay_barrier_reached
|
||||
|| self.delivery_pending
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -2344,7 +2353,19 @@ where
|
||||
return false;
|
||||
}
|
||||
|
||||
self.continuation_attempt = ContinuationAttempt::ReplayAny;
|
||||
self.continuation_attempt = match error.kind() {
|
||||
ProviderErrorKind::ConcurrencyQueueTimeout
|
||||
if error.send_state() == UpstreamSendState::NotSent
|
||||
&& error.continuation_recovery_disposition()
|
||||
== Some(ContinuationRecoveryDisposition::ClientReplayRequired) =>
|
||||
{
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::AccountQueueTimeout)
|
||||
}
|
||||
ProviderErrorKind::NoEligibleAccount
|
||||
| ProviderErrorKind::AccountCapacityUnavailable
|
||||
| ProviderErrorKind::QuotaExhausted => ContinuationAttempt::ReplayAny,
|
||||
_ => return false,
|
||||
};
|
||||
self.excluded_accounts.insert(pin.account().clone());
|
||||
true
|
||||
}
|
||||
|
||||
@@ -252,6 +252,13 @@ impl ProviderAccountStateOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// 只能由客户端携带完整历史恢复的换号原因
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ClientReplayTrigger {
|
||||
UpstreamCapacity,
|
||||
AccountQueueTimeout,
|
||||
}
|
||||
|
||||
/// 当前 attempt 对 previous-response 的唯一处理方式
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ContinuationAttempt {
|
||||
@@ -269,7 +276,7 @@ pub enum ContinuationAttempt {
|
||||
/// 该枚举本身不证明客户端 input 完整,也不授权 Provider 清除 previous-response
|
||||
ReplayAny,
|
||||
/// 仅迁移账号绑定,随后要求客户端携带完整历史重放;不得发送当前增量输入
|
||||
RotateForClientReplay,
|
||||
RotateForClientReplay(ClientReplayTrigger),
|
||||
}
|
||||
|
||||
impl ContinuationAttempt {
|
||||
@@ -280,7 +287,7 @@ impl ContinuationAttempt {
|
||||
Self::Native => "native",
|
||||
Self::ReplayOwner => "replay_owner",
|
||||
Self::ReplayAny => "replay_any",
|
||||
Self::RotateForClientReplay => "rotate_for_client_replay",
|
||||
Self::RotateForClientReplay(_) => "rotate_for_client_replay",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -648,7 +655,7 @@ impl AttemptContext {
|
||||
.map(|owner| owner.account()),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay => None,
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||
});
|
||||
self.request.upstream_adapters.as_ref().map_or(
|
||||
Ok(upstream_adapter::UpstreamAdapterSelection::Native),
|
||||
|
||||
@@ -26,9 +26,10 @@ use gateway_core::engine::provider::{
|
||||
Provider, ProviderCallMetadata, ProviderRegistry, ProviderRequest, ProviderStream,
|
||||
};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, CommitRequirement,
|
||||
ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore, GatewayEngine,
|
||||
IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest, RecoveryReport,
|
||||
AttemptContext, AttemptCoordinator, AttemptRecord, AttemptTransport, ClientReplayTrigger,
|
||||
CommitRequirement, ContinuationAttempt, EngineError, ExecutionOutcome, ExecutionStore,
|
||||
GatewayEngine, IntermediateFailure, ModelRequestFinalization, ModelRequestId, NewModelRequest,
|
||||
RecoveryReport,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||
@@ -2606,7 +2607,7 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
if contexts.len() == 2 {
|
||||
assert_eq!(
|
||||
contexts[1].continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity)
|
||||
);
|
||||
assert!(
|
||||
contexts[1]
|
||||
@@ -2629,6 +2630,85 @@ fn native_capacity_above_wait_limit_rotates_before_requesting_client_replay() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_queue_timeout_requests_full_history_only_after_replacement_admission() {
|
||||
use ProviderErrorKind::{ConcurrencyQueueFull, ConcurrencyQueueTimeout, NoEligibleAccount};
|
||||
for (kind, replay_allowed, rotations, spare, expected_selections) in [
|
||||
(ConcurrencyQueueTimeout, true, 1, true, 2),
|
||||
(ConcurrencyQueueTimeout, true, 1, false, 2),
|
||||
(ConcurrencyQueueTimeout, true, 0, true, 1),
|
||||
(ConcurrencyQueueTimeout, false, 1, true, 1),
|
||||
(ConcurrencyQueueFull, true, 1, true, 1),
|
||||
] {
|
||||
let Operation::Generate(generate) = generate_operation() else {
|
||||
unreachable!()
|
||||
};
|
||||
let operation =
|
||||
Operation::Generate(generate.with_provider_session_state(
|
||||
ProviderSessionState::new("openai", Map::new()).unwrap(),
|
||||
));
|
||||
let plan = plan_with_policy(
|
||||
&operation,
|
||||
AccountSelectionPolicy::new(RotationStrategy::Smart, NonZeroU32::MIN)
|
||||
.with_max_account_rotations(rotations),
|
||||
);
|
||||
let mut original = ProviderError::new(kind, UpstreamSendState::NotSent);
|
||||
if replay_allowed {
|
||||
original = original.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
);
|
||||
}
|
||||
let replacement = if spare {
|
||||
ProviderError::responses_replay_required("account_rotated", UpstreamSendState::NotSent)
|
||||
} else {
|
||||
ProviderError::new(NoEligibleAccount, UpstreamSendState::NotSent)
|
||||
};
|
||||
let (coordinator, store, provider) =
|
||||
coordinator(vec![Script::Error(original), Script::Error(replacement)]);
|
||||
let owner = ProviderAccountId::new("acct_one").unwrap();
|
||||
let pin = NativeContinuationPin::new(
|
||||
PreviousResponseId::new("client-previous"),
|
||||
PreviousResponseId::new("upstream-previous"),
|
||||
ClientApiKeyId::new("key_client_1").unwrap(),
|
||||
ProviderKind::new("openai").unwrap(),
|
||||
owner.clone(),
|
||||
);
|
||||
let mut session = block_on(coordinator.start(
|
||||
model_request(&operation, SystemTime::now() + Duration::from_secs(30)),
|
||||
operation,
|
||||
plan,
|
||||
None,
|
||||
Some(ContinuationBinding::Pinned(pin)),
|
||||
CancellationToken::new(),
|
||||
))
|
||||
.unwrap();
|
||||
let Err(EngineError::Provider(error)) = block_on(session.collect_uncommitted()) else {
|
||||
panic!("expected a local selection error");
|
||||
};
|
||||
assert_eq!(error.kind(), kind);
|
||||
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
error.client_visible_upstream_error().and_then(|e| e.code()),
|
||||
(spare && expected_selections == 2).then_some("previous_response_not_found")
|
||||
);
|
||||
let contexts = provider.contexts.lock().unwrap();
|
||||
assert_eq!(contexts.len(), expected_selections);
|
||||
if let Some(probe) = contexts.get(1) {
|
||||
assert_eq!(
|
||||
probe.continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout
|
||||
)
|
||||
);
|
||||
assert!(probe.excluded_accounts().contains(&owner));
|
||||
}
|
||||
assert_eq!(
|
||||
store.state.lock().unwrap().finalizations[0].attempt_count,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_continuation_client_replay_required_is_terminal() {
|
||||
for (kind, send_state) in [
|
||||
|
||||
@@ -21,7 +21,7 @@ use gateway_core::concurrency::{
|
||||
CapacityWait, ConcurrencyQueuePolicy, ConcurrencyWaitQueue, QueueRejection, WaitPriority,
|
||||
};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, ContinuationAttempt,
|
||||
AttemptContext, ClientReplayTrigger, ContinuationAttempt,
|
||||
policy::{AccountPolicyError, AccountScheduleOwnership},
|
||||
};
|
||||
use gateway_core::provider_ports::{
|
||||
@@ -522,6 +522,17 @@ impl CodexCredentialSelector {
|
||||
)
|
||||
};
|
||||
let selection = async {
|
||||
if request.attempt.continuation_attempt()
|
||||
== ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout,
|
||||
)
|
||||
{
|
||||
let queue = ConcurrencyQueuePolicy {
|
||||
max_waiting: 0,
|
||||
..policy.queue_policy()
|
||||
};
|
||||
return select(queue, Some(QueueRejection::Timeout)).await;
|
||||
}
|
||||
let rejection = match select(policy.queue_policy(), None).await {
|
||||
Err(CredentialSelectionError::QueueRejected(reason))
|
||||
if !follow_only
|
||||
@@ -530,7 +541,7 @@ impl CodexCredentialSelector {
|
||||
request.attempt.continuation_attempt(),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay
|
||||
| ContinuationAttempt::RotateForClientReplay(_)
|
||||
) =>
|
||||
{
|
||||
reason
|
||||
@@ -761,7 +772,7 @@ impl CodexCredentialSelector {
|
||||
.map(|owner| owner.account().clone()),
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::ReplayAny
|
||||
| ContinuationAttempt::RotateForClientReplay => None,
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => None,
|
||||
};
|
||||
let required_account = request.attempt.required_account().cloned();
|
||||
if required_account
|
||||
@@ -1654,7 +1665,7 @@ impl CodexCredentialSelector {
|
||||
affinity_telemetry,
|
||||
admitted_session: binding_key.filter(|_| !cache_preference).cloned(),
|
||||
capacity: capacity.map(AccountCapacitySnapshot::with_acquired_request),
|
||||
_guard: guard,
|
||||
guard,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2324,10 +2335,14 @@ pub struct CodexCredentialLease {
|
||||
// 已准入请求允许完成;只有中间件改变会话身份时才需要再次认领
|
||||
admitted_session: Option<ProviderSessionAffinityKey>,
|
||||
capacity: Option<AccountCapacitySnapshot>,
|
||||
_guard: Box<dyn ProviderLeaseGuard>,
|
||||
guard: Box<dyn ProviderLeaseGuard>,
|
||||
}
|
||||
|
||||
impl CodexCredentialLease {
|
||||
pub(crate) async fn release(self) -> Result<(), CredentialSelectionError> {
|
||||
Ok(self.guard.release().await?)
|
||||
}
|
||||
|
||||
pub(crate) const fn transport(&self) -> super::ResponsesTransport {
|
||||
self.transport
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ use gateway_core::engine::provider::{
|
||||
ProviderRequestObservation, ProviderSelectionObservation, ProviderStream,
|
||||
};
|
||||
use gateway_core::engine::upstream_adapter::UpstreamAdapterSelection;
|
||||
use gateway_core::engine::{AttemptContext, AttemptTransport, ContinuationAttempt};
|
||||
use gateway_core::engine::{
|
||||
AttemptContext, AttemptTransport, ClientReplayTrigger, ContinuationAttempt,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, ContinuationFailure,
|
||||
ContinuationRecoveryDisposition, OpaqueUpstreamValue, ProviderConnectionObservation,
|
||||
@@ -750,12 +752,13 @@ impl Provider for CodexProvider {
|
||||
&[],
|
||||
context.client_api_key_ref(),
|
||||
);
|
||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay
|
||||
if let ContinuationAttempt::RotateForClientReplay(trigger) = context.continuation_attempt()
|
||||
&& (selection_session_affinity.is_none()
|
||||
|| context.account_selection_policy().account_affinity()
|
||||
== AccountAffinity::Relaxed)
|
||||
|| (trigger == ClientReplayTrigger::UpstreamCapacity
|
||||
&& context.account_selection_policy().account_affinity()
|
||||
== AccountAffinity::Relaxed))
|
||||
{
|
||||
// 没有可持续的会话绑定就无法保证完整历史使用替代账号,交回原始容量错误
|
||||
// 上游过载时宽松亲和无法固定替代账号;本地排队超时则可按实时空位调度完整请求
|
||||
return Err(provider_error(
|
||||
ProviderErrorKind::NoEligibleAccount,
|
||||
UpstreamSendState::NotSent,
|
||||
@@ -783,7 +786,25 @@ impl Provider for CodexProvider {
|
||||
guardian,
|
||||
)
|
||||
.await
|
||||
.map_err(map_selection_error)
|
||||
.map_err(|error| {
|
||||
let can_request_replay = matches!(
|
||||
error,
|
||||
CredentialSelectionError::QueueRejected(
|
||||
gateway_core::concurrency::QueueRejection::Timeout
|
||||
)
|
||||
) && context.continuation_attempt()
|
||||
== ContinuationAttempt::Native
|
||||
&& !adapted
|
||||
&& selection_session_affinity.is_some();
|
||||
let error = map_selection_error(error);
|
||||
if can_request_replay {
|
||||
error.with_continuation_recovery_disposition(
|
||||
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||
)
|
||||
} else {
|
||||
error
|
||||
}
|
||||
})
|
||||
};
|
||||
// 恢复期间排队也消耗启动窗口;只包住选账号,不限制业务响应时长
|
||||
let lease = if let Some(remaining) = context.connection_budget().startup_remaining() {
|
||||
@@ -805,9 +826,13 @@ impl Provider for CodexProvider {
|
||||
CredentialSelectionError::NoEligibleCredential,
|
||||
));
|
||||
}
|
||||
if context.continuation_attempt() == ContinuationAttempt::RotateForClientReplay {
|
||||
if matches!(
|
||||
context.continuation_attempt(),
|
||||
ContinuationAttempt::RotateForClientReplay(_)
|
||||
) {
|
||||
// Core 已确认允许换号;选号器迁移共享绑定后,完整历史仍须由客户端提供
|
||||
// 不将旧账号的 previous_response_id 或增量输入发送给替代账号
|
||||
lease.release().await.map_err(map_selection_error)?;
|
||||
return Err(continuation_replay_required_error("account_rotated"));
|
||||
}
|
||||
let adapter = context.upstream_adapter_for_account(
|
||||
@@ -1034,7 +1059,8 @@ impl CodexProvider {
|
||||
ContinuationAttempt::ReplayOwner | ContinuationAttempt::ReplayAny => {
|
||||
PreviousResponseScope::ExternalUnknown
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
||||
ContinuationAttempt::None
|
||||
| ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
PreviousResponseScope::ExternalUnknown
|
||||
}
|
||||
};
|
||||
|
||||
@@ -55,8 +55,8 @@ use gateway_core::engine::middleware::{
|
||||
use gateway_core::engine::probe::AccountProbeTarget;
|
||||
use gateway_core::engine::provider::{Provider as _, ProviderRequest};
|
||||
use gateway_core::engine::{
|
||||
AccountAttemptContext, AttemptContext, AttemptTransport, ContinuationAttempt, ModelRequestId,
|
||||
ProviderAccountStateOwner, RequestAttemptContext,
|
||||
AccountAttemptContext, AttemptContext, AttemptTransport, ClientReplayTrigger,
|
||||
ContinuationAttempt, ModelRequestId, ProviderAccountStateOwner, RequestAttemptContext,
|
||||
};
|
||||
use gateway_core::error::{
|
||||
ContinuationFailure, ContinuationRecoveryDisposition, PreDeliveryRetry, ProviderErrorKind,
|
||||
@@ -12820,6 +12820,109 @@ async fn late_quota_continuation_rejection_requires_client_replay_before_output(
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_queue_recovery_checks_an_immediate_spare_in_each_affinity_mode() {
|
||||
use gateway_core::account::AccountAffinity::{Preferred, Relaxed, Strict};
|
||||
use gateway_core::concurrency::ConcurrencyQueuePolicy;
|
||||
for mode in [Strict, Preferred, Relaxed] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let owner = ProviderAccountId::new("acct_provider_contract").unwrap();
|
||||
create_account(&store, owner.as_str()).await;
|
||||
create_account(&store, "acct_affinity_switch_b").await;
|
||||
let leases = Arc::new(TestLeaseCoordinator::default());
|
||||
leases.busy_accounts.lock().unwrap().insert(owner.clone());
|
||||
let server = MockServer::start().await;
|
||||
let (provider, _) = provider_and_quota_with_affinity_and_base_url_and_leases(
|
||||
&store,
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
server.uri(),
|
||||
Arc::clone(&leases),
|
||||
0,
|
||||
);
|
||||
let kind = ProviderKind::new("openai").unwrap();
|
||||
let key = ClientApiKeyId::new("key_openai_contract").unwrap();
|
||||
let pin = NativeContinuationPin::new(
|
||||
PreviousResponseId::new("resp_previous"),
|
||||
PreviousResponseId::new("resp_previous"),
|
||||
key.clone(),
|
||||
kind,
|
||||
owner.clone(),
|
||||
);
|
||||
let select = |attempt, excluded, timeout| {
|
||||
let context = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_queue_recovery").unwrap(),
|
||||
key.clone(),
|
||||
),
|
||||
NonZeroU32::MIN,
|
||||
SystemTime::now() + Duration::from_secs(10),
|
||||
account_policy()
|
||||
.with_account_affinity(mode)
|
||||
.with_queue(ConcurrencyQueuePolicy {
|
||||
max_waiting: 3,
|
||||
timeout,
|
||||
}),
|
||||
AccountAttemptContext::new(excluded, None, None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
Some(ContinuationBinding::Pinned(pin.clone())),
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.with_continuation_attempt(attempt);
|
||||
Arc::clone(&provider).execute(
|
||||
planned_request("openai", quota_continuation_operation(true)),
|
||||
context,
|
||||
)
|
||||
};
|
||||
let native = select(
|
||||
ContinuationAttempt::Native,
|
||||
BTreeSet::new(),
|
||||
Duration::from_millis(30),
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(native.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
|
||||
assert_eq!(
|
||||
native.continuation_recovery_disposition(),
|
||||
Some(ContinuationRecoveryDisposition::ClientReplayRequired)
|
||||
);
|
||||
assert!(native.client_visible_upstream_error().is_none());
|
||||
|
||||
for busy in [true, false] {
|
||||
*leases.busy.lock().unwrap() = busy;
|
||||
let replacement = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
select(
|
||||
ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::AccountQueueTimeout,
|
||||
),
|
||||
BTreeSet::from([owner.clone()]),
|
||||
Duration::from_secs(5),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("replacement must not queue")
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(replacement.send_state(), UpstreamSendState::NotSent);
|
||||
assert_eq!(
|
||||
replacement
|
||||
.client_visible_upstream_error()
|
||||
.and_then(|e| e.code()),
|
||||
(!busy).then_some("previous_response_not_found")
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
server
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|r| !r.url.path().ends_with("/responses"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_replay_rotation_without_session_identity_does_not_select_or_send() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
@@ -12834,7 +12937,7 @@ async fn client_replay_rotation_without_session_identity_does_not_select_or_send
|
||||
"client-previous",
|
||||
"upstream-previous",
|
||||
2,
|
||||
ContinuationAttempt::RotateForClientReplay,
|
||||
ContinuationAttempt::RotateForClientReplay(ClientReplayTrigger::UpstreamCapacity),
|
||||
),
|
||||
)
|
||||
.await
|
||||
@@ -12976,7 +13079,9 @@ async fn continuation_full_client_replay_selects_another_account() {
|
||||
Some(ContinuationBinding::Pinned(pin)),
|
||||
CancellationToken::new(),
|
||||
)
|
||||
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay);
|
||||
.with_continuation_attempt(ContinuationAttempt::RotateForClientReplay(
|
||||
ClientReplayTrigger::UpstreamCapacity,
|
||||
));
|
||||
error = Arc::clone(&provider)
|
||||
.execute(
|
||||
planned_request("openai", quota_continuation_operation(true)),
|
||||
|
||||
@@ -91,7 +91,7 @@ pub(super) fn continuation_account(
|
||||
.map_err(|_| invalid_continuation())
|
||||
}
|
||||
(ContinuationAttempt::ReplayAny, _) => Ok(None),
|
||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay, _) => {
|
||||
(ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_), _) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ pub(super) fn apply_continuation(
|
||||
}
|
||||
apply_replay(request, previous, account, current_input)
|
||||
}
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay => {
|
||||
ContinuationAttempt::None | ContinuationAttempt::RotateForClientReplay(_) => {
|
||||
Err(invalid_continuation())
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -2524,10 +2524,12 @@ OpenAI 严格亲和下后代线程的会话账号等待不随普通账号排队
|
||||
| --- | --- | --- |
|
||||
| `keyQueueTimeoutSeconds` | `30` | Key 排队超时,1~120 秒 |
|
||||
| `accountQueueTimeoutSeconds` | `30` | 账号排队超时,1~120 秒 |
|
||||
| `switchAccountOnQueueFailure` | `false` | 开启后,账号队满或超时可再选一次允许且可立即准入的账号,不重新排队;关闭或无空位时返回原错误 |
|
||||
| `switchAccountOnQueueFailure` | `false` | 开启后,普通请求在账号队满或超时可再选一次允许且可立即准入的账号,不重新排队;关闭或无空位时返回原错误 |
|
||||
|
||||
两层从各自首次入队开始计时,账号重选、Provider 切换或内部重试不重置账号时限。
|
||||
请求总期限优先,排队超时不中断已开始的上游生成。密钥排队失败、必须跟随根线程的后代、固定账号与原生续写不触发换号。
|
||||
请求总期限优先,排队超时不中断已开始的上游生成。密钥排队失败、必须跟随根线程的后代与显式固定账号不触发换号。
|
||||
OpenAI 已知会话的原生续写只在原账号排队。若等待超时且尚未发送,三种亲和模式均可在换号预算内尝试一次立即准入。
|
||||
有空位时返回 `previous_response_not_found`,由客户端携带完整历史重发;没有空位时返回原排队超时。此恢复独立于普通排队换号开关。
|
||||
OpenAI 严格模式成功换号后迁移绑定,优先模式临时分流时保留主绑定。
|
||||
设置更新须提交两层队列容量、两个超时值和换号开关,对新请求生效
|
||||
|
||||
|
||||
@@ -872,6 +872,7 @@ Key 的 RPM 在成功准入时才计数,金额限制在入队前及成功准
|
||||
普通账号容量等待只包含并发;严格亲和下的后代线程还可等待根线程恢复或迁移绑定,但等待不使权限、额度或冷却检查失效。
|
||||
密钥准入与账号选择各自从首次入队开始计时,账号重选、Provider 切换和后续重试共享账号等待预算,两层均受请求总期限约束。
|
||||
账号队满或超时释放队位后,可按设置对允许换号的请求再选一次可立即准入的账号。各 Provider 仍检查原有资格、租约和会话归属;OpenAI 严格亲和在取得租约后以当前绑定版本提交迁移。
|
||||
OpenAI 原生续写在本地账号排队超时后,由 Core 按换号预算排除原账号,Provider 只尝试立即准入。成功后释放租约并要求客户端以完整历史重发,原增量不跨账号发送。
|
||||
队列满/超时属于本地容量拒绝,不作为上游限流反馈或 Provider 故障熔断证据
|
||||
|
||||
#### Guardian 独立并发
|
||||
|
||||
Reference in New Issue
Block a user