tiny-counter 0.1.0

Track event counts across time windows with fixed memory and fast queries
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
/// Multi-interval event counter with coordinated rotation.
pub mod config;

use std::{collections::HashMap, ops::Range};

use chrono::{DateTime, Utc};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use self::config::EventCounterConfig;
use crate::{IntervalConfig, IntervalCounter, Result, TimeUnit};

/// A counter that tracks events across multiple time unit granularities simultaneously.
///
/// All intervals share the same starting_instant, ensuring they rotate in sync.
/// This allows querying the same events at different time scales (minutes, hours, days, etc.).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct SingleEventCounter {
    starting_instant: DateTime<Utc>,
    intervals: HashMap<TimeUnit, IntervalCounter>,
    dirty: bool,
    /// Reserved slots for transactional rate limiting.
    /// These are in-flight operations that haven't been committed yet.
    #[cfg_attr(feature = "serde", serde(skip))]
    pending: u32,
}

impl SingleEventCounter {
    /// Creates a new SingleEventCounter with multiple intervals.
    ///
    /// All intervals share the same starting_instant, ensuring synchronized rotation.
    pub(crate) fn new(config: &EventCounterConfig, starting_instant: DateTime<Utc>) -> Self {
        let mut intervals = HashMap::new();
        for interval_config in config.as_vec() {
            let counter = IntervalCounter::new(interval_config.bucket_count(), starting_instant);
            intervals.insert(interval_config.time_unit(), counter);
        }
        Self {
            starting_instant,
            intervals,
            dirty: false,
            pending: 0,
        }
    }

    /// Records an event in all intervals at the current time.
    ///
    /// Each interval counter calls advance_if_needed internally during record.
    pub fn record(&mut self, count: u32) {
        for counter in self.intervals.values_mut() {
            counter.increment_bucket(0, count);
        }
    }

    /// Records an event that occurred at a specific time.
    ///
    /// Advances all intervals to 'now', then records the event at 'time' in all intervals.
    /// Returns an error if the event time is in the future.
    pub(crate) fn record_at(&mut self, count: u32, time: DateTime<Utc>) -> Result<()> {
        for (time_unit, counter) in self.intervals.iter_mut() {
            counter.increment_at(count, time, time_unit)?;
        }
        Ok(())
    }

    /// Queries the sum of counts for a specific time unit within the given bucket range.
    ///
    /// Returns None if the time unit is not tracked by this counter.
    /// If time_unit is TimeUnit::Ever, uses the longest tracked time unit.
    pub(crate) fn sum_range(&self, time_unit: TimeUnit, range: Range<usize>) -> Option<u32> {
        // Then query
        self.intervals
            .get(&time_unit)
            .map(|counter| counter.sum_range(range.start, range.end))
    }

    /// Finds the index of the first non-zero bucket for a specific time unit.
    ///
    /// Returns None if the time unit is not tracked or all buckets are zero.
    /// Index 0 is the current interval, higher indices are older intervals.
    pub(crate) fn last_seen_in(&self, time_unit: TimeUnit) -> Option<usize> {
        // Get the counter for this time unit
        let counter = self.intervals.get(&time_unit)?;

        // Find first non-zero bucket
        (0..counter.bucket_count()).find(|&i| counter.bucket_value(i).unwrap_or(0) > 0)
    }

    /// Finds the index of the oldest non-zero bucket for a specific time unit.
    ///
    /// Returns None if the time unit is not tracked or all buckets are zero.
    /// Index 0 is the current interval, higher indices are older intervals.
    /// If time_unit is TimeUnit::Ever, uses the longest tracked time unit.
    ///
    /// This is the opposite of last_seen: it searches from the oldest bucket
    /// (highest index) toward the newest (index 0).
    pub(crate) fn first_seen_in(&self, time_unit: TimeUnit) -> Option<usize> {
        // Get the counter for this time unit
        let counter = self.intervals.get(&time_unit)?;

        // Find last non-zero bucket (iterate from oldest to newest)
        (0..counter.bucket_count())
            .rev()
            .find(|&i| counter.bucket_value(i).unwrap_or_default() > 0)
    }

    /// Returns the shared starting instant for all intervals.
    pub(crate) fn starting_instant(&self) -> DateTime<Utc> {
        self.starting_instant
    }

    pub(crate) fn interval_start(&self, time_unit: TimeUnit) -> Option<DateTime<Utc>> {
        let counter = self.intervals.get(&time_unit)?;
        Some(counter.interval_start())
    }

