asupersync 0.3.4

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Runtime Resource Cleanup Verification Engine
//!
//! Provides comprehensive tracking and verification that all runtime resources
//! (file handles, memory, network connections, I/O operations) are properly
//! cleaned up during region close and cancellation scenarios.
//!
//! # Core Invariant: "Region Close = Quiescence + Resource Cleanup"
//!
//! The asupersync runtime's fundamental invariant states that when a region closes,
//! it reaches complete quiescence. This verification engine extends that invariant
//! to ensure quiescence includes proper cleanup of ALL associated resources.
//!
//! # Architecture
//!
//! ```text
//! ┌──────────────────┐    track    ┌───────────────────┐
//! │ Resource         │ ──────────▶ │ Cleanup           │
//! │ Allocation       │             │ Verifier          │
//! │ Points           │             │                   │
//! └──────────────────┘             └─────────┬─────────┘
//!                                            │ verify
//!//! ┌──────────────────┐              ┌───────────────────┐
//! │ Region Close     │ ◀──────────  │ Resource          │
//! │ Hook             │   verify     │ Attribution       │
//! │                  │   cleanup    │ Database          │
//! └──────────────────┘              └───────────────────┘
//! ```
//!
//! # Resource Categories Tracked
//!
//! 1. **File Descriptors** - Files, sockets, pipes, epoll/kqueue descriptors
//! 2. **Memory Allocations** - Heap allocations tracked by region ownership
//! 3. **Network Connections** - TCP/UDP sockets, TLS sessions
//! 4. **I/O Operations** - Pending async I/O operations and their buffers
//! 5. **System Resources** - Timers, signal handlers, thread-local storage
//!
//! # Integration Points
//!
//! The verifier hooks into existing runtime infrastructure:
//! - **Resource Monitor** - Leverages existing resource tracking
//! - **State Verifier** - Integrates with state transition validation
//! - **Region Table** - Hooks region close events
//! - **Observability** - Reports violations through structured logging

use crate::types::{RegionId, TaskId};

use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, SystemTime};
use thiserror::Error;

/// Errors that can occur during resource cleanup verification.
#[derive(Debug, Error)]
pub enum ResourceCleanupError {
    /// Resource leak detected during region close.
    #[error(
        "resource leak detected in region {region_id:?}: {leak_count} resources not cleaned up"
    )]
    ResourceLeak {
        /// Region whose close verification found leaked resources.
        region_id: RegionId,
        /// Number of resources that failed cleanup before region close.
        leak_count: usize,
        /// Resource type categories represented among the leaks.
        resource_types: Vec<ResourceType>,
    },

    /// Resource attribution failed - cannot determine owner.
    #[error("cannot attribute resource {resource_id:?} to any region")]
    AttributionFailed {
        /// Resource that could not be attributed to a region.
        resource_id: ResourceId,
    },

    /// Resource tracking is not enabled.
    #[error("resource cleanup verification is not enabled")]
    NotEnabled,

    /// Invalid resource state transition.
    #[error("invalid resource state transition: {resource_id:?} from {from:?} to {to:?}")]
    InvalidTransition {
        /// Resource whose state transition was rejected.
        resource_id: ResourceId,
        /// Current resource state.
        from: ResourceState,
        /// Requested target resource state.
        to: ResourceState,
    },

    /// Resource cleanup is still in progress and must be rechecked before close.
    #[error(
        "resource cleanup still pending in region {region_id:?}: {pending_count} resources not yet cleaned"
    )]
    CleanupPending {
        /// Region whose cleanup is not yet complete.
        region_id: RegionId,
        /// Number of resources still in cleanup.
        pending_count: usize,
        /// Resource type categories represented among the pending resources.
        resource_types: Vec<ResourceType>,
    },
}

/// Unique identifier for tracked resources.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ResourceId(u64);

impl ResourceId {
    /// Sentinel returned for resources filtered out by the tracking policy.
    const UNTRACKED: Self = Self(0);

