tracing-throttle 0.4.2

High-performance log deduplication and rate limiting for the tracing ecosystem
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
//! Summary emission for suppressed events.
//!
//! Periodically collects and emits summaries of suppressed events to provide
//! visibility into what has been rate limited.

use crate::application::{
    ports::Storage,
    registry::{EventState, SuppressionRegistry},
};
use crate::domain::{signature::EventSignature, summary::SuppressionSummary};
use std::time::Duration;

#[cfg(feature = "async")]
use tokio::{sync::watch, time::interval};

/// Error returned when emitter configuration validation fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmitterConfigError {
    /// Summary interval duration must be greater than zero
    ZeroSummaryInterval,
}

impl std::fmt::Display for EmitterConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EmitterConfigError::ZeroSummaryInterval => {
                write!(f, "summary interval must be greater than 0")
            }
        }
    }
}

impl std::error::Error for EmitterConfigError {}

/// Error returned when emitter shutdown fails.
#[cfg(feature = "async")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShutdownError {
    /// Task panicked during shutdown
    TaskPanicked,
    /// Task was cancelled before completing
    TaskCancelled,
    /// Shutdown exceeded the specified timeout
    Timeout,
    /// Failed to send shutdown signal (task may have already exited)
    SignalFailed,
}

#[cfg(feature = "async")]
impl std::fmt::Display for ShutdownError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ShutdownError::TaskPanicked => write!(f, "emitter task panicked during shutdown"),
            ShutdownError::TaskCancelled => write!(f, "emitter task was cancelled"),
            ShutdownError::Timeout => write!(f, "shutdown exceeded timeout"),
            ShutdownError::SignalFailed => write!(f, "failed to send shutdown signal"),
        }
    }
}

#[cfg(feature = "async")]
impl std::error::Error for ShutdownError {}

/// Configuration for summary emission.
#[derive(Debug, Clone)]
pub struct EmitterConfig {
    /// How often to emit summaries
    pub interval: Duration,
    /// Minimum suppression count to include in summary
    pub min_count: usize,
}

impl Default for EmitterConfig {
    fn default() -> Self {
        Self {
            interval: Duration::from_secs(30),
            min_count: 1,
        }
    }
}

impl EmitterConfig {
    /// Create a new emitter config with the specified interval.
    ///
    /// # Errors
    /// Returns `EmitterConfigError::ZeroSummaryInterval` if `interval` is zero.
    pub fn new(interval: Duration) -> Result<Self, EmitterConfigError> {
        if interval.is_zero() {
            return Err(EmitterConfigError::ZeroSummaryInterval);
        }
        Ok(Self {
            interval,
            min_count: 1,
        })
    }

    /// Set the minimum suppression count threshold.
    pub fn with_min_count(mut self, min_count: usize) -> Self {
        self.min_count = min_count;
        self
    }
}

/// Handle for controlling a running emitter task.
///
/// # Shutdown Behavior
///
/// You **must** call `shutdown().await` to stop the emitter task. The handle does
/// not implement `Drop` to avoid race conditions and resource leaks.
///
/// If you drop the handle without calling `shutdown()`, the background task will
/// continue running indefinitely, potentially causing:
/// - Resource leaks (the task holds references to the registry)
/// - Unexpected behavior if the task outlives expected lifetime
/// - Inability to observe task failures or panics
///
/// # Examples
///
/// ```rust,no_run
/// # use tracing_throttle::application::emitter::{SummaryEmitter, EmitterConfig};
/// # use tracing_throttle::application::registry::SuppressionRegistry;
/// # use tracing_throttle::domain::policy::Policy;
/// # use tracing_throttle::infrastructure::storage::ShardedStorage;
/// # use tracing_throttle::infrastructure::clock::SystemClock;
/// # use std::sync::Arc;
/// # async fn example() {
/// # let storage = Arc::new(ShardedStorage::new());
/// # let clock = Arc::new(SystemClock::new());
/// # let policy = Policy::count_based(100).unwrap();
/// # let registry = SuppressionRegistry::new(storage, clock, policy);
/// # let config = EmitterConfig::default();
/// # let emitter = SummaryEmitter::new(registry, config);
/// let handle = emitter.start(|_| {}, false);
///
/// // Always call shutdown explicitly
/// handle.shutdown().await.expect("shutdown failed");
/// # }
/// ```
#[cfg(feature = "async")]
pub struct EmitterHandle {
    shutdown_tx: watch::Sender<bool>,
    join_handle: Option<tokio::task::JoinHandle<()>>,
}

