diff --git a/backend/crates/gateway-api/tests/data_plane/models.rs b/backend/crates/gateway-api/tests/data_plane/models.rs index d6e18874c..c1afeb5d4 100644 --- a/backend/crates/gateway-api/tests/data_plane/models.rs +++ b/backend/crates/gateway-api/tests/data_plane/models.rs @@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba runtime["account_queue_timeout_seconds"] = serde_json::json!(30); runtime["switch_account_on_queue_failure"] = serde_json::json!(false); settings.runtime = serde_json::from_value(runtime).unwrap(); - settings.fast_mode = FastMode::Disabled; + settings.fast_mode = Some(FastMode::Disabled); }), ..Default::default() })); @@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba "model-a" ); assert_ne!( - execution.client.policy().account_scope().fast_mode(), - FastMode::Disabled + execution + .client + .policy() + .account_scope() + .fast_mode_override(), + Some(FastMode::Disabled) ); } } diff --git a/backend/crates/gateway-core/src/account/scope.rs b/backend/crates/gateway-core/src/account/scope.rs index 2d6da5611..28bb45825 100644 --- a/backend/crates/gateway-core/src/account/scope.rs +++ b/backend/crates/gateway-core/src/account/scope.rs @@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory { providers_with_accounts: BTreeSet, providers_by_group: BTreeMap>, group_model_access: BTreeMap, + group_fast_modes: BTreeMap, } impl RuntimeAccountDirectory { @@ -129,6 +130,7 @@ impl RuntimeAccountDirectory { providers_with_accounts, providers_by_group, group_model_access: BTreeMap::new(), + group_fast_modes: BTreeMap::new(), } } @@ -141,6 +143,12 @@ impl RuntimeAccountDirectory { self } + #[must_use] + pub fn with_group_fast_modes(mut self, policies: BTreeMap) -> Self { + self.group_fast_modes = policies; + self + } + pub(crate) fn accounts_in_group( &self, group: &AccountGroupId, @@ -288,7 +296,7 @@ impl ClientRoutingScope { pub struct FrozenAccountScope { allow_image_generation: bool, allow_subagents: bool, - fast_mode: FastMode, + fast_mode_override: Option, request_profiles: BTreeMap, directory: Arc, client_scope: ClientRoutingScope, @@ -355,16 +363,34 @@ impl FrozenAccountScope { self } - /// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关 + /// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算 #[must_use] - pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self { - self.fast_mode = fast_mode; + pub const fn with_fast_mode_override(mut self, fast_mode: Option) -> Self { + self.fast_mode_override = fast_mode; self } #[must_use] - pub const fn fast_mode(&self) -> FastMode { - self.fast_mode + pub const fn fast_mode_override(&self) -> Option { + self.fast_mode_override + } + + /// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录 + #[must_use] + pub fn fast_mode_for_account( + &self, + account_id: &ProviderAccountId, + upstream_model: &str, + ) -> FastMode { + if let Some(mode) = self.fast_mode_override { + return mode; + } + let Some(account) = self.directory.account(account_id) else { + return FastMode::Default; + }; + self.matching_groups(account, |access| access.allows(upstream_model)) + .filter_map(|id| self.directory.group_fast_modes.get(id)) + .fold(FastMode::Default, |mode, other| mode.merge(*other)) } #[must_use] @@ -376,7 +402,7 @@ impl FrozenAccountScope { Self { allow_image_generation: true, allow_subagents: true, - fast_mode: FastMode::Default, + fast_mode_override: None, request_profiles: BTreeMap::new(), directory, client_scope, @@ -460,18 +486,31 @@ impl FrozenAccountScope { } match &self.client_scope { ClientRoutingScope::AllAccounts => true, + ClientRoutingScope::Restricted { .. } => { + self.matching_groups(account, accepts).next().is_some() + } + } + } + + fn matching_groups<'a>( + &'a self, + account: &'a RuntimeAccount, + accepts: impl Fn(&AccountModelAccess) -> bool + 'a, + ) -> impl Iterator { + let enabled = match &self.client_scope { + ClientRoutingScope::AllAccounts => None, ClientRoutingScope::Restricted { enabled_group_ids, .. - } => account - .group_ids() - .intersection(enabled_group_ids) - .any(|id| { - self.directory - .group_model_access - .get(id) - .is_none_or(&accepts) - }), - } + } => Some(enabled_group_ids), + }; + account.group_ids().iter().filter(move |id| { + enabled.is_some_and(|groups| groups.contains(*id)) + && self + .directory + .group_model_access + .get(*id) + .is_none_or(&accepts) + }) } #[must_use] diff --git a/backend/crates/gateway-core/src/engine/coordinator.rs b/backend/crates/gateway-core/src/engine/coordinator.rs index fd01d2f84..8132bd882 100644 --- a/backend/crates/gateway-core/src/engine/coordinator.rs +++ b/backend/crates/gateway-core/src/engine/coordinator.rs @@ -1200,7 +1200,6 @@ where .with_lease_metadata(Arc::clone(&self.lease_metadata)) .with_response_control(self.response_control.clone()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) - .with_fast_mode(self.plan.fast_mode()) .with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider())) .with_pricing(self.plan.pricing()) .with_request_location(self.plan.request_location().cloned()) diff --git a/backend/crates/gateway-core/src/engine/mod.rs b/backend/crates/gateway-core/src/engine/mod.rs index 901661023..3676968cb 100644 --- a/backend/crates/gateway-core/src/engine/mod.rs +++ b/backend/crates/gateway-core/src/engine/mod.rs @@ -330,7 +330,6 @@ pub struct RequestAttemptContext { prompt_rewrite_rules: Option>, pricing: Arc, request_profile: Option, - fast_mode: FastMode, openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings, openai_request_settings: crate::settings::OpenAiRequestSettings, request_location: Option, @@ -424,12 +423,6 @@ impl RequestAttemptContext { self } - #[must_use] - pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self { - self.fast_mode = fast_mode; - self - } - #[must_use] pub fn with_privacy( mut self, @@ -478,7 +471,6 @@ impl RequestAttemptContext { request_profile: None, prompt_rewrite_rules: None, pricing: Arc::default(), - fast_mode: FastMode::Default, openai_websocket_pool: Default::default(), openai_request_settings: Default::default(), request_location: None, @@ -743,8 +735,14 @@ impl AttemptContext { } #[must_use] - pub const fn fast_mode(&self) -> FastMode { - self.request.fast_mode + pub fn fast_mode_for_account( + &self, + account: &ProviderAccountId, + upstream_model: &str, + ) -> FastMode { + self.account_scope().map_or(FastMode::Default, |scope| { + scope.fast_mode_for_account(account, upstream_model) + }) } #[must_use] diff --git a/backend/crates/gateway-core/src/policy/mod.rs b/backend/crates/gateway-core/src/policy/mod.rs index a1cd8e795..bd8abf490 100644 --- a/backend/crates/gateway-core/src/policy/mod.rs +++ b/backend/crates/gateway-core/src/policy/mod.rs @@ -158,7 +158,7 @@ impl RateLimits { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientSettings { pub request_profiles: BTreeMap, - pub fast_mode: FastMode, + pub fast_mode_override: Option, pub limits: RateLimits, } @@ -185,18 +185,18 @@ impl ClientPolicy { pub(crate) fn with_settings( mut self, profiles: &BTreeMap, - fast_mode: FastMode, + fast_mode_override: Option, limits: RateLimits, ) -> Self { if self.account_scope.request_profiles() != profiles - || self.account_scope.fast_mode() != fast_mode + || self.account_scope.fast_mode_override() != fast_mode_override { self.account_scope = Arc::new( self.account_scope .as_ref() .clone() .with_request_profiles(profiles.clone()) - .with_fast_mode(fast_mode), + .with_fast_mode_override(fast_mode_override), ); } self.limits = limits; @@ -217,7 +217,7 @@ impl ClientPolicy { name_snapshot: None, defaults: Arc::new(ClientSettings { request_profiles: account_scope.request_profiles().clone(), - fast_mode: account_scope.fast_mode(), + fast_mode_override: account_scope.fast_mode_override(), limits, }), key_id, diff --git a/backend/crates/gateway-core/src/routing/mod.rs b/backend/crates/gateway-core/src/routing/mod.rs index 71908bdd8..2dce0c63b 100644 --- a/backend/crates/gateway-core/src/routing/mod.rs +++ b/backend/crates/gateway-core/src/routing/mod.rs @@ -23,7 +23,7 @@ use std::fmt; use std::num::{NonZeroU32, NonZeroU64}; use std::sync::Arc; -use crate::account::{AccountSelectionPolicy, FastMode}; +use crate::account::AccountSelectionPolicy; use crate::operation::{CapabilityRequirements, Feature, OperationKind}; use crate::validation::{IdentifierError, RoutingError, validate_text}; @@ -767,11 +767,6 @@ impl RoutingPlan { Arc::clone(&self.pricing) } - #[must_use] - pub fn fast_mode(&self) -> FastMode { - self.account_scope.fast_mode() - } - /// 本次请求冻结的已编译规则,重试不读取新的全局策略 #[must_use] pub fn privacy(&self) -> Option> { diff --git a/backend/crates/gateway-core/src/routing/request_settings.rs b/backend/crates/gateway-core/src/routing/request_settings.rs index 306b177f8..640f1e81d 100644 --- a/backend/crates/gateway-core/src/routing/request_settings.rs +++ b/backend/crates/gateway-core/src/routing/request_settings.rs @@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues}; #[serde(deny_unknown_fields)] pub struct ExecutionSettings { pub runtime: SettingsValues, - pub fast_mode: FastMode, + /// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端 + pub fast_mode: Option, pub client_limits: RateLimits, /// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点 pub timeout_ms: Option, @@ -38,7 +39,7 @@ struct ExecutionOverrides { defaults: Arc, client_key_id: String, input: Arc, - fast_mode: Option>, + fast_mode: Option>>, client_limits: Option>, timeout_ms: Option>>, } @@ -186,9 +187,10 @@ impl RequestSettings { #[must_use] pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy { let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None); + let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults()); policy.with_settings( values.runtime.request_profiles(), - values.fast_mode, + fast_mode, values.client_limits, ) } @@ -247,9 +249,7 @@ impl RequestSettings { } ExecutionSettings { runtime, - fast_mode: overrides - .and_then(|scope| scope.fast_mode.as_ref()) - .map_or(defaults.fast_mode, |change| change.value), + fast_mode: self.fast_mode_override(key, defaults), client_limits: overrides .and_then(|scope| scope.client_limits.as_ref()) .map_or(defaults.limits, |change| change.value), @@ -259,6 +259,15 @@ impl RequestSettings { } } + fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option { + self.execution + .as_ref() + .filter(|scope| scope.client_key_id == key) + .and_then(|scope| scope.fast_mode.as_ref()) + .map(|change| change.value) + .unwrap_or(defaults.fast_mode_override) + } + pub(crate) fn execution_deadline( &self, key: &ClientApiKeyId, diff --git a/backend/crates/gateway-core/src/routing/snapshot.rs b/backend/crates/gateway-core/src/routing/snapshot.rs index 844380e0a..dccb4b6e5 100644 --- a/backend/crates/gateway-core/src/routing/snapshot.rs +++ b/backend/crates/gateway-core/src/routing/snapshot.rs @@ -583,12 +583,19 @@ async fn compile_runtime_snapshot( .map(|group| (group.id.clone(), std::mem::take(&mut group.model_access))) .collect(); let account_directory = Arc::new( - RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access), + RuntimeAccountDirectory::new(accounts) + .with_group_model_access(group_model_access) + .with_group_fast_modes( + groups + .values() + .filter(|group| group.enabled && group.fast_mode != FastMode::Default) + .map(|group| (group.id.clone(), group.fast_mode)) + .collect(), + ), ); let mut client_policies = Vec::with_capacity(facts.client_policies.len()); for policy in facts.client_policies { - let mut fast_mode = FastMode::Default; let mut allow_image_generation = true; let mut allow_subagents = true; let account_scope = if policy.group_ids.is_empty() { @@ -607,8 +614,7 @@ async fn compile_runtime_snapshot( let group = groups .get(&group_id) .ok_or(RuntimeSnapshotCompileError::InvalidData)?; - // 停用只影响选号,仍绑定的分组继续贡献请求策略 - fast_mode = fast_mode.merge(group.fast_mode); + // 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制 allow_image_generation &= group.allow_image_generation; allow_subagents &= group.allow_subagents; bound_groups.push(RoutingGroupSnapshot::new( @@ -635,7 +641,6 @@ async fn compile_runtime_snapshot( account_scope .with_image_generation(allow_image_generation) .with_subagents(allow_subagents) - .with_fast_mode(fast_mode) .with_request_profiles(policy.request_profiles), ), true, diff --git a/backend/crates/gateway-core/tests/engine/coordinator.rs b/backend/crates/gateway-core/tests/engine/coordinator.rs index 90e604845..3a24e3252 100644 --- a/backend/crates/gateway-core/tests/engine/coordinator.rs +++ b/backend/crates/gateway-core/tests/engine/coordinator.rs @@ -1138,26 +1138,12 @@ fn plan_with_location( operation: &Operation, account_selection_policy: AccountSelectionPolicy, request_location: gateway_core::account::RequestLocation, -) -> RoutingPlan { - plan_with_location_and_fast_policy( - operation, - account_selection_policy, - request_location, - FastMode::Default, - ) -} - -fn plan_with_location_and_fast_policy( - operation: &Operation, - account_selection_policy: AccountSelectionPolicy, - request_location: gateway_core::account::RequestLocation, - fast_mode: FastMode, ) -> RoutingPlan { plan_with_profiles( operation, account_selection_policy, request_location, - fast_mode, + FastMode::Default, Default::default(), ) } @@ -1255,7 +1241,7 @@ fn plan_with_protection( operation, Arc::new( FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts()) - .with_fast_mode(fast_mode) + .with_fast_mode_override(Some(fast_mode)) .with_request_profiles(profiles), ), &RoutingContext { @@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() { #[test] fn global_location_and_group_fast_policy_reach_every_account_retry() { + use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot}; + for mode in [ FastMode::Default, FastMode::Enabled, @@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() { timezone: "Asia/Tokyo".parse().unwrap(), ..Default::default() }; - let route_plan = plan_with_location_and_fast_policy( - &operation, - plan(&operation).account_selection_policy(), - location.clone(), - mode, + let kind = ProviderKind::new("openai").unwrap(); + let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap(); + let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap(); + let second_mode = if mode == FastMode::Disabled { + FastMode::Default + } else { + FastMode::Disabled + }; + let directory = Arc::new( + RuntimeAccountDirectory::new( + [ + ("acct_first", first_group.clone()), + ("acct_second", second_group.clone()), + ] + .into_iter() + .map(|(account, group)| { + ( + ProviderAccountId::new(account).unwrap(), + RuntimeAccount::new(kind.clone(), BTreeSet::from([group])), + ) + }) + .collect(), + ) + .with_group_fast_modes(BTreeMap::from([ + (first_group.clone(), mode), + (second_group.clone(), second_mode), + ])), ); + let scope = Arc::new(FrozenAccountScope::new( + Arc::clone(&directory), + ClientRoutingScope::restricted( + vec![ + RoutingGroupSnapshot::new(first_group.clone(), "A".into()), + RoutingGroupSnapshot::new(second_group.clone(), "B".into()), + ], + BTreeSet::from([first_group, second_group]), + BTreeSet::from([kind.clone()]), + ) + .unwrap(), + )); + let route_plan = RuntimeSnapshot::new( + ConfigRevision::new(1).unwrap(), + gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None) + .with_request_location(location.clone(), true), + vec![kind.clone()], + vec![ProviderModel::new( + kind, + UpstreamModelId::new("gpt-5").unwrap(), + ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)), + )], + Vec::new(), + ) + .unwrap() + .with_account_directory(directory) + .plan( + &PublicModelId::new("gpt-5").unwrap(), + &operation, + Arc::clone(&scope), + &RoutingContext::default(), + ) + .unwrap(); let (coordinator, _, provider) = coordinator(vec![ Script::Stream { account_id: "acct_first", @@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() { block_on(session.commit_downstream(Some(200))).unwrap(); let contexts = provider.contexts.lock().unwrap(); assert_eq!(contexts.len(), 2); - assert!( - contexts - .iter() - .all(|context| context.request_location() == Some(&location) - && context.fast_mode() == mode) - ); + for (context, account, expected) in [ + (&contexts[0], "acct_first", mode), + (&contexts[1], "acct_second", second_mode), + ] { + assert_eq!(context.request_location(), Some(&location)); + assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope)); + assert_eq!( + context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"), + expected, + ); + } } } diff --git a/backend/crates/gateway-core/tests/engine/execution/mod.rs b/backend/crates/gateway-core/tests/engine/execution/mod.rs index 6919d99a5..d2dc2918e 100644 --- a/backend/crates/gateway-core/tests/engine/execution/mod.rs +++ b/backend/crates/gateway-core/tests/engine/execution/mod.rs @@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider { request: ProviderRequest, context: AttemptContext, ) -> Result { - self.policies.lock().unwrap().push(context.fast_mode()); let candidate = request.candidate(); + self.policies + .lock() + .unwrap() + .push(context.fast_mode_for_account( + &ProviderAccountId::new("acct_start").unwrap(), + candidate.upstream_model().unwrap().as_str(), + )); let metadata = ProviderCallMetadata::new( candidate.provider().clone(), candidate.upstream_model().unwrap().clone(), @@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy( account_scope(&provider, "acct_start") .as_ref() .clone() - .with_fast_mode(fast_mode) + .with_fast_mode_override(Some(fast_mode)) .with_image_generation(allow_image_generation), ), enabled, @@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() { .execution_values() .unwrap() .fast_mode, - FastMode::Disabled + Some(FastMode::Disabled) ); assert_eq!( prepared @@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() { account_scope(&provider, "acct_start") .as_ref() .clone() - .with_fast_mode(FastMode::Disabled) + .with_fast_mode_override(Some(FastMode::Disabled)) .with_request_profiles(profiles(name)), ), true, @@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() { let configuration = RequestSettings::new(snapshots.acquire().unwrap()) .with_execution(parent.client().policy(), previous.timeout_ms); let mut values = previous.clone(); - values.fast_mode = FastMode::Default; + values.fast_mode = Some(FastMode::Default); values.client_limits = RateLimits::unlimited(); values.timeout_ms = Some(90_000); let mut runtime = serde_json::to_value(&values.runtime).unwrap(); @@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() { Some(actual.clone()) ); assert_eq!(actual.client_limits.max_concurrency, expected_limit); - assert_eq!(actual.fast_mode, expected_fast); + assert_eq!(actual.fast_mode, Some(expected_fast)); assert_eq!(actual.timeout_ms, expected_timeout); let facts = serde_json::to_value(actual.runtime).unwrap(); assert_eq!(facts["request_profiles"]["openai"]["identity"], profile); diff --git a/backend/crates/gateway-core/tests/routing/request_settings.rs b/backend/crates/gateway-core/tests/routing/request_settings.rs index 98a7df85d..ce01d4e18 100644 --- a/backend/crates/gateway-core/tests/routing/request_settings.rs +++ b/backend/crates/gateway-core/tests/routing/request_settings.rs @@ -53,7 +53,7 @@ fn policy_with_profiles( Arc::new( FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts()) .with_request_profiles(overrides) - .with_fast_mode(FastMode::Disabled), + .with_fast_mode_override(Some(FastMode::Disabled)), ), true, RateLimits { @@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() { values.runtime = values .runtime .with_model_mappings(BTreeMap::from([("alias".into(), "model".into())])); - values.fast_mode = FastMode::Default; + values.fast_mode = Some(FastMode::Default); values.client_limits = RateLimits::unlimited(); values.timeout_ms = Some(90_000); let changed = original.replace_execution(&values, "plugin").unwrap(); @@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() { parent_values.runtime.request_profiles(), &profiles(&[("openai", "parent"), ("xai", "second")]) ); - assert_eq!(parent_values.fast_mode, FastMode::Default); + assert_eq!(parent_values.fast_mode, Some(FastMode::Default)); let child_settings = rebased.with_execution(&child, Some(60_000)); let child_values = child_settings.execution_values().unwrap(); assert_eq!( child_values.runtime.request_profiles(), &profiles(&[("openai", "child"), ("xai", "second")]) ); - assert_eq!(child_values.fast_mode, FastMode::Disabled); + assert_eq!(child_values.fast_mode, Some(FastMode::Disabled)); assert_eq!(child_values.client_limits, child.limits()); assert_eq!(child_values.timeout_ms, Some(60_000)); assert_eq!(child_settings.snapshot().mapped_model("alias"), "model"); @@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() { ); } +#[test] +fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() { + use gateway_core::{ + account::ProviderAccountId, + routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory}, + }; + let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap(); + let account = ProviderAccountId::new("acct_group_fast").unwrap(); + let provider = ProviderKind::new("openai").unwrap(); + let scope = Arc::new(FrozenAccountScope::new( + Arc::new( + RuntimeAccountDirectory::new(BTreeMap::from([( + account.clone(), + RuntimeAccount::new(provider.clone(), [group.clone()].into()), + )])) + .with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()), + ), + ClientRoutingScope::restricted( + vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())], + [group].into(), + [provider].into(), + ) + .unwrap(), + )); + let key = |name: &str| { + ClientPolicy::new( + ClientApiKeyId::new(name).unwrap(), + PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(), + scope.clone(), + true, + RateLimits::unlimited(), + ) + }; + let parent = key("parent"); + let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None); + assert_eq!(settings.execution_values().unwrap().fast_mode, None); + let resolved = |settings: &RequestSettings, key| { + settings + .apply_policy(key) + .account_scope() + .fast_mode_for_account(&account, "model") + }; + assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled); + let unchanged = settings + .replace_execution(&settings.execution_values().unwrap(), "pass-through") + .unwrap(); + assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled); + + let mut values = settings.execution_values().unwrap(); + values.fast_mode = Some(FastMode::Default); + let direct_default = settings + .replace_execution(&values, "follow-client") + .unwrap(); + assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default); + values.fast_mode = Some(FastMode::Enabled); + let enabled = settings.replace_execution(&values, "force-fast").unwrap(); + assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled); + values.fast_mode = Some(FastMode::Default); + let default = enabled.replace_execution(&values, "follow-client").unwrap(); + assert_eq!(resolved(&default, parent.clone()), FastMode::Default); + values.fast_mode = None; + let cleared = default.replace_execution(&values, "group-policy").unwrap(); + assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled); + assert_eq!( + cleared.inspect()["execution"]["fast_mode"]["value"], + serde_json::Value::Null + ); + let child = key("child"); + assert_eq!( + resolved(&default.with_execution(&child, None), child), + FastMode::Disabled + ); + assert_eq!(resolved(&settings, parent), FastMode::Disabled); +} + #[test] fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() { let host = snapshot(1, "first"); diff --git a/backend/crates/gateway-core/tests/routing/snapshot.rs b/backend/crates/gateway-core/tests/routing/snapshot.rs index 4bf42b06d..edefe500b 100644 --- a/backend/crates/gateway-core/tests/routing/snapshot.rs +++ b/backend/crates/gateway-core/tests/routing/snapshot.rs @@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication() } #[test] -fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { +fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() { use gateway_core::account::ProviderAccountId; use gateway_core::routing::AccountGroupId; for (mode, other_mode, expected) in [ @@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { let open_group_id = AccountGroupId::new("grp_00000000000000000000000000000002").unwrap(); let account_id = ProviderAccountId::new("acct_fast_policy").unwrap(); + let first_account = ProviderAccountId::new("acct_first_group").unwrap(); + let second_account = ProviderAccountId::new("acct_second_group").unwrap(); let facts = SnapshotFacts::new( revision(1), revision(1), @@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { ) .with_fast_mode(other_mode), ], - vec![SnapshotProviderAccountFacts::new( - account_id.clone(), - "alpha", - )], + [&account_id, &first_account, &second_account] + .into_iter() + .map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha")) + .collect(), vec![ + SnapshotAccountGroupMemberFacts::new( + group_id.clone(), + first_account.clone(), + ), + SnapshotAccountGroupMemberFacts::new( + open_group_id.clone(), + second_account.clone(), + ), SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()), ], @@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { &Default::default(), ) .unwrap(); + for (account, effective) in [ + ( + &account_id, + if group_enabled { expected } else { other_mode }, + ), + ( + &first_account, + if group_enabled { + mode + } else { + FastMode::Default + }, + ), + (&second_account, other_mode), + ] { + assert_eq!( + plan.account_scope() + .fast_mode_for_account(account, "public-model"), + if bound { effective } else { FastMode::Default }, + "account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}" + ); + } assert_eq!( - plan.fast_mode(), - if bound { expected } else { FastMode::Default }, - "mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}" + plan.account_scope().allows(&first_account), + !bound || group_enabled ); } } } } +#[test] +fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() { + use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId}; + use gateway_core::routing::AccountGroupId; + + let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap(); + let account = ProviderAccountId::new("acct_model_fast").unwrap(); + let facts = SnapshotFacts::new( + revision(1), + revision(1), + SettingsValues::new(3, "smart", BTreeMap::new(), None, None), + vec![SnapshotClientPolicyFacts::new( + ClientApiKeyId::new("key_model_fast").unwrap(), + PlaintextClientApiKey::new("fixture-model-fast").unwrap(), + vec![group(1), group(2)], + RateLimits::unlimited(), + )], + vec![ + SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true) + .with_fast_mode(FastMode::Enabled) + .with_model_access( + AccountModelAccess::new( + AccountModelAccessMode::Allowlist, + vec!["fast-model".into()], + ) + .unwrap(), + ), + SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true) + .with_fast_mode(FastMode::Disabled) + .with_model_access( + AccountModelAccess::new( + AccountModelAccessMode::Denylist, + vec!["fast-model".into()], + ) + .unwrap(), + ), + SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true) + .with_fast_mode(FastMode::Disabled), + ], + vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")], + (1..=3) + .map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone())) + .collect(), + ); + let snapshot = block_on( + RuntimeSnapshotCompiler::new( + Arc::new(TestSnapshotStore::new(Ok(facts))), + Arc::new(TestCatalog::Unavailable), + ) + .compile(), + ) + .unwrap(); + let scope = snapshot.client_policies().next().unwrap().account_scope(); + for (model, expected) in [ + ("fast-model", FastMode::Enabled), + ("standard-model", FastMode::Disabled), + ] { + assert!(scope.allows_model(&account, model)); + assert_eq!(scope.fast_mode_for_account(&account, model), expected); + } +} + #[test] fn group_feature_permissions_merge_independently_with_deny_precedence() { use gateway_core::account::ProviderAccountId; diff --git a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/execution.rs b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/execution.rs index 70bd7de60..ee8621b66 100644 --- a/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/execution.rs +++ b/backend/crates/gateway-plugin/runtime/src/adapter/upstream_adapter/execution.rs @@ -248,21 +248,21 @@ impl Execution { request_body_limit, ) .map_err(|error| fault_error(error, UpstreamSendState::NotSent))?; + let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?; let request = UpstreamAdapterRequest { adapter_id: declaration.id.clone(), provider: declaration.provider, - upstream_model: invocation - .metadata - .upstream_model() - .ok_or_else(invalid)? - .as_str() - .to_owned(), + upstream_model: upstream_model.as_str().to_owned(), client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(), account_id: invocation.account.account_id().as_str().to_owned(), credential_revision: invocation.account.credential_revision().get(), protocol: invocation.operation.protocol().to_owned(), client_transport: invocation.context.client_transport().as_str().to_owned(), - fast_mode: invocation.context.fast_mode().as_str().to_owned(), + fast_mode: invocation + .context + .fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str()) + .as_str() + .to_owned(), request_elapsed_ms: u64::try_from( invocation.context.timing_started_at().elapsed().as_millis(), ) diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs b/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs index 9ffe0abb2..329e3a1ae 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/compatibility.rs @@ -7,13 +7,16 @@ use serde_json::{Value, json}; #[tokio::test] async fn middleware_preserves_fast_modes_and_sources() { for (mode, expected) in [ - (FastMode::Default, FastMode::Default), - (FastMode::Enabled, FastMode::Enabled), - (FastMode::Disabled, FastMode::Disabled), - (FastMode::Enabled, FastMode::Disabled), - (FastMode::Ultrafast, FastMode::Ultrafast), - (FastMode::Enabled, FastMode::Ultrafast), - (FastMode::Disabled, FastMode::Default), + (None, None), + (None, Some(FastMode::Default)), + (Some(FastMode::Default), Some(FastMode::Default)), + (Some(FastMode::Enabled), Some(FastMode::Enabled)), + (Some(FastMode::Disabled), Some(FastMode::Disabled)), + (Some(FastMode::Enabled), Some(FastMode::Disabled)), + (Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)), + (Some(FastMode::Enabled), Some(FastMode::Ultrafast)), + (Some(FastMode::Disabled), Some(FastMode::Default)), + (Some(FastMode::Enabled), None), ] { let snapshot = gateway_core::routing::RuntimeSnapshot::new( ConfigRevision::new(1).unwrap(), @@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() { let settings = settings.replace_execution(&seed, "seed").unwrap(); let wire = serde_json::to_value(&seed).unwrap(); let mut updated = wire.clone(); - updated["fast_mode"] = json!(expected.as_str()); - updated["timeout_ms"] = json!(90_000); + updated["fast_mode"] = json!(expected); let contribution = crate::support::contribution( Capability::Middleware, vec![Stage::Request], @@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() { id: "fast-settings", configuration: json!({ "mode":"settings", "expected_settings":wire, "settings":updated, - "expected_fast_source": if mode == FastMode::Default { Value::Null } else { - json!({"instance_id":"seed", "order":1, "value":mode.as_str()}) + "expected_fast_source": if mode.is_none() { Value::Null } else { + json!({"instance_id":"seed", "order":1, "value":mode}) }, }), bindings: vec![binding( @@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() { assert_eq!(settings.execution_values().unwrap().fast_mode, expected); assert_eq!( settings.execution_values().unwrap().timeout_ms, - Some(90_000) + Some(60_000) ); let sources = settings.inspect(); let fast_source = &sources["execution"]["fast_mode"]; - if mode == FastMode::Default && expected == FastMode::Default { + if mode.is_none() && expected.is_none() { assert!(fast_source.is_null()); } else { assert_eq!( @@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() { "fast-settings" } ); - assert_eq!(fast_source["value"], expected.as_str()); + assert_eq!(fast_source["value"], json!(expected)); } - assert_eq!( - sources["execution"]["timeout_ms"]["instance_id"], - "fast-settings" - ); + assert!(sources["execution"]["timeout_ms"].is_null()); next.run(request).await }) }), 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 ea7c6017a..7052970ac 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/policy/mod.rs @@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() { let baseline = ExecutionSettings { runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None) .with_request_profiles(profiles("key-default")), - fast_mode: FastMode::Disabled, + fast_mode: Some(FastMode::Disabled), client_limits: RateLimits { max_concurrency: 2, requests_per_minute: 10, @@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() { gateway_core::routing::ClientRoutingScope::all_accounts(), ) .with_request_profiles(profiles("key-default")) - .with_fast_mode(baseline.fast_mode), + .with_fast_mode_override(baseline.fast_mode), ), true, baseline.client_limits, diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs b/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs index 933962684..67d48b60f 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/upstream_adapter.rs @@ -179,7 +179,6 @@ fn context_with_body_limit( ClientApiKeyId::new(key).unwrap(), ) .with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation)) - .with_fast_mode(mode) .with_request_body_limit(bytes), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(5), @@ -187,7 +186,13 @@ fn context_with_body_limit( gateway_core::account::RotationStrategy::RoundRobin, std::num::NonZeroU32::new(1).unwrap(), ), - AccountAttemptContext::new(Default::default(), None, None), + AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new( + gateway_core::routing::FrozenAccountScope::new( + Arc::default(), + gateway_core::routing::ClientRoutingScope::all_accounts(), + ) + .with_fast_mode_override(Some(mode)), + )), None, CancellationToken::new(), ) diff --git a/backend/crates/gateway-plugin/runtime/tests/support/middleware/mod.rs b/backend/crates/gateway-plugin/runtime/tests/support/middleware/mod.rs index 98c75a649..613def79b 100644 --- a/backend/crates/gateway-plugin/runtime/tests/support/middleware/mod.rs +++ b/backend/crates/gateway-plugin/runtime/tests/support/middleware/mod.rs @@ -588,7 +588,7 @@ async fn main() -> Result<(), Box> { ); if let Some(expected) = configuration.get("expected_fast_source") { let sources = &call.request.head.settings_sources["execution"]; - assert_eq!(sources["input"]["fast_mode"], "default"); + assert!(sources["input"]["fast_mode"].is_null()); assert_eq!(&sources["fast_mode"], expected); } if let Some(settings) = configuration.get("settings") { diff --git a/backend/crates/gateway-plugin/sdk/docs/capabilities.md b/backend/crates/gateway-plugin/sdk/docs/capabilities.md index fd19e498e..7bc985e9f 100644 --- a/backend/crates/gateway-plugin/sdk/docs/capabilities.md +++ b/backend/crates/gateway-plugin/sdk/docs/capabilities.md @@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)? #### 模型请求与 attempt -`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略; +`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用; attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 @@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。 -`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。 +`fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。 +保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位 `runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。 SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。 线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。 diff --git a/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md b/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md index abefb80a8..70688c532 100644 --- a/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md +++ b/backend/crates/gateway-plugin/sdk/docs/upstream-adapters.md @@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili `TypedCall` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影; 原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件 -`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线, +`fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线, 适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。 其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt) diff --git a/backend/crates/providers/openai/src/provider/mod.rs b/backend/crates/providers/openai/src/provider/mod.rs index 235e04b1b..eb430d225 100644 --- a/backend/crates/providers/openai/src/provider/mod.rs +++ b/backend/crates/providers/openai/src/provider/mod.rs @@ -863,7 +863,7 @@ impl Provider for CodexProvider { && codex_guardian_role(payload.body(), payload.context()) == Some(CodexGuardianRole::Housekeeper)) && let Some(tier) = fast_policy_tier( - context.fast_mode(), + context.fast_mode_for_account(lease.account_id(), upstream_model.as_str()), payload.body().get("service_tier").and_then(Value::as_str), |tier| { self.catalog diff --git a/backend/crates/providers/openai/tests/provider/contract/mod.rs b/backend/crates/providers/openai/tests/provider/contract/mod.rs index 4acb82e12..94c1edd19 100644 --- a/backend/crates/providers/openai/tests/provider/contract/mod.rs +++ b/backend/crates/providers/openai/tests/provider/contract/mod.rs @@ -1660,7 +1660,6 @@ pub(super) fn context_with_middleware( ModelRequestId::new(request_id).expect("request id"), ClientApiKeyId::new("key_openai_contract").expect("client key id"), ) - .with_fast_mode(fast_mode) .with_middleware( Some(plan), Arc::from([]), @@ -1671,8 +1670,12 @@ pub(super) fn context_with_middleware( NonZeroU32::MIN, SystemTime::now() + Duration::from_secs(30), account_policy(), - AccountAttemptContext::new(BTreeSet::new(), None, None) - .with_account_scope(contract_account_scope()), + AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new( + contract_account_scope() + .as_ref() + .clone() + .with_fast_mode_override(Some(fast_mode)), + )), None, CancellationToken::new(), ) @@ -1696,14 +1699,23 @@ fn context_with_pricing( fast_mode: FastMode, pricing: gateway_core::metering::PricingOverrides, ) -> AttemptContext { - context_for_request( + AttemptContext::new( RequestAttemptContext::new( ModelRequestId::new(request_id).expect("request id"), ClientApiKeyId::new("key_openai_contract").expect("client key id"), ) - .with_fast_mode(fast_mode) .with_pricing(Arc::new(pricing)) .with_request_location(Some(global_request_location())), + NonZeroU32::MIN, + SystemTime::now() + Duration::from_secs(30), + account_policy(), + AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new( + contract_account_scope() + .as_ref() + .clone() + .with_fast_mode_override(Some(fast_mode)), + )), + None, cancellation, ) } @@ -8714,6 +8726,77 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra let original = operation.clone(); let provider = provider_with_catalog_and_base_url(&store, base_url).await; let catalog = provider.query_model_capabilities().await.unwrap(); + let groups: Vec<_> = (1..=2) + .map(|id| { + gateway_core::routing::AccountGroupId::new(format!("grp_{id:032x}")).unwrap() + }) + .collect(); + let provider_kind = ProviderKind::new("openai").unwrap(); + // 同一个 Key 绑定两个互不相交的账号组,另一个组不能改写本次账号的档位 + let scope = Arc::new(FrozenAccountScope::new( + Arc::new( + RuntimeAccountDirectory::new( + ["acct_provider_contract", other] + .into_iter() + .zip(&groups) + .map(|(id, group)| { + ( + ProviderAccountId::new(id).unwrap(), + RuntimeAccount::new( + provider_kind.clone(), + [group.clone()].into(), + ), + ) + }) + .collect(), + ) + .with_group_fast_modes( + [ + (groups[0].clone(), fast_mode), + ( + groups[1].clone(), + if fast_mode == FastMode::Disabled { + FastMode::Enabled + } else { + FastMode::Disabled + }, + ), + ] + .into(), + ), + ), + ClientRoutingScope::restricted( + groups + .iter() + .map(|id| { + gateway_core::routing::RoutingGroupSnapshot::new( + id.clone(), + id.to_string(), + ) + }) + .collect(), + groups.into_iter().collect(), + [provider_kind].into(), + ) + .unwrap(), + )); + let context = AttemptContext::new( + RequestAttemptContext::new( + ModelRequestId::new("req_service_tier").unwrap(), + ClientApiKeyId::new("key_openai_contract").unwrap(), + ), + NonZeroU32::MIN, + SystemTime::now() + Duration::from_secs(30), + account_policy(), + AccountAttemptContext::new( + BTreeSet::new(), + Some(ProviderAccountId::new("acct_provider_contract").unwrap()), + None, + ) + .with_account_scope(scope), + None, + CancellationToken::new(), + ); let mut stream = provider .execute( planned_request_with_presentation( @@ -8722,11 +8805,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra "gpt-5.4", catalog[0].presentation().cloned(), ), - context_with_fast_policy( - "req_service_tier", - CancellationToken::new(), - fast_mode, - ), + context, ) .await .expect("provider stream"); @@ -13327,8 +13406,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_ RequestAttemptContext::new( ModelRequestId::new(format!("req_fast_turn_{index}")).unwrap(), key, - ) - .with_fast_mode(fast_mode), + ), NonZeroU32::new(1).unwrap(), SystemTime::now() + Duration::from_secs(30), account_policy(), @@ -13337,7 +13415,12 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_ None, Some(ProviderAccountStateOwner::new(provider_kind, account)), ) - .with_account_scope(contract_account_scope()), + .with_account_scope(Arc::new( + contract_account_scope() + .as_ref() + .clone() + .with_fast_mode_override(Some(fast_mode)), + )), binding, CancellationToken::new(), ) 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 2420b8289..1a7b10fde 100644 --- a/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs +++ b/backend/crates/providers/openai/tests/provider/contract/upstream_adapter.rs @@ -235,7 +235,13 @@ impl gateway_core::engine::upstream_adapter::UpstreamAdapter for AdapterProbe { Some("chatgpt-acct_provider_contract".as_bytes().to_vec()) ); assert!(header("cookie").is_none()); - assert_eq!(invocation.context.fast_mode(), FastMode::Disabled); + assert_eq!( + invocation.context.fast_mode_for_account( + invocation.account.account_id(), + invocation.metadata.upstream_model().unwrap().as_str(), + ), + FastMode::Disabled, + ); let Operation::Generate(generate) = &invocation.operation else { panic!("adapter must receive the original operation kind"); }; @@ -304,7 +310,6 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an ModelRequestId::new("req_adapter_native").unwrap(), ClientApiKeyId::new("key_openai_contract").unwrap(), ) - .with_fast_mode(FastMode::Disabled) .with_upstream_adapters(Some( gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new( Arc::new(AdapterProbe { @@ -322,8 +327,12 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an NonZeroU32::MIN, SystemTime::now() + Duration::from_secs(5), account_policy(), - AccountAttemptContext::new(BTreeSet::new(), None, None) - .with_account_scope(contract_account_scope()), + AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new( + contract_account_scope() + .as_ref() + .clone() + .with_fast_mode_override(Some(FastMode::Disabled)), + )), None, CancellationToken::new(), ); diff --git a/docs/api.md b/docs/api.md index ad5da18f4..cbb867033 100644 --- a/docs/api.md +++ b/docs/api.md @@ -2177,7 +2177,8 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen `allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。 Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。 -`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端 +`fastMode` 默认跟随客户端。每次选定账号后,只合并当前 Key 绑定、已启用、包含该账号且允许本次上游模型的分组策略。 +其他账号的分组、停用分组和不允许该模型的分组不参与。同一账号命中多个有效分组时,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端 | 值 | OpenAI Responses 顶层 `service_tier` | | --- | --- | @@ -2189,7 +2190,7 @@ Key 绑定多个组时,按模型分别合并启用组中的合格账号。例 目标档位缺少目录支持时保留原请求。 OAuth 和 Responses API Key 共用上述档位规则,出站兼容层不额外删除原生 Responses 的 `auto/default`。 宿主策略在 request 中间件之后应用,形成 attempt 输入基线;attempt 中间件继续改写档位时,以改写后的实际发送值为准。 -HTTP 和每个 WebSocket `response.create` 均使用请求开始时的分组策略,同一请求重试保持该策略; +HTTP 和每个 WebSocket `response.create` 均冻结请求开始时的分组配置,重试按实际选中的账号和上游模型计算策略。 HTTP 请求头及新建 WS 的握手提示按当时的最终出站档位构造;复用 WS 时不重发握手头, 每个 `response.create` 仍独立应用档位策略,请求档位统计与本地费用估算使用各帧的最终出站档位 diff --git a/docs/architecture.md b/docs/architecture.md index 056eeca51..22e9ad243 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -231,7 +231,7 @@ flowchart LR Runtime 将插件改写交回同一设置编译器;API 在认证、版本检查与正文解压前传递有效配置,不按业务接口增加设置包装。HTTP 超时由路由终端消费,`None` 清除本次超时。 OpenAI 的 Fast 设置在 attempt 中间件前形成正文基线;OpenAI / xAI 的插件头修改覆盖账号与画像生成的同名头,不按字段名拦截。 HTTP 正文的寿命覆盖惰性读取,WebSocket 升级后由独立连接取消信号和冻结发布代次接管,101 响应正文结束不会取消会话 -- **模型设置按请求重算**:Key 自身的画像、Fast 和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。 +- **模型设置按请求重算**:Key 自身的画像和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。Fast 分组默认值在选定账号后计算,请求设置只保留显式覆盖。 认证、插件使用的 `ExecutionSettings` 视图和执行终端共用该规则。设置改写经过编译后由终端复用结果,截止时间仍相对请求开始时刻计算,不发布全局配置。 子调用保留显式改写,在目标 Key 作用域重算默认值;Key 限额、Fast 和模型超时的覆盖绑定原 Key,同级调用互不改写。 原生 Responses WebSocket 每轮从当前快照重新认证,保留握手的显式改写;已经开始的执行不随全局发布改变。具体字段与来源合同见 [SDK 中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#http-入口) @@ -555,9 +555,10 @@ Store 将策略与设置 revision 原子持久化;编译结果随快照、计 每条规则跨承载副本原子提交;发送前拒绝携带 `NotSent` 和禁止重试标记。被规则改写的握手头参与 WS 池身份,防止复用旧值, 关闭策略不进入改写管线。字段与执行限制见[隐私策略 API](api.md#隐私策略) -Fast 策略由 Core 合并 Client Key 的全部绑定分组并随同一快照链路冻结,禁用分组也参与合并; -不按所选账号的分组重新解释。档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。 -OpenAI Provider 在独立编码请求上、生成上游头与观测前统一应用顶层档位覆盖,HTTP、WS 与重试共用。 +Fast 分组配置由 Core 随账号目录冻结,选号后通过同一账号范围解析器合并当前 Key 授权该账号与模型的启用分组策略。 +请求设置中的显式 Fast 覆盖优先于分组策略;未覆盖时,换号按新账号重算,仍使用请求开始时的快照,不读取新的全局配置。 +档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。 +OpenAI Provider 在选定账号后、attempt 中间件前应用顶层档位覆盖,HTTP、WS 与重试共用;上游适配器取得同一账号与模型的有效策略。 该策略不改变选号、会话亲和或共享原始请求;每个新 WS 请求重新取得当前策略。 WS 路由提示属于握手,连接复用时不重发;档位变化不重建连接或打断 `previous_response_id` 续写, 各帧正文及计费仍使用本次请求的最终档位 diff --git a/frontend/src/i18n/locales/en/groups.json b/frontend/src/i18n/locales/en/groups.json index efc3d9488..3e78f2113 100644 --- a/frontend/src/i18n/locales/en/groups.json +++ b/frontend/src/i18n/locales/en/groups.json @@ -43,7 +43,7 @@ "forceUltrafast": "Force Ultrafast", "subagents": "Collaborative subagents", "memberModels": "Member account models", - "fastModeHelp": "Default follows the client. Disable downgrades both accelerated tiers to standard. A forced tier overrides the client selection when the model supports it.", + "fastModeHelp": "Default follows the client, Disable uses the standard tier, and Fast or Ultrafast overrides the client when supported. Only enabled groups bound to this key that contain the selected account and allow the model contribute. When several groups qualify, precedence is Disable > Fast > Ultrafast > Default", "subagentsHelp": "Enable lets the client decide when to start a collaborative subagent. Disable rejects requests identified as coming from a collaborative subagent.", "noProviderSettings": "No group-specific settings for this platform" }, diff --git a/frontend/src/i18n/locales/zh-Hans/groups.json b/frontend/src/i18n/locales/zh-Hans/groups.json index cbc014358..01175267c 100644 --- a/frontend/src/i18n/locales/zh-Hans/groups.json +++ b/frontend/src/i18n/locales/zh-Hans/groups.json @@ -43,7 +43,7 @@ "forceUltrafast": "超快速", "subagents": "协作子代理", "memberModels": "成员账号模型", - "fastModeHelp": "默认跟随客户端。禁用会将加速请求降为标准档。选择快速或超快速时,若模型支持该档位,分组设置会覆盖客户端选择", + "fastModeHelp": "默认跟随客户端,禁用将加速请求降为标准档,快速和超快速在模型支持时覆盖客户端选择。仅合并选中账号所属、Key 已绑定且允许本次模型的启用分组。同一账号命中多个有效分组时,优先级为禁用 > 快速 > 超快速 > 默认", "subagentsHelp": "启用后由客户端决定是否启动协作子代理。禁用会拒绝可识别的协作子代理请求", "noProviderSettings": "该平台暂无分组专属设置" }, diff --git a/frontend/src/i18n/locales/zh-Hant/groups.json b/frontend/src/i18n/locales/zh-Hant/groups.json index 353337dae..0aefd5617 100644 --- a/frontend/src/i18n/locales/zh-Hant/groups.json +++ b/frontend/src/i18n/locales/zh-Hant/groups.json @@ -43,7 +43,7 @@ "forceUltrafast": "超快速", "subagents": "協作子代理", "memberModels": "成員帳號模型", - "fastModeHelp": "預設跟隨用戶端。禁用會將加速請求降為標準檔。選擇快速或超快速時,若模型支援該檔位,分組設定會覆寫用戶端選擇", + "fastModeHelp": "預設跟隨用戶端,禁用將加速請求降為標準檔,快速和超快速在模型支援時覆寫用戶端選擇。僅合併所選帳號所屬、Key 已綁定且允許本次模型的已啟用分組。同一帳號命中多個有效分組時,優先順序為禁用 > 快速 > 超快速 > 預設", "subagentsHelp": "啟用後由用戶端決定是否啟動協作子代理。禁用會拒絕可識別的協作子代理請求", "noProviderSettings": "此平台暫無分組專屬設定" },