    /// Generate a new unique resource ID.
    pub fn new() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
    }

    /// Return the sentinel ID for resources intentionally left untracked.
    pub fn untracked() -> Self {
        Self::UNTRACKED
    }

    /// Whether this ID represents a resource tracked by the verifier.
    pub fn is_tracked(self) -> bool {
        self != Self::UNTRACKED
    }
}

/// Categories of tracked resources.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResourceType {
    /// File descriptor (file, socket, pipe).
    FileDescriptor,
    /// Heap memory allocation.
    HeapAllocation,
    /// Network connection (TCP/UDP socket).
    NetworkConnection,
    /// Async I/O operation in flight.
    IoOperation,
    /// Timer or deadline registration.
    Timer,
    /// Thread-local resource.
    ThreadLocal,
    /// Custom resource type.
    Custom(u32),
}

impl ResourceType {
    /// Check if this resource type requires immediate cleanup on region close.
    pub fn requires_immediate_cleanup(self) -> bool {
        matches!(
            self,
            Self::FileDescriptor | Self::NetworkConnection | Self::IoOperation
        )
    }

    /// Check if this resource type can be deferred for cleanup.
    pub fn allows_deferred_cleanup(self) -> bool {
        matches!(self, Self::HeapAllocation | Self::ThreadLocal)
    }
}

/// State of a tracked resource throughout its lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResourceState {
    /// Resource has been allocated but not yet attached to a region.
    Allocated,
    /// Resource is owned by a specific region and in active use.
    Active,
    /// Resource is being cleaned up (region is closing).
    Cleaning,
    /// Resource cleanup has completed successfully.
    Cleaned,
    /// Resource was abandoned without proper cleanup (leak detected).
    Leaked,
}

impl ResourceState {
    /// Check if this is a valid state transition.
    pub fn can_transition_to(self, target: Self) -> bool {
        use ResourceState::{Active, Allocated, Cleaned, Cleaning, Leaked};
        match (self, target) {
            (Allocated, Active) => true,
            (Allocated, Cleaned) => true,
            (Active, Cleaning) => true,
            (Active, Cleaned) => true,
            (Cleaning, Cleaned) => true,
            (Cleaned, Cleaned) => true,
            (Active, Leaked) => true,
            (Allocated, Leaked) => true,
            (Cleaning, Leaked) => true,
            _ => false,
        }
    }
}

/// Details of a tracked resource.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRecord {
    /// Unique identifier for this resource.
    pub id: ResourceId,
    /// Category of resource.
    pub resource_type: ResourceType,
    /// Current state in cleanup lifecycle.
    pub state: ResourceState,
    /// Region that owns this resource (if any).
    pub owner_region: Option<RegionId>,
    /// Task that allocated this resource (if any).
    pub allocating_task: Option<TaskId>,
    /// Timestamp when resource was allocated.
    pub allocated_at: SystemTime,
    /// Timestamp when resource state last changed.
    pub last_updated: SystemTime,
    /// Optional description for debugging.
    pub description: Option<String>,
    /// File descriptor number (for FileDescriptor resources).
    pub file_descriptor: Option<i32>,
    /// Size in bytes (for HeapAllocation resources).
    pub size_bytes: Option<usize>,
}

impl ResourceRecord {
    /// Create a new resource record.
    pub fn new(
        resource_type: ResourceType,
        owner_region: Option<RegionId>,
        allocating_task: Option<TaskId>,
    ) -> Self {
        let now = SystemTime::now();
        Self {
            id: ResourceId::new(),
            resource_type,
            state: ResourceState::Allocated,
            owner_region,
            allocating_task,
            allocated_at: now,
            last_updated: now,
            description: None,
            file_descriptor: None,
            size_bytes: None,
        }
    }

    /// Transition resource to a new state.
    pub fn transition_to(&mut self, new_state: ResourceState) -> Result<(), ResourceCleanupError> {
        if !self.state.can_transition_to(new_state) {
            return Err(ResourceCleanupError::InvalidTransition {
                resource_id: self.id,
                from: self.state,
                to: new_state,
            });
        }

        self.state = new_state;
        self.last_updated = SystemTime::now();
        Ok(())
    }

