perf-sentinel-core 0.2.2

Core library for perf-sentinel: polyglot performance anti-pattern detector
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
//! Configuration parsing for `.perf-sentinel.toml`.
//!
//! Supports both the new sectioned format (`[thresholds]`, `[detection]`, `[green]`, `[daemon]`)
//! and the legacy flat format for backward compatibility.

use serde::Deserialize;

/// Top-level configuration for perf-sentinel.
#[derive(Debug, Clone)]
pub struct Config {
    // --- Thresholds ---
    /// Maximum allowed critical N+1 SQL findings before quality gate fails.
    pub n_plus_one_sql_critical_max: u32,
    /// Maximum allowed warning+ N+1 HTTP findings before quality gate fails.
    pub n_plus_one_http_warning_max: u32,
    /// Maximum allowed I/O waste ratio before quality gate fails.
    pub io_waste_ratio_max: f64,

    // --- Detection ---
    /// N+1 detection threshold: minimum repeated similar queries to flag.
    pub n_plus_one_threshold: u32,
    /// Sliding window duration in milliseconds for N+1 detection.
    pub window_duration_ms: u64,
    /// Threshold in milliseconds above which an operation is considered slow.
    pub slow_query_threshold_ms: u64,
    /// Minimum occurrences of a slow template to flag as a finding.
    pub slow_query_min_occurrences: u32,
    /// Maximum child spans per parent before flagging excessive fanout.
    pub max_fanout: u32,

    // --- Green ---
    /// Whether `GreenOps` scoring is enabled.
    pub green_enabled: bool,
    /// Optional region for gCO₂eq conversion (e.g. "eu-west-3", "FR", "us-east-1").
    pub green_region: Option<String>,

    // --- Daemon ---
    /// Address for the daemon to listen on.
    pub listen_addr: String,
    /// Port for OTLP HTTP receiver.
    pub listen_port: u16,
    /// Port for OTLP gRPC receiver.
    pub listen_port_grpc: u16,
    /// Unix socket path for JSON ingestion.
    pub json_socket: String,
    /// Maximum number of active traces in streaming mode.
    pub max_active_traces: usize,
    /// Trace TTL in milliseconds for streaming mode eviction.
    pub trace_ttl_ms: u64,
    /// Sampling rate for incoming traces (0.0 - 1.0).
    pub sampling_rate: f64,
    /// Maximum events kept per trace (ring buffer size).
    pub max_events_per_trace: usize,
    /// Maximum payload size in bytes for JSON deserialization.
    pub max_payload_size: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            // Thresholds
            n_plus_one_sql_critical_max: 0,
            n_plus_one_http_warning_max: 3,
            io_waste_ratio_max: 0.30,
            // Detection
            n_plus_one_threshold: 5,
            window_duration_ms: 500,
            slow_query_threshold_ms: 500,
            slow_query_min_occurrences: 3,
            max_fanout: 20,
            // Green
            green_enabled: true,
            green_region: None,
            // Daemon
            listen_addr: "127.0.0.1".to_string(),
            listen_port: 4318,
            listen_port_grpc: 4317,
            json_socket: "/tmp/perf-sentinel.sock".to_string(),
            max_active_traces: 10_000,
            trace_ttl_ms: 30_000,
            sampling_rate: 1.0,
            max_events_per_trace: 1_000,
            max_payload_size: 1_048_576, // 1 MB
        }
    }
}

// --- Internal raw deserialization types ---

#[derive(Deserialize, Default)]
#[serde(default)]
struct RawConfig {
    // Sections (new format)
    thresholds: ThresholdsSection,
    detection: DetectionSection,
    green: GreenSection,
    daemon: DaemonSection,

