asupersync 0.3.1

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
//! Trace event filtering during recording.
//!
//! This module provides [`TraceFilter`] for controlling which events are recorded
//! during trace capture. Filtering reduces trace size for targeted debugging.
//!
//! # Features
//!
//! - **Kind filtering**: Include or exclude specific event categories
//! - **Entity filtering**: Record events only for specific regions or tasks
//! - **Sampling**: Probabilistic recording for high-frequency events
//! - **Custom predicates**: User-defined filter logic
//!
//! # Example
//!
//! ```ignore
//! use asupersync::trace::filter::{TraceFilter, EventCategory};
//!
//! // Create a filter for scheduling and time events only
//! let filter = TraceFilter::default()
//!     .include_kinds([EventCategory::Scheduling, EventCategory::Time])
//!     .with_sample_rate(0.1); // Sample 10% of high-frequency events
//!
//! // Create a minimal scheduling-only filter
//! let minimal = TraceFilter::scheduling_only();
//!
//! // Filter excluding RNG values
//! let no_rng = TraceFilter::no_rng();
//! ```

use crate::types::{RegionId, TaskId};
use std::collections::BTreeSet;
use std::sync::Arc;

type FilterPredicate = dyn Fn(&dyn FilterableEvent) -> bool + Send + Sync;

// =============================================================================
// Event Kind Categories
// =============================================================================

/// Categories of trace events for filtering.
///
/// These categories group related events for easier filtering configuration.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, PartialOrd, Ord)]
pub enum EventCategory {
    /// Task scheduling events (scheduled, yielded, completed, spawned).
    Scheduling,

    /// Virtual time events (advanced, timers created/fired/cancelled).
    Time,

    /// I/O events (ready, result, error).
    Io,

    /// Random number generation events (seed, values).
    Rng,

    /// Region lifecycle events.
    Region,

    /// Waker invocation events.
    Waker,

    /// Chaos injection events.
    Chaos,

    /// Checkpoint events.
    Checkpoint,
}

impl EventCategory {
    /// Returns all event kinds.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::Scheduling,
            Self::Time,
            Self::Io,
            Self::Rng,
            Self::Region,
            Self::Waker,
            Self::Chaos,
            Self::Checkpoint,
        ]
    }

    /// Returns event kinds that are typically high-frequency and may benefit from sampling.
    #[must_use]
    pub const fn high_frequency() -> &'static [Self] {
        &[Self::Rng, Self::Waker]
    }

    /// Returns true if this event kind is subject to sampling.
    #[must_use]
    pub fn is_sampled(&self) -> bool {
        matches!(self, Self::Rng | Self::Waker)
    }
}

// =============================================================================
// Filter Match Trait
// =============================================================================

/// Trait for extracting filter-relevant information from events.
pub trait FilterableEvent {
    /// Returns the event kind category.
    fn event_kind(&self) -> EventCategory;

    /// Returns the task ID if this event is task-scoped.
    fn task_id(&self) -> Option<TaskId>;

    /// Returns the region ID if this event is region-scoped.
    fn region_id(&self) -> Option<RegionId>;
}

// =============================================================================
// Trace Filter
// =============================================================================

/// Filter for controlling which trace events are recorded.
///
/// The filter is evaluated for each event during recording. Events that don't
/// pass the filter are dropped and not stored in the trace.
///
/// # Evaluation Order
///
/// Filters are evaluated in this order:
/// 1. Kind exclusion (if excluded, drop immediately)
/// 2. Kind inclusion (if include list is non-empty and kind not in it, drop)
/// 3. Entity filtering (region/task filters)
/// 4. Sampling (for high-frequency events)
/// 5. Custom predicate (if provided)
///
/// # Default Behavior
///
/// The default filter records all events (no filtering applied).
#[derive(Clone)]
pub struct TraceFilter {
    /// Event kinds to include (empty = all kinds).
    include_kinds: BTreeSet<EventCategory>,

    /// Event kinds to exclude (takes precedence over include).
    exclude_kinds: BTreeSet<EventCategory>,

    /// Only record events for these regions (None = all regions).
    region_filter: Option<BTreeSet<RegionId>>,

    /// Explicitly excluded regions (always dropped).
    exclude_regions: BTreeSet<RegionId>,

