sonda-core 0.4.0

Core engine for Sonda — synthetic telemetry generation library
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! Value generators produce f64 values for each tick.
//!
//! All generators implement the `ValueGenerator` trait and are constructed
//! via `create_generator()` which returns `Box<dyn ValueGenerator>`.
//!
//! Log generators implement the `LogGenerator` trait and produce `LogEvent`
//! values. They are constructed via `create_log_generator()`.

pub mod constant;
pub mod csv_replay;
pub mod log_replay;
pub mod log_template;
pub mod sawtooth;
pub mod sequence;
pub mod sine;
pub mod step;
pub mod uniform;

use std::collections::{BTreeMap, HashMap};

use self::constant::Constant;
use self::csv_replay::CsvReplayGenerator;
use self::log_replay::LogReplayGenerator;
use self::log_template::{LogTemplateGenerator, TemplateEntry};
use self::sawtooth::Sawtooth;
use self::sequence::SequenceGenerator;
use self::sine::Sine;
use self::step::StepGenerator;
use self::uniform::UniformRandom;
use crate::model::log::{LogEvent, Severity};
use crate::{ConfigError, SondaError};

/// A generator produces a single f64 value for a given tick index.
///
/// Implementations must be deterministic for a given configuration and tick.
/// Side effects are not allowed in `value()`.
pub trait ValueGenerator: Send + Sync {
    /// Produce a value for the given tick index (0-based, monotonically increasing).
    fn value(&self, tick: u64) -> f64;
}

/// Configuration for a value generator, used for YAML deserialization.
///
/// The `type` field selects which generator to instantiate. Additional fields
/// are specific to each variant.
///
/// # Example YAML
///
/// ```yaml
/// generator:
///   type: sine
///   amplitude: 5.0
///   period_secs: 30
///   offset: 10.0
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(tag = "type"))]
pub enum GeneratorConfig {
    /// A generator that always returns the same value.
    #[cfg_attr(feature = "config", serde(rename = "constant"))]
    Constant {
        /// The fixed value returned on every tick.
        value: f64,
    },
    /// A generator that returns deterministically random values in `[min, max]`.
    #[cfg_attr(feature = "config", serde(rename = "uniform"))]
    Uniform {
        /// Lower bound of the output range (inclusive).
        min: f64,
        /// Upper bound of the output range (inclusive).
        max: f64,
        /// Optional seed for deterministic replay. Defaults to 0 when absent.
        seed: Option<u64>,
    },
    /// A generator that follows a sine curve.
    #[cfg_attr(feature = "config", serde(rename = "sine"))]
    Sine {
        /// Half the peak-to-peak swing of the wave.
        amplitude: f64,
        /// Duration of one full cycle in seconds.
        period_secs: f64,
        /// Vertical offset applied to every sample (the wave's midpoint).
        offset: f64,
    },
    /// A generator that linearly ramps from `min` to `max` then resets.
    #[cfg_attr(feature = "config", serde(rename = "sawtooth"))]
    Sawtooth {
        /// Value at the start of each period.
        min: f64,
        /// Value approached at the end of each period (never reached).
        max: f64,
        /// Duration of one full ramp in seconds.
        period_secs: f64,
    },
    /// A generator that steps through an explicit sequence of values.
    #[cfg_attr(feature = "config", serde(rename = "sequence"))]
    Sequence {
        /// The ordered list of values to step through. Must not be empty.
        values: Vec<f64>,
        /// When true (default), the sequence cycles. When false, the last value
        /// is returned for all ticks beyond the sequence length.
        repeat: Option<bool>,
    },
    /// A generator that replays numeric values from a CSV file.
    #[cfg_attr(feature = "config", serde(rename = "csv_replay"))]
    CsvReplay {
        /// Path to the CSV file containing numeric values.
        file: String,
        /// Zero-based column index to read. Defaults to 0 when absent.
        column: Option<usize>,
        /// Whether to skip the first data row as a header. Defaults to true
        /// when absent.
        has_header: Option<bool>,
        /// When true (default), the values cycle. When false, the last value
        /// is returned for all ticks beyond the file length.
        repeat: Option<bool>,
    },
    /// A monotonic step counter: `start + tick * step_size`, with optional wrap-around.
    ///
    /// Useful for testing `rate()` and `increase()` PromQL functions.
    #[cfg_attr(feature = "config", serde(rename = "step"))]
    Step {
        /// Initial value at tick 0. Defaults to 0.0 when absent.
        #[cfg_attr(feature = "config", serde(default))]
        start: Option<f64>,
        /// Increment applied per tick.
        step_size: f64,
        /// Optional wrap-around threshold. When set and greater than `start`,
        /// the value wraps via modular arithmetic.
        max: Option<f64>,
    },
}

