mstlo 0.1.0

A Rust library for online monitoring of Signal Temporal Logic (STL) specifications.
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
//! Ring-buffer primitives used by the STL monitor implementation.
//!
//! This module provides:
//! - [`Step`], a timestamped signal sample,
//! - [`RingBufferTrait`], an abstraction over ring-buffer-like storage, and
//! - [`RingBuffer`], a `VecDeque`-backed implementation.
//!
//! It also includes [`guarded_prune`], a helper for pruning while protecting
//! data needed by pending evaluations.

#[cfg(feature = "track-cache-size")]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{collections::VecDeque, time::Duration};

#[cfg(feature = "track-cache-size")]
/// Global counter for elements currently residing in any ring buffer.
pub static GLOBAL_CACHE_SIZE: AtomicUsize = AtomicUsize::new(0);

/// A single sampled value of a named signal at a given timestamp.
#[derive(Clone, Debug, PartialEq)]
pub struct Step<T> {
    /// Signal identifier this step belongs to.
    pub signal: &'static str,
    /// Sampled value for the signal.
    pub value: T,
    /// Logical/event timestamp of this sample.
    pub timestamp: Duration,
}

impl<T> Step<T> {
    /// Creates a new [`Step`].
    ///
    /// # Arguments
    /// * `signal` - Signal identifier.
    /// * `value` - Sample value.
    /// * `timestamp` - Timestamp associated with the sample.
    pub fn new(signal: &'static str, value: T, timestamp: Duration) -> Self {
        Step {
            signal,
            value,
            timestamp,
        }
    }
}

/// Common interface for timestamped ring buffers.
///
/// Implementors are expected to maintain steps in ascending timestamp order.
pub trait RingBufferTrait {
    /// The value type stored in each [`Step`].
    type Value;

    /// The backing container type that stores steps.
    type Container: IntoIterator;

    /// Immutable iterator over stored steps.
    type Iter<'a>: Iterator<Item = &'a Step<Self::Value>>
    where
        Self: 'a;

    /// Mutable iterator over stored steps.
    type IterMut<'a>: Iterator<Item = &'a mut Step<Self::Value>>
    where
        Self: 'a;

    /// Creates an empty buffer.
    fn new() -> Self;
    /// Returns `true` when the buffer contains no steps.
    fn is_empty(&self) -> bool;
    /// Returns the number of stored steps.
    fn len(&self) -> usize;
    /// Returns the newest step, if any.
    fn get_back(&self) -> Option<&Step<Self::Value>>;
    /// Returns the oldest step, if any.
    fn get_front(&self) -> Option<&Step<Self::Value>>;
    /// Removes and returns the oldest step.
    fn pop_front(&mut self) -> Option<Step<Self::Value>>;
    /// Removes and returns the newest step.
    fn pop_back(&mut self) -> Option<Step<Self::Value>>;

    /// Appends a step to the buffer.
    fn add_step(&mut self, step: Step<Self::Value>);
    /// Replaces a step with matching timestamp.
    ///
    /// Returns `true` if a step was updated, `false` if no matching timestamp
    /// was found.
    fn update_step(&mut self, step: Step<Self::Value>) -> bool;

    /// Prune steps older than `max_age` from the buffer.
    fn prune(&mut self, max_age: Duration);

    /// Returns an iterator over all steps from oldest to newest.
    fn iter<'a>(&'a self) -> Self::Iter<'a>;

    #[cfg(feature = "track-cache-size")]
    /// Enables or disables global cache size tracking for this specific buffer.
    fn set_tracked(&mut self, tracked: bool);
}

/// `VecDeque`-backed ring buffer for timestamped signal steps.
#[derive(Clone, Debug)]
pub struct RingBuffer<T> {
    steps: VecDeque<Step<T>>,
    #[cfg(feature = "track-cache-size")]
    is_tracked: bool,
}

impl<T> Default for RingBuffer<T>
where
    T: Copy,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> RingBuffer<T>
