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
//! Configuration conversion tests.
//!
//! Tests that data can be correctly converted between different EventStore
//! configurations via export/import, including bucket count changes and
//! time unit changes.

use chrono::{Duration, TimeZone, Utc};
use proptest::prelude::*;
use std::sync::Arc;
use tiny_counter::{EventStore, TestClock, TimeUnit};

// Helper to create a store with specific configuration and optional clock
fn create_store(
    bucket_count: usize,
    time_unit: TimeUnit,
    clock: Option<Arc<dyn tiny_counter::Clock>>,
) -> EventStore {
    let mut builder = EventStore::builder();

    builder = match time_unit {
        TimeUnit::Seconds => builder.track_seconds(bucket_count),
        TimeUnit::Minutes => builder.track_minutes(bucket_count),
        TimeUnit::Hours => builder.track_hours(bucket_count),
        TimeUnit::Days => builder.track_days(bucket_count),
        TimeUnit::Weeks => builder.track_weeks(bucket_count),
        TimeUnit::Months => builder.track_months(bucket_count),
        TimeUnit::Years => builder.track_years(bucket_count),
        TimeUnit::Ever => builder.track_days(bucket_count),
    };

    if let Some(clock) = clock {
        builder = builder.with_clock(clock);
    }

    builder.build().unwrap()
}

// Helper to record events at specific times
fn record_events_at_times(store: &EventStore, event_id: &str, events: Vec<(u32, i64)>) {
    let now = Utc::now();
    for (count, seconds_ago) in events {
        if count == 0 {
            continue;
        }
        let timestamp = now - Duration::seconds(seconds_ago);
        let _ = store.record_count_at(event_id, count, timestamp);
    }
}

// ============================================================================
// Basic Configuration Conversion
// ============================================================================

#[test]
fn convert_hours_to_days() {
    // Source: 72 hour buckets (3 days)
    let source = EventStore::builder().track_hours(72).build().unwrap();

    source.record_count("event", 1000);

    let source_sum = source.query("event").last_hours(72).sum().unwrap();

    // Export and import to days
    let exported = source.export_all().unwrap();

    let target = EventStore::builder().track_days(7).build().unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_days(7).sum().unwrap_or(0);

    // Data should be preserved or lost due to config differences, but never increased
    assert!(target_sum <= source_sum);
}

#[test]
fn convert_days_to_hours() {
    // Source: 7 day buckets
    let source = EventStore::builder().track_days(7).build().unwrap();

    source.record_count("event", 500);

    let source_sum = source.query("event").last_days(7).sum().unwrap();

    // Export and import to hours
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_hours(168) // 7 days worth
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_hours(168).sum().unwrap_or(0);

    // Data should be preserved or lost, but never increased
    assert!(target_sum <= source_sum);
}

#[test]
fn convert_with_bucket_count_increase() {
    // Source: 10 buckets
    let source = EventStore::builder().track_hours(10).build().unwrap();

    source.record_count("event", 200);

    // Export and import to more buckets
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_hours(50) // More granularity
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    // Sum should be preserved
    let source_sum = source.query("event").last_hours(10).sum().unwrap();
    let target_sum = target.query("event").last_hours(50).sum().unwrap();

    assert_eq!(source_sum, target_sum);
}

#[test]
fn convert_with_bucket_count_decrease() {
    let fixed_time = Utc::now();
    let clock = TestClock::build_for_testing_at(fixed_time);

    // Source: 50 hour buckets
    let source = EventStore::builder()
        .track_hours(50)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Spread events across time
    for i in 0..10 {
        source.record_ago("event", Duration::hours(i * 2));
    }

    let source_sum_20h = source.query("event").last_hours(20).sum().unwrap();

    // Export and import to fewer buckets
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_hours(20)
        .with_clock(Arc::new(clock))
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_hours(20).sum().unwrap();

    // Data within target window should be preserved
    assert_eq!(source_sum_20h, target_sum);
}

// ============================================================================
// Round-Trip Conversion
// ============================================================================

