rust-task-queue 0.1.5

Production-ready Redis task queue with intelligent auto-scaling, Actix Web integration, and enterprise-grade observability for high-performance async Rust applications.
Documentation
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
use crate::{queue::queue_names, QueueMetrics, RedisBroker, TaskQueueError};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Enhanced autoscaler configuration with multi-dimensional scaling triggers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoScalerConfig {
    pub min_workers: usize,
    pub max_workers: usize,
    pub scale_up_count: usize,
    pub scale_down_count: usize,

    // Multi-dimensional thresholds
    pub scaling_triggers: ScalingTriggers,

    // Adaptive learning parameters
    pub enable_adaptive_thresholds: bool,
    pub learning_rate: f64,
    pub adaptation_window_minutes: u32,

    // Hysteresis and stability
    pub scale_up_cooldown_seconds: u64,
    pub scale_down_cooldown_seconds: u64,
    pub consecutive_signals_required: usize,

    // Performance targets for adaptive learning
    pub target_sla: SLATargets,
}

/// Multi-dimensional scaling triggers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingTriggers {
    pub queue_pressure_threshold: f64,     // Weighted queue depth score
    pub worker_utilization_threshold: f64, // Target worker utilization %
    pub task_complexity_threshold: f64,    // Complex task overload factor
    pub error_rate_threshold: f64,         // Maximum acceptable error rate
    pub memory_pressure_threshold: f64,    // Memory usage per worker (MB)
}

/// SLA targets for adaptive threshold learning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SLATargets {
    pub max_p95_latency_ms: f64,
    pub min_success_rate: f64,
    pub max_queue_wait_time_ms: f64,
    pub target_worker_utilization: f64,
}

impl Default for AutoScalerConfig {
    fn default() -> Self {
        Self {
            min_workers: 1,
            max_workers: 20,
            scale_up_count: 2,
            scale_down_count: 1,

            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },

            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,

            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,

            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        }
    }
}

impl AutoScalerConfig {
    pub fn validate(&self) -> Result<(), TaskQueueError> {
        if self.min_workers == 0 {
            return Err(TaskQueueError::Configuration(
                "Minimum workers must be greater than 0".to_string(),
            ));
        }

        if self.max_workers < self.min_workers {
            return Err(TaskQueueError::Configuration(
                "Maximum workers must be greater than or equal to minimum workers".to_string(),
            ));
        }

        if self.max_workers > 1000 {
            return Err(TaskQueueError::Configuration(
                "Maximum workers cannot exceed 1000".to_string(),
            ));
        }

        if self.scale_up_count == 0 || self.scale_up_count > 50 {
            return Err(TaskQueueError::Configuration(
                "Scale up count must be between 1 and 50".to_string(),
            ));
        }

        if self.scale_down_count == 0 || self.scale_down_count > 50 {
            return Err(TaskQueueError::Configuration(
                "Scale down count must be between 1 and 50".to_string(),
            ));
        }

        // Validate scaling triggers
        let triggers = &self.scaling_triggers;
        if triggers.queue_pressure_threshold <= 0.0 || triggers.queue_pressure_threshold > 2.0 {
            return Err(TaskQueueError::Configuration(
                "Queue pressure threshold must be between 0.1 and 2.0".to_string(),
            ));
        }

        if triggers.worker_utilization_threshold <= 0.0
            || triggers.worker_utilization_threshold > 1.0
        {
            return Err(TaskQueueError::Configuration(
                "Worker utilization threshold must be between 0.1 and 1.0".to_string(),
            ));
        }

        if triggers.error_rate_threshold < 0.0 || triggers.error_rate_threshold > 1.0 {
            return Err(TaskQueueError::Configuration(
                "Error rate threshold must be between 0.0 and 1.0".to_string(),
            ));
        }

        if self.learning_rate <= 0.0 || self.learning_rate > 1.0 {
            return Err(TaskQueueError::Configuration(
                "Learning rate must be between 0.01 and 1.0".to_string(),
            ));
        }

        Ok(())
    }
}

#[derive(Debug)]
pub enum ScalingAction {
    ScaleUp(usize),
    ScaleDown(usize),
    NoAction,
}

/// Enhanced metrics with multi-dimensional analysis
#[derive(Debug, Serialize, Deserialize)]
pub struct AutoScalerMetrics {
    pub active_workers: i64,
    pub total_pending_tasks: i64,
    pub queue_metrics: Vec<QueueMetrics>,

    // Enhanced metrics
    pub queue_pressure_score: f64,
    pub worker_utilization: f64,
    pub task_complexity_factor: f64,
    pub error_rate: f64,
    pub memory_pressure_mb: f64,
    pub avg_queue_wait_time_ms: f64,
    pub throughput_trend: f64,
}

/// Adaptive threshold controller that learns from system performance
#[derive(Debug)]
pub struct AdaptiveThresholdController {
    current_thresholds: ScalingTriggers,
    performance_history: Vec<PerformanceSnapshot>,
    last_adaptation: Instant,
    learning_rate: f64,
    target_sla: SLATargets,
    adaptation_window: Duration,
}

#[derive(Debug, Clone)]
#[allow(dead_code)] // Fields reserved for future Phase 2/3 enhancements
struct PerformanceSnapshot {
    timestamp: Instant,
    latency_p95_ms: f64,
    success_rate: f64,
    queue_wait_time_ms: f64,
    worker_utilization: f64,
    scaling_action_taken: Option<ScalingAction>,
}