    /// Mark this resource as being actively used by a region.
    pub fn activate(&mut self, region_id: RegionId) -> Result<(), ResourceCleanupError> {
        self.owner_region = Some(region_id);
        self.transition_to(ResourceState::Active)
    }

    /// Begin cleanup process for this resource.
    pub fn begin_cleanup(&mut self) -> Result<(), ResourceCleanupError> {
        self.transition_to(ResourceState::Cleaning)
    }

    /// Mark cleanup as completed.
    pub fn complete_cleanup(&mut self) -> Result<(), ResourceCleanupError> {
        self.transition_to(ResourceState::Cleaned)
    }

    /// Mark resource as leaked (cleanup failed).
    pub fn mark_leaked(&mut self) -> Result<(), ResourceCleanupError> {
        self.transition_to(ResourceState::Leaked)
    }
}

/// Configuration for resource cleanup verification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceCleanupConfig {
    /// Enable resource cleanup verification.
    pub enable_verification: bool,
    /// Enable detailed resource tracking (higher memory overhead).
    pub enable_detailed_tracking: bool,
    /// Enable stack trace capture for resource allocations.
    pub enable_allocation_traces: bool,
    /// Maximum number of resources to track before evicting oldest.
    pub max_tracked_resources: usize,
    /// Grace period for resource cleanup after region close.
    pub cleanup_grace_period_ms: u64,
    /// Whether to panic on detected resource leaks.
    pub panic_on_leaks: bool,
    /// Resource types to track (empty = track all).
    pub tracked_resource_types: HashSet<ResourceType>,
}

impl Default for ResourceCleanupConfig {
    fn default() -> Self {
        Self {
            enable_verification: true,
            enable_detailed_tracking: cfg!(debug_assertions),
            enable_allocation_traces: false,
            max_tracked_resources: 10_000,
            cleanup_grace_period_ms: 1000, // 1 second
            panic_on_leaks: cfg!(debug_assertions),
            tracked_resource_types: HashSet::new(), // Track all by default
        }
    }
}

/// Statistics about resource cleanup verification.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ResourceCleanupStats {
    /// Total number of resources allocated.
    pub total_allocated: u64,
    /// Total number of resources cleaned up successfully.
    pub total_cleaned: u64,
    /// Total number of resource leaks detected.
    pub total_leaked: u64,
    /// Current number of actively tracked resources.
    pub currently_tracked: u64,
    /// Peak number of simultaneously tracked resources.
    pub peak_tracked: u64,
    /// Number of regions that closed with clean resource states.
    pub clean_region_closes: u64,
    /// Number of regions that closed with resource leaks.
    pub leaked_region_closes: u64,
}

/// Runtime Resource Cleanup Verification Engine.
///
/// This is the main component that tracks resource allocation, ownership,
/// and cleanup to verify the "region close = quiescence" invariant includes
/// proper resource cleanup.
pub struct ResourceCleanupVerifier {
    /// Configuration for verification behavior.
    config: ResourceCleanupConfig,
    /// Database of currently tracked resources.
    resources: RwLock<HashMap<ResourceId, ResourceRecord>>,
    /// Mapping from region ID to owned resource IDs.
    region_resources: RwLock<HashMap<RegionId, HashSet<ResourceId>>>,
    /// Statistics about verification activity.
    stats: RwLock<ResourceCleanupStats>,
    /// Whether verification is currently active.
    is_active: AtomicBool,
    #[cfg(feature = "tracing-integration")]
    instance_id: u64,
}

impl ResourceCleanupVerifier {
    /// Create a new resource cleanup verifier.
    pub fn new(config: ResourceCleanupConfig) -> Self {
        #[cfg(feature = "tracing-integration")]
        let instance_id = {
            static NEXT_INSTANCE_ID: AtomicU64 = AtomicU64::new(1);
            NEXT_INSTANCE_ID.fetch_add(1, Ordering::Relaxed)
        };

        Self {
            config,
            resources: RwLock::new(HashMap::new()),
            region_resources: RwLock::new(HashMap::new()),
            stats: RwLock::new(ResourceCleanupStats::default()),
            is_active: AtomicBool::new(false),
            #[cfg(feature = "tracing-integration")]
            instance_id,
        }
    }

