Skip to main content

rsigma_eval/correlation_engine/
mod.rs

1//! Stateful correlation engine with time-windowed aggregation.
2//!
3//! `CorrelationEngine` wraps the stateless `Engine` and adds support for
4//! Sigma correlation rules: `event_count`, `value_count`, `temporal`,
5//! `temporal_ordered`, `value_sum`, `value_avg`, `value_percentile`,
6//! and `value_median`.
7//!
8//! # Architecture
9//!
10//! 1. Events are first evaluated against detection rules (stateless)
11//! 2. Detection matches update correlation window state (stateful)
12//! 3. When a correlation condition is met, a `CorrelationResult` is emitted
13//! 4. Correlation results can chain into higher-level correlations
14
15mod introspect;
16#[cfg(test)]
17mod tests;
18mod types;
19
20pub use introspect::{CorrelationInfo, CorrelationStateSnapshot, GroupKeyPart, GroupStateInfo};
21pub use types::*;
22
23use std::borrow::Cow;
24use std::collections::HashMap;
25
26use chrono::Utc;
27
28use rsigma_parser::{CorrelationRule, CorrelationType, SigmaCollection, SigmaRule, WindowMode};
29
30use crate::correlation::{
31    CompiledCorrelation, EventBuffer, EventRefBuffer, GroupKey, WindowDecision, WindowState,
32    apply_window_open, compile_correlation,
33};
34use crate::engine::{Engine, IdentifiedEvaluation};
35use crate::error::{EvalError, Result};
36use crate::event::{Event, EventValue};
37use crate::logsource::{ExtractLogSource, LogSourceExtractor};
38use crate::pipeline::{Pipeline, apply_pipelines, apply_pipelines_to_correlation};
39use crate::result::{CorrelationBody, EvaluationResult, ResultBody, RuleHeader};
40use crate::rule_metadata::{RuleBundleMetadata, RuleMetadataLookup};
41use crate::timestamp::{epoch_seconds_from_float, epoch_seconds_from_int, parse_timestamp_str};
42
43type RuleIdentity = (Option<String>, Option<String>);
44
45// =============================================================================
46// Correlation Engine
47// =============================================================================
48
49/// Current snapshot schema version. Bump when the serialized format changes.
50const SNAPSHOT_VERSION: u32 = 1;
51
52/// Parent hops evaluated after a first-level correlation fire in one event.
53/// The first-level result is produced by `feed_detections`; each loop
54/// iteration here walks one parent. A chain longer than this is updated
55/// and emitted through this many hops, then leftover parents are dropped
56/// with a `WARN`.
57const MAX_CHAIN_DEPTH: usize = 10;
58
59/// Timespan above which a correlation without a per-group entry cap is
60/// warned about at load: a busy group's window retains `timespan` x event
61/// rate entries, which `max_state_entries` does not see.
62const LONG_WINDOW_WARN_SECS: u64 = 3600;
63
64/// Stateful correlation engine.
65///
66/// Wraps the stateless `Engine` for detection rules and adds time-windowed
67/// correlation on top. Supports all 7 Sigma correlation types and chaining.
68///
69/// Generic over the inner engine's logsource extractor `L`, which defaults to
70/// [`LogSourceExtractor`] (see [`Engine`]).
71pub struct CorrelationEngine<L = LogSourceExtractor> {
72    /// Inner stateless detection engine.
73    engine: Engine<L>,
74    /// Compiled correlation rules.
75    correlations: Vec<CompiledCorrelation>,
76    /// Maps rule ID/name -> indices into `correlations` that reference it.
77    /// This allows quick lookup: "which correlations care about rule X?"
78    rule_index: HashMap<String, Vec<usize>>,
79    /// Maps detection rule index -> (rule_id, rule_name, rule_title) for reverse lookup.
80    /// Used to find which correlations a detection match triggers.
81    rule_ids: Vec<(Option<String>, Option<String>, String)>,
82    /// Per-(correlation_index, group_key) window state.
83    state: HashMap<(usize, GroupKey), WindowState>,
84    /// Last alert timestamp per (correlation_index, group_key) for suppression.
85    last_alert: HashMap<(usize, GroupKey), i64>,
86    /// Per-(correlation_index, group_key) compressed event buffer (`Full` mode).
87    event_buffers: HashMap<(usize, GroupKey), EventBuffer>,
88    /// Per-(correlation_index, group_key) event reference buffer (`Refs` mode).
89    event_ref_buffers: HashMap<(usize, GroupKey), EventRefBuffer>,
90    /// Set of rule IDs/names (detections or correlations) that are
91    /// "correlation-only" (referenced by correlations where `generate == false`).
92    /// Used to filter their output when `config.emit_detections == false`.
93    correlation_only_rules: std::collections::HashSet<String>,
94    /// Rules referenced by at least one correlation with `generate: true`.
95    /// Such a reference wins over correlation-only references.
96    generated_rules: std::collections::HashSet<String>,
97    /// Configuration.
98    config: CorrelationConfig,
99    /// Processing pipelines applied to rules during add_rule.
100    pipelines: Vec<Pipeline>,
101}
102
103impl CorrelationEngine {
104    /// Create a new correlation engine with the given configuration.
105    pub fn new(config: CorrelationConfig) -> Self {
106        Self::with_engine(config, Engine::new())
107    }
108}
109
110impl<L> CorrelationEngine<L> {
111    /// Create a new correlation engine whose inner detection engine prunes
112    /// with `extractor`, a custom [`ExtractLogSource`] implementation.
113    pub fn with_logsource_extractor(config: CorrelationConfig, extractor: L) -> Self {
114        Self::with_engine(config, Engine::with_logsource_extractor(extractor))
115    }
116
117    fn with_engine(config: CorrelationConfig, engine: Engine<L>) -> Self {
118        CorrelationEngine {
119            engine,
120            correlations: Vec::new(),
121            rule_index: HashMap::new(),
122            rule_ids: Vec::new(),
123            state: HashMap::new(),
124            last_alert: HashMap::new(),
125            event_buffers: HashMap::new(),
126            event_ref_buffers: HashMap::new(),
127            correlation_only_rules: std::collections::HashSet::new(),
128            generated_rules: std::collections::HashSet::new(),
129            config,
130            pipelines: Vec::new(),
131        }
132    }
133
134    /// Add a pipeline to the engine.
135    ///
136    /// Pipelines are applied to rules during `add_rule` / `add_collection`.
137    pub fn add_pipeline(&mut self, pipeline: Pipeline) {
138        self.pipelines.push(pipeline);
139        self.pipelines.sort_by_key(|p| p.priority);
140    }
141
142    /// Set global `include_event` on the inner detection engine.
143    pub fn set_include_event(&mut self, include: bool) {
144        self.engine.set_include_event(include);
145    }
146
147    /// Forward to [`crate::Engine::set_match_detail`] on the inner detection
148    /// engine. Correlation detections inherit the level set here.
149    pub fn set_match_detail(&mut self, level: crate::result::MatchDetailLevel) {
150        self.engine.set_match_detail(level);
151    }
152
153    /// Forward to [`crate::Engine::set_bloom_prefilter`] on the inner
154    /// detection engine. Off by default; the optimization helps only on
155    /// substring-heavy rule sets paired with mostly-non-matching events.
156    pub fn set_bloom_prefilter(&mut self, enabled: bool) {
157        self.engine.set_bloom_prefilter(enabled);
158    }
159
160    /// Forward to [`crate::Engine::set_logsource_extractor`] on the inner
161    /// detection engine. Correlation inherits logsource pruning, since
162    /// `process_event` evaluates through this engine.
163    pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
164        self.engine.set_logsource_extractor(extractor);
165    }
166
167    /// Total rule candidates pruned by logsource on the inner engine.
168    pub fn logsource_pruned_total(&self) -> u64 {
169        self.engine.logsource_pruned_total()
170    }
171
172    /// Total evaluate calls with no extractable event logsource (fail-open).
173    pub fn logsource_absent_total(&self) -> u64 {
174        self.engine.logsource_absent_total()
175    }
176
177    /// Forward to [`crate::Engine::set_bloom_max_bytes`] on the inner
178    /// detection engine.
179    pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
180        self.engine.set_bloom_max_bytes(max_bytes);
181    }
182
183    /// Forward to [`crate::Engine::set_cross_rule_ac`] on the inner
184    /// detection engine. Off by default. Available behind the
185    /// `daachorse-index` Cargo feature.
186    #[cfg(feature = "daachorse-index")]
187    pub fn set_cross_rule_ac(&mut self, enabled: bool) {
188        self.engine.set_cross_rule_ac(enabled);
189    }
190
191    /// Set the global correlation event mode.
192    ///
193    /// - `None`: no event storage (default)
194    /// - `Full`: compressed event bodies
195    /// - `Refs`: lightweight timestamp + ID references
196    pub fn set_correlation_event_mode(&mut self, mode: CorrelationEventMode) {
197        self.config.correlation_event_mode = mode;
198    }
199
200    /// Set the maximum number of events to store per correlation window group.
201    /// Only meaningful when `correlation_event_mode` is not `None`.
202    pub fn set_max_correlation_events(&mut self, max: usize) {
203        self.config.max_correlation_events = max;
204    }
205
206    /// Add a single detection rule.
207    ///
208    /// If pipelines are set, the rule is cloned and transformed before compilation.
209    /// The inner engine receives the already-transformed rule directly (not through
210    /// its own pipeline, to avoid double transformation).
211    pub fn add_rule(&mut self, rule: &SigmaRule) -> Result<()> {
212        if self.pipelines.is_empty() {
213            self.apply_custom_attributes(&rule.custom_attributes);
214            self.rule_ids
215                .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
216            self.engine.add_rule(rule)?;
217        } else {
218            let mut transformed = rule.clone();
219            apply_pipelines(&self.pipelines, &mut transformed)?;
220            self.apply_custom_attributes(&transformed.custom_attributes);
221            self.rule_ids.push((
222                transformed.id.clone(),
223                transformed.name.clone(),
224                transformed.title.clone(),
225            ));
226            // Use compile_rule + add_compiled_rule to bypass inner engine's pipelines
227            let compiled = crate::compiler::compile_rule(&transformed)?;
228            self.engine.add_compiled_rule(compiled);
229        }
230        Ok(())
231    }
232
233    /// Read `rsigma.*` custom attributes from a rule and apply them to the
234    /// engine configuration.  This allows pipelines to influence engine
235    /// behaviour via `SetCustomAttribute` transformations — the same pattern
236    /// used by pySigma backends (e.g. pySigma-backend-loki).
237    ///
238    /// Supported attributes:
239    /// - `rsigma.timestamp_field` — prepends a field name to the timestamp
240    ///   extraction priority list so the correlation engine can find the
241    ///   event timestamp in non-standard field names.
242    /// - `rsigma.suppress` — sets the default suppression window (e.g. `5m`).
243    ///   Only applied when the CLI did not already set `--suppress`.
244    /// - `rsigma.action` — sets the default post-fire action (`alert`/`reset`).
245    ///   Only applied when the CLI did not already set `--action`.
246    fn apply_custom_attributes(
247        &mut self,
248        attrs: &std::collections::HashMap<String, yaml_serde::Value>,
249    ) {
250        // rsigma.timestamp_field — prepend to priority list, skip duplicates
251        if let Some(field) = attrs.get("rsigma.timestamp_field").and_then(|v| v.as_str())
252            && !self.config.timestamp_fields.iter().any(|f| f == field)
253        {
254            self.config.timestamp_fields.insert(0, field.to_string());
255        }
256
257        // rsigma.suppress — only when CLI didn't already set one
258        if let Some(val) = attrs.get("rsigma.suppress").and_then(|v| v.as_str())
259            && self.config.suppress.is_none()
260            && let Ok(ts) = rsigma_parser::Timespan::parse(val)
261        {
262            self.config.suppress = Some(ts.seconds);
263        }
264
265        // rsigma.action — only when CLI left it at the default (Alert)
266        if let Some(val) = attrs.get("rsigma.action").and_then(|v| v.as_str())
267            && self.config.action_on_match == CorrelationAction::Alert
268            && let Ok(a) = val.parse::<CorrelationAction>()
269        {
270            self.config.action_on_match = a;
271        }
272    }
273
274    /// Add a single correlation rule.
275    pub fn add_correlation(&mut self, corr: &CorrelationRule) -> Result<()> {
276        let owned;
277        let effective = if self.pipelines.is_empty() {
278            corr
279        } else {
280            owned = {
281                let mut c = corr.clone();
282                apply_pipelines_to_correlation(&self.pipelines, &mut c)?;
283                c
284            };
285            &owned
286        };
287
288        // Apply engine-level custom attributes from the (possibly transformed)
289        // correlation rule (e.g. rsigma.timestamp_field).
290        self.apply_custom_attributes(&effective.custom_attributes);
291
292        let compiled = compile_correlation(effective)?;
293        if self.has_unbounded_long_window(&compiled) {
294            log::warn!(
295                "Correlation '{}' has a {}s timespan and no per-group entry cap; \
296                 a busy group retains timespan x event rate entries. \
297                 Set max_group_entries (--max-group-entries) or the rsigma.max_group_entries attribute to bound it.",
298                compiled.id.as_deref().unwrap_or(&compiled.title),
299                compiled.timespan_secs
300            );
301        }
302        let idx = self.correlations.len();
303
304        // Index by each referenced rule ID/name
305        for rule_ref in &compiled.rule_refs {
306            self.rule_index
307                .entry(rule_ref.clone())
308                .or_default()
309                .push(idx);
310        }
311
312        // A rule is standalone when any referencing correlation requests it,
313        // regardless of the order in which correlations are loaded.
314        for rule_ref in &compiled.rule_refs {
315            if compiled.generate {
316                self.generated_rules.insert(rule_ref.clone());
317                self.correlation_only_rules.remove(rule_ref);
318            } else if !self.generated_rules.contains(rule_ref) {
319                self.correlation_only_rules.insert(rule_ref.clone());
320            }
321        }
322
323        self.correlations.push(compiled);
324        Ok(())
325    }
326
327    /// Whether `corr` keeps a window longer than [`LONG_WINDOW_WARN_SECS`]
328    /// with no per-group entry cap from the rule or the engine config.
329    fn has_unbounded_long_window(&self, corr: &CompiledCorrelation) -> bool {
330        corr.timespan_secs > LONG_WINDOW_WARN_SECS
331            && corr
332                .max_group_entries
333                .or(self.config.max_group_entries)
334                .is_none()
335    }
336
337    /// Add all rules and correlations from a parsed collection.
338    ///
339    /// Detection rules are added first (so they're available for correlation
340    /// references), then correlation rules. Detection rules are compiled
341    /// sequentially and then pushed to the inner engine in a single batch,
342    /// so the inverted index and bloom filter are rebuilt exactly once for
343    /// the whole collection. Without this batching, large rule sets
344    /// (multi-thousand rules) hit an O(N²) rebuild cost on load.
345    pub fn add_collection(&mut self, collection: &SigmaCollection) -> Result<()> {
346        let mut compiled_batch = Vec::with_capacity(collection.rules.len());
347        if self.pipelines.is_empty() {
348            for rule in &collection.rules {
349                self.apply_custom_attributes(&rule.custom_attributes);
350                self.rule_ids
351                    .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
352                compiled_batch.push(crate::compiler::compile_rule(rule)?);
353            }
354        } else {
355            for rule in &collection.rules {
356                let mut transformed = rule.clone();
357                apply_pipelines(&self.pipelines, &mut transformed)?;
358                self.apply_custom_attributes(&transformed.custom_attributes);
359                self.rule_ids.push((
360                    transformed.id.clone(),
361                    transformed.name.clone(),
362                    transformed.title.clone(),
363                ));
364                // Bypass the inner engine's pipelines (would double-transform)
365                compiled_batch.push(crate::compiler::compile_rule(&transformed)?);
366            }
367        }
368        self.engine.extend_compiled_rules(compiled_batch);
369        // Apply filter rules to the inner engine's detection rules
370        for filter in &collection.filters {
371            self.engine.apply_filter(filter)?;
372        }
373        for corr in &collection.correlations {
374            self.add_correlation(corr)?;
375        }
376        self.validate_rule_refs()?;
377        self.detect_correlation_cycles()?;
378        Ok(())
379    }
380
381    /// Validate that every correlation's `rule_refs` resolve to at least one
382    /// known detection rule (by ID or name) or another correlation (by ID or name).
383    fn validate_rule_refs(&self) -> Result<()> {
384        let mut known: std::collections::HashSet<&str> = std::collections::HashSet::new();
385
386        for (id, name, _) in &self.rule_ids {
387            if let Some(id) = id {
388                known.insert(id.as_str());
389            }
390            if let Some(name) = name {
391                known.insert(name.as_str());
392            }
393        }
394        for corr in &self.correlations {
395            if let Some(ref id) = corr.id {
396                known.insert(id.as_str());
397            }
398            if let Some(ref name) = corr.name {
399                known.insert(name.as_str());
400            }
401        }
402
403        for corr in &self.correlations {
404            for rule_ref in &corr.rule_refs {
405                if !known.contains(rule_ref.as_str()) {
406                    return Err(EvalError::UnknownRuleRef(rule_ref.clone()));
407                }
408            }
409        }
410        Ok(())
411    }
412
413    /// Detect cycles in the correlation reference graph.
414    ///
415    /// Builds a directed graph where each correlation (identified by its id/name)
416    /// has edges to the correlations it references via `rule_refs`. Uses DFS with
417    /// a "gray/black" coloring scheme to detect back-edges (cycles).
418    ///
419    /// Returns `Err(EvalError::CorrelationCycle)` if a cycle is found.
420    fn detect_correlation_cycles(&self) -> Result<()> {
421        // Build a set of all correlation identifiers (id and/or name)
422        let mut corr_identifiers: HashMap<&str, usize> = HashMap::new();
423        for (idx, corr) in self.correlations.iter().enumerate() {
424            if let Some(ref id) = corr.id {
425                corr_identifiers.insert(id.as_str(), idx);
426            }
427            if let Some(ref name) = corr.name {
428                corr_identifiers.insert(name.as_str(), idx);
429            }
430        }
431
432        // Build adjacency list: corr index → set of corr indices it references
433        let mut adj: Vec<Vec<usize>> = vec![Vec::new(); self.correlations.len()];
434        for (idx, corr) in self.correlations.iter().enumerate() {
435            for rule_ref in &corr.rule_refs {
436                if let Some(&target_idx) = corr_identifiers.get(rule_ref.as_str()) {
437                    adj[idx].push(target_idx);
438                }
439            }
440        }
441
442        // DFS cycle detection with three states: white (unvisited), gray (in stack), black (done)
443        let mut state = vec![0u8; self.correlations.len()]; // 0=white, 1=gray, 2=black
444        let mut path: Vec<usize> = Vec::new();
445
446        for start in 0..self.correlations.len() {
447            if state[start] == 0
448                && let Some(cycle) = Self::dfs_find_cycle(start, &adj, &mut state, &mut path)
449            {
450                let names: Vec<String> = cycle
451                    .iter()
452                    .map(|&i| {
453                        self.correlations[i]
454                            .id
455                            .as_deref()
456                            .or(self.correlations[i].name.as_deref())
457                            .unwrap_or(&self.correlations[i].title)
458                            .to_string()
459                    })
460                    .collect();
461                return Err(crate::error::EvalError::CorrelationCycle(
462                    names.join(" -> "),
463                ));
464            }
465        }
466        Ok(())
467    }
468
469    /// DFS helper that returns the cycle path if a back-edge is found.
470    fn dfs_find_cycle(
471        node: usize,
472        adj: &[Vec<usize>],
473        state: &mut [u8],
474        path: &mut Vec<usize>,
475    ) -> Option<Vec<usize>> {
476        state[node] = 1; // gray
477        path.push(node);
478
479        for &next in &adj[node] {
480            if state[next] == 1 {
481                // Back-edge found — extract cycle from path
482                if let Some(pos) = path.iter().position(|&n| n == next) {
483                    let mut cycle = path[pos..].to_vec();
484                    cycle.push(next); // close the cycle
485                    return Some(cycle);
486                }
487            }
488            if state[next] == 0
489                && let Some(cycle) = Self::dfs_find_cycle(next, adj, state, path)
490            {
491                return Some(cycle);
492            }
493        }
494
495        path.pop();
496        state[node] = 2; // black
497        None
498    }
499
500    /// Process an event, extracting the timestamp from configured event fields.
501    ///
502    /// When no timestamp field is found, the `timestamp_fallback` policy applies:
503    /// - `WallClock`: use `Utc::now()` (good for real-time streaming)
504    /// - `Skip`: return detections only, skip correlation state updates
505    pub fn process_event<E: Event>(&mut self, event: &E) -> ProcessResult
506    where
507        L: ExtractLogSource<E>,
508    {
509        let detections = self.engine.evaluate_identified(event);
510        self.correlate_identified_detections(event, detections)
511    }
512
513    /// Run the correlation layer over externally-produced detections.
514    ///
515    /// Like [`process_event`](Self::process_event) but the detections are
516    /// supplied by the caller instead of computed by this engine's inner
517    /// detection engine. This lets a multi-engine router run detection in a
518    /// per-schema engine and still feed every detection into one shared
519    /// correlation store. Timestamp extraction and the `timestamp_fallback`
520    /// policy match `process_event`. Rule identity is recovered as in
521    /// [`process_with_detections`](Self::process_with_detections).
522    pub fn correlate_detections(
523        &mut self,
524        event: &impl Event,
525        all_detections: Vec<EvaluationResult>,
526    ) -> ProcessResult {
527        let identities = all_detections
528            .iter()
529            .map(|detection| self.find_rule_identity(detection))
530            .collect();
531        self.correlate_with_identities(event, all_detections, identities)
532    }
533
534    pub(crate) fn correlate_identified_detections(
535        &mut self,
536        event: &impl Event,
537        detections: Vec<IdentifiedEvaluation>,
538    ) -> ProcessResult {
539        let (all_detections, identities) = split_identified(detections);
540        self.correlate_with_identities(event, all_detections, identities)
541    }
542
543    fn correlate_with_identities(
544        &mut self,
545        event: &impl Event,
546        all_detections: Vec<EvaluationResult>,
547        identities: Vec<RuleIdentity>,
548    ) -> ProcessResult {
549        let ts = match self.extract_event_timestamp(event) {
550            Some(ts) => ts,
551            None => match self.config.timestamp_fallback {
552                TimestampFallback::WallClock => Utc::now().timestamp(),
553                TimestampFallback::Skip => {
554                    // Still surface detections, but skip correlation state.
555                    return self.filter_detections(all_detections, identities);
556                }
557            },
558        };
559        self.process_with_detection_identities(event, all_detections, identities, ts)
560    }
561
562    /// Process an event with an explicit Unix epoch timestamp (seconds).
563    ///
564    /// The timestamp is clamped to `[0, i64::MAX / 2]` to prevent overflow
565    /// when adding timespan durations internally.
566    pub fn process_event_at<E: Event>(&mut self, event: &E, timestamp_secs: i64) -> ProcessResult
567    where
568        L: ExtractLogSource<E>,
569    {
570        let detections = self.engine.evaluate_identified(event);
571        let (all_detections, identities) = split_identified(detections);
572        self.process_with_detection_identities(event, all_detections, identities, timestamp_secs)
573    }
574
575    /// Process an event with pre-computed detection results.
576    ///
577    /// Enables external parallelism: callers can run detection (via
578    /// [`evaluate`](Self::evaluate)) in parallel, then feed results here
579    /// sequentially for stateful correlation.
580    ///
581    /// A result carries its rule's `id` but not its `name`, so a detection
582    /// from a rule without an `id` is matched to its rule by title and feeds
583    /// no correlation when several such rules share that title.
584    /// [`process_event_at`](Self::process_event_at) and
585    /// [`process_batch`](Self::process_batch) keep the compiled identity.
586    pub fn process_with_detections(
587        &mut self,
588        event: &impl Event,
589        all_detections: Vec<EvaluationResult>,
590        timestamp_secs: i64,
591    ) -> ProcessResult {
592        let identities = all_detections
593            .iter()
594            .map(|detection| self.find_rule_identity(detection))
595            .collect();
596        self.process_with_detection_identities(event, all_detections, identities, timestamp_secs)
597    }
598
599    fn process_with_detection_identities(
600        &mut self,
601        event: &impl Event,
602        all_detections: Vec<EvaluationResult>,
603        identities: Vec<RuleIdentity>,
604        timestamp_secs: i64,
605    ) -> ProcessResult {
606        let timestamp_secs = timestamp_secs.clamp(0, i64::MAX / 2);
607
608        // Memory management — evict before adding new state to enforce limit
609        if self.state.len() >= self.config.max_state_entries {
610            self.evict_all(timestamp_secs);
611        }
612
613        // Feed detection matches into correlations
614        let mut correlations: Vec<EvaluationResult> = Vec::new();
615        let mut fired_indices = Vec::new();
616        self.feed_detections(
617            event,
618            &identities,
619            timestamp_secs,
620            &mut correlations,
621            &mut fired_indices,
622        );
623
624        // Chain — parent firings go into a separate vec so we do not
625        // alias `correlations` as both the input slice and the output.
626        let mut chained = Vec::new();
627        let mut chained_indices = Vec::new();
628        self.chain_correlations(
629            &correlations,
630            &fired_indices,
631            timestamp_secs,
632            &mut chained,
633            &mut chained_indices,
634        );
635        correlations.extend(chained);
636        fired_indices.extend(chained_indices);
637
638        // Filter detections and correlations by the generate flag of the
639        // correlations that reference them.
640        let mut out = self.filter_detections(all_detections, identities);
641        out.extend(
642            correlations
643                .into_iter()
644                .zip(fired_indices)
645                .filter(|(_, idx)| {
646                    let corr = &self.correlations[*idx];
647                    let identities = corr.id.as_deref().into_iter().chain(corr.name.as_deref());
648                    !self.is_correlation_only(identities)
649                })
650                .map(|(result, _)| result),
651        );
652        out
653    }
654
655    /// Run stateless detection only (no correlation), delegating to the inner engine.
656    ///
657    /// Returns one [`EvaluationResult`] per matched detection. Takes `&self`
658    /// so it can be called concurrently from multiple threads (e.g. via
659    /// `rayon::par_iter`) while the mutable correlation phase runs
660    /// sequentially afterwards.
661    pub fn evaluate<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
662    where
663        L: ExtractLogSource<E>,
664    {
665        self.engine.evaluate(event)
666    }
667
668    /// Process a batch of events: parallel detection, then sequential correlation.
669    ///
670    /// When the `parallel` feature is enabled, the stateless detection phase runs
671    /// concurrently via rayon. Timestamp extraction also runs in the parallel
672    /// phase (it borrows `&self.config` immutably). After `collect()` releases the
673    /// immutable borrows, each event's pre-computed detections are fed into the
674    /// stateful correlation engine sequentially.
675    pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult>
676    where
677        L: ExtractLogSource<E> + Sync,
678    {
679        // Borrow split: take immutable refs to fields needed for the parallel phase.
680        // These are released by collect() before the sequential &mut self phase.
681        let engine = &self.engine;
682        let ts_fields = &self.config.timestamp_fields;
683
684        let batch_results: Vec<(Vec<IdentifiedEvaluation>, Option<i64>)> = {
685            #[cfg(feature = "parallel")]
686            {
687                use rayon::prelude::*;
688                events
689                    .par_iter()
690                    .map(|e| {
691                        let detections = engine.evaluate_identified(e);
692                        let ts = extract_event_ts(e, ts_fields);
693                        (detections, ts)
694                    })
695                    .collect()
696            }
697            #[cfg(not(feature = "parallel"))]
698            {
699                events
700                    .iter()
701                    .map(|e| {
702                        let detections = engine.evaluate_identified(e);
703                        let ts = extract_event_ts(e, ts_fields);
704                        (detections, ts)
705                    })
706                    .collect()
707            }
708        };
709
710        // Sequential correlation phase
711        let mut results = Vec::with_capacity(events.len());
712        for ((identified, ts_opt), event) in batch_results.into_iter().zip(events) {
713            let (detections, identities) = split_identified(identified);
714            let ts = match ts_opt {
715                Some(ts) => ts,
716                None => match self.config.timestamp_fallback {
717                    TimestampFallback::WallClock => Utc::now().timestamp(),
718                    TimestampFallback::Skip => {
719                        // Still return detection results, but skip correlation
720                        results.push(self.filter_detections(detections, identities));
721                        continue;
722                    }
723                },
724            };
725            results.push(self.process_with_detection_identities(event, detections, identities, ts));
726        }
727        results
728    }
729
730    /// Filter detections by the `generate` flag / `emit_detections` config.
731    ///
732    /// If `emit_detections` is false and some rules are correlation-only,
733    /// their detection output is suppressed.
734    fn filter_detections(
735        &self,
736        all_detections: Vec<EvaluationResult>,
737        identities: Vec<RuleIdentity>,
738    ) -> Vec<EvaluationResult> {
739        if !self.config.emit_detections && !self.correlation_only_rules.is_empty() {
740            all_detections
741                .into_iter()
742                .zip(identities)
743                .filter_map(|(detection, (id, name))| {
744                    let identities = id.as_deref().into_iter().chain(name.as_deref());
745                    (!self.is_correlation_only(identities)).then_some(detection)
746                })
747                .collect()
748        } else {
749            all_detections
750        }
751    }
752
753    /// Whether output for a rule (detection or correlation) with these
754    /// identities is suppressed: only correlations without `generate: true`
755    /// reference it, and `emit_detections` is off.
756    fn is_correlation_only<'a>(
757        &self,
758        mut identities: impl Iterator<Item = &'a str> + Clone,
759    ) -> bool {
760        !self.config.emit_detections
761            && identities
762                .clone()
763                .any(|identity| self.correlation_only_rules.contains(identity))
764            && !identities.any(|identity| self.generated_rules.contains(identity))
765    }
766
767    /// Feed detection matches into correlation window states.
768    fn feed_detections(
769        &mut self,
770        event: &impl Event,
771        identities: &[RuleIdentity],
772        ts: i64,
773        out: &mut Vec<EvaluationResult>,
774        fired_indices: &mut Vec<usize>,
775    ) {
776        // Collect all (corr_idx, rule_id, rule_name) tuples upfront to avoid
777        // borrow conflicts between self.rule_ids and self.update_correlation.
778        let mut work: Vec<(usize, Option<String>, Option<String>)> = Vec::new();
779
780        for (rule_id, rule_name) in identities {
781            // Collect correlation indices that reference this rule
782            let mut corr_indices = Vec::new();
783            if let Some(id) = rule_id
784                && let Some(indices) = self.rule_index.get(id)
785            {
786                corr_indices.extend(indices);
787            }
788            if let Some(name) = rule_name
789                && let Some(indices) = self.rule_index.get(name)
790            {
791                corr_indices.extend(indices);
792            }
793
794            corr_indices.sort_unstable();
795            corr_indices.dedup();
796
797            for &corr_idx in &corr_indices {
798                work.push((corr_idx, rule_id.clone(), rule_name.clone()));
799            }
800        }
801
802        for (corr_idx, rule_id, rule_name) in work {
803            let before = out.len();
804            self.update_correlation(corr_idx, event, ts, &rule_id, &rule_name, out);
805            if out.len() > before {
806                fired_indices.push(corr_idx);
807            }
808        }
809    }
810
811    /// Find the (id, name) for a detection match by searching our rule_ids table.
812    fn find_rule_identity(&self, det: &EvaluationResult) -> RuleIdentity {
813        // Prefer the stable ID carried by the result.
814        if let Some(ref match_id) = det.header.rule_id {
815            for (id, name, _) in &self.rule_ids {
816                if id.as_deref() == Some(match_id.as_str()) {
817                    return (id.clone(), name.clone());
818                }
819            }
820        }
821
822        // `process_with_detections` accepts the public EvaluationResult shape,
823        // which does not carry a rule name. Recover name-only rule identity
824        // from the title retained alongside the compiled rule.
825        let mut title_matches = self
826            .rule_ids
827            .iter()
828            .filter(|(_, _, title)| title == &det.header.rule_title);
829        if let Some((id, name, _)) = title_matches.next()
830            && title_matches.next().is_none()
831        {
832            return (id.clone(), name.clone());
833        }
834
835        (det.header.rule_id.clone(), None)
836    }
837
838    /// Resolve the event mode for a given correlation.
839    fn resolve_event_mode(&self, corr_idx: usize) -> CorrelationEventMode {
840        let corr = &self.correlations[corr_idx];
841        corr.event_mode
842            .unwrap_or(self.config.correlation_event_mode)
843    }
844
845    /// Resolve the max events cap for a given correlation.
846    fn resolve_max_events(&self, corr_idx: usize) -> usize {
847        let corr = &self.correlations[corr_idx];
848        corr.max_events
849            .unwrap_or(self.config.max_correlation_events)
850    }
851
852    /// Resolve the per-group window-state entry cap for a given correlation.
853    /// `None` means unbounded.
854    fn resolve_max_group_entries(&self, corr_idx: usize) -> Option<usize> {
855        let corr = &self.correlations[corr_idx];
856        corr.max_group_entries.or(self.config.max_group_entries)
857    }
858
859    /// Update a single correlation's state and check its condition.
860    fn update_correlation(
861        &mut self,
862        corr_idx: usize,
863        event: &impl Event,
864        ts: i64,
865        rule_id: &Option<String>,
866        rule_name: &Option<String>,
867        out: &mut Vec<EvaluationResult>,
868    ) {
869        // Borrow the correlation by reference — no cloning needed.  Rust allows
870        // simultaneous &self.correlations and &mut self.state / &mut self.last_alert
871        // because they are disjoint struct fields.
872        let corr = &self.correlations[corr_idx];
873        let corr_type = corr.correlation_type;
874        let timespan = corr.timespan_secs;
875        let window_mode = corr.window_mode;
876        let gap_secs = corr.gap_secs;
877        let level = corr.level;
878        let suppress_secs = corr.suppress_secs.or(self.config.suppress);
879        let action = corr.action.unwrap_or(self.config.action_on_match);
880        let event_mode = self.resolve_event_mode(corr_idx);
881        let max_events = self.resolve_max_events(corr_idx);
882        let max_group_entries = self.resolve_max_group_entries(corr_idx);
883
884        // Determine the rule_ref strings for alias resolution and temporal tracking.
885        let mut ref_strs: Vec<&str> = Vec::new();
886        if let Some(id) = rule_id.as_deref() {
887            ref_strs.push(id);
888        }
889        if let Some(name) = rule_name.as_deref() {
890            ref_strs.push(name);
891        }
892        let rule_ref = ref_strs
893            .iter()
894            .copied()
895            .find(|identity| corr.rule_refs.iter().any(|rule_ref| rule_ref == identity))
896            .unwrap_or("");
897
898        // An event without every group-by value cannot be assigned to a
899        // correlation group.
900        let Some(group_key) = GroupKey::extract(event, &corr.group_by, &ref_strs) else {
901            return;
902        };
903
904        // Get or create window state
905        let state_key = (corr_idx, group_key.clone());
906        let state = self
907            .state
908            .entry(state_key.clone())
909            .or_insert_with(|| WindowState::new_for(corr_type));
910
911        // Apply the window's pre-insert maintenance (sliding evict, tumbling
912        // bucket reset/late-event discard, or session gap/cap reset). On
913        // `Reset` the event buffers below are cleared in sync; on `Discard`
914        // (a late arrival in an earlier tumbling bucket) the event is dropped
915        // without touching the state or buffers.
916        let cutoff = ts - timespan as i64;
917        let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
918        if decision == WindowDecision::Discard {
919            return;
920        }
921        let reset = decision == WindowDecision::Reset;
922
923        // Push the new event into the state
924        match corr_type {
925            CorrelationType::EventCount => {
926                state.push_event_count(ts);
927            }
928            CorrelationType::ValueCount => {
929                if let Some(ref fields) = corr.condition.field
930                    && let Some(key) = composite_value_count_key(event, fields)
931                {
932                    state.push_value_count(ts, key);
933                }
934            }
935            CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
936                state.push_temporal(ts, rule_ref);
937            }
938            CorrelationType::ValueSum
939            | CorrelationType::ValueAvg
940            | CorrelationType::ValuePercentile
941            | CorrelationType::ValueMedian => {
942                if let Some(ref fields) = corr.condition.field
943                    && let Some(field_name) = fields.first()
944                    && let Some(val) = event.get_field(field_name)
945                    && let Some(n) = value_to_f64_ev(&val)
946                {
947                    state.push_numeric(ts, n);
948                }
949            }
950        }
951
952        // Enforce the per-group entry cap. Session windows keep their oldest
953        // entry as the span anchor so truncation cannot silently extend the
954        // `timespan` cap.
955        if let Some(cap) = max_group_entries {
956            state.truncate_oldest(cap, window_mode == WindowMode::Session);
957        }
958
959        // Push event into buffer based on event mode. Keep the buffer's retained
960        // events aligned with the window state: sliding evicts by the trailing
961        // cutoff, while tumbling/session clear the buffer when the window reset.
962        match event_mode {
963            CorrelationEventMode::Full => {
964                let buf = self
965                    .event_buffers
966                    .entry(state_key.clone())
967                    .or_insert_with(|| EventBuffer::new(max_events));
968                if window_mode == rsigma_parser::WindowMode::Sliding {
969                    buf.evict(cutoff);
970                } else if reset {
971                    buf.clear();
972                }
973                let json = event.to_json();
974                buf.push(ts, &json);
975            }
976            CorrelationEventMode::Refs => {
977                let buf = self
978                    .event_ref_buffers
979                    .entry(state_key.clone())
980                    .or_insert_with(|| EventRefBuffer::new(max_events));
981                if window_mode == rsigma_parser::WindowMode::Sliding {
982                    buf.evict(cutoff);
983                } else if reset {
984                    buf.clear();
985                }
986                let json = event.to_json();
987                buf.push(ts, &json);
988            }
989            CorrelationEventMode::None => {}
990        }
991
992        // Check condition — after this, `state` is no longer used (NLL drops the borrow).
993        let fired = state.check_condition(
994            &corr.condition,
995            corr_type,
996            &corr.rule_refs,
997            corr.extended_expr.as_ref(),
998        );
999
1000        if let Some(agg_value) = fired {
1001            let alert_key = (corr_idx, group_key.clone());
1002
1003            // Suppression check: skip if we've already alerted within the suppress window
1004            let suppressed = if let Some(suppress) = suppress_secs {
1005                if let Some(&last_ts) = self.last_alert.get(&alert_key) {
1006                    (ts - last_ts) < suppress as i64
1007                } else {
1008                    false
1009                }
1010            } else {
1011                false
1012            };
1013
1014            if !suppressed {
1015                // Retrieve stored events / refs based on mode
1016                let (events, event_refs) = match event_mode {
1017                    CorrelationEventMode::Full => {
1018                        let stored = self
1019                            .event_buffers
1020                            .get(&alert_key)
1021                            .map(|buf| buf.decompress_all())
1022                            .unwrap_or_default();
1023                        (Some(stored), None)
1024                    }
1025                    CorrelationEventMode::Refs => {
1026                        let stored = self
1027                            .event_ref_buffers
1028                            .get(&alert_key)
1029                            .map(|buf| buf.refs())
1030                            .unwrap_or_default();
1031                        (None, Some(stored))
1032                    }
1033                    CorrelationEventMode::None => (None, None),
1034                };
1035
1036                // Only clone title/id/tags when we actually produce output
1037                let corr = &self.correlations[corr_idx];
1038                let result = EvaluationResult {
1039                    header: RuleHeader {
1040                        rule_title: corr.title.clone(),
1041                        rule_id: corr.id.clone(),
1042                        level,
1043                        tags: corr.tags.clone(),
1044                        custom_attributes: corr.custom_attributes.clone(),
1045                        enrichments: None,
1046                    },
1047                    body: ResultBody::Correlation(CorrelationBody {
1048                        correlation_type: corr_type,
1049                        group_key: group_key.to_pairs(&corr.group_by),
1050                        aggregated_value: agg_value,
1051                        timespan_secs: timespan,
1052                        events,
1053                        event_refs,
1054                    }),
1055                };
1056                out.push(result);
1057
1058                // Record alert time for suppression
1059                self.last_alert.insert(alert_key.clone(), ts);
1060
1061                // Action on match
1062                if action == CorrelationAction::Reset {
1063                    if let Some(state) = self.state.get_mut(&alert_key) {
1064                        state.clear();
1065                    }
1066                    if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
1067                        buf.clear();
1068                    }
1069                    if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
1070                        buf.clear();
1071                    }
1072                }
1073            }
1074        }
1075    }
1076
1077    /// IDs and names a fired correlation can be referenced by.
1078    ///
1079    /// Parents index `rule_refs` as written in YAML (id or name). The
1080    /// emitted result only carries `rule_id`, so name-based parents need
1081    /// this extra key or they never see the child.
1082    fn chain_lookup_keys(&self, corr_idx: usize) -> Vec<String> {
1083        let corr = &self.correlations[corr_idx];
1084        let mut keys = Vec::with_capacity(2);
1085        keys.extend(corr.id.iter().cloned());
1086        if corr.name.as_ref() != corr.id.as_ref() {
1087            keys.extend(corr.name.iter().cloned());
1088        }
1089        keys
1090    }
1091
1092    /// Propagate correlation results to higher-level correlations (chaining).
1093    ///
1094    /// When a correlation fires, any correlation that references it (by ID or name)
1095    /// is updated. Newly fired parents are appended to `out`, with their
1096    /// correlation indices in `out_indices`, and become the next `pending`
1097    /// set. Limits chain depth to 10 to prevent infinite loops.
1098    fn chain_correlations(
1099        &mut self,
1100        fired: &[EvaluationResult],
1101        fired_indices: &[usize],
1102        ts: i64,
1103        out: &mut Vec<EvaluationResult>,
1104        out_indices: &mut Vec<usize>,
1105    ) {
1106        debug_assert_eq!(fired.len(), fired_indices.len());
1107        // Chaining only needs which correlation fired and for which group, so
1108        // `pending` carries that instead of cloning results and their events.
1109        // Only correlation results chain. Detections never reach here.
1110        let mut pending: Vec<(usize, Vec<(String, String)>)> = fired_indices
1111            .iter()
1112            .zip(fired)
1113            .filter_map(|(&idx, result)| Some((idx, result.as_correlation()?.group_key.clone())))
1114            .collect();
1115        let mut depth = 0;
1116
1117        while !pending.is_empty() && depth < MAX_CHAIN_DEPTH {
1118            depth += 1;
1119
1120            // Collect work items: (corr_idx, group_key_pairs, fired_ref)
1121            #[allow(clippy::type_complexity)]
1122            let mut work: Vec<(usize, Vec<(String, String)>, String)> = Vec::new();
1123            let mut seen = std::collections::HashSet::<(usize, String)>::new();
1124            for (source_idx, group_key) in &pending {
1125                for key in self.chain_lookup_keys(*source_idx) {
1126                    if let Some(indices) = self.rule_index.get(&key) {
1127                        for &corr_idx in indices {
1128                            if seen.insert((corr_idx, key.clone())) {
1129                                work.push((corr_idx, group_key.clone(), key.clone()));
1130                            }
1131                        }
1132                    }
1133                }
1134            }
1135
1136            let mut next_pending = Vec::new();
1137            for (corr_idx, group_key_pairs, fired_ref) in work {
1138                let corr = &self.correlations[corr_idx];
1139                let corr_type = corr.correlation_type;
1140                let timespan = corr.timespan_secs;
1141                let window_mode = corr.window_mode;
1142                let gap_secs = corr.gap_secs;
1143                let level = corr.level;
1144                let suppress_secs = corr.suppress_secs.or(self.config.suppress);
1145                let action = corr.action.unwrap_or(self.config.action_on_match);
1146
1147                let Some(group_key) = GroupKey::from_pairs(&group_key_pairs, &corr.group_by) else {
1148                    continue;
1149                };
1150                let state_key = (corr_idx, group_key.clone());
1151                let state = self
1152                    .state
1153                    .entry(state_key.clone())
1154                    .or_insert_with(|| WindowState::new_for(corr_type));
1155
1156                // Late arrivals in an earlier tumbling bucket are discarded;
1157                // chained correlations keep no event buffers, so `Reset` needs
1158                // no extra bookkeeping here.
1159                if apply_window_open(state, ts, timespan, window_mode, gap_secs)
1160                    == WindowDecision::Discard
1161                {
1162                    continue;
1163                }
1164
1165                match corr_type {
1166                    CorrelationType::EventCount => {
1167                        state.push_event_count(ts);
1168                    }
1169                    CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
1170                        state.push_temporal(ts, &fired_ref);
1171                    }
1172                    _ => {
1173                        state.push_event_count(ts);
1174                    }
1175                }
1176
1177                // Same per-group cap as the direct path; session windows
1178                // keep the span anchor.
1179                if let Some(cap) = corr.max_group_entries.or(self.config.max_group_entries) {
1180                    state.truncate_oldest(cap, window_mode == WindowMode::Session);
1181                }
1182
1183                let fired = state.check_condition(
1184                    &corr.condition,
1185                    corr_type,
1186                    &corr.rule_refs,
1187                    corr.extended_expr.as_ref(),
1188                );
1189
1190                if let Some(agg_value) = fired {
1191                    let alert_key = state_key;
1192                    let suppressed = if let Some(suppress) = suppress_secs {
1193                        self.last_alert
1194                            .get(&alert_key)
1195                            .is_some_and(|&last_ts| (ts - last_ts) < suppress as i64)
1196                    } else {
1197                        false
1198                    };
1199                    if suppressed {
1200                        continue;
1201                    }
1202
1203                    let corr = &self.correlations[corr_idx];
1204                    let fired_group_key = group_key.to_pairs(&corr.group_by);
1205                    let result = EvaluationResult {
1206                        header: RuleHeader {
1207                            rule_title: corr.title.clone(),
1208                            rule_id: corr.id.clone(),
1209                            level,
1210                            tags: corr.tags.clone(),
1211                            custom_attributes: corr.custom_attributes.clone(),
1212                            enrichments: None,
1213                        },
1214                        body: ResultBody::Correlation(CorrelationBody {
1215                            correlation_type: corr_type,
1216                            group_key: fired_group_key.clone(),
1217                            aggregated_value: agg_value,
1218                            timespan_secs: timespan,
1219                            // Chained correlations don't include events
1220                            // (they aggregate over correlation results, not
1221                            // raw events)
1222                            events: None,
1223                            event_refs: None,
1224                        }),
1225                    };
1226                    next_pending.push((corr_idx, fired_group_key));
1227                    out.push(result);
1228                    out_indices.push(corr_idx);
1229                    self.last_alert.insert(alert_key.clone(), ts);
1230
1231                    if action == CorrelationAction::Reset
1232                        && let Some(state) = self.state.get_mut(&alert_key)
1233                    {
1234                        state.clear();
1235                    }
1236                }
1237            }
1238
1239            pending = next_pending;
1240        }
1241
1242        if !pending.is_empty() {
1243            log::warn!(
1244                "Correlation chain depth limit reached ({MAX_CHAIN_DEPTH}); \
1245                 {} pending result(s) were not propagated further. \
1246                 This may indicate a cycle in correlation references.",
1247                pending.len()
1248            );
1249        }
1250    }
1251
1252    // =========================================================================
1253    // Timestamp extraction
1254    // =========================================================================
1255
1256    /// Extract a Unix epoch timestamp (seconds) from an event.
1257    ///
1258    /// Tries each configured timestamp field in order. Supports:
1259    /// - Numeric values (epoch seconds, or epoch millis if > 1e12)
1260    /// - ISO 8601 strings (e.g., "2024-07-10T12:30:00Z")
1261    ///
1262    /// Returns `None` if no field yields a valid timestamp; a value before
1263    /// 1970 or past the representable range does not count as one.
1264    fn extract_event_timestamp(&self, event: &impl Event) -> Option<i64> {
1265        for field_name in &self.config.timestamp_fields {
1266            if let Some(val) = event.get_field(field_name)
1267                && let Some(ts) = parse_timestamp_value(&val)
1268            {
1269                return Some(ts);
1270            }
1271        }
1272        None
1273    }
1274
1275    // =========================================================================
1276    // State management
1277    // =========================================================================
1278
1279    /// Manually evict all expired state entries.
1280    pub fn evict_expired(&mut self, now_secs: i64) {
1281        self.evict_all(now_secs);
1282    }
1283
1284    /// Evict expired entries and remove empty states.
1285    fn evict_all(&mut self, now_secs: i64) {
1286        // Phase 1: Time-based eviction — remove entries outside their correlation
1287        // window. Eviction is window-mode aware:
1288        //
1289        // - Sliding: trim entries older than the trailing cutoff, as always.
1290        // - Tumbling/session: never trim from the front — that would forget the
1291        //   bucket/session start and silently weaken the `timespan` cap (the
1292        //   window would drift toward sliding semantics). Instead, drop the
1293        //   whole group once it is stale (no event within its bucket span /
1294        //   session gap), which is exactly the point at which the next arrival
1295        //   would reset it anyway.
1296        let specs: Vec<(u64, WindowMode, Option<u64>)> = self
1297            .correlations
1298            .iter()
1299            .map(|c| (c.timespan_secs, c.window_mode, c.gap_secs))
1300            .collect();
1301
1302        self.state.retain(|&(corr_idx, _), state| {
1303            if let Some(&(timespan, mode, gap)) = specs.get(corr_idx) {
1304                match mode {
1305                    WindowMode::Sliding => {
1306                        state.evict(now_secs - timespan as i64);
1307                    }
1308                    WindowMode::Tumbling | WindowMode::Session => {
1309                        let staleness = if mode == WindowMode::Session {
1310                            gap.unwrap_or(timespan)
1311                        } else {
1312                            timespan
1313                        } as i64;
1314                        if state
1315                            .latest_timestamp()
1316                            .is_some_and(|last| now_secs - last > staleness)
1317                        {
1318                            state.clear();
1319                        }
1320                    }
1321                }
1322            }
1323            !state.is_empty()
1324        });
1325
1326        // Evict event buffers in sync with window state: sliding buffers trim by
1327        // the trailing cutoff, tumbling/session buffers live and die with their
1328        // window state (dropped above when the group went stale).
1329        let state = &self.state;
1330        self.event_buffers.retain(|key, buf| {
1331            if let Some(&(timespan, mode, _)) = specs.get(key.0) {
1332                match mode {
1333                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
1334                    WindowMode::Tumbling | WindowMode::Session => {
1335                        if !state.contains_key(key) {
1336                            return false;
1337                        }
1338                    }
1339                }
1340            }
1341            !buf.is_empty()
1342        });
1343        self.event_ref_buffers.retain(|key, buf| {
1344            if let Some(&(timespan, mode, _)) = specs.get(key.0) {
1345                match mode {
1346                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
1347                    WindowMode::Tumbling | WindowMode::Session => {
1348                        if !state.contains_key(key) {
1349                            return false;
1350                        }
1351                    }
1352                }
1353            }
1354            !buf.is_empty()
1355        });
1356
1357        // Phase 2: Hard cap — if still over limit after time-based eviction (e.g.
1358        // high-cardinality traffic with long windows), drop the stalest entries
1359        // until we're at 90% capacity to avoid evicting on every single event.
1360        if self.state.len() >= self.config.max_state_entries {
1361            let target = self.config.max_state_entries * 9 / 10;
1362            let excess = self.state.len() - target;
1363
1364            log::warn!(
1365                "Correlation state hard cap reached ({} entries, max {}); \
1366                 evicting {} stalest entries to {} (90% capacity). \
1367                 This indicates high-cardinality traffic; consider raising \
1368                 max_state_entries or shortening correlation windows.",
1369                self.state.len(),
1370                self.config.max_state_entries,
1371                excess,
1372                target,
1373            );
1374
1375            // Partition by latest timestamp so the `excess` stalest entries
1376            // come first, and clone only their keys.
1377            let mut by_staleness: Vec<_> = self
1378                .state
1379                .iter()
1380                .map(|(k, v)| (k, v.latest_timestamp().unwrap_or(i64::MIN)))
1381                .collect();
1382            if excess < by_staleness.len() {
1383                by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
1384            }
1385            let stalest: Vec<_> = by_staleness
1386                .iter()
1387                .take(excess)
1388                .map(|&(k, _)| k.clone())
1389                .collect();
1390
1391            // Drop the stalest entries (and their associated event buffers)
1392            for key in stalest {
1393                self.state.remove(&key);
1394                self.last_alert.remove(&key);
1395                self.event_buffers.remove(&key);
1396                self.event_ref_buffers.remove(&key);
1397            }
1398        }
1399
1400        // Phase 3: Evict stale last_alert entries — remove if the suppress window
1401        // has passed or if the corresponding window state no longer exists.
1402        self.last_alert.retain(|key, &mut alert_ts| {
1403            let suppress = if key.0 < self.correlations.len() {
1404                self.correlations[key.0]
1405                    .suppress_secs
1406                    .or(self.config.suppress)
1407                    .unwrap_or(0)
1408            } else {
1409                0
1410            };
1411            (now_secs - alert_ts) < suppress as i64
1412        });
1413    }
1414
1415    /// Number of active state entries (for monitoring).
1416    pub fn state_count(&self) -> usize {
1417        self.state.len()
1418    }
1419
1420    /// Number of detection rules loaded.
1421    pub fn detection_rule_count(&self) -> usize {
1422        self.engine.rule_count()
1423    }
1424
1425    /// Number of correlation rules loaded.
1426    pub fn correlation_rule_count(&self) -> usize {
1427        self.correlations.len()
1428    }
1429
1430    /// Number of active event buffers (for monitoring).
1431    pub fn event_buffer_count(&self) -> usize {
1432        self.event_buffers.len()
1433    }
1434
1435    /// Total compressed bytes across all event buffers (for monitoring).
1436    pub fn event_buffer_bytes(&self) -> usize {
1437        self.event_buffers
1438            .values()
1439            .map(|b| b.compressed_bytes())
1440            .sum()
1441    }
1442
1443    /// Number of active event ref buffers — `Refs` mode (for monitoring).
1444    pub fn event_ref_buffer_count(&self) -> usize {
1445        self.event_ref_buffers.len()
1446    }
1447
1448    /// Access the inner stateless engine.
1449    pub fn engine(&self) -> &Engine<L> {
1450        &self.engine
1451    }
1452
1453    /// Resolve a rule key (an id, or a title for a rule without one) to the
1454    /// documentation of every loaded rule that carries it, across both the
1455    /// detection rules and the correlations.
1456    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
1457        let mut variants = Vec::new();
1458        self.collect_rule_metadata(key, &mut variants);
1459        RuleMetadataLookup::from_variants(variants)
1460    }
1461
1462    pub(crate) fn collect_rule_metadata(&self, key: &str, out: &mut Vec<RuleBundleMetadata>) {
1463        self.engine.collect_rule_metadata(key, out);
1464        crate::rule_metadata::matching_correlations(&self.correlations, key, out);
1465    }
1466
1467    /// Export all mutable correlation state as a serializable snapshot.
1468    ///
1469    /// The snapshot uses stable correlation identifiers (id > name > title)
1470    /// instead of internal indices, so it survives rule reloads as long as
1471    /// the correlation rules keep the same identifiers.
1472    pub fn export_state(&self) -> CorrelationSnapshot {
1473        let mut windows: HashMap<String, Vec<(GroupKey, WindowState)>> = HashMap::new();
1474        for ((idx, gk), ws) in &self.state {
1475            let corr_id = self.correlation_stable_id(*idx);
1476            windows
1477                .entry(corr_id)
1478                .or_default()
1479                .push((gk.clone(), ws.clone()));
1480        }
1481
1482        let mut last_alert: HashMap<String, Vec<(GroupKey, i64)>> = HashMap::new();
1483        for ((idx, gk), ts) in &self.last_alert {
1484            let corr_id = self.correlation_stable_id(*idx);
1485            last_alert
1486                .entry(corr_id)
1487                .or_default()
1488                .push((gk.clone(), *ts));
1489        }
1490
1491        let mut event_buffers: HashMap<String, Vec<(GroupKey, EventBuffer)>> = HashMap::new();
1492        for ((idx, gk), buf) in &self.event_buffers {
1493            let corr_id = self.correlation_stable_id(*idx);
1494            event_buffers
1495                .entry(corr_id)
1496                .or_default()
1497                .push((gk.clone(), buf.clone()));
1498        }
1499
1500        let mut event_ref_buffers: HashMap<String, Vec<(GroupKey, EventRefBuffer)>> =
1501            HashMap::new();
1502        for ((idx, gk), buf) in &self.event_ref_buffers {
1503            let corr_id = self.correlation_stable_id(*idx);
1504            event_ref_buffers
1505                .entry(corr_id)
1506                .or_default()
1507                .push((gk.clone(), buf.clone()));
1508        }
1509
1510        CorrelationSnapshot {
1511            version: SNAPSHOT_VERSION,
1512            windows,
1513            last_alert,
1514            event_buffers,
1515            event_ref_buffers,
1516        }
1517    }
1518
1519    /// Import previously exported state, mapping stable identifiers back to
1520    /// current correlation indices. Entries whose identifiers no longer match
1521    /// any loaded correlation are silently dropped.
1522    ///
1523    /// Returns `false` (and imports nothing) if the snapshot version is
1524    /// incompatible with the current schema.
1525    pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
1526        if snapshot.version != SNAPSHOT_VERSION {
1527            return false;
1528        }
1529        let id_to_idx = self.build_id_to_index_map();
1530
1531        for (corr_id, groups) in snapshot.windows {
1532            if let Some(&idx) = id_to_idx.get(&corr_id) {
1533                for (gk, ws) in groups {
1534                    self.state.insert((idx, gk), ws);
1535                }
1536            }
1537        }
1538
1539        for (corr_id, groups) in snapshot.last_alert {
1540            if let Some(&idx) = id_to_idx.get(&corr_id) {
1541                for (gk, ts) in groups {
1542                    self.last_alert.insert((idx, gk), ts);
1543                }
1544            }
1545        }
1546
1547        for (corr_id, groups) in snapshot.event_buffers {
1548            if let Some(&idx) = id_to_idx.get(&corr_id) {
1549                for (gk, buf) in groups {
1550                    self.event_buffers.insert((idx, gk), buf);
1551                }
1552            }
1553        }
1554
1555        for (corr_id, groups) in snapshot.event_ref_buffers {
1556            if let Some(&idx) = id_to_idx.get(&corr_id) {
1557                for (gk, buf) in groups {
1558                    self.event_ref_buffers.insert((idx, gk), buf);
1559                }
1560            }
1561        }
1562
1563        true
1564    }
1565
1566    /// Stable identifier for a correlation rule: prefers id, then name, then title.
1567    fn correlation_stable_id(&self, idx: usize) -> String {
1568        let corr = &self.correlations[idx];
1569        corr.id
1570            .clone()
1571            .or_else(|| corr.name.clone())
1572            .unwrap_or_else(|| corr.title.clone())
1573    }
1574
1575    /// Build a reverse map from stable id → current correlation index.
1576    fn build_id_to_index_map(&self) -> HashMap<String, usize> {
1577        self.correlations
1578            .iter()
1579            .enumerate()
1580            .map(|(idx, _)| (self.correlation_stable_id(idx), idx))
1581            .collect()
1582    }
1583}
1584
1585impl Default for CorrelationEngine {
1586    fn default() -> Self {
1587        Self::new(CorrelationConfig::default())
1588    }
1589}
1590
1591fn split_identified(
1592    identified: Vec<IdentifiedEvaluation>,
1593) -> (Vec<EvaluationResult>, Vec<RuleIdentity>) {
1594    identified
1595        .into_iter()
1596        .map(|identified| {
1597            (
1598                identified.result,
1599                (identified.rule_id, identified.rule_name),
1600            )
1601        })
1602        .unzip()
1603}
1604
1605// =============================================================================
1606// Timestamp parsing helpers
1607// =============================================================================
1608
1609/// Extract a timestamp from an event using the given field names.
1610///
1611/// Standalone version of `CorrelationEngine::extract_event_timestamp` for use
1612/// in contexts where borrowing `&self` is not possible (e.g. rayon closures).
1613fn extract_event_ts(event: &impl Event, timestamp_fields: &[String]) -> Option<i64> {
1614    for field_name in timestamp_fields {
1615        if let Some(val) = event.get_field(field_name)
1616            && let Some(ts) = parse_timestamp_value(&val)
1617        {
1618            return Some(ts);
1619        }
1620    }
1621    None
1622}
1623
1624/// Parse an [`EventValue`] as a Unix epoch timestamp in seconds.
1625///
1626/// Values before 1970, non-finite floats, and dates past the representable
1627/// range are `None`, so the next timestamp field or the fallback applies.
1628fn parse_timestamp_value(val: &EventValue) -> Option<i64> {
1629    match val {
1630        EventValue::Int(i) => epoch_seconds_from_int(*i),
1631        EventValue::Float(f) => epoch_seconds_from_float(*f),
1632        EventValue::Str(s) => parse_timestamp_str(s)
1633            .map(|dt| dt.timestamp())
1634            .filter(|ts| *ts >= 0),
1635        _ => None,
1636    }
1637}
1638
1639/// Render a value for a `value_count` distinct key. Unlike a group key, a
1640/// null counts as the distinct value `null`.
1641fn value_to_string_for_count(v: &EventValue) -> Option<String> {
1642    match v {
1643        EventValue::Null => Some("null".to_string()),
1644        v => v.as_str().map(Cow::into_owned),
1645    }
1646}
1647
1648/// Build a composite distinct-key for `value_count` over one or more fields.
1649///
1650/// Each field's value is rendered with [`value_to_string_for_count`] and the
1651/// rendered parts are joined with `\u{1f}` (the ASCII Unit Separator), which
1652/// is unlikely to occur in normal log data. If any field is missing or has a
1653/// type that does not produce a stable string representation, the event is
1654/// excluded from the distinct count (return `None`), matching the historical
1655/// single-field behavior.
1656fn composite_value_count_key(event: &impl Event, fields: &[String]) -> Option<String> {
1657    // Common case: exactly one field. Avoid the separator overhead.
1658    if let [field_name] = fields {
1659        let val = event.get_field(field_name)?;
1660        return value_to_string_for_count(&val);
1661    }
1662
1663    let mut parts = Vec::with_capacity(fields.len());
1664    for field_name in fields {
1665        let val = event.get_field(field_name)?;
1666        let rendered = value_to_string_for_count(&val)?;
1667        parts.push(rendered);
1668    }
1669    Some(parts.join("\u{1f}"))
1670}
1671
1672/// Convert an [`EventValue`] to f64 for numeric aggregation.
1673fn value_to_f64_ev(v: &EventValue) -> Option<f64> {
1674    v.as_f64()
1675}