    // Legacy flat fields (backward compatibility)
    max_payload_size: Option<usize>,
    n_plus_one_threshold: Option<u32>,
    listen_addr: Option<String>,
    listen_port: Option<u16>,
    window_duration_ms: Option<u64>,
    trace_ttl_ms: Option<u64>,
    max_active_traces: Option<usize>,
    max_events_per_trace: Option<usize>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
#[allow(clippy::struct_field_names)] // fields like `n_plus_one_sql_critical_max` repeat the struct context but match the TOML keys
struct ThresholdsSection {
    n_plus_one_sql_critical_max: Option<u32>,
    n_plus_one_http_warning_max: Option<u32>,
    io_waste_ratio_max: Option<f64>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct DetectionSection {
    window_duration_ms: Option<u64>,
    n_plus_one_min_occurrences: Option<u32>,
    slow_query_threshold_ms: Option<u64>,
    slow_query_min_occurrences: Option<u32>,
    max_fanout: Option<u32>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct GreenSection {
    enabled: Option<bool>,
    region: Option<String>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct DaemonSection {
    listen_address: Option<String>,
    listen_port_http: Option<u16>,
    listen_port_grpc: Option<u16>,
    json_socket: Option<String>,
    max_active_traces: Option<usize>,
    trace_ttl_ms: Option<u64>,
    sampling_rate: Option<f64>,
    max_events_per_trace: Option<usize>,
    max_payload_size: Option<usize>,
}

impl From<RawConfig> for Config {
    fn from(raw: RawConfig) -> Self {
        let defaults = Self::default();

        // Sections take priority over flat fields, flat fields over defaults.
        Self {
            // Thresholds
            n_plus_one_sql_critical_max: raw
                .thresholds
                .n_plus_one_sql_critical_max
                .unwrap_or(defaults.n_plus_one_sql_critical_max),
            n_plus_one_http_warning_max: raw
                .thresholds
                .n_plus_one_http_warning_max
                .unwrap_or(defaults.n_plus_one_http_warning_max),
            io_waste_ratio_max: raw
                .thresholds
                .io_waste_ratio_max
                .unwrap_or(defaults.io_waste_ratio_max),

            // Detection: section > flat > default
            n_plus_one_threshold: raw
                .detection
                .n_plus_one_min_occurrences
                .or(raw.n_plus_one_threshold)
                .unwrap_or(defaults.n_plus_one_threshold),
            window_duration_ms: raw
                .detection
                .window_duration_ms
                .or(raw.window_duration_ms)
                .unwrap_or(defaults.window_duration_ms),
            slow_query_threshold_ms: raw
                .detection
                .slow_query_threshold_ms
                .unwrap_or(defaults.slow_query_threshold_ms),
            slow_query_min_occurrences: raw
                .detection
                .slow_query_min_occurrences
                .unwrap_or(defaults.slow_query_min_occurrences),
            max_fanout: raw.detection.max_fanout.unwrap_or(defaults.max_fanout),

            // Green
            green_enabled: raw.green.enabled.unwrap_or(defaults.green_enabled),
            green_region: raw.green.region.or(defaults.green_region),

            // Daemon: section > flat > default
            listen_addr: raw
                .daemon
                .listen_address
                .or(raw.listen_addr)
                .unwrap_or(defaults.listen_addr),
            listen_port: raw
                .daemon
                .listen_port_http
                .or(raw.listen_port)
                .unwrap_or(defaults.listen_port),
            listen_port_grpc: raw
                .daemon
                .listen_port_grpc
                .unwrap_or(defaults.listen_port_grpc),
            json_socket: raw.daemon.json_socket.unwrap_or(defaults.json_socket),
            max_active_traces: raw
                .daemon
                .max_active_traces
                .or(raw.max_active_traces)
                .unwrap_or(defaults.max_active_traces),
            trace_ttl_ms: raw
                .daemon
                .trace_ttl_ms
                .or(raw.trace_ttl_ms)
                .unwrap_or(defaults.trace_ttl_ms),
            sampling_rate: raw.daemon.sampling_rate.unwrap_or(defaults.sampling_rate),
            max_events_per_trace: raw
                .daemon
                .max_events_per_trace
                .or(raw.max_events_per_trace)
                .unwrap_or(defaults.max_events_per_trace),
            max_payload_size: raw
                .daemon
                .max_payload_size
                .or(raw.max_payload_size)
                .unwrap_or(defaults.max_payload_size),
        }
    }
}

fn check_range<T: PartialOrd + std::fmt::Display>(
    name: &str,
    val: &T,
    min: &T,
    max: &T,
) -> Result<(), String> {
    if val < min {
        return Err(format!("{name} must be >= {min}, got {val}"));
    }
    if val > max {
        return Err(format!("{name} must be <= {max}, got {val}"));
    }
    Ok(())
}

fn check_min<T: PartialOrd + std::fmt::Display>(
    name: &str,
    val: &T,
    min: &T,
) -> Result<(), String> {
    if val < min {
        return Err(format!("{name} must be >= {min}, got {val}"));
    }
    Ok(())
}

impl Config {
    /// Validate that config values are within acceptable bounds.
    ///
    /// # Errors
    ///
    /// Returns a `String` description of the first invalid value found.
    /// The caller (`load_from_str`) wraps this in `ConfigError::Validation`.
    pub fn validate(&self) -> Result<(), String> {
        self.validate_daemon_limits()?;
        self.validate_detection_params()?;
        self.validate_rates()?;
        self.validate_listen_addr()?;
        Ok(())
    }

    fn validate_daemon_limits(&self) -> Result<(), String> {
        check_range(
            "max_payload_size",
            &self.max_payload_size,
            &1024,
            &(100 * 1024 * 1024),
        )?;
        check_range("max_active_traces", &self.max_active_traces, &1, &1_000_000)?;
        check_range(
            "max_events_per_trace",
            &self.max_events_per_trace,
            &1,
            &100_000,
        )?;
        check_range("trace_ttl_ms", &self.trace_ttl_ms, &100, &3_600_000)?;
        check_range("listen_port_http", &self.listen_port, &1, &65535)?;
        check_range("listen_port_grpc", &self.listen_port_grpc, &1, &65535)?;
        Ok(())
    }

    fn validate_detection_params(&self) -> Result<(), String> {
        check_min("n_plus_one_threshold", &self.n_plus_one_threshold, &1)?;
        check_min("window_duration_ms", &self.window_duration_ms, &1)?;
        check_min("slow_query_threshold_ms", &self.slow_query_threshold_ms, &1)?;
        check_min(
            "slow_query_min_occurrences",
            &self.slow_query_min_occurrences,
            &1,
        )?;
        check_range("max_fanout", &self.max_fanout, &1, &100_000)?;
        Ok(())
    }

    fn validate_rates(&self) -> Result<(), String> {
        if !(0.0..=1.0).contains(&self.sampling_rate) {
            return Err(format!(
                "sampling_rate must be in [0.0, 1.0], got {}",
                self.sampling_rate
            ));
        }
        if !(0.0..=1.0).contains(&self.io_waste_ratio_max) {
            return Err(format!(
                "io_waste_ratio_max must be in [0.0, 1.0], got {}",
                self.io_waste_ratio_max
            ));
        }
        Ok(())
    }

    #[allow(clippy::unnecessary_wraps)]
    fn validate_listen_addr(&self) -> Result<(), String> {
        if self.listen_addr != "127.0.0.1" && self.listen_addr != "::1" {
            tracing::warn!(
                "Daemon configured to listen on non-loopback address: {}. \
                 Endpoints have no authentication, use a reverse proxy or \
                 network policy for security.",
                self.listen_addr
            );
        }
        Ok(())
    }
}

/// Load configuration from a TOML string.
///
/// Supports both the sectioned format and the legacy flat format.
/// Validates that all values are within acceptable bounds after parsing.
///
/// # Errors
///
/// Returns an error if the TOML content cannot be parsed or contains invalid values.
///
/// # Errors
///
/// Returns `ConfigError::Parse` if the TOML is malformed, or
/// `ConfigError::Validation` if a field value is out of bounds.
pub fn load_from_str(content: &str) -> Result<Config, ConfigError> {
    let raw: RawConfig = toml::from_str(content).map_err(ConfigError::Parse)?;
    let config = Config::from(raw);
    config.validate().map_err(ConfigError::Validation)?;
    Ok(config)
}

/// Errors that can occur during configuration loading.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// TOML parsing error.
    #[error("config parse error: {0}")]
    Parse(#[from] toml::de::Error),
    /// Validation error (out-of-range values).
    #[error("config validation error: {0}")]
    Validation(String),
}

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

    #[test]
    fn default_config_has_safe_defaults() {
        let config = Config::default();
        assert_eq!(config.max_payload_size, 1_048_576);
        assert_eq!(config.listen_addr, "127.0.0.1");
        assert_eq!(config.n_plus_one_threshold, 5);
        assert_eq!(config.window_duration_ms, 500);
        assert_eq!(config.trace_ttl_ms, 30_000);
        assert_eq!(config.max_active_traces, 10_000);
        assert_eq!(config.max_events_per_trace, 1_000);
    }

    #[test]
    fn parse_empty_toml_gives_defaults() {
        let config = load_from_str("").unwrap();
        assert_eq!(config.max_payload_size, 1_048_576);
    }

    #[test]
    fn parse_partial_toml() {
        let config = load_from_str("n_plus_one_threshold = 10").unwrap();
        assert_eq!(config.n_plus_one_threshold, 10);
        assert_eq!(config.max_payload_size, 1_048_576); // default preserved
    }

    #[test]
    fn parse_window_config() {
        let config = load_from_str(
            "window_duration_ms = 1000\ntrace_ttl_ms = 60000\nmax_active_traces = 5000",
        )
        .unwrap();
        assert_eq!(config.window_duration_ms, 1000);
        assert_eq!(config.trace_ttl_ms, 60_000);
        assert_eq!(config.max_active_traces, 5000);
    }

    #[test]
    fn parse_sectioned_format() {
        let toml = r#"
[thresholds]
n_plus_one_sql_critical_max = 2
n_plus_one_http_warning_max = 5
io_waste_ratio_max = 0.50

[detection]
window_duration_ms = 1000
n_plus_one_min_occurrences = 10

[green]
enabled = false

[daemon]
listen_address = "0.0.0.0"
listen_port_http = 9418
listen_port_grpc = 9417
json_socket = "/var/run/perf-sentinel.sock"
max_active_traces = 20000
trace_ttl_ms = 60000
sampling_rate = 0.5
max_events_per_trace = 500
max_payload_size = 2097152
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.n_plus_one_sql_critical_max, 2);
        assert_eq!(config.n_plus_one_http_warning_max, 5);
        assert!((config.io_waste_ratio_max - 0.50).abs() < f64::EPSILON);
        assert_eq!(config.n_plus_one_threshold, 10);
        assert_eq!(config.window_duration_ms, 1000);
        assert!(!config.green_enabled);
        assert_eq!(config.listen_addr, "0.0.0.0");
        assert_eq!(config.listen_port, 9418);
        assert_eq!(config.listen_port_grpc, 9417);
        assert_eq!(config.json_socket, "/var/run/perf-sentinel.sock");
        assert_eq!(config.max_active_traces, 20_000);
        assert_eq!(config.trace_ttl_ms, 60_000);
        assert!((config.sampling_rate - 0.5).abs() < f64::EPSILON);
        assert_eq!(config.max_events_per_trace, 500);
        assert_eq!(config.max_payload_size, 2_097_152);
    }

    #[test]
    fn section_overrides_flat_field() {
        let toml = r"
n_plus_one_threshold = 7
window_duration_ms = 800

[detection]
n_plus_one_min_occurrences = 12
";
        let config = load_from_str(toml).unwrap();
        // Section takes priority over flat field
        assert_eq!(config.n_plus_one_threshold, 12);
        // Flat field used when section does not override
        assert_eq!(config.window_duration_ms, 800);
    }

    #[test]
    fn new_fields_have_correct_defaults() {
        let config = Config::default();
        assert_eq!(config.n_plus_one_sql_critical_max, 0);
        assert_eq!(config.n_plus_one_http_warning_max, 3);
        assert!((config.io_waste_ratio_max - 0.30).abs() < f64::EPSILON);
        assert!(config.green_enabled);
        assert_eq!(config.listen_port_grpc, 4317);
        assert_eq!(config.json_socket, "/tmp/perf-sentinel.sock");
        assert!((config.sampling_rate - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn default_config_validates() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn rejects_sampling_rate_above_one() {
        let result = load_from_str("[daemon]\nsampling_rate = 5.0");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("sampling_rate"), "got: {err}");
    }

    #[test]
    fn rejects_negative_sampling_rate() {
        let result = load_from_str("[daemon]\nsampling_rate = -0.1");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_io_waste_ratio_max_above_one() {
        let result = load_from_str("[thresholds]\nio_waste_ratio_max = 1.5");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("io_waste_ratio_max"), "got: {err}");
    }

    #[test]
    fn rejects_zero_max_payload_size() {
        let result = load_from_str("[daemon]\nmax_payload_size = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_n_plus_one_threshold() {
        let result = load_from_str("n_plus_one_threshold = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_active_traces() {
        let result = load_from_str("max_active_traces = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_events_per_trace() {
        let result = load_from_str("max_events_per_trace = 0");
        assert!(result.is_err());
    }

    #[test]
    fn slow_query_defaults() {
        let config = Config::default();
        assert_eq!(config.slow_query_threshold_ms, 500);
        assert_eq!(config.slow_query_min_occurrences, 3);
        assert!(config.green_region.is_none());
    }

    #[test]
    fn parse_slow_query_config() {
        let toml = r"
[detection]
slow_query_threshold_ms = 1000
slow_query_min_occurrences = 5
";
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.slow_query_threshold_ms, 1000);
        assert_eq!(config.slow_query_min_occurrences, 5);
    }

    #[test]
    fn parse_green_region() {
        let toml = r#"
[green]
enabled = true
region = "eu-west-3"
"#;
        let config = load_from_str(toml).unwrap();
        assert_eq!(config.green_region.as_deref(), Some("eu-west-3"));
    }

    #[test]
    fn rejects_zero_slow_query_threshold() {
        let result = load_from_str("[detection]\nslow_query_threshold_ms = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_slow_query_min_occurrences() {
        let result = load_from_str("[detection]\nslow_query_min_occurrences = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_max_fanout() {
        let result = load_from_str("[detection]\nmax_fanout = 0");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_max_fanout_over_100k() {
        let result = load_from_str("[detection]\nmax_fanout = 100001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_fanout"), "got: {err}");
    }

    #[test]
    fn accepts_max_fanout_at_100k() {
        let result = load_from_str("[detection]\nmax_fanout = 100000");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_payload_size_over_100mb() {
        let result = load_from_str("[daemon]\nmax_payload_size = 104857601");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_payload_size"), "got: {err}");
    }

    #[test]
    fn accepts_max_payload_size_at_100mb() {
        let result = load_from_str("[daemon]\nmax_payload_size = 104857600");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_active_traces_over_1m() {
        let result = load_from_str("[daemon]\nmax_active_traces = 1000001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_active_traces"), "got: {err}");
    }

    #[test]
    fn accepts_max_active_traces_at_1m() {
        let result = load_from_str("[daemon]\nmax_active_traces = 1000000");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_max_events_per_trace_over_100k() {
        let result = load_from_str("[daemon]\nmax_events_per_trace = 100001");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max_events_per_trace"), "got: {err}");
    }

    #[test]
    fn accepts_max_events_per_trace_at_100k() {
        let result = load_from_str("[daemon]\nmax_events_per_trace = 100000");
        assert!(result.is_ok());
    }

    #[test]
    fn rejects_trace_ttl_below_100() {
        let result = load_from_str("[daemon]\ntrace_ttl_ms = 50");
        assert!(result.is_err());
    }

    #[test]
    fn rejects_zero_window_duration() {
        let result = load_from_str("[detection]\nwindow_duration_ms = 0");
        assert!(result.is_err());
    }

    #[test]
    fn green_disabled_parses() {
        let config = load_from_str("[green]\nenabled = false").unwrap();
        assert!(!config.green_enabled);
    }

    // -- Port validation --

    #[test]
    fn rejects_port_zero() {
        let result = load_from_str("[daemon]\nlisten_port_http = 0");
        assert!(result.is_err());
    }

    #[test]
    fn accepts_port_one() {
        let config = load_from_str("[daemon]\nlisten_port_http = 1").unwrap();
        assert_eq!(config.listen_port, 1);
    }

    #[test]
    fn accepts_port_65535() {
        let config = load_from_str("[daemon]\nlisten_port_http = 65535").unwrap();
        assert_eq!(config.listen_port, 65535);
    }

    #[test]
    fn rejects_grpc_port_zero() {
        let result = load_from_str("[daemon]\nlisten_port_grpc = 0");
        assert!(result.is_err());
    }

    // -- trace_ttl_ms upper bound --

    #[test]
    fn rejects_trace_ttl_above_1h() {
        let result = load_from_str("[daemon]\ntrace_ttl_ms = 3600001");
        assert!(result.is_err());
    }

    #[test]
    fn accepts_trace_ttl_at_1h() {
        let config = load_from_str("[daemon]\ntrace_ttl_ms = 3600000").unwrap();
        assert_eq!(config.trace_ttl_ms, 3_600_000);
    }

    #[test]
    fn accepts_trace_ttl_at_100ms() {
        let config = load_from_str("[daemon]\ntrace_ttl_ms = 100").unwrap();
        assert_eq!(config.trace_ttl_ms, 100);
    }

    // -- Sampling rate edge cases --

    #[test]
    fn accepts_sampling_rate_zero() {
        let config = load_from_str("[daemon]\nsampling_rate = 0.0").unwrap();
        assert!((config.sampling_rate - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn accepts_sampling_rate_one() {
        let config = load_from_str("[daemon]\nsampling_rate = 1.0").unwrap();
        assert!((config.sampling_rate - 1.0).abs() < f64::EPSILON);
    }
}