    /// Start resource cleanup verification.
    pub fn start(&self) -> Result<(), ResourceCleanupError> {
        if !self.config.enable_verification {
            return Err(ResourceCleanupError::NotEnabled);
        }

        self.is_active.store(true, Ordering::Release);
        #[cfg(feature = "tracing-integration")]
        crate::tracing_compat::debug!(
            "Started resource cleanup verifier instance {}",
            self.instance_id
        );
        Ok(())
    }

    /// Stop resource cleanup verification.
    pub fn stop(&self) {
        self.is_active.store(false, Ordering::Release);
        #[cfg(feature = "tracing-integration")]
        crate::tracing_compat::debug!(
            "Stopped resource cleanup verifier instance {}",
            self.instance_id
        );
    }

    /// Check if verification is currently active.
    pub fn is_active(&self) -> bool {
        self.is_active.load(Ordering::Acquire)
    }

    /// Track allocation of a new resource.
    pub fn track_allocation(
        &self,
        resource_type: ResourceType,
        owner_region: Option<RegionId>,
        allocating_task: Option<TaskId>,
    ) -> Result<ResourceId, ResourceCleanupError> {
        if !self.is_active() {
            return Err(ResourceCleanupError::NotEnabled);
        }

        // Check if we should track this resource type
        if !self.config.tracked_resource_types.is_empty()
            && !self.config.tracked_resource_types.contains(&resource_type)
        {
            return Ok(ResourceId::untracked());
        }

        let mut record = ResourceRecord::new(resource_type, owner_region, allocating_task);
        let resource_id = record.id;

        // Update resource to active state if it has an owner region
        if let Some(region_id) = owner_region {
            record.activate(region_id)?;
        }

        // Insert into tracking database.
        let evicted_region_resource = {
            let mut resources = self.resources.write();
            resources.insert(resource_id, record);

            // Evict oldest resources if we're over the limit
            let mut evicted_region_resource = None;
            if resources.len() > self.config.max_tracked_resources {
                // Find the oldest resource in Cleaned state to evict
                let oldest_cleaned = resources
                    .iter()
                    .filter(|(_, record)| record.state == ResourceState::Cleaned)
                    .min_by_key(|(_, record)| record.last_updated)
                    .map(|(id, _)| *id);

                if let Some(id_to_evict) = oldest_cleaned {
                    evicted_region_resource = resources.remove(&id_to_evict).and_then(|record| {
                        record
                            .owner_region
                            .map(|region_id| (region_id, id_to_evict))
                    });
                }
            }
            evicted_region_resource
        };

        if let Some((region_id, evicted_resource_id)) = evicted_region_resource {
            let mut region_resources = self.region_resources.write();
            if let Some(resource_ids) = region_resources.get_mut(&region_id) {
                resource_ids.remove(&evicted_resource_id);
                if resource_ids.is_empty() {
                    region_resources.remove(&region_id);
                }
            }
        }

        // Track region ownership if applicable
        if let Some(region_id) = owner_region {
            let mut region_resources = self.region_resources.write();
            region_resources
                .entry(region_id)
                .or_default()
                .insert(resource_id);
        }

        // Update statistics
        {
            let mut stats = self.stats.write();
            stats.total_allocated += 1;
            stats.currently_tracked += 1;
            if stats.currently_tracked > stats.peak_tracked {
                stats.peak_tracked = stats.currently_tracked;
            }
        }

        crate::tracing_compat::trace!(
            "Tracked allocation: resource_id={:?} type={:?} region={:?}",
            resource_id,
            resource_type,
            owner_region
        );

        Ok(resource_id)
    }

