kelora 0.9.0

A command-line log analysis tool with embedded Rhai scripting
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
#![allow(dead_code)]
use chrono::{DateTime, Utc};
use indexmap::IndexMap;
use rhai::Dynamic;
use serde::{Deserialize, Serialize};

/// Context type for lines around matches
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ContextType {
    #[default]
    None, // Regular event, no context
    Match,  // Event that matched filters
    Before, // Before-context for a match
    After,  // After-context for a match
    Both,   // Overlapping context (before + after)
}

/// Flattening style for nested data structures
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlattenStyle {
    /// Use dots for objects and brackets for arrays: "user.name", "items[0].value"
    #[default]
    Bracket,
    /// Use dots everywhere: "user.name", "items.0.value"
    Dot,
    /// Use underscores everywhere: "user_name", "items_0_value"
    Underscore,
}

impl FlattenStyle {
    /// Format an object field key
    fn format_object_key(&self, parent: &str, key: &str) -> String {
        match self {
            FlattenStyle::Bracket | FlattenStyle::Dot => {
                if parent.is_empty() {
                    key.to_string()
                } else {
                    format!("{}.{}", parent, key)
                }
            }
            FlattenStyle::Underscore => {
                if parent.is_empty() {
                    key.to_string()
                } else {
                    format!("{}_{}", parent, key)
                }
            }
        }
    }

    /// Format an array index key
    fn format_array_key(&self, parent: &str, index: usize) -> String {
        match self {
            FlattenStyle::Bracket => {
                if parent.is_empty() {
                    format!("[{}]", index)
                } else {
                    format!("{}[{}]", parent, index)
                }
            }
            FlattenStyle::Dot => {
                if parent.is_empty() {
                    index.to_string()
                } else {
                    format!("{}.{}", parent, index)
                }
            }
            FlattenStyle::Underscore => {
                if parent.is_empty() {
                    index.to_string()
                } else {
                    format!("{}_{}", parent, index)
                }
            }
        }
    }
}

/// Flatten a Dynamic value into a flat map of key-value pairs
///
/// This function recursively traverses nested maps and arrays, generating
/// flat keys according to the specified style. It respects max_depth to
/// prevent infinite recursion and memory issues.
///
/// # Arguments
/// * `value` - The Dynamic value to flatten
/// * `style` - The flattening style (Bracket, Dot, Underscore)
/// * `max_depth` - Maximum recursion depth (0 = unlimited)
pub fn flatten_dynamic(
    value: &Dynamic,
    style: FlattenStyle,
    max_depth: usize,
) -> IndexMap<String, Dynamic> {
    let mut result = IndexMap::new();
    // Convert max_depth=0 to unlimited
    let effective_max_depth = if max_depth == 0 {
        usize::MAX
    } else {
        max_depth
    };
    flatten_dynamic_recursive(value, "", style, 0, effective_max_depth, &mut result);
    result
}

/// Recursive helper for flatten_dynamic
fn flatten_dynamic_recursive(
    value: &Dynamic,
    prefix: &str,
    style: FlattenStyle,
    current_depth: usize,
    max_depth: usize,
    result: &mut IndexMap<String, Dynamic>,
) {
    // If we've reached max depth, store as-is
    if current_depth >= max_depth {
        let key = if prefix.is_empty() {
            "value".to_string()
        } else {
            prefix.to_string()
        };
        result.insert(key, value.clone());
        return;
    }

    if let Some(map) = value.clone().try_cast::<rhai::Map>() {
        // Handle Rhai Map (object)
        if map.is_empty() {
            // Empty objects become null values
            let key = if prefix.is_empty() {
                "value".to_string()
            } else {
                prefix.to_string()
            };
            result.insert(key, Dynamic::UNIT);
        } else {
            for (key, val) in map {
                let new_key = style.format_object_key(prefix, key.as_ref());
                flatten_dynamic_recursive(
                    &val,
                    &new_key,
                    style,
                    current_depth + 1,
                    max_depth,
                    result,
                );
            }
        }
    } else if let Some(array) = value.clone().try_cast::<rhai::Array>() {
        // Handle Rhai Array
        if array.is_empty() {
            // Empty arrays become null values
            let key = if prefix.is_empty() {
                "value".to_string()
            } else {
                prefix.to_string()
            };
            result.insert(key, Dynamic::UNIT);
        } else {
            for (index, val) in array.iter().enumerate() {
                let new_key = style.format_array_key(prefix, index);
                flatten_dynamic_recursive(
                    val,
                    &new_key,
                    style,
                    current_depth + 1,
                    max_depth,
                    result,
                );
            }
        }
    } else {
        // Scalar value - store it
        let key = if prefix.is_empty() {
            "value".to_string()
        } else {
            prefix.to_string()
        };
        result.insert(key, value.clone());
    }
}

