tasker-orchestration 0.1.7

Orchestration system for tasker workflow coordination
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
//! # Backoff Calculator
//!
//! Handles all backoff logic for step retries with exponential backoff calculations.
//!
//! ## Overview
//!
//! The BackoffCalculator provides unified handling of both server-requested backoff
//! (via Retry-After headers) and exponential backoff calculations. It integrates
//! with the model layer to update step backoff settings and publishes events
//! for observability.
//!
//! ## Key Features
//!
//! - **Exponential Backoff**: Configurable base delay with exponential growth
//! - **Server-Requested Backoff**: Honor Retry-After headers from APIs
//! - **Jitter Support**: Optional randomization to prevent thundering herd
//! - **Maximum Delay Caps**: Prevent infinite backoff growth
//! - **Event Publishing**: Observability for backoff decisions
//!
//! ## Rails Heritage
//!
//! Migrated from `lib/tasker/orchestration/backoff_calculator.rb` with enhanced
//! type safety and performance optimizations.

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::collections::HashMap;
use std::sync::Arc;
// TAS-61 Phase 6C/6D: V2 configuration is canonical
use tasker_shared::config::tasker::TaskerConfig;
use uuid::Uuid;

/// Configuration for backoff calculation behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackoffCalculatorConfig {
    /// Base delay in seconds for exponential backoff
    pub base_delay_seconds: u32,
    /// Maximum delay cap in seconds
    pub max_delay_seconds: u32,
    /// Exponential multiplier (default: 2.0)
    pub multiplier: f64,
    /// Whether to add jitter to prevent thundering herd
    pub jitter_enabled: bool,
    /// Maximum jitter percentage (0.0 to 1.0)
    pub max_jitter: f64,
}

impl Default for BackoffCalculatorConfig {
    fn default() -> Self {
        Self {
            base_delay_seconds: 1,
            max_delay_seconds: 300, // 5 minutes
            multiplier: 2.0,
            jitter_enabled: true,
            max_jitter: 0.1, // 10% jitter
        }
    }
}

impl From<Arc<TaskerConfig>> for BackoffCalculatorConfig {
    fn from(config: Arc<TaskerConfig>) -> BackoffCalculatorConfig {
        // Use the first default backoff value as base delay, or fallback to 1 second
        let base_delay_seconds = config
            .common
            .backoff
            .default_backoff_seconds
            .first()
            .copied()
            .unwrap_or(1);

        BackoffCalculatorConfig {
            base_delay_seconds,
            max_delay_seconds: config.common.backoff.max_backoff_seconds,
            multiplier: config.common.backoff.backoff_multiplier,
            jitter_enabled: config.common.backoff.jitter_enabled,
            max_jitter: config.common.backoff.jitter_max_percentage,
        }
    }
}

impl From<&TaskerConfig> for BackoffCalculatorConfig {
    fn from(config: &TaskerConfig) -> BackoffCalculatorConfig {
        // Use the first default backoff value as base delay, or fallback to 1 second
        let base_delay_seconds = config
            .common
            .backoff
            .default_backoff_seconds
            .first()
            .copied()
            .unwrap_or(1);

        BackoffCalculatorConfig {
            base_delay_seconds,
            max_delay_seconds: config.common.backoff.max_backoff_seconds,
            multiplier: config.common.backoff.backoff_multiplier,
            jitter_enabled: config.common.backoff.jitter_enabled,
            max_jitter: config.common.backoff.jitter_max_percentage,
        }
    }
}

/// Context for backoff calculation decisions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackoffContext {
    /// HTTP response headers (if applicable)
    pub headers: HashMap<String, String>,
    /// Error context that triggered the backoff
    pub error_context: Option<String>,
    /// Metadata for backoff decision
    pub metadata: HashMap<String, serde_json::Value>,
}

impl Default for BackoffContext {
    fn default() -> Self {
        Self::new()
    }
}