    /// Returns whether this counter has unsaved changes.
    pub(crate) fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Marks this counter as having unsaved changes.
    pub(crate) fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    /// Marks this counter as clean (all changes saved).
    pub(crate) fn reset_dirty(&mut self) {
        self.dirty = false;
    }

    /// Advances all intervals to the given time.
    pub fn advance_if_needed(&mut self, now: DateTime<Utc>) {
        for (unit, counter) in self.intervals.iter_mut() {
            counter.advance_if_needed(unit, now);
        }
        self.starting_instant = now;
    }

    pub(crate) fn memory_usage(&self) -> usize {
        let mut total = 0usize;
        for interval_counter in self.intervals.values() {
            // Each bucket is u64 (8 bytes)
            total =
                total.saturating_add(interval_counter.bucket_count() * std::mem::size_of::<u64>());
        }
        total
    }

    pub(crate) fn is_empty(&self, time_unit: TimeUnit) -> bool {
        self.sum_range(time_unit, 0..usize::MAX).unwrap_or_default() == 0
    }

    /// Returns the current pending reservation count.
    pub(crate) fn pending_count(&self) -> u32 {
        self.pending
    }

    /// Increments the pending reservation count by 1.
    /// Uses saturating addition to prevent overflow (though u32::MAX pending reservations is not realistic).
    pub(crate) fn increment_pending(&mut self) {
        self.pending = self.pending.saturating_add(1);
    }

    /// Decrements the pending reservation count by 1, saturating at zero.
    pub(crate) fn decrement_pending(&mut self) {
        self.pending = self.pending.saturating_sub(1);
    }

    /// Provides immutable access to all interval counters.
    pub(crate) fn intervals(&self) -> &HashMap<TimeUnit, IntervalCounter> {
        &self.intervals
    }

    /// Gets the interval counter for a specific time unit.
    /// Returns None if the time unit is not tracked.
    pub(crate) fn interval(&self, time_unit: TimeUnit) -> Option<&IntervalCounter> {
        self.intervals.get(&time_unit)
    }

    #[cfg(test)]
    pub(crate) fn interval_mut(&mut self, time_unit: TimeUnit) -> Option<&mut IntervalCounter> {
        self.intervals.get_mut(&time_unit)
    }

    /// Returns the total count for a time unit including pending reservations.
    ///
    /// This is used by transactional rate limiting to prevent race conditions.
    /// The pending count represents reserved slots that haven't been committed yet.
    pub(crate) fn total_with_pending(&self, time_unit: TimeUnit, range: Range<usize>) -> u32 {
        let actual_count = self.sum_range(time_unit, range).unwrap_or(0);
        actual_count.saturating_add(self.pending_count())
    }

    /// Merges another counter's data into this counter.
    ///
    /// The merge algorithm:
    /// 1. Converts other counter to match self's configuration if they differ
    /// 2. Aligns both counters to the same starting_instant (the most recent one)
    /// 3. Adds bucket values from other to self for each time unit
    /// 4. Addition is commutative: order doesn't matter
    ///
    /// Configuration conversion preserves as much data as possible:
    /// - If other has more buckets, truncates oldest data
    /// - If other has fewer buckets, extends with zeros
    /// - If other has different time units, adds missing ones (empty) or removes extra ones
    pub(crate) fn merge(&mut self, other: SingleEventCounter) -> Result<()> {
        // Extract self's configuration
        let self_config = self.as_counter_config();

        // Convert other to match self's configuration
        let other_converted = crate::config_converter::convert_if_needed(other, &self_config);

        // Determine the most recent starting_instant
        let target_instant = self.starting_instant.max(other_converted.starting_instant);

        // Align self to target_instant
        if self.starting_instant < target_instant {
            self.advance_if_needed(target_instant);
        }

        // Align converted other to target_instant
        let mut other_aligned = other_converted;
        if other_aligned.starting_instant < target_instant {
            other_aligned.advance_if_needed(target_instant);
        }

        // Add bucket values for each time unit
        for (time_unit, self_counter) in &mut self.intervals {
            if let Some(other_counter) = other_aligned.intervals.get(time_unit) {
                // Add each bucket from other to self
                // After conversion, bucket counts match
                self_counter.merge(other_counter);
            }
        }

        Ok(())
    }

