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
/// Config conversion for merge operations.
///
/// This module handles converting SingleEventCounter configurations to enable
/// merging counters with different time units or bucket counts.
use chrono::{DateTime, Utc};

use crate::{
    sync_time::synchronized_start, Error, EventCounterConfig, IntervalConfig, IntervalCounter,
    SingleEventCounter,
};

/// Converts a counter to match the target configuration, preserving all events.
///
/// Events are recorded at bucket midpoints. Gap events (present in larger intervals
/// but not smaller ones) are detected by tracking expected counts and preserved.
pub fn convert_if_needed(
    source: SingleEventCounter,
    target_config: &EventCounterConfig,
) -> SingleEventCounter {
    let source_config = source.as_counter_config();
    if &source_config == target_config {
        return source;
    }
    convert(source, &source_config, target_config)
}

fn convert(
    source: SingleEventCounter,
    source_config: &EventCounterConfig,
    target_config: &EventCounterConfig,
) -> SingleEventCounter {
    let now = source.starting_instant();
    let starting_instant = synchronized_start(now);
    let mut target = target_config.create_counter(starting_instant);
    target.advance_if_needed(now);

    replay_into(source_config, &source, &mut target);

    target
}

pub fn replay(source: &SingleEventCounter, target: &mut SingleEventCounter) {
    replay_into(&source.as_counter_config(), source, target);
}

fn replay_into(
    source_config: &EventCounterConfig,
    source: &SingleEventCounter,
    target: &mut SingleEventCounter,
) {
    let configs = source_config.configs();
    let intervals = source.intervals();

    if configs.is_empty() {
        return;
    }

    let mut start_bucket: usize = 0;

    for interval_idx in 0..configs.len() {
        let config = &configs[interval_idx];

        let interval = &intervals[&config.time_unit()];

        let mut checksum = if let Some(next_config) = configs.get(interval_idx + 1) {
            let next_interval = &intervals[&next_config.time_unit()];
            Some(Checksum::new(config, interval, next_config, next_interval))
        } else {
            None
        };

        // Expected is the events in the next interval if an only if it's disjoint from this one.
        transfer_buckets(config, interval, start_bucket, &mut checksum, target);

        if let Some(checksum) = checksum {
            // Record the events that fell in the gap between the end of this
            // interval (buckets * bucket duration) and the end of the first bucket in the next interval.
            start_bucket = checksum.last_bucket + 1;
            record_gaps(config, interval, checksum, target);
        }
    }
}

struct Checksum<'a> {
    pub(crate) buckets: IntervalCounter,

    pub(crate) last_bucket: usize,
    next_config: &'a IntervalConfig,
    pub(crate) next_interval: &'a IntervalCounter,
}

impl<'a> Checksum<'a> {
    fn new(
        this_config: &IntervalConfig,
        this_interval: &'a IntervalCounter,
        next_config: &'a IntervalConfig,
        next_interval: &'a IntervalCounter,
    ) -> Self {
        let now = this_config.first_moment_ever(this_interval.interval_start());

        let last_bucket = next_config
            .time_unit()
            .bucket_idx(next_interval.interval_start(), now)
            .unwrap_or_default();
        let buckets = IntervalCounter::new(last_bucket + 1, next_interval.interval_start());
        Self {
            buckets,

            last_bucket,
            next_config,
            next_interval,
        }
    }

    fn next_interval_start(&self) -> DateTime<Utc> {
        self.next_interval.interval_start()
    }

    fn record_at(&mut self, count: u32, time: DateTime<Utc>) {
        let _ = self
            .buckets
            .increment_at(count, time, &self.next_config.time_unit());
    }
}

