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 support for storing retry stats in DB (#13793)
Anurag Thakur200a8066b673
diff --git a/config/config.example.toml b/config/config.example.tomlindex ee06387837..fece980b75 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1494,6 +1494,11 @@ reopen_workflow_buffer_time_in_seconds = 3600 # time in seconds to be added inmax_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recoveryredis_ttl_buffer_in_seconds= 300 # buffer time in seconds to be added to redis ttl for Revenue Recovery+# Redis lock configuration guarding the retry-stats read-merge-write+[revenue_recovery.retry_stats_lock]+redis_lock_expiry_seconds = 10 # Seconds before redis lock expires+delay_between_retries_in_milliseconds = 100 # Wait between attempts to acquire a contended lock+[clone_connector_allowlist]connector_names = "connector_names" # Comma-separated list of cloneable connector namesdiff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 57b0581fba..3d3b770774 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -486,6 +486,11 @@ reopen_workflow_buffer_time_in_seconds = 3600 # time in seconds to be added inmax_random_schedule_delay_in_seconds = 300 # max random delay in seconds to schedule the payment for Revenue Recoveryredis_ttl_buffer_in_seconds=300 # buffer time in seconds to be added to redis ttl for Revenue Recovery+# Redis lock configuration guarding the retry-stats read-merge-write+[revenue_recovery.retry_stats_lock]+redis_lock_expiry_seconds = 10 # Seconds before redis lock expires+delay_between_retries_in_milliseconds = 100 # Wait between attempts to acquire a contended lock+[chat]enabled = false # Enable or disable chat featureshyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow hostdiff --git a/config/development.toml b/config/development.tomlindex 31977570ed..d3693cd5b0 100644--- a/config/development.toml+++ b/config/development.toml@@ -1607,6 +1607,11 @@ max_random_schedule_delay_in_seconds = 300redis_ttl_buffer_in_seconds= 300unretried_invoice_schedule_time_offset_seconds = 60+# Redis lock configuration guarding the retry-stats read-merge-write+[revenue_recovery.retry_stats_lock]+redis_lock_expiry_seconds = 10 # Seconds before redis lock expires+delay_between_retries_in_milliseconds = 100 # Wait between attempts to acquire a contended lock+[revenue_recovery.card_config.amex]max_retries_per_day = 20max_retry_count_for_thirty_day = 20diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex fc2099915e..2e54e26939 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1491,6 +1491,11 @@ initial_timestamp_in_seconds = 3600 # number of seconds added to start tijob_schedule_buffer_time_in_seconds = 3600 # time in seconds to be added in schedule time as a bufferreopen_workflow_buffer_time_in_seconds = 60 # time in seconds to be added in scheduling for calculate workflow+# Redis lock configuration guarding the retry-stats read-merge-write+[revenue_recovery.retry_stats_lock]+redis_lock_expiry_seconds = 10 # Seconds before redis lock expires+delay_between_retries_in_milliseconds = 100 # Wait between attempts to acquire a contended lock+[clone_connector_allowlist]connector_names = "stripe, adyen, peachpayments, cybersource, braintree, nuvei, worldpay, loonio, gigadat, zift" # Comma-separated list of cloneable connector namesdiff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 75d8936098..a1866ee5ea 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -13756,6 +13756,15 @@ impl PaymentRevenueRecoveryMetadata {.connector_customer_id.to_owned()}++ /// Card network of the recovery card, from the billing-connector payment method+ /// details+ pub fn get_card_network(&self) -> Option<common_enums::enums::CardNetwork> {+ self.billing_connector_payment_method_details+ .as_ref()+ .and_then(|details| details.get_billing_connector_card_info())+ .and_then(|card| card.card_network.clone())+ }}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rsindex 80494f08a3..550798b1fc 100644--- a/crates/diesel_models/src/lib.rs+++ b/crates/diesel_models/src/lib.rs@@ -7,6 +7,8 @@ pub mod capture;pub mod card_issuer;pub mod cards_info;pub mod configs;+#[cfg(feature = "v2")]+pub mod revenue_recovery_retry_stats;pub mod authentication;pub mod authorization;diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rsindex 52c517ec4f..b920f33cff 100644--- a/crates/diesel_models/src/query.rs+++ b/crates/diesel_models/src/query.rs@@ -6,6 +6,8 @@ mod capture;pub mod card_issuer;pub mod cards_info;pub mod configs;+#[cfg(feature = "v2")]+pub mod revenue_recovery_retry_stats;pub mod authentication;pub mod authorization;diff --git a/crates/diesel_models/src/query/revenue_recovery_retry_stats.rs b/crates/diesel_models/src/query/revenue_recovery_retry_stats.rsnew file mode 100644index 0000000000..b19f3565e9--- /dev/null+++ b/crates/diesel_models/src/query/revenue_recovery_retry_stats.rs@@ -0,0 +1,52 @@+use async_bb8_diesel::AsyncRunQueryDsl;+use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};+use error_stack::ResultExt;+use hyperswitch_masking::Secret;++use super::generics;+use crate::{+ errors,+ revenue_recovery_retry_stats::{RevenueRecoveryRetryStats, RevenueRecoveryRetryStatsNew},+ schema_v2::revenue_recovery_retry_stats::dsl,+ DatabaseConnectionWithContext, StorageResult,+};++impl RevenueRecoveryRetryStatsNew {+ pub async fn insert(+ self,+ conn: &DatabaseConnectionWithContext<'_>,+ ) -> StorageResult<RevenueRecoveryRetryStats> {+ diesel::insert_into(<RevenueRecoveryRetryStats as HasTable>::table())+ .values(self)+ .get_result_async::<RevenueRecoveryRetryStats>(conn.raw_connection())+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("error inserting revenue_recovery_retry_stats row")+ }+}++impl RevenueRecoveryRetryStats {+ pub async fn update_stats(+ conn: &DatabaseConnectionWithContext<'_>,+ cluster_key: String,+ stats: Secret<serde_json::Value>,+ ) -> StorageResult<Self> {+ diesel::update(<Self as HasTable>::table().filter(dsl::cluster_key.eq(cluster_key)))+ .set(dsl::stats.eq(stats))+ .get_result_async::<Self>(conn.raw_connection())+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("error updating revenue_recovery_retry_stats row")+ }++ pub async fn find_by_key(+ conn: &DatabaseConnectionWithContext<'_>,+ key: String,+ ) -> StorageResult<Option<Self>> {+ generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::cluster_key.eq(key),+ )+ .await+ }+}diff --git a/crates/diesel_models/src/revenue_recovery_retry_stats.rs b/crates/diesel_models/src/revenue_recovery_retry_stats.rsnew file mode 100644index 0000000000..f86c759a4e--- /dev/null+++ b/crates/diesel_models/src/revenue_recovery_retry_stats.rs@@ -0,0 +1,21 @@+use diesel::{Identifiable, Queryable, Selectable};+use hyperswitch_masking::Secret;++use crate::schema_v2::revenue_recovery_retry_stats;++#[derive(+ Clone, Debug, Queryable, Identifiable, Selectable, serde::Serialize, serde::Deserialize,+)]+#[diesel(table_name = revenue_recovery_retry_stats, check_for_backend(diesel::pg::Pg))]+#[diesel(primary_key(cluster_key))]+pub struct RevenueRecoveryRetryStats {+ pub cluster_key: String,+ pub stats: Secret<serde_json::Value>,+}++#[derive(Clone, Debug, diesel::Insertable, serde::Serialize, serde::Deserialize)]+#[diesel(table_name = revenue_recovery_retry_stats)]+pub struct RevenueRecoveryRetryStatsNew {+ pub cluster_key: String,+ pub stats: Secret<serde_json::Value>,+}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 5bed5246a6..798899e327 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1651,6 +1651,16 @@ diesel::table! {}}+diesel::table! {+ use diesel::sql_types::*;+ use crate::enums::diesel_exports::*;++ revenue_recovery_retry_stats (cluster_key) {+ cluster_key -> Text,+ stats -> Jsonb,+ }+}+diesel::table! {use diesel::sql_types::*;use crate::enums::diesel_exports::*;@@ -1976,6 +1986,7 @@ diesel::allow_tables_to_appear_in_same_query!(process_tracker,refund,relay,+ revenue_recovery_retry_stats,reverse_lookup,roles,routing_algorithm,diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rsindex d0bc50b20e..9da43761f6 100644--- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs@@ -1,3 +1,7 @@+pub mod retry_stats;+pub mod retry_stats_cluster_key;+pub mod retry_stats_document;+use api_models::{payments as api_payments, webhooks};use common_enums::enums as common_enums;use common_types::primitive_wrappers;@@ -107,6 +111,7 @@ pub struct RecoveryPaymentAttempt {pub network_decline_code: Option<String>,pub error_code: Option<String>,pub created_at: PrimitiveDateTime,+ pub standardised_error_code: Option<common_enums::StandardisedCode>,}impl RecoveryPaymentAttempt {@@ -324,6 +329,7 @@ impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt.as_ref().map(|error| error.code.clone()),created_at: payment_attempt.created_at,+ standardised_error_code: None,}}}diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats.rs b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats.rsnew file mode 100644index 0000000000..b484cbada7--- /dev/null+++ b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats.rs@@ -0,0 +1,7 @@+use super::{retry_stats_cluster_key::RetryStatsClusterKey, retry_stats_document::StatsDocument};++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct RevenueRecoveryRetryStats {+ pub cluster_key: RetryStatsClusterKey,+ pub stats: StatsDocument,+}diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_cluster_key.rs b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_cluster_key.rsnew file mode 100644index 0000000000..7084ab6d15--- /dev/null+++ b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_cluster_key.rs@@ -0,0 +1,391 @@+use std::{fmt, str::FromStr};++use common_enums::{CardType, StandardisedCode};+use router_env::logger;++/// Layout version prefixed to every persisted cluster key. Bump this whenever+/// the key layout changes (segment order, segment count, escaping rules) so+/// `from_db_string` rejects keys written under an old layout instead of silently+/// misreading them.+pub const RETRY_STATS_KEY_VERSION: &str = "v1";+pub const KEY_SEPARATOR: char = '|';+pub const SEGMENT_SEPARATOR: char = '/';+pub const WILDCARD_SEGMENT: &str = "*";+pub const UNKNOWN_SEGMENT: &str = "UNK";++/// A single cluster-key dimension. Generic over the strict type of its resolved+/// value (`StandardisedCode` for the error code, `CardType` for the funding type,+/// `String` for the free-text issuer) so a value of the wrong kind cannot be placed+/// in the wrong slot at construction time. `Unknown` marks a value we could not+/// resolve; `Any` is the wildcard placeholder used by ancestor roll-up nodes.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Dim<T> {+ Val(T),+ Unknown,+ Any,+}++impl<T: fmt::Display> Dim<T> {+ fn as_segment(&self) -> String {+ match self {+ Self::Val(raw) => escape_segment(&raw.to_string()),+ Self::Unknown => UNKNOWN_SEGMENT.to_string(),+ Self::Any => WILDCARD_SEGMENT.to_string(),+ }+ }+}++impl<T: FromStr> Dim<T> {+ /// Build a dimension from a raw event string, normalizing the reserved+ /// spellings (empty/`*`/`UNK`) to `Unknown` and parsing the remainder into `T`.+ /// A value that does not parse into `T` also yields `Unknown`.+ pub fn from_event_value(value: Option<&str>) -> Self {+ match value.map(str::trim).filter(|v| !v.is_empty()) {+ None => Self::Unknown,+ Some(v) if v == WILDCARD_SEGMENT || v.eq_ignore_ascii_case(UNKNOWN_SEGMENT) => {+ Self::Unknown+ }+ Some(v) => T::from_str(v).map(Self::Val).unwrap_or(Self::Unknown),+ }+ }++ fn parse_segment(s: &str) -> Option<Self> {+ match s {+ WILDCARD_SEGMENT => Some(Self::Any),+ UNKNOWN_SEGMENT => Some(Self::Unknown),+ _ => {+ let decoded = unescape_segment(s)?;+ Some(+ T::from_str(&decoded)+ .map(Self::Val)+ .unwrap_or(Self::Unknown),+ )+ }+ }+ }+}++fn escape_segment(raw: &str) -> String {+ let mut out = String::with_capacity(raw.len());+ for ch in raw.chars() {+ match ch {+ '%' => out.push_str("%25"),+ '|' => out.push_str("%7C"),+ '/' => out.push_str("%2F"),+ '*' => out.push_str("%2A"),+ _ => out.push(ch),+ }+ }+ out+}++/// Reverse [`escape_segment`]. Percent-decoding is **byte-oriented**: a `%XX`+/// escape contributes one raw byte and literal characters contribute their UTF-8+/// bytes, then the whole buffer is validated as UTF-8 in one shot. This keeps the+/// decoder compatible with standard percent-encoding — a `%`-escaped multi-byte+/// UTF-8 sequence (e.g. `%C3%BC`) reassembles into the original character instead+/// of being mangled into one Latin-1 char per byte. Malformed escapes (short or+/// non-hex) and byte sequences that are not valid UTF-8 both yield `None`.+fn unescape_segment(encoded: &str) -> Option<String> {+ let mut bytes = Vec::with_capacity(encoded.len());+ let mut chars = encoded.chars();+ while let Some(ch) = chars.next() {+ if ch == '%' {+ let hi = chars.next()?;+ let lo = chars.next()?;+ bytes.push(u8::from_str_radix(&format!("{hi}{lo}"), 16).ok()?);+ } else {+ let mut buf = [0u8; 4];+ bytes.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());+ }+ }+ String::from_utf8(bytes).ok()+}++/// Compile-time guard invoked once per generated key: asserts the dimension+/// indices are exactly `0, 1, 2, …` in declaration order. This is what turns the+/// explicit position numbers in [`define_retry_stats_key!`] from decoration into+/// an enforced invariant — a reorder, a gap, or a duplicated index makes this+/// `assert!` fail at compile time rather than silently shifting the wire layout.+#[allow(clippy::indexing_slicing)]+const fn assert_contiguous_indices(indices: &[usize]) {+ let mut i = 0;+ while i < indices.len() {+ assert!(+ indices[i] == i,+ "retry-stats cluster key: dimension indices must be 0, 1, 2, … in \+ declaration order. Do NOT reorder or insert dimensions — only append \+ a new one with the next index, and bump RETRY_STATS_KEY_VERSION."+ );+ i += 1;+ }+}++/// Declares the cluster key's dimensions **once**, in persisted order, and+/// generates the struct plus the entire serialize/deserialize surface from that+/// single ordered list: the `Dim<_>` fields, `SEGMENT_COUNT`, `segments`,+/// `leaf`/`new`, and the exact-mirror `as_db_string` / `from_db_string` pair.+///+/// Each dimension carries an explicit `<index> =>` position. The index is not+/// cosmetic: [`assert_contiguous_indices`] enforces at compile time that the+/// indices run `0, 1, 2, …` in the order the fields are written, so the hazards+/// called out at the invocation site turn into build failures instead of silent+/// data corruption.+macro_rules! define_retry_stats_key {+ (+ $(#[$struct_meta:meta])*+ $vis:vis struct $name:ident {+ $(+ $(#[$field_meta:meta])*+ $idx:literal => $field:ident : $ty:ty+ ),* $(,)?+ }+ ) => {+ $(#[$struct_meta])*+ #[derive(Clone, Debug, PartialEq, Eq)]+ $vis struct $name {+ $(+ $(#[$field_meta])*+ pub $field: Dim<$ty>,+ )*+ }++ /// Number of dimension segments in a key, derived from the dimension list+ /// so it can never drift from the number of fields.+ const SEGMENT_COUNT: usize = [$( $idx ),*].len();++ // Compile-time check that the declared indices are `0, 1, 2, ...` in order.+ const _: () = assert_contiguous_indices(&[$( $idx ),*]);++ impl $name {+ /// Assemble a fully-qualified (leaf) key from already-resolved dimensions.+ pub fn leaf($($field: Dim<$ty>),*) -> Self {+ Self { $($field),* }+ }++ /// Convenience constructor for callers (e.g. a retry algorithm) that+ /// already hold concrete dimension values rather than `Dim`s.+ pub fn new($($field: impl Into<$ty>),*) -> Self {+ Self { $($field: Dim::Val($field.into())),* }+ }++ /// The key's dimension segments in persisted order. Generated straight+ /// from the dimension list, so it is the same order `from_db_string`+ /// consumes them in — the two can never disagree by hand.+ fn segments(&self) -> [String; SEGMENT_COUNT] {+ [ $( self.$field.as_segment() ),* ]+ }++ /// Serialize to the persisted `cluster_key`. Generated as the exact+ /// mirror of `from_db_string`: both walk the dimension list in the same+ /// order, so a stored row decodes iff the layout is unchanged.+ pub fn as_db_string(&self) -> String {+ let mut out = String::new();+ out.push_str(RETRY_STATS_KEY_VERSION);+ out.push(KEY_SEPARATOR);+ out.push_str(&self.segments().join(&SEGMENT_SEPARATOR.to_string()));+ out+ }++ /// Parse a persisted `cluster_key`. Generated as the exact mirror of+ /// `as_db_string`. Parsing is strict about arity (exactly+ /// [`SEGMENT_COUNT`] segments): a key with extra or missing segments is+ /// rejected as `None` rather than silently truncated or padded, so a+ /// miswritten row can never resolve to the wrong cluster.+ pub fn from_db_string(raw: &str) -> Option<Self> {+ let Some((version, rest)) = raw.split_once(KEY_SEPARATOR) else {+ logger::error!(+ cluster_key = raw,+ "revenue_recovery_retry_stats: cluster key has no version separator"+ );+ return None;+ };+ if version != RETRY_STATS_KEY_VERSION {+ logger::error!(+ cluster_key = raw,+ version,+ expected_version = RETRY_STATS_KEY_VERSION,+ "revenue_recovery_retry_stats: cluster key written under an unsupported layout version"+ );+ return None;+ }+ let segments = rest.split(SEGMENT_SEPARATOR).collect::<Vec<_>>();+ let Ok([$($field),*]) = <[&str; SEGMENT_COUNT]>::try_from(segments) else {+ logger::error!(+ cluster_key = raw,+ expected_segments = SEGMENT_COUNT,+ "revenue_recovery_retry_stats: cluster key has the wrong number of segments"+ );+ return None;+ };+ Some(Self {+ $(+ $field: Dim::<$ty>::parse_segment($field)+ .or_else(|| Self::log_segment_failure(raw, stringify!($field), $field))?,+ )*+ })+ }+ }+ };+}++// The cluster key's single source of truth.+//+// ⚠️ ORDER IS A PERSISTENCE CONTRACT. The `<index> =>` position of each+// dimension below is the exact segment position it occupies in every row+// already stored in the database. Because serialization is positional:+//+// • REORDERING two dimensions silently swaps the meaning of every stored+// segment. For same-typed dimensions (e.g. two `String`s) the generated+// code stays byte-identical and even the roundtrip tests still pass — the+// corruption is invisible to both the type checker and the tests.+// • INSERTING a dimension anywhere but the end shifts every following+// segment by one, so old rows decode into the wrong fields.+//+// The explicit indices exist to make both mistakes a COMPILE ERROR:+// `assert_contiguous_indices` requires them to stay `0, 1, 2, …` in written+// order, so a reorder or a mid-list insert fails the build.+//+// The ONLY safe change is to APPEND a new dimension with the next index.+// Never edit the index of an existing dimension.+define_retry_stats_key! {+ /// The dimensional key a retry outcome is recorded under+ pub struct RetryStatsClusterKey {+ 0 => error_code: StandardisedCode,+ 1 => card_type: CardType,+ 2 => issuer: String,+ }+}++impl RetryStatsClusterKey {+ /// Build an error-code-only key: keyed on the error code with `card_type`+ /// and `issuer` left `Unknown`, serializing to `error_code/UNK/UNK`+ pub fn from_error_code(error_code: StandardisedCode) -> Self {+ Self {+ error_code: Dim::Val(error_code),+ card_type: Dim::Unknown,+ issuer: Dim::Unknown,+ }+ }++ /// Log a segment that could not be decoded back into a `Dim` and propagate the+ /// failure as `None`. Only reachable when `unescape_segment` rejects malformed+ /// percent-escaping — parse failures on a strictly-typed value degrade to+ /// `Dim::Unknown` inside `parse_segment` rather than surfacing here.+ fn log_segment_failure<T>(raw: &str, field: &str, segment: &str) -> Option<T> {+ logger::error!(+ cluster_key = raw,+ field,+ segment,+ "revenue_recovery_retry_stats: cluster key segment failed to decode"+ );+ None+ }+}++#[cfg(test)]+#[allow(clippy::indexing_slicing)]+mod tests {+ use super::*;++ #[test]+ fn leaf_roundtrips() {+ let key = RetryStatsClusterKey::new(StandardisedCode::DoNotHonor, CardType::Credit, "HDFC");+ let raw = key.as_db_string();+ assert_eq!(raw, "v1|do_not_honor/CREDIT/HDFC");+ assert_eq!(RetryStatsClusterKey::from_db_string(&raw), Some(key));+ }++ #[test]+ fn segment_count_matches_declared_dimensions() {+ // Pins the generated arity: this is `error_code / card_type / issuer`.+ // If this changes you added or removed a dimension — a layout change that+ // must bump RETRY_STATS_KEY_VERSION and migrate existing rows.+ assert_eq!(SEGMENT_COUNT, 3);+ }++ #[test]+ fn issuer_delimiters_and_stars_are_percent_escaped() {+ let key =+ RetryStatsClusterKey::new(StandardisedCode::DoNotHonor, CardType::Debit, "H|D*F/C");+ let raw = key.as_db_string();+ assert!(raw.contains("%7C"));+ assert!(raw.contains("%2A"));+ assert!(raw.contains("%2F"));+ assert_eq!(RetryStatsClusterKey::from_db_string(&raw), Some(key));+ }++ #[test]+ fn non_ascii_issuer_roundtrips() {+ // Non-ASCII issuer names ride through escaping literally and must survive+ // a full serialize -> parse cycle without corruption.+ let key =+ RetryStatsClusterKey::new(StandardisedCode::DoNotHonor, CardType::Credit, "Zürich");+ assert_eq!(+ RetryStatsClusterKey::from_db_string(&key.as_db_string()),+ Some(key)+ );+ }++ #[test]+ fn standard_percent_encoded_utf8_decodes_correctly() {+ // A `%`-escaped multi-byte UTF-8 sequence (standard percent-encoding of "ü")+ // must reassemble into the original character, not one Latin-1 char per byte.+ let key = RetryStatsClusterKey::from_db_string("v1|do_not_honor/CREDIT/Z%C3%BCrich")+ .expect("valid key");+ assert_eq!(key.issuer, Dim::Val("Zürich".to_string()));+ }++ #[test]+ fn invalid_utf8_percent_sequence_is_rejected() {+ // A lone continuation byte is not valid UTF-8, so the segment must fail to+ // decode rather than producing a mojibake issuer.+ assert!(RetryStatsClusterKey::from_db_string("v1|do_not_honor/CREDIT/%FF").is_none());+ }++ #[test]+ fn from_error_code_uses_unknown_sub_dims() {+ let key = RetryStatsClusterKey::from_error_code(StandardisedCode::InsufficientFunds);+ assert_eq!(key.as_db_string(), "v1|insufficient_funds/UNK/UNK");+ }++ #[test]+ fn from_db_rejects_foreign_versions_and_wildcards() {+ assert!(RetryStatsClusterKey::from_db_string("v2|a/b/c").is_none());+ assert!(RetryStatsClusterKey::from_db_string("v1|do_not_honor/*/*").is_some());+ }++ #[test]+ fn from_db_rejects_wrong_segment_counts() {+ assert!(RetryStatsClusterKey::from_db_string("v1|a/b").is_none());+ assert!(RetryStatsClusterKey::from_db_string("v1|a/b/c/d").is_none());+ assert!(RetryStatsClusterKey::from_db_string("v1|").is_none());+ assert!(RetryStatsClusterKey::from_db_string("v1").is_none());+ }++ #[test]+ fn unknown_and_any_dims_roundtrip() {+ let key = RetryStatsClusterKey {+ error_code: Dim::Unknown,+ card_type: Dim::Any,+ issuer: Dim::Val("HDFC".into()),+ };+ assert_eq!(key.as_db_string(), "v1|UNK/*/HDFC");+ assert_eq!(+ RetryStatsClusterKey::from_db_string(&key.as_db_string()),+ Some(key)+ );+ }++ #[test]+ fn from_event_value_normalizes_reserved_spellings() {+ assert_eq!(Dim::<String>::from_event_value(Some(" ")), Dim::Unknown);+ assert_eq!(Dim::<String>::from_event_value(None), Dim::Unknown);+ assert_eq!(Dim::<String>::from_event_value(Some("*")), Dim::Unknown);+ assert_eq!(Dim::<String>::from_event_value(Some("unk")), Dim::Unknown);+ assert_eq!(+ Dim::<String>::from_event_value(Some("HDFC")),+ Dim::Val("HDFC".into())+ );+ }+}diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_document.rs b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_document.rsnew file mode 100644index 0000000000..2b5c3a1eb7--- /dev/null+++ b/crates/hyperswitch_domain_models/src/revenue_recovery/retry_stats_document.rs@@ -0,0 +1,302 @@+use router_env::logger;+use serde::{Deserialize, Serialize};+use time::PrimitiveDateTime;++/// Success counter for a single slot. Invariant: `k <= n` — every successful retry+/// is also counted as a retry, so the success count can never exceed the total.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct SlotCounter {+ /// `n` = total number of retries recorded in this slot.+ #[serde(default)]+ pub n: u64,+ /// `k` = number of those retries that succeeded (`k <= n`).+ #[serde(default)]+ pub k: u64,+}++impl SlotCounter {+ pub fn record(&mut self, success: bool) {+ self.n = self.n.saturating_add(1);+ if success {+ self.k = self.k.saturating_add(1);+ }+ }+}++/// Stats document persisted per key. Each slot family holds a fixed number+/// of buckets whose count is statically fixed by the [`SlotFamily`] associated+/// constants, so `dow`/`dom`/`hod` can never carry the wrong number of items.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct StatsDocument {+ /// `dow` = day of week: one bucket per weekday (Monday..=Sunday).+ #[serde(default)]+ pub dow: [SlotCounter; SlotFamily::DOW_SLOT_COUNT],+ /// `dom` = day of month: one bucket per calendar day (1..=31).+ #[serde(default)]+ pub dom: [SlotCounter; SlotFamily::DOM_SLOT_COUNT],+ /// `hod` = hour of day: one bucket per hour (0..=23).+ #[serde(default)]+ pub hod: [SlotCounter; SlotFamily::HOD_SLOT_COUNT],+}++impl StatsDocument {+ pub fn from_json(value: &serde_json::Value) -> Result<Self, serde_json::Error> {+ serde_json::from_value(value.clone()).map_err(|error| {+ logger::error!(+ ?error,+ "revenue_recovery_retry_stats: failed to deserialize stats document"+ );+ error+ })+ }++ pub fn to_json(&self) -> serde_json::Value {+ serde_json::to_value(self).unwrap_or_else(|error| {+ logger::error!(+ ?error,+ "revenue_recovery_retry_stats: failed to serialize stats document"+ );+ serde_json::json!({})+ })+ }+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct EventSlots {+ /// `dow` = day of week: bucket index 0..=6 (Monday..=Sunday).+ pub dow: u8,+ /// `dom` = day of month: bucket index 0..=30 (calendar day 1..=31 minus 1).+ pub dom: u8,+ /// `hod` = hour of day: bucket index 0..=23.+ pub hod: u8,+}++impl EventSlots {+ /// Derive the day-of-week / day-of-month / hour-of-day bucket indices from an+ /// event's `created_at`.+ ///+ /// Hyperswitch persists `created_at` as a **UTC** `PrimitiveDateTime`, but that+ /// type carries no offset, so we make the timezone explicit via `assume_utc()`.+ pub fn from_utc(ts: PrimitiveDateTime) -> Self {+ let utc = ts.assume_utc();+ Self {+ dow: validate_slot(SlotFamily::Dow, utc.weekday().number_days_from_monday(), ts),+ dom: validate_slot(SlotFamily::Dom, utc.day().saturating_sub(1), ts),+ hod: validate_slot(SlotFamily::Hod, utc.hour(), ts),+ }+ }+}++/// Guard a derived slot index against its family's static bucket count. Returns the+/// index unchanged, but logs an error for any out-of-range value so the anomaly is+/// visible+fn validate_slot(family: SlotFamily, slot: u8, ts: PrimitiveDateTime) -> u8 {+ if usize::from(slot) >= family.slot_count() {+ logger::error!(+ slot_family = family.name(),+ slot,+ bucket_count = family.slot_count(),+ timestamp = %ts,+ "revenue_recovery_retry_stats: derived slot index is out of range for its family; \+ dropping this family's update (possible timezone/timestamp anomaly)"+ );+ }+ slot+}++#[derive(Clone, Copy, Debug)]+pub struct SlotUpdate {+ pub slot: u8,+ pub success: bool,+}++#[derive(Clone, Debug)]+pub struct StatsDelta {+ pub updates: Vec<(SlotFamily, SlotUpdate)>,+}++impl StatsDelta {+ pub fn for_event(slots: EventSlots, success: bool) -> Self {+ Self {+ updates: vec![+ (+ SlotFamily::Dow,+ SlotUpdate {+ slot: slots.dow,+ success,+ },+ ),+ (+ SlotFamily::Dom,+ SlotUpdate {+ slot: slots.dom,+ success,+ },+ ),+ (+ SlotFamily::Hod,+ SlotUpdate {+ slot: slots.hod,+ success,+ },+ ),+ ],+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum SlotFamily {+ Dow,+ Dom,+ Hod,+}++impl SlotFamily {+ /// Day-of-week buckets (Monday..=Sunday).+ pub const DOW_SLOT_COUNT: usize = 7;+ /// Day-of-month buckets (day 1..=31 mapped to index 0..=30).+ pub const DOM_SLOT_COUNT: usize = 31;+ /// Hour-of-day buckets (0..=23).+ pub const HOD_SLOT_COUNT: usize = 24;++ /// The statically-known number of buckets for this family.+ pub const fn slot_count(self) -> usize {+ match self {+ Self::Dow => Self::DOW_SLOT_COUNT,+ Self::Dom => Self::DOM_SLOT_COUNT,+ Self::Hod => Self::HOD_SLOT_COUNT,+ }+ }++ pub fn name(&self) -> &'static str {+ match self {+ Self::Dow => "dow",+ Self::Dom => "dom",+ Self::Hod => "hod",+ }+ }+}++impl StatsDocument {+ /// Fold a [`StatsDelta`] into this document, returning the updated document. Takes+ /// `self` by value so calls chain fluently (`doc.merge(&d1).merge(&d2)`); start+ /// from `StatsDocument::default()` when there is no existing document.+ pub fn merge(mut self, delta: &StatsDelta) -> Self {+ for (family, update) in &delta.updates {+ let slots: &mut [SlotCounter] = match family {+ SlotFamily::Dow => &mut self.dow,+ SlotFamily::Dom => &mut self.dom,+ SlotFamily::Hod => &mut self.hod,+ };+ // Out-of-range slots are dropped rather than panicking; valid time-derived+ // slots always fall within the statically-sized bucket range.+ if let Some(counter) = slots.get_mut(usize::from(update.slot)) {+ counter.record(update.success);+ }+ }+ self+ }+}++#[cfg(test)]+#[allow(clippy::indexing_slicing)]+mod tests {+ use super::*;++ fn delta(slots: &[(SlotFamily, u8, bool)]) -> StatsDelta {+ StatsDelta {+ updates: slots+ .iter()+ .map(|(f, s, ok)| {+ (+ *f,+ SlotUpdate {+ slot: *s,+ success: *ok,+ },+ )+ })+ .collect(),+ }+ }++ fn is_empty(slots: &[SlotCounter]) -> bool {+ slots.iter().all(|c| *c == SlotCounter::default())+ }++ #[test]+ fn from_utc_produces_in_range_slots() {+ let date = time::Date::from_calendar_date(2026, time::Month::August, 19)+ .expect("valid calendar date");+ let clock = time::Time::from_hms(13, 30, 0).expect("valid time");+ let slots = EventSlots::from_utc(PrimitiveDateTime::new(date, clock));++ assert!(usize::from(slots.dow) < SlotFamily::DOW_SLOT_COUNT);+ assert!(usize::from(slots.dom) < SlotFamily::DOM_SLOT_COUNT);+ assert!(usize::from(slots.hod) < SlotFamily::HOD_SLOT_COUNT);+ // 2026-08-19 is a Wednesday (index 2); day 19 -> index 18; hour 13.+ assert_eq!(slots.dow, 2);+ assert_eq!(slots.dom, 18);+ assert_eq!(slots.hod, 13);+ }++ #[test]+ fn slot_arrays_have_statically_fixed_lengths() {+ let doc = StatsDocument::default();+ assert_eq!(doc.dow.len(), SlotFamily::DOW_SLOT_COUNT);+ assert_eq!(doc.dom.len(), SlotFamily::DOM_SLOT_COUNT);+ assert_eq!(doc.hod.len(), SlotFamily::HOD_SLOT_COUNT);+ }++ #[test]+ fn merge_into_empty_creates_entries() {+ let doc = StatsDocument::default().merge(&delta(&[(SlotFamily::Dow, 3, true)]));+ assert_eq!(doc.dow[3], SlotCounter { n: 1, k: 1 });+ assert!(is_empty(&doc.dom));+ assert!(is_empty(&doc.hod));+ }++ #[test]+ fn merge_accumulates_across_calls() {+ let d1 = delta(&[(SlotFamily::Hod, 9, true)]);+ let d2 = delta(&[(SlotFamily::Hod, 9, false)]);+ let d3 = delta(&[(SlotFamily::Hod, 10, true)]);+ let doc = StatsDocument::default().merge(&d1).merge(&d2).merge(&d3);+ assert_eq!(doc.hod[9], SlotCounter { n: 2, k: 1 });+ assert_eq!(doc.hod[10], SlotCounter { n: 1, k: 1 });+ }++ #[test]+ fn merge_is_associative_over_deltas() {+ let d1 = delta(&[(SlotFamily::Dom, 9, true)]);+ let d2 = delta(&[(SlotFamily::Dom, 9, false)]);+ let d3 = delta(&[(SlotFamily::Dom, 9, true)]);+ let left = StatsDocument::default().merge(&d1).merge(&d2).merge(&d3);+ let mut combined = StatsDelta { updates: vec![] };+ combined.updates.extend(d2.updates.clone());+ combined.updates.extend(d3.updates.clone());+ let right = StatsDocument::default().merge(&d1).merge(&combined);+ assert_eq!(left.dom[9], right.dom[9]);+ }++ #[test]+ fn out_of_range_slot_is_ignored() {+ // day-of-month index 31 is out of range (valid 0..=30) and must not panic.+ let doc = StatsDocument::default().merge(&delta(&[(SlotFamily::Dom, 31, true)]));+ assert!(is_empty(&doc.dom));+ }++ #[test]+ fn marginal_consistency_holds() {+ let d = delta(&[+ (SlotFamily::Dow, 1, true),+ (SlotFamily::Dom, 5, true),+ (SlotFamily::Hod, 9, true),+ ]);+ let doc = StatsDocument::default().merge(&d);+ let sum = |m: &[SlotCounter]| m.iter().map(|c| c.n).sum::<u64>();+ assert_eq!(sum(&doc.dow), sum(&doc.dom));+ assert_eq!(sum(&doc.dom), sum(&doc.hod));+ }+}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 4da60ed3e3..c79f6088da 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -430,6 +430,8 @@ 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";+ /// Revenue Recovery retry-stats key. Enables recording of retry outcome stats+ pub const REVREC_RETRY_STATS_ENABLED: &str = "revenue_recovery.retry_stats.enabled";/// Whether the adaptive revenue recovery retry algorithm — static ladder combined with/// the smart algorithm — replaces the decider-based smart retry implementationpub const ADAPTIVE_RETRY_ENABLED: &str = "revenue_recovery.adaptive_retry_enabled";diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 52434f7a75..488de56879 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -875,6 +875,18 @@ impl DatabaseBackedConfig for OfferEngineEnabled {const KEY: &'static str = "offer_engine_enabled";}+config! {+ superposition_key = REVREC_RETRY_STATS_ENABLED,+ output = bool,+ default = true,+ requires = dimension_state::DimensionsGlobal,+ targeting_key = id_type::MerchantId+}++impl DatabaseBackedConfig for RevrecRetryStatsEnabled {+ const KEY: &'static str = "revrec_retry_stats_enabled";+}+config! {superposition_key = OFFER_ENGINE_CREDENTIAL_SOURCE,output = crate::core::offer_engine::types::OfferEngineCredentialSource,diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex 6908bc1f43..30dac9e5c4 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 retry_stats;pub mod schedule;pub mod transformers;pub mod types;@@ -72,6 +73,7 @@ pub async fn upsert_calculate_pcr_task(business_profile: &domain::Profile,intent_retry_count: u16,payment_attempt_id: Option<id_type::GlobalAttemptId>,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {@@ -125,6 +127,7 @@ pub async fn upsert_calculate_pcr_task(global_payment_id: payment_id.clone(),merchant_id: platform.get_processor().get_account().get_id().to_owned(),profile_id: business_profile.get_id().to_owned(),+ prev_attempt_error_code,payment_attempt_id,revenue_recovery_retry,invoice_scheduled_time: None,@@ -190,6 +193,9 @@ pub async fn record_internal_attempt_and_execute_payment() -> Result<(), sch_errors::ProcessTrackerError> {let db = &*state.store;+ // Standardised error code for the attempt whose failure triggered this execute task,+ let prev_attempt_error_code = tracking_data.prev_attempt_error_code;+let card_info = api_models::payments::AdditionalCardInfo::foreign_from(payment_processor_token);// record attempt call@@ -226,6 +232,7 @@ pub async fn record_internal_attempt_and_execute_payment(execute_task_process,revenue_recovery_payment_data,revenue_recovery_metadata,+ prev_attempt_error_code,)).await?;}@@ -319,6 +326,9 @@ pub async fn perform_execute_payment(payment_intent,revenue_recovery_payment_data,&tracking_data.payment_attempt_id,+ // No new attempt was made (no token), so the chain's failed attempt+ // is unchanged — carry its already-resolved code forward.+ tracking_data.prev_attempt_error_code,)).await?;// Unlock the customer status only if all tokens are hard declined and payment intent is in Failed status@@ -385,6 +395,7 @@ pub async fn perform_execute_payment(payment_intent.get_id().clone(),revenue_recovery_payment_data.profile.get_id().clone(),attempt_id.clone(),+ tracking_data.prev_attempt_error_code,storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,tracking_data.revenue_recovery_retry,state.conf.application_source,@@ -457,6 +468,7 @@ async fn insert_psync_pcr_task_to_pt(payment_id: GlobalPaymentId,profile_id: id_type::ProfileId,payment_attempt_id: id_type::GlobalAttemptId,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,application_source: common_enums::ApplicationSource,@@ -470,6 +482,7 @@ async fn insert_psync_pcr_task_to_pt(merchant_id,profile_id,payment_attempt_id,+ prev_attempt_error_code,revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),// PSYNC has its own row; scheduling state lives on CALCULATE.@@ -512,6 +525,9 @@ pub async fn perform_payments_sync(revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,payment_intent: &PaymentIntent,) -> Result<(), errors::ProcessTrackerError> {+ // Standardised error code for the failed attempt that motivated this retry chain,+ let prev_attempt_error_code = tracking_data.prev_attempt_error_code;+let psync_data = api::call_psync_api(state,&tracking_data.global_payment_id,@@ -546,6 +562,7 @@ pub async fn perform_payments_sync(new_revenue_recovery_payment_data,payment_attempt,&mut revenue_recovery_metadata,+ prev_attempt_error_code,),).await?;@@ -669,6 +686,7 @@ pub async fn perform_calculate_workflow(payment_intent,&tracking_data.profile_id,&tracking_data.payment_attempt_id,+ tracking_data.prev_attempt_error_code,storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,retry_algorithm_type,scheduled_time,@@ -922,6 +940,7 @@ async fn insert_execute_pcr_task_to_pt(payment_intent: &PaymentIntent,profile_id: &id_type::ProfileId,payment_attempt_id: &id_type::GlobalAttemptId,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,runner: storage::ProcessTrackerRunner,revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,schedule_time: time::PrimitiveDateTime,@@ -1031,6 +1050,7 @@ async fn insert_execute_pcr_task_to_pt(merchant_id: merchant_id.clone(),profile_id: profile_id.clone(),payment_attempt_id: payment_attempt_id.clone(),+ prev_attempt_error_code,revenue_recovery_retry,invoice_scheduled_time: Some(schedule_time),// EXECUTE has its own row; scheduling state lives on CALCULATE.@@ -1310,6 +1330,7 @@ pub async fn resume_revenue_recovery_process_tracker(tracking_data.global_payment_id.clone(),tracking_data.profile_id.clone(),active_attempt_id.clone(),+ tracking_data.prev_attempt_error_code,runner,tracking_data.revenue_recovery_retry,state.conf.application_source,diff --git a/crates/router/src/core/revenue_recovery/retry_stats.rs b/crates/router/src/core/revenue_recovery/retry_stats.rsnew file mode 100644index 0000000000..e7e7e8e474--- /dev/null+++ b/crates/router/src/core/revenue_recovery/retry_stats.rs@@ -0,0 +1,4 @@+pub mod events;+pub mod record;++pub use events::RetryOutcomeEvent;diff --git a/crates/router/src/core/revenue_recovery/retry_stats/events.rs b/crates/router/src/core/revenue_recovery/retry_stats/events.rsnew file mode 100644index 0000000000..94108a3b32--- /dev/null+++ b/crates/router/src/core/revenue_recovery/retry_stats/events.rs@@ -0,0 +1,140 @@+use common_enums::{CardNetwork, CardType, StandardisedCode};+use hyperswitch_domain_models::{+ payments::payment_attempt::PaymentAttempt,+ revenue_recovery::{+ retry_stats_cluster_key::{Dim, RetryStatsClusterKey},+ retry_stats_document::{EventSlots, StatsDelta},+ },+};+use router_env::logger;+use time::PrimitiveDateTime;++use crate::{consts, core::payments::helpers, routes::SessionState};++pub struct RetryOutcomeEvent {+ pub key: RetryStatsClusterKey,+ pub delta: StatsDelta,+ pub success: bool,+}++impl RetryOutcomeEvent {+ /// Method-agnostic core: build an event from already-resolved dimensions.+ fn build(+ error_code_dim: Dim<StandardisedCode>,+ card_type_dim: Dim<CardType>,+ issuer_dim: Dim<String>,+ success: bool,+ created_at: PrimitiveDateTime,+ ) -> Self {+ let slots = EventSlots::from_utc(created_at);+ let delta = StatsDelta::for_event(slots, success);++ Self {+ key: RetryStatsClusterKey::leaf(error_code_dim, card_type_dim, issuer_dim),+ delta,+ success,+ }+ }++ /// Build an event from the retry's freshly resolved attempt and the previous+ /// attempt's standardised error code, resolved once at ingestion time (see+ /// [`resolve_standardised_error_code`]) and carried on the workflow tracking data, so+ /// the recorder never re-reads the previous attempt from the payments store. A `None`+ /// code maps to the `Unknown` error-code dimension.+ pub fn from_attempt(+ payment_attempt: &PaymentAttempt,+ standardised_error_code: Option<StandardisedCode>,+ success: bool,+ ) -> Self {+ let error_code_dim = match standardised_error_code {+ Some(code) => Dim::Val(code),+ None => Dim::Unknown,+ };+ Self::build(+ error_code_dim,+ Dim::Unknown,+ Dim::Unknown,+ success,+ payment_attempt.created_at,+ )+ }+}++/// Resolve the standardised error code from an attempt+pub async fn resolve_standardised_error_code_from_attempt(+ state: &SessionState,+ payment_attempt: &PaymentAttempt,+ card_network: Option<CardNetwork>,+) -> Option<StandardisedCode> {+ resolve_standardised_error_code(+ state,+ payment_attempt.connector.clone(),+ payment_attempt+ .error+ .as_ref()+ .map(|error| error.code.clone()),+ payment_attempt+ .error+ .as_ref()+ .map(|error| error.message.clone()),+ payment_attempt+ .error+ .as_ref()+ .and_then(|error| error.network_decline_code.clone()),+ card_network,+ )+ .await+}++/// Resolve the standardised error code from an attempt's connector + error fields.+///+/// The code is resolved from the GSM table using the connector + error code, keyed on+/// the Payment/Authorize flow. Returns `None` when no GSM record matches or the+/// connector/error code is absent; the recorder maps that to the `Unknown` dimension.+///+/// Called at ingestion time (the revenue-recovery webhook) where these fields are in+/// hand, so the async retry-stats path never has to read the attempt back from the+/// payments store.+pub async fn resolve_standardised_error_code(+ state: &SessionState,+ connector: Option<String>,+ error_code: Option<String>,+ error_message: Option<String>,+ network_decline_code: Option<String>,+ card_network: Option<CardNetwork>,+) -> Option<StandardisedCode> {+ match (error_code, connector) {+ (Some(error_code), Some(connector)) => {+ let gsm_record = helpers::get_gsm_record(+ state,+ connector,+ consts::PAYMENT_FLOW_STR,+ consts::AUTHORIZE_FLOW_STR,+ Some(error_code.clone()),+ error_message,+ network_decline_code,+ card_network,+ )+ .await;++ let standardised_code = gsm_record.and_then(|record| record.standardised_code);+ if standardised_code.is_none() {+ logger::warn!(+ connector_error_code = error_code,+ "revenue_recovery_retry_stats: no standardised code resolved from GSM for \+ the attempt's error; recording error_code dimension as Unknown"+ );+ }+ standardised_code+ }+ (error_code, connector) => {+ logger::warn!(+ has_error_code = error_code.is_some(),+ has_connector = connector.is_some(),+ "revenue_recovery_retry_stats: attempt is missing error code and/or connector; \+ recording error_code dimension as Unknown"+ );+ None+ }+ }+}diff --git a/crates/router/src/core/revenue_recovery/retry_stats/record.rs b/crates/router/src/core/revenue_recovery/retry_stats/record.rsnew file mode 100644index 0000000000..8efa5aab12--- /dev/null+++ b/crates/router/src/core/revenue_recovery/retry_stats/record.rs@@ -0,0 +1,200 @@+use common_utils::errors::CustomResult;+use error_stack::ResultExt;+use hyperswitch_domain_models::revenue_recovery::retry_stats::RevenueRecoveryRetryStats as DomainRevenueRecoveryRetryStats;+use redis_interface::SetnxReply;+use router_env::{instrument, logger, tracing};+use storage_impl::{+ errors::StorageError, revenue_recovery_retry_stats::RevenueRecoveryRetryStatsInterface,+};++use super::events::RetryOutcomeEvent;+use crate::{+ core::configs::dimension_state,+ routes::{app::SessionStateInfo, SessionState},+};++impl RetryOutcomeEvent {+ /// Redis key of the per-cluster-key lock guarding this event's read-merge-write.+ fn get_redis_locking_key(&self) -> String {+ format!(+ "revenue_recovery_retry_stats_lock:{}",+ self.key.as_db_string()+ )+ }++ /// Record this outcome into `revenue_recovery_retry_stats` under a per-key+ /// Redis lock so concurrent writers don't lose updates in the read-merge-write.+ /// Recording is best-effort: any failure is logged and swallowed so it never+ /// affects the payment/recovery flow that invoked it.+ #[instrument(skip_all)]+ pub async fn record(&self, state: &SessionState) {+ let dimensions: dimension_state::DimensionsGlobal = dimension_state::Dimensions::new();+ let enabled = dimensions+ .get_revrec_retry_stats_enabled(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ None,+ )+ .await;++ if !enabled {+ logger::info!("revenue_recovery_retry_stats: recording disabled via config");+ return;+ }++ let redis_conn = match state.store.get_redis_conn() {+ Ok(conn) => conn,+ Err(error) => {+ logger::error!(+ ?error,+ "revenue_recovery_retry_stats: unable to acquire redis connection"+ );+ return;+ }+ };+ let store = state.store.get_revenue_recovery_retry_stats_store();++ let db_key = self.key.as_db_string();++ let retry_stats_lock = state.conf().revenue_recovery.retry_stats_lock;+ let lock_retries = retry_stats_lock.lock_retries();+ let delay_between_retries_in_milliseconds =+ retry_stats_lock.delay_between_retries_in_milliseconds;+ let redis_lock_expiry_seconds = retry_stats_lock.redis_lock_expiry_seconds;++ match persist_node(+ store.as_ref(),+ &redis_conn,+ self,+ lock_retries,+ delay_between_retries_in_milliseconds,+ redis_lock_expiry_seconds,+ )+ .await+ {+ Ok(()) => logger::info!(+ cluster_key = %db_key,+ success = self.success,+ "revenue_recovery_retry_stats outcome recorded"+ ),+ Err(error) => logger::error!(+ cluster_key = %db_key,+ ?error,+ "revenue_recovery_retry_stats: failed to persist retry outcome"+ ),+ }+ }+}++/// Serialize the read-merge-write for a cluster key under a per-key Redis lock (SETNX+/// with expiry) so concurrent recorders don't lose updates+async fn persist_node(+ store: &dyn RevenueRecoveryRetryStatsInterface<Error = StorageError>,+ redis_conn: &redis_interface::RedisConnectionWithContext,+ event: &RetryOutcomeEvent,+ lock_retries: u32,+ delay_between_retries_in_milliseconds: u32,+ redis_lock_expiry_seconds: u32,+) -> CustomResult<(), StorageError> {+ let db_key = event.key.as_db_string();+ let lock_key = event.get_redis_locking_key();+ let lock_token = uuid::Uuid::new_v4().to_string();++ let wait_duration =+ std::time::Duration::from_millis(u64::from(delay_between_retries_in_milliseconds));+ let mut acquired = false;+ for _retry in 0..lock_retries {+ match redis_conn+ .set_key_if_not_exists_with_expiry(+ &lock_key.as_str().into(),+ lock_token.clone(),+ Some(i64::from(redis_lock_expiry_seconds)),+ )+ .await+ {+ Ok(SetnxReply::KeySet) => {+ acquired = true;+ break;+ }+ Ok(SetnxReply::KeyNotSet) => {+ actix_web::rt::time::sleep(wait_duration).await;+ }+ Err(error) => {+ Err(error).change_context(StorageError::KVError)?;+ }+ }+ }++ if acquired {+ let result = merge_and_write(store, event).await;+ release_lock(redis_conn, &lock_key, &lock_token).await;+ result+ } else {+ // Lock was still contended after the retry budget; dropping this update is+ // acceptable for best-effort stats.+ logger::warn!(+ cluster_key = %db_key,+ "revenue_recovery_retry_stats: lock contended after retries, skipping this update"+ );+ Ok(())+ }+}++async fn merge_and_write(+ store: &dyn RevenueRecoveryRetryStatsInterface<Error = StorageError>,+ event: &RetryOutcomeEvent,+) -> CustomResult<(), StorageError> {+ // Resolve the current document and whether a row already exists. A row whose+ // stored document is corrupt (`DeserializationFailed`) is treated as+ // present-but-empty and rebuilt, rather than dropping the event.+ let (current_doc, row_exists) = match store+ .find_revenue_recovery_retry_stats_by_cluster_key(&event.key)+ .await+ {+ Ok(Some(row)) => (Some(row.stats), true),+ Ok(None) => (None, false),+ Err(error) if matches!(error.current_context(), StorageError::DeserializationFailed) => {+ logger::error!(+ cluster_key = %event.key.as_db_string(),+ ?error,+ "revenue_recovery_retry_stats: stored document is corrupt, rebuilding from empty"+ );+ // The row exists but is unreadable, so overwrite it rather than insert.+ (None, true)+ }+ Err(error) => return Err(error),+ };++ let record = DomainRevenueRecoveryRetryStats {+ cluster_key: event.key.clone(),+ stats: current_doc.unwrap_or_default().merge(&event.delta),+ };++ // The per-key redis lock plus the read above tell us whether the row exists, so we+ // insert on first sight and update thereafter — no DB-level upsert/conflict handling.+ if row_exists {+ store.update_revenue_recovery_retry_stats(record).await?;+ } else {+ store.insert_revenue_recovery_retry_stats(record).await?;+ }++ Ok(())+}++/// Release the lock only if we still own it, so we never delete a lock that has+/// already expired and been re-acquired by another writer.+async fn release_lock(+ redis_conn: &redis_interface::RedisConnectionWithContext,+ lock_key: &str,+ lock_token: &str,+) {+ let owned = matches!(+ redis_conn.get_key::<Option<String>>(&lock_key.into()).await,+ Ok(Some(stored)) if stored == lock_token+ );+ if owned {+ if let Err(error) = redis_conn.delete_key(&lock_key.into()).await {+ logger::warn!(lock_key = %lock_key, ?error, "revenue_recovery_retry_stats: failed to release lock");+ }+ }+}diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 62ff1ce83a..fec5d46115 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -32,7 +32,7 @@ use hyperswitch_domain_models::{};use time::PrimitiveDateTime;-use super::errors::StorageErrorExt;+use super::{errors::StorageErrorExt, retry_stats};use crate::{consts,core::{@@ -116,6 +116,7 @@ impl RevenueRecoveryPaymentIntentStatus {revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,payment_attempt: PaymentAttempt,revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,) -> Result<(), errors::ProcessTrackerError> {let connector_customer_id = payment_intent.extract_connector_customer_id_from_payment_intent()@@ -160,6 +161,15 @@ impl RevenueRecoveryPaymentIntentStatus {).await?;+ // Record the psync-resolved retry outcome into revenue_recovery_retry_stats.+ retry_stats::RetryOutcomeEvent::from_attempt(+ &payment_attempt,+ prev_attempt_error_code,+ true,+ )+ .record(state)+ .await;+// publish events to kafkaif let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(state,@@ -272,6 +282,7 @@ impl RevenueRecoveryPaymentIntentStatus {payment_intent,revenue_recovery_payment_data,psync_response.payment_attempt.get_id(),+ None, // TODO: Retry stats not recorded for partially charged payments)).await?;@@ -298,6 +309,15 @@ impl RevenueRecoveryPaymentIntentStatus {business_status::PSYNC_WORKFLOW_COMPLETE,).await?;++ retry_stats::RetryOutcomeEvent::from_attempt(+ &payment_attempt,+ prev_attempt_error_code,+ false,+ )+ .record(state)+ .await;+// publish events to kafkaif let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(state,@@ -334,7 +354,13 @@ impl RevenueRecoveryPaymentIntentStatus {).await;- // Reopen calculate workflow on payment failure+ let reopened_standardised_error_code =+ retry_stats::events::resolve_standardised_error_code_from_attempt(+ state,+ &psync_response.payment_attempt,+ revenue_recovery_metadata.get_card_network(),+ )+ .await;Box::pin(reopen_calculate_workflow_on_payment_failure(state,&process_tracker,@@ -343,6 +369,7 @@ impl RevenueRecoveryPaymentIntentStatus {payment_intent,revenue_recovery_payment_data,psync_response.payment_attempt.get_id(),+ reopened_standardised_error_code,)).await?;}@@ -366,6 +393,7 @@ impl RevenueRecoveryPaymentIntentStatus {&process_tracker,revenue_recovery_metadata,revenue_recovery_payment_data,+ prev_attempt_error_code,)).await?;}@@ -734,6 +762,13 @@ impl Action {.await;// Reopen calculate workflow on payment failure+ let reopened_standardised_error_code =+ retry_stats::events::resolve_standardised_error_code_from_attempt(+ state,+ &payment_data.payment_attempt,+ revenue_recovery_metadata.get_card_network(),+ )+ .await;Box::pin(reopen_calculate_workflow_on_payment_failure(state,process,@@ -742,6 +777,7 @@ impl Action {payment_intent,revenue_recovery_payment_data,latest_attempt_id,+ reopened_standardised_error_code,)).await?;@@ -774,12 +810,15 @@ impl Action {execute_task_process: &storage::ProcessTracker,revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,) -> Result<(), errors::ProcessTrackerError> {logger::info!("Entering execute_payment_task_response_handler");let db = &*state.store;match self {Self::SyncPayment(payment_attempt) => {+ // 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(revenue_recovery_payment_data.billing_mca.get_id().clone(),db,@@ -790,6 +829,7 @@ impl Action {payment_intent.id.clone(),revenue_recovery_payment_data.profile.get_id().to_owned(),payment_attempt.id.clone(),+ prev_attempt_error_code,storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,revenue_recovery_payment_data.retry_algorithm,state.conf.application_source,@@ -846,6 +886,14 @@ impl Action {Ok(())}Self::TerminalFailure(payment_attempt) => {+ retry_stats::RetryOutcomeEvent::from_attempt(+ payment_attempt,+ prev_attempt_error_code,+ false,+ )+ .record(state)+ .await;+db.as_scheduler().finish_process_with_business_status(execute_task_process.clone(),@@ -858,6 +906,14 @@ impl Action {Ok(())}Self::SuccessfulPayment(payment_attempt) => {+ retry_stats::RetryOutcomeEvent::from_attempt(+ payment_attempt,+ prev_attempt_error_code,+ true,+ )+ .record(state)+ .await;+db.as_scheduler().finish_process_with_business_status(execute_task_process.clone(),@@ -916,6 +972,7 @@ impl Action {}}+ #[allow(clippy::too_many_arguments)]pub async fn payment_sync_call(state: &SessionState,revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,@@ -1015,6 +1072,21 @@ impl Action {.await;// Reopen calculate workflow on payment failure+ let card_network = payment_intent+ .feature_metadata+ .as_ref()+ .and_then(|feature_metadata| {+ feature_metadata.payment_revenue_recovery_metadata.clone()+ })+ .and_then(|metadata| metadata.convert_back().get_card_network());++ let reopened_standardised_error_code =+ retry_stats::events::resolve_standardised_error_code_from_attempt(+ state,+ &payment_attempt,+ card_network,+ )+ .await;Box::pin(reopen_calculate_workflow_on_payment_failure(state,process,@@ -1023,6 +1095,7 @@ impl Action {payment_intent,revenue_recovery_payment_data,payment_attempt.get_id(),+ reopened_standardised_error_code,)).await?;@@ -1052,6 +1125,7 @@ impl Action {psync_task_process: &storage::ProcessTracker,revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,) -> Result<(), errors::ProcessTrackerError> {logger::info!("Entering psync_response_handler");@@ -1121,6 +1195,13 @@ impl Action {Self::TerminalFailure(payment_attempt) => {// TODO: Add support for retrying failed outgoing recordback webhooks// finish the current psync task+ retry_stats::RetryOutcomeEvent::from_attempt(+ payment_attempt,+ prev_attempt_error_code,+ false,+ )+ .record(state)+ .await;db.as_scheduler().finish_process_with_business_status(psync_task_process.clone(),@@ -1133,6 +1214,13 @@ impl Action {}Self::SuccessfulPayment(payment_attempt) => {// finish the current psync task+ retry_stats::RetryOutcomeEvent::from_attempt(+ payment_attempt,+ prev_attempt_error_code,+ true,+ )+ .record(state)+ .await;db.as_scheduler().finish_process_with_business_status(psync_task_process.clone(),@@ -1257,6 +1345,7 @@ impl Action {}/// Reopen calculate workflow when payment fails+#[allow(clippy::too_many_arguments)]pub async fn reopen_calculate_workflow_on_payment_failure(state: &SessionState,process: &storage::ProcessTracker,@@ -1265,6 +1354,7 @@ pub async fn reopen_calculate_workflow_on_payment_failure(payment_intent: &PaymentIntent,revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,latest_attempt_id: &id_type::GlobalAttemptId,+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,) -> RecoveryResult<()> {let db = &*state.store;let id = payment_intent.id.clone();@@ -1283,6 +1373,8 @@ pub async fn reopen_calculate_workflow_on_payment_failure(let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {payment_attempt_id: latest_attempt_id.clone(),+ // Standardised error code for `latest_attempt_id`+ prev_attempt_error_code,revenue_recovery_retry: retry_algorithm_type,merchant_id: old_tracking_data.merchant_id.clone(),profile_id: old_tracking_data.profile_id.clone(),diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rsindex 84bd45ed44..19ed1c3813 100644--- a/crates/router/src/core/webhooks/recovery_incoming.rs+++ b/crates/router/src/core/webhooks/recovery_incoming.rs@@ -29,6 +29,7 @@ use crate::{self, admin,errors::{self, CustomResult},payments::{self, helpers},+ revenue_recovery::retry_stats,},db::{errors::RevenueRecoveryError, StorageInterface},routes::{app::ReqState, metrics, SessionState},@@ -285,6 +286,9 @@ async fn handle_schedule_failed_payment(recovery_attempt_from_payment_attempt.as_ref().map(|attempt| attempt.attempt_id.clone()),+ recovery_attempt_from_payment_attempt+ .as_ref()+ .and_then(|attempt| attempt.standardised_error_code),storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,revenue_recovery_retry,)@@ -638,20 +642,40 @@ impl RevenueRecoveryAttempt {)})});- let payment_attempt =- final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {- attempt_id: res.id.to_owned(),- attempt_status: res.status.to_owned(),- feature_metadata: res.feature_metadata.to_owned(),- amount: res.amount.net_amount,- network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available- network_decline_code: res- .error- .clone()- .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available- error_code: res.error.clone().map(|error| error.code),- created_at: res.created_at,- });+ let payment_attempt = match final_attempt {+ Some(res) => {+ let standardised_error_code =+ retry_stats::events::resolve_standardised_error_code(+ state,+ res.connector.clone(),+ res.error.as_ref().map(|e| e.code.clone()),+ res.error.as_ref().map(|e| e.message.clone()),+ res.error+ .as_ref()+ .and_then(|e| e.network_decline_code.clone()),+ self.0.card_info.card_network.clone(),+ )+ .await;+ Some(revenue_recovery::RecoveryPaymentAttempt {+ attempt_id: res.id.to_owned(),+ attempt_status: res.status.to_owned(),+ feature_metadata: res.feature_metadata.to_owned(),+ amount: res.amount.net_amount,+ network_advice_code: res+ .error+ .clone()+ .and_then(|e| e.network_advice_code), // Placeholder, to be populated if available+ network_decline_code: res+ .error+ .clone()+ .and_then(|e| e.network_decline_code), // Placeholder, to be populated if available+ error_code: res.error.clone().map(|error| error.code),+ created_at: res.created_at,+ standardised_error_code,+ })+ }+ None => None,+ };// If we have an attempt, combine it with payment_intent in a tuple.let res_with_payment_intent_and_attempt =payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));@@ -711,6 +735,26 @@ impl RevenueRecoveryAttempt {let (recovery_attempt, updated_recovery_intent) = match attempt_response {Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {+ let standardised_error_code = retry_stats::events::resolve_standardised_error_code(+ state,+ payment_connector_name+ .as_ref()+ .map(|connector| connector.to_string()),+ attempt_response+ .error_details+ .as_ref()+ .map(|error| error.code.clone()),+ attempt_response+ .error_details+ .as_ref()+ .map(|error| error.message.clone()),+ attempt_response+ .error_details+ .as_ref()+ .and_then(|error| error.network_decline_code.clone()),+ self.0.card_info.card_network.clone(),+ )+ .await;Ok((revenue_recovery::RecoveryPaymentAttempt {attempt_id: attempt_response.id.clone(),@@ -730,6 +774,7 @@ impl RevenueRecoveryAttempt {.clone().map(|error| error.code),created_at: attempt_response.created_at,+ standardised_error_code,},revenue_recovery::RecoveryPaymentIntent {payment_id: payment_intent.payment_id.clone(),diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 3833347562..2c193aa549 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -66,6 +66,8 @@ use hyperswitch_domain_models::{use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};use redis_interface::errors::RedisError;use router_env::logger;+#[cfg(feature = "v2")]+use storage_impl::revenue_recovery_retry_stats;use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb,};@@ -156,6 +158,12 @@ pub trait StorageInterface:+ 'static{fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;+ #[cfg(feature = "v2")]+ fn get_revenue_recovery_retry_stats_store(+ &self,+ ) -> Box<+ dyn revenue_recovery_retry_stats::RevenueRecoveryRetryStatsInterface<Error = StorageError>,+ >;fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>;fn get_subscription_store(&self)-> Box<dyn subscriptions::state::SubscriptionStorageInterface>;@@ -246,6 +254,14 @@ impl StorageInterface for Store {fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {Box::new(self.clone())}+ #[cfg(feature = "v2")]+ fn get_revenue_recovery_retry_stats_store(+ &self,+ ) -> Box<+ dyn revenue_recovery_retry_stats::RevenueRecoveryRetryStatsInterface<Error = StorageError>,+ > {+ Box::new(self.clone())+ }fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {Box::new(self.clone())}@@ -281,6 +297,14 @@ impl StorageInterface for MockDb {fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {Box::new(self.clone())}+ #[cfg(feature = "v2")]+ fn get_revenue_recovery_retry_stats_store(+ &self,+ ) -> Box<+ dyn revenue_recovery_retry_stats::RevenueRecoveryRetryStatsInterface<Error = StorageError>,+ > {+ Box::new(self.clone())+ }fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {Box::new(self.clone())}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 2612d6132a..c267d2a7d3 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -47,6 +47,8 @@ use scheduler::{};use serde::Serialize;use storage_impl::redis::kv_store::RedisConnInterface;+#[cfg(feature = "v2")]+use storage_impl::revenue_recovery_retry_stats;use time::PrimitiveDateTime;use super::{@@ -3651,6 +3653,17 @@ impl StorageInterface for KafkaStore {Box::new(self.clone())}+ #[cfg(feature = "v2")]+ fn get_revenue_recovery_retry_stats_store(+ &self,+ ) -> Box<+ dyn revenue_recovery_retry_stats::RevenueRecoveryRetryStatsInterface<+ Error = errors::StorageError,+ >,+ > {+ self.diesel_store.get_revenue_recovery_retry_stats_store()+ }+fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {Box::new(self.clone())}diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex 2fed15d28c..a277f1841e 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -26,6 +26,9 @@ pub struct RevenueRecoveryWorkflowTrackingData {pub billing_mca_id: id_type::MerchantConnectorAccountId,pub revenue_recovery_retry: enums::RevenueRecoveryAlgorithmType,pub invoice_scheduled_time: Option<time::PrimitiveDateTime>,+ /// Standardised error code for the failed attempt that motivated this retry chain,+ #[serde(default)]+ pub prev_attempt_error_code: Option<enums::StandardisedCode>,/// 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.@@ -98,6 +101,36 @@ pub struct RevenueRecoverySettings {pub recovery_timestamp: RecoveryTimestamp,pub card_config: RetryLimitsConfig,pub redis_ttl_in_seconds: i64,+ #[serde(default)]+ pub retry_stats_lock: RetryStatsLockSettings,+}++/// Redis distributed-lock settings for revenue-recovery retry-stats recording+#[derive(Debug, Clone, serde::Deserialize)]+#[serde(deny_unknown_fields)]+pub struct RetryStatsLockSettings {+ /// TTL on the per-cluster-key lock+ pub redis_lock_expiry_seconds: u32,+ /// Delay between successive attempts to acquire a contended lock.+ pub delay_between_retries_in_milliseconds: u32,+}++impl Default for RetryStatsLockSettings {+ fn default() -> Self {+ Self {+ redis_lock_expiry_seconds: 10,+ delay_between_retries_in_milliseconds: 100,+ }+ }+}++impl RetryStatsLockSettings {+ pub fn lock_retries(&self) -> u32 {+ self.redis_lock_expiry_seconds+ .saturating_mul(1000)+ .checked_div(self.delay_between_retries_in_milliseconds)+ .unwrap_or(1)+ }}#[derive(Debug, serde::Deserialize, Clone)]diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex dde0acf18f..3bf13c896f 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -44,6 +44,8 @@ pub mod payouts;pub mod platform_wrapper;pub mod redis;pub mod refund;+#[cfg(feature = "v2")]+pub mod revenue_recovery_retry_stats;mod reverse_lookup;pub mod subscription;pub mod utils;diff --git a/crates/storage_impl/src/revenue_recovery_retry_stats.rs b/crates/storage_impl/src/revenue_recovery_retry_stats.rsnew file mode 100644index 0000000000..4aae222b18--- /dev/null+++ b/crates/storage_impl/src/revenue_recovery_retry_stats.rs@@ -0,0 +1,227 @@+use common_enums::StandardisedCode;+use common_utils::{+ errors::{CustomResult, ValidationError},+ types::keymanager,+};+pub use diesel_models::revenue_recovery_retry_stats::{+ RevenueRecoveryRetryStats, RevenueRecoveryRetryStatsNew,+};+use error_stack::{report, ResultExt};+use hyperswitch_domain_models::revenue_recovery::{+ retry_stats::RevenueRecoveryRetryStats as DomainRevenueRecoveryRetryStats,+ retry_stats_cluster_key::RetryStatsClusterKey, retry_stats_document::StatsDocument,+};+use hyperswitch_masking::{PeekInterface, Secret};+use router_env::{instrument, tracing};++use crate::{+ behaviour::Conversion, connection, errors::StorageError, kv_router_store::KVRouterStore,+ DatabaseStore, MockDb, RouterStore,+};++/// Parse a diesel row into the strongly-typed domain model.+fn domain_from_diesel_row(+ item: RevenueRecoveryRetryStats,+) -> CustomResult<DomainRevenueRecoveryRetryStats, ValidationError> {+ // The cluster key is layout-versioned and self-validating: a row written under an+ // unsupported layout (or a corrupt key) is rejected here rather than silently+ // resolving to the wrong cluster.+ let cluster_key = RetryStatsClusterKey::from_db_string(&item.cluster_key).ok_or_else(|| {+ report!(ValidationError::InvalidValue {+ message: format!(+ "revenue_recovery_retry_stats: unparseable cluster_key '{}'",+ item.cluster_key+ ),+ })+ })?;+ let stats = StatsDocument::from_json(item.stats.peek()).map_err(|error| {+ report!(ValidationError::InvalidValue {+ message: format!("revenue_recovery_retry_stats: unparseable stats document: {error}"),+ })+ })?;+ Ok(DomainRevenueRecoveryRetryStats { cluster_key, stats })+}++#[async_trait::async_trait]+impl Conversion for DomainRevenueRecoveryRetryStats {+ type DstType = RevenueRecoveryRetryStats;+ type NewDstType = RevenueRecoveryRetryStatsNew;++ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ Ok(RevenueRecoveryRetryStats {+ cluster_key: self.cluster_key.as_db_string(),+ stats: Secret::new(self.stats.to_json()),+ })+ }++ async fn convert_back(+ _state: &keymanager::KeyManagerState,+ item: Self::DstType,+ _key: &Secret<Vec<u8>>,+ _key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError> {+ domain_from_diesel_row(item)+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ Ok(RevenueRecoveryRetryStatsNew {+ cluster_key: self.cluster_key.as_db_string(),+ stats: Secret::new(self.stats.to_json()),+ })+ }+}++/// Storage access for the revenue-recovery `revenue_recovery_retry_stats` doc-store.+#[async_trait::async_trait]+pub trait RevenueRecoveryRetryStatsInterface: Send + Sync {+ type Error;++ /// Fetch the stored stats document for a single cluster key (`None` when absent).+ /// Takes a [`RetryStatsClusterKey`] (serializing it internally) and returns the+ /// parsed domain model.+ async fn find_revenue_recovery_retry_stats_by_cluster_key(+ &self,+ cluster_key: &RetryStatsClusterKey,+ ) -> CustomResult<Option<DomainRevenueRecoveryRetryStats>, Self::Error>;++ /// Fetch the stats recorded against an error code alone. While only the error_code+ /// dimension is populated, leaves are stored under `error_code/UNK/UNK`+ /// ([`RetryStatsClusterKey::from_error_code`]); this queries that exact key.+ async fn find_revenue_recovery_retry_stats_by_error_code(+ &self,+ error_code: StandardisedCode,+ ) -> CustomResult<Option<DomainRevenueRecoveryRetryStats>, Self::Error> {+ self.find_revenue_recovery_retry_stats_by_cluster_key(+ &RetryStatsClusterKey::from_error_code(error_code),+ )+ .await+ }++ /// Insert a new stats document for a key that does not yet exist. Takes the domain+ /// model and serializes both columns internally.+ async fn insert_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, Self::Error>;++ /// Overwrite the stats document for a key that already exists. Takes the domain+ /// model and serializes both columns internally.+ async fn update_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, Self::Error>;+}++#[async_trait::async_trait]+impl<T: DatabaseStore> RevenueRecoveryRetryStatsInterface for RouterStore<T> {+ type Error = StorageError;++ #[instrument(skip_all)]+ async fn find_revenue_recovery_retry_stats_by_cluster_key(+ &self,+ cluster_key: &RetryStatsClusterKey,+ ) -> CustomResult<Option<DomainRevenueRecoveryRetryStats>, StorageError> {+ // Read from the write primary: callers do read-modify-write on the same row,+ // so a lagged replica can miss a just-committed INSERT and trigger a duplicate-key violation.+ let conn = connection::pg_connection_write(self).await?;+ RevenueRecoveryRetryStats::find_by_key(&conn, cluster_key.as_db_string())+ .await+ .map_err(|error| report!(StorageError::from(error)))?+ .map(domain_from_diesel_row)+ .transpose()+ .change_context(StorageError::DeserializationFailed)+ }++ #[instrument(skip_all)]+ async fn insert_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ let inserted = RevenueRecoveryRetryStatsNew {+ cluster_key: revenue_recovery_retry_stats.cluster_key.as_db_string(),+ stats: Secret::new(revenue_recovery_retry_stats.stats.to_json()),+ }+ .insert(&conn)+ .await+ .map_err(|error| report!(StorageError::from(error)))?;+ domain_from_diesel_row(inserted).change_context(StorageError::DeserializationFailed)+ }++ #[instrument(skip_all)]+ async fn update_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ let updated = RevenueRecoveryRetryStats::update_stats(+ &conn,+ revenue_recovery_retry_stats.cluster_key.as_db_string(),+ Secret::new(revenue_recovery_retry_stats.stats.to_json()),+ )+ .await+ .map_err(|error| report!(StorageError::from(error)))?;+ domain_from_diesel_row(updated).change_context(StorageError::DeserializationFailed)+ }+}++#[async_trait::async_trait]+impl<T: DatabaseStore> RevenueRecoveryRetryStatsInterface for KVRouterStore<T> {+ type Error = StorageError;++ #[instrument(skip_all)]+ async fn find_revenue_recovery_retry_stats_by_cluster_key(+ &self,+ cluster_key: &RetryStatsClusterKey,+ ) -> CustomResult<Option<DomainRevenueRecoveryRetryStats>, StorageError> {+ self.router_store+ .find_revenue_recovery_retry_stats_by_cluster_key(cluster_key)+ .await+ }++ #[instrument(skip_all)]+ async fn insert_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ self.router_store+ .insert_revenue_recovery_retry_stats(revenue_recovery_retry_stats)+ .await+ }++ #[instrument(skip_all)]+ async fn update_revenue_recovery_retry_stats(+ &self,+ revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ self.router_store+ .update_revenue_recovery_retry_stats(revenue_recovery_retry_stats)+ .await+ }+}++#[async_trait::async_trait]+impl RevenueRecoveryRetryStatsInterface for MockDb {+ type Error = StorageError;++ async fn find_revenue_recovery_retry_stats_by_cluster_key(+ &self,+ _cluster_key: &RetryStatsClusterKey,+ ) -> CustomResult<Option<DomainRevenueRecoveryRetryStats>, StorageError> {+ Err(StorageError::MockDbError)?+ }++ async fn insert_revenue_recovery_retry_stats(+ &self,+ _revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ Err(StorageError::MockDbError)?+ }++ async fn update_revenue_recovery_retry_stats(+ &self,+ _revenue_recovery_retry_stats: DomainRevenueRecoveryRetryStats,+ ) -> CustomResult<DomainRevenueRecoveryRetryStats, StorageError> {+ Err(StorageError::MockDbError)?+ }+}diff --git a/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/down.sql b/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/down.sqlnew file mode 100644index 0000000000..707c118020--- /dev/null+++ b/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS revenue_recovery_retry_stats;diff --git a/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/up.sql b/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/up.sqlnew file mode 100644index 0000000000..6aada13c77--- /dev/null+++ b/v2_compatible_migrations/2026-08-13-000001_create_revenue_recovery_retry_stats/up.sql@@ -0,0 +1,4 @@+CREATE TABLE IF NOT EXISTS revenue_recovery_retry_stats (+ cluster_key TEXT NOT NULL PRIMARY KEY,+ stats JSONB NOT NULL+);