where
    T: Copy,
{
    /// Creates an empty [`RingBuffer`].
    pub fn new() -> Self {
        RingBuffer {
            steps: VecDeque::new(),
            #[cfg(feature = "track-cache-size")]
            is_tracked: false, // Default to false to avoid unintended tracking
        }
    }

    /// Appends a new step.
    pub fn add_step(&mut self, step: Step<T>) {
        self.steps.push_back(step);
        #[cfg(feature = "track-cache-size")]
        if self.is_tracked {
            GLOBAL_CACHE_SIZE.fetch_add(1, Ordering::Relaxed);
        }
    }

    /// Replaces the step with the same timestamp.
    ///
    /// Returns `true` when a matching timestamp exists.
    ///
    /// This uses binary search and therefore assumes the internal storage is
    /// sorted by timestamp.
    pub fn update_step(&mut self, step: Step<T>) -> bool {
        self.steps
            .binary_search_by(|s| s.timestamp.cmp(&step.timestamp))
            .map(|index| {
                self.steps[index] = step;
            })
            .is_ok()
    }

    /// Returns an iterator over all stored steps from oldest to newest.
    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, Step<T>> {
        self.steps.iter()
    }
}

impl<T> RingBufferTrait for RingBuffer<T>
where
    T: Copy,
{
    type Value = T;
    type Container = VecDeque<Step<T>>;
    type Iter<'a>
        = std::collections::vec_deque::Iter<'a, Step<T>>
    where
        Self: 'a;

    type IterMut<'a>
        = std::collections::vec_deque::IterMut<'a, Step<T>>
    where
        Self: 'a;

    fn new() -> Self {
        Self::new()
    }
    fn is_empty(&self) -> bool {
        self.steps.is_empty()
    }
    fn len(&self) -> usize {
        self.steps.len()
    }
    fn get_back(&self) -> Option<&Step<T>> {
        self.steps.back()
    }
    fn get_front(&self) -> Option<&Step<T>> {
        self.steps.front()
    }
    fn pop_front(&mut self) -> Option<Step<Self::Value>> {
        let res = self.steps.pop_front();
        #[cfg(feature = "track-cache-size")]
        if res.is_some() && self.is_tracked {
            GLOBAL_CACHE_SIZE.fetch_sub(1, Ordering::Relaxed);
        }
        res
    }
    fn pop_back(&mut self) -> Option<Step<Self::Value>> {
        let res = self.steps.pop_back();
        #[cfg(feature = "track-cache-size")]
        if res.is_some() && self.is_tracked {
            GLOBAL_CACHE_SIZE.fetch_sub(1, Ordering::Relaxed);
        }
        res
    }

    fn add_step(&mut self, step: Step<T>) {
        self.add_step(step)
    }
    fn update_step(&mut self, step: Step<Self::Value>) -> bool {
        self.update_step(step)
    }
    fn prune(&mut self, max_age: Duration) {
        let current_time = match self.get_back() {
            Some(step) => step.timestamp,
            None => return, // Buffer is empty, nothing to prune
        };
        let max_age = current_time.saturating_sub(max_age);

        #[cfg(feature = "track-cache-size")]
        {
            let mut removed = 0;
            while let Some(front_step) = self.steps.front() {
                if front_step.timestamp < max_age {
                    removed += 1;
                    self.steps.pop_front();
                } else {
                    break;
                }
            }
            if self.is_tracked && removed > 0 {
                GLOBAL_CACHE_SIZE.fetch_sub(removed, Ordering::Relaxed);
            }
        }
        #[cfg(not(feature = "track-cache-size"))]
        {
            while let Some(front_step) = self.steps.front() {
                if front_step.timestamp < max_age {
                    self.steps.pop_front();
                } else {
                    break;
                }
            }
        }
    }

    fn iter<'a>(&'a self) -> Self::Iter<'a> {
        self.iter()
    }

    #[cfg(feature = "track-cache-size")]
    fn set_tracked(&mut self, tracked: bool) {
        self.is_tracked = tracked;
    }
}
#[cfg(feature = "track-cache-size")]
impl<T> Drop for RingBuffer<T> {
    fn drop(&mut self) {
        let remaining = self.steps.len();
        if remaining > 0 && self.is_tracked {
            GLOBAL_CACHE_SIZE.fetch_sub(remaining, Ordering::Relaxed);
        }
    }
}