/// Hysteresis controller to prevent oscillations
#[derive(Debug)]
pub struct HysteresisController {
    scale_up_consecutive_signals: usize,
    scale_down_consecutive_signals: usize,
    required_consecutive_signals: usize,
    last_scaling_action: Option<(Instant, ScalingAction)>,
    scale_up_cooldown: Duration,
    scale_down_cooldown: Duration,
}

pub struct AutoScaler {
    broker: Arc<RedisBroker>,
    config: AutoScalerConfig,
    adaptive_controller: Option<AdaptiveThresholdController>,
    hysteresis_controller: HysteresisController,
    metrics_history: Vec<AutoScalerMetrics>,
    start_time: Instant,
}

impl AutoScaler {
    pub fn new(broker: Arc<RedisBroker>) -> Self {
        let config = AutoScalerConfig::default();
        Self::with_config(broker, config)
    }

    pub fn with_config(broker: Arc<RedisBroker>, config: AutoScalerConfig) -> Self {
        let adaptive_controller = if config.enable_adaptive_thresholds {
            Some(AdaptiveThresholdController::new(
                config.scaling_triggers.clone(),
                config.learning_rate,
                config.target_sla.clone(),
                Duration::from_secs(config.adaptation_window_minutes as u64 * 60),
            ))
        } else {
            None
        };

        let hysteresis_controller = HysteresisController::new(
            config.consecutive_signals_required,
            Duration::from_secs(config.scale_up_cooldown_seconds),
            Duration::from_secs(config.scale_down_cooldown_seconds),
        );

        Self {
            broker,
            config,
            adaptive_controller,
            hysteresis_controller,
            metrics_history: Vec::new(),
            start_time: Instant::now(),
        }
    }

    pub async fn collect_metrics(&self) -> Result<AutoScalerMetrics, TaskQueueError> {
        let active_workers = self.broker.get_active_workers().await?;

        let queues = [
            queue_names::DEFAULT,
            queue_names::HIGH_PRIORITY,
            queue_names::LOW_PRIORITY,
        ];
        let mut queue_metrics = Vec::new();
        let mut total_pending_tasks = 0;
        let mut total_processed_tasks = 0;
        let mut total_failed_tasks = 0;

        for queue in &queues {
            let metrics = self.broker.get_queue_metrics(queue).await?;
            total_pending_tasks += metrics.pending_tasks;
            total_processed_tasks += metrics.processed_tasks;
            total_failed_tasks += metrics.failed_tasks;
            queue_metrics.push(metrics);
        }

        // Calculate enhanced metrics
        let queue_pressure_score =
            self.calculate_queue_pressure_score(&queue_metrics, active_workers);
        let worker_utilization = self.calculate_worker_utilization(active_workers, &queue_metrics);
        let task_complexity_factor = self.calculate_task_complexity_factor(&queue_metrics);
        let error_rate = self.calculate_error_rate(total_processed_tasks, total_failed_tasks);
        let memory_pressure_mb = self.estimate_memory_pressure(active_workers);
        let avg_queue_wait_time_ms = self.calculate_avg_queue_wait_time(&queue_metrics);
        let throughput_trend = self.calculate_throughput_trend(&queue_metrics);

        Ok(AutoScalerMetrics {
            active_workers,
            total_pending_tasks,
            queue_metrics,
            queue_pressure_score,
            worker_utilization,
            task_complexity_factor,
            error_rate,
            memory_pressure_mb,
            avg_queue_wait_time_ms,
            throughput_trend,
        })
    }

    pub fn decide_scaling_action(
        &mut self,
        metrics: &AutoScalerMetrics,
    ) -> Result<ScalingAction, TaskQueueError> {
        let current_workers = metrics.active_workers as usize;

        // Get current thresholds (potentially adaptive)
        let thresholds = if let Some(ref adaptive) = self.adaptive_controller {
            adaptive.get_current_thresholds().clone()
        } else {
            self.config.scaling_triggers.clone()
        };

        // Multi-dimensional scaling decision
        let scale_up_signals = Self::count_scale_up_signals_static(metrics, &thresholds);
        let scale_down_signals = Self::count_scale_down_signals_static(metrics, &thresholds);

        let proposed_action = if scale_up_signals >= 2 && current_workers < self.config.max_workers
        {
            let scale_count = std::cmp::min(
                self.config.scale_up_count,
                self.config.max_workers - current_workers,
            );
            ScalingAction::ScaleUp(scale_count)
        } else if scale_down_signals >= 2 && current_workers > self.config.min_workers {
            let scale_count = std::cmp::min(
                self.config.scale_down_count,
                current_workers - self.config.min_workers,
            );
            ScalingAction::ScaleDown(scale_count)
        } else {
            ScalingAction::NoAction
        };

        // Apply hysteresis control
        let final_action = if self
            .hysteresis_controller
            .should_execute_scaling(&proposed_action)
        {
            #[cfg(feature = "tracing")]
            match &proposed_action {
                ScalingAction::ScaleUp(count) => {
                    tracing::info!(
                        "Enhanced auto-scaling up: queue_pressure={:.2}, utilization={:.2}, complexity={:.2}, adding {} workers",
                        metrics.queue_pressure_score,
                        metrics.worker_utilization,
                        metrics.task_complexity_factor,
                        count
                    );
                }
                ScalingAction::ScaleDown(count) => {
                    tracing::info!(
                        "Enhanced auto-scaling down: queue_pressure={:.2}, utilization={:.2}, removing {} workers",
                        metrics.queue_pressure_score,
                        metrics.worker_utilization,
                        count
                    );
                }
                _ => {}
            }

            proposed_action
        } else {
            ScalingAction::NoAction
        };

        // Record for adaptive learning
        if let Some(ref mut adaptive) = self.adaptive_controller {
            adaptive.record_performance_snapshot(metrics, &final_action);
        }

        // Store metrics history for trend analysis
        self.metrics_history.push(metrics.clone());
        if self.metrics_history.len() > 100 {
            self.metrics_history.remove(0);
        }

        Ok(final_action)
    }

