wasm4pm 26.6.25

High-performance process mining algorithms in WebAssembly for JavaScript/TypeScript
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
//! SPC History Ring Buffer — Fix one-shot SPC problem
//!
//! Maintains a sliding window of 100 SPC snapshots for historical analysis.
//! Enables Western Electric rules to evaluate trends across cycles, not just
//! within a single cycle's data.

use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

// ---------------------------------------------------------------------------
// Step 1: Ring Buffer Data Structure
// ---------------------------------------------------------------------------

/// Fixed-size ring buffer that automatically evicts oldest entries when full.
///
/// # Type Parameters
/// * `T` - Item type (must implement Clone)
/// * `N` - Capacity (max number of items stored)
///
/// # Example
/// ```
/// # use wasm4pm::spc_history::RingBuffer;
/// let mut buffer: RingBuffer<i32, 5> = RingBuffer::new();
/// buffer.push(1);
/// buffer.push(2);
/// assert_eq!(buffer.len(), 2);
/// ```
pub struct RingBuffer<T, const N: usize> {
    buffer: VecDeque<T>,
}

impl<T: Clone, const N: usize> Default for RingBuffer<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Clone, const N: usize> RingBuffer<T, N> {
    /// Create a new empty ring buffer with capacity N.
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let buffer: RingBuffer<i32, 10> = RingBuffer::new();
    /// assert_eq!(buffer.len(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            buffer: VecDeque::with_capacity(N),
        }
    }

    /// Push an item into the buffer.
    ///
    /// If the buffer is full (len == N), the oldest item is evicted first.
    ///
    /// # Arguments
    /// * `item` - Item to store
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let mut buffer: RingBuffer<i32, 3> = RingBuffer::new();
    /// buffer.push(1);
    /// buffer.push(2);
    /// buffer.push(3);
    /// buffer.push(4); // 1 is evicted
    /// assert_eq!(buffer.len(), 3);
    /// ```
    pub fn push(&mut self, item: T) {
        if self.buffer.len() == N {
            self.buffer.pop_front();
        }
        self.buffer.push_back(item);
    }

    /// Return current number of items in the buffer.
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let mut buffer: RingBuffer<i32, 5> = RingBuffer::new();
    /// assert_eq!(buffer.len(), 0);
    /// buffer.push(42);
    /// assert_eq!(buffer.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Return true if buffer is empty.
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let buffer: RingBuffer<i32, 5> = RingBuffer::new();
    /// assert!(buffer.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Return iterator over items in insertion order (oldest to newest).
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let mut buffer: RingBuffer<i32, 3> = RingBuffer::new();
    /// buffer.push(1);
    /// buffer.push(2);
    /// let values: Vec<_> = buffer.iter().copied().collect();
    /// assert_eq!(values, vec![1, 2]);
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.buffer.iter()
    }

    /// Clear all items from the buffer.
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::RingBuffer;
    /// let mut buffer: RingBuffer<i32, 5> = RingBuffer::new();
    /// buffer.push(1);
    /// buffer.push(2);
    /// buffer.clear();
    /// assert_eq!(buffer.len(), 0);
    /// ```
    pub fn clear(&mut self) {
        self.buffer.clear();
    }
}

// ---------------------------------------------------------------------------
// Step 2: SpcHistory Struct
// ---------------------------------------------------------------------------

/// Snapshot of SPC metrics at a point in time.
///
/// Captures the four key dimensions tracked by SPC:
/// - Event rate (events per trace)
/// - Trace duration average
/// - Activity frequency
/// - Health state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpcSnapshot {
    /// ISO-8601 timestamp or cycle identifier.
    pub timestamp: String,
    /// Mean events per trace.
    pub event_rate: f64,
    /// Mean trace duration in milliseconds.
    pub trace_duration_avg: f64,
    /// Activity frequency metric.
    pub activity_frequency: f64,
    /// Health state code (0=Normal, 1=Warning, 2=Degraded, 3=Critical, 4=Failed).
    pub health_state: u8,
}

