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::{BTreeMap, HashMap, HashSet};
25use std::sync::Arc;
26
27use chrono::Utc;
28
29use rsigma_parser::{CorrelationRule, CorrelationType, SigmaCollection, SigmaRule, WindowMode};
30
31use crate::correlation::{
32    CompiledCorrelation, EventBuffer, EventRef, EventRefBuffer, GroupKey, RefEntry, Retained,
33    WindowDecision, WindowState, apply_window_open, compile_correlation,
34};
35use crate::engine::{Engine, IdentifiedEvaluation};
36use crate::error::{EvalError, Result};
37use crate::event::{Event, EventValue};
38use crate::logsource::{ExtractLogSource, LogSourceExtractor};
39use crate::pipeline::{Pipeline, apply_pipelines, apply_pipelines_to_correlation};
40use crate::result::{CorrelationBody, EvaluationResult, EventSource, ResultBody, RuleHeader};
41use crate::rule_metadata::{RuleBundleMetadata, RuleMetadataLookup};
42use crate::tenant::TenantId;
43use crate::timestamp::{epoch_seconds_from_float, epoch_seconds_from_int, parse_timestamp_str};
44
45type RuleIdentity = (Option<String>, Option<String>);
46
47// =============================================================================
48// Correlation Engine
49// =============================================================================
50
51/// Current snapshot schema version. Bump when the serialized format changes.
52pub(crate) const SNAPSHOT_VERSION: u32 = 2;
53
54/// Parent hops evaluated after a first-level correlation fire in one event.
55/// The first-level result is produced by `feed_detections`; each loop
56/// iteration here walks one parent. A chain longer than this is updated
57/// and emitted through this many hops, then leftover parents are dropped
58/// with a `WARN`.
59const MAX_CHAIN_DEPTH: usize = 10;
60
61/// Timespan above which a correlation without a per-group entry cap is
62/// warned about at load: a busy group's window retains `timespan` x event
63/// rate entries, which `max_state_entries` does not see.
64const LONG_WINDOW_WARN_SECS: u64 = 3600;
65
66/// Event retention a correlation needs for itself and for the chain above it.
67#[derive(Debug, Clone, Default)]
68struct Retention {
69    /// Strongest event mode required by this correlation or any correlation
70    /// that references it, directly or through another correlation.
71    mode: CorrelationEventMode,
72    /// Largest retention cap required by that chain.
73    cap: usize,
74    /// Whether any correlation that references this one retains events.
75    feeds_retaining_parent: bool,
76    /// The correlation's `rule_refs`, interned so each buffered event shares
77    /// one string as its source rule. Empty when nothing is retained.
78    rule_refs: Vec<Arc<str>>,
79    /// The correlation's stable identifier, interned as the source of the
80    /// entries it hands to its parents. `None` when nothing is retained.
81    stable_id: Option<Arc<str>>,
82}
83
84/// The events, references, and sources a firing correlation reports.
85#[derive(Default)]
86struct ReportedEvents {
87    events: Option<Vec<serde_json::Value>>,
88    event_refs: Option<Vec<EventRef>>,
89    event_sources: Option<Vec<EventSource>>,
90}
91
92/// Stateful correlation engine.
93///
94/// Wraps the stateless `Engine` for detection rules and adds time-windowed
95/// correlation on top. Supports all 7 Sigma correlation types and chaining.
96///
97/// Generic over the inner engine's logsource extractor `L`, which defaults to
98/// [`LogSourceExtractor`] (see [`Engine`]).
99pub struct CorrelationEngine<L = LogSourceExtractor> {
100    /// Inner stateless detection engine.
101    engine: Engine<L>,
102    /// Compiled correlation rules.
103    correlations: Vec<CompiledCorrelation>,
104    /// Maps rule ID/name -> indices into `correlations` that reference it.
105    /// This allows quick lookup: "which correlations care about rule X?"
106    rule_index: HashMap<String, Vec<usize>>,
107    /// Maps detection rule index -> (rule_id, rule_name, rule_title) for reverse lookup.
108    /// Used to find which correlations a detection match triggers.
109    rule_ids: Vec<(Option<String>, Option<String>, String)>,
110    /// Per-(tenant, correlation_index, group_key) window state.
111    state: HashMap<StateKey, WindowState>,
112    /// Last alert timestamp per (tenant, correlation_index, group_key) for suppression.
113    last_alert: HashMap<StateKey, i64>,
114    /// Per-(tenant, correlation_index, group_key) compressed event buffer (`Full` mode).
115    event_buffers: HashMap<StateKey, EventBuffer>,
116    /// Per-(tenant, correlation_index, group_key) event reference buffer (`Refs` mode).
117    event_ref_buffers: HashMap<StateKey, EventRefBuffer>,
118    /// Set of rule IDs/names (detections or correlations) that are
119    /// "correlation-only" (referenced by correlations where `generate == false`).
120    /// Used to filter their output when `config.emit_detections == false`.
121    correlation_only_rules: std::collections::HashSet<String>,
122    /// Rules referenced by at least one correlation with `generate: true`.
123    /// Such a reference wins over correlation-only references.
124    generated_rules: std::collections::HashSet<String>,
125    /// Configuration.
126    config: CorrelationConfig,
127    /// Processing pipelines applied to rules during add_rule.
128    pipelines: Vec<Pipeline>,
129    /// Events skipped by `require_tenant` because they carried no tenant.
130    untenanted_skipped: u64,
131    /// Live state keys per tenant, kept in step with `state` while a
132    /// per-tenant cap is set, so quota checks and eviction touch only that
133    /// tenant's entries. Empty when there is no per-tenant cap.
134    tenant_keys: HashMap<Option<TenantId>, HashSet<StateKey>>,
135    /// Entries evicted because a tenant hit its quota.
136    tenant_quota_evictions: u64,
137    /// Sequence number the next processed event gets. Retained buffer entries
138    /// carry it so a parent correlation can skip an event it already merged.
139    next_event_seq: u64,
140    /// Per-correlation event retention, recomputed when the rule set or the
141    /// engine defaults change.
142    retention: Vec<Retention>,
143    /// Whether `retention` needs recomputing before the next event.
144    retention_dirty: bool,
145}
146
147impl CorrelationEngine {
148    /// Create a new correlation engine with the given configuration.
149    pub fn new(config: CorrelationConfig) -> Self {
150        Self::with_engine(config, Engine::new())
151    }
152}
153
154impl<L> CorrelationEngine<L> {
155    /// Create a new correlation engine whose inner detection engine prunes
156    /// with `extractor`, a custom [`ExtractLogSource`] implementation.
157    pub fn with_logsource_extractor(config: CorrelationConfig, extractor: L) -> Self {
158        Self::with_engine(config, Engine::with_logsource_extractor(extractor))
159    }
160
161    fn with_engine(config: CorrelationConfig, engine: Engine<L>) -> Self {
162        CorrelationEngine {
163            engine,
164            correlations: Vec::new(),
165            rule_index: HashMap::new(),
166            rule_ids: Vec::new(),
167            state: HashMap::new(),
168            last_alert: HashMap::new(),
169            event_buffers: HashMap::new(),
170            event_ref_buffers: HashMap::new(),
171            correlation_only_rules: std::collections::HashSet::new(),
172            generated_rules: std::collections::HashSet::new(),
173            config,
174            pipelines: Vec::new(),
175            untenanted_skipped: 0,
176            tenant_keys: HashMap::new(),
177            tenant_quota_evictions: 0,
178            next_event_seq: 1,
179            retention: Vec::new(),
180            retention_dirty: true,
181        }
182    }
183
184    /// Add a pipeline to the engine.
185    ///
186    /// Pipelines are applied to rules during `add_rule` / `add_collection`.
187    pub fn add_pipeline(&mut self, pipeline: Pipeline) {
188        self.pipelines.push(pipeline);
189        self.pipelines.sort_by_key(|p| p.priority);
190    }
191
192    /// Set global `include_event` on the inner detection engine.
193    pub fn set_include_event(&mut self, include: bool) {
194        self.engine.set_include_event(include);
195    }
196
197    /// Forward to [`crate::Engine::set_match_detail`] on the inner detection
198    /// engine. Correlation detections inherit the level set here.
199    pub fn set_match_detail(&mut self, level: crate::result::MatchDetailLevel) {
200        self.engine.set_match_detail(level);
201    }
202
203    /// Forward to [`crate::Engine::set_bloom_prefilter`] on the inner
204    /// detection engine. Off by default; the optimization helps only on
205    /// substring-heavy rule sets paired with mostly-non-matching events.
206    pub fn set_bloom_prefilter(&mut self, enabled: bool) {
207        self.engine.set_bloom_prefilter(enabled);
208    }
209
210    /// Forward to [`crate::Engine::set_logsource_extractor`] on the inner
211    /// detection engine. Correlation inherits logsource pruning, since
212    /// `process_event` evaluates through this engine.
213    pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
214        self.engine.set_logsource_extractor(extractor);
215    }
216
217    /// Total rule candidates pruned by logsource on the inner engine.
218    pub fn logsource_pruned_total(&self) -> u64 {
219        self.engine.logsource_pruned_total()
220    }
221
222    /// Total evaluate calls with no extractable event logsource (fail-open).
223    pub fn logsource_absent_total(&self) -> u64 {
224        self.engine.logsource_absent_total()
225    }
226
227    /// Forward to [`crate::Engine::set_bloom_max_bytes`] on the inner
228    /// detection engine.
229    pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
230        self.engine.set_bloom_max_bytes(max_bytes);
231    }
232
233    /// Forward to [`crate::Engine::set_cross_rule_ac`] on the inner
234    /// detection engine. Off by default. Available behind the
235    /// `daachorse-index` Cargo feature.
236    #[cfg(feature = "daachorse-index")]
237    pub fn set_cross_rule_ac(&mut self, enabled: bool) {
238        self.engine.set_cross_rule_ac(enabled);
239    }
240
241    /// Set the global correlation event mode.
242    ///
243    /// - `None`: no event storage (default)
244    /// - `Full`: compressed event bodies
245    /// - `Refs`: lightweight timestamp + ID references
246    pub fn set_correlation_event_mode(&mut self, mode: CorrelationEventMode) {
247        self.config.correlation_event_mode = mode;
248        self.retention_dirty = true;
249    }
250
251    /// Set the maximum number of events to store per correlation window group.
252    /// Only meaningful when `correlation_event_mode` is not `None`.
253    pub fn set_max_correlation_events(&mut self, max: usize) {
254        self.config.max_correlation_events = max;
255        self.retention_dirty = true;
256    }
257
258    /// Add a single detection rule.
259    ///
260    /// If pipelines are set, the rule is cloned and transformed before compilation.
261    /// The inner engine receives the already-transformed rule directly (not through
262    /// its own pipeline, to avoid double transformation).
263    pub fn add_rule(&mut self, rule: &SigmaRule) -> Result<()> {
264        if self.pipelines.is_empty() {
265            self.apply_custom_attributes(&rule.custom_attributes);
266            self.rule_ids
267                .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
268            self.engine.add_rule(rule)?;
269        } else {
270            let mut transformed = rule.clone();
271            apply_pipelines(&self.pipelines, &mut transformed)?;
272            self.apply_custom_attributes(&transformed.custom_attributes);
273            self.rule_ids.push((
274                transformed.id.clone(),
275                transformed.name.clone(),
276                transformed.title.clone(),
277            ));
278            // Use compile_rule + add_compiled_rule to bypass inner engine's pipelines
279            let compiled = crate::compiler::compile_rule(&transformed)?;
280            self.engine.add_compiled_rule(compiled);
281        }
282        Ok(())
283    }
284
285    /// Read `rsigma.*` custom attributes from a rule and apply them to the
286    /// engine configuration.  This allows pipelines to influence engine
287    /// behaviour via `SetCustomAttribute` transformations — the same pattern
288    /// used by pySigma backends (e.g. pySigma-backend-loki).
289    ///
290    /// Supported attributes:
291    /// - `rsigma.timestamp_field` — prepends a field name to the timestamp
292    ///   extraction priority list so the correlation engine can find the
293    ///   event timestamp in non-standard field names.
294    /// - `rsigma.suppress` — sets the default suppression window (e.g. `5m`).
295    ///   Only applied when the CLI did not already set `--suppress`.
296    /// - `rsigma.action` — sets the default post-fire action (`alert`/`reset`).
297    ///   Only applied when the CLI did not already set `--action`.
298    fn apply_custom_attributes(
299        &mut self,
300        attrs: &std::collections::HashMap<String, yaml_serde::Value>,
301    ) {
302        // rsigma.timestamp_field — prepend to priority list, skip duplicates
303        if let Some(field) = attrs.get("rsigma.timestamp_field").and_then(|v| v.as_str())
304            && !self.config.timestamp_fields.iter().any(|f| f == field)
305        {
306            self.config.timestamp_fields.insert(0, field.to_string());
307        }
308
309        // rsigma.suppress — only when CLI didn't already set one
310        if let Some(val) = attrs.get("rsigma.suppress").and_then(|v| v.as_str())
311            && self.config.suppress.is_none()
312            && let Ok(ts) = rsigma_parser::Timespan::parse(val)
313        {
314            self.config.suppress = Some(ts.seconds);
315        }
316
317        // rsigma.action — only when CLI left it at the default (Alert)
318        if let Some(val) = attrs.get("rsigma.action").and_then(|v| v.as_str())
319            && self.config.action_on_match == CorrelationAction::Alert
320            && let Ok(a) = val.parse::<CorrelationAction>()
321        {
322            self.config.action_on_match = a;
323        }
324    }
325
326    /// Add a single correlation rule.
327    pub fn add_correlation(&mut self, corr: &CorrelationRule) -> Result<()> {
328        let owned;
329        let effective = if self.pipelines.is_empty() {
330            corr
331        } else {
332            owned = {
333                let mut c = corr.clone();
334                apply_pipelines_to_correlation(&self.pipelines, &mut c)?;
335                c
336            };
337            &owned
338        };
339
340        // Apply engine-level custom attributes from the (possibly transformed)
341        // correlation rule (e.g. rsigma.timestamp_field).
342        self.apply_custom_attributes(&effective.custom_attributes);
343
344        let compiled = compile_correlation(effective)?;
345        if self.has_unbounded_long_window(&compiled) {
346            log::warn!(
347                "Correlation '{}' has a {}s timespan and no per-group entry cap; \
348                 a busy group retains timespan x event rate entries. \
349                 Set max_group_entries (--max-group-entries) or the rsigma.max_group_entries attribute to bound it.",
350                compiled.id.as_deref().unwrap_or(&compiled.title),
351                compiled.timespan_secs
352            );
353        }
354        let idx = self.correlations.len();
355
356        // Index by each referenced rule ID/name
357        for rule_ref in &compiled.rule_refs {
358            self.rule_index
359                .entry(rule_ref.clone())
360                .or_default()
361                .push(idx);
362        }
363
364        // A rule is standalone when any referencing correlation requests it,
365        // regardless of the order in which correlations are loaded.
366        for rule_ref in &compiled.rule_refs {
367            if compiled.generate {
368                self.generated_rules.insert(rule_ref.clone());
369                self.correlation_only_rules.remove(rule_ref);
370            } else if !self.generated_rules.contains(rule_ref) {
371                self.correlation_only_rules.insert(rule_ref.clone());
372            }
373        }
374
375        self.correlations.push(compiled);
376        self.retention_dirty = true;
377        Ok(())
378    }
379
380    /// Whether `corr` keeps a window longer than [`LONG_WINDOW_WARN_SECS`]
381    /// with no per-group entry cap from the rule or the engine config.
382    fn has_unbounded_long_window(&self, corr: &CompiledCorrelation) -> bool {
383        corr.timespan_secs > LONG_WINDOW_WARN_SECS
384            && corr
385                .max_group_entries
386                .or(self.config.max_group_entries)
387                .is_none()
388    }
389
390    /// Add all rules and correlations from a parsed collection.
391    ///
392    /// Detection rules are added first (so they're available for correlation
393    /// references), then correlation rules. Detection rules are compiled
394    /// sequentially and then pushed to the inner engine in a single batch,
395    /// so the inverted index and bloom filter are rebuilt exactly once for
396    /// the whole collection. Without this batching, large rule sets
397    /// (multi-thousand rules) hit an O(N²) rebuild cost on load.
398    pub fn add_collection(&mut self, collection: &SigmaCollection) -> Result<()> {
399        let mut compiled_batch = Vec::with_capacity(collection.rules.len());
400        if self.pipelines.is_empty() {
401            for rule in &collection.rules {
402                self.apply_custom_attributes(&rule.custom_attributes);
403                self.rule_ids
404                    .push((rule.id.clone(), rule.name.clone(), rule.title.clone()));
405                compiled_batch.push(crate::compiler::compile_rule(rule)?);
406            }
407        } else {
408            for rule in &collection.rules {
409                let mut transformed = rule.clone();
410                apply_pipelines(&self.pipelines, &mut transformed)?;
411                self.apply_custom_attributes(&transformed.custom_attributes);
412                self.rule_ids.push((
413                    transformed.id.clone(),
414                    transformed.name.clone(),
415                    transformed.title.clone(),
416                ));
417                // Bypass the inner engine's pipelines (would double-transform)
418                compiled_batch.push(crate::compiler::compile_rule(&transformed)?);
419            }
420        }
421        self.engine.extend_compiled_rules(compiled_batch);
422        // Apply filter rules to the inner engine's detection rules
423        for filter in &collection.filters {
424            self.engine.apply_filter(filter)?;
425        }
426        for corr in &collection.correlations {
427            self.add_correlation(corr)?;
428        }
429        self.validate_rule_refs()?;
430        self.detect_correlation_cycles()?;
431        Ok(())
432    }
433
434    /// Validate that every correlation's `rule_refs` resolve to at least one
435    /// known detection rule (by ID or name) or another correlation (by ID or name).
436    fn validate_rule_refs(&self) -> Result<()> {
437        let mut known: std::collections::HashSet<&str> = std::collections::HashSet::new();
438
439        for (id, name, _) in &self.rule_ids {
440            if let Some(id) = id {
441                known.insert(id.as_str());
442            }
443            if let Some(name) = name {
444                known.insert(name.as_str());
445            }
446        }
447        for corr in &self.correlations {
448            if let Some(ref id) = corr.id {
449                known.insert(id.as_str());
450            }
451            if let Some(ref name) = corr.name {
452                known.insert(name.as_str());
453            }
454        }
455
456        for corr in &self.correlations {
457            for rule_ref in &corr.rule_refs {
458                if !known.contains(rule_ref.as_str()) {
459                    return Err(EvalError::UnknownRuleRef(rule_ref.clone()));
460                }
461            }
462        }
463        Ok(())
464    }
465
466    /// Detect cycles in the correlation reference graph.
467    ///
468    /// Builds a directed graph where each correlation (identified by its id/name)
469    /// has edges to the correlations it references via `rule_refs`. Uses DFS with
470    /// a "gray/black" coloring scheme to detect back-edges (cycles).
471    ///
472    /// Returns `Err(EvalError::CorrelationCycle)` if a cycle is found.
473    fn detect_correlation_cycles(&self) -> Result<()> {
474        // Build a set of all correlation identifiers (id and/or name)
475        let mut corr_identifiers: HashMap<&str, usize> = HashMap::new();
476        for (idx, corr) in self.correlations.iter().enumerate() {
477            if let Some(ref id) = corr.id {
478                corr_identifiers.insert(id.as_str(), idx);
479            }
480            if let Some(ref name) = corr.name {
481                corr_identifiers.insert(name.as_str(), idx);
482            }
483        }
484
485        // Build adjacency list: corr index → set of corr indices it references
486        let mut adj: Vec<Vec<usize>> = vec![Vec::new(); self.correlations.len()];
487        for (idx, corr) in self.correlations.iter().enumerate() {
488            for rule_ref in &corr.rule_refs {
489                if let Some(&target_idx) = corr_identifiers.get(rule_ref.as_str()) {
490                    adj[idx].push(target_idx);
491                }
492            }
493        }
494
495        // DFS cycle detection with three states: white (unvisited), gray (in stack), black (done)
496        let mut state = vec![0u8; self.correlations.len()]; // 0=white, 1=gray, 2=black
497        let mut path: Vec<usize> = Vec::new();
498
499        for start in 0..self.correlations.len() {
500            if state[start] == 0
501                && let Some(cycle) = Self::dfs_find_cycle(start, &adj, &mut state, &mut path)
502            {
503                let names: Vec<String> = cycle
504                    .iter()
505                    .map(|&i| {
506                        self.correlations[i]
507                            .id
508                            .as_deref()
509                            .or(self.correlations[i].name.as_deref())
510                            .unwrap_or(&self.correlations[i].title)
511                            .to_string()
512                    })
513                    .collect();
514                return Err(crate::error::EvalError::CorrelationCycle(
515                    names.join(" -> "),
516                ));
517            }
518        }
519        Ok(())
520    }
521
522    /// DFS helper that returns the cycle path if a back-edge is found.
523    fn dfs_find_cycle(
524        node: usize,
525        adj: &[Vec<usize>],
526        state: &mut [u8],
527        path: &mut Vec<usize>,
528    ) -> Option<Vec<usize>> {
529        state[node] = 1; // gray
530        path.push(node);
531
532        for &next in &adj[node] {
533            if state[next] == 1 {
534                // Back-edge found — extract cycle from path
535                if let Some(pos) = path.iter().position(|&n| n == next) {
536                    let mut cycle = path[pos..].to_vec();
537                    cycle.push(next); // close the cycle
538                    return Some(cycle);
539                }
540            }
541            if state[next] == 0
542                && let Some(cycle) = Self::dfs_find_cycle(next, adj, state, path)
543            {
544                return Some(cycle);
545            }
546        }
547
548        path.pop();
549        state[node] = 2; // black
550        None
551    }
552
553    /// Process an event, extracting the timestamp from configured event fields.
554    ///
555    /// When no timestamp field is found, the `timestamp_fallback` policy applies:
556    /// - `WallClock`: use `Utc::now()` (good for real-time streaming)
557    /// - `Skip`: return detections only, skip correlation state updates
558    pub fn process_event<E: Event>(&mut self, event: &E) -> ProcessResult
559    where
560        L: ExtractLogSource<E>,
561    {
562        self.process_event_for_tenant(event, None)
563    }
564
565    /// Process an event as `tenant`, extracting the timestamp from configured
566    /// event fields.
567    ///
568    /// The tenant keys every window this event touches; correlation results
569    /// carry it. `None` is the untenanted bucket used when tenancy is off.
570    pub fn process_event_for_tenant<E: Event>(
571        &mut self,
572        event: &E,
573        tenant: Option<&TenantId>,
574    ) -> ProcessResult
575    where
576        L: ExtractLogSource<E>,
577    {
578        let detections = self.engine.evaluate_identified(event);
579        self.correlate_identified_detections_for_tenant(event, detections, tenant)
580    }
581
582    /// Run the correlation layer over externally-produced detections.
583    ///
584    /// Like [`process_event`](Self::process_event) but the detections are
585    /// supplied by the caller instead of computed by this engine's inner
586    /// detection engine. This lets a multi-engine router run detection in a
587    /// per-schema engine and still feed every detection into one shared
588    /// correlation store. Timestamp extraction and the `timestamp_fallback`
589    /// policy match `process_event`. Rule identity is recovered as in
590    /// [`process_with_detections`](Self::process_with_detections).
591    pub fn correlate_detections(
592        &mut self,
593        event: &impl Event,
594        all_detections: Vec<EvaluationResult>,
595    ) -> ProcessResult {
596        self.correlate_detections_for_tenant(event, all_detections, None)
597    }
598
599    /// Like [`correlate_detections`](Self::correlate_detections) but as
600    /// `tenant`.
601    pub fn correlate_detections_for_tenant(
602        &mut self,
603        event: &impl Event,
604        all_detections: Vec<EvaluationResult>,
605        tenant: Option<&TenantId>,
606    ) -> ProcessResult {
607        let identities = all_detections
608            .iter()
609            .map(|detection| self.find_rule_identity(detection))
610            .collect();
611        self.correlate_with_identities(event, all_detections, identities, tenant)
612    }
613
614    /// Run the correlation layer over detections identified by this engine's
615    /// rule table, keying every window by `tenant`.
616    pub(crate) fn correlate_identified_detections_for_tenant(
617        &mut self,
618        event: &impl Event,
619        detections: Vec<IdentifiedEvaluation>,
620        tenant: Option<&TenantId>,
621    ) -> ProcessResult {
622        let (all_detections, identities) = split_identified(detections);
623        self.correlate_with_identities(event, all_detections, identities, tenant)
624    }
625
626    fn correlate_with_identities(
627        &mut self,
628        event: &impl Event,
629        all_detections: Vec<EvaluationResult>,
630        identities: Vec<RuleIdentity>,
631        tenant: Option<&TenantId>,
632    ) -> ProcessResult {
633        let ts = match self.extract_event_timestamp(event) {
634            Some(ts) => ts,
635            None => match self.config.timestamp_fallback {
636                TimestampFallback::WallClock => Utc::now().timestamp(),
637                TimestampFallback::Skip => {
638                    // Still surface detections, but skip correlation state.
639                    return self.filter_detections(all_detections, identities);
640                }
641            },
642        };
643        self.process_with_detection_identities(event, all_detections, identities, ts, tenant)
644    }
645
646    /// Process an event with an explicit Unix epoch timestamp (seconds).
647    ///
648    /// The timestamp is clamped to `[0, i64::MAX / 2]` to prevent overflow
649    /// when adding timespan durations internally.
650    pub fn process_event_at<E: Event>(&mut self, event: &E, timestamp_secs: i64) -> ProcessResult
651    where
652        L: ExtractLogSource<E>,
653    {
654        self.process_event_at_for_tenant(event, timestamp_secs, None)
655    }
656
657    /// Like [`process_event_at`](Self::process_event_at) but as `tenant`.
658    pub fn process_event_at_for_tenant<E: Event>(
659        &mut self,
660        event: &E,
661        timestamp_secs: i64,
662        tenant: Option<&TenantId>,
663    ) -> ProcessResult
664    where
665        L: ExtractLogSource<E>,
666    {
667        let detections = self.engine.evaluate_identified(event);
668        let (all_detections, identities) = split_identified(detections);
669        self.process_with_detection_identities(
670            event,
671            all_detections,
672            identities,
673            timestamp_secs,
674            tenant,
675        )
676    }
677
678    /// Process an event with pre-computed detection results.
679    ///
680    /// Enables external parallelism: callers can run detection (via
681    /// [`evaluate`](Self::evaluate)) in parallel, then feed results here
682    /// sequentially for stateful correlation.
683    ///
684    /// A result carries its rule's `id` but not its `name`, so a detection
685    /// from a rule without an `id` is matched to its rule by title and feeds
686    /// no correlation when several such rules share that title.
687    /// [`process_event_at`](Self::process_event_at) and
688    /// [`process_batch`](Self::process_batch) keep the compiled identity.
689    pub fn process_with_detections(
690        &mut self,
691        event: &impl Event,
692        all_detections: Vec<EvaluationResult>,
693        timestamp_secs: i64,
694    ) -> ProcessResult {
695        self.process_with_detections_for_tenant(event, all_detections, timestamp_secs, None)
696    }
697
698    /// Like [`process_with_detections`](Self::process_with_detections) but as
699    /// `tenant`.
700    pub fn process_with_detections_for_tenant(
701        &mut self,
702        event: &impl Event,
703        all_detections: Vec<EvaluationResult>,
704        timestamp_secs: i64,
705        tenant: Option<&TenantId>,
706    ) -> ProcessResult {
707        let identities = all_detections
708            .iter()
709            .map(|detection| self.find_rule_identity(detection))
710            .collect();
711        self.process_with_detection_identities(
712            event,
713            all_detections,
714            identities,
715            timestamp_secs,
716            tenant,
717        )
718    }
719
720    fn process_with_detection_identities(
721        &mut self,
722        event: &impl Event,
723        all_detections: Vec<EvaluationResult>,
724        identities: Vec<RuleIdentity>,
725        timestamp_secs: i64,
726        tenant: Option<&TenantId>,
727    ) -> ProcessResult {
728        let timestamp_secs = timestamp_secs.clamp(0, i64::MAX / 2);
729
730        // A shared `None` bucket is never allowed when tenancy is required:
731        // skip the event's correlation update and count it.
732        if self.config.require_tenant && tenant.is_none() {
733            self.untenanted_skipped += 1;
734            return self.filter_detections(all_detections, identities);
735        }
736
737        // Memory management — evict before adding new state to enforce limit
738        if self.state.len() >= self.config.max_state_entries {
739            self.evict_all(timestamp_secs);
740        }
741
742        if self.retention_dirty {
743            self.refresh_retention();
744        }
745
746        let event_seq = self.next_event_seq;
747        self.next_event_seq = self.next_event_seq.saturating_add(1);
748
749        // Feed detection matches into correlations
750        let mut correlations: Vec<EvaluationResult> = Vec::new();
751        let mut fired_indices = Vec::new();
752        let mut fired_retained = Vec::new();
753        self.feed_detections(
754            event,
755            &identities,
756            timestamp_secs,
757            tenant,
758            event_seq,
759            &mut correlations,
760            &mut fired_indices,
761            &mut fired_retained,
762        );
763
764        // Chain — parent firings go into a separate vec so we do not
765        // alias `correlations` as both the input slice and the output.
766        let mut chained = Vec::new();
767        let mut chained_indices = Vec::new();
768        self.chain_correlations(
769            &correlations,
770            &fired_indices,
771            fired_retained,
772            timestamp_secs,
773            &mut chained,
774            &mut chained_indices,
775        );
776        correlations.extend(chained);
777        fired_indices.extend(chained_indices);
778
779        // Filter detections and correlations by the generate flag of the
780        // correlations that reference them.
781        let mut out = self.filter_detections(all_detections, identities);
782        out.extend(
783            correlations
784                .into_iter()
785                .zip(fired_indices)
786                .filter(|(_, idx)| {
787                    let corr = &self.correlations[*idx];
788                    let identities = corr.id.as_deref().into_iter().chain(corr.name.as_deref());
789                    !self.is_correlation_only(identities)
790                })
791                .map(|(result, _)| result),
792        );
793        out
794    }
795
796    /// Number of events skipped by `require_tenant` because they carried no
797    /// tenant.
798    pub fn untenanted_skipped(&self) -> u64 {
799        self.untenanted_skipped
800    }
801
802    /// Events skipped by `require_tenant` since the previous call, draining the
803    /// counter.
804    pub fn take_untenanted_skipped(&mut self) -> u64 {
805        std::mem::take(&mut self.untenanted_skipped)
806    }
807
808    /// Set the per-tenant state cap. `None` leaves only the global cap.
809    pub fn set_max_state_entries_per_tenant(&mut self, max: Option<usize>) {
810        self.config.max_state_entries_per_tenant = max;
811        self.tenant_keys.clear();
812        if max.is_some() {
813            for key in self.state.keys() {
814                self.tenant_keys
815                    .entry(key.tenant.clone())
816                    .or_default()
817                    .insert(key.clone());
818            }
819        }
820    }
821
822    /// Entries evicted because a tenant hit its quota since the previous call,
823    /// draining the counter.
824    pub fn take_tenant_quota_evictions(&mut self) -> u64 {
825        std::mem::take(&mut self.tenant_quota_evictions)
826    }
827
828    /// Run stateless detection only (no correlation), delegating to the inner engine.
829    ///
830    /// Returns one [`EvaluationResult`] per matched detection. Takes `&self`
831    /// so it can be called concurrently from multiple threads (e.g. via
832    /// `rayon::par_iter`) while the mutable correlation phase runs
833    /// sequentially afterwards.
834    pub fn evaluate<E: Event>(&self, event: &E) -> Vec<EvaluationResult>
835    where
836        L: ExtractLogSource<E>,
837    {
838        self.engine.evaluate(event)
839    }
840
841    /// Process a batch of events: parallel detection, then sequential correlation.
842    ///
843    /// When the `parallel` feature is enabled, the stateless detection phase runs
844    /// concurrently via rayon. Timestamp extraction also runs in the parallel
845    /// phase (it borrows `&self.config` immutably). After `collect()` releases the
846    /// immutable borrows, each event's pre-computed detections are fed into the
847    /// stateful correlation engine sequentially.
848    pub fn process_batch<E: Event + Sync>(&mut self, events: &[&E]) -> Vec<ProcessResult>
849    where
850        L: ExtractLogSource<E> + Sync,
851    {
852        self.process_batch_for_tenants(events, &[])
853    }
854
855    /// Process a batch of events, each as the tenant at its position in
856    /// `tenants`.
857    ///
858    /// `tenants` is either empty (every event is untenanted) or exactly as
859    /// long as `events`. Any other length is a caller bug: in debug builds it
860    /// trips a `debug_assert!`, and in release builds it logs and returns one
861    /// empty result per event.
862    pub fn process_batch_for_tenants<E: Event + Sync>(
863        &mut self,
864        events: &[&E],
865        tenants: &[Option<TenantId>],
866    ) -> Vec<ProcessResult>
867    where
868        L: ExtractLogSource<E> + Sync,
869    {
870        if !tenants.is_empty() && tenants.len() != events.len() {
871            debug_assert!(
872                false,
873                "tenants must be empty or parallel to events: {} tenants for {} events",
874                tenants.len(),
875                events.len()
876            );
877            log::error!(
878                "tenant slice length mismatch: {} tenants for {} events; returning empty results",
879                tenants.len(),
880                events.len()
881            );
882            return vec![ProcessResult::new(); events.len()];
883        }
884
885        // Borrow split: take immutable refs to fields needed for the parallel phase.
886        // These are released by collect() before the sequential &mut self phase.
887        let engine = &self.engine;
888        let ts_fields = &self.config.timestamp_fields;
889
890        let batch_results: Vec<(Vec<IdentifiedEvaluation>, Option<i64>)> =
891            crate::parallel::map_ordered(events, |e| {
892                let detections = engine.evaluate_identified(e);
893                let ts = extract_event_ts(e, ts_fields);
894                (detections, ts)
895            });
896
897        // Sequential correlation phase
898        let mut results = Vec::with_capacity(events.len());
899        for (index, ((identified, ts_opt), event)) in
900            batch_results.into_iter().zip(events).enumerate()
901        {
902            let tenant = crate::tenant::tenant_at(tenants, index);
903            let (detections, identities) = split_identified(identified);
904            let ts = match ts_opt {
905                Some(ts) => ts,
906                None => match self.config.timestamp_fallback {
907                    TimestampFallback::WallClock => Utc::now().timestamp(),
908                    TimestampFallback::Skip => {
909                        // Still return detection results, but skip correlation
910                        results.push(self.filter_detections(detections, identities));
911                        continue;
912                    }
913                },
914            };
915            results.push(
916                self.process_with_detection_identities(event, detections, identities, ts, tenant),
917            );
918        }
919        results
920    }
921
922    /// Filter detections by the `generate` flag / `emit_detections` config.
923    ///
924    /// If `emit_detections` is false and some rules are correlation-only,
925    /// their detection output is suppressed.
926    fn filter_detections(
927        &self,
928        all_detections: Vec<EvaluationResult>,
929        identities: Vec<RuleIdentity>,
930    ) -> Vec<EvaluationResult> {
931        if !self.config.emit_detections && !self.correlation_only_rules.is_empty() {
932            all_detections
933                .into_iter()
934                .zip(identities)
935                .filter_map(|(detection, (id, name))| {
936                    let identities = id.as_deref().into_iter().chain(name.as_deref());
937                    (!self.is_correlation_only(identities)).then_some(detection)
938                })
939                .collect()
940        } else {
941            all_detections
942        }
943    }
944
945    /// Whether output for a rule (detection or correlation) with these
946    /// identities is suppressed: only correlations without `generate: true`
947    /// reference it, and `emit_detections` is off.
948    fn is_correlation_only<'a>(
949        &self,
950        mut identities: impl Iterator<Item = &'a str> + Clone,
951    ) -> bool {
952        !self.config.emit_detections
953            && identities
954                .clone()
955                .any(|identity| self.correlation_only_rules.contains(identity))
956            && !identities.any(|identity| self.generated_rules.contains(identity))
957    }
958
959    /// Feed detection matches into correlation window states.
960    #[allow(clippy::too_many_arguments)]
961    fn feed_detections(
962        &mut self,
963        event: &impl Event,
964        identities: &[RuleIdentity],
965        ts: i64,
966        tenant: Option<&TenantId>,
967        event_seq: u64,
968        out: &mut Vec<EvaluationResult>,
969        fired_indices: &mut Vec<usize>,
970        fired_retained: &mut Vec<Option<Retained>>,
971    ) {
972        // Collect all (corr_idx, rule_id, rule_name) tuples upfront to avoid
973        // borrow conflicts between self.rule_ids and self.update_correlation.
974        let mut work: Vec<(usize, Option<String>, Option<String>)> = Vec::new();
975
976        for (rule_id, rule_name) in identities {
977            // Collect correlation indices that reference this rule
978            let mut corr_indices = Vec::new();
979            if let Some(id) = rule_id
980                && let Some(indices) = self.rule_index.get(id)
981            {
982                corr_indices.extend(indices);
983            }
984            if let Some(name) = rule_name
985                && let Some(indices) = self.rule_index.get(name)
986            {
987                corr_indices.extend(indices);
988            }
989
990            corr_indices.sort_unstable();
991            corr_indices.dedup();
992
993            for &corr_idx in &corr_indices {
994                work.push((corr_idx, rule_id.clone(), rule_name.clone()));
995            }
996        }
997
998        for (corr_idx, rule_id, rule_name) in work {
999            let before = out.len();
1000            let retained = self.update_correlation(
1001                corr_idx, event, ts, tenant, &rule_id, &rule_name, event_seq, out,
1002            );
1003            if out.len() > before {
1004                fired_indices.push(corr_idx);
1005                fired_retained.push(retained);
1006            }
1007        }
1008    }
1009
1010    /// Find the (id, name) for a detection match by searching our rule_ids table.
1011    fn find_rule_identity(&self, det: &EvaluationResult) -> RuleIdentity {
1012        // Prefer the stable ID carried by the result.
1013        if let Some(ref match_id) = det.header.rule_id {
1014            for (id, name, _) in &self.rule_ids {
1015                if id.as_deref() == Some(match_id.as_str()) {
1016                    return (id.clone(), name.clone());
1017                }
1018            }
1019        }
1020
1021        // `process_with_detections` accepts the public EvaluationResult shape,
1022        // which does not carry a rule name. Recover name-only rule identity
1023        // from the title retained alongside the compiled rule.
1024        let mut title_matches = self
1025            .rule_ids
1026            .iter()
1027            .filter(|(_, _, title)| title == &det.header.rule_title);
1028        if let Some((id, name, _)) = title_matches.next()
1029            && title_matches.next().is_none()
1030        {
1031            return (id.clone(), name.clone());
1032        }
1033
1034        (det.header.rule_id.clone(), None)
1035    }
1036
1037    /// Update a single correlation's state and check its condition.
1038    ///
1039    /// When the correlation fires and a correlation that references it
1040    /// retains events, returns the entries it retained at that moment, captured
1041    /// before an `action: reset` clears them.
1042    #[allow(clippy::too_many_arguments)]
1043    fn update_correlation(
1044        &mut self,
1045        corr_idx: usize,
1046        event: &impl Event,
1047        ts: i64,
1048        tenant: Option<&TenantId>,
1049        rule_id: &Option<String>,
1050        rule_name: &Option<String>,
1051        event_seq: u64,
1052        out: &mut Vec<EvaluationResult>,
1053    ) -> Option<Retained> {
1054        // Copy the scalars and resolve the group key while borrowing the
1055        // correlation immutably. The borrow ends before the state entry so the
1056        // tenant quota can evict from `self.state`.
1057        let (
1058            corr_type,
1059            timespan,
1060            window_mode,
1061            gap_secs,
1062            level,
1063            suppress_secs,
1064            action,
1065            event_mode,
1066            max_events,
1067            retention_mode,
1068            retention_cap,
1069            max_group_entries,
1070            rule_ref,
1071            source_rule,
1072            group_key,
1073        ) = {
1074            let corr = &self.correlations[corr_idx];
1075            let corr_type = corr.correlation_type;
1076            let timespan = corr.timespan_secs;
1077            let window_mode = corr.window_mode;
1078            let gap_secs = corr.gap_secs;
1079            let level = corr.level;
1080            let suppress_secs = corr.suppress_secs.or(self.config.suppress);
1081            let action = corr.action.unwrap_or(self.config.action_on_match);
1082            let event_mode = corr
1083                .event_mode
1084                .unwrap_or(self.config.correlation_event_mode);
1085            let max_events = corr
1086                .max_events
1087                .unwrap_or(self.config.max_correlation_events);
1088            let retention_mode = self.retention[corr_idx].mode;
1089            let retention_cap = self.retention[corr_idx].cap;
1090            let max_group_entries = corr.max_group_entries.or(self.config.max_group_entries);
1091
1092            // Determine the rule_ref strings for alias resolution and temporal tracking.
1093            let mut ref_strs: Vec<&str> = Vec::new();
1094            if let Some(id) = rule_id.as_deref() {
1095                ref_strs.push(id);
1096            }
1097            if let Some(name) = rule_name.as_deref() {
1098                ref_strs.push(name);
1099            }
1100            let rule_pos = ref_strs.iter().find_map(|identity| {
1101                corr.rule_refs
1102                    .iter()
1103                    .position(|rule_ref| rule_ref == identity)
1104            });
1105            let rule_ref = rule_pos
1106                .map(|pos| corr.rule_refs[pos].clone())
1107                .unwrap_or_default();
1108            let source_rule =
1109                rule_pos.and_then(|pos| self.retention[corr_idx].rule_refs.get(pos).cloned());
1110
1111            // An event without every group-by value cannot be assigned to a
1112            // correlation group.
1113            let group_key = GroupKey::extract(event, &corr.group_by, &ref_strs)?;
1114
1115            (
1116                corr_type,
1117                timespan,
1118                window_mode,
1119                gap_secs,
1120                level,
1121                suppress_secs,
1122                action,
1123                event_mode,
1124                max_events,
1125                retention_mode,
1126                retention_cap,
1127                max_group_entries,
1128                rule_ref,
1129                source_rule,
1130                group_key,
1131            )
1132        };
1133
1134        // Get or create window state
1135        let state_key = StateKey {
1136            tenant: tenant.cloned(),
1137            corr_idx,
1138            group_key: group_key.clone(),
1139        };
1140        let is_new = !self.state.contains_key(&state_key);
1141        if is_new
1142            && let Some(cap) = self.config.max_state_entries_per_tenant
1143            && self.tenant_len(&state_key.tenant) >= cap
1144        {
1145            self.evict_tenant(tenant, ts);
1146        }
1147        if is_new {
1148            self.note_tenant_insert(&state_key);
1149        }
1150        let state = self
1151            .state
1152            .entry(state_key.clone())
1153            .or_insert_with(|| WindowState::new_for(corr_type));
1154
1155        // Re-borrow the correlation: `self.state` and `self.correlations` are
1156        // disjoint fields, so the mutable state borrow and this read coexist.
1157        let corr = &self.correlations[corr_idx];
1158
1159        // Apply the window's pre-insert maintenance (sliding evict, tumbling
1160        // bucket reset/late-event discard, or session gap/cap reset). On
1161        // `Reset` the event buffers below are cleared in sync; on `Discard`
1162        // (a late arrival in an earlier tumbling bucket) the event is dropped
1163        // without touching the state or buffers.
1164        let cutoff = ts - timespan as i64;
1165        let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
1166        if decision == WindowDecision::Discard {
1167            return None;
1168        }
1169        let reset = decision == WindowDecision::Reset;
1170
1171        // Push the new event into the state
1172        match corr_type {
1173            CorrelationType::EventCount => {
1174                state.push_event_count(ts);
1175            }
1176            CorrelationType::ValueCount => {
1177                if let Some(ref fields) = corr.condition.field
1178                    && let Some(key) = composite_value_count_key(event, fields)
1179                {
1180                    state.push_value_count(ts, key);
1181                }
1182            }
1183            CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
1184                state.push_temporal(ts, &rule_ref);
1185            }
1186            CorrelationType::ValueSum
1187            | CorrelationType::ValueAvg
1188            | CorrelationType::ValuePercentile
1189            | CorrelationType::ValueMedian => {
1190                if let Some(ref fields) = corr.condition.field
1191                    && let Some(field_name) = fields.first()
1192                    && let Some(val) = event.get_field(field_name)
1193                    && let Some(n) = value_to_f64_ev(&val)
1194                {
1195                    state.push_numeric(ts, n);
1196                }
1197            }
1198        }
1199
1200        // Enforce the per-group entry cap. Session windows keep their oldest
1201        // entry as the span anchor so truncation cannot silently extend the
1202        // `timespan` cap.
1203        if let Some(cap) = max_group_entries {
1204            state.truncate_oldest(cap, window_mode == WindowMode::Session);
1205        }
1206
1207        // Push event into the buffer its retention requires, which can be
1208        // stronger than this correlation's own mode when a parent retains
1209        // events. Keep the buffer's retained entries aligned with the window
1210        // state: sliding evicts by the trailing cutoff, while tumbling/session
1211        // clear the buffer when the window reset.
1212        match retention_mode {
1213            CorrelationEventMode::Full => {
1214                let buf = self
1215                    .event_buffers
1216                    .entry(state_key.clone())
1217                    .or_insert_with(|| EventBuffer::new(retention_cap));
1218                if window_mode == rsigma_parser::WindowMode::Sliding {
1219                    buf.evict(cutoff);
1220                } else if reset {
1221                    buf.clear();
1222                }
1223                let json = event.to_json();
1224                buf.push_seq(event_seq, ts, &json, source_rule);
1225            }
1226            CorrelationEventMode::Refs => {
1227                let buf = self
1228                    .event_ref_buffers
1229                    .entry(state_key.clone())
1230                    .or_insert_with(|| EventRefBuffer::new(retention_cap));
1231                if window_mode == rsigma_parser::WindowMode::Sliding {
1232                    buf.evict(cutoff);
1233                } else if reset {
1234                    buf.clear();
1235                }
1236                let json = event.to_json();
1237                buf.push_seq(event_seq, ts, &json, source_rule);
1238            }
1239            CorrelationEventMode::None => {}
1240        }
1241
1242        // Check condition — after this, `state` is no longer used (NLL drops the borrow).
1243        let fired = state.check_condition(
1244            &corr.condition,
1245            corr_type,
1246            &corr.rule_refs,
1247            corr.extended_expr.as_ref(),
1248        );
1249
1250        if let Some(agg_value) = fired {
1251            let alert_key = state_key.clone();
1252
1253            // Suppression check: skip if we've already alerted within the suppress window
1254            let suppressed = if let Some(suppress) = suppress_secs {
1255                if let Some(&last_ts) = self.last_alert.get(&alert_key) {
1256                    (ts - last_ts) < suppress as i64
1257                } else {
1258                    false
1259                }
1260            } else {
1261                false
1262            };
1263
1264            if !suppressed {
1265                let reported = self.reported_events(&alert_key, event_mode, max_events);
1266                let retained = self.capture_retained(&alert_key);
1267
1268                // Only clone title/id/tags when we actually produce output
1269                let corr = &self.correlations[corr_idx];
1270                let result = EvaluationResult {
1271                    header: RuleHeader {
1272                        rule_title: corr.title.clone(),
1273                        rule_id: corr.id.clone(),
1274                        tenant_id: tenant.cloned(),
1275                        level,
1276                        tags: corr.tags.clone(),
1277                        custom_attributes: corr.custom_attributes.clone(),
1278                        enrichments: None,
1279                        ruleset: None,
1280                    },
1281                    body: ResultBody::Correlation(CorrelationBody {
1282                        correlation_type: corr_type,
1283                        group_key: group_key.to_pairs(&corr.group_by),
1284                        aggregated_value: agg_value,
1285                        timespan_secs: timespan,
1286                        events: reported.events,
1287                        event_refs: reported.event_refs,
1288                        event_sources: reported.event_sources,
1289                    }),
1290                };
1291                out.push(result);
1292
1293                // Record alert time for suppression
1294                self.last_alert.insert(alert_key.clone(), ts);
1295
1296                // Action on match
1297                if action == CorrelationAction::Reset {
1298                    if let Some(state) = self.state.get_mut(&alert_key) {
1299                        state.clear();
1300                    }
1301                    if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
1302                        buf.clear();
1303                    }
1304                    if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
1305                        buf.clear();
1306                    }
1307                }
1308                return retained;
1309            }
1310        }
1311        None
1312    }
1313
1314    /// Events or references a correlation reports for one group: the newest
1315    /// `cap` retained entries in its own `mode`, oldest first. A refs mode can
1316    /// read a buffer that a parent's retention made full.
1317    fn reported_events(
1318        &self,
1319        key: &StateKey,
1320        mode: CorrelationEventMode,
1321        cap: usize,
1322    ) -> ReportedEvents {
1323        match mode {
1324            CorrelationEventMode::Full => {
1325                let (events, sources) = self
1326                    .event_buffers
1327                    .get(key)
1328                    .map(|buf| buf.newest_events(cap))
1329                    .unwrap_or_default();
1330                ReportedEvents {
1331                    events: Some(events),
1332                    event_refs: None,
1333                    event_sources: Some(sources),
1334                }
1335            }
1336            CorrelationEventMode::Refs => {
1337                let (refs, sources) = if let Some(buf) = self.event_ref_buffers.get(key) {
1338                    buf.newest_refs(cap)
1339                } else if let Some(buf) = self.event_buffers.get(key) {
1340                    buf.newest_refs(cap)
1341                } else {
1342                    Default::default()
1343                };
1344                ReportedEvents {
1345                    events: None,
1346                    event_refs: Some(refs),
1347                    event_sources: Some(sources),
1348                }
1349            }
1350            CorrelationEventMode::None => ReportedEvents::default(),
1351        }
1352    }
1353
1354    /// Entries a firing correlation hands to the correlations that reference
1355    /// it, or `None` when none of them retains events.
1356    fn capture_retained(&self, key: &StateKey) -> Option<Retained> {
1357        let retention = &self.retention[key.corr_idx];
1358        if !retention.feeds_retaining_parent {
1359            return None;
1360        }
1361        match retention.mode {
1362            CorrelationEventMode::Full => self.event_buffers.get(key).map(EventBuffer::retained),
1363            CorrelationEventMode::Refs => self
1364                .event_ref_buffers
1365                .get(key)
1366                .map(EventRefBuffer::retained),
1367            CorrelationEventMode::None => None,
1368        }
1369    }
1370
1371    /// Merge the entries the firing child `via` delivered into a parent's
1372    /// buffer for `key`, converting full entries when the parent retains only
1373    /// references.
1374    fn merge_retained(&mut self, key: &StateKey, retained: &Retained, via: Option<&Arc<str>>) {
1375        let retention = &self.retention[key.corr_idx];
1376        let cap = retention.cap;
1377        match (retention.mode, retained) {
1378            (CorrelationEventMode::Full, Retained::Full(entries)) => {
1379                self.event_buffers
1380                    .entry(key.clone())
1381                    .or_insert_with(|| EventBuffer::new(cap))
1382                    .merge(entries, via);
1383            }
1384            (CorrelationEventMode::Refs, Retained::Refs(entries)) => {
1385                self.event_ref_buffers
1386                    .entry(key.clone())
1387                    .or_insert_with(|| EventRefBuffer::new(cap))
1388                    .merge(entries, via);
1389            }
1390            (CorrelationEventMode::Refs, Retained::Full(entries)) => {
1391                let refs: Vec<RefEntry> = entries.iter().filter_map(|e| e.to_ref()).collect();
1392                self.event_ref_buffers
1393                    .entry(key.clone())
1394                    .or_insert_with(|| EventRefBuffer::new(cap))
1395                    .merge(&refs, via);
1396            }
1397            // A child retains at least as strongly as every parent, so a full
1398            // parent only meets reference entries past the chain depth limit.
1399            (CorrelationEventMode::Full, Retained::Refs(_)) | (CorrelationEventMode::None, _) => {}
1400        }
1401    }
1402
1403    /// Recompute the event retention each correlation needs from its own mode
1404    /// and cap and from every correlation that references it, directly or
1405    /// through another correlation.
1406    fn refresh_retention(&mut self) {
1407        let len = self.correlations.len();
1408        let mut retention = vec![Retention::default(); len];
1409        let mut done = vec![false; len];
1410        let mut visiting = vec![false; len];
1411        for idx in 0..len {
1412            self.compute_retention(idx, &mut retention, &mut done, &mut visiting, 0);
1413        }
1414        for (idx, entry) in retention.iter_mut().enumerate() {
1415            if entry.mode != CorrelationEventMode::None {
1416                entry.rule_refs = self.correlations[idx]
1417                    .rule_refs
1418                    .iter()
1419                    .map(|rule_ref| Arc::from(rule_ref.as_str()))
1420                    .collect();
1421                entry.stable_id = Some(Arc::from(self.correlation_stable_id(idx)));
1422            }
1423        }
1424        self.retention = retention;
1425        self.retention_dirty = false;
1426    }
1427
1428    /// Resolve one correlation's retention by walking to the correlations that
1429    /// reference it. `add_correlation` alone does not reject cycles, so the
1430    /// walk stops on a correlation already being resolved and at
1431    /// [`MAX_CHAIN_DEPTH`].
1432    fn compute_retention(
1433        &self,
1434        idx: usize,
1435        out: &mut [Retention],
1436        done: &mut [bool],
1437        visiting: &mut [bool],
1438        depth: usize,
1439    ) -> Retention {
1440        if done[idx] {
1441            return out[idx].clone();
1442        }
1443        let own = self.own_retention(idx);
1444        if visiting[idx] || depth >= MAX_CHAIN_DEPTH {
1445            return own;
1446        }
1447
1448        visiting[idx] = true;
1449        let mut result = own;
1450        for parent in self.referencing_correlations(idx) {
1451            let parent_retention = self.compute_retention(parent, out, done, visiting, depth + 1);
1452            result.mode = stronger_mode(result.mode, parent_retention.mode);
1453            if parent_retention.mode != CorrelationEventMode::None {
1454                result.feeds_retaining_parent = true;
1455                result.cap = result.cap.max(parent_retention.cap);
1456            }
1457        }
1458        visiting[idx] = false;
1459
1460        out[idx] = result.clone();
1461        done[idx] = true;
1462        result
1463    }
1464
1465    /// Event retention a correlation requests for itself, before propagation.
1466    fn own_retention(&self, idx: usize) -> Retention {
1467        let corr = &self.correlations[idx];
1468        let mode = corr
1469            .event_mode
1470            .unwrap_or(self.config.correlation_event_mode);
1471        let cap = corr
1472            .max_events
1473            .unwrap_or(self.config.max_correlation_events);
1474        Retention {
1475            mode,
1476            cap: if mode == CorrelationEventMode::None {
1477                0
1478            } else {
1479                cap
1480            },
1481            ..Retention::default()
1482        }
1483    }
1484
1485    /// Correlations whose `rule_refs` name `idx`.
1486    fn referencing_correlations(&self, idx: usize) -> Vec<usize> {
1487        let mut parents = Vec::new();
1488        for key in self.chain_lookup_keys(idx) {
1489            if let Some(indices) = self.rule_index.get(&key) {
1490                for &parent in indices {
1491                    if !parents.contains(&parent) {
1492                        parents.push(parent);
1493                    }
1494                }
1495            }
1496        }
1497        parents
1498    }
1499
1500    /// IDs and names a fired correlation can be referenced by.
1501    ///
1502    /// Parents index `rule_refs` as written in YAML (id or name). The
1503    /// emitted result only carries `rule_id`, so name-based parents need
1504    /// this extra key or they never see the child.
1505    fn chain_lookup_keys(&self, corr_idx: usize) -> Vec<String> {
1506        let corr = &self.correlations[corr_idx];
1507        let mut keys = Vec::with_capacity(2);
1508        keys.extend(corr.id.iter().cloned());
1509        if corr.name.as_ref() != corr.id.as_ref() {
1510            keys.extend(corr.name.iter().cloned());
1511        }
1512        keys
1513    }
1514
1515    /// Propagate correlation results to higher-level correlations (chaining).
1516    ///
1517    /// When a correlation fires, any correlation that references it (by ID or name)
1518    /// is updated. Newly fired parents are appended to `out`, with their
1519    /// correlation indices in `out_indices`, and become the next `pending`
1520    /// set. Limits chain depth to 10 to prevent infinite loops.
1521    fn chain_correlations(
1522        &mut self,
1523        fired: &[EvaluationResult],
1524        fired_indices: &[usize],
1525        fired_retained: Vec<Option<Retained>>,
1526        ts: i64,
1527        out: &mut Vec<EvaluationResult>,
1528        out_indices: &mut Vec<usize>,
1529    ) {
1530        debug_assert_eq!(fired.len(), fired_indices.len());
1531        debug_assert_eq!(fired.len(), fired_retained.len());
1532        // Chaining only needs which correlation fired, for which group, and
1533        // the events it retained, so `pending` carries that instead of cloning
1534        // results. Retained entries live once per level in `retained` next to
1535        // the child that delivered them, and pending and work items index into
1536        // it, so a child that feeds several parents is not cloned per parent.
1537        // Only correlation results chain. Detections never reach here.
1538        let mut retained: Vec<(Retained, Option<Arc<str>>)> = Vec::new();
1539        #[allow(clippy::type_complexity)]
1540        let mut pending: Vec<(
1541            usize,
1542            Vec<(String, String)>,
1543            Option<TenantId>,
1544            Option<usize>,
1545        )> = fired_indices
1546            .iter()
1547            .zip(fired)
1548            .zip(fired_retained)
1549            .filter_map(|((&idx, result), entries)| {
1550                let group_key = result.as_correlation()?.group_key.clone();
1551                let slot = entries.map(|entries| {
1552                    retained.push((entries, self.retention[idx].stable_id.clone()));
1553                    retained.len() - 1
1554                });
1555                Some((idx, group_key, result.header.tenant_id.clone(), slot))
1556            })
1557            .collect();
1558        let mut depth = 0;
1559
1560        while !pending.is_empty() && depth < MAX_CHAIN_DEPTH {
1561            depth += 1;
1562
1563            // Collect work items: (corr_idx, group_key_pairs, fired_ref, tenant, retained slot)
1564            #[allow(clippy::type_complexity)]
1565            let mut work: Vec<(
1566                usize,
1567                Vec<(String, String)>,
1568                String,
1569                Option<TenantId>,
1570                Option<usize>,
1571            )> = Vec::new();
1572            let mut seen = std::collections::HashSet::<(usize, String, Option<TenantId>)>::new();
1573            for (source_idx, group_key, tenant, slot) in &pending {
1574                for key in self.chain_lookup_keys(*source_idx) {
1575                    if let Some(indices) = self.rule_index.get(&key) {
1576                        for &corr_idx in indices {
1577                            if seen.insert((corr_idx, key.clone(), tenant.clone())) {
1578                                work.push((
1579                                    corr_idx,
1580                                    group_key.clone(),
1581                                    key.clone(),
1582                                    tenant.clone(),
1583                                    *slot,
1584                                ));
1585                            }
1586                        }
1587                    }
1588                }
1589            }
1590
1591            let mut next_pending = Vec::new();
1592            let mut next_retained = Vec::new();
1593            for (corr_idx, group_key_pairs, fired_ref, tenant, slot) in work {
1594                let (
1595                    corr_type,
1596                    timespan,
1597                    window_mode,
1598                    gap_secs,
1599                    level,
1600                    suppress_secs,
1601                    action,
1602                    event_mode,
1603                    max_events,
1604                    max_group_entries,
1605                    group_key,
1606                ) = {
1607                    let corr = &self.correlations[corr_idx];
1608                    let Some(group_key) = GroupKey::from_pairs(&group_key_pairs, &corr.group_by)
1609                    else {
1610                        continue;
1611                    };
1612                    (
1613                        corr.correlation_type,
1614                        corr.timespan_secs,
1615                        corr.window_mode,
1616                        corr.gap_secs,
1617                        corr.level,
1618                        corr.suppress_secs.or(self.config.suppress),
1619                        corr.action.unwrap_or(self.config.action_on_match),
1620                        corr.event_mode
1621                            .unwrap_or(self.config.correlation_event_mode),
1622                        corr.max_events
1623                            .unwrap_or(self.config.max_correlation_events),
1624                        corr.max_group_entries.or(self.config.max_group_entries),
1625                        group_key,
1626                    )
1627                };
1628                let state_key = StateKey {
1629                    tenant: tenant.clone(),
1630                    corr_idx,
1631                    group_key: group_key.clone(),
1632                };
1633                let is_new = !self.state.contains_key(&state_key);
1634                if is_new
1635                    && let Some(cap) = self.config.max_state_entries_per_tenant
1636                    && self.tenant_len(&state_key.tenant) >= cap
1637                {
1638                    self.evict_tenant(tenant.as_ref(), ts);
1639                }
1640                if is_new {
1641                    self.note_tenant_insert(&state_key);
1642                }
1643                let state = self
1644                    .state
1645                    .entry(state_key.clone())
1646                    .or_insert_with(|| WindowState::new_for(corr_type));
1647
1648                // Late arrivals in an earlier tumbling bucket are discarded.
1649                // A tumbling or session reset clears the parent's buffers in
1650                // sync with its window state, as on the direct path.
1651                let decision = apply_window_open(state, ts, timespan, window_mode, gap_secs);
1652                if decision == WindowDecision::Discard {
1653                    continue;
1654                }
1655                if decision == WindowDecision::Reset {
1656                    if let Some(buf) = self.event_buffers.get_mut(&state_key) {
1657                        buf.clear();
1658                    }
1659                    if let Some(buf) = self.event_ref_buffers.get_mut(&state_key) {
1660                        buf.clear();
1661                    }
1662                }
1663
1664                match corr_type {
1665                    CorrelationType::EventCount => {
1666                        state.push_event_count(ts);
1667                    }
1668                    CorrelationType::Temporal | CorrelationType::TemporalOrdered => {
1669                        state.push_temporal(ts, &fired_ref);
1670                    }
1671                    _ => {
1672                        state.push_event_count(ts);
1673                    }
1674                }
1675
1676                // Same per-group cap as the direct path; session windows
1677                // keep the span anchor.
1678                if let Some(cap) = max_group_entries {
1679                    state.truncate_oldest(cap, window_mode == WindowMode::Session);
1680                }
1681
1682                // `self.state` and `self.correlations` are disjoint fields, so
1683                // the mutable state borrow and this read coexist.
1684                let corr = &self.correlations[corr_idx];
1685                let fired = state.check_condition(
1686                    &corr.condition,
1687                    corr_type,
1688                    &corr.rule_refs,
1689                    corr.extended_expr.as_ref(),
1690                );
1691
1692                if let Some(slot) = slot {
1693                    let (entries, via) = &retained[slot];
1694                    self.merge_retained(&state_key, entries, via.as_ref());
1695                }
1696                if window_mode == WindowMode::Sliding {
1697                    let cutoff = ts - timespan as i64;
1698                    if let Some(buf) = self.event_buffers.get_mut(&state_key) {
1699                        buf.evict(cutoff);
1700                    }
1701                    if let Some(buf) = self.event_ref_buffers.get_mut(&state_key) {
1702                        buf.evict(cutoff);
1703                    }
1704                }
1705
1706                if let Some(agg_value) = fired {
1707                    let alert_key = state_key;
1708                    let suppressed = if let Some(suppress) = suppress_secs {
1709                        self.last_alert
1710                            .get(&alert_key)
1711                            .is_some_and(|&last_ts| (ts - last_ts) < suppress as i64)
1712                    } else {
1713                        false
1714                    };
1715                    if suppressed {
1716                        continue;
1717                    }
1718
1719                    let reported = self.reported_events(&alert_key, event_mode, max_events);
1720                    let next_slot = self.capture_retained(&alert_key).map(|entries| {
1721                        next_retained.push((entries, self.retention[corr_idx].stable_id.clone()));
1722                        next_retained.len() - 1
1723                    });
1724
1725                    let corr = &self.correlations[corr_idx];
1726                    let fired_group_key = group_key.to_pairs(&corr.group_by);
1727                    let result = EvaluationResult {
1728                        header: RuleHeader {
1729                            rule_title: corr.title.clone(),
1730                            rule_id: corr.id.clone(),
1731                            tenant_id: tenant.clone(),
1732                            level,
1733                            tags: corr.tags.clone(),
1734                            custom_attributes: corr.custom_attributes.clone(),
1735                            enrichments: None,
1736                            ruleset: None,
1737                        },
1738                        body: ResultBody::Correlation(CorrelationBody {
1739                            correlation_type: corr_type,
1740                            group_key: fired_group_key.clone(),
1741                            aggregated_value: agg_value,
1742                            timespan_secs: timespan,
1743                            events: reported.events,
1744                            event_refs: reported.event_refs,
1745                            event_sources: reported.event_sources,
1746                        }),
1747                    };
1748                    next_pending.push((corr_idx, fired_group_key, tenant.clone(), next_slot));
1749                    out.push(result);
1750                    out_indices.push(corr_idx);
1751                    self.last_alert.insert(alert_key.clone(), ts);
1752
1753                    if action == CorrelationAction::Reset {
1754                        if let Some(state) = self.state.get_mut(&alert_key) {
1755                            state.clear();
1756                        }
1757                        if let Some(buf) = self.event_buffers.get_mut(&alert_key) {
1758                            buf.clear();
1759                        }
1760                        if let Some(buf) = self.event_ref_buffers.get_mut(&alert_key) {
1761                            buf.clear();
1762                        }
1763                    }
1764                }
1765            }
1766
1767            pending = next_pending;
1768            retained = next_retained;
1769        }
1770
1771        if !pending.is_empty() {
1772            log::warn!(
1773                "Correlation chain depth limit reached ({MAX_CHAIN_DEPTH}); \
1774                 {} pending result(s) were not propagated further. \
1775                 This may indicate a cycle in correlation references.",
1776                pending.len()
1777            );
1778        }
1779    }
1780
1781    // =========================================================================
1782    // Timestamp extraction
1783    // =========================================================================
1784
1785    /// Extract a Unix epoch timestamp (seconds) from an event.
1786    ///
1787    /// Tries each configured timestamp field in order. Supports:
1788    /// - Numeric values (epoch seconds, or epoch millis if > 1e12)
1789    /// - ISO 8601 strings (e.g., "2024-07-10T12:30:00Z")
1790    ///
1791    /// Returns `None` if no field yields a valid timestamp; a value before
1792    /// 1970 or past the representable range does not count as one.
1793    fn extract_event_timestamp(&self, event: &impl Event) -> Option<i64> {
1794        for field_name in &self.config.timestamp_fields {
1795            if let Some(val) = event.get_field(field_name)
1796                && let Some(ts) = parse_timestamp_value(&val)
1797            {
1798                return Some(ts);
1799            }
1800        }
1801        None
1802    }
1803
1804    // =========================================================================
1805    // State management
1806    // =========================================================================
1807
1808    /// Manually evict all expired state entries.
1809    pub fn evict_expired(&mut self, now_secs: i64) {
1810        self.evict_all(now_secs);
1811    }
1812
1813    /// Index a new state key under its tenant while a per-tenant cap is set.
1814    fn note_tenant_insert(&mut self, key: &StateKey) {
1815        if self.config.max_state_entries_per_tenant.is_some() {
1816            self.tenant_keys
1817                .entry(key.tenant.clone())
1818                .or_default()
1819                .insert(key.clone());
1820        }
1821    }
1822
1823    /// Drop a removed state key from its tenant's index.
1824    fn note_tenant_removal(&mut self, key: &StateKey) {
1825        if let Some(keys) = self.tenant_keys.get_mut(&key.tenant) {
1826            keys.remove(key);
1827            if keys.is_empty() {
1828                self.tenant_keys.remove(&key.tenant);
1829            }
1830        }
1831    }
1832
1833    /// Live state entries of `tenant`, tracked while a per-tenant cap is set.
1834    fn tenant_len(&self, tenant: &Option<TenantId>) -> usize {
1835        self.tenant_keys.get(tenant).map_or(0, HashSet::len)
1836    }
1837
1838    /// Remove one state entry and every sidecar keyed by it.
1839    fn remove_state_entry(&mut self, key: &StateKey) -> bool {
1840        let existed = self.state.remove(key).is_some();
1841        if existed {
1842            self.note_tenant_removal(key);
1843        }
1844        self.last_alert.remove(key);
1845        self.event_buffers.remove(key);
1846        self.event_ref_buffers.remove(key);
1847        existed
1848    }
1849
1850    /// Evict one tenant's expired entries, then its stalest entries down to 90%
1851    /// of the configured per-tenant cap. Returns how many entries were removed.
1852    fn evict_tenant(&mut self, tenant: Option<&TenantId>, now_secs: i64) -> usize {
1853        let Some(cap) = self.config.max_state_entries_per_tenant else {
1854            return 0;
1855        };
1856        let tenant_key = tenant.cloned();
1857        let keys: Vec<StateKey> = self
1858            .tenant_keys
1859            .get(&tenant_key)
1860            .map(|keys| keys.iter().cloned().collect())
1861            .unwrap_or_default();
1862
1863        // Expired phase: drop the tenant's emptied windows. `last_alert` stays,
1864        // so a group evicted here is still suppressed until `evict_all` ages
1865        // the alert out.
1866        let mut evicted = 0;
1867        for key in &keys {
1868            let Some(state) = self.state.get_mut(key) else {
1869                continue;
1870            };
1871            if let Some(correlation) = self.correlations.get(key.corr_idx) {
1872                let timespan = correlation.timespan_secs as i64;
1873                match correlation.window_mode {
1874                    WindowMode::Sliding => {
1875                        state.evict(now_secs - timespan);
1876                    }
1877                    mode @ (WindowMode::Tumbling | WindowMode::Session) => {
1878                        let staleness = if mode == WindowMode::Session {
1879                            correlation.gap_secs.map_or(timespan, |gap| gap as i64)
1880                        } else {
1881                            timespan
1882                        };
1883                        if state
1884                            .latest_timestamp()
1885                            .is_some_and(|last| now_secs - last > staleness)
1886                        {
1887                            state.clear();
1888                        }
1889                    }
1890                }
1891            }
1892            if state.is_empty() {
1893                self.state.remove(key);
1894                self.note_tenant_removal(key);
1895                self.event_buffers.remove(key);
1896                self.event_ref_buffers.remove(key);
1897                evicted += 1;
1898            }
1899        }
1900
1901        // Stalest phase: at the cap, drop the tenant's stalest windows down to
1902        // 90% of it, and at least one.
1903        let count = self.tenant_len(&tenant_key);
1904        if count >= cap {
1905            let target = cap * 9 / 10;
1906            let excess = count.saturating_sub(target);
1907            let mut by_staleness: Vec<_> = self
1908                .tenant_keys
1909                .get(&tenant_key)
1910                .into_iter()
1911                .flatten()
1912                .filter_map(|key| {
1913                    self.state
1914                        .get(key)
1915                        .map(|state| (key, state.latest_timestamp().unwrap_or(i64::MIN)))
1916                })
1917                .collect();
1918            if excess < by_staleness.len() {
1919                by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
1920            }
1921            let stalest: Vec<_> = by_staleness
1922                .iter()
1923                .take(excess)
1924                .map(|&(key, _)| key.clone())
1925                .collect();
1926            for key in stalest {
1927                if self.remove_state_entry(&key) {
1928                    evicted += 1;
1929                }
1930            }
1931        }
1932
1933        self.tenant_quota_evictions += evicted as u64;
1934        evicted
1935    }
1936
1937    /// Evict expired entries and remove empty states.
1938    fn evict_all(&mut self, now_secs: i64) {
1939        // Phase 1: Time-based eviction — remove entries outside their correlation
1940        // window. Eviction is window-mode aware:
1941        //
1942        // - Sliding: trim entries older than the trailing cutoff, as always.
1943        // - Tumbling/session: never trim from the front — that would forget the
1944        //   bucket/session start and silently weaken the `timespan` cap (the
1945        //   window would drift toward sliding semantics). Instead, drop the
1946        //   whole group once it is stale (no event within its bucket span /
1947        //   session gap), which is exactly the point at which the next arrival
1948        //   would reset it anyway.
1949        let specs: Vec<(u64, WindowMode, Option<u64>)> = self
1950            .correlations
1951            .iter()
1952            .map(|c| (c.timespan_secs, c.window_mode, c.gap_secs))
1953            .collect();
1954
1955        let mut removed_keys = Vec::new();
1956        self.state.retain(|key, state| {
1957            if let Some(&(timespan, mode, gap)) = specs.get(key.corr_idx) {
1958                match mode {
1959                    WindowMode::Sliding => {
1960                        state.evict(now_secs - timespan as i64);
1961                    }
1962                    WindowMode::Tumbling | WindowMode::Session => {
1963                        let staleness = if mode == WindowMode::Session {
1964                            gap.unwrap_or(timespan)
1965                        } else {
1966                            timespan
1967                        } as i64;
1968                        if state
1969                            .latest_timestamp()
1970                            .is_some_and(|last| now_secs - last > staleness)
1971                        {
1972                            state.clear();
1973                        }
1974                    }
1975                }
1976            }
1977            if state.is_empty() {
1978                removed_keys.push(key.clone());
1979                false
1980            } else {
1981                true
1982            }
1983        });
1984        for key in removed_keys {
1985            self.note_tenant_removal(&key);
1986        }
1987
1988        // Evict event buffers in sync with window state: sliding buffers trim by
1989        // the trailing cutoff, tumbling/session buffers live and die with their
1990        // window state (dropped above when the group went stale).
1991        let state = &self.state;
1992        self.event_buffers.retain(|key, buf| {
1993            if let Some(&(timespan, mode, _)) = specs.get(key.corr_idx) {
1994                match mode {
1995                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
1996                    WindowMode::Tumbling | WindowMode::Session => {
1997                        if !state.contains_key(key) {
1998                            return false;
1999                        }
2000                    }
2001                }
2002            }
2003            !buf.is_empty()
2004        });
2005        self.event_ref_buffers.retain(|key, buf| {
2006            if let Some(&(timespan, mode, _)) = specs.get(key.corr_idx) {
2007                match mode {
2008                    WindowMode::Sliding => buf.evict(now_secs - timespan as i64),
2009                    WindowMode::Tumbling | WindowMode::Session => {
2010                        if !state.contains_key(key) {
2011                            return false;
2012                        }
2013                    }
2014                }
2015            }
2016            !buf.is_empty()
2017        });
2018
2019        // Phase 2: Hard cap — if still over limit after time-based eviction (e.g.
2020        // high-cardinality traffic with long windows), drop the stalest entries
2021        // until we're at 90% capacity to avoid evicting on every single event.
2022        if self.state.len() >= self.config.max_state_entries {
2023            let target = self.config.max_state_entries * 9 / 10;
2024            let excess = self.state.len() - target;
2025
2026            log::warn!(
2027                "Correlation state hard cap reached ({} entries, max {}); \
2028                 evicting {} stalest entries to {} (90% capacity). \
2029                 This indicates high-cardinality traffic; consider raising \
2030                 max_state_entries or shortening correlation windows.",
2031                self.state.len(),
2032                self.config.max_state_entries,
2033                excess,
2034                target,
2035            );
2036
2037            // Partition by latest timestamp so the `excess` stalest entries
2038            // come first, and clone only their keys.
2039            let mut by_staleness: Vec<_> = self
2040                .state
2041                .iter()
2042                .map(|(k, v)| (k, v.latest_timestamp().unwrap_or(i64::MIN)))
2043                .collect();
2044            if excess < by_staleness.len() {
2045                by_staleness.select_nth_unstable_by_key(excess, |&(_, ts)| ts);
2046            }
2047            let stalest: Vec<_> = by_staleness
2048                .iter()
2049                .take(excess)
2050                .map(|&(k, _)| k.clone())
2051                .collect();
2052
2053            // Drop the stalest entries (and their associated event buffers)
2054            for key in stalest {
2055                self.remove_state_entry(&key);
2056            }
2057        }
2058
2059        // Phase 3: Evict stale last_alert entries — remove if the suppress window
2060        // has passed or if the corresponding window state no longer exists.
2061        self.last_alert.retain(|key, &mut alert_ts| {
2062            let suppress = if key.corr_idx < self.correlations.len() {
2063                self.correlations[key.corr_idx]
2064                    .suppress_secs
2065                    .or(self.config.suppress)
2066                    .unwrap_or(0)
2067            } else {
2068                0
2069            };
2070            (now_secs - alert_ts) < suppress as i64
2071        });
2072    }
2073
2074    /// Number of active state entries (for monitoring).
2075    pub fn state_count(&self) -> usize {
2076        self.state.len()
2077    }
2078
2079    /// Number of detection rules loaded.
2080    pub fn detection_rule_count(&self) -> usize {
2081        self.engine.rule_count()
2082    }
2083
2084    /// Number of correlation rules loaded.
2085    pub fn correlation_rule_count(&self) -> usize {
2086        self.correlations.len()
2087    }
2088
2089    /// Number of active event buffers (for monitoring).
2090    pub fn event_buffer_count(&self) -> usize {
2091        self.event_buffers.len()
2092    }
2093
2094    /// Total compressed bytes across all event buffers (for monitoring).
2095    pub fn event_buffer_bytes(&self) -> usize {
2096        self.event_buffers
2097            .values()
2098            .map(|b| b.compressed_bytes())
2099            .sum()
2100    }
2101
2102    /// Number of active event ref buffers — `Refs` mode (for monitoring).
2103    pub fn event_ref_buffer_count(&self) -> usize {
2104        self.event_ref_buffers.len()
2105    }
2106
2107    /// Access the inner stateless engine.
2108    pub fn engine(&self) -> &Engine<L> {
2109        &self.engine
2110    }
2111
2112    /// Resolve a rule key (an id, or a title for a rule without one) to the
2113    /// documentation of every loaded rule that carries it, across both the
2114    /// detection rules and the correlations.
2115    pub fn rule_metadata(&self, key: &str) -> RuleMetadataLookup {
2116        let mut variants = Vec::new();
2117        self.collect_rule_metadata(key, &mut variants);
2118        RuleMetadataLookup::from_variants(variants)
2119    }
2120
2121    pub(crate) fn collect_rule_metadata(&self, key: &str, out: &mut Vec<RuleBundleMetadata>) {
2122        self.engine.collect_rule_metadata(key, out);
2123        crate::rule_metadata::matching_correlations(&self.correlations, key, out);
2124    }
2125
2126    /// Export all mutable correlation state as a serializable snapshot.
2127    ///
2128    /// The snapshot uses stable correlation identifiers (id > name > title)
2129    /// instead of internal indices, so it survives rule reloads as long as
2130    /// the correlation rules keep the same identifiers. State is nested per
2131    /// tenant; with tenancy off it is one `tenant: None` entry.
2132    pub fn export_state(&self) -> CorrelationSnapshot {
2133        let mut by_tenant: BTreeMap<Option<TenantId>, TenantStateSnapshot> = BTreeMap::new();
2134
2135        for (key, ws) in &self.state {
2136            let corr_id = self.correlation_stable_id(key.corr_idx);
2137            by_tenant
2138                .entry(key.tenant.clone())
2139                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
2140                .windows
2141                .entry(corr_id)
2142                .or_default()
2143                .push((key.group_key.clone(), ws.clone()));
2144        }
2145
2146        for (key, ts) in &self.last_alert {
2147            let corr_id = self.correlation_stable_id(key.corr_idx);
2148            by_tenant
2149                .entry(key.tenant.clone())
2150                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
2151                .last_alert
2152                .entry(corr_id)
2153                .or_default()
2154                .push((key.group_key.clone(), *ts));
2155        }
2156
2157        for (key, buf) in &self.event_buffers {
2158            let corr_id = self.correlation_stable_id(key.corr_idx);
2159            by_tenant
2160                .entry(key.tenant.clone())
2161                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
2162                .event_buffers
2163                .entry(corr_id)
2164                .or_default()
2165                .push((key.group_key.clone(), buf.clone()));
2166        }
2167
2168        for (key, buf) in &self.event_ref_buffers {
2169            let corr_id = self.correlation_stable_id(key.corr_idx);
2170            by_tenant
2171                .entry(key.tenant.clone())
2172                .or_insert_with(|| TenantStateSnapshot::empty(key.tenant.clone()))
2173                .event_ref_buffers
2174                .entry(corr_id)
2175                .or_default()
2176                .push((key.group_key.clone(), buf.clone()));
2177        }
2178
2179        CorrelationSnapshot {
2180            version: SNAPSHOT_VERSION,
2181            windows: HashMap::new(),
2182            last_alert: HashMap::new(),
2183            event_buffers: HashMap::new(),
2184            event_ref_buffers: HashMap::new(),
2185            tenants: by_tenant.into_values().collect(),
2186            rulesets: BTreeMap::new(),
2187        }
2188    }
2189
2190    /// Import previously exported state, mapping stable identifiers back to
2191    /// current correlation indices. Entries whose identifiers no longer match
2192    /// any loaded correlation are silently dropped.
2193    ///
2194    /// A snapshot exported by a fan-out over exactly one ruleset imports that
2195    /// ruleset's state.
2196    ///
2197    /// Returns `false` (and imports nothing) if the snapshot version is
2198    /// incompatible with the current schema, or if the snapshot holds state
2199    /// for several rulesets.
2200    pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
2201        self.import_state_detailed(snapshot).is_some()
2202    }
2203
2204    /// Like [`import_state`](Self::import_state), returning the counts of
2205    /// restored and discarded entries.
2206    ///
2207    /// Accepts versions 1 and 2. Attribution follows
2208    /// [`CorrelationConfig::require_tenant`]: with it set, untenanted entries
2209    /// are discarded; without it, tenanted entries are discarded. Returns
2210    /// `None` for an unknown version or a multi-ruleset snapshot that does not
2211    /// fit this engine.
2212    pub fn import_state_detailed(
2213        &mut self,
2214        mut snapshot: CorrelationSnapshot,
2215    ) -> Option<ImportStats> {
2216        if !matches!(snapshot.version, 1 | 2) {
2217            return None;
2218        }
2219        if !snapshot.rulesets.is_empty() {
2220            if snapshot.has_collection_state() || snapshot.rulesets.len() != 1 {
2221                return None;
2222            }
2223            let (_, inner) = std::mem::take(&mut snapshot.rulesets).pop_first()?;
2224            return self.import_state_detailed(inner);
2225        }
2226        let id_to_idx = self.build_id_to_index_map();
2227        let require_tenant = self.config.require_tenant;
2228        let mut stats = ImportStats::default();
2229
2230        let mut tenant_states = std::mem::take(&mut snapshot.tenants);
2231        // The version 1 top-level maps are the untenanted bucket.
2232        tenant_states.push(TenantStateSnapshot {
2233            tenant: None,
2234            windows: snapshot.windows,
2235            last_alert: snapshot.last_alert,
2236            event_buffers: snapshot.event_buffers,
2237            event_ref_buffers: snapshot.event_ref_buffers,
2238        });
2239
2240        for tenant_state in tenant_states {
2241            let entries = tenant_state.window_entries();
2242            let tenant = tenant_state.tenant;
2243            let keep = if require_tenant {
2244                tenant.is_some()
2245            } else {
2246                tenant.is_none()
2247            };
2248            if !keep {
2249                if tenant.is_none() {
2250                    stats.discarded_untenanted += entries;
2251                } else {
2252                    stats.discarded_tenanted += entries;
2253                }
2254                continue;
2255            }
2256
2257            for (corr_id, groups) in tenant_state.windows {
2258                if let Some(&idx) = id_to_idx.get(&corr_id) {
2259                    for (gk, ws) in groups {
2260                        let key = StateKey {
2261                            tenant: tenant.clone(),
2262                            corr_idx: idx,
2263                            group_key: gk,
2264                        };
2265                        if self.state.insert(key.clone(), ws).is_none() {
2266                            self.note_tenant_insert(&key);
2267                        }
2268                        stats.restored += 1;
2269                    }
2270                }
2271            }
2272
2273            for (corr_id, groups) in tenant_state.last_alert {
2274                if let Some(&idx) = id_to_idx.get(&corr_id) {
2275                    for (gk, ts) in groups {
2276                        self.last_alert.insert(
2277                            StateKey {
2278                                tenant: tenant.clone(),
2279                                corr_idx: idx,
2280                                group_key: gk,
2281                            },
2282                            ts,
2283                        );
2284                    }
2285                }
2286            }
2287
2288            for (corr_id, groups) in tenant_state.event_buffers {
2289                if let Some(&idx) = id_to_idx.get(&corr_id) {
2290                    for (gk, buf) in groups {
2291                        self.event_buffers.insert(
2292                            StateKey {
2293                                tenant: tenant.clone(),
2294                                corr_idx: idx,
2295                                group_key: gk,
2296                            },
2297                            buf,
2298                        );
2299                    }
2300                }
2301            }
2302
2303            for (corr_id, groups) in tenant_state.event_ref_buffers {
2304                if let Some(&idx) = id_to_idx.get(&corr_id) {
2305                    for (gk, buf) in groups {
2306                        self.event_ref_buffers.insert(
2307                            StateKey {
2308                                tenant: tenant.clone(),
2309                                corr_idx: idx,
2310                                group_key: gk,
2311                            },
2312                            buf,
2313                        );
2314                    }
2315                }
2316            }
2317        }
2318
2319        self.resequence_imported_buffers();
2320
2321        Some(stats)
2322    }
2323
2324    /// Give restored buffer entries distinct sequence numbers, so a snapshot
2325    /// written before entries carried one still deduplicates on merge, and
2326    /// raise `next_event_seq` above every restored value.
2327    fn resequence_imported_buffers(&mut self) {
2328        let mut highest = 0u64;
2329        for buf in self.event_buffers.values() {
2330            highest = highest.max(buf.max_seq());
2331        }
2332        for buf in self.event_ref_buffers.values() {
2333            highest = highest.max(buf.max_seq());
2334        }
2335        self.next_event_seq = self.next_event_seq.max(highest.saturating_add(1));
2336
2337        let mut next = self.next_event_seq;
2338        for buf in self.event_buffers.values_mut() {
2339            buf.sequence_unsequenced(&mut next);
2340        }
2341        for buf in self.event_ref_buffers.values_mut() {
2342            buf.sequence_unsequenced(&mut next);
2343        }
2344        self.next_event_seq = next;
2345    }
2346
2347    /// Stable identifier for a correlation rule: prefers id, then name, then title.
2348    fn correlation_stable_id(&self, idx: usize) -> String {
2349        let corr = &self.correlations[idx];
2350        corr.id
2351            .clone()
2352            .or_else(|| corr.name.clone())
2353            .unwrap_or_else(|| corr.title.clone())
2354    }
2355
2356    /// Build a reverse map from stable id → current correlation index.
2357    fn build_id_to_index_map(&self) -> HashMap<String, usize> {
2358        self.correlations
2359            .iter()
2360            .enumerate()
2361            .map(|(idx, _)| (self.correlation_stable_id(idx), idx))
2362            .collect()
2363    }
2364}
2365
2366impl Default for CorrelationEngine {
2367    fn default() -> Self {
2368        Self::new(CorrelationConfig::default())
2369    }
2370}
2371
2372/// Retention strength ordering: `full` over `refs` over `none`.
2373fn stronger_mode(a: CorrelationEventMode, b: CorrelationEventMode) -> CorrelationEventMode {
2374    match (a, b) {
2375        (CorrelationEventMode::Full, _) | (_, CorrelationEventMode::Full) => {
2376            CorrelationEventMode::Full
2377        }
2378        (CorrelationEventMode::Refs, _) | (_, CorrelationEventMode::Refs) => {
2379            CorrelationEventMode::Refs
2380        }
2381        _ => CorrelationEventMode::None,
2382    }
2383}
2384
2385fn split_identified(
2386    identified: Vec<IdentifiedEvaluation>,
2387) -> (Vec<EvaluationResult>, Vec<RuleIdentity>) {
2388    identified
2389        .into_iter()
2390        .map(|identified| {
2391            (
2392                identified.result,
2393                (identified.rule_id, identified.rule_name),
2394            )
2395        })
2396        .unzip()
2397}
2398
2399// =============================================================================
2400// Timestamp parsing helpers
2401// =============================================================================
2402
2403/// Extract a timestamp from an event using the given field names.
2404///
2405/// Standalone version of `CorrelationEngine::extract_event_timestamp` for use
2406/// in contexts where borrowing `&self` is not possible (e.g. rayon closures).
2407fn extract_event_ts(event: &impl Event, timestamp_fields: &[String]) -> Option<i64> {
2408    for field_name in timestamp_fields {
2409        if let Some(val) = event.get_field(field_name)
2410            && let Some(ts) = parse_timestamp_value(&val)
2411        {
2412            return Some(ts);
2413        }
2414    }
2415    None
2416}
2417
2418/// Parse an [`EventValue`] as a Unix epoch timestamp in seconds.
2419///
2420/// Values before 1970, non-finite floats, and dates past the representable
2421/// range are `None`, so the next timestamp field or the fallback applies.
2422fn parse_timestamp_value(val: &EventValue) -> Option<i64> {
2423    match val {
2424        EventValue::Int(i) => epoch_seconds_from_int(*i),
2425        EventValue::Float(f) => epoch_seconds_from_float(*f),
2426        EventValue::Str(s) => parse_timestamp_str(s)
2427            .map(|dt| dt.timestamp())
2428            .filter(|ts| *ts >= 0),
2429        _ => None,
2430    }
2431}
2432
2433/// Render a value for a `value_count` distinct key. Unlike a group key, a
2434/// null counts as the distinct value `null`.
2435fn value_to_string_for_count(v: &EventValue) -> Option<String> {
2436    match v {
2437        EventValue::Null => Some("null".to_string()),
2438        v => v.as_str().map(Cow::into_owned),
2439    }
2440}
2441
2442/// Build a composite distinct-key for `value_count` over one or more fields.
2443///
2444/// Each field's value is rendered with [`value_to_string_for_count`] and the
2445/// rendered parts are joined with `\u{1f}` (the ASCII Unit Separator), which
2446/// is unlikely to occur in normal log data. If any field is missing or has a
2447/// type that does not produce a stable string representation, the event is
2448/// excluded from the distinct count (return `None`), matching the historical
2449/// single-field behavior.
2450fn composite_value_count_key(event: &impl Event, fields: &[String]) -> Option<String> {
2451    // Common case: exactly one field. Avoid the separator overhead.
2452    if let [field_name] = fields {
2453        let val = event.get_field(field_name)?;
2454        return value_to_string_for_count(&val);
2455    }
2456
2457    let mut parts = Vec::with_capacity(fields.len());
2458    for field_name in fields {
2459        let val = event.get_field(field_name)?;
2460        let rendered = value_to_string_for_count(&val)?;
2461        parts.push(rendered);
2462    }
2463    Some(parts.join("\u{1f}"))
2464}
2465
2466/// Convert an [`EventValue`] to f64 for numeric aggregation.
2467fn value_to_f64_ev(v: &EventValue) -> Option<f64> {
2468    v.as_f64()
2469}