impl BackoffContext {
    /// Create a new backoff context
    pub fn new() -> Self {
        Self {
            headers: HashMap::new(),
            error_context: None,
            metadata: HashMap::new(),
        }
    }

    /// Add a header to the context
    pub fn with_header(mut self, key: String, value: String) -> Self {
        self.headers.insert(key, value);
        self
    }

    /// Add error context
    pub fn with_error(mut self, error: String) -> Self {
        self.error_context = Some(error);
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: String, value: serde_json::Value) -> Self {
        self.metadata.insert(key, value);
        self
    }
}

/// BackoffCalculator handles all backoff logic for step retries
///
/// This component provides unified handling of both server-requested backoff
/// (via Retry-After headers) and exponential backoff calculations.
/// It integrates with the workflow step model to apply backoff settings.
#[derive(Clone, Debug)]
pub struct BackoffCalculator {
    config: BackoffCalculatorConfig,
    pool: PgPool,
}

impl BackoffCalculator {
    /// Create a new BackoffCalculator with configuration
    pub fn new(config: BackoffCalculatorConfig, pool: PgPool) -> Self {
        Self { config, pool }
    }

    /// Create a BackoffCalculator with default configuration
    pub fn with_defaults(pool: PgPool) -> Self {
        Self::new(BackoffCalculatorConfig::default(), pool)
    }

    /// Calculate and apply backoff for a step based on response context
    ///
    /// This method determines whether to use server-requested backoff or
    /// exponential backoff, calculates the appropriate delay, and updates
    /// the step with backoff information.
    pub async fn calculate_and_apply_backoff(
        &self,
        step_uuid: &Uuid,
        context: BackoffContext,
    ) -> Result<BackoffResult, BackoffError> {
        // Check for server-requested backoff first
        if let Some(retry_after) = self.extract_retry_after_header(&context) {
            self.apply_server_requested_backoff(step_uuid, retry_after)
                .await
        } else {
            // Fall back to exponential backoff
            self.apply_exponential_backoff(step_uuid, &context).await
        }
    }

    /// Extract Retry-After header from context
    fn extract_retry_after_header(&self, context: &BackoffContext) -> Option<u32> {
        // Find retry-after header (case-insensitive)
        let retry_after_value = context
            .headers
            .iter()
            .find(|(key, _)| key.to_lowercase() == "retry-after")
            .map(|(_, value)| value)?;

        // Try parsing as seconds (integer)
        if let Ok(seconds) = retry_after_value.parse::<u32>() {
            return Some(seconds);
        }

        // Try parsing as HTTP date (RFC 2822)
        if let Ok(date) = DateTime::parse_from_rfc2822(retry_after_value) {
            let now = Utc::now();
            let diff = date.signed_duration_since(now);
            if diff.num_seconds() > 0 {
                return Some(diff.num_seconds() as u32);
            }
        }

        None
    }

    /// TAS-57: Atomically update backoff with row-level locking
    ///
    /// This method uses SELECT FOR UPDATE to acquire a row-level lock before updating,
    /// preventing race conditions when multiple orchestrators process the same step failure.
    /// Also updates last_attempted_at to ensure timing consistency with SQL calculations.
    async fn update_backoff_atomic(
        &self,
        step_uuid: &Uuid,
        delay_seconds: u32,
    ) -> Result<(), BackoffError> {
        // Begin transaction
        let mut tx = self.pool.begin().await.map_err(BackoffError::Database)?;

        // Acquire row-level lock with SELECT FOR UPDATE
        // This blocks other transactions from modifying this row until we commit
        sqlx::query!(
            "SELECT workflow_step_uuid
             FROM tasker.workflow_steps
             WHERE workflow_step_uuid = $1
             FOR UPDATE",
            step_uuid
        )
        .fetch_one(&mut *tx)
        .await
        .map_err(BackoffError::Database)?;

        // Update both backoff and timestamp within locked transaction
        // The timestamp ensures SQL fallback calculations use consistent timing
        sqlx::query!(
            "UPDATE tasker.workflow_steps
             SET backoff_request_seconds = $1,
                 last_attempted_at = NOW(),
                 updated_at = NOW()
             WHERE workflow_step_uuid = $2",
            delay_seconds as i32,
            step_uuid
        )
        .execute(&mut *tx)
        .await
        .map_err(BackoffError::Database)?;

        // Commit transaction and release lock
        tx.commit().await.map_err(BackoffError::Database)?;

        Ok(())
    }

