Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(revenue-recovery): add A/B monitoring implementation (#14285)

Rohan Malib7d06975d045
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 0ad78ac0cd..aaa2d16727 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -25315,6 +25315,14 @@
"description": "First Payment Attempt Network Advice Code",
"example": "02",
"nullable": true
+ },
+ "revenue_recovery_ab_routing": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RevenueRecoveryABAlgorithm"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -31912,6 +31920,13 @@
}
}
},
+ "RevenueRecoveryABAlgorithm": {
+ "type": "string",
+ "description": "The retry implementations available within the `Smart` arm of revenue recovery.",
+ "enum": [
+ "adaptive_retry"
+ ]
+ },
"RevenueRecoveryAlgorithmType": {
"type": "string",
"enum": [
@@ -34935,9 +34950,16 @@
"enum": [
"Unset"
]
+ },
+ {
+ "type": "string",
+ "description": "Leave the active attempt id as it is.",
+ "enum": [
+ "NoAction"
+ ]
}
],
- "description": "Whether active attempt is to be set/unset"
+ "description": "Whether active attempt is to be set/unset/left alone"
},
"UpdateApiKeyRequest": {
"type": "object",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 2b4d6dd8e8..54c90869bc 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -70,7 +70,7 @@ pub enum PayoutConnectors {
}
#[cfg(feature = "v2")]
-/// Whether active attempt is to be set/unset
+/// Whether active attempt is to be set/unset/left alone
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub enum UpdateActiveAttempt {
/// Request to set the active attempt id
@@ -78,6 +78,8 @@ pub enum UpdateActiveAttempt {
Set(common_utils::id_type::GlobalAttemptId),
/// To unset the active attempt id
Unset,
+ /// Leave the active attempt id as it is.
+ NoAction,
}
/// Generic enum to handle updating or clearing a field
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 9e10ed0ec5..5caa4b3693 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -14183,6 +14183,10 @@ pub struct PaymentRevenueRecoveryMetadata {
/// First Payment Attempt Network Advice Code
#[schema(value_type = Option<String>, example = "02")]
pub first_payment_attempt_network_advice_code: Option<String>,
+ /// Revenue Recovery A/B routing: the algorithm this invoice was assigned to.
+ #[schema(value_type = Option<RevenueRecoveryABAlgorithm>, example = "adaptive_retry")]
+ #[serde(default)]
+ pub revenue_recovery_ab_routing: Option<common_enums::RevenueRecoveryABAlgorithm>,
}
#[cfg(feature = "v2")]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a67ef1df35..a086ee6d35 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -373,6 +373,28 @@ pub enum RevenueRecoveryAlgorithmType {
Cascading,
}
+/// The retry implementations available within the `Smart` arm of revenue recovery.
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Hash,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ strum::EnumIter,
+ ToSchema,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum RevenueRecoveryABAlgorithm {
+ /// Adaptive Retry algorithm.
+ AdaptiveRetry,
+}
+
#[derive(
Default,
Clone,
diff --git a/crates/common_utils/src/id_type/global_id/payment.rs b/crates/common_utils/src/id_type/global_id/payment.rs
index 62f72375c1..fc83b5287c 100644
--- a/crates/common_utils/src/id_type/global_id/payment.rs
+++ b/crates/common_utils/src/id_type/global_id/payment.rs
@@ -43,6 +43,12 @@ impl GlobalPaymentId {
}
}
+impl crate::id_type::TargetingKey for GlobalPaymentId {
+ fn targeting_key_value(&self) -> &str {
+ self.get_string_repr()
+ }
+}
+
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId {
type Error = error_stack::Report<errors::ValidationError>;
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index 79acee7f45..b9da46f2d5 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -239,6 +239,11 @@ pub mod business_status {
/// A task that reaches this status should not be retried (rescheduled for execution) later.
pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED";
+ /// A revenue recovery invoice reached the end of its grace window, so there is no legitimate
+ /// time left to schedule a retry at — whatever retry budget remains. Distinct from
+ /// `RETRIES_EXCEEDED`, which is the budget itself running out.
+ pub const GRACE_WINDOW_EXPIRED: &str = "GRACE_WINDOW_EXPIRED";
+
/// The outgoing webhook was successfully delivered in the initial attempt.
/// Further retries of the task are not required.
pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL";
diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs
index 87ee72bf87..ad1250eb47 100644
--- a/crates/diesel_models/src/types.rs
+++ b/crates/diesel_models/src/types.rs
@@ -505,6 +505,9 @@ pub struct PaymentRevenueRecoveryMetadata {
pub first_payment_attempt_network_decline_code: Option<String>,
/// First Payment Attempt Network Advice Code
pub first_payment_attempt_network_advice_code: Option<String>,
+ /// Revenue Recovery A/B routing: the algorithm this invoice was assigned to.
+ #[serde(default)]
+ pub revenue_recovery_ab_routing: Option<common_enums::RevenueRecoveryABAlgorithm>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index a9fdb72e0d..d552137437 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -953,6 +953,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: from.invoice_billing_started_at_time,
+ revenue_recovery_ab_routing: from.revenue_recovery_ab_routing,
}
}
@@ -978,6 +979,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: self.invoice_billing_started_at_time,
+ revenue_recovery_ab_routing: self.revenue_recovery_ab_routing,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 9541928578..b6390d4fbe 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1725,6 +1725,9 @@ where
first_payment_attempt_network_advice_code: first_network_advice_code,
first_payment_attempt_network_decline_code: first_network_decline_code,
first_payment_attempt_pg_error_code: first_pg_error_code,
+ revenue_recovery_ab_routing: revenue_recovery
+ .as_ref()
+ .and_then(|data| data.revenue_recovery_ab_routing),
}),
None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in payment attempt")?,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 31fa0c2b1d..bec3d15e68 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -1658,8 +1658,10 @@ impl PaymentAttempt {
self.amount_details.surcharge_amount
}
+ /// Network of the card, as stored on the attempt's payment method data.
pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> {
- todo!()
+ self.extract_additional_card_info()
+ .and_then(|card_info| card_info.card_network)
}
/// Funding type of the card, as stored on the attempt's payment method data.
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index cdb3491eeb..f443c8436f 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -1001,6 +1001,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AdditionalCardInfo,
common_types::payments::RecoveryAction,
api_models::enums::RevenueRecoveryAlgorithmType,
+ api_models::enums::RevenueRecoveryABAlgorithm,
api_models::enums::ProcessTrackerStatus,
api_models::proxy::ProxyRequest,
api_models::proxy::ProxyResponse,
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index a88270f88a..c0a9cc1b14 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -452,6 +452,10 @@ pub mod superposition {
/// Whether the adaptive revenue recovery retry algorithm — static ladder combined with
/// the smart algorithm — replaces the decider-based smart retry implementation
pub const ADAPTIVE_RETRY_ENABLED: &str = "revenue_recovery.adaptive_retry_enabled";
+ /// Whether A/B routing decides which retry implementation an invoice runs.
+ pub const REVENUE_RECOVERY_AB_ENABLED: &str = "revenue_recovery.ab_enabled";
+ /// Which retry implementation inside the `Smart` arm an invoice runs under A/B routing.
+ pub const REVENUE_RECOVERY_AB_ALGORITHM: &str = "revenue_recovery.ab_algorithm";
/// Days from the first attempt during which an invoice may still be retried
pub const RECOVERY_GRACE_PERIOD_DAYS: &str = "revenue_recovery.grace_period_days";
/// Total retries an invoice is allowed across its whole recovery lifecycle
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index 52f5ae48e5..58c280ad85 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -724,6 +724,47 @@ impl DatabaseBackedConfig for AdaptiveRetryEnabled {
}
}
+config! {
+ superposition_key = REVENUE_RECOVERY_AB_ENABLED,
+ output = bool,
+ default = false,
+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
+ targeting_key = id_type::PaymentId
+}
+
+impl DatabaseBackedConfig for RevenueRecoveryAbEnabled {
+ const KEY: &'static str = "revenue_recovery_ab_enabled";
+
+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ dimensions
+ .get_profile_id()
+ .map(|profile_id| format!("{}_{}", Self::KEY, profile_id.get_string_repr()))
+ }
+}
+
+// Unlike the other revenue recovery configs this one is bucketed: the targeting key is the
+// invoice, so an experiment on this key splits traffic per invoice rather than per merchant.
+#[cfg(feature = "v2")]
+config! {
+ superposition_key = REVENUE_RECOVERY_AB_ALGORITHM,
+ output = common_enums::RevenueRecoveryABAlgorithm,
+ default = common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry,
+ string_enum = true,
+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
+ targeting_key = id_type::GlobalPaymentId
+}
+
+#[cfg(feature = "v2")]
+impl DatabaseBackedConfig for RevenueRecoveryAbAlgorithm {
+ const KEY: &'static str = "revenue_recovery_ab_algorithm";
+
+ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ dimensions
+ .get_profile_id()
+ .map(|profile_id| format!("{}_{}", Self::KEY, profile_id.get_string_repr()))
+ }
+}
+
config! {
superposition_key = RECOVERY_GRACE_PERIOD_DAYS,
output = i64,
diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs
index 909bf10e17..37377ea354 100644
--- a/crates/router/src/core/payments/operations/payment_update_intent.rs
+++ b/crates/router/src/core/payments/operations/payment_update_intent.rs
@@ -247,12 +247,11 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda
None => payment_intent.amount_details,
};
- let active_attempt_id = set_active_attempt_id
- .map(|active_attempt_req| match active_attempt_req {
- UpdateActiveAttempt::Set(global_attempt_id) => Some(global_attempt_id),
- UpdateActiveAttempt::Unset => None,
- })
- .unwrap_or(payment_intent.active_attempt_id);
+ let active_attempt_id = match set_active_attempt_id {
+ Some(UpdateActiveAttempt::Set(global_attempt_id)) => Some(global_attempt_id),
+ Some(UpdateActiveAttempt::Unset) => None,
+ Some(UpdateActiveAttempt::NoAction) | None => payment_intent.active_attempt_id,
+ };
let payment_intent = hyperswitch_domain_models::payments::PaymentIntent {
amount_details: updated_amount_details,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index e8b17846cd..e6c0d04f2b 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -7796,6 +7796,8 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payment
.clone(),
invoice_billing_started_at_time: payment_revenue_recovery_metadata
.invoice_billing_started_at_time,
+ revenue_recovery_ab_routing: payment_revenue_recovery_metadata
+ .revenue_recovery_ab_routing,
}
});
let apple_pay_details = feature_metadata
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index 768f97141d..1df0b54748 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -64,6 +64,72 @@ use common_enums::enums::ProcessTrackerStatus;
#[cfg(feature = "v1")]
use crate::types::common_enums;
+/// Resolves the retry implementation this invoice should use from the A/B configuration and
+/// records it on the intent, so every later retry replays the same one.
+pub async fn assign_and_record_ab_routing(
+ state: &SessionState,
+ payment_id: &GlobalPaymentId,
+ feature_metadata: Option<api_payments::FeatureMetadata>,
+ revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
+ dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
+) -> common_enums::RevenueRecoveryABAlgorithm {
+ let assigned_algorithm = dimensions
+ .get_revenue_recovery_ab_algorithm(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ Some(payment_id),
+ )
+ .await;
+
+ let updated_feature_metadata = feature_metadata.and_then(|mut feature_metadata| {
+ feature_metadata
+ .revenue_recovery
+ .as_mut()
+ .map(|revenue_recovery_metadata| {
+ revenue_recovery_metadata.revenue_recovery_ab_routing = Some(assigned_algorithm);
+ })
+ .map(|_| feature_metadata)
+ });
+
+ match updated_feature_metadata {
+ Some(feature_metadata) => {
+ let payment_update_req =
+ api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
+ feature_metadata,
+ enums::UpdateActiveAttempt::NoAction,
+ );
+
+ match Box::pin(api::update_payment_intent_api(
+ state,
+ payment_id.clone(),
+ revenue_recovery_payment_data,
+ payment_update_req,
+ ))
+ .await
+ {
+ Ok(_) => router_env::logger::info!(
+ payment_id = %payment_id.get_string_repr(),
+ algorithm = %assigned_algorithm,
+ "A/B routing assigned a retry implementation to this invoice"
+ ),
+ Err(error) => router_env::logger::error!(
+ ?error,
+ payment_id = %payment_id.get_string_repr(),
+ algorithm = %assigned_algorithm,
+ "Failed to record the A/B routing assignment on the invoice"
+ ),
+ }
+ }
+ None => router_env::logger::warn!(
+ payment_id = %payment_id.get_string_repr(),
+ "Cannot record an A/B routing assignment: the invoice has no revenue \
+ recovery metadata"
+ ),
+ }
+
+ assigned_algorithm
+}
+
#[allow(clippy::too_many_arguments)]
pub async fn upsert_calculate_pcr_task(
billing_connector_account: &domain::MerchantConnectorAccount,
@@ -190,6 +256,53 @@ pub async fn upsert_calculate_pcr_task(
1,
router_env::metric_attributes!(("flow", "CalculateWorkflow")),
);
+
+ // A/B routing normally assigns the invoice its retry implementation here, once. The
+ // CALCULATE workflow repeats the assignment only for an invoice that reaches it
+ // without one, which means this write did not land.
+ let dimensions = crate::core::configs::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_organization_id(
+ platform
+ .get_processor()
+ .get_account()
+ .organization_id
+ .clone(),
+ )
+ .with_profile_id(business_profile.get_id().clone());
+
+ if dimensions
+ .get_revenue_recovery_ab_enabled(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await
+ {
+ // Boxed so the recovery payment data below lives on the heap rather than in this
+ // function's future.
+ Box::pin(async {
+ let revenue_recovery_payment_data = pcr::RevenueRecoveryPaymentData {
+ merchant_account: platform.get_processor().get_account().clone(),
+ profile: business_profile.clone(),
+ key_store: platform.get_processor().get_key_store().clone(),
+ billing_mca: billing_connector_account.clone(),
+ retry_algorithm: revenue_recovery_retry,
+ psync_data: None,
+ };
+
+ assign_and_record_ab_routing(
+ state,
+ payment_id,
+ recovery_intent_from_payment_intent.feature_metadata.clone(),
+ &revenue_recovery_payment_data,
+ &dimensions,
+ )
+ .await;
+ })
+ .await;
+ }
}
}
@@ -596,6 +709,41 @@ pub async fn perform_payments_sync(
Ok(())
}
+/// When the invoice's recovery grace window closes: its billing start plus the configured grace
+/// period.
+async fn get_recovery_grace_window_end(
+ state: &SessionState,
+ payment_intent: &PaymentIntent,
+ billing_connector: common_enums::connector_enums::Connector,
+) -> CustomResult<time::PrimitiveDateTime, errors::RecoveryError> {
+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_connector(billing_connector);
+
+ let grace_period_days = dimensions
+ .get_recovery_grace_period_days(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+
+ let grace_window_start = payment_intent
+ .get_revenue_recovery_metadata()
+ .and_then(|revenue_recovery_metadata| {
+ revenue_recovery_metadata.invoice_billing_started_at_time
+ })
+ .ok_or(errors::RecoveryError::ValueNotFound)
+ .attach_printable(
+ "Cannot bound the invoice by its grace window: the intent has no billing start time",
+ )?;
+
+ grace_window_start
+ .checked_add(time::Duration::days(grace_period_days))
+ .ok_or(errors::RecoveryError::ValueNotFound)
+ .attach_printable("The end of the grace window does not fit a timestamp")
+}
+
/// `attempts_already_made` counts the initial charge, which is not a retry, so the retry about to
/// be scheduled is retry number `attempts_already_made`.
fn is_retry_budget_exhausted(attempts_already_made: i32, max_retry_count: u16) -> bool {
@@ -697,47 +845,104 @@ pub async fn perform_calculate_workflow(
"Failed to get max retry count from billing merchant connector account",
)?;
- let (payment_processor_token_response, next_static_ladder_progress) =
- if is_retry_budget_exhausted(process.retry_count, max_retry_count) {
- logger::info!(
- process_id = %process.id,
- retry_count = process.retry_count,
- ?max_retry_count,
- "Invoice reached the retry ceiling configured on the billing MCA"
- );
- (
- revenue_recovery_workflow::PaymentProcessorTokenResponse::RetriesExhausted,
- None,
- )
- } else {
- // 3. Get best available token
- match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(
+ let retry_budget_exhausted = is_retry_budget_exhausted(process.retry_count, max_retry_count);
+
+ // 2b. Bound the invoice by its grace window as well as its retry count.
+ let grace_window_end = if retry_budget_exhausted {
+ None
+ } else {
+ Some(
+ get_recovery_grace_window_end(
state,
- &connector_customer_id,
payment_intent,
revenue_recovery_payment_data.billing_mca.connector_name,
- retry_algorithm_type,
- process.retry_count,
- tracking_data,
- &static_ladder_progress,
- max_retry_count,
+ )
+ .await?,
)
- .await
- {
- Ok(token_and_schedule) => token_and_schedule,
- Err(e) => {
- logger::error!(
- error = ?e,
- connector_customer_id = %connector_customer_id,
- "Failed to get best PSP token"
- );
- (
- revenue_recovery_workflow::PaymentProcessorTokenResponse::None,
- None,
- )
- }
+ };
+
+ let grace_window_elapsed = grace_window_end
+ .is_some_and(|grace_window_end| grace_window_end <= common_utils::date_time::now());
+
+ let (payment_processor_token_response, next_static_ladder_progress) = if retry_budget_exhausted
+ {
+ logger::info!(
+ process_id = %process.id,
+ retry_count = process.retry_count,
+ ?max_retry_count,
+ "Invoice reached the retry ceiling configured on the billing MCA"
+ );
+ (
+ revenue_recovery_workflow::PaymentProcessorTokenResponse::RetriesExhausted,
+ None,
+ )
+ } else if grace_window_elapsed {
+ logger::info!(
+ process_id = %process.id,
+ retry_count = process.retry_count,
+ ?grace_window_end,
+ "Invoice is past its recovery grace window"
+ );
+ (
+ revenue_recovery_workflow::PaymentProcessorTokenResponse::GraceWindowExpired,
+ None,
+ )
+ } else {
+ // The allowances the adaptive model needs, derived once here from the window
+ // established above rather than inside an arm. Unreachable as `None`: this arm is
+ // only taken when retries remain, and the window is computed — or errored — above.
+ let grace_window_end = grace_window_end
+ .ok_or(errors::RecoveryError::ValueNotFound)
+ .attach_printable("Cannot derive the recovery allowances: the grace window is unset")?;
+
+ let remaining_grace_days = u32::try_from(
+ (grace_window_end - common_utils::date_time::now())
+ .whole_days()
+ .max(0),
+ )
+ .change_context(errors::RecoveryError::ValueNotFound)
+ .attach_printable("The days left in the grace window do not fit a day count")?;
+
+ let retries_already_made = u32::try_from(process.retry_count)
+ .change_context(errors::RecoveryError::ValueNotFound)
+ .attach_printable("Failed to read how many retries have already been made")?;
+
+ // Saturating so an invoice already past its ceiling reads as no budget left rather
+ // than wrapping to an enormous one.
+ let remaining_budget = u32::from(max_retry_count).saturating_sub(retries_already_made);
+
+ // 3. Get best available token
+ match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(
+ state,
+ &connector_customer_id,
+ payment_intent,
+ revenue_recovery_payment_data.billing_mca.connector_name,
+ retry_algorithm_type,
+ process.retry_count,
+ tracking_data,
+ &static_ladder_progress,
+ max_retry_count,
+ platform.get_provider().get_provider_merchant_id(),
+ remaining_grace_days,
+ remaining_budget,
+ revenue_recovery_payment_data,
+ )
+ .await
+ {
+ Ok(token_and_schedule) => token_and_schedule,
+ Err(e) => {
+ logger::error!(
+ error = ?e,
+ connector_customer_id = %connector_customer_id,
+ "Failed to get best PSP token"
+ );
+ (
+ revenue_recovery_workflow::PaymentProcessorTokenResponse::None,
+ None,
+ )
}
- };
+ }
+ };
match payment_processor_token_response {
revenue_recovery_workflow::PaymentProcessorTokenResponse::ScheduledTime {
@@ -859,6 +1064,34 @@ pub async fn perform_calculate_workflow(
event_type = Some(common_enums::EventType::PaymentFailed);
}
+ revenue_recovery_workflow::PaymentProcessorTokenResponse::GraceWindowExpired => {
+ // Terminal for the same reason as an exhausted ladder — rescheduling would keep the job
+ // alive forever — but recorded under its own business status so the two reasons stay
+ // distinguishable after the fact.
+ logger::info!(
+ process_id = %process.id,
+ connector_customer_id = %connector_customer_id,
+ retry_count = process.retry_count,
+ "Grace window expired, finishing CALCULATE_WORKFLOW"
+ );
+
+ db.as_scheduler()
+ .finish_process_with_business_status(
+ process.clone(),
+ business_status::GRACE_WINDOW_EXPIRED,
+ )
+ .await
+ .map_err(|e| {
+ logger::error!(
+ process_id = %process.id,
+ error = ?e,
+ "Failed to finish CALCULATE_WORKFLOW after the grace window expired"
+ );
+ sch_errors::ProcessTrackerError::ProcessUpdateFailed
+ })?;
+
+ event_type = Some(common_enums::EventType::PaymentFailed);
+ }
revenue_recovery_workflow::PaymentProcessorTokenResponse::HardDecline => {
// Finish calculate workflow with CALCULATE_WORKFLOW_FINISH
logger::info!(
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index bdd0aef642..3348b380d7 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -296,3 +296,25 @@ counter_metric!(VAULT_CALL_FAILURES, GLOBAL_METER);
// Encryption/keymanager latency for payment_methods operations
histogram_metric_f64!(PAYMENT_METHOD_CRYPTO_DURATION, GLOBAL_METER);
+
+// Revenue recovery A/B routing
+//
+// Both count invoices the A/B arm could not price, which it treats as an error. They matter for
+// experiment validity rather than availability: an arm that drops invoices for reasons correlated
+// with the arm itself biases the comparison, and the logs alone make that invisible in aggregate.
+counter_metric!(
+ REVENUE_RECOVERY_AB_MISSING_ERROR_CODE,
+ GLOBAL_METER,
+ name: "revenue_recovery.ab.missing_error_code",
+ description: "Invoices whose assigned algorithm needed the previous attempt's error code to \
+ pick a retry time, but the CALCULATE task carried none",
+ unit: "1",
+);
+counter_metric!(
+ REVENUE_RECOVERY_AB_UNASSIGNED_ALGORITHM,
+ GLOBAL_METER,
+ name: "revenue_recovery.ab.unassigned_algorithm",
+ description: "Invoices that reached the A/B arm with no retry implementation recorded on the \
+ intent, so no algorithm could be replayed",
+ unit: "1",
+);
diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs
index 26ee9ceb02..de28f3cea4 100644
--- a/crates/router/src/workflows/revenue_recovery.rs
+++ b/crates/router/src/workflows/revenue_recovery.rs
@@ -83,6 +83,7 @@ use crate::{
revenue_recovery as pcr_storage_types,
revenue_recovery_redis_operation::PaymentProcessorTokenDetails,
},
+ transformers::ForeignFrom,
},
};
use crate::{routes::SessionState, types::storage};
@@ -648,6 +649,10 @@ pub enum PaymentProcessorTokenResponse {
/// The configured retry ladder has no slot left for this invoice
RetriesExhausted,
+ /// The invoice is past the end of its recovery grace window, so there is no legitimate time
+ /// left to retry at — whatever retry budget remains.
+ GraceWindowExpired,
+
/// No retry info available / nothing to do yet
None,
}
@@ -729,6 +734,123 @@ async fn get_adaptive_retry_allowances(
Ok((remaining_grace_days, remaining_budget))
}
+/// The adaptive model's retry time for an invoice, or `None` when the model cannot be consulted.
+#[cfg(feature = "v2")]
+async fn get_adaptive_retry_time_for_error_code(
+ state: &SessionState,
+ algorithm: common_enums::RevenueRecoveryABAlgorithm,
+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,
+ remaining_grace_days: u32,
+ remaining_budget: u32,
+) -> Option<time::PrimitiveDateTime> {
+ let Some(error_code) = prev_attempt_error_code else {
+ crate::routes::metrics::REVENUE_RECOVERY_AB_MISSING_ERROR_CODE.add(
+ 1,
+ router_env::metric_attributes!(("algorithm", algorithm.to_string())),
+ );
+ return None;
+ };
+
+ compute_adaptive_retry_time(state, error_code, remaining_grace_days, remaining_budget)
+ .await
+ .map(common_utils::date_time::convert_to_pdt)
+}
+
+/// Picks the retry time for an invoice enrolled in A/B routing, then finds a token for it.
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+async fn get_token_with_schedule_time_for_ab_routing(
+ state: &SessionState,
+ connector_customer_id: &str,
+ payment_intent: &PaymentIntent,
+ tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
+ remaining_grace_days: u32,
+ remaining_budget: u32,
+ // Both needed only to assign an implementation to an invoice that arrives without one
+ revenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,
+ ab_dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
+) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {
+ let algorithm = payment_intent
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.as_ref())
+ .and_then(|revenue_recovery_metadata| {
+ revenue_recovery_metadata.revenue_recovery_ab_routing
+ });
+
+ logger::info!(
+ payment_id = %payment_intent.id.get_string_repr(),
+ ?algorithm,
+ "A/B routing read the retry implementation assigned to this invoice"
+ );
+
+ let schedule_time = match algorithm {
+ Some(assigned_algorithm @ common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry) => {
+ let adaptive_time = get_adaptive_retry_time_for_error_code(
+ state,
+ assigned_algorithm,
+ tracking_data.prev_attempt_error_code,
+ remaining_grace_days,
+ remaining_budget,
+ )
+ .await;
+
+ logger::info!(
+ error_code = ?tracking_data.prev_attempt_error_code,
+ remaining_grace_days = remaining_grace_days,
+ remaining_budget = remaining_budget,
+ schedule_time = ?adaptive_time,
+ "Adaptive retry decision"
+ );
+
+ adaptive_time
+ }
+ None => {
+ crate::routes::metrics::REVENUE_RECOVERY_AB_UNASSIGNED_ALGORITHM.add(1, &[]);
+
+ let assigned_algorithm = pcr::assign_and_record_ab_routing(
+ state,
+ &payment_intent.id,
+ payment_intent
+ .feature_metadata
+ .as_ref()
+ .map(api_models::payments::FeatureMetadata::foreign_from),
+ revenue_recovery_payment_data,
+ ab_dimensions,
+ )
+ .await;
+
+ get_adaptive_retry_time_for_error_code(
+ state,
+ assigned_algorithm,
+ tracking_data.prev_attempt_error_code,
+ remaining_grace_days,
+ remaining_budget,
+ )
+ .await
+ }
+ };
+
+ let schedule_time = schedule_time.ok_or_else(|| {
+ logger::error!(
+ payment_id = %payment_intent.id.get_string_repr(),
+ ?algorithm,
+ error_code = ?tracking_data.prev_attempt_error_code,
+ "No retry time available — the assigned algorithm produced none and this path has no \
+ ladder to fall back on"
+ );
+ errors::ProcessTrackerError::EApiErrorResponse
+ })?;
+
+ get_token_availability_for_schedule_time(
+ state,
+ connector_customer_id,
+ payment_intent,
+ schedule_time,
+ )
+ .await
+}
+
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
@@ -741,6 +863,12 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
static_ladder_progress: &pcr::schedule::StaticLadderProgress,
max_retry_count: u16,
+ // Needed only to resolve the A/B gate
+ provider_merchant_id: hyperswitch_domain_models::platform::ProviderMerchantId,
+ remaining_grace_days: u32,
+ remaining_budget: u32,
+ // Needed only to assign an implementation to an invoice that arrives without one
+ revenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,
) -> CustomResult<
(
PaymentProcessorTokenResponse,
@@ -799,7 +927,33 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
)
.await;
- if adaptive_retry_enabled {
+ let ab_dimensions = crate::core::configs::dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_provider_merchant_id(provider_merchant_id)
+ .with_organization_id(payment_intent.organization_id.clone())
+ .with_profile_id(payment_intent.profile_id.clone());
+
+ let ab_enabled = ab_dimensions
+ .get_revenue_recovery_ab_enabled(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+
+ if ab_enabled {
+ payment_processor_token_response = get_token_with_schedule_time_for_ab_routing(
+ state,
+ connector_customer_id,
+ payment_intent,
+ tracking_data,
+ remaining_grace_days,
+ remaining_budget,
+ revenue_recovery_payment_data,
+ &ab_dimensions,
+ )
+ .await?;
+ } else if adaptive_retry_enabled {
// Same shape as the cascading arm — compute the schedule time, then gate on
// the token. The only additions are the adaptive candidate and the choice
// between the two.
@@ -943,6 +1097,10 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
logger::debug!("Retry ladder exhausted");
}
+ PaymentProcessorTokenResponse::GraceWindowExpired => {
+ logger::debug!("Grace window expired");
+ }
+
PaymentProcessorTokenResponse::None => {
logger::debug!("No retry info available");
}