    fn count_scale_up_signals_static(
        metrics: &AutoScalerMetrics,
        thresholds: &ScalingTriggers,
    ) -> usize {
        let mut signals = 0;

        if metrics.queue_pressure_score > thresholds.queue_pressure_threshold {
            signals += 1;
        }
        if metrics.worker_utilization > thresholds.worker_utilization_threshold {
            signals += 1;
        }
        if metrics.task_complexity_factor > thresholds.task_complexity_threshold {
            signals += 1;
        }
        if metrics.error_rate > thresholds.error_rate_threshold {
            signals += 1;
        }
        if metrics.memory_pressure_mb > thresholds.memory_pressure_threshold {
            signals += 1;
        }

        signals
    }

    fn count_scale_down_signals_static(
        metrics: &AutoScalerMetrics,
        thresholds: &ScalingTriggers,
    ) -> usize {
        let mut signals = 0;

        // Scale down when metrics are well below thresholds
        if metrics.queue_pressure_score < thresholds.queue_pressure_threshold * 0.3 {
            signals += 1;
        }
        if metrics.worker_utilization < thresholds.worker_utilization_threshold * 0.4 {
            signals += 1;
        }
        if metrics.task_complexity_factor < thresholds.task_complexity_threshold * 0.5 {
            signals += 1;
        }
        if metrics.error_rate < thresholds.error_rate_threshold * 0.2 {
            signals += 1;
        }
        if metrics.memory_pressure_mb < thresholds.memory_pressure_threshold * 0.5 {
            signals += 1;
        }

        signals
    }

    fn calculate_queue_pressure_score(
        &self,
        queue_metrics: &[QueueMetrics],
        active_workers: i64,
    ) -> f64 {
        let mut weighted_pressure = 0.0;
        let queue_weights = [
            (queue_names::HIGH_PRIORITY, 3.0),
            (queue_names::DEFAULT, 1.0),
            (queue_names::LOW_PRIORITY, 0.3),
        ];

        for metrics in queue_metrics {
            let weight = queue_weights
                .iter()
                .find(|(name, _)| *name == metrics.queue_name)
                .map(|(_, w)| *w)
                .unwrap_or(1.0);

            let queue_pressure = if active_workers > 0 {
                metrics.pending_tasks as f64 / active_workers as f64
            } else {
                metrics.pending_tasks as f64
            };

            weighted_pressure += queue_pressure * weight;
        }

        weighted_pressure / queue_weights.len() as f64
    }

    fn calculate_worker_utilization(
        &self,
        active_workers: i64,
        queue_metrics: &[QueueMetrics],
    ) -> f64 {
        if active_workers == 0 {
            return 0.0;
        }

        let total_work = queue_metrics
            .iter()
            .map(|m| m.pending_tasks + m.processed_tasks)
            .sum::<i64>();

        let utilization = total_work as f64 / (active_workers as f64 * 100.0);
        utilization.min(1.0)
    }

    fn calculate_task_complexity_factor(&self, _queue_metrics: &[QueueMetrics]) -> f64 {
        // Simplified complexity calculation
        // In a real implementation, this would analyze historical execution times
        1.0
    }

    fn calculate_error_rate(&self, processed: i64, failed: i64) -> f64 {
        let total = processed + failed;
        if total == 0 {
            return 0.0;
        }
        failed as f64 / total as f64
    }

    fn estimate_memory_pressure(&self, active_workers: i64) -> f64 {
        // Simplified memory estimation
        // In a real implementation, this would query actual memory usage
        active_workers as f64 * 50.0 // Assume 50MB per worker baseline
    }

    fn calculate_avg_queue_wait_time(&self, _queue_metrics: &[QueueMetrics]) -> f64 {
        // Simplified calculation
        // In a real implementation, this would track actual wait times
        0.0
    }

    fn calculate_throughput_trend(&self, _queue_metrics: &[QueueMetrics]) -> f64 {
        // Simplified trend calculation
        // In a real implementation, this would analyze historical throughput
        0.0
    }

