1mod 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
47pub(crate) const SNAPSHOT_VERSION: u32 = 2;
53
54const MAX_CHAIN_DEPTH: usize = 10;
60
61const LONG_WINDOW_WARN_SECS: u64 = 3600;
65
66#[derive(Debug, Clone, Default)]
68struct Retention {
69 mode: CorrelationEventMode,
72 cap: usize,
74 feeds_retaining_parent: bool,
76 rule_refs: Vec<Arc<str>>,
79 stable_id: Option<Arc<str>>,
82}
83
84#[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
92pub struct CorrelationEngine<L = LogSourceExtractor> {
100 engine: Engine<L>,
102 correlations: Vec<CompiledCorrelation>,
104 rule_index: HashMap<String, Vec<usize>>,
107 rule_ids: Vec<(Option<String>, Option<String>, String)>,
110 state: HashMap<StateKey, WindowState>,
112 last_alert: HashMap<StateKey, i64>,
114 event_buffers: HashMap<StateKey, EventBuffer>,
116 event_ref_buffers: HashMap<StateKey, EventRefBuffer>,
118 correlation_only_rules: std::collections::HashSet<String>,
122 generated_rules: std::collections::HashSet<String>,
125 config: CorrelationConfig,
127 pipelines: Vec<Pipeline>,
129 untenanted_skipped: u64,
131 tenant_keys: HashMap<Option<TenantId>, HashSet<StateKey>>,
135 tenant_quota_evictions: u64,
137 next_event_seq: u64,
140 retention: Vec<Retention>,
143 retention_dirty: bool,
145}
146
147impl CorrelationEngine {
148 pub fn new(config: CorrelationConfig) -> Self {
150 Self::with_engine(config, Engine::new())
151 }
152}
153
154impl<L> CorrelationEngine<L> {
155 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 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 pub fn set_include_event(&mut self, include: bool) {
194 self.engine.set_include_event(include);
195 }
196
197 pub fn set_match_detail(&mut self, level: crate::result::MatchDetailLevel) {
200 self.engine.set_match_detail(level);
201 }
202
203 pub fn set_bloom_prefilter(&mut self, enabled: bool) {
207 self.engine.set_bloom_prefilter(enabled);
208 }
209
210 pub fn set_logsource_extractor(&mut self, extractor: Option<L>) {
214 self.engine.set_logsource_extractor(extractor);
215 }
216
217 pub fn logsource_pruned_total(&self) -> u64 {
219 self.engine.logsource_pruned_total()
220 }
221
222 pub fn logsource_absent_total(&self) -> u64 {
224 self.engine.logsource_absent_total()
225 }
226
227 pub fn set_bloom_max_bytes(&mut self, max_bytes: usize) {
230 self.engine.set_bloom_max_bytes(max_bytes);
231 }
232
233 #[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 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 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 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 let compiled = crate::compiler::compile_rule(&transformed)?;
280 self.engine.add_compiled_rule(compiled);
281 }
282 Ok(())
283 }
284
285 fn apply_custom_attributes(
299 &mut self,
300 attrs: &std::collections::HashMap<String, yaml_serde::Value>,
301 ) {
302 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 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 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 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 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 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 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 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 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 compiled_batch.push(crate::compiler::compile_rule(&transformed)?);
419 }
420 }
421 self.engine.extend_compiled_rules(compiled_batch);
422 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 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 fn detect_correlation_cycles(&self) -> Result<()> {
474 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 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 let mut state = vec![0u8; self.correlations.len()]; 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 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; path.push(node);
531
532 for &next in &adj[node] {
533 if state[next] == 1 {
534 if let Some(pos) = path.iter().position(|&n| n == next) {
536 let mut cycle = path[pos..].to_vec();
537 cycle.push(next); 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; None
551 }
552
553 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 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 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 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 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 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 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 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 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 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 if self.config.require_tenant && tenant.is_none() {
733 self.untenanted_skipped += 1;
734 return self.filter_detections(all_detections, identities);
735 }
736
737 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 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 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 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 pub fn untenanted_skipped(&self) -> u64 {
799 self.untenanted_skipped
800 }
801
802 pub fn take_untenanted_skipped(&mut self) -> u64 {
805 std::mem::take(&mut self.untenanted_skipped)
806 }
807
808 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 pub fn take_tenant_quota_evictions(&mut self) -> u64 {
825 std::mem::take(&mut self.tenant_quota_evictions)
826 }
827
828 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 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 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 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 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 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 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 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 #[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 let mut work: Vec<(usize, Option<String>, Option<String>)> = Vec::new();
975
976 for (rule_id, rule_name) in identities {
977 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 fn find_rule_identity(&self, det: &EvaluationResult) -> RuleIdentity {
1012 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 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 #[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 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 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 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 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 let corr = &self.correlations[corr_idx];
1158
1159 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 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 if let Some(cap) = max_group_entries {
1204 state.truncate_oldest(cap, window_mode == WindowMode::Session);
1205 }
1206
1207 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 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 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 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 self.last_alert.insert(alert_key.clone(), ts);
1295
1296 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 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 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 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 (CorrelationEventMode::Full, Retained::Refs(_)) | (CorrelationEventMode::None, _) => {}
1400 }
1401 }
1402
1403 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 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 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 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 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 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 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 #[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 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 if let Some(cap) = max_group_entries {
1679 state.truncate_oldest(cap, window_mode == WindowMode::Session);
1680 }
1681
1682 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 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 pub fn evict_expired(&mut self, now_secs: i64) {
1810 self.evict_all(now_secs);
1811 }
1812
1813 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 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 fn tenant_len(&self, tenant: &Option<TenantId>) -> usize {
1835 self.tenant_keys.get(tenant).map_or(0, HashSet::len)
1836 }
1837
1838 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 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 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 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 fn evict_all(&mut self, now_secs: i64) {
1939 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 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 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 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 for key in stalest {
2055 self.remove_state_entry(&key);
2056 }
2057 }
2058
2059 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 pub fn state_count(&self) -> usize {
2076 self.state.len()
2077 }
2078
2079 pub fn detection_rule_count(&self) -> usize {
2081 self.engine.rule_count()
2082 }
2083
2084 pub fn correlation_rule_count(&self) -> usize {
2086 self.correlations.len()
2087 }
2088
2089 pub fn event_buffer_count(&self) -> usize {
2091 self.event_buffers.len()
2092 }
2093
2094 pub fn event_buffer_bytes(&self) -> usize {
2096 self.event_buffers
2097 .values()
2098 .map(|b| b.compressed_bytes())
2099 .sum()
2100 }
2101
2102 pub fn event_ref_buffer_count(&self) -> usize {
2104 self.event_ref_buffers.len()
2105 }
2106
2107 pub fn engine(&self) -> &Engine<L> {
2109 &self.engine
2110 }
2111
2112 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 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 pub fn import_state(&mut self, snapshot: CorrelationSnapshot) -> bool {
2201 self.import_state_detailed(snapshot).is_some()
2202 }
2203
2204 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 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 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 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 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
2372fn 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
2399fn 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
2418fn 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
2433fn 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
2442fn composite_value_count_key(event: &impl Event, fields: &[String]) -> Option<String> {
2451 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
2466fn value_to_f64_ev(v: &EventValue) -> Option<f64> {
2468 v.as_f64()
2469}