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
use crate::math::MulAdd;
macro_rules! impl_event_rate_float {
($name:ident, $builder:ident, $ty:ty) => {
/// Smoothed event rate tracker.
///
/// Uses an EMA of inter-arrival times, inverted on query to produce
/// a rate (events per unit time). The rate adapts smoothly to changes
/// in event frequency.
///
/// # Use Cases
/// - Message throughput monitoring
/// - Order rate tracking
/// - Adaptive rate limiting input
#[derive(Debug, Clone)]
pub struct $name {
alpha: $ty,
one_minus_alpha: $ty,
interval: $ty,
last_timestamp: $ty,
count: u64,
min_samples: u64,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
alpha: Option<$ty>,
min_samples: u64,
}
impl $name {
/// Creates a builder.
#[inline]
#[must_use]
pub fn builder() -> $builder {
$builder {
alpha: Option::None,
min_samples: 2,
}
}
/// Records an event at the given timestamp.
///
/// If two events share a timestamp, the interval is zero and
/// `rate()` returns `None` until a non-zero interval is observed.
#[inline]
pub fn tick(&mut self, timestamp: $ty) {
self.count += 1;
if self.count == 1 {
self.last_timestamp = timestamp;
return;
}
let dt = timestamp - self.last_timestamp;
self.last_timestamp = timestamp;
if self.count == 2 {
self.interval = dt;
} else {
self.interval = self.alpha.fma(dt, self.one_minus_alpha * self.interval);
}
}
/// Current smoothed event rate (events per unit time).
///
/// Returns `None` if not primed or if interval is zero.
#[inline]
#[must_use]
pub fn rate(&self) -> Option<$ty> {
if self.count < self.min_samples || self.interval <= (0.0 as $ty) {
Option::None
} else {
Option::Some(1.0 as $ty / self.interval)
}
}
/// Current smoothed inter-event interval, or `None` if < 2 events.
#[inline]
#[must_use]
pub fn interval(&self) -> Option<$ty> {
if self.count >= 2 {
Option::Some(self.interval)
} else {
Option::None
}
}
/// Number of events recorded.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Whether the tracker has reached `min_samples`.
#[inline]
#[must_use]
pub fn is_primed(&self) -> bool {
self.count >= self.min_samples
}
/// Resets to uninitialized state.
#[inline]
pub fn reset(&mut self) {
self.interval = 0.0 as $ty;
self.last_timestamp = 0.0 as $ty;
self.count = 0;
}
}
impl $builder {
/// Direct smoothing factor for interval EMA.
#[inline]
#[must_use]
pub fn alpha(mut self, alpha: $ty) -> Self {
self.alpha = Option::Some(alpha);
self
}
/// Halflife for interval smoothing.
#[inline]
#[must_use]
#[cfg(any(feature = "std", feature = "libm"))]
pub fn halflife(mut self, halflife: $ty) -> Self {
let ln2 = core::f64::consts::LN_2 as $ty;
let alpha = 1.0 as $ty - crate::math::exp((-ln2 / halflife) as f64) as $ty;
self.alpha = Option::Some(alpha);
self
}
/// Span for interval smoothing.
#[inline]
#[must_use]
pub fn span(mut self, n: u64) -> Self {
let alpha = 2.0 as $ty / (n as $ty + 1.0 as $ty);
self.alpha = Option::Some(alpha);
self
}
/// Minimum events before rate is valid. Default: 2.
#[inline]
#[must_use]
pub fn min_samples(mut self, min: u64) -> Self {
self.min_samples = min;
self
}
/// Builds the event rate tracker.
///
/// # Errors
///
/// - Alpha must have been set.
/// - Alpha must be in (0, 1) exclusive.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let alpha = self.alpha.ok_or(crate::ConfigError::Missing("alpha"))?;
if !(alpha > 0.0 as $ty && alpha < 1.0 as $ty) {
return Err(crate::ConfigError::Invalid(
"EventRate alpha must be in (0, 1)",
));
}
Ok($name {
alpha,
one_minus_alpha: 1.0 as $ty - alpha,
interval: 0.0 as $ty,
last_timestamp: 0.0 as $ty,
count: 0,
min_samples: self.min_samples,
})
}
}
};
}
impl_event_rate_float!(EventRateF64, EventRateF64Builder, f64);
impl_event_rate_float!(EventRateF32, EventRateF32Builder, f32);
macro_rules! impl_event_rate_int {
($name:ident, $builder:ident, $ty:ty, $acc_ty:ty) => {
/// Smoothed event rate tracker (integer variant).
///
/// Uses kernel-style fixed-point EMA on inter-arrival ticks.
/// Rate query returns `unit / smoothed_interval` where unit is
/// the caller's time unit.
#[derive(Debug, Clone)]
pub struct $name {
acc: $acc_ty,
shift: u32,
span: u64,
last_timestamp: $ty,
count: u64,
min_samples: u64,
initialized: bool,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
span: Option<u64>,
min_samples: u64,
}
impl $name {
/// Creates a builder.
#[inline]
#[must_use]
pub fn builder() -> $builder {
$builder {
span: Option::None,
min_samples: 2,
}
}
/// Records an event at the given tick.
#[inline]
pub fn tick(&mut self, timestamp: $ty) {
self.count += 1;
if self.count == 1 {
self.last_timestamp = timestamp;
return;
}
let dt = timestamp - self.last_timestamp;
self.last_timestamp = timestamp;
if !self.initialized {
self.acc = (dt as $acc_ty) << self.shift;
self.initialized = true;
} else {
let dt_shifted = (dt as $acc_ty) << self.shift;
self.acc += (dt_shifted - self.acc) >> self.shift;
}
}
/// Current smoothed inter-event interval, or `None` if < 2 events.
#[inline]
#[must_use]
pub fn interval(&self) -> Option<$ty> {
if self.count >= 2 && self.initialized {
Option::Some((self.acc >> self.shift) as $ty)
} else {
Option::None
}
}
/// Effective span after rounding.
#[inline]
#[must_use]
pub fn effective_span(&self) -> u64 {
self.span
}
/// Number of events recorded.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Whether the tracker has reached `min_samples`.
#[inline]
#[must_use]
pub fn is_primed(&self) -> bool {
self.count >= self.min_samples
}
/// Resets to uninitialized state.
#[inline]
pub fn reset(&mut self) {
self.acc = 0;
self.last_timestamp = 0;
self.count = 0;
self.initialized = false;
}
}
impl $builder {
/// Smoothing span. Rounded up to next `2^k - 1`.
#[inline]
#[must_use]
pub fn span(mut self, n: u64) -> Self {
self.span = Option::Some(n);
self
}
/// Minimum events before rate is valid. Default: 2.
#[inline]
#[must_use]
pub fn min_samples(mut self, min: u64) -> Self {
self.min_samples = min;
self
}
/// Builds the event rate tracker.
///
/// # Errors
///
/// - Span must have been set and >= 1.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let requested = self.span.ok_or(crate::ConfigError::Missing("span"))?;
if requested < 1 {
return Err(crate::ConfigError::Invalid("EventRate span must be >= 1"));
}
let effective = crate::ema::next_power_of_two_minus_one(requested);
let shift = crate::ema::log2_of_span_plus_one(effective);
Ok($name {
acc: 0,
shift,
span: effective,
last_timestamp: 0,
count: 0,
min_samples: self.min_samples,
initialized: false,
})
}
}
};
}
impl_event_rate_int!(EventRateI64, EventRateI64Builder, i64, i128);
impl_event_rate_int!(EventRateI32, EventRateI32Builder, i32, i64);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constant_rate() {
let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
// Events every 10 units → rate should converge to 0.1
for i in 0..100 {
er.tick(i as f64 * 10.0);
}
let rate = er.rate().unwrap();
assert!((rate - 0.1).abs() < 0.01, "rate should be ~0.1, got {rate}");
}
#[test]
fn burst_increases_rate() {
let mut er = EventRateF64::builder().alpha(0.5).build().unwrap();
// Normal rate: every 10 units
for i in 0..20 {
er.tick(i as f64 * 10.0);
}
let normal_rate = er.rate().unwrap();
// Burst: events every 1 unit
for i in 0..20 {
er.tick(200.0 + i as f64);
}
let burst_rate = er.rate().unwrap();
assert!(
burst_rate > normal_rate,
"burst rate ({burst_rate}) should exceed normal ({normal_rate})"
);
}
#[test]
fn priming() {
let mut er = EventRateF64::builder()
.alpha(0.3)
.min_samples(5)
.build()
.unwrap();
for i in 0..4 {
er.tick(i as f64 * 10.0);
assert!(er.rate().is_none());
}
er.tick(40.0);
assert!(er.rate().is_some());
}
#[test]
fn reset() {
let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
for i in 0..10 {
er.tick(i as f64 * 10.0);
}
er.reset();
assert_eq!(er.count(), 0);
assert!(er.rate().is_none());
}
#[test]
fn f32_basic() {
let mut er = EventRateF32::builder().alpha(0.3).build().unwrap();
er.tick(0.0);
er.tick(10.0);
assert!(er.rate().is_some());
}
#[test]
fn i64_basic() {
let mut er = EventRateI64::builder().span(7).build().unwrap();
for i in 0..10 {
er.tick(i * 100);
}
let interval = er.interval().unwrap();
assert!(
(interval - 100).abs() <= 1,
"interval should be ~100, got {interval}"
);
}
#[test]
fn i32_basic() {
let mut er = EventRateI32::builder().span(3).build().unwrap();
er.tick(0);
er.tick(50);
assert!(er.interval().is_some());
}
#[test]
fn zero_interval_returns_none() {
let mut er = EventRateF64::builder().alpha(0.3).build().unwrap();
er.tick(100.0);
er.tick(100.0); // same timestamp → interval = 0
// rate() should return None (division by zero guard)
assert!(
er.rate().is_none(),
"rate should be None with zero interval"
);
}
#[test]
fn errors_without_alpha() {
let result = EventRateF64::builder().build();
assert!(matches!(result, Err(crate::ConfigError::Missing("alpha"))));
}
}