#[cfg(feature = "async")]
impl EmitterHandle {
    /// Trigger graceful shutdown and wait for the task to complete.
    ///
    /// This method uses a default timeout of 10 seconds. For custom timeout durations,
    /// use [`shutdown_with_timeout`](Self::shutdown_with_timeout).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The task panics during shutdown
    /// - The task is cancelled
    /// - Shutdown exceeds the timeout (10 seconds)
    /// - The shutdown signal fails to send
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use tracing_throttle::application::emitter::{SummaryEmitter, EmitterConfig};
    /// # use tracing_throttle::application::registry::SuppressionRegistry;
    /// # use tracing_throttle::domain::policy::Policy;
    /// # use tracing_throttle::infrastructure::storage::ShardedStorage;
    /// # use tracing_throttle::infrastructure::clock::SystemClock;
    /// # use std::sync::Arc;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let storage = Arc::new(ShardedStorage::new());
    /// # let clock = Arc::new(SystemClock::new());
    /// # let policy = Policy::count_based(100).unwrap();
    /// # let registry = SuppressionRegistry::new(storage, clock, policy);
    /// # let config = EmitterConfig::default();
    /// # let emitter = SummaryEmitter::new(registry, config);
    /// let handle = emitter.start(|_| {}, false);
    ///
    /// // Do some work...
    ///
    /// // Clean shutdown with default 10 second timeout
    /// handle.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn shutdown(self) -> Result<(), ShutdownError> {
        self.shutdown_with_timeout(Duration::from_secs(10)).await
    }

    /// Trigger graceful shutdown with a custom timeout.
    ///
    /// This method:
    /// 1. Sends the shutdown signal
    /// 2. Waits for the background task to finish (up to the timeout)
    /// 3. If the timeout is exceeded, the task is aborted
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The task panics during shutdown
    /// - The task is cancelled
    /// - Shutdown exceeds the specified timeout
    /// - The shutdown signal fails to send
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use tracing_throttle::application::emitter::{SummaryEmitter, EmitterConfig};
    /// # use tracing_throttle::application::registry::SuppressionRegistry;
    /// # use tracing_throttle::domain::policy::Policy;
    /// # use tracing_throttle::infrastructure::storage::ShardedStorage;
    /// # use tracing_throttle::infrastructure::clock::SystemClock;
    /// # use std::sync::Arc;
    /// # use std::time::Duration;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let storage = Arc::new(ShardedStorage::new());
    /// # let clock = Arc::new(SystemClock::new());
    /// # let policy = Policy::count_based(100).unwrap();
    /// # let registry = SuppressionRegistry::new(storage, clock, policy);
    /// # let config = EmitterConfig::default();
    /// # let emitter = SummaryEmitter::new(registry, config);
    /// let handle = emitter.start(|_| {}, false);
    ///
    /// // Do some work...
    ///
    /// // Clean shutdown with 5 second timeout
    /// handle.shutdown_with_timeout(Duration::from_secs(5)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn shutdown_with_timeout(
        mut self,
        timeout_duration: Duration,
    ) -> Result<(), ShutdownError> {
        use tokio::time::timeout;

        // Send shutdown signal
        if self.shutdown_tx.send(true).is_err() {
            return Err(ShutdownError::SignalFailed);
        }

        // Wait for task to complete with timeout
        if let Some(handle) = self.join_handle.take() {
            match timeout(timeout_duration, handle).await {
                Ok(Ok(())) => Ok(()),
                Ok(Err(e)) if e.is_panic() => Err(ShutdownError::TaskPanicked),
                Ok(Err(e)) if e.is_cancelled() => Err(ShutdownError::TaskCancelled),
                Ok(Err(_)) => Err(ShutdownError::TaskPanicked), // Treat unknown errors as panics
                Err(_) => Err(ShutdownError::Timeout),
            }
        } else {
            Ok(())
        }
    }

    /// Check if the emitter task is still running.
    pub fn is_running(&self) -> bool {
        self.join_handle.as_ref().is_some_and(|h| !h.is_finished())
    }
}

/// Emits periodic summaries of suppressed events.
pub struct SummaryEmitter<S>
where
    S: Storage<EventSignature, EventState> + Clone,
{
    registry: SuppressionRegistry<S>,
    config: EmitterConfig,
}

