Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(ucs): add config_source dispatcher for DB vs Superposition UCS path (#13294)
Amitsingh Tanwar5786b738c088
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex d9985f40a3..a7575ce9b9 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2727,7 +2727,13 @@ pt_mapping_outgoing_connector_webhooks = { value = { default_mapping = { frequen], type = "string" }, description = "Controls whether payment processing continues when an applicable pre-FRM check fails", change_reason = "Initial setup" }+ucs_enabled = { value = "enabled", schema = { type = "string", enum = ["disabled", "enabled", "shadow_disabled"] }, description = "UCS mode: disabled (off), enabled (on with shadow allowed), shadow_disabled (on but shadow traffic stopped)", change_reason = "Initial setup" }+ucs_rollout_config = { value = { rollout_percent = 0.0, execution_mode = "shadow", kill_switch_enabled = false, kill_switch_threshold = 1 }, schema = { type = "object" }, description = "UCS rollout configuration controlling traffic routing percentage to Unified Connector Service", change_reason = "Initial setup" }++ucs_shadow_kill_switch_threshold = { value = 1, schema = { type = "integer", minimum = 1, maximum = 9223372036854775807 }, description = "Global shadow request-failure count at which UCS shadow proxying stops; shadow_disabled also stops shadow traffic independently", change_reason = "UCS shadow kill switch threshold" }+[dimensions]+flow_name = { position = 21, schema = { type = "string" }, type = "REGULAR", description = "Payment flow name (e.g. Authorize, PSync, Execute, RSync, Webhooks)", change_reason = "Initial setup" }always_collect_billing_details_from_wallet_connector = { position = 7, schema = { type = "boolean" }, type = "REGULAR" }always_collect_shipping_details_from_wallet_connector = { position = 8, schema = { type = "boolean" }, type = "REGULAR" }connector = { position = 1, schema = { enum = [diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 6f5f228313..43308b6328 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -3185,6 +3185,7 @@ impl ExecutionPath {pub enum UcsAvailability {Enabled,Disabled,+ ShadowDisabled,}#[derive(diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex e321d2a592..91e0a60804 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -102,6 +102,27 @@ pub struct UnifiedConnectorServiceClientConfig {/// Set of connectors for which psync is disabled in unified connector service#[serde(default, deserialize_with = "deserialize_hashset")]pub ucs_psync_disabled_connectors: HashSet<Connector>,++ /// Controls where UCS configuration (ucs_enabled, rollout config) is read from.+ /// Set to "database" to use the configs table, or "superposition" to use+ /// the Superposition service. Allows runtime switching without redeployment.+ #[serde(default = "default_config_source")]+ pub config_source: UcsConfigSource,+}++/// Controls where UCS configuration (ucs_enabled, rollout config) is read from.+#[derive(Debug, Clone, Copy, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum UcsConfigSource {+ /// Read UCS config from the `configs` database table (legacy behavior).+ #[default]+ Database,+ /// Read UCS config from Superposition service.+ Superposition,+}++fn default_config_source() -> UcsConfigSource {+ UcsConfigSource::Database}/// Connection timeout for the Unified Connector Service in seconds.diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 2bd53014fc..5529acf804 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -602,6 +602,12 @@ pub mod superposition {"webhooks.unverified_webhook_merchant_connector_account_rate_limit";/// save wallet decrypted data in lockerpub const SAVE_WALLET_DECRYPTED_DATA: &str = "vaulting.save_wallet_decrypted_data";+ /// UCS rollout configuration key (contains RolloutConfig with percentage, URLs, etc.)+ pub const UCS_ROLLOUT_CONFIG: &str = "ucs_rollout_config";+ /// Global request-failure threshold for the UCS shadow kill switch.+ pub const UCS_SHADOW_KILL_SWITCH_THRESHOLD: &str = "ucs_shadow_kill_switch_threshold";+ /// UCS enabled configuration key (controls UCS mode: disabled, enabled, shadow_disabled)+ pub const UCS_ENABLED: &str = "ucs_enabled";/// checkout sdk configurationpub const CHECKOUT_SDK: &str = "checkout_sdk";/// Pre-FRM failure handling modediff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex c8fa7564d2..110d9dfe69 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -17,7 +17,7 @@ use api_models::{},};use base64::Engine;-use common_enums::{enums::ExecutionMode, ConnectorType, WalletDecryptedToken};+use common_enums::{enums::ExecutionMode, ConnectorType, UcsAvailability, WalletDecryptedToken};use common_types::payments::InstallmentOption;#[cfg(feature = "v2")]use common_utils::id_type::GenerateId;@@ -2631,6 +2631,44 @@ pub async fn is_config_flag_enabled(state: &SessionState, config_key: &str) -> b.unwrap_or(false)}+/// Reads UCS enabled mode purely from Superposition service (no DB fallback).+pub async fn get_ucs_enabled_mode_from_superposition(state: &SessionState) -> UcsAvailability {+ match state+ .superposition_service+ .get_config_value::<String>(consts::superposition::UCS_ENABLED, None, None)+ .await+ {+ Ok(value) => value.parse::<UcsAvailability>().unwrap_or_else(|err| {+ logger::warn!(+ error = ?err,+ ucs_enabled_value = %value,+ "Failed to parse ucs_enabled value from superposition. Defaulting to Disabled."+ );+ UcsAvailability::Disabled+ }),+ Err(err) => {+ logger::error!(+ error = ?err,+ "Failed to fetch UCS enabled from superposition. Defaulting to Disabled."+ );+ UcsAvailability::Disabled+ }+ }+}++/// Reads the UCS config source setting from the application config.+pub fn get_ucs_config_source(+ state: &SessionState,+) -> external_services::grpc_client::unified_connector_service::UcsConfigSource {+ state+ .conf+ .grpc_client+ .unified_connector_service+ .as_ref()+ .map(|c| c.config_source)+ .unwrap_or_default()+}+#[derive(Debug, Clone, Deserialize)]pub struct RolloutConfig {pub rollout_percent: f64,@@ -2992,6 +3030,45 @@ pub async fn should_execute_based_on_rollout_with_precedence(Ok(RolloutExecutionResult::default())}+/// Reads rollout config purely from Superposition — dimensions handle precedence via context.+/// No DB fallback.+pub async fn should_execute_based_on_rollout_with_precedence_from_superposition(+ state: &SessionState,+ superposition_key: &str,+ context: Option<external_services::superposition::ConfigContext>,+) -> RouterResult<RolloutExecutionResult> {+ match state+ .superposition_service+ .get_config_value::<serde_json::Value>(superposition_key, context.as_ref(), None)+ .await+ {+ Ok(json_value) => {+ let mut execution_result = json_value+ .parse_value::<RolloutConfig>("RolloutConfig")+ .map(RolloutExecutionResult::from)+ .map_err(|err| {+ logger::error!(+ error = ?err,+ "Failed to parse superposition rollout config. Defaulting to not execute."+ );+ RolloutExecutionResult::default()+ })+ .unwrap_or_default();+ if execution_result.should_execute {+ execution_result.proxy_override = build_rollout_proxy_override(state);+ }+ Ok(execution_result)+ }+ Err(err) => {+ logger::error!(+ error = ?err,+ "Failed to fetch rollout config from superposition. Defaulting to not execute."+ );+ Ok(RolloutExecutionResult::default())+ }+ }+}+pub fn determine_standard_vault_action(is_network_tokenization_enabled: bool,mandate_id: Option<mandates::MandateIds>,diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 3e12065ad0..0c329bbd30 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1,4 +1,4 @@-use std::{borrow::Cow, str::FromStr, time::Instant};+use std::{borrow::Cow, collections::HashSet, str::FromStr, time::Instant};use actix_web::ResponseError;use api_models::admin;@@ -17,9 +17,14 @@ use common_utils::{};use diesel_models::types::FeatureMetadata;use error_stack::ResultExt;-use external_services::grpc_client::{- unified_connector_service::{ConnectorAuthMetadata, UnifiedConnectorServiceError},- LineageIds,+use external_services::{+ grpc_client::{+ unified_connector_service::{+ ConnectorAuthMetadata, UcsConfigSource, UnifiedConnectorServiceError,+ },+ LineageIds,+ },+ superposition,};use hyperswitch_connectors::utils::CardData;#[cfg(feature = "v2")]@@ -51,8 +56,10 @@ use crate::{errors::{self, RouterResult},payments::{helpers::{+ get_ucs_config_source, get_ucs_enabled_mode_from_superposition,is_config_flag_enabled, is_googlepay_predecrypted_flow_supported,should_execute_based_on_rollout, should_execute_based_on_rollout_with_precedence,+ should_execute_based_on_rollout_with_precedence_from_superposition,MerchantConnectorAccountType, ProxyOverride, RolloutExecutionResult,WebhookRolloutConfig, WebhookRolloutExecutionResult,},@@ -882,19 +889,26 @@ type UnifiedConnectorServiceCreateOrderResult = CustomResult<UnifiedConnectorServiceError,>;-/// Checks if the Unified Connector Service (UCS) is available for use+/// Checks if the Unified Connector Service (UCS) is available for use.+/// Reads from DB only (original behavior).pub(crate) async fn check_ucs_availability(state: &SessionState) -> UcsAvailability {+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();let is_client_available = state.grpc_client.unified_connector_service_client.is_some();let is_enabled = is_config_flag_enabled(state, consts::UCS_ENABLED).await;match (is_client_available, is_enabled) {(true, true) => {- router_env::logger::debug!("UCS is available and enabled");+ router_env::logger::debug!(request_id = %request_id, "UCS is available and enabled");UcsAvailability::Enabled}_ => {router_env::logger::debug!(+ request_id = %request_id,"UCS client is {} and UCS is {} in configuration",if is_client_available {"available"@@ -908,17 +922,60 @@ pub(crate) async fn check_ucs_availability(state: &SessionState) -> UcsAvailabil}}+/// Checks UCS availability reading purely from Superposition (no DB fallback).+/// Supports three-value UcsAvailability: Enabled, Disabled, ShadowDisabled.+async fn check_ucs_availability_from_superposition(state: &SessionState) -> UcsAvailability {+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();+ let is_client_available = state.grpc_client.unified_connector_service_client.is_some();++ let ucs_mode = get_ucs_enabled_mode_from_superposition(state).await;++ match (is_client_available, &ucs_mode) {+ (true, UcsAvailability::Enabled) => {+ router_env::logger::debug!(request_id = %request_id, "UCS is available and enabled");+ UcsAvailability::Enabled+ }+ (true, UcsAvailability::ShadowDisabled) => {+ router_env::logger::debug!(request_id = %request_id, "UCS is available but shadow is disabled");+ UcsAvailability::ShadowDisabled+ }+ _ => {+ router_env::logger::debug!(+ request_id = %request_id,+ "UCS client is {} and UCS mode is {:?} in configuration",+ if is_client_available {+ "available"+ } else {+ "not available"+ },+ ucs_mode+ );+ UcsAvailability::Disabled+ }+ }+}+/// Determines the connector integration type based on UCS configuration or on bothpub async fn determine_connector_integration_type(state: &SessionState,connector: Connector,) -> RouterResult<ConnectorIntegrationType> {+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();match state.conf.grpc_client.unified_connector_service.as_ref() {Some(ucs_config) => {- let is_ucs_only = ucs_config.ucs_only_connectors.contains(&connector);+ let is_ucs_only = is_ucs_only_connector(&ucs_config.ucs_only_connectors, connector);if is_ucs_only {router_env::logger::debug!(+ request_id = %request_id,connector = ?connector,ucs_only_list = is_ucs_only,"Using UcsConnector"@@ -926,6 +983,7 @@ pub async fn determine_connector_integration_type(Ok(ConnectorIntegrationType::UcsConnector)} else {router_env::logger::debug!(+ request_id = %request_id,connector = ?connector,"Using DirectandUCSConnector - not in ucs_only_list");@@ -934,6 +992,7 @@ pub async fn determine_connector_integration_type(}None => {router_env::logger::debug!(+ request_id = %request_id,connector = ?connector,"UCS config not present, using DirectandUCSConnector");@@ -942,6 +1001,35 @@ pub async fn determine_connector_integration_type(}}+const INLINE_UCS_ONLY_CONNECTORS: &[Connector] = &[+ Connector::Imerchantsolutions,+ Connector::Paytm,+ Connector::Phonepe,+ Connector::Hyperpg,+ Connector::Revolv3,+ Connector::Fiservcommercehub,+ Connector::AbsaSanlam,+ Connector::Interpayments,+ Connector::Payconex,+ Connector::Dlocal,+ Connector::Barclaycard,+ Connector::TsysTransit,+ Connector::Jpmorgan,+ Connector::Datatrans,+ Connector::Givepayments,+ Connector::Tesouro,+ Connector::Citigate,+ Connector::Ilixium,+ Connector::Moneris,+ Connector::Elavon,+ Connector::Worldpayraft,+];++fn is_ucs_only_connector(configured_connectors: &HashSet<Connector>, connector: Connector) -> bool {+ INLINE_UCS_ONLY_CONNECTORS.contains(&connector) || configured_connectors.contains(&connector)+}++/// Routes UCS execution using the configured UCS config source.pub async fn should_call_unified_connector_service<F: Clone, T, R>(state: &SessionState,processor: &Processor,@@ -951,17 +1039,64 @@ pub async fn should_call_unified_connector_service<F: Clone, T, R>(shadow_ucs_call_connector_action: Option<CallConnectorAction>,transaction_type: common_enums::TransactionType,) -> RouterResult<(ExecutionPath, SessionState, RolloutExecutionResult)>+where+ R: Send + Sync + Clone,+{+ let config_source = get_ucs_config_source(state);++ match config_source {+ UcsConfigSource::Superposition => {+ Box::pin(should_call_ucs_via_superposition(+ state,+ processor,+ router_data,+ previous_gateway,+ call_connector_action,+ shadow_ucs_call_connector_action,+ transaction_type,+ ))+ .await+ }+ UcsConfigSource::Database => {+ Box::pin(should_call_ucs_via_db(+ state,+ processor,+ router_data,+ previous_gateway,+ call_connector_action,+ shadow_ucs_call_connector_action,+ transaction_type,+ ))+ .await+ }+ }+}++/// Legacy DB-based implementation: reads UCS config from the configs database table.+/// No superposition involved.+async fn should_call_ucs_via_db<F: Clone, T, R>(+ state: &SessionState,+ processor: &Processor,+ router_data: &RouterData<F, T, R>,+ previous_gateway: Option<GatewaySystem>,+ call_connector_action: CallConnectorAction,+ shadow_ucs_call_connector_action: Option<CallConnectorAction>,+ transaction_type: common_enums::TransactionType,+) -> RouterResult<(ExecutionPath, SessionState, RolloutExecutionResult)>whereR: Send + Sync + Clone,{// Extract context informationlet merchant_id = processor.get_account().get_id().get_string_repr();let org_id = processor.get_account().get_org_id().get_string_repr();+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();let connector_name = &router_data.connector;- let connector_enum = Connector::from_str(connector_name)- .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)- .attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))?;+ let connector_enum = parse_connector_name(connector_name)?;let flow_name = get_flow_name::<F>()?;@@ -970,33 +1105,189 @@ where// Build rollout keys in ascending precedence order.// Payments use org-level hierarchy; payouts use a single merchant-level key for now.- let rollout_keys = match transaction_type {+ let (rollout_keys, _) = build_rollout_context_for_transaction(+ transaction_type,+ org_id,+ merchant_id,+ connector_name,+ &flow_name,+ router_data,+ );++ // Determine connector integration type+ let connector_integration_type =+ determine_connector_integration_type(state, connector_enum).await?;++ // Try keys highest → lowest precedence, use first match found+ let mut rollout_result =+ should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;++ let (gateway_system, execution_path, session_state) = resolve_ucs_execution_decision(+ state,+ merchant_id,+ connector_name,+ &flow_name,+ previous_gateway,+ call_connector_action,+ shadow_ucs_call_connector_action,+ ucs_availability,+ &mut rollout_result,+ connector_integration_type,+ router_data.payment_method,+ router_data.payment_method_type,+ &router_data.payment_id,+ )+ .await?;++ router_env::logger::info!(+ request_id = %request_id,+ "Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}",+ gateway_system,+ execution_path,+ merchant_id,+ connector_name,+ flow_name+ );++ Ok((execution_path, session_state, rollout_result))+}++/// Superposition-based implementation: reads all UCS config purely from Superposition+/// with dimensional context. No DB fallback.+async fn should_call_ucs_via_superposition<F: Clone, T, R>(+ state: &SessionState,+ processor: &Processor,+ router_data: &RouterData<F, T, R>,+ previous_gateway: Option<GatewaySystem>,+ call_connector_action: CallConnectorAction,+ shadow_ucs_call_connector_action: Option<CallConnectorAction>,+ transaction_type: common_enums::TransactionType,+) -> RouterResult<(ExecutionPath, SessionState, RolloutExecutionResult)>+where+ R: Send + Sync + Clone,+{+ let merchant_id = processor.get_account().get_id().get_string_repr();+ let org_id = processor.get_account().get_org_id().get_string_repr();+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();++ let connector_name = &router_data.connector;+ let connector_enum = parse_connector_name(connector_name)?;++ let flow_name = get_flow_name::<F>()?;++ let ucs_availability = check_ucs_availability_from_superposition(state).await;++ let (rollout_keys, superposition_context) = build_rollout_context_for_transaction(+ transaction_type,+ org_id,+ merchant_id,+ connector_name,+ &flow_name,+ router_data,+ );++ let connector_integration_type =+ determine_connector_integration_type(state, connector_enum).await?;++ let mut rollout_result = should_execute_based_on_rollout_with_precedence_from_superposition(+ state,+ consts::superposition::UCS_ROLLOUT_CONFIG,+ Some(superposition_context),+ )+ .await?;++ let (gateway_system, execution_path, session_state) = resolve_ucs_execution_decision(+ state,+ merchant_id,+ connector_name,+ &flow_name,+ previous_gateway,+ call_connector_action,+ shadow_ucs_call_connector_action,+ ucs_availability,+ &mut rollout_result,+ connector_integration_type,+ router_data.payment_method,+ router_data.payment_method_type,+ &router_data.payment_id,+ )+ .await?;++ router_env::logger::info!(+ request_id = %request_id,+ "Payment gateway decision (Superposition): gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}, rollout_keys={:?}",+ gateway_system,+ execution_path,+ merchant_id,+ connector_name,+ flow_name,+ rollout_keys+ );++ Ok((execution_path, session_state, rollout_result))+}++/// Parses a connector name string into the Connector enum.+fn parse_connector_name(connector_name: &str) -> RouterResult<Connector> {+ Connector::from_str(connector_name)+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)+ .attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))+}++/// Builds rollout keys and superposition context based on the transaction type.+fn build_rollout_context_for_transaction<F: Clone, T, R>(+ transaction_type: common_enums::TransactionType,+ org_id: &str,+ merchant_id: &str,+ connector_name: &str,+ flow_name: &str,+ router_data: &RouterData<F, T, R>,+) -> (Vec<String>, superposition::ConfigContext) {+ match transaction_type {common_enums::TransactionType::Payment- | common_enums::TransactionType::ThreeDsAuthentication => build_rollout_keys_by_precedence(+ | common_enums::TransactionType::ThreeDsAuthentication => build_rollout_keys_and_context(org_id,merchant_id,connector_name,- &flow_name,+ flow_name,router_data.payment_method,router_data.payment_method_type,),- common_enums::TransactionType::Payout => build_rollout_keys_for_payouts(+ common_enums::TransactionType::Payout => build_rollout_keys_and_context_for_payouts(merchant_id,connector_name,- &flow_name,+ flow_name,router_data.payment_method_type,),- };-- // Determine connector integration type- let connector_integration_type =- determine_connector_integration_type(state, connector_enum).await?;-- // Try keys highest → lowest precedence, use first match found- let mut rollout_result =- should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;+ }+}- // Single decision point using pattern matching+/// Resolves the shared execution path + session state for UCS routing.+#[allow(clippy::too_many_arguments)]+async fn resolve_ucs_execution_decision(+ state: &SessionState,+ merchant_id: &str,+ connector_name: &str,+ flow_name: &str,+ previous_gateway: Option<GatewaySystem>,+ call_connector_action: CallConnectorAction,+ shadow_ucs_call_connector_action: Option<CallConnectorAction>,+ ucs_availability: UcsAvailability,+ rollout_result: &mut RolloutExecutionResult,+ connector_integration_type: ConnectorIntegrationType,+ payment_method: common_enums::PaymentMethod,+ payment_method_type: Option<PaymentMethodType>,+ payment_id: &str,+) -> RouterResult<(GatewaySystem, ExecutionPath, SessionState)> {+ let request_id = state+ .request_id+ .as_ref()+ .map(|r| r.to_string())+ .unwrap_or_default();let (mut gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled{match call_connector_action {@@ -1009,7 +1300,7 @@ where| CallConnectorAction::HandleResponse { .. }| CallConnectorAction::HandleResponseWithoutBuildRequest| CallConnectorAction::StatusUpdate { .. } => {- router_env::logger::debug!("UCS is disabled, using Direct gateway");+ router_env::logger::debug!(request_id = %request_id, "UCS is disabled, using Direct gateway");(GatewaySystem::Direct, ExecutionPath::Direct)}}@@ -1017,6 +1308,7 @@ wherematch call_connector_action {CallConnectorAction::UCSConsumeResponse(_) => {router_env::logger::info!(+ request_id = %request_id,"CallConnectorAction UCSConsumeResponse received, using UCS gateway");(@@ -1026,6 +1318,7 @@ where}CallConnectorAction::HandleResponse { .. } => {router_env::logger::info!(+ request_id = %request_id,"CallConnectorAction HandleResponse received, using Direct gateway");if shadow_ucs_call_connector_action.is_some() {@@ -1041,34 +1334,26 @@ where| CallConnectorAction::HandleResponseWithoutBuildRequest| CallConnectorAction::Avoid| CallConnectorAction::StatusUpdate { .. } => {- // If a rollout config key exists use its execution mode,- // otherwise default to Shadow so all traffic mirrors through UCS.let execution_mode = if rollout_result.should_execute {rollout_result.execution_mode} else {ExecutionMode::Shadow};+ let execution_mode = resolve_execution_mode(execution_mode, ucs_availability);decide_execution_path(connector_integration_type, previous_gateway, execution_mode)?}}};- // Kill switch: a scope whose failure counter exceeds the configured threshold serves from- // the direct integration regardless of what its rollout config says.- //- // Only the primary path is diverted, and it is diverted to shadow rather than to direct — the- // merchant is served by the direct integration either way, but shadow keeps mirroring, so a- // tripped scope still produces the comparison signal needed to confirm a fix before it is- // reset. Shadow itself falls back to direct below when no proxy override is configured.if matches!(execution_path, ExecutionPath::UnifiedConnectorService)&& is_kill_switch_applicable(connector_integration_type, &call_connector_action){let rollout_scope = build_merchant_rollout_scope(merchant_id,connector_name,- &flow_name,- router_data.payment_method,- router_data.payment_method_type,+ flow_name,+ payment_method,+ payment_method_type,);// This is the scope the decision is made under. Every connector call the decision@@ -1090,8 +1375,8 @@ wheremerchant_id = %merchant_id,connector = %connector_name,flow = %flow_name,- payment_method = ?router_data.payment_method,- payment_method_type = ?router_data.payment_method_type,+ payment_method = ?payment_method,+ payment_method_type = ?payment_method_type,kill_switch_enabled = rollout_result.kill_switch_enabled,threshold = rollout_result.kill_switch_threshold,connector_decline_threshold = ?rollout_result.connector_decline_threshold,@@ -1103,17 +1388,17 @@ where}}- // Apply the global shadow kill switch before any proxy override.+ // Apply both manual and automatic shadow stops before any proxy override.if matches!(execution_path, ExecutionPath::ShadowUnifiedConnectorService)- && kill_switch::shadow::is_kill_switched(state).await+ && kill_switch::shadow::should_stop(state, ucs_availability).await{gateway_system = GatewaySystem::Direct;execution_path = ExecutionPath::Direct;router_env::logger::warn!(- payment_id = %router_data.payment_id,+ payment_id = %payment_id,merchant_id = %merchant_id,key = consts::UCS_SHADOW_KILL_SWITCH_REDIS_KEY,- "Shadow kill switch active; routing to Direct without proxy override"+ "Shadow stopped by availability or kill switch; routing to Direct without proxy override");}@@ -1124,6 +1409,7 @@ wherematch &rollout_result.proxy_override {Some(proxy_override) => {router_env::logger::debug!(+ request_id = %request_id,proxy_override = ?proxy_override,"Creating updated session state with proxy configuration for Shadow UCS");@@ -1132,6 +1418,7 @@ whereNone => {// info, not debug: this downgrade has to be visible at default log levels.router_env::logger::info!(+ request_id = %request_id,"No proxy override available for Shadow UCS; falling back to Direct, so no shadow comparison will run for this request");execution_path = ExecutionPath::Direct;@@ -1139,22 +1426,10 @@ where}}}- ExecutionPath::Direct | ExecutionPath::UnifiedConnectorService => {- // For Direct and UCS flows, use original state- state.clone()- }+ ExecutionPath::Direct | ExecutionPath::UnifiedConnectorService => state.clone(),};- router_env::logger::info!(- "Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}",- gateway_system,- execution_path,- merchant_id,- connector_name,- flow_name- );-- Ok((execution_path, session_state, rollout_result))+ Ok((gateway_system, execution_path, session_state))}/// Creates a new SessionState with proxy configuration updated from the override@@ -1180,6 +1455,23 @@ fn create_updated_session_state_with_proxy(updated_state}+/// Resolves the effective execution mode by applying the shadow disabled switch.+/// If the resolved mode is Shadow and ucs_enabled is "shadow_disabled",+/// falls back to NotApplicable (Direct path).+fn resolve_execution_mode(+ execution_mode: ExecutionMode,+ ucs_availability: UcsAvailability,+) -> ExecutionMode {+ if execution_mode == ExecutionMode::Shadow+ && ucs_availability == UcsAvailability::ShadowDisabled+ {+ router_env::logger::info!("UCS shadow is disabled, falling back to Direct");+ ExecutionMode::NotApplicable+ } else {+ execution_mode+ }+}+/// Whether the kill switch may divert this call away from UCS.////// Two cases have nothing to fall back to, so diverting them would not protect the merchant — it@@ -1221,10 +1513,16 @@ pub async fn is_ucs_execution_path_for_external_vault_proxy(.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven).attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))?;- match check_ucs_availability(state).await {+ let config_source = get_ucs_config_source(state);+ let ucs_availability = match config_source {+ UcsConfigSource::Database => check_ucs_availability(state).await,+ UcsConfigSource::Superposition => check_ucs_availability_from_superposition(state).await,+ };++ match ucs_availability {UcsAvailability::Disabled => Ok(false),- UcsAvailability::Enabled => {- let rollout_keys = build_rollout_keys_by_precedence(+ UcsAvailability::Enabled | UcsAvailability::ShadowDisabled => {+ let (rollout_keys, superposition_context) = build_rollout_keys_and_context(processor.get_account().get_org_id().get_string_repr(),processor.get_account().get_id().get_string_repr(),connector_name,@@ -1234,8 +1532,19 @@ pub async fn is_ucs_execution_path_for_external_vault_proxy(payment_method_type,);- let rollout_result =- should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?;+ let rollout_result = match config_source {+ UcsConfigSource::Database => {+ should_execute_based_on_rollout_with_precedence(state, &rollout_keys).await?+ }+ UcsConfigSource::Superposition => {+ should_execute_based_on_rollout_with_precedence_from_superposition(+ state,+ consts::superposition::UCS_ROLLOUT_CONFIG,+ Some(superposition_context),+ )+ .await?+ }+ };let connector_integration_type =determine_connector_integration_type(state, connector_enum).await?;@@ -1245,7 +1554,7 @@ pub async fn is_ucs_execution_path_for_external_vault_proxy(let (gateway_system, _execution_path) = decide_execution_path(connector_integration_type,None,- rollout_result.execution_mode,+ resolve_execution_mode(rollout_result.execution_mode, ucs_availability),)?;Ok(matches!(@@ -1374,52 +1683,120 @@ pub fn build_merchant_rollout_scope(}}-/// Rollout config keys, **lowest precedence first**. The caller reverses this and takes the-/// first key that exists, so the order is load-bearing.-fn build_rollout_keys_by_precedence(+/// The caller tries keys highest -> lowest and uses the first match found.+/// Builds rollout config keys in ascending precedence order (lowest -> highest):+/// 1. `ucs_rollout_config_<org_id>` -- org level+/// 2. `ucs_rollout_config_<org_id>_<merchant_id>` -- org + merchant+/// 3. `ucs_rollout_config_<org_id>_<merchant_id>_<connector>_...` -- org + merchant + connector+/// 4. `ucs_rollout_config_<merchant_id>_<connector>_...` -- merchant + connector (highest)+///+/// The caller iterates highest -> lowest and uses the first match found.+fn build_rollout_keys_and_context(org_id: &str,merchant_id: &str,connector_name: &str,flow_name: &str,payment_method: common_enums::PaymentMethod,payment_method_type: Option<PaymentMethodType>,-) -> Vec<String> {+) -> (Vec<String>, superposition::ConfigContext) {let prefix = consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX;- let scope = build_merchant_rollout_scope(- merchant_id,- connector_name,- flow_name,- payment_method,- payment_method_type,- );+ let is_refund_flow = matches!(flow_name, "Execute" | "RSync");++ // Build base context (common for all flows)+ let mut context = superposition::ConfigContext::new()+ .with("organization_id", org_id)+ .with("provider_merchant_id", merchant_id)+ .with("connector", connector_name)+ .with("flow_name", flow_name);- vec![+ let (merchant_connector_key, org_merchant_connector_key) = if is_refund_flow {+ // Refund flows: ucs_rollout_config_<merchant_id>_<connector>_<flow>+ (+ format!("{prefix}_{merchant_id}_{connector_name}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{flow_name}"),+ )+ } else {+ let payment_method_str = payment_method.to_string();+ match payment_method {+ common_enums::PaymentMethod::Wallet+ | common_enums::PaymentMethod::BankRedirect+ | common_enums::PaymentMethod::Voucher+ | common_enums::PaymentMethod::PayLater => {+ let payment_method_type_str = payment_method_type+ .map(|pmt| pmt.to_string())+ .unwrap_or_else(|| "unknown".to_string());++ // Add payment_method and payment_method_type to context+ context = context+ .with("payment_method", &payment_method_str)+ .with("payment_method_type", &payment_method_type_str);++ (+ format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{payment_method_type_str}_{flow_name}"),+ )+ }+ common_enums::PaymentMethod::Card+ | common_enums::PaymentMethod::CardRedirect+ | common_enums::PaymentMethod::Upi+ | common_enums::PaymentMethod::Crypto+ | common_enums::PaymentMethod::Reward+ | common_enums::PaymentMethod::BankDebit+ | common_enums::PaymentMethod::RealTimePayment+ | common_enums::PaymentMethod::BankTransfer+ | common_enums::PaymentMethod::GiftCard+ | common_enums::PaymentMethod::MobilePayment+ | common_enums::PaymentMethod::NetworkToken+ | common_enums::PaymentMethod::OpenBanking => {+ // Add payment_method to context+ context = context.with("payment_method", &payment_method_str);++ (+ format!("{prefix}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),+ format!("{prefix}_{org_id}_{merchant_id}_{connector_name}_{payment_method_str}_{flow_name}"),+ )+ }+ }+ };++ // Ascending precedence order (lowest first, highest last)+ let keys = vec![format!("{prefix}_{org_id}"),format!("{prefix}_{org_id}_{merchant_id}"),- format!("{prefix}_{org_id}_{scope}"),- format!("{prefix}_{scope}"),- ]+ org_merchant_connector_key,+ merchant_connector_key,+ ];++ (keys, context)}/// Build rollout key for payouts — single key, org-level precedence not applied to payouts yet.-fn build_rollout_keys_for_payouts(+fn build_rollout_keys_and_context_for_payouts(merchant_id: &str,connector_name: &str,flow_name: &str,payment_method_type: Option<PaymentMethodType>,-) -> Vec<String> {+) -> (Vec<String>, superposition::ConfigContext) {let pmt = payment_method_type.map(|t| t.to_string()).unwrap_or_else(|| "unknown".to_string());- vec![format!(+ let context = superposition::ConfigContext::new()+ .with("provider_merchant_id", merchant_id)+ .with("connector", connector_name)+ .with("flow_name", flow_name)+ .with("payment_method_type", &pmt);++ let keys = vec![format!("{}_{}_{}_{}_{}",consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,merchant_id,connector_name,pmt,flow_name- )]+ )];++ (keys, context)}/// Extracts the gateway system from the payment intent's feature metadata@@ -1527,12 +1904,12 @@ pub async fn should_call_unified_connector_service_for_webhooks(router_env::logger::debug!("UCS is disabled for webhooks, using Direct gateway");(GatewaySystem::Direct, ExecutionPath::Direct)} else {- // UCS is enabled, use decide function with no previous gateway for webhooks- decide_execution_path(- connector_integration_type,- previous_gateway,+ let execution_mode = resolve_execution_mode(rollout_result.rollout_execution_result.execution_mode,- )?+ ucs_availability,+ );++ decide_execution_path(connector_integration_type, previous_gateway, execution_mode)?};router_env::logger::info!(diff --git a/crates/router/src/core/unified_connector_service/kill_switch.rs b/crates/router/src/core/unified_connector_service/kill_switch.rsindex bae2ed91e1..35def29976 100644--- a/crates/router/src/core/unified_connector_service/kill_switch.rs+++ b/crates/router/src/core/unified_connector_service/kill_switch.rs@@ -586,7 +586,7 @@ pub async fn trip_status(.await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to read the shadow kill switch counter")?;- let threshold = shadow::threshold(&state);+ let threshold = shadow::threshold(&state).await;return Ok(crate::services::ApplicationResponse::Json(KillSwitchStatusResponse {rollout_scope: key_or_scope,@@ -873,7 +873,8 @@ mod tests {pub mod shadow {use std::{error::Error, io::ErrorKind};- use common_enums::ApiClientError;+ use common_enums::{ApiClientError, UcsAvailability};+ use external_services::grpc_client::unified_connector_service::UcsConfigSource;use hyperswitch_domain_models::router_data::ErrorResponse;use hyperswitch_interfaces::{api::gateway::GetRouterData, errors::ConnectorError};use router_env::logger;@@ -881,8 +882,10 @@ pub mod shadow {use super::{exceeds_threshold, read_hash_counter, write_hash_counter, COUNTER_FIELD};use crate::{consts::{+ superposition::UCS_SHADOW_KILL_SWITCH_THRESHOLD,UCS_SHADOW_KILL_SWITCH_REDIS_KEY as COUNTER_KEY, UCS_SHADOW_KILL_SWITCH_TTL_IN_SECONDS,},+ core::payments::helpers::get_ucs_config_source,routes::SessionState,};@@ -920,12 +923,45 @@ pub mod shadow {.await}- pub(super) fn threshold(state: &SessionState) -> u64 {- state+ /// Use a global Superposition value for the Superposition routing path. An invalid or+ /// unavailable value preserves the configured comparison-service threshold.+ pub(super) async fn threshold(state: &SessionState) -> u64 {+ let fallback = state.conf.comparison_service.as_ref()- .map_or(1, |config| config.shadow_kill_switch_threshold)+ .map_or(1, |config| config.shadow_kill_switch_threshold);+ if get_ucs_config_source(state) != UcsConfigSource::Superposition {+ return fallback;+ }++ let value = match state+ .superposition_service+ .get_config_value::<i64>(UCS_SHADOW_KILL_SWITCH_THRESHOLD, None, None)+ .await+ {+ Ok(value) => value,+ Err(error) => {+ logger::warn!(+ ?error,+ fallback,+ "Failed to read Superposition UCS shadow kill switch threshold; using comparison-service configuration"+ );+ return fallback;+ }+ };++ match u64::try_from(value) {+ Ok(threshold) if threshold > 0 => threshold,+ _ => {+ logger::warn!(+ value,+ fallback,+ "Invalid Superposition UCS shadow kill switch threshold; using comparison-service configuration"+ );+ fallback+ }+ }}fn request_failure_reason(error: &error_stack::Report<ConnectorError>) -> ShadowFailureReason {@@ -1033,7 +1069,7 @@ pub mod shadow {"SHADOW_KILL_SWITCH_COUNTER_INCREMENTED");- let configured_threshold = threshold(state);+ let configured_threshold = threshold(state).await;// The atomic Redis increment returns the threshold value to only one// request, so concurrent failures do not repeat the trip event.if let Some(count) = count.filter(|count| *count == configured_threshold) {@@ -1058,11 +1094,16 @@ pub mod shadow {}}- /// Read only for a resultant shadow path, before changing any proxy settings.- /// An unreadable Redis counter routes shadow to Direct.- pub async fn is_kill_switched(state: &SessionState) -> bool {+ /// Stop shadow when manually disabled or when the global failure counter trips.+ /// Called only for a resultant shadow path, before changing any proxy settings.+ /// An unreadable Redis counter also stops shadow.+ pub async fn should_stop(state: &SessionState, ucs_availability: UcsAvailability) -> bool {+ if ucs_availability == UcsAvailability::ShadowDisabled {+ return true;+ }+match read_counter(state).await {- Ok(count) => exceeds_threshold(count, threshold(state)),+ Ok(count) => exceeds_threshold(count, threshold(state).await),Err(error) => {logger::warn!(?error,