#[test]
fn round_trip_hours_to_days_to_hours() {
    let source = EventStore::builder().track_hours(24).build().unwrap();

    source.record_count("event", 100);

    let initial_sum = source.query("event").last_hours(24).sum().unwrap();

    // A -> B (hours to days)
    let exported_a = source.export_all().unwrap();
    let store_b = EventStore::builder().track_days(7).build().unwrap();
    store_b.import_all(exported_a).unwrap();

    // B -> A2 (days back to hours)
    let exported_b = store_b.export_all().unwrap();
    let store_a2 = EventStore::builder().track_hours(24).build().unwrap();
    store_a2.import_all(exported_b).unwrap();

    let final_sum = store_a2.query("event").last_hours(24).sum().unwrap();

    // Round trip should preserve data
    assert_eq!(initial_sum, final_sum);
}

#[test]
fn convert_days_to_hours_before_midnight() {
    // Fixed time: Dec 31, 2024 23:00:00 (before year boundary)
    let clock = TestClock::new_at(Utc.with_ymd_and_hms(2024, 12, 31, 23, 0, 0).unwrap());

    // Source: 7 day buckets
    let source = EventStore::builder()
        .track_days(7)
        .with_clock(clock.clone())
        .build()
        .unwrap();

    source.record_count("event", 500);

    let source_sum = source.query("event").last_days(7).sum().unwrap();

    // Export and import to hours
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_hours(168) // 7 days worth
        .with_clock(clock)
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_hours(168).sum().unwrap_or(0);

    // Data should be preserved or lost, but never increased
    assert!(target_sum <= source_sum);
}

#[test]
fn convert_days_to_hours_after_midnight() {
    // Fixed time: Jan 1, 2025 01:00:00 (after year boundary)
    let clock = TestClock::new_at(Utc.with_ymd_and_hms(2025, 1, 1, 1, 0, 0).unwrap());

    // Source: 7 day buckets
    let source = EventStore::builder()
        .track_days(7)
        .with_clock(clock.clone())
        .build()
        .unwrap();

    source.record_count("event", 500);

    let source_sum = source.query("event").last_days(7).sum().unwrap();

    // Export and import to hours
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_hours(168) // 7 days worth
        .with_clock(clock)
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_hours(168).sum().unwrap_or(0);

    // Data should be preserved or lost, but never increased
    assert!(target_sum <= source_sum);
}

#[test]
fn round_trip_hours_to_days_to_hours_before_midnight() {
    // Fixed time: Dec 31, 2024 23:00:00 (before year boundary)
    let clock = TestClock::new_at(Utc.with_ymd_and_hms(2024, 12, 31, 23, 0, 0).unwrap());

    let source = EventStore::builder()
        .track_hours(24)
        .with_clock(clock.clone())
        .build()
        .unwrap();

    source.record_count("event", 100);

    let initial_sum = source.query("event").last_hours(24).sum().unwrap();

    // A -> B (hours to days)
    let exported_a = source.export_all().unwrap();
    let store_b = EventStore::builder()
        .track_days(7)
        .with_clock(clock.clone())
        .build()
        .unwrap();
    store_b.import_all(exported_a).unwrap();

    // B -> A2 (days back to hours)
    let exported_b = store_b.export_all().unwrap();
    let store_a2 = EventStore::builder()
        .track_hours(24)
        .with_clock(clock)
        .build()
        .unwrap();
    store_a2.import_all(exported_b).unwrap();

    let final_sum = store_a2.query("event").last_hours(24).sum().unwrap();

    // Round trip should preserve data
    assert_eq!(initial_sum, final_sum);
}

#[test]
fn round_trip_hours_to_days_to_hours_after_midnight() {
    // Fixed time: Jan 1, 2025 01:00:00 (after year boundary)
    let clock = TestClock::new_at(Utc.with_ymd_and_hms(2025, 1, 1, 1, 0, 0).unwrap());

    let source = EventStore::builder()
        .track_hours(24)
        .with_clock(clock.clone())
        .build()
        .unwrap();

    source.record_count("event", 100);

    let initial_sum = source.query("event").last_hours(24).sum().unwrap();

    // A -> B (hours to days)
    let exported_a = source.export_all().unwrap();
    let store_b = EventStore::builder()
        .track_days(7)
        .with_clock(clock.clone())
        .build()
        .unwrap();
    store_b.import_all(exported_a).unwrap();

    // B -> A2 (days back to hours)
    let exported_b = store_b.export_all().unwrap();
    let store_a2 = EventStore::builder()
        .track_hours(24)
        .with_clock(clock)
        .build()
        .unwrap();
    store_a2.import_all(exported_b).unwrap();

    let final_sum = store_a2.query("event").last_hours(24).sum().unwrap();

    // Round trip should preserve data
    assert_eq!(initial_sum, final_sum);
}

