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

refactor(revenue_recovery): read max hybrid cascading retry count from config (#15151)

CHALLA NISHANTH BABU9b2417b07bd9
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 4847a701aa..5c263bc8ef 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -295,14 +295,6 @@ impl MerchantConnectorAccount {
.is_some_and(|recovery| recovery.enable_partial_authorization)
}
- /// Positions on the cascading ladder available to an invoice under the hybrid scheme.
- pub fn get_max_hybrid_cascading_retry_count(&self) -> Option<u16> {
- self.feature_metadata
- .as_ref()
- .and_then(|metadata| metadata.revenue_recovery.as_ref())
- .map(|recovery| recovery.max_hybrid_cascading_retry_count)
- }
-
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.id.clone()
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index d02ef6294b..cd6e491ef6 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -496,6 +496,10 @@ pub mod superposition {
pub const RECOVERY_GRACE_PERIOD_DAYS: &str = "revenue_recovery.grace_period_days";
/// Total retries an invoice is allowed across its whole recovery lifecycle
pub const RECOVERY_MAX_RETRY_COUNT: &str = "revenue_recovery.max_retry_count";
+ /// Positions on the static ladder available to an invoice under the hybrid static + adaptive
+ /// scheme. Controlled internally rather than by merchants, for both trigger models
+ pub const RECOVERY_MAX_HYBRID_CASCADING_RETRY_COUNT: &str =
+ "revenue_recovery.max_hybrid_cascading_retry_count";
/// Payment sync (psync) retry process tracker mapping key
pub const PT_MAPPING_PAYMENT_SYNC: &str = "process_tracker.pt_mapping_payment_sync";
/// Refund sync retry process tracker mapping key
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
index cafa6ac852..00a638e682 100644
--- a/crates/router/src/core/configs/dimension_config.rs
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -972,6 +972,22 @@ impl DatabaseBackedConfig for RecoveryMaxRetryCount {
}
}
+config! {
+ superposition_key = RECOVERY_MAX_HYBRID_CASCADING_RETRY_COUNT,
+ output = u32,
+ default = 0,
+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,
+ targeting_key = id_type::ProfileId
+}
+
+impl DatabaseBackedConfig for RecoveryMaxHybridCascadingRetryCount {
+ const KEY: &'static str = "recovery_max_hybrid_cascading_retry_count";
+
+ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {
+ None
+ }
+}
+
config! {
superposition_key = PT_MAPPING_PAYMENT_SYNC,
output = scheduler::types::process_data::ConnectorPTMapping,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 09a1d6c627..23ac17d11a 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -470,8 +470,6 @@ pub enum RevenueRecoveryError {
BillingConnectorInvoiceSyncFailed,
#[error("Failed to fetch connector customer ID")]
CustomerIdNotFound,
- #[error("Failed to get the retry count for payment intent")]
- RetryCountFetchFailed,
#[error("Failed to get the billing threshold retry count")]
BillingThresholdRetryCountFetchFailed,
#[error("Failed to get the retry algorithm type")]
@@ -528,7 +526,6 @@ impl common_utils::errors::ErrorSwitch<ApiErrorResponse> for RevenueRecoveryErro
| Self::ProcessTrackerResponseError
| Self::BillingConnectorPaymentsSyncFailed
| Self::BillingConnectorInvoiceSyncFailed
- | Self::RetryCountFetchFailed
| Self::RetryAlgorithmUpdationFailed
| Self::RevenueRecoveryRedisInsertFailed => ApiErrorResponse::WebhookProcessingFailure,
}
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index bb7ab9ac83..2316990fe6 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -194,12 +194,22 @@ pub async fn upsert_calculate_pcr_task(
payment_id.get_string_repr()
);
- let max_hybrid_cascading_retry_count = billing_connector_account
- .get_max_hybrid_cascading_retry_count()
- .ok_or(errors::RevenueRecoveryError::RetryCountFetchFailed)
- .attach_printable(
- "Failed to get max hybrid cascading retry count from billing merchant connector account",
- )?;
+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()
+ .with_processor_merchant_id(
+ recovery_intent_from_payment_intent
+ .merchant_id
+ .clone()
+ .into(),
+ )
+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
+ .with_profile_id(business_profile.get_id().clone());
+ let max_hybrid_cascading_retry_count = dimensions
+ .get_recovery_max_hybrid_cascading_retry_count(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
// Create tracking data
let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
@@ -796,10 +806,10 @@ fn get_recovery_grace_window_end(
.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 {
- attempts_already_made > i32::from(max_retry_count)
+/// `retries_already_made` is the invoice's retries so far, not counting its first attempt, so
+/// retries stop once it reaches `max_retry_count`.
+fn is_retry_budget_exhausted(retries_already_made: u16, max_retry_count: u16) -> bool {
+ retries_already_made >= max_retry_count
}
pub async fn perform_calculate_workflow(
@@ -865,24 +875,29 @@ pub async fn perform_calculate_workflow(
)
.await?;
+ let total_retry_count = payment_intent
+ .get_revenue_recovery_retry_count()
+ .ok_or(errors::RecoveryError::ValueNotFound)
+ .attach_printable(
+ "Failed to get the retry count from the payment intent's revenue recovery metadata",
+ )?;
+
let static_ladder_progress = match tracking_data.static_ladder_progress.clone() {
Some(static_ladder_progress) => static_ladder_progress,
None => {
- let max_hybrid_cascading_retry_count = revenue_recovery_payment_data
- .billing_mca
- .get_max_hybrid_cascading_retry_count()
- .ok_or(errors::RecoveryError::ValueNotFound)
- .attach_printable(
- "Failed to get max hybrid cascading retry count from billing merchant connector account",
- )?;
- let intent_retry_count = payment_intent
- .get_revenue_recovery_retry_count()
- .ok_or(errors::RecoveryError::ValueNotFound)
- .attach_printable(
- "Failed to get the retry count from the payment intent's revenue recovery metadata",
- )?;
+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
+ .with_profile_id(payment_intent.profile_id.clone());
+ let max_hybrid_cascading_retry_count = dimensions
+ .get_recovery_max_hybrid_cascading_retry_count(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
schedule::StaticLadderProgress::seed_for_existing_invoice(
- intent_retry_count,
+ total_retry_count,
max_hybrid_cascading_retry_count,
)
}
@@ -897,7 +912,7 @@ pub async fn perform_calculate_workflow(
"Failed to get max retry count from billing merchant connector account",
)?;
- let retry_budget_exhausted = is_retry_budget_exhausted(process.retry_count, max_retry_count);
+ let retry_budget_exhausted = is_retry_budget_exhausted(total_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 {
@@ -923,7 +938,7 @@ pub async fn perform_calculate_workflow(
{
logger::info!(
process_id = %process.id,
- retry_count = process.retry_count,
+ retry_count = total_retry_count,
?max_retry_count,
"Invoice reached the retry ceiling configured on the billing MCA"
);
@@ -934,7 +949,7 @@ pub async fn perform_calculate_workflow(
} else if grace_window_elapsed {
logger::info!(
process_id = %process.id,
- retry_count = process.retry_count,
+ retry_count = total_retry_count,
?grace_window_end,
"Invoice is past its recovery grace window"
);
@@ -961,14 +976,9 @@ pub async fn perform_calculate_workflow(
.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)
- .inspect_err(|_| metrics::REVENUE_RECOVERY_RETRY_COUNT_INVALID.add(1, &[]))
- .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);
+ let remaining_budget = u32::from(max_retry_count.saturating_sub(total_retry_count));
// 3. Get best available token
match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(
@@ -977,7 +987,7 @@ pub async fn perform_calculate_workflow(
payment_intent,
revenue_recovery_payment_data.billing_mca.connector_name,
retry_algorithm_type,
- process.retry_count,
+ u32::from(total_retry_count),
tracking_data,
&static_ladder_progress,
platform.get_provider().get_provider_merchant_id(),
@@ -1116,7 +1126,7 @@ pub async fn perform_calculate_workflow(
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
- retry_count = process.retry_count,
+ retry_count = total_retry_count,
"Retry ladder exhausted, finishing CALCULATE_WORKFLOW"
);
@@ -1144,7 +1154,7 @@ pub async fn perform_calculate_workflow(
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
- retry_count = process.retry_count,
+ retry_count = total_retry_count,
"Grace window expired, finishing CALCULATE_WORKFLOW"
);
diff --git a/crates/router/src/core/revenue_recovery/schedule.rs b/crates/router/src/core/revenue_recovery/schedule.rs
index f05273bd30..500dc1d52f 100644
--- a/crates/router/src/core/revenue_recovery/schedule.rs
+++ b/crates/router/src/core/revenue_recovery/schedule.rs
@@ -6,19 +6,17 @@ use time::PrimitiveDateTime;
pub struct StaticLadderProgress {
/// Rungs already used; the next one to offer is `consumed_rungs + 1`.
#[serde(default)]
- pub consumed_rungs: i32,
+ pub consumed_rungs: u32,
}
impl StaticLadderProgress {
/// Opening position for an invoice entering recovery for the first time.
pub fn seed_for_new_invoice(
intent_retry_count: u16,
- max_hybrid_cascading_retry_count: u16,
+ max_hybrid_cascading_retry_count: u32,
) -> Self {
Self {
- consumed_rungs: intent_retry_count
- .min(max_hybrid_cascading_retry_count)
- .into(),
+ consumed_rungs: u32::from(intent_retry_count).min(max_hybrid_cascading_retry_count),
}
}
@@ -26,17 +24,16 @@ impl StaticLadderProgress {
/// — a row written before this field existed.
pub fn seed_for_existing_invoice(
intent_retry_count: u16,
- max_hybrid_cascading_retry_count: u16,
+ max_hybrid_cascading_retry_count: u32,
) -> Self {
Self {
- consumed_rungs: intent_retry_count
- .min(max_hybrid_cascading_retry_count.saturating_sub(1))
- .into(),
+ consumed_rungs: u32::from(intent_retry_count)
+ .min(max_hybrid_cascading_retry_count.saturating_sub(1)),
}
}
/// The rung to ask the ladder for on this decision — the one after those already used.
- pub fn next_rung(&self) -> i32 {
+ pub fn next_rung(&self) -> u32 {
self.consumed_rungs + 1
}
}
@@ -91,7 +88,7 @@ fn keep_rung(
/// A decision taken off the ladder, which uses up the rung it supplied. The only way the ladder
/// advances, and so the only way it is spent.
-fn spend_rung(queried_rung: i32, schedule_time: PrimitiveDateTime) -> ScheduleDecision {
+fn spend_rung(queried_rung: u32, schedule_time: PrimitiveDateTime) -> ScheduleDecision {
ScheduleDecision {
schedule_time,
next_progress: StaticLadderProgress {
@@ -110,7 +107,7 @@ fn spend_rung(queried_rung: i32, schedule_time: PrimitiveDateTime) -> ScheduleDe
pub fn decide_next_retry(
schedule: &StaticLadderProgress,
ladder: StaticLadderRole,
- queried_rung: i32,
+ queried_rung: u32,
model_time: Option<PrimitiveDateTime>,
static_time: Option<PrimitiveDateTime>,
fallback_time: Option<PrimitiveDateTime>,
@@ -154,7 +151,7 @@ mod tests {
epoch + Duration::hours(hours)
}
- fn at_rung(consumed_rungs: i32) -> StaticLadderProgress {
+ fn at_rung(consumed_rungs: u32) -> StaticLadderProgress {
StaticLadderProgress { consumed_rungs }
}
@@ -164,7 +161,7 @@ mod tests {
// allowance. They differ only in whether the ladder may open fully consumed: a new invoice
// may, an invoice already in recovery keeps one position in hand.
- const HYBRID_CAP: u16 = 5;
+ const HYBRID_CAP: u32 = 5;
#[test]
fn a_new_invoice_below_the_cap_consumes_what_the_connector_spent() {
@@ -180,7 +177,7 @@ mod tests {
// The connector used the whole allowance before recovery ever saw the invoice, so there
// is no cascading position left and the model carries it alone.
assert_eq!(
- StaticLadderProgress::seed_for_new_invoice(HYBRID_CAP, HYBRID_CAP).consumed_rungs,
+ StaticLadderProgress::seed_for_new_invoice(5, HYBRID_CAP).consumed_rungs,
5
);
// Beyond the cap clamps rather than running past it.
@@ -203,7 +200,7 @@ mod tests {
// Unlike a new invoice, one position is held back — an invoice mid-recovery always has a
// cascading retry left to offer.
assert_eq!(
- StaticLadderProgress::seed_for_existing_invoice(HYBRID_CAP, HYBRID_CAP).consumed_rungs,
+ StaticLadderProgress::seed_for_existing_invoice(5, HYBRID_CAP).consumed_rungs,
4
);
assert_eq!(
diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs
index 323fa11564..80afa29b60 100644
--- a/crates/router/src/core/revenue_recovery/types.rs
+++ b/crates/router/src/core/revenue_recovery/types.rs
@@ -1293,13 +1293,18 @@ impl Action {
pub(crate) async fn decide_retry_failure_action(
state: &SessionState,
merchant_id: &id_type::MerchantId,
- pt: storage::ProcessTracker,
+ _pt: storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> RecoveryResult<Self> {
let db = &*state.store;
- let next_retry_count = pt.retry_count + 1;
+ let total_retry_count = payment_intent
+ .get_revenue_recovery_retry_count()
+ .ok_or(errors::RecoveryError::ValueNotFound)
+ .attach_printable(
+ "Failed to get the retry count from the payment intent's revenue recovery metadata",
+ )?;
let error_message = payment_attempt
.error
.as_ref()
@@ -1338,7 +1343,7 @@ impl Action {
.get_schedule_time_based_on_retry_type(
state,
merchant_id,
- next_retry_count,
+ u32::from(total_retry_count),
payment_attempt,
payment_intent,
is_hard_decline,
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 009918ed34..384a24b26b 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -381,17 +381,6 @@ counter_metric!(
the three steps could not be completed",
unit: "1",
);
-// Not to be read as "the invoice ran out of retries", which is the ordinary end of its life and
-// finishes the job cleanly. This counts a stored retry count that is not a count at all — the only
-// way `i32 -> u32` fails is a negative — so the remaining budget cannot be derived from it.
-counter_metric!(
- REVENUE_RECOVERY_RETRY_COUNT_INVALID,
- GLOBAL_METER,
- name: "revenue_recovery.retry_count_invalid",
- description: "Invoices whose stored retry count was negative and so not a usable count, \
- leaving the remaining retry budget underivable and ending recovery",
- unit: "1",
-);
// Analytics reports generated by the process tracker
counter_metric!(
diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs
index eb3a17239a..37bfedfd3f 100644
--- a/crates/router/src/types/storage/revenue_recovery.rs
+++ b/crates/router/src/types/storage/revenue_recovery.rs
@@ -56,7 +56,7 @@ impl RevenueRecoveryPaymentData {
&self,
state: &SessionState,
merchant_id: &id_type::MerchantId,
- retry_count: i32,
+ retry_count: u32,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
is_hard_decline: bool,
diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs
index 60b296a0d8..a8d64dd8f2 100644
--- a/crates/router/src/workflows/revenue_recovery.rs
+++ b/crates/router/src/workflows/revenue_recovery.rs
@@ -242,7 +242,7 @@ pub(crate) async fn get_schedule_time_to_retry_mit_payments(
db: &dyn StorageInterface,
superposition_client: &external_services::superposition::SuperpositionClient,
dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,
- retry_count: i32,
+ retry_count: u32,
) -> Option<time::PrimitiveDateTime> {
let mapping = dimensions
.get_pt_mapping_pcr_retries(db, superposition_client, None)
@@ -261,7 +261,7 @@ pub(crate) async fn get_schedule_time_to_retry_adaptive_payments(
db: &dyn StorageInterface,
superposition_client: &external_services::superposition::SuperpositionClient,
dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,
- queried_rung: i32,
+ queried_rung: u32,
) -> Option<time::PrimitiveDateTime> {
let mapping = dimensions
.get_pt_mapping_adaptive_retries(db, superposition_client, None)
@@ -802,7 +802,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
payment_intent: &PaymentIntent,
billing_connector: common_enums::connector_enums::Connector,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
- retry_count: i32,
+ retry_count: u32,
tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
static_ladder_progress: &pcr::schedule::StaticLadderProgress,
// Needed only to resolve the A/B gate
@@ -873,7 +873,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
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_provider_merchant_id(provider_merchant_id.clone())
.with_organization_id(payment_intent.organization_id.clone())
.with_profile_id(payment_intent.profile_id.clone());
@@ -950,14 +950,22 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
let static_time = match ladder_role {
pcr::schedule::StaticLadderRole::Standby => None,
pcr::schedule::StaticLadderRole::Ceiling => {
- let max_hybrid_cascading_retry_count = revenue_recovery_payment_data
- .billing_mca
- .get_max_hybrid_cascading_retry_count()
- .map(i32::from)
- .ok_or(errors::ProcessTrackerError::MissingRequiredField)
- .attach_printable(
- "Failed to get max hybrid cascading retry count from billing merchant connector account",
- )?;
+ let max_hybrid_cascading_retry_count = {
+ let 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_profile_id(payment_intent.profile_id.clone());
+ dimensions
+ .get_recovery_max_hybrid_cascading_retry_count(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await
+ };
if queried_rung <= max_hybrid_cascading_retry_count {
get_schedule_time_to_retry_adaptive_payments(
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 48bd9e0af9..2414899cb0 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -379,8 +379,9 @@ pub fn get_outgoing_webhook_retry_schedule_time(
pub fn get_pcr_payments_retry_schedule_time(
mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping,
- retry_count: i32,
+ retry_count: u32,
) -> Option<i32> {
+ let retry_count = i32::try_from(retry_count).ok()?;
let mapping = mapping.default_mapping;
// TODO: check if the current scheduled time is not more than the configured timerange
@@ -500,7 +501,7 @@ mod tests {
/// slot is the delay before one retry, so `N` slots describe the charge plus `N` retries.
fn walk_pcr_ladder(
mapping: &process_data::RetryMapping,
- attempts_already_made: i32,
+ attempts_already_made: u32,
) -> (usize, i32) {
let mut retry_count = attempts_already_made;
let mut elapsed = 0;
@@ -525,7 +526,7 @@ mod tests {
#[test]
fn test_pcr_retry_ladder_leaves_thirteen_retries_to_us_ending_on_day_twenty_eight() {
const DAY: i32 = 24 * 60 * 60;
- const BILLING_CONNECTOR_RETRY_THRESHOLD: i32 = 2;
+ const BILLING_CONNECTOR_RETRY_THRESHOLD: u32 = 2;
let mapping = process_data::RetryMapping {
start_after: DAY,