    pub async fn get_scaling_recommendations(&self) -> Result<String, TaskQueueError> {
        let metrics = self.collect_metrics().await?;
        let mut scaling_decision_copy = self.clone();
        let action = scaling_decision_copy.decide_scaling_action(&metrics)?;

        let mut report = format!(
            "Enhanced Auto-scaling Status Report:\n\
             - Active Workers: {}\n\
             - Total Pending Tasks: {}\n\
             - Queue Pressure Score: {:.2}\n\
             - Worker Utilization: {:.1}%\n\
             - Task Complexity Factor: {:.2}\n\
             - Error Rate: {:.1}%\n\
             - Memory Pressure: {:.1} MB\n\n",
            metrics.active_workers,
            metrics.total_pending_tasks,
            metrics.queue_pressure_score,
            metrics.worker_utilization * 100.0,
            metrics.task_complexity_factor,
            metrics.error_rate * 100.0,
            metrics.memory_pressure_mb
        );

        for queue_metric in &metrics.queue_metrics {
            report.push_str(&format!(
                "Queue '{}': {} pending, {} processed, {} failed\n",
                queue_metric.queue_name,
                queue_metric.pending_tasks,
                queue_metric.processed_tasks,
                queue_metric.failed_tasks
            ));
        }

        report.push_str(&format!("\nRecommended Action: {:?}\n", action));

        if let Some(ref adaptive) = self.adaptive_controller {
            report.push_str(&format!(
                "\nAdaptive Thresholds Enabled: {}\n",
                adaptive.get_adaptation_status()
            ));
        }

        Ok(report)
    }
}

// Clone implementation for AutoScaler (needed for decision making without borrowing issues)
impl Clone for AutoScaler {
    fn clone(&self) -> Self {
        let adaptive_controller = self.adaptive_controller.clone();
        let hysteresis_controller = self.hysteresis_controller.clone();

        Self {
            broker: self.broker.clone(),
            config: self.config.clone(),
            adaptive_controller,
            hysteresis_controller,
            metrics_history: self.metrics_history.clone(),
            start_time: self.start_time,
        }
    }
}

// Clone implementation for AutoScalerMetrics
impl Clone for AutoScalerMetrics {
    fn clone(&self) -> Self {
        Self {
            active_workers: self.active_workers,
            total_pending_tasks: self.total_pending_tasks,
            queue_metrics: self.queue_metrics.clone(),
            queue_pressure_score: self.queue_pressure_score,
            worker_utilization: self.worker_utilization,
            task_complexity_factor: self.task_complexity_factor,
            error_rate: self.error_rate,
            memory_pressure_mb: self.memory_pressure_mb,
            avg_queue_wait_time_ms: self.avg_queue_wait_time_ms,
            throughput_trend: self.throughput_trend,
        }
    }
}

impl AdaptiveThresholdController {
    pub fn new(
        initial_thresholds: ScalingTriggers,
        learning_rate: f64,
        target_sla: SLATargets,
        adaptation_window: Duration,
    ) -> Self {
        Self {
            current_thresholds: initial_thresholds,
            performance_history: Vec::new(),
            last_adaptation: Instant::now(),
            learning_rate,
            target_sla,
            adaptation_window,
        }
    }

    pub fn get_current_thresholds(&self) -> &ScalingTriggers {
        &self.current_thresholds
    }

    pub fn record_performance_snapshot(
        &mut self,
        metrics: &AutoScalerMetrics,
        action: &ScalingAction,
    ) {
        let snapshot = PerformanceSnapshot {
            timestamp: Instant::now(),
            latency_p95_ms: 0.0, // Would be filled from actual metrics
            success_rate: 1.0 - metrics.error_rate,
            queue_wait_time_ms: metrics.avg_queue_wait_time_ms,
            worker_utilization: metrics.worker_utilization,
            scaling_action_taken: match action {
                ScalingAction::NoAction => None,
                _ => Some(action.clone()),
            },
        };

        self.performance_history.push(snapshot);

        // Keep only recent history
        let cutoff_time = Instant::now() - self.adaptation_window;
        self.performance_history
            .retain(|s| s.timestamp > cutoff_time);

        // Adapt thresholds if enough time has passed
        if self.last_adaptation.elapsed() > Duration::from_secs(300) {
            self.adapt_thresholds();
            self.last_adaptation = Instant::now();
        }
    }

    fn adapt_thresholds(&mut self) {
        if self.performance_history.is_empty() {
            return;
        }

        let recent_performance =
            &self.performance_history[self.performance_history.len().saturating_sub(10)..];

        let avg_success_rate = recent_performance
            .iter()
            .map(|s| s.success_rate)
            .sum::<f64>()
            / recent_performance.len() as f64;

        let avg_utilization = recent_performance
            .iter()
            .map(|s| s.worker_utilization)
            .sum::<f64>()
            / recent_performance.len() as f64;

        // Adapt queue pressure threshold based on success rate
        if avg_success_rate < self.target_sla.min_success_rate {
            // Lower threshold to scale up more aggressively
            self.current_thresholds.queue_pressure_threshold *= 1.0 - self.learning_rate;
        } else if avg_success_rate > self.target_sla.min_success_rate + 0.02 {
            // Raise threshold to scale up less aggressively
            self.current_thresholds.queue_pressure_threshold *= 1.0 + (self.learning_rate * 0.5);
        }

        // Adapt utilization threshold based on target utilization
        let utilization_diff = avg_utilization - self.target_sla.target_worker_utilization;
        if utilization_diff.abs() > 0.1 {
            let adjustment = -utilization_diff * self.learning_rate;
            self.current_thresholds.worker_utilization_threshold *= 1.0 + adjustment;
        }

        // Clamp thresholds to reasonable ranges
        self.current_thresholds.queue_pressure_threshold = self
            .current_thresholds
            .queue_pressure_threshold
            .clamp(0.1, 2.0);
        self.current_thresholds.worker_utilization_threshold = self
            .current_thresholds
            .worker_utilization_threshold
            .clamp(0.1, 0.95);
    }

    pub fn get_adaptation_status(&self) -> String {
        format!(
            "Thresholds adapted {} times, {} performance samples",
            0,
            self.performance_history.len()
        )
    }
}