/// Flatten an entire Event's fields
pub fn flatten_event_fields(
    event: &Event,
    style: FlattenStyle,
    max_depth: usize,
) -> IndexMap<String, Dynamic> {
    let mut result = IndexMap::new();

    for (key, value) in &event.fields {
        if value.clone().try_cast::<rhai::Map>().is_some() {
            // Flatten nested objects
            let flattened = flatten_dynamic(value, style, max_depth);
            for (flat_key, flat_value) in flattened {
                let full_key = style.format_object_key(key, &flat_key);
                result.insert(full_key, flat_value);
            }
        } else if value.clone().try_cast::<rhai::Array>().is_some() {
            // Flatten arrays
            let flattened = flatten_dynamic(value, style, max_depth);
            for (flat_key, flat_value) in flattened {
                let full_key = if flat_key == "value" {
                    key.clone()
                } else {
                    style.format_object_key(key, &flat_key)
                };
                result.insert(full_key, flat_value);
            }
        } else {
            // Scalar values - keep as-is
            result.insert(key.clone(), value.clone());
        }
    }

    result
}

/// Convert serde_json::Value to rhai::Dynamic recursively
/// This is the single source of truth for JSON to Rhai conversion
pub fn json_to_dynamic(value: &serde_json::Value) -> Dynamic {
    match value {
        serde_json::Value::String(s) => Dynamic::from(s.clone()),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Dynamic::from(i)
            } else if let Some(f) = n.as_f64() {
                Dynamic::from(f)
            } else {
                Dynamic::from(n.to_string())
            }
        }
        serde_json::Value::Bool(b) => Dynamic::from(*b),
        serde_json::Value::Null => Dynamic::UNIT,
        serde_json::Value::Array(arr) => {
            // Convert JSON array to Rhai array recursively
            let mut rhai_array = rhai::Array::new();
            for item in arr {
                rhai_array.push(json_to_dynamic(item));
            }
            Dynamic::from(rhai_array)
        }
        serde_json::Value::Object(obj) => {
            // Convert JSON object to Rhai map recursively
            let mut rhai_map = rhai::Map::new();
            for (key, val) in obj {
                rhai_map.insert(key.clone().into(), json_to_dynamic(val));
            }
            Dynamic::from(rhai_map)
        }
    }
}

/// Core field name constants to ensure consistency across the codebase
pub const TIMESTAMP_FIELD_NAMES: &[&str] = &[
    "ts",
    "_ts",
    "timestamp",
    "at",
    "time",
    "@timestamp",
    "log_timestamp",
    "event_time",
    "datetime",
    "date_time",
    "created_at",
    "logged_at",
    "_t",
    "@t",
    "t",
];

pub const LEVEL_FIELD_NAMES: &[&str] = &[
    "level",
    "lvl",
    "severity",
    "log_level",
    "loglevel",
    "priority",
    "sev",
    "@level",
    "log_severity",
    "error_level",
    "event_level",
    "_level",
    "@l",
];

