lessence 0.4.0

Extract the essence of your logs — compress repetitive lines while preserving all unique information
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
use ahash::AHasher;
use anyhow::Result;
use std::hash::{Hash, Hasher};

use crate::config::Config;
use crate::patterns::{
    LogLine, Token, duration::DurationDetector, email::EmailPatternDetector, hash::HashDetector,
    json::JsonDetector, kubernetes::KubernetesDetector, names::NameDetector,
    network::NetworkDetector, path::PathDetector, process::ProcessDetector,
    quoted::QuotedStringDetector, timestamp::TimestampDetector, uuid::UuidDetector,
};

pub struct Normalizer {
    config: Config,
    // Pattern detectors
    email_detector: EmailPatternDetector,
}

impl Normalizer {
    pub fn new(config: Config) -> Self {
        Self {
            config,
            email_detector: EmailPatternDetector::new().unwrap(),
        }
    }

    pub fn normalize_line(&self, original: String) -> Result<LogLine> {
        let mut normalized = original.clone();
        let mut tokens = Vec::with_capacity(8);

        // Apply normalizations in optimized order (most specific to least specific)
        // This prevents conflicts and maximizes pattern detection accuracy

        // 1. TIMESTAMPS (highest priority - most specific format)
        if self.config.normalize_timestamps {
            let (new_normalized, mut new_tokens) =
                TimestampDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 2. EMAIL ADDRESSES (before paths to ensure emails in URLs are handled correctly)
        if self.config.normalize_emails && normalized.contains('@') {
            let (new_normalized, mut new_tokens) =
                self.email_detector.detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 3. PATHS (URLs, file paths, CLI flags - must run early to preserve URL structure)
        // Must run BEFORE network patterns to handle URLs as complete units
        if self.config.normalize_paths {
            let (new_normalized, mut new_tokens) = PathDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 4. JSON (structured data, Event objects, K8s objects)
        if self.config.normalize_json && normalized.contains('{') {
            let (new_normalized, mut new_tokens) = JsonDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 5. UUIDs (MUST run BEFORE hashes to prevent UUID fragmentation!)
        // UUIDs contain hex segments that could be mistaken for hashes
        if self.config.normalize_uuids {
            let (new_normalized, mut new_tokens) = UuidDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 6. NETWORK PATTERNS (IP addresses, ports, FQDNs - very specific formats)
        // Must run AFTER paths to avoid breaking URLs
        if self.config.normalize_ips || self.config.normalize_ports || self.config.normalize_fqdns {
            let (new_normalized, mut new_tokens) = NetworkDetector::detect_and_replace(
                &normalized,
                self.config.normalize_ips,
                self.config.normalize_ports,
                self.config.normalize_fqdns,
            );
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 7. HASHES (specific length and hex pattern)
        // Must run AFTER UUIDs to avoid detecting UUID segments as hashes
        if self.config.normalize_hashes {
            let (new_normalized, mut new_tokens) = HashDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 8. PROCESS IDs (specific patterns like [pid=123], (12345))
        if self.config.normalize_pids {
            let (new_normalized, mut new_tokens) = ProcessDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 9. KUBERNETES PATTERNS (namespaces, volumes, plugins, pod names)
        // PROTECTED DOMAIN: Must run before generic patterns to prevent pattern theft
        if self.config.normalize_kubernetes {
            let (new_normalized, mut new_tokens) =
                KubernetesDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // NEW PATTERNS FROM 001-READ-THE-CURRENT (Now correctly placed AFTER Kubernetes)

        // HttpStatusClass - Groups HTTP status codes (200-299 → 2xx, etc.)
        {
            let (new_normalized, mut new_tokens) =
                crate::patterns::http_status::HttpStatusDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // BracketContext - Detects [error] [mod_jk] style patterns
        if normalized.contains('[') {
            let (new_normalized, mut new_tokens) =
                crate::patterns::bracket_context::BracketContextDetector::detect_and_replace(
                    &normalized,
                );
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // KeyValuePair - Detects config=value, metrics patterns
        if normalized.contains('=') {
            let (new_normalized, mut new_tokens) =
                crate::patterns::key_value::KeyValueDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // LogWithModule - Detects [level] module patterns for Apache/nginx
        if normalized.contains('[') {
            let (new_normalized, mut new_tokens) =
                crate::patterns::log_module::LogWithModuleDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // StructuredMessage - Detects JSON/logfmt structured logging
        if normalized.contains('{') || normalized.contains('=') {
            let (new_normalized, mut new_tokens) =
                crate::patterns::structured::StructuredMessageDetector::detect_and_replace(
                    &normalized,
                );
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 10. DURATIONS & MEASUREMENTS (broad category including decimals, sizes, percentages, HTTP codes)
        // Runs LATE to avoid conflicts with more specific patterns above
        if self.config.normalize_durations {
            let (new_normalized, mut new_tokens) =
                DurationDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // 11. NAMES (generic hyphenated component names with variable suffixes)
        // Runs after specific patterns to catch remaining variable names
        let (new_normalized, mut new_tokens) = NameDetector::detect_and_replace(&normalized);
        normalized = new_normalized;
        tokens.append(&mut new_tokens);

        // 12. QUOTED STRINGS (generic quoted variables - high priority for mount operations)
        // Must run after paths to catch normalized quoted paths properly
        if normalized.contains('"') || normalized.contains('\'') {
            let (new_normalized, mut new_tokens) =
                QuotedStringDetector::detect_and_replace(&normalized);
            normalized = new_normalized;
            tokens.append(&mut new_tokens);
        }

        // Generate hash for fast comparison
        let hash = self.calculate_hash(&normalized);

        Ok(LogLine {
            original,
            normalized,
            tokens,
            hash,
        })
    }

    fn calculate_hash(&self, normalized: &str) -> u64 {
        let mut hasher = AHasher::default();
        normalized.hash(&mut hasher);
        hasher.finish()
    }

    #[allow(clippy::cast_precision_loss)] // usize lengths → f64 for ratio calc
    pub fn similarity_score(&self, line1: &LogLine, line2: &LogLine) -> f64 {
        let s1 = &line1.normalized;
        let s2 = &line2.normalized;

        if s1 == s2 {
            return 100.0;
        }

        // Ultra-fast similarity: check length difference first
        let len1 = s1.len();
        let len2 = s2.len();
        let max_len = len1.max(len2);
        let min_len = len1.min(len2);

        if max_len == 0 {
            return 100.0;
        }

        // If length difference is too large, reject quickly
        let length_ratio = min_len as f64 / max_len as f64;
        if length_ratio < 0.7 {
            return length_ratio * 100.0;
        }

        // Fast byte-level overlap check (no allocation — works on &[u8] directly)
        let b1 = s1.as_bytes();
        let b2 = s2.as_bytes();
        let compare_len = min_len;
        let mut matches: u32 = 0;

        for i in 0..compare_len {
            if b1[i] == b2[i] {
                matches += 1;
            }
        }

        (f64::from(matches) / max_len as f64) * 100.0
    }

    pub fn are_similar(&self, line1: &LogLine, line2: &LogLine) -> bool {
        // Quick hash comparison first
        if line1.hash == line2.hash {
            return true;
        }

        // If hashes don't match, check similarity score
        let score = self.similarity_score(line1, line2);
        score >= f64::from(self.config.threshold)
    }

    pub fn format_collapsed_line(&self, first: &LogLine, last: &LogLine, count: usize) -> String {
        if self.config.compact {
            // Compact format: [+N similar, varying: TYPE]
            let variation_types = self.summarize_variation_types(&first.tokens, &last.tokens);
            if variation_types.is_empty() {
                format!("[+{count} similar]")
            } else {
                format!(
                    "[+{} similar, varying: {}]",
                    count,
                    variation_types.join(", ")
                )
            }
        } else {
            format!(
                "[...collapsed {} similar lines from {} to {}...]",
                count,
                self.format_timestamp(first),
                self.format_timestamp(last)
            )
        }
    }

    fn format_timestamp(&self, log_line: &LogLine) -> String {
        // Extract first timestamp string from original line using simple regex
        for token in &log_line.tokens {
            if let Token::Timestamp(ts_str) = token {
                // Extract just the time part for display (HH:MM:SS.mmm or HH:MM:SS,mmm)
                if let Some(time_part) = Self::extract_time_part(ts_str) {
                    return time_part;
                }
            }
        }
        "unknown".to_string()
    }

    fn extract_time_part(timestamp: &str) -> Option<String> {
        // Return the full timestamp string as-is from the original log
        // This preserves user's format and shows meaningful ranges
        Some(timestamp.to_string())
    }

    fn summarize_variation_types(
        &self,
        first_tokens: &[Token],
        last_tokens: &[Token],
    ) -> Vec<String> {
        let mut types = std::collections::HashSet::new();

        // Helper function to get token type name and value
        let get_token_info = |token: &Token| -> (&str, String) {
            match token {
                Token::Timestamp(v) => ("timestamp", v.clone()),
                Token::IPv4(v) => ("IP", v.clone()),
                Token::IPv6(v) => ("IP", v.clone()),
                Token::Port(v) => ("port", v.to_string()),
                Token::Hash(_, v) => ("hash", v.clone()),
                Token::Uuid(v) => ("UUID", v.clone()),
                Token::Pid(v) => ("PID", v.to_string()),
                Token::ThreadID(v) => ("thread", v.clone()),
                Token::Path(v) => ("path", v.clone()),
                Token::Json(v) => ("json", v.clone()),
                Token::Duration(v) => ("duration", v.clone()),
                Token::Size(v) => ("size", v.clone()),
                Token::Number(v) => ("number", v.clone()),
                Token::HttpStatus(v) => ("http_status", v.to_string()),
                Token::QuotedString(v) => ("quoted_string", v.clone()),
                Token::Name(v) => ("name", v.clone()),
                Token::KubernetesNamespace(v) => ("namespace", v.clone()),
                Token::VolumeName(v) => ("volume", v.clone()),
                Token::PluginType(v) => ("plugin", v.clone()),
                Token::PodName(v) => ("pod", v.clone()),
                Token::HttpStatusClass(v) => ("http_status_class", v.clone()),
                Token::BracketContext(v) => ("bracket_context", v.join(",")),
                Token::KeyValuePair { key, value_type } => {
                    ("key_value_pair", format!("{key}={value_type}"))
                }
                Token::Email(v) => ("email", v.clone()),
                Token::LogWithModule { .. } => ("log_with_module", String::new()),
                Token::StructuredMessage { .. } => ("structured_message", String::new()),
            }
        };

        // Create maps of token types to values for first and last
        let mut first_values: std::collections::HashMap<&str, Vec<String>> =
            std::collections::HashMap::new();
        let mut last_values: std::collections::HashMap<&str, Vec<String>> =
            std::collections::HashMap::new();

        for token in first_tokens {
            let (token_type, value) = get_token_info(token);
            first_values.entry(token_type).or_default().push(value);
        }

        for token in last_tokens {
            let (token_type, value) = get_token_info(token);
            last_values.entry(token_type).or_default().push(value);
        }

        // Find token types that actually vary between first and last
        let all_types: std::collections::HashSet<&str> = first_values
            .keys()
            .chain(last_values.keys())
            .copied()
            .collect();

        for token_type in all_types {
            // In essence mode, ignore timestamp variations as they're tokenized for temporal independence
            if self.config.essence_mode && token_type == "timestamp" {
                continue;
            }

            let first_vals = first_values.get(token_type).cloned().unwrap_or_default();
            let last_vals = last_values.get(token_type).cloned().unwrap_or_default();

            // If the sets of values differ, this token type varies
            if first_vals != last_vals {
                types.insert(token_type.to_string());
            }
        }

        let mut result: Vec<String> = types.into_iter().collect();
        result.sort();
        result
    }
}

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

    #[test]
    fn test_timestamp_normalization() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        let line = normalizer
            .normalize_line("2025-01-20 10:15:30 Error occurred".to_string())
            .unwrap();

        assert_eq!(line.normalized, "<TIMESTAMP> Error occurred");
        assert_eq!(line.tokens.len(), 1);
        assert!(matches!(line.tokens[0], Token::Timestamp(_)));
    }

    #[test]
    fn test_ip_port_normalization() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        let line = normalizer
            .normalize_line("Connection to 192.168.1.100:8080 failed".to_string())
            .unwrap();

        assert_eq!(line.normalized, "Connection to <IP>:<PORT> failed");
        assert_eq!(line.tokens.len(), 2);
    }

    #[test]
    fn test_similarity_calculation() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        let line1 = normalizer
            .normalize_line(
                "2025-01-20 10:15:01 [pid=12345] Connection failed to 192.168.1.100:8080"
                    .to_string(),
            )
            .unwrap();

        let line2 = normalizer
            .normalize_line(
                "2025-01-20 10:15:02 [pid=12346] Connection failed to 192.168.1.101:8081"
                    .to_string(),
            )
            .unwrap();

        assert!(normalizer.are_similar(&line1, &line2));
        let score = normalizer.similarity_score(&line1, &line2);
        assert!(score >= 85.0);
    }

    #[test]
    fn test_hash_consistency() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        let line1 = normalizer
            .normalize_line("<TIMESTAMP> [pid=<PID>] Connection failed to <IP>:<PORT>".to_string())
            .unwrap();

        let line2 = normalizer
            .normalize_line("<TIMESTAMP> [pid=<PID>] Connection failed to <IP>:<PORT>".to_string())
            .unwrap();

        assert_eq!(line1.hash, line2.hash);
    }

    #[test]
    fn test_disabled_normalization() {
        let config = Config {
            normalize_timestamps: false,
            normalize_ips: false,
            normalize_ports: false,
            ..Config::default()
        };

        let normalizer = Normalizer::new(config);

        let line = normalizer
            .normalize_line("2025-01-20 10:15:30 Connection to 192.168.1.100 failed".to_string())
            .unwrap();

        // Even with timestamps/IPs/ports disabled, other always-on patterns
        // (durations, names, etc.) still normalize numbers and decimals
        assert_eq!(
            line.normalized,
            "<NUMBER>-01-20 10:15:30 Connection to <DECIMAL>.<DECIMAL> failed"
        );
    }

    #[test]
    fn test_timestamp_format_preservation() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        // Test PostgreSQL comma format
        let line1 = normalizer
            .normalize_line("2025-09-18 13:26:30,188 INFO: test message".to_string())
            .unwrap();

        let formatted = normalizer.format_timestamp(&line1);
        assert_eq!(formatted, "2025-09-18 13:26:30,188");

        // Test PostgreSQL UTC format
        let line2 = normalizer
            .normalize_line("2025-09-18 13:26:53.345 UTC [24] LOG test".to_string())
            .unwrap();

        let formatted2 = normalizer.format_timestamp(&line2);
        assert_eq!(formatted2, "2025-09-18 13:26:53.345 UTC");

        // Test ISO 8601 format
        let line3 = normalizer
            .normalize_line("2025-01-20T10:15:30.123Z INFO test".to_string())
            .unwrap();

        let formatted3 = normalizer.format_timestamp(&line3);
        assert_eq!(formatted3, "2025-01-20T10:15:30.123Z");
    }

    #[test]
    fn test_invalid_timestamp_handling() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        // Test invalid date that would crash parsing
        let line = normalizer
            .normalize_line("2025-02-31 25:99:99,999 ERROR: invalid timestamp".to_string())
            .unwrap();

        // Should not crash and should preserve the invalid timestamp
        let formatted = normalizer.format_timestamp(&line);
        assert_eq!(formatted, "2025-02-31 25:99:99,999");
    }

    #[test]
    fn test_no_timestamp_handling() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        // Test line with no timestamp
        let line = normalizer
            .normalize_line("Just a log message with no timestamp".to_string())
            .unwrap();

        let formatted = normalizer.format_timestamp(&line);
        assert_eq!(formatted, "unknown");
    }

    #[test]
    fn test_port_detection_vs_timestamps() {
        let config = Config::default();
        let normalizer = Normalizer::new(config);

        // Test that timestamps are NOT detected as ports
        let line1 = normalizer
            .normalize_line("2025-01-20 10:15:30 Connection failed".to_string())
            .unwrap();

        // Should normalize timestamp but NOT detect ports in the time
        assert_eq!(line1.normalized, "<TIMESTAMP> Connection failed");
        assert!(
            line1
                .tokens
                .iter()
                .any(|t| matches!(t, Token::Timestamp(_)))
        );
        assert!(!line1.tokens.iter().any(|t| matches!(t, Token::Port(_))));

        // Test that actual ports ARE detected
        let line2 = normalizer
            .normalize_line("Connection to localhost:8080 failed".to_string())
            .unwrap();

        assert_eq!(line2.normalized, "Connection to localhost:<PORT> failed");
        assert!(line2.tokens.iter().any(|t| matches!(t, Token::Port(8080))));

        // Test that IP:port combinations work
        let line3 = normalizer
            .normalize_line("Connection to 192.168.1.1:3000 failed".to_string())
            .unwrap();

        assert_eq!(line3.normalized, "Connection to <IP>:<PORT> failed");
        assert!(line3.tokens.iter().any(|t| matches!(t, Token::IPv4(_))));
        assert!(line3.tokens.iter().any(|t| matches!(t, Token::Port(3000))));

        // Test that IPv6:port combinations work
        let line4 = normalizer
            .normalize_line("Connection to [2001:db8::1]:8080 failed".to_string())
            .unwrap();

        assert_eq!(line4.normalized, "Connection to [<IP>]:<PORT> failed");
        assert!(line4.tokens.iter().any(|t| matches!(t, Token::IPv6(_))));
        assert!(line4.tokens.iter().any(|t| matches!(t, Token::Port(8080))));
    }

    // --- similarity_score direct tests (mutant kills) ---

    #[test]
    fn test_similarity_score_identical() {
        let normalizer = Normalizer::new(Config::default());
        let line = normalizer
            .normalize_line("hello world".to_string())
            .unwrap();
        let score = normalizer.similarity_score(&line, &line);
        assert!((score - 100.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_similarity_score_completely_different() {
        let normalizer = Normalizer::new(Config::default());
        let a = normalizer.normalize_line("aaaa".to_string()).unwrap();
        let b = normalizer.normalize_line("zzzz".to_string()).unwrap();
        let score = normalizer.similarity_score(&a, &b);
        assert!(
            score < 1.0,
            "Completely different strings should score near 0, got {score}"
        );
    }

    #[test]
    fn test_similarity_score_partial_match() {
        let normalizer = Normalizer::new(Config::default());
        let a = normalizer.normalize_line("hello".to_string()).unwrap();
        let b = normalizer.normalize_line("hella".to_string()).unwrap();
        let score = normalizer.similarity_score(&a, &b);
        // 4/5 chars match = 80.0
        assert!(
            (score - 80.0).abs() < f64::EPSILON,
            "Expected 80.0, got {score}"
        );
    }

    #[test]
    fn test_similarity_score_length_ratio_rejection() {
        let normalizer = Normalizer::new(Config::default());
        let short = normalizer.normalize_line("ab".to_string()).unwrap();
        let long = normalizer.normalize_line("abcdefghij".to_string()).unwrap();
        let score = normalizer.similarity_score(&short, &long);
        // ratio = 2/10 = 0.2, below 0.7 threshold → returns 0.2 * 100 = 20.0
        assert!(
            (score - 20.0).abs() < f64::EPSILON,
            "Expected 20.0 (ratio rejection), got {score}"
        );
    }

    #[test]
    fn test_similarity_score_empty_strings() {
        let normalizer = Normalizer::new(Config::default());
        let empty = LogLine {
            original: String::new(),
            normalized: String::new(),
            tokens: vec![],
            hash: 0,
        };
        let score = normalizer.similarity_score(&empty, &empty);
        assert!(
            (score - 100.0).abs() < f64::EPSILON,
            "Empty vs empty should be 100.0"
        );
    }

    #[test]
    fn test_similarity_score_at_length_ratio_boundary() {
        let normalizer = Normalizer::new(Config::default());
        let ten_chars = normalizer.normalize_line("abcdefghij".to_string()).unwrap();

        // 7/10 = 0.7, exactly at threshold → NOT rejected → char comparison: 7/10 = 70.0
        let seven_match = normalizer.normalize_line("abcdefg".to_string()).unwrap();
        let score = normalizer.similarity_score(&seven_match, &ten_chars);
        assert!(
            (score - 70.0).abs() < f64::EPSILON,
            "At boundary (0.7), should use char comparison. Got {score}"
        );

        // 6/10 = 0.6, below threshold → rejected early → returns 0.6*100 = 60.0
        let six_match = normalizer.normalize_line("abcdef".to_string()).unwrap();
        let score_below = normalizer.similarity_score(&six_match, &ten_chars);
        assert!(
            (score_below - 60.0).abs() < f64::EPSILON,
            "Below boundary, should return ratio*100=60.0. Got {score_below}"
        );

        // 7 chars but last differs → ratio=0.7, char comparison: 6/10 = 60.0
        let seven_mismatch = normalizer.normalize_line("abcdefz".to_string()).unwrap();
        let score_mismatch = normalizer.similarity_score(&seven_mismatch, &ten_chars);
        assert!(
            (score_mismatch - 60.0).abs() < f64::EPSILON,
            "At boundary with mismatch, char comparison gives 60.0. Got {score_mismatch}"
        );

        // 7 chars, none match → ratio=0.7, NOT rejected, char comparison: 0/10 = 0.0
        let seven_none = normalizer.normalize_line("xyzxyzx".to_string()).unwrap();
        let score_none = normalizer.similarity_score(&seven_none, &ten_chars);
        assert!(
            score_none < 1.0,
            "At boundary with zero char matches, should be ~0. Got {score_none}"
        );
    }

    #[test]
    fn test_similarity_score_one_char_diff() {
        let normalizer = Normalizer::new(Config::default());
        let a = normalizer.normalize_line("abcdefghij".to_string()).unwrap();
        let b = normalizer.normalize_line("abcdefghix".to_string()).unwrap();
        let score = normalizer.similarity_score(&a, &b);
        // 9/10 chars match = 90.0
        assert!(
            (score - 90.0).abs() < f64::EPSILON,
            "Expected 90.0, got {score}"
        );
    }

    // --- summarize_variation_types direct tests (mutant kills) ---

    #[test]
    fn test_variation_types_different_ips() {
        let normalizer = Normalizer::new(Config::default());
        let first = vec![Token::IPv4("10.0.0.1".to_string())];
        let last = vec![Token::IPv4("10.0.0.2".to_string())];
        let types = normalizer.summarize_variation_types(&first, &last);
        assert_eq!(types, vec!["IP"]);
    }

    #[test]
    fn test_variation_types_same_tokens_no_variation() {
        let normalizer = Normalizer::new(Config::default());
        let tokens = vec![Token::IPv4("10.0.0.1".to_string())];
        let types = normalizer.summarize_variation_types(&tokens, &tokens);
        assert!(types.is_empty(), "Same tokens should produce no variation");
    }

    #[test]
    fn test_variation_types_essence_mode_skips_timestamps() {
        let config = Config {
            essence_mode: true,
            ..Config::default()
        };
        let normalizer = Normalizer::new(config);
        let first = vec![Token::Timestamp("2025-01-01T00:00:00Z".to_string())];
        let last = vec![Token::Timestamp("2025-01-02T00:00:00Z".to_string())];
        let types = normalizer.summarize_variation_types(&first, &last);
        assert!(
            types.is_empty(),
            "Essence mode should skip timestamp variations"
        );
    }

    #[test]
    fn test_variation_types_non_essence_includes_timestamps() {
        let normalizer = Normalizer::new(Config::default());
        let first = vec![Token::Timestamp("2025-01-01T00:00:00Z".to_string())];
        let last = vec![Token::Timestamp("2025-01-02T00:00:00Z".to_string())];
        let types = normalizer.summarize_variation_types(&first, &last);
        assert_eq!(types, vec!["timestamp"]);
    }

    #[test]
    fn test_variation_types_multiple_types_sorted() {
        let normalizer = Normalizer::new(Config::default());
        let first = vec![
            Token::IPv4("10.0.0.1".to_string()),
            Token::Uuid("aaa".to_string()),
        ];
        let last = vec![
            Token::IPv4("10.0.0.2".to_string()),
            Token::Uuid("bbb".to_string()),
        ];
        let types = normalizer.summarize_variation_types(&first, &last);
        assert_eq!(types, vec!["IP", "UUID"]);
    }

    // --- normalize_line short-circuit tests (mutant kills) ---

    #[test]
    fn test_normalize_ips_only_flag() {
        let config = Config {
            normalize_ips: true,
            normalize_ports: false,
            normalize_fqdns: false,
            ..Config::default()
        };
        let normalizer = Normalizer::new(config);
        let line = normalizer
            .normalize_line("connect to 10.0.0.1:8080".to_string())
            .unwrap();
        assert!(
            line.tokens.iter().any(|t| matches!(t, Token::IPv4(_))),
            "IPs should be detected"
        );
    }

    #[test]
    fn test_normalize_ports_only_flag() {
        let config = Config {
            normalize_ips: false,
            normalize_ports: true,
            normalize_fqdns: false,
            ..Config::default()
        };
        let normalizer = Normalizer::new(config);
        let line = normalizer
            .normalize_line("connect to localhost:8080".to_string())
            .unwrap();
        assert!(
            line.tokens.iter().any(|t| matches!(t, Token::Port(_))),
            "Ports should be detected"
        );
    }
}