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
feat(revenue-recovery): add adaptive retry scheduling for revenue recovery (#13824)
Rohan Mali4e31a5f253c4
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex bda30a33ad..4da60ed3e3 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -430,6 +430,13 @@ 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";+ /// 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";+ /// 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+ pub const RECOVERY_MAX_RETRY_COUNT: &str = "revenue_recovery.max_retry_count";/// Payment sync (psync) retry process tracker mapping keypub const PT_MAPPING_PAYMENT_SYNC: &str = "process_tracker.pt_mapping_payment_sync";/// Refund sync retry process tracker mapping keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex b9ab4f6e3a..52434f7a75 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -644,6 +644,60 @@ impl DatabaseBackedConfig for PtMappingPcrRetries {}}+config! {+ superposition_key = ADAPTIVE_RETRY_ENABLED,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for AdaptiveRetryEnabled {+ const KEY: &'static str = "adaptive_retry_enabled";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|merchant_id| format!("{}_{}", merchant_id.get_string_repr(), Self::KEY))+ }+}++config! {+ superposition_key = RECOVERY_GRACE_PERIOD_DAYS,+ output = i64,+ default = 30,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for RecoveryGracePeriodDays {+ const KEY: &'static str = "recovery_grace_period_days";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|merchant_id| format!("{}_{}", merchant_id.get_string_repr(), Self::KEY))+ }+}++config! {+ superposition_key = RECOVERY_MAX_RETRY_COUNT,+ output = i64,+ default = 15,+ requires = dimension_state::DimensionsWithProcessorMerchantIdAndConnector,+ targeting_key = id_type::PaymentId+}++impl DatabaseBackedConfig for RecoveryMaxRetryCount {+ const KEY: &'static str = "recovery_max_retry_count";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_processor_merchant_id()+ .map(|merchant_id| format!("{}_{}", merchant_id.get_string_repr(), Self::KEY))+ }+}+config! {superposition_key = PT_MAPPING_PAYMENT_SYNC,output = scheduler::types::process_data::ConnectorPTMapping,diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex 34cf5d633d..6908bc1f43 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -1,4 +1,5 @@pub mod api;+pub mod schedule;pub mod transformers;pub mod types;use std::marker::PhantomData;@@ -127,6 +128,7 @@ pub async fn upsert_calculate_pcr_task(payment_attempt_id,revenue_recovery_retry,invoice_scheduled_time: None,+ static_ladder_progress: schedule::StaticLadderProgress::default(),};let tag = ["PCR"];@@ -470,6 +472,8 @@ async fn insert_psync_pcr_task_to_pt(payment_attempt_id,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(),};let tag = ["REVENUE_RECOVERY"];let process_tracker_entry = storage::ProcessTrackerNew::new(@@ -613,7 +617,7 @@ pub async fn perform_calculate_workflow(.await?;// 2. Get best available token- let payment_processor_token_response =+ let (payment_processor_token_response, next_static_ladder_progress) =match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(state,&connector_customer_id,@@ -621,17 +625,21 @@ 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,).await{- Ok(token_opt) => token_opt,+ 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+ (+ revenue_recovery_workflow::PaymentProcessorTokenResponse::None,+ None,+ )}};@@ -667,20 +675,8 @@ pub async fn perform_calculate_workflow().await?;- db.as_scheduler()- .finish_process_with_business_status(- process.clone(),- business_status::CALCULATE_WORKFLOW_SCHEDULED,- )- .await- .map_err(|e| {- logger::error!(- process_id = %process.id,- error = ?e,- "Failed to update CALCULATE_WORKFLOW status to complete"- );- sch_errors::ProcessTrackerError::ProcessUpdateFailed- })?;+ finish_calculate_workflow_with_progress(db, process, next_static_ladder_progress)+ .await?;logger::info!(process_id = %process.id,@@ -802,6 +798,59 @@ pub async fn perform_calculate_workflow(Ok(())}+/// Finish the CALCULATE_WORKFLOW row, carrying any updated adaptive scheduling state.+async fn finish_calculate_workflow_with_progress(+ db: &dyn StorageInterface,+ process: &storage::ProcessTracker,+ next_static_ladder_progress: Option<schedule::StaticLadderProgress>,+) -> Result<(), sch_errors::ProcessTrackerError> {+ let pt_update = match next_static_ladder_progress {+ // The adaptive path has a ladder position to carry, so the consumed rung and the finish+ // go out in one write rather than leaving a window where one landed without the other.+ Some(static_ladder_progress) => {+ let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =+ serde_json::from_value(process.tracking_data.clone())+ .change_context(errors::RecoveryError::ValueNotFound)+ .attach_printable(+ "Failed to deserialize the tracking data from process tracker",+ )?;++ tracking_data.static_ladder_progress = static_ladder_progress;++ let tracking_data = serde_json::to_value(tracking_data)+ .change_context(errors::RecoveryError::ValueNotFound)+ .attach_printable("Failed to serialize the tracking data for process tracker")?;++ storage::ProcessTrackerUpdate::Update {+ name: None,+ retry_count: None,+ schedule_time: None,+ tracking_data: Some(tracking_data),+ business_status: Some(String::from(business_status::CALCULATE_WORKFLOW_SCHEDULED)),+ status: Some(ProcessTrackerStatus::Finish),+ updated_at: Some(common_utils::date_time::now()),+ }+ }+ // Nothing to persist - the same status-only write this row has always taken.+ None => storage::ProcessTrackerUpdate::StatusUpdate {+ status: ProcessTrackerStatus::Finish,+ business_status: Some(String::from(business_status::CALCULATE_WORKFLOW_SCHEDULED)),+ },+ };++ db.as_scheduler()+ .finish_process_with_update(process.clone(), pt_update)+ .await+ .map_err(|error| {+ logger::error!(+ process_id = %process.id,+ error = ?error,+ "Failed to update CALCULATE_WORKFLOW status to complete"+ );+ sch_errors::ProcessTrackerError::ProcessUpdateFailed+ })+}+/// Update the schedule time for a CALCULATE_WORKFLOW process trackerasync fn update_calculate_job_schedule_time(db: &dyn StorageInterface,@@ -984,6 +1033,8 @@ async fn insert_execute_pcr_task_to_pt(payment_attempt_id: payment_attempt_id.clone(),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(),};let tag = ["PCR"];diff --git a/crates/router/src/core/revenue_recovery/schedule.rs b/crates/router/src/core/revenue_recovery/schedule.rsnew file mode 100644index 0000000000..d3a9386732--- /dev/null+++ b/crates/router/src/core/revenue_recovery/schedule.rs@@ -0,0 +1,235 @@+use time::PrimitiveDateTime;++#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct StaticLadderProgress {+ /// Static ladder positions consumed so far.+ #[serde(default)]+ pub consumed_rungs: i32,+}++impl StaticLadderProgress {+ /// Ladder position to query for this decision.+ pub fn next_rung(&self) -> i32 {+ self.consumed_rungs + 1+ }+}++/// Which algorithm produced the scheduled time.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ScheduleSource {+ Static,+ Adaptive,+}++/// Outcome of one scheduling decision.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ScheduleDecision {+ /// Time to schedule the next retry for.+ pub schedule_time: PrimitiveDateTime,+ /// State to persist back onto the tracking data.+ pub next_progress: StaticLadderProgress,+ /// Which algorithm won, for logging and analytics.+ pub source: ScheduleSource,+}++pub fn decide_next_retry(+ schedule: &StaticLadderProgress,+ queried_rung: i32,+ static_time: 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,+ },+ None => ScheduleDecision {+ schedule_time: static_time,+ next_progress: StaticLadderProgress {+ consumed_rungs: queried_rung,+ },+ source: ScheduleSource::Static,+ },+ }+}++#[cfg(test)]+mod tests {+ use time::Duration;++ use super::*;++ /// `hours` past a fixed epoch, so tests read as a timeline.+ fn at(hours: i64) -> PrimitiveDateTime {+ let epoch = PrimitiveDateTime::new(+ time::Date::from_calendar_date(2026, time::Month::January, 1)+ .expect("valid calendar date"),+ time::Time::MIDNIGHT,+ );+ epoch + Duration::hours(hours)+ }++ fn at_rung(consumed_rungs: i32) -> StaticLadderProgress {+ StaticLadderProgress { consumed_rungs }+ }++ // ---- rung sourcing ----------------------------------------------------++ #[test]+ fn a_fresh_schedule_starts_the_ladder_at_one() {+ // Nothing consumed yet, so the first position offered is 1. Never 0 — `get_delay`+ // returns `None` for a non-positive index, which would fail the very first decision.+ assert_eq!(StaticLadderProgress::default().consumed_rungs, 0);+ assert_eq!(StaticLadderProgress::default().next_rung(), 1);+ }++ #[test]+ fn stored_rung_advances_by_one() {+ // Independent of `retry_count`, which runs ahead as adaptive retries are inserted.+ // Following it would exhaust a five-entry ladder long before rung 5.+ assert_eq!(at_rung(3).next_rung(), 4);+ }++ // ---- adaptive wins ----------------------------------------------------++ #[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)));++ assert_eq!(decision.schedule_time, at(72));+ assert_eq!(decision.source, ScheduleSource::Adaptive);+ // Rung 3 was offered but not used, so it is offered again next time.+ assert_eq!(decision.next_progress.consumed_rungs, 2);+ assert_eq!(decision.next_progress.next_rung(), 3);+ }++ #[test]+ fn adaptive_the_day_before_static_wins() {+ let static_time = at(240);+ let adaptive_time = at(240 - 1);+ assert!(adaptive_time.date() < static_time.date());++ let decision = decide_next_retry(+ &StaticLadderProgress::default(),+ 1,+ static_time,+ Some(adaptive_time),+ );++ assert_eq!(decision.schedule_time, adaptive_time);+ assert_eq!(decision.source, ScheduleSource::Adaptive);+ }++ // ---- static wins ------------------------------------------------------++ #[test]+ fn adaptive_later_day_loses_and_consumes_the_rung() {+ let decision = decide_next_retry(&at_rung(2), 3, at(240), Some(at(336)));++ assert_eq!(decision.schedule_time, at(240));+ assert_eq!(decision.source, ScheduleSource::Static);+ assert_eq!(decision.next_progress.consumed_rungs, 3);+ }++ #[test]+ fn no_adaptive_opinion_uses_static_and_consumes_the_rung() {+ let decision = decide_next_retry(&StaticLadderProgress::default(), 1, at(240), None);++ assert_eq!(decision.schedule_time, at(240));+ assert_eq!(decision.source, ScheduleSource::Static);+ assert_eq!(decision.next_progress.consumed_rungs, 1);+ }++ // ---- ties go to static ------------------------------------------------++ #[test]+ fn adaptive_earlier_on_the_same_day_still_loses() {+ // Static on day 10 at 18:00, adaptive on day 10 at 09:00. Static already covers that+ // day, so the earlier instant does not earn a second attempt on it.+ let static_time = at(240 + 18);+ let adaptive_time = at(240 + 9);+ assert_eq!(static_time.date(), adaptive_time.date());++ let decision = decide_next_retry(+ &StaticLadderProgress::default(),+ 1,+ static_time,+ Some(adaptive_time),+ );++ assert_eq!(decision.schedule_time, static_time);+ assert_eq!(decision.source, ScheduleSource::Static);+ assert_eq!(decision.next_progress.consumed_rungs, 1);+ }++ #[test]+ fn adaptive_identical_to_static_loses() {+ let decision =+ decide_next_retry(&StaticLadderProgress::default(), 1, at(240), Some(at(240)));++ assert_eq!(decision.source, ScheduleSource::Static);+ }++ // ---- successive decisions ---------------------------------------------++ #[test]+ fn a_rung_survives_repeated_adaptive_wins_and_is_spent_once() {+ // Driven through `next_rung` exactly as the workflow does, so rung sourcing is under+ // test rather than assumed.+ let schedule = StaticLadderProgress::default();++ // 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)));+ assert_eq!(first.source, ScheduleSource::Adaptive);++ // The process tracker's retry_count is now 2, but rung 1 was never used, so it is+ // offered again.+ 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)));+ 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);+ assert_eq!(third.source, ScheduleSource::Static);+ assert_eq!(third.next_progress.consumed_rungs, 1);++ // Three attempts in, exactly one static position spent — the next query is rung 2,+ // not rung 4 as `retry_count` alone would have given.+ assert_eq!(third.next_progress.next_rung(), 2);+ }++ // ---- persistence ------------------------------------------------------++ #[test]+ fn round_trips_through_json_and_absent_fields_default() {+ let schedule = at_rung(3);+ let encoded = serde_json::to_value(&schedule).expect("serialises");+ let decoded: StaticLadderProgress = serde_json::from_value(encoded).expect("deserialises");+ assert_eq!(decoded, schedule);++ // Invoices already in flight have no `static_ladder_progress` at all.+ let empty: StaticLadderProgress = serde_json::from_value(serde_json::json!({}))+ .expect("absent fields fall back to defaults");+ assert_eq!(empty, StaticLadderProgress::default());+ assert_eq!(empty.consumed_rungs, 0);+ // …and therefore resume at whatever the ladder was already indexed by.+ assert_eq!(empty.next_rung(), 1);+ }+}diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 92d518a5a1..62ff1ce83a 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -1289,6 +1289,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure(global_payment_id: old_tracking_data.global_payment_id.clone(),billing_mca_id: old_tracking_data.billing_mca_id.clone(),invoice_scheduled_time: old_tracking_data.invoice_scheduled_time,+ static_ladder_progress: old_tracking_data.static_ladder_progress,};let tracking_data = serde_json::to_value(new_tracking_data)diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 8e97154186..2612d6132a 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -2969,6 +2969,15 @@ impl ProcessTrackerInterface for KafkaStore {.finish_process_with_business_status(this, business_status).await}+ async fn finish_process_with_update(+ &self,+ this: storage::ProcessTracker,+ update: storage::ProcessTrackerUpdate,+ ) -> CustomResult<(), errors::StorageError> {+ self.diesel_store+ .finish_process_with_update(this, update)+ .await+ }async fn find_processes_by_time_status(&self,time_lower_limit: PrimitiveDateTime,diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex 0991a40ca4..2fed15d28c 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -13,7 +13,10 @@ use hyperswitch_masking::PeekInterface;use router_env::logger;use serde::{Deserialize, Serialize};-use crate::{db::StorageInterface, routes::SessionState, types, workflows::revenue_recovery};+use crate::{+ core::revenue_recovery::schedule::StaticLadderProgress, db::StorageInterface,+ routes::SessionState, types, workflows::revenue_recovery,+};#[derive(serde::Serialize, serde::Deserialize, Debug)]pub struct RevenueRecoveryWorkflowTrackingData {pub merchant_id: id_type::MerchantId,@@ -23,6 +26,11 @@ pub struct RevenueRecoveryWorkflowTrackingData {pub billing_mca_id: id_type::MerchantConnectorAccountId,pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType,pub invoice_scheduled_time: Option<time::PrimitiveDateTime>,+ /// Adaptive retry scheduling state — how far down the static ladder this invoice has+ /// 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,}#[derive(Debug, Clone)]diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex 7baca6324b..30a199ca40 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -636,8 +636,19 @@ 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,-) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {+ static_ladder_progress: &pcr::schedule::StaticLadderProgress,+) -> CustomResult<+ (+ PaymentProcessorTokenResponse,+ Option<pcr::schedule::StaticLadderProgress>,+ ),+ errors::ProcessTrackerError,+> {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.+ let mut next_static_ladder_progress = None;match retry_algorithm_type {RevenueRecoveryAlgorithmType::Monitoring => {logger::error!("Monitoring type found for Revenue Recovery retry payment");@@ -656,74 +667,87 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(.await.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;- let payment_processor_token = payment_intent- .feature_metadata- .as_ref()- .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())- .map(|recovery_metadata| {- recovery_metadata- .billing_connector_payment_details- .payment_processor_token- .clone()- });-- let payment_processor_tokens_details =- RedisTokenManager::get_payment_processor_metadata_for_connector_customer(+ payment_processor_token_response = get_token_availability_for_schedule_time(+ state,+ connector_customer_id,+ payment_intent,+ time,+ )+ .await?;+ }++ RevenueRecoveryAlgorithmType::Smart => {+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())+ .with_connector(billing_connector);++ let adaptive_retry_enabled = dimensions+ .get_adaptive_retry_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await;++ 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.+ let queried_rung = static_ladder_progress.next_rung();+ let static_time = get_schedule_time_to_retry_mit_payments(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ &dimensions,+ queried_rung,+ )+ .await+ .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;++ // 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;++ let decision = pcr::schedule::decide_next_retry(+ static_ladder_progress,+ queried_rung,+ static_time,+ adaptive_time,+ );++ logger::info!(+ source = ?decision.source,+ queried_rung = queried_rung,+ static_time = ?static_time,+ schedule_time = ?decision.schedule_time,+ "Adaptive retry decision"+ );++ payment_processor_token_response = get_token_availability_for_schedule_time(state,connector_customer_id,+ payment_intent,+ decision.schedule_time,)- .await- .change_context(errors::ProcessTrackerError::ERedisError(- errors::RedisError::RedisConnectionError.into(),- ))?;-- // Get the token info from redis- let payment_processor_tokens_details_with_retry_info = payment_processor_token- .as_ref()- .and_then(|t| payment_processor_tokens_details.get(t));+ .await?;- // If payment_processor_tokens_details_with_retry_info is None, then no schedule time- match payment_processor_tokens_details_with_retry_info {- None => {- payment_processor_token_response = PaymentProcessorTokenResponse::None;- logger::debug!("No payment processor token found for cascading retry");- }- Some(payment_token) => {- if payment_token.token_status.is_hard_decline.unwrap_or(false) {- payment_processor_token_response =- PaymentProcessorTokenResponse::HardDecline;- } else if payment_token.retry_wait_time_hours > 0 {- let utc_schedule_time: time::OffsetDateTime =- time::OffsetDateTime::now_utc()- + time::Duration::hours(payment_token.retry_wait_time_hours);- let next_available_time = time::PrimitiveDateTime::new(- utc_schedule_time.date(),- utc_schedule_time.time(),- );-- payment_processor_token_response =- PaymentProcessorTokenResponse::NextAvailableTime {- next_available_time,- };- } else {- payment_processor_token_response =- PaymentProcessorTokenResponse::ScheduledTime {- scheduled_time: time,- };- }+ // The rung is consumed only when a retry is genuinely scheduled. The other+ // responses finish or reschedule the CALCULATE job without an attempt.+ if matches!(+ payment_processor_token_response,+ PaymentProcessorTokenResponse::ScheduledTime { .. }+ ) {+ next_static_ladder_progress = Some(decision.next_progress);}+ } else {+ payment_processor_token_response = get_best_psp_token_available_for_smart_retry(+ state,+ connector_customer_id,+ payment_intent,+ )+ .await+ .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;}}-- RevenueRecoveryAlgorithmType::Smart => {- payment_processor_token_response = get_best_psp_token_available_for_smart_retry(- state,- connector_customer_id,- payment_intent,- )- .await- .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;- }}match &mut payment_processor_token_response {@@ -758,6 +782,73 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(}}+ Ok((+ payment_processor_token_response,+ next_static_ladder_progress,+ ))+}++/// Check the invoice's payment processor token against a schedule time already decided.+/// Shared by the cascading and adaptive paths so both gate on the same conditions+#[cfg(feature = "v2")]+async fn get_token_availability_for_schedule_time(+ state: &SessionState,+ connector_customer_id: &str,+ payment_intent: &PaymentIntent,+ scheduled_time: time::PrimitiveDateTime,+) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {+ let payment_processor_token = payment_intent+ .feature_metadata+ .as_ref()+ .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())+ .map(|recovery_metadata| {+ recovery_metadata+ .billing_connector_payment_details+ .payment_processor_token+ .clone()+ });++ let payment_processor_tokens_details =+ RedisTokenManager::get_payment_processor_metadata_for_connector_customer(+ state,+ connector_customer_id,+ )+ .await+ .change_context(errors::ProcessTrackerError::ERedisError(+ errors::RedisError::RedisConnectionError.into(),+ ))?;++ // Get the token info from redis+ let payment_processor_tokens_details_with_retry_info = payment_processor_token+ .as_ref()+ .and_then(|token| payment_processor_tokens_details.get(token));++ // If payment_processor_tokens_details_with_retry_info is None, then no schedule time+ let payment_processor_token_response = match payment_processor_tokens_details_with_retry_info {+ None => {+ logger::debug!("No payment processor token found for retry");+ PaymentProcessorTokenResponse::None+ }+ Some(payment_token) => {+ if payment_token.token_status.is_hard_decline.unwrap_or(false) {+ PaymentProcessorTokenResponse::HardDecline+ } else if payment_token.retry_wait_time_hours > 0 {+ let utc_schedule_time: time::OffsetDateTime = time::OffsetDateTime::now_utc()+ + time::Duration::hours(payment_token.retry_wait_time_hours);+ let next_available_time = time::PrimitiveDateTime::new(+ utc_schedule_time.date(),+ utc_schedule_time.time(),+ );++ PaymentProcessorTokenResponse::NextAvailableTime {+ next_available_time,+ }+ } else {+ PaymentProcessorTokenResponse::ScheduledTime { scheduled_time }+ }+ }+ };+Ok(payment_processor_token_response)}diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rsindex 8d9396472c..de78c2fd40 100644--- a/crates/scheduler/src/db/process_tracker.rs+++ b/crates/scheduler/src/db/process_tracker.rs@@ -55,6 +55,13 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static {business_status: &'static str,) -> CustomResult<(), errors::StorageError>;+ /// Finish a process while updating any other columns in the same write.+ async fn finish_process_with_update(+ &self,+ this: storage::ProcessTracker,+ update: storage::ProcessTrackerUpdate,+ ) -> CustomResult<(), errors::StorageError>;+async fn find_processes_by_time_status(&self,time_lower_limit: PrimitiveDateTime,@@ -182,6 +189,18 @@ impl ProcessTrackerInterface for Store {Ok(())}+ async fn finish_process_with_update(+ &self,+ this: storage::ProcessTracker,+ update: storage::ProcessTrackerUpdate,+ ) -> CustomResult<(), errors::StorageError> {+ self.update_process(this, update)+ .await+ .attach_printable("Failed to finish process with update")?;+ metrics::TASK_FINISHED.add(1, &[]);+ Ok(())+ }+async fn process_tracker_update_process_status_by_ids(&self,task_ids: Vec<String>,@@ -292,6 +311,15 @@ impl ProcessTrackerInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn finish_process_with_update(+ &self,+ _this: storage::ProcessTracker,+ _update: storage::ProcessTrackerUpdate,+ ) -> CustomResult<(), errors::StorageError> {+ // [#172]: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }+async fn process_tracker_update_process_status_by_ids(&self,_task_ids: Vec<String>,