    /// Only record events for these tasks (None = all tasks).
    task_filter: Option<BTreeSet<TaskId>>,

    /// Sample rate for high-frequency events (0.0-1.0).
    /// 1.0 = record all, 0.5 = record 50%, 0.0 = record none.
    sample_rate: f64,

    /// Custom filter predicate (must be Send + Sync for multi-threaded use).
    /// The predicate returns true if the event should be recorded.
    custom: Option<Arc<FilterPredicate>>,

    /// RNG state for sampling decisions.
    sample_state: u64,
}

impl Default for TraceFilter {
    fn default() -> Self {
        Self {
            include_kinds: BTreeSet::new(),
            exclude_kinds: BTreeSet::new(),
            region_filter: None,
            exclude_regions: BTreeSet::new(),
            task_filter: None,
            sample_rate: 1.0,
            custom: None,
            sample_state: 0,
        }
    }
}

impl std::fmt::Debug for TraceFilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TraceFilter")
            .field("include_kinds", &self.include_kinds)
            .field("exclude_kinds", &self.exclude_kinds)
            .field("region_filter", &self.region_filter)
            .field("exclude_regions", &self.exclude_regions)
            .field("task_filter", &self.task_filter)
            .field("sample_rate", &self.sample_rate)
            .field("custom", &self.custom.as_ref().map(|_| "<predicate>"))
            .finish_non_exhaustive()
    }
}

impl TraceFilter {
    /// Creates a new filter that records all events.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // =========================================================================
    // Predefined Filters
    // =========================================================================

    /// Creates a filter that only records scheduling decisions.
    ///
    /// This is the minimal filter for replay that captures:
    /// - Task scheduling, yielding, and completion
    /// - RNG seed (but not values)
    /// - Chaos injections
    #[must_use]
    pub fn scheduling_only() -> Self {
        let mut filter = Self::new();
        filter.include_kinds = [EventCategory::Scheduling, EventCategory::Chaos]
            .into_iter()
            .collect();
        filter
    }

    /// Creates a filter that records everything except RNG values.
    ///
    /// This is a common configuration that:
    /// - Records all scheduling, time, I/O, and chaos events
    /// - Records RNG seed but excludes individual RNG values
    /// - Significantly reduces trace size for executions with heavy RNG use
    #[must_use]
    pub fn no_rng() -> Self {
        let mut filter = Self::new();
        filter.exclude_kinds.insert(EventCategory::Rng);
        filter
    }

    /// Creates a filter that records only events for a specific region subtree.
    ///
    /// Use this when debugging a specific region and its children.
    #[must_use]
    pub fn region_subtree(root: RegionId) -> Self {
        let mut filter = Self::new();
        let mut regions = BTreeSet::new();
        regions.insert(root);
        filter.region_filter = Some(regions);
        filter
    }

    /// Creates a filter focused on I/O events for debugging I/O-related issues.
    #[must_use]
    pub fn io_focused() -> Self {
        let mut filter = Self::new();
        filter.include_kinds = [
            EventCategory::Io,
            EventCategory::Scheduling,
            EventCategory::Time,
        ]
        .into_iter()
        .collect();
        filter
    }

    /// Creates a filter that samples high-frequency events at the given rate.
    #[must_use]
    pub fn with_sampling(rate: f64) -> Self {
        let mut filter = Self::new();
        filter.sample_rate = rate.clamp(0.0, 1.0);
        filter
    }

    // =========================================================================
    // Builder Methods
    // =========================================================================

    /// Sets the event kinds to include.
    ///
    /// If non-empty, only events of these kinds will be recorded.
    /// Kind exclusion still takes precedence.
    #[must_use]
    pub fn include_kinds<I>(mut self, kinds: I) -> Self
    where
        I: IntoIterator<Item = EventCategory>,
    {
        self.include_kinds = kinds.into_iter().collect();
        self
    }

    /// Adds an event kind to the include list.
    #[must_use]
    pub fn include_kind(mut self, kind: EventCategory) -> Self {
        self.include_kinds.insert(kind);
        self
    }

