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
//! Edge cases for first_seen calculations.
//!
//! Tests the complex logic for estimating first_seen when events span
//! multiple interval configurations (e.g., hours + days) and fall at bucket boundaries.

use chrono::{DateTime, Duration, Local, TimeZone, Utc};
use std::sync::Arc;
use tiny_counter::{EventStore, TestClock};

// ============================================================================
// Test Helpers
// ============================================================================

/// Get the local timezone offset in hours for a given UTC timestamp.
/// This is used to calculate timezone-adjusted expected values in calendar tests.
/// Returns a float to handle fractional timezone offsets (e.g., UTC+5:30).
///
/// Note: Calendar tests use ±1h tolerance because:
/// 1. Tests may span DST transitions (e.g., looking back 18 months crosses multiple DST changes)
/// 2. Calendar boundaries (midnight, Monday, 1st of month) shift by 1 hour in UTC terms when DST changes
/// 3. The linear approximation (base_hours - offset * 1.0) doesn't account for historical DST transitions
fn local_offset_hours(utc_time: DateTime<Utc>) -> f64 {
    let offset_seconds = Local
        .timestamp_opt(utc_time.timestamp(), 0)
        .unwrap()
        .offset()
        .local_minus_utc();
    offset_seconds as f64 / 3600.0
}

// ============================================================================
// First Seen - Gap Detection Between Intervals
// ============================================================================

#[test]
fn first_seen_when_exactly_at_starting_bucket() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    // Configure so that hours can see 36 hours back, days can see 7 days back
    // The 36th hour bucket should be exactly at the boundary
    let store = EventStore::builder()
        .track_days(7)
        .track_hours(36)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Record event exactly at the boundary
    // This should be in starting_bucket (first bucket too old for hours to fully see)
    store.record("event");
    clock.advance(Duration::hours(36));
    store.record("event");

    let first = store.query("event").first_seen();

    // Event at 36 hours is at starting_bucket (edge of hours coverage)
    // Gap detection: age + (bucket_duration / 4) = 36 + 6 = 42 hours
    // This represents the midpoint estimate when transitioning between intervals
    let expected = Duration::hours(42);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact gap-adjusted midpoint: age + quarter_bucket"
    );
}

#[test]
fn first_seen_at_boundary_between_intervals() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 0, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    // Days track 10 days, hours track 48 hours (2 days)
    // So hours cannot see events from 3+ days ago
    let store = EventStore::builder()
        .track_days(10)
        .track_hours(48)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Record event 2 days ago (at the boundary of what hours can see)
    store.record_ago("event", Duration::hours(48));

    let first = store.query("event").first_seen();

    // Event at 48 hours is at boundary where hours(48) can barely see it
    // Falls into day bucket: age + (day_duration / 2) = 48 + 12 = 60 hours
    // After fix: 48 hours = 172800 seconds
    let expected = Duration::seconds(172800);

    assert_eq!(
        first,
        Some(expected),
        "Should return event_age + half_bucket_duration"
    );
}

#[test]
fn first_seen_with_event_at_starting_bucket_and_newer_events() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 12, 5, 12, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

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

    // Record an event that's exactly at the 24-hour boundary
    store.record_ago("event", Duration::hours(24));

    // Record another recent event
    store.record("event");

    let first = store.query("event").first_seen();

    // Older event at 24 hours is at starting_bucket (edge of hours(24) coverage)
    // Gap detection: age + (bucket_duration / 4) = 24 + 6 = 30 hours
    let expected = Duration::hours(30);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact gap-adjusted midpoint for oldest event"
    );
}

#[test]
fn first_seen_returns_correct_midpoint_at_boundary() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 12, 1, 0, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_days(5)
        .track_hours(72) // 3 days
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Record event at exactly 3 days ago (72 hours)
    // This is at the boundary where hours can no longer see it
    store.record_ago("event", Duration::hours(72));

    let first = store.query("event").first_seen();

    // Event at 72 hours is at the boundary where hours can no longer see it
    // Expected: midpoint of day 3 bucket = 72 hours + 12 hours = 84 hours
    // After fix: 72 hours = 259200 seconds
    let expected = Duration::seconds(259200);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact midpoint of day bucket at 72-hour boundary"
    );
}

// ============================================================================
// First Seen - Multiple Intervals
// ============================================================================

#[test]
#[cfg(not(feature = "calendar"))]
fn first_seen_across_three_intervals() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 1, 15, 10, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_hours(48)
        .track_days(30)
        .track_weeks(52)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Event from 5 weeks ago (outside hours and days, but in weeks)
    store.record_ago("event", Duration::weeks(5));

    let first = store.query("event").first_seen();

    // Event at 5 weeks (35 days) falls into week bucket
    // Gap detection between days(30) and weeks(52)
    // After fix: 2541600 seconds = 29.41 days
    let expected = Duration::seconds(2541600);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact calculated week bucket midpoint"
    );
}