impl SpcSnapshot {
    /// Create a new SPC snapshot.
    ///
    /// # Arguments
    /// * `timestamp` - ISO-8601 timestamp or cycle identifier
    /// * `event_rate` - Mean events per trace
    /// * `trace_duration_avg` - Mean trace duration (ms)
    /// * `activity_frequency` - Activity frequency metric
    /// * `health_state` - Health state code (0-4)
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::SpcSnapshot;
    /// let snapshot = SpcSnapshot {
    ///     timestamp: "2026-04-13T12:00:00Z".to_string(),
    ///     event_rate: 5.2,
    ///     trace_duration_avg: 150.0,
    ///     activity_frequency: 0.85,
    ///     health_state: 0,
    /// };
    /// assert_eq!(snapshot.health_state, 0);
    /// ```
    pub fn new(
        timestamp: String,
        event_rate: f64,
        trace_duration_avg: f64,
        activity_frequency: f64,
        health_state: u8,
    ) -> Self {
        Self {
            timestamp,
            event_rate,
            trace_duration_avg,
            activity_frequency,
            health_state,
        }
    }
}

/// SPC history container with ring buffer storage.
///
/// Maintains up to 100 snapshots for trend analysis across cycles.
/// Enables detection of gradual degradation or improvement over time.
pub struct SpcHistory {
    /// Ring buffer storing up to 100 snapshots.
    pub history: RingBuffer<SpcSnapshot, 100>,
    /// Total number of cycles recorded (monotonically increasing).
    pub cycle_count: u64,
}

impl SpcHistory {
    /// Create a new empty SPC history.
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::SpcHistory;
    /// let history = SpcHistory::new();
    /// assert_eq!(history.cycle_count, 0);
    /// assert!(!history.has_sufficient_data());
    /// ```
    pub fn new() -> Self {
        Self {
            history: RingBuffer::new(),
            cycle_count: 0,
        }
    }

    /// Record a new snapshot into the history.
    ///
    /// Increments cycle count and stores snapshot (evicts oldest if full).
    ///
    /// # Arguments
    /// * `snapshot` - SPC metrics for this cycle
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::{SpcHistory, SpcSnapshot};
    /// let mut history = SpcHistory::new();
    /// let snapshot = SpcSnapshot::new(
    ///     "2026-04-13T12:00:00Z".to_string(),
    ///     5.2,
    ///     150.0,
    ///     0.85,
    ///     0,
    /// );
    /// history.record_snapshot(snapshot);
    /// assert_eq!(history.cycle_count, 1);
    /// assert!(!history.has_sufficient_data()); // needs 9 total
    /// ```
    ///
    /// Non-finite values (NaN, +/-Inf) in f64 fields are sanitized to 0.0
    /// to prevent silent WE-rule alert masking downstream.
    pub fn record_snapshot(&mut self, snapshot: SpcSnapshot) {
        self.history.push(Self::sanitize(snapshot));
        self.cycle_count = self.cycle_count.saturating_add(1);
    }

    /// Replace contents wholesale and set `cycle_count` to `cycle_count`
    /// exactly once. Counterpart of `get_all_snapshots` + `cycle_count`
    /// for round-tripping through `get_spc_history`/`set_spc_history`.
    /// Per-call `record_snapshot` would inflate cycle_count by N.
    pub fn restore(&mut self, snapshots: Vec<SpcSnapshot>, cycle_count: u64) {
        self.history.clear();
        for snap in snapshots {
            self.history.push(Self::sanitize(snap));
        }
        self.cycle_count = cycle_count;
    }