    /// Sets the event kinds to exclude.
    ///
    /// Events of these kinds will never be recorded, even if in the include list.
    #[must_use]
    pub fn exclude_kinds<I>(mut self, kinds: I) -> Self
    where
        I: IntoIterator<Item = EventCategory>,
    {
        self.exclude_kinds = kinds.into_iter().collect();
        self
    }

    /// Adds an event kind to the exclude list.
    #[must_use]
    pub fn exclude_kind(mut self, kind: EventCategory) -> Self {
        self.exclude_kinds.insert(kind);
        self
    }

    /// Sets the region filter.
    ///
    /// Only events associated with these regions will be recorded.
    /// Events not associated with any region are always recorded.
    #[must_use]
    pub fn filter_regions<I>(mut self, regions: I) -> Self
    where
        I: IntoIterator<Item = RegionId>,
    {
        self.region_filter = Some(regions.into_iter().collect());
        self
    }

    /// Adds a region to the region filter.
    #[must_use]
    pub fn include_region(mut self, region: RegionId) -> Self {
        self.region_filter
            .get_or_insert_with(BTreeSet::new)
            .insert(region);
        self
    }

    /// Excludes a specific region from recording.
    ///
    /// This is an explicit exclusion and always takes precedence over
    /// inclusion filters.
    #[must_use]
    pub fn exclude_region(mut self, region: RegionId) -> Self {
        self.exclude_regions.insert(region);
        if let Some(ref mut regions) = self.region_filter {
            regions.remove(&region);
        }
        self
    }

    /// Excludes a specific region from recording.
    ///
    /// Alias for [`exclude_region`](Self::exclude_region).
    #[must_use]
    pub fn exclude_region_explicit(self, region: RegionId) -> Self {
        self.exclude_region(region)
    }

    /// Sets the task filter.
    ///
    /// Only events associated with these tasks will be recorded.
    /// Events not associated with any task are always recorded.
    #[must_use]
    pub fn filter_tasks<I>(mut self, tasks: I) -> Self
    where
        I: IntoIterator<Item = TaskId>,
    {
        self.task_filter = Some(tasks.into_iter().collect());
        self
    }

    /// Adds a task to the task filter.
    #[must_use]
    pub fn include_task(mut self, task: TaskId) -> Self {
        self.task_filter
            .get_or_insert_with(BTreeSet::new)
            .insert(task);
        self
    }

    /// Sets the sample rate for high-frequency events.
    ///
    /// - 1.0 = record all events (no sampling)
    /// - 0.5 = record approximately 50% of sampled events
    /// - 0.0 = record no sampled events
    ///
    /// Only events in [`EventCategory::high_frequency()`] are subject to sampling.
    #[must_use]
    pub fn with_sample_rate(mut self, rate: f64) -> Self {
        self.sample_rate = rate.clamp(0.0, 1.0);
        self
    }

    /// Sets a custom filter predicate.
    ///
    /// The predicate receives each event and returns `true` if it should be recorded.
    /// This is evaluated after all other filters.
    #[must_use]
    pub fn with_custom<F>(mut self, predicate: F) -> Self
    where
        F: Fn(&dyn FilterableEvent) -> bool + Send + Sync + 'static,
    {
        self.custom = Some(Arc::new(predicate));
        self
    }

    /// Seeds the sampling RNG for reproducible filtering.
    ///
    /// This is useful for deterministic replay of filtered traces.
    #[must_use]
    pub fn with_sample_seed(mut self, seed: u64) -> Self {
        self.sample_state = seed;
        self
    }

    // =========================================================================
    // Filter Evaluation
    // =========================================================================

    /// Evaluates whether an event should be recorded.
    ///
    /// Returns `true` if the event passes all filter criteria.
    pub fn should_record(&mut self, event: &dyn FilterableEvent) -> bool {
        let kind = event.event_kind();

        // 1. Check exclusion (takes precedence)
        if self.exclude_kinds.contains(&kind) {
            return false;
        }

        // 2. Check inclusion (if include list is non-empty)
        if !self.include_kinds.is_empty() && !self.include_kinds.contains(&kind) {
            return false;
        }

        // 3. Check explicit region exclusions
        if let Some(region) = event.region_id() {
            if self.exclude_regions.contains(&region) {
                return false;
            }
        }

        // 4. Check region filter
        if let Some(ref regions) = self.region_filter {
            if let Some(region) = event.region_id() {
                if !regions.contains(&region) {
                    return false;
                }
            }
            // Events without region association pass through
        }

        // 5. Check task filter
        if let Some(ref tasks) = self.task_filter {
            if let Some(task) = event.task_id() {
                if !tasks.contains(&task) {
                    return false;
                }
            }
            // Events without task association pass through
        }

        // 6. Apply sampling for high-frequency events
        if kind.is_sampled() && self.sample_rate < 1.0 && !self.sample() {
            return false;
        }

        // 7. Apply custom predicate
        if let Some(ref predicate) = self.custom {
            if !predicate(event) {
                return false;
            }
        }

        true
    }