#[test]
fn round_trip_with_different_bucket_counts() {
    let source = EventStore::builder().track_days(10).build().unwrap();

    source.record_count("event", 250);

    let initial_sum = source.query("event").last_days(10).sum().unwrap();

    // A -> B (10 days to 30 days)
    let exported_a = source.export_all().unwrap();
    let store_b = EventStore::builder().track_days(30).build().unwrap();
    store_b.import_all(exported_a).unwrap();

    // B -> A2 (30 days back to 10 days)
    let exported_b = store_b.export_all().unwrap();
    let store_a2 = EventStore::builder().track_days(10).build().unwrap();
    store_a2.import_all(exported_b).unwrap();

    let final_sum = store_a2.query("event").last_days(10).sum().unwrap();

    assert_eq!(initial_sum, final_sum);
}

// ============================================================================
// Conversion Preserves First Seen
// ============================================================================

#[test]
fn conversion_preserves_first_seen() {
    let fixed_time = Utc::now();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let source = EventStore::builder()
        .track_hours(72)
        .track_days(7)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Old event
    source.record_ago("event", Duration::days(2));
    // Recent event
    source.record("event");

    let source_first = source.query("event").first_seen().unwrap();

    // Convert to different config
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_days(14)
        .track_weeks(4)
        .with_clock(Arc::new(clock))
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_first = target.query("event").first_seen().unwrap();

    // first_seen should be approximately preserved (within coarser bucket resolution)
    // When converting configs, bucket midpoint estimates can vary significantly
    let diff_hours = (source_first.num_hours() - target_first.num_hours()).abs();
    assert!(diff_hours <= 48); // Within 2 day tolerance for config conversion
}

// ============================================================================
// Property-Based Conversion Tests
// ============================================================================

// Strategy for generating TimeUnit (excluding Ever)
fn time_unit_strategy() -> impl Strategy<Value = TimeUnit> {
    prop_oneof![
        Just(TimeUnit::Minutes),
        Just(TimeUnit::Hours),
        Just(TimeUnit::Days),
        Just(TimeUnit::Weeks),
        Just(TimeUnit::Months),
    ]
}

// Strategy for testing at different times of day (half past each hour)
fn hour_of_day_strategy() -> impl Strategy<Value = u32> {
    (0u32..24).boxed()
}