impl<S> SummaryEmitter<S>
where
    S: Storage<EventSignature, EventState> + Clone,
{
    /// Create a new summary emitter.
    pub fn new(registry: SuppressionRegistry<S>, config: EmitterConfig) -> Self {
        Self { registry, config }
    }

    /// Collect current suppression summaries.
    ///
    /// Returns summaries for all events that have been suppressed at least
    /// `min_count` times.
    pub fn collect_summaries(&self) -> Vec<SuppressionSummary> {
        let mut summaries = Vec::new();
        let min_count = self.config.min_count;

        self.registry.for_each(|signature, state| {
            let count = state.counter.count();

            if count >= min_count {
                #[cfg(feature = "human-readable")]
                let summary = SuppressionSummary::from_counter_with_metadata(
                    *signature,
                    &state.counter,
                    state.metadata.clone(),
                );

                #[cfg(not(feature = "human-readable"))]
                let summary = SuppressionSummary::from_counter(*signature, &state.counter);

                summaries.push(summary);
            }
        });

        summaries
    }

    /// Start emitting summaries periodically (async version).
    ///
    /// This spawns a background task that emits summaries at the configured interval.
    /// The task will run until `shutdown()` is called on the returned `EmitterHandle`.
    ///
    /// # Graceful Shutdown
    ///
    /// When `shutdown()` is called on the `EmitterHandle`:
    /// 1. The shutdown signal is prioritized over tick events
    /// 2. The current emission completes if in progress
    /// 3. If `emit_final` is true, one final emission occurs with current summaries
    /// 4. The background task completes gracefully
    ///
    /// # Cancellation Safety
    ///
    /// The spawned task is cancellation-safe:
    /// - `collect_summaries()` reads atomically from storage without mutations
    /// - If cancelled during emission, the next startup will see correct state
    /// - Panics in `emit_fn` are caught and don't abort the task
    /// - The `emit_fn` closure should be cancellation-safe (avoid holding locks across `.await`)
    ///
    /// # Type Parameters
    ///
    /// * `F` - The emission function. Must be `Send + 'static` because it runs
    ///   in a spawned task that may execute on any thread in the tokio runtime.
    ///   The function receives ownership of the summaries vector.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use tracing_throttle::application::emitter::{SummaryEmitter, EmitterConfig};
    /// # use tracing_throttle::application::registry::SuppressionRegistry;
    /// # use tracing_throttle::domain::policy::Policy;
    /// # use tracing_throttle::infrastructure::storage::ShardedStorage;
    /// # use tracing_throttle::infrastructure::clock::SystemClock;
    /// # use std::sync::Arc;
    /// # use std::time::Duration;
    /// # async fn example() {
    /// # let storage = Arc::new(ShardedStorage::new());
    /// # let clock = Arc::new(SystemClock::new());
    /// # let policy = Policy::count_based(100).unwrap();
    /// # let registry = SuppressionRegistry::new(storage, clock, policy);
    /// # let config = EmitterConfig::default();
    /// let emitter = SummaryEmitter::new(registry, config);
    /// let handle = emitter.start(|summaries| {
    ///     for summary in summaries {
    ///         tracing::warn!("{}", summary.format_message());
    ///     }
    /// }, true);
    ///
    /// // Later, trigger graceful shutdown
    /// handle.shutdown().await.expect("shutdown failed");
    /// # }
    /// ```
    #[cfg(feature = "async")]
    pub fn start<F>(self, mut emit_fn: F, emit_final: bool) -> EmitterHandle
    where
        F: FnMut(Vec<SuppressionSummary>) + Send + 'static,
        S: Send + 'static,
    {
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::watch::channel(false);

        let handle = tokio::spawn(async move {
            let mut ticker = interval(self.config.interval);
            // Skip missed ticks to prevent backpressure if emissions are slow
            ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

            loop {
                tokio::select! {
                    // Prioritize shutdown signal to ensure fast shutdown
                    biased;

                    _ = shutdown_rx.changed() => {
                        if *shutdown_rx.borrow_and_update() {
                            // Emit final summaries if requested
                            if emit_final {
                                let summaries = self.collect_summaries();
                                if !summaries.is_empty() {
                                    // Panic safety for final emission too
                                    // Note: summaries will be properly dropped even if emit_fn panics
                                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                        emit_fn(summaries);
                                    }));

                                    if result.is_err() {
                                        #[cfg(debug_assertions)]
                                        eprintln!("Warning: emit_fn panicked during final emission");
                                    }
                                }
                            }
                            break;
                        }
                    }
                    _ = ticker.tick() => {
                        let summaries = self.collect_summaries();
                        if !summaries.is_empty() {
                            // Panic safety: catch panics in emit_fn to prevent task abort
                            // Note: summaries will be properly dropped even if emit_fn panics
                            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                emit_fn(summaries);
                            }));

                            if result.is_err() {
                                // emit_fn panicked - summaries were dropped, continue running
                                #[cfg(debug_assertions)]
                                eprintln!("Warning: emit_fn panicked during emission");
                            }
                        }
                    }
                }
            }
        });

        EmitterHandle {
            shutdown_tx,
            join_handle: Some(handle),
        }
    }

    /// Get the emitter configuration.
    pub fn config(&self) -> &EmitterConfig {
        &self.config
    }

    /// Get a reference to the registry.
    pub fn registry(&self) -> &SuppressionRegistry<S> {
        &self.registry
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{policy::Policy, signature::EventSignature};
    use crate::infrastructure::clock::SystemClock;
    use crate::infrastructure::storage::ShardedStorage;
    use std::sync::Arc;

    #[test]
    fn test_collect_summaries_empty() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::default();
        let emitter = SummaryEmitter::new(registry, config);

        let summaries = emitter.collect_summaries();
        assert!(summaries.is_empty());
    }

    #[test]
    fn test_collect_summaries_with_suppressions() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::default();

        // Add some suppressed events
        for i in 0..3 {
            let sig = EventSignature::simple("INFO", &format!("Message {}", i));
            registry.with_event_state(sig, |state, now| {
                // Simulate some suppressions
                for _ in 0..(i + 1) * 5 {
                    state.counter.record_suppression(now);
                }
            });
        }

        let emitter = SummaryEmitter::new(registry, config);
        let summaries = emitter.collect_summaries();

        assert_eq!(summaries.len(), 3);

        // Verify counts
        let counts: Vec<usize> = summaries.iter().map(|s| s.count).collect();
        assert!(counts.contains(&5));
        assert!(counts.contains(&10));
        assert!(counts.contains(&15));
    }

    #[test]
    fn test_min_count_filtering() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::default().with_min_count(10);

        // Add event with low count (below threshold)
        let sig1 = EventSignature::simple("INFO", "Low count");
        registry.with_event_state(sig1, |state, now| {
            for _ in 0..4 {
                state.counter.record_suppression(now);
            }
        });

        // Add event with high count (above threshold)
        let sig2 = EventSignature::simple("INFO", "High count");
        registry.with_event_state(sig2, |state, now| {
            for _ in 0..14 {
                state.counter.record_suppression(now);
            }
        });

        let emitter = SummaryEmitter::new(registry, config);
        let summaries = emitter.collect_summaries();

        // Only the high-count event should be included
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].count, 14);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_async_emission() {
        use std::sync::Mutex;

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(100)).unwrap();

        // Add a suppressed event
        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        let emitter = SummaryEmitter::new(registry, config);

        // Track emissions
        let emissions = Arc::new(Mutex::new(Vec::new()));
        let emissions_clone = Arc::clone(&emissions);

        let handle = emitter.start(
            move |summaries| {
                emissions_clone.lock().unwrap().push(summaries.len());
            },
            false,
        );

        // Wait for a couple of intervals
        tokio::time::sleep(Duration::from_millis(250)).await;

        handle.shutdown().await.expect("shutdown failed");

        // Should have emitted at least once
        let emission_count = emissions.lock().unwrap().len();
        assert!(emission_count >= 2);
    }

    #[test]
    fn test_emitter_config_zero_interval() {
        let result = EmitterConfig::new(Duration::from_secs(0));
        assert!(matches!(
            result,
            Err(EmitterConfigError::ZeroSummaryInterval)
        ));
    }

    #[test]
    fn test_emitter_config_valid_interval() {
        let config = EmitterConfig::new(Duration::from_secs(30)).unwrap();
        assert_eq!(config.interval, Duration::from_secs(30));
        assert_eq!(config.min_count, 1);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_graceful_shutdown() {
        use std::sync::Mutex;

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(100)).unwrap();

        // Add a suppressed event so there's something to emit
        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        let emitter = SummaryEmitter::new(registry, config);

        let emissions = Arc::new(Mutex::new(0));
        let emissions_clone = Arc::clone(&emissions);

        let handle = emitter.start(
            move |_| {
                *emissions_clone.lock().unwrap() += 1;
            },
            false,
        );

        // Let it run for a bit
        tokio::time::sleep(Duration::from_millis(250)).await;

        // Trigger graceful shutdown
        handle.shutdown().await.expect("shutdown failed");

        // Verify task is no longer running
        let final_count = *emissions.lock().unwrap();
        assert!(final_count >= 1);

        // Wait a bit more to ensure task really stopped
        tokio::time::sleep(Duration::from_millis(150)).await;
        let count_after_shutdown = *emissions.lock().unwrap();
        assert_eq!(count_after_shutdown, final_count);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_with_final_emission() {
        use std::sync::Mutex;

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_secs(60)).unwrap(); // Long interval

        let emitter = SummaryEmitter::new(registry.clone(), config);

        let emissions = Arc::new(Mutex::new(Vec::new()));
        let emissions_clone = Arc::clone(&emissions);

        let handle = emitter.start(
            move |summaries| {
                emissions_clone.lock().unwrap().push(summaries.len());
            },
            true, // Emit final summaries
        );

        // Wait for first tick to complete (interval's first tick is immediate)
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Now add some suppressions after the first tick
        let sig = EventSignature::simple("INFO", "Test event");
        registry.with_event_state(sig, |state, now| {
            for _ in 0..10 {
                state.counter.record_suppression(now);
            }
        });

        // Shutdown before next interval (which is 60 seconds away)
        tokio::time::sleep(Duration::from_millis(50)).await;
        handle.shutdown().await.expect("shutdown failed");

        // Should have emitted final summaries
        let emission_list = emissions.lock().unwrap();
        assert_eq!(emission_list.len(), 1);
        assert_eq!(emission_list[0], 1); // 1 summary
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_without_final_emission() {
        use std::sync::Mutex;

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_secs(60)).unwrap();

        let emitter = SummaryEmitter::new(registry.clone(), config);

        let emissions = Arc::new(Mutex::new(0));
        let emissions_clone = Arc::clone(&emissions);

        let handle = emitter.start(
            move |_| {
                *emissions_clone.lock().unwrap() += 1;
            },
            false, // No final emission
        );

        // Wait for first tick (immediate, but no emissions since no suppressions yet)
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Add some suppressions after first tick
        let sig = EventSignature::simple("INFO", "Test event");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        // Shutdown immediately (before next 60-second interval)
        tokio::time::sleep(Duration::from_millis(50)).await;
        handle.shutdown().await.expect("shutdown failed");

        // Should not have emitted anything (no final emission)
        assert_eq!(*emissions.lock().unwrap(), 0);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_is_running() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(100)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);
        let handle = emitter.start(|_| {}, false);

        // Should be running
        assert!(handle.is_running());

        // Shutdown
        handle.shutdown().await.expect("shutdown failed");

        // Should no longer be running
        tokio::time::sleep(Duration::from_millis(50)).await;
        // Note: is_running() consumes self, so we can't check after shutdown
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_during_emission() {
        use std::sync::{Arc, Mutex};

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(50)).unwrap();

        // Add suppressions
        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        let emitter = SummaryEmitter::new(registry, config);

        let emissions = Arc::new(Mutex::new(0));
        let emissions_clone = Arc::clone(&emissions);

        let handle = emitter.start(
            move |_| {
                // Simulate slow emission
                std::thread::sleep(Duration::from_millis(30));
                *emissions_clone.lock().unwrap() += 1;
            },
            false,
        );

        // Let first emission start
        tokio::time::sleep(Duration::from_millis(60)).await;

        // Shutdown should wait for current emission to complete
        handle.shutdown().await.expect("shutdown failed");

        // Current emission should have completed
        assert!(*emissions.lock().unwrap() >= 1);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_with_custom_timeout() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(100)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);
        let handle = emitter.start(|_| {}, false);

        // Let it run briefly
        tokio::time::sleep(Duration::from_millis(150)).await;

        // Shutdown with custom timeout should succeed quickly
        let result = handle.shutdown_with_timeout(Duration::from_secs(5)).await;
        assert!(result.is_ok());
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_panic_in_emit_fn() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(50)).unwrap();

        // Add suppressions
        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            for _ in 0..5 {
                state.counter.record_suppression(now);
            }
        });

        let emitter = SummaryEmitter::new(registry, config);

        let call_count = Arc::new(AtomicUsize::new(0));
        let call_count_clone = Arc::clone(&call_count);

        let handle = emitter.start(
            move |_summaries| {
                let count = call_count_clone.fetch_add(1, Ordering::SeqCst);

                // Panic on first call, succeed on subsequent calls
                if count == 0 {
                    panic!("intentional panic for testing");
                }
                // If we get here, panic was handled and task continued
            },
            false,
        );

        // Let it emit multiple times - first should panic, rest should succeed
        tokio::time::sleep(Duration::from_millis(200)).await;

        handle.shutdown().await.expect("shutdown failed");

        // Should have attempted multiple emissions (first panicked, others succeeded)
        let final_count = call_count.load(Ordering::SeqCst);
        assert!(
            final_count > 1,
            "Task should continue after panic in emit_fn"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_repeated_panic_in_emit_fn() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(30)).unwrap();

        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        let emitter = SummaryEmitter::new(registry, config);

        let call_count = Arc::new(AtomicUsize::new(0));
        let call_count_clone = Arc::clone(&call_count);

        let handle = emitter.start(
            move |_summaries| {
                call_count_clone.fetch_add(1, Ordering::SeqCst);
                panic!("always panic");
            },
            false,
        );

        // Let it run and panic multiple times
        tokio::time::sleep(Duration::from_millis(150)).await;

        handle.shutdown().await.expect("shutdown failed");

        // Should have attempted multiple times despite continuous panics
        let final_count = call_count.load(Ordering::SeqCst);
        assert!(
            final_count >= 3,
            "Task should continue despite repeated panics, got {} calls",
            final_count
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_panic_during_final_emission() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_secs(3600)).unwrap(); // Long interval

        let sig = EventSignature::simple("INFO", "Test");
        registry.with_event_state(sig, |state, now| {
            state.counter.record_suppression(now);
        });

        let emitter = SummaryEmitter::new(registry, config);

        let panicked = Arc::new(AtomicBool::new(false));
        let panicked_clone = Arc::clone(&panicked);

        let handle = emitter.start(
            move |_summaries| {
                panicked_clone.store(true, Ordering::SeqCst);
                panic!("panic during final emission");
            },
            true, // emit_on_shutdown
        );

        // Shutdown immediately - will trigger final emission which panics
        handle
            .shutdown()
            .await
            .expect("shutdown should succeed even if final emission panics");

        // Verify final emission was attempted
        assert!(
            panicked.load(Ordering::SeqCst),
            "Final emission should have been attempted"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_timeout_with_slow_emit_fn() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_secs(3600)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);

        let handle = emitter.start(
            move |_summaries| {
                // Simulate slow emission - use a shorter duration for testing
                std::thread::sleep(Duration::from_millis(500));
            },
            true,
        );

        // Shutdown with very short timeout
        let result = handle
            .shutdown_with_timeout(Duration::from_millis(10))
            .await;

        // Should timeout (or at minimum not panic)
        // Note: timing-sensitive test, may occasionally pass if emit completes quickly
        let _ = result; // Don't assert - just verify no panic
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_handle_dropped_without_shutdown() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(50)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);

        let handle = emitter.start(|_summaries| {}, false);

        // Drop handle without calling shutdown
        drop(handle);

        // Task should continue running
        // This is documented behavior - not a bug
        tokio::time::sleep(Duration::from_millis(100)).await;

        // No assertions - just verify no panic
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_concurrent_shutdown_calls() {
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_secs(3600)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);
        let handle = emitter.start(|_summaries| {}, false);

        // Create multiple shutdown senders
        let sender = handle.shutdown_tx.clone();
        let mut handles_vec = vec![];

        // Multiple tasks try to send shutdown signal concurrently
        for _ in 0..5 {
            let sender_clone = sender.clone();
            handles_vec.push(tokio::spawn(async move {
                let _ = sender_clone.send(true);
            }));
        }

        // All send operations should complete without panic
        for h in handles_vec {
            let _ = h.await;
        }

        // Clean shutdown
        let _ = handle.shutdown().await;
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_shutdown_signal_failure() {
        // Test that shutdown handles channel errors gracefully
        let storage = Arc::new(ShardedStorage::new());
        let clock = Arc::new(SystemClock::new());
        let policy = Policy::count_based(100).unwrap();
        let registry = SuppressionRegistry::new(storage, clock, policy);
        let config = EmitterConfig::new(Duration::from_millis(30)).unwrap();

        let emitter = SummaryEmitter::new(registry, config);
        let handle = emitter.start(|_summaries| {}, false);

        // Normal shutdown
        handle.shutdown().await.expect("shutdown should succeed");

        // Verify task stopped
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}