/// Construct a `Box<dyn ValueGenerator>` from the given configuration.
///
/// The `rate` parameter (events per second) is required by time-based generators
/// (`Sine`, `Sawtooth`) to convert `period_secs` into period ticks.
///
/// # Errors
///
/// Returns [`SondaError::Config`] if the generator configuration is invalid
/// (e.g., an empty values list for the sequence generator).
pub fn create_generator(
    config: &GeneratorConfig,
    rate: f64,
) -> Result<Box<dyn ValueGenerator>, SondaError> {
    match config {
        GeneratorConfig::Constant { value } => Ok(Box::new(Constant::new(*value))),
        GeneratorConfig::Uniform { min, max, seed } => {
            Ok(Box::new(UniformRandom::new(*min, *max, seed.unwrap_or(0))))
        }
        GeneratorConfig::Sine {
            amplitude,
            period_secs,
            offset,
        } => Ok(Box::new(Sine::new(*amplitude, *period_secs, *offset, rate))),
        GeneratorConfig::Sawtooth {
            min,
            max,
            period_secs,
        } => Ok(Box::new(Sawtooth::new(*min, *max, *period_secs, rate))),
        GeneratorConfig::Sequence { values, repeat } => Ok(Box::new(SequenceGenerator::new(
            values.clone(),
            repeat.unwrap_or(true),
        )?)),
        GeneratorConfig::CsvReplay {
            file,
            column,
            has_header,
            repeat,
        } => Ok(Box::new(CsvReplayGenerator::new(
            file,
            column.unwrap_or(0),
            has_header.unwrap_or(true),
            repeat.unwrap_or(true),
        )?)),
        GeneratorConfig::Step {
            start,
            step_size,
            max,
        } => Ok(Box::new(StepGenerator::new(
            start.unwrap_or(0.0),
            *step_size,
            *max,
        ))),
    }
}

// ---------------------------------------------------------------------------
// Log generators
// ---------------------------------------------------------------------------

/// A log generator produces a `LogEvent` for a given tick index.
///
/// Implementations must be deterministic for a given configuration and tick.
/// Side effects are not allowed in `generate()`.
pub trait LogGenerator: Send + Sync {
    /// Produce a `LogEvent` for the given tick index (0-based, monotonically increasing).
    fn generate(&self, tick: u64) -> LogEvent;
}

/// Configuration for one message template used by [`LogGeneratorConfig::Template`].
///
/// The `message` field may contain `{placeholder}` tokens that are resolved
/// using the corresponding value pool from `field_pools`.
///
/// # Example YAML
///
/// ```yaml
/// message: "Request from {ip} to {endpoint}"
/// field_pools:
///   ip:
///     - "10.0.0.1"
///     - "10.0.0.2"
///   endpoint:
///     - "/api"
///     - "/health"
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
pub struct TemplateConfig {
    /// The message template. Use `{field_name}` for dynamic placeholders.
    pub message: String,
    /// Maps placeholder names to their value pools.
    ///
    /// Uses `BTreeMap` for deterministic iteration order, matching the
    /// codebase convention for ordered maps.
    #[cfg_attr(feature = "config", serde(default))]
    pub field_pools: BTreeMap<String, Vec<String>>,
}