    pub(crate) fn as_counter_config(&self) -> EventCounterConfig {
        let mut configs: Vec<IntervalConfig> = Default::default();
        for (time_unit, counter) in self.intervals.iter() {
            let bucket_count = counter.bucket_count();
            let res = IntervalConfig::new(bucket_count, *time_unit);
            if let Ok(config) = res {
                configs.push(config);
            }
        }
        EventCounterConfig::new(configs)
    }

    /// Test helper: Gets bucket count for a time unit.
    #[cfg(test)]
    pub(crate) fn bucket_count(&self, time_unit: TimeUnit) -> usize {
        self.intervals
            .get(&time_unit)
            .map(|counter| counter.bucket_count())
            .unwrap_or(0)
    }

    /// Test helper: Gets value from a specific bucket in a time unit.
    #[cfg(test)]
    pub(crate) fn bucket_value(&self, time_unit: TimeUnit, bucket_idx: usize) -> u32 {
        self.intervals
            .get(&time_unit)
            .and_then(|counter| counter.bucket_value(bucket_idx))
            .unwrap_or(0)
    }

    /// Test helper: Gets sum of all buckets for a time unit.
    #[cfg(test)]
    pub(crate) fn sum_for_unit(&self, time_unit: TimeUnit) -> u32 {
        self.sum_range(time_unit, 0..usize::MAX).unwrap_or_default()
    }

    /// Test helper: Gets total events (max across all time units).
    #[cfg(test)]
    pub(crate) fn total_events(&mut self) -> u32 {
        let Some(unit) = self.intervals.keys().max() else {
            return 0;
        };
        self.sum_range(*unit, 0..usize::MAX).unwrap_or(0)
    }

    /// Test helper: Checks if a time unit is configured.
    #[cfg(test)]
    pub(crate) fn has_time_unit(&self, time_unit: TimeUnit) -> bool {
        self.intervals.contains_key(&time_unit)
    }
}

#[cfg(test)]
mod tests {
    use chrono::{Duration, TimeZone};

    use crate::{sync_time::synchronized_start, Result};

    use super::*;

