Skip to main content

rsigma_eval/correlation/
window.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2
3use rsigma_parser::{ConditionExpr, CorrelationType, WindowMode};
4use serde::Serialize;
5
6use super::CompiledCondition;
7
8// =============================================================================
9// Window State
10// =============================================================================
11
12/// Per-group mutable state within a time window.
13///
14/// Each variant matches the type of aggregation being performed.
15#[derive(Debug, Clone, Serialize, serde::Deserialize)]
16pub enum WindowState {
17    /// For `event_count`: timestamps of matching events.
18    EventCount { timestamps: VecDeque<i64> },
19    /// For `value_count`: (timestamp, field_value) pairs.
20    ValueCount { entries: VecDeque<(i64, String)> },
21    /// For `temporal` / `temporal_ordered`: rule_ref -> list of hit timestamps.
22    Temporal {
23        rule_hits: HashMap<String, VecDeque<i64>>,
24    },
25    /// For `value_sum`, `value_avg`, `value_percentile`, `value_median`:
26    /// (timestamp, numeric_value) pairs.
27    NumericAgg { entries: VecDeque<(i64, f64)> },
28}
29
30impl WindowState {
31    /// Create a new empty window state for the given correlation type.
32    pub fn new_for(corr_type: CorrelationType) -> Self {
33        match corr_type {
34            CorrelationType::EventCount => WindowState::EventCount {
35                timestamps: VecDeque::new(),
36            },
37            CorrelationType::ValueCount => WindowState::ValueCount {
38                entries: VecDeque::new(),
39            },
40            CorrelationType::Temporal | CorrelationType::TemporalOrdered => WindowState::Temporal {
41                rule_hits: HashMap::new(),
42            },
43            CorrelationType::ValueSum
44            | CorrelationType::ValueAvg
45            | CorrelationType::ValuePercentile
46            | CorrelationType::ValueMedian => WindowState::NumericAgg {
47                entries: VecDeque::new(),
48            },
49        }
50    }
51
52    /// Remove all entries older than the cutoff timestamp.
53    pub fn evict(&mut self, cutoff: i64) {
54        match self {
55            WindowState::EventCount { timestamps } => {
56                while timestamps.front().is_some_and(|&t| t < cutoff) {
57                    timestamps.pop_front();
58                }
59            }
60            WindowState::ValueCount { entries } => {
61                while entries.front().is_some_and(|(t, _)| *t < cutoff) {
62                    entries.pop_front();
63                }
64            }
65            WindowState::Temporal { rule_hits } => {
66                for timestamps in rule_hits.values_mut() {
67                    while timestamps.front().is_some_and(|&t| t < cutoff) {
68                        timestamps.pop_front();
69                    }
70                }
71                // Remove empty rule entries
72                rule_hits.retain(|_, ts| !ts.is_empty());
73            }
74            WindowState::NumericAgg { entries } => {
75                while entries.front().is_some_and(|(t, _)| *t < cutoff) {
76                    entries.pop_front();
77                }
78            }
79        }
80    }
81
82    /// Returns true if this state has no entries.
83    pub fn is_empty(&self) -> bool {
84        match self {
85            WindowState::EventCount { timestamps } => timestamps.is_empty(),
86            WindowState::ValueCount { entries } => entries.is_empty(),
87            WindowState::Temporal { rule_hits } => rule_hits.is_empty(),
88            WindowState::NumericAgg { entries } => entries.is_empty(),
89        }
90    }
91
92    /// Returns the most recent timestamp in this window, or `None` if empty.
93    pub fn latest_timestamp(&self) -> Option<i64> {
94        match self {
95            WindowState::EventCount { timestamps } => timestamps.back().copied(),
96            WindowState::ValueCount { entries } => entries.back().map(|(t, _)| *t),
97            WindowState::Temporal { rule_hits } => {
98                rule_hits.values().filter_map(|ts| ts.back().copied()).max()
99            }
100            WindowState::NumericAgg { entries } => entries.back().map(|(t, _)| *t),
101        }
102    }
103
104    /// Returns the oldest timestamp in this window, or `None` if empty.
105    ///
106    /// Entries are appended in arrival order, so the front of each deque holds
107    /// the earliest timestamp. For temporal state the minimum is taken across
108    /// all per-rule deques.
109    pub fn earliest_timestamp(&self) -> Option<i64> {
110        match self {
111            WindowState::EventCount { timestamps } => timestamps.front().copied(),
112            WindowState::ValueCount { entries } => entries.front().map(|(t, _)| *t),
113            WindowState::Temporal { rule_hits } => rule_hits
114                .values()
115                .filter_map(|ts| ts.front().copied())
116                .min(),
117            WindowState::NumericAgg { entries } => entries.front().map(|(t, _)| *t),
118        }
119    }
120
121    /// Enforce a per-group entry cap by dropping the oldest entries.
122    ///
123    /// `cap` is the maximum number of retained entries (clamped to at least
124    /// 1). For temporal state the cap applies to each referenced rule's hit
125    /// deque independently, since the deques are what grow with event rate.
126    ///
127    /// When `preserve_front` is set (session windows), the oldest entry is
128    /// kept and truncation happens behind it: the front entry anchors the
129    /// session's total-span cap (`timespan`), so dropping it would silently
130    /// let the session extend past the cap. Truncation can only under-count;
131    /// it never extends a window.
132    pub fn truncate_oldest(&mut self, cap: usize, preserve_front: bool) {
133        let cap = cap.max(1);
134
135        fn truncate_deque<T>(deque: &mut VecDeque<T>, cap: usize, preserve_front: bool) {
136            if deque.len() <= cap {
137                return;
138            }
139            if preserve_front {
140                let anchor = deque.pop_front().expect("len > cap >= 1");
141                // Keep the anchor plus the newest cap - 1 entries.
142                let excess = deque.len() - (cap - 1);
143                deque.drain(..excess);
144                deque.push_front(anchor);
145            } else {
146                let excess = deque.len() - cap;
147                deque.drain(..excess);
148            }
149        }
150
151        match self {
152            WindowState::EventCount { timestamps } => {
153                truncate_deque(timestamps, cap, preserve_front);
154            }
155            WindowState::ValueCount { entries } => {
156                truncate_deque(entries, cap, preserve_front);
157            }
158            WindowState::Temporal { rule_hits } => {
159                for timestamps in rule_hits.values_mut() {
160                    truncate_deque(timestamps, cap, preserve_front);
161                }
162            }
163            WindowState::NumericAgg { entries } => {
164                truncate_deque(entries, cap, preserve_front);
165            }
166        }
167    }
168
169    /// Clear all entries from the window state (used by `CorrelationAction::Reset`).
170    pub fn clear(&mut self) {
171        match self {
172            WindowState::EventCount { timestamps } => timestamps.clear(),
173            WindowState::ValueCount { entries } => entries.clear(),
174            WindowState::Temporal { rule_hits } => rule_hits.clear(),
175            WindowState::NumericAgg { entries } => entries.clear(),
176        }
177    }
178
179    /// Record an event_count hit.
180    pub fn push_event_count(&mut self, ts: i64) {
181        if let WindowState::EventCount { timestamps } = self {
182            timestamps.push_back(ts);
183        }
184    }
185
186    /// Record a value_count hit with the field value.
187    pub fn push_value_count(&mut self, ts: i64, value: String) {
188        if let WindowState::ValueCount { entries } = self {
189            entries.push_back((ts, value));
190        }
191    }
192
193    /// Record a temporal hit for a specific rule reference.
194    pub fn push_temporal(&mut self, ts: i64, rule_ref: &str) {
195        if let WindowState::Temporal { rule_hits } = self {
196            rule_hits
197                .entry(rule_ref.to_string())
198                .or_default()
199                .push_back(ts);
200        }
201    }
202
203    /// Record a numeric aggregation value.
204    pub fn push_numeric(&mut self, ts: i64, value: f64) {
205        if let WindowState::NumericAgg { entries } = self {
206            entries.push_back((ts, value));
207        }
208    }
209
210    /// Evaluate the window state against the correlation condition.
211    ///
212    /// Returns `Some(aggregated_value)` if the condition is satisfied,
213    /// `None` otherwise.
214    ///
215    /// For temporal correlations with an extended expression, the expression
216    /// is evaluated against the set of rules that have fired in the window.
217    pub fn check_condition(
218        &self,
219        condition: &CompiledCondition,
220        corr_type: CorrelationType,
221        rule_refs: &[String],
222        extended_expr: Option<&ConditionExpr>,
223    ) -> Option<f64> {
224        let value = match (self, corr_type) {
225            (WindowState::EventCount { timestamps }, CorrelationType::EventCount) => {
226                timestamps.len() as f64
227            }
228            (WindowState::ValueCount { entries }, CorrelationType::ValueCount) => {
229                // Count distinct values
230                let distinct: HashSet<&String> = entries.iter().map(|(_, v)| v).collect();
231                distinct.len() as f64
232            }
233            (WindowState::Temporal { rule_hits }, CorrelationType::Temporal) => {
234                // If an extended expression is provided, evaluate it
235                if let Some(expr) = extended_expr {
236                    if eval_temporal_expr(expr, rule_hits) {
237                        return Some(count_fired_rules(rule_refs, rule_hits) as f64);
238                    } else {
239                        return None;
240                    }
241                }
242                count_fired_rules(rule_refs, rule_hits) as f64
243            }
244            (WindowState::Temporal { rule_hits }, CorrelationType::TemporalOrdered) => {
245                // If an extended expression is provided, evaluate it first
246                if let Some(expr) = extended_expr
247                    && !eval_temporal_expr(expr, rule_hits)
248                {
249                    return None;
250                }
251                // Check if all referenced rules fired in order
252                if check_temporal_ordered(rule_refs, rule_hits) {
253                    count_distinct_rules(rule_refs) as f64
254                } else {
255                    0.0
256                }
257            }
258            (WindowState::NumericAgg { entries }, CorrelationType::ValueSum) => {
259                entries.iter().map(|(_, v)| v).sum()
260            }
261            (WindowState::NumericAgg { entries }, CorrelationType::ValueAvg) => {
262                if entries.is_empty() {
263                    0.0
264                } else {
265                    let sum: f64 = entries.iter().map(|(_, v)| v).sum();
266                    sum / entries.len() as f64
267                }
268            }
269            (WindowState::NumericAgg { entries }, CorrelationType::ValuePercentile) => {
270                // The value at the condition's percentile rank (0-100), by
271                // linear interpolation; the predicates then apply to it.
272                window_percentile(entries, condition.percentile)?
273            }
274            (WindowState::NumericAgg { entries }, CorrelationType::ValueMedian) => {
275                // An empty window has no median. Returning `0.0` here would
276                // spuriously satisfy predicates like `lte: 0` or `eq: 0`, so
277                // match the percentile branch and skip evaluation.
278                window_median(entries)?
279            }
280            _ => return None, // mismatched state/type
281        };
282
283        if condition.check(value) {
284            Some(value)
285        } else {
286            None
287        }
288    }
289}
290
291impl WindowState {
292    /// Number of retained entries in this window. For temporal state this is
293    /// the total across all per-rule hit deques.
294    pub fn entry_count(&self) -> usize {
295        match self {
296            WindowState::EventCount { timestamps } => timestamps.len(),
297            WindowState::ValueCount { entries } => entries.len(),
298            WindowState::Temporal { rule_hits } => rule_hits.values().map(VecDeque::len).sum(),
299            WindowState::NumericAgg { entries } => entries.len(),
300        }
301    }
302
303    /// Compute the current aggregate value for this window *without* applying
304    /// the correlation's threshold condition.
305    ///
306    /// Unlike [`check_condition`](WindowState::check_condition), which returns
307    /// `None` when the threshold is not met, this returns the raw "got" value
308    /// the introspection surface reports so an operator can see the gap to the
309    /// threshold. Returns `None` only when no value is defined (an empty
310    /// percentile/median window, or a state/type mismatch).
311    pub fn current_value(
312        &self,
313        corr_type: CorrelationType,
314        rule_refs: &[String],
315        percentile: Option<u64>,
316    ) -> Option<f64> {
317        match (self, corr_type) {
318            (WindowState::EventCount { timestamps }, CorrelationType::EventCount) => {
319                Some(timestamps.len() as f64)
320            }
321            (WindowState::ValueCount { entries }, CorrelationType::ValueCount) => {
322                let distinct: HashSet<&String> = entries.iter().map(|(_, v)| v).collect();
323                Some(distinct.len() as f64)
324            }
325            (
326                WindowState::Temporal { rule_hits },
327                CorrelationType::Temporal | CorrelationType::TemporalOrdered,
328            ) => Some(count_fired_rules(rule_refs, rule_hits) as f64),
329            (WindowState::NumericAgg { entries }, CorrelationType::ValueSum) => {
330                Some(entries.iter().map(|(_, v)| v).sum())
331            }
332            (WindowState::NumericAgg { entries }, CorrelationType::ValueAvg) => {
333                if entries.is_empty() {
334                    Some(0.0)
335                } else {
336                    let sum: f64 = entries.iter().map(|(_, v)| v).sum();
337                    Some(sum / entries.len() as f64)
338                }
339            }
340            (WindowState::NumericAgg { entries }, CorrelationType::ValuePercentile) => {
341                window_percentile(entries, percentile)
342            }
343            (WindowState::NumericAgg { entries }, CorrelationType::ValueMedian) => {
344                window_median(entries)
345            }
346            _ => None,
347        }
348    }
349}
350
351/// Start of the tumbling bucket that contains `ts`, aligned to epoch.
352///
353/// Uses `rem_euclid` so negative timestamps align to the bucket below them
354/// rather than toward zero.
355fn bucket_start(ts: i64, timespan: i64) -> i64 {
356    ts - ts.rem_euclid(timespan)
357}
358
359/// Outcome of a window's pre-insert maintenance for a new event.
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361pub enum WindowDecision {
362    /// The current window continues; push the event into it.
363    Extend,
364    /// The window rolled over and the state was cleared; push the event into
365    /// the fresh window. Callers must also clear any associated event buffers
366    /// so they stay in sync with the state.
367    Reset,
368    /// The event predates the current window (a late arrival in an earlier
369    /// tumbling bucket); do not push it and leave the state untouched.
370    Discard,
371}
372
373/// Apply a correlation window's pre-insert maintenance for a new event at `ts`,
374/// before the event is pushed into `state`.
375///
376/// - `Sliding` evicts entries older than `ts - timespan` (the existing default)
377///   and always extends.
378/// - `Tumbling` resets the window when `ts` falls in a *later*
379///   boundary-aligned bucket than the latest retained entry, and discards
380///   events that fall in an *earlier* bucket (a late arrival must not wipe the
381///   active bucket's accumulation).
382/// - `Session` resets when `ts` is more than `gap` after the latest entry, or
383///   when extending would push the total span past `timespan` (the hard cap).
384///
385/// Out-of-order arrivals follow the engine's arrival-order contract: decisions
386/// are made relative to the entries currently retained, not a global watermark.
387pub fn apply_window_open(
388    state: &mut WindowState,
389    ts: i64,
390    timespan_secs: u64,
391    window: WindowMode,
392    gap_secs: Option<u64>,
393) -> WindowDecision {
394    let timespan = timespan_secs as i64;
395    match window {
396        WindowMode::Sliding => {
397            state.evict(ts - timespan);
398            WindowDecision::Extend
399        }
400        WindowMode::Tumbling => {
401            if timespan <= 0 {
402                return WindowDecision::Extend;
403            }
404            match state.latest_timestamp() {
405                Some(last) if bucket_start(ts, timespan) > bucket_start(last, timespan) => {
406                    state.clear();
407                    WindowDecision::Reset
408                }
409                Some(last) if bucket_start(ts, timespan) < bucket_start(last, timespan) => {
410                    WindowDecision::Discard
411                }
412                _ => WindowDecision::Extend,
413            }
414        }
415        WindowMode::Session => {
416            // `gap` is required for session windows; fall back to `timespan` if
417            // it is somehow absent so the window still has a bound.
418            let gap = gap_secs.map(|g| g as i64).unwrap_or(timespan);
419            let reset = match (state.earliest_timestamp(), state.latest_timestamp()) {
420                (Some(start), Some(last)) => {
421                    (ts - last) > gap || (timespan > 0 && (ts - start) > timespan)
422                }
423                _ => false,
424            };
425            if reset {
426                state.clear();
427                WindowDecision::Reset
428            } else {
429                WindowDecision::Extend
430            }
431        }
432    }
433}
434
435/// Number of distinct rule references, so a rule listed twice in `rules`
436/// counts once.
437fn count_distinct_rules(rule_refs: &[String]) -> usize {
438    rule_refs.iter().collect::<HashSet<_>>().len()
439}
440
441/// Number of distinct referenced rules with at least one hit in the window.
442fn count_fired_rules(rule_refs: &[String], rule_hits: &HashMap<String, VecDeque<i64>>) -> usize {
443    rule_refs
444        .iter()
445        .filter(|r| rule_hits.get(r.as_str()).is_some_and(|ts| !ts.is_empty()))
446        .collect::<HashSet<_>>()
447        .len()
448}
449
450/// Check if all referenced rules fired in the correct order within the window.
451///
452/// For `temporal_ordered`, each rule must have at least one hit, and there
453/// must exist a sequence of timestamps (one per rule) that is non-decreasing
454/// and follows the rule ordering.
455///
456/// Taking the earliest hit at or after the previous rule's choice is enough:
457/// any valid sequence can swap in that earlier hit and stay valid, so the
458/// check is one pass over each rule's hits.
459pub(super) fn check_temporal_ordered(
460    rule_refs: &[String],
461    rule_hits: &HashMap<String, VecDeque<i64>>,
462) -> bool {
463    let mut previous = i64::MIN;
464    for rule_ref in rule_refs {
465        let earliest = rule_hits
466            .get(rule_ref.as_str())
467            .and_then(|hits| hits.iter().copied().filter(|&ts| ts >= previous).min());
468        match earliest {
469            Some(ts) => previous = ts,
470            None => return false,
471        }
472    }
473    true
474}
475
476/// Evaluate a boolean condition expression against the set of rules that have
477/// fired within the temporal window.
478///
479/// Each `Identifier` in the expression is treated as a rule reference — it's
480/// `true` if that rule has at least one hit in `rule_hits`.
481pub(super) fn eval_temporal_expr(
482    expr: &ConditionExpr,
483    rule_hits: &HashMap<String, VecDeque<i64>>,
484) -> bool {
485    match expr {
486        ConditionExpr::Identifier(name) => rule_hits
487            .get(name.as_str())
488            .is_some_and(|ts| !ts.is_empty()),
489        ConditionExpr::And(children) => children.iter().all(|c| eval_temporal_expr(c, rule_hits)),
490        ConditionExpr::Or(children) => children.iter().any(|c| eval_temporal_expr(c, rule_hits)),
491        ConditionExpr::Not(child) => !eval_temporal_expr(child, rule_hits),
492        ConditionExpr::Selector { .. } => {
493            // Selectors are not meaningful for temporal condition evaluation
494            false
495        }
496    }
497}
498
499/// The window's finite values, in arrival order.
500fn finite_values(entries: &VecDeque<(i64, f64)>) -> Vec<f64> {
501    entries
502        .iter()
503        .map(|(_, v)| *v)
504        .filter(|v| v.is_finite())
505        .collect()
506}
507
508/// Value at `percentile` (default 50) across the window's finite values, or
509/// `None` when there are none.
510fn window_percentile(entries: &VecDeque<(i64, f64)>, percentile: Option<u64>) -> Option<f64> {
511    let mut values = finite_values(entries);
512    if values.is_empty() {
513        return None;
514    }
515    let rank = percentile.map(|p| p as f64).unwrap_or(50.0);
516    Some(percentile_linear_interp(&mut values, rank))
517}
518
519/// Median of the window's finite values, averaging the two middle values for
520/// an even count, or `None` when there are none.
521fn window_median(entries: &VecDeque<(i64, f64)>) -> Option<f64> {
522    let mut values = finite_values(entries);
523    let n = values.len();
524    if n == 0 {
525        return None;
526    }
527    let (below, &mut upper, _) = values.select_nth_unstable_by(n / 2, f64::total_cmp);
528    if n.is_multiple_of(2) {
529        let lower = below.iter().copied().max_by(f64::total_cmp)?;
530        Some((lower + upper) / 2.0)
531    } else {
532        Some(upper)
533    }
534}
535
536/// Compute the value at a given percentile rank using linear interpolation.
537///
538/// Returns 0.0 if `values` is empty. `values` may be in any order and is
539/// partially reordered in place, which keeps this O(n) on average instead of
540/// a full sort per evaluation.
541/// `percentile` is from 0.0 to 100.0.
542pub(super) fn percentile_linear_interp(values: &mut [f64], percentile: f64) -> f64 {
543    if values.is_empty() {
544        return 0.0;
545    }
546    let n = values.len();
547    if n == 1 {
548        return values[0];
549    }
550
551    // Clamp percentile to [0, 100]
552    let p = percentile.clamp(0.0, 100.0) / 100.0;
553
554    // Use the "C = 1" interpolation method (most common in statistics)
555    // rank = p * (n - 1)
556    let rank = p * (n - 1) as f64;
557    let lower = rank.floor() as usize;
558    let upper = rank.ceil() as usize;
559    let fraction = rank - lower as f64;
560
561    let (_, &mut low, above) = values.select_nth_unstable_by(lower.min(n - 1), f64::total_cmp);
562    if lower == upper || upper >= n {
563        low
564    } else {
565        // `above` holds every value ordered after `low`, so its minimum is
566        // the next value in sorted order.
567        let high = above.iter().copied().min_by(f64::total_cmp).unwrap_or(low);
568        low + fraction * (high - low)
569    }
570}