    /// Apply server-requested backoff from Retry-After header
    async fn apply_server_requested_backoff(
        &self,
        step_uuid: &Uuid,
        retry_after_seconds: u32,
    ) -> Result<BackoffResult, BackoffError> {
        // Cap the server-requested delay
        let delay_seconds = retry_after_seconds.min(self.config.max_delay_seconds);

        // TAS-57: Use atomic update instead of direct query
        self.update_backoff_atomic(step_uuid, delay_seconds).await?;

        Ok(BackoffResult {
            delay_seconds,
            backoff_type: BackoffType::ServerRequested,
            next_retry_at: Utc::now() + Duration::seconds(delay_seconds as i64),
        })
    }

    /// Apply exponential backoff based on attempt count
    async fn apply_exponential_backoff(
        &self,
        step_uuid: &Uuid,
        _context: &BackoffContext,
    ) -> Result<BackoffResult, BackoffError> {
        // Get current attempt count
        let step = sqlx::query!(
            "SELECT attempts FROM tasker.workflow_steps WHERE workflow_step_uuid = $1",
            step_uuid
        )
        .fetch_one(&self.pool)
        .await
        .map_err(BackoffError::Database)?;

        let attempts = step.attempts.unwrap_or(0) as u32;

        // Calculate exponential delay: base_delay * multiplier^attempts
        let base_delay = self.config.base_delay_seconds as f64;
        let multiplier = self.config.multiplier;
        let exponential_delay = base_delay * multiplier.powi(attempts as i32);

        // Apply maximum cap
        let mut delay_seconds = exponential_delay.min(self.config.max_delay_seconds as f64) as u32;

        // Add jitter if enabled
        if self.config.jitter_enabled {
            delay_seconds = self.apply_jitter(delay_seconds);
        }

        // TAS-57: Use atomic update instead of direct query
        self.update_backoff_atomic(step_uuid, delay_seconds).await?;

        Ok(BackoffResult {
            delay_seconds,
            backoff_type: BackoffType::Exponential,
            next_retry_at: Utc::now() + Duration::seconds(delay_seconds as i64),
        })
    }

    /// Apply jitter to delay to prevent thundering herd
    fn apply_jitter(&self, delay_seconds: u32) -> u32 {
        use rand::Rng;

        let jitter_range = (delay_seconds as f64 * self.config.max_jitter) as u32;
        if jitter_range == 0 {
            return delay_seconds;
        }

        let mut rng = rand::rng();
        let jitter = rng.random_range(0..=jitter_range);

        // Add or subtract jitter randomly
        if rng.random_bool(0.5) {
            delay_seconds.saturating_add(jitter)
        } else {
            delay_seconds.saturating_sub(jitter)
        }
    }

    /// Check if a step is ready to retry after backoff period
    pub async fn is_ready_to_retry(&self, step_uuid: Uuid) -> Result<bool, BackoffError> {
        let step = sqlx::query!(
            r#"
            SELECT backoff_request_seconds, last_attempted_at
            FROM tasker.workflow_steps
            WHERE workflow_step_uuid = $1
            "#,
            step_uuid
        )
        .fetch_one(&self.pool)
        .await
        .map_err(BackoffError::Database)?;

        match (step.backoff_request_seconds, step.last_attempted_at) {
            (Some(backoff_seconds), Some(last_attempt)) => {
                let retry_available_at = last_attempt + Duration::seconds(backoff_seconds as i64);
                Ok(Utc::now().naive_utc() >= retry_available_at)
            }
            _ => Ok(true), // No backoff or no last attempt, ready to retry
        }
    }