    #[test]
    fn test_new_creates_counter_with_multiple_intervals() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.starting_instant(), start);
        assert_eq!(counter.intervals.len(), 3);
        assert!(counter.intervals.contains_key(&TimeUnit::Minutes));
        assert!(counter.intervals.contains_key(&TimeUnit::Hours));
        assert!(counter.intervals.contains_key(&TimeUnit::Days));
    }

    #[test]
    fn test_record_updates_all_intervals_simultaneously() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        counter.record(5);

        // All intervals should have recorded the event
        assert_eq!(counter.bucket_value(TimeUnit::Minutes, 0), 5);
        assert_eq!(counter.bucket_value(TimeUnit::Hours, 0), 5);
        assert_eq!(counter.bucket_value(TimeUnit::Days, 0), 5);
    }

    #[test]
    fn test_record_at_updates_all_intervals_simultaneously() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        let event_time = start - chrono::Duration::minutes(30);
        counter.record_at(10, event_time).unwrap();

        // Both intervals should have recorded the event (in different buckets)
        // Minutes: 30 minutes ago = bucket 30 (0=current, 1=same interval before, 2-30=past)
        assert_eq!(counter.bucket_value(TimeUnit::Minutes, 30), 10);
        // Hours: same hour, before starting_instant = bucket 1
        assert_eq!(counter.bucket_value(TimeUnit::Hours, 1), 10);
    }

    #[test]
    fn test_record_at_propagates_errors() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        let future_time = start + chrono::Duration::hours(5);

        // Future events should fail
        let result = counter.record_at(10, future_time);
        assert!(result.is_err());
    }

    #[test]
    fn test_query_with_minutes_returns_some() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        counter.record(7);

        assert_eq!(counter.bucket_value(TimeUnit::Minutes, 0), 7);
    }

    #[test]
    fn test_query_with_untracked_time_unit_returns_none() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.sum_range(TimeUnit::Hours, 0..1), None);
        assert_eq!(counter.sum_range(TimeUnit::Days, 0..1), None);
    }

    #[test]
    fn test_last_seen_finds_first_nonzero_bucket() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        // Record event 5 minutes ago
        let event_time = start - chrono::Duration::minutes(5);
        counter.record_at(1, event_time).unwrap();

        // Event should be in bucket 5 (0=current, 1=same before, 2-5=past)
        let result = counter.last_seen_in(TimeUnit::Minutes);
        assert_eq!(result, Some(5));
    }

    #[test]
    fn test_last_seen_returns_none_if_all_buckets_zero() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.last_seen_in(TimeUnit::Minutes), None);
    }

    #[test]
    fn test_last_seen_returns_none_for_untracked_time_unit() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.last_seen_in(TimeUnit::Hours), None);
    }

    #[test]
    fn test_first_seen_finds_oldest_nonzero_bucket() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        // Record event 10 minutes ago
        let event_time_1 = start - chrono::Duration::minutes(10);
        counter.record_at(1, event_time_1).unwrap();

        // Record event 5 minutes ago
        let event_time_2 = start - chrono::Duration::minutes(5);
        counter.record_at(1, event_time_2).unwrap();

        // first_seen should find the oldest event (10 minutes ago at bucket 10)
        let result = counter.first_seen_in(TimeUnit::Minutes);
        assert_eq!(result, Some(10));

        // last_seen should find the newest event (5 minutes ago at bucket 5)
        let last_result = counter.last_seen_in(TimeUnit::Minutes);
        assert_eq!(last_result, Some(5));
    }

    #[test]
    fn test_first_seen_returns_none_if_all_buckets_zero() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.first_seen_in(TimeUnit::Minutes), None);
    }

    #[test]
    fn test_first_seen_returns_none_for_untracked_time_unit() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        assert_eq!(counter.first_seen_in(TimeUnit::Hours), None);
    }

    #[test]
    fn test_first_seen_with_single_event() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        // Record event 15 minutes ago
        let event_time = start - chrono::Duration::minutes(15);
        counter.record_at(1, event_time).unwrap();

        // Both first_seen and last_seen should return the same bucket
        let first_result = counter.first_seen_in(TimeUnit::Minutes);
        let last_result = counter.last_seen_in(TimeUnit::Minutes);
        assert_eq!(first_result, Some(15));
        assert_eq!(last_result, Some(15));
    }

    #[test]
    fn test_first_seen_with_current_bucket() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(60, TimeUnit::Minutes)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 10, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        // Record event in current bucket
        counter.record(1);

        // first_seen should return bucket 0 (current)
        let result = counter.first_seen_in(TimeUnit::Minutes);
        assert_eq!(result, Some(0));
    }

    #[test]
    fn test_first_last_seen_in_worked_example() -> Result<()> {
        // Verify: Converting Days(10) to Days(15) preserves total event count
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 12, 30, 0).unwrap();
        let start = synchronized_start(now);
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
            IntervalConfig::new_unchecked(28, TimeUnit::Days),
        ]);
        let mut source = SingleEventCounter::new(&source_config, start);
        source.advance_if_needed(now);

        source.record_at(5, now - Duration::hours(24))?;
        source.record_at(4, now - Duration::minutes(90))?;
        source.record_at(3, now - Duration::minutes(58))?;
        source.record_at(2, now - Duration::minutes(45))?;
        source.record_at(1, now)?;

        let total = source.total_events();
        assert_eq!(
            total,
            5 + 4 + 3 + 2 + 1,
            "Conversion must have actually correct count"
        );

        assert_eq!(source.last_seen_in(TimeUnit::Days), Some(0)); // today
        assert_eq!(source.last_seen_in(TimeUnit::Hours), Some(0)); // 12pm - 1pm today
        assert_eq!(source.last_seen_in(TimeUnit::Minutes), Some(0)); // 12:30pm - 12:31pm.

        assert_eq!(source.first_seen_in(TimeUnit::Days), Some(1)); // yesterday
        assert_eq!(source.first_seen_in(TimeUnit::Hours), Some(23)); // 24 hours ago (now visible with fix!)
        assert_eq!(source.first_seen_in(TimeUnit::Minutes), Some(58)); // 11:31am - 11:32pm

        Ok(())
    }

    #[test]
    fn test_different_bucket_counts_per_interval() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let counter = SingleEventCounter::new(&config, start);

        // Verify each interval has its configured bucket count
        let minutes_counter = counter.intervals.get(&TimeUnit::Minutes).unwrap();
        assert_eq!(
            minutes_counter.sum_range(0, 60),
            0 // Empty but can query 60 buckets
        );

        let hours_counter = counter.intervals.get(&TimeUnit::Hours).unwrap();
        assert_eq!(hours_counter.sum_range(0, 24), 0);

        let days_counter = counter.intervals.get(&TimeUnit::Days).unwrap();
        assert_eq!(days_counter.sum_range(0, 7), 0);
    }

    #[test]
    fn test_integration_record_once_query_at_different_granularities() {
        let config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(60, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
        ]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 12, 0, 0).unwrap();
        let mut counter = SingleEventCounter::new(&config, start);

        counter.record(1);

        // All granularities should see the same event
        assert_eq!(counter.bucket_value(TimeUnit::Minutes, 0), 1);
        assert_eq!(counter.bucket_value(TimeUnit::Hours, 0), 1);
        assert_eq!(counter.bucket_value(TimeUnit::Days, 0), 1);

        // Query multiple buckets
        assert_eq!(counter.sum_range(TimeUnit::Minutes, 0..60), Some(1));
        assert_eq!(counter.sum_range(TimeUnit::Hours, 0..24), Some(1));
        assert_eq!(counter.sum_range(TimeUnit::Days, 0..7), Some(1));
    }

    #[test]
    fn test_merge_combines_counts() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config, start);
        counter1.record(3);

        let mut counter2 = SingleEventCounter::new(&config, start);
        counter2.record(5);

        counter1.merge(counter2).unwrap();

        // Should have 3 + 5 = 8
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 8);
    }

    #[test]
    fn test_merge_is_commutative() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter_a1 = SingleEventCounter::new(&config, start);
        counter_a1.record(3);

        let mut counter_b1 = SingleEventCounter::new(&config, start);
        counter_b1.record(5);

        let mut counter_a2 = SingleEventCounter::new(&config, start);
        counter_a2.record(3);

        let mut counter_b2 = SingleEventCounter::new(&config, start);
        counter_b2.record(5);

        // a + b
        counter_a1.merge(counter_b1).unwrap();

        // b + a
        counter_b2.merge(counter_a2).unwrap();

        // Both should equal 8
        assert_eq!(counter_a1.bucket_value(TimeUnit::Days, 0), 8);
        assert_eq!(counter_b2.bucket_value(TimeUnit::Days, 0), 8);
    }

    #[test]
    fn test_merge_is_associative() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter_a1 = SingleEventCounter::new(&config, start);
        counter_a1.record(3);

        let mut counter_b1 = SingleEventCounter::new(&config, start);
        counter_b1.record(5);

        let mut counter_c1 = SingleEventCounter::new(&config, start);
        counter_c1.record(7);

        let mut counter_a2 = SingleEventCounter::new(&config, start);
        counter_a2.record(3);

        let mut counter_b2 = SingleEventCounter::new(&config, start);
        counter_b2.record(5);

        let mut counter_c2 = SingleEventCounter::new(&config, start);
        counter_c2.record(7);

        // (a + b) + c
        counter_a1.merge(counter_b1).unwrap();
        counter_a1.merge(counter_c1).unwrap();

        // a + (b + c)
        counter_b2.merge(counter_c2).unwrap();
        counter_a2.merge(counter_b2).unwrap();

        // Both should equal 15
        assert_eq!(counter_a1.bucket_value(TimeUnit::Days, 0), 15);
        assert_eq!(counter_a2.bucket_value(TimeUnit::Days, 0), 15);
    }

    #[test]
    fn test_merge_handles_alignment_when_starting_instant_differs() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let start1 = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let start2 = Utc.with_ymd_and_hms(2025, 1, 2, 0, 0, 0).unwrap(); // 1 day later

        let mut counter1 = SingleEventCounter::new(&config, start1);
        counter1.record(3);

        let mut counter2 = SingleEventCounter::new(&config, start2);
        counter2.record(5);

        counter1.merge(counter2).unwrap();

        // After merge, counter1 should have most recent starting_instant (start2)
        assert_eq!(counter1.starting_instant(), start2);

        // counter1's 3 events should be in bucket 1 (1 day ago)
        // counter2's 5 events should be in bucket 0 (today)
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 5);
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 1), 3);
    }

    #[test]
    fn test_merge_preserves_most_recent_starting_instant() {
        let config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let start1 = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let start2 = Utc.with_ymd_and_hms(2025, 1, 3, 0, 0, 0).unwrap(); // 2 days later

        let mut counter1 = SingleEventCounter::new(&config, start1);
        counter1.record(10);

        let counter2 = SingleEventCounter::new(&config, start2);

        counter1.merge(counter2).unwrap();

        // Should preserve the most recent starting_instant
        assert_eq!(counter1.starting_instant(), start2);
    }

    #[test]
    fn test_merge_with_different_time_units_converts_config() {
        // Counter 1 tracks Days + Weeks
        let config1 = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
            IntervalConfig::new_unchecked(4, TimeUnit::Weeks),
        ]);

        // Counter 2 tracks Days + Hours (different!)
        let config2 = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config1, start);
        counter1.record(10);

        let mut counter2 = SingleEventCounter::new(&config2, start);
        counter2.record(5);

        // Merging counters with different configs should now succeed via conversion
        let result = counter1.merge(counter2);
        assert!(result.is_ok(), "Merge should succeed by converting config");

        // Counter1 should preserve its time units (Days + Weeks)
        // Counter2's 5 events were recorded in both Hours and Days of counter2
        // When converted to Days+Weeks, those 5 events appear in both Days and Weeks
        // So both intervals should sum to 15 (10 from counter1 + 5 from counter2)
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 15);
        assert_eq!(counter1.bucket_value(TimeUnit::Weeks, 0), 15); // counter1(10) + counter2(5)
    }

    #[test]
    fn test_merge_with_subset_configs_converts() {
        // Counter 1 tracks Days + Weeks + Months
        let config1 = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
            IntervalConfig::new_unchecked(4, TimeUnit::Weeks),
            IntervalConfig::new_unchecked(12, TimeUnit::Months),
        ]);

        // Counter 2 tracks only Days (subset!)
        let config2 =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config1, start);
        counter1.record(10);

        let mut counter2 = SingleEventCounter::new(&config2, start);
        counter2.record(5);

        // Merging counters with different configs should now succeed via conversion
        let result = counter1.merge(counter2);
        assert!(result.is_ok(), "Merge should succeed by converting config");

        // Counter1 keeps all its time units
        // Counter2's 5 events were recorded in Days of counter2
        // When converted to Days+Weeks+Months, those 5 events appear in all intervals
        // So all intervals should sum to 15 (10 from counter1 + 5 from counter2)
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 15);
        assert_eq!(counter1.bucket_value(TimeUnit::Weeks, 0), 15); // counter1(10) + counter2(5)
        assert_eq!(counter1.bucket_value(TimeUnit::Months, 0), 15); // counter1(10) + counter2(5)
    }

    #[test]
    fn test_merge_converts_different_bucket_counts() {
        // With config conversion, merge now handles different bucket counts
        // by converting other counter to match self's bucket count

        // Counter 1 has 7 buckets (tracks 7 days)
        let config1 =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);

        // Counter 2 has 14 buckets (tracks 14 days)
        let config2 =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(14, TimeUnit::Days)]);

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config1, start);
        counter1.record(10);

        let mut counter2 = SingleEventCounter::new(&config2, start);
        counter2.record(5);

        // Merge should now succeed via config conversion
        let result = counter1.merge(counter2);

        assert!(
            result.is_ok(),
            "Merge should succeed by converting bucket counts"
        );

        // Data should be merged correctly
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 15);
    }

    #[test]
    fn test_merge_with_same_time_units_but_different_bucket_counts() {
        // Counter 1 tracks Days with 7 buckets
        let config1 =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);

        // Counter 2 tracks Days with 14 buckets (different!)
        let config2 =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(14, TimeUnit::Days)]);

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config1, start);
        counter1.record(10);

        let mut counter2 = SingleEventCounter::new(&config2, start);
        counter2.record(5);

        // With config conversion: merge now converts and succeeds
        let result = counter1.merge(counter2);
        assert!(
            result.is_ok(),
            "Merge should succeed by converting bucket counts"
        );

        // Data should be merged correctly
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 15);
    }

    #[test]
    fn test_merge_with_multiple_time_units_and_different_bucket_counts() {
        // Counter 1 tracks Days (7 buckets) + Hours (24 buckets)
        let config1 = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);

        // Counter 2 tracks Days (14 buckets) + Hours (48 buckets) - different bucket counts!
        let config2 = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(14, TimeUnit::Days),
            IntervalConfig::new_unchecked(48, TimeUnit::Hours),
        ]);

        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();

        let mut counter1 = SingleEventCounter::new(&config1, start);
        counter1.record(10);

        let mut counter2 = SingleEventCounter::new(&config2, start);
        counter2.record(5);

        // With config conversion: merge now converts and succeeds
        let result = counter1.merge(counter2);
        assert!(
            result.is_ok(),
            "Merge should succeed by converting bucket counts"
        );

        // Data should be merged correctly for both time units
        assert_eq!(counter1.bucket_value(TimeUnit::Days, 0), 15);
        assert_eq!(counter1.bucket_value(TimeUnit::Hours, 0), 15);
    }
}