/// Transfers buckets from source to target, returning expected counts for next interval.
fn transfer_buckets(
    config: &IntervalConfig,
    interval: &IntervalCounter,
    start_bucket: usize,
    checksum: &mut Option<Checksum<'_>>,
    target: &mut SingleEventCounter,
) {
    let interval_start = interval.interval_start();
    let starting_instant = target.starting_instant();
    let time_unit = config.time_unit();
    for bucket_idx in 0..config.bucket_count() {
        let count = match interval.bucket_value(bucket_idx) {
            Some(c) if c > 0 => c,
            _ => continue,
        };
        let bucket_time = time_unit.bucket_time(starting_instant, interval_start, bucket_idx);
        if let Some(checksum) = checksum {
            checksum.record_at(count, bucket_time);
        }
        if bucket_idx >= start_bucket {
            target
                .record_at(count, bucket_time)
                .expect("Recording in the future");
        }
    }
}

/// Records gap events: counts in larger interval exceeding expected from smaller interval.
/// For example, 45 * minutes, then mapping onto hour buckets.
/// An event recorded 50 minutes ago would be in the hour bucket, but not in the minutes.
fn record_gaps(
    config: &IntervalConfig,
    interval: &IntervalCounter,
    checksum: Checksum<'_>,
    target: &mut SingleEventCounter,
) {
    let next_interval = checksum.next_interval;
    let next = checksum.next_config;
    let now = checksum.next_interval_start();

    let interval_start = interval.interval_start();

    // Only one bucket can have a gap: the last bucket that the current interval touches.
    // This is the bucket at index mapped_to_larger, which straddles the boundary.
    // All other buckets are either fully covered (and transferred directly) or
    // fully outside the current interval's range (no gap, just uncovered events).
    let bucket_idx = checksum.last_bucket;
    let calculated = checksum.buckets.bucket_value(bucket_idx).unwrap_or(0);
    let actual = match next_interval.bucket_value(bucket_idx) {
        Some(count) => count,
        None => return,
    };
    if actual <= calculated {
        return;
    }

    let difference = actual - calculated;

    // The time where the entire smaller bucket (e.g. 45 minutes ago) ends
    let prev_coverage = config.first_moment_ever(interval_start);
    // The time when the bucket in the hour long bucket stops?/starts?, e.g. 60 minutes ago.
    let bucket_end = next.time_unit().bucket_end(now, bucket_idx);

    let gap_middle = prev_coverage.signed_duration_since(bucket_end) / 2;

    let timestamp = prev_coverage - gap_middle;
    if let Err(Error::FutureEvent) = target.record_at(difference, timestamp) {
        let _ = target.record_at(difference, now);
    }
}

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

    use super::*;

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

    impl EventCounterConfig {
        fn single(bucket_count: usize, time_unit: TimeUnit) -> Self {
            Self::new(vec![IntervalConfig::new_unchecked(bucket_count, time_unit)])
        }

        fn two(
            bucket_count1: usize,
            time_unit1: TimeUnit,
            bucket_count2: usize,
            time_unit2: TimeUnit,
        ) -> Self {
            Self::new(vec![
                IntervalConfig::new_unchecked(bucket_count1, time_unit1),
                IntervalConfig::new_unchecked(bucket_count2, time_unit2),
            ])
        }
    }

    impl SingleEventCounter {
        /// Test helper: Increments a specific bucket for a time unit.
        pub(crate) fn increment_bucket(
            &mut self,
            time_unit: TimeUnit,
            bucket_idx: usize,
            count: u32,
        ) {
            self.interval_mut(time_unit)
                .unwrap()
                .increment_bucket(bucket_idx, count);
        }
    }

    #[test]
    fn test_conversion_preserves_starting_instant() {
        // Verify: Starting instant transfers to converted counter unchanged
        let start = Utc.with_ymd_and_hms(2025, 6, 15, 12, 30, 45).unwrap();
        let source_config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let source = SingleEventCounter::new(&source_config, start);

        let target_config = EventCounterConfig::single(14, TimeUnit::Days);
        let converted = convert(source, &source_config, &target_config);

        assert_eq!(converted.starting_instant(), start);
    }

    #[test]
    fn test_conversion_handles_gaps() -> Result<()> {
        // Verify: Event in gap between Minutes(30) and Hours(24) is preserved
        // Gap: 30-60 minutes is covered by Hours but not Minutes
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(30, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);

        let mut source = SingleEventCounter::new(&source_config, synchronized_start(now));
        source.advance_if_needed(now);

        // Simulate event at 45 minutes ago: in Hours bucket 0, but outside Minutes range
        source.record_at(10, now - Duration::minutes(45))?;

        let old_total = source.total_events();
        let target_config = EventCounterConfig::single(60, TimeUnit::Minutes);
        let mut converted = convert(source, &source_config, &target_config);

        assert_eq!(
            converted.total_events(),
            old_total,
            "Gap events must be preserved"
        );
        assert_eq!(
            converted.total_events(),
            10,
            "Converted counter should have data"
        );
        Ok(())
    }

    #[test]
    fn test_conversion_handles_gaps_offset() -> Result<()> {
        // Verify: Event in gap between Minutes(30) and Hours(24) is preserved
        // Gap: 30-60 minutes is covered by Hours but not Minutes
        let now = Utc.with_ymd_and_hms(2025, 1, 1, 0, 50, 0).unwrap();
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(30, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);

        let mut source = SingleEventCounter::new(&source_config, synchronized_start(now));
        source.advance_if_needed(now);

        // Simulate event at 45 minutes ago: in Hours bucket 0, but outside Minutes range
        source.record_at(10, now - Duration::minutes(45))?;

        let old_total = source.total_events();
        let target_config = EventCounterConfig::single(60, TimeUnit::Minutes);
        let mut converted = convert(source, &source_config, &target_config);

        assert_eq!(
            converted.total_events(),
            old_total,
            "Gap events must be preserved"
        );
        assert_eq!(
            converted.total_events(),
            10,
            "Converted counter should have data"
        );
        Ok(())
    }

    #[test]
    fn test_conversion_adds_missing_time_units() {
        let source_config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(7, TimeUnit::Days)]);
        let now = Utc.with_ymd_and_hms(2025, 12, 1, 12, 30, 0).unwrap();
        let start = synchronized_start(now);
        let mut source = SingleEventCounter::new(&source_config, start);
        source.advance_if_needed(now);

        source.increment_bucket(TimeUnit::Days, 0, 42);

        let target_config = EventCounterConfig::two(7, TimeUnit::Days, 24, TimeUnit::Hours);
        let converted = convert(source, &source_config, &target_config);

        // Check structure: both time units exist
        assert_eq!(converted.intervals().len(), 2);
        assert!(converted.has_time_unit(TimeUnit::Days));
        assert!(converted.has_time_unit(TimeUnit::Hours));

        // Check preservation: 42 events in both Days and Hours
        let days_total = converted.sum_for_unit(TimeUnit::Days);
        let hours_total = converted.sum_for_unit(TimeUnit::Hours);
        assert!(days_total > 0);
        assert_eq!(days_total, hours_total);
    }

    #[test]
    fn test_conversion_removes_extra_time_units() {
        // Verify: Converting Days(7) + Hours(24) to Days(7) removes Hours
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(7, TimeUnit::Days),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);
        let mut source = SingleEventCounter::new(&source_config, start);
        source.increment_bucket(TimeUnit::Days, 0, 10);
        source.increment_bucket(TimeUnit::Hours, 0, 10);

        let old_total = source.total_events();
        let target_config = EventCounterConfig::single(7, TimeUnit::Days);
        let mut converted = convert(source, &source_config, &target_config);

        // Check structure: only Days remains
        assert_eq!(converted.intervals().len(), 1);
        assert!(converted.has_time_unit(TimeUnit::Days));
        assert!(!converted.has_time_unit(TimeUnit::Hours));

        // Check preservation: total unchanged
        assert_eq!(converted.total_events(), old_total);
    }

    #[test]
    fn test_conversion_empty_counter() {
        // Verify: Empty Days(5) converts to Days(10) + Hours(24) with correct structure
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let source_config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(5, TimeUnit::Days)]);
        let source = SingleEventCounter::new(&source_config, start);

        let target_config = EventCounterConfig::two(10, TimeUnit::Days, 24, TimeUnit::Hours);
        let converted = convert(source, &source_config, &target_config);

        // Check structure: both time units with correct bucket counts
        assert_eq!(converted.intervals().len(), 2);
        assert_eq!(converted.bucket_count(TimeUnit::Days), 10);
        assert_eq!(converted.bucket_count(TimeUnit::Hours), 24);
    }

    #[test]
    fn test_conversion_handles_future_events_gracefully() {
        // Verify: Conversion handles FutureEvent errors from timestamp rounding
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let source_config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(10, TimeUnit::Days)]);
        let mut source = SingleEventCounter::new(&source_config, start);

        // Add event in bucket 0 (current day, may round to future)
        source.increment_bucket(TimeUnit::Days, 0, 100);

        let target_config = EventCounterConfig::single(20, TimeUnit::Days);
        let converted = convert(source, &source_config, &target_config);

        // Check no panic: conversion completes successfully
        assert_eq!(converted.intervals().len(), 1);
    }

    #[test]
    fn test_conversion_skips_events_too_old_for_target() {
        // Verify: Events outside target range are handled gracefully
        let start = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        let source_config =
            EventCounterConfig::new(vec![IntervalConfig::new_unchecked(365, TimeUnit::Days)]);
        let mut source = SingleEventCounter::new(&source_config, start);

        // Add event 300 days ago (too old for 7-day target)
        source.increment_bucket(TimeUnit::Days, 300, 50);

        let target_config = EventCounterConfig::single(7, TimeUnit::Days);
        let converted = convert(source, &source_config, &target_config);

        // Check no panic: conversion completes (old events dropped)
        assert_eq!(converted.intervals().len(), 1);
    }

    #[test]
    fn test_conversion_touching_bucket_intervals() -> Result<()> {
        // Verify: Converting Days(10) to Days(15) preserves total event count
        let now = Utc.with_ymd_and_hms(2025, 12, 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(1, now)?; // 12:30pm
        source.record_at(2, now - Duration::minutes(10))?; // 12:20am
        source.record_at(3, now - Duration::minutes(32))?; // 11:58am
        source.record_at(4, now - Duration::minutes(58))?; // 11:32am
        source.record_at(5, now - Duration::minutes(90))?; // 11:00am

        let old_total = source.total_events();
        assert_eq!(
            old_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::Hours), Some(1)); // 11am - 12pm today (we don't see yesterday)
        assert_eq!(source.first_seen_in(TimeUnit::Minutes), Some(58)); // 11:31am - 11:32pm

        let target_config = EventCounterConfig::single(360, TimeUnit::Minutes);
        let mut target = convert(source, &source_config, &target_config);

        let new_total = target.total_events();

        let counter = target
            .interval(TimeUnit::Minutes)
            .expect("Minutes are definitely here");
        assert_eq!(
            new_total, old_total,
            "Conversion must preserve total event count"
        );

        assert_eq!(
            counter.non_zero_idx(),
            vec![
                0,  // 12:30:30 pm
                9,  // 12:20:30 pm
                31, // 11:58:30 am
                57, // 11:32:30 am
                75, // 11:00:30 am (converted from Hours bucket 1 midpoint)
            ],
        );
        Ok(())
    }

    #[test]
    fn test_conversion_overlapping_bucket_intervals() -> Result<()> {
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(120, TimeUnit::Minutes), // 120 minutes is exactly
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),    // 2 hours
            IntervalConfig::new_unchecked(28, TimeUnit::Days),
        ]);
        let now = Utc.with_ymd_and_hms(2025, 12, 1, 12, 30, 0).unwrap();
        let start = synchronized_start(now);
        let mut source = SingleEventCounter::new(&source_config, start);
        source.advance_if_needed(now);

        source.record_at(1, now)?; // 12:30pm
        source.record_at(2, now - Duration::minutes(10))?; // 12:20am
        source.record_at(3, now - Duration::minutes(32))?; // 11:58am
        source.record_at(4, now - Duration::minutes(58))?; // 11:32am
        source.record_at(5, now - Duration::minutes(90))?; // 11:00am

        let old_total = source.total_events();
        assert_eq!(
            old_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::Hours), Some(1)); // 11am - 12pm today (we don't see yesterday)
        assert_eq!(source.first_seen_in(TimeUnit::Minutes), Some(90)); // 11:00am - 11:01pm

        let target_config = EventCounterConfig::single(360, TimeUnit::Minutes);
        let mut target = convert(source, &source_config, &target_config);

        let new_total = target.total_events();

        let counter = target
            .interval(TimeUnit::Minutes)
            .expect("Minutes are definitely here");
        assert_eq!(
            new_total, old_total,
            "Conversion must preserve total event count"
        );

        assert_eq!(
            counter.non_zero_idx(),
            vec![
                0,  // 12:30:30 pm
                9,  // 12:20:30 am
                31, // 11:58:30 am
                57, // 11:32:30 am
                89, // 11:00:30 am
            ],
        );
        Ok(())
    }

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

        source.record_at(1, now)?; // 11:59pm
        source.record_at(2, now - Duration::minutes(10))?; // 11:48am
        source.record_at(3, now - Duration::minutes(32))?; // 11:27am
        source.record_at(4, now - Duration::minutes(58))?; // 11:01am
        source.record_at(5, now - Duration::minutes(90))?; // 10:31am

        let old_total = source.total_events();
        assert_eq!(
            old_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:00pm - 12:01pm.

        assert_eq!(source.first_seen_in(TimeUnit::Hours), Some(1)); // 10am - 11pm today (we don't see yesterday)
        assert_eq!(source.first_seen_in(TimeUnit::Minutes), Some(32)); // 11:27pm - 11:28pm

        let target_config = EventCounterConfig::single(360, TimeUnit::Minutes);
        let mut target = convert(source, &source_config, &target_config);

        let new_total = target.total_events();

        let counter = target
            .interval(TimeUnit::Minutes)
            .expect("Minutes are definitely here");
        assert_eq!(
            new_total, old_total,
            "Conversion must preserve total event count"
        );

        assert_eq!(
            counter.non_zero_idx(),
            vec![
                0,  // 11:59:30 pm
                9,  // 11:49:30 am
                31, // 11:27:30 am
                52, // 11:07:30 am // gap-adjusted midpoint
                89, // 10:29:30 am
            ],
        );
        Ok(())
    }

    #[test]
    fn test_conversion_preserves_count_with_disjoint_intervals() -> Result<()> {
        // Verify: Converting with disjoint intervals (45min + 24hr) preserves total count
        // Gap: 45-60 minutes is covered by hours but not minutes
        let now = Utc.with_ymd_and_hms(2025, 12, 1, 12, 0, 0).unwrap();
        let start = synchronized_start(now);
        let source_config = EventCounterConfig::new(vec![
            IntervalConfig::new_unchecked(45, TimeUnit::Minutes),
            IntervalConfig::new_unchecked(24, TimeUnit::Hours),
        ]);
        let mut source = SingleEventCounter::new(&source_config, start);
        source.advance_if_needed(now);

        // Record events at various times
        source.record_at(5, now - Duration::minutes(10))?; // 10 min ago - in both intervals
        source.record_at(7, now - Duration::minutes(50))?; // 50 min ago - in gap (hours only)
        source.record_at(3, now - Duration::minutes(90))?; // 90 min ago - in hours only

        let source_total = source.total_events();
        // Conversion must preserve total event count
        assert_eq!(source_total, 5 + 7 + 3);

        let target_config = EventCounterConfig::single(180, TimeUnit::Minutes);
        let mut target = convert(source, &source_config, &target_config);

        // Conversion must preserve total event count
        assert_eq!(
            target.total_events(),
            source_total,
            "Conversion must preserve total event count"
        );

        Ok(())
    }
}