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): systematic k retry selection (#14486)
balakrishnak-ctrlbad88dd0b28b
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 10e5983ced..29a6a45983 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -32088,7 +32088,9 @@"type": "string","description": "The retry implementations available within the `Smart` arm of revenue recovery.","enum": [- "adaptive_retry"+ "adaptive_retry",+ "systematic_k_max_at_softmax",+ "systematic_k_max_at_score"]},"RevenueRecoveryAlgorithmType": {diff --git a/config/config.example.toml b/config/config.example.tomlindex 41f3a63759..b63f4ba921 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1566,7 +1566,9 @@ billing_connectors_which_requires_dispute_record_back_call = "chargebee" # Listmonitoring_threshold_in_seconds = 60 # 60 secs , threshold for monitoring the retry systemretry_algorithm_type = "cascading" # type of retry algorithmredis_ttl_in_seconds=3888000 # ttl for redis for storing payment processor token details-default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the mathmodel retries at when a cluster has no hour-of-day history+default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the retry model schedules at when a cluster has no hour-of-day history+exploration_floor = 0.10 # minimum probability the systematic-k sampler gives every candidate day+tie_tolerance = 1e-4 # day values within this distance count as tied and split their share equally# Card specific configuration for Revenue Recovery[revenue_recovery.card_config.amex]diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex 6e099088e3..05f6cd7b7c 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -488,7 +488,9 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated listmonitoring_threshold_in_seconds = 10368000retry_algorithm_type = "cascading"redis_ttl_in_seconds=3888000-default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the mathmodel retries at when a cluster has no hour-of-day history+default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the retry model schedules at when a cluster has no hour-of-day history+exploration_floor = 0.10 # minimum probability the systematic-k sampler gives every candidate day+tie_tolerance = 1e-4 # day values within this distance count as tied and split their share equally# Card specific configuration for Revenue Recovery[revenue_recovery.card_config.amex]diff --git a/config/development.toml b/config/development.tomlindex 12dcdaec0b..51eb80d8ea 100644--- a/config/development.toml+++ b/config/development.toml@@ -1688,7 +1688,9 @@ ucs_psync_disabled_connectors = "cashtocode, trustly" # Comma-separated listmonitoring_threshold_in_seconds = 60retry_algorithm_type = "cascading"redis_ttl_in_seconds=3888000-default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the mathmodel retries at when a cluster has no hour-of-day history+default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the retry model schedules at when a cluster has no hour-of-day history+exploration_floor = 0.10 # minimum probability the systematic-k sampler gives every candidate day+tie_tolerance = 1e-4 # day values within this distance count as tied and split their share equally[revenue_recovery.recovery_timestamp]initial_timestamp_in_seconds = 3600diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 56e340f3b7..176a5a5e35 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -1545,7 +1545,9 @@ connector_list = "juspaythreedsserver, ctp_mastercard, ctp_visa"monitoring_threshold_in_seconds = 60 # threshold for monitoring the retry systemretry_algorithm_type = "cascading" # type of retry algorithmredis_ttl_in_seconds=3888000 # ttl for redis for storing payment processor token details-default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the mathmodel retries at when a cluster has no hour-of-day history+default_retry_hour_utc = 12 # fallback hour-of-day (UTC, 0-23) the retry model schedules at when a cluster has no hour-of-day history+exploration_floor = 0.10 # minimum probability the systematic-k sampler gives every candidate day+tie_tolerance = 1e-4 # day values within this distance count as tied and split their share equally# Card specific configuration for Revenue Recovery[revenue_recovery.card_config.amex]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 65a5cda33b..872c3973b9 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -391,8 +391,16 @@ pub enum RevenueRecoveryAlgorithmType {#[serde(rename_all = "snake_case")]#[strum(serialize_all = "snake_case")]pub enum RevenueRecoveryABAlgorithm {- /// Adaptive Retry algorithm.+ /// Adaptive Retry algorithm. The pairing production ran before systematic sampling existed:+ /// the weekday and month-day signals are softmaxed before the max, and the day is drawn by the+ /// per-day walk. Kept as the control arm, and kept stable because invoices already carry it.AdaptiveRetry,+ /// Control's combine, drawn instead by systematic sampling. Differs from `AdaptiveRetry` in the+ /// sampler alone, so a difference between the two is attributable to the draw.+ SystematicKMaxAtSoftmax,+ /// Systematic sampling over the max of the raw scores. Differs from `SystematicKMaxAtSoftmax`+ /// in the combine alone, so a difference between those two is attributable to the combine.+ SystematicKMaxAtScore,}#[derive(diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex 58c280ad85..442c4d372f 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -748,7 +748,7 @@ impl DatabaseBackedConfig for RevenueRecoveryAbEnabled {config! {superposition_key = REVENUE_RECOVERY_AB_ALGORITHM,output = common_enums::RevenueRecoveryABAlgorithm,- default = common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry,+ default = common_enums::RevenueRecoveryABAlgorithm::SystematicKMaxAtScore,string_enum = true,requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,targeting_key = id_type::GlobalPaymentIddiff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex e9cb4444b3..61b5e00c94 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -726,6 +726,15 @@ pub async fn perform_payments_sync(Ok(())}+/// Counts an invoice whose grace window could not be established. Every caller is terminal, and+/// they fail for unrelated reasons — the invoice carries no billing start date, the configured+/// period pushes the end date past what a timestamp holds, or the days left do not fit the model's+/// day count — so `reason` is what separates them.+fn record_grace_window_unresolved(reason: &'static str) {+ metrics::REVENUE_RECOVERY_GRACE_WINDOW_UNRESOLVED+ .add(1, router_env::metric_attributes!(("reason", reason)));+}+/// When the invoice's recovery grace window closes: its billing start plus the configured grace/// period.async fn get_recovery_grace_window_end(@@ -750,14 +759,20 @@ async fn get_recovery_grace_window_end(.and_then(|revenue_recovery_metadata| {revenue_recovery_metadata.invoice_billing_started_at_time})- .ok_or(errors::RecoveryError::ValueNotFound)+ .ok_or_else(|| {+ record_grace_window_unresolved("missing_billing_start_time");+ errors::RecoveryError::ValueNotFound+ }).attach_printable("Cannot bound the invoice by its grace window: the intent has no billing start time",)?;grace_window_start.checked_add(time::Duration::days(grace_period_days))- .ok_or(errors::RecoveryError::ValueNotFound)+ .ok_or_else(|| {+ record_grace_window_unresolved("grace_window_end_overflow");+ errors::RecoveryError::ValueNotFound+ }).attach_printable("The end of the grace window does not fit a timestamp")}@@ -905,9 +920,11 @@ pub async fn perform_calculate_workflow(None,)} else {- // The allowances the adaptive model needs, derived once here from the window- // established above rather than inside an arm. Unreachable as `None`: this arm is- // only taken when retries remain, and the window is computed — or errored — above.+ // The allowances the retry model needs, derived once here from the window established+ // above and handed to whichever arm runs. Both arms read the same pair, so enrolling an+ // invoice in A/B routing cannot change the budget its model is working against.+ // Unreachable as `None`: this arm is only taken when retries remain, and the window is+ // computed — or errored — above.let grace_window_end = grace_window_end.ok_or(errors::RecoveryError::ValueNotFound).attach_printable("Cannot derive the recovery allowances: the grace window is unset")?;@@ -917,10 +934,12 @@ pub async fn perform_calculate_workflow(.whole_days().max(0),)+ .inspect_err(|_| record_grace_window_unresolved("grace_days_out_of_range")).change_context(errors::RecoveryError::ValueNotFound).attach_printable("The days left in the grace window do not fit a day count")?;let retries_already_made = u32::try_from(process.retry_count)+ .inspect_err(|_| metrics::REVENUE_RECOVERY_RETRY_COUNT_INVALID.add(1, &[])).change_context(errors::RecoveryError::ValueNotFound).attach_printable("Failed to read how many retries have already been made")?;@@ -938,7 +957,6 @@ pub async fn perform_calculate_workflow(process.retry_count,tracking_data,&static_ladder_progress,- max_retry_count,platform.get_provider().get_provider_merchant_id(),remaining_grace_days,remaining_budget,@@ -961,6 +979,19 @@ pub async fn perform_calculate_workflow(}};+ // Counted here rather than where each outcome is produced, because this is the only point all+ // six pass through: the retry-ceiling and grace-window checks above short-circuit the workflow+ // entirely, and the ladder-exhausted case returns early inside it. Four of the six mean the+ // invoice is not retried; the two that schedule something are counted as well, since a drop+ // rate is only readable against a denominator.+ metrics::REVENUE_RECOVERY_CALCULATE_OUTCOME.add(+ 1,+ router_env::metric_attributes!(+ ("outcome", payment_processor_token_response.as_str()),+ ("algorithm", retry_algorithm_type.to_string())+ ),+ );+match payment_processor_token_response {revenue_recovery_workflow::PaymentProcessorTokenResponse::ScheduledTime {scheduled_time,@@ -1172,15 +1203,15 @@ pub async fn perform_calculate_workflow(Ok(())}-/// Finish the CALCULATE_WORKFLOW row, carrying any updated adaptive scheduling state.+/// Finish the CALCULATE_WORKFLOW row, carrying any supplied ladder 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.+ // A ladder position was supplied, so it 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())diff --git a/crates/router/src/core/revenue_recovery/schedule.rs b/crates/router/src/core/revenue_recovery/schedule.rsindex 608e91dacb..5abde952a3 100644--- a/crates/router/src/core/revenue_recovery/schedule.rs+++ b/crates/router/src/core/revenue_recovery/schedule.rs@@ -33,19 +33,20 @@ impl StaticLadderProgress {}}- /// Ladder position to query for this decision.+ /// The next ladder position after those already consumed. Unused in production since the+ /// static ladder was removed from the decision; kept with the inert counter.pub fn next_rung(&self) -> i32 {self.consumed_rungs + 1}}-/// Which algorithm produced the scheduled time.+/// Which source produced the scheduled time.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(rename_all = "snake_case")]pub enum ScheduleSource {- Static,- Adaptive,- /// The MIT cascading ladder, consulted only once the other two have nothing to offer.+ /// Whichever retry model the invoice was routed to.+ Model,+ /// The MIT cascading ladder, the global fallback for whatever the model declines.Fallback,}@@ -56,56 +57,39 @@ pub struct ScheduleDecision {pub schedule_time: PrimitiveDateTime,/// State to persist back onto the tracking data.pub next_progress: StaticLadderProgress,- /// Which algorithm won, for logging and analytics.+ /// Which source won, for logging and analytics.pub source: ScheduleSource,}-/// Choose between the two candidates, falling back to the MIT cascading ladder when neither has-/// one to offer, and `None` when nothing is left to schedule.+/// The retry model decides whenever it has an opinion; the MIT cascading ladder is the global+/// fallback for everything it declines. `None` when neither has anything to offer.+///+/// The two are NOT compared — the model's time is taken as it stands, however much later than the+/// fallback's it falls. The fallback is a standby, not a ceiling.+///+/// Neither source spends a ladder position, so `next_progress` echoes what it was handed. The+/// counter is inert here and kept only so the persisted field keeps round-tripping; removing it+/// reaches merchant-facing config and belongs in its own change.pub fn decide_next_retry(schedule: &StaticLadderProgress,- queried_rung: i32,- static_time: Option<PrimitiveDateTime>,- adaptive_time: Option<PrimitiveDateTime>,+ model_time: Option<PrimitiveDateTime>,fallback_time: Option<PrimitiveDateTime>,) -> Option<ScheduleDecision> {- // Adaptive spends no ladder position, so the count stays put and the same position is offered- // again on the next decision.- let adaptive = |schedule_time| ScheduleDecision {+ let decision = |schedule_time, source| ScheduleDecision {schedule_time,next_progress: StaticLadderProgress {consumed_rungs: schedule.consumed_rungs,},- source: ScheduleSource::Adaptive,- };- let static_ladder = |schedule_time| ScheduleDecision {- schedule_time,- next_progress: StaticLadderProgress {- consumed_rungs: queried_rung,- },- source: ScheduleSource::Static,+ source,};- match (static_time, adaptive_time) {- // The earlier calendar day wins. A tie goes to static: the ladder already covers that- // day, so an earlier hour on it does not earn a second attempt.- (Some(static_time), Some(adaptive_time)) if adaptive_time.date() < static_time.date() => {- Some(adaptive(adaptive_time))- }- (Some(static_time), _) => Some(static_ladder(static_time)),- // Ladder spent, so the adaptive time stands unopposed.- (None, Some(adaptive_time)) => Some(adaptive(adaptive_time)),- // The adaptive ladder is spent and the model declined, so the MIT cascading ladder gets- // the last word. It spends no adaptive position, so the count stays put; `None` here- // means there is genuinely nothing left to schedule for this invoice.- (None, None) => fallback_time.map(|schedule_time| ScheduleDecision {- schedule_time,- next_progress: StaticLadderProgress {- consumed_rungs: schedule.consumed_rungs,- },- source: ScheduleSource::Fallback,- }),- }+ model_time+ .map(|schedule_time| decision(schedule_time, ScheduleSource::Model))+ // The model declined, so the global fallback gets the last word. `None` here means there is+ // genuinely nothing left to schedule for this invoice.+ .or_else(|| {+ fallback_time.map(|schedule_time| decision(schedule_time, ScheduleSource::Fallback))+ })}#[cfg(test)]@@ -131,12 +115,10 @@ mod tests {/// A decision the caller would act on. Panics where the test's premise is that one exists.fn expect_decision(schedule: &StaticLadderProgress,- queried_rung: i32,- static_time: Option<PrimitiveDateTime>,- adaptive_time: Option<PrimitiveDateTime>,+ model_time: Option<PrimitiveDateTime>,+ fallback_time: Option<PrimitiveDateTime>,) -> ScheduleDecision {- decide_next_retry(schedule, queried_rung, static_time, adaptive_time, None)- .expect("a time was available")+ decide_next_retry(schedule, model_time, fallback_time).expect("a time was available")}// ---- seeding ----------------------------------------------------------@@ -159,7 +141,7 @@ mod tests {#[test]fn a_new_invoice_at_or_past_the_cap_opens_the_ladder_fully_consumed() {// The connector used the whole allowance before recovery ever saw the invoice, so there- // is no cascading position left and the adaptive algorithm carries it alone.+ // is no cascading position left and the model carries it alone.assert_eq!(StaticLadderProgress::seed_for_new_invoice(HYBRID_CAP, HYBRID_CAP).consumed_rungs,5@@ -217,179 +199,56 @@ mod tests {);}- // ---- 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 ----------------------------------------------------+ // ---- the model decides, the global fallback covers what it declines ---#[test]- fn adaptive_earlier_day_wins_and_leaves_the_rung_unconsumed() {- let schedule = at_rung(2);- let decision = expect_decision(&schedule, 3, Some(at(240)), Some(at(72)));-- assert_eq!(decision.schedule_time, at(72));- assert_eq!(decision.source, ScheduleSource::Adaptive);- // 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);- }+ fn a_later_model_time_still_wins() {+ // The fallback is not a ceiling: a model day after the fallback's is taken as it stands.+ // Nothing here compares the two.+ let fallback_time = at(240);+ let model_time = at(336);+ assert!(model_time.date() > fallback_time.date());- #[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 = expect_decision(- &StaticLadderProgress::default(),- 1,- Some(static_time),- Some(adaptive_time),- );+ let decision = expect_decision(&at_rung(2), Some(model_time), Some(fallback_time));- assert_eq!(decision.schedule_time, adaptive_time);- assert_eq!(decision.source, ScheduleSource::Adaptive);+ assert_eq!(decision.schedule_time, model_time);+ assert_eq!(decision.source, ScheduleSource::Model);}- // ---- static wins -------------------------------------------------------#[test]- fn adaptive_later_day_loses_and_consumes_the_rung() {- let decision = expect_decision(&at_rung(2), 3, Some(at(240)), Some(at(336)));+ fn no_model_opinion_uses_the_global_fallback() {+ let decision = expect_decision(&StaticLadderProgress::default(), None, Some(at(240)));assert_eq!(decision.schedule_time, at(240));- assert_eq!(decision.source, ScheduleSource::Static);- assert_eq!(decision.next_progress.consumed_rungs, 3);+ assert_eq!(decision.source, ScheduleSource::Fallback);}#[test]- fn no_adaptive_opinion_uses_static_and_consumes_the_rung() {- let decision = expect_decision(&StaticLadderProgress::default(), 1, Some(at(240)), None);-- assert_eq!(decision.schedule_time, at(240));- assert_eq!(decision.source, ScheduleSource::Static);- assert_eq!(decision.next_progress.consumed_rungs, 1);+ fn both_declining_yields_no_decision() {+ assert_eq!(decide_next_retry(&at_rung(5), None, None), None);}- // ---- 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 = expect_decision(- &StaticLadderProgress::default(),- 1,- Some(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);- }+ // ---- the rung counter is inert ----------------------------------------#[test]- fn adaptive_identical_to_static_loses() {- let decision = expect_decision(- &StaticLadderProgress::default(),- 1,- Some(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 = expect_decision(&schedule, queried_rung, Some(at(240)), Some(at(72)));- assert_eq!(first.source, ScheduleSource::Adaptive);-- // The process tracker's retry_count is now 2, but rung 1 was never used, so it is- // offered again.- let schedule = first.next_progress;- let queried_rung = schedule.next_rung();- assert_eq!(queried_rung, 1);- let second = expect_decision(&schedule, queried_rung, Some(at(240)), Some(at(120)));- assert_eq!(second.source, ScheduleSource::Adaptive);-- // retry_count 3, and still rung 1.- let schedule = second.next_progress;- let queried_rung = schedule.next_rung();- assert_eq!(queried_rung, 1);- let third = expect_decision(&schedule, queried_rung, Some(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);- }-- // ---- an exhausted ladder ------------------------------------------------ #[test]- fn an_exhausted_ladder_hands_the_slot_to_adaptive() {- // Past the ladder's last entry there is no static candidate, but the invoice is not- // finished — the adaptive algorithm carries it for the rest of the grace window.- let decision = expect_decision(&at_rung(5), 6, None, Some(at(72)));-- assert_eq!(decision.schedule_time, at(72));- assert_eq!(decision.source, ScheduleSource::Adaptive);- }-- #[test]- fn an_exhausted_ladder_does_not_advance_the_position() {- // There was no position to spend, so the count stays where the ladder left it rather- // than creeping past the end on every adaptive retry.- let decision = expect_decision(&at_rung(5), 6, None, Some(at(72)));-- assert_eq!(decision.next_progress.consumed_rungs, 5);- }-- #[test]- fn both_algorithms_declining_yields_no_decision() {- // The ladder is spent and the model has no opinion. Only here is there genuinely- // nothing left to schedule, and the caller ends the invoice.- assert_eq!(decide_next_retry(&at_rung(5), 6, None, None, None), None);- }-- #[test]- fn an_exhausted_ladder_ignores_the_day_comparison() {- // With no static day to beat, an adaptive time far in the future still wins — the tie- // rule only applies when there are two candidates.- let decision = expect_decision(&StaticLadderProgress::default(), 1, None, Some(at(2400)));-- assert_eq!(decision.schedule_time, at(2400));- assert_eq!(decision.source, ScheduleSource::Adaptive);+ fn no_source_spends_a_ladder_position() {+ // With the static ladder gone, neither source advances the count: whatever a decision is+ // handed, it hands back. Pinned because the field is still persisted and still seeded, so+ // a future edit that starts moving it would otherwise change stored state unnoticed.+ for (model_time, fallback_time, expected_source) in [+ (Some(at(72)), None, ScheduleSource::Model),+ (Some(at(72)), Some(at(240)), ScheduleSource::Model),+ (None, Some(at(240)), ScheduleSource::Fallback),+ ] {+ for consumed_rungs in [0, 1, 5] {+ let schedule = at_rung(consumed_rungs);+ let decision = expect_decision(&schedule, model_time, fallback_time);++ assert_eq!(decision.source, expected_source);+ assert_eq!(decision.next_progress, schedule);+ assert_eq!(decision.next_progress.consumed_rungs, consumed_rungs);+ }+ }}// ---- persistence ------------------------------------------------------diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 39620b3393..ffda75f9b9 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -304,19 +304,29 @@ counter_metric!(VAULT_CALL_FAILURES, GLOBAL_METER);// Encryption/keymanager latency for payment_methods operationshistogram_metric_f64!(PAYMENT_METHOD_CRYPTO_DURATION, GLOBAL_METER);-// Revenue recovery A/B routing+// Revenue recovery//-// Both count invoices the A/B arm could not price, which it treats as an error. They matter for-// experiment validity rather than availability: an arm that drops invoices for reasons correlated-// with the arm itself biases the comparison, and the logs alone make that invisible in aggregate.+// Every counter below marks a point where an invoice stopped being priced or stopped being+// recovered. Each one existed only as a log line first, which answers "did this happen to this+// invoice" but never "how often, and to which invoices" — and the second question is the one that+// decides both whether an experiment is valid and whether recovery is healthy.+//+// Where an arm can be attributed, the algorithm is carried as an attribute: an arm that drops+// invoices for reasons correlated with the arm itself biases the comparison, and an unlabelled+// aggregate cannot show that.++// Points where an invoice could not be priced at all.counter_metric!(REVENUE_RECOVERY_AB_MISSING_ERROR_CODE,GLOBAL_METER,name: "revenue_recovery.ab.missing_error_code",- description: "Invoices whose assigned algorithm needed the previous attempt's error code to \- pick a retry time, but the CALCULATE task carried none",+ description: "Invoices whose retry model needed the previous attempt's error code to pick a \+ time, but the CALCULATE task carried none — the model declines and the global \+ fallback covers it; `algorithm` is `unenrolled` outside the experiment",unit: "1",);+// No algorithm attribute on this one: the thing being counted is that no arm was resolved yet, so+// there is nothing to attribute it to.counter_metric!(REVENUE_RECOVERY_AB_UNASSIGNED_ALGORITHM,GLOBAL_METER,@@ -325,3 +335,57 @@ counter_metric!(intent, so no algorithm could be replayed",unit: "1",);+counter_metric!(+ REVENUE_RECOVERY_NO_SCHEDULE_TIME,+ GLOBAL_METER,+ name: "revenue_recovery.no_schedule_time",+ description: "Invoices left with no retry time after both sources declined — the assigned \+ model and the MIT cascading ladder behind it",+ unit: "1",+);++// The stats store is shared by every arm, so a failure here says nothing about which algorithm an+// invoice was on — it carries the cluster instead. Every code failing at once is the store being+// unreachable; one code failing alone is that cluster's stored document.+counter_metric!(+ REVENUE_RECOVERY_STATS_LOOKUP_FAILED,+ GLOBAL_METER,+ name: "revenue_recovery.stats_lookup_failed",+ description: "Retry-stats lookups that errored, so the model declined and the invoice fell \+ through to the global fallback — distinct from a cluster with no stats yet",+ unit: "1",+);++// Points where recovery itself ends, whichever algorithm was running.+//+// The verdict every CALCULATE decision ends on, by outcome and by the algorithm that produced it.+// Four of the six outcomes mean the invoice is not being retried; the two that do schedule+// something are counted as well, because a drop rate is only readable against the total.+counter_metric!(+ REVENUE_RECOVERY_CALCULATE_OUTCOME,+ GLOBAL_METER,+ name: "revenue_recovery.calculate_outcome",+ description: "CALCULATE decisions by outcome (scheduled, next_available_time, hard_decline, \+ retries_exhausted, grace_window_expired, none) and retry algorithm",+ unit: "1",+);+counter_metric!(+ REVENUE_RECOVERY_GRACE_WINDOW_UNRESOLVED,+ GLOBAL_METER,+ name: "revenue_recovery.grace_window_unresolved",+ description: "Invoices whose grace window — how long they have left to be recovered — could \+ not be established, ending recovery for that invoice; `reason` says which of \+ the three steps could not be completed",+ unit: "1",+);+// Not to be read as "the invoice ran out of retries", which is the ordinary end of its life and+// finishes the job cleanly. This counts a stored retry count that is not a count at all — the only+// way `i32 -> u32` fails is a negative — so the remaining budget cannot be derived from it.+counter_metric!(+ REVENUE_RECOVERY_RETRY_COUNT_INVALID,+ GLOBAL_METER,+ name: "revenue_recovery.retry_count_invalid",+ description: "Invoices whose stored retry count was negative and so not a usable count, \+ leaving the remaining retry budget underivable and ending recovery",+ unit: "1",+);diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rsindex fbfc90665c..469f74f823 100644--- a/crates/router/src/types/storage/revenue_recovery.rs+++ b/crates/router/src/types/storage/revenue_recovery.rs@@ -29,9 +29,11 @@ pub struct RevenueRecoveryWorkflowTrackingData {/// 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.+ /// Ladder position carried across an invoice's recovery. Inert since the static ladder was+ /// removed from the decision — nothing advances it and nothing reads it to pick a time — but+ /// still seeded and still persisted, so it keeps round-tripping until it is removed properly.+ /// 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: Option<StaticLadderProgress>,}@@ -103,12 +105,20 @@ pub struct RevenueRecoverySettings {pub redis_ttl_in_seconds: i64,#[serde(default)]pub retry_stats_lock: RetryStatsLockSettings,- /// Fallback hour-of-day (UTC, 0–23) the MathModel schedules a retry at when a cluster has no+ /// Fallback hour-of-day (UTC, 0–23) the retry model schedules at when a cluster has no/// usable hour-of-day history. Overridable per environment via the config file's/// `[revenue_recovery]` section or the `ROUTER__REVENUE_RECOVERY__DEFAULT_RETRY_HOUR_UTC` env var;/// when omitted it defaults to noon UTC (see [`DefaultRetryHour`]).#[serde(default)]pub default_retry_hour_utc: DefaultRetryHour,+ /// Minimum probability the systematic-k sampler gives every candidate day, so no day is ruled+ /// out on a model that has never tried it. `ROUTER__REVENUE_RECOVERY__EXPLORATION_FLOOR`.+ #[serde(default)]+ pub exploration_floor: ExplorationFloor,+ /// Distance within which two day values count as tied and split their share of the budget+ /// equally. `ROUTER__REVENUE_RECOVERY__TIE_TOLERANCE`. See [`TieTolerance`] before raising it.+ #[serde(default)]+ pub tie_tolerance: TieTolerance,}/// Redis distributed-lock settings for revenue-recovery retry-stats recording@@ -139,7 +149,7 @@ impl RetryStatsLockSettings {}}-/// Fallback hour-of-day (UTC, 0–23) for the MathModel. A newtype so its `Default` (noon UTC = 12) is+/// Fallback hour-of-day (UTC, 0–23) for the retry model. A newtype so its `Default` (noon UTC = 12) is/// carried automatically by both `#[derive(Default)]` on the settings and serde's `#[serde(default)]`/// — the value lives in exactly one place, with no field-list repetition.#[derive(Debug, Clone, Copy, serde::Deserialize)]@@ -151,6 +161,87 @@ impl Default for DefaultRetryHour {}}+impl DefaultRetryHour {+ /// The hour to schedule at: the configured one when it names a real hour, the default+ /// otherwise. Out of range it would degrade to midnight downstream, which is a legal-looking+ /// time nobody would question — so it warns instead of being quietly clamped.+ pub fn resolve(self) -> u8 {+ if self.0 <= 23 {+ return self.0;+ }+ let fallback = Self::default().0;+ logger::warn!(+ configured = self.0,+ fallback,+ "revenue_recovery.default_retry_hour_utc is outside 0-23; using the default"+ );+ fallback+ }+}++/// Exploration floor for the systematic-k sampler: the minimum inclusion probability every+/// candidate day is guaranteed. A business dial — higher explores more and uses the model less.+/// Values above `budget / window_length` are infeasible and get clamped at the point of use.+#[derive(Debug, Clone, Copy, serde::Deserialize)]+pub struct ExplorationFloor(pub f64);++impl Default for ExplorationFloor {+ fn default() -> Self {+ Self(0.10)+ }+}++impl ExplorationFloor {+ /// The floor to sample with: the configured one when it is a probability, the default+ /// otherwise. Outside `[0, 1)` it is not one, and the sampler clamps it at the point of use —+ /// so without this the misconfiguration would never surface anywhere.+ pub fn resolve(self) -> f64 {+ if (0.0..1.0).contains(&self.0) {+ return self.0;+ }+ let fallback = Self::default().0;+ logger::warn!(+ configured = self.0,+ fallback,+ "revenue_recovery.exploration_floor is not in [0, 1); using the default"+ );+ fallback+ }+}++/// Distance within which two candidate-day values are treated as tied.+///+/// Raising this is not safe by inspection. A merge only changes anything where the group spans the+/// rank the budget ran out at, and there it averages a near-certain day with a floored one — a+/// swing of up to `1 − exploration_floor`. On production stats the smallest gap at that rank was+/// 4.2e-05, so above that this starts reallocating probability between days the model ranks apart.+#[derive(Debug, Clone, Copy, serde::Deserialize)]+pub struct TieTolerance(pub f64);++impl Default for TieTolerance {+ fn default() -> Self {+ Self(1e-4)+ }+}++impl TieTolerance {+ /// The tolerance to group by: the configured one when it is a usable distance, the default+ /// otherwise. Negative merges nothing and non-finite merges everything, since every `<=`+ /// against `NaN` is false and every one against infinity is true.+ pub fn resolve(self) -> f64 {+ if self.0 >= 0.0 && self.0.is_finite() {+ return self.0;+ }+ let fallback = Self::default().0;+ logger::warn!(+ configured = self.0,+ fallback,+ "revenue_recovery.tie_tolerance is negative or not finite; using the default"+ );+ fallback+ }+}+#[derive(Debug, serde::Deserialize, Clone)]pub struct RecoveryTimestamp {pub initial_timestamp_in_seconds: i64,@@ -198,3 +289,40 @@ impl RetryLimitsConfig {}}}++#[cfg(test)]+mod tunable_tests {+ use super::*;++ #[test]+ fn a_usable_value_is_returned_as_configured() {+ assert_eq!(DefaultRetryHour(0).resolve(), 0);+ assert_eq!(DefaultRetryHour(23).resolve(), 23);+ assert!((ExplorationFloor(0.0).resolve() - 0.0).abs() < f64::EPSILON);+ assert!((ExplorationFloor(0.25).resolve() - 0.25).abs() < f64::EPSILON);+ assert!((TieTolerance(0.0).resolve() - 0.0).abs() < f64::EPSILON);+ assert!((TieTolerance(1e-3).resolve() - 1e-3).abs() < f64::EPSILON);+ }++ #[test]+ fn an_unusable_value_falls_back_to_the_default() {+ // Each guard's far side, including the boundary that is deliberately excluded: a floor of+ // exactly 1.0 means "always", which is not a floor.+ assert_eq!(+ DefaultRetryHour(24).resolve(),+ DefaultRetryHour::default().0+ );+ for floor in [1.0, -0.1, f64::NAN, f64::INFINITY] {+ assert!(+ (ExplorationFloor(floor).resolve() - ExplorationFloor::default().0).abs()+ < f64::EPSILON+ );+ }+ for tolerance in [-1e-9, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {+ assert!(+ (TieTolerance(tolerance).resolve() - TieTolerance::default().0).abs()+ < f64::EPSILON+ );+ }+ }+}diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex de28f3cea4..c759cb6d03 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -253,23 +253,6 @@ pub(crate) async fn get_schedule_time_to_retry_mit_payments(scheduler_utils::get_time_from_delta(time_delta)}-/// Static ladder time for the adaptive retry algorithm.-#[cfg(feature = "v2")]-pub(crate) async fn get_schedule_time_to_retry_adaptive_payments(- db: &dyn StorageInterface,- superposition_client: &external_services::superposition::SuperpositionClient,- dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,- retry_count: i32,-) -> Option<time::PrimitiveDateTime> {- let mapping = dimensions- .get_pt_mapping_adaptive_retries(db, superposition_client, None)- .await;-- let time_delta = scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, retry_count);-- scheduler_utils::get_time_from_delta(time_delta)-}-#[derive(Debug, Clone)]pub struct RetryDecision {pub retry_time: time::PrimitiveDateTime,@@ -657,86 +640,25 @@ pub enum PaymentProcessorTokenResponse {None,}-/// The two allowances the math model needs: how much of the invoice's grace window is left, and-/// how many retries remain of the merchant's budget. The grace window comes from Superposition,-/// the budget from the billing connector's account.#[cfg(feature = "v2")]-async fn get_adaptive_retry_allowances(- state: &SessionState,- dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,- payment_intent: &PaymentIntent,- max_retry_count: u16,- retry_count: i32,- now: time::PrimitiveDateTime,-) -> Result<(u32, u32), errors::ProcessTrackerError> {- let grace_period_days = dimensions- .get_recovery_grace_period_days(- state.store.as_ref(),- state.superposition_service.as_ref(),- None,- )- .await;-- let grace_window_start = payment_intent- .feature_metadata- .as_ref()- .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.as_ref())- .and_then(|revenue_recovery_metadata| {- revenue_recovery_metadata.invoice_billing_started_at_time- })- .ok_or_else(|| {- logger::error!(- payment_id = %payment_intent.id.get_string_repr(),- "adaptive retry: the invoice has no billing start time, so its grace window \- cannot be established"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;-- let grace_window_end = grace_window_start- .checked_add(time::Duration::days(grace_period_days))- .ok_or_else(|| {- logger::error!(- payment_id = %payment_intent.id.get_string_repr(),- grace_period_days,- %grace_window_start,- "adaptive retry: failed to calculate the grace window end time"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;-- let days_left_in_grace_window = (grace_window_end - now).whole_days().max(0);-- let remaining_grace_days: u32 = days_left_in_grace_window.try_into().map_err(|error| {- logger::error!(- ?error,- payment_id = %payment_intent.id.get_string_repr(),- days_left_in_grace_window,- "adaptive retry: the days left in the grace window do not fit the model's day count"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;-- let retries_already_made: u32 = retry_count.try_into().map_err(|error| {- logger::error!(- ?error,- payment_id = %payment_intent.id.get_string_repr(),- retry_count,- "adaptive retry: failed to read how many retries have already been made"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;-- // Saturating so an invoice already past its ceiling reads as no budget left rather than- // wrapping to an enormous one.- let remaining_budget = u32::from(max_retry_count).saturating_sub(retries_already_made);-- Ok((remaining_grace_days, remaining_budget))+impl PaymentProcessorTokenResponse {+ /// Stable metric label for the outcome. Spelled out rather than derived so a renamed variant+ /// cannot silently break the series a dashboard is grouped on.+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::HardDecline => "hard_decline",+ Self::ScheduledTime { .. } => "scheduled",+ Self::NextAvailableTime { .. } => "next_available_time",+ Self::RetriesExhausted => "retries_exhausted",+ Self::GraceWindowExpired => "grace_window_expired",+ Self::None => "none",+ }+ }}-/// The adaptive model's retry time for an invoice, or `None` when the model cannot be consulted.+/// The assigned arm's retry time for an invoice, or `None` when the model cannot be consulted.#[cfg(feature = "v2")]-async fn get_adaptive_retry_time_for_error_code(+async fn get_retry_time_for_error_code(state: &SessionState,algorithm: common_enums::RevenueRecoveryABAlgorithm,prev_attempt_error_code: Option<common_enums::StandardisedCode>,@@ -748,20 +670,30 @@ async fn get_adaptive_retry_time_for_error_code(1,router_env::metric_attributes!(("algorithm", algorithm.to_string())),);+ logger::info!(+ ?algorithm,+ "retry model: the CALCULATE task carries no error code, so the model cannot be \+ consulted — falling back to the cascading ladder"+ );return None;};- compute_adaptive_retry_time(state, error_code, remaining_grace_days, remaining_budget)- .await- .map(common_utils::date_time::convert_to_pdt)+ compute_model_retry_time(+ state,+ error_code,+ remaining_grace_days,+ remaining_budget,+ RetryModelVariant::from(algorithm),+ )+ .await+ .map(common_utils::date_time::convert_to_pdt)}/// Picks the retry time for an invoice enrolled in A/B routing, then finds a token for it.#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]-async fn get_token_with_schedule_time_for_ab_routing(+async fn get_ab_routed_retry_time(state: &SessionState,- connector_customer_id: &str,payment_intent: &PaymentIntent,tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,remaining_grace_days: u32,@@ -769,7 +701,10 @@ async fn get_token_with_schedule_time_for_ab_routing(// Both needed only to assign an implementation to an invoice that arrives without onerevenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,ab_dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,-) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {+) -> (+ Option<time::PrimitiveDateTime>,+ common_enums::RevenueRecoveryABAlgorithm,+) {let algorithm = payment_intent.feature_metadata.as_ref()@@ -784,31 +719,15 @@ async fn get_token_with_schedule_time_for_ab_routing("A/B routing read the retry implementation assigned to this invoice");- let schedule_time = match algorithm {- Some(assigned_algorithm @ common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry) => {- let adaptive_time = get_adaptive_retry_time_for_error_code(- state,- assigned_algorithm,- tracking_data.prev_attempt_error_code,- remaining_grace_days,- remaining_budget,- )- .await;-- logger::info!(- error_code = ?tracking_data.prev_attempt_error_code,- remaining_grace_days = remaining_grace_days,- remaining_budget = remaining_budget,- schedule_time = ?adaptive_time,- "Adaptive retry decision"- );-- adaptive_time- }+ // Resolve the arm first, then run it once. Dispatching inside the arms would leave the+ // just-assigned invoice on a second path, and an arm added to only one of them would run the+ // wrong algorithm on an invoice's FIRST retry and the right one thereafter.+ let assigned_algorithm = match algorithm {+ Some(assigned_algorithm) => assigned_algorithm,None => {crate::routes::metrics::REVENUE_RECOVERY_AB_UNASSIGNED_ALGORITHM.add(1, &[]);- let assigned_algorithm = pcr::assign_and_record_ab_routing(+ pcr::assign_and_record_ab_routing(state,&payment_intent.id,payment_intent@@ -818,37 +737,26 @@ async fn get_token_with_schedule_time_for_ab_routing(revenue_recovery_payment_data,ab_dimensions,)- .await;-- get_adaptive_retry_time_for_error_code(- state,- assigned_algorithm,- tracking_data.prev_attempt_error_code,- remaining_grace_days,- remaining_budget,- ).await}};- let schedule_time = schedule_time.ok_or_else(|| {- logger::error!(- payment_id = %payment_intent.id.get_string_repr(),- ?algorithm,- error_code = ?tracking_data.prev_attempt_error_code,- "No retry time available — the assigned algorithm produced none and this path has no \- ladder to fall back on"- );- errors::ProcessTrackerError::EApiErrorResponse- })?;-- get_token_availability_for_schedule_time(+ let schedule_time = get_retry_time_for_error_code(state,- connector_customer_id,- payment_intent,- schedule_time,+ assigned_algorithm,+ tracking_data.prev_attempt_error_code,+ remaining_grace_days,+ remaining_budget,)- .await+ .await;++ logger::info!(+ ?assigned_algorithm,+ schedule_time = ?schedule_time,+ "A/B routing ran the invoice's assigned arm"+ );++ (schedule_time, assigned_algorithm)}#[cfg(feature = "v2")]@@ -862,7 +770,6 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(retry_count: i32,tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,static_ladder_progress: &pcr::schedule::StaticLadderProgress,- max_retry_count: u16,// Needed only to resolve the A/B gateprovider_merchant_id: hyperswitch_domain_models::platform::ProviderMerchantId,remaining_grace_days: u32,@@ -877,9 +784,8 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(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 ladder position for a retry that never happened.+ // Ladder position to write back onto the CALCULATE row. `None` leaves the stored count alone,+ // which is the case for every outcome but one — see where it is set.let mut next_static_ladder_progress = None;match retry_algorithm_type {RevenueRecoveryAlgorithmType::Monitoring => {@@ -941,60 +847,66 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type().await;- if ab_enabled {- payment_processor_token_response = get_token_with_schedule_time_for_ab_routing(- state,- connector_customer_id,- payment_intent,- tracking_data,- remaining_grace_days,- remaining_budget,- revenue_recovery_payment_data,- &ab_dimensions,- )- .await?;- } else if adaptive_retry_enabled {- // Same shape as the cascading arm — compute the schedule time, then gate on- // the token. The only additions are the adaptive candidate and the choice- // between the two.- let now = common_utils::date_time::now();- let queried_rung = static_ladder_progress.next_rung();-- let static_time = get_schedule_time_to_retry_adaptive_payments(- state.store.as_ref(),- state.superposition_service.as_ref(),- &dimensions,- queried_rung,- )- .await;-- let (remaining_grace_days, remaining_budget) = get_adaptive_retry_allowances(- state,- &dimensions,- payment_intent,- max_retry_count,- retry_count,- now,- )- .await?;-- let adaptive_time = match tracking_data.prev_attempt_error_code {- Some(error_code) => compute_adaptive_retry_time(+ if ab_enabled || adaptive_retry_enabled {+ // Same shape as the cascading arm — compute the schedule time, then gate on the+ // token. The addition is the model's candidate, which decides outright whenever+ // it has one; the cascading ladder covers only the decisions it declines.+ //+ // Enrolled and unenrolled invoices differ ONLY in which variant produces that+ // candidate. The allowances it works against arrive as arguments, and everything+ // after it — the fallback, the decision, the token — is shared, so enrolling an+ // invoice cannot change whether it gets retried at all.+ let (model_time, assigned_algorithm) = if ab_enabled {+ let (time, algorithm) = get_ab_routed_retry_time(state,- error_code,+ payment_intent,+ tracking_data,remaining_grace_days,remaining_budget,+ revenue_recovery_payment_data,+ &ab_dimensions,)- .await- .map(common_utils::date_time::convert_to_pdt),- None => None,+ .await;+ (time, Some(algorithm))+ } else {+ let time = match tracking_data.prev_attempt_error_code {+ // Not enrolled in A/B routing, so this runs the baseline pairing.+ Some(error_code) => compute_model_retry_time(+ state,+ error_code,+ remaining_grace_days,+ remaining_budget,+ RetryModelVariant::default(),+ )+ .await+ .map(common_utils::date_time::convert_to_pdt),+ // Counted here as well as on the A/B branch: the condition is the same,+ // and with A/B off this is the branch every invoice takes, so counting it+ // only there would read zero exactly when it matters.+ None => {+ crate::routes::metrics::REVENUE_RECOVERY_AB_MISSING_ERROR_CODE.add(+ 1,+ router_env::metric_attributes!(("algorithm", "unenrolled")),+ );+ logger::info!(+ payment_id = %payment_intent.id.get_string_repr(),+ "retry model: the CALCULATE task carries no error code, so the \+ model cannot be consulted — falling back to the cascading \+ ladder"+ );+ None+ }+ };+ (time, None)};- // Neither algorithm has a time to offer: the adaptive ladder is spent and the- // model declined. Only then is the MIT cascading ladder consulted, so the- // lookup costs nothing on the paths that never reach it.- let fallback_time = match (static_time, adaptive_time) {- (None, None) => {+ // The MIT cascading ladder is the global fallback for everything the model+ // declines, indexed by the invoice's overall retry count. Resolved only on the+ // decline path, so the Superposition read costs nothing when the model decides —+ // `None` here means "not consulted", not "nothing to offer".+ let fallback_time = match model_time {+ Some(_) => None,+ None => {get_schedule_time_to_retry_mit_payments(state.store.as_ref(),state.superposition_service.as_ref(),@@ -1003,39 +915,49 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type().await}- _ => None,};let decision = pcr::schedule::decide_next_retry(static_ladder_progress,- queried_rung,- static_time,- adaptive_time,+ model_time,fallback_time,).ok_or_else(|| {logger::error!(- queried_rung = queried_rung,+ retry_count = retry_count,error_code = ?tracking_data.prev_attempt_error_code,remaining_grace_days = remaining_grace_days,remaining_budget = remaining_budget,- "No retry time available — the static ladder is exhausted, the adaptive \- algorithm declined and the MIT ladder had nothing left"+ "No retry time available — the model declined and the MIT cascading \+ ladder had nothing left"+ );+ // Counted, not just logged: an arm that loses invoices at a different rate+ // from another is measuring its own drop rate rather than retry quality, and+ // an aggregate count cannot show that.+ crate::routes::metrics::REVENUE_RECOVERY_NO_SCHEDULE_TIME.add(+ 1,+ router_env::metric_attributes!((+ "algorithm",+ assigned_algorithm+ .map_or_else(|| "unenrolled".to_string(), |arm| arm.to_string())+ )),);- errors::ProcessTrackerError::EApiErrorResponse+ errors::ProcessTrackerError::FlowExecutionError {+ flow: "revenue_recovery_no_schedule_time",+ }})?;logger::info!(source = ?decision.source,- queried_rung = queried_rung,- static_time = ?static_time,- adaptive_time = ?adaptive_time,+ retry_count = retry_count,+ model_time = ?model_time,fallback_time = ?fallback_time,error_code = ?tracking_data.prev_attempt_error_code,remaining_grace_days = remaining_grace_days,remaining_budget = remaining_budget,+ ab_enabled = ab_enabled,schedule_time = ?decision.schedule_time,- "Adaptive retry decision"+ "Retry decision");payment_processor_token_response = get_token_availability_for_schedule_time(@@ -1046,8 +968,8 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type().await?;- // The rung is consumed only when a retry is genuinely scheduled. The other- // responses finish or reschedule the CALCULATE job without an attempt.+ // The ladder position is carried back 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 { .. }@@ -1129,7 +1051,7 @@ pub(crate) fn get_invoice_payment_processor_token(}/// 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+/// Shared by the cascading and model paths so both gate on the same conditions#[cfg(feature = "v2")]async fn get_token_availability_for_schedule_time(state: &SessionState,@@ -1602,17 +1524,22 @@ pub fn add_random_delay_to_schedule_time(}// ----------------------------------------------------------------------------// MathModel retry-time prediction — the data-driven half of the Cascading (MathModel) strategy.+// Retry-time prediction — the data-driven half of the Cascading strategy.//// Given a cluster's day-of-week / day-of-month / hour-of-day success stats (`StatsDocument`), the-// remaining retry budget, and the grace window, it returns the datetime to retry on — via per-tick-// probabilistic firing (real randomness, no seed) with a runway guard. The caller `min()`s this-// with the Superposition static-schedule time (MathModel can only make a retry happen SOONER).+// remaining retry budget, and the grace window, it returns the datetime to retry on. The caller+// takes this time as it stands; the MIT cascading ladder covers only the decisions this+// declines.+//+// The DAY is produced by two independently selectable stages — see `RetryModelVariant`: a COMBINE+// folding the weekday and month-day signals into one weight per candidate day, and a SELECTION+// drawing one day from those weights. The HOUR always uses the per-tick walk.//// Returns `Some(datetime)` whenever the grace window has at least one retriable day, and `None` only// when the window is empty (`grace_days <= 1` — no future day to retry on). WITHIN a non-empty window-// the pick never fails: Laplace smoothing gives every slot a defined estimate and the runway guard-// guarantees a pick even for sparse/empty stats.+// the pick never fails: Laplace smoothing gives every slot a defined estimate, and both samplers+// always land on a day — the runway guard forces one for per-tick, and `Σπ = budget ≥ 1` puts at+// least one probe on the line for systematic-k.//// INDEXING (must match `retry_stats_document::EventSlots::from_utc`, which is how the stats are// recorded):@@ -1727,8 +1654,87 @@ fn slot_scores(slots: &[SlotCounter]) -> BTreeMap<u8, f64> {out}-/// Which signal won the softmax `max` for a candidate day. Carried through the pick so the log can-/// name it without re-deriving. `Tie` = both axes equal (e.g. a cold cluster: both uniform).+/// How the day-of-week and day-of-month signals are folded into one weight per candidate day.+/// Both take a `max` of the two axes; they differ in whether the axes are rescaled first.+///+/// Softmaxing each axis before the max makes each one sum to 1 across the candidate days, so the+/// two are comparable whatever their raw spread. Taking the max first skips that, so the axis+/// carrying larger raw scores wins on scale alone.+#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DayCombine {+ /// Softmax each axis over the candidate days, then take the elementwise max.+ MaxAtSoftmax,+ /// Take the elementwise max of the raw scores, then softmax once.+ MaxAtScore,+}++/// How one day is drawn from the per-day weights.+#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum DaySelection {+ /// Per-day Bernoulli walk with the runway guard. Consumes the weights' MAGNITUDES.+ PerTick,+ /// Systematic πps: draw a whole schedule, act on its soonest day. Rank-only — magnitudes are+ /// discarded, so any monotone transform of the weights yields an identical draw.+ SystematicK,+}++/// Which combine and which sampler this call runs. Independent axes on purpose: a combine change+/// and a sampler change are separately attributable only if they can be varied separately.+///+/// Public because the arm an invoice gets is an experiment-assignment decision, which belongs above+/// this layer — this module only executes the variant it is handed. `Default` is the baseline an+/// invoice runs when nothing selects otherwise; it is NOT the same as the control arm, which is+/// pinned separately in the `From` impl below.+#[cfg(feature = "v2")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct RetryModelVariant {+ pub combine: DayCombine,+ pub selection: DaySelection,+}++#[cfg(feature = "v2")]+impl Default for RetryModelVariant {+ fn default() -> Self {+ Self {+ combine: DayCombine::MaxAtScore,+ selection: DaySelection::SystematicK,+ }+ }+}++/// The experiment arm an invoice was assigned, resolved to the pair of choices that actually run.+///+/// This is the only place the experiment taxonomy meets the retry model, which is why the match is+/// exhaustive with no `_` arm: a new arm added upstream must fail to compile here rather than fall+/// through to some other pairing and quietly produce an experiment that measures nothing.+///+/// Every arm spells its pairing out rather than deferring to `Default`. An arm is persisted on the+/// invoice and replayed across its retries, so one that tracked the default would switch algorithm+/// mid-recovery the moment the default moved.+#[cfg(feature = "v2")]+impl From<common_enums::RevenueRecoveryABAlgorithm> for RetryModelVariant {+ fn from(algorithm: common_enums::RevenueRecoveryABAlgorithm) -> Self {+ match algorithm {+ common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry => Self {+ combine: DayCombine::MaxAtSoftmax,+ selection: DaySelection::PerTick,+ },+ common_enums::RevenueRecoveryABAlgorithm::SystematicKMaxAtSoftmax => Self {+ combine: DayCombine::MaxAtSoftmax,+ selection: DaySelection::SystematicK,+ },+ common_enums::RevenueRecoveryABAlgorithm::SystematicKMaxAtScore => Self {+ combine: DayCombine::MaxAtScore,+ selection: DaySelection::SystematicK,+ },+ }+ }+}++/// Which signal won the `max` for a candidate day. Carried through the pick so the log can name it+/// without re-deriving. `Tie` = both axes equal (e.g. a cold cluster: both uniform).#[cfg(feature = "v2")]#[derive(Clone, Copy, Debug)]enum DayAxis {@@ -1750,8 +1756,7 @@ impl DayAxis {/// Why `pick_index` landed on the index it returned — so the caller can attribute the pick honestly/// (a forced or exhausted pick must NOT be logged as if the weights drove it). `Weights` carries the-/// chosen item's tag (for the day pick, its `DayAxis`), resolved AT pick time so the caller never-/// re-indexes to find it.+/// chosen item's tag, resolved AT pick time so the caller never re-indexes to find it.#[cfg(feature = "v2")]#[derive(Clone, Copy, Debug)]enum PickDriver<T> {@@ -1771,6 +1776,7 @@ impl PickDriver<DayAxis> {}/// Per-tick probabilistic pick over an ordered list of non-negative WEIGHTS, with the runway guard.+/// Serves the HOUR axis; the day axis draws its whole schedule at once via `select_systematic_k_day`./// Fires index k with probability `min(budget · weight_k / remaining_weight, 1)` (remaining_weight/// via a suffix-sum); `budget >= remaining` forces a fire. Weights need not be normalized — only/// their ratios matter. `tags` runs parallel to `weights`; the chosen index's tag rides back inside@@ -1817,7 +1823,7 @@ fn pick_index<T: Copy + std::fmt::Debug>(} else {(f64::from(budget) * w / s).min(1.0)};- // Draw the (unseeded) random value into a variable so the per-step decision is fully logged.+ // Draw into a variable so the per-step decision is fully logged.let draw = common_utils::generate_random_f64_unit();let fired = draw < p;logger::debug!(@@ -1830,7 +1836,7 @@ fn pick_index<T: Copy + std::fmt::Debug>(fire_probability = p,rand_draw = draw,fired = fired,- "mathmodel: pick step"+ "retry model: pick step");if fired {return Some((@@ -1845,7 +1851,7 @@ fn pick_index<T: Copy + std::fmt::Debug>(}logger::debug!(context = context,- "mathmodel: pick exhausted — no step fired (budget 0); no candidate to schedule"+ "retry model: pick exhausted — no step fired (budget 0); no candidate to schedule");None}@@ -1858,6 +1864,12 @@ fn pick_index<T: Copy + std::fmt::Debug>(fn pick_hour(hod: &[SlotCounter], default_hour: u8) -> u8 {let scores = slot_scores(hod);if scores.is_empty() {+ // Without this the chosen hour is indistinguishable from one the model actually picked,+ // since a real pick can land on the default hour too.+ logger::debug!(+ default_hour = default_hour,+ "retry model: no usable hour-of-day history — falling back to the configured hour"+ );return default_hour;}let hours: Vec<u8> = (0u8..24).collect();@@ -1883,19 +1895,24 @@ fn softmax(xs: &[f64]) -> Vec<f64> {/// THE COMBINE SEAM. Fold the day-of-week and day-of-month signals into one weight per candidate day.///-/// v1: softmax each axis over the CANDIDATE DAYS, then take the max — "this day is good if either its-/// weekday OR its month-day is historically good." Simplest defensible combine; since the result is-/// `min()`d with the static schedule downstream, the downside is bounded. Known trade-offs accepted-/// for v1: `max` optimism (a day strong on one axis but weak on the other is picked on its strong-/// side) and a mild grace-dependent tilt toward day-of-month. To try a better combine later-/// (max-at-score / sum-of-logits / posterior sampling), change ONLY this function.+/// Both variants say "this day is good if either its weekday OR its month-day is historically good";+/// they differ in whether the two axes are put on a common footing before the `max` (see+/// [`DayCombine`]). Shared trade-off: `max` optimism — a day strong on one axis but weak on the other+/// is picked on its strong side. A better combine (sum-of-logits, posterior sampling) changes ONLY+/// this function.+///+/// The softmax is kept in both arms even though `SystematicK` discards magnitudes, because+/// `PerTick` does not: the weights must be well-formed for whichever sampler runs.////// Returns per-day `(weight, winning_axis)`; the winner lets the caller log which signal drove a pick.+/// Note the winner is decided on whatever the `max` compared, so it is NOT comparable across+/// variants — the same day can report a different axis under each.#[cfg(feature = "v2")]fn combine_day_weight(dates: &[time::Date],dow: &BTreeMap<u8, f64>,dom: &BTreeMap<u8, f64>,+ combine: DayCombine,) -> (Vec<f64>, Vec<DayAxis>) {let dow_sc: Vec<f64> = dates.iter()@@ -1909,49 +1926,265 @@ fn combine_day_weight(.iter().map(|d| dom.get(&d.day().saturating_sub(1)).copied().unwrap_or(0.0)).collect();- let p_dow = softmax(&dow_sc);- let p_dom = softmax(&dom_sc);- p_dow++ // Whichever pair the `max` compares — normalized per axis, or raw — decides both the weight and+ // the attributed axis.+ let (weekday_values, month_day_values) = match combine {+ DayCombine::MaxAtSoftmax => (softmax(&dow_sc), softmax(&dom_sc)),+ DayCombine::MaxAtScore => (dow_sc, dom_sc),+ };++ let (maxed, winners): (Vec<f64>, Vec<DayAxis>) = weekday_values.iter()- .zip(p_dom.iter())- .map(|(&pw, &pm)| {- let winner = if pm > pw {+ .zip(month_day_values.iter())+ .map(|(&weekday, &month_day)| {+ let winner = if month_day > weekday {DayAxis::Dom- } else if pw > pm {+ } else if weekday > month_day {DayAxis::Dow} else {DayAxis::Tie // both axes equal (e.g. a cold cluster: both uniform) — neither "won"};- (pw.max(pm), winner)+ (weekday.max(month_day), winner)})- .unzip()+ .unzip();++ let weights = match combine {+ DayCombine::MaxAtSoftmax => maxed, // already per-axis probabilities+ DayCombine::MaxAtScore => softmax(&maxed),+ };+ (weights, winners)+}++/// Per-day values → inclusion probabilities. Exact optimum of+///+/// ```text+/// maximise Σ πᵢ·vᵢ (spend the budget on the best days)+/// subject to Σ πᵢ = k (spend it exactly)+/// πᵢ ≤ 1 (a day cannot be retried twice)+/// πᵢ ≥ ε (every day stays reachable)+/// ```+///+/// The optimum is a greedy pour, no solver: floor every day at ε, then raise days to 1.0 in+/// descending value order until the budget runs out.+///+/// Two guards below fail SILENTLY if removed — the vector still sums to k and still yields k days:+/// * **ε capped at k/n.** Above it the problem is infeasible and the pour emits NEGATIVE+/// probabilities, breaking the monotone cumulative sum `systematic_sample` binary-searches.+/// * **Days within `tie_tolerance` split their share.** Ranking alone breaks ties by array+/// position, giving days of equal value wildly different probabilities. Splitting leaves the+/// group total untouched.+#[cfg(feature = "v2")]+fn inclusion_probabilities(+ values: &[f64],+ budget: u32,+ epsilon: f64,+ tie_tolerance: f64,+) -> Vec<f64> {+ let n = values.len();+ if n == 0 {+ return Vec::new();+ }+ // `usize -> f64`. std offers no `From`/`TryFrom` here (a 64-bit `usize` exceeds f64's exact+ // range), and routing through `u32` would be WORSE than the cast: the fallback for an+ // out-of-range count returns a wrong magnitude, where `as` stays exact to 2^53 and merely+ // rounds beyond it. `n` is a candidate-day count, capped at `MAX_GRACE_DAYS` (31).+ #[allow(clippy::as_conversions)]+ let n_f = n as f64;+ // πᵢ ≤ 1 caps the total at n, so a budget wider than the window can only spend n — every day+ // pinned at 1.0, which is the old runway guard arrived at by arithmetic rather than by a rule.+ let k = f64::from(budget).min(n_f);+ let eps = epsilon.clamp(0.0, k / n_f);++ let mut pi = vec![eps; n];+ let mut remaining = k - eps * n_f;++ // (day index, value), best first. Carrying the value means neither the sort nor the grouping+ // below looks anything up again. `total_cmp` orders floats outright where `partial_cmp` has no+ // answer for NaN; `.reverse()` makes it descending.+ let mut ranked: Vec<(usize, f64)> = values.iter().copied().enumerate().collect();+ ranked.sort_by(|(_, value), (_, other_value)| value.total_cmp(other_value).reverse());++ for &(day, _) in &ranked {+ if remaining <= 1e-12 {+ break;+ }+ if let Some(slot) = pi.get_mut(day) {+ let take = (1.0 - eps).min(remaining);+ *slot += take;+ remaining -= take;+ }+ }++ // Split each tied group's share equally over its members (see the doc comment above). `ranked`+ // is sorted by value, so tied days are adjacent and `chunk_by` hands each run over as a slice.+ for tied_days in+ ranked.chunk_by(|(_, value), (_, other_value)| (value - other_value).abs() <= tie_tolerance)+ {+ if tied_days.len() > 1 {+ let total: f64 = tied_days.iter().filter_map(|&(day, _)| pi.get(day)).sum();+ // `usize -> f64`, exact: a tied group is a subset of the window, so at most 31.+ #[allow(clippy::as_conversions)]+ let share = total / tied_days.len() as f64;+ for &(day, _) in tied_days {+ if let Some(slot) = pi.get_mut(day) {+ *slot = share;+ }+ }+ }+ }+ pi+}++/// Pick exactly k distinct days, each with probability exactly `pi[i]` — one uniform draw, one pass.+///+/// Lay the probabilities end to end on a line. They sum to k, so the line is exactly k units long;+/// take probes at `u, u+1, … u+(k−1)` and keep whichever day's segment each probe lands in.+///+/// Both guarantees are geometric, not statistical — they hold on every single draw, not on average:+/// * **exactly k distinct days** — the last probe sits at `u+k−1 < k`, so all k land on the line;+/// probes are exactly 1 apart and no segment exceeds length 1 (πᵢ ≤ 1), so no two share a day.+/// * **each day at exactly πᵢ** — wrap the line onto a circle of circumference 1 and all k probes+/// map to the same point, namely `u`, which is uniform; a segment of length πᵢ therefore catches+/// a probe with probability exactly πᵢ.+///+/// `order` lays the segments down shuffled, REDRAWN PER CALL. It changes neither guarantee (both+/// come from segment lengths) but it decides which day COMBINATIONS are reachable: in calendar+/// order a day at π = 1.00 fills a whole unit and is caught wherever `u` starts, collapsing the+/// joint distribution to a handful of schedules with many day-pairs at probability zero. A shuffle+/// computed once and reused is just a different fixed order and fixes nothing.+///+/// Numerical limit: accumulated edges drift ~1e-14, so for `u` within that of 1.0 the last probe+/// can fall past the final edge and collapse onto a taken segment, yielding k−1 days. Needs+/// `u > 1 − 1e-14` and the caller uses only the soonest day, so it is documented rather than+/// patched — the fixes for it (rescaling probes, normalising π) are what silently break G1/G2.+///+/// `probe_count` is `k`, passed rather than recovered from `Σπ`. The two are equal by construction+/// — `inclusion_probabilities` pours exactly `k` — but reading it back off the accumulated line+/// means a float round-trip, and an infinite or absurd `pi` would then produce a probe count to+/// match and loop on it. Being told how many probes to place removes that and the cast with it.+#[cfg(feature = "v2")]+fn systematic_sample(pi: &[f64], u: f64, order: &[usize], probe_count: usize) -> Vec<usize> {+ // Right edge of each segment, accumulated along the shuffled line.+ let mut acc = 0.0;+ let edges: Vec<f64> = order+ .iter()+ .map(|&idx| {+ acc += pi.get(idx).copied().unwrap_or(0.0);+ acc+ })+ .collect();+ if edges.is_empty() {+ return Vec::new();+ }++ let mut selected: Vec<usize> = (0..probe_count)+ .filter_map(|step| {+ // `usize -> f64`, exact: `step` is bounded by `probe_count`, itself the budget.+ // Written `u + step` rather than an accumulated `+ 1.0` per probe: one rounding+ // instead of `step` of them, and the doc above records why probe arithmetic is+ // left alone.+ #[allow(clippy::as_conversions)]+ let probe = u + step as f64;+ // First segment whose right edge is strictly past the probe.+ let position = edges+ .partition_point(|&edge| edge <= probe)+ .min(edges.len().saturating_sub(1));+ order.get(position).copied()+ })+ .collect();+ // Calendar order, so the caller's "soonest" is the first. G1 already makes the days distinct;+ // the dedup covers the clamp above firing on a probe pushed past the last edge by drift.+ selected.sort_unstable();+ selected.dedup();+ selected+}++/// Choose which candidate day to schedule: draw a whole systematic-k schedule over the window, then+/// take the NEAREST day it selected.+///+/// The alternative to the per-day walk (`pick_index`), which decides a day at a time without seeing+/// the end of the window and so skips good days early, runs out of slack and hits the runway guard.+/// That guard is not patchable: at `days_remaining == budget_remaining` the constraints have one+/// feasible point. Deciding how MANY days before WHICH days makes the state unreachable, since+/// `Σπ = k` comes from the geometry of the line rather than a countdown.+///+/// Values enter only through the ranking, so magnitudes are discarded — deliberate, given the+/// upstream softmax turns small quality differences into enormous weight ratios.+///+/// NOTE — the ON-DEMAND form: the schedule is redrawn each decision and only its earliest day used.+/// Drawing once at first failure and persisting all k dates is the recommended design; on-demand+/// drifts from its promised marginals and starves the end of the window. What it costs is+/// measurability, not recovery. Upfront needs somewhere to persist the k dates and their πᵢ.+///+/// Returns the chosen index into `weights` together with its inclusion probability.+#[cfg(feature = "v2")]+fn select_systematic_k_day(+ weights: &[f64],+ budget: u32,+ epsilon: f64,+ tie_tolerance: f64,+) -> Option<(usize, f64)> {+ if weights.is_empty() || budget == 0 {+ return None;+ }+ let pi = inclusion_probabilities(weights, budget, epsilon, tie_tolerance);++ // Redrawn per invoice — see `systematic_sample` on why a cached order fixes nothing.+ let order = common_utils::generate_random_permutation(weights.len());++ let u = common_utils::generate_random_f64_unit();+ // The same `k` the pour spends: the budget, capped by the window it has to spend it over.+ let probe_count = usize::try_from(budget)+ .unwrap_or(usize::MAX)+ .min(weights.len());+ let selected = systematic_sample(&pi, u, &order, probe_count);+ let chosen = selected.first().copied()?;+ let chosen_inclusion_probability = pi.get(chosen).copied().unwrap_or(0.0);++ logger::debug!(+ budget = budget,+ epsilon = epsilon,+ window_len = weights.len(),+ uniform_draw = u,+ scheduled_days = ?selected,+ chosen_index = chosen,+ chosen_inclusion_probability = chosen_inclusion_probability,+ "retry model: systematic-k selection"+ );++ Some((chosen, chosen_inclusion_probability))}/// Predict the retry datetime from cluster stats.////// * `stats` the cluster's parsed success stats (dow/dom/hod `{n,k}` counters)-/// * `budget` retries remaining (drives the runway guard)+/// * `budget` retries remaining (the per-tick runway guard, and the k of systematic-k)/// * `grace_days` grace period, in days, COUNTING the failure day (today). Retriable window = the/// `grace_days - 1` future days, capped at 31./// * `default_hour` fallback hour-of-day (UTC) used when the cluster has no usable hour history/// (from `revenue_recovery.default_retry_hour_utc` config).////// The window starts on the **NEXT day** (failure day + 1), never on the failure day itself — the-/// charge just failed today, so a same-day retry is low value. The min-gap / past-time guard rails-/// are applied by the CALLER on the returned time (per the MathModel design).+/// charge just failed today, so a same-day retry is low value. That is also what keeps the result+/// in the future: nothing downstream re-checks it, and the only post-processing is a few seconds of+/// random jitter.////// Returns `None` when `budget == 0` (no retries left to schedule) or `grace_days <= 1` (no future/// day inside the grace period); otherwise `Some`./// V1 LIMITATION: a grace of 1 (today only) with retries still available is treated as "no retry"; a-/// later version will handle that edge (e.g. a same-day retry after a delay). Uses real randomness-/// (no seed). The caller `min()`s the result with the static schedule time.+/// later version will handle that edge (e.g. a same-day retry after a delay). The caller takes the+/// result as it stands, rather than bounding it by the cascading ladder.#[cfg(feature = "v2")]#[instrument(skip_all)]-pub fn compute_mathmodel_retry_time(+pub fn compute_predicted_retry_time(stats: &StatsDocument,budget: u32,grace_days: u32,default_hour: u8,+ variant: RetryModelVariant,+ exploration_floor: f64,+ tie_tolerance: f64,) -> Option<time::OffsetDateTime> {// `grace_days` COUNTS the failure day (today), which we never retry on — so the retriable window// is the `grace_days - 1` future days [failure_day + 1 .. failure_day + grace_days - 1]. When that@@ -1963,7 +2196,7 @@ pub fn compute_mathmodel_retry_time(logger::debug!(budget = budget,grace_days = grace_days,- "mathmodel: declined — no future day inside the grace window (grace_days <= 1)"+ "retry model: declined — no future day inside the grace window (grace_days <= 1)");return None;}@@ -1974,7 +2207,7 @@ pub fn compute_mathmodel_retry_time(logger::debug!(budget = budget,grace_days = grace_days,- "mathmodel: declined — no retry budget remaining"+ "retry model: declined — no retry budget remaining");return None;}@@ -1989,7 +2222,7 @@ pub fn compute_mathmodel_retry_time(logger::debug!(configured = grace_days,capped = MAX_GRACE_DAYS,- "mathmodel: grace window capped"+ "retry model: grace window capped");}// future_days is capped at MAX_GRACE_DAYS (31), so this always fits usize; 0 is an unreachable@@ -2010,10 +2243,15 @@ pub fn compute_mathmodel_retry_time(window_len = window_len,window_start = %start,default_hour = default_hour,- "mathmodel: decision start"+ exploration_floor = exploration_floor,+ tie_tolerance = tie_tolerance,+ combine = ?variant.combine,+ selection = ?variant.selection,+ "retry model: decision start");- let (day_weights, winners) = combine_day_weight(&dates, &dow_scores, &dom_scores);+ let (day_weights, winners) =+ combine_day_weight(&dates, &dow_scores, &dom_scores, variant.combine);// Per-candidate-day scores: the day-of-week and day-of-month signals plus the combined weight the// pick is about to run on. Zipped (not indexed) over the parallel vectors.@@ -2034,99 +2272,150 @@ pub fn compute_mathmodel_retry_time(dom_score = dom_score,combined_weight = weight,winning_axis = winner.as_str(),- "mathmodel: candidate day score"+ "retry model: candidate day score");}- // winners ride along so the winning axis returns inside pick_driver — no re-indexing afterwards.- // `None` means no candidate fired (no budget / empty window) -> nothing to schedule -> return None.- let (day_idx, pick_driver) = pick_index(&day_weights, &winners, budget, "day")?;+ // `None` means there was nothing to schedule (no budget / empty window) -> return None.+ // `driver` names what settled the pick; `inclusion_probability` is only defined for the sampler+ // that computes one.+ let (day_idx, driver, day_inclusion_probability) = match variant.selection {+ DaySelection::PerTick => {+ let (idx, pick_driver) = pick_index(&day_weights, &winners, budget, "day")?;+ (idx, pick_driver.label(), None)+ }+ DaySelection::SystematicK => {+ let (idx, pi) =+ select_systematic_k_day(&day_weights, budget, exploration_floor, tie_tolerance)?;+ let axis = winners.get(idx).map_or("unknown", |axis| axis.as_str());+ (idx, axis, Some(pi))+ }+ };let hour = pick_hour(&stats.hod, default_hour);let time = time::Time::from_hms(hour, 0, 0).unwrap_or(time::Time::MIDNIGHT);- // day_idx is always in range (from pick_index over these vecs); `.get` keeps it panic-free.+ // day_idx is always in range (both samplers index these vecs); `.get` keeps it panic-free.let chosen_date = *dates.get(day_idx)?;let chosen_weight = day_weights.get(day_idx).copied().unwrap_or(0.0);let retry_at = chosen_date.with_time(time).assume_offset(now.offset());- // Final decision. A forced (runway-guard) pick labels itself (not the softmax winner) for honest- // back-test attribution.+ // Final decision. The inclusion probability is logged because it is the propensity this draw was+ // made under: without it the schedule cannot be evaluated off-policy afterwards, and it cannot be+ // reconstructed at analysis time because the value surface drifts between draw and analysis.logger::debug!(chosen_day = %chosen_date,chosen_hour = hour,retry_at = %retry_at,- driver = pick_driver.label(),+ combine = ?variant.combine,+ selection = ?variant.selection,+ driver = driver,+ inclusion_probability = ?day_inclusion_probability,weight = chosen_weight,- "mathmodel: decision final"+ "retry model: decision final");Some(retry_at)}-/// Adaptive retry time for a failed invoice: fetch the cluster's success stats by the-/// (standardised) error code and ask the math model when to retry.+/// Retry time for a failed invoice: fetch the cluster's success stats by the (standardised) error+/// code and ask the assigned retry model when to retry.////// `remaining_grace_days` and `remaining_budget` are resolved by the caller (from the invoice's/// grace window and retry allowance) and passed straight through to the model.////// Returns `None` on every "no opinion" case — no stats recorded for the cluster yet, a lookup/// failure (a corrupt stored key/document surfaces as one), or the model itself declining — so the-/// caller always has the static ladder to fall back on. The returned instant is UTC+/// caller always has the global fallback behind it. The returned instant is UTC/// (`OffsetDateTime`); the codebase stays in explicit UTC and only converts to a naive/// `PrimitiveDateTime` at the schedule boundary.#[cfg(feature = "v2")]-pub async fn compute_adaptive_retry_time(+pub async fn compute_model_retry_time(state: &SessionState,error_code: common_enums::StandardisedCode,remaining_grace_days: u32,remaining_budget: u32,+ variant: RetryModelVariant,) -> Option<time::OffsetDateTime> {- // Fetch the stats recorded against this error code. The store builds the cluster key and- // parses the stored document internally; `None` when the cluster has no recorded history yet.- let record = state+ // The store builds the cluster key and parses the stored document internally. A missing cluster+ // and a failed lookup both decline, but they are different problems, so they are logged apart —+ // a cluster with no history yet is the ordinary reason this path produces no time.+ let record = match state.store.get_revenue_recovery_retry_stats_store().find_revenue_recovery_retry_stats_by_error_code(error_code).await- .map_err(|error| {- logger::error!(?error, ?error_code, "adaptive retry: failed to fetch stats");- })- .ok()??;+ {+ Ok(Some(record)) => record,+ Ok(None) => {+ logger::info!(+ ?error_code,+ remaining_grace_days,+ remaining_budget,+ "retry model: no stats recorded for this cluster yet — declining"+ );+ return None;+ }+ Err(error) => {+ logger::error!(?error, ?error_code, "retry model: failed to fetch stats");+ // Counted apart from the cold-start decline above: that one is expected and shrinks as+ // clusters accumulate history, this one is the store failing and does not.+ crate::routes::metrics::REVENUE_RECOVERY_STATS_LOOKUP_FAILED.add(+ 1,+ router_env::metric_attributes!(("cluster", error_code.to_string())),+ );+ return None;+ }+ };logger::debug!(?error_code,remaining_grace_days,remaining_budget,- "adaptive retry: stats fetched — running mathmodel"+ "retry model: stats fetched — running the model");- // A configured hour outside 0..=23 is a misconfiguration; warn (so it's visible) and fall back to- // noon UTC rather than letting it silently degrade to midnight downstream.- let configured_hour = state.conf.revenue_recovery.default_retry_hour_utc.0;- let default_hour = if configured_hour <= 23 {- configured_hour- } else {- logger::warn!(- configured_hour,- "adaptive retry: revenue_recovery.default_retry_hour_utc is out of range (0-23); using noon UTC"- );- 12- };- compute_mathmodel_retry_time(+ // Each tunable validates itself and warns on the way past, so a misconfigured deployment is+ // visible rather than silently degraded. See the `resolve` methods for what each rejects.+ let retry_time = compute_predicted_retry_time(&record.stats,remaining_budget,remaining_grace_days,- default_hour,- )+ state.conf.revenue_recovery.default_retry_hour_utc.resolve(),+ variant,+ state.conf.revenue_recovery.exploration_floor.resolve(),+ state.conf.revenue_recovery.tie_tolerance.resolve(),+ );++ // Every reason the model itself declines (empty grace window, spent budget, a sampler that+ // fired nothing) is logged at debug inside the model, which is off in production. Log the+ // decline once here at info so the rate is visible; the reason stays at debug.+ if retry_time.is_none() {+ logger::info!(+ ?error_code,+ remaining_grace_days,+ remaining_budget,+ combine = ?variant.combine,+ selection = ?variant.selection,+ "retry model: declined to schedule — falling back to the cascading ladder"+ );+ }++ retry_time}-#[cfg(all(test, feature = "v2"))]-mod mathmodel_retry_time_tests {+// Split rather than `cfg(all(test, feature = "v2"))`: clippy recognises a test module by a literal+// `cfg(test)` attribute and does not look inside `all(...)`, so the combined form loses the+// in-test lint allowances (`expect_used`, `unwrap_used`, `panic`) that `.clippy.toml` grants.+#[cfg(test)]+#[cfg(feature = "v2")]+mod retry_model_tests {use super::*;- // The default retry hour the production config supplies (see `default_retry_hour_utc`); passed- // explicitly here so the tests don't depend on config plumbing.+ // The values the production config supplies, passed explicitly so the tests do not depend on+ // config plumbing. Kept in step with the defaults on `RevenueRecoverySettings`.const DEFAULT_RETRY_HOUR: u8 = 12;+ const EXPLORATION_FLOOR: f64 = 0.10;+ const TIE_TOLERANCE: f64 = 1e-4;fn ctr(n: u64, k: u64) -> SlotCounter {SlotCounter { n, k }@@ -2168,6 +2457,30 @@ mod mathmodel_retry_time_tests {(a - b).abs() <= tol}+ // Every combine x selection pairing. The contract tests below run over all four, because the+ // guarantees they assert (in-window, never panics, declines only when it should) must not depend+ // on which variant an invoice was bucketed into.+ fn all_variants() -> [RetryModelVariant; 4] {+ [+ RetryModelVariant {+ combine: DayCombine::MaxAtSoftmax,+ selection: DaySelection::PerTick,+ },+ RetryModelVariant {+ combine: DayCombine::MaxAtSoftmax,+ selection: DaySelection::SystematicK,+ },+ RetryModelVariant {+ combine: DayCombine::MaxAtScore,+ selection: DaySelection::PerTick,+ },+ RetryModelVariant {+ combine: DayCombine::MaxAtScore,+ selection: DaySelection::SystematicK,+ },+ ]+ }+#[test]fn scores_match_hand_math() {let doc = sample();@@ -2195,19 +2508,110 @@ mod mathmodel_retry_time_tests {}let dow = BTreeMap::from([(0u8, 5.0)]); // Monday dominantlet dom = BTreeMap::<u8, f64>::new(); // no month-day signal- let (weights, _) = combine_day_weight(&dates, &dow, &dom);- let argmax = weights- .iter()- .enumerate()- .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))- .map(|(i, _)| i)- .unwrap_or(0);- let winning_date = dates.get(argmax).copied().expect("argmax within window");+ for combine in [DayCombine::MaxAtSoftmax, DayCombine::MaxAtScore] {+ let (weights, _) = combine_day_weight(&dates, &dow, &dom, combine);+ let argmax = weights+ .iter()+ .enumerate()+ .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))+ .map(|(i, _)| i)+ .unwrap_or(0);+ let winning_date = dates.get(argmax).copied().expect("argmax within window");+ assert_eq!(+ winning_date, start,+ "{combine:?}: Monday's dominant score must make the Monday date win"+ );+ assert_eq!(winning_date.weekday().number_days_from_monday(), 0);+ }+ }++ fn window_from(year: i32, month: time::Month, day: u8, len: usize) -> Vec<time::Date> {+ let start = time::Date::from_calendar_date(year, month, day).expect("valid calendar date");+ let mut dates = vec![start];+ while dates.len() < len {+ let next = dates+ .last()+ .and_then(|d| d.next_day())+ .expect("next calendar day exists");+ dates.push(next);+ }+ dates+ }++ #[test]+ fn combines_disagree_because_recurrence_dilutes_the_weekday_axis() {+ // The two combines differ only by a per-axis offset, and under MaxAtSoftmax that offset+ // carries a structural term: softmaxing the weekday axis OVER THE CANDIDATE DAYS splits a+ // weekday's mass across its recurrences, while a day-of-month occurs once in any window of+ // <= 31 days and keeps all of its. So the same evidence ranks differently, and the gap grows+ // with the window. 2026-08-25 + 14 days holds two Fridays and one 1st.+ let dates = window_from(2026, time::Month::August, 25, 14);+ let dow = BTreeMap::from([(4u8, 9.21)]); // Friday, decisive within its axis+ let dom = BTreeMap::from([(0u8, 5.09)]); // the 1st, a narrower lead within its axis+ let top = |w: &[f64]| {+ w.iter()+ .enumerate()+ .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))+ .map(|(i, _)| i)+ .unwrap_or(0)+ };++ let (a_weights, _) = combine_day_weight(&dates, &dow, &dom, DayCombine::MaxAtSoftmax);+ let (b_weights, _) = combine_day_weight(&dates, &dow, &dom, DayCombine::MaxAtScore);+ let a_top = dates.get(top(&a_weights)).copied().expect("top in window");+ let b_top = dates.get(top(&b_weights)).copied().expect("top in window");++ assert_eq!(a_top.day(), 1, "MaxAtSoftmax should favour the unique 1st");assert_eq!(- winning_date, start,- "Monday's dominant score must make the Monday date win"+ b_top.weekday().number_days_from_monday(),+ 4,+ "MaxAtScore compares raw scores, so the higher-scoring Friday should win"+ );+ assert_ne!(+ a_top, b_top,+ "the two combines must be distinguishable here");- assert_eq!(winning_date.weekday().number_days_from_monday(), 0);+ }++ #[test]+ fn empty_axis_floors_the_ranking_under_max_at_softmax() {+ // COLD START. An axis with no recorded history scores 0.0 everywhere, and under+ // MaxAtSoftmax that softmaxes to a UNIFORM 1/n — which the `max` then applies as a floor.+ // Any preference the live axis expresses below 1/n is erased: here the Thursdays (score 2.0)+ // collapse onto days with no signal at all, leaving two distinct weights where the raw scores+ // have three. Under systematic-k those flattened days form one tie group and split their+ // probability equally, so the live axis's ordering among them is gone, not merely compressed.+ // MaxAtScore floors at a raw 0.0 instead and keeps the ordering.+ let dates = window_from(2026, time::Month::August, 25, 14);+ let dow_only = BTreeMap::from([(0u8, 5.0), (3u8, 2.0)]); // Monday strong, Thursday mild+ let empty = BTreeMap::<u8, f64>::new();+ let (a_weights, _) =+ combine_day_weight(&dates, &dow_only, &empty, DayCombine::MaxAtSoftmax);+ let (b_weights, _) = combine_day_weight(&dates, &dow_only, &empty, DayCombine::MaxAtScore);++ // index 2 = Thursday 27 Aug (score 2.0), index 0 = Tuesday 25 Aug (no signal).+ let a_thursday = a_weights.get(2).copied().expect("index in window");+ let a_unscored = a_weights.first().copied().expect("index in window");+ let b_thursday = b_weights.get(2).copied().expect("index in window");+ let b_unscored = b_weights.first().copied().expect("index in window");++ assert!(+ approx(a_thursday, a_unscored, 1e-12),+ "MaxAtSoftmax should floor both at the uniform 1/n: {a_thursday} vs {a_unscored}"+ );+ assert!(+ b_thursday > b_unscored,+ "MaxAtScore should keep the Thursday above an unscored day: {b_thursday} vs {b_unscored}"+ );++ let distinct = |w: &[f64]| {+ let mut v: Vec<u64> = w.iter().map(|x| x.to_bits()).collect();+ v.sort_unstable();+ v.dedup();+ v.len()+ };+ assert_eq!(distinct(&a_weights), 2, "A flattens to two levels");+ assert_eq!(distinct(&b_weights), 3, "B keeps all three levels");}#[test]@@ -2229,18 +2633,28 @@ mod mathmodel_retry_time_tests {// never panics — for both rich and empty stats. (Window starts on the NEXT day; the bounds// carry a 1-day slack so a midnight tick between captures can't flake it.)let grace: u32 = 14;- for stats in [sample(), StatsDocument::default()] {- for _ in 0..200 {- let before = common_utils::date_time::now().assume_utc();- let dt = compute_mathmodel_retry_time(&stats, 3, grace, DEFAULT_RETRY_HOUR)+ for variant in all_variants() {+ for stats in [sample(), StatsDocument::default()] {+ for _ in 0..200 {+ let before = common_utils::date_time::now().assume_utc();+ let dt = compute_predicted_retry_time(+ &stats,+ 3,+ grace,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE,+ ).expect("grace > 1 => Some");- let last = (before + time::Duration::days(i64::from(grace) + 1)).date();- assert!(- dt.date() > before.date() && dt.date() <= last,- "date {} out of window",- dt.date()- );- assert!(dt.hour() < 24);+ let last = (before + time::Duration::days(i64::from(grace) + 1)).date();+ assert!(+ dt.date() > before.date() && dt.date() <= last,+ "{variant:?}: date {} out of window",+ dt.date()+ );+ assert!(dt.hour() < 24);+ }}}}@@ -2249,34 +2663,81 @@ mod mathmodel_retry_time_tests {fn window_starts_next_day() {// Failure day is excluded: the earliest candidate is tomorrow. grace COUNTS today, so grace 2// = today + 1 future day (tomorrow) — assert the pick is that next day, not the failure day.- let before = common_utils::date_time::now().assume_utc();- let dt = compute_mathmodel_retry_time(&sample(), 3, 2, DEFAULT_RETRY_HOUR)+ for variant in all_variants() {+ let before = common_utils::date_time::now().assume_utc();+ let dt = compute_predicted_retry_time(+ &sample(),+ 3,+ 2,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE,+ ).expect("grace 2 => Some");- assert!(- dt.date() > before.date(),- "expected next day, got {} (today {})",- dt.date(),- before.date()- );- assert!(dt.date() <= (before + time::Duration::days(2)).date());+ assert!(+ dt.date() > before.date(),+ "{variant:?}: expected next day, got {} (today {})",+ dt.date(),+ before.date()+ );+ assert!(dt.date() <= (before + time::Duration::days(2)).date());+ }}#[test]fn grace_zero_and_one_return_none() {// grace COUNTS today; grace 0 = no grace, grace 1 = today only -> no future day -> None (v1).- assert!(compute_mathmodel_retry_time(&sample(), 3, 0, DEFAULT_RETRY_HOUR).is_none());- assert!(compute_mathmodel_retry_time(&sample(), 3, 1, DEFAULT_RETRY_HOUR).is_none());+ for variant in all_variants() {+ assert!(compute_predicted_retry_time(+ &sample(),+ 3,+ 0,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE+ )+ .is_none());+ assert!(compute_predicted_retry_time(+ &sample(),+ 3,+ 1,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE+ )+ .is_none());+ }}#[test]fn zero_budget_returns_none() {// No retries left: the model must NOT hand back a date (pick_index with budget 0 would// otherwise fall through to the last grace day). Guard holds for any grace / stats shape.- assert!(compute_mathmodel_retry_time(&sample(), 0, 14, DEFAULT_RETRY_HOUR).is_none());- assert!(- compute_mathmodel_retry_time(&StatsDocument::default(), 0, 30, DEFAULT_RETRY_HOUR)- .is_none()- );+ for variant in all_variants() {+ assert!(compute_predicted_retry_time(+ &sample(),+ 0,+ 14,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE+ )+ .is_none());+ assert!(compute_predicted_retry_time(+ &StatsDocument::default(),+ 0,+ 30,+ DEFAULT_RETRY_HOUR,+ variant,+ EXPLORATION_FLOOR,+ TIE_TOLERANCE,+ )+ .is_none());+ }}#[test]@@ -2317,8 +2778,16 @@ mod mathmodel_retry_time_tests {let corrupt = doc_with(&[(0, 1, 100), (3, 2, 50)], &[(5, 1, 80)], &[(9, 1, 30)]);let before = common_utils::date_time::now().assume_utc();for _ in 0..50 {- let dt = compute_mathmodel_retry_time(&corrupt, 3, 14, DEFAULT_RETRY_HOUR)- .expect("grace > 1 => Some");+ let dt = compute_predicted_retry_time(+ &corrupt,+ 3,+ 14,+ DEFAULT_RETRY_HOUR,+ RetryModelVariant::default(),+ EXPLORATION_FLOOR,+ TIE_TOLERANCE,+ )+ .expect("grace > 1 => Some");assert!(dt.date() > before.date() && dt.hour() < 24);}}@@ -2334,8 +2803,16 @@ mod mathmodel_retry_time_tests {#[test]fn grace_is_capped_at_max() {let before = common_utils::date_time::now().assume_utc();- let dt = compute_mathmodel_retry_time(&sample(), 3, 365, DEFAULT_RETRY_HOUR)- .expect("grace > 1 => Some");+ let dt = compute_predicted_retry_time(+ &sample(),+ 3,+ 365,+ DEFAULT_RETRY_HOUR,+ RetryModelVariant::default(),+ EXPLORATION_FLOOR,+ TIE_TOLERANCE,+ )+ .expect("grace > 1 => Some");let last = (before + time::Duration::days(i64::from(MAX_GRACE_DAYS) + 1)).date();assert!(dt.date() <= last,@@ -2352,4 +2829,322 @@ mod mathmodel_retry_time_tests {assert_eq!(idx, 0);assert!(matches!(driver, PickDriver::RunwayGuard));}++ // A window of distinct descending values, so the greedy pour has an unambiguous ranking.+ fn descending_values(n: usize) -> Vec<f64> {+ let mut value = 1.0;+ (0..n)+ .map(|_| {+ let current = value;+ value -= 0.01;+ current+ })+ .collect()+ }++ #[test]+ fn inclusion_probabilities_spend_the_budget_exactly() {+ // The line must be exactly k units long and every segment a usable probability.+ // `expected` is written out, not recomputed, so the cap is asserted rather than mirrored.+ for (n, budget, eps, expected) in [+ (30, 15, 0.10, 15.0),+ (30, 15, 0.00, 15.0),+ (7, 3, 0.25, 3.0),+ (31, 1, 0.10, 1.0),+ (5, 5, 0.10, 5.0),+ (5, 9, 0.10, 5.0), // budget wider than the window: capped at n+ ] {+ let pi = inclusion_probabilities(&descending_values(n), budget, eps, TIE_TOLERANCE);+ let total: f64 = pi.iter().sum();+ assert!(+ approx(total, expected, 1e-9),+ "n={n} budget={budget} eps={eps}: Σπ={total}, expected {expected}"+ );+ assert!(+ pi.iter().all(|&p| (0.0..=1.0).contains(&p)),+ "n={n} budget={budget} eps={eps}: π outside [0,1]: {pi:?}"+ );+ }+ }++ #[test]+ fn epsilon_above_k_over_n_is_capped_not_trusted() {+ // ε > k/n makes the remainder negative, so the pour emits negative probabilities while+ // still summing to k and returning k days — nothing notices, but the cumsum stops rising.+ let n = 30;+ let budget = 15; // k/n = 0.5+ for eps in [0.55, 0.60, 0.95] {+ let pi = inclusion_probabilities(&descending_values(n), budget, eps, TIE_TOLERANCE);+ let min = pi.iter().copied().fold(f64::MAX, f64::min);+ assert!(+ min >= 0.0,+ "eps={eps} produced a negative probability: {min}"+ );+ assert!(approx(pi.iter().sum::<f64>(), f64::from(budget), 1e-9));+ }+ }++ #[test]+ fn tied_values_receive_equal_probability() {+ // Ranking alone breaks ties by array position. Equal evidence must mean equal odds.+ let values = vec![0.9, 0.1809, 0.1809, 0.1809, 0.1809, 0.05];+ let pi = inclusion_probabilities(&values, 3, 0.10, TIE_TOLERANCE);+ let tied = pi.get(1..5).expect("tied group within range");+ let first = tied.first().copied().expect("non-empty tied group");+ assert!(+ tied.iter().all(|&p| approx(p, first, 1e-12)),+ "tied days drew unequal probabilities: {tied:?}"+ );+ assert!(approx(pi.iter().sum::<f64>(), 3.0, 1e-9));+ }++ #[test]+ fn tie_tolerance_merges_only_within_its_own_width() {+ // Two days straddling the rank the pour runs out at — the only place merging changes+ // anything. Both directions asserted: swallowing the second would reallocate probability+ // between days the model does rank apart.+ let inside = vec![0.5 + TIE_TOLERANCE / 10.0, 0.5, 0.2, 0.1];+ let pi = inclusion_probabilities(&inside, 2, 0.10, TIE_TOLERANCE);+ let first = pi.first().copied().expect("index in range");+ let second = pi.get(1).copied().expect("index in range");+ assert!(+ approx(first, second, 1e-12),+ "values within the tolerance must split: {first} vs {second}"+ );++ let outside = vec![0.5 + TIE_TOLERANCE * 1000.0, 0.5, 0.2, 0.1];+ let pi = inclusion_probabilities(&outside, 2, 0.10, TIE_TOLERANCE);+ let first = pi.first().copied().expect("index in range");+ let second = pi.get(1).copied().expect("index in range");+ assert!(+ first > second,+ "values outside the tolerance must keep their order: {first} vs {second}"+ );++ // Splitting redistributes inside the group, so the budget is spent exactly either way.+ for values in [inside, outside] {+ let total: f64 = inclusion_probabilities(&values, 2, 0.10, TIE_TOLERANCE)+ .iter()+ .sum();+ assert!(+ approx(total, 2.0, 1e-9),+ "budget not spent exactly: {total}"+ );+ }+ }++ #[test]+ fn control_arm_is_pinned_and_does_not_track_the_default() {+ // AdaptiveRetry is persisted on live invoices, so it must keep its pairing whatever the+ // default becomes — otherwise an in-flight invoice switches algorithm mid-recovery.+ assert_eq!(+ RetryModelVariant::from(common_enums::RevenueRecoveryABAlgorithm::AdaptiveRetry),+ RetryModelVariant {+ combine: DayCombine::MaxAtSoftmax,+ selection: DaySelection::PerTick,+ }+ );+ }++ #[test]+ fn each_arm_varies_at_most_one_axis_from_its_reference() {+ // Attributability: SystematicKMaxAtSoftmax moves only the sampler from control, and+ // SystematicKMaxAtScore only the combine from it. An arm moving both against both+ // references leaves nothing able to say which change caused a result.+ use common_enums::RevenueRecoveryABAlgorithm as Arm;+ let control = RetryModelVariant::from(Arm::AdaptiveRetry);+ let softmax_k = RetryModelVariant::from(Arm::SystematicKMaxAtSoftmax);+ let score_k = RetryModelVariant::from(Arm::SystematicKMaxAtScore);++ let axes_differing = |a: RetryModelVariant, b: RetryModelVariant| {+ usize::from(a.combine != b.combine) + usize::from(a.selection != b.selection)+ };+ assert_eq!(+ axes_differing(control, softmax_k),+ 1,+ "sampler comparison must hold the combine fixed"+ );+ assert_eq!(+ axes_differing(softmax_k, score_k),+ 1,+ "combine comparison must hold the sampler fixed"+ );+ }++ #[test]+ fn arms_map_to_distinct_variants() {+ // Two arms on the same pairing compare an arm against itself, which reads as a null.+ use strum::IntoEnumIterator;+ let mut seen: Vec<RetryModelVariant> = Vec::new();+ for arm in common_enums::RevenueRecoveryABAlgorithm::iter() {+ let variant = RetryModelVariant::from(arm);+ assert!(+ !seen.contains(&variant),+ "{arm:?} duplicates an earlier arm's variant: {variant:?}"+ );+ seen.push(variant);+ }+ }++ #[test]+ fn arm_config_strings_are_pinned() {+ // These are the values configured in the Superposition workspace, derived by strum rather+ // than written out — the trailing K is the kind of thing a derive can render either way.+ use common_enums::RevenueRecoveryABAlgorithm as Arm;+ for (arm, expected) in [+ (Arm::AdaptiveRetry, "adaptive_retry"),+ (Arm::SystematicKMaxAtSoftmax, "systematic_k_max_at_softmax"),+ (Arm::SystematicKMaxAtScore, "systematic_k_max_at_score"),+ ] {+ assert_eq!(arm.to_string(), expected);+ assert_eq!(+ expected.parse::<Arm>().expect("config string must parse"),+ arm,+ "a config value that does not round-trip falls back to the configured default, \+ silently enrolling the invoice in an arm nobody chose"+ );+ }+ }++ #[test]+ fn entropy_seams_match_what_the_sampler_assumes() {+ // Two `common_utils` contracts the exactly-k guarantee rests on and the type system does+ // not enforce, pinned here so a seam change fails in this module.++ // u ∈ [0, 1): at 1.0 the last probe sits at k, off the end of a k-unit line. Probed+ // statistically, so this catches a widened range, not the exact endpoint.+ for _ in 0..10_000 {+ let u = common_utils::generate_random_f64_unit();+ assert!((0.0..1.0).contains(&u), "u outside [0, 1): {u}");+ }++ // `order` addresses the line, so a duplicate would lay one day down twice and drop+ // another, breaking both the marginals and the distinct-days guarantee.+ for length in [1usize, 2, 7, 29, 31] {+ let order = common_utils::generate_random_permutation(length);+ assert_eq!(order.len(), length, "wrong length for {length}");+ let mut sorted = order.clone();+ sorted.sort_unstable();+ assert!(+ sorted.iter().copied().eq(0..length),+ "not a permutation of 0..{length}: {order:?}"+ );+ }+ }++ #[test]+ fn systematic_sample_always_returns_exactly_k_distinct_days() {+ // G1 is geometric, so it holds on EVERY draw, not on average — including the endpoints+ // u = 0 and u → 1⁻ where probes sit exactly on segment boundaries.+ let n = 30;+ let budget: u32 = 15;+ let pi = inclusion_probabilities(&descending_values(n), budget, 0.10, TIE_TOLERANCE);+ let order: Vec<usize> = (0..n).collect();+ let expected_days = usize::try_from(budget).unwrap_or(0);+ for step in 0..1000 {+ let u = f64::from(step) / 1000.0;+ let selected = systematic_sample(&pi, u, &order, expected_days);+ assert_eq!(+ selected.len(),+ expected_days,+ "u={u} selected {} days, expected {budget}",+ selected.len()+ );+ let mut distinct = selected.clone();+ distinct.dedup();+ assert_eq!(distinct.len(), selected.len(), "u={u} repeated a day");+ }+ }++ #[test]+ fn realised_selection_rate_matches_the_promised_probability() {+ // G2: day i is selected with probability exactly πᵢ. Checked as a frequency over draws, so+ // the tolerance is sampling noise on 20k draws, not the guarantee's own error.+ let n = 12;+ let values = descending_values(n);+ let pi = inclusion_probabilities(&values, 4, 0.10, TIE_TOLERANCE);+ let order: Vec<usize> = (0..n).collect();+ let draws: u32 = 20_000;+ let mut hits = vec![0u32; n];+ for step in 0..draws {+ let u = (f64::from(step) + 0.5) / f64::from(draws);+ for day in systematic_sample(&pi, u, &order, 4) {+ if let Some(count) = hits.get_mut(day) {+ *count += 1;+ }+ }+ }+ for (day, (&count, &promised)) in hits.iter().zip(pi.iter()).enumerate() {+ let realised = f64::from(count) / f64::from(draws);+ assert!(+ approx(realised, promised, 0.01),+ "day {day}: realised {realised}, promised {promised}"+ );+ }+ }++ #[test]+ fn exploration_floor_keeps_every_day_reachable_in_the_schedule() {+ // What ε buys: every day lands in SOME schedule, including the worst-rated. Asserted on+ // the draw, since which day the caller acts on is a different question — see below.+ let n = 10;+ let pi = inclusion_probabilities(&descending_values(n), 3, 0.10, TIE_TOLERANCE);+ let order: Vec<usize> = (0..n).collect();+ let mut seen = vec![false; n];+ for step in 0..2_000 {+ let u = (f64::from(step) + 0.5) / 2000.0;+ for day in systematic_sample(&pi, u, &order, 3) {+ if let Some(hit) = seen.get_mut(day) {+ *hit = true;+ }+ }+ }+ assert!(+ seen.iter().all(|&hit| hit),+ "a day was never reachable despite the exploration floor: {seen:?}"+ );+ }++ #[test]+ fn returned_day_is_the_nearest_one_drawn() {+ // On-demand returns the SOONEST day, so a day pinned at π = 1.0 near the front comes back+ // every time: ε spreads the schedule, not the day acted on. Front-loaded values make the+ // pick deterministic; only back-loaded ones let it move.+ let front_best = descending_values(10);+ for _ in 0..200 {+ let (idx, pi) =+ select_systematic_k_day(&front_best, 3, 0.10, TIE_TOLERANCE).expect("budget > 0");+ assert_eq!(+ idx, 0,+ "a pinned soonest day must always be the one returned"+ );+ assert!(approx(pi, 1.0, 1e-9), "day 0 should be pinned, got π={pi}");+ }++ let back_best: Vec<f64> = descending_values(10).into_iter().rev().collect();+ let mut distinct = std::collections::BTreeSet::new();+ for _ in 0..400 {+ let (idx, _) =+ select_systematic_k_day(&back_best, 3, 0.10, TIE_TOLERANCE).expect("budget > 0");+ distinct.insert(idx);+ }+ assert!(+ distinct.len() > 1,+ "back-loaded values should not pin the returned day: {distinct:?}"+ );+ }++ #[test]+ fn systematic_k_day_declines_only_when_there_is_nothing_to_schedule() {+ assert!(select_systematic_k_day(&[], 5, 0.10, TIE_TOLERANCE).is_none());+ assert!(select_systematic_k_day(&[1.0, 1.0], 0, 0.10, TIE_TOLERANCE).is_none());+ // Budget wider than the window pins every day at 1.0, so the soonest day is always day 0.+ let (idx, pi) =+ select_systematic_k_day(&[0.1, 0.2, 0.3], 9, 0.10, TIE_TOLERANCE).expect("budget > 0");+ assert_eq!(idx, 0);+ assert!(+ approx(pi, 1.0, 1e-9),+ "every day should be certain, got {pi}"+ );+ }}