impl Clone for AdaptiveThresholdController {
    fn clone(&self) -> Self {
        Self {
            current_thresholds: self.current_thresholds.clone(),
            performance_history: self.performance_history.clone(),
            last_adaptation: self.last_adaptation,
            learning_rate: self.learning_rate,
            target_sla: self.target_sla.clone(),
            adaptation_window: self.adaptation_window,
        }
    }
}

impl HysteresisController {
    pub fn new(
        consecutive_signals_required: usize,
        scale_up_cooldown: Duration,
        scale_down_cooldown: Duration,
    ) -> Self {
        Self {
            scale_up_consecutive_signals: 0,
            scale_down_consecutive_signals: 0,
            required_consecutive_signals: consecutive_signals_required,
            last_scaling_action: None,
            scale_up_cooldown,
            scale_down_cooldown,
        }
    }

    pub fn should_execute_scaling(&mut self, proposed_action: &ScalingAction) -> bool {
        // Check cooldown periods
        if let Some((last_time, ref last_action)) = self.last_scaling_action {
            let cooldown_period = match last_action {
                ScalingAction::ScaleUp(_) => self.scale_up_cooldown,
                ScalingAction::ScaleDown(_) => self.scale_down_cooldown,
                ScalingAction::NoAction => Duration::from_secs(0),
            };

            if last_time.elapsed() < cooldown_period {
                return false;
            }
        }

        // Check consecutive signals
        let should_execute = match proposed_action {
            ScalingAction::ScaleUp(_) => {
                self.scale_up_consecutive_signals += 1;
                self.scale_down_consecutive_signals = 0;
                self.scale_up_consecutive_signals >= self.required_consecutive_signals
            }
            ScalingAction::ScaleDown(_) => {
                self.scale_down_consecutive_signals += 1;
                self.scale_up_consecutive_signals = 0;
                self.scale_down_consecutive_signals >= self.required_consecutive_signals
            }
            ScalingAction::NoAction => {
                self.scale_up_consecutive_signals = 0;
                self.scale_down_consecutive_signals = 0;
                false
            }
        };

        if should_execute {
            self.last_scaling_action = Some((Instant::now(), proposed_action.clone()));
            self.scale_up_consecutive_signals = 0;
            self.scale_down_consecutive_signals = 0;
        }

        should_execute
    }
}

impl Clone for HysteresisController {
    fn clone(&self) -> Self {
        Self {
            scale_up_consecutive_signals: self.scale_up_consecutive_signals,
            scale_down_consecutive_signals: self.scale_down_consecutive_signals,
            required_consecutive_signals: self.required_consecutive_signals,
            last_scaling_action: self.last_scaling_action.clone(),
            scale_up_cooldown: self.scale_up_cooldown,
            scale_down_cooldown: self.scale_down_cooldown,
        }
    }
}

