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
fix(routing): send all dashboard routing dimensions to the Decision Engine (#13846)
Ankit Kumar Gupta20672a134537
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 220ae2e529..337c433d77 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -43058,6 +43058,14 @@"$ref": "#/components/schemas/DeRoutableConnectorChoice"},"description": "Fallback connectors used if routing rule evaluation fails.\n\nThese connectors will be returned if no rule matches.\n\nExample:\n```json\n[\n{\n\"gateway_name\": \"stripe\",\n\"gateway_id\": \"mca_123\"\n}\n]\n```"+ },+ "algorithm_for": {+ "allOf": [+ {+ "$ref": "#/components/schemas/TransactionType"+ }+ ],+ "nullable": true}}},diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rsindex f321585d13..d94870bab8 100644--- a/crates/api_models/src/routing.rs+++ b/crates/api_models/src/routing.rs@@ -2149,6 +2149,12 @@ pub struct RoutingEvaluateRequest {/// ]/// ```pub fallback_output: Vec<DeRoutableConnectorChoice>,++ /// Transaction type whose active rule should be evaluated; absent keeps the+ /// DE's legacy type-blind lookup.+ #[serde(skip_serializing_if = "Option::is_none")]+ #[schema(value_type = Option<TransactionType>)]+ pub algorithm_for: Option<TransactionType>,}impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {}diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 5966ec3d7c..8e5d1d7ae7 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -4458,6 +4458,7 @@ pub async fn update_profile(merchant_id: id_type::MerchantId,key_store: domain::MerchantKeyStore,request: api::ProfileUpdate,+ provider_merchant_id: Option<hyperswitch_domain_models::platform::ProviderMerchantId>,) -> RouterResponse<api::ProfileResponse> {let db = state.store.as_ref();@@ -4478,6 +4479,33 @@ pub async fn update_profile(id: profile_id.get_string_repr().to_owned(),})?;+ // DE-cut-over profiles manage routing via the routing APIs; direct writes would diverge the engines.+ #[cfg(feature = "v1")]+ if request.routing_algorithm.is_some() || request.payout_routing_algorithm.is_some() {+ // The provider merchant is a real superposition dimension and differs from the+ // processor under connected-account auth, so it must match what the routing and+ // payment paths resolve; fall back to the auth merchant only when unavailable.+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(+ hyperswitch_domain_models::platform::ProcessorMerchantId::from(merchant_id.clone()),+ )+ .with_provider_merchant_id(provider_merchant_id.unwrap_or_else(|| {+ hyperswitch_domain_models::platform::ProviderMerchantId::new(merchant_id.clone())+ }))+ .with_profile_id(profile_id.clone());+ if crate::core::payments::routing::utils::is_decision_engine_routing_effective(+ &state,+ &dimensions,+ )+ .await+ {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "routing_algorithm cannot be set directly for a profile routed by the Decision Engine; use the routing APIs".to_string(),+ }+ .into());+ }+ }+let profile_update = request.get_update_profile_object(&state, &key_store, &business_profile).await?;diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 3872d2de07..e7170067f1 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -4474,6 +4474,7 @@ pub async fn build_merchant_enabled_pms_context(let (result, routing_approach) = routing::perform_session_flow_routing(sfr,business_profile,+ &dimensions,&enums::TransactionType::Payment,).awaitdiff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex b2777e28d9..da49754b59 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -11351,6 +11351,7 @@ wherefallback_config,backend_input,transaction_type,+ dimensions,).await?;ConnectorCallType::SessionMultiple(routing_output)@@ -12827,6 +12828,7 @@ pub async fn perform_session_token_routing<F, D>(fallback_config: Vec<api_models::routing::RoutableConnectorChoice>,mut backend_input: dsl_inputs::BackendInput,transaction_type: enums::TransactionType,+ dimensions: &DimensionsWithProcessorAndProviderMerchantIdAndProfileId,) -> RouterResult<api::SessionConnectorDatas>whereF: Clone,@@ -12855,6 +12857,12 @@ whereactive_mca_ids: &active_mca_ids,default_config: &fallback_config,backend_input: &mut backend_input,+ dimensions,+ payment_id: payment_data+ .get_payment_intent()+ .payment_id+ .get_string_repr()+ .to_string(),};let routing_algorithm: routing::MerchantAccountRoutingAlgorithm = business_profilediff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 3cb7ce3c38..9c38668b57 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -115,6 +115,9 @@ pub struct SessionRoutingPmTypeInput<'a> {backend_input: dsl_inputs::BackendInput,allowed_connectors: FxHashMap<SessionRoutingConnectorKey, api::GetToken>,profile_id: &'a common_utils::id_type::ProfileId,+ /// Resolves whether this profile is cut over to the Decision Engine.+ dimensions: &'a dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ payment_id: String,}#[cfg(feature = "v2")]@@ -448,7 +451,7 @@ pub fn make_dsl_input(| domain::PaymentMethodData::OpenBanking(_)| domain::PaymentMethodData::MobilePayment(_) => None,}),- card_discovery: None,+ card_discovery: payments_dsl_input.payment_attempt.card_discovery,};let issuer_data_input = dsl_inputs::IssuerDataInput {@@ -902,6 +905,53 @@ pub async fn perform_static_routing_locally(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),+ );+}+pub struct SessionRoutingInput<'a> {pub state: &'a SessionState,pub business_profile: &'a domain::Profile,@@ -913,6 +963,9 @@ pub struct SessionRoutingInput<'a> {&'a std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,pub default_config: &'a Vec<routing_types::RoutableConnectorChoice>,pub backend_input: &'a mut backend::BackendInput,+ /// Resolves whether this profile is cut over to the Decision Engine.+ pub dimensions: &'a dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+ pub payment_id: String,}#[cfg(feature = "v1")]@@ -953,19 +1006,64 @@ impl RoutingStage for SessionRoutingStage {Vec<routing_types::SessionRoutingChoice>,> = FxHashMap::default();- for (pm_type, allowed_connectors) in pm_type_map {- let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;- let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();+ // Both are independent of payment method type, so they are 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;++ // 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+ // the calls cannot be collapsed into one -- but they need not be serialised.+ let pm_entries = pm_type_map+ .into_iter()+ .map(|(pm_type, allowed_connectors)| {+ let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;+ let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();+ let mut backend_input = input.backend_input.clone();+ backend_input.payment_method.payment_method = Some(euclid_pm);+ backend_input.payment_method.payment_method_type = Some(euclid_pmt);+ (pm_type, allowed_connectors, backend_input)+ })+ .collect::<Vec<_>>();++ // 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(+ input.state,+ pm_entries+ .iter()+ .map(|(_, _, backend_input)| backend_input.clone())+ .collect(),+ input.business_profile,+ input.payment_id.clone(),+ input.default_config.clone(),+ *input.transaction_type,+ utils::RoutingFlow::SessionToken,+ )+ .await+ } else {+ vec![Vec::new(); pm_entries.len()]+ };- input.backend_input.payment_method.payment_method = Some(euclid_pm);- input.backend_input.payment_method.payment_method_type = Some(euclid_pmt);+ let mut shadow_entries: Vec<utils::ShadowBatchEntry> = Vec::new();+ for ((pm_type, allowed_connectors, backend_input), de_connectors) in+ pm_entries.into_iter().zip(de_results)+ {let algorithm_id = match &*self.ctx.routing_algorithm {MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => {&algorithm_ref.algorithm_id}};+ // Evaluated even under cutover, so an empty DE result falls back to the+ // merchant's own rule rather than the flat fallback list.let cached_algorithm = algorithm_id.clone().async_and_then(|algorithm_id| async move {@@ -981,7 +1079,7 @@ impl RoutingStage for SessionRoutingStage {.await;let static_input = StaticRoutingInput {- backend_input: input.backend_input,+ backend_input: &backend_input,};let static_stage = cached_algorithm.map(|cached_algorithm| StaticRoutingStage {@@ -1016,11 +1114,53 @@ 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.+ 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+ // it here would shift those numbers for cut-over merchants.+ utils::select_routing_result(+ input.state,+ input.dimensions,+ input.business_profile,+ chosen_connectors,+ de_connectors,+ )+ .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+ };+let primary = perform_cgraph_filtering(input.state,input.key_store,chosen_connectors,- input.backend_input.clone(),+ backend_input.clone(),None,profile_id,input.transaction_type,@@ -1033,7 +1173,7 @@ impl RoutingStage for SessionRoutingStage {input.state,input.key_store,input.default_config.clone(),- input.backend_input.clone(),+ backend_input.clone(),None,profile_id,input.transaction_type,@@ -1082,6 +1222,21 @@ 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,@@ -1546,28 +1701,15 @@ impl RoutingStage for HybridRoutingStage {utils::HybridRoutingOutcome::empty()});- // Keep legacy diff/selection logs for dashboard compatibility.- // Routing behavior remains hybrid-first; this is logging-only parity.- let comparison = utils::compare_and_log_result(+ // 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,);- // 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(),@@ -1611,10 +1753,11 @@ pub async fn perform_hybrid_routing_if_enabled(static_is_volume_split,};- let is_decision_engine_cutover_enabled = matches!(- utils::get_routing_result_source(state, dimensions).await,- api_models::routing::RoutingResultSource::DecisionEngine- );+ // 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).+ let is_decision_engine_cutover_enabled =+ utils::is_decision_engine_routing_effective(state, dimensions).await;let has_active_routing_algorithm = business_profile.routing_algorithm.clone()@@ -1625,19 +1768,10 @@ pub async fn perform_hybrid_routing_if_enabled(.and_then(|algorithm_ref| algorithm_ref.algorithm_id).is_some();- if !has_active_routing_algorithm {- logger::debug!(- business_profile_id=?business_profile.get_id(),- "decision_engine_euclid: no active routing algorithm, skipping DE evaluation"- );- logger::info!(- business_profile_id=?business_profile.get_id(),- routing_source = "hyperswitch_static",- "decision_engine_euclid: selected routing source after hybrid stage"- );-- (static_connectors.to_vec(), static_approach)- } else if is_decision_engine_cutover_enabled {+ // A cut-over profile's rules live on the Decision Engine, so a missing Hyperswitch+ // algorithm is the normal state and must not skip evaluation; for every other profile+ // there is nothing to evaluate against, so the DE call is skipped.+ if is_decision_engine_cutover_enabled {let hybrid_stage_outcome = stage.route(input).await@@ -1666,6 +1800,18 @@ pub async fn perform_hybrid_routing_if_enabled(static_connectors,static_approach,)+ } else if !has_active_routing_algorithm {+ logger::debug!(+ business_profile_id=?business_profile.get_id(),+ "decision_engine_euclid: no active routing algorithm, skipping DE evaluation"+ );+ logger::info!(+ business_profile_id=?business_profile.get_id(),+ routing_source = "hyperswitch_static",+ "decision_engine_euclid: selected routing source after hybrid stage"+ );++ (static_connectors.to_vec(), static_approach)} else {logger::debug!(business_profile_id=?business_profile.get_id(),@@ -1711,6 +1857,8 @@ pub async fn perform_hybrid_routing_if_enabled(shadow_fallback,shadow_static_connectors,static_is_volume_split,+ api_enums::TransactionType::Payment,+ utils::RoutingFlow::Payment,).await;}@@ -1785,33 +1933,54 @@ pub async fn perform_static_routing_v1(let fallback_config = get_merchant_fallback_config().await?;- let algorithm_id = if let Some(id) = algorithm_id {- id- } else {- logger::debug!("euclid_routing: active algorithm isn't present, default falling back");- return Ok((fallback_config, None));- };+ // A cut-over profile may have rules only on the DE, so a missing HS algorithm must not skip DE evaluation.+ let de_routing_effective = utils::is_decision_engine_routing_effective(state, dimensions).await;- let cached_algorithm = match ensure_algorithm_cached_v1(- state,- merchant_id,- algorithm_id,- business_profile.get_id(),- &api_enums::TransactionType::from(transaction_data),- )- .await- {- Ok(algo) => algo,- Err(err) => {- logger::error!(- error=?err,- "euclid_routing: ensure_algorithm_cached failed, falling back to merchant default connectors"+ let algorithm_id = match algorithm_id {+ // Evaluated even under cutover. The DE result is still preferred, but when it comes+ // back empty -- the engine is unreachable, or the profile's rules have not been+ // migrated yet -- the merchant's own rule is a far better answer than the flat+ // fallback list. The ref is never cleared, so cutover stays a reversible config flip.+ Some(id) => Some(id),+ None if de_routing_effective => {+ logger::debug!(+ "decision_engine_euclid: no active HS algorithm, profile is cut over; evaluating on DE");-+ None+ }+ None => {+ logger::debug!("euclid_routing: active algorithm isn't present, default falling back");return Ok((fallback_config, None));}};+ let cached_algorithm = match algorithm_id {+ Some(algorithm_id) => match ensure_algorithm_cached_v1(+ state,+ merchant_id,+ algorithm_id,+ business_profile.get_id(),+ &api_enums::TransactionType::from(transaction_data),+ )+ .await+ {+ Ok(algo) => Some(algo),+ Err(err) => {+ logger::error!(+ error=?err,+ "euclid_routing: ensure_algorithm_cached failed, falling back to merchant default connectors"+ );++ if de_routing_effective {+ None+ } else {+ return Ok((fallback_config, None));+ }+ }+ },+ None => None,+ };+let payment_id = match transaction_data {routing::TransactionData::Payment(payment_data) => payment_data.payment_attempt@@ -1835,49 +2004,58 @@ 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) =- 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(+ let (+ routable_connectors,+ routing_approach,+ is_volume_split,+ de_evaluated_connector,+ hs_eval_succeeded,+ ) = 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)+ }+ 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(),+ api_enums::TransactionType::from(transaction_data),+ utils::RoutingFlow::Payment,).await.map_err(|e| logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule")).unwrap_or_default()- };+ };- let evaluated = (|| -> RoutingResult<(+ let evaluated = (|| -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>,Option<common_enums::RoutingApproach>,bool,)> {- Ok(match cached_algorithm.as_ref() {- CachedAlgorithm::Single(conn) => (+ Ok(match cached_algorithm.as_deref() {+ // No HS algorithm (cut-over profile): HS side is the fallback list.+ None => (fallback_config.clone(), None, false),+ Some(CachedAlgorithm::Single(conn)) => (vec![(**conn).clone()],Some(common_enums::RoutingApproach::StraightThroughRouting),false,),- CachedAlgorithm::Priority(plist) => (plist.clone(), None, false),- CachedAlgorithm::VolumeSplit(splits) => (+ Some(CachedAlgorithm::Priority(plist)) => (plist.clone(), None, false),+ Some(CachedAlgorithm::VolumeSplit(splits)) => (perform_volume_split(splits.to_vec()).change_context(errors::RoutingError::ConnectorSelectionFailed)?,Some(common_enums::RoutingApproach::VolumeBasedRouting),true,),- CachedAlgorithm::Advanced(interpreter) => {+ Some(CachedAlgorithm::Advanced(interpreter)) => {let dsl_output = execute_dsl_v1(backend_input, interpreter)?;let is_volume_split = matches!(dsl_output,@@ -1892,31 +2070,41 @@ pub async fn perform_static_routing_v1(})})();- let (routable_connectors, routing_approach, is_volume_split) = evaluated+ let hs_eval_succeeded = evaluated.is_ok();+ 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,- )- }- };+ (+ routable_connectors,+ routing_approach,+ is_volume_split,+ de_evaluated_connector,+ hs_eval_succeeded,+ )+ }+ };- // Diff-logged (is_equal / is_equal_length / is_volume) and fed to the kill switch.+ // 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(),- "evaluate_routing".to_string(),+ utils::RoutingFlow::Payment.as_str().to_string(),is_volume_split,);- utils::record_de_diff_and_maybe_trip_kill_switch(state, business_profile.get_id(), comparison)+ 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(@@ -2809,6 +2997,7 @@ pub async fn perform_session_flow_routing<'a>(pub async fn perform_session_flow_routing(session_input: SessionFlowRoutingInput<'_>,business_profile: &domain::Profile,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,transaction_type: &api_enums::TransactionType,) -> RoutingResult<(FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>,@@ -2882,7 +3071,7 @@ pub async fn perform_session_flow_routing(.attach_printable("Unable to parse routing_parameters from metadata of payment_intent").unwrap_or(None);- let mut backend_input = dsl_inputs::BackendInput {+ let backend_input = dsl_inputs::BackendInput {metadata,payment: payment_input,payment_method: payment_method_input,@@ -2915,32 +3104,103 @@ pub async fn perform_session_flow_routing(get_active_mca_ids_for_session(session_input.state, session_input.key_store, &profile_id).await;- for (pm_type, allowed_connectors) in pm_type_map {- let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;- let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();+ // Independent of payment method type, so resolved once rather than per iteration.+ let de_routing_effective =+ utils::is_decision_engine_routing_effective(session_input.state, dimensions).await;- backend_input.payment_method.payment_method = Some(euclid_pm);- backend_input.payment_method.payment_method_type = Some(euclid_pmt);+ let payment_id = session_input+ .payment_intent+ .payment_id+ .get_string_repr()+ .to_string();++ // 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 they cannot be+ // collapsed into one call -- but they need not be serialised.+ let pm_entries = pm_type_map+ .into_iter()+ .map(|(pm_type, allowed_connectors)| {+ let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;+ let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();+ let mut backend_input = backend_input.clone();+ backend_input.payment_method.payment_method = Some(euclid_pm);+ backend_input.payment_method.payment_method_type = Some(euclid_pmt);+ (pm_type, allowed_connectors, backend_input)+ })+ .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;++ // 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 {+ routing::helpers::get_merchant_default_config(+ &*session_input.state.clone().store,+ profile_id.get_string_repr(),+ transaction_type,+ )+ .await+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?+ } else {+ Vec::new()+ };++ // 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.+ let de_results: Vec<Vec<routing_types::RoutableConnectorChoice>> = if de_routing_effective {+ utils::decision_engine_routing_batch_with_fallback(+ session_input.state,+ pm_entries+ .iter()+ .map(|(_, _, backend_input)| backend_input.clone())+ .collect(),+ business_profile,+ payment_id.clone(),+ de_fallback_config.clone(),+ *transaction_type,+ utils::RoutingFlow::PaymentMethodList,+ )+ .await+ } else {+ vec![Vec::new(); pm_entries.len()]+ };++ let mut shadow_entries: Vec<utils::ShadowBatchEntry> = Vec::new();+ for ((pm_type, allowed_connectors, backend_input), de_connectors) in+ pm_entries.into_iter().zip(de_results)+ {let session_pm_input = SessionRoutingPmTypeInput {state: session_input.state,key_store: session_input.key_store,// attempt_id: session_input.payment_attempt.get_id(),routing_algorithm: &routing_algorithm,- backend_input: backend_input.clone(),+ backend_input,allowed_connectors,profile_id: &profile_id,+ dimensions,+ payment_id: payment_id.clone(),};- let (routable_connector_choice_option, routing_approach) =+ let (routable_connector_choice_option, routing_approach, shadow_entry) =perform_session_routing_for_pm_type(&session_pm_input,transaction_type,business_profile,&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 {@@ -2972,18 +3232,37 @@ 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,- _business_profile: &domain::Profile,+ business_profile: &domain::Profile,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;@@ -2991,6 +3270,22 @@ async fn perform_session_routing_for_pm_type(MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,};+ // The Decision Engine call moved to the caller (one batch per request), so the+ // fallback list is only needed here as the no-algorithm result.+ let fallback_config = if algorithm_id.is_none() {+ routing::helpers::get_merchant_default_config(+ &*session_pm_input.state.clone().store,+ session_pm_input.profile_id.get_string_repr(),+ transaction_type,+ )+ .await+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)?+ } else {+ Vec::new()+ };++ // Evaluated even under cutover, so an empty DE result falls back to the merchant's own+ // rule rather than the flat fallback list.let (chosen_connectors, routing_approach) = if let Some(ref algorithm_id) = algorithm_id {let cached_algorithm = ensure_algorithm_cached_v1(&session_pm_input.state.clone(),@@ -3021,18 +3316,49 @@ async fn perform_session_routing_for_pm_type(),}} else {- (- routing::helpers::get_merchant_default_config(- &*session_pm_input.state.clone().store,- session_pm_input.profile_id.get_string_repr(),- transaction_type,- )- .await- .change_context(errors::RoutingError::FallbackConfigFetchFailed)?,- None,+ (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.+ 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(+ session_pm_input.state,+ session_pm_input.dimensions,+ business_profile,+ chosen_connectors,+ de_connectors,)+ .await+ } else {+ 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,@@ -3068,9 +3394,9 @@ async fn perform_session_routing_for_pm_type(}if final_selection.is_empty() {- Ok((None, routing_approach))+ Ok((None, routing_approach, shadow_entry))} else {- Ok((Some(final_selection), routing_approach))+ Ok((Some(final_selection), routing_approach, shadow_entry))}}diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rsindex 410075f6c1..44fa1744e9 100644--- a/crates/router/src/core/payments/routing/utils.rs+++ b/crates/router/src/core/payments/routing/utils.rs@@ -14,7 +14,7 @@ use api_models::{};use async_trait::async_trait;use common_enums::TransactionType;-use common_utils::{ext_traits::BytesExt, id_type};+use common_utils::{ext_traits::BytesExt, id_type, types::MinorUnit};use diesel_models::{enums, routing_algorithm};use error_stack::ResultExt;use euclid::{@@ -464,6 +464,7 @@ pub fn build_static_routing_request_for_hybrid(Some(payment_id),input,convert_fallback_to_de_choices(fallback_output),+ TransactionType::Payment,)}@@ -629,6 +630,7 @@ pub async fn perform_decision_euclid_routing(payment_id: String,events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>,fallback_output: Vec<RoutableConnectorChoice>,+ algorithm_for: TransactionType,) -> RoutingResult<RoutingEvaluateResponse> {logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation");@@ -640,6 +642,7 @@ pub async fn perform_decision_euclid_routing(Some(payment_id),input,fallback_output,+ algorithm_for,)?;events_wrapper.set_request_body(routing_request.clone());@@ -705,12 +708,51 @@ pub fn transform_de_output_for_router(Ok(ordered)}+/// 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.+#[derive(Debug, Clone, Copy)]+pub enum RoutingFlow {+ Payment,+ SessionToken,+ PaymentMethodList,+}++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.+ fn event_name(self) -> String {+ match self {+ Self::Payment => "DecisionEngine: Euclid Static Routing".to_string(),+ Self::SessionToken => {+ "DecisionEngine: Euclid Static Routing (session tokens)".to_string()+ }+ Self::PaymentMethodList => {+ "DecisionEngine: Euclid Static Routing (payment method list)".to_string()+ }+ }+ }+}+pub async fn decision_engine_routing(state: &SessionState,backend_input: BackendInput,business_profile: &domain::Profile,payment_id: String,merchant_fallback_config: Vec<RoutableConnectorChoice>,+ algorithm_for: TransactionType,+ routing_flow: RoutingFlow,) -> RoutingResult<Vec<RoutableConnectorChoice>> {let routing_events_wrapper = RoutingEventsWrapper::new(state.tenant.tenant_id.clone(),@@ -718,7 +760,7 @@ pub async fn decision_engine_routing(payment_id.clone(),business_profile.get_id().to_owned(),business_profile.merchant_id.to_owned(),- "DecisionEngine: Euclid Static Routing".to_string(),+ routing_flow.event_name(),None,true,false,@@ -731,6 +773,7 @@ pub async fn decision_engine_routing(payment_id,routing_events_wrapper,merchant_fallback_config,+ algorithm_for,).await;@@ -969,28 +1012,111 @@ pub async fn link_de_euclid_routing_algorithm(Ok(())}-pub async fn list_de_euclid_routing_algorithms(+pub async fn deactivate_de_euclid_routing_algorithm(state: &SessionState,- routing_list_request: ListRountingAlgorithmsRequest,-) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {- logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms");- let created_by = routing_list_request.created_by;+ routing_request: DeactivateRoutingConfigRequest,+) -> RoutingResult<()> {+ logger::debug!("decision_engine_euclid: deactivate api call for euclid routing algorithm");++ EuclidApiClient::send_decision_engine_request::<_, String>(+ state,+ services::Method::Post,+ "routing/deactivate",+ Some(routing_request.clone()),+ Some(EUCLID_API_TIMEOUT),+ None,+ )+ .await?;++ logger::debug!(decision_engine_euclid_deactivated=?routing_request, "decision_engine_euclid: deactivate_de_euclid_routing_algorithm completed");+ Ok(())+}++/// Fetches DE rules for a profile as raw JSON records (no HS-representability filter).+pub async fn fetch_de_euclid_routing_records_raw(+ state: &SessionState,+ created_by: String,+ active_only: bool,+) -> RoutingResult<Vec<serde_json::Value>> {+ let path = if active_only {+ format!("routing/list/active/{created_by}")+ } else {+ format!("routing/list/{created_by}")+ };let events_response = EuclidApiClient::send_decision_engine_request(state,services::Method::Post,- format!("routing/list/{created_by}").as_str(),+ path.as_str(),None::<()>,Some(EUCLID_API_TIMEOUT),None,).await?;- let euclid_response: Vec<RoutingAlgorithmRecord> =- events_response- .response- .ok_or(errors::RoutingError::OpenRouterError(- "Response from decision engine API is empty".to_string(),- ))?;+ events_response+ .response+ .ok_or(errors::RoutingError::OpenRouterError(+ "Response from decision engine API is empty".to_string(),+ ))+ .map_err(error_stack::Report::from)+}++/// Rule ids from raw DE records, including rules HS cannot represent. Existence and+/// already-active checks must use this rather than the lenient parse, or an+/// unrepresentable rule reads as absent.+pub fn de_euclid_routing_record_ids(raw_records: &[serde_json::Value]) -> Vec<String> {+ raw_records+ .iter()+ .filter_map(|record| {+ record+ .get("id")+ .and_then(|id| id.as_str())+ .map(|id| id.to_string())+ })+ .collect()+}++/// Transaction type of a raw DE record, for callers that must not drop unrepresentable rules.+pub fn de_euclid_routing_record_algorithm_for(raw: &serde_json::Value) -> Option<TransactionType> {+ raw.get("algorithm_for")+ .and_then(|value| value.as_str())+ .and_then(|value| serde_json::from_value(serde_json::Value::String(value.to_string())).ok())+}++/// Parses a raw DE record; None (with a log) for rules HS cannot represent (e.g. `ab_test`).+pub fn parse_de_euclid_routing_record(raw: serde_json::Value) -> Option<RoutingAlgorithmRecord> {+ serde_json::from_value::<RoutingAlgorithmRecord>(raw)+ .map_err(|error| {+ logger::warn!(+ ?error,+ "decision_engine_euclid: skipping DE routing record not representable in Hyperswitch"+ );+ })+ .ok()+}++/// Fetches DE rules for a profile, skipping records HS cannot represent.+pub async fn fetch_de_euclid_routing_records(+ state: &SessionState,+ created_by: String,+ active_only: bool,+) -> RoutingResult<Vec<RoutingAlgorithmRecord>> {+ Ok(+ fetch_de_euclid_routing_records_raw(state, created_by, active_only)+ .await?+ .into_iter()+ .filter_map(parse_de_euclid_routing_record)+ .collect(),+ )+}++pub async fn list_de_euclid_routing_algorithms(+ state: &SessionState,+ routing_list_request: ListRountingAlgorithmsRequest,+) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {+ logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms");+ let euclid_response =+ fetch_de_euclid_routing_records(state, routing_list_request.created_by, false).await?;Ok(euclid_response.into_iter()@@ -1004,19 +1130,7 @@ pub async fn list_de_euclid_active_routing_algorithm(created_by: String,) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm");- let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request(- state,- services::Method::Post,- format!("routing/list/active/{created_by}").as_str(),- None::<()>,- Some(EUCLID_API_TIMEOUT),- None,- )- .await?- .response- .ok_or(errors::RoutingError::OpenRouterError(- "Response from decision engine API is empty".to_string(),- ))?;+ let response = fetch_de_euclid_routing_records(state, created_by, true).await?;Ok(response.into_iter()@@ -1241,6 +1355,7 @@ async fn is_de_diff_threshold_exceeded(}/// 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,@@ -1249,9 +1364,11 @@ pub async fn shadow_decision_engine_routing(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)+ 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")@@ -1261,11 +1378,267 @@ pub async fn shadow_decision_engine_routing(compare_and_log_result(de_result,hs_connectors,- "evaluate_routing".to_string(),+ 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`.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct RoutingEvaluateBatchEntry {+ pub payment_id: Option<String>,+ pub parameters: HashMap<String, Option<ValueType>>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct RoutingEvaluateBatchRequest {+ pub created_by: String,+ pub fallback_output: Vec<DeRoutableConnectorChoice>,+ pub algorithm_for: TransactionType,+ pub requests: Vec<RoutingEvaluateBatchEntry>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct RoutingEvaluateBatchResponse {+ pub results: Vec<RoutingEvaluateResponse>,+}++/// Evaluates one rule against several parameter sets in a single Decision Engine+/// round trip. The engine fetches and parses the active algorithm once, so a session+/// request with N wallet types costs one call and one rule lookup instead of N each.+///+/// Results come back positionally: `results[i]` answers `backend_inputs[i]`. An entry+/// the engine could not evaluate is an empty list, mirroring how callers of the+/// single-call path treat a failed evaluation.+pub async fn decision_engine_routing_batch(+ state: &SessionState,+ backend_inputs: Vec<BackendInput>,+ business_profile: &domain::Profile,+ payment_id: String,+ merchant_fallback_config: Vec<RoutableConnectorChoice>,+ algorithm_for: TransactionType,+ routing_flow: RoutingFlow,+) -> RoutingResult<Vec<Vec<RoutableConnectorChoice>>> {+ let expected_len = backend_inputs.len();+ let created_by = business_profile.get_id().get_string_repr().to_string();+ let fallback_output = convert_fallback_to_de_choices(merchant_fallback_config);++ let requests = backend_inputs+ .into_iter()+ .map(|backend_input| {+ convert_backend_input_to_routing_eval(+ created_by.clone(),+ Some(payment_id.clone()),+ backend_input,+ fallback_output.clone(),+ algorithm_for,+ )+ .map(|request| RoutingEvaluateBatchEntry {+ payment_id: request.payment_id,+ parameters: request.parameters,+ })+ })+ .collect::<RoutingResult<Vec<_>>>()?;++ let batch_request = RoutingEvaluateBatchRequest {+ created_by,+ fallback_output,+ algorithm_for,+ requests,+ };++ let mut events_wrapper: RoutingEventsWrapper<RoutingEvaluateBatchRequest> =+ RoutingEventsWrapper::new(+ state.tenant.tenant_id.clone(),+ state.request_id.clone(),+ payment_id,+ business_profile.get_id().to_owned(),+ business_profile.merchant_id.to_owned(),+ routing_flow.event_name(),+ None,+ true,+ false,+ );+ events_wrapper.set_request_body(batch_request.clone());++ let event_response = EuclidApiClient::send_decision_engine_request::<+ RoutingEvaluateBatchRequest,+ RoutingEvaluateBatchResponse,+ >(+ state,+ services::Method::Post,+ "routing/evaluate/batch",+ Some(batch_request),+ Some(EUCLID_API_TIMEOUT),+ Some(events_wrapper),+ )+ .await?;++ let batch_response = event_response+ .response+ .ok_or(errors::RoutingError::OpenRouterError(+ "Response from decision engine batch API is empty".to_string(),+ ))?;++ if batch_response.results.len() != expected_len {+ return Err(errors::RoutingError::OpenRouterError(format!(+ "decision engine batch returned {} results for {} requests",+ batch_response.results.len(),+ expected_len+ ))+ .into());+ }++ let transformed = batch_response+ .results+ .into_iter()+ .map(|entry| {+ // A per-entry failure is an empty list rather than a batch failure: one+ // wallet type falling back must not take the others down with it.+ if entry.status == "error" {+ return Vec::new();+ }+ extract_de_output_connectors(entry.output)+ .and_then(|output| transform_de_output_for_router(output, entry.evaluated_output))+ .map_err(|error| {+ logger::error!(+ ?error,+ "decision_engine_euclid: failed to transform a batch entry"+ );+ })+ .unwrap_or_default()+ })+ .collect::<Vec<_>>();++ if let Some(mut routing_event) = event_response.event {+ routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string());+ routing_event+ .set_routable_connectors(transformed.iter().flatten().cloned().collect::<Vec<_>>());+ state.event_handler.log_event(&routing_event);+ }++ Ok(transformed)+}++/// The batch call, degrading to concurrent single evaluations when the engine does+/// not expose the batch endpoint yet. Lets Hyperswitch deploy ahead of the engine:+/// against an old engine every batch call fails once and the singles carry the+/// request, and once the engine ships the endpoint the fallback stops firing.+pub async fn decision_engine_routing_batch_with_fallback(+ state: &SessionState,+ backend_inputs: Vec<BackendInput>,+ business_profile: &domain::Profile,+ payment_id: String,+ merchant_fallback_config: Vec<RoutableConnectorChoice>,+ algorithm_for: TransactionType,+ routing_flow: RoutingFlow,+) -> Vec<Vec<RoutableConnectorChoice>> {+ match decision_engine_routing_batch(+ state,+ backend_inputs.clone(),+ business_profile,+ payment_id.clone(),+ merchant_fallback_config.clone(),+ algorithm_for,+ routing_flow,+ )+ .await+ {+ Ok(results) => results,+ Err(error) => {+ logger::warn!(+ ?error,+ "decision_engine_euclid: batch evaluate failed, falling back to single evaluations"+ );+ futures::future::join_all(backend_inputs.into_iter().map(|backend_input| {+ decision_engine_routing(+ state,+ backend_input,+ business_profile,+ payment_id.clone(),+ merchant_fallback_config.clone(),+ algorithm_for,+ routing_flow,+ )+ }))+ .await+ .into_iter()+ .map(|result| {+ result+ .inspect_err(|error| {+ logger::error!(+ ?error,+ "decision_engine_euclid: single evaluation failed in batch fallback"+ );+ })+ .unwrap_or_default()+ })+ .collect()+ }+ }+}++/// 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;}@@ -1316,6 +1689,12 @@ pub struct ActivateRoutingConfigRequest {pub routing_algorithm_id: String,}+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]+pub struct DeactivateRoutingConfigRequest {+ pub created_by: String,+ pub routing_algorithm_id: String,+}+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]pub struct ListRountingAlgorithmsRequest {pub created_by: String,@@ -1327,6 +1706,7 @@ pub fn convert_backend_input_to_routing_eval(payment_id: Option<String>,input: BackendInput,fallback_output: Vec<DeRoutableConnectorChoice>,+ algorithm_for: TransactionType,) -> RoutingResult<RoutingEvaluateRequest> {let mut params: HashMap<String, Option<ValueType>> = HashMap::new();@@ -1392,6 +1772,23 @@ pub fn convert_backend_input_to_routing_eval(Some(ValueType::EnumVariant(sfu.to_string())),);}+ if let Some(surcharge_amount) = input.payment.surcharge_amount {+ params.insert(+ "surcharge_amount".to_string(),+ Some(ValueType::Number(+ surcharge_amount+ .get_amount_as_i64()+ .try_into()+ .unwrap_or_default(),+ )),+ );+ }+ if let Some(transaction_initiator) = input.payment.transaction_initiator {+ params.insert(+ "transaction_initiator".to_string(),+ Some(ValueType::EnumVariant(transaction_initiator.to_string())),+ );+ }// PaymentMethodif let Some(pm) = input.payment_method.payment_method {@@ -1423,6 +1820,12 @@ pub fn convert_backend_input_to_routing_eval(Some(ValueType::EnumVariant(network.to_string())),);}+ if let Some(card_discovery) = input.payment_method.card_discovery {+ params.insert(+ "card_discovery".to_string(),+ Some(ValueType::EnumVariant(card_discovery.to_string())),+ );+ }// Mandateif let Some(pt) = input.mandate.payment_type {@@ -1444,6 +1847,18 @@ pub fn convert_backend_input_to_routing_eval();}+ // Issuer+ if let Some(country) = input+ .issuer_data+ .as_ref()+ .and_then(|data| data.country.as_ref())+ {+ params.insert(+ "issuer_country".to_string(),+ Some(ValueType::EnumVariant(country.to_string())),+ );+ }+// Metadataif let Some(meta) = input.metadata {for (k, v) in meta.into_iter() {@@ -1462,6 +1877,7 @@ pub fn convert_backend_input_to_routing_eval(payment_id,parameters: params,fallback_output,+ algorithm_for: Some(algorithm_for),})}@@ -1476,7 +1892,7 @@ fn insert_dirvalue_param(params: &mut HashMap<String, Option<ValueType>>, dv: di}dir::DirValue::CardType(v) => {params.insert(- "card".to_string(),+ "card_type".to_string(),Some(ValueType::EnumVariant(v.to_string())),);}@@ -2043,6 +2459,173 @@ fn stringify_choice(c: RoutableConnectorChoice) -> ConnectorInfo {)}+// Reverse of the transformers above: rebuilds a euclid AST from a Decision Engine+// program, so a rule authored on the DE can be served through the same typed+// response shape as a Hyperswitch-authored one.+impl TryFrom<Program> for ast::Program<ConnectorSelection> {+ type Error = error_stack::Report<errors::RoutingError>;++ fn try_from(p: Program) -> Result<Self, Self::Error> {+ if !p.globals.is_empty() {+ // Globals are only reachable through `ValueType::GlobalRef`, which+ // `convert_value_back` rejects, so an unreferenced map is safe to drop.+ logger::debug!("euclid: dropping unreferenced globals while converting DE program");+ }++ Ok(Self {+ default_selection: convert_output_back(p.default_selection)?,+ rules: p+ .rules+ .into_iter()+ .map(convert_rule_back)+ .collect::<RoutingResult<Vec<_>>>()?,+ metadata: p.metadata.unwrap_or_default(),+ })+ }+}++fn convert_rule_back(rule: Rule) -> RoutingResult<ast::Rule<ConnectorSelection>> {+ Ok(ast::Rule {+ name: rule.name,+ // `routing_type` carries no information the output does not already hold.+ connector_selection: convert_output_back(rule.output)?,+ statements: rule+ .statements+ .into_iter()+ .map(convert_if_stmt_back)+ .collect::<RoutingResult<Vec<_>>>()?,+ })+}++fn convert_if_stmt_back(stmt: IfStatement) -> RoutingResult<ast::IfStatement> {+ Ok(ast::IfStatement {+ condition: stmt+ .condition+ .into_iter()+ .map(convert_comparison_back)+ .collect::<RoutingResult<Vec<_>>>()?,+ nested: stmt+ .nested+ .map(|v| {+ v.into_iter()+ .map(convert_if_stmt_back)+ .collect::<RoutingResult<Vec<_>>>()+ })+ .transpose()?,+ })+}++fn convert_comparison_back(c: Comparison) -> RoutingResult<ast::Comparison> {+ Ok(ast::Comparison {+ lhs: c.lhs,+ comparison: convert_comparison_type_back(c.comparison),+ value: convert_value_back(c.value)?,+ metadata: c.metadata,+ })+}++fn convert_comparison_type_back(ct: ComparisonType) -> ast::ComparisonType {+ match ct {+ ComparisonType::Equal => ast::ComparisonType::Equal,+ ComparisonType::NotEqual => ast::ComparisonType::NotEqual,+ ComparisonType::LessThan => ast::ComparisonType::LessThan,+ ComparisonType::LessThanEqual => ast::ComparisonType::LessThanEqual,+ ComparisonType::GreaterThan => ast::ComparisonType::GreaterThan,+ ComparisonType::GreaterThanEqual => ast::ComparisonType::GreaterThanEqual,+ }+}++/// DE amounts are `u64`; euclid's `MinorUnit` is `i64`. Anything above `i64::MAX`+/// would wrap to a negative amount, so it is rejected rather than silently mangled.+fn de_number_to_minor_unit(n: u64) -> RoutingResult<MinorUnit> {+ i64::try_from(n)+ .map(MinorUnit::new)+ .map_err(|error| {+ logger::error!(+ error = ?error,+ value = %n,+ "euclid: DE number does not fit in MinorUnit"+ );+ errors::RoutingError::GenericConversionError {+ from: "u64".to_string(),+ to: "MinorUnit".to_string(),+ }+ })+ .map_err(error_stack::Report::from)+ .attach_printable("DE number out of range for MinorUnit")+}++fn convert_value_back(v: ValueType) -> RoutingResult<ast::ValueType> {+ match v {+ ValueType::Number(n) => Ok(ast::ValueType::Number(de_number_to_minor_unit(n)?)),+ ValueType::EnumVariant(e) => Ok(ast::ValueType::EnumVariant(e)),+ ValueType::MetadataVariant(m) => Ok(ast::ValueType::MetadataVariant(ast::MetadataValue {+ key: m.key,+ value: m.value,+ })),+ ValueType::StrValue(s) => Ok(ast::ValueType::StrValue(s)),+ ValueType::NumberArray(arr) => Ok(ast::ValueType::NumberArray(+ arr.into_iter()+ .map(de_number_to_minor_unit)+ .collect::<RoutingResult<Vec<_>>>()?,+ )),+ ValueType::EnumVariantArray(arr) => Ok(ast::ValueType::EnumVariantArray(arr)),+ ValueType::NumberComparisonArray(arr) => Ok(ast::ValueType::NumberComparisonArray(+ arr.into_iter()+ .map(|nc| {+ Ok(ast::NumberComparison {+ comparison_type: convert_comparison_type_back(nc.comparison_type),+ number: de_number_to_minor_unit(nc.number)?,+ })+ })+ .collect::<RoutingResult<Vec<_>>>()?,+ )),+ // Euclid's AST has no global-reference form.+ ValueType::GlobalRef(name) => Err(error_stack::Report::from(+ errors::RoutingError::GenericConversionError {+ from: "ValueType::GlobalRef".to_string(),+ to: "euclid ValueType".to_string(),+ },+ ))+ .attach_printable_lazy(|| format!("unsupported global reference {name} in DE program")),+ }+}++fn convert_output_back(output: Output) -> RoutingResult<ConnectorSelection> {+ match output {+ // Euclid has no single-connector output; a one-element priority list is equivalent.+ Output::Single(info) => Ok(ConnectorSelection::Priority(vec![parse_choice(info)?])),+ Output::Priority(infos) => Ok(ConnectorSelection::Priority(+ infos+ .into_iter()+ .map(parse_choice)+ .collect::<RoutingResult<Vec<_>>>()?,+ )),+ Output::VolumeSplit(splits) => Ok(ConnectorSelection::VolumeSplit(+ splits+ .into_iter()+ .map(|vs| {+ Ok(ConnectorVolumeSplit {+ connector: parse_choice(vs.output)?,+ split: vs.split,+ })+ })+ .collect::<RoutingResult<Vec<_>>>()?,+ )),+ Output::VolumeSplitPriority(_) => Err(error_stack::Report::from(+ errors::RoutingError::GenericConversionError {+ from: "Output::VolumeSplitPriority".to_string(),+ to: "ConnectorSelection".to_string(),+ },+ ))+ .attach_printable("euclid has no volume-split-priority connector selection"),+ }+}++fn parse_choice(info: ConnectorInfo) -> RoutingResult<RoutableConnectorChoice> {+ DeRoutableConnectorChoice::try_from(info).map(RoutableConnectorChoice::from)+}+pub async fn get_routing_result_source(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,@@ -2079,6 +2662,19 @@ pub async fn get_routing_result_source(source}}++/// Effective cutover: routing_result_source is DecisionEngine AND the global+/// static_routing_enabled flag is on — the flag always wins, for APIs and payment paths alike.+pub async fn is_decision_engine_routing_effective(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,+) -> bool {+ state.conf.open_router.static_routing_enabled+ && matches!(+ get_routing_result_source(state, dimensions).await,+ api_routing::RoutingResultSource::DecisionEngine+ )+}pub async fn select_routing_result<T>(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,@@ -2089,7 +2685,13 @@ pub async fn select_routing_result<T>(whereT: Clone + IntoIterator,{- let routing_result_source = get_routing_result_source(state, dimensions).await;+ // Same predicate as every other consumer: with the global flag off the profile is+ // Hyperswitch-routed, so reads must not serve DE records the payment path ignores.+ let routing_result_source = if is_decision_engine_routing_effective(state, dimensions).await {+ api_routing::RoutingResultSource::DecisionEngine+ } else {+ api_routing::RoutingResultSource::HyperswitchRouting+ };match routing_result_source {api_routing::RoutingResultSource::DecisionEngine => {@@ -2100,9 +2702,13 @@ wherelet is_de_result_empty = de_result.clone().into_iter().next().is_none();if is_de_result_empty {- logger::debug!(+ // Warn, not debug: this is a cut-over profile being routed by Hyperswitch+ // because the engine returned nothing -- unreachable, or the profile's rules+ // are not migrated yet. Under DE-only writes the Hyperswitch rule is frozen+ // at the moment of cutover, so this needs to be visible rather than silent.+ logger::warn!(business_profile_id=?business_profile.get_id(),- "decision_engine_euclid: DE result empty, falling back to Hyperswitch result"+ "decision_engine_euclid: DE result empty for a cut-over profile, serving the Hyperswitch result");hyperswitch_result} else {@@ -2975,3 +3581,210 @@ mod transform_de_output_tests {);}}++#[cfg(test)]+mod de_program_round_trip_tests {+ use super::*;++ fn mca_id(id: &str) -> id_type::MerchantConnectorAccountId {+ id_type::MerchantConnectorAccountId::wrap(id.to_string()).unwrap()+ }++ fn choice(connector: RoutableConnectors, id: &str) -> RoutableConnectorChoice {+ RoutableConnectorChoice {+ choice_kind: api_routing::RoutableChoiceKind::FullStruct,+ connector,+ merchant_connector_id: Some(mca_id(id)),+ }+ }++ fn comparison(lhs: &str, value: ast::ValueType) -> ast::Comparison {+ ast::Comparison {+ lhs: lhs.to_string(),+ comparison: ast::ComparisonType::Equal,+ value,+ metadata: HashMap::new(),+ }+ }++ /// A program exercising nesting and every value type euclid and the DE share.+ fn sample_program() -> ast::Program<ConnectorSelection> {+ ast::Program {+ default_selection: ConnectorSelection::Priority(vec![choice(+ RoutableConnectors::Stripe,+ "mca_default0000000000000",+ )]),+ rules: vec![ast::Rule {+ name: "cards_to_adyen".to_string(),+ connector_selection: ConnectorSelection::Priority(vec![+ choice(RoutableConnectors::Adyen, "mca_adyen00000000000000000"),+ choice(RoutableConnectors::Stripe, "mca_stripe0000000000000000"),+ ]),+ statements: vec![ast::IfStatement {+ condition: vec![+ comparison(+ "payment_method",+ ast::ValueType::EnumVariant("card".to_string()),+ ),+ comparison("amount", ast::ValueType::Number(MinorUnit::new(1000))),+ comparison(+ "currency",+ ast::ValueType::EnumVariantArray(vec![+ "USD".to_string(),+ "EUR".to_string(),+ ]),+ ),+ comparison(+ "udf",+ ast::ValueType::MetadataVariant(ast::MetadataValue {+ key: "tier".to_string(),+ value: "gold".to_string(),+ }),+ ),+ comparison("label", ast::ValueType::StrValue("vip".to_string())),+ comparison(+ "amounts",+ ast::ValueType::NumberArray(vec![MinorUnit::new(1), MinorUnit::new(2)]),+ ),+ comparison(+ "band",+ ast::ValueType::NumberComparisonArray(vec![ast::NumberComparison {+ comparison_type: ast::ComparisonType::GreaterThan,+ number: MinorUnit::new(500),+ }]),+ ),+ ],+ nested: Some(vec![ast::IfStatement {+ condition: vec![comparison(+ "card_network",+ ast::ValueType::EnumVariant("visa".to_string()),+ )],+ nested: None,+ }]),+ }],+ }],+ metadata: HashMap::new(),+ }+ }++ fn round_trip(program: ast::Program<ConnectorSelection>) -> ast::Program<ConnectorSelection> {+ let de: Program = program.try_into().expect("euclid -> DE failed");+ de.try_into().expect("DE -> euclid failed")+ }++ /// The property that lets the DE-authored rule be served as a normal typed+ /// response: converting out and back must not change the program.+ #[test]+ fn round_trip_is_lossless() {+ let original = sample_program();+ let expected = serde_json::to_value(&original).unwrap();+ let actual = serde_json::to_value(round_trip(original)).unwrap();+ assert_eq!(expected, actual);+ }++ #[test]+ fn round_trip_is_lossless_for_volume_split() {+ let original = ast::Program {+ default_selection: ConnectorSelection::VolumeSplit(vec![+ ConnectorVolumeSplit {+ connector: choice(RoutableConnectors::Stripe, "mca_stripe0000000000000000"),+ split: 70,+ },+ ConnectorVolumeSplit {+ connector: choice(RoutableConnectors::Adyen, "mca_adyen00000000000000000"),+ split: 30,+ },+ ]),+ rules: vec![],+ metadata: HashMap::new(),+ };+ let expected = serde_json::to_value(&original).unwrap();+ let actual = serde_json::to_value(round_trip(original)).unwrap();+ assert_eq!(expected, actual);+ }++ /// The DE can express a bare single connector; euclid cannot, so it widens to+ /// a one-element priority list, which routes identically.+ #[test]+ fn single_output_widens_to_priority_of_one() {+ let de = Program {+ globals: HashMap::new(),+ default_selection: Output::Single(ConnectorInfo::new(+ "stripe".to_string(),+ Some("mca_stripe0000000000000000".to_string()),+ )),+ rules: vec![],+ metadata: None,+ };+ let converted = ast::Program::try_from(de).expect("single output should convert");+ match converted.default_selection {+ ConnectorSelection::Priority(choices) => {+ assert_eq!(choices.len(), 1);+ assert_eq!(+ choices.first().map(|c| c.connector.to_string()),+ Some("stripe".to_string())+ );+ }+ other => panic!("expected priority, got {other:?}"),+ }+ }++ #[test]+ fn missing_metadata_becomes_empty_not_an_error() {+ let de = Program {+ globals: HashMap::new(),+ default_selection: Output::Priority(vec![ConnectorInfo::new(+ "stripe".to_string(),+ None,+ )]),+ rules: vec![],+ metadata: None,+ };+ assert!(ast::Program::try_from(de).unwrap().metadata.is_empty());+ }++ // Everything below is a DE construct euclid cannot represent. Each must fail+ // loudly rather than round-trip into a rule that routes differently.++ #[test]+ fn rejects_volume_split_priority_output() {+ let de = Program {+ globals: HashMap::new(),+ default_selection: Output::VolumeSplitPriority(vec![]),+ rules: vec![],+ metadata: None,+ };+ assert!(ast::Program::try_from(de).is_err());+ }++ #[test]+ fn rejects_global_ref_value() {+ assert!(convert_value_back(ValueType::GlobalRef("g".to_string())).is_err());+ }++ #[test]+ fn rejects_number_that_would_wrap_negative() {+ // u64::MAX as i64 would be -1, silently inverting the comparison.+ assert!(convert_value_back(ValueType::Number(u64::MAX)).is_err());+ let max_i64 = u64::try_from(i64::MAX).unwrap_or(u64::MAX);+ assert!(de_number_to_minor_unit(max_i64 + 1).is_err());+ assert_eq!(+ de_number_to_minor_unit(max_i64).unwrap(),+ MinorUnit::new(i64::MAX)+ );+ }++ #[test]+ fn rejects_unknown_connector_name() {+ let de = Program {+ globals: HashMap::new(),+ default_selection: Output::Priority(vec![ConnectorInfo::new(+ "not_a_real_connector".to_string(),+ None,+ )]),+ rules: vec![],+ metadata: None,+ };+ assert!(ast::Program::try_from(de).is_err());+ }+}diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 1727af3639..23de8bf9ce 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -183,11 +183,8 @@ pub async fn routing_entry(.with_provider_merchant_id(platform.get_provider().get_provider_merchant_id()).with_profile_id(profile_id.clone());- let routing_source = get_routing_result_source(&state, &dimensions).await;- let is_cutover = matches!(- routing_source,- routing_types::RoutingResultSource::DecisionEngine- );+ // Flag-gated like every other cutover consumer, so the dashboard matches payment-path behavior.+ let is_cutover = is_decision_engine_routing_effective(&state, &dimensions).await;// Mint a fresh one-time code only when a card was clicked (`target`) on a cut-over profile.let redirect_url = match (is_cutover, target) {@@ -262,6 +259,265 @@ pub async fn routing_entry())}+/// Effective cutover for this profile (per-profile source AND the global static flag).+#[cfg(feature = "v1")]+async fn is_profile_cutover_effective(+ state: &SessionState,+ platform: &domain::Platform,+ profile_id: common_utils::id_type::ProfileId,+) -> bool {+ let dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())+ .with_profile_id(profile_id);+ is_decision_engine_routing_effective(state, &dimensions).await+}++/// DE 4xx becomes an actionable InvalidRequestData with the DE's message; anything else stays a 500.+#[cfg(feature = "v1")]+fn map_de_write_error(+ error: error_stack::Report<errors::RoutingError>,+ printable: &'static str,+) -> error_stack::Report<errors::ApiErrorResponse> {+ let client_error_message = match error.current_context() {+ errors::RoutingError::RoutingEventsError {+ message,+ status_code,+ } if (400u16..500).contains(status_code) => Some(message.clone()),+ _ => None,+ };+ match client_error_message {+ Some(message) => error.change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: format!("Decision Engine rejected the request: {message}"),+ }),+ None => error+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(printable),+ }+}++/// Converts to the DE shape; None for kinds the DE cannot host (3DS) or unconvertible programs.+#[cfg(feature = "v1")]+fn convert_euclid_algorithm_to_de_static(+ algorithm: routing_types::StaticRoutingAlgorithm,+) -> Option<StaticRoutingAlgorithm> {+ match algorithm {+ routing_types::StaticRoutingAlgorithm::Advanced(program) => match program.try_into() {+ Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),+ Err(e) => {+ router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid");+ None+ }+ },+ routing_types::StaticRoutingAlgorithm::Single(conn) => {+ Some(StaticRoutingAlgorithm::Single(Box::new((*conn).into())))+ }+ routing_types::StaticRoutingAlgorithm::Priority(connectors) => Some(+ StaticRoutingAlgorithm::Priority(connectors.into_iter().map(Into::into).collect()),+ ),+ routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => Some(+ StaticRoutingAlgorithm::VolumeSplit(splits.into_iter().map(Into::into).collect()),+ ),+ routing_types::StaticRoutingAlgorithm::ThreeDsDecisionRule(_) => {+ router_env::logger::error!(+ "decision_engine_euclid: ThreeDsDecisionRules are not yet implemented"+ );+ None+ }+ }+}++/// Mirrors the "already active" precondition on DE state; best-effort so a failed+/// listing never blocks the idempotent DE activation.+#[cfg(feature = "v1")]+async fn ensure_de_rule_not_already_active(+ state: &SessionState,+ profile_id: &common_utils::id_type::ProfileId,+ transaction_type: &enums::TransactionType,+ de_rule_id: &str,+) -> RouterResult<()> {+ let active_records =+ // Raw records: a rule HS cannot represent is still active on the DE.+ fetch_de_euclid_routing_records_raw(state, profile_id.get_string_repr().to_string(), true)+ .await+ .map_err(|error| {+ router_env::logger::warn!(+ ?error,+ "decision_engine_euclid: failed to list active DE rules for the already-active check"+ );+ })+ .unwrap_or_default();+ utils::when(+ active_records.iter().any(|record| {+ de_euclid_routing_record_algorithm_for(record).as_ref() == Some(transaction_type)+ && record.get("id").and_then(|id| id.as_str()) == Some(de_rule_id)+ }),+ || {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "Algorithm is already active".to_string(),+ })+ },+ )?;+ Ok(())+}++/// Looks for `algorithm_id` on the Decision Engine under a single profile.+///+/// `Ok(None)` means the profile is not cut over, or the DE simply has no such rule.+/// `Err` is reserved for the DE call itself failing, so callers can tell "no such rule"+/// apart from "could not ask".+#[cfg(feature = "v1")]+async fn find_de_record_in_profile(+ state: &SessionState,+ platform: &domain::Platform,+ business_profile: &domain::Profile,+ algorithm_id: &common_utils::id_type::RoutingId,+) -> Result<Option<RoutingAlgorithmRecord>, error_stack::Report<errors::RoutingError>> {+ if !is_profile_cutover_effective(state, platform, business_profile.get_id().clone()).await {+ return Ok(None);+ }++ let records = fetch_de_euclid_routing_records(+ state,+ business_profile.get_id().get_string_repr().to_string(),+ false,+ )+ .await+ .inspect_err(|error| {+ router_env::logger::warn!(+ ?error,+ profile_id = %business_profile.get_id().get_string_repr(),+ "decision_engine_euclid: failed to list DE rules while resolving a rule id"+ );+ })?;++ Ok(records+ .into_iter()+ .find(|record| &record.id == algorithm_id))+}++/// Finds a DE-only rule (no HS row) in the caller's profile, else the merchant's cut-over profiles.+#[cfg(feature = "v1")]+async fn find_de_record_for_algorithm(+ state: &SessionState,+ platform: &domain::Platform,+ authentication_profile_id: Option<common_utils::id_type::ProfileId>,+ algorithm_id: &common_utils::id_type::RoutingId,+) -> RouterResult<Option<(domain::Profile, RoutingAlgorithmRecord)>> {+ let db = state.store.as_ref();+ let processor = platform.get_processor();++ let candidate_profiles = match authentication_profile_id {+ Some(profile_id) => {+ core_utils::validate_and_get_business_profile(db, processor, Some(&profile_id))+ .await?+ .map(|profile| vec![profile])+ .unwrap_or_default()+ }+ None => db+ .list_profile_by_merchant_id(+ processor.get_key_store(),+ processor.get_account().get_id(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to list profiles while resolving a DE-only rule id")?,+ };++ // One profile's DE failure must not abort the scan (a later profile may hold the rule)+ // nor turn an unknown id into anything but a not-found; but if nothing matched and the+ // DE did fail, surface that instead of claiming the rule does not exist.+ let mut de_lookup_error = None;+ for business_profile in candidate_profiles {+ match find_de_record_in_profile(state, platform, &business_profile, algorithm_id).await {+ Ok(Some(record)) => return Ok(Some((business_profile, record))),+ Ok(None) => continue,+ Err(error) => {+ de_lookup_error = Some(error);+ continue;+ }+ }+ }++ match de_lookup_error {+ Some(error) => Err(map_de_write_error(+ error,+ "decision_engine_euclid: failed to list DE rules while resolving a rule id",+ )),+ None => Ok(None),+ }+}++/// Maps a DE rule record onto the same api shape a Hyperswitch-authored rule returns,+/// converting an advanced program back into the euclid AST.+#[cfg(feature = "v1")]+fn de_record_to_merchant_routing_algorithm(+ record: RoutingAlgorithmRecord,+) -> RouterResult<routing_types::MerchantRoutingAlgorithm> {+ let algorithm = match record.algorithm_data {+ StaticRoutingAlgorithm::Single(conn) => {+ routing_types::DeRoutableConnectorChoice::try_from(*conn)+ .map(|choice| {+ routing_types::RoutingAlgorithmWrapper::Static(+ routing_types::StaticRoutingAlgorithm::Single(Box::new(choice.into())),+ )+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to convert DE single connector to api shape")?+ }+ StaticRoutingAlgorithm::Priority(connectors) => connectors+ .into_iter()+ .map(|conn| routing_types::DeRoutableConnectorChoice::try_from(conn).map(Into::into))+ .collect::<Result<Vec<_>, _>>()+ .map(|choices| {+ routing_types::RoutingAlgorithmWrapper::Static(+ routing_types::StaticRoutingAlgorithm::Priority(choices),+ )+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to convert DE priority connectors to api shape")?,+ StaticRoutingAlgorithm::VolumeSplit(splits) => splits+ .into_iter()+ .map(|split| {+ routing_types::DeRoutableConnectorChoice::try_from(split.output).map(|choice| {+ routing_types::ConnectorVolumeSplit {+ connector: choice.into(),+ split: split.split,+ }+ })+ })+ .collect::<Result<Vec<_>, _>>()+ .map(|splits| {+ routing_types::RoutingAlgorithmWrapper::Static(+ routing_types::StaticRoutingAlgorithm::VolumeSplit(splits),+ )+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to convert DE volume split to api shape")?,+ StaticRoutingAlgorithm::Advanced(program) => {+ euclid::frontend::ast::Program::try_from(program)+ .map(|program| {+ routing_types::RoutingAlgorithmWrapper::Static(+ routing_types::StaticRoutingAlgorithm::Advanced(program),+ )+ })+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to convert DE advanced algorithm to euclid AST")?+ }+ };++ Ok(routing_types::MerchantRoutingAlgorithm {+ id: record.id,+ profile_id: record.created_by,+ name: record.name,+ description: record.description.unwrap_or_default(),+ algorithm,+ created_at: record.created_at.assume_utc().unix_timestamp(),+ modified_at: record.modified_at.assume_utc().unix_timestamp(),+ algorithm_for: record.algorithm_for,+ })+}+pub enum TransactionData<'a> {Payment(PaymentsDslInput<'a>),#[cfg(feature = "payouts")]@@ -374,53 +630,101 @@ pub async fn retrieve_merchant_routing_dictionary(routing_metadata,);- let mut result = routing_metadata+ let result: Vec<routing_types::RoutingDictionaryRecord> = routing_metadata.into_iter().map(ForeignInto::foreign_into).collect::<Vec<_>>();- if let Some(profile_ids) = profile_id_list {- let mut de_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];- // DE_TODO: need to replace this with batch API call to reduce the number of network calls- for profile_id in &profile_ids {+ // The merchant-level listing (no profile filter) stays Hyperswitch-only: the DE list+ // API is unpaginated, so merging it into a limit/offset page would break paging.+ // DE-backed rules are served by the profile-scoped listing below.+ #[cfg(feature = "v1")]+ let result =+ merge_de_routing_records(&state, &platform, result, profile_id_list, transaction_type)+ .await?;++ metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]);+ Ok(service_api::ApplicationResponse::Json(+ routing_types::RoutingKind::RoutingAlgorithm(result),+ ))+}++/// Merges DE-held rules into a profile-scoped listing, per profile and only for profiles+/// effectively cut over. Profiles served by Hyperswitch keep the HS records untouched.+#[cfg(feature = "v1")]+async fn merge_de_routing_records(+ state: &SessionState,+ platform: &domain::Platform,+ hs_result: Vec<routing_types::RoutingDictionaryRecord>,+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,+ transaction_type: enums::TransactionType,+) -> RouterResult<Vec<routing_types::RoutingDictionaryRecord>> {+ let Some(profile_ids) = profile_id_list else {+ return Ok(hs_result);+ };++ let mut cutover_profiles = Vec::new();+ for profile_id in &profile_ids {+ if is_profile_cutover_effective(state, platform, profile_id.clone()).await {+ cutover_profiles.push(profile_id.clone());+ }+ }+ if cutover_profiles.is_empty() {+ return Ok(hs_result);+ }++ // Issued concurrently: the Decision Engine lists one profile per call, so a serial loop+ // would cost N round trips (each up to the 5s client timeout) in wall-clock time.+ // DE_TODO: a batch list endpoint on the Decision Engine would also cut the call count.+ let mut de_result: Vec<routing_types::RoutingDictionaryRecord> =+ futures::future::join_all(cutover_profiles.iter().map(|profile_id| async move {let list_request = ListRountingAlgorithmsRequest {created_by: profile_id.get_string_repr().to_string(),};- list_de_euclid_routing_algorithms(&state, list_request)+ list_de_euclid_routing_algorithms(state, list_request).await.map_err(|e| {router_env::logger::error!(decision_engine_error=?e, "decision_engine_euclid");}).ok() // Avoid throwing error if Decision Engine is not available or other errors- .map(|mut de_routing| de_result.append(&mut de_routing));- // filter de_result based on transaction type- de_result.retain(|record| record.algorithm_for == Some(transaction_type));- // append dynamic routing algorithms to de_result- de_result.append(- &mut result- .clone()- .into_iter()- .filter(|record: &routing_types::RoutingDictionaryRecord| {- record.kind == routing_types::RoutingAlgorithmKind::Dynamic- })- .collect::<Vec<_>>(),- );- }- compare_and_log_result(- de_result.clone(),- result.clone(),- "list_routing".to_string(),- false,- );- result =- build_list_routing_result(&state, platform, &result, &de_result, profile_ids.clone())- .await?;- }+ .unwrap_or_default()+ }))+ .await+ .into_iter()+ .flatten()+ .collect();+ // filter de_result based on transaction type+ de_result.retain(|record| record.algorithm_for == Some(transaction_type));+ // append dynamic routing algorithms to de_result once (DE cannot represent them)+ de_result.extend(+ hs_result+ .iter()+ .filter(|record| record.kind == routing_types::RoutingAlgorithmKind::Dynamic)+ .cloned(),+ );+ compare_and_log_result(+ de_result.clone(),+ hs_result.clone(),+ "list_routing".to_string(),+ false,+ );- metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]);- Ok(service_api::ApplicationResponse::Json(- routing_types::RoutingKind::RoutingAlgorithm(result),- ))+ let mut merged = build_list_routing_result(+ state,+ platform.clone(),+ &hs_result,+ &de_result,+ cutover_profiles.clone(),+ )+ .await?;+ // Profiles not cut over keep their Hyperswitch records verbatim.+ let cutover: HashSet<_> = cutover_profiles.into_iter().collect();+ merged.extend(+ hs_result+ .into_iter()+ .filter(|record| !cutover.contains(&record.profile_id)),+ );+ Ok(merged)}async fn build_list_routing_result(@@ -436,17 +740,26 @@ async fn build_list_routing_result(let by_profile =|rec: &&routing_types::RoutingDictionaryRecord| &rec.profile_id == profile_id;let de_result_for_profile = de_results.iter().filter(by_profile).cloned().collect();- let hs_result_for_profile = hs_results.iter().filter(by_profile).cloned().collect();- let business_profile = core_utils::validate_and_get_business_profile(+ let mut hs_result_for_profile: Vec<routing_types::RoutingDictionaryRecord> =+ hs_results.iter().filter(by_profile).cloned().collect();+ let business_profile = match core_utils::validate_and_get_business_profile(db,platform.get_processor(),Some(profile_id),)- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ .await+ {+ Ok(Some(business_profile)) => business_profile,+ // A missing profile must not fail the listing; serve its HS records.+ Ok(None) | Err(_) => {+ router_env::logger::warn!(+ profile_id = %profile_id.get_string_repr(),+ "decision_engine_euclid: profile unavailable during routing list merge, serving HS records"+ );+ list_result.append(&mut hs_result_for_profile);+ continue;+ }+ };let dimensions = dimension_state::Dimensions::new().with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())@@ -602,12 +915,18 @@ pub async fn create_routing_algorithm_under_profile(.await?;}- let mut decision_engine_routing_id: Option<String> = None;-- // Provision the scope before dual-writing into it: DE does not verify the scope exists, and- // a rule attached to one with no merchant account routes fine but breaks the dashboard handoff.- // Non-fatal and gating on purpose — merchants must be able to create rules while DE is down.- // A skipped write shows as pending in the reconciliation report and re-migrating repairs it.+ // 3DS decision rules cannot live on the DE, so they follow the HS path even under+ // cutover. Kind and transaction_type are independent request fields, so both must+ // exclude — otherwise a rule is written on one engine and read back from the other.+ let is_three_ds_rule = matches!(algorithm, EuclidAlgorithm::ThreeDsDecisionRule(_))+ || transaction_type == enums::TransactionType::ThreeDsAuthentication;+ let de_routing_effective = !is_three_ds_rule+ && is_profile_cutover_effective(&state, &platform, profile_id.clone()).await;++ // Provision the scope before writing into it: DE does not verify the scope exists, and+ // a rule attached to one with no merchant account routes fine but breaks the dashboard+ // handoff. Non-fatal for the dual-write path — merchants must be able to create rules+ // while DE is down — but required under cutover, where DE is the only destination.let de_scope_provisioned = match helpers::sync_decision_engine_hierarchy(&state,processor.get_account(),@@ -622,81 +941,94 @@ pub async fn create_routing_algorithm_under_profile(profile_id = ?profile_id.get_string_repr(),"decision_engine_euclid: skipping rule dual-write, scope could not be provisioned");+ if de_routing_effective {+ return Err(err)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "decision_engine_euclid: scope provisioning failed for a cut-over profile",+ );+ }false}};- if let Some(euclid_algorithm) = request.algorithm.clone().filter(|_| de_scope_provisioned) {- let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm {- EuclidAlgorithm::Advanced(program) => match program.try_into() {- Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),- Err(e) => {- router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid");- None- }- },- EuclidAlgorithm::Single(conn) => {- Some(StaticRoutingAlgorithm::Single(Box::new(conn.into())))- }- EuclidAlgorithm::Priority(connectors) => {- let converted: Vec<ConnectorInfo> =- connectors.into_iter().map(Into::into).collect();- Some(StaticRoutingAlgorithm::Priority(converted))- }- EuclidAlgorithm::VolumeSplit(splits) => {- let converted: Vec<VolumeSplit<ConnectorInfo>> =- splits.into_iter().map(Into::into).collect();- Some(StaticRoutingAlgorithm::VolumeSplit(converted))- }- EuclidAlgorithm::ThreeDsDecisionRule(_) => {- router_env::logger::error!(- "decision_engine_euclid: ThreeDsDecisionRules are not yet implemented"- );- None- }+ let maybe_static_algorithm = convert_euclid_algorithm_to_de_static(algorithm.clone());++ let build_routing_rule = |static_algorithm: StaticRoutingAlgorithm| RoutingRule {+ rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()),+ name: name.to_string(),+ description: Some(description.clone()),+ created_by: profile_id.get_string_repr().to_string(),+ algorithm: static_algorithm,+ algorithm_for: transaction_type.into(),+ metadata: Some(RoutingMetadata {+ kind: algorithm.get_kind().foreign_into(),+ }),+ };++ if de_routing_effective {+ // DE-only write: hard-fail on DE errors; nothing is written to Hyperswitch.+ let static_algorithm =+ maybe_static_algorithm.ok_or(errors::ApiErrorResponse::InvalidRequestData {+ message: "This algorithm cannot be represented on the Decision Engine".to_string(),+ })?;+ let routing_rule = build_routing_rule(static_algorithm);++ let de_routing_id = create_de_euclid_routing_algo(&state, &routing_rule)+ .await+ .map_err(|error| map_de_write_error(error, "decision_engine_euclid: rule creation failed on the Decision Engine for a cut-over profile"))?;++ let timestamp = common_utils::date_time::now_unix_timestamp();+ let record = routing_types::RoutingDictionaryRecord {+ id: algorithm_id,+ profile_id,+ name: name.to_string(),+ kind: algorithm.get_kind(),+ description: description.clone(),+ created_at: timestamp,+ modified_at: timestamp,+ algorithm_for: Some(transaction_type.to_owned()),+ decision_engine_routing_id: Some(de_routing_id),};- if let Some(static_algorithm) = maybe_static_algorithm {- let routing_rule = RoutingRule {- rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()),- name: name.to_string(),- description: Some(description.clone()),- created_by: profile_id.get_string_repr().to_string(),- algorithm: static_algorithm,- algorithm_for: transaction_type.into(),- metadata: Some(RoutingMetadata {- kind: algorithm.get_kind().foreign_into(),- }),- };+ metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(record));+ }- match create_de_euclid_routing_algo(&state, &routing_rule).await {- Ok(id) => {- decision_engine_routing_id = Some(id);- }- Err(e)- if matches!(- e.current_context(),- errors::RoutingError::DecisionEngineValidationError(_)- ) =>+ let mut decision_engine_routing_id: Option<String> = None;++ // No scope on the DE means the dual-write would attach the rule to a merchant account+ // that does not exist; skip it and let the reconciliation report surface it as pending.+ if let Some(static_algorithm) = maybe_static_algorithm.filter(|_| de_scope_provisioned) {+ let routing_rule = build_routing_rule(static_algorithm);++ match create_de_euclid_routing_algo(&state, &routing_rule).await {+ Ok(id) => {+ decision_engine_routing_id = Some(id);+ }+ Err(e)+ if matches!(+ e.current_context(),+ errors::RoutingError::DecisionEngineValidationError(_)+ ) =>+ {+ if let errors::RoutingError::DecisionEngineValidationError(msg) =+ e.current_context(){- if let errors::RoutingError::DecisionEngineValidationError(msg) =- e.current_context()- {- router_env::logger::error!(- decision_engine_euclid_error = ?msg,- decision_engine_euclid_request = ?routing_rule,- "failed to create rule in decision_engine with validation error"- );- }- }- Err(e) => {router_env::logger::error!(- decision_engine_euclid_error = ?e,+ decision_engine_euclid_error = ?msg,decision_engine_euclid_request = ?routing_rule,- "failed to create rule in decision_engine"+ "failed to create rule in decision_engine with validation error");}}+ Err(e) => {+ router_env::logger::error!(+ decision_engine_euclid_error = ?e,+ decision_engine_euclid_request = ?routing_rule,+ "failed to create rule in decision_engine"+ );+ }}}@@ -805,21 +1137,74 @@ pub async fn link_routing_config_under_profile(#[cfg(feature = "v1")]pub async fn link_routing_config(state: SessionState,- processor: domain::Processor,+ platform: domain::Platform,authentication_profile_id: Option<common_utils::id_type::ProfileId>,algorithm_id: common_utils::id_type::RoutingId,transaction_type: enums::TransactionType,) -> RouterResponse<routing_types::RoutingDictionaryRecord> {metrics::ROUTING_LINK_CONFIG.add(1, &[]);let db = state.store.as_ref();+ let processor = platform.get_processor().clone();- let routing_algorithm = db+ let routing_algorithm = match db.find_routing_algorithm_by_algorithm_id_processor_merchant_id(&algorithm_id,processor.get_account().get_id(),).await- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;+ {+ Ok(routing_algorithm) => routing_algorithm,+ Err(error) => {+ // DE-only rule ids (e.g. created on the DE dashboard) activate directly on the DE.+ if let Some((business_profile, record)) = find_de_record_for_algorithm(+ &state,+ &platform,+ authentication_profile_id.clone(),+ &algorithm_id,+ )+ .await?+ {+ utils::when(record.algorithm_for != transaction_type, || {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: format!(+ "Cannot use {}'s routing algorithm for {} operation",+ record.algorithm_for, transaction_type+ ),+ })+ })?;++ ensure_de_rule_not_already_active(+ &state,+ business_profile.get_id(),+ &transaction_type,+ record.id.get_string_repr(),+ )+ .await?;++ link_de_euclid_routing_algorithm(+ &state,+ ActivateRoutingConfigRequest {+ created_by: business_profile.get_id().get_string_repr().to_string(),+ routing_algorithm_id: record.id.get_string_repr().to_string(),+ },+ )+ .await+ .map_err(|error| {+ map_de_write_error(+ error,+ "decision_engine_euclid: rule activation failed on the Decision Engine",+ )+ })?;++ metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(+ diesel_models::routing_algorithm::RoutingProfileMetadata::from(record)+ .foreign_into(),+ ));+ }+ return Err(error).change_context(errors::ApiErrorResponse::ResourceIdNotFound);+ }+ };let business_profile = core_utils::validate_and_get_business_profile(db,@@ -1067,6 +1452,108 @@ pub async fn link_routing_config(})})?;+ // 3DS decision rules stay HS-managed even under cutover; kind and+ // transaction_type must agree here and in create/unlink/list, or a rule is+ // written on one engine and read back from the other.+ let de_routing_effective = !matches!(+ routing_algorithm.kind,+ diesel_models::enums::RoutingAlgorithmKind::ThreeDsDecisionRule+ ) && transaction_type+ != enums::TransactionType::ThreeDsAuthentication+ && is_profile_cutover_effective(+ &state,+ &platform,+ business_profile.get_id().clone(),+ )+ .await;++ if de_routing_effective {+ // Activate on the DE (hard-fail), leaving HS state untouched; rules the+ // DE doesn't know yet are created on it first.+ let de_rule_id = match routing_algorithm.decision_engine_routing_id.clone() {+ Some(id) => id,+ None => {+ let profile_id_str =+ business_profile.get_id().get_string_repr().to_string();+ let existing_records =+ fetch_de_euclid_routing_records(&state, profile_id_str.clone(), false)+ .await+ .map_err(|error| {+ map_de_write_error(+ error,+ "decision_engine_euclid: failed to list DE rules during activation",+ )+ })?;++ if existing_records+ .iter()+ .any(|record| record.id == algorithm_id)+ {+ // Migrated rules carry the HS algorithm id on the DE side.+ algorithm_id.get_string_repr().to_string()+ } else {+ let api_algorithm: routing_types::StaticRoutingAlgorithm =+ routing_algorithm+ .algorithm_data+ .clone()+ .parse_value("StaticRoutingAlgorithm")+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("unable to parse routing algorithm data")?;+ let static_algorithm = convert_euclid_algorithm_to_de_static(+ api_algorithm,+ )+ .ok_or(errors::ApiErrorResponse::InvalidRequestData {+ message:+ "This algorithm cannot be represented on the Decision Engine"+ .to_string(),+ })?;+ let routing_rule = RoutingRule {+ rule_id: Some(algorithm_id.get_string_repr().to_owned()),+ name: routing_algorithm.name.clone(),+ description: routing_algorithm.description.clone(),+ created_by: profile_id_str,+ algorithm: static_algorithm,+ algorithm_for: routing_algorithm.algorithm_for.into(),+ metadata: Some(RoutingMetadata {+ kind: routing_algorithm.kind,+ }),+ };+ create_de_euclid_routing_algo(&state, &routing_rule)+ .await+ .map_err(|error| map_de_write_error(error, "decision_engine_euclid: rule creation failed on the Decision Engine during activation"))?+ }+ }+ };++ ensure_de_rule_not_already_active(+ &state,+ business_profile.get_id(),+ &transaction_type,+ &de_rule_id,+ )+ .await?;++ link_de_euclid_routing_algorithm(+ &state,+ ActivateRoutingConfigRequest {+ created_by: business_profile.get_id().get_string_repr().to_string(),+ routing_algorithm_id: de_rule_id,+ },+ )+ .await+ .map_err(|error| {+ map_de_write_error(+ error,+ "decision_engine_euclid: rule activation failed on the Decision Engine",+ )+ })?;++ metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(+ routing_algorithm.foreign_into(),+ ));+ }+utils::when(routing_ref.algorithm_id == Some(algorithm_id.clone()),|| {@@ -1171,20 +1658,39 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(#[cfg(feature = "v1")]pub async fn retrieve_routing_algorithm_from_algorithm_id(state: SessionState,- processor: domain::Processor,+ platform: domain::Platform,authentication_profile_id: Option<common_utils::id_type::ProfileId>,algorithm_id: common_utils::id_type::RoutingId,) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]);let db = state.store.as_ref();+ let processor = platform.get_processor().clone();- let routing_algorithm = db+ let routing_algorithm = match db.find_routing_algorithm_by_algorithm_id_processor_merchant_id(&algorithm_id,processor.get_account().get_id(),).await- .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;+ {+ Ok(routing_algorithm) => routing_algorithm,+ Err(error) => {+ // DE-only rules have no HS row; serve them from the DE.+ if let Some((_business_profile, record)) = find_de_record_for_algorithm(+ &state,+ &platform,+ authentication_profile_id.clone(),+ &algorithm_id,+ )+ .await?+ {+ let response = de_record_to_merchant_routing_algorithm(record)?;+ metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(response));+ }+ return Err(error).to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound);+ }+ };let business_profile = core_utils::validate_and_get_business_profile(db,@@ -1197,6 +1703,24 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;+ // Cut-over first: the profile's rules live on the DE, which can edit a rule in place,+ // so an HS row for a migrated rule may be stale. Serve the DE copy when it has one and+ // keep the HS row as the fallback. A DE failure degrades to the HS row rather than+ // failing a read.+ match find_de_record_in_profile(&state, &platform, &business_profile, &algorithm_id).await {+ Ok(Some(record)) => {+ let response = de_record_to_merchant_routing_algorithm(record)?;+ metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(response));+ }+ Ok(None) => (),+ Err(error) => router_env::logger::warn!(+ ?error,+ profile_id = %business_profile.get_id().get_string_repr(),+ "decision_engine_euclid: DE lookup failed on retrieve, serving the Hyperswitch row"+ ),+ }+let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("unable to parse routing algorithm")?;@@ -1258,7 +1782,7 @@ pub async fn unlink_routing_config_under_profile(#[cfg(feature = "v1")]pub async fn unlink_routing_config(state: SessionState,- processor: domain::Processor,+ platform: domain::Platform,request: routing_types::RoutingConfigRequest,authentication_profile_id: Option<common_utils::id_type::ProfileId>,transaction_type: enums::TransactionType,@@ -1266,6 +1790,7 @@ pub async fn unlink_routing_config(metrics::ROUTING_UNLINK_CONFIG.add(1, &[]);let db = state.store.as_ref();+ let processor = platform.get_processor().clone();let profile_id = request.profile_id@@ -1284,6 +1809,57 @@ pub async fn unlink_routing_config(authentication_profile_id,&business_profile,)?;++ // 3DS decision rules stay HS-managed even under cutover.+ let de_routing_effective = transaction_type+ != enums::TransactionType::ThreeDsAuthentication+ && is_profile_cutover_effective(&state, &platform, profile_id.clone()).await;++ if de_routing_effective {+ // Deactivate on the DE (hard-fail). Raw records so an unrepresentable+ // active rule errors instead of reporting "already inactive".+ let profile_id_str = profile_id.get_string_repr().to_string();+ let raw_active_record = fetch_de_euclid_routing_records_raw(+ &state,+ profile_id_str.clone(),+ true,+ )+ .await+ .map_err(|error| map_de_write_error(error, "decision_engine_euclid: failed to list active DE rules during deactivation"))?+ .into_iter()+ .find(|record| {+ de_euclid_routing_record_algorithm_for(record) == Some(transaction_type)+ })+ .ok_or(errors::ApiErrorResponse::PreconditionFailed {+ message: "Algorithm is already inactive".to_string(),+ })?;+ let active_record = parse_de_euclid_routing_record(raw_active_record).ok_or(+ errors::ApiErrorResponse::InvalidRequestData {+ message: "The active rule on the Decision Engine cannot be managed through Hyperswitch; deactivate it from the Decision Engine dashboard".to_string(),+ },+ )?;++ deactivate_de_euclid_routing_algorithm(+ &state,+ DeactivateRoutingConfigRequest {+ created_by: profile_id_str,+ routing_algorithm_id: active_record.id.get_string_repr().to_string(),+ },+ )+ .await+ .map_err(|error| {+ map_de_write_error(+ error,+ "decision_engine_euclid: rule deactivation failed on the Decision Engine",+ )+ })?;++ metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);+ return Ok(service_api::ApplicationResponse::Json(+ diesel_models::routing_algorithm::RoutingProfileMetadata::from(active_record)+ .foreign_into(),+ ));+ }let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type {enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),#[cfg(feature = "payouts")]@@ -1601,6 +2177,52 @@ pub async fn retrieve_linked_routing_config()};+ // Prefetch the Decision Engine's active rules for every eligible profile at once. The+ // engine lists one profile per call, so issuing them inside the loop cost one serial+ // round trip per profile, each up to the 5s client timeout. A profile is eligible if+ // Hyperswitch has an active ref (the pre-existing behaviour) or it is cut over (where+ // the rule can live only on the engine). Absent from the map means "do not consult".+ let de_active_by_profile: HashMap<+ common_utils::id_type::ProfileId,+ Vec<routing_types::RoutingDictionaryRecord>,+ > = futures::future::join_all(business_profiles.iter().map(|business_profile| {+ let profile_id = business_profile.get_id().clone();+ // Parsed leniently only to decide eligibility; the loop below still parses+ // authoritatively and surfaces a malformed ref as an error.+ let has_hs_ref = match transaction_type {+ enums::TransactionType::Payment => &business_profile.routing_algorithm,+ #[cfg(feature = "payouts")]+ enums::TransactionType::Payout => &business_profile.payout_routing_algorithm,+ enums::TransactionType::ThreeDsAuthentication => {+ &business_profile.three_ds_decision_rule_algorithm+ }+ }+ .clone()+ .and_then(|val| {+ val.parse_value::<routing_types::RoutingAlgorithmRef>("RoutingAlgorithmRef")+ .ok()+ })+ .and_then(|routing_ref| routing_ref.algorithm_id)+ .is_some();+ let state = &state;+ let platform = &platform;+ async move {+ // 3DS rules never live on the DE.+ let de_routing_effective = transaction_type+ != enums::TransactionType::ThreeDsAuthentication+ && is_profile_cutover_effective(state, platform, profile_id.clone()).await;+ if !has_hs_ref && !de_routing_effective {+ return None;+ }+ let records = fetch_decision_engine_active_rules(state, &profile_id).await;+ Some((profile_id, records))+ }+ }))+ .await+ .into_iter()+ .flatten()+ .collect();+let mut active_algorithms = Vec::new();for business_profile in business_profiles {@@ -1622,23 +2244,29 @@ pub async fn retrieve_linked_routing_config(.attach_printable("unable to deserialize routing algorithm ref from merchant account")?.unwrap_or_default();- if let Some(algorithm_id) = routing_ref.algorithm_id {- let record = db- .find_routing_algorithm_metadata_by_algorithm_id_profile_id(- &algorithm_id,- profile_id,- )- .await- .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;- let hs_records: Vec<routing_types::RoutingDictionaryRecord> =- vec![record.foreign_into()];- let de_records = retrieve_decision_engine_active_rules(- &state,+ let hs_records: Vec<routing_types::RoutingDictionaryRecord> = match routing_ref.algorithm_id+ {+ Some(algorithm_id) => {+ let record = db+ .find_routing_algorithm_metadata_by_algorithm_id_profile_id(+ &algorithm_id,+ profile_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;+ vec![record.foreign_into()]+ }+ None => Vec::new(),+ };++ // Prefetched above: present only for profiles that have an HS ref or are cut over+ // (a cut-over profile can be active only on the DE, with no HS ref at all).+ if let Some(de_prefetched) = de_active_by_profile.get(profile_id).cloned() {+ let de_records = merge_decision_engine_active_rules(+ de_prefetched,&transaction_type,- profile_id.clone(),hs_records.clone(),- )- .await;+ );compare_and_log_result(de_records.clone(),hs_records.clone(),@@ -1719,14 +2347,32 @@ pub async fn retrieve_decision_engine_active_rules(profile_id: common_utils::id_type::ProfileId,hs_records: Vec<routing_types::RoutingDictionaryRecord>,) -> Vec<routing_types::RoutingDictionaryRecord> {- let mut de_records =- list_de_euclid_active_routing_algorithm(state, profile_id.get_string_repr().to_owned())- .await- .map_err(|e| {- router_env::logger::error!(?e, "Failed to list DE Euclid active routing algorithm");- })- .ok() // Avoid throwing error if Decision Engine is not available or other errors thrown- .unwrap_or_default();+ let de_records = fetch_decision_engine_active_rules(state, &profile_id).await;+ merge_decision_engine_active_rules(de_records, transaction_type, hs_records)+}++/// The network half of the active-rules lookup, split out so callers listing several+/// profiles can issue the per-profile calls concurrently instead of serially.+pub async fn fetch_decision_engine_active_rules(+ state: &SessionState,+ profile_id: &common_utils::id_type::ProfileId,+) -> Vec<routing_types::RoutingDictionaryRecord> {+ list_de_euclid_active_routing_algorithm(state, profile_id.get_string_repr().to_owned())+ .await+ .map_err(|e| {+ router_env::logger::error!(?e, "Failed to list DE Euclid active routing algorithm");+ })+ .ok() // Avoid throwing error if Decision Engine is not available or other errors thrown+ .unwrap_or_default()+}++/// The pure half: splice in the Hyperswitch dynamic algorithms the DE cannot represent and+/// keep only the requested transaction type.+pub fn merge_decision_engine_active_rules(+ mut de_records: Vec<routing_types::RoutingDictionaryRecord>,+ transaction_type: &enums::TransactionType,+ hs_records: Vec<routing_types::RoutingDictionaryRecord>,+) -> Vec<routing_types::RoutingDictionaryRecord> {// Use Hs records to list the dynamic algorithms as DE is not supporting dynamic algorithms in HS standardlet mut dynamic_algos = hs_records.into_iter()@@ -2902,18 +3548,16 @@ async fn migrate_rules_for_profile(// The decision engine keys rule create on the Hyperswitch algorithm id, so re-writing an// existing rule is a key conflict — without this a finished migration reads as total failure.// A read failure here is not fatal: the set stays empty and every rule is attempted.- let already_in_decision_engine: HashSet<String> = match list_de_euclid_routing_algorithms(+ // Raw records: a rule shape Hyperswitch cannot represent is still present on the DE, and+ // reading it as absent would re-create it on every run.+ let already_in_decision_engine: HashSet<String> = match fetch_de_euclid_routing_records_raw(&state,- ListRountingAlgorithmsRequest {- created_by: profile_id.get_string_repr().to_string(),- },+ profile_id.get_string_repr().to_string(),+ false,).await{- Ok(records) => records- .into_iter()- .map(|record| record.id.get_string_repr().to_string())- .collect(),+ Ok(records) => de_euclid_routing_record_ids(&records).into_iter().collect(),Err(err) => {router_env::logger::warn!(decision_engine_error = ?err,diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex 9452e10db6..5c9345e769 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -2950,7 +2950,9 @@ pub async fn redact_routing_cache();let routing_payouts_cache_key = cache::CacheKind::Routing(routing_payouts_key.clone().into());- let routing_payments_cache_key = cache::CacheKind::CGraph(routing_payments_key.clone().into());+ // Routing, not CGraph: the kind selects which in-memory cache subscribers evict from, and+ // this key lives in ROUTING_CACHE. (Redis deletion is by key, so only other pods were affected.)+ let routing_payments_cache_key = cache::CacheKind::Routing(routing_payments_key.clone().into());cache::redact_from_redis_and_publish(state.store.get_cache_store().as_ref(),[routing_payouts_cache_key, routing_payments_cache_key],diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rsindex 6f20e4b617..233e98716e 100644--- a/crates/router/src/routes/profiles.rs+++ b/crates/router/src/routes/profiles.rs@@ -259,6 +259,7 @@ pub async fn profile_update(&req,payload,|state, auth_data, req, _| {+ let provider_merchant_id = auth_data.platform.get_provider().get_provider_merchant_id();update_profile(state,&profile_id,@@ -270,6 +271,7 @@ pub async fn profile_update(.clone(),auth_data.platform.get_processor().get_key_store().clone(),req,+ Some(provider_merchant_id),)},auth::auth_type(@@ -330,6 +332,7 @@ pub async fn profile_update(merchant_account.get_id().clone(),key_store,req,+ None,)},auth::auth_type(diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rsindex 62576662b0..b9b71454df 100644--- a/crates/router/src/routes/routing.rs+++ b/crates/router/src/routes/routing.rs@@ -3,6 +3,8 @@//! Functions that are used to perform the api level configuration, retrieval, updation//! of Routing configs.+use std::str::FromStr;+use actix_web::{web, HttpRequest, Responder};use api_models::{enums,@@ -172,7 +174,7 @@ pub async fn routing_link_config(let profile_id = auth.profile.map(|profile| profile.get_id().clone());routing::link_routing_config(state,- auth.platform.get_processor().clone(),+ auth.platform.clone(),profile_id,algorithm,transaction_type@@ -270,7 +272,7 @@ pub async fn routing_retrieve_config(let profile_id = auth.profile.map(|profile| profile.get_id().clone());routing::retrieve_routing_algorithm_from_algorithm_id(state,- auth.platform.get_processor().clone(),+ auth.platform.clone(),profile_id,algorithm_id,)@@ -489,7 +491,7 @@ pub async fn routing_unlink_config(let profile_id = auth.profile.map(|profile| profile.get_id().clone());routing::unlink_routing_config(state,- auth.platform.get_processor().clone(),+ auth.platform.clone(),payload_req.clone(),profile_id,transaction_type@@ -1678,7 +1680,24 @@ pub async fn evaluate_routing_rule(state,&req,json_payload.clone(),- |state, _auth: auth::AuthenticationData, payload, _| async move {+ |state, auth: auth::AuthenticationData, payload, _| async move {+ // `created_by` is a DE profile id; restrict it to the caller's merchant.+ let profile_id = common_utils::id_type::ProfileId::from_str(&payload.created_by)+ .change_context(ApiErrorResponse::InvalidRequestData {+ message: "created_by is not a valid profile id".to_string(),+ })?;+ // A profile outside the caller's merchant surfaces as ProfileNotFound; report it+ // as the ownership failure it is rather than leaking a lookup error.+ crate::core::utils::validate_and_get_business_profile(+ state.store.as_ref(),+ auth.platform.get_processor(),+ Some(&profile_id),+ )+ .await+ .change_context(ApiErrorResponse::InvalidRequestData {+ message: "created_by does not belong to the authenticated merchant".to_string(),+ })?;+let euclid_response: RoutingEvaluateResponse =EuclidApiClient::send_decision_engine_request(&state,