/// Configuration for a log generator, used for YAML deserialization.
///
/// The `type` field selects which generator to instantiate.
///
/// # Example YAML — template generator
///
/// ```yaml
/// generator:
///   type: template
///   templates:
///     - message: "Request from {ip} to {endpoint}"
///       field_pools:
///         ip: ["10.0.0.1", "10.0.0.2"]
///         endpoint: ["/api", "/health"]
///   severity_weights:
///     info: 0.7
///     warn: 0.2
///     error: 0.1
///   seed: 42
/// ```
///
/// # Example YAML — replay generator
///
/// ```yaml
/// generator:
///   type: replay
///   file: /var/log/app.log
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Deserialize))]
#[cfg_attr(feature = "config", serde(tag = "type"))]
pub enum LogGeneratorConfig {
    /// Generates events from message templates with randomized field pool values.
    #[cfg_attr(feature = "config", serde(rename = "template"))]
    Template {
        /// One or more template entries. Templates are selected round-robin by tick.
        templates: Vec<TemplateConfig>,
        /// Optional severity weight map. Keys are severity names (`info`, `warn`, etc.),
        /// values are relative weights. Defaults to `info: 1.0` when absent.
        #[cfg_attr(feature = "config", serde(default))]
        severity_weights: Option<HashMap<String, f64>>,
        /// Seed for deterministic replay. Defaults to `0` when absent.
        seed: Option<u64>,
    },
    /// Replays lines from a file, cycling back to the start when exhausted.
    #[cfg_attr(feature = "config", serde(rename = "replay"))]
    Replay {
        /// Path to the file containing log lines to replay.
        file: String,
    },
}

/// Parse a severity name string into a [`Severity`] variant.
fn parse_severity(s: &str) -> Result<Severity, SondaError> {
    match s.to_lowercase().as_str() {
        "trace" => Ok(Severity::Trace),
        "debug" => Ok(Severity::Debug),
        "info" => Ok(Severity::Info),
        "warn" | "warning" => Ok(Severity::Warn),
        "error" => Ok(Severity::Error),
        "fatal" => Ok(Severity::Fatal),
        other => Err(SondaError::Config(ConfigError::invalid(format!(
            "unknown severity {:?}: must be one of trace, debug, info, warn, error, fatal",
            other
        )))),
    }
}