pub const MESSAGE_FIELD_NAMES: &[&str] = &[
    "msg",
    "message",
    "content",
    "data",
    "log",
    "text",
    "description",
    "details",
    "body",
    "payload",
    "event_message",
    "log_message",
    "_message",
    "@message",
    "@m",
    "event", // CEF event name field (lowest priority)
];

/// Create an ordered iterator over event fields, prioritizing timestamps, log levels, and messages
///
/// If the event has been processed by key filtering (--keys/--exclude-keys),
/// the existing order is preserved. Otherwise, returns field pairs in this order:
/// 1. Timestamp fields (in order of TIMESTAMP_FIELD_NAMES)
/// 2. Log level fields (in order of LEVEL_FIELD_NAMES)
/// 3. Message fields (in order of MESSAGE_FIELD_NAMES)
/// 4. All other fields (sorted alphabetically)
pub fn ordered_fields(event: &Event) -> Vec<(&String, &rhai::Dynamic)> {
    // If the event has been processed by key filtering, preserve the existing order
    if event.key_filtered {
        return event.fields.iter().collect();
    }

    let mut ordered = Vec::with_capacity(event.fields.len());

    // 1. Add timestamp fields in priority order
    for &ts_name in TIMESTAMP_FIELD_NAMES {
        if let Some((key, value)) = event.fields.get_key_value(ts_name) {
            ordered.push((key, value));
        }
    }

    // 2. Add log level fields in priority order
    for &level_name in LEVEL_FIELD_NAMES {
        if let Some((key, value)) = event.fields.get_key_value(level_name) {
            ordered.push((key, value));
        }
    }

    // 3. Add message fields in priority order
    for &msg_name in MESSAGE_FIELD_NAMES {
        if let Some((key, value)) = event.fields.get_key_value(msg_name) {
            ordered.push((key, value));
        }
    }

    // 4. Add all remaining fields in IndexMap order (no additional sorting)
    let remaining: Vec<_> = event
        .fields
        .iter()
        .filter(|(key, _)| {
            !TIMESTAMP_FIELD_NAMES.contains(&key.as_str())
                && !LEVEL_FIELD_NAMES.contains(&key.as_str())
                && !MESSAGE_FIELD_NAMES.contains(&key.as_str())
        })
        .collect();

    ordered.extend(remaining);

    ordered
}

#[derive(Debug, Clone, Default)]
pub struct Event {
    pub fields: IndexMap<String, Dynamic>,
    /// Flag indicating whether this event has been processed by key filtering (--keys/--exclude-keys)
    pub key_filtered: bool,
    pub original_line: String,
    pub line_num: Option<usize>,
    pub filename: Option<String>,
    pub span: SpanInfo,
    /// Parsed timestamp field for efficient timestamp operations
    /// This is populated automatically when timestamps are extracted from fields
    pub parsed_ts: Option<DateTime<Utc>>,
    /// Context type for this event (match, before, after, none)
    pub context_type: ContextType,
    /// Ensures timestamp parsing statistics are recorded at most once per event
    pub(crate) timestamp_stats_recorded: bool,
}

/// Span assignment status for events when --span is active
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanStatus {
    Included,
    Late,
    Unassigned,
    Filtered,
}

impl SpanStatus {
    pub fn as_str(&self) -> &'static str {
        match self {
            SpanStatus::Included => "included",
            SpanStatus::Late => "late",
            SpanStatus::Unassigned => "unassigned",
            SpanStatus::Filtered => "filtered",
        }
    }
}

/// Span metadata stored on each event for Rhai exposure
#[derive(Debug, Clone, Default)]
pub struct SpanInfo {
    pub status: Option<SpanStatus>,
    pub span_id: Option<String>,
    pub span_start: Option<DateTime<Utc>>,
    pub span_end: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FieldValue {
    String(String),
    Number(f64),
    Boolean(bool),
    Null,
}

impl Event {
    pub fn with_capacity(original_line: String, capacity: usize) -> Self {
        Self {
            fields: IndexMap::with_capacity(capacity),
            key_filtered: false,
            original_line,
            line_num: None,
            filename: None,
            span: SpanInfo::default(),
            parsed_ts: None,
            context_type: ContextType::None,
            timestamp_stats_recorded: false,
        }
    }