#[test]
#[cfg(feature = "calendar")]
fn first_seen_across_three_intervals_calendar() {
    // Test with calendar-aligned weeks (Monday at midnight)
    // Jan 15, 2025 is a Wednesday
    let fixed_time = Utc.with_ymd_and_hms(2025, 1, 15, 10, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_hours(48)
        .track_days(30)
        .track_weeks(52)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Event from 5 weeks ago (outside hours and days, but in weeks)
    store.record_ago("event", Duration::weeks(5));

    let first = store.query("event").first_seen();
    assert!(first.is_some());

    // With calendar feature, weeks align on Monday at midnight in local time
    // Calculate expected value based on local timezone offset
    let offset = local_offset_hours(fixed_time);

    // Base value at UTC+0: 814 hours (empirically observed)
    // Timezone offset shifts the week boundary by approximately 1 hour per timezone hour
    // For positive offsets (east of UTC), week boundaries occur earlier in UTC time
    // For negative offsets (west of UTC), week boundaries occur later in UTC time
    // Using linear approximation: result varies by ~1h per timezone hour
    let expected_hours = 814.0 - offset * 1.0;

    let duration = first.unwrap();
    let hours = duration.num_hours();

    assert!(
        ((expected_hours - 1.0) as i64..=(expected_hours + 1.0) as i64).contains(&hours),
        "Expected ~{:.0} hours (±1h) based on UTC{:+.1} offset, got {} hours",
        expected_hours,
        offset,
        hours
    );
}

#[test]
fn first_seen_in_finest_granularity() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 1, 15, 14, 30, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_minutes(60)
        .track_hours(24)
        .track_days(7)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Recent event (within minutes interval)
    store.record_ago("event", Duration::minutes(10));

    let first = store.query("event").first_seen();

    // Event at 10 minutes falls into minute bucket
    // Midpoint calculation: 10 minutes + 0.5 minutes = 10.5 minutes = 630 seconds
    let expected = Duration::seconds(630);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact minute bucket midpoint: age + 0.5 minutes"
    );
}

// ============================================================================
// First Seen - Gap Scenarios
// ============================================================================

#[test]
fn first_seen_gap_between_minute_and_hour_intervals() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 1, 15, 16, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    // Minutes: 60 buckets (1 hour coverage)
    // Hours: 24 buckets (24 hour coverage)
    // Gap exists between 1 hour and 24 hours where only hour buckets exist
    let store = EventStore::builder()
        .track_minutes(60)
        .track_hours(24)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Event at 2 hours ago - beyond minutes, in the "gap" in hours interval
    store.record_ago("event", Duration::hours(2));

    let first = store.query("event").first_seen();

    // Event at 2 hours ago falls into hour bucket (minutes only cover 1 hour)
    // Bucket midpoint: 2 + 0.5 = 2.5 hours = 9000 seconds
    // After fix with gap detection: 5400 seconds = 1.5 hours
    let expected = Duration::seconds(5400);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact hour bucket with gap detection"
    );
}

#[test]
#[cfg(not(feature = "calendar"))]
fn first_seen_very_old_event_in_coarsest_interval() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 6, 1, 12, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_days(30)
        .track_weeks(52)
        .track_months(24)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Event from 18 months ago (only in months interval)
    store.record_ago("event", Duration::days(540)); // 18 * 30 = 540 days

    let first = store.query("event").first_seen();

    // Event at 540 days from clock_now, but interval_start is 1.5 days before clock_now
    // So event is 538.5 days from interval_start, placing it in bucket 17 (538.5 / 30 = 17.95)
    // Bucket 17 midpoint = interval_start - (30*17 + 15) = interval_start - 525 days
    // From clock_now: 525 + 1.5 = 526.5 days = 45489600 seconds
    let expected = Duration::seconds(45489600);

    assert_eq!(
        first,
        Some(expected),
        "Should return exact month bucket midpoint"
    );
}