    /// Mark a resource as cleaned up.
    pub fn track_cleanup(&self, resource_id: ResourceId) -> Result<(), ResourceCleanupError> {
        if !self.is_active() {
            return Err(ResourceCleanupError::NotEnabled);
        }

        if !resource_id.is_tracked() {
            return Ok(());
        }

        let mut resources = self.resources.write();
        if let Some(record) = resources.get_mut(&resource_id) {
            if record.state == ResourceState::Cleaned {
                return Ok(());
            }

            record.complete_cleanup()?;

            // Update statistics
            drop(resources);
            let mut stats = self.stats.write();
            stats.total_cleaned += 1;
            stats.currently_tracked = stats.currently_tracked.saturating_sub(1);

            crate::tracing_compat::trace!("Tracked cleanup: resource_id={:?}", resource_id);
            Ok(())
        } else {
            Err(ResourceCleanupError::AttributionFailed { resource_id })
        }
    }

    /// Verify that all resources owned by a region are properly cleaned up.
    ///
    /// This is called during region close to enforce the "region close = quiescence"
    /// invariant includes proper resource cleanup.
    pub fn verify_region_cleanup(&self, region_id: RegionId) -> Result<(), ResourceCleanupError> {
        if !self.is_active() {
            return Ok(()); // Skip verification if disabled
        }

        // Get all resources owned by this region
        let owned_resources = {
            let region_resources = self.region_resources.read();
            region_resources
                .get(&region_id)
                .cloned()
                .unwrap_or_default()
        };

        if owned_resources.is_empty() {
            // No resources to clean up - perfect!
            let mut stats = self.stats.write();
            stats.clean_region_closes += 1;
            return Ok(());
        }

        // Check each owned resource for proper cleanup. Region close may only
        // succeed once every tracked resource is already Cleaned.
        let mut leaked_resources = Vec::new();
        let mut leaked_types = HashSet::new();
        let mut pending_resources = Vec::new();
        let mut pending_types = HashSet::new();

        {
            let mut resources = self.resources.write();
            for resource_id in &owned_resources {
                if let Some(record) = resources.get_mut(resource_id) {
                    match record.state {
                        ResourceState::Active => {
                            // Active at region close means cleanup did not run.
                            record.mark_leaked().ok();
                            leaked_resources.push(*resource_id);
                            leaked_types.insert(record.resource_type);
                        }
                        ResourceState::Cleaning => {
                            // Cleanup is in progress. Keep the region mapping
                            // until a later check either observes Cleaned or
                            // the grace period expires.
                            let grace_period =
                                Duration::from_millis(self.config.cleanup_grace_period_ms);
                            if record.last_updated.elapsed().unwrap_or_default() >= grace_period {
                                record.mark_leaked().ok();
                                leaked_resources.push(*resource_id);
                                leaked_types.insert(record.resource_type);
                            } else {
                                pending_resources.push(*resource_id);
                                pending_types.insert(record.resource_type);
                            }
                        }
                        ResourceState::Leaked => {
                            // Already marked as leaked
                            leaked_resources.push(*resource_id);
                            leaked_types.insert(record.resource_type);
                        }
                        ResourceState::Cleaned => {
                            // Resource properly cleaned up - no action needed
                        }
                        ResourceState::Allocated => {
                            // Resource never became active - mark as leaked
                            record.mark_leaked().ok();
                            leaked_resources.push(*resource_id);
                            leaked_types.insert(record.resource_type);
                        }
                    }
                }
            }
        }

        // Update statistics and clean up region mapping
        {
            let mut stats = self.stats.write();
            if leaked_resources.is_empty() && pending_resources.is_empty() {
                stats.clean_region_closes += 1;
            } else if !leaked_resources.is_empty() {
                stats.leaked_region_closes += 1;
                stats.total_leaked += leaked_resources.len() as u64;
                stats.currently_tracked = stats
                    .currently_tracked
                    .saturating_sub(leaked_resources.len() as u64);
            }
        }

        if !pending_resources.is_empty() && leaked_resources.is_empty() {
            let error = ResourceCleanupError::CleanupPending {
                region_id,
                pending_count: pending_resources.len(),
                resource_types: pending_types.into_iter().collect(),
            };

            crate::tracing_compat::debug!("Resource cleanup verification pending: {}", error);
            return Err(error);
        }

        if pending_resources.is_empty() || !leaked_resources.is_empty() {
            let mut region_resources = self.region_resources.write();
            region_resources.remove(&region_id);
        }

        // Report any leaks found
        if !leaked_resources.is_empty() {
            let error = ResourceCleanupError::ResourceLeak {
                region_id,
                leak_count: leaked_resources.len(),
                resource_types: leaked_types.into_iter().collect(),
            };

            crate::tracing_compat::error!("Resource cleanup verification failed: {}", error);

            #[cfg(feature = "tracing-integration")]
            {
                // Log details of each leaked resource.
                let resources = self.resources.read();
                for resource_id in &leaked_resources {
                    if let Some(record) = resources.get(resource_id) {
                        crate::tracing_compat::warn!(
                            "Leaked resource: {:?} (type={:?}, allocated_at={:?})",
                            resource_id,
                            record.resource_type,
                            record.allocated_at
                        );
                    }
                }
            }

            assert!(
                !self.config.panic_on_leaks,
                "Resource cleanup verification failed: {}",
                error
            );

            return Err(error);
        }

        crate::tracing_compat::debug!(
            "Region cleanup verified successfully: region_id={:?} resources_cleaned={}",
            region_id,
            owned_resources.len()
        );

        Ok(())
    }

