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(revenue-recovery): invoke adaptive retry algo (#13926)
Rohan Mali56cc59175e31
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 0938d8e81f..574a447e38 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -31197,6 +31197,13 @@"example": "10","minimum": 0},+ "max_hybrid_cascading_retry_count": {+ "type": "integer",+ "format": "int32",+ "description": "Number of cascading (static) retries an invoice may use under the hybrid static + adaptive\nscheme.",+ "example": "5",+ "minimum": 0+ },"billing_account_reference": {"type": "integer","format": "int32",diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex 502aecacd6..1e42b4663d 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2565,6 +2565,28 @@ client_session_validation_enabled = { value = true, schema = { type = "boolean"],], start_after = 60 }, schema = { type = "object" }, description = "Payout sync retry mapping configuration per connector", change_reason = "Initial setup" }"payments.poll_config_external_three_ds" = { value = { delay_in_secs = 2, frequency = 5 }, schema = { type = "object" }, description = "Poll configuration for external 3DS authentication per connector", change_reason = "Initial setup" }+"process_tracker.pt_mapping_adaptive_retries" = { value = { default_mapping = { frequencies = [+ [+ 10800,+ 2,+ ],+ [+ 21600,+ 3,+ ],+ [+ 32400,+ 3,+ ],+ [+ 43200,+ 3,+ ],+ [+ 64800,+ 3,+ ],+], start_after = 60 } }, schema = { type = "object" }, description = "Static ladder process tracker mapping used by the adaptive revenue recovery retry algorithm", change_reason = "Initial setup" }"process_tracker.pt_mapping_dispute_sync" = { value = { default_mapping = { frequencies = [[300,diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rsindex b67adf44b2..8f2d4293f1 100644--- a/crates/api_models/src/admin.rs+++ b/crates/api_models/src/admin.rs@@ -1263,6 +1263,11 @@ pub struct RevenueRecoveryMetadata {/// Maximum number of `billing connector` retries before revenue recovery can start executing retries.#[schema(value_type = u16, example = "10")]pub billing_connector_retry_threshold: u16,+ /// Number of cascading (static) retries an invoice may use under the hybrid static + adaptive+ /// scheme.+ #[serde(default)]+ #[schema(value_type = u16, example = "5")]+ pub max_hybrid_cascading_retry_count: u16,/// Billing account reference id is payment gateway id at billing connector end./// Merchants need to provide a mapping between these merchant connector account and the corresponding account reference IDs for each `billing connector`.#[schema(value_type = u16, example = r#"{ "mca_vDSg5z6AxnisHq5dbJ6g": "stripe_123", "mca_vDSg5z6AumisHqh4x5m1": "adyen_123" }"#)]diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rsindex 75235e7276..3fbf42c04f 100644--- a/crates/diesel_models/src/merchant_connector_account.rs+++ b/crates/diesel_models/src/merchant_connector_account.rs@@ -301,6 +301,8 @@ pub struct RevenueRecoveryMetadata {pub max_retry_count: u16,/// Maximum number of `billing connector` retries before revenue recovery can start executing retries.pub billing_connector_retry_threshold: u16,+ #[serde(default)]+ pub max_hybrid_cascading_retry_count: u16,/// Billing account reference id is payment gateway id at billing connector end./// Merchants need to provide a mapping between these merchant connector account and the corresponding/// account reference IDs for each `billing connector`.diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex 96ebce4ad5..183e05ca77 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -280,6 +280,14 @@ impl MerchantConnectorAccount {.map(|recovery| recovery.max_retry_count)}+ /// 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()}@@ -373,6 +381,10 @@ pub struct MerchantConnectorAccountFeatureMetadata {pub struct RevenueRecoveryMetadata {pub max_retry_count: u16,pub billing_connector_retry_threshold: u16,+ /// Number of positions on the cascading (static) ladder available to an invoice under the+ /// hybrid static + adaptive scheme.+ #[serde(default)]+ pub max_hybrid_cascading_retry_count: u16,pub mca_reference: AccountReferenceMap,}@@ -1224,6 +1236,8 @@ impl From<MerchantConnectorAccountFeatureMetadata>max_retry_count: recovery_metadata.max_retry_count,billing_connector_retry_threshold: recovery_metadata.billing_connector_retry_threshold,+ max_hybrid_cascading_retry_count: recovery_metadata+ .max_hybrid_cascading_retry_count,billing_account_reference: DieselBillingAccountReference(recovery_metadata.mca_reference.recovery_to_billing,),@@ -1247,6 +1261,8 @@ impl From<DieselMerchantConnectorAccountFeatureMetadata>max_retry_count: recovery_metadata.max_retry_count,billing_connector_retry_threshold: recovery_metadata.billing_connector_retry_threshold,+ max_hybrid_cascading_retry_count: recovery_metadata+ .max_hybrid_cascading_retry_count,mca_reference: AccountReferenceMap {recovery_to_billing: recovery_metadata.billing_account_reference.0,billing_to_recovery,diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex c612efec4e..5a1095e254 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -1258,6 +1258,17 @@ impl PaymentIntent {.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())}+ /// Retries already made against this invoice, by the billing connector and by recovery+ /// together. Zero for an intent that has not entered recovery.+ pub fn get_revenue_recovery_retry_count(&self) -> Option<u16> {+ self.feature_metadata+ .as_ref()+ .and_then(|feature_metadata| {+ feature_metadata.payment_revenue_recovery_metadata.as_ref()+ })+ .map(|revenue_recovery_metadata| revenue_recovery_metadata.total_retry_count)+ }+pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> {self.feature_metadata.clone()}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 1f096284b6..23bb7b33d0 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -430,6 +430,9 @@ pub mod superposition {"pt_mapping_outgoing_connector_webhooks";/// PCR (Revenue Recovery) payments retry process tracker mapping keypub const PT_MAPPING_PCR_RETRIES: &str = "process_tracker.pt_mapping_pcr_retries";+ /// Static ladder process tracker mapping used by the adaptive revenue recovery retry+ /// algorithm, kept separate from the cascading ladder so the two can be tuned independently+ pub const PT_MAPPING_ADAPTIVE_RETRIES: &str = "process_tracker.pt_mapping_adaptive_retries";/// Revenue Recovery retry-stats key. Enables recording of retry outcome statspub const REVREC_RETRY_STATS_ENABLED: &str = "revenue_recovery.retry_stats.enabled";/// Whether the adaptive revenue recovery retry algorithm — static ladder combined withdiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 0e57e27bba..78d663e64f 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -644,6 +644,23 @@ impl DatabaseBackedConfig for PtMappingPcrRetries {}}+config! {+ superposition_key = PT_MAPPING_ADAPTIVE_RETRIES,+ output = scheduler::types::process_data::RevenueRecoveryPaymentProcessTrackerMapping,+ default = scheduler::types::process_data::RevenueRecoveryPaymentProcessTrackerMapping::default(),+ object = true,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for PtMappingAdaptiveRetries {+ const KEY: &'static str = "pt_mapping_adaptive_retries";++ fn db_key(_dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ Some(Self::KEY.to_string())+ }+}+config! {superposition_key = ADAPTIVE_RETRY_ENABLED,output = bool,diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex 9d0ca0a797..768f97141d 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -121,6 +121,13 @@ 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",+ )?;+// Create tracking datalet calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {billing_mca_id: billing_connector_account.get_id(),@@ -131,7 +138,10 @@ pub async fn upsert_calculate_pcr_task(payment_attempt_id,revenue_recovery_retry,invoice_scheduled_time: None,- static_ladder_progress: schedule::StaticLadderProgress::default(),+ static_ladder_progress: Some(schedule::StaticLadderProgress::seed_for_new_invoice(+ intent_retry_count,+ max_hybrid_cascading_retry_count,+ )),};let tag = ["PCR"];@@ -414,6 +424,7 @@ pub async fn perform_execute_payment(storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,tracking_data.revenue_recovery_retry,state.conf.application_source,+ tracking_data.static_ladder_progress.clone(),).await?;@@ -487,6 +498,7 @@ async fn insert_psync_pcr_task_to_pt(runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,application_source: common_enums::ApplicationSource,+ static_ladder_progress: Option<schedule::StaticLadderProgress>,) -> RouterResult<storage::ProcessTracker> {let task = PSYNC_WORKFLOW;let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner);@@ -500,8 +512,7 @@ async fn insert_psync_pcr_task_to_pt(prev_attempt_error_code,revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),- // PSYNC has its own row; scheduling state lives on CALCULATE.- static_ladder_progress: schedule::StaticLadderProgress::default(),+ static_ladder_progress,};let tag = ["REVENUE_RECOVERY"];let process_tracker_entry = storage::ProcessTrackerNew::new(@@ -586,11 +597,9 @@ pub async fn perform_payments_sync(}/// `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`. No ceiling configured means no gate.-fn is_retry_budget_exhausted(attempts_already_made: i32, max_retry_count: Option<u16>) -> bool {- max_retry_count- .map(|max_retry_count| attempts_already_made > i32::from(max_retry_count))- .unwrap_or(false)+/// 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)}pub async fn perform_calculate_workflow(@@ -656,10 +665,37 @@ pub async fn perform_calculate_workflow().await?;+ 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",+ )?;+ schedule::StaticLadderProgress::seed_for_existing_invoice(+ intent_retry_count,+ max_hybrid_cascading_retry_count,+ )+ }+ };+// 2. Bound the invoice by the merchant's ceiling, independently of the retry ladder.let max_retry_count = revenue_recovery_payment_data.billing_mca- .get_max_retry_count();+ .get_max_retry_count()+ .ok_or(errors::RecoveryError::ValueNotFound)+ .attach_printable(+ "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) {@@ -682,8 +718,10 @@ pub async fn perform_calculate_workflow(revenue_recovery_payment_data.billing_mca.connector_name,retry_algorithm_type,process.retry_count,- &tracking_data.static_ladder_progress,- )+ tracking_data,+ &static_ladder_progress,+ max_retry_count,+ ).await{Ok(token_and_schedule) => token_and_schedule,@@ -731,6 +769,7 @@ pub async fn perform_calculate_workflow(storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,retry_algorithm_type,scheduled_time,+ next_static_ladder_progress.clone(),).await?;@@ -900,7 +939,7 @@ async fn finish_calculate_workflow_with_progress("Failed to deserialize the tracking data from process tracker",)?;- tracking_data.static_ladder_progress = static_ladder_progress;+ tracking_data.static_ladder_progress = Some(static_ladder_progress);let tracking_data = serde_json::to_value(tracking_data).change_context(errors::RecoveryError::ValueNotFound)@@ -1011,6 +1050,7 @@ async fn insert_execute_pcr_task_to_pt(runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,schedule_time: time::PrimitiveDateTime,+ static_ladder_progress: Option<schedule::StaticLadderProgress>,) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> {let task = "EXECUTE_WORKFLOW";@@ -1055,6 +1095,8 @@ async fn insert_execute_pcr_task_to_pt()?;tracking_data.revenue_recovery_retry = revenue_recovery_retry;+ tracking_data.static_ladder_progress = static_ladder_progress;+ tracking_data.prev_attempt_error_code = prev_attempt_error_code;let tracking_data_json = serde_json::to_value(&tracking_data).change_context(errors::RecoveryError::ValueNotFound)@@ -1120,8 +1162,7 @@ async fn insert_execute_pcr_task_to_pt(prev_attempt_error_code,revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),- // EXECUTE has its own row; scheduling state lives on CALCULATE.- static_ladder_progress: schedule::StaticLadderProgress::default(),+ static_ladder_progress,};let tag = ["PCR"];@@ -1401,6 +1442,7 @@ pub async fn resume_revenue_recovery_process_tracker(runner,tracking_data.revenue_recovery_retry,state.conf.application_source,+ tracking_data.static_ladder_progress.clone(),).await?}diff --git a/crates/router/src/core/revenue_recovery/schedule.rs b/crates/router/src/core/revenue_recovery/schedule.rsindex d3a9386732..608e91dacb 100644--- a/crates/router/src/core/revenue_recovery/schedule.rs+++ b/crates/router/src/core/revenue_recovery/schedule.rs@@ -8,6 +8,31 @@ pub struct StaticLadderProgress {}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,+ ) -> Self {+ Self {+ consumed_rungs: intent_retry_count+ .min(max_hybrid_cascading_retry_count)+ .into(),+ }+ }++ /// Opening position for an invoice already in recovery whose ladder state was never recorded+ /// — a row written before this field existed.+ pub fn seed_for_existing_invoice(+ intent_retry_count: u16,+ max_hybrid_cascading_retry_count: u16,+ ) -> Self {+ Self {+ consumed_rungs: intent_retry_count+ .min(max_hybrid_cascading_retry_count.saturating_sub(1))+ .into(),+ }+ }+/// Ladder position to query for this decision.pub fn next_rung(&self) -> i32 {self.consumed_rungs + 1@@ -20,6 +45,8 @@ impl StaticLadderProgress {pub enum ScheduleSource {Static,Adaptive,+ /// The MIT cascading ladder, consulted only once the other two have nothing to offer.+ Fallback,}/// Outcome of one scheduling decision.@@ -33,32 +60,51 @@ pub struct ScheduleDecision {pub source: ScheduleSource,}+/// Choose between the two candidates, falling back to the MIT cascading ladder when neither has+/// one to offer, and `None` when nothing is left to schedule.pub fn decide_next_retry(schedule: &StaticLadderProgress,queried_rung: i32,- static_time: PrimitiveDateTime,+ static_time: Option<PrimitiveDateTime>,adaptive_time: Option<PrimitiveDateTime>,-) -> ScheduleDecision {- let winning_adaptive_time =- adaptive_time.filter(|adaptive_time| adaptive_time.date() < static_time.date());-- match winning_adaptive_time {- Some(adaptive_time) => ScheduleDecision {- schedule_time: adaptive_time,- next_progress: StaticLadderProgress {- // No static attempt was spent, so the ladder must not advance — the same- // position is offered again on the next decision.- consumed_rungs: schedule.consumed_rungs,- },- source: ScheduleSource::Adaptive,+ fallback_time: Option<PrimitiveDateTime>,+) -> Option<ScheduleDecision> {+ // Adaptive spends no ladder position, so the count stays put and the same position is offered+ // again on the next decision.+ let adaptive = |schedule_time| ScheduleDecision {+ schedule_time,+ next_progress: StaticLadderProgress {+ consumed_rungs: schedule.consumed_rungs,},- None => ScheduleDecision {- schedule_time: static_time,+ source: ScheduleSource::Adaptive,+ };+ let static_ladder = |schedule_time| ScheduleDecision {+ schedule_time,+ next_progress: StaticLadderProgress {+ consumed_rungs: queried_rung,+ },+ source: ScheduleSource::Static,+ };++ match (static_time, adaptive_time) {+ // The earlier calendar day wins. A tie goes to static: the ladder already covers that+ // day, so an earlier hour on it does not earn a second attempt.+ (Some(static_time), Some(adaptive_time)) if adaptive_time.date() < static_time.date() => {+ Some(adaptive(adaptive_time))+ }+ (Some(static_time), _) => Some(static_ladder(static_time)),+ // Ladder spent, so the adaptive time stands unopposed.+ (None, Some(adaptive_time)) => Some(adaptive(adaptive_time)),+ // The adaptive ladder is spent and the model declined, so the MIT cascading ladder gets+ // the last word. It spends no adaptive position, so the count stays put; `None` here+ // means there is genuinely nothing left to schedule for this invoice.+ (None, None) => fallback_time.map(|schedule_time| ScheduleDecision {+ schedule_time,next_progress: StaticLadderProgress {- consumed_rungs: queried_rung,+ consumed_rungs: schedule.consumed_rungs,},- source: ScheduleSource::Static,- },+ source: ScheduleSource::Fallback,+ }),}}@@ -82,6 +128,95 @@ mod tests {StaticLadderProgress { consumed_rungs }}+ /// A decision the caller would act on. Panics where the test's premise is that one exists.+ fn expect_decision(+ schedule: &StaticLadderProgress,+ queried_rung: i32,+ static_time: Option<PrimitiveDateTime>,+ adaptive_time: Option<PrimitiveDateTime>,+ ) -> ScheduleDecision {+ decide_next_retry(schedule, queried_rung, static_time, adaptive_time, None)+ .expect("a time was available")+ }++ // ---- seeding ----------------------------------------------------------+ //+ // Both constructors clamp the billing connector's own attempts against the cascading+ // 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;++ #[test]+ fn a_new_invoice_below_the_cap_consumes_what_the_connector_spent() {+ // Two billing-connector attempts, so the ladder resumes at position 3.+ let schedule = StaticLadderProgress::seed_for_new_invoice(2, HYBRID_CAP);++ assert_eq!(schedule.consumed_rungs, 2);+ assert_eq!(schedule.next_rung(), 3);+ }++ #[test]+ fn a_new_invoice_at_or_past_the_cap_opens_the_ladder_fully_consumed() {+ // The connector used the whole allowance before recovery ever saw the invoice, so there+ // is no cascading position left and the adaptive algorithm carries it alone.+ assert_eq!(+ StaticLadderProgress::seed_for_new_invoice(HYBRID_CAP, HYBRID_CAP).consumed_rungs,+ 5+ );+ // Beyond the cap clamps rather than running past it.+ assert_eq!(+ StaticLadderProgress::seed_for_new_invoice(9, HYBRID_CAP).consumed_rungs,+ 5+ );+ }++ #[test]+ fn an_existing_invoice_below_the_cap_consumes_what_the_connector_spent() {+ let schedule = StaticLadderProgress::seed_for_existing_invoice(2, HYBRID_CAP);++ assert_eq!(schedule.consumed_rungs, 2);+ assert_eq!(schedule.next_rung(), 3);+ }++ #[test]+ fn an_existing_invoice_at_or_past_the_cap_keeps_one_position_in_hand() {+ // 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,+ 4+ );+ assert_eq!(+ StaticLadderProgress::seed_for_existing_invoice(9, HYBRID_CAP).consumed_rungs,+ 4+ );+ // And the position it offers is the last one on the ladder.+ assert_eq!(+ StaticLadderProgress::seed_for_existing_invoice(9, HYBRID_CAP).next_rung(),+ 5+ );+ }++ #[test]+ fn an_unconfigured_cap_opens_the_ladder_at_the_top() {+ // A billing connector with no hybrid allowance configured reads as zero. Neither+ // constructor may underflow; both must leave the ladder unconsumed so the first decision+ // still has position 1 to offer.+ assert_eq!(+ StaticLadderProgress::seed_for_new_invoice(4, 0).consumed_rungs,+ 0+ );+ assert_eq!(+ StaticLadderProgress::seed_for_existing_invoice(4, 0).consumed_rungs,+ 0+ );+ assert_eq!(+ StaticLadderProgress::seed_for_existing_invoice(4, 0).next_rung(),+ 1+ );+ }+// ---- rung sourcing ----------------------------------------------------#[test]@@ -104,7 +239,7 @@ mod tests {#[test]fn adaptive_earlier_day_wins_and_leaves_the_rung_unconsumed() {let schedule = at_rung(2);- let decision = decide_next_retry(&schedule, 3, at(240), Some(at(72)));+ let decision = expect_decision(&schedule, 3, Some(at(240)), Some(at(72)));assert_eq!(decision.schedule_time, at(72));assert_eq!(decision.source, ScheduleSource::Adaptive);@@ -119,10 +254,10 @@ mod tests {let adaptive_time = at(240 - 1);assert!(adaptive_time.date() < static_time.date());- let decision = decide_next_retry(+ let decision = expect_decision(&StaticLadderProgress::default(),1,- static_time,+ Some(static_time),Some(adaptive_time),);@@ -134,7 +269,7 @@ mod tests {#[test]fn adaptive_later_day_loses_and_consumes_the_rung() {- let decision = decide_next_retry(&at_rung(2), 3, at(240), Some(at(336)));+ let decision = expect_decision(&at_rung(2), 3, Some(at(240)), Some(at(336)));assert_eq!(decision.schedule_time, at(240));assert_eq!(decision.source, ScheduleSource::Static);@@ -143,7 +278,7 @@ mod tests {#[test]fn no_adaptive_opinion_uses_static_and_consumes_the_rung() {- let decision = decide_next_retry(&StaticLadderProgress::default(), 1, at(240), None);+ let decision = expect_decision(&StaticLadderProgress::default(), 1, Some(at(240)), None);assert_eq!(decision.schedule_time, at(240));assert_eq!(decision.source, ScheduleSource::Static);@@ -160,10 +295,10 @@ mod tests {let adaptive_time = at(240 + 9);assert_eq!(static_time.date(), adaptive_time.date());- let decision = decide_next_retry(+ let decision = expect_decision(&StaticLadderProgress::default(),1,- static_time,+ Some(static_time),Some(adaptive_time),);@@ -174,8 +309,12 @@ mod tests {#[test]fn adaptive_identical_to_static_loses() {- let decision =- decide_next_retry(&StaticLadderProgress::default(), 1, at(240), Some(at(240)));+ let decision = expect_decision(+ &StaticLadderProgress::default(),+ 1,+ Some(at(240)),+ Some(at(240)),+ );assert_eq!(decision.source, ScheduleSource::Static);}@@ -191,7 +330,7 @@ mod tests {// Fresh invoice: rung 1 is offered, adaptive takes the slot.let queried_rung = schedule.next_rung();assert_eq!(queried_rung, 1);- let first = decide_next_retry(&schedule, queried_rung, at(240), Some(at(72)));+ let first = expect_decision(&schedule, queried_rung, Some(at(240)), Some(at(72)));assert_eq!(first.source, ScheduleSource::Adaptive);// The process tracker's retry_count is now 2, but rung 1 was never used, so it is@@ -199,14 +338,14 @@ mod tests {let schedule = first.next_progress;let queried_rung = schedule.next_rung();assert_eq!(queried_rung, 1);- let second = decide_next_retry(&schedule, queried_rung, at(240), Some(at(120)));+ let second = expect_decision(&schedule, queried_rung, Some(at(240)), Some(at(120)));assert_eq!(second.source, ScheduleSource::Adaptive);// retry_count 3, and still rung 1.let schedule = second.next_progress;let queried_rung = schedule.next_rung();assert_eq!(queried_rung, 1);- let third = decide_next_retry(&schedule, queried_rung, at(240), None);+ let third = expect_decision(&schedule, queried_rung, Some(at(240)), None);assert_eq!(third.source, ScheduleSource::Static);assert_eq!(third.next_progress.consumed_rungs, 1);@@ -215,6 +354,44 @@ mod tests {assert_eq!(third.next_progress.next_rung(), 2);}+ // ---- an exhausted ladder ----------------------------------------------++ #[test]+ fn an_exhausted_ladder_hands_the_slot_to_adaptive() {+ // Past the ladder's last entry there is no static candidate, but the invoice is not+ // finished — the adaptive algorithm carries it for the rest of the grace window.+ let decision = expect_decision(&at_rung(5), 6, None, Some(at(72)));++ assert_eq!(decision.schedule_time, at(72));+ assert_eq!(decision.source, ScheduleSource::Adaptive);+ }++ #[test]+ fn an_exhausted_ladder_does_not_advance_the_position() {+ // There was no position to spend, so the count stays where the ladder left it rather+ // than creeping past the end on every adaptive retry.+ let decision = expect_decision(&at_rung(5), 6, None, Some(at(72)));++ assert_eq!(decision.next_progress.consumed_rungs, 5);+ }++ #[test]+ fn both_algorithms_declining_yields_no_decision() {+ // The ladder is spent and the model has no opinion. Only here is there genuinely+ // nothing left to schedule, and the caller ends the invoice.+ assert_eq!(decide_next_retry(&at_rung(5), 6, None, None, None), None);+ }++ #[test]+ fn an_exhausted_ladder_ignores_the_day_comparison() {+ // With no static day to beat, an adaptive time far in the future still wins — the tie+ // rule only applies when there are two candidates.+ let decision = expect_decision(&StaticLadderProgress::default(), 1, None, Some(at(2400)));++ assert_eq!(decision.schedule_time, at(2400));+ assert_eq!(decision.source, ScheduleSource::Adaptive);+ }+// ---- persistence ------------------------------------------------------#[test]diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 9554f4aacf..7c81aaeb4a 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -817,6 +817,20 @@ impl Action {let db = &*state.store;match self {Self::SyncPayment(payment_attempt) => {+ let static_ladder_progress =+ serde_json::from_value::<pcr::RevenueRecoveryWorkflowTrackingData>(+ execute_task_process.tracking_data.clone(),+ )+ .map_err(|error| {+ logger::warn!(+ ?error,+ process_id = %execute_task_process.id,+ "Failed to read the ladder position off the execute workflow"+ );+ })+ .ok()+ .and_then(|tracking_data| tracking_data.static_ladder_progress);+// Carry the failed attempt's pre-resolved standardised error code into the// PSYNC task it schedules.revenue_recovery_core::insert_psync_pcr_task_to_pt(@@ -833,6 +847,7 @@ impl Action {storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,revenue_recovery_payment_data.retry_algorithm,state.conf.application_source,+ static_ladder_progress,).await.change_context(errors::RecoveryError::ProcessTrackerFailure)diff --git a/crates/router/src/types.rs b/crates/router/src/types.rsindex 368ecdfc44..803506628d 100644--- a/crates/router/src/types.rs+++ b/crates/router/src/types.rs@@ -1620,6 +1620,8 @@ impl ForeignFrom<&domain::MerchantConnectorAccountFeatureMetadata>max_retry_count: revenue_recovery_metadata.max_retry_count,billing_connector_retry_threshold: revenue_recovery_metadata.billing_connector_retry_threshold,+ max_hybrid_cascading_retry_count: revenue_recovery_metadata+ .max_hybrid_cascading_retry_count,billing_account_reference: revenue_recovery_metadata.mca_reference.recovery_to_billing@@ -1649,6 +1651,8 @@ impl ForeignTryFrom<&api_models::admin::MerchantConnectorAccountFeatureMetadata>max_retry_count: revenue_recovery_metadata.max_retry_count,billing_connector_retry_threshold: revenue_recovery_metadata.billing_connector_retry_threshold,+ max_hybrid_cascading_retry_count: revenue_recovery_metadata+ .max_hybrid_cascading_retry_count,mca_reference,})})diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex 09604db569..fbfc90665c 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -33,7 +33,7 @@ pub struct RevenueRecoveryWorkflowTrackingData {/// been. Only meaningful on the CALCULATE row, which is reopened rather than recreated/// and so survives for the whole recovery lifecycle of an invoice.#[serde(default)]- pub static_ladder_progress: StaticLadderProgress,+ pub static_ladder_progress: Option<StaticLadderProgress>,}#[derive(Debug, Clone)]diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 329b81f002..1b4d8e202d 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -254,6 +254,23 @@ pub(crate) async fn get_schedule_time_to_retry_mit_payments(scheduler_utils::get_time_from_delta(time_delta)}+/// Static ladder time for the adaptive retry algorithm.+#[cfg(feature = "v2")]+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,+ retry_count: i32,+) -> Option<time::PrimitiveDateTime> {+ let mapping = dimensions+ .get_pt_mapping_adaptive_retries(db, superposition_client, None)+ .await;++ let time_delta = scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, retry_count);++ scheduler_utils::get_time_from_delta(time_delta)+}+#[derive(Debug, Clone)]pub struct RetryDecision {pub retry_time: time::PrimitiveDateTime,@@ -637,7 +654,85 @@ pub enum PaymentProcessorTokenResponse {None,}+/// The two allowances the math model needs: how much of the invoice's grace window is left, and+/// how many retries remain of the merchant's budget. The grace window comes from Superposition,+/// the budget from the billing connector's account.#[cfg(feature = "v2")]+async fn get_adaptive_retry_allowances(+ state: &SessionState,+ dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ payment_intent: &PaymentIntent,+ max_retry_count: u16,+ retry_count: i32,+ now: time::PrimitiveDateTime,+) -> Result<(u32, u32), errors::ProcessTrackerError> {+ 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+ .feature_metadata+ .as_ref()+ .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.as_ref())+ .and_then(|revenue_recovery_metadata| {+ revenue_recovery_metadata.invoice_billing_started_at_time+ })+ .ok_or_else(|| {+ logger::error!(+ payment_id = %payment_intent.id.get_string_repr(),+ "adaptive retry: the invoice has no billing start time, so its grace window \+ cannot be established"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;++ let grace_window_end = grace_window_start+ .checked_add(time::Duration::days(grace_period_days))+ .ok_or_else(|| {+ logger::error!(+ payment_id = %payment_intent.id.get_string_repr(),+ grace_period_days,+ %grace_window_start,+ "adaptive retry: failed to calculate the grace window end time"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;++ let days_left_in_grace_window = (grace_window_end - now).whole_days().max(0);++ let remaining_grace_days: u32 = days_left_in_grace_window.try_into().map_err(|error| {+ logger::error!(+ ?error,+ payment_id = %payment_intent.id.get_string_repr(),+ days_left_in_grace_window,+ "adaptive retry: the days left in the grace window do not fit the model's day count"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;++ let retries_already_made: u32 = retry_count.try_into().map_err(|error| {+ logger::error!(+ ?error,+ payment_id = %payment_intent.id.get_string_repr(),+ retry_count,+ "adaptive retry: failed to read how many retries have already been made"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;++ // 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);++ Ok((remaining_grace_days, remaining_budget))+}++#[cfg(feature = "v2")]+#[allow(clippy::too_many_arguments)]pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(state: &SessionState,connector_customer_id: &str,@@ -645,7 +740,9 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(billing_connector: common_enums::connector_enums::Connector,retry_algorithm_type: RevenueRecoveryAlgorithmType,retry_count: i32,+ tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,static_ladder_progress: &pcr::schedule::StaticLadderProgress,+ max_retry_count: u16,) -> CustomResult<(PaymentProcessorTokenResponse,@@ -656,7 +753,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;// Updated scheduling state, set only when a retry is actually scheduled by the adaptive// path. The other responses reschedule the CALCULATE job without making an attempt, so- // persisting there would consume a pinned static time for a retry that never happened.+ // persisting there would consume a ladder position for a retry that never happened.let mut next_static_ladder_progress = None;match retry_algorithm_type {RevenueRecoveryAlgorithmType::Monitoring => {@@ -708,31 +805,83 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(// 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.+ let now = common_utils::date_time::now();let queried_rung = static_ladder_progress.next_rung();- let static_time = get_schedule_time_to_retry_mit_payments(++ let static_time = get_schedule_time_to_retry_adaptive_payments(state.store.as_ref(),state.superposition_service.as_ref(),&dimensions,queried_rung,)- .await- .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;+ .await;++ let (remaining_grace_days, remaining_budget) = get_adaptive_retry_allowances(+ state,+ &dimensions,+ payment_intent,+ max_retry_count,+ retry_count,+ now,+ )+ .await?;++ let adaptive_time = match tracking_data.prev_attempt_error_code {+ Some(error_code) => compute_adaptive_retry_time(+ state,+ error_code,+ remaining_grace_days,+ remaining_budget,+ )+ .await+ .map(common_utils::date_time::convert_to_pdt),+ None => None,+ };- // The one extra call. `None` whenever the algorithm has no opinion, in which- // case the decision resolves to the static time exactly as cascading would.- let adaptive_time: Option<time::PrimitiveDateTime> = None;+ // Neither algorithm has a time to offer: the adaptive ladder is spent and the+ // model declined. Only then is the MIT cascading ladder consulted, so the+ // lookup costs nothing on the paths that never reach it.+ let fallback_time = match (static_time, adaptive_time) {+ (None, None) => {+ get_schedule_time_to_retry_mit_payments(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ &dimensions,+ retry_count,+ )+ .await+ }+ _ => None,+ };let decision = pcr::schedule::decide_next_retry(static_ladder_progress,queried_rung,static_time,adaptive_time,- );+ fallback_time,+ )+ .ok_or_else(|| {+ logger::error!(+ queried_rung = queried_rung,+ error_code = ?tracking_data.prev_attempt_error_code,+ remaining_grace_days = remaining_grace_days,+ remaining_budget = remaining_budget,+ "No retry time available — the static ladder is exhausted, the adaptive \+ algorithm declined and the MIT ladder had nothing left"+ );+ errors::ProcessTrackerError::EApiErrorResponse+ })?;logger::info!(source = ?decision.source,queried_rung = queried_rung,static_time = ?static_time,+ adaptive_time = ?adaptive_time,+ fallback_time = ?fallback_time,+ error_code = ?tracking_data.prev_attempt_error_code,+ remaining_grace_days = remaining_grace_days,+ remaining_budget = remaining_budget,schedule_time = ?decision.schedule_time,"Adaptive retry decision");