    pub fn default_with_line(line: String) -> Self {
        Self {
            original_line: line,
            ..Default::default()
        }
    }

    pub fn set_field(&mut self, key: String, value: Dynamic) {
        self.fields.insert(key, value);
    }

    pub fn set_metadata(&mut self, line_num: usize, filename: Option<String>) {
        self.line_num = Some(line_num);
        self.filename = filename;
    }

    pub fn set_span_info(&mut self, info: SpanInfo) {
        self.span = info;
    }

    /// Filter to only show specified keys, keeping only fields that actually exist
    pub fn filter_keys(&mut self, keys: &[String]) {
        let mut new_fields = IndexMap::with_capacity(keys.len());

        // Only include fields that are both requested and exist
        for key in keys {
            if let Some(value) = self.fields.get(key) {
                new_fields.insert(key.clone(), value.clone());
            }
        }

        self.fields = new_fields;
    }

    /// Try to parse and extract timestamp from the fields map
    pub fn extract_timestamp(&mut self) {
        self.extract_timestamp_with_parser(None);
    }

    /// Try to parse and extract timestamp from the fields map with optional adaptive parser
    pub fn extract_timestamp_with_parser(
        &mut self,
        parser: Option<&mut crate::timestamp::AdaptiveTsParser>,
    ) {
        self.extract_timestamp_with_config(parser, &crate::timestamp::TsConfig::default());
    }