    /// Returns true if no filtering is configured (record all events).
    #[must_use]
    pub fn is_pass_through(&self) -> bool {
        self.include_kinds.is_empty()
            && self.exclude_kinds.is_empty()
            && self.region_filter.is_none()
            && self.exclude_regions.is_empty()
            && self.task_filter.is_none()
            && (self.sample_rate - 1.0).abs() < f64::EPSILON
            && self.custom.is_none()
    }

    /// Performs a sampling decision.
    ///
    /// Uses a simple xorshift for fast, reproducible sampling.
    #[allow(clippy::cast_precision_loss)]
    fn sample(&mut self) -> bool {
        // xorshift64 — avoid the zero fixed-point
        let mut x = self.sample_state;
        if x == 0 {
            x = 1;
        }
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.sample_state = x;

        // Convert to [0, 1) range
        let normalized = (x as f64) / (u64::MAX as f64);
        normalized < self.sample_rate
    }

    // =========================================================================
    // Inspection
    // =========================================================================

    /// Returns true if this filter includes the given event kind.
    #[must_use]
    pub fn includes_kind(&self, kind: EventCategory) -> bool {
        !self.exclude_kinds.contains(&kind)
            && (self.include_kinds.is_empty() || self.include_kinds.contains(&kind))
    }

    /// Returns the configured sample rate.
    #[must_use]
    pub fn sample_rate(&self) -> f64 {
        self.sample_rate
    }

    /// Returns the included kinds (empty = all).
    #[must_use]
    pub fn included_kinds(&self) -> &BTreeSet<EventCategory> {
        &self.include_kinds
    }

    /// Returns the excluded kinds.
    #[must_use]
    pub fn excluded_kinds(&self) -> &BTreeSet<EventCategory> {
        &self.exclude_kinds
    }

    /// Returns explicitly excluded regions.
    #[must_use]
    pub fn excluded_regions(&self) -> &BTreeSet<RegionId> {
        &self.exclude_regions
    }
}

// =============================================================================
// FilterBuilder (for Lab runtime integration)
// =============================================================================

/// Builder for configuring trace filters with a fluent API.
///
/// This is designed for integration with `LabRuntimeBuilder`:
///
/// ```ignore
/// let lab = LabRuntimeBuilder::new()
///     .record_trace()
///     .trace_filter(|f| f
///         .include_kinds([EventCategory::Scheduling, EventCategory::Time])
///         .exclude_region(RegionId(0))
///         .sample_rate(0.1))
///     .build();
/// ```
pub struct FilterBuilder {
    filter: TraceFilter,
}

impl FilterBuilder {
    /// Creates a new filter builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            filter: TraceFilter::new(),
        }
    }

    /// Includes the given event kinds.
    #[must_use]
    pub fn include_kinds<I>(mut self, kinds: I) -> Self
    where
        I: IntoIterator<Item = EventCategory>,
    {
        self.filter = self.filter.include_kinds(kinds);
        self
    }

    /// Excludes the given event kinds.
    #[must_use]
    pub fn exclude_kinds<I>(mut self, kinds: I) -> Self
    where
        I: IntoIterator<Item = EventCategory>,
    {
        self.filter = self.filter.exclude_kinds(kinds);
        self
    }

    /// Excludes the root region (useful for reducing noise).
    #[must_use]
    pub fn exclude_root_region(mut self) -> Self {
        self.filter = self.filter.exclude_region(RegionId::testing_default());
        self
    }

    /// Sets the sample rate for high-frequency events.
    #[must_use]
    pub fn sample_rate(mut self, rate: f64) -> Self {
        self.filter = self.filter.with_sample_rate(rate);
        self
    }

    /// Builds the filter.
    #[must_use]
    pub fn build(self) -> TraceFilter {
        self.filter
    }
}

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