/// Construct a `Box<dyn LogGenerator>` from the given configuration.
///
/// # Errors
/// - Returns [`SondaError::Config`] if severity weight keys are invalid.
/// - Returns [`SondaError::Config`] if the replay file is empty or cannot be parsed.
/// - Returns [`SondaError::Generator`] if the replay file cannot be read.
pub fn create_log_generator(
    config: &LogGeneratorConfig,
) -> Result<Box<dyn LogGenerator>, SondaError> {
    match config {
        LogGeneratorConfig::Template {
            templates,
            severity_weights,
            seed,
        } => {
            let seed = seed.unwrap_or(0);

            // Build severity weight vector from the optional map.
            let weights: Vec<(Severity, f64)> = if let Some(map) = severity_weights {
                let mut pairs = Vec::with_capacity(map.len());
                for (name, weight) in map {
                    let severity = parse_severity(name)?;
                    pairs.push((severity, *weight));
                }
                // Sort by severity ordinal for deterministic ordering.
                pairs.sort_by(|a, b| a.0.cmp(&b.0));
                pairs
            } else {
                vec![]
            };

            // Convert TemplateConfig into TemplateEntry.
            let entries: Vec<TemplateEntry> = templates
                .iter()
                .map(|tc| TemplateEntry {
                    message: tc.message.clone(),
                    field_pools: tc.field_pools.clone(),
                })
                .collect();

            Ok(Box::new(LogTemplateGenerator::new(entries, weights, seed)))
        }
        LogGeneratorConfig::Replay { file } => {
            let path = std::path::Path::new(file);
            Ok(Box::new(LogReplayGenerator::from_file(path)?))
        }
    }
}

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

    // ---- Factory tests -------------------------------------------------------

    #[test]
    fn factory_constant_returns_configured_value() {
        let config = GeneratorConfig::Constant { value: 1.0 };
        let gen = create_generator(&config, 100.0).expect("constant factory");
        assert_eq!(gen.value(0), 1.0);
        assert_eq!(gen.value(1_000_000), 1.0);
    }

    #[test]
    fn factory_uniform_returns_values_in_range() {
        let config = GeneratorConfig::Uniform {
            min: 0.0,
            max: 1.0,
            seed: Some(7),
        };
        let gen = create_generator(&config, 100.0).expect("uniform factory");
        for tick in 0..1000 {
            let v = gen.value(tick);
            assert!(
                v >= 0.0 && v <= 1.0,
                "uniform value {v} out of [0,1] at tick {tick}"
            );
        }
    }

    #[test]
    fn factory_uniform_seed_none_defaults_to_zero_seed() {
        // When seed is None the factory must behave the same as seed Some(0).
        let config_none = GeneratorConfig::Uniform {
            min: 0.0,
            max: 1.0,
            seed: None,
        };
        let config_zero = GeneratorConfig::Uniform {
            min: 0.0,
            max: 1.0,
            seed: Some(0),
        };
        let gen_none = create_generator(&config_none, 1.0).expect("uniform none factory");
        let gen_zero = create_generator(&config_zero, 1.0).expect("uniform zero factory");
        for tick in 0..100 {
            assert_eq!(
                gen_none.value(tick),
                gen_zero.value(tick),
                "seed=None must equal seed=Some(0) at tick {tick}"
            );
        }
    }

    #[test]
    fn factory_sine_value_at_zero_equals_offset() {
        let config = GeneratorConfig::Sine {
            amplitude: 5.0,
            period_secs: 10.0,
            offset: 3.0,
        };
        let gen = create_generator(&config, 1.0).expect("sine factory");
        assert!(
            (gen.value(0) - 3.0).abs() < 1e-10,
            "sine factory: value(0) must equal offset"
        );
    }

    #[test]
    fn factory_sawtooth_value_at_zero_equals_min() {
        let config = GeneratorConfig::Sawtooth {
            min: 5.0,
            max: 15.0,
            period_secs: 10.0,
        };
        let gen = create_generator(&config, 1.0).expect("sawtooth factory");
        assert_eq!(
            gen.value(0),
            5.0,
            "sawtooth factory: value(0) must equal min"
        );
    }

    // ---- Sequence factory tests -----------------------------------------------

    #[test]
    fn factory_sequence_repeat_true_creates_working_generator() {
        let config = GeneratorConfig::Sequence {
            values: vec![1.0, 2.0, 3.0],
            repeat: Some(true),
        };
        let gen = create_generator(&config, 1.0).expect("sequence factory repeat=true");
        assert_eq!(gen.value(0), 1.0);
        assert_eq!(gen.value(1), 2.0);
        assert_eq!(gen.value(2), 3.0);
        assert_eq!(gen.value(3), 1.0, "should wrap around");
    }

    #[test]
    fn factory_sequence_repeat_false_creates_working_generator() {
        let config = GeneratorConfig::Sequence {
            values: vec![1.0, 2.0, 3.0],
            repeat: Some(false),
        };
        let gen = create_generator(&config, 1.0).expect("sequence factory repeat=false");
        assert_eq!(gen.value(0), 1.0);
        assert_eq!(gen.value(4), 3.0, "should clamp to last value");
    }

    #[test]
    fn factory_sequence_repeat_none_defaults_to_true() {
        let config = GeneratorConfig::Sequence {
            values: vec![1.0, 2.0],
            repeat: None,
        };
        let gen = create_generator(&config, 1.0).expect("sequence factory repeat=None");
        // With repeat defaulting to true, tick=2 on a 2-element seq should wrap to index 0
        assert_eq!(
            gen.value(2),
            1.0,
            "repeat=None should default to true (cycling)"
        );
    }

    #[test]
    fn factory_sequence_empty_values_returns_error() {
        let config = GeneratorConfig::Sequence {
            values: vec![],
            repeat: Some(true),
        };
        let result = create_generator(&config, 1.0);
        assert!(result.is_err(), "empty sequence must return an error");
    }

    // ---- Step factory tests ---------------------------------------------------

    #[test]
    fn factory_step_linear_growth() {
        let config = GeneratorConfig::Step {
            start: None,
            step_size: 1.0,
            max: None,
        };
        let gen = create_generator(&config, 1.0).expect("step factory");
        assert_eq!(gen.value(0), 0.0);
        assert_eq!(gen.value(1), 1.0);
        assert_eq!(gen.value(100), 100.0);
    }

    #[test]
    fn factory_step_with_start() {
        let config = GeneratorConfig::Step {
            start: Some(10.0),
            step_size: 2.0,
            max: None,
        };
        let gen = create_generator(&config, 1.0).expect("step factory with start");
        assert_eq!(gen.value(0), 10.0);
        assert_eq!(gen.value(1), 12.0);
        assert_eq!(gen.value(5), 20.0);
    }

    #[test]
    fn factory_step_with_wrap() {
        let config = GeneratorConfig::Step {
            start: Some(0.0),
            step_size: 1.0,
            max: Some(3.0),
        };
        let gen = create_generator(&config, 1.0).expect("step factory with wrap");
        assert_eq!(gen.value(0), 0.0);
        assert_eq!(gen.value(3), 0.0, "should wrap at max");
        assert_eq!(gen.value(4), 1.0);
    }

    #[test]
    fn factory_step_start_none_defaults_to_zero() {
        let config_none = GeneratorConfig::Step {
            start: None,
            step_size: 1.0,
            max: None,
        };
        let config_zero = GeneratorConfig::Step {
            start: Some(0.0),
            step_size: 1.0,
            max: None,
        };
        let gen_none = create_generator(&config_none, 1.0).expect("step start=None");
        let gen_zero = create_generator(&config_zero, 1.0).expect("step start=0");
        for tick in 0..10 {
            assert_eq!(
                gen_none.value(tick),
                gen_zero.value(tick),
                "start=None must equal start=Some(0.0) at tick {tick}"
            );
        }
    }

    // ---- Config deserialization tests ----------------------------------------
    // These tests require the `config` feature (serde_yaml_ng).

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_constant_config() {
        let yaml = "type: constant\nvalue: 42.0\n";
        let config: GeneratorConfig = serde_yaml_ng::from_str(yaml).expect("deserialize constant");
        match config {
            GeneratorConfig::Constant { value } => {
                assert_eq!(value, 42.0);
            }
            _ => panic!("expected Constant variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_uniform_config_with_seed() {
        let yaml = "type: uniform\nmin: 1.0\nmax: 5.0\nseed: 99\n";
        let config: GeneratorConfig = serde_yaml_ng::from_str(yaml).expect("deserialize uniform");
        match config {
            GeneratorConfig::Uniform { min, max, seed } => {
                assert_eq!(min, 1.0);
                assert_eq!(max, 5.0);
                assert_eq!(seed, Some(99));
            }
            _ => panic!("expected Uniform variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_uniform_config_without_seed() {
        let yaml = "type: uniform\nmin: 0.0\nmax: 10.0\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize uniform no seed");
        match config {
            GeneratorConfig::Uniform { min, max, seed } => {
                assert_eq!(min, 0.0);
                assert_eq!(max, 10.0);
                assert_eq!(seed, None);
            }
            _ => panic!("expected Uniform variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sine_config() {
        let yaml = "type: sine\namplitude: 5.0\nperiod_secs: 30\noffset: 10.0\n";
        let config: GeneratorConfig = serde_yaml_ng::from_str(yaml).expect("deserialize sine");
        match config {
            GeneratorConfig::Sine {
                amplitude,
                period_secs,
                offset,
            } => {
                assert_eq!(amplitude, 5.0);
                assert_eq!(period_secs, 30.0);
                assert_eq!(offset, 10.0);
            }
            _ => panic!("expected Sine variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sawtooth_config() {
        let yaml = "type: sawtooth\nmin: 0.0\nmax: 100.0\nperiod_secs: 60.0\n";
        let config: GeneratorConfig = serde_yaml_ng::from_str(yaml).expect("deserialize sawtooth");
        match config {
            GeneratorConfig::Sawtooth {
                min,
                max,
                period_secs,
            } => {
                assert_eq!(min, 0.0);
                assert_eq!(max, 100.0);
                assert_eq!(period_secs, 60.0);
            }
            _ => panic!("expected Sawtooth variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_step_config_full() {
        let yaml = "type: step\nstart: 10.0\nstep_size: 2.5\nmax: 100.0\n";
        let config: GeneratorConfig = serde_yaml_ng::from_str(yaml).expect("deserialize step");
        match config {
            GeneratorConfig::Step {
                start,
                step_size,
                max,
            } => {
                assert_eq!(start, Some(10.0));
                assert_eq!(step_size, 2.5);
                assert_eq!(max, Some(100.0));
            }
            _ => panic!("expected Step variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_step_config_minimal() {
        let yaml = "type: step\nstep_size: 1.0\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize step minimal");
        match config {
            GeneratorConfig::Step {
                start,
                step_size,
                max,
            } => {
                assert_eq!(start, None, "start should default to None when omitted");
                assert_eq!(step_size, 1.0);
                assert_eq!(max, None, "max should be None when omitted");
            }
            _ => panic!("expected Step variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_step_config_integer_values() {
        // YAML integers should coerce to f64
        let yaml = "type: step\nstart: 0\nstep_size: 1\nmax: 1000\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize step with integers");
        match config {
            GeneratorConfig::Step {
                start,
                step_size,
                max,
            } => {
                assert_eq!(start, Some(0.0));
                assert_eq!(step_size, 1.0);
                assert_eq!(max, Some(1000.0));
            }
            _ => panic!("expected Step variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sequence_config_with_repeat() {
        let yaml = "type: sequence\nvalues: [1.0, 2.0, 3.0]\nrepeat: true\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize sequence with repeat");
        match config {
            GeneratorConfig::Sequence { values, repeat } => {
                assert_eq!(values, vec![1.0, 2.0, 3.0]);
                assert_eq!(repeat, Some(true));
            }
            _ => panic!("expected Sequence variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sequence_config_without_repeat() {
        let yaml = "type: sequence\nvalues: [10.0, 20.0]\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize sequence without repeat");
        match config {
            GeneratorConfig::Sequence { values, repeat } => {
                assert_eq!(values, vec![10.0, 20.0]);
                assert_eq!(repeat, None, "repeat should be None when omitted");
            }
            _ => panic!("expected Sequence variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sequence_config_repeat_false() {
        let yaml = "type: sequence\nvalues: [5.0]\nrepeat: false\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize sequence repeat=false");
        match config {
            GeneratorConfig::Sequence { values, repeat } => {
                assert_eq!(values, vec![5.0]);
                assert_eq!(repeat, Some(false));
            }
            _ => panic!("expected Sequence variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_sequence_config_integer_values() {
        // YAML integers should coerce to f64
        let yaml = "type: sequence\nvalues: [10, 20, 30]\nrepeat: true\n";
        let config: GeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize sequence with integer values");
        match config {
            GeneratorConfig::Sequence { values, repeat } => {
                assert_eq!(values, vec![10.0, 20.0, 30.0]);
                assert_eq!(repeat, Some(true));
            }
            _ => panic!("expected Sequence variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_example_yaml_scenario_file() {
        // Validate the example file from examples/sequence-alert-test.yaml
        let yaml = "\
name: cpu_spike_test
rate: 1
duration: 80s

generator:
  type: sequence
  values: [10, 10, 10, 10, 10, 95, 95, 95, 95, 95, 10, 10, 10, 10, 10, 10]
  repeat: true

labels:
  instance: server-01
  job: node

encoder:
  type: prometheus_text
sink:
  type: stdout
";
        let config: crate::config::ScenarioConfig =
            serde_yaml_ng::from_str(yaml).expect("example YAML must deserialize");
        assert_eq!(config.name, "cpu_spike_test");
        assert_eq!(config.rate, 1.0);
        assert_eq!(config.duration, Some("80s".to_string()));
        match &config.generator {
            GeneratorConfig::Sequence { values, repeat } => {
                assert_eq!(values.len(), 16);
                assert_eq!(values[0], 10.0);
                assert_eq!(values[5], 95.0);
                assert_eq!(values[10], 10.0);
                assert_eq!(*repeat, Some(true));
            }
            _ => panic!("expected Sequence generator variant in example YAML"),
        }
    }

    // ---- Send + Sync contract tests ------------------------------------------

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn generators_are_send_and_sync() {
        // These are compile-time checks — if the types don't implement Send+Sync the
        // test binary will not compile.
        assert_send_sync::<crate::generator::uniform::UniformRandom>();
        assert_send_sync::<crate::generator::sine::Sine>();
        assert_send_sync::<crate::generator::sawtooth::Sawtooth>();
        assert_send_sync::<crate::generator::constant::Constant>();
        assert_send_sync::<crate::generator::sequence::SequenceGenerator>();
        assert_send_sync::<crate::generator::csv_replay::CsvReplayGenerator>();
        assert_send_sync::<crate::generator::step::StepGenerator>();
    }

    // ---- LogGeneratorConfig deserialization tests ----------------------------
    // These tests require the `config` feature (serde_yaml_ng).

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_log_template_config_minimal() {
        let yaml = "\
type: template
templates:
  - message: \"hello {name}\"
    field_pools:
      name:
        - alice
        - bob
";
        let config: LogGeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize template config");
        match config {
            LogGeneratorConfig::Template {
                templates,
                severity_weights,
                seed,
            } => {
                assert_eq!(templates.len(), 1);
                assert_eq!(templates[0].message, "hello {name}");
                assert!(templates[0].field_pools.contains_key("name"));
                assert_eq!(
                    templates[0].field_pools["name"],
                    vec!["alice".to_string(), "bob".to_string()]
                );
                assert!(
                    severity_weights.is_none(),
                    "severity_weights must default to None"
                );
                assert!(seed.is_none(), "seed must default to None");
            }
            _ => panic!("expected Template variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_log_template_config_with_weights_and_seed() {
        let yaml = "\
type: template
templates:
  - message: \"msg\"
    field_pools: {}
severity_weights:
  info: 0.7
  warn: 0.2
  error: 0.1
seed: 42
";
        let config: LogGeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize template config with weights");
        match config {
            LogGeneratorConfig::Template {
                severity_weights,
                seed,
                ..
            } => {
                let weights = severity_weights.expect("severity_weights should be present");
                assert!((weights["info"] - 0.7).abs() < 1e-10);
                assert!((weights["warn"] - 0.2).abs() < 1e-10);
                assert!((weights["error"] - 0.1).abs() < 1e-10);
                assert_eq!(seed, Some(42));
            }
            _ => panic!("expected Template variant"),
        }
    }

    #[cfg(feature = "config")]
    #[test]
    fn deserialize_log_replay_config() {
        let yaml = "type: replay\nfile: /var/log/app.log\n";
        let config: LogGeneratorConfig =
            serde_yaml_ng::from_str(yaml).expect("deserialize replay config");
        match config {
            LogGeneratorConfig::Replay { file } => {
                assert_eq!(file, "/var/log/app.log");
            }
            _ => panic!("expected Replay variant"),
        }
    }

    // ---- create_log_generator factory tests ----------------------------------

    #[test]
    fn factory_template_config_creates_working_generator() {
        let config = LogGeneratorConfig::Template {
            templates: vec![TemplateConfig {
                message: "event {id}".into(),
                field_pools: {
                    let mut m = BTreeMap::new();
                    m.insert("id".into(), vec!["1".into(), "2".into(), "3".into()]);
                    m
                },
            }],
            severity_weights: None,
            seed: Some(0),
        };
        let gen = create_log_generator(&config).expect("template factory must succeed");
        let event = gen.generate(0);
        // Must not contain unresolved placeholder.
        assert!(!event.message.contains('{'));
    }

    #[test]
    fn factory_template_config_seed_none_defaults_correctly() {
        // seed: None should not error and should produce a generator.
        let config = LogGeneratorConfig::Template {
            templates: vec![TemplateConfig {
                message: "static message".into(),
                field_pools: BTreeMap::new(),
            }],
            severity_weights: None,
            seed: None,
        };
        let gen = create_log_generator(&config).expect("template with seed=None must succeed");
        assert_eq!(gen.generate(0).message, "static message");
    }

    #[test]
    fn factory_template_invalid_severity_key_returns_error() {
        let config = LogGeneratorConfig::Template {
            templates: vec![TemplateConfig {
                message: "msg".into(),
                field_pools: BTreeMap::new(),
            }],
            severity_weights: {
                let mut m = HashMap::new();
                m.insert("bogus".into(), 1.0);
                Some(m)
            },
            seed: None,
        };
        let result = create_log_generator(&config);
        assert!(
            result.is_err(),
            "invalid severity key 'bogus' must produce Err"
        );
    }

    #[test]
    fn factory_replay_config_missing_file_returns_error() {
        let config = LogGeneratorConfig::Replay {
            file: "/this/path/does/not/exist.log".into(),
        };
        let result = create_log_generator(&config);
        assert!(result.is_err(), "missing replay file must produce Err");
    }

    #[test]
    fn factory_replay_config_creates_working_generator() {
        use std::io::Write;
        use tempfile::NamedTempFile;
        let mut tmp = NamedTempFile::new().expect("create temp file");
        writeln!(tmp, "line one").expect("write");
        writeln!(tmp, "line two").expect("write");
        let config = LogGeneratorConfig::Replay {
            file: tmp.path().to_string_lossy().into_owned(),
        };
        let gen =
            create_log_generator(&config).expect("replay factory with real file must succeed");
        assert_eq!(gen.generate(0).message, "line one");
        assert_eq!(gen.generate(1).message, "line two");
        assert_eq!(gen.generate(2).message, "line one");
    }

    #[test]
    fn log_generators_are_send_and_sync() {
        assert_send_sync::<crate::generator::log_template::LogTemplateGenerator>();
        assert_send_sync::<crate::generator::log_replay::LogReplayGenerator>();
    }
}