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
refactor(routing): remove the DE-vs-HS shadow diff and its kill switch (#14167)
Prajjwal Kumar423eedb75ea2
diff --git a/config/config.example.toml b/config/config.example.tomlindex 299be3c5fa..fc9fae663f 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1492,15 +1492,10 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List[open_router]dynamic_routing_enabled = true # Enable or disable Open Router for dynamic routingstatic_routing_enabled = true # Enable or disable Open Router for static routing-shadow_routing_enabled = false # Shadow-evaluate static routing on DE for non-cutover profiles (diff logging + kill switch only); requires static_routing_enabledurl = "http://localhost:8080" # Open Router URLdashboard_url = "http://localhost:5173" # Decision Engine dashboard (browser) URL for merchant SSO redirectadmin_secret = "" # Shared secret sent as x-admin-secret on Decision Engine admin endpoints; empty disables the header-[open_router.diff_kill_switch]-enabled = false # Enable automatic per-profile cutover back to Hyperswitch routing on repeated DE diffs-diff_count_threshold = 100 # Non-volume routing diffs per profile within the counter window that trip the kill switch-[grpc_client.unified_connector_service]base_url = "http://localhost:8000" # Unified Connector Service Base URLconnection_timeout = 10 # Connection Timeout Duration in Secondsdiff --git a/config/development.toml b/config/development.tomlindex 986707099a..6b15763770 100644--- a/config/development.toml+++ b/config/development.toml@@ -1615,15 +1615,10 @@ connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"[open_router]dynamic_routing_enabled = falsestatic_routing_enabled = false-shadow_routing_enabled = falseurl = "http://localhost:8080"dashboard_url = "http://localhost:5173"admin_secret = ""-[open_router.diff_kill_switch]-enabled = false-diff_count_threshold = 100-[l2_l3_data_config]enabled = "true"diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 41af2826b9..06eed4387f 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -425,13 +425,6 @@ pub struct DebitRoutingConfig {pub struct OpenRouter {pub dynamic_routing_enabled: bool,pub static_routing_enabled: bool,- /// Shadow-evaluate static routing on the Decision Engine for profiles that are NOT cut- /// over, logging DE-vs-HS diffs and feeding the diff kill switch while the Hyperswitch- /// result keeps serving traffic. Requires `static_routing_enabled`.- #[serde(default)]- pub shadow_routing_enabled: bool,- #[serde(default)]- pub diff_kill_switch: DecisionEngineDiffKillSwitch,pub url: String,/// Browser-facing Decision Engine dashboard base URL, used for the merchant SSO redirect.#[serde(default)]@@ -444,24 +437,6 @@ pub struct OpenRouter {pub admin_secret: Secret<String>,}-#[derive(Debug, Deserialize, Clone)]-#[serde(default)]-pub struct DecisionEngineDiffKillSwitch {- pub enabled: bool,- /// Lifetime non-volume diff count per profile that trips the cutover back to Hyperswitch- /// routing. The counter does not expire; clear it via the diff-counter reset API.- pub diff_count_threshold: u64,-}--impl Default for DecisionEngineDiffKillSwitch {- fn default() -> Self {- Self {- enabled: false,- diff_count_threshold: 100,- }- }-}-#[derive(Debug, Deserialize, Clone, Default)]#[serde(default)]pub struct CloneConnectorAllowlistConfig {diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rsindex f58be0f8ed..a08893e3fc 100644--- a/crates/router/src/core/metrics.rs+++ b/crates/router/src/core/metrics.rs@@ -91,8 +91,6 @@ counter_metric!(DYNAMIC_CONTRACT_BASED_ROUTING, GLOBAL_METER);histogram_metric_f64!(DECISION_ENGINE_REQUEST_TIME, GLOBAL_METER);counter_metric!(DECISION_ENGINE_REQUESTS, GLOBAL_METER);-counter_metric!(DECISION_ENGINE_ROUTING_DIFF, GLOBAL_METER);-counter_metric!(DECISION_ENGINE_KILL_SWITCH_TRIGGERED, GLOBAL_METER);// Qualifying UCS failures seen by the kill switch, emitted whether or not it is turned on so the// classifier can be validated against real traffic before the switch is turned on.diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 278f734f81..c98bb51d30 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -13228,15 +13228,14 @@ pub async fn static_dynamic_routing_v1_for_payments(backend_input: euclid::backend::BackendInput,fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,) -> RouterResult<routing::RoutingConnectorOutcomeWithApproachAndEligibility> {- let (static_connectors, static_approach, static_is_volume_split) =- routing::perform_static_routing_locally(- state,- business_profile,- &payment_dsl_input,- &backend_input,- &fallback_config,- )- .await?;+ let (static_connectors, static_approach) = routing::perform_static_routing_locally(+ state,+ business_profile,+ &payment_dsl_input,+ &backend_input,+ &fallback_config,+ )+ .await?;let (connectors, routing_approach) = routing::perform_hybrid_routing_if_enabled(state,@@ -13247,7 +13246,6 @@ pub async fn static_dynamic_routing_v1_for_payments(&fallback_config,&static_connectors,static_approach,- static_is_volume_split,).await;diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 3d180c31d2..4785661ba2 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -717,8 +717,6 @@ pub struct RoutingContext {pub struct RoutingConnectorOutcome {pub connectors: Vec<routing_types::RoutableConnectorChoice>,- /// Selection involved a volume split (randomized), so a DE-vs-HS diff is expected.- pub is_volume_split: bool,}impl RoutingConnectorOutcome {@@ -755,17 +753,13 @@ impl RoutingConnectorOutcome {pub fn empty() -> Self {Self {connectors: Vec::new(),- is_volume_split: false,}}}impl From<Vec<routing_types::RoutableConnectorChoice>> for RoutingConnectorOutcome {fn from(connectors: Vec<routing_types::RoutableConnectorChoice>) -> Self {- Self {- connectors,- is_volume_split: false,- }+ Self { connectors }}}@@ -845,7 +839,6 @@ pub async fn perform_static_routing_locally() -> errors::RouterResult<(Vec<routing_types::RoutableConnectorChoice>,common_enums::RoutingApproach,- bool,)> {let txn_type = routing::transaction_type_from_payments_dsl(payment_dsl_input);@@ -896,8 +889,6 @@ pub async fn perform_static_routing_locally(.await.unwrap_or_else(RoutingConnectorOutcome::empty);- let is_volume_split = outcome.is_volume_split;-let (static_connectors, static_approach) = outcome.resolve_or_fallback_with_approach("static-routing",fallback_config,@@ -908,54 +899,7 @@ pub async fn perform_static_routing_locally(common_enums::RoutingApproach::DefaultFallback,);- Ok((static_connectors, static_approach, is_volume_split))-}--/// Spawns one batch shadow evaluation for a whole session/pre-routing request.-///-/// These flows evaluate per payment method type; the batch keeps that off the request-/// path and down to a single engine round trip. The result is only load-bearing for a-/// cut-over profile -- for everyone else it exists purely for the diff, so the request-/// never waits on it.-#[cfg(feature = "v1")]-fn spawn_session_shadow_batch_evaluation(- state: &SessionState,- business_profile: &domain::Profile,- payment_id: String,- entries: Vec<utils::ShadowBatchEntry>,- fallback_config: Vec<routing_types::RoutableConnectorChoice>,- transaction_type: api_enums::TransactionType,- routing_flow: utils::RoutingFlow,-) {- use router_env::tracing::Instrument;-- let shadow_state = state.clone();- let shadow_profile = business_profile.clone();- let shadow_span = router_env::tracing::info_span!(- "shadow_decision_engine_routing",- de_shadow = true,- routing_flow = routing_flow.as_str(),- entry_count = entries.len(),- profile_id = %business_profile.get_id().get_string_repr(),- merchant_id = %business_profile.merchant_id.get_string_repr(),- payment_id = %payment_id,- );-- tokio::spawn(- async move {- utils::shadow_decision_engine_routing_batch(- shadow_state,- shadow_profile,- payment_id,- entries,- fallback_config,- transaction_type,- routing_flow,- )- .await;- }- .instrument(shadow_span),- );+ Ok((static_connectors, static_approach))}pub struct SessionRoutingInput<'a> {@@ -1012,13 +956,10 @@ impl RoutingStage for SessionRoutingStage {Vec<routing_types::SessionRoutingChoice>,> = FxHashMap::default();- // Both are independent of payment method type, so they are resolved once rather- // than per iteration.+ // Independent of payment method type, so it is resolved once rather than+ // per iteration.let de_routing_effective =utils::is_decision_engine_routing_effective(input.state, input.dimensions).await;- let shadow_evaluation_enabled = input.state.conf.open_router.static_routing_enabled- && input.state.conf.open_router.shadow_routing_enabled- && profile_has_active_routing_algorithm(input.business_profile);// Built up front so the Decision Engine calls can be issued together rather// than one wallet type at a time. A rule may branch on payment method type, so@@ -1038,7 +979,6 @@ impl RoutingStage for SessionRoutingStage {// One batch call for a cut-over profile: the engine fetches the rule once and// evaluates every wallet type's parameters in a single round trip. Against an// engine without the batch endpoint this degrades to concurrent single calls.- // Not cut over, the result is shadow-only and is spawned after the loop.let de_results: Vec<Vec<routing_types::RoutableConnectorChoice>> =if de_routing_effective {utils::decision_engine_routing_batch_with_fallback(@@ -1058,8 +998,6 @@ impl RoutingStage for SessionRoutingStage {vec![Vec::new(); pm_entries.len()]};- let mut shadow_entries: Vec<utils::ShadowBatchEntry> = Vec::new();-for ((pm_type, allowed_connectors, backend_input), de_connectors) inpm_entries.into_iter().zip(de_results){@@ -1121,25 +1059,8 @@ impl RoutingStage for SessionRoutingStage {common_enums::RoutingApproach::DefaultFallback,);- let is_volume_split = matches!(- static_approach,- common_enums::RoutingApproach::VolumeBasedRouting- );-- // The DE result is only load-bearing for a cut-over profile. Everyone else- // gets it shadow-evaluated off the request path, so the diff stays visible- // without adding a round trip to session token generation.+ // The DE result is only load-bearing for a cut-over profile.let chosen_connectors = if de_routing_effective {- // Diff logging only. The kill switch is deliberately not fed from here:- // it gates routing for the whole profile, and tripping it on a- // session-flow discrepancy would disable DE routing for payments too.- utils::compare_and_log_result(- de_connectors.clone(),- chosen_connectors.clone(),- utils::RoutingFlow::SessionToken.as_str().to_string(),- is_volume_split,- );-// Only the connector list is swapped; `RoutingApproach` is left as the// Hyperswitch side derived it, matching `perform_static_routing_v1` --// it is persisted on the attempt and read by analytics, so relabelling@@ -1153,13 +1074,6 @@ impl RoutingStage for SessionRoutingStage {).await} else {- if shadow_evaluation_enabled {- shadow_entries.push(utils::ShadowBatchEntry {- backend_input: backend_input.clone(),- hs_connectors: chosen_connectors.clone(),- is_volume: is_volume_split,- });- }chosen_connectors};@@ -1230,20 +1144,6 @@ impl RoutingStage for SessionRoutingStage {}}- // One spawned batch evaluation for the whole request, replacing a spawned- // call per wallet type. Off the request path; diff logging only.- if !shadow_entries.is_empty() {- spawn_session_shadow_batch_evaluation(- input.state,- input.business_profile,- input.payment_id.clone(),- shadow_entries,- input.default_config.clone(),- *input.transaction_type,- utils::RoutingFlow::SessionToken,- );- }-Ok(RoutingConnectorOutcomeForSessionRouting {session_output: result,routing_approach: final_routing_approach,@@ -1670,8 +1570,6 @@ pub struct HybridRoutingInput<'a> {pub fallback_config: &'a [routing_types::RoutableConnectorChoice],pub static_connectors: &'a [routing_types::RoutableConnectorChoice],pub static_approach: common_enums::RoutingApproach,- /// Whether the HS static selection involved a volume split.- pub static_is_volume_split: bool,}#[cfg(feature = "v1")]@@ -1748,9 +1646,8 @@ impl RoutingStage for HybridRoutingStage {);RoutingConnectorOutcomeWithApproach::empty()} else {- // An unreachable/erroring DE is treated as an empty (unresponsive) outcome so the- // diff is still logged and counted below; the caller falls back to the HS static- // result. This keeps unresponsive-DE handling identical to the static path.+ // An unreachable/erroring DE is treated as an empty outcome; the caller falls+ // back to the HS static result, identical to the static path's handling.let hybrid_outcome = utils::decision_engine_hybrid_routing(input.state,input.business_profile,@@ -1767,15 +1664,6 @@ impl RoutingStage for HybridRoutingStage {utils::HybridRoutingOutcome::empty()});- // Diff logging only — no kill-switch counting: this stage runs solely for- // cut-over profiles, whose DE-only writes make the HS baseline stale by design.- utils::compare_and_log_result(- hybrid_outcome.connectors.clone(),- input.static_connectors.to_vec(),- "evaluate_routing".to_string(),- input.static_is_volume_split,- );-RoutingConnectorOutcomeWithApproach {connectors: hybrid_outcome.connectors,routing_approach: hybrid_outcome.routing_approach.into(),@@ -1816,7 +1704,6 @@ pub async fn perform_hybrid_routing_if_enabled(fallback_config: &[routing_types::RoutableConnectorChoice],static_connectors: &[routing_types::RoutableConnectorChoice],static_approach: common_enums::RoutingApproach,- static_is_volume_split: bool,) -> (Vec<routing_types::RoutableConnectorChoice>,common_enums::RoutingApproach,@@ -1830,12 +1717,10 @@ pub async fn perform_hybrid_routing_if_enabled(fallback_config,static_connectors,static_approach: static_approach.clone(),- static_is_volume_split,};// Flag-aware like every other consumer: with static_routing_enabled off the profile is- // Hyperswitch-routed, so this stage must not run (the kill-switch counting below is- // skipped on the premise that it only ever runs for cut-over profiles).+ // Hyperswitch-routed, so this stage must not run.let is_decision_engine_cutover_enabled =utils::is_decision_engine_routing_effective(state, dimensions).await;let has_active_routing_algorithm = profile_has_active_routing_algorithm(business_profile);@@ -1895,49 +1780,6 @@ pub async fn perform_hybrid_routing_if_enabled("decision_engine_euclid: selected routing source after hybrid stage");- // Shadow mode: diff-check DE against the HS result for non-cutover profiles without- // touching the payment path — detached task, HS result serves the payment either way.- if state.conf.open_router.static_routing_enabled- && state.conf.open_router.shadow_routing_enabled- {- use router_env::tracing::Instrument;-- let payment_id = payment_dsl_input- .payment_attempt- .payment_id- .get_string_repr()- .to_string();- let shadow_state = state.clone();- let shadow_profile = business_profile.clone();- let shadow_backend_input = backend_input.clone();- let shadow_fallback = fallback_config.to_vec();- let shadow_static_connectors = static_connectors.to_vec();- let shadow_span = router_env::tracing::info_span!(- "shadow_decision_engine_routing",- de_shadow = true,- profile_id = %business_profile.get_id().get_string_repr(),- merchant_id = %business_profile.merchant_id.get_string_repr(),- payment_id = %payment_id,- );- tokio::spawn(- async move {- utils::shadow_decision_engine_routing(- shadow_state,- shadow_profile,- payment_id,- shadow_backend_input,- shadow_fallback,- shadow_static_connectors,- static_is_volume_split,- api_enums::TransactionType::Payment,- utils::RoutingFlow::Payment,- )- .await;- }- .instrument(shadow_span),- );- }-(static_connectors.to_vec(), static_approach)}}@@ -1950,28 +1792,17 @@ pub async fn static_routing_v1(let outcome = match routing_algorithm {CachedAlgorithm::Single(conn) => RoutingConnectorOutcome {connectors: vec![(**conn).clone()],- is_volume_split: false,},CachedAlgorithm::Priority(plist) => RoutingConnectorOutcome {connectors: plist.clone(),- is_volume_split: false,},CachedAlgorithm::VolumeSplit(splits) => RoutingConnectorOutcome {connectors: perform_volume_split(splits.to_vec()).change_context(errors::RoutingError::ConnectorSelectionFailed)?,- is_volume_split: true,},- CachedAlgorithm::Advanced(interpreter) => {- let dsl_output = execute_dsl_v1(backend_input, interpreter)?;- let is_volume_split = matches!(- dsl_output,- routing_types::StaticRoutingAlgorithm::VolumeSplit(_)- );- RoutingConnectorOutcome {- connectors: dsl_output_to_connectors(dsl_output)?,- is_volume_split,- }- }+ CachedAlgorithm::Advanced(interpreter) => RoutingConnectorOutcome {+ connectors: execute_dsl_and_get_connector_v1(backend_input, interpreter)?,+ },};Ok(outcome)}@@ -2076,21 +1907,16 @@ pub async fn perform_static_routing_v1(routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data),};- let (- routable_connectors,- routing_approach,- is_volume_split,- de_evaluated_connector,- hs_eval_succeeded,- ) = match backend_input {+ let (routable_connectors, routing_approach, de_evaluated_connector) = match backend_input {Err(err) => {logger::error!(error=?err, "euclid_routing: failed to build routing input, falling back to merchant default connectors");- (fallback_config.clone(), None, false, Vec::default(), false)+ (fallback_config.clone(), None, Vec::default())}Ok(backend_input) => {- // Decision engine evaluation is diagnostic only; errors degrade to an empty result.- let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled {- logger::debug!("decision_engine_euclid: decision_engine routing not enabled");+ // The engine result is load-bearing only for a cut-over profile, so nobody else+ // pays the round trip. Errors degrade to an empty result, which+ // `select_routing_result` answers with the Hyperswitch result.+ let de_evaluated_connector = if !de_routing_effective {Vec::default()} else {utils::decision_engine_routing(@@ -2110,74 +1936,41 @@ pub async fn perform_static_routing_v1(let evaluated = (|| -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>,Option<common_enums::RoutingApproach>,- bool,)> {Ok(match cached_algorithm.as_deref() {// No HS algorithm (cut-over profile): HS side is the fallback list.- None => (fallback_config.clone(), None, false),+ None => (fallback_config.clone(), None),Some(CachedAlgorithm::Single(conn)) => (vec![(**conn).clone()],Some(common_enums::RoutingApproach::StraightThroughRouting),- false,),- Some(CachedAlgorithm::Priority(plist)) => (plist.clone(), None, false),+ Some(CachedAlgorithm::Priority(plist)) => (plist.clone(), None),Some(CachedAlgorithm::VolumeSplit(splits)) => (perform_volume_split(splits.to_vec()).change_context(errors::RoutingError::ConnectorSelectionFailed)?,Some(common_enums::RoutingApproach::VolumeBasedRouting),- true,),- Some(CachedAlgorithm::Advanced(interpreter)) => {- let dsl_output = execute_dsl_v1(backend_input, interpreter)?;- let is_volume_split = matches!(- dsl_output,- routing_types::StaticRoutingAlgorithm::VolumeSplit(_)- );- (- dsl_output_to_connectors(dsl_output)?,- Some(common_enums::RoutingApproach::RuleBasedRouting),- is_volume_split,- )- }+ Some(CachedAlgorithm::Advanced(interpreter)) => (+ execute_dsl_and_get_connector_v1(backend_input, interpreter)?,+ Some(common_enums::RoutingApproach::RuleBasedRouting),+ ),})})();- let hs_eval_succeeded = evaluated.is_ok();- let (routable_connectors, routing_approach, is_volume_split) = evaluated+ let (routable_connectors, routing_approach) = evaluated.unwrap_or_else(|err| {logger::error!(error=?err, "euclid_routing: algorithm evaluation failed, falling back to merchant default connectors");- (fallback_config.clone(), None, false)+ (fallback_config.clone(), None)});(routable_connectors,routing_approach,- is_volume_split,de_evaluated_connector,- hs_eval_succeeded,)}};- // Always diff-log (dashboards consume this for cut-over profiles too), but feed the- // kill switch only from a successfully evaluated HS algorithm on a non-cut-over- // profile — under DE-only writes the HS baseline is stale by design.- let comparison = utils::compare_and_log_result(- de_evaluated_connector.clone(),- routable_connectors.clone(),- utils::RoutingFlow::Payment.as_str().to_string(),- is_volume_split,- );-- if cached_algorithm.is_some() && hs_eval_succeeded && !de_routing_effective {- utils::record_de_diff_and_maybe_trip_kill_switch(- state,- business_profile.get_id(),- comparison,- )- .await;- }-Ok((utils::select_routing_result(state,@@ -3222,14 +3015,8 @@ pub async fn perform_session_flow_routing(}).collect::<Vec<_>>();- // Not cut over, the evaluation is shadow-only and off the request path.- let collect_shadow_entries = !de_routing_effective- && session_input.state.conf.open_router.static_routing_enabled- && session_input.state.conf.open_router.shadow_routing_enabled- && profile_has_active_routing_algorithm(business_profile);-// Same list for every wallet type, so it is fetched once rather than per iteration.- let de_fallback_config = if de_routing_effective || collect_shadow_entries {+ let de_fallback_config = if de_routing_effective {routing::helpers::get_merchant_default_config(&*session_input.state.clone().store,profile_id.get_string_repr(),@@ -3253,7 +3040,7 @@ pub async fn perform_session_flow_routing(.collect(),business_profile,payment_id.clone(),- de_fallback_config.clone(),+ de_fallback_config,*transaction_type,utils::RoutingFlow::PaymentMethodList,)@@ -3262,8 +3049,6 @@ pub async fn perform_session_flow_routing(vec![Vec::new(); pm_entries.len()]};- let mut shadow_entries: Vec<utils::ShadowBatchEntry> = Vec::new();-for ((pm_type, allowed_connectors, backend_input), de_connectors) inpm_entries.into_iter().zip(de_results){@@ -3279,7 +3064,7 @@ pub async fn perform_session_flow_routing(payment_id: payment_id.clone(),};- let (routable_connector_choice_option, routing_approach, shadow_entry) =+ let (routable_connector_choice_option, routing_approach) =perform_session_routing_for_pm_type(&session_pm_input,transaction_type,@@ -3287,14 +3072,9 @@ pub async fn perform_session_flow_routing(&active_mca_ids,de_routing_effective,de_connectors,- collect_shadow_entries,).await?;- if let Some(entry) = shadow_entry {- shadow_entries.push(entry);- }-final_routing_approach = routing_approach;if let Some(routable_connector_choice) = routable_connector_choice_option {@@ -3326,25 +3106,10 @@ pub async fn perform_session_flow_routing(}}- // One spawned batch evaluation for the whole request, replacing a spawned call per- // wallet type. Off the request path; diff logging only.- if !shadow_entries.is_empty() {- spawn_session_shadow_batch_evaluation(- session_input.state,- business_profile,- payment_id,- shadow_entries,- de_fallback_config,- *transaction_type,- utils::RoutingFlow::PaymentMethodList,- );- }-Ok((result, final_routing_approach))}#[cfg(feature = "v1")]-#[allow(clippy::too_many_arguments)]async fn perform_session_routing_for_pm_type(session_pm_input: &SessionRoutingPmTypeInput<'_>,transaction_type: &api_enums::TransactionType,@@ -3352,11 +3117,9 @@ async fn perform_session_routing_for_pm_type(active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,de_routing_effective: bool,de_connectors: Vec<api_models::routing::RoutableConnectorChoice>,- collect_shadow_entry: bool,) -> RoutingResult<(Option<Vec<api_models::routing::RoutableConnectorChoice>>,Option<common_enums::RoutingApproach>,- Option<utils::ShadowBatchEntry>,)> {let merchant_id = &session_pm_input.key_store.merchant_id;@@ -3413,24 +3176,8 @@ async fn perform_session_routing_for_pm_type((fallback_config.clone(), None)};- let is_volume_split = matches!(- routing_approach,- Some(common_enums::RoutingApproach::VolumeBasedRouting)- );-- // Load-bearing only for a cut-over profile; everyone else gets it shadow-evaluated off- // the request path, so the diff stays visible without adding a round trip per wallet- // type to the payment method list.+ // The DE result is only load-bearing for a cut-over profile.let chosen_connectors = if de_routing_effective {- // Diff logging only; see the note in `SessionRoutingStage` on why the kill switch- // is not fed from these flows.- utils::compare_and_log_result(- de_connectors.clone(),- chosen_connectors.clone(),- utils::RoutingFlow::PaymentMethodList.as_str().to_string(),- is_volume_split,- );-// Connector list only; see the note in `SessionRoutingStage` on why// `routing_approach` is left untouched.utils::select_routing_result(@@ -3445,14 +3192,6 @@ async fn perform_session_routing_for_pm_type(chosen_connectors};- // Handed back to the caller, which shadow-evaluates the whole request in one- // spawned batch instead of one task per wallet type.- let shadow_entry = collect_shadow_entry.then(|| utils::ShadowBatchEntry {- backend_input: session_pm_input.backend_input.clone(),- hs_connectors: chosen_connectors.clone(),- is_volume: is_volume_split,- });-let mut final_selection = perform_cgraph_filtering(&session_pm_input.state.clone(),session_pm_input.key_store,@@ -3488,9 +3227,9 @@ async fn perform_session_routing_for_pm_type(}if final_selection.is_empty() {- Ok((None, routing_approach, shadow_entry))+ Ok((None, routing_approach))} else {- Ok((Some(final_selection), routing_approach, shadow_entry))+ Ok((Some(final_selection), routing_approach))}}diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex a26a9c3312..48d4955bf8 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -715,9 +715,9 @@ pub fn transform_de_output_for_router(/// Which call site produced a Decision Engine evaluation.///-/// Carried into the routing event and the Hyperswitch/DE diff log so the three flows-/// can be told apart -- previously all three logged under the same name, which made a-/// session-flow discrepancy indistinguishable from a payment one.+/// Carried into the routing event so the three flows can be told apart -- previously+/// all three logged under the same name, which made a session-flow discrepancy+/// indistinguishable from a payment one.#[derive(Debug, Clone, Copy)]pub enum RoutingFlow {Payment,@@ -726,17 +726,8 @@ pub enum RoutingFlow {}impl RoutingFlow {- /// Label used in the HS/DE diff log. `Payment` keeps its historical value so- /// existing queries over that log keep working.- pub fn as_str(self) -> &'static str {- match self {- Self::Payment => "evaluate_routing",- Self::SessionToken => "session_token_routing",- Self::PaymentMethodList => "payment_method_list_pre_routing",- }- }-- /// Name recorded on the routing event. `Payment` is unchanged for the same reason.+ /// Name recorded on the routing event. `Payment` keeps its historical value so+ /// existing queries over these events keep working.fn event_name(self) -> String {match self {Self::Payment => "DecisionEngine: Euclid Static Routing".to_string(),@@ -1143,251 +1134,6 @@ pub async fn list_de_euclid_active_routing_algorithm(.collect())}-/// Outcome of a DE-vs-HS routing comparison, used to drive the diff kill switch.-#[derive(Debug, Clone, Copy)]-pub struct DeComparisonResult {- pub is_equal: bool,- pub is_equal_length: bool,- pub is_volume: bool,- pub is_de_result_empty: bool,-}--/// Classification of a countable DE-vs-HS divergence, also used as the log/metric tag.-#[derive(Debug, Clone, Copy)]-enum DeDiffReason {- ResultMismatch,- LengthMismatch,- Unresponsive,-}--impl DeDiffReason {- fn as_str(self) -> &'static str {- match self {- Self::ResultMismatch => "decision_engine_result_mismatch",- Self::LengthMismatch => "decision_engine_length_mismatch",- Self::Unresponsive => "decision_engine_unresponsive",- }- }-}--impl DeComparisonResult {- /// Why this comparison counts toward the kill switch, if it does (empty DE result => `Unresponsive`).- fn diff_reason(self) -> Option<DeDiffReason> {- if self.is_equal {- None- } else if self.is_de_result_empty {- Some(DeDiffReason::Unresponsive)- } else if !self.is_equal_length {- Some(DeDiffReason::LengthMismatch)- } else {- Some(DeDiffReason::ResultMismatch)- }- }-}--pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(- de_result: Vec<T>,- result: Vec<T>,- flow: String,- is_volume: bool,-) -> DeComparisonResult {- let is_de_result_empty = de_result.is_empty();- let is_equal_in_length = de_result.len() == result.len();- // Equal means identical: same length AND same elements in order — an empty or- // prefix-only DE result is not equal (zip alone would be vacuously true).- let is_equal = is_equal_in_length- && de_result- .iter()- .zip(result.iter())- .all(|(a, b)| T::is_equal(a, b));-- router_env::logger::debug!(- routing_flow=?flow,- is_equal=?is_equal,- is_equal_length=?is_equal_in_length,- is_volume=?is_volume,- is_de_result_empty=?is_de_result_empty,- de_response=?to_json_string(&de_result),- hs_response=?to_json_string(&result),- "decision_engine_euclid"- );-- DeComparisonResult {- is_equal,- is_equal_length: is_equal_in_length,- is_volume,- is_de_result_empty,- }-}--fn de_diff_count_key(profile_id: &id_type::ProfileId) -> String {- format!(- "routing_decision_engine_{}_diff_count",- profile_id.get_string_repr()- )-}--/// Clears the per-profile routing diff counter, releasing the kill-switch overlay (reset API).-pub async fn reset_de_diff_counter(- state: &SessionState,- profile_id: &id_type::ProfileId,-) -> errors::RouterResult<()> {- let redis_conn = state- .store- .get_redis_conn()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to get redis connection to reset routing diff counter")?;-- redis_conn- .delete_key(&de_diff_count_key(profile_id).as_str().into())- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to delete routing diff counter key")?;-- Ok(())-}--/// Counts a non-volume DE-vs-HS diff and cuts the profile over to Hyperswitch at the threshold.-pub async fn record_de_diff_and_maybe_trip_kill_switch(- state: &SessionState,- profile_id: &id_type::ProfileId,- comparison: DeComparisonResult,-) {- let config = &state.conf.open_router.diff_kill_switch;- let countable_reason = match comparison.diff_reason() {- Some(reason) if config.enabled && !comparison.is_volume => Some(reason),- _ => None,- };-- if let Some(reason) = countable_reason {- // Treat a zero threshold as 1 so the one-shot cutover log/metric below still fires.- let threshold = config.diff_count_threshold.max(1);-- logger::warn!(- routing_flow=?"evaluate_routing",- profile_id=?profile_id.get_string_repr(),- "{}: counting routing diff towards the kill switch threshold",- reason.as_str()- );-- metrics::DECISION_ENGINE_ROUTING_DIFF.add(- 1,- router_env::metric_attributes!(- ("profile_id", profile_id.get_string_repr().to_string()),- ("reason", reason.as_str())- ),- );-- match state.store.get_redis_conn() {- Ok(redis_conn) => {- let counter_key = de_diff_count_key(profile_id);- let increment_result = redis_conn- .increment_fields_in_hash(&counter_key.as_str().into(), &[("count", 1)])- .await;-- match increment_result.as_ref().map(|counts| counts.first()) {- Ok(Some(count)) => {- let diff_count = u64::try_from(*count).unwrap_or(u64::MAX);-- // The counter is a lifetime total (no TTL) and is cleared only via the- // diff-counter reset API. HINCRBY is atomic and sequential, so exactly- // one request observes the threshold value; the cutover alarm fires- // once. Enforcement is passive from here — the counter stays at/over- // threshold and get_routing_result_source overlays Hyperswitch routing.- if diff_count == threshold {- alert_cutover(profile_id, diff_count, threshold);- }- }- Ok(None) => {- logger::error!("decision_engine_euclid: empty response while incrementing routing diff counter");- }- Err(err) => {- logger::error!(error=?err, "decision_engine_euclid: failed to increment routing diff counter");- }- }- }- Err(err) => {- logger::error!(error=?err, "decision_engine_euclid: unable to get redis connection to record routing diff");- }- }- }-}--/// One-shot cutover alarm on the threshold-crossing diff (enforcement is the passive overlay in `get_routing_result_source`).-fn alert_cutover(profile_id: &id_type::ProfileId, diff_count: u64, threshold: u64) {- metrics::DECISION_ENGINE_KILL_SWITCH_TRIGGERED.add(- 1,- router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())),- );- router_env::logger::error!(- routing_flow=?"auto_cutover",- profile_id=?profile_id.get_string_repr(),- diff_count=?diff_count,- threshold=?threshold,- "decision_engine_euclid: routing diff threshold breached, cutting profile over to Hyperswitch routing"- );-}--/// Whether the profile's diff counter has reached the threshold; fail-open (disabled switch or any Redis error => false).-async fn is_de_diff_threshold_exceeded(- state: &SessionState,- profile_id: &id_type::ProfileId,-) -> bool {- let config = &state.conf.open_router.diff_kill_switch;- if config.enabled {- match state.store.get_redis_conn() {- Ok(redis_conn) => match redis_conn- .get_hash_field::<Option<u64>>(- &de_diff_count_key(profile_id).as_str().into(),- "count",- )- .await- {- Ok(count) => count.unwrap_or(0) >= config.diff_count_threshold.max(1),- Err(err) => {- logger::error!(error=?err, "decision_engine_euclid: kill switch counter lookup failed, using configured routing source");- false- }- },- Err(err) => {- logger::error!(error=?err, "decision_engine_euclid: unable to get redis connection for kill switch check");- false- }- }- } else {- false- }-}--/// Shadow-evaluates the DE rule off the payment path and logs the DE-vs-HS diff (observation-only, never feeds the kill switch).-#[allow(clippy::too_many_arguments)]-pub async fn shadow_decision_engine_routing(- state: SessionState,- business_profile: domain::Profile,- payment_id: String,- backend_input: BackendInput,- fallback_config: Vec<RoutableConnectorChoice>,- hs_connectors: Vec<RoutableConnectorChoice>,- is_volume: bool,- algorithm_for: TransactionType,- routing_flow: RoutingFlow,-) {- let de_result =- decision_engine_routing(&state, backend_input, &business_profile, payment_id, fallback_config, algorithm_for, routing_flow)- .await- .map_err(|err| {- logger::error!(shadow_decision_engine_error=?err, "decision_engine_euclid: error in shadow evaluation of rule")- })- .unwrap_or_default();-- compare_and_log_result(- de_result,- hs_connectors,- routing_flow.as_str().to_string(),- is_volume,- );-}-/// One evaluation in a batch request: the parameters that differ per call./// Everything shared (`created_by`, fallback, transaction type) lives on the/// enclosing request, matching the Decision Engine's `/routing/evaluate/batch`.@@ -1590,109 +1336,6 @@ pub async fn decision_engine_routing_batch_with_fallback(}}-/// One shadow comparison: the per-type input and the Hyperswitch result to diff against.-pub struct ShadowBatchEntry {- pub backend_input: BackendInput,- pub hs_connectors: Vec<RoutableConnectorChoice>,- pub is_volume: bool,-}--/// Shadow-evaluates a whole session/PML request in one batch call and logs one diff-/// per payment method type. Observation only; never feeds the kill switch.-#[allow(clippy::too_many_arguments)]-pub async fn shadow_decision_engine_routing_batch(- state: SessionState,- business_profile: domain::Profile,- payment_id: String,- entries: Vec<ShadowBatchEntry>,- fallback_config: Vec<RoutableConnectorChoice>,- algorithm_for: TransactionType,- routing_flow: RoutingFlow,-) {- let backend_inputs = entries- .iter()- .map(|entry| entry.backend_input.clone())- .collect::<Vec<_>>();-- // No single-call fallback here, deliberately: the events layer surfaces every- // engine failure without a status code, so "endpoint absent" cannot be told apart- // from "this merchant has no active rule" -- and for the latter, N single calls- // fail identically to the batch. A failed shadow batch just logs empty diffs.- // The load-bearing cut-over path keeps the fallback, which is what protects the- // window where the engine predates the batch endpoint.- let entry_count = entries.len();- let de_results = decision_engine_routing_batch(- &state,- backend_inputs,- &business_profile,- payment_id,- fallback_config,- algorithm_for,- routing_flow,- )- .await- .map_err(|error| {- logger::warn!(- ?error,- "decision_engine_euclid: shadow batch evaluate failed"- );- })- .unwrap_or_else(|_| vec![Vec::new(); entry_count]);-- for (entry, de_result) in entries.into_iter().zip(de_results) {- compare_and_log_result(- de_result,- entry.hs_connectors,- routing_flow.as_str().to_string(),- entry.is_volume,- );- }-}--pub trait RoutingEq<T> {- fn is_equal(a: &T, b: &T) -> bool;-}--impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord {- fn is_equal(a: &Self, b: &Self) -> bool {- a.id == b.id- && a.name == b.name- && a.profile_id == b.profile_id- && a.description == b.description- && a.kind == b.kind- && a.algorithm_for == b.algorithm_for- }-}--impl RoutingEq<Self> for String {- fn is_equal(a: &Self, b: &Self) -> bool {- a.to_lowercase() == b.to_lowercase()- }-}--impl RoutingEq<Self> for RoutableConnectorChoice {- fn is_equal(a: &Self, b: &Self) -> bool {- a.connector.eq(&b.connector)- && a.choice_kind.eq(&b.choice_kind)- && a.merchant_connector_id.eq(&b.merchant_connector_id)- }-}--pub fn to_json_string<T: Serialize>(value: &T) -> String {- serde_json::to_string(value)- .map_err(|error| {- logger::error!(- error=?error,- "euclid: failed to serialize value to json string"- );- errors::RoutingError::GenericConversionError {- from: "T".to_string(),- to: "JsonValue".to_string(),- }- })- .unwrap_or_default()-}-#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]pub struct ActivateRoutingConfigRequest {pub created_by: String,@@ -2641,36 +2284,13 @@ pub async fn get_routing_result_source(dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,) -> api_routing::RoutingResultSource {// No customer_id and payment_id in call sites so passing Targeting key as None.- let source = dimensions+ dimensions.get_routing_result_source(state.store.as_ref(),state.superposition_service.as_ref(),None,)- .await;-- // Overlay Hyperswitch routing when the diff counter is at/over threshold, without mutating the stored source (covers routing + dashboard, both resolve here).- let overlay_hyperswitch = matches!(source, api_routing::RoutingResultSource::DecisionEngine)- && match dimensions.get_profile_id() {- Some(profile_id) => {- let exceeded = is_de_diff_threshold_exceeded(state, profile_id).await;- if exceeded {- logger::info!(- routing_flow=?"kill_switch_active",- profile_id=?profile_id.get_string_repr(),- "decision_engine_euclid: diff threshold reached, overlaying Hyperswitch routing result"- );- }- exceeded- }- None => false,- };-- if overlay_hyperswitch {- api_routing::RoutingResultSource::HyperswitchRouting- } else {- source- }+ .await}/// Effective cutover routing_result_source is DecisionEngine and either global routing flag (static or dynamic) is on - the flags always win, for APIs and payment paths alike.@@ -3066,19 +2686,6 @@ impl RoutingApproach {_ => Self::Default,}}-- /// Only DE static outcomes are diff-comparable; unmapped dynamic approaches land on- /// `Default` and must not feed the kill switch.- pub fn is_de_static_result(&self) -> bool {- match self {- Self::StaticRouting => true,- Self::Exploitation- | Self::Exploration- | Self::Elimination- | Self::ContractBased- | Self::Default => false,- }- }}impl From<RoutingApproach> for common_enums::RoutingApproach {diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 50a1f8123b..797364a93e 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -696,13 +696,6 @@ async fn merge_de_routing_records(.filter(|record| record.kind == routing_types::RoutingAlgorithmKind::Dynamic).cloned(),);- compare_and_log_result(- de_result.clone(),- hs_result.clone(),- "list_routing".to_string(),- false,- );-let mut merged = build_list_routing_result(state,platform.clone(),@@ -2291,12 +2284,6 @@ pub async fn retrieve_linked_routing_config(&transaction_type,hs_records.clone(),);- compare_and_log_result(- de_records.clone(),- hs_records.clone(),- "list_active_routing".to_string(),- false,- );let dimensions = dimension_state::Dimensions::new().with_provider_merchant_id(platform.get_provider().get_provider_merchant_id()).with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())@@ -3350,22 +3337,6 @@ impl RoutableConnectors {}}-/// Clears the Decision Engine routing diff kill-switch counter for a profile, so the switch can-/// trip again after the profile is re-enabled for the Decision Engine.-pub async fn reset_decision_engine_diff_counter(- state: SessionState,- profile_id: common_utils::id_type::ProfileId,-) -> RouterResult<service_api::ApplicationResponse<()>> {- reset_de_diff_counter(&state, &profile_id).await?;-- router_env::logger::info!(- profile_id=?profile_id.get_string_repr(),- "decision_engine_euclid: routing diff counter reset via api"- );-- Ok(service_api::ApplicationResponse::StatusOk)-}-/// A merchant account and its key store, by id. Migration works from/// `routing_algorithm.merchant_id` rather than an authenticated context, so it resolves its own.async fn get_merchant_account(@@ -3882,9 +3853,7 @@ pub async fn routing_migration_status(only_in_de.sort();}- // The *configured* cut-over. `get_routing_result_source` would overlay Hyperswitch- // routing when the diff counter is over threshold — right for a payment, wrong here: a- // tripped kill switch would turn a runtime condition into a migration verdict.+ // The configured cut-over source for this profile.let dimensions = dimension_state::Dimensions::new().with_processor_merchant_id(merchant_id.clone().into()).with_provider_merchant_id(diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex ca626629e0..a0e89aec16 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1180,10 +1180,6 @@ impl Routing {let mut route = web::scope("/routing").app_data(web::Data::new(state.clone())).service(web::resource("/entry").route(web::post().to(routing::routing_entry)))- .service(- web::resource("/decision-engine/{profile_id}/diff-counter")- .route(web::delete().to(routing::reset_decision_engine_diff_counter)),- ).service(web::resource("/active").route(web::get().to(|state, req, query_params| {routing::routing_retrieve_linked_config(state, req, query_params, None)diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex c7ced9669a..45e7cc6359 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -93,7 +93,6 @@ impl From<Flow> for ApiIdentifier {| Flow::UpdateDynamicRoutingConfigs| Flow::DecisionManagerUpsertConfig| Flow::RoutingEvaluateRule- | Flow::DecisionEngineDiffCounterReset| Flow::DecisionEngineRuleMigration| Flow::DecisionEngineMigrationStatus| Flow::VolumeSplitOnRoutingTypediff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rsindex b9b71454df..2bf435d1e4 100644--- a/crates/router/src/routes/routing.rs+++ b/crates/router/src/routes/routing.rs@@ -1773,26 +1773,6 @@ pub async fn migrate_routing_rules(.await}-#[instrument(skip_all, fields(flow = ?Flow::DecisionEngineDiffCounterReset))]-pub async fn reset_decision_engine_diff_counter(- state: web::Data<AppState>,- req: HttpRequest,- path: web::Path<common_utils::id_type::ProfileId>,-) -> impl Responder {- let flow = Flow::DecisionEngineDiffCounterReset;- let profile_id = path.into_inner();- Box::pin(oss_api::server_wrap(- flow,- state,- &req,- profile_id.clone(),- |state, _, profile_id, _| routing::reset_decision_engine_diff_counter(state, profile_id),- &auth::AdminApiAuth,- api_locking::LockAction::NotApplicable,- ))- .await-}-#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]#[instrument(skip_all)]pub async fn call_decide_gateway_open_router(diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex ce10484817..7eb73e963c 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -679,8 +679,6 @@ pub enum Flow {VolumeSplitOnRoutingType,/// Routing evaluate rule flowRoutingEvaluateRule,- /// Reset the Decision Engine routing diff kill-switch counter for a profile- DecisionEngineDiffCounterReset,/// Report whether the Unified Connector Service kill switch has tripped a scopeUnifiedConnectorServiceKillSwitchStatus,/// Clear a Unified Connector Service kill switch cutover