impl Clone for ScalingAction {
    fn clone(&self) -> Self {
        match self {
            ScalingAction::ScaleUp(count) => ScalingAction::ScaleUp(*count),
            ScalingAction::ScaleDown(count) => ScalingAction::ScaleDown(*count),
            ScalingAction::NoAction => ScalingAction::NoAction,
        }
    }
}

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

    #[test]
    fn test_autoscaler_config_default() {
        let config = AutoScalerConfig::default();

        assert_eq!(config.min_workers, 1);
        assert_eq!(config.max_workers, 20);
        assert_eq!(config.scale_up_count, 2);
        assert_eq!(config.scale_down_count, 1);
        assert_eq!(config.scaling_triggers.queue_pressure_threshold, 0.75);
        assert_eq!(config.scaling_triggers.worker_utilization_threshold, 0.80);
        assert_eq!(config.scaling_triggers.task_complexity_threshold, 1.5);
        assert_eq!(config.scaling_triggers.error_rate_threshold, 0.05);
        assert_eq!(config.scaling_triggers.memory_pressure_threshold, 512.0);
        assert!(config.enable_adaptive_thresholds);
        assert_eq!(config.learning_rate, 0.1);
        assert_eq!(config.adaptation_window_minutes, 30);
        assert_eq!(config.scale_up_cooldown_seconds, 60);
        assert_eq!(config.scale_down_cooldown_seconds, 300);
        assert_eq!(config.consecutive_signals_required, 2);
        assert_eq!(config.target_sla.max_p95_latency_ms, 5000.0);
        assert_eq!(config.target_sla.min_success_rate, 0.95);
        assert_eq!(config.target_sla.max_queue_wait_time_ms, 10000.0);
        assert_eq!(config.target_sla.target_worker_utilization, 0.70);
    }

    #[test]
    fn test_autoscaler_config_validation_valid() {
        let config = AutoScalerConfig {
            min_workers: 2,
            max_workers: 10,
            scale_up_count: 3,
            scale_down_count: 2,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_autoscaler_config_validation_min_workers_zero() {
        let config = AutoScalerConfig {
            min_workers: 0,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Minimum workers must be greater than 0"));
    }

    #[test]
    fn test_autoscaler_config_validation_max_less_than_min() {
        let config = AutoScalerConfig {
            min_workers: 10,
            max_workers: 5,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Maximum workers must be greater than or equal to minimum workers"));
    }

    #[test]
    fn test_autoscaler_config_validation_max_workers_too_high() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 1001,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Maximum workers cannot exceed 1000"));
    }

    #[test]
    fn test_autoscaler_config_validation_invalid_scale_up_count() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 0,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Scale up count must be between 1 and 50"));
    }

    #[test]
    fn test_autoscaler_config_validation_invalid_scale_down_count() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 0,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Scale down count must be between 1 and 50"));
    }

    #[test]
    fn test_autoscaler_config_validation_invalid_scaling_triggers() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.0,
                worker_utilization_threshold: 0.0,
                task_complexity_threshold: 0.0,
                error_rate_threshold: 0.0,
                memory_pressure_threshold: 0.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("Queue pressure threshold must be between 0.1 and 2.0"));
    }

    #[test]
    fn test_autoscaler_config_validation_invalid_learning_rate() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.0,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let result = config.validate();
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Learning rate must be between 0.01 and 1.0"));
    }

    #[test]
    fn test_autoscaler_config_serialization() {
        let config = AutoScalerConfig::default();

        // Test JSON serialization
        let json = serde_json::to_string(&config).expect("Failed to serialize to JSON");
        let deserialized: AutoScalerConfig =
            serde_json::from_str(&json).expect("Failed to deserialize from JSON");

        assert_eq!(config.min_workers, deserialized.min_workers);
        assert_eq!(config.max_workers, deserialized.max_workers);
        assert_eq!(config.scale_up_count, deserialized.scale_up_count);
        assert_eq!(config.scale_down_count, deserialized.scale_down_count);
        assert_eq!(
            config.scaling_triggers.queue_pressure_threshold,
            deserialized.scaling_triggers.queue_pressure_threshold
        );
        assert_eq!(
            config.scaling_triggers.worker_utilization_threshold,
            deserialized.scaling_triggers.worker_utilization_threshold
        );
        assert_eq!(
            config.scaling_triggers.task_complexity_threshold,
            deserialized.scaling_triggers.task_complexity_threshold
        );
        assert_eq!(
            config.scaling_triggers.error_rate_threshold,
            deserialized.scaling_triggers.error_rate_threshold
        );
        assert_eq!(
            config.scaling_triggers.memory_pressure_threshold,
            deserialized.scaling_triggers.memory_pressure_threshold
        );
        assert_eq!(
            config.enable_adaptive_thresholds,
            deserialized.enable_adaptive_thresholds
        );
        assert_eq!(config.learning_rate, deserialized.learning_rate);
        assert_eq!(
            config.adaptation_window_minutes,
            deserialized.adaptation_window_minutes
        );
        assert_eq!(
            config.scale_up_cooldown_seconds,
            deserialized.scale_up_cooldown_seconds
        );
        assert_eq!(
            config.scale_down_cooldown_seconds,
            deserialized.scale_down_cooldown_seconds
        );
        assert_eq!(
            config.consecutive_signals_required,
            deserialized.consecutive_signals_required
        );
        assert_eq!(
            config.target_sla.max_p95_latency_ms,
            deserialized.target_sla.max_p95_latency_ms
        );
        assert_eq!(
            config.target_sla.min_success_rate,
            deserialized.target_sla.min_success_rate
        );
        assert_eq!(
            config.target_sla.max_queue_wait_time_ms,
            deserialized.target_sla.max_queue_wait_time_ms
        );
        assert_eq!(
            config.target_sla.target_worker_utilization,
            deserialized.target_sla.target_worker_utilization
        );
    }

    fn create_test_autoscaler_metrics(
        active_workers: i64,
        total_pending_tasks: i64,
    ) -> AutoScalerMetrics {
        let queue_pressure_score = if active_workers > 0 {
            total_pending_tasks as f64 / active_workers as f64
        } else {
            total_pending_tasks as f64
        };

        AutoScalerMetrics {
            active_workers,
            total_pending_tasks,
            queue_metrics: vec![QueueMetrics {
                queue_name: "default".to_string(),
                pending_tasks: total_pending_tasks,
                processed_tasks: 100,
                failed_tasks: 5,
            }],
            queue_pressure_score,
            worker_utilization: if active_workers > 0 { 0.6 } else { 0.0 },
            task_complexity_factor: 1.0,
            error_rate: 5.0 / 105.0, // 5 failed out of 105 total
            memory_pressure_mb: active_workers as f64 * 50.0,
            avg_queue_wait_time_ms: 0.0,
            throughput_trend: 0.0,
        }
    }

    fn create_test_autoscaler_metrics_with_high_pressure(
        active_workers: i64,
        total_pending_tasks: i64,
    ) -> AutoScalerMetrics {
        let queue_pressure_score = if active_workers > 0 {
            total_pending_tasks as f64 / active_workers as f64
        } else {
            total_pending_tasks as f64
        };

        AutoScalerMetrics {
            active_workers,
            total_pending_tasks,
            queue_metrics: vec![QueueMetrics {
                queue_name: "default".to_string(),
                pending_tasks: total_pending_tasks,
                processed_tasks: 100,
                failed_tasks: 5,
            }],
            queue_pressure_score,
            worker_utilization: 0.95,    // High utilization
            task_complexity_factor: 2.0, // High complexity
            error_rate: 0.08,            // High error rate
            memory_pressure_mb: 600.0,   // High memory pressure
            avg_queue_wait_time_ms: 0.0,
            throughput_trend: 0.0,
        }
    }

    fn create_test_autoscaler_metrics_with_low_pressure(
        active_workers: i64,
        total_pending_tasks: i64,
    ) -> AutoScalerMetrics {
        let queue_pressure_score = if active_workers > 0 {
            total_pending_tasks as f64 / active_workers as f64
        } else {
            total_pending_tasks as f64
        };

        AutoScalerMetrics {
            active_workers,
            total_pending_tasks,
            queue_metrics: vec![QueueMetrics {
                queue_name: "default".to_string(),
                pending_tasks: total_pending_tasks,
                processed_tasks: 100,
                failed_tasks: 5,
            }],
            queue_pressure_score,
            worker_utilization: 0.2,     // Low utilization
            task_complexity_factor: 0.5, // Low complexity
            error_rate: 0.01,            // Low error rate
            memory_pressure_mb: 100.0,   // Low memory pressure
            avg_queue_wait_time_ms: 0.0,
            throughput_trend: 0.0,
        }
    }

    #[allow(dead_code)]
    fn create_mock_autoscaler() -> AutoScaler {
        // Create a dummy broker for testing purposes
        let redis_url = "redis://localhost:6379";
        let mut config = deadpool_redis::Config::from_url(redis_url);
        config.pool = Some(deadpool_redis::PoolConfig::new(1));

        let pool = config
            .create_pool(Some(deadpool_redis::Runtime::Tokio1))
            .expect("Failed to create pool");

        let broker = Arc::new(crate::broker::RedisBroker { pool });
        AutoScaler::new(broker)
    }

    #[test]
    fn test_scaling_action_scale_up() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 2 workers, high pressure conditions that should trigger scale up
        let metrics = create_test_autoscaler_metrics_with_high_pressure(2, 12);

        // Run scaling decision multiple times to satisfy consecutive signals requirement
        let action1 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");
        let action2 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        // The second action should trigger scaling due to consecutive signals
        match action2 {
            ScalingAction::ScaleUp(count) => assert_eq!(count, 2),
            _ => panic!(
                "Expected ScaleUp action, got {:?}. First action was {:?}",
                action2, action1
            ),
        }
    }

    #[test]
    fn test_scaling_action_scale_down() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 5 workers, low pressure conditions that should trigger scale down
        let metrics = create_test_autoscaler_metrics_with_low_pressure(5, 2);

        // Run scaling decision multiple times to satisfy consecutive signals requirement
        let action1 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");
        let action2 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        // The second action should trigger scaling due to consecutive signals
        match action2 {
            ScalingAction::ScaleDown(count) => assert_eq!(count, 1),
            _ => panic!(
                "Expected ScaleDown action, got {:?}. First action was {:?}",
                action2, action1
            ),
        }
    }

    #[test]
    fn test_scaling_action_no_action() {
        let config = AutoScalerConfig::default();

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 3 workers, moderate conditions that should not trigger scaling
        let metrics = create_test_autoscaler_metrics(3, 9);

        let action = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        match action {
            ScalingAction::NoAction => {}
            _ => panic!("Expected NoAction, got {:?}", action),
        }
    }

    #[test]
    fn test_scaling_action_at_max_workers() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 5,
            scale_up_count: 3,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 5 workers (at max), 20 tasks = 4 tasks per worker (> threshold but can't scale up)
        let metrics = create_test_autoscaler_metrics(5, 20);

        let action = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        match action {
            ScalingAction::NoAction => {}
            _ => panic!("Expected NoAction when at max workers"),
        }
    }

    #[test]
    fn test_scaling_action_at_min_workers() {
        let config = AutoScalerConfig {
            min_workers: 3,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 2,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 3 workers (at min), 1 task = 0.33 tasks per worker (< threshold but can't scale down)
        let metrics = create_test_autoscaler_metrics(3, 1);

        let action = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        match action {
            ScalingAction::NoAction => {}
            _ => panic!("Expected NoAction when at min workers"),
        }
    }

    #[test]
    fn test_scaling_action_limited_by_max_workers() {
        let config = AutoScalerConfig {
            min_workers: 1,
            max_workers: 5,
            scale_up_count: 10,
            scale_down_count: 1,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 3 workers, high pressure conditions that should trigger scale up but limited by max
        let metrics = create_test_autoscaler_metrics_with_high_pressure(3, 15);

        // Run scaling decision multiple times to satisfy consecutive signals requirement
        let action1 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");
        let action2 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        // The second action should trigger scaling due to consecutive signals
        match action2 {
            ScalingAction::ScaleUp(count) => assert_eq!(count, 2), // Limited by max_workers
            _ => panic!(
                "Expected ScaleUp action limited by max workers, got {:?}. First action was {:?}",
                action2, action1
            ),
        }
    }

    #[test]
    fn test_scaling_action_limited_by_min_workers() {
        let config = AutoScalerConfig {
            min_workers: 3,
            max_workers: 10,
            scale_up_count: 2,
            scale_down_count: 10,
            scaling_triggers: ScalingTriggers {
                queue_pressure_threshold: 0.75,
                worker_utilization_threshold: 0.80,
                task_complexity_threshold: 1.5,
                error_rate_threshold: 0.05,
                memory_pressure_threshold: 512.0,
            },
            enable_adaptive_thresholds: true,
            learning_rate: 0.1,
            adaptation_window_minutes: 30,
            scale_up_cooldown_seconds: 60,
            scale_down_cooldown_seconds: 300,
            consecutive_signals_required: 2,
            target_sla: SLATargets {
                max_p95_latency_ms: 5000.0,
                min_success_rate: 0.95,
                max_queue_wait_time_ms: 10000.0,
                target_worker_utilization: 0.70,
            },
        };

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 6 workers, low pressure conditions that should trigger scale down but limited by min
        let metrics = create_test_autoscaler_metrics_with_low_pressure(6, 3);

        // Run scaling decision multiple times to satisfy consecutive signals requirement
        let action1 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");
        let action2 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        // The second action should trigger scaling due to consecutive signals
        match action2 {
            ScalingAction::ScaleDown(count) => assert_eq!(count, 3), // Limited by min_workers
            _ => panic!(
                "Expected ScaleDown action limited by min workers, got {:?}. First action was {:?}",
                action2, action1
            ),
        }
    }

    #[test]
    fn test_scaling_action_zero_workers() {
        let config = AutoScalerConfig::default();

        let broker = Arc::new(crate::broker::RedisBroker {
            pool: deadpool_redis::Config::from_url("redis://localhost:6379")
                .create_pool(Some(deadpool_redis::Runtime::Tokio1))
                .expect("Failed to create pool"),
        });

        let mut autoscaler = AutoScaler::with_config(broker, config);

        // 0 workers, high pressure conditions (should definitely scale up)
        let metrics = create_test_autoscaler_metrics_with_high_pressure(0, 10);

        // Run scaling decision multiple times to satisfy consecutive signals requirement
        let action1 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");
        let action2 = autoscaler
            .decide_scaling_action(&metrics)
            .expect("Failed to decide scaling action");

        // The second action should trigger scaling due to consecutive signals
        match action2 {
            ScalingAction::ScaleUp(count) => assert_eq!(count, 2),
            _ => panic!(
                "Expected ScaleUp action with zero workers, got {:?}. First action was {:?}",
                action2, action1
            ),
        }
    }

    #[test]
    fn test_autoscaler_metrics_debug() {
        let metrics = create_test_autoscaler_metrics(5, 25);
        let debug_str = format!("{:?}", metrics);

        assert!(debug_str.contains("AutoScalerMetrics"));
        assert!(debug_str.contains("active_workers: 5"));
        assert!(debug_str.contains("total_pending_tasks: 25"));
        assert!(debug_str.contains("queue_pressure_score: 5"));
        assert!(debug_str.contains("worker_utilization: 0.6"));
        assert!(debug_str.contains("task_complexity_factor: 1"));
        assert!(debug_str.contains("error_rate:"));
        assert!(debug_str.contains("memory_pressure_mb: 250"));
        assert!(debug_str.contains("avg_queue_wait_time_ms: 0"));
        assert!(debug_str.contains("throughput_trend: 0"));
    }

    #[test]
    fn test_scaling_action_debug() {
        let scale_up = ScalingAction::ScaleUp(3);
        let scale_down = ScalingAction::ScaleDown(2);
        let no_action = ScalingAction::NoAction;

        assert!(format!("{:?}", scale_up).contains("ScaleUp(3)"));
        assert!(format!("{:?}", scale_down).contains("ScaleDown(2)"));
        assert!(format!("{:?}", no_action).contains("NoAction"));
    }

    #[test]
    fn test_autoscaler_config_clone() {
        let original = AutoScalerConfig::default();
        let cloned = original.clone();

        assert_eq!(original.min_workers, cloned.min_workers);
        assert_eq!(original.max_workers, cloned.max_workers);
        assert_eq!(original.scale_up_count, cloned.scale_up_count);
        assert_eq!(original.scale_down_count, cloned.scale_down_count);
        assert_eq!(
            original.scaling_triggers.queue_pressure_threshold,
            cloned.scaling_triggers.queue_pressure_threshold
        );
        assert_eq!(
            original.scaling_triggers.worker_utilization_threshold,
            cloned.scaling_triggers.worker_utilization_threshold
        );
        assert_eq!(
            original.scaling_triggers.task_complexity_threshold,
            cloned.scaling_triggers.task_complexity_threshold
        );
        assert_eq!(
            original.scaling_triggers.error_rate_threshold,
            cloned.scaling_triggers.error_rate_threshold
        );
        assert_eq!(
            original.scaling_triggers.memory_pressure_threshold,
            cloned.scaling_triggers.memory_pressure_threshold
        );
        assert_eq!(
            original.enable_adaptive_thresholds,
            cloned.enable_adaptive_thresholds
        );
        assert_eq!(original.learning_rate, cloned.learning_rate);
        assert_eq!(
            original.adaptation_window_minutes,
            cloned.adaptation_window_minutes
        );
        assert_eq!(
            original.scale_up_cooldown_seconds,
            cloned.scale_up_cooldown_seconds
        );
        assert_eq!(
            original.scale_down_cooldown_seconds,
            cloned.scale_down_cooldown_seconds
        );
        assert_eq!(
            original.consecutive_signals_required,
            cloned.consecutive_signals_required
        );
        assert_eq!(
            original.target_sla.max_p95_latency_ms,
            cloned.target_sla.max_p95_latency_ms
        );
        assert_eq!(
            original.target_sla.min_success_rate,
            cloned.target_sla.min_success_rate
        );
        assert_eq!(
            original.target_sla.max_queue_wait_time_ms,
            cloned.target_sla.max_queue_wait_time_ms
        );
        assert_eq!(
            original.target_sla.target_worker_utilization,
            cloned.target_sla.target_worker_utilization
        );
    }
}