/// Prunes a cache while protecting entries at or after a given timestamp.
///
/// This is useful when pruning caches with zero lookahead but pending evaluations
/// that require recent data. The function ensures that all entries at or after
/// `protected_ts` are preserved, even if `lookahead` would normally allow their removal.
///
/// # Arguments
/// * `cache` - The ring buffer to prune
/// * `lookahead` - The normal lookahead duration for pruning
/// * `protected_ts` - Timestamp to protect; entries at or after this will not be pruned
pub fn guarded_prune<C>(cache: &mut C, lookahead: Duration, protected_ts: Duration)
where
    C: RingBufferTrait,
{
    let Some(back) = cache.get_back() else { return };
    // Preserve entries at or after the earliest pending evaluation timestamp.
    let distance_to_protected = back.timestamp.saturating_sub(protected_ts);
    let effective_max_age = lookahead.max(distance_to_protected);
    cache.prune(effective_max_age);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ring_creation() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::new(0, 0),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::new(0, 0),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::new(0, 0),
        });

        for i in 0..3 {
            if let Some(step) = signal.steps.get(i) {
                assert_eq!(step.value, i + 1)
            }
        }
    }

    #[test]
    fn ring_prune() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::from_secs(3),
        });

        // Prune steps older than 1 second from the latest timestamp (which is 3 seconds)
        // This should remove the step with timestamp 1 second
        signal.prune(Duration::from_secs(1));

        assert_eq!(signal.len(), 2);
        assert_eq!(signal.get_front().unwrap().value, 2);
        assert_eq!(signal.get_back().unwrap().value, 3);
    }
    #[test]
    fn ring_get_back() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::from_secs(3),
        });
        let back_step = signal.get_back().unwrap();
        assert_eq!(back_step.value, 3);
    }
    #[test]
    fn ring_get_front() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::from_secs(3),
        });
        let front_step = signal.get_front().unwrap();
        assert_eq!(front_step.value, 1);
    }
    #[test]
    fn ring_pop_front() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::from_secs(3),
        });
        let popped_step = signal.pop_front().unwrap();
        assert_eq!(popped_step.value, 1);
        assert_eq!(signal.len(), 2);
        assert_eq!(signal.get_front().unwrap().value, 2);
        assert_eq!(signal.get_back().unwrap().value, 3);
    }
    #[test]
    fn ring_iter() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });
        signal.add_step(Step {
            signal: "x",
            value: 3,
            timestamp: Duration::from_secs(3),
        });
        let mut iter = signal.iter();
        assert_eq!(iter.next().unwrap().value, 1);
        assert_eq!(iter.next().unwrap().value, 2);
        assert_eq!(iter.next().unwrap().value, 3);
        assert!(iter.next().is_none());
    }
    #[test]
    fn ring_is_empty() {
        let signal: RingBuffer<bool> = RingBuffer::new();
        assert!(signal.is_empty());
    }

    #[test]
    fn default_ring_buffer() {
        let signal: RingBuffer<i32> = RingBuffer::default();
        assert!(signal.is_empty());
    }

    #[test]
    fn ring_prune_empty_buffer() {
        let mut signal: RingBuffer<f64> = RingBuffer::new();
        // Pruning an empty buffer should be a no-op
        signal.prune(Duration::from_secs(1));
        assert!(signal.is_empty());
    }

    #[test]
    fn ring_update_step() {
        let mut signal = RingBuffer::new();
        signal.add_step(Step {
            signal: "x",
            value: 1,
            timestamp: Duration::from_secs(1),
        });
        signal.add_step(Step {
            signal: "x",
            value: 2,
            timestamp: Duration::from_secs(2),
        });

        // Update existing timestamp
        let updated = signal.update_step(Step {
            signal: "x",
            value: 10,
            timestamp: Duration::from_secs(1),
        });
        assert!(updated);
        assert_eq!(signal.get_front().unwrap().value, 10);

        // Update non-existing timestamp
        let not_updated = signal.update_step(Step {
            signal: "x",
            value: 20,
            timestamp: Duration::from_secs(5),
        });
        assert!(!not_updated);
    }
}