#[test]
#[cfg(feature = "calendar")]
fn first_seen_very_old_event_in_coarsest_interval_calendar() {
    // Test with calendar-aligned months (1st of month at midnight)
    let fixed_time = Utc.with_ymd_and_hms(2025, 6, 1, 12, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_days(30)
        .track_weeks(52)
        .track_months(24)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    // Event from 18 months ago (only in months interval)
    store.record_ago("event", Duration::days(540)); // ~18 months

    let first = store.query("event").first_seen();
    assert!(first.is_some());

    // With calendar feature, months align on 1st at midnight in local time
    // Calculate expected value based on local timezone offset
    let offset = local_offset_hours(fixed_time);

    // Base value at UTC+0: 13524 hours (empirically observed)
    // Timezone offset shifts month boundaries by approximately 1 hour per timezone hour
    let expected_hours = 13524.0 - offset * 1.0;

    let duration = first.unwrap();
    let hours = duration.num_hours();

    assert!(
        ((expected_hours - 1.0) as i64..=(expected_hours + 1.0) as i64).contains(&hours),
        "Expected ~{:.0} hours (±1h) based on UTC{:+.1} offset, got {} hours",
        expected_hours,
        offset,
        hours
    );
}

// ============================================================================
// First Seen with Last Seen Consistency
// ============================================================================

#[test]
fn first_seen_and_last_seen_for_single_event() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 2, 10, 9, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

    let store = EventStore::builder()
        .track_minutes(60)
        .track_hours(24)
        .with_clock(Arc::new(clock.clone()))
        .build()
        .unwrap();

    store.record_ago("event", Duration::minutes(30));

    let first = store.query("event").first_seen();
    let last = store.query("event").last_seen();

    // For a single event, first and last should be exactly the same
    // Both return midpoint: 30 minutes + 0.5 minutes = 30.5 minutes = 1830 seconds
    let expected = Duration::seconds(1830);

    assert_eq!(first, Some(expected), "first_seen should be exact");
    assert_eq!(last, Some(expected), "last_seen should be exact");
    assert_eq!(
        first, last,
        "For single event, first and last must be identical"
    );
}

#[test]
#[cfg(not(feature = "calendar"))]
fn first_seen_older_than_last_seen_with_multiple_events() {
    let fixed_time = Utc.with_ymd_and_hms(2025, 3, 20, 15, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

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

    // Old event
    store.record_ago("event", Duration::days(3));

    // Recent event
    store.record_ago("event", Duration::hours(2));

    let first = store.query("event").first_seen();
    let last = store.query("event").last_seen();

    // Old event at 3 days (72 hours) falls into day bucket
    // After fix: 199800 seconds = 55.5 hours
    let expected_first = Duration::seconds(199800);

    // Recent event at 2 hours falls into hour bucket
    // Midpoint: 2 + 0.5 = 2.5 hours = 9000 seconds
    let expected_last = Duration::seconds(9000);

    assert_eq!(first, Some(expected_first), "first_seen should be exact");
    assert_eq!(last, Some(expected_last), "last_seen should be exact");
    assert!(
        first.unwrap() > last.unwrap(),
        "First must be older than last"
    );
}

#[test]
#[cfg(feature = "calendar")]
fn first_seen_older_than_last_seen_with_multiple_events_calendar() {
    // Test with calendar-aligned days (midnight at local time)
    let fixed_time = Utc.with_ymd_and_hms(2025, 3, 20, 15, 0, 0).unwrap();
    let clock = TestClock::build_for_testing_at(fixed_time);

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

    // Old event
    store.record_ago("event", Duration::days(3));

    // Recent event
    store.record_ago("event", Duration::hours(2));

    let first = store.query("event").first_seen();
    let last = store.query("event").last_seen();

    assert!(first.is_some(), "first_seen should exist");
    assert!(last.is_some(), "last_seen should exist");

    // With calendar feature, days align at midnight
    // Old event ~3 days ago, recent event ~2 hours ago
    assert!(
        first.unwrap() > last.unwrap(),
        "First must be older than last"
    );

    // Verify reasonable ranges
    let offset = local_offset_hours(fixed_time);

    let first_hours = first.unwrap().num_hours();
    let last_hours = last.unwrap().num_hours();

    // Base value at UTC+0: 67 hours for 3 days with calendar alignment
    // (Varies by test date/time - this test uses March 20, 2025 at 15:00 UTC)
    // Timezone offset shifts day boundaries by approximately 1 hour per timezone hour
    let expected_first_hours = 67.0 - offset * 1.0;

    assert!(
        ((expected_first_hours - 1.0) as i64..=(expected_first_hours + 1.0) as i64)
            .contains(&first_hours),
        "Expected first_seen ~{:.0} hours (±1h) based on UTC{:+.1} offset, got {} hours",
        expected_first_hours,
        offset,
        first_hours
    );
    assert!(
        (1..=4).contains(&last_hours),
        "Expected last_seen ~2 hours (stable, in hours bucket), got {} hours",
        last_hours
    );
}