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): auto primary→shadow kill switch on prism/transformation failures (#13616)
Shubhodip pal99885bcda34d
diff --git a/crates/hyperswitch_interfaces/src/helpers.rs b/crates/hyperswitch_interfaces/src/helpers.rsindex f7a6550c9a..c42292d14c 100644--- a/crates/hyperswitch_interfaces/src/helpers.rs+++ b/crates/hyperswitch_interfaces/src/helpers.rs@@ -1,5 +1,5 @@use common_utils::{- consts::{X_CONNECTOR_NAME, X_SUB_FLOW_NAME},+ consts::{X_CONNECTOR_NAME, X_PAYMENT_METHOD, X_PAYMENT_METHOD_TYPE, X_SUB_FLOW_NAME},errors as common_utils_errors,ext_traits::Encode,request,@@ -62,6 +62,21 @@ pub async fn serialize_comparison_results_and_send<S, F, RouterDReq, RouterDRespreturn;};+ // Capture before the router data is consumed by `to_value`. Either side works+ // as the source of truth since both ran the same payment — pick whichever is+ // available so the headers still go out even if one side errored upstream.+ let (payment_method, payment_method_type) = {+ let from_result =+ |res: &Result<router_data::RouterData<F, RouterDReq, RouterDResp>, String>| {+ res.as_ref()+ .ok()+ .map(|rd| (rd.payment_method.to_string(), rd.payment_method_type))+ };+ from_result(&hyperswitch_result)+ .or_else(|| from_result(&unified_connector_service_result))+ .unwrap_or_else(|| (String::new(), None))+ };+let to_value = |res: Result<router_data::RouterData<F, RouterDReq, RouterDResp>, String>,side: &str| {match res {@@ -94,6 +109,12 @@ pub async fn serialize_comparison_results_and_send<S, F, RouterDReq, RouterDRespconnector_name,sub_flow_name,request_id,+ if payment_method.is_empty() {+ None+ } else {+ Some(payment_method)+ },+ payment_method_type.map(|pmt| pmt.to_string()),).await.inspect_err(|e| logger::warn!("Failed to send comparison data: {:?}", e));@@ -132,6 +153,8 @@ pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(connector_name,Some("webhook".to_string()),request_id,+ None, // payment_method not derivable from a generic webhook payload+ None, // payment_method_type same).await{@@ -140,6 +163,7 @@ pub async fn serialize_webhook_outcome_and_send_to_comparison_service<P, S>(}/// Sends router data comparison to external service+#[allow(clippy::too_many_arguments)]pub async fn send_comparison_data(state: &dyn api_client::ApiClientWrapper,comparison_data: ComparisonData,@@ -147,6 +171,8 @@ pub async fn send_comparison_data(connector_name: String,sub_flow_name: Option<String>,request_id: Option<String>,+ payment_method: Option<String>,+ payment_method_type: Option<String>,) -> common_utils_errors::CustomResult<(), errors::HttpClientError> {let mut request = request::RequestBuilder::new().method(request::Method::Post)@@ -168,6 +194,17 @@ pub async fn send_comparison_data();}+ if let Some(pm) = payment_method.filter(|pm| !pm.is_empty()) {+ request.add_header(X_PAYMENT_METHOD, hyperswitch_masking::Maskable::Normal(pm));+ }++ if let Some(pmt) = payment_method_type.filter(|pmt| !pmt.is_empty()) {+ request.add_header(+ X_PAYMENT_METHOD_TYPE,+ hyperswitch_masking::Maskable::Normal(pmt),+ );+ }+if let Some(req_id) = request_id {request.add_header(consts::X_REQUEST_ID,diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 9773f1bda5..25a247ee3f 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -1398,3 +1398,65 @@ impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {}}}++/// Classification of a UCS failure for the primary→shadow kill switch.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UcsKillSwitchReason {+ /// Couldn't even reach Prism (gRPC dial/transport failure).+ UcsUnreachable,+ /// Prism itself returned a non-success gRPC status.+ UcsError,+ /// Prism reached the connector but the connector endpoint returned a non-2xx.+ ConnectorErrorViaUcs,+ /// The request/response transformation layer in Prism is malformed for this flow.+ TransformationBroken,+ /// Catch-all for variants that don't fit anywhere else. Treated as+ /// kill-switch-eligible by default — fail-safe beats fail-open during a migration.+ UnknownError,+}++impl UcsKillSwitchReason {+ /// Stable label used in metrics and logs.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::UcsUnreachable => "ucs_unreachable",+ Self::UcsError => "ucs_error",+ Self::ConnectorErrorViaUcs => "connector_error_via_ucs",+ Self::TransformationBroken => "transformation_broken",+ Self::UnknownError => "unknown_error",+ }+ }+}++impl UnifiedConnectorServiceError {+ /// Classify whether an error from a **primary**-mode UCS call should trip the+ /// primary→shadow kill switch.+ ///+ /// Policy: **every `UnifiedConnectorServiceError` trips the switch.** No+ /// carve-outs — even variants that look like "config errors" (`NotImplemented`)+ /// indicate Primary is not serving traffic the way it should be, and the+ /// legacy Direct path will succeed where Prism failed. Auto-flipping on a+ /// false positive costs nothing; missing a real failure costs an outage.+ pub fn ucs_kill_switch_reason(&self) -> Option<UcsKillSwitchReason> {+ match self {+ // Can't reach Prism at all (gRPC dial, DNS, TLS, LB, pod down).+ Self::ConnectionError(_) => Some(UcsKillSwitchReason::UcsUnreachable),++ // Any Prism-side gRPC status — server-class, client-class, and+ // `Unimplemented`. All of them mean Prism returned a non-success.+ Self::TonicStatus { .. } => Some(UcsKillSwitchReason::UcsError),++ // Connector returned any non-2xx through Prism.+ Self::ConnectorError(_) => Some(UcsKillSwitchReason::ConnectorErrorViaUcs),++ // Prism's response couldn't be decoded — transformation layer is suspect.+ Self::ResponseDeserializationFailed | Self::ParsingFailed => {+ Some(UcsKillSwitchReason::TransformationBroken)+ }++ // Everything else — `NotImplemented`, encoding bugs, marker "operation+ // failed" variants, webhook-path failures. Catch-all flips by design.+ _ => Some(UcsKillSwitchReason::UnknownError),+ }+ }+}diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex 866edcfbec..a350be1db4 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -399,7 +399,7 @@ async fn resolve_proxy_ucs_gateway_and_vault_mca<PayF: Clone, RdF: Clone, T, R>(whereR: Send + Sync + Clone,{- let (execution_path, updated_state) =+ let (execution_path, updated_state, _matched_rollout_key) =unified_connector_service::should_call_unified_connector_service(state,processor,@@ -1379,7 +1379,7 @@ async fn call_ucs_authenticate_proxy()});- let (execution_path, updated_state) =+ let (execution_path, updated_state, _matched_rollout_key) =unified_connector_service::should_call_unified_connector_service(state,processor,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex aef3197f6a..a1453a509c 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3470,16 +3470,17 @@ where{let previous_gateway = extract_gateway_system_from_payment_intent(payment_data);- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- platform.get_processor(),- &router_data,- previous_gateway,- call_connector_action.clone(),- None,- common_enums::TransactionType::Payment,- )- .await?;+ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ platform.get_processor(),+ &router_data,+ previous_gateway,+ call_connector_action.clone(),+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),@@ -3549,6 +3550,7 @@ wheremerchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key.clone(),},).await?;@@ -3567,6 +3569,7 @@ wheremerchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key.clone(),};let (connector_request, should_continue) = if should_continue_further {@@ -6295,16 +6298,17 @@ where// Extract previous gateway from payment datalet previous_gateway = extract_gateway_system_from_payment_intent(payment_data);- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- processor,- &router_data,- previous_gateway,- call_connector_action.clone(),- shadow_ucs_call_connector_action.clone(),- common_enums::TransactionType::Payment,- )- .await?;+ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ processor,+ &router_data,+ previous_gateway,+ call_connector_action.clone(),+ shadow_ucs_call_connector_action.clone(),+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),@@ -6326,6 +6330,7 @@ wheremerchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};if core_utils::get_flow_name::<F>().unwrap_or_default() != "PSync" {@@ -6885,16 +6890,17 @@ wherelet previous_gateway = extract_gateway_system_from_payment_intent(payment_data);// do order creation- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- platform.get_processor(),- &router_data,- previous_gateway,- call_connector_action.clone(),- None,- common_enums::TransactionType::Payment,- )- .await?;+ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ platform.get_processor(),+ &router_data,+ previous_gateway,+ call_connector_action.clone(),+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),@@ -6916,6 +6922,7 @@ wheremerchant_connector_account: merchant_connector_account_type_details.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};let should_continue = match router_data@@ -7017,16 +7024,17 @@ where// Extract previous gateway from payment datalet previous_gateway = extract_gateway_system_from_payment_intent(payment_data);- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- processor,- &router_data,- previous_gateway,- call_connector_action.clone(),- None,- common_enums::TransactionType::Payment,- )- .await?;+ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ processor,+ &router_data,+ previous_gateway,+ call_connector_action.clone(),+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),business_profile.get_id().clone(),@@ -7047,6 +7055,7 @@ wheremerchant_connector_account: merchant_connector_account_type_details.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};let call_connector_service_response = call_connector_service(&updated_state,@@ -7212,16 +7221,19 @@ where).await?;- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- platform.get_processor(),- &router_data,- None,- call_connector_action.clone(),- None,- common_enums::TransactionType::Payment,- )- .await?;+ let previous_gateway = extract_gateway_system_from_payment_intent(payment_data);++ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ platform.get_processor(),+ &router_data,+ previous_gateway,+ call_connector_action.clone(),+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),@@ -7243,6 +7255,7 @@ wheremerchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};// Update feature metadata to track Direct routing usage for stickiness@@ -8271,16 +8284,17 @@ wheredyn api::Connector:services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,{- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- processor,- &router_data,- None, // No previous gateway information required for session flow- call_connector_action.clone(),- None,- common_enums::TransactionType::Payment,- )- .await?;+ let (execution_path, updated_state, _matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ processor,+ &router_data,+ None, // No previous gateway information required for session flow+ call_connector_action.clone(),+ None,+ common_enums::TransactionType::Payment,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(),@@ -8302,6 +8316,7 @@ wheremerchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: None,};router_datadiff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 55ae3df855..700d5f2794 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -1647,6 +1647,7 @@ pub async fn call_unified_connector_service_pre_authenticate(payment_pre_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_pre_authenticate_request, grpc_headers| async move {let response = client.payment_pre_authenticate(@@ -1793,6 +1794,7 @@ pub async fn call_unified_connector_service_pre_authenticate_proxy(payment_pre_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_pre_authenticate_request, grpc_headers| async move {let response = Box::pin(client.payment_pre_authenticate(payment_pre_authenticate_request,diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 2069e9bb92..ecf76cdb6b 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -816,6 +816,7 @@ pub async fn call_unified_connector_service_authenticate(payment_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_authenticate_request, grpc_headers| async move {let response = Box::pin(client.payment_authenticate(payment_authenticate_request,@@ -975,6 +976,7 @@ pub async fn call_unified_connector_service_authenticate_proxy(payment_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_authenticate_request, grpc_headers| async move {let response = Box::pin(client.payment_authenticate(payment_authenticate_request,@@ -1081,6 +1083,7 @@ pub async fn call_unified_connector_service_post_authenticate(payment_post_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_post_authenticate_request, grpc_headers| async move {let response = Box::pin(client.payment_post_authenticate(payment_post_authenticate_request,@@ -1224,6 +1227,7 @@ pub async fn call_unified_connector_service_post_authenticate_proxy(payment_post_authenticate_request,headers_builder,unified_connector_service_execution_mode,+ None,|mut router_data, payment_post_authenticate_request, grpc_headers| async move {let response = Box::pin(client.payment_post_authenticate(payment_post_authenticate_request,diff --git a/crates/router/src/core/payments/gateway/access_token_gateway.rs b/crates/router/src/core/payments/gateway/access_token_gateway.rsindex e1eb72b1c8..4022c4bfd9 100644--- a/crates/router/src/core/payments/gateway/access_token_gateway.rs+++ b/crates/router/src/core/payments/gateway/access_token_gateway.rs@@ -80,6 +80,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client@@ -165,6 +166,7 @@ wherecreate_access_token_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, create_access_token_request, grpc_headers| async move {let response = match client.create_access_token(diff --git a/crates/router/src/core/payments/gateway/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rsindex cc1bdc88e7..fe6f5fde6a 100644--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs@@ -75,6 +75,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -135,6 +136,7 @@ whererecurring_payment_charge_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, recurring_payment_charge_request, grpc_headers| async move {let response = match Box::pin(client.recurring_payment_charge(recurring_payment_charge_request,@@ -241,6 +243,7 @@ wheregranular_authorize_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_authorize_request, grpc_headers| async move {let response = match Box::pin(client.payment_authorize(granular_authorize_request,diff --git a/crates/router/src/core/payments/gateway/cancel_gateway.rs b/crates/router/src/core/payments/gateway/cancel_gateway.rsindex c807e5f0ee..f989b78ccf 100644--- a/crates/router/src/core/payments/gateway/cancel_gateway.rs+++ b/crates/router/src/core/payments/gateway/cancel_gateway.rs@@ -65,6 +65,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -114,6 +115,7 @@ wherepayment_void_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_void_request, grpc_headers| async move {let response = match client.payment_void(payment_void_request, connector_auth_metadata, grpc_headers)diff --git a/crates/router/src/core/payments/gateway/capture_gateway.rs b/crates/router/src/core/payments/gateway/capture_gateway.rsindex c0fe74cc4d..46843d33a4 100644--- a/crates/router/src/core/payments/gateway/capture_gateway.rs+++ b/crates/router/src/core/payments/gateway/capture_gateway.rs@@ -65,6 +65,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -112,6 +113,7 @@ wherepayment_capture_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_capture_request, grpc_headers| async move {let response = match client.payment_capture(diff --git a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rsindex e11f80a6ef..136c642c4d 100644--- a/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/complete_authorize_gateway.rs@@ -69,6 +69,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -117,6 +118,7 @@ wheregranular_authorize_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_authorize_request, grpc_headers| async move {let response = match Box::pin(client.payment_authorize(granular_authorize_request,diff --git a/crates/router/src/core/payments/gateway/context.rs b/crates/router/src/core/payments/gateway/context.rsindex 9cfc19ad5f..3fcf110639 100644--- a/crates/router/src/core/payments/gateway/context.rs+++ b/crates/router/src/core/payments/gateway/context.rs@@ -42,6 +42,11 @@ pub struct RouterGatewayContext {/// Execution path (Direct, UCS, or Shadow)pub execution_path: ExecutionPath,++ /// The rollout config key that produced the Primary/Shadow execution-mode+ /// decision for this request, if any. Captured at routing time so the UCS+ /// primary→shadow kill switch knows exactly which `configs` row to flip.+ pub ucs_matched_rollout_key: Option<String>,}impl RouterGatewayContext {@@ -73,6 +78,7 @@ impl RouterGatewayContext {execution_mode,execution_path,creds_identifier,+ ucs_matched_rollout_key: None,}}pub fn direct(@@ -93,6 +99,7 @@ impl RouterGatewayContext {execution_mode: ExecutionMode::NotApplicable,execution_path: ExecutionPath::Direct,creds_identifier,+ ucs_matched_rollout_key: None,}}}diff --git a/crates/router/src/core/payments/gateway/create_customer_gateway.rs b/crates/router/src/core/payments/gateway/create_customer_gateway.rsindex c060bddc83..63702936cc 100644--- a/crates/router/src/core/payments/gateway/create_customer_gateway.rs+++ b/crates/router/src/core/payments/gateway/create_customer_gateway.rs@@ -74,6 +74,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client@@ -125,6 +126,7 @@ wherecreate_connector_customer_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, create_connector_customer_request, grpc_headers| async move {let response = match Box::pin(client.create_connector_customer(create_connector_customer_request,diff --git a/crates/router/src/core/payments/gateway/create_order_gateway.rs b/crates/router/src/core/payments/gateway/create_order_gateway.rsindex a3c6902f55..a03ff0edbc 100644--- a/crates/router/src/core/payments/gateway/create_order_gateway.rs+++ b/crates/router/src/core/payments/gateway/create_order_gateway.rs@@ -70,6 +70,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -117,6 +118,7 @@ wherecreate_order_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, create_order_request, grpc_headers| async move {let response = match Box::pin(client.payment_create_order(create_order_request,diff --git a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rsindex a3cd03ac79..6406eae59b 100644--- a/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs+++ b/crates/router/src/core/payments/gateway/incremental_authorization_gateway.rs@@ -78,6 +78,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -128,6 +129,7 @@ whereincremental_authorization_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, incremental_authorization_request, grpc_headers| async move {let response = match Box::pin(client.payment_incremental_authorization(incremental_authorization_request,diff --git a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rsindex 34b7dc2107..7b7c5efd63 100644--- a/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs+++ b/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs@@ -76,6 +76,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -122,6 +123,7 @@ wherepayment_method_tokenize_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_method_tokenize_request, grpc_headers| async move {let response = match Box::pin(client.payment_method_tokenize(payment_method_tokenize_request,diff --git a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rsindex 980083756e..2a212baad5 100644--- a/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs+++ b/crates/router/src/core/payments/gateway/pre_authorize_void_gateway.rs@@ -73,6 +73,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -122,6 +123,7 @@ wherepayment_void_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_void_request, grpc_headers| async move {let response = match client.payment_void(payment_void_request, connector_auth_metadata, grpc_headers)diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rsindex 5157c6dbc8..9bc132b15f 100644--- a/crates/router/src/core/payments/gateway/psync_gateway.rs+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs@@ -133,6 +133,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let is_ucs_psync_disabled = state.conf.grpc_client@@ -199,6 +200,7 @@ wherepayment_get_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_get_request, grpc_headers| async move {let response = match client.payment_get(payment_get_request, connector_auth_metadata, grpc_headers)diff --git a/crates/router/src/core/payments/gateway/session_gateway.rs b/crates/router/src/core/payments/gateway/session_gateway.rsindex 3c53a7d0b2..6653d47b71 100644--- a/crates/router/src/core/payments/gateway/session_gateway.rs+++ b/crates/router/src/core/payments/gateway/session_gateway.rs@@ -70,6 +70,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -118,6 +119,7 @@ wherecreate_sdk_session_token_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, create_sdk_session_token_request, grpc_headers| async move {let response = match Box::pin(client.create_sdk_session_token(create_sdk_session_token_request,diff --git a/crates/router/src/core/payments/gateway/session_token_gateway.rs b/crates/router/src/core/payments/gateway/session_token_gateway.rsindex 6294e325a5..d17f9a3ae7 100644--- a/crates/router/src/core/payments/gateway/session_token_gateway.rs+++ b/crates/router/src/core/payments/gateway/session_token_gateway.rs@@ -72,6 +72,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client@@ -120,6 +121,7 @@ wherecreate_session_token_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, create_session_token_request, grpc_headers| async move {let response = match client.create_session_token(diff --git a/crates/router/src/core/payments/gateway/setup_mandate.rs b/crates/router/src/core/payments/gateway/setup_mandate.rsindex 4c299a6fb6..70ddcc3210 100644--- a/crates/router/src/core/payments/gateway/setup_mandate.rs+++ b/crates/router/src/core/payments/gateway/setup_mandate.rs@@ -68,6 +68,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -115,6 +116,7 @@ wherepayment_setup_recurring_request,header_payload,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, payment_setup_recurring_request, grpc_headers| async move {let response = match Box::pin(client.payment_setup_recurring(payment_setup_recurring_request,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 9613e74c31..522e75cf78 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2524,7 +2524,7 @@ pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool {.unwrap_or(false)}-#[derive(Debug, Clone, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct RolloutConfig {pub rollout_percent: f64,pub http_url: Option<String>,@@ -2561,6 +2561,9 @@ pub struct RolloutExecutionResult {pub should_execute: bool,pub proxy_override: Option<ProxyOverride>,pub execution_mode: ExecutionMode,+ /// The exact config key that produced this result, if any. Used by the+ /// primary→shadow kill switch to know which row to flip.+ pub matched_config_key: Option<String>,}impl Default for RolloutExecutionResult {@@ -2569,6 +2572,7 @@ impl Default for RolloutExecutionResult {should_execute: false,proxy_override: None,execution_mode: ExecutionMode::NotApplicable,+ matched_config_key: None,}}}@@ -2656,6 +2660,7 @@ impl From<RolloutConfig> for RolloutExecutionResult {should_execute: true,proxy_override,execution_mode: config.execution_mode,+ matched_config_key: None,}}false => {@@ -2765,7 +2770,11 @@ pub async fn should_execute_based_on_rollout_with_precedence(Some(config) => {logger::info!(config_key = %key, "Rollout config found, using this key");return Ok(serde_json::from_str::<RolloutConfig>(&config.config)- .map(RolloutExecutionResult::from)+ .map(|rollout| {+ let mut result = RolloutExecutionResult::from(rollout);+ result.matched_config_key = Some(key.clone());+ result+ }).map_err(|err| {logger::error!(error = ?err,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 03f723f1bb..399e8e9eac 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -4082,16 +4082,17 @@ pub async fn decide_unified_connector_service_payout<F: Clone>(// Extract previous gateway from payment datalet previous_gateway = extract_gateway_system_from_payouts(payout_data);- let (execution_path, updated_state) = should_call_unified_connector_service(- state,- platform.get_processor(),- router_data,- previous_gateway,- common_enums::enums::CallConnectorAction::Trigger,- None,- common_enums::TransactionType::Payout,- )- .await?;+ let (execution_path, updated_state, matched_rollout_key) =+ should_call_unified_connector_service(+ state,+ platform.get_processor(),+ router_data,+ previous_gateway,+ common_enums::enums::CallConnectorAction::Trigger,+ None,+ common_enums::TransactionType::Payout,+ )+ .await?;let lineage_ids = grpc_client::LineageIds::new(payout_data.payouts.merchant_id.clone(),@@ -4138,6 +4139,7 @@ pub async fn decide_unified_connector_service_payout<F: Clone>(merchant_connector_account,execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};// Update feature metadata to track Direct routing usage for stickinessupdate_gateway_system_in_payout_metadata(payout_data, gateway_context.get_gateway_system())?;diff --git a/crates/router/src/core/payouts/gateway/cancel_gateway.rs b/crates/router/src/core/payouts/gateway/cancel_gateway.rsindex ff76a9bc68..1d5ef70612 100644--- a/crates/router/src/core/payouts/gateway/cancel_gateway.rs+++ b/crates/router/src/core/payouts/gateway/cancel_gateway.rs@@ -63,6 +63,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -111,6 +112,7 @@ wheregranular_payout_void_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_payout_void_request, grpc_headers| async move {let response = Box::pin(client.payout_void(granular_payout_void_request,diff --git a/crates/router/src/core/payouts/gateway/context.rs b/crates/router/src/core/payouts/gateway/context.rsindex a268c08125..7e7377f01c 100644--- a/crates/router/src/core/payouts/gateway/context.rs+++ b/crates/router/src/core/payouts/gateway/context.rs@@ -26,6 +26,10 @@ pub struct RouterGatewayContext {pub execution_path: ExecutionPath,/// Execution mode (Primary or Shadow)pub execution_mode: ExecutionMode,+ /// The rollout config key that produced the Primary/Shadow execution-mode+ /// decision for this request, if any. Captured at routing time so the UCS+ /// primary→shadow kill switch knows exactly which `configs` row to flip.+ pub ucs_matched_rollout_key: Option<String>,}impl RouterGatewayContext {/// Get the gateway system (Direct, UnifiedConnectorService, etc.)diff --git a/crates/router/src/core/payouts/gateway/create_gateway.rs b/crates/router/src/core/payouts/gateway/create_gateway.rsindex df8b9492dd..5d8f8f3d89 100644--- a/crates/router/src/core/payouts/gateway/create_gateway.rs+++ b/crates/router/src/core/payouts/gateway/create_gateway.rs@@ -63,6 +63,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -116,6 +117,7 @@ wheregranular_payout_create_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_payout_create_request, grpc_headers| async move {let response = Box::pin(client.payout_create(granular_payout_create_request,diff --git a/crates/router/src/core/payouts/gateway/eligibility_gateway.rs b/crates/router/src/core/payouts/gateway/eligibility_gateway.rsindex 1c773a22a7..a03e60ed5b 100644--- a/crates/router/src/core/payouts/gateway/eligibility_gateway.rs+++ b/crates/router/src/core/payouts/gateway/eligibility_gateway.rs@@ -63,6 +63,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -111,6 +112,7 @@ wheregranular_payout_eligibility_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_payout_eligibility_request, grpc_headers| async move {let response = Box::pin(client.payout_eligibility(granular_payout_eligibility_request,diff --git a/crates/router/src/core/payouts/gateway/fulfill_gateway.rs b/crates/router/src/core/payouts/gateway/fulfill_gateway.rsindex 3186a94a7a..552e741d81 100644--- a/crates/router/src/core/payouts/gateway/fulfill_gateway.rs+++ b/crates/router/src/core/payouts/gateway/fulfill_gateway.rs@@ -111,6 +111,7 @@ wheregranular_payout_transfer_request,grpc_headers,unified_connector_service_execution_mode,+ None,|mut router_data, granular_payout_transfer_request, grpc_headers| async move {let response = Box::pin(client.payout_transfer(granular_payout_transfer_request,diff --git a/crates/router/src/core/payouts/gateway/quote_gateway.rs b/crates/router/src/core/payouts/gateway/quote_gateway.rsindex e8bf52cd9a..061c0e3f53 100644--- a/crates/router/src/core/payouts/gateway/quote_gateway.rs+++ b/crates/router/src/core/payouts/gateway/quote_gateway.rs@@ -111,6 +111,7 @@ wheregranular_payout_stage_request,grpc_headers,unified_connector_service_execution_mode,+ None,|mut router_data, granular_payout_stage_request, grpc_headers| async move {let response = Box::pin(client.payout_stage(granular_payout_stage_request,diff --git a/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rsindex 30bfc740e0..9fdb41c1f4 100644--- a/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs+++ b/crates/router/src/core/payouts/gateway/recipient_account_gateway.rs@@ -63,6 +63,7 @@ wherelet lineage_ids = context.lineage_ids;let header_payload = context.header_payload;let unified_connector_service_execution_mode = context.execution_mode;+ let ucs_matched_rollout_key = context.ucs_matched_rollout_key;let client = state.grpc_client.unified_connector_service_client@@ -110,6 +111,7 @@ wheregranular_payout_enroll_disburse_account_request,grpc_headers,unified_connector_service_execution_mode,+ ucs_matched_rollout_key,|mut router_data, granular_payout_enroll_disburse_account_request, grpc_headers| async move {let response = Box::pin(client.payout_enroll_disburse_account(granular_payout_enroll_disburse_account_request,diff --git a/crates/router/src/core/payouts/gateway/recipient_gateway.rs b/crates/router/src/core/payouts/gateway/recipient_gateway.rsindex cada638327..80d89e3430 100644--- a/crates/router/src/core/payouts/gateway/recipient_gateway.rs+++ b/crates/router/src/core/payouts/gateway/recipient_gateway.rs@@ -110,6 +110,7 @@ wheregranular_payout_create_recipient_request,grpc_headers,unified_connector_service_execution_mode,+ None,|mut router_data, granular_payout_create_recipient_request, grpc_headers| async move {let response = Box::pin(client.payout_create_recipient(granular_payout_create_recipient_request,diff --git a/crates/router/src/core/payouts/gateway/sync_gateway.rs b/crates/router/src/core/payouts/gateway/sync_gateway.rsindex d5757dbc23..49e5b3fb1d 100644--- a/crates/router/src/core/payouts/gateway/sync_gateway.rs+++ b/crates/router/src/core/payouts/gateway/sync_gateway.rs@@ -111,6 +111,7 @@ wheregranular_payout_get_request,grpc_headers,unified_connector_service_execution_mode,+ None,|mut router_data, granular_payout_get_request, grpc_headers| async move {let response = Box::pin(client.payout_get(granular_payout_get_request,diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex baa915b9ee..b12928bbb3 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -221,7 +221,7 @@ pub async fn trigger_refund_to_gateway().await?;- let (execution_path, updated_state) =+ let (execution_path, updated_state, matched_rollout_key) =unified_connector_service::should_call_unified_connector_service(state,platform.get_processor(),@@ -256,6 +256,7 @@ pub async fn trigger_refund_to_gateway(merchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};// Add access token for both UCS and direct connector paths@@ -887,7 +888,7 @@ pub async fn sync_refund_with_gateway(// Access token available or not needed - proceed with execution// Check which gateway system to use for refund sync- let (execution_path, updated_state) =+ let (execution_path, updated_state, matched_rollout_key) =unified_connector_service::should_call_unified_connector_service(state,platform.get_processor(),@@ -922,6 +923,7 @@ pub async fn sync_refund_with_gateway(merchant_connector_account: merchant_connector_account.clone(),execution_path,execution_mode,+ ucs_matched_rollout_key: matched_rollout_key,};// Add access token for both UCS and direct connector pathsdiff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 390a84d140..b896a53623 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -32,6 +32,7 @@ use hyperswitch_domain_models::{router_request_types::RefundsData,router_response_types::{PaymentsResponseData, PayoutsResponseData, RefundsResponseData},};+use hyperswitch_interfaces::unified_connector_service::transformers::UcsKillSwitchReason;use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};use router_env::{instrument, logger, tracing};use unified_connector_service_cards::CardNumber;@@ -303,7 +304,7 @@ pub async fn should_call_unified_connector_service<F: Clone, T, R>(call_connector_action: CallConnectorAction,shadow_ucs_call_connector_action: Option<CallConnectorAction>,transaction_type: common_enums::TransactionType,-) -> RouterResult<(ExecutionPath, SessionState)>+) -> RouterResult<(ExecutionPath, SessionState, Option<String>)>whereR: Send + Sync + Clone,{@@ -441,7 +442,11 @@ whereflow_name);- Ok((execution_path, session_state))+ Ok((+ execution_path,+ session_state,+ rollout_result.matched_config_key,+ ))}/// Creates a new SessionState with proxy configuration updated from the override@@ -3010,6 +3015,7 @@ pub async fn ucs_logging_wrapper_granular<T, F, Fut, Req, Resp, GrpcReq, FlowOutgrpc_request: GrpcReq,grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal,execution_mode: ExecutionMode,+ matched_rollout_key: Option<String>,handler: F,) -> CustomResult<(RouterData<T, Req, Resp>, FlowOutput), UnifiedConnectorServiceError>where@@ -3042,6 +3048,9 @@ wherelet refund_id = router_data.refund_id.clone();let dispute_id = router_data.dispute_id.clone();let payout_id = router_data.payout_id.clone();+ // Captured before `handler` consumes router_data, in case the kill switch fires.+ let kill_switch_merchant_id = merchant_id.clone();+ let kill_switch_connector_name = connector_name.clone();let grpc_header = grpc_header_builder.build();// Log the actual gRPC request with maskinglet grpc_request_body = hyperswitch_masking::masked_serialize(&grpc_request)@@ -3093,6 +3102,23 @@ whererouter_env::metric_attributes!(("connector", connector_name.clone(),)),);+ // Trip the primary→shadow kill switch if this is a Prism-side or+ // transformation-layer failure on the Primary path. Errors are logged+ // inside; a failed flip never affects the in-flight payment.+ maybe_activate_ucs_kill_switch(+ state,+ &kill_switch_merchant_id,+ &kill_switch_connector_name,+ std::any::type_name::<T>()+ .split("::")+ .last()+ .unwrap_or_default(),+ execution_mode,+ matched_rollout_key.clone(),+ error.current_context(),+ )+ .await;+let error_body = serde_json::json!({"error": error.to_string(),"error_type": "ucs_call_failed"@@ -3131,6 +3157,168 @@ where})}+/// Flip the given rollout config row from `Primary` (or `NotApplicable`) to `Shadow`,+/// forcing `rollout_percent` to `1.0` so every subsequent request takes the Shadow+/// path until an operator restores Primary after the underlying UCS issue is fixed.+///+/// Callers must have already verified the connector is **not** in+/// `ucs_only_connectors` and that `matched_rollout_key` is connector-scoped.+async fn activate_ucs_kill_switch(+ state: &SessionState,+ matched_rollout_key: &str,+ connector_name: &str,+ flow_name: &str,+ reason: UcsKillSwitchReason,+) {+ let existing = match state.store.find_config_by_key(matched_rollout_key).await {+ Ok(cfg) => cfg,+ Err(err) => {+ router_env::logger::error!(+ key = %matched_rollout_key,+ error = ?err,+ "UCS kill switch: rollout row disappeared between decision and flip"+ );+ return;+ }+ };++ let mut parsed: crate::core::payments::helpers::RolloutConfig =+ match serde_json::from_str(&existing.config) {+ Ok(cfg) => cfg,+ Err(err) => {+ router_env::logger::warn!(+ key = %matched_rollout_key,+ error = ?err,+ "UCS kill switch: rollout config did not parse as RolloutConfig; skipping"+ );+ return;+ }+ };++ if parsed.execution_mode == ExecutionMode::Shadow {+ router_env::logger::debug!(key = %matched_rollout_key, "UCS kill switch already active");+ return;+ }++ parsed.execution_mode = ExecutionMode::Shadow;++ let serialized = match serde_json::to_string(&parsed) {+ Ok(s) => s,+ Err(err) => {+ router_env::logger::error!(+ key = %matched_rollout_key,+ error = ?err,+ "UCS kill switch: failed to serialize downgraded RolloutConfig"+ );+ return;+ }+ };++ if let Err(err) = state+ .store+ .update_config_by_key(+ matched_rollout_key,+ diesel_models::configs::ConfigUpdate::Update {+ config: Some(serialized),+ },+ )+ .await+ {+ router_env::logger::error!(+ key = %matched_rollout_key,+ error = ?err,+ "UCS kill switch: DB update failed; primary→shadow flip NOT persisted"+ );+ return;+ }++ crate::routes::metrics::UCS_PRIMARY_TO_SHADOW_KILL_SWITCH.add(+ 1,+ router_env::metric_attributes!(+ ("connector", connector_name.to_string()),+ ("flow", flow_name.to_string()),+ ("error_kind", reason.as_str()),+ ),+ );++ router_env::logger::error!(+ event = "ucs_kill_switch_activated",+ connector = %connector_name,+ flow = %flow_name,+ rollout_key = %matched_rollout_key,+ error_kind = reason.as_str(),+ "UCS kill switch flipped primary → shadow"+ );+}++/// Entry point invoked from the UCS error path. Skips ucs_only connectors.+/// Only invoked in `ExecutionMode::Primary` — shadow/direct paths never reach here.+#[allow(clippy::too_many_arguments)]+async fn maybe_activate_ucs_kill_switch(+ state: &SessionState,+ merchant_id: &id_type::MerchantId,+ connector_name: &str,+ flow_name: &str,+ execution_mode: ExecutionMode,+ matched_config_key: Option<String>,+ error: &UnifiedConnectorServiceError,+) {+ if execution_mode != ExecutionMode::Primary {+ return;+ }++ let Some(reason) = error.ucs_kill_switch_reason() else {+ return;+ };++ let is_ucs_only = state+ .conf+ .grpc_client+ .unified_connector_service+ .as_ref()+ .and_then(|ucs_config| {+ Connector::from_str(connector_name)+ .ok()+ .map(|c| ucs_config.ucs_only_connectors.contains(&c))+ })+ .unwrap_or(false);++ if is_ucs_only {+ router_env::logger::debug!(+ connector = %connector_name,+ "UCS kill switch fired but connector is ucs_only; skipping mode flip"+ );+ return;+ }++ let Some(matched_key) = matched_config_key else {+ router_env::logger::warn!(+ merchant_id = %merchant_id.get_string_repr(),+ connector = %connector_name,+ flow = %flow_name,+ error_kind = reason.as_str(),+ "UCS kill switch fired but no matched rollout config key was recorded"+ );+ return;+ };++ // Refuse to flip rows whose key doesn't itself contain the connector name:+ // org-level and org+merchant-level rows would affect other connectors/merchants.+ let connector_marker = format!("_{connector_name}_");+ if !matched_key.contains(&connector_marker) {+ router_env::logger::warn!(+ merchant_id = %merchant_id.get_string_repr(),+ connector = %connector_name,+ rollout_key = %matched_key,+ error_kind = reason.as_str(),+ "UCS kill switch: matched rollout row is not connector-scoped; refusing to auto-flip"+ );+ return;+ }++ activate_ucs_kill_switch(state, &matched_key, connector_name, flow_name, reason).await;+}+/// UCS wrapper for webhook flows. It centralizes header building and handler/// invocation plus masked request/response logging, and takes no/// `RouterData` — incoming webhooks don't have one at the UCS call site. `flow` isdiff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 437b79ff52..54348fe5d1 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -70,6 +70,7 @@ counter_metric!(THREE_DS_DOWNGRADE_COUNT, GLOBAL_METER);counter_metric!(RESPONSE_DESERIALIZATION_FAILURE, GLOBAL_METER);counter_metric!(CONNECTOR_ERROR_RESPONSE_COUNT, GLOBAL_METER);counter_metric!(REQUEST_TIMEOUT_COUNT, GLOBAL_METER);+counter_metric!(UCS_PRIMARY_TO_SHADOW_KILL_SWITCH, GLOBAL_METER);counter_metric!(EXECUTE_PRETASK_COUNT, GLOBAL_METER);counter_metric!(CONNECTOR_PAYMENT_METHOD_TOKENIZATION, GLOBAL_METER);