Skip to content

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

feat(routing): add automatic kill switch for decision engine routing diffs (#13564)

Prajjwal Kumar89979d622b55
diff --git a/config/config.example.toml b/config/config.example.toml
index 9100d7f078..7e943c17cc 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1423,10 +1423,15 @@ billing_connectors_which_require_payment_sync = "stripebilling, recurly" # List
[open_router]
dynamic_routing_enabled = true # Enable or disable Open Router for dynamic routing
static_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_enabled
url = "http://localhost:8080" # Open Router URL
dashboard_url = "http://localhost:5173" # Decision Engine dashboard (browser) URL for merchant SSO redirect
admin_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 URL
connection_timeout = 10 # Connection Timeout Duration in Seconds
diff --git a/config/development.toml b/config/development.toml
index 219115a05b..7275ce000c 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1559,10 +1559,15 @@ connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"
[open_router]
dynamic_routing_enabled = false
static_routing_enabled = false
+shadow_routing_enabled = false
url = "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.rs
index e760d28e60..d7b817c026 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -417,6 +417,13 @@ 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)]
@@ -429,6 +436,24 @@ 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.rs
index 80eae04dd3..18b70053ca 100644
--- a/crates/router/src/core/metrics.rs
+++ b/crates/router/src/core/metrics.rs
@@ -91,6 +91,8 @@ 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);
#[cfg(feature = "partial-auth")]
counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER);
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 2123b1dc8d..3fc2fff77b 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -12970,14 +12970,15 @@ 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) = routing::perform_static_routing_locally(
- state,
- business_profile,
- &payment_dsl_input,
- &backend_input,
- &fallback_config,
- )
- .await?;
+ 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 (connectors, routing_approach) = routing::perform_hybrid_routing_if_enabled(
state,
@@ -12988,6 +12989,7 @@ 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.rs
index 10b027bb41..4975d1bf6f 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -707,6 +707,8 @@ 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 {
@@ -743,13 +745,17 @@ 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 }
+ Self {
+ connectors,
+ is_volume_split: false,
+ }
}
}
@@ -807,13 +813,10 @@ impl RoutingStage for StaticRoutingStage {
fn route<'a>(&'a self, input: Self::Input<'a>) -> Self::Fut<'a> {
Box::pin(async move {
- let connectors =
- static_routing_v1(&self.ctx.routing_algorithm, input.backend_input.clone())
- .await
- .change_context(errors::RoutingError::DslExecutionError)
- .attach_printable("euclid: unable to perform static routing locally")?;
-
- Ok(RoutingConnectorOutcome { connectors })
+ static_routing_v1(&self.ctx.routing_algorithm, input.backend_input.clone())
+ .await
+ .change_context(errors::RoutingError::DslExecutionError)
+ .attach_printable("euclid: unable to perform static routing locally")
})
}
@@ -832,6 +835,7 @@ 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);
@@ -865,7 +869,7 @@ pub async fn perform_static_routing_locally(
},
});
- let (static_connectors, static_approach) = static_stage
+ let outcome = static_stage
.clone()
.async_and_then(|static_stage| async move {
static_stage
@@ -878,23 +882,23 @@ pub async fn perform_static_routing_locally(
);
})
.ok()
- .map(|outcome| RoutingConnectorOutcome {
- connectors: outcome.connectors,
- })
})
.await
- .unwrap_or_else(RoutingConnectorOutcome::empty)
- .resolve_or_fallback_with_approach(
- "static-routing",
- fallback_config,
- static_stage
- .as_ref()
- .map(|s| s.routing_approach())
- .unwrap_or(common_enums::RoutingApproach::DefaultFallback),
- common_enums::RoutingApproach::DefaultFallback,
- );
+ .unwrap_or_else(RoutingConnectorOutcome::empty);
- Ok((static_connectors, static_approach))
+ let is_volume_split = outcome.is_volume_split;
+
+ let (static_connectors, static_approach) = outcome.resolve_or_fallback_with_approach(
+ "static-routing",
+ fallback_config,
+ static_stage
+ .as_ref()
+ .map(|s| s.routing_approach())
+ .unwrap_or(common_enums::RoutingApproach::DefaultFallback),
+ common_enums::RoutingApproach::DefaultFallback,
+ );
+
+ Ok((static_connectors, static_approach, is_volume_split))
}
pub struct SessionRoutingInput<'a> {
@@ -998,9 +1002,6 @@ impl RoutingStage for SessionRoutingStage {
);
})
.ok()
- .map(|outcome| RoutingConnectorOutcome {
- connectors: outcome.connectors,
- })
})
.await
.unwrap_or_else(RoutingConnectorOutcome::empty)
@@ -1387,6 +1388,8 @@ 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")]
@@ -1523,6 +1526,9 @@ 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.
let hybrid_outcome = utils::decision_engine_hybrid_routing(
input.state,
input.business_profile,
@@ -1533,15 +1539,34 @@ impl RoutingStage for HybridRoutingStage {
},
input.static_connectors.to_vec(),
)
- .await?;
+ .await
+ .unwrap_or_else(|error| {
+ logger::error!(error=?error, "euclid: hybrid DE evaluation failed, treating as unresponsive");
+ utils::HybridRoutingOutcome::empty()
+ });
// Keep legacy diff/selection logs for dashboard compatibility.
// Routing behavior remains hybrid-first; this is logging-only parity.
- utils::compare_and_log_result(
+ let comparison = utils::compare_and_log_result(
hybrid_outcome.connectors.clone(),
input.static_connectors.to_vec(),
"evaluate_routing".to_string(),
+ input.static_is_volume_split,
);
+
+ // Dynamic DE selections legitimately reorder connectors; count static
+ // outcomes, plus empty ones so an unresponsive DE feeds the kill switch.
+ if hybrid_outcome.routing_approach.is_de_static_result()
+ || comparison.is_de_result_empty
+ {
+ utils::record_de_diff_and_maybe_trip_kill_switch(
+ input.state,
+ input.business_profile.get_id(),
+ comparison,
+ )
+ .await;
+ }
+
RoutingConnectorOutcomeWithApproach {
connectors: hybrid_outcome.connectors,
routing_approach: hybrid_outcome.routing_approach.into(),
@@ -1568,6 +1593,7 @@ 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,
@@ -1581,6 +1607,7 @@ pub async fn perform_hybrid_routing_if_enabled(
fallback_config,
static_connectors,
static_approach: static_approach.clone(),
+ static_is_volume_split,
};
let is_decision_engine_cutover_enabled = matches!(
@@ -1627,6 +1654,37 @@ pub async fn perform_hybrid_routing_if_enabled(
routing_source = "hyperswitch_static",
"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
+ {
+ 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();
+
+ 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,
+ )
+ .await;
+ });
+ }
+
(static_connectors.to_vec(), static_approach)
}
}
@@ -1634,18 +1692,35 @@ pub async fn perform_hybrid_routing_if_enabled(
pub async fn static_routing_v1(
routing_algorithm: &CachedAlgorithm,
backend_input: backend::BackendInput,
-) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
+) -> RoutingResult<RoutingConnectorOutcome> {
logger::debug!("euclid_routing: performing routing for connector selection");
- let routable_connectors = match routing_algorithm {
- CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
- CachedAlgorithm::Priority(plist) => plist.clone(),
- CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())
- .change_context(errors::RoutingError::ConnectorSelectionFailed)?,
+ 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) => {
- execute_dsl_and_get_connector_v1(backend_input, 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,
+ }
}
};
- Ok(routable_connectors)
+ Ok(outcome)
}
pub async fn perform_static_routing_v1(
@@ -1704,12 +1779,6 @@ pub async fn perform_static_routing_v1(
}
};
- let backend_input = match transaction_data {
- routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
- #[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
- };
-
let payment_id = match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_attempt
@@ -1725,55 +1794,97 @@ pub async fn perform_static_routing_v1(
.to_string(),
};
- // Decision of de-routing is stored
- let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled {
- logger::debug!("decision_engine_euclid: decision_engine routing not enabled");
- Vec::default()
- } else {
- utils::decision_engine_routing(
- state,
- backend_input.clone(),
- business_profile,
- payment_id,
- fallback_config,
- )
- .await
- .map_err(|e|
- // errors are ignored as this is just for diff checking as of now (optional flow).
- logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule")
- )
- .unwrap_or_default()
+ // A routing failure must never fail the payment: any error building the routing input, or
+ // evaluating the active algorithm, falls back to the merchant default connectors.
+ let backend_input = match transaction_data {
+ routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data),
+ #[cfg(feature = "payouts")]
+ routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data),
};
- let (routable_connectors, routing_approach) = match cached_algorithm.as_ref() {
- CachedAlgorithm::Single(conn) => (
- vec![(**conn).clone()],
- Some(common_enums::RoutingApproach::StraightThroughRouting),
- ),
- CachedAlgorithm::Priority(plist) => (plist.clone(), None),
- CachedAlgorithm::VolumeSplit(splits) => (
- perform_volume_split(splits.to_vec())
- .change_context(errors::RoutingError::ConnectorSelectionFailed)?,
- Some(common_enums::RoutingApproach::VolumeBasedRouting),
- ),
- CachedAlgorithm::Advanced(interpreter) => (
- execute_dsl_and_get_connector_v1(backend_input, interpreter)?,
- Some(common_enums::RoutingApproach::RuleBasedRouting),
- ),
- };
+ let (routable_connectors, routing_approach, is_volume_split, 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())
+ }
+ 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");
+ Vec::default()
+ } else {
+ utils::decision_engine_routing(
+ state,
+ backend_input.clone(),
+ business_profile,
+ payment_id,
+ fallback_config.clone(),
+ )
+ .await
+ .map_err(|e| logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule"))
+ .unwrap_or_default()
+ };
- // Results are logged for diff(between legacy and decision_engine's euclid) and have parameters as:
- // is_equal: verifies all output are matching in order,
- // is_equal_length: matches length of both outputs (useful for verifying volume based routing
- // results)
- // de_response: response from the decision_engine's euclid
- // hs_response: response from legacy_euclid
- utils::compare_and_log_result(
+ let evaluated = (|| -> RoutingResult<(
+ Vec<routing_types::RoutableConnectorChoice>,
+ Option<common_enums::RoutingApproach>,
+ bool,
+ )> {
+ Ok(match cached_algorithm.as_ref() {
+ CachedAlgorithm::Single(conn) => (
+ vec![(**conn).clone()],
+ Some(common_enums::RoutingApproach::StraightThroughRouting),
+ false,
+ ),
+ CachedAlgorithm::Priority(plist) => (plist.clone(), None, false),
+ CachedAlgorithm::VolumeSplit(splits) => (
+ perform_volume_split(splits.to_vec())
+ .change_context(errors::RoutingError::ConnectorSelectionFailed)?,
+ Some(common_enums::RoutingApproach::VolumeBasedRouting),
+ true,
+ ),
+ 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,
+ )
+ }
+ })
+ })();
+
+ let (routable_connectors, routing_approach, is_volume_split) = 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)
+ });
+
+ (
+ routable_connectors,
+ routing_approach,
+ is_volume_split,
+ de_evaluated_connector,
+ )
+ }
+ };
+
+ // Diff-logged (is_equal / is_equal_length / is_volume) and fed to the kill switch.
+ let comparison = utils::compare_and_log_result(
de_evaluated_connector.clone(),
routable_connectors.clone(),
"evaluate_routing".to_string(),
+ is_volume_split,
);
+ utils::record_de_diff_and_maybe_trip_kill_switch(state, business_profile.get_id(), comparison)
+ .await;
+
Ok((
utils::select_routing_result(
state,
@@ -1893,15 +2004,19 @@ pub fn perform_routing_for_single_straight_through_algorithm(
})
}
-fn execute_dsl_and_get_connector_v1(
+fn execute_dsl_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
-) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- let routing_output: routing_types::StaticRoutingAlgorithm = interpreter
+) -> RoutingResult<routing_types::StaticRoutingAlgorithm> {
+ interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
- .change_context(errors::RoutingError::DslExecutionError)?;
+ .change_context(errors::RoutingError::DslExecutionError)
+}
+fn dsl_output_to_connectors(
+ routing_output: routing_types::StaticRoutingAlgorithm,
+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
Ok(match routing_output {
routing_types::StaticRoutingAlgorithm::Priority(plist) => plist,
@@ -1913,6 +2028,13 @@ fn execute_dsl_and_get_connector_v1(
})
}
+fn execute_dsl_and_get_connector_v1(
+ backend_input: dsl_inputs::BackendInput,
+ interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
+ dsl_output_to_connectors(execute_dsl_v1(backend_input, interpreter)?)
+}
+
pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs
index f00217bc6c..5c35115300 100644
--- a/crates/router/src/core/payments/routing/utils.rs
+++ b/crates/router/src/core/payments/routing/utils.rs
@@ -91,6 +91,16 @@ pub struct HybridRoutingOutcome {
pub routing_approach: RoutingApproach,
}
+impl HybridRoutingOutcome {
+ /// Empty outcome (no DE connectors); the caller falls back to the Hyperswitch static result.
+ pub fn empty() -> Self {
+ Self {
+ connectors: Vec::new(),
+ routing_approach: RoutingApproach::Default,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DecisionEngineEndpoint {
DecideGateway,
@@ -530,10 +540,7 @@ pub fn normalize_hybrid_routing_response(
logger::debug!(
"euclid: hybrid routing response did not include usable evaluated connectors or static output; returning empty connector set"
);
- HybridRoutingOutcome {
- connectors: Vec::new(),
- routing_approach: RoutingApproach::Default,
- }
+ HybridRoutingOutcome::empty()
};
Ok(outcome)
@@ -1034,12 +1041,56 @@ 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 {
+ Some(DeDiffReason::ResultMismatch)
+ } else if self.is_equal_length {
+ None
+ } else if self.is_de_result_empty {
+ Some(DeDiffReason::Unresponsive)
+ } else {
+ Some(DeDiffReason::LengthMismatch)
+ }
+ }
+}
+
pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(
de_result: Vec<T>,
result: Vec<T>,
flow: String,
-) {
- let is_equal = if de_result.is_empty() && result.is_empty() {
+ is_volume: bool,
+) -> DeComparisonResult {
+ let is_de_result_empty = de_result.is_empty();
+ let is_equal = if is_de_result_empty && result.is_empty() {
true
} else {
de_result
@@ -1054,10 +1105,163 @@ pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(
routing_flow=?flow,
is_equal=?is_equal,
is_equal_length=?is_equal_in_length,
+ is_volume=?is_volume,
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()
+ )
+}
+
+/// 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).
+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,
+) {
+ let de_result =
+ decision_engine_routing(&state, backend_input, &business_profile, payment_id, fallback_config)
+ .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,
+ "evaluate_routing".to_string(),
+ is_volume,
+ );
}
pub trait RoutingEq<T> {
@@ -1841,14 +2045,37 @@ pub async fn get_routing_result_source(
state: &SessionState,
dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
) -> api_routing::RoutingResultSource {
- // No customer_id and payment_id in call sites so passing Targeting key as None
- dimensions
+ // No customer_id and payment_id in call sites so passing Targeting key as None.
+ let source = dimensions
.get_routing_result_source(
state.store.as_ref(),
state.superposition_service.as_ref(),
None,
)
- .await
+ .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
+ }
}
pub async fn select_routing_result<T>(
state: &SessionState,
@@ -2221,6 +2448,19 @@ 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.rs
index 448ef5132b..d5b533e475 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -283,6 +283,7 @@ pub async fn retrieve_merchant_routing_dictionary(
de_result.clone(),
result.clone(),
"list_routing".to_string(),
+ false,
);
result =
build_list_routing_result(&state, platform, &result, &de_result, profile_ids.clone())
@@ -1493,6 +1494,7 @@ pub async fn retrieve_linked_routing_config(
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())