    /// Get current verification statistics.
    pub fn get_stats(&self) -> ResourceCleanupStats {
        self.stats.read().clone()
    }

    /// Get details of all currently tracked resources.
    pub fn get_tracked_resources(&self) -> HashMap<ResourceId, ResourceRecord> {
        self.resources.read().clone()
    }

    /// Get all resources owned by a specific region.
    pub fn get_region_resources(&self, region_id: RegionId) -> Vec<ResourceRecord> {
        let region_resources = self.region_resources.read();
        let resource_ids = region_resources
            .get(&region_id)
            .cloned()
            .unwrap_or_default();

        let resources = self.resources.read();
        resource_ids
            .into_iter()
            .filter_map(|id| resources.get(&id).cloned())
            .collect()
    }

    /// Force cleanup verification for all tracked resources.
    /// This is primarily for testing and debugging.
    pub fn force_global_cleanup_check(&self) -> Vec<ResourceCleanupError> {
        let mut errors = Vec::new();

        // Get all unique region IDs that own resources
        let region_ids: HashSet<RegionId> = {
            let region_resources = self.region_resources.read();
            region_resources.keys().copied().collect()
        };

        // Verify cleanup for each region
        for region_id in region_ids {
            if let Err(error) = self.verify_region_cleanup(region_id) {
                errors.push(error);
            }
        }

        errors
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;

    #[test]
    fn test_resource_state_transitions() {
        use ResourceState::*;

        // Valid transitions
        assert!(Allocated.can_transition_to(Active));
        assert!(Allocated.can_transition_to(Cleaned));
        assert!(Active.can_transition_to(Cleaning));
        assert!(Active.can_transition_to(Cleaned));
        assert!(Cleaning.can_transition_to(Cleaned));
        assert!(Cleaned.can_transition_to(Cleaned));
        assert!(Active.can_transition_to(Leaked));
        assert!(Allocated.can_transition_to(Leaked));
        assert!(Cleaning.can_transition_to(Leaked));

        // Invalid transitions
        assert!(!Cleaned.can_transition_to(Active));
        assert!(!Leaked.can_transition_to(Cleaned));
        assert!(!Allocated.can_transition_to(Cleaning));
    }

    #[test]
    fn test_resource_record_lifecycle() -> Result<(), ResourceCleanupError> {
        let region_id = RegionId::new_ephemeral();
        let task_id = TaskId::new_ephemeral();

        let mut record =
            ResourceRecord::new(ResourceType::FileDescriptor, Some(region_id), Some(task_id));

        assert_eq!(record.state, ResourceState::Allocated);

        // Activate resource
        record.activate(region_id)?;
        assert_eq!(record.state, ResourceState::Active);
        assert_eq!(record.owner_region, Some(region_id));

        // Begin cleanup
        record.begin_cleanup()?;
        assert_eq!(record.state, ResourceState::Cleaning);

        // Complete cleanup
        record.complete_cleanup()?;
        assert_eq!(record.state, ResourceState::Cleaned);
        Ok(())
    }

    #[test]
    fn test_resource_cleanup_verifier() -> Result<(), ResourceCleanupError> {
        let config = ResourceCleanupConfig::default();
        let verifier = ResourceCleanupVerifier::new(config);

        // Start verification
        verifier.start()?;
        assert!(verifier.is_active());

        let region_id = RegionId::new_ephemeral();

        // Track resource allocation
        let resource_id =
            verifier.track_allocation(ResourceType::FileDescriptor, Some(region_id), None)?;

        // Verify region has the resource
        let region_resources = verifier.get_region_resources(region_id);
        assert_eq!(region_resources.len(), 1);
        assert_eq!(region_resources[0].id, resource_id);

        // Clean up the resource
        verifier.track_cleanup(resource_id)?;

        // Verify region cleanup
        verifier.verify_region_cleanup(region_id)?;

        let stats = verifier.get_stats();
        assert_eq!(stats.total_allocated, 1);
        assert_eq!(stats.total_cleaned, 1);
        assert_eq!(stats.total_leaked, 0);
        assert_eq!(stats.clean_region_closes, 1);
        Ok(())
    }

    #[test]
    fn filtered_resource_cleanup_is_a_noop() -> Result<(), ResourceCleanupError> {
        let mut tracked_resource_types = HashSet::new();
        tracked_resource_types.insert(ResourceType::FileDescriptor);
        let config = ResourceCleanupConfig {
            tracked_resource_types,
            ..Default::default()
        };
        let verifier = ResourceCleanupVerifier::new(config);
        verifier.start()?;

        let region_id = RegionId::new_ephemeral();
        let resource_id = verifier.track_allocation(ResourceType::Timer, Some(region_id), None)?;

        assert!(!resource_id.is_tracked());
        assert!(verifier.get_region_resources(region_id).is_empty());
        verifier.track_cleanup(resource_id)?;

        let stats = verifier.get_stats();
        assert_eq!(stats.total_allocated, 0);
        assert_eq!(stats.total_cleaned, 0);
        assert_eq!(stats.currently_tracked, 0);
        Ok(())
    }

    #[test]
    fn duplicate_cleanup_does_not_corrupt_statistics() -> Result<(), ResourceCleanupError> {
        let verifier = ResourceCleanupVerifier::new(ResourceCleanupConfig::default());
        verifier.start()?;

        let region_id = RegionId::new_ephemeral();
        let resource_id =
            verifier.track_allocation(ResourceType::FileDescriptor, Some(region_id), None)?;

        verifier.track_cleanup(resource_id)?;
        verifier.track_cleanup(resource_id)?;

        let stats = verifier.get_stats();
        assert_eq!(stats.total_allocated, 1);
        assert_eq!(stats.total_cleaned, 1);
        assert_eq!(stats.currently_tracked, 0);
        Ok(())
    }

    #[test]
    fn evicting_cleaned_resource_removes_region_index() -> Result<(), ResourceCleanupError> {
        let config = ResourceCleanupConfig {
            max_tracked_resources: 1,
            ..Default::default()
        };
        let verifier = ResourceCleanupVerifier::new(config);
        verifier.start()?;

        let first_region = RegionId::new_ephemeral();
        let first_resource =
            verifier.track_allocation(ResourceType::HeapAllocation, Some(first_region), None)?;
        verifier.track_cleanup(first_resource)?;

        let second_region = RegionId::new_ephemeral();
        let _second_resource =
            verifier.track_allocation(ResourceType::FileDescriptor, Some(second_region), None)?;

        assert!(
            verifier.get_region_resources(first_region).is_empty(),
            "evicted cleaned resources must not leave stale region ownership entries",
        );
        assert_eq!(verifier.get_region_resources(second_region).len(), 1);
        Ok(())
    }

    #[test]
    fn test_resource_leak_detection() -> Result<(), ResourceCleanupError> {
        let config = ResourceCleanupConfig {
            panic_on_leaks: false, // Don't panic in tests
            ..Default::default()
        };
        let verifier = ResourceCleanupVerifier::new(config);

        verifier.start()?;

        let region_id = RegionId::new_ephemeral();

        // Allocate resource but don't clean it up
        let _resource_id =
            verifier.track_allocation(ResourceType::FileDescriptor, Some(region_id), None)?;

        // Try to close region without cleaning up resource
        let result = verifier.verify_region_cleanup(region_id);
        assert!(matches!(
            result,
            Err(ResourceCleanupError::ResourceLeak { .. })
        ));
        let Err(ResourceCleanupError::ResourceLeak {
            region_id: leaked_region,
            leak_count,
            resource_types,
        }) = result
        else {
            return Ok(());
        };

        assert_eq!(leaked_region, region_id);
        assert_eq!(leak_count, 1);
        assert!(resource_types.contains(&ResourceType::FileDescriptor));

        let stats = verifier.get_stats();
        assert_eq!(stats.total_leaked, 1);
        assert_eq!(stats.leaked_region_closes, 1);
        Ok(())
    }

    #[test]
    fn test_pending_cleanup_does_not_close_region_mapping() -> Result<(), ResourceCleanupError> {
        let config = ResourceCleanupConfig {
            panic_on_leaks: false,
            cleanup_grace_period_ms: 60_000,
            ..Default::default()
        };
        let verifier = ResourceCleanupVerifier::new(config);
        verifier.start()?;

        let region_id = RegionId::new_ephemeral();
        let resource_id =
            verifier.track_allocation(ResourceType::NetworkConnection, Some(region_id), None)?;

        {
            let mut resources = verifier.resources.write();
            let Some(record) = resources.get_mut(&resource_id) else {
                return Err(ResourceCleanupError::AttributionFailed { resource_id });
            };
            record.begin_cleanup()?;
        }

        let result = verifier.verify_region_cleanup(region_id);
        assert!(matches!(
            result,
            Err(ResourceCleanupError::CleanupPending {
                pending_count: 1,
                ..
            })
        ));

        assert_eq!(
            verifier.get_region_resources(region_id).len(),
            1,
            "pending cleanup must remain attributed for a later recheck"
        );

        verifier.track_cleanup(resource_id)?;
        verifier.verify_region_cleanup(region_id)?;
        assert!(verifier.get_region_resources(region_id).is_empty());
        Ok(())
    }

    #[test]
    fn pending_cleanup_tolerates_system_clock_skew() -> Result<(), ResourceCleanupError> {
        let config = ResourceCleanupConfig {
            panic_on_leaks: false,
            cleanup_grace_period_ms: 10,
            ..Default::default()
        };
        let verifier = ResourceCleanupVerifier::new(config);
        verifier.start()?;

        let region_id = RegionId::new_ephemeral();
        let resource_id =
            verifier.track_allocation(ResourceType::NetworkConnection, Some(region_id), None)?;

        {
            let mut resources = verifier.resources.write();
            let Some(record) = resources.get_mut(&resource_id) else {
                return Err(ResourceCleanupError::AttributionFailed { resource_id });
            };
            record.begin_cleanup()?;
            record.last_updated = SystemTime::now() + Duration::from_secs(60);
        }

        let result = verifier.verify_region_cleanup(region_id);
        assert!(matches!(
            result,
            Err(ResourceCleanupError::CleanupPending {
                pending_count: 1,
                ..
            })
        ));

        let stats = verifier.get_stats();
        assert_eq!(stats.total_leaked, 0);
        assert_eq!(stats.leaked_region_closes, 0);
        assert_eq!(verifier.get_region_resources(region_id).len(), 1);
        Ok(())
    }
}