    /// Extract timestamp with configuration
    pub fn extract_timestamp_with_config(
        &mut self,
        parser: Option<&mut crate::timestamp::AdaptiveTsParser>,
        ts_config: &crate::timestamp::TsConfig,
    ) {
        // Extract and parse timestamp with comprehensive field recognition
        if self.parsed_ts.is_none() {
            if let Some((field_name, ts_str)) =
                crate::timestamp::identify_timestamp_field(&self.fields, ts_config)
            {
                let mut parsed = false;
                let parsed_ts = if let Some(parser) = parser {
                    parser.parse_ts_with_config(
                        &ts_str,
                        ts_config.custom_format.as_deref(),
                        ts_config.default_timezone.as_deref(),
                    )
                } else {
                    // Use the enhanced adaptive parser as default
                    let mut default_parser = crate::timestamp::AdaptiveTsParser::new();
                    default_parser.parse_ts_with_config(
                        &ts_str,
                        ts_config.custom_format.as_deref(),
                        ts_config.default_timezone.as_deref(),
                    )
                };

                if let Some(ts) = parsed_ts {
                    self.parsed_ts = Some(ts);
                    parsed = true;
                }

                if !self.timestamp_stats_recorded {
                    crate::stats::stats_record_timestamp_detection(&field_name, &ts_str, parsed);
                    self.timestamp_stats_recorded = true;
                }
            } else if !self.timestamp_stats_recorded {
                crate::stats::stats_record_timestamp_absent();
                self.timestamp_stats_recorded = true;
            }
        }
    }
}

impl std::fmt::Display for FieldValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FieldValue::String(s) => write!(f, "{}", s),
            FieldValue::Number(n) => write!(f, "{}", n),
            FieldValue::Boolean(b) => write!(f, "{}", b),
            FieldValue::Null => write!(f, "null"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;
    use proptest::strategy::{BoxedStrategy, Strategy};

    fn arb_dynamic(depth: u32) -> BoxedStrategy<Dynamic> {
        use proptest::collection::vec;

        let leaf = prop_oneof![
            any::<i64>().prop_map(Dynamic::from),
            prop::num::f64::NORMAL.prop_map(Dynamic::from),
            any::<bool>().prop_map(Dynamic::from),
            "[ -~]{0,16}".prop_map(Dynamic::from),
            Just(Dynamic::UNIT),
        ]
        .boxed();

        leaf.prop_recursive(depth, 64, 8, |inner| {
            let map = vec(("[a-z]{1,8}".prop_map(|s: String| s), inner.clone()), 0..4).prop_map(
                |entries| {
                    let mut map = rhai::Map::new();
                    for (k, v) in entries {
                        map.insert(k.into(), v);
                    }
                    Dynamic::from(map)
                },
            );

            let array = vec(inner, 0..4).prop_map(|items| {
                let mut arr = rhai::Array::new();
                for item in items {
                    arr.push(item);
                }
                Dynamic::from(arr)
            });

            prop_oneof![map, array]
        })
        .boxed()
    }
    use chrono::{TimeZone, Utc};
    use rhai::{Array, Map};

    #[test]
    fn test_flatten_dynamic_simple_object() {
        let mut map = Map::new();
        map.insert("name".into(), Dynamic::from("alice"));
        map.insert("age".into(), Dynamic::from(25i64));

        let dynamic_map = Dynamic::from(map);
        let flattened = flatten_dynamic(&dynamic_map, FlattenStyle::Bracket, 10);

        assert_eq!(flattened.get("name").unwrap().to_string(), "alice");
        assert_eq!(flattened.get("age").unwrap().to_string(), "25");
    }

    #[test]
    fn test_flatten_dynamic_nested_object() {
        let mut inner_map = Map::new();
        inner_map.insert("street".into(), Dynamic::from("123 Main St"));
        inner_map.insert("city".into(), Dynamic::from("Boston"));

        let mut outer_map = Map::new();
        outer_map.insert("name".into(), Dynamic::from("alice"));
        outer_map.insert("address".into(), Dynamic::from(inner_map));

        let dynamic_map = Dynamic::from(outer_map);
        let flattened = flatten_dynamic(&dynamic_map, FlattenStyle::Bracket, 10);

        assert_eq!(flattened.get("name").unwrap().to_string(), "alice");
        assert_eq!(
            flattened.get("address.street").unwrap().to_string(),
            "123 Main St"
        );
        assert_eq!(flattened.get("address.city").unwrap().to_string(), "Boston");
    }

    #[test]
    fn test_flatten_dynamic_array() {
        let array = vec![
            Dynamic::from("item1"),
            Dynamic::from("item2"),
            Dynamic::from(42i64),
        ];

        let dynamic_array = Dynamic::from(array);
        let flattened = flatten_dynamic(&dynamic_array, FlattenStyle::Bracket, 10);

        assert_eq!(flattened.get("[0]").unwrap().to_string(), "item1");
        assert_eq!(flattened.get("[1]").unwrap().to_string(), "item2");
        assert_eq!(flattened.get("[2]").unwrap().to_string(), "42");
    }

    #[test]
    fn test_flatten_dynamic_mixed_structure() {
        let mut item1 = Map::new();
        item1.insert("id".into(), Dynamic::from(1i64));
        item1.insert("name".into(), Dynamic::from("first"));

        let mut item2 = Map::new();
        item2.insert("id".into(), Dynamic::from(2i64));
        item2.insert("name".into(), Dynamic::from("second"));

        let array = vec![Dynamic::from(item1), Dynamic::from(item2)];

        let mut root = Map::new();
        root.insert("user".into(), Dynamic::from("alice"));
        root.insert("items".into(), Dynamic::from(array));

        let dynamic_root = Dynamic::from(root);
        let flattened = flatten_dynamic(&dynamic_root, FlattenStyle::Bracket, 10);

        assert_eq!(flattened.get("user").unwrap().to_string(), "alice");
        assert_eq!(flattened.get("items[0].id").unwrap().to_string(), "1");
        assert_eq!(flattened.get("items[0].name").unwrap().to_string(), "first");
        assert_eq!(flattened.get("items[1].id").unwrap().to_string(), "2");
        assert_eq!(
            flattened.get("items[1].name").unwrap().to_string(),
            "second"
        );
    }

    #[test]
    fn test_flatten_styles() {
        let mut inner = Map::new();
        inner.insert("value".into(), Dynamic::from(42i64));

        let array = vec![Dynamic::from(inner)];

        let mut root = Map::new();
        root.insert("data".into(), Dynamic::from(array));

        let dynamic_root = Dynamic::from(root);

        // Test bracket style
        let bracket = flatten_dynamic(&dynamic_root, FlattenStyle::Bracket, 10);
        assert!(bracket.contains_key("data[0].value"));

        // Test dot style
        let dot = flatten_dynamic(&dynamic_root, FlattenStyle::Dot, 10);
        assert!(dot.contains_key("data.0.value"));

        // Test underscore style
        let underscore = flatten_dynamic(&dynamic_root, FlattenStyle::Underscore, 10);
        assert!(underscore.contains_key("data_0_value"));
    }

    #[test]
    fn extract_timestamp_uses_custom_field_when_present() {
        let mut event = Event::default_with_line("line".to_string());
        event.set_field(
            "custom_ts".to_string(),
            Dynamic::from("2024-05-19T12:34:56Z"),
        );
        event.set_field("ts".to_string(), Dynamic::from("2020-01-01T00:00:00Z"));

        let config = crate::timestamp::TsConfig {
            custom_field: Some("custom_ts".to_string()),
            custom_format: None,
            default_timezone: None,
            auto_parse: true,
        };

        event.extract_timestamp_with_config(None, &config);

        let parsed = event
            .parsed_ts
            .expect("expected timestamp parsed from custom field");
        assert_eq!(
            parsed,
            Utc.with_ymd_and_hms(2024, 5, 19, 12, 34, 56).unwrap()
        );
    }

    #[test]
    fn extract_timestamp_missing_custom_field_does_not_fallback() {
        let mut event = Event::default_with_line("line".to_string());
        event.set_field("ts".to_string(), Dynamic::from("2024-05-19T12:34:56Z"));

        let config = crate::timestamp::TsConfig {
            custom_field: Some("custom_ts".to_string()),
            custom_format: None,
            default_timezone: None,
            auto_parse: true,
        };

        event.extract_timestamp_with_config(None, &config);

        assert!(
            event.parsed_ts.is_none(),
            "timestamp should remain unset when custom field is missing"
        );
        assert!(
            event.timestamp_stats_recorded,
            "absence should be recorded even when timestamp not parsed"
        );
    }

    #[test]
    fn extract_timestamp_non_string_custom_field_does_not_fallback() {
        let mut event = Event::default_with_line("line".to_string());
        event.set_field("custom_ts".to_string(), Dynamic::from(123_i64));
        event.set_field("ts".to_string(), Dynamic::from("2024-05-19T12:34:56Z"));

        let config = crate::timestamp::TsConfig {
            custom_field: Some("custom_ts".to_string()),
            custom_format: None,
            default_timezone: None,
            auto_parse: true,
        };

        event.extract_timestamp_with_config(None, &config);

        assert!(
            event.parsed_ts.is_none(),
            "non-string custom timestamp should not be parsed"
        );
        assert!(
            event.timestamp_stats_recorded,
            "invalid custom timestamp should count as absent"
        );
    }

    #[test]
    fn test_flatten_max_depth() {
        let mut deep = Map::new();
        deep.insert("level4".into(), Dynamic::from("deep"));

        let mut level3 = Map::new();
        level3.insert("level3".into(), Dynamic::from(deep));

        let mut level2 = Map::new();
        level2.insert("level2".into(), Dynamic::from(level3));

        let mut level1 = Map::new();
        level1.insert("level1".into(), Dynamic::from(level2));

        let dynamic_root = Dynamic::from(level1);

        // With max_depth=2, should stop at level2
        let flattened = flatten_dynamic(&dynamic_root, FlattenStyle::Bracket, 2);

        // Should have flattened up to level2 but not deeper
        assert!(flattened.contains_key("level1.level2"));
        assert!(!flattened.contains_key("level1.level2.level3.level4"));
    }

    #[test]
    fn test_flatten_empty_structures() {
        let empty_map = Map::new();
        let empty_array = Array::new();

        let flattened_map = flatten_dynamic(&Dynamic::from(empty_map), FlattenStyle::Bracket, 10);
        let flattened_array =
            flatten_dynamic(&Dynamic::from(empty_array), FlattenStyle::Bracket, 10);

        // Empty structures should produce a single null value
        assert_eq!(flattened_map.len(), 1);
        assert!(flattened_map.get("value").unwrap().is_unit());

        assert_eq!(flattened_array.len(), 1);
        assert!(flattened_array.get("value").unwrap().is_unit());
    }

    #[test]
    fn test_flatten_unlimited_depth() {
        // Create a very deeply nested structure
        let mut deep = Map::new();
        deep.insert("level8".into(), Dynamic::from("deepest"));

        let mut level7 = Map::new();
        level7.insert("level7".into(), Dynamic::from(deep));

        let mut level6 = Map::new();
        level6.insert("level6".into(), Dynamic::from(level7));

        let mut level5 = Map::new();
        level5.insert("level5".into(), Dynamic::from(level6));

        let mut level4 = Map::new();
        level4.insert("level4".into(), Dynamic::from(level5));

        let mut level3 = Map::new();
        level3.insert("level3".into(), Dynamic::from(level4));

        let mut level2 = Map::new();
        level2.insert("level2".into(), Dynamic::from(level3));

        let mut level1 = Map::new();
        level1.insert("level1".into(), Dynamic::from(level2));

        let dynamic_root = Dynamic::from(level1);

        // With max_depth=0 (unlimited), should flatten completely
        let unlimited = flatten_dynamic(&dynamic_root, FlattenStyle::Bracket, 0);

        // Should have fully flattened the deep structure
        assert!(unlimited.contains_key("level1.level2.level3.level4.level5.level6.level7.level8"));
        assert_eq!(
            unlimited
                .get("level1.level2.level3.level4.level5.level6.level7.level8")
                .unwrap()
                .to_string(),
            "deepest"
        );

        // Compare with limited depth
        let limited = flatten_dynamic(&dynamic_root, FlattenStyle::Bracket, 3);

        // Should stop at level 3 and contain the remaining structure as a string
        assert!(limited.contains_key("level1.level2.level3"));
        assert!(!limited.contains_key("level1.level2.level3.level4.level5.level6.level7.level8"));
    }
    proptest! {
        #[test]
        fn prop_flatten_preserves_scalars(value in arb_dynamic(3), style in prop_oneof![Just(FlattenStyle::Bracket), Just(FlattenStyle::Dot), Just(FlattenStyle::Underscore)]) {
            let flattened = flatten_dynamic(&value, style, 0);
            prop_assert!(!flattened.is_empty());

            if value.clone().try_cast::<rhai::Map>().is_none() && value.clone().try_cast::<rhai::Array>().is_none() {
                prop_assert_eq!(flattened.len(), 1);
                let (_, v) = flattened.iter().next().unwrap();
                prop_assert_eq!(v.clone().type_name(), value.type_name());
            }
        }

        #[test]
        fn prop_flatten_depth_limit_dot(depth in 1usize..5, value in arb_dynamic(3)) {
            let flattened = flatten_dynamic(&value, FlattenStyle::Dot, depth);
            for key in flattened.keys() {
                if key != "value" {
                    let segments = key.split('.').count();
                    prop_assert!(segments <= depth);
                }
            }
        }
    }
}