proptest! {
    /// Converting A→B→A preserves total counts (within window)
    #[test]
    fn conversion_round_trip_preserves_counts(
        bucket_count_a in 5usize..20,
        bucket_count_b in 5usize..20,
        time_unit in time_unit_strategy(),
        event_count in 1u32..100,
        hour in hour_of_day_strategy(),
    ) {
        // Create clock at half past the given hour on Jan 1, 2025
        let time = Utc.with_ymd_and_hms(2025, 1, 1, hour, 30, 0).unwrap();
        let clock1 = TestClock::new_at(time);
        let clock2 = TestClock::new_at(time);
        let clock3 = TestClock::new_at(time);

        // Create store A with event
        let store_a = create_store(bucket_count_a, time_unit, Some(clock1));
        store_a.record_count("test_event", event_count);

        // Get initial count
        let initial_sum = store_a
            .query("test_event")
            .last_minutes(1)
            .sum()
            .unwrap_or(0);

        // Export from A
        let exported_a = store_a.export_all().unwrap();

        // Import into B (conversion A→B)
        let store_b = create_store(bucket_count_b, time_unit, Some(clock2));
        store_b.import_all(exported_a).unwrap();

        // Re-export from B
        let exported_b = store_b.export_all().unwrap();

        // Import back into A2 (conversion B→A)
        let store_a2 = create_store(bucket_count_a, time_unit, Some(clock3));
        store_a2.import_all(exported_b).unwrap();

        // Get final count
        let final_sum = store_a2
            .query("test_event")
            .last_minutes(1)
            .sum()
            .unwrap_or(0);

        // Should preserve counts within the window (or only lose due to window limits)
        prop_assert!(final_sum <= initial_sum);
        prop_assert!(final_sum == 0 || final_sum == initial_sum); // Either preserved or lost
    }

    /// Sum is preserved or only loses old data (never creates data)
    #[test]
    fn conversion_preserves_or_loses_old_data(
        source_buckets in 5usize..15,
        target_buckets in 5usize..15,
        time_unit in time_unit_strategy(),
        events in prop::collection::vec(1u32..50, 1..10),
        hour in hour_of_day_strategy(),
    ) {
        // Create clock at half past the given hour on Jan 1, 2025
        let time = Utc.with_ymd_and_hms(2025, 1, 1, hour, 30, 0).unwrap();
        let clock1 = TestClock::new_at(time);
        let clock2 = TestClock::new_at(time);

        // Create source store with multiple events at different times
        let source_store = create_store(source_buckets, time_unit, Some(clock1));
        let event_data: Vec<_> = events
            .iter()
            .enumerate()
            .map(|(i, &count)| (count, (i as i64) * 60)) // Events every minute
            .collect();
        record_events_at_times(&source_store, "test", event_data);

        // Get source sum (query the smallest time window that makes sense)
        let source_sum = source_store
            .query("test")
            .last_minutes(60)
            .sum()
            .unwrap_or(0);

        // Export and import (triggers conversion)
        let exported = source_store.export_all().unwrap();
        let target_store = create_store(target_buckets, time_unit, Some(clock2));
        target_store.import_all(exported).unwrap();

        // Get target sum (use same query window)
        let target_sum = target_store
            .query("test")
            .last_minutes(60)
            .sum()
            .unwrap_or(0);

        // Sum should be preserved or only lose old data (if target has fewer buckets)
        prop_assert!(
            target_sum <= source_sum,
            "Conversion should not create events: source={}, target={}",
            source_sum,
            target_sum
        );
    }

    /// Conversion is deterministic (same input → same output)
    #[test]
    fn conversion_is_deterministic(
        bucket_count in 5usize..20,
        time_unit in time_unit_strategy(),
        event_count in 1u32..100,
        hour in hour_of_day_strategy(),
    ) {
        // Create clock at half past the given hour on Jan 1, 2025
        let time = Utc.with_ymd_and_hms(2025, 1, 1, hour, 30, 0).unwrap();
        let clock1 = TestClock::new_at(time);
        let clock2 = TestClock::new_at(time);

        // Create two identical stores
        let store1 = create_store(bucket_count, time_unit, Some(clock1));
        store1.record_count("test", event_count);

        let store2 = create_store(bucket_count, time_unit, Some(clock2));
        store2.record_count("test", event_count);

        // Query both
        let sum1 = store1.query("test").last_minutes(1).sum();
        let sum2 = store2.query("test").last_minutes(1).sum();

        // Should be identical (deterministic)
        prop_assert_eq!(sum1, sum2);
    }

}

// ============================================================================
// Edge Cases in Conversion
// ============================================================================

#[test]
fn convert_with_data_loss_outside_window() {
    let fixed_time = Utc::now();
    let clock = TestClock::build_for_testing_at(fixed_time);

    // Source: track 30 days
    let source = EventStore::builder()
        .track_days(30)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Old event (20 days ago)
    source.record_ago("event", Duration::days(20));
    // Recent event (2 days ago)
    source.record_ago("event", Duration::days(2));

    let source_all = source.query("event").last_days(30).sum().unwrap();
    assert_eq!(source_all, 2);

    // Target: only track 7 days (will lose 20-day-old event)
    let exported = source.export_all().unwrap();

    let target = EventStore::builder()
        .track_days(7)
        .with_clock(Arc::new(clock))
        .build()
        .unwrap();

    target.import_all(exported).unwrap();

    let target_sum = target.query("event").last_days(7).sum().unwrap();

    // Should only have the recent event (within 7 day window)
    assert_eq!(target_sum, 1);
}

#[test]
fn convert_empty_store() {
    let source = EventStore::builder().track_hours(24).build().unwrap();

    let exported = source.export_all().unwrap();
    assert_eq!(exported.len(), 0);

    let target = EventStore::builder().track_days(7).build().unwrap();

    target.import_all(exported).unwrap();

    // Should still be empty
    assert_eq!(target.query("any").last_days(7).sum(), None);
}