// =============================================================================
// Tests
// =============================================================================

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

    // Simple test event for filter testing
    struct TestEvent {
        kind: EventCategory,
        task: Option<TaskId>,
        region: Option<RegionId>,
    }

    impl FilterableEvent for TestEvent {
        fn event_kind(&self) -> EventCategory {
            self.kind
        }

        fn task_id(&self) -> Option<TaskId> {
            self.task
        }

        fn region_id(&self) -> Option<RegionId> {
            self.region
        }
    }

    fn make_task_id(index: u32) -> TaskId {
        TaskId::new_for_test(index, 0)
    }

    fn make_region_id(index: u32) -> RegionId {
        RegionId::new_for_test(index, 0)
    }

    #[test]
    fn default_filter_passes_all() {
        let mut filter = TraceFilter::default();
        assert!(filter.is_pass_through());

        let event = TestEvent {
            kind: EventCategory::Scheduling,
            task: Some(make_task_id(1)),
            region: Some(make_region_id(0)),
        };
        assert!(filter.should_record(&event));
    }

    #[test]
    fn include_kinds_filter() {
        let mut filter =
            TraceFilter::new().include_kinds([EventCategory::Scheduling, EventCategory::Time]);

        let scheduling = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: None,
        };
        let io = TestEvent {
            kind: EventCategory::Io,
            task: None,
            region: None,
        };

        assert!(filter.should_record(&scheduling));
        assert!(!filter.should_record(&io));
    }

    #[test]
    fn exclude_kinds_filter() {
        let mut filter = TraceFilter::new().exclude_kind(EventCategory::Rng);

        let rng = TestEvent {
            kind: EventCategory::Rng,
            task: None,
            region: None,
        };
        let scheduling = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: None,
        };

        assert!(!filter.should_record(&rng));
        assert!(filter.should_record(&scheduling));
    }

    #[test]
    fn exclude_takes_precedence_over_include() {
        let mut filter = TraceFilter::new()
            .include_kinds([EventCategory::Scheduling, EventCategory::Rng])
            .exclude_kind(EventCategory::Rng);

        let rng = TestEvent {
            kind: EventCategory::Rng,
            task: None,
            region: None,
        };
        assert!(!filter.should_record(&rng));
    }

    #[test]
    fn task_filter() {
        let task1 = make_task_id(1);
        let task2 = make_task_id(2);

        let mut filter = TraceFilter::new().filter_tasks([task1]);

        let event1 = TestEvent {
            kind: EventCategory::Scheduling,
            task: Some(task1),
            region: None,
        };
        let event2 = TestEvent {
            kind: EventCategory::Scheduling,
            task: Some(task2),
            region: None,
        };
        let no_task = TestEvent {
            kind: EventCategory::Time,
            task: None,
            region: None,
        };

        assert!(filter.should_record(&event1));
        assert!(!filter.should_record(&event2));
        assert!(filter.should_record(&no_task)); // No task = passes through
    }

    #[test]
    fn region_filter() {
        let region1 = make_region_id(1);
        let region2 = make_region_id(2);

        let mut filter = TraceFilter::new().filter_regions([region1]);

        let event1 = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region1),
        };
        let event2 = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region2),
        };
        let no_region = TestEvent {
            kind: EventCategory::Time,
            task: None,
            region: None,
        };

        assert!(filter.should_record(&event1));
        assert!(!filter.should_record(&event2));
        assert!(filter.should_record(&no_region)); // No region = passes through
    }

    #[test]
    fn exclude_region_blocks_events() {
        let region1 = make_region_id(1);
        let region2 = make_region_id(2);

        let mut filter = TraceFilter::new().exclude_region(region1);

        let excluded = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region1),
        };
        let allowed = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region2),
        };

        assert!(!filter.should_record(&excluded));
        assert!(filter.should_record(&allowed));
        assert!(filter.excluded_regions().contains(&region1));
    }

    #[test]
    fn exclude_region_overrides_region_filter() {
        let region1 = make_region_id(1);
        let region2 = make_region_id(2);

        let mut filter = TraceFilter::new()
            .filter_regions([region1, region2])
            .exclude_region(region2);

        let event1 = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region1),
        };
        let event2 = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(region2),
        };

        assert!(filter.should_record(&event1));
        assert!(!filter.should_record(&event2));
    }

    #[test]
    fn sampling() {
        // Seed for reproducibility
        let mut filter = TraceFilter::new()
            .with_sample_rate(0.5)
            .with_sample_seed(42);

        // Count how many RNG events pass
        let mut passed = 0;
        let total = 1000;

        for _ in 0..total {
            let event = TestEvent {
                kind: EventCategory::Rng, // High-frequency, subject to sampling
                task: None,
                region: None,
            };
            if filter.should_record(&event) {
                passed += 1;
            }
        }

        // Should be approximately 50% (with some variance)
        assert!(passed > 400 && passed < 600, "Passed: {passed}");
    }

    #[test]
    fn no_sampling_for_non_high_frequency() {
        let mut filter = TraceFilter::new()
            .with_sample_rate(0.0) // Would drop all sampled events
            .with_sample_seed(42);

        // Scheduling is not high-frequency, so not sampled
        let event = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: None,
        };

        // Should pass even with 0% sample rate
        assert!(filter.should_record(&event));
    }

    #[test]
    fn custom_predicate() {
        let mut filter = TraceFilter::new().with_custom(|event| {
            // Only allow events with a task ID
            event.task_id().is_some()
        });

        let with_task = TestEvent {
            kind: EventCategory::Scheduling,
            task: Some(make_task_id(1)),
            region: None,
        };
        let without_task = TestEvent {
            kind: EventCategory::Time,
            task: None,
            region: None,
        };

        assert!(filter.should_record(&with_task));
        assert!(!filter.should_record(&without_task));
    }

    #[test]
    fn predefined_scheduling_only() {
        let filter = TraceFilter::scheduling_only();

        assert!(filter.includes_kind(EventCategory::Scheduling));
        assert!(filter.includes_kind(EventCategory::Chaos));
        assert!(!filter.includes_kind(EventCategory::Rng));
        assert!(!filter.includes_kind(EventCategory::Io));
    }

    #[test]
    fn predefined_no_rng() {
        let filter = TraceFilter::no_rng();

        assert!(!filter.includes_kind(EventCategory::Rng));
        assert!(filter.includes_kind(EventCategory::Scheduling));
        assert!(filter.includes_kind(EventCategory::Time));
    }

    #[test]
    fn predefined_io_focused() {
        let filter = TraceFilter::io_focused();

        assert!(filter.includes_kind(EventCategory::Io));
        assert!(filter.includes_kind(EventCategory::Scheduling));
        assert!(filter.includes_kind(EventCategory::Time));
        assert!(!filter.includes_kind(EventCategory::Rng));
        assert!(!filter.includes_kind(EventCategory::Waker));
    }

    #[test]
    fn filter_builder() {
        let filter = FilterBuilder::new()
            .include_kinds([EventCategory::Scheduling, EventCategory::Time])
            .exclude_kinds([EventCategory::Waker])
            .sample_rate(0.5)
            .build();

        assert!(filter.includes_kind(EventCategory::Scheduling));
        assert!(!filter.includes_kind(EventCategory::Rng));
        assert!(!filter.includes_kind(EventCategory::Waker));
        assert!((filter.sample_rate() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn filter_builder_exclude_root_region() {
        let mut filter = FilterBuilder::new().exclude_root_region().build();
        let root = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(make_region_id(0)),
        };
        let non_root = TestEvent {
            kind: EventCategory::Scheduling,
            task: None,
            region: Some(make_region_id(7)),
        };

        assert!(!filter.should_record(&root));
        assert!(filter.should_record(&non_root));
    }

    #[test]
    fn is_pass_through() {
        assert!(TraceFilter::default().is_pass_through());
        assert!(!TraceFilter::no_rng().is_pass_through());
        assert!(!TraceFilter::scheduling_only().is_pass_through());
        assert!(!TraceFilter::with_sampling(0.5).is_pass_through());
    }
}