From 4888681a04595dccf6979f16343db87688ddb742 Mon Sep 17 00:00:00 2001 From: Zyy <0x@ainz.cc> Date: Thu, 12 Nov 2026 18:56:30 +0800 Subject: [PATCH] feat(scheduling): weight quota resets by window in smart scheduling (#694) Co-authored-by: Zyy --- .../tests/use_case/service_contract.rs | 6 +- .../gateway-api/tests/admin/settings.rs | 15 +- .../crates/gateway-core/src/account/mod.rs | 2 +- .../gateway-core/src/account/selection.rs | 38 +++-- .../src/account/smart_scheduling.rs | 107 ++++++++++++-- .../crates/gateway-core/tests/account/mod.rs | 4 + .../tests/account/smart_scheduling.rs | 100 +++++++++++-- .../tests/engine/execution/mod.rs | 1 + .../gateway-core/tests/engine/policy.rs | 1 + .../gateway-core/tests/provider_ports/mod.rs | 1 + .../runtime/tests/generation/policy/mod.rs | 1 + .../sdk/src/call/services/settings.rs | 9 ++ .../src/redis/credential_leases/mod.rs | 1 + .../tests/postgres/runtime_settings.rs | 18 ++- .../openai/src/credential/quota/scheduling.rs | 4 +- .../openai/src/credential/quota/snapshot.rs | 23 ++- .../openai/src/credential/selector.rs | 1 + .../tests/credential/contract/capacity.rs | 1 + .../contract/scheduling_projection.rs | 1 + .../tests/credential/quota/scheduling.rs | 86 +++++++++++ .../tests/provider/contract/capacity.rs | 2 + .../openai/tests/provider/contract/mod.rs | 1 + .../provider/contract/session_binding.rs | 3 + .../provider/contract/upstream_adapter.rs | 1 + .../crates/providers/openai/tests/support.rs | 1 + .../providers/xai/src/credential/quota.rs | 24 ++- backend/crates/providers/xai/tests/admin.rs | 1 + .../providers/xai/tests/credential/quota.rs | 41 ++++++ .../xai/tests/credential/selector.rs | 1 + .../xai/tests/provider/contract/mod.rs | 1 + docs/api.md | 8 +- docs/architecture.md | 4 +- frontend/src/api/modules/settings/index.ts | 1 + frontend/src/i18n/locales/en/settings.json | 8 + .../src/i18n/locales/zh-Hans/settings.json | 8 + .../src/i18n/locales/zh-Hant/settings.json | 8 + .../components/SmartSchedulingModal.vue | 138 ++++++++++++++---- 37 files changed, 569 insertions(+), 102 deletions(-) diff --git a/backend/crates/gateway-admin/tests/use_case/service_contract.rs b/backend/crates/gateway-admin/tests/use_case/service_contract.rs index d1488564a..67fe0dd6d 100644 --- a/backend/crates/gateway-admin/tests/use_case/service_contract.rs +++ b/backend/crates/gateway-admin/tests/use_case/service_contract.rs @@ -100,7 +100,9 @@ fn contract_type(mut item: Item, name: &str) -> Item { attrs.retain(|attr| attr.path().is_ident("serde")); attrs.insert( 0, - if name == "SmartSchedulingConfig" { + if name == "ResetWindowWeights" { + parse_quote!(#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]) + } else if name == "SmartSchedulingConfig" { parse_quote!(#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]) } else if comparable { parse_quote!(#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]) @@ -256,7 +258,7 @@ fn sdk_settings_contract_matches_host_declarations() { ), ( "../gateway-core/src/account/smart_scheduling.rs", - &["SmartSchedulingValues"][..], + &["SmartSchedulingValues", "ResetWindowWeights"][..], ), ( "../gateway-core/src/metering/pricing.rs", diff --git a/backend/crates/gateway-api/tests/admin/settings.rs b/backend/crates/gateway-api/tests/admin/settings.rs index 23f2f8fac..292c76def 100644 --- a/backend/crates/gateway-api/tests/admin/settings.rs +++ b/backend/crates/gateway-api/tests/admin/settings.rs @@ -268,7 +268,7 @@ async fn smart_settings_round_trip_and_invalid_updates_leave_the_saved_value_int let fixture = AdminTestFixture::new().await; fixture.auth.insert_session("valid-session"); let mut body = update_body(); - let custom = json!({"loadWeight": 2.0, "quotaWeight": 0.0, "healthWeight": 1.0, "latencyWeight": 0.5, "resetWeight": 1.2, "queueWeight": 2.3}); + let custom = json!({"loadWeight": 2.0, "quotaWeight": 0.0, "healthWeight": 1.0, "latencyWeight": 0.5, "resetWeight": 1.2, "queueWeight": 2.3, "resetWindowWeights":{"fiveHour":0.0,"weekly":1.5,"monthly":0.0}}); body["smartScheduling"] = custom.clone(); let response = app(fixture.state()) .oneshot(request( @@ -301,6 +301,19 @@ async fn smart_settings_round_trip_and_invalid_updates_leave_the_saved_value_int missing.as_object_mut().unwrap().remove(field); invalid_values.push(missing); } + for windows in [ + json!({}), + json!({"weekly":1}), + json!(null), + json!({"fiveHour":0,"weekly":1.23,"monthly":0}), + json!({"fiveHour":-1,"weekly":1,"monthly":0}), + json!({"fiveHour":0,"weekly":1,"monthly":10.1}), + json!({"fiveHour":0,"weekly":1,"monthly":0,"daily":1}), + ] { + let mut invalid = custom.clone(); + invalid["resetWindowWeights"] = windows; + invalid_values.push(invalid); + } for invalid in invalid_values { body["smartScheduling"] = invalid; let response = app(fixture.state()) diff --git a/backend/crates/gateway-core/src/account/mod.rs b/backend/crates/gateway-core/src/account/mod.rs index b10f34320..f95d7fbd8 100644 --- a/backend/crates/gateway-core/src/account/mod.rs +++ b/backend/crates/gateway-core/src/account/mod.rs @@ -27,7 +27,7 @@ pub use error::CredentialError; pub use model::*; pub(crate) use selection::smart_score; pub use selection::*; -pub use smart_scheduling::{SmartSchedulingConfig, SmartSchedulingConfigError}; +pub use smart_scheduling::{QuotaResetPeriod, SmartSchedulingConfig, SmartSchedulingConfigError}; pub use store::{ AccountCatalogObservation, AccountCatalogOmissions, ProviderAccountStore, StoredAccountCatalog, }; diff --git a/backend/crates/gateway-core/src/account/selection.rs b/backend/crates/gateway-core/src/account/selection.rs index 056666a8f..77d54476f 100644 --- a/backend/crates/gateway-core/src/account/selection.rs +++ b/backend/crates/gateway-core/src/account/selection.rs @@ -3,7 +3,7 @@ use std::cmp::Reverse; use std::collections::{BTreeSet, HashMap}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant, SystemTime}; use futures::FutureExt; @@ -245,6 +245,7 @@ pub struct AccountRuntimeSignals { pub in_flight: u32, pub last_started_at: Option, pub quota_reset_at: Option, + pub quota_reset_windows: Option>, /// Provider 归一化的剩余额度基点:0 耗尽,10_000 全部可用 pub quota_remaining_rank: Option, pub cooldown: Option, @@ -459,6 +460,7 @@ impl AccountRuntimeSignals { pub fn with_provider_quota(mut self, quota: Option) -> Self { if let Some(quota) = quota { self.quota_reset_at = quota.reset_at; + self.quota_reset_windows = quota.reset_windows; self.quota_remaining_rank = quota.remaining_rank; } self @@ -482,9 +484,17 @@ impl AccountRuntimeSignals { } } +/// Provider 确认为账号通用且属于受支持周期的重置观测 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountQuotaResetWindow { + pub period: super::QuotaResetPeriod, + pub reset_at: SystemTime, +} + /// Provider 从私有 quota JSON 投影出的中立调度事实 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct AccountQuotaSignals { + reset_windows: Option>, reset_at: Option, remaining_rank: Option, } @@ -496,16 +506,23 @@ impl AccountQuotaSignals { Self { reset_at, remaining_rank, + reset_windows: None, } } #[must_use] - pub const fn reset_at(self) -> Option { + pub fn with_reset_windows(mut self, windows: Vec) -> Self { + self.reset_windows = (!windows.is_empty()).then(|| windows.into()); + self + } + + #[must_use] + pub const fn reset_at(&self) -> Option { self.reset_at } #[must_use] - pub const fn remaining_rank(self) -> Option { + pub const fn remaining_rank(&self) -> Option { self.remaining_rank } } @@ -940,8 +957,6 @@ impl AccountSelector { // 首输出 10 秒时延迟得分减半;固定尺度不随其他候选账号变化 const SMART_LATENCY_HALF_SCORE_MS: f64 = 10_000.0; -// 距重置一小时时得分减半;未知和已过期时间不提供重置奖励 -const SMART_RESET_HALF_SCORE_SECONDS: f64 = 3_600.0; fn capacity_utilization(candidate: &AccountCandidate, context: &AccountSelectionContext) -> f64 { context @@ -997,15 +1012,6 @@ pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelecti SMART_LATENCY_HALF_SCORE_MS / (SMART_LATENCY_HALF_SCORE_MS + latency as f64) }); - let reset = candidate - .signals - .quota_reset_at - .and_then(|reset| reset.duration_since(now).ok()) - .filter(|remaining| !remaining.is_zero()) - .map_or(0.0, |remaining| { - SMART_RESET_HALF_SCORE_SECONDS - / (SMART_RESET_HALF_SCORE_SECONDS + remaining.as_secs_f64()) - }); let [ load_weight, quota_weight, @@ -1018,5 +1024,5 @@ pub(crate) fn smart_score(candidate: &AccountCandidate, context: &AccountSelecti + quota_weight * quota + health_weight * failure + latency_weight * latency - + reset_weight * reset + + reset_weight * config.reset_score(&candidate.signals, now) } diff --git a/backend/crates/gateway-core/src/account/smart_scheduling.rs b/backend/crates/gateway-core/src/account/smart_scheduling.rs index 3d9ccedad..4551b3b45 100644 --- a/backend/crates/gateway-core/src/account/smart_scheduling.rs +++ b/backend/crates/gateway-core/src/account/smart_scheduling.rs @@ -1,11 +1,40 @@ //! 智能调度参数;固定十分位保证快照可精确比较,浮点数只用于 wire 与评分 +use std::time::SystemTime; + +use super::AccountRuntimeSignals; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(into = "SmartSchedulingValues")] pub struct SmartSchedulingConfig { weights: [u8; 6], + reset_windows: [u8; 3], +} + +/// 账号通用额度的周期;Provider 按上游周期事实投影,不依赖窗口名称和槽位 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QuotaResetPeriod { + FiveHour, + Weekly, + Monthly, +} + +impl QuotaResetPeriod { + const fn seconds(self) -> u32 { + match self { + Self::FiveHour => 18_000, + Self::Weekly => 604_800, + Self::Monthly => 2_592_000, + } + } +} + +fn weight_tenths(value: f64, field: &'static str) -> Result { + if !(0.0..=10.0).contains(&value) || (value * 10.0).round() / 10.0 != value { + return Err(SmartSchedulingConfigError::InvalidWeight(field)); + } + Ok((value * 10.0).round() as u8) } impl<'de> Deserialize<'de> for SmartSchedulingConfig { @@ -23,6 +52,7 @@ impl Default for SmartSchedulingConfig { fn default() -> Self { Self { weights: [10, 8, 10, 5, 0, 0], + reset_windows: [0; 3], } } } @@ -50,19 +80,15 @@ impl SmartSchedulingConfig { .into_iter() .enumerate() { - let value = weights[index]; - if !value.is_finite() - || !(0.0..=10.0).contains(&value) - || (value * 10.0).round() / 10.0 != value - { - return Err(SmartSchedulingConfigError::InvalidWeight(field)); - } - tenths[index] = (value * 10.0).round() as u8; + tenths[index] = weight_tenths(weights[index], field)?; } if tenths == [0; 6] { return Err(SmartSchedulingConfigError::EmptyWeights); } - Ok(Self { weights: tenths }) + Ok(Self { + weights: tenths, + ..Self::default() + }) } #[must_use] @@ -70,11 +96,44 @@ impl SmartSchedulingConfig { self.weights.map(|weight| f64::from(weight) / 10.0) } + fn reset_enabled(self) -> bool { + self.weights[4] > 0 && self.reset_windows != [0; 3] + } + + pub(crate) fn reset_score(self, signals: &AccountRuntimeSignals, now: SystemTime) -> f64 { + if !self.reset_enabled() { + return 0.0; + } + let mut scores = [0.0_f64; 3]; + for window in signals.quota_reset_windows.as_deref().unwrap_or_default() { + let Ok(remaining) = window.reset_at.duration_since(now) else { + continue; + }; + if remaining.is_zero() { + continue; + } + let half = f64::from(window.period.seconds()) / 7.0; + let score = half / (half + remaining.as_secs_f64()); + // 同一周期只计最近的有效重置,避免重复额度桶叠加得分 + let slot = &mut scores[window.period as usize]; + *slot = slot.max(score); + } + // 缺失周期得零分,分母固定,避免少报窗口反而提高排名 + let weights = self.reset_windows.map(f64::from); + scores + .into_iter() + .zip(weights) + .map(|(score, w)| score * w) + .sum::() + / weights.into_iter().sum::() + } + pub(crate) fn score_tolerance(self) -> f64 { // 与系数同步缩放,避免仅放大相同比例的系数就改变近似最优候选集合 - // 排队系数只参与入队选择,不能放大立即选号的候选容差 + // 排队和未启用的重置窗口不能放大立即选号的容差 + let count = if self.reset_enabled() { 5 } else { 4 }; 0.05 * f64::from( - self.weights[..5] + self.weights[..count] .iter() .copied() .map(u16::from) @@ -92,20 +151,37 @@ struct SmartSchedulingValues { latency_weight: f64, reset_weight: f64, queue_weight: f64, + #[serde(default)] + reset_window_weights: ResetWindowWeights, +} + +#[derive(Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ResetWindowWeights { + five_hour: f64, + weekly: f64, + monthly: f64, } impl TryFrom for SmartSchedulingConfig { type Error = SmartSchedulingConfigError; fn try_from(value: SmartSchedulingValues) -> Result { - Self::new([ + let mut config = Self::new([ value.load_weight, value.quota_weight, value.health_weight, value.latency_weight, value.reset_weight, value.queue_weight, - ]) + ])?; + let windows = value.reset_window_weights; + config.reset_windows = [ + weight_tenths(windows.five_hour, "fiveHour")?, + weight_tenths(windows.weekly, "weekly")?, + weight_tenths(windows.monthly, "monthly")?, + ]; + Ok(config) } } @@ -126,6 +202,11 @@ impl From for SmartSchedulingValues { latency_weight, reset_weight, queue_weight, + reset_window_weights: ResetWindowWeights { + five_hour: f64::from(value.reset_windows[0]) / 10.0, + weekly: f64::from(value.reset_windows[1]) / 10.0, + monthly: f64::from(value.reset_windows[2]) / 10.0, + }, } } } diff --git a/backend/crates/gateway-core/tests/account/mod.rs b/backend/crates/gateway-core/tests/account/mod.rs index 93e1e1634..488789ba0 100644 --- a/backend/crates/gateway-core/tests/account/mod.rs +++ b/backend/crates/gateway-core/tests/account/mod.rs @@ -56,6 +56,7 @@ fn candidate(id: &str, in_flight: u32, remaining: Option) -> AccountCandida in_flight, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: remaining, cooldown: None, failure_rate_basis_points: None, @@ -228,6 +229,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -247,6 +249,7 @@ fn diagnostic_selection_bypasses_all_local_account_eligibility() { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -641,6 +644,7 @@ fn provider_quota_overlay_should_preserve_store_concurrency_facts() { in_flight: 2, last_started_at: Some(last_started_at), quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/gateway-core/tests/account/smart_scheduling.rs b/backend/crates/gateway-core/tests/account/smart_scheduling.rs index d2cc6dd73..80e208f31 100644 --- a/backend/crates/gateway-core/tests/account/smart_scheduling.rs +++ b/backend/crates/gateway-core/tests/account/smart_scheduling.rs @@ -1,7 +1,8 @@ //! 验证智能调度权重、软亲和与容量约束的组合行为 use gateway_core::account::{ - AccountSelector, PreferredAccountSelection, RotationStrategy, SmartSchedulingConfig, + AccountQuotaResetWindow, AccountSelector, PreferredAccountSelection, QuotaResetPeriod, + RotationStrategy, SmartSchedulingConfig, }; use serde_json::json; use std::time::{Duration, Instant, SystemTime}; @@ -62,9 +63,10 @@ fn smart_config_rejects_invalid_weights_and_incomplete_wire_values() { #[test] fn reset_weight_rewards_only_future_resets_and_preserves_capacity_checks() { let mut context = context(RotationStrategy::Smart); - context.policy = context - .policy - .with_smart_scheduling(SmartSchedulingConfig::new([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).unwrap()); + context.policy = context.policy.with_smart_scheduling(serde_json::from_value(json!({ + "loadWeight":0, "quotaWeight":0, "healthWeight":0, "latencyWeight":0, "resetWeight":1, "queueWeight":0, + "resetWindowWeights":{"fiveHour":0,"weekly":1,"monthly":0} + })).unwrap()); let mut candidates = [ candidate_with_concurrency("acct_unknown", 0, 2), candidate_with_concurrency("acct_past", 0, 2), @@ -72,10 +74,20 @@ fn reset_weight_rewards_only_future_resets_and_preserves_capacity_checks() { candidate_with_concurrency("acct_near", 0, 2), candidate_with_concurrency("acct_far", 0, 2), ]; - candidates[1].signals.quota_reset_at = Some(context.now - Duration::from_secs(1)); - candidates[2].signals.quota_reset_at = Some(context.now); - candidates[3].signals.quota_reset_at = Some(context.now + Duration::from_secs(3600)); - candidates[4].signals.quota_reset_at = Some(context.now + Duration::from_secs(86_400)); + for (candidate, reset_at) in candidates[1..].iter_mut().zip([ + context.now - Duration::from_secs(1), + context.now, + context.now + Duration::from_secs(3600), + context.now + Duration::from_secs(86_400), + ]) { + candidate.signals.quota_reset_windows = Some( + [AccountQuotaResetWindow { + period: QuotaResetPeriod::Weekly, + reset_at, + }] + .into(), + ); + } assert_eq!( AccountSelector .select(&candidates, &context) @@ -92,8 +104,8 @@ fn reset_weight_rewards_only_future_resets_and_preserves_capacity_checks() { let scores = snapshot["events"][0]["data"]["candidates"] .as_array() .unwrap(); - for (candidate, expected) in scores.iter().zip([0.0, 0.0, 0.0, 0.5, 0.04]) { - assert_eq!(candidate["smartScore"].as_f64().unwrap(), expected); + for (candidate, expected) in scores.iter().zip([0.0, 0.0, 0.0, 0.96, 0.5]) { + assert!((candidate["smartScore"].as_f64().unwrap() - expected).abs() < 1e-10); } candidates[3].signals.in_flight = 2; assert_eq!( @@ -120,6 +132,36 @@ fn reset_weight_rewards_only_future_resets_and_preserves_capacity_checks() { ); } +#[test] +fn zero_or_absent_window_weights_disable_reset_scores_and_tolerance() { + let mut context = context(RotationStrategy::Smart); + let mut candidate = candidate_with_concurrency("acct_reset", 0, 2); + candidate.signals.quota_reset_windows = Some( + [AccountQuotaResetWindow { + period: QuotaResetPeriod::Monthly, + reset_at: context.now + Duration::from_secs(1), + }] + .into(), + ); + let legacy = json!({"loadWeight":0,"quotaWeight":0,"healthWeight":0,"latencyWeight":0,"resetWeight":10,"queueWeight":0}); + let mut disabled = legacy.clone(); + disabled["resetWindowWeights"] = json!({"fiveHour":0,"weekly":0,"monthly":0}); + for wire in [legacy, disabled] { + let config: SmartSchedulingConfig = serde_json::from_value(wire).unwrap(); + context.policy = context.policy.with_smart_scheduling(config); + let trace = gateway_core::diagnostics::TraceContext::new("req_zero_windows"); + trace.account_selection(std::slice::from_ref(&candidate), &context, None); + let events = trace.snapshot().unwrap(); + let data = &events["events"][0]["data"]; + assert_eq!(data["candidates"][0]["smartScore"], 0.0); + assert_eq!(data["smartScoreTolerance"], 0.0); + assert_eq!( + serde_json::to_value(config).unwrap()["resetWindowWeights"], + json!({"fiveHour":0.0,"weekly":0.0,"monthly":0.0}) + ); + } +} + #[test] fn queue_weight_balances_live_pressure_and_health_only_when_enabled_for_smart() { for (strategy, queue_weight, expects_shortest) in [ @@ -349,3 +391,41 @@ fn higher_weight_recovery_preserves_usable_soft_affinity() { ); } } + +#[test] +fn missing_expired_and_duplicate_periods_do_not_inflate_reset_score() { + let mut context = context(RotationStrategy::Smart); + let mut candidate = candidate_with_concurrency("acct_partial", 0, 2); + candidate.signals.quota_reset_at = Some(context.now + Duration::from_secs(1)); + candidate.signals.quota_reset_windows = Some( + [ + (QuotaResetPeriod::Weekly, 86400), + (QuotaResetPeriod::Weekly, 90000), + (QuotaResetPeriod::Weekly, 0), + (QuotaResetPeriod::FiveHour, 0), + ] + .map(|(period, delta)| AccountQuotaResetWindow { + period, + reset_at: context.now + Duration::from_secs(delta), + }) + .into(), + ); + for scale in [1.0, 0.5] { + let mut config = serde_json::to_value( + SmartSchedulingConfig::new([0.0, 0.0, 0.0, 0.0, 1.0, 0.0]).unwrap(), + ) + .unwrap(); + config["resetWindowWeights"] = json!({ + "weekly": 2.0*scale, "fiveHour": 4.0*scale, "monthly": 4.0*scale + }); + context.policy = context + .policy + .with_smart_scheduling(serde_json::from_value(config).unwrap()); + let trace = gateway_core::diagnostics::TraceContext::new("req_partial"); + trace.account_selection(std::slice::from_ref(&candidate), &context, None); + assert_eq!( + trace.snapshot().unwrap()["events"][0]["data"]["candidates"][0]["smartScore"], + 0.1 + ); + } +} diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index 0a22df84c..dbd0e350a 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -2324,6 +2324,7 @@ impl Provider for PolicySelectingProvider { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/gateway-core/tests/engine/policy.rs b/backend/crates/gateway-core/tests/engine/policy.rs index 10e47a59a..9fbd1fa00 100644 --- a/backend/crates/gateway-core/tests/engine/policy.rs +++ b/backend/crates/gateway-core/tests/engine/policy.rs @@ -77,6 +77,7 @@ fn candidate(id: &str) -> AccountCandidate { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/gateway-core/tests/provider_ports/mod.rs b/backend/crates/gateway-core/tests/provider_ports/mod.rs index e97678497..50dbb8819 100644 --- a/backend/crates/gateway-core/tests/provider_ports/mod.rs +++ b/backend/crates/gateway-core/tests/provider_ports/mod.rs @@ -200,6 +200,7 @@ fn scheduling_state_preserves_provider_neutral_signals() { in_flight: 2, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: Some(7), cooldown: None, failure_rate_basis_points: Some(125), diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs index 583cb485d..7de163212 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs @@ -630,6 +630,7 @@ fn candidate(id: &str, weight: u16) -> AccountCandidate { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs index 54a7532be..034887865 100644 --- a/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs +++ b/backend/crates/gateway-plugin/sdk/src/call/services/settings.rs @@ -256,6 +256,15 @@ pub struct SmartSchedulingConfig { pub latency_weight: f64, pub reset_weight: f64, pub queue_weight: f64, + #[serde(default)] + pub reset_window_weights: ResetWindowWeights, +} +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ResetWindowWeights { + pub five_hour: f64, + pub weekly: f64, + pub monthly: f64, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] diff --git a/backend/crates/gateway-store/src/redis/credential_leases/mod.rs b/backend/crates/gateway-store/src/redis/credential_leases/mod.rs index 1f4ccb479..71dfc2d69 100644 --- a/backend/crates/gateway-store/src/redis/credential_leases/mod.rs +++ b/backend/crates/gateway-store/src/redis/credential_leases/mod.rs @@ -676,6 +676,7 @@ impl RedisProviderLeaseCoordinator { in_flight: signal.in_flight, last_started_at: signal.last_started_at.map(Into::into), quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs index 202bc22e4..d2296e338 100644 --- a/backend/crates/gateway-store/tests/postgres/runtime_settings.rs +++ b/backend/crates/gateway-store/tests/postgres/runtime_settings.rs @@ -126,21 +126,23 @@ async fn smart_settings_round_trip_publish_and_restore_database_defaults() { SmartSchedulingConfig::default() ); let mut update = settings_with_margin(3600); - update.values.smart_scheduling = - SmartSchedulingConfig::new([0.0, 2.0, 1.0, 0.5, 1.2, 2.3]).unwrap(); - let expected = update.values.smart_scheduling; + let expected = serde_json::json!({ + "loadWeight": 0.0, "quotaWeight": 2.0, "healthWeight": 1.0, "latencyWeight": 0.5, "resetWeight": 1.2, "queueWeight": 2.3, + "resetWindowWeights": {"fiveHour":2.0,"weekly":8.0,"monthly":0.0} + }); + update.values.smart_scheduling = serde_json::from_value(expected.clone()).unwrap(); repository.update_runtime_settings(update).await.unwrap(); let reloaded = repository.load_runtime_settings().await.unwrap(); - assert_eq!(reloaded.values.smart_scheduling, expected); + assert_eq!( + serde_json::to_value(reloaded.values.smart_scheduling).unwrap(), + expected + ); let snapshot = PgRuntimeSnapshotRepository::new(database.pool.clone()) .load_runtime_snapshot() .await .unwrap(); let snapshot_values = serde_json::to_value(&snapshot.settings).unwrap(); - assert_eq!( - snapshot_values["smart_scheduling"], - serde_json::to_value(expected).unwrap() - ); + assert_eq!(snapshot_values["smart_scheduling"], expected); assert!(snapshot.config_revision > before.config_revision); sqlx::query("update runtime_settings set smart_scheduling_json = default where id = 1") .execute(&database.pool) diff --git a/backend/crates/providers/openai/src/credential/quota/scheduling.rs b/backend/crates/providers/openai/src/credential/quota/scheduling.rs index 484a71474..2700e607f 100644 --- a/backend/crates/providers/openai/src/credential/quota/scheduling.rs +++ b/backend/crates/providers/openai/src/credential/quota/scheduling.rs @@ -72,7 +72,7 @@ struct CodexQuotaRefreshAttempt { wall_at: SystemTime, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] struct CodexQuotaSchedulingEntry { version: u64, revision: CredentialRevision, @@ -211,7 +211,7 @@ impl CodexQuotaSchedulingProjection { .filter(|entry| { entry.revision == account.revision() && Instant::now() < entry.expires_at }) - .and_then(|entry| entry.signals) + .and_then(|entry| entry.signals.clone()) } pub(super) fn reserve_periodic_refreshes( diff --git a/backend/crates/providers/openai/src/credential/quota/snapshot.rs b/backend/crates/providers/openai/src/credential/quota/snapshot.rs index 007b8fe8d..5b2d7b52b 100644 --- a/backend/crates/providers/openai/src/credential/quota/snapshot.rs +++ b/backend/crates/providers/openai/src/credential/quota/snapshot.rs @@ -8,8 +8,8 @@ use std::time::{Duration, SystemTime}; use chrono::{DateTime, Utc}; use gateway_core::account::{ - AccountQuotaSignals, CredentialRevision, ProviderAccountId, QuotaEvidence, QuotaObservation, - QuotaState, + AccountQuotaResetWindow, AccountQuotaSignals, CredentialRevision, ProviderAccountId, + QuotaEvidence, QuotaObservation, QuotaResetPeriod, QuotaState, }; use gateway_protocol::openai::events::{CreditsSnapshot, parse_credits_from_object}; use serde_json::{Map, Value}; @@ -371,6 +371,7 @@ pub(crate) fn quota_scheduling_signals( let now = SystemTime::now(); let mut remaining_rank: Option = None; let mut reset_at: Option = None; + let mut reset_windows = Vec::new(); for window in &snapshot.windows { if quota_window_ttl(window, snapshot.observed_at(), now).is_none() { continue; @@ -385,10 +386,22 @@ pub(crate) fn quota_scheduling_signals( } if let Some(reset) = window_reset_at.filter(|reset| *reset > now) { reset_at = Some(reset_at.map_or(reset, |current| current.min(reset))); + if window.is_account_wide() { + let period = match window.kind() { + CodexQuotaWindowKind::ShortTerm => QuotaResetPeriod::FiveHour, + CodexQuotaWindowKind::Weekly => QuotaResetPeriod::Weekly, + CodexQuotaWindowKind::Monthly => QuotaResetPeriod::Monthly, + CodexQuotaWindowKind::Other => continue, + }; + reset_windows.push(AccountQuotaResetWindow { + period, + reset_at: reset, + }); + } } } if remaining_rank.is_some() || reset_at.is_some() { - Some(AccountQuotaSignals::new(reset_at, remaining_rank)) + Some(AccountQuotaSignals::new(reset_at, remaining_rank).with_reset_windows(reset_windows)) } else { None } @@ -636,9 +649,7 @@ fn parse_rate_limit_windows( .transpose()?; let limit_reached = optional_bool(window, "limit_reached")?.unwrap_or(false); let kind = quota_window_kind(window_seconds); - // primary/secondary 是协议槽位,不代表固定周期 - // 窗口身份使用上游 - // limit_id 和实际时长,5h/周/月分类只参与展示 + // 槽位不代表周期,窗口键保留上游额度桶和实际时长;周期分类供展示及智能调度使用 let key = match window_seconds { Some(seconds) => format!("{source}:{seconds}s"), None => format!("{source}:{name}"), diff --git a/backend/crates/providers/openai/src/credential/selector.rs b/backend/crates/providers/openai/src/credential/selector.rs index db3740d1c..d45d344a9 100644 --- a/backend/crates/providers/openai/src/credential/selector.rs +++ b/backend/crates/providers/openai/src/credential/selector.rs @@ -1054,6 +1054,7 @@ impl CodexCredentialSelector { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/credential/contract/capacity.rs b/backend/crates/providers/openai/tests/credential/contract/capacity.rs index ed0573fb1..6d553a3ad 100644 --- a/backend/crates/providers/openai/tests/credential/contract/capacity.rs +++ b/backend/crates/providers/openai/tests/credential/contract/capacity.rs @@ -16,6 +16,7 @@ fn busy_signal(in_flight: u32) -> AccountRuntimeSignals { in_flight, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs b/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs index 8d75ba411..7ad96a362 100644 --- a/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs +++ b/backend/crates/providers/openai/tests/credential/contract/scheduling_projection.rs @@ -52,6 +52,7 @@ fn signal(in_flight: u32) -> AccountRuntimeSignals { in_flight, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/credential/quota/scheduling.rs b/backend/crates/providers/openai/tests/credential/quota/scheduling.rs index 0e53d15d5..542435f2f 100644 --- a/backend/crates/providers/openai/tests/credential/quota/scheduling.rs +++ b/backend/crates/providers/openai/tests/credential/quota/scheduling.rs @@ -86,6 +86,7 @@ async fn old_weekly_quota_should_outweigh_one_in_flight_title_request() { in_flight: u32::from(account.id().as_str() == "acct_74"), last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -280,3 +281,88 @@ async fn reset_window_should_not_clear_confirmed_exhaustion() { QuotaAccessState::Exhausted ); } + +#[tokio::test] +async fn weekly_window_prefers_the_first_weekly_reset_independently_of_short_resets() { + let store = Arc::new(MemoryAccountStore::default()); + let now = UNIX_EPOCH + Duration::from_secs(timestamp(SystemTime::now())); + let mut accounts = Vec::new(); + // 三个账号的短窗口与周窗口顺序相反,确保选择的是配置的窗口而非最早时间 + for (id, hour, day) in [("acct_one", 1, 2), ("acct_two", 2, 3), ("acct_three", 3, 1)] { + accounts.push(persist_snapshot(&store, id, now, json!({ + "primary_window": {"used_percent":10,"limit_window_seconds":18000,"reset_at":timestamp(now) + hour * 3600u64}, + "secondary_window": {"used_percent":10,"limit_window_seconds":604800,"reset_at":timestamp(now) + day * 86400u64} + })).await); + } + let service = quota_service(&store); + service.prepare_scheduling(&accounts).await; + let candidates = accounts + .into_iter() + .map(|account| AccountCandidate { + inherited_concurrency: None, + signals: AccountRuntimeSignals { + in_flight: 0, + last_started_at: None, + quota_reset_at: None, + quota_reset_windows: None, + quota_remaining_rank: None, + cooldown: None, + failure_rate_basis_points: None, + first_output_latency_ms: None, + } + .with_provider_quota(service.scheduling_signals(&account)), + account, + }) + .collect::>(); + let mut config = json!({"loadWeight":0,"quotaWeight":0,"healthWeight":0,"latencyWeight":0,"resetWeight":1,"queueWeight":0}); + let policy = |strategy, config: &Value| { + AccountSelectionPolicy::new(strategy, NonZeroU32::new(3).unwrap()) + .with_smart_scheduling(serde_json::from_value(config.clone()).unwrap()) + }; + let mut context = AccountSelectionContext { + policy: policy(RotationStrategy::Smart, &config), + now, + excluded_accounts: Default::default(), + busy_accounts: Default::default(), + preferred_account: None, + preferred_account_overrides_weight: false, + round_robin_cursor: 0, + eligibility: AccountEligibilityPolicy::Enforce, + account_scope: None, + reserved_concurrency: 0, + }; + let selected = |pool: &[AccountCandidate], context: &AccountSelectionContext| { + AccountSelector + .select(pool, context) + .unwrap() + .candidate() + .account + .id() + .as_str() + .to_owned() + }; + config["resetWindowWeights"] = json!({"fiveHour":1,"weekly":0,"monthly":0}); + context.policy = policy(RotationStrategy::Smart, &config); + assert_eq!(selected(&candidates, &context), "acct_one"); + config["resetWindowWeights"] = json!({"fiveHour":0,"weekly":1,"monthly":0}); + context.policy = policy(RotationStrategy::Smart, &config); + assert_eq!(selected(&candidates, &context), "acct_three"); + let trace = gateway_core::diagnostics::TraceContext::new("req_weekly"); + trace.account_selection(&candidates, &context, None); + let snapshot = trace.snapshot().unwrap(); + let data = &snapshot["events"][0]["data"]; + for (candidate, expected) in + data["candidates"] + .as_array() + .unwrap() + .iter() + .zip([1.0 / 3.0, 0.25, 0.5]) + { + assert!((candidate["smartScore"].as_f64().unwrap() - expected).abs() < 1e-10); + } + assert!(1.0 / 3.0 - 0.25 > data["smartScoreTolerance"].as_f64().unwrap()); + context.round_robin_cursor = 1; + assert_eq!(selected(&candidates[..2], &context), "acct_one"); + context.policy = policy(RotationStrategy::QuotaResetPriority, &config); + assert_eq!(selected(&candidates, &context), "acct_one"); +} diff --git a/backend/crates/providers/openai/tests/provider/contract/capacity.rs b/backend/crates/providers/openai/tests/provider/contract/capacity.rs index b3503c894..dba860bc0 100644 --- a/backend/crates/providers/openai/tests/provider/contract/capacity.rs +++ b/backend/crates/providers/openai/tests/provider/contract/capacity.rs @@ -194,6 +194,7 @@ async fn guardian_and_normal_requests_use_independent_capacity_and_observations( in_flight, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -326,6 +327,7 @@ async fn a_full_capacity_pool_does_not_block_the_other_pools_queue() { in_flight: if guardian_waits { 1 } else { 2 }, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 1bfbbef05..04f420884 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -3879,6 +3879,7 @@ async fn capacity_selection_error_preserves_classification_and_retry_after() { in_flight: u32::MAX, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs index f1101f562..3475516c5 100644 --- a/backend/crates/providers/openai/tests/provider/contract/session_binding.rs +++ b/backend/crates/providers/openai/tests/provider/contract/session_binding.rs @@ -1659,6 +1659,7 @@ async fn preferred_final_thread_rewrite_within_the_session_preserves_the_primary in_flight: 100, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -1888,6 +1889,7 @@ async fn preferred_primary_migration_distinguishes_temporary_and_persistent_unav in_flight: 2, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, @@ -2013,6 +2015,7 @@ async fn preferred_spillover_stays_stable_and_concurrent_migration_claims_one_pr in_flight: 100, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs b/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs index 47c1a2e4d..e21940815 100644 --- a/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs +++ b/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs @@ -1155,6 +1155,7 @@ async fn guardian_reservation_survives_upstream_adapters_and_metadata_precedence in_flight: 2, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/openai/tests/support.rs b/backend/crates/providers/openai/tests/support.rs index 0c35afe1e..7a01140d4 100644 --- a/backend/crates/providers/openai/tests/support.rs +++ b/backend/crates/providers/openai/tests/support.rs @@ -957,6 +957,7 @@ impl ProviderLeasePort for TestLeaseCoordinator { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/xai/src/credential/quota.rs b/backend/crates/providers/xai/src/credential/quota.rs index 7cdd18273..074df75df 100644 --- a/backend/crates/providers/xai/src/credential/quota.rs +++ b/backend/crates/providers/xai/src/credential/quota.rs @@ -7,8 +7,8 @@ use std::time::{Duration, Instant, SystemTime}; use chrono::{DateTime, Utc}; use gateway_core::account::{ - AccountQuotaSignals, CredentialRevision, ProviderAccount, ProviderAccountId, QuotaObservation, - QuotaState, + AccountQuotaResetWindow, AccountQuotaSignals, CredentialRevision, ProviderAccount, + ProviderAccountId, QuotaObservation, QuotaResetPeriod, QuotaState, }; use tokio::sync::Mutex; @@ -180,7 +180,7 @@ struct GrokQuotaProjectionState { entries: BTreeMap, } -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] struct GrokQuotaSchedulingEntry { version: u64, revision: CredentialRevision, @@ -317,7 +317,7 @@ impl GrokQuotaSchedulingProjection { .filter(|entry| { entry.revision == account.revision() && Instant::now() < entry.expires_at }) - .and_then(|entry| entry.signals) + .and_then(|entry| entry.signals.clone()) } } @@ -585,8 +585,20 @@ fn quota_scheduling_signals(billing: &GrokBillingPresentation) -> Option now); - (remaining_rank.is_some() || reset_at.is_some()) - .then(|| AccountQuotaSignals::new(reset_at, remaining_rank)) + (remaining_rank.is_some() || reset_at.is_some()).then(|| { + let signals = AccountQuotaSignals::new(reset_at, remaining_rank); + let period = match billing.period_kind() { + GrokQuotaPeriodKind::Weekly => Some(QuotaResetPeriod::Weekly), + GrokQuotaPeriodKind::Monthly => Some(QuotaResetPeriod::Monthly), + GrokQuotaPeriodKind::Other => None, + }; + match (period, reset_at) { + (Some(period), Some(reset_at)) if billing.has_authoritative_quota() => { + signals.with_reset_windows(vec![AccountQuotaResetWindow { period, reset_at }]) + } + _ => signals, + } + }) } /// 把 xAI billing 文档归一化为访问结论 diff --git a/backend/crates/providers/xai/tests/admin.rs b/backend/crates/providers/xai/tests/admin.rs index 67c7dd0c3..93b96a08e 100644 --- a/backend/crates/providers/xai/tests/admin.rs +++ b/backend/crates/providers/xai/tests/admin.rs @@ -827,6 +827,7 @@ impl ProviderLeasePort for TestLeases { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/xai/tests/credential/quota.rs b/backend/crates/providers/xai/tests/credential/quota.rs index 4381a53a3..c0a186376 100644 --- a/backend/crates/providers/xai/tests/credential/quota.rs +++ b/backend/crates/providers/xai/tests/credential/quota.rs @@ -301,6 +301,47 @@ async fn billing_access_and_scheduling_use_current_quota_fields() { } } +#[tokio::test] +async fn billing_projects_only_recognized_periods_with_quota_evidence() { + use gateway_core::account::{AccountQuotaResetWindow, AccountQuotaSignals, QuotaResetPeriod}; + let end = "2099-08-01T00:00:00Z"; + let reset_at = SystemTime::from(chrono::DateTime::parse_from_rfc3339(end).unwrap()); + for (kind, used, expected) in [ + ( + "USAGE_PERIOD_TYPE_WEEKLY", + Some(25), + Some(QuotaResetPeriod::Weekly), + ), + ( + "USAGE_PERIOD_TYPE_MONTHLY", + Some(25), + Some(QuotaResetPeriod::Monthly), + ), + ("USAGE_PERIOD_TYPE_MONTHLY", None, None), + ("USAGE_PERIOD_TYPE_DAILY", Some(25), None), + ] { + let (store, repository) = repository_with_accounts(&[("period", "period")]).await; + let mut config = serde_json::json!({"currentPeriod":{"type":kind,"end":end}}); + if let Some(percent) = used { + config["creditUsagePercent"] = percent.into(); + } + let body = serde_json::to_vec(&serde_json::json!({"config":config})).unwrap(); + let service = + crate::support::grok_quota_service(repository, QueueBillingTransport::success(&body)); + let id = account_id("period"); + service.refresh_account(&id).await.unwrap(); + let mut signals = AccountQuotaSignals::new(Some(reset_at), used.map(|_| 7500)); + if let Some(period) = expected { + signals = + signals.with_reset_windows(vec![AccountQuotaResetWindow { period, reset_at }]); + } + assert_eq!( + service.scheduling_signals(&store.account(&id).unwrap()), + Some(signals) + ); + } +} + #[tokio::test] async fn signed_prepaid_balance_preserves_wire_and_recovers_access_when_current() { use gateway_core::account::QuotaAccessState::{Allowed, Exhausted}; diff --git a/backend/crates/providers/xai/tests/credential/selector.rs b/backend/crates/providers/xai/tests/credential/selector.rs index 276f967b0..a9cf56b53 100644 --- a/backend/crates/providers/xai/tests/credential/selector.rs +++ b/backend/crates/providers/xai/tests/credential/selector.rs @@ -140,6 +140,7 @@ impl SelectorFixture { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/backend/crates/providers/xai/tests/provider/contract/mod.rs b/backend/crates/providers/xai/tests/provider/contract/mod.rs index 1e6c5a943..f384e9c2e 100644 --- a/backend/crates/providers/xai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/xai/tests/provider/contract/mod.rs @@ -1855,6 +1855,7 @@ impl ProviderLeasePort for DiagnosticLeasePort { in_flight: 0, last_started_at: None, quota_reset_at: None, + quota_reset_windows: None, quota_remaining_rank: None, cooldown: None, failure_rate_basis_points: None, diff --git a/docs/api.md b/docs/api.md index 9c7dcbc4e..f48a66bb3 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2346,16 +2346,18 @@ Chat Completions 和 Responses 通过原生 OpenAI Provider 选号时,缺少 "healthWeight": 1.0, "latencyWeight": 0.5, "resetWeight": 0.0, - "queueWeight": 0.0 + "queueWeight": 0.0, + "resetWindowWeights": { "fiveHour": 0.0, "weekly": 0.0, "monthly": 0.0 } } ``` 六项系数分别调整负载、剩余额度、健康、首个有效输出延迟、额度重置和排队压力的评分偏好,范围 `0~10`、最多一位小数, 至少一项大于 `0`。`0` 仅关闭对应评分维度,不放宽账号资格、额度或并发限制;系数不表示流量百分比。 -缺字段、`null`、未知字段及无效数值均返回 `422`,不写入配置。读取设置额外返回只读 +缺少必填系数、系数为 `null`、未知字段及无效数值均返回 `422`,不写入配置。读取设置额外返回只读 `smartSchedulingDefaults`,内容为上述默认对象,用于恢复默认与自定义状态比较,不可提交到更新接口 -`resetWeight` 越大越偏向即将重置额度的账号,复用已有有效重置时间,未知或已过期时不加分。 +`resetWeight` 控制重置分在总评分中的比重。`resetWindowWeights` 中的 `fiveHour`、`weekly`、`monthly` 分别表示 5 小时、周和月的相对系数。三项均为 0~10、最多一位小数。默认均为 0,旧配置省略整个字段时也取 0;全部为 0 时不计重置分。设为 `{"fiveHour":0,"weekly":1,"monthly":0}` 可只按周重置评分。只计算账号通用窗口,未知、缺失或已过期的周期贡献为零;独立的 `quota_reset_priority` 策略仍按最早有效重置时间排序 + `queueWeight` 只在没有可立即使用的账号、需要选择等待队列时参与评分,越大越偏向等待人数少的账号。 设为 `0` 时沿用最短队列规则;启用后结合其余五项评分选择队列。队列人数限于当前进程,只有开启账号排队才会生效, 不影响已入队请求的位置、队内 FIFO、容量上限或等待超时。两项默认均为 `0` diff --git a/docs/architecture.md b/docs/architecture.md index 1aec6247d..2eabc2464 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -674,9 +674,9 @@ OpenAI 只使用未满 30 分钟且尚未收到变化通知的账号目录排除 ### 智能调度 Core 定义、校验并统一拥有评分规则,内置选号与诊断复用同一函数;Store 随运行设置和配置 revision 原子保存, -快照编译器将其纳入 `AccountSelectionPolicy`。近似最优容差随立即选号的五项系数总和缩放 +快照编译器将其纳入 `AccountSelectionPolicy`。近似最优容差随立即选号的有效系数总和缩放 -- 额度重置使用 Provider 的有效重置时间,未知或已过期时间不加分 +- 额度重置按 5 小时、周、月分别评分。Provider 复用已有额度快照的周期分类,只投影账号通用窗口。每个周期取最近的未来重置,以周期的七分之一为尺度 `H`,得分为 `H / (H + 剩余秒数)`。三个周期按所配系数取加权平均,缺失、未知或过期不加分,分母不随账号变化;三项默认为 0,此时重置不参与评分及容差计算 - 排队系数只在选择等待队列时结合其他评分和进程内实时等待人数,不影响立即选号分数与容差;系数为零时选最短队列。 `ConcurrencyWaitQueue` 在同一锁内读取队长并入队,保持已有位置、同级 FIFO、取消回收、容量和共享等待预算;Provider 传入候选须已限定续写范围 - 健康分按已发送尝试的结果计算账号级平滑失败率并随时间衰减;明确容量拒绝的平滑权重为 0.4,其他可计分失败和成功为 0.2 diff --git a/frontend/src/api/modules/settings/index.ts b/frontend/src/api/modules/settings/index.ts index 966a52714..3fdffe67f 100644 --- a/frontend/src/api/modules/settings/index.ts +++ b/frontend/src/api/modules/settings/index.ts @@ -30,6 +30,7 @@ export interface SmartSchedulingConfig { latencyWeight: number resetWeight: number queueWeight: number + resetWindowWeights: { fiveHour: number, weekly: number, monthly: number } } export interface RuntimeSettings { diff --git a/frontend/src/i18n/locales/en/settings.json b/frontend/src/i18n/locales/en/settings.json index 36c04cfe4..bb0cc2305 100644 --- a/frontend/src/i18n/locales/en/settings.json +++ b/frontend/src/i18n/locales/en/settings.json @@ -150,6 +150,14 @@ "unitLabel": "USD / 1M tokens" }, "scheduling": { + "runtimeGroup": "Runtime signals", + "quotaGroup": "Quota", + "queueGroup": "Queue", + "windowMode": "Reset window weights", + "windowHelp": "Higher weights give a window more influence on the reset score. Set a weight to 0 to ignore that window.", + "fiveHour": "5 hours", + "weekly": "Weekly", + "monthly": "Monthly", "roundRobin": "Round robin", "autoReviewSlotsHelp": "Applies to Codex accounts only: with a regular concurrency limit of 10 and 3 auto review slots, up to 10 regular requests and 3 auto review requests can run independently", "autoReviewQueueHelp": "With dedicated slots, auto review uses a separate queue that may exceed account queue capacity, while total queue capacity, queue timeout, and API key limits still apply", diff --git a/frontend/src/i18n/locales/zh-Hans/settings.json b/frontend/src/i18n/locales/zh-Hans/settings.json index 318490216..9a37f1f30 100644 --- a/frontend/src/i18n/locales/zh-Hans/settings.json +++ b/frontend/src/i18n/locales/zh-Hans/settings.json @@ -150,6 +150,14 @@ "unitLabel": "USD / 百万 Token" }, "scheduling": { + "runtimeGroup": "运行状态", + "quotaGroup": "额度", + "queueGroup": "排队", + "windowMode": "重置窗口系数", + "windowHelp": "系数越大,该窗口越影响重置评分。设为 0 可忽略该窗口。", + "fiveHour": "5 小时", + "weekly": "周", + "monthly": "月", "roundRobin": "轮询", "autoReviewSlotsHelp": "仅对 Codex 账号生效,普通并发为 10、审批名额为 3 时,两类请求分别最多运行 10 个和 3 个,互不占用名额", "autoReviewQueueHelp": "开启独立额度后,审批请求单独排队,可超过账号队列容量,仍受总等待容量、排队超时与密钥限额约束", diff --git a/frontend/src/i18n/locales/zh-Hant/settings.json b/frontend/src/i18n/locales/zh-Hant/settings.json index 188bed3f5..e3393bdbd 100644 --- a/frontend/src/i18n/locales/zh-Hant/settings.json +++ b/frontend/src/i18n/locales/zh-Hant/settings.json @@ -150,6 +150,14 @@ "unitLabel": "USD / 百萬 Token" }, "scheduling": { + "runtimeGroup": "執行狀態", + "quotaGroup": "額度", + "queueGroup": "排隊", + "windowMode": "重置視窗係數", + "windowHelp": "係數越大,該窗口越影響重置評分。設為 0 可忽略該窗口。", + "fiveHour": "5 小時", + "weekly": "週", + "monthly": "月", "roundRobin": "輪詢", "autoReviewSlotsHelp": "僅對 Codex 賬號生效,普通併發爲 10、審批名額爲 3 時,兩類請求分別最多運行 10 個和 3 個,互不佔用名額", "autoReviewQueueHelp": "開啓獨立額度後,審批請求單獨排隊,可超過賬號隊列容量,仍受總等待容量、排隊超時與密鑰限額約束", diff --git a/frontend/src/views/settings/components/SmartSchedulingModal.vue b/frontend/src/views/settings/components/SmartSchedulingModal.vue index 499bd67d3..6e82e87bf 100644 --- a/frontend/src/views/settings/components/SmartSchedulingModal.vue +++ b/frontend/src/views/settings/components/SmartSchedulingModal.vue @@ -18,38 +18,81 @@ const { t } = useI18n({ useScope: 'global' }) const open = defineModel({ required: true }) const formId = useId() -const fields = computed(() => ([ +interface WeightGroup { + id: 'runtime' | 'quota' | 'queue' + title: string + fields: { key: Exclude, label: string, help: string }[] +} +const groups = computed(() => [ { - key: 'loadWeight', - label: t('settings.scheduling.weights.load'), - help: t('settings.scheduling.weights.loadHelp'), + id: 'runtime', + title: t('settings.scheduling.runtimeGroup'), + fields: [ + { + key: 'loadWeight', + label: t('settings.scheduling.weights.load'), + help: t('settings.scheduling.weights.loadHelp'), + }, + { + key: 'healthWeight', + label: t('settings.scheduling.weights.health'), + help: t('settings.scheduling.weights.healthHelp'), + }, + { + key: 'latencyWeight', + label: t('settings.scheduling.weights.latency'), + help: t('settings.scheduling.weights.latencyHelp'), + }, + ], }, { - key: 'quotaWeight', - label: t('settings.scheduling.weights.quota'), - help: t('settings.scheduling.weights.quotaHelp'), + id: 'quota', + title: t('settings.scheduling.quotaGroup'), + fields: [ + { + key: 'quotaWeight', + label: t('settings.scheduling.weights.quota'), + help: t('settings.scheduling.weights.quotaHelp'), + }, + { + key: 'resetWeight', + label: t('settings.scheduling.weights.reset'), + help: t('settings.scheduling.weights.resetHelp'), + }, + ], }, { - key: 'healthWeight', - label: t('settings.scheduling.weights.health'), - help: t('settings.scheduling.weights.healthHelp'), + id: 'queue', + title: t('settings.scheduling.queueGroup'), + fields: [ + { + key: 'queueWeight', + label: t('settings.scheduling.weights.queue'), + help: t('settings.scheduling.weights.queueHelp'), + }, + ], + }, +]) +const fields = computed(() => groups.value.flatMap(group => group.fields)) +const periods = computed(() => [ + { + key: 'fiveHour', + label: t('settings.scheduling.fiveHour'), }, { - key: 'latencyWeight', - label: t('settings.scheduling.weights.latency'), - help: t('settings.scheduling.weights.latencyHelp'), + key: 'weekly', + label: t('settings.scheduling.weekly'), }, { - key: 'resetWeight', - label: t('settings.scheduling.weights.reset'), - help: t('settings.scheduling.weights.resetHelp'), + key: 'monthly', + label: t('settings.scheduling.monthly'), }, - { - key: 'queueWeight', - label: t('settings.scheduling.weights.queue'), - help: t('settings.scheduling.weights.queueHelp'), - }, -] as const)) +] as const) +const windows = reactive({ fiveHour: '', weekly: '', monthly: '' }) +function validWeight(input: string) { + const value = Number(input) + return input.trim() !== '' && Number.isFinite(value) && value >= 0 && value <= 10 && Math.round(value * 10) / 10 === value +} const draft = reactive({ loadWeight: '', quotaWeight: '', @@ -60,8 +103,7 @@ const draft = reactive({ }) const submitted = shallowRef(false) const errors = computed(() => Object.fromEntries(fields.value.map(({ key }) => { - const value = Number(draft[key]) - const valid = draft[key].trim() && Number.isFinite(value) && value >= 0 && value <= 10 && Math.round(value * 10) / 10 === value + const valid = validWeight(draft[key]) return [ key, valid @@ -74,6 +116,8 @@ const emptyWeights = computed(() => fields.value.every(({ key }) => Number(draft function replaceDraft(config: SmartSchedulingConfig) { for (const { key } of fields.value) draft[key] = String(config[key]) + for (const { key } of periods.value) + windows[key] = String(config.resetWindowWeights[key]) submitted.value = false } @@ -84,9 +128,14 @@ watch(open, (value) => { function confirm() { submitted.value = true - if (Object.values(errors.value).some(Boolean) || emptyWeights.value) + if (Object.values(errors.value).some(Boolean) || emptyWeights.value || !Object.values(windows).every(validWeight)) return emit('confirm', { + resetWindowWeights: { + fiveHour: Number(windows.fiveHour), + weekly: Number(windows.weekly), + monthly: Number(windows.monthly), + }, loadWeight: Number(draft.loadWeight), quotaWeight: Number(draft.quotaWeight), healthWeight: Number(draft.healthWeight), @@ -104,9 +153,12 @@ function confirm() {

{{ t('settings.scheduling.enabledHelp') }}

-
-
- +
+

+ {{ group.title }} +

+
+