    /// Clear backoff for a step (e.g., after successful execution)
    pub async fn clear_backoff(&self, step_uuid: Uuid) -> Result<(), BackoffError> {
        sqlx::query!(
            "UPDATE tasker.workflow_steps SET backoff_request_seconds = NULL WHERE workflow_step_uuid = $1",
            step_uuid
        )
        .execute(&self.pool)
        .await
        .map_err(BackoffError::Database)?;

        Ok(())
    }
}

/// Result of a backoff calculation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackoffResult {
    /// Calculated delay in seconds
    pub delay_seconds: u32,
    /// Type of backoff applied
    pub backoff_type: BackoffType,
    /// When the step will be ready for retry
    pub next_retry_at: DateTime<Utc>,
}

/// Type of backoff calculation applied
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BackoffType {
    /// Server requested via Retry-After header
    ServerRequested,
    /// Exponential backoff with optional jitter
    Exponential,
}

/// Errors that can occur during backoff calculation
#[derive(Debug, thiserror::Error)]
pub enum BackoffError {
    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),

    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),

    #[error("Step not found: {0}")]
    StepNotFound(i64),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_backoff_config_default() {
        let config = BackoffCalculatorConfig::default();
        assert_eq!(config.base_delay_seconds, 1);
        assert_eq!(config.max_delay_seconds, 300);
        assert_eq!(config.multiplier, 2.0);
        assert!(config.jitter_enabled);
        assert_eq!(config.max_jitter, 0.1);
    }

    #[test]
    fn test_backoff_context_builder() {
        let context = BackoffContext::new()
            .with_header("retry-after".to_string(), "60".to_string())
            .with_error("Rate limited".to_string());

        assert_eq!(context.headers.get("retry-after"), Some(&"60".to_string()));
        assert_eq!(context.error_context, Some("Rate limited".to_string()));
    }

    #[test]
    fn test_extract_retry_after_seconds() {
        let context =
            BackoffContext::new().with_header("retry-after".to_string(), "120".to_string());

        // Test the parsing logic directly without creating a calculator
        let headers = &context.headers;
        let retry_after = headers
            .get("retry-after")
            .and_then(|value| value.parse::<u32>().ok());

        assert_eq!(retry_after, Some(120));
    }

    #[test]
    fn test_backoff_context_default() {
        let context = BackoffContext::default();
        assert!(context.headers.is_empty());
        assert!(context.error_context.is_none());
        assert!(context.metadata.is_empty());
    }

    #[test]
    fn test_backoff_context_with_metadata() {
        let context = BackoffContext::new()
            .with_metadata("retry_count".to_string(), serde_json::json!(3))
            .with_metadata("source".to_string(), serde_json::json!("api_gateway"));

        assert_eq!(context.metadata.len(), 2);
        assert_eq!(context.metadata["retry_count"], serde_json::json!(3));
        assert_eq!(context.metadata["source"], serde_json::json!("api_gateway"));
    }

    #[test]
    fn test_backoff_context_full_builder_chain() {
        let context = BackoffContext::new()
            .with_header("Retry-After".to_string(), "60".to_string())
            .with_header("X-RateLimit-Reset".to_string(), "1700000000".to_string())
            .with_error("429 Too Many Requests".to_string())
            .with_metadata("endpoint".to_string(), serde_json::json!("/api/v1/tasks"));

        assert_eq!(context.headers.len(), 2);
        assert!(context.error_context.is_some());
        assert_eq!(context.metadata.len(), 1);
    }

    #[test]
    fn test_backoff_config_custom_values() {
        let config = BackoffCalculatorConfig {
            base_delay_seconds: 5,
            max_delay_seconds: 600,
            multiplier: 3.0,
            jitter_enabled: false,
            max_jitter: 0.2,
        };

        assert_eq!(config.base_delay_seconds, 5);
        assert_eq!(config.max_delay_seconds, 600);
        assert_eq!(config.multiplier, 3.0);
        assert!(!config.jitter_enabled);
        assert_eq!(config.max_jitter, 0.2);
    }

    #[test]
    fn test_backoff_config_serialization_roundtrip() {
        let config = BackoffCalculatorConfig::default();
        let json = serde_json::to_string(&config).expect("serialize");
        let deserialized: BackoffCalculatorConfig =
            serde_json::from_str(&json).expect("deserialize");

        assert_eq!(deserialized.base_delay_seconds, config.base_delay_seconds);
        assert_eq!(deserialized.max_delay_seconds, config.max_delay_seconds);
        assert_eq!(deserialized.multiplier, config.multiplier);
        assert_eq!(deserialized.jitter_enabled, config.jitter_enabled);
        assert_eq!(deserialized.max_jitter, config.max_jitter);
    }

    #[test]
    fn test_backoff_result_construction() {
        let now = Utc::now();
        let result = BackoffResult {
            delay_seconds: 30,
            backoff_type: BackoffType::Exponential,
            next_retry_at: now + Duration::seconds(30),
        };

        assert_eq!(result.delay_seconds, 30);
        assert!(matches!(result.backoff_type, BackoffType::Exponential));
        assert!(result.next_retry_at > now);
    }

    #[test]
    fn test_backoff_result_server_requested_type() {
        let result = BackoffResult {
            delay_seconds: 120,
            backoff_type: BackoffType::ServerRequested,
            next_retry_at: Utc::now() + Duration::seconds(120),
        };

        assert_eq!(result.delay_seconds, 120);
        assert!(matches!(result.backoff_type, BackoffType::ServerRequested));
    }

    #[test]
    fn test_backoff_error_display_messages() {
        let db_err = BackoffError::Database(sqlx::Error::ColumnNotFound("col".to_string()));
        assert!(db_err.to_string().contains("Database error"));

        let config_err = BackoffError::InvalidConfig("negative delay".to_string());
        assert_eq!(
            config_err.to_string(),
            "Invalid configuration: negative delay"
        );

        let step_err = BackoffError::StepNotFound(99);
        assert_eq!(step_err.to_string(), "Step not found: 99");
    }

    #[test]
    fn test_backoff_result_serialization() {
        let result = BackoffResult {
            delay_seconds: 60,
            backoff_type: BackoffType::Exponential,
            next_retry_at: Utc::now(),
        };

        let json = serde_json::to_value(&result).expect("serialize");
        assert_eq!(json["delay_seconds"], 60);
        assert_eq!(json["backoff_type"], "Exponential");
    }

    // --- Tests requiring a database pool (for BackoffCalculator methods) ---

    // --- Pure unit tests for extract_retry_after_header (no DB needed) ---

    fn make_calculator() -> BackoffCalculator {
        let pool = PgPool::connect_lazy("postgresql://test").expect("lazy pool");
        BackoffCalculator::with_defaults(pool)
    }

    fn make_calculator_with_config(config: BackoffCalculatorConfig) -> BackoffCalculator {
        let pool = PgPool::connect_lazy("postgresql://test").expect("lazy pool");
        BackoffCalculator::new(config, pool)
    }

    #[tokio::test]
    async fn test_extract_retry_after_case_insensitive() {
        let calculator = make_calculator();

        // Lowercase
        let ctx = BackoffContext::new().with_header("retry-after".to_string(), "30".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), Some(30));

        // Mixed case
        let ctx = BackoffContext::new().with_header("Retry-After".to_string(), "60".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), Some(60));

        // Uppercase
        let ctx = BackoffContext::new().with_header("RETRY-AFTER".to_string(), "90".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), Some(90));
    }

    #[tokio::test]
    async fn test_extract_retry_after_missing_header() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new().with_header("X-Custom".to_string(), "value".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    #[tokio::test]
    async fn test_extract_retry_after_invalid_value() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new()
            .with_header("retry-after".to_string(), "not-a-number".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    #[tokio::test]
    async fn test_extract_retry_after_empty_headers() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new();
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    #[tokio::test]
    async fn test_extract_retry_after_rfc2822_date() {
        let calculator = make_calculator();
        // Create a date 120 seconds in the future
        let future = Utc::now() + Duration::seconds(120);
        let rfc2822 = future.to_rfc2822();
        let ctx = BackoffContext::new().with_header("Retry-After".to_string(), rfc2822);
        let result = calculator.extract_retry_after_header(&ctx);
        // Should parse as roughly 120 seconds (allow some tolerance for test execution time)
        assert!(result.is_some());
        let seconds = result.unwrap();
        assert!(
            (118..=122).contains(&seconds),
            "Expected ~120, got {seconds}"
        );
    }

    #[tokio::test]
    async fn test_extract_retry_after_rfc2822_past_date() {
        let calculator = make_calculator();
        // A date in the past should return None (negative duration)
        let past = Utc::now() - Duration::seconds(60);
        let rfc2822 = past.to_rfc2822();
        let ctx = BackoffContext::new().with_header("Retry-After".to_string(), rfc2822);
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    #[tokio::test]
    async fn test_extract_retry_after_zero_seconds() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new().with_header("retry-after".to_string(), "0".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), Some(0));
    }

    #[tokio::test]
    async fn test_extract_retry_after_large_value() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new().with_header("retry-after".to_string(), "86400".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), Some(86400));
    }

    #[tokio::test]
    async fn test_extract_retry_after_negative_value() {
        let calculator = make_calculator();
        // Negative numbers fail u32 parse
        let ctx = BackoffContext::new().with_header("retry-after".to_string(), "-30".to_string());
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    #[tokio::test]
    async fn test_extract_retry_after_empty_value() {
        let calculator = make_calculator();
        let ctx = BackoffContext::new().with_header("retry-after".to_string(), String::new());
        assert_eq!(calculator.extract_retry_after_header(&ctx), None);
    }

    // --- Pure unit tests for apply_jitter (no DB needed) ---

    #[tokio::test]
    async fn test_apply_jitter_within_bounds() {
        let config = BackoffCalculatorConfig {
            jitter_enabled: true,
            max_jitter: 0.1, // 10%
            ..Default::default()
        };
        let calculator = make_calculator_with_config(config);

        for _ in 0..50 {
            let jittered = calculator.apply_jitter(100);
            assert!(jittered >= 90, "Jitter too low: {jittered}");
            assert!(jittered <= 110, "Jitter too high: {jittered}");
        }
    }

    #[tokio::test]
    async fn test_apply_jitter_zero_delay() {
        let calculator = make_calculator();
        let jittered = calculator.apply_jitter(0);
        assert_eq!(jittered, 0, "Zero delay should remain zero");
    }

    #[tokio::test]
    async fn test_apply_jitter_small_delay_no_underflow() {
        let calculator = make_calculator();
        let jittered = calculator.apply_jitter(1);
        // max_jitter 0.1 * 1 = 0.1 → rounds to 0, so returns original
        assert_eq!(jittered, 1);
    }

    #[tokio::test]
    async fn test_apply_jitter_large_delay() {
        let config = BackoffCalculatorConfig {
            max_jitter: 0.1,
            ..Default::default()
        };
        let calculator = make_calculator_with_config(config);

        for _ in 0..50 {
            let jittered = calculator.apply_jitter(10_000);
            // 10% of 10000 = 1000, so range is 9000-11000
            assert!(jittered >= 9000, "Jitter too low: {jittered}");
            assert!(jittered <= 11000, "Jitter too high: {jittered}");
        }
    }

    #[tokio::test]
    async fn test_apply_jitter_zero_max_jitter() {
        let config = BackoffCalculatorConfig {
            max_jitter: 0.0,
            ..Default::default()
        };
        let calculator = make_calculator_with_config(config);

        // Zero jitter means value is unchanged
        let jittered = calculator.apply_jitter(100);
        assert_eq!(jittered, 100);
    }

    #[tokio::test]
    async fn test_apply_jitter_saturating_behavior() {
        let config = BackoffCalculatorConfig {
            max_jitter: 0.5, // 50% jitter
            ..Default::default()
        };
        let calculator = make_calculator_with_config(config);

        // With u32::MAX, subtraction should saturate at 0, addition at u32::MAX
        for _ in 0..20 {
            let jittered = calculator.apply_jitter(u32::MAX);
            // saturating_add and saturating_sub prevent overflow
            assert!(jittered > 0);
        }
    }

    // --- BackoffType tests ---

    #[test]
    fn test_backoff_type_serialization_roundtrip() {
        let types = [BackoffType::ServerRequested, BackoffType::Exponential];
        for bt in &types {
            let json = serde_json::to_string(bt).expect("serialize");
            let deserialized: BackoffType = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(format!("{deserialized:?}"), format!("{bt:?}"));
        }
    }

    #[test]
    fn test_backoff_type_debug() {
        assert_eq!(
            format!("{:?}", BackoffType::ServerRequested),
            "ServerRequested"
        );
        assert_eq!(format!("{:?}", BackoffType::Exponential), "Exponential");
    }

    // --- BackoffError tests ---

    #[test]
    fn test_backoff_error_invalid_config_display() {
        let err = BackoffError::InvalidConfig("multiplier must be > 0".to_string());
        assert_eq!(
            err.to_string(),
            "Invalid configuration: multiplier must be > 0"
        );
    }

    #[test]
    fn test_backoff_error_step_not_found_display() {
        let err = BackoffError::StepNotFound(42);
        assert_eq!(err.to_string(), "Step not found: 42");
    }

    // --- BackoffContext edge cases ---

    #[test]
    fn test_backoff_context_header_overwrite() {
        let context = BackoffContext::new()
            .with_header("retry-after".to_string(), "60".to_string())
            .with_header("retry-after".to_string(), "120".to_string());

        assert_eq!(context.headers.get("retry-after"), Some(&"120".to_string()));
        assert_eq!(context.headers.len(), 1);
    }

    #[test]
    fn test_backoff_context_metadata_overwrite() {
        let context = BackoffContext::new()
            .with_metadata("count".to_string(), serde_json::json!(1))
            .with_metadata("count".to_string(), serde_json::json!(2));

        assert_eq!(context.metadata["count"], serde_json::json!(2));
        assert_eq!(context.metadata.len(), 1);
    }

    #[test]
    fn test_backoff_result_clone() {
        let result = BackoffResult {
            delay_seconds: 45,
            backoff_type: BackoffType::Exponential,
            next_retry_at: Utc::now(),
        };
        let cloned = result.clone();
        assert_eq!(cloned.delay_seconds, 45);
        assert!(matches!(cloned.backoff_type, BackoffType::Exponential));
    }

    #[tokio::test]
    async fn test_backoff_calculator_debug() {
        let calculator = make_calculator();
        let debug = format!("{calculator:?}");
        assert!(debug.contains("BackoffCalculator"));
        assert!(debug.contains("config"));
    }

    #[tokio::test]
    async fn test_backoff_calculator_clone() {
        let calculator = make_calculator();
        let cloned = calculator.clone();
        assert_eq!(
            cloned.config.base_delay_seconds,
            calculator.config.base_delay_seconds
        );
    }
}