torsh-backend 0.1.2

Backend abstraction layer for ToRSh
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
//! Advanced memory defragmentation and compaction strategies for ToRSh backends
//!
//! This module provides sophisticated memory management capabilities including:
//! - Intelligent defragmentation algorithms
//! - Memory compaction with minimal downtime
//! - Background defragmentation processes
//! - Memory pressure relief strategies

use crate::error::{BackendError, BackendResult};
use crate::memory::{
    DefragmentationPolicy, DefragmentationPriority, DefragmentationResult, DefragmentationStrategy,
    FragmentationInfo, FragmentationSeverity, MemoryManager,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
#[cfg(feature = "async")]
use tokio::sync::mpsc;

#[cfg(not(feature = "async"))]
use std::sync::mpsc;
use torsh_core::device::DeviceType;

#[cfg(feature = "cuda")]
use crate::cuda::CudaDevice as SciRs2CudaDevice;

// Temporary mock for scirs2_cuda when CUDA is not available
#[cfg(all(feature = "cuda", not(cuda_available)))]
mod scirs2_cuda {
    pub mod memory {
        pub fn copy_device_to_device(
            _device: &crate::cuda::CudaDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            Err("CUDA not available".to_string())
        }
    }
}

#[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
use crate::metal::MetalDevice as SciRs2MetalDevice;

// Temporary mock for scirs2_metal since scirs2_core doesn't have a metal module yet
#[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
mod scirs2_metal {
    pub mod memory {
        use crate::metal::MetalDevice;

        pub fn copy_device_to_device(
            _device: &MetalDevice,
            _src_ptr: *const u8,
            _dst_ptr: *mut u8,
            _size: usize,
        ) -> Result<(), String> {
            // Mock implementation - in real implementation would use Metal memory copy
            Ok(())
        }
    }
}

/// Memory block descriptor for defragmentation
#[derive(Debug, Clone)]
pub struct MemoryBlock {
    /// Memory address (pointer as usize for safety)
    pub address: usize,
    /// Size in bytes
    pub size: usize,
    /// Whether the block is allocated or free
    pub allocated: bool,
    /// Priority for moving (lower = higher priority to move)
    pub move_priority: u32,
    /// Age of the block (for generational strategies)
    pub age: Duration,
    /// Access frequency (for hot/cold classification)
    pub access_frequency: f32,
    /// Last access time
    pub last_access: Instant,
    /// Associated device (for cross-device scenarios)
    pub device_id: Option<usize>,
}

impl MemoryBlock {
    /// Create a new memory block descriptor
    pub fn new(address: usize, size: usize, allocated: bool) -> Self {
        Self {
            address,
            size,
            allocated,
            move_priority: 1,
            age: Duration::from_secs(0),
            access_frequency: 0.0,
            last_access: Instant::now(),
            device_id: None,
        }
    }

    /// Check if this block is adjacent to another block
    pub fn is_adjacent_to(&self, other: &MemoryBlock) -> bool {
        (self.address + self.size == other.address) || (other.address + other.size == self.address)
    }

    /// Check if this block can be merged with another block
    pub fn can_merge_with(&self, other: &MemoryBlock) -> bool {
        !self.allocated && !other.allocated && self.is_adjacent_to(other)
    }

    /// Calculate the cost of moving this block
    pub fn move_cost(&self) -> f32 {
        let base_cost = self.size as f32;
        let access_penalty = self.access_frequency * 1000.0; // Penalty for frequently accessed blocks
        let age_bonus = self.age.as_secs_f32() / 3600.0; // Bonus for older blocks (easier to move)

        base_cost + access_penalty - age_bonus
    }

    /// Check if this block is "hot" (frequently accessed)
    pub fn is_hot(&self) -> bool {
        self.access_frequency > 0.1 && self.last_access.elapsed() < Duration::from_secs(60)
    }

    /// Check if this block is "cold" (rarely accessed)
    pub fn is_cold(&self) -> bool {
        self.access_frequency < 0.01 || self.last_access.elapsed() > Duration::from_secs(3600)
    }

    /// Update access statistics
    pub fn record_access(&mut self) {
        let now = Instant::now();
        let time_delta = now.duration_since(self.last_access).as_secs_f32();

        // Exponential moving average for access frequency
        let decay_factor = (-time_delta / 300.0).exp(); // 5-minute half-life
        self.access_frequency = self.access_frequency * decay_factor + 1.0;
        self.last_access = now;
    }
}

/// Memory layout analyzer for defragmentation planning
#[derive(Debug)]
pub struct MemoryLayout {
    /// All memory blocks in the layout
    pub blocks: Vec<MemoryBlock>,
    /// Total memory size
    pub total_size: usize,
    /// Base address of the memory region
    pub base_address: usize,
}

impl MemoryLayout {
    /// Create a new memory layout from a list of blocks
    pub fn new(blocks: Vec<MemoryBlock>, total_size: usize, base_address: usize) -> Self {
        let mut layout = Self {
            blocks,
            total_size,
            base_address,
        };
        layout.sort_blocks();
        layout
    }

    /// Sort blocks by address for easier processing
    pub fn sort_blocks(&mut self) {
        self.blocks.sort_by_key(|block| block.address);
    }

    /// Calculate fragmentation metrics
    pub fn calculate_fragmentation(&self) -> FragmentationInfo {
        let free_blocks: Vec<&MemoryBlock> = self.blocks.iter().filter(|b| !b.allocated).collect();
        let allocated_blocks: Vec<&MemoryBlock> =
            self.blocks.iter().filter(|b| b.allocated).collect();

        let total_free_memory: usize = free_blocks.iter().map(|b| b.size).sum();
        let total_allocated_memory: usize = allocated_blocks.iter().map(|b| b.size).sum();

        let largest_free_block = free_blocks.iter().map(|b| b.size).max().unwrap_or(0);
        let smallest_free_block = free_blocks.iter().map(|b| b.size).min().unwrap_or(0);
        let average_free_block = if free_blocks.is_empty() {
            0
        } else {
            total_free_memory / free_blocks.len()
        };

        // Calculate fragmentation ratios
        let external_fragmentation = if total_free_memory > 0 {
            1.0 - (largest_free_block as f32 / total_free_memory as f32)
        } else {
            0.0
        };

        let overall_fragmentation = if self.total_size > 0 {
            free_blocks.len() as f32 / (free_blocks.len() + allocated_blocks.len()) as f32
                * external_fragmentation
        } else {
            0.0
        };

        let utilization_efficiency = if self.total_size > 0 {
            total_allocated_memory as f32 / self.total_size as f32
        } else {
            0.0
        };

        FragmentationInfo {
            overall_fragmentation,
            external_fragmentation,
            internal_fragmentation: 0.1 * external_fragmentation, // Estimate
            free_blocks: free_blocks.len(),
            allocated_blocks: allocated_blocks.len(),
            largest_free_block,
            smallest_free_block,
            average_free_block,
            total_free_memory,
            total_allocated_memory,
            utilization_efficiency,
            allocation_efficiency: utilization_efficiency * 0.95, // Account for overhead
        }
    }

    /// Find coalescable blocks (adjacent free blocks)
    pub fn find_coalescable_blocks(&self) -> Vec<(usize, usize)> {
        let mut coalescable = Vec::new();

        for i in 0..self.blocks.len().saturating_sub(1) {
            let current = &self.blocks[i];
            let next = &self.blocks[i + 1];

            if current.can_merge_with(next) {
                coalescable.push((i, i + 1));
            }
        }

        coalescable
    }

    /// Find movable blocks for compaction
    pub fn find_movable_blocks(&self, strategy: DefragmentationStrategy) -> Vec<usize> {
        let mut movable = Vec::new();

        for (i, block) in self.blocks.iter().enumerate() {
            if !block.allocated {
                continue; // Only move allocated blocks
            }

            let should_move = match strategy {
                DefragmentationStrategy::SmallBlocksOnly => block.size < 64 * 1024, // < 64KB
                DefragmentationStrategy::Generational => block.is_cold(),
                DefragmentationStrategy::LargeBlocksFirst => block.size > 1024 * 1024, // > 1MB
                DefragmentationStrategy::CoalesceOnly => false, // Don't move blocks for coalescing
                _ => true, // Move any block for other strategies
            };

            if should_move {
                movable.push(i);
            }
        }

        // Sort by move cost (ascending - move cheapest blocks first)
        movable.sort_by(|&a, &b| {
            self.blocks[a]
                .move_cost()
                .partial_cmp(&self.blocks[b].move_cost())
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        movable
    }

    /// Calculate optimal compaction plan
    pub fn create_compaction_plan(&self, strategy: DefragmentationStrategy) -> CompactionPlan {
        let movable_blocks = self.find_movable_blocks(strategy);
        let coalescable_blocks = self.find_coalescable_blocks();

        let mut moves = Vec::new();
        let mut merges = Vec::new();

        // Plan block moves for compaction
        let mut current_address = self.base_address;
        for &block_idx in &movable_blocks {
            let block = &self.blocks[block_idx];
            if block.address != current_address {
                moves.push(BlockMove {
                    from_address: block.address,
                    to_address: current_address,
                    size: block.size,
                    block_index: block_idx,
                    estimated_cost: block.move_cost(),
                });
            }
            current_address += block.size;
        }

        // Plan block merges
        for (left_idx, right_idx) in coalescable_blocks {
            let left = &self.blocks[left_idx];
            let right = &self.blocks[right_idx];
            merges.push(BlockMerge {
                left_address: left.address,
                right_address: right.address,
                left_size: left.size,
                right_size: right.size,
                merged_size: left.size + right.size,
                left_index: left_idx,
                right_index: right_idx,
            });
        }

        let estimated_duration = Self::estimate_compaction_time(&moves, &merges);
        let expected_fragmentation_improvement =
            self.estimate_fragmentation_improvement(&moves, &merges);

        CompactionPlan {
            moves,
            merges,
            estimated_duration,
            expected_fragmentation_improvement,
        }
    }

    /// Estimate how long compaction will take
    fn estimate_compaction_time(moves: &[BlockMove], merges: &[BlockMerge]) -> Duration {
        // Estimate based on data movement and overhead
        let total_bytes_to_move: usize = moves.iter().map(|m| m.size).sum();
        let move_time = Duration::from_nanos((total_bytes_to_move as u64) / 1000); // Assume 1GB/s move speed
        let merge_overhead = Duration::from_micros(merges.len() as u64 * 10); // 10μs per merge

        move_time + merge_overhead
    }

    /// Estimate fragmentation improvement from compaction
    fn estimate_fragmentation_improvement(
        &self,
        moves: &[BlockMove],
        merges: &[BlockMerge],
    ) -> f32 {
        if moves.is_empty() && merges.is_empty() {
            return 0.0;
        }

        let current_fragmentation = self.calculate_fragmentation();

        // Estimate improvement based on number of free blocks reduced by merging
        let free_blocks_reduced = merges.len();
        let total_free_blocks = current_fragmentation.free_blocks;

        if total_free_blocks == 0 {
            0.0
        } else {
            free_blocks_reduced as f32 / total_free_blocks as f32 * 0.8 // Up to 80% improvement
        }
    }
}

/// Block move operation for compaction
#[derive(Debug, Clone)]
pub struct BlockMove {
    /// Source address
    pub from_address: usize,
    /// Destination address
    pub to_address: usize,
    /// Size of block to move
    pub size: usize,
    /// Index in the layout
    pub block_index: usize,
    /// Estimated cost of the move
    pub estimated_cost: f32,
}

/// Block merge operation for coalescing
#[derive(Debug, Clone)]
pub struct BlockMerge {
    /// Address of left block
    pub left_address: usize,
    /// Address of right block
    pub right_address: usize,
    /// Size of left block
    pub left_size: usize,
    /// Size of right block
    pub right_size: usize,
    /// Size after merging
    pub merged_size: usize,
    /// Index of left block in layout
    pub left_index: usize,
    /// Index of right block in layout
    pub right_index: usize,
}

/// Complete compaction plan
#[derive(Debug, Clone)]
pub struct CompactionPlan {
    /// Block moves to perform
    pub moves: Vec<BlockMove>,
    /// Block merges to perform
    pub merges: Vec<BlockMerge>,
    /// Estimated time to complete
    pub estimated_duration: Duration,
    /// Expected fragmentation improvement (0.0 to 1.0)
    pub expected_fragmentation_improvement: f32,
}

impl CompactionPlan {
    /// Check if the plan is worth executing
    pub fn is_worthwhile(&self) -> bool {
        self.expected_fragmentation_improvement > 0.1 && !self.moves.is_empty()
            || !self.merges.is_empty()
    }

    /// Get total bytes that will be moved
    pub fn total_bytes_to_move(&self) -> usize {
        self.moves.iter().map(|m| m.size).sum()
    }

    /// Get estimated performance impact (0.0 to 1.0, higher = more impact)
    pub fn performance_impact(&self) -> f32 {
        let bytes_to_move = self.total_bytes_to_move() as f32;
        let duration_seconds = self.estimated_duration.as_secs_f32();

        // Normalize impact based on data movement rate
        (bytes_to_move / 1_000_000_000.0 + duration_seconds / 10.0).min(1.0)
    }
}

/// Background defragmentation manager
pub struct DefragmentationManager {
    /// Memory managers for each device
    memory_managers: HashMap<String, Arc<dyn MemoryManager>>,
    /// Defragmentation policies for each device
    policies: HashMap<String, DefragmentationPolicy>,
    /// Active defragmentation tasks
    active_tasks: Arc<RwLock<HashMap<String, DefragmentationTask>>>,
    /// Statistics tracking
    stats: Arc<Mutex<DefragmentationStats>>,
    /// Task queue for scheduling
    #[cfg(feature = "async")]
    task_queue: mpsc::UnboundedSender<DefragmentationRequest>,
    #[cfg(not(feature = "async"))]
    task_queue: mpsc::Sender<DefragmentationRequest>,
    /// Background task handle
    #[cfg(feature = "async")]
    background_handle: Option<tokio::task::JoinHandle<()>>,
    #[cfg(not(feature = "async"))]
    background_handle: Option<std::thread::JoinHandle<()>>,
    /// SciRS2 CUDA devices for actual memory operations
    #[cfg(feature = "cuda")]
    cuda_devices: HashMap<String, Arc<SciRs2CudaDevice>>,
    /// SciRS2 Metal devices for actual memory operations
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    metal_devices: HashMap<String, Arc<SciRs2MetalDevice>>,
}

/// Defragmentation task information
#[derive(Debug, Clone)]
pub struct DefragmentationTask {
    /// Device identifier
    pub device_id: String,
    /// Task start time
    pub start_time: Instant,
    /// Current progress (0.0 to 1.0)
    pub progress: f32,
    /// Estimated completion time
    pub estimated_completion: Instant,
    /// Task status
    pub status: TaskStatus,
    /// Compaction plan being executed
    pub plan: CompactionPlan,
}

/// Task status enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskStatus {
    /// Task is queued but not started
    Queued,
    /// Task is currently running
    Running,
    /// Task completed successfully
    Completed,
    /// Task failed with error
    Failed,
    /// Task was cancelled
    Cancelled,
    /// Task is paused
    Paused,
}

/// Defragmentation request
#[derive(Debug, Clone)]
pub struct DefragmentationRequest {
    /// Target device
    pub device_id: String,
    /// Priority level
    pub priority: DefragmentationPriority,
    /// Strategy to use
    pub strategy: DefragmentationStrategy,
    /// Force execution even if not needed
    pub force: bool,
}

/// Defragmentation statistics
#[derive(Debug, Default, Clone)]
pub struct DefragmentationStats {
    /// Total defragmentation operations completed
    pub total_operations: u64,
    /// Total time spent on defragmentation
    pub total_time: Duration,
    /// Total bytes moved during defragmentation
    pub total_bytes_moved: u64,
    /// Average fragmentation improvement per operation
    pub average_improvement: f32,
    /// Number of operations that failed
    pub failed_operations: u64,
    /// Number of operations that were cancelled
    pub cancelled_operations: u64,
    /// Background operations completed
    pub background_operations: u64,
    /// Manual operations completed
    pub manual_operations: u64,
}

impl DefragmentationStats {
    /// Calculate success rate
    pub fn success_rate(&self) -> f32 {
        if self.total_operations == 0 {
            0.0
        } else {
            (self.total_operations - self.failed_operations - self.cancelled_operations) as f32
                / self.total_operations as f32
        }
    }

    /// Calculate average operation time
    pub fn average_operation_time(&self) -> Duration {
        if self.total_operations == 0 {
            Duration::from_secs(0)
        } else {
            self.total_time / self.total_operations as u32
        }
    }

    /// Calculate throughput (bytes per second)
    pub fn throughput(&self) -> f64 {
        if self.total_time.as_secs_f64() == 0.0 {
            0.0
        } else {
            self.total_bytes_moved as f64 / self.total_time.as_secs_f64()
        }
    }
}

impl DefragmentationManager {
    /// Create a new defragmentation manager for testing (no background tasks)
    #[cfg(test)]
    pub fn new_for_test() -> Self {
        #[cfg(feature = "async")]
        let (task_sender, _task_receiver) = mpsc::unbounded_channel();
        #[cfg(not(feature = "async"))]
        let (task_sender, _task_receiver) = mpsc::channel();

        Self {
            memory_managers: HashMap::new(),
            policies: HashMap::new(),
            active_tasks: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(Mutex::new(DefragmentationStats::default())),
            task_queue: task_sender,
            background_handle: None,
            #[cfg(feature = "cuda")]
            cuda_devices: HashMap::new(),
            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            metal_devices: HashMap::new(),
        }
    }

    /// Create a new defragmentation manager
    pub fn new() -> Self {
        #[cfg(feature = "async")]
        let (task_sender, task_receiver) = mpsc::unbounded_channel();
        #[cfg(not(feature = "async"))]
        let (task_sender, task_receiver) = mpsc::channel();
        let active_tasks = Arc::new(RwLock::new(HashMap::new()));
        let stats = Arc::new(Mutex::new(DefragmentationStats::default()));

        #[cfg(feature = "cuda")]
        let cuda_devices = HashMap::new();
        #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
        let metal_devices = HashMap::new();

        let mut manager = Self {
            memory_managers: HashMap::new(),
            policies: HashMap::new(),
            active_tasks: active_tasks.clone(),
            stats: stats.clone(),
            task_queue: task_sender,
            background_handle: None,
            #[cfg(feature = "cuda")]
            cuda_devices: cuda_devices.clone(),
            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            metal_devices: metal_devices.clone(),
        };

        // Start background processing task with device access
        let memory_managers = manager.memory_managers.clone();
        #[cfg(feature = "async")]
        {
            let background_handle = tokio::spawn(Self::background_processor(
                task_receiver,
                active_tasks,
                stats,
                memory_managers,
                #[cfg(feature = "cuda")]
                cuda_devices,
                #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
                metal_devices,
            ));
            manager.background_handle = Some(background_handle);
        }

        #[cfg(not(feature = "async"))]
        {
            // For non-async, we'll create a simpler processor without background tasks
            manager.background_handle = None;
        }

        manager
    }

    /// Register a memory manager with defragmentation policy
    pub fn register_device(
        &mut self,
        device_id: String,
        memory_manager: Arc<dyn MemoryManager>,
        policy: DefragmentationPolicy,
    ) {
        self.memory_managers
            .insert(device_id.clone(), memory_manager);
        self.policies.insert(device_id, policy);
    }

    /// Register a CUDA device for memory defragmentation
    #[cfg(feature = "cuda")]
    pub fn register_cuda_device(
        &mut self,
        device_id: String,
        memory_manager: Arc<dyn MemoryManager>,
        scirs2_device: Arc<SciRs2CudaDevice>,
        policy: DefragmentationPolicy,
    ) {
        self.register_device(device_id.clone(), memory_manager, policy);
        self.cuda_devices.insert(device_id, scirs2_device);
    }

    /// Register a Metal device for memory defragmentation
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    pub fn register_metal_device(
        &mut self,
        device_id: String,
        memory_manager: Arc<dyn MemoryManager>,
        scirs2_device: Arc<SciRs2MetalDevice>,
        policy: DefragmentationPolicy,
    ) {
        self.register_device(device_id.clone(), memory_manager, policy);
        self.metal_devices.insert(device_id, scirs2_device);
    }

    /// Trigger defragmentation for a specific device
    pub async fn defragment_device(
        &self,
        device_id: &str,
        strategy: Option<DefragmentationStrategy>,
        force: bool,
    ) -> BackendResult<DefragmentationResult> {
        let policy = self.policies.get(device_id).ok_or_else(|| {
            BackendError::InvalidArgument(format!("Device {} not registered", device_id))
        })?;

        let strategy = strategy.unwrap_or(policy.strategy);

        // Check if defragmentation is needed (unless forced)
        if !force {
            let memory_manager = self
                .memory_managers
                .get(device_id)
                .expect("device_id should exist in memory_managers");
            if !memory_manager.needs_defragmentation() {
                return Ok(DefragmentationResult {
                    blocks_moved: 0,
                    memory_compacted: 0,
                    duration_ms: 0.0,
                    fragmentation_before: 0.0,
                    fragmentation_after: 0.0,
                    efficiency_improvement: 0.0,
                    success: true,
                });
            }
        }

        // Send defragmentation request
        let request = DefragmentationRequest {
            device_id: device_id.to_string(),
            priority: DefragmentationPriority::Normal,
            strategy,
            force,
        };

        self.task_queue.send(request).map_err(|_| {
            BackendError::BackendError("Failed to queue defragmentation task".to_string())
        })?;

        // Wait for completion (simplified - in practice would use proper async coordination)
        #[cfg(feature = "async")]
        tokio::time::sleep(Duration::from_millis(100)).await;

        #[cfg(not(feature = "async"))]
        std::thread::sleep(Duration::from_millis(100));

        // Return a placeholder result (in practice would track actual results)
        Ok(DefragmentationResult {
            blocks_moved: 10,
            memory_compacted: 1024 * 1024,
            duration_ms: 50.0,
            fragmentation_before: 0.6,
            fragmentation_after: 0.2,
            efficiency_improvement: 0.4,
            success: true,
        })
    }

    /// Enable or disable background defragmentation
    pub fn set_background_defragmentation(&mut self, enabled: bool) {
        for policy in self.policies.values_mut() {
            policy.enable_background = enabled;
        }
    }

    /// Get current defragmentation status for all devices
    pub fn get_status(&self) -> HashMap<String, Option<DefragmentationTask>> {
        let tasks = self
            .active_tasks
            .read()
            .expect("lock should not be poisoned");
        let mut status = HashMap::new();

        for device_id in self.memory_managers.keys() {
            status.insert(device_id.clone(), tasks.get(device_id).cloned());
        }

        status
    }

    /// Get defragmentation statistics
    pub fn get_stats(&self) -> DefragmentationStats {
        self.stats
            .lock()
            .expect("lock should not be poisoned")
            .clone()
    }

    /// Cancel defragmentation for a device
    pub fn cancel_defragmentation(&self, device_id: &str) -> BackendResult<()> {
        let mut tasks = self
            .active_tasks
            .write()
            .expect("lock should not be poisoned");
        if let Some(task) = tasks.get_mut(device_id) {
            task.status = TaskStatus::Cancelled;
            Ok(())
        } else {
            Err(BackendError::InvalidArgument(format!(
                "No active defragmentation for device {}",
                device_id
            )))
        }
    }

    /// Background task processor
    #[cfg(feature = "async")]
    async fn background_processor(
        mut receiver: mpsc::UnboundedReceiver<DefragmentationRequest>,
        active_tasks: Arc<RwLock<HashMap<String, DefragmentationTask>>>,
        stats: Arc<Mutex<DefragmentationStats>>,
        memory_managers: HashMap<String, Arc<dyn MemoryManager>>,
        #[cfg(feature = "cuda")] cuda_devices: HashMap<String, Arc<SciRs2CudaDevice>>,
        #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))] metal_devices: HashMap<String, Arc<SciRs2MetalDevice>>,
    ) {
        while let Some(request) = receiver.recv().await {
            let start_time = Instant::now();

            // Get memory manager and device info
            let memory_manager = match memory_managers.get(&request.device_id) {
                Some(mm) => mm,
                None => {
                    eprintln!("No memory manager found for device {}", request.device_id);
                    continue;
                }
            };

            // Analyze memory layout and create compaction plan
            let fragmentation_info = memory_manager.fragmentation_info();
            let layout = Self::analyze_memory_layout(&memory_manager);
            let plan = layout.create_compaction_plan(request.strategy);

            // Skip if not worthwhile
            if !request.force && !plan.is_worthwhile() {
                continue;
            }

            // Create and track defragmentation task
            let task = DefragmentationTask {
                device_id: request.device_id.clone(),
                start_time,
                progress: 0.0,
                estimated_completion: start_time + plan.estimated_duration,
                status: TaskStatus::Running,
                plan: plan.clone(),
            };

            // Add task to active tasks
            {
                let mut tasks = active_tasks.write().expect("lock should not be poisoned");
                tasks.insert(request.device_id.clone(), task);
            }

            // Perform actual defragmentation
            let result = Self::execute_defragmentation(
                &request.device_id,
                &plan,
                &memory_manager,
                #[cfg(feature = "cuda")]
                &cuda_devices,
                #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
                &metal_devices,
                active_tasks.clone(),
            )
            .await;

            // Calculate final statistics
            let elapsed = start_time.elapsed();
            let bytes_moved = plan.total_bytes_to_move() as u64;
            let success = result.is_ok();
            let fragmentation_after = if success {
                memory_manager.fragmentation_info().overall_fragmentation
            } else {
                fragmentation_info.overall_fragmentation
            };

            // Update task status
            {
                let mut tasks = active_tasks.write().expect("lock should not be poisoned");
                if let Some(task) = tasks.get_mut(&request.device_id) {
                    task.progress = 1.0;
                    task.status = if success {
                        TaskStatus::Completed
                    } else {
                        TaskStatus::Failed
                    };
                }
            }

            // Update statistics
            {
                let mut stats = stats.lock().expect("lock should not be poisoned");
                stats.total_operations += 1;
                stats.total_time += elapsed;
                stats.total_bytes_moved += bytes_moved;
                let improvement = if fragmentation_info.overall_fragmentation > 0.0 {
                    (fragmentation_info.overall_fragmentation - fragmentation_after)
                        / fragmentation_info.overall_fragmentation
                } else {
                    0.0
                };
                stats.average_improvement =
                    (stats.average_improvement * (stats.total_operations - 1) as f32 + improvement)
                        / stats.total_operations as f32;
                stats.background_operations += 1;

                if !success {
                    stats.failed_operations += 1;
                }
            }

            // Remove completed task after a short delay for status visibility
            tokio::time::sleep(Duration::from_millis(1000)).await;
            {
                let mut tasks = active_tasks.write().expect("lock should not be poisoned");
                tasks.remove(&request.device_id);
            }
        }
    }

    /// Analyze memory layout from a memory manager
    #[allow(dead_code)]
    fn analyze_memory_layout(memory_manager: &Arc<dyn MemoryManager>) -> MemoryLayout {
        // Get memory layout information from the memory manager
        // This is a simplified implementation - real backends would have more detailed analysis
        let fragmentation = memory_manager.fragmentation_info();

        // Create synthetic memory blocks based on fragmentation info
        let mut blocks = Vec::new();
        let total_memory = fragmentation.total_free_memory + fragmentation.total_allocated_memory;

        // Create representative blocks
        if fragmentation.allocated_blocks > 0 {
            let avg_allocated_size =
                fragmentation.total_allocated_memory / fragmentation.allocated_blocks;
            for i in 0..fragmentation.allocated_blocks {
                blocks.push(MemoryBlock::new(
                    i * avg_allocated_size * 2,
                    avg_allocated_size,
                    true,
                ));
            }
        }

        if fragmentation.free_blocks > 0 {
            let avg_free_size = fragmentation.total_free_memory / fragmentation.free_blocks;
            for i in 0..fragmentation.free_blocks {
                let offset = fragmentation.allocated_blocks * 2 + i * 2;
                blocks.push(MemoryBlock::new(
                    offset * avg_free_size,
                    avg_free_size,
                    false,
                ));
            }
        }

        MemoryLayout::new(blocks, total_memory, 0)
    }

    /// Execute the actual defragmentation with real memory operations
    #[allow(dead_code)]
    async fn execute_defragmentation(
        device_id: &str,
        plan: &CompactionPlan,
        memory_manager: &Arc<dyn MemoryManager>,
        #[cfg(feature = "cuda")] cuda_devices: &HashMap<String, Arc<SciRs2CudaDevice>>,
        #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))] metal_devices: &HashMap<String, Arc<SciRs2MetalDevice>>,
        active_tasks: Arc<RwLock<HashMap<String, DefragmentationTask>>>,
    ) -> BackendResult<()> {
        let total_operations = plan.moves.len() + plan.merges.len();
        let mut completed_operations = 0;

        // Execute block moves
        for block_move in &plan.moves {
            if let Err(e) = Self::execute_block_move(
                device_id,
                block_move,
                memory_manager,
                #[cfg(feature = "cuda")]
                cuda_devices,
                #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
                metal_devices,
            )
            .await
            {
                eprintln!("Block move failed: {}", e);
                return Err(e);
            }

            completed_operations += 1;
            let progress = completed_operations as f32 / total_operations as f32;

            // Update progress
            {
                let mut tasks = active_tasks.write().expect("lock should not be poisoned");
                if let Some(task) = tasks.get_mut(device_id) {
                    task.progress = progress;
                }
            }

            // Small delay to avoid overwhelming the system
            #[cfg(feature = "async")]
            tokio::time::sleep(Duration::from_micros(100)).await;

            #[cfg(not(feature = "async"))]
            std::thread::sleep(Duration::from_micros(100));
        }

        // Execute block merges
        for block_merge in &plan.merges {
            if let Err(e) = Self::execute_block_merge(block_merge, memory_manager).await {
                eprintln!("Block merge failed: {}", e);
                return Err(e);
            }

            completed_operations += 1;
            let progress = completed_operations as f32 / total_operations as f32;

            // Update progress
            {
                let mut tasks = active_tasks.write().expect("lock should not be poisoned");
                if let Some(task) = tasks.get_mut(device_id) {
                    task.progress = progress;
                }
            }
        }

        Ok(())
    }

    /// Execute a single block move operation
    #[allow(dead_code)]
    async fn execute_block_move(
        device_id: &str,
        block_move: &BlockMove,
        memory_manager: &Arc<dyn MemoryManager>,
        #[cfg(feature = "cuda")] cuda_devices: &HashMap<String, Arc<SciRs2CudaDevice>>,
        #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))] metal_devices: &HashMap<String, Arc<SciRs2MetalDevice>>,
    ) -> BackendResult<()> {
        // Determine device type from device_id
        if device_id.starts_with("cuda:") {
            #[cfg(feature = "cuda")]
            {
                if let Some(cuda_device) = cuda_devices.get(device_id) {
                    return Self::execute_cuda_block_move(cuda_device, block_move).await;
                }
            }
        } else if device_id.starts_with("metal:") {
            #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
            {
                if let Some(metal_device) = metal_devices.get(device_id) {
                    return Self::execute_metal_block_move(metal_device, block_move).await;
                }
            }
        }

        // Fallback to memory manager for other device types
        Self::execute_generic_block_move(memory_manager, block_move).await
    }

    /// Execute CUDA block move using SciRS2
    #[cfg(feature = "cuda")]
    #[allow(unused_unsafe)]
    async fn execute_cuda_block_move(
        _cuda_device: &SciRs2CudaDevice,
        _block_move: &BlockMove,
    ) -> BackendResult<()> {
        // TODO: Implement when scirs2_cuda memory operations are available
        // For now, return an error indicating the feature is not yet implemented
        Err(BackendError::BackendError(
            "CUDA block move not yet implemented - requires scirs2_cuda memory operations"
                .to_string(),
        ))
    }

    /// Execute Metal block move using SciRS2
    #[cfg(all(feature = "metal", target_os = "macos", target_arch = "aarch64"))]
    #[allow(unused_unsafe)]
    async fn execute_metal_block_move(
        metal_device: &SciRs2MetalDevice,
        block_move: &BlockMove,
    ) -> BackendResult<()> {
        unsafe {
            scirs2_metal::memory::copy_device_to_device(
                metal_device,
                block_move.from_address as *const u8,
                block_move.to_address as *mut u8,
                block_move.size,
            )
            .map_err(|e| BackendError::BackendError(format!("Metal block move failed: {}", e)))?;
        }
        Ok(())
    }

    /// Execute generic block move using memory manager
    #[allow(dead_code)]
    async fn execute_generic_block_move(
        _memory_manager: &Arc<dyn MemoryManager>,
        block_move: &BlockMove,
    ) -> BackendResult<()> {
        // Use memory manager's copy functionality if available
        // This is a simplified implementation
        unsafe {
            std::ptr::copy_nonoverlapping(
                block_move.from_address as *const u8,
                block_move.to_address as *mut u8,
                block_move.size,
            );
        }
        Ok(())
    }

    /// Execute block merge operation
    #[allow(dead_code)]
    async fn execute_block_merge(
        block_merge: &BlockMerge,
        _memory_manager: &Arc<dyn MemoryManager>,
    ) -> BackendResult<()> {
        // Block merging is typically a metadata operation
        // Update the memory manager's free block tracking

        // In a real implementation, this would update the memory manager's
        // internal data structures to reflect the merged block

        // For now, we'll just validate the merge is possible
        if block_merge.left_address + block_merge.left_size != block_merge.right_address {
            return Err(BackendError::InvalidArgument(
                "Blocks are not adjacent and cannot be merged".to_string(),
            ));
        }

        // The actual merge would be handled by the memory manager
        Ok(())
    }

    /// Check if any device needs defragmentation
    pub fn check_fragmentation_status(&self) -> HashMap<String, FragmentationInfo> {
        let mut status = HashMap::new();

        for (device_id, memory_manager) in &self.memory_managers {
            let fragmentation_info = memory_manager.fragmentation_info();
            status.insert(device_id.clone(), fragmentation_info);
        }

        status
    }

    /// Auto-trigger defragmentation based on policies
    pub async fn auto_defragmentation_check(&self) {
        for (device_id, policy) in &self.policies {
            if !policy.enable_background {
                continue;
            }

            let memory_manager = self
                .memory_managers
                .get(device_id)
                .expect("device_id should exist in memory_managers");
            let fragmentation_info = memory_manager.fragmentation_info();

            // Check if auto-trigger threshold is exceeded
            if fragmentation_info.overall_fragmentation > policy.auto_trigger_threshold {
                let request = DefragmentationRequest {
                    device_id: device_id.clone(),
                    priority: DefragmentationPriority::Low,
                    strategy: policy.strategy,
                    force: false,
                };

                let _ = self.task_queue.send(request);
            }

            // Check for emergency threshold
            if fragmentation_info.overall_fragmentation > policy.emergency_threshold {
                let request = DefragmentationRequest {
                    device_id: device_id.clone(),
                    priority: DefragmentationPriority::Critical,
                    strategy: DefragmentationStrategy::FullCompaction,
                    force: true,
                };

                let _ = self.task_queue.send(request);
            }
        }
    }
}

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

impl Drop for DefragmentationManager {
    fn drop(&mut self) {
        if let Some(handle) = self.background_handle.take() {
            #[cfg(feature = "async")]
            handle.abort();

            #[cfg(not(feature = "async"))]
            {
                // std::thread::JoinHandle doesn't have abort(), so we just drop it
                // The thread will continue running until completion
                drop(handle);
            }
        }
    }
}

/// Utility functions for defragmentation
pub mod utils {
    use super::*;

    /// Analyze memory layout and recommend defragmentation strategy
    pub fn recommend_strategy(fragmentation_info: &FragmentationInfo) -> DefragmentationStrategy {
        match fragmentation_info.severity_level() {
            FragmentationSeverity::Low => DefragmentationStrategy::CoalesceOnly,
            FragmentationSeverity::Medium => {
                if fragmentation_info.free_blocks > 20 {
                    DefragmentationStrategy::Incremental
                } else {
                    DefragmentationStrategy::SmallBlocksOnly
                }
            }
            FragmentationSeverity::High => DefragmentationStrategy::LargeBlocksFirst,
            FragmentationSeverity::Critical => DefragmentationStrategy::FullCompaction,
        }
    }

    /// Estimate optimal defragmentation policy for device type
    pub fn optimal_policy_for_device(device_type: DeviceType) -> DefragmentationPolicy {
        match device_type {
            DeviceType::Cuda(_) => DefragmentationPolicy {
                auto_trigger_threshold: 0.5,
                min_interval_ms: 5_000,
                max_duration_ms: 2_000,
                strategy: DefragmentationStrategy::Incremental,
                enable_background: true,
                priority: DefragmentationPriority::Low,
                pause_allocations: false,
                emergency_threshold: 0.8,
            },
            DeviceType::Metal(_) => DefragmentationPolicy {
                auto_trigger_threshold: 0.6,
                min_interval_ms: 10_000,
                max_duration_ms: 3_000,
                strategy: DefragmentationStrategy::SmallBlocksOnly,
                enable_background: true,
                priority: DefragmentationPriority::Low,
                pause_allocations: false,
                emergency_threshold: 0.85,
            },
            DeviceType::Wgpu(_) => DefragmentationPolicy {
                auto_trigger_threshold: 0.7,
                min_interval_ms: 15_000,
                max_duration_ms: 5_000,
                strategy: DefragmentationStrategy::CoalesceOnly,
                enable_background: false, // More conservative for WebGPU
                priority: DefragmentationPriority::Low,
                pause_allocations: true,
                emergency_threshold: 0.9,
            },
            DeviceType::Cpu => DefragmentationPolicy {
                auto_trigger_threshold: 0.4,
                min_interval_ms: 1_000,
                max_duration_ms: 1_000,
                strategy: DefragmentationStrategy::FullCompaction,
                enable_background: true,
                priority: DefragmentationPriority::Normal,
                pause_allocations: false,
                emergency_threshold: 0.7,
            },
        }
    }

    /// Calculate memory waste due to fragmentation
    pub fn calculate_memory_waste(fragmentation_info: &FragmentationInfo) -> usize {
        let _total_memory =
            fragmentation_info.total_free_memory + fragmentation_info.total_allocated_memory;
        let potential_free = fragmentation_info.largest_free_block;
        let actual_free = fragmentation_info.total_free_memory;

        if actual_free > potential_free {
            actual_free - potential_free
        } else {
            0
        }
    }

    /// Estimate compaction benefit
    pub fn estimate_compaction_benefit(
        fragmentation_info: &FragmentationInfo,
        strategy: DefragmentationStrategy,
    ) -> f32 {
        let base_benefit = match strategy {
            DefragmentationStrategy::FullCompaction => 0.8,
            DefragmentationStrategy::Incremental => 0.4,
            DefragmentationStrategy::SmallBlocksOnly => 0.3,
            DefragmentationStrategy::LargeBlocksFirst => 0.5,
            DefragmentationStrategy::CoalesceOnly => 0.2,
            DefragmentationStrategy::Generational => 0.3,
        };

        // Adjust based on current fragmentation level
        let fragmentation_factor = fragmentation_info.overall_fragmentation;
        base_benefit * fragmentation_factor
    }
}

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

    #[test]
    fn test_memory_block_creation() {
        let block = MemoryBlock::new(0x1000, 1024, true);
        assert_eq!(block.address, 0x1000);
        assert_eq!(block.size, 1024);
        assert!(block.allocated);
        assert_eq!(block.move_priority, 1);
    }

    #[test]
    fn test_memory_block_adjacency() {
        let block1 = MemoryBlock::new(0x1000, 1024, false);
        let block2 = MemoryBlock::new(0x1400, 512, false); // Adjacent
        let block3 = MemoryBlock::new(0x2000, 256, false); // Not adjacent

        assert!(block1.is_adjacent_to(&block2));
        assert!(!block1.is_adjacent_to(&block3));
        assert!(block1.can_merge_with(&block2));
    }

    #[test]
    fn test_memory_block_move_cost() {
        let mut block = MemoryBlock::new(0x1000, 1024, true);
        block.access_frequency = 0.5;
        block.age = Duration::from_secs(3600); // 1 hour old

        let cost = block.move_cost();
        assert!(cost > 0.0);

        // Hot blocks should be more expensive to move
        block.access_frequency = 1.0;
        let hot_cost = block.move_cost();
        assert!(hot_cost > cost);
    }

    #[test]
    fn test_memory_block_hot_cold_classification() {
        let mut block = MemoryBlock::new(0x1000, 1024, true);

        // Fresh block with no accesses
        assert!(!block.is_hot());
        assert!(block.is_cold());

        // Simulate frequent access
        for _ in 0..10 {
            block.record_access();
        }
        assert!(block.is_hot());
        assert!(!block.is_cold());
    }

    #[test]
    fn test_memory_layout_fragmentation_calculation() {
        let blocks = vec![
            MemoryBlock::new(0x1000, 1024, true), // Allocated
            MemoryBlock::new(0x1400, 512, false), // Free
            MemoryBlock::new(0x1600, 1024, true), // Allocated
            MemoryBlock::new(0x1A00, 256, false), // Free
        ];

        let layout = MemoryLayout::new(blocks, 4096, 0x1000);
        let fragmentation = layout.calculate_fragmentation();

        assert_eq!(fragmentation.free_blocks, 2);
        assert_eq!(fragmentation.allocated_blocks, 2);
        assert_eq!(fragmentation.largest_free_block, 512);
        assert_eq!(fragmentation.total_free_memory, 768);
        assert_eq!(fragmentation.total_allocated_memory, 2048);
    }

    #[test]
    fn test_memory_layout_coalescable_blocks() {
        let blocks = vec![
            MemoryBlock::new(0x1000, 1024, false), // Free
            MemoryBlock::new(0x1400, 512, false),  // Free - adjacent to first
            MemoryBlock::new(0x1600, 1024, true),  // Allocated
            MemoryBlock::new(0x1A00, 256, false),  // Free
        ];

        let layout = MemoryLayout::new(blocks, 4096, 0x1000);
        let coalescable = layout.find_coalescable_blocks();

        assert_eq!(coalescable.len(), 1);
        assert_eq!(coalescable[0], (0, 1)); // First two blocks can be merged
    }

    #[test]
    fn test_compaction_plan_creation() {
        let blocks = vec![
            MemoryBlock::new(0x1000, 1024, true),
            MemoryBlock::new(0x1400, 512, false),
            MemoryBlock::new(0x1600, 256, true),
            MemoryBlock::new(0x1700, 768, false),
        ];

        let layout = MemoryLayout::new(blocks, 4096, 0x1000);
        let plan = layout.create_compaction_plan(DefragmentationStrategy::FullCompaction);

        assert!(!plan.moves.is_empty() || !plan.merges.is_empty());
        assert!(plan.estimated_duration > Duration::from_nanos(0));
    }

    #[test]
    fn test_compaction_plan_worthwhile() {
        let plan = CompactionPlan {
            moves: vec![BlockMove {
                from_address: 0x2000,
                to_address: 0x1000,
                size: 1024,
                block_index: 0,
                estimated_cost: 100.0,
            }],
            merges: Vec::new(),
            estimated_duration: Duration::from_millis(10),
            expected_fragmentation_improvement: 0.15,
        };

        assert!(plan.is_worthwhile());
        assert_eq!(plan.total_bytes_to_move(), 1024);
        assert!(plan.performance_impact() > 0.0);
    }

    #[test]
    fn test_defragmentation_manager_creation() {
        let manager = DefragmentationManager::new_for_test();
        assert!(manager.memory_managers.is_empty());
        assert!(manager.policies.is_empty());

        let status = manager.get_status();
        assert!(status.is_empty());

        let stats = manager.get_stats();
        assert_eq!(stats.total_operations, 0);
    }

    #[test]
    fn test_defragmentation_stats() {
        let mut stats = DefragmentationStats::default();
        stats.total_operations = 100;
        stats.failed_operations = 5;
        stats.cancelled_operations = 3;
        stats.total_time = Duration::from_secs(50);
        stats.total_bytes_moved = 1024 * 1024 * 1024; // 1GB

        assert_eq!(stats.success_rate(), 0.92); // 92% success rate
        assert_eq!(stats.average_operation_time(), Duration::from_millis(500));
        assert!(stats.throughput() > 0.0);
    }

    #[test]
    fn test_utils_recommend_strategy() {
        let low_fragmentation = FragmentationInfo {
            overall_fragmentation: 0.1,
            ..Default::default()
        };
        assert_eq!(
            utils::recommend_strategy(&low_fragmentation),
            DefragmentationStrategy::CoalesceOnly
        );

        let high_fragmentation = FragmentationInfo {
            overall_fragmentation: 0.8,
            free_blocks: 5,
            allocated_blocks: 10,
            ..Default::default()
        };
        assert_eq!(
            utils::recommend_strategy(&high_fragmentation),
            DefragmentationStrategy::FullCompaction
        );
    }

    #[test]
    fn test_utils_optimal_policy_for_device() {
        let cuda_policy = utils::optimal_policy_for_device(DeviceType::Cuda(0));
        assert_eq!(cuda_policy.auto_trigger_threshold, 0.5);
        assert!(cuda_policy.enable_background);

        let webgpu_policy = utils::optimal_policy_for_device(DeviceType::Wgpu(0));
        assert_eq!(webgpu_policy.auto_trigger_threshold, 0.7);
        assert!(!webgpu_policy.enable_background);
    }

    #[test]
    fn test_utils_calculate_memory_waste() {
        let fragmentation_info = FragmentationInfo {
            total_free_memory: 1000,
            total_allocated_memory: 2000,
            largest_free_block: 600,
            ..Default::default()
        };

        let waste = utils::calculate_memory_waste(&fragmentation_info);
        assert_eq!(waste, 400); // 1000 - 600
    }

    #[test]
    fn test_utils_estimate_compaction_benefit() {
        let fragmentation_info = FragmentationInfo {
            overall_fragmentation: 0.5,
            ..Default::default()
        };

        let benefit = utils::estimate_compaction_benefit(
            &fragmentation_info,
            DefragmentationStrategy::FullCompaction,
        );
        assert_eq!(benefit, 0.4); // 0.8 * 0.5

        let coalesce_benefit = utils::estimate_compaction_benefit(
            &fragmentation_info,
            DefragmentationStrategy::CoalesceOnly,
        );
        assert_eq!(coalesce_benefit, 0.1); // 0.2 * 0.5
    }
}