    /// Replace non-finite floats with 0.0 to keep downstream stats finite.
    fn sanitize(mut s: SpcSnapshot) -> SpcSnapshot {
        if !s.event_rate.is_finite() {
            s.event_rate = 0.0;
        }
        if !s.trace_duration_avg.is_finite() {
            s.trace_duration_avg = 0.0;
        }
        if !s.activity_frequency.is_finite() {
            s.activity_frequency = 0.0;
        }
        s
    }

    /// Check if sufficient historical data exists for Western Electric rules.
    ///
    /// Returns true if at least 9 snapshots are recorded (minimum for Rule 2).
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::{SpcHistory, SpcSnapshot};
    /// let mut history = SpcHistory::new();
    /// assert!(!history.has_sufficient_data());
    ///
    /// for i in 0..9 {
    ///     history.record_snapshot(SpcSnapshot::new(
    ///         format!("cycle-{}", i),
    ///         5.0, 150.0, 0.8, 0,
    ///     ));
    /// }
    /// assert!(history.has_sufficient_data());
    /// ```
    pub fn has_sufficient_data(&self) -> bool {
        self.history.len() >= 9
    }

    /// Get historical event rates as a vector (oldest to newest).
    ///
    /// Useful for trend analysis and Western Electric Rule evaluation.
    ///
    /// # Returns
    /// Vector of event_rate values in chronological order
    ///
    /// # Example
    /// ```
    /// # use wasm4pm::spc_history::{SpcHistory, SpcSnapshot};
    /// let mut history = SpcHistory::new();
    /// history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
    /// history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 0));
    /// let rates = history.get_event_rates();
    /// assert_eq!(rates, vec![5.0, 5.5]);
    /// ```
    pub fn get_event_rates(&self) -> Vec<f64> {
        self.history.iter().map(|s| s.event_rate).collect()
    }

    /// Get historical trace duration averages as a vector (oldest to newest).
    ///
    /// # Returns
    /// Vector of trace_duration_avg values in chronological order
    pub fn get_trace_durations(&self) -> Vec<f64> {
        self.history.iter().map(|s| s.trace_duration_avg).collect()
    }

    /// Get historical activity frequencies as a vector (oldest to newest).
    ///
    /// # Returns
    /// Vector of activity_frequency values in chronological order
    pub fn get_activity_frequencies(&self) -> Vec<f64> {
        self.history.iter().map(|s| s.activity_frequency).collect()
    }

    /// Get all snapshots as a vector (oldest to newest).
    ///
    /// # Returns
    /// Vector of cloned snapshots in chronological order
    pub fn get_all_snapshots(&self) -> Vec<SpcSnapshot> {
        self.history.iter().cloned().collect()
    }

    /// Clear all history (reset to empty state).
    ///
    /// Cycle count resets to 0.
    pub fn clear(&mut self) {
        self.history.clear();
        self.cycle_count = 0;
    }
}

// ---------------------------------------------------------------------------
// Step 3: Thread Local Storage (accessed from lib.rs)
// ---------------------------------------------------------------------------

/// Thread-local storage for SPC history.
///
/// Defined in lib.rs as:
/// ```rust
/// thread_local! {
///     pub static SPC_HISTORY: RefCell<spc_history::SpcHistory> =
///         RefCell::new(spc_history::SpcHistory::new());
/// }
/// ```
///
/// Access via:
/// ```rust
/// SPC_HISTORY.with(|history| {
///     history.borrow_mut().record_snapshot(snapshot);
/// });
/// ```

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_ring_buffer_basic() {
        let mut buffer: RingBuffer<i32, 3> = RingBuffer::new();
        assert_eq!(buffer.len(), 0);
        assert!(buffer.is_empty());

        buffer.push(1);
        assert_eq!(buffer.len(), 1);
        assert!(!buffer.is_empty());

        buffer.push(2);
        buffer.push(3);
        assert_eq!(buffer.len(), 3);

        // Eviction: buffer is full, push 4 should evict 1
        buffer.push(4);
        assert_eq!(buffer.len(), 3); // Still capacity 3
        let values: Vec<_> = buffer.iter().copied().collect();
        assert_eq!(values, vec![2, 3, 4]); // 1 evicted
    }

    #[test]
    fn test_ring_buffer_iteration() {
        let mut buffer: RingBuffer<i32, 5> = RingBuffer::new();
        buffer.push(10);
        buffer.push(20);
        buffer.push(30);

        let values: Vec<_> = buffer.iter().copied().collect();
        assert_eq!(values, vec![10, 20, 30]);
    }

    #[test]
    fn test_ring_buffer_clear() {
        let mut buffer: RingBuffer<i32, 5> = RingBuffer::new();
        buffer.push(1);
        buffer.push(2);
        buffer.clear();
        assert_eq!(buffer.len(), 0);
        assert!(buffer.is_empty());
    }

    #[test]
    fn test_spc_snapshot_new() {
        let snapshot = SpcSnapshot::new("2026-04-13T12:00:00Z".to_string(), 5.2, 150.0, 0.85, 0);
        assert_eq!(snapshot.timestamp, "2026-04-13T12:00:00Z");
        assert_eq!(snapshot.event_rate, 5.2);
        assert_eq!(snapshot.trace_duration_avg, 150.0);
        assert_eq!(snapshot.activity_frequency, 0.85);
        assert_eq!(snapshot.health_state, 0);
    }

    #[test]
    fn test_spc_history_new() {
        let history = SpcHistory::new();
        assert_eq!(history.cycle_count, 0);
        assert_eq!(history.history.len(), 0);
        assert!(!history.has_sufficient_data());
    }

    #[test]
    fn test_spc_history_record_snapshot() {
        let mut history = SpcHistory::new();
        let snapshot = SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0);

        history.record_snapshot(snapshot);
        assert_eq!(history.cycle_count, 1);
        assert_eq!(history.history.len(), 1);
        assert!(!history.has_sufficient_data()); // Needs 9
    }

    #[test]
    fn test_spc_history_sufficient_data() {
        let mut history = SpcHistory::new();

        // Add 8 snapshots - not enough
        for i in 0..8 {
            history.record_snapshot(SpcSnapshot::new(format!("cycle-{}", i), 5.0, 150.0, 0.8, 0));
        }
        assert!(!history.has_sufficient_data());

        // Add 9th snapshot - now sufficient
        history.record_snapshot(SpcSnapshot::new("cycle-8".into(), 5.0, 150.0, 0.8, 0));
        assert!(history.has_sufficient_data());
        assert_eq!(history.cycle_count, 9);
    }

    #[test]
    fn test_spc_history_get_event_rates() {
        let mut history = SpcHistory::new();
        history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
        history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 0));
        history.record_snapshot(SpcSnapshot::new("t3".into(), 6.0, 160.0, 0.84, 0));

        let rates = history.get_event_rates();
        assert_eq!(rates, vec![5.0, 5.5, 6.0]);
    }

    #[test]
    fn test_spc_history_get_trace_durations() {
        let mut history = SpcHistory::new();
        history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
        history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 0));

        let durations = history.get_trace_durations();
        assert_eq!(durations, vec![150.0, 155.0]);
    }

    #[test]
    fn test_spc_history_get_activity_frequencies() {
        let mut history = SpcHistory::new();
        history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
        history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 0));

        let freqs = history.get_activity_frequencies();
        assert_eq!(freqs, vec![0.8, 0.82]);
    }

    #[test]
    fn test_spc_history_ring_buffer_eviction() {
        let mut history = SpcHistory::new();

        // Fill buffer to capacity (100)
        for i in 0..100 {
            history.record_snapshot(SpcSnapshot::new(
                format!("cycle-{}", i),
                i as f64,
                150.0,
                0.8,
                0,
            ));
        }
        assert_eq!(history.history.len(), 100);
        assert_eq!(history.cycle_count, 100);

        // Add 101st snapshot - should evict oldest (cycle-0)
        history.record_snapshot(SpcSnapshot::new("cycle-100".into(), 100.0, 150.0, 0.8, 0));
        assert_eq!(history.history.len(), 100); // Still 100
        assert_eq!(history.cycle_count, 101);

        // Check that oldest is now cycle-1
        let oldest = history.history.iter().next().unwrap();
        assert_eq!(oldest.timestamp, "cycle-1");
        assert_eq!(oldest.event_rate, 1.0);
    }

    #[test]
    fn test_spc_history_clear() {
        let mut history = SpcHistory::new();
        history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
        history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 0));

        assert_eq!(history.cycle_count, 2);
        assert_eq!(history.history.len(), 2);

        history.clear();
        assert_eq!(history.cycle_count, 0);
        assert_eq!(history.history.len(), 0);
        assert!(history.history.is_empty());
    }

    #[test]
    fn test_spc_history_default() {
        let history = SpcHistory::new();
        assert_eq!(history.cycle_count, 0);
        assert_eq!(history.history.len(), 0);
    }

    /// Push 101 snapshots into a capacity-100 ring buffer.
    /// Verify that:
    /// - Only 100 snapshots are retained (oldest evicted).
    /// - The first retained snapshot is the 2nd one pushed (cycle-1, event_rate=1.0).
    /// - The last retained snapshot is the 101st one pushed (cycle-100, event_rate=100.0).
    /// - All 100 retained snapshots are in strict chronological order (event_rate ascending).
    #[test]
    fn test_ring_buffer_101_pushes_chronological_order() {
        let mut history = SpcHistory::new();

        for i in 0..=100u64 {
            history.record_snapshot(SpcSnapshot::new(
                format!("cycle-{}", i),
                i as f64, // event_rate doubles as unique marker
                150.0,
                0.8,
                0,
            ));
        }

        // Exactly 100 snapshots remain (oldest, cycle-0 with rate=0.0, was evicted).
        assert_eq!(history.history.len(), 100, "ring buffer must cap at 100");
        assert_eq!(
            history.cycle_count, 101,
            "cycle counter must be monotonically 101"
        );

        let snapshots = history.get_all_snapshots();

        // Oldest retained is cycle-1 (event_rate=1.0).
        assert_eq!(
            snapshots[0].timestamp, "cycle-1",
            "oldest retained must be cycle-1 after 101 pushes"
        );
        assert_eq!(
            snapshots[0].event_rate, 1.0,
            "oldest retained event_rate must be 1.0"
        );

        // Newest retained is cycle-100 (event_rate=100.0).
        assert_eq!(
            snapshots[99].timestamp, "cycle-100",
            "newest retained must be cycle-100"
        );
        assert_eq!(
            snapshots[99].event_rate, 100.0,
            "newest retained event_rate must be 100.0"
        );

        // All entries are in strict chronological order (event_rate strictly increasing).
        let rates: Vec<f64> = snapshots.iter().map(|s| s.event_rate).collect();
        for w in rates.windows(2) {
            assert!(
                w[1] > w[0],
                "snapshots must be in chronological order: {} followed by {}",
                w[0],
                w[1]
            );
        }
    }

    #[test]
    fn test_spc_history_get_all_snapshots() {
        let mut history = SpcHistory::new();
        history.record_snapshot(SpcSnapshot::new("t1".into(), 5.0, 150.0, 0.8, 0));
        history.record_snapshot(SpcSnapshot::new("t2".into(), 5.5, 155.0, 0.82, 1));

        let snapshots = history.get_all_snapshots();
        assert_eq!(snapshots.len(), 2);
        assert_eq!(snapshots[0].timestamp, "t1");
        assert_eq!(snapshots[1].timestamp, "t2");
        assert_eq!(snapshots[0].health_state, 0);
        assert_eq!(snapshots[1].health_state, 1);
    }
}