perf-sentinel-core 0.11.1

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
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! Raw serde deserialization layer for `.perf-sentinel.toml`: the private
//! `*Section` structs, the `RawConfig -> Config` conversion, and the
//! per-section conversion helpers.

use std::collections::HashMap;
use std::time::Duration;

use serde::Deserialize;

use crate::score::alumet::config::DEFAULT_ENERGY_INTERVAL_SECS;
use crate::score::alumet::{AlumetBrokerConfig, AlumetConfig, AlumetDatabaseConfig};
use crate::score::cloud_energy::config::{CloudEnergyConfig, ServiceCloudConfig};
use crate::score::kepler::{KeplerConfig, KeplerMetricKind};
use crate::score::redfish::{RedfishConfig, RedfishEndpoint};
use crate::score::scaphandre::{ProcessMatcher, ScaphandreConfig};

use crate::score::carbon::DEFAULT_EMBODIED_CARBON_PER_REQUEST_GCO2;

use super::validate::has_control_char;
use super::{
    Config, DEFAULT_FULCIO_URL, DEFAULT_REKOR_URL, DaemonAckConfig, DaemonArchiveConfig,
    DaemonConfig, DaemonCorsConfig, DaemonEnvironment, DaemonTlsConfig, DetectionConfig,
    GreenConfig, ReportingConfig, SigstoreConfig, ThresholdsConfig,
};

#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct RawConfig {
    thresholds: ThresholdsSection,
    detection: DetectionSection,
    pub(super) green: GreenSection,
    pub(super) daemon: DaemonSection,
    reporting: ReportingSection,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct ReportingSection {
    intent: Option<String>,
    confidentiality_level: Option<String>,
    org_config_path: Option<String>,
    disclose_output_path: Option<String>,
    disclose_period: Option<String>,
    sigstore: SigstoreSection,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct SigstoreSection {
    rekor_url: Option<String>,
    fulcio_url: Option<String>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct ArchiveSection {
    path: Option<String>,
    max_size_mb: Option<u64>,
    max_files: Option<u32>,
}

#[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>,
    n_plus_one_messaging_warning_max: Option<u32>,
    io_waste_ratio_max: Option<f64>,
    min_usable_span_ratio: 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>,
    chatty_service_min_calls: Option<u32>,
    pool_saturation_concurrent_threshold: Option<u32>,
    serialized_min_sequential: Option<u32>,
    sanitizer_aware_classification: Option<String>,
    grouping_attributes: Option<Vec<String>>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct GreenSection {
    enabled: Option<bool>,
    default_region: Option<String>,
    service_regions: HashMap<String, String>,
    embodied_carbon_per_request_gco2: Option<f64>,
    use_hourly_profiles: Option<bool>,
    scaphandre: ScaphandreSection,
    pub(super) kepler: KeplerSection,
    pub(super) alumet: AlumetSection,
    redfish: RedfishSection,
    cloud: CloudSection,
    pub(super) broker_static: BrokerStaticSection,
    per_operation_coefficients: Option<bool>,
    include_network_transport: Option<bool>,
    network_energy_per_byte_kwh: Option<f64>,
    hourly_profiles_file: Option<String>,
    calibration_file: Option<String>,
    electricity_maps: ElectricityMapsSection,
}

/// Raw deserialization target for `[green.scaphandre]`.
///
/// Converted to a `ScaphandreConfig` during `RawConfig → Config` only
/// when `endpoint` is set: an empty table (no fields) leaves
/// `Config::green.scaphandre = None`.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct ScaphandreSection {
    pub(super) endpoint: Option<String>,
    pub(super) scrape_interval_secs: Option<u64>,
    pub(super) process_map: HashMap<String, ProcessMatcher>,
    pub(super) auth_header: Option<String>,
}

/// Raw deserialization target for `[green.kepler]`.
///
/// Converted to a `KeplerConfig` during `RawConfig → Config` only when
/// `endpoint` is set. The optional `metric_kind` string accepts
/// `"container"` (default) or `"process"`.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct KeplerSection {
    pub(super) endpoint: Option<String>,
    pub(super) scrape_interval_secs: Option<u64>,
    pub(super) metric_kind: Option<String>,
    pub(super) service_mappings: HashMap<String, String>,
    pub(super) auth_header: Option<String>,
}

/// Raw deserialization target for `[green.alumet]`.
///
/// Converted to an `AlumetConfig` during `RawConfig → Config` only when
/// `endpoint` is set. `metric_name` and `label_key` are then mandatory,
/// enforced by [`validate_alumet_raw`] before the conversion runs.
/// `deny_unknown_fields` so a typo'd key or subsection name
/// (`[green.alumet.databse]`) fails loudly instead of silently
/// disabling a feature.
#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub(super) struct AlumetSection {
    pub(super) endpoint: Option<String>,
    pub(super) scrape_interval_secs: Option<u64>,
    pub(super) metric_name: Option<String>,
    pub(super) label_key: Option<String>,
    pub(super) energy_interval_secs: Option<f64>,
    pub(super) service_mappings: HashMap<String, String>,
    pub(super) auth_header: Option<String>,
    pub(super) database: Option<AlumetDatabaseSection>,
    pub(super) broker: Option<AlumetBrokerSection>,
}

/// Raw deserialization target for `[green.alumet.broker]`.
///
/// `deny_unknown_fields` for the same reason as the database section: a
/// typo would silently disable the messaging waste figure.
#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub(super) struct AlumetBrokerSection {
    pub(super) label_value: Option<String>,
    pub(super) region: Option<String>,
}

/// Raw deserialization target for `[green.alumet.database]`.
///
/// `deny_unknown_fields` on purpose: a typo here (`label = ...`) would
/// otherwise silently disable the database waste figure.
#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub(super) struct AlumetDatabaseSection {
    pub(super) label_value: Option<String>,
    pub(super) region: Option<String>,
}

/// Raw deserialization target for `[green.redfish]`.
///
/// Converted to a `RedfishConfig` during `RawConfig → Config` only
/// when at least one `endpoints` entry is set.
#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub(super) struct RedfishSection {
    pub(super) endpoints: HashMap<String, RedfishEndpoint>,
    pub(super) scrape_interval_secs: Option<u64>,
    pub(super) service_mappings: HashMap<String, String>,
    pub(super) ca_bundle_path: Option<String>,
    pub(super) auth_header: Option<String>,
}

/// Raw deserialization target for `[green.cloud]`.
///
/// Converted to a `CloudEnergyConfig` during `RawConfig -> Config` only
/// when `prometheus_endpoint` is set.
#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct CloudSection {
    pub(super) prometheus_endpoint: Option<String>,
    pub(super) scrape_interval_secs: Option<u64>,
    pub(super) default_provider: Option<String>,
    pub(super) default_instance_type: Option<String>,
    pub(super) cpu_metric: Option<String>,
    pub(super) services: HashMap<String, CloudServiceRaw>,
    pub(super) auth_header: Option<String>,
}

/// Raw deserialization for a single entry in `[green.cloud.services]`.
///
/// Supports two forms:
/// - Instance type: `{ provider = "aws", instance_type = "m5.large" }`
/// - Manual watts: `{ idle_watts = 45, max_watts = 120 }`
#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct CloudServiceRaw {
    provider: Option<String>,
    instance_type: Option<String>,
    idle_watts: Option<f64>,
    max_watts: Option<f64>,
    cpu_query: Option<String>,
}

/// Raw deserialization target for `[green.electricity_maps]`.
///
/// Converted to an `ElectricityMapsConfig` during `RawConfig -> Config`
/// only when `api_key` is set (directly or via env var).
#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) struct ElectricityMapsSection {
    pub(super) api_key: Option<String>,
    pub(super) endpoint: Option<String>,
    pub(super) poll_interval_secs: Option<u64>,
    pub(super) region_map: HashMap<String, String>,
    pub(super) emission_factor_type: Option<String>,
    pub(super) temporal_granularity: Option<String>,
}

#[derive(Deserialize, Default)]
#[serde(default)]
pub(super) 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>,
    /// `"staging"` (default) or `"production"`. Validated
    /// in `Config::validate`; invalid values fail at load time with a
    /// clear error. Case-insensitive.
    pub(super) environment: Option<String>,
    tls_cert_path: Option<String>,
    tls_key_path: Option<String>,
    max_retained_findings: Option<usize>,
    max_retained_traces: Option<usize>,
    ingest_queue_capacity: Option<usize>,
    analysis_queue_capacity: Option<usize>,
    memory_high_water_pct: Option<u8>,
    api_enabled: Option<bool>,
    correlation: CorrelationSection,
    ack: DaemonAckSection,
    cors: DaemonCorsSection,
    archive: ArchiveSection,
}

/// Raw deserialization target for `[daemon.correlation]`.
#[derive(Deserialize, Default)]
#[serde(default)]
struct CorrelationSection {
    enabled: Option<bool>,
    window_minutes: Option<u64>,
    lag_threshold_ms: Option<u64>,
    min_co_occurrences: Option<u32>,
    min_confidence: Option<f64>,
    max_tracked_pairs: Option<usize>,
}

/// Raw deserialization target for `[daemon.ack]`.
#[derive(Deserialize, Default)]
#[serde(default)]
struct DaemonAckSection {
    enabled: Option<bool>,
    storage_path: Option<String>,
    api_key: Option<String>,
    toml_path: Option<String>,
}

/// Raw deserialization target for `[daemon.cors]`.
#[derive(Deserialize, Default)]
#[serde(default)]
struct DaemonCorsSection {
    allowed_origins: Vec<String>,
}

#[allow(deprecated)] // the two transport fields are retained for API compatibility only
impl From<RawConfig> for Config {
    #[allow(clippy::too_many_lines)] // Sectioned config-to-typed mapping: splitting would scatter field assignments across helpers
    fn from(raw: RawConfig) -> Self {
        let thresholds_defaults = ThresholdsConfig::default();
        let detection_defaults = DetectionConfig::default();
        let green_defaults = GreenConfig::default();
        let daemon_defaults = DaemonConfig::default();
        let correlation_defaults = crate::detect::correlate_cross::CorrelationConfig::default();
        let ack_defaults = DaemonAckConfig::default();

        Self {
            thresholds: ThresholdsConfig {
                n_plus_one_sql_critical_max: raw
                    .thresholds
                    .n_plus_one_sql_critical_max
                    .unwrap_or(thresholds_defaults.n_plus_one_sql_critical_max),
                n_plus_one_http_warning_max: raw
                    .thresholds
                    .n_plus_one_http_warning_max
                    .unwrap_or(thresholds_defaults.n_plus_one_http_warning_max),
                n_plus_one_messaging_warning_max: raw
                    .thresholds
                    .n_plus_one_messaging_warning_max
                    .unwrap_or(thresholds_defaults.n_plus_one_messaging_warning_max),
                io_waste_ratio_max: raw
                    .thresholds
                    .io_waste_ratio_max
                    .unwrap_or(thresholds_defaults.io_waste_ratio_max),
                // Opt-in rule: absent key stays None (disabled), no default.
                min_usable_span_ratio: raw.thresholds.min_usable_span_ratio,
            },
            detection: DetectionConfig {
                n_plus_one_threshold: raw
                    .detection
                    .n_plus_one_min_occurrences
                    .unwrap_or(detection_defaults.n_plus_one_threshold),
                window_duration_ms: raw
                    .detection
                    .window_duration_ms
                    .unwrap_or(detection_defaults.window_duration_ms),
                slow_query_threshold_ms: raw
                    .detection
                    .slow_query_threshold_ms
                    .unwrap_or(detection_defaults.slow_query_threshold_ms),
                slow_query_min_occurrences: raw
                    .detection
                    .slow_query_min_occurrences
                    .unwrap_or(detection_defaults.slow_query_min_occurrences),
                max_fanout: raw
                    .detection
                    .max_fanout
                    .unwrap_or(detection_defaults.max_fanout),
                chatty_service_min_calls: raw
                    .detection
                    .chatty_service_min_calls
                    .unwrap_or(detection_defaults.chatty_service_min_calls),
                pool_saturation_concurrent_threshold: raw
                    .detection
                    .pool_saturation_concurrent_threshold
                    .unwrap_or(detection_defaults.pool_saturation_concurrent_threshold),
                serialized_min_sequential: raw
                    .detection
                    .serialized_min_sequential
                    .unwrap_or(detection_defaults.serialized_min_sequential),
                sanitizer_aware_classification:
                    crate::detect::sanitizer_aware::SanitizerAwareMode::from_config(
                        raw.detection.sanitizer_aware_classification.as_deref(),
                    ),
                grouping_attributes: raw.detection.grouping_attributes.map_or_else(
                    || detection_defaults.grouping_attributes.clone(),
                    |attrs| {
                        let kept: Vec<String> = attrs
                            .into_iter()
                            .filter(|a| !a.trim().is_empty())
                            .collect();
                        if kept.len() > super::MAX_GROUPING_ATTRIBUTES {
                            // Silence here would read as "my attribute is
                            // never present" rather than "it was dropped".
                            tracing::warn!(
                                cap = super::MAX_GROUPING_ATTRIBUTES,
                                configured = kept.len(),
                                dropped = ?kept[super::MAX_GROUPING_ATTRIBUTES..],
                                "[detection] grouping_attributes exceeds the cap, extra entries ignored"
                            );
                        }
                        kept.into_iter()
                            .take(super::MAX_GROUPING_ATTRIBUTES)
                            .collect()
                    },
                ),
            },
            green: {
                // Deprecated 0.9.25: transport is always counted, always
                // displayed, and its coefficient is fixed for disclosure
                // comparability. Both keys are parsed, warned, ignored.
                if raw.green.network_energy_per_byte_kwh.is_some() {
                    tracing::warn!(
                        "[green] network_energy_per_byte_kwh is deprecated and ignored \
                         since 0.9.25, the transport coefficient is fixed"
                    );
                }
                if raw.green.include_network_transport.is_some() {
                    tracing::warn!(
                        "[green] include_network_transport is deprecated and ignored \
                         since 0.9.25, the transport term is always counted and displayed"
                    );
                }
                // Zero is no longer a way to opt the SCI M term out of a
                // published figure. Warned and clamped, never fatal.
                if raw.green.embodied_carbon_per_request_gco2 == Some(0.0) {
                    tracing::warn!(
                        "[green] embodied_carbon_per_request_gco2 = 0.0 is no longer honoured \
                         since 0.9.25, no hardware has zero embodied carbon: using the default \
                         {DEFAULT_EMBODIED_CARBON_PER_REQUEST_GCO2}"
                    );
                }
                GreenConfig {
                // Deprecated, retained for API compatibility: both report
                // what scoring applies, never what the TOML asked for.
                include_network_transport: true,
                network_energy_per_byte_kwh:
                    crate::score::carbon::DEFAULT_NETWORK_ENERGY_PER_BYTE_KWH,
                enabled: raw.green.enabled.unwrap_or(green_defaults.enabled),
                // Lowercase default_region and service_regions keys so
                // resolve_region's lowercase lookup matches regardless of
                // config casing, without paying the lowercase cost on every
                // downstream call site.
                default_region: raw.green.default_region.map(|s| s.to_ascii_lowercase()),
                service_regions: raw
                    .green
                    .service_regions
                    .into_iter()
                    .map(|(k, v)| (k.to_ascii_lowercase(), v))
                    .collect(),
                embodied_carbon_per_request_gco2: raw
                    .green
                    .embodied_carbon_per_request_gco2
                    // Only an exact zero is swallowed: negative and NaN
                    // must still reach validation and fail loudly.
                    .filter(|v| *v != 0.0)
                    .unwrap_or(green_defaults.embodied_carbon_per_request_gco2),
                use_hourly_profiles: raw
                    .green
                    .use_hourly_profiles
                    .unwrap_or(green_defaults.use_hourly_profiles),
                scaphandre: convert_scaphandre_section(&raw.green.scaphandre),
                kepler: convert_kepler_section(&raw.green.kepler),
                alumet: convert_alumet_section(&raw.green.alumet),
                redfish: convert_redfish_section(&raw.green.redfish),
                cloud_energy: convert_cloud_section(&raw.green.cloud),
                broker_static: convert_broker_static_section(&raw.green.broker_static),
                per_operation_coefficients: raw
                    .green
                    .per_operation_coefficients
                    .unwrap_or(green_defaults.per_operation_coefficients),
                hourly_profiles_file: raw.green.hourly_profiles_file.clone(),
                custom_hourly_profiles: raw.green.hourly_profiles_file.as_ref().and_then(|path| {
                    if has_control_char(path) {
                        tracing::warn!(
                            "hourly_profiles_file path contains control characters, skipping"
                        );
                        return None;
                    }
                    let p = std::path::Path::new(path);
                    match crate::score::carbon::load_custom_profiles(p) {
                        Ok(profiles) => Some(std::sync::Arc::new(profiles)),
                        Err(e) => {
                            // Not logged at warn: validate_green() will
                            // surface a hard error for this case.
                            tracing::debug!(
                                error = %e,
                                "Custom hourly profiles failed to load"
                            );
                            None
                        }
                    }
                }),
                calibration_file: raw.green.calibration_file.clone(),
                calibration: raw.green.calibration_file.as_ref().and_then(|path| {
                    if has_control_char(path) {
                        tracing::warn!(
                            "calibration_file path contains control characters, skipping"
                        );
                        return None;
                    }
                    match crate::calibrate::load_calibration_file(path) {
                        Ok(data) => Some(data),
                        Err(e) => {
                            tracing::debug!(
                                error = %e,
                                "Calibration file failed to load"
                            );
                            None
                        }
                    }
                }),
                electricity_maps: convert_electricity_maps_section(&raw.green.electricity_maps),
                }
            },
            daemon: DaemonConfig {
                listen_addr: raw
                    .daemon
                    .listen_address
                    .unwrap_or(daemon_defaults.listen_addr),
                listen_port: raw
                    .daemon
                    .listen_port_http
                    .unwrap_or(daemon_defaults.listen_port),
                listen_port_grpc: raw
                    .daemon
                    .listen_port_grpc
                    .unwrap_or(daemon_defaults.listen_port_grpc),
                json_socket: raw
                    .daemon
                    .json_socket
                    .unwrap_or(daemon_defaults.json_socket),
                max_active_traces: raw
                    .daemon
                    .max_active_traces
                    .unwrap_or(daemon_defaults.max_active_traces),
                trace_ttl_ms: raw
                    .daemon
                    .trace_ttl_ms
                    .unwrap_or(daemon_defaults.trace_ttl_ms),
                sampling_rate: raw
                    .daemon
                    .sampling_rate
                    .unwrap_or(daemon_defaults.sampling_rate),
                max_events_per_trace: raw
                    .daemon
                    .max_events_per_trace
                    .unwrap_or(daemon_defaults.max_events_per_trace),
                max_payload_size: raw
                    .daemon
                    .max_payload_size
                    .unwrap_or(daemon_defaults.max_payload_size),
                // Parse environment into the typed enum. Invalid strings are
                // rejected by load_from_str() before reaching this conversion;
                // direct callers (tests only) get Staging as a safe default.
                environment: match raw.daemon.environment.as_deref() {
                    None => daemon_defaults.environment,
                    Some(s) => parse_daemon_environment(s).unwrap_or(DaemonEnvironment::Staging),
                },
                max_retained_findings: raw
                    .daemon
                    .max_retained_findings
                    .unwrap_or(daemon_defaults.max_retained_findings),
                max_retained_traces: raw
                    .daemon
                    .max_retained_traces
                    .unwrap_or(daemon_defaults.max_retained_traces),
                ingest_queue_capacity: raw
                    .daemon
                    .ingest_queue_capacity
                    .unwrap_or(daemon_defaults.ingest_queue_capacity),
                analysis_queue_capacity: raw
                    .daemon
                    .analysis_queue_capacity
                    .unwrap_or(daemon_defaults.analysis_queue_capacity),
                memory_high_water_pct: raw
                    .daemon
                    .memory_high_water_pct
                    .unwrap_or(daemon_defaults.memory_high_water_pct),
                api_enabled: raw
                    .daemon
                    .api_enabled
                    .unwrap_or(daemon_defaults.api_enabled),
                tls: DaemonTlsConfig {
                    cert_path: raw.daemon.tls_cert_path,
                    key_path: raw.daemon.tls_key_path,
                },
                ack: DaemonAckConfig {
                    enabled: raw.daemon.ack.enabled.unwrap_or(ack_defaults.enabled),
                    storage_path: raw.daemon.ack.storage_path,
                    api_key: resolve_ack_api_key(raw.daemon.ack.api_key, || {
                        std::env::var("PERF_SENTINEL_ACK_API_KEY").ok()
                    }),
                    toml_path: raw.daemon.ack.toml_path,
                },
                cors: DaemonCorsConfig {
                    allowed_origins: raw.daemon.cors.allowed_origins,
                },
                correlation: {
                    let c = &raw.daemon.correlation;
                    crate::detect::correlate_cross::CorrelationConfig {
                        enabled: c.enabled.unwrap_or(correlation_defaults.enabled),
                        window_ms: c
                            .window_minutes
                            .map_or(correlation_defaults.window_ms, |m| m.saturating_mul(60_000)),
                        lag_threshold_ms: c
                            .lag_threshold_ms
                            .unwrap_or(correlation_defaults.lag_threshold_ms),
                        min_co_occurrences: c
                            .min_co_occurrences
                            .unwrap_or(correlation_defaults.min_co_occurrences),
                        min_confidence: c
                            .min_confidence
                            .unwrap_or(correlation_defaults.min_confidence),
                        max_tracked_pairs: c
                            .max_tracked_pairs
                            .unwrap_or(correlation_defaults.max_tracked_pairs),
                    }
                },
                archive: convert_archive_section(&raw.daemon.archive),
            },
            reporting: ReportingConfig {
                intent: raw.reporting.intent,
                confidentiality_level: raw.reporting.confidentiality_level,
                org_config_path: raw.reporting.org_config_path,
                disclose_output_path: raw.reporting.disclose_output_path,
                disclose_period: raw.reporting.disclose_period,
                sigstore: SigstoreConfig {
                    rekor_url: raw
                        .reporting
                        .sigstore
                        .rekor_url
                        .unwrap_or_else(|| DEFAULT_REKOR_URL.to_string()),
                    fulcio_url: raw
                        .reporting
                        .sigstore
                        .fulcio_url
                        .unwrap_or_else(|| DEFAULT_FULCIO_URL.to_string()),
                },
            },
        }
    }
}

/// Convert the raw `[daemon.archive]` TOML section into a typed config.
/// Returns `None` when `path` is absent (the operator did not opt in).
fn convert_archive_section(raw: &ArchiveSection) -> Option<DaemonArchiveConfig> {
    let path = raw.path.clone()?;
    let defaults = DaemonArchiveConfig::default();
    Some(DaemonArchiveConfig {
        path,
        max_size_mb: raw.max_size_mb.unwrap_or(defaults.max_size_mb),
        max_files: raw.max_files.unwrap_or(defaults.max_files),
    })
}

/// Parse a case-insensitive environment string into [`DaemonEnvironment`].
///
/// Returns `None` for any value that is not `"staging"` or `"production"`.
/// Called from [`Config::from`] (which falls back to default on error,
/// deferring the real rejection to [`Config::validate`]).
pub(super) fn parse_daemon_environment(value: &str) -> Option<DaemonEnvironment> {
    let trimmed = value.trim();
    if trimmed.eq_ignore_ascii_case("staging") {
        Some(DaemonEnvironment::Staging)
    } else if trimmed.eq_ignore_ascii_case("production") {
        Some(DaemonEnvironment::Production)
    } else {
        None
    }
}

/// Convert the raw `[green.cloud]` TOML section into a typed config.
///
/// Returns `None` when `prometheus_endpoint` is absent (section empty
/// or not present). Per-service entries are classified as either
/// `InstanceType` or `ManualWatts` based on which fields are set.
fn convert_cloud_section(raw: &CloudSection) -> Option<CloudEnergyConfig> {
    convert_cloud_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_CLOUD_AUTH_HEADER").ok()
    })
}

/// Test-friendly inner form: takes the env-var lookup as a closure so
/// tests can exercise the precedence branch without mutating the
/// global process env. Same pattern as
/// [`convert_electricity_maps_section_with_env`].
pub(super) fn convert_cloud_section_with_env(
    raw: &CloudSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<CloudEnergyConfig> {
    let endpoint = raw.prometheus_endpoint.as_ref()?;
    let mut services = HashMap::with_capacity(raw.services.len());
    for (name, svc) in &raw.services {
        let config = if svc.idle_watts.is_some() || svc.max_watts.is_some() {
            // Manual watts mode: both must be present (validated later).
            ServiceCloudConfig::ManualWatts {
                idle_watts: svc.idle_watts.unwrap_or(0.0),
                max_watts: svc.max_watts.unwrap_or(0.0),
                cpu_query: svc.cpu_query.clone(),
            }
        } else {
            ServiceCloudConfig::InstanceType {
                provider: svc.provider.clone(),
                instance_type: svc.instance_type.clone().unwrap_or_default(),
                cpu_query: svc.cpu_query.clone(),
            }
        };
        services.insert(name.clone(), config);
    }

    // Auth header: env var takes precedence over config file.
    let from_env = env_lookup();
    let auth_header = from_env.clone().or_else(|| raw.auth_header.clone());
    if from_env.is_none() && raw.auth_header.is_some() {
        tracing::warn!(
            "[green.cloud] auth_header is set in the config file. \
             Prefer the PERF_SENTINEL_CLOUD_AUTH_HEADER environment variable \
             to avoid committing secrets to version control."
        );
    }

    Some(CloudEnergyConfig {
        prometheus_endpoint: endpoint.clone(),
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(15)),
        default_provider: raw.default_provider.clone(),
        default_instance_type: raw.default_instance_type.clone(),
        cpu_metric: raw.cpu_metric.clone(),
        services,
        auth_header,
    })
}

/// Convert the raw `[green.scaphandre]` TOML section into a typed config.
///
/// Returns `None` when `endpoint` is absent (section empty or not present).
fn convert_scaphandre_section(raw: &ScaphandreSection) -> Option<ScaphandreConfig> {
    convert_scaphandre_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_SCAPHANDRE_AUTH_HEADER").ok()
    })
}

/// Test-friendly inner form: takes the env-var lookup as a closure so
/// tests can exercise the precedence branch without mutating the
/// global process env. Same pattern as
/// [`convert_electricity_maps_section_with_env`].
pub(super) fn convert_scaphandre_section_with_env(
    raw: &ScaphandreSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<ScaphandreConfig> {
    let endpoint = raw.endpoint.as_ref()?;

    // Auth header: env var takes precedence over config file.
    let from_env = env_lookup();
    let auth_header = from_env.clone().or_else(|| raw.auth_header.clone());
    if from_env.is_none() && raw.auth_header.is_some() {
        tracing::warn!(
            "[green.scaphandre] auth_header is set in the config file. \
             Prefer the PERF_SENTINEL_SCAPHANDRE_AUTH_HEADER environment variable \
             to avoid committing secrets to version control."
        );
    }

    Some(ScaphandreConfig {
        endpoint: endpoint.clone(),
        // Default scrape interval 5s; clamped in validate_green
        // to the [1, 3600] range.
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(5)),
        process_map: raw.process_map.clone(),
        auth_header,
    })
}

/// Parse a `[green.kepler] metric_kind = "..."` string into the typed
/// enum. Returns `Container` when the field is absent. Matching is
/// case-insensitive after trimming. Returns an error string when the
/// value is set-but-empty, set-but-unrecognized, or one of the legacy
/// `process_package` / `process_dram` aliases that targeted metrics
/// Kepler never published. The raw operator-typed string is preserved
/// verbatim in error messages so `grep -F` against the source TOML
/// stays reliable.
pub(super) fn parse_kepler_metric_kind(raw: Option<&str>) -> Result<KeplerMetricKind, String> {
    let Some(literal) = raw else {
        return Ok(KeplerMetricKind::Container);
    };
    // Reject control chars before any branch interpolates `literal`
    // into an error: ANSI escapes in TOML would otherwise reach stderr.
    if has_control_char(literal) {
        return Err("[green.kepler] metric_kind contains control characters".to_string());
    }
    let trimmed = literal.trim();
    if trimmed.is_empty() {
        return Err(format!(
            "[green.kepler] metric_kind '{literal}' is empty; \
             remove the field for the default or set it to 'container' or 'process'"
        ));
    }
    // `eq_ignore_ascii_case` skips the `to_ascii_lowercase` alloc,
    // matches `parse_daemon_environment` on the same TOML surface.
    if trimmed.eq_ignore_ascii_case("container") {
        return Ok(KeplerMetricKind::Container);
    }
    if trimmed.eq_ignore_ascii_case("process") {
        return Ok(KeplerMetricKind::Process);
    }
    if trimmed.eq_ignore_ascii_case("process_package")
        || trimmed.eq_ignore_ascii_case("process_dram")
    {
        return Err(format!(
            "[green.kepler] metric_kind '{literal}' was removed in v0.7.5. \
             Kepler v2 only exposes per-process CPU joules, use 'process' instead."
        ));
    }
    Err(format!(
        "[green.kepler] metric_kind '{literal}' is not recognized \
         (expected 'container' or 'process')"
    ))
}

/// Convert the raw `[green.kepler]` TOML section into a typed config.
///
/// Returns `None` when `endpoint` is absent. An invalid `metric_kind`
/// also yields `None` here as a defense-in-depth fallback. The
/// authoritative rejection happens upstream in [`load_from_str`]
/// before [`Config::from`] runs, so reaching this branch with a
/// malformed `metric_kind` means the operator bypassed `load_from_str`
/// (e.g. constructed a `RawConfig` directly in a test).
fn convert_kepler_section(raw: &KeplerSection) -> Option<KeplerConfig> {
    convert_kepler_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_KEPLER_AUTH_HEADER").ok()
    })
}

pub(super) fn convert_kepler_section_with_env(
    raw: &KeplerSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<KeplerConfig> {
    let endpoint = raw.endpoint.as_ref()?;
    let metric_kind = match parse_kepler_metric_kind(raw.metric_kind.as_deref()) {
        Ok(k) => k,
        Err(msg) => {
            tracing::error!("{msg}");
            return None;
        }
    };
    let from_env = env_lookup();
    let auth_header = from_env.clone().or_else(|| raw.auth_header.clone());
    if from_env.is_none() && raw.auth_header.is_some() {
        tracing::warn!(
            "[green.kepler] auth_header is set in the config file. \
             Prefer the PERF_SENTINEL_KEPLER_AUTH_HEADER environment variable \
             to avoid committing secrets to version control."
        );
    }
    Some(KeplerConfig {
        endpoint: endpoint.clone(),
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(5)),
        metric_kind,
        service_mappings: raw.service_mappings.clone(),
        auth_header,
    })
}

/// Raw deserialization target for `[green.broker_static]`.
///
/// `deny_unknown_fields`: a typo would silently disable the figure.
#[derive(Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub(super) struct BrokerStaticSection {
    pub(super) nodes: Option<u32>,
    pub(super) instance_type: Option<String>,
    pub(super) provider: Option<String>,
    pub(super) region: Option<String>,
}

/// Convert `[green.broker_static]` into a typed config. `None` unless
/// both `nodes` and `instance_type` are set, the two fields with no
/// defensible default.
fn convert_broker_static_section(
    raw: &BrokerStaticSection,
) -> Option<crate::score::broker_static::StaticBrokerConfig> {
    let nodes = raw.nodes?;
    let instance_type = raw.instance_type.as_ref()?.trim().to_string();
    Some(crate::score::broker_static::StaticBrokerConfig {
        nodes,
        instance_type,
        // An explicitly empty value reads as "unset", the same as an
        // absent key, rather than failing the provider allow-list.
        provider: raw
            .provider
            .as_deref()
            .map(|p| p.trim().to_ascii_lowercase())
            .filter(|p| !p.is_empty())
            .unwrap_or_else(|| "generic".to_string()),
        region: raw.region.clone(),
    })
}

/// Validate the raw `[green.alumet]` section before the lossy
/// `Config::from` conversion.
///
/// Same rationale as [`parse_kepler_metric_kind`]: the conversion would
/// otherwise downgrade a missing `metric_name` to a log line and
/// silently drop the whole section, so an operator who set an endpoint
/// but forgot the metric would get no scraper and no error. There is no
/// default for `metric_name` or `label_key` because Alumet's exporter
/// applies an operator-chosen `prefix`/`suffix` to every name and the
/// per-service series is named after an operator-chosen
/// `energy-attribution` formula. Guessing would scrape nothing, or
/// worse, the wrong series.
/// Reject a half-declared `[green.broker_static]`: `nodes` and
/// `instance_type` are both required and have no defensible default, so
/// one without the other must be a loud error, not a silently inert
/// section.
pub(super) fn validate_broker_static_raw(raw: &BrokerStaticSection) -> Result<(), String> {
    match (raw.nodes.is_some(), raw.instance_type.is_some()) {
        (true, false) => Err(
            "[green.broker_static] instance_type is required when nodes is set; \
             without it the section is silently inert and the messaging waste \
             figure never appears"
                .to_string(),
        ),
        (false, true) => Err(
            "[green.broker_static] nodes is required when instance_type is set; \
             without it the section is silently inert and the messaging waste \
             figure never appears"
                .to_string(),
        ),
        _ => Ok(()),
    }
}

pub(super) fn validate_alumet_raw(raw: &AlumetSection) -> Result<(), String> {
    if raw.endpoint.is_none() {
        // A database declaration without an endpoint would be silently
        // inert (no scraper ever starts), reject it loudly instead.
        if raw.database.is_some() {
            return Err(
                "[green.alumet.database] is set but [green.alumet] endpoint is missing; \
                 without an endpoint no scraper starts and the figure never appears"
                    .to_string(),
            );
        }
        if raw.broker.is_some() {
            return Err(
                "[green.alumet.broker] is set but [green.alumet] endpoint is missing; \
                 without an endpoint no scraper starts and the figure never appears"
                    .to_string(),
            );
        }
        return Ok(());
    }
    require_alumet_field(raw.metric_name.as_deref(), "metric_name")?;
    require_alumet_field(raw.label_key.as_deref(), "label_key")?;
    if let Some(secs) = raw.energy_interval_secs
        && (!secs.is_finite() || secs <= 0.0 || secs > 3600.0)
    {
        return Err(format!(
            "[green.alumet] energy_interval_secs must be a finite value in (0, 3600], got {secs}. \
             It mirrors the poll_interval of the Alumet source feeding the metric."
        ));
    }
    if let Some(db) = raw.database.as_ref() {
        let Some(label_value) = db.label_value.as_deref() else {
            return Err(
                "[green.alumet.database] label_value is required when the section is present"
                    .to_string(),
            );
        };
        super::validate::validate_workload_fields(
            "[green.alumet.database]",
            label_value,
            db.region.as_deref(),
        )?;
    }
    if let Some(broker) = raw.broker.as_ref() {
        let Some(label_value) = broker.label_value.as_deref() else {
            return Err(
                "[green.alumet.broker] label_value is required when the section is present"
                    .to_string(),
            );
        };
        super::validate::validate_workload_fields(
            "[green.alumet.broker]",
            label_value,
            broker.region.as_deref(),
        )?;
    }
    Ok(())
}

/// Reject an absent, empty, or control-char-bearing mandatory Alumet
/// string field. Control chars are checked before the value reaches an
/// error message, mirroring [`parse_kepler_metric_kind`].
fn require_alumet_field(value: Option<&str>, field: &str) -> Result<(), String> {
    let Some(literal) = value else {
        return Err(format!(
            "[green.alumet] {field} is required when endpoint is set. \
             Alumet's prometheus-exporter names metrics with an operator-chosen \
             prefix/suffix (default suffix '_alumet'), so there is no safe default. \
             Run `curl <endpoint> | grep -i energy` and copy the name verbatim."
        ));
    };
    if has_control_char(literal) {
        return Err(format!(
            "[green.alumet] {field} contains control characters"
        ));
    }
    if literal.trim().is_empty() {
        return Err(format!("[green.alumet] {field} must not be empty"));
    }
    Ok(())
}

/// Convert the raw `[green.alumet]` TOML section into a typed config.
///
/// Returns `None` when `endpoint` is absent. Missing mandatory fields
/// also yield `None` as defense in depth, the authoritative rejection
/// happens upstream in [`validate_alumet_raw`].
fn convert_alumet_section(raw: &AlumetSection) -> Option<AlumetConfig> {
    convert_alumet_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_ALUMET_AUTH_HEADER").ok()
    })
}

pub(super) fn convert_alumet_section_with_env(
    raw: &AlumetSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<AlumetConfig> {
    let endpoint = raw.endpoint.as_ref()?;
    if let Err(msg) = validate_alumet_raw(raw) {
        tracing::error!("{msg}");
        return None;
    }
    let metric_name = raw.metric_name.as_ref()?.trim().to_string();
    let label_key = raw.label_key.as_ref()?.trim().to_string();

    let from_env = env_lookup();
    let auth_header = from_env.clone().or_else(|| raw.auth_header.clone());
    if from_env.is_none() && raw.auth_header.is_some() {
        tracing::warn!(
            "[green.alumet] auth_header is set in the config file. \
             Prefer the PERF_SENTINEL_ALUMET_AUTH_HEADER environment variable \
             to avoid committing secrets to version control."
        );
    }
    Some(AlumetConfig {
        endpoint: endpoint.clone(),
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(5)),
        metric_name,
        label_key,
        energy_interval_secs: raw
            .energy_interval_secs
            .unwrap_or(DEFAULT_ENERGY_INTERVAL_SECS),
        service_mappings: raw.service_mappings.clone(),
        auth_header,
        // label_value stays verbatim (no trim): the docs promise an
        // exact match with the wire label, spaces included.
        database: raw.database.as_ref().and_then(|db| {
            db.label_value.as_ref().map(|lv| AlumetDatabaseConfig {
                label_value: lv.clone(),
                region: db.region.clone(),
            })
        }),
        broker: raw.broker.as_ref().and_then(|b| {
            b.label_value.as_ref().map(|lv| AlumetBrokerConfig {
                label_value: lv.clone(),
                region: b.region.clone(),
            })
        }),
    })
}

/// Convert the raw `[green.redfish]` TOML section into a typed config.
/// Returns `None` when `endpoints` is empty.
fn convert_redfish_section(raw: &RedfishSection) -> Option<RedfishConfig> {
    convert_redfish_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_REDFISH_AUTH_HEADER").ok()
    })
}

pub(super) fn convert_redfish_section_with_env(
    raw: &RedfishSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<RedfishConfig> {
    if raw.endpoints.is_empty() {
        return None;
    }
    let from_env = env_lookup();
    let auth_header = from_env.clone().or_else(|| raw.auth_header.clone());
    if from_env.is_none() && raw.auth_header.is_some() {
        tracing::warn!(
            "[green.redfish] auth_header is set in the config file. \
             Prefer the PERF_SENTINEL_REDFISH_AUTH_HEADER environment variable \
             to avoid committing secrets to version control."
        );
    }
    Some(RedfishConfig {
        endpoints: raw.endpoints.clone(),
        scrape_interval: Duration::from_secs(raw.scrape_interval_secs.unwrap_or(60)),
        service_mappings: raw.service_mappings.clone(),
        ca_bundle_path: raw.ca_bundle_path.clone(),
        auth_header,
    })
}

/// Convert the raw `[green.electricity_maps]` TOML section into a typed config.
///
/// Returns `None` when no `api_key` is set (neither in config nor env var).
pub(super) fn convert_electricity_maps_section(
    raw: &ElectricityMapsSection,
) -> Option<crate::score::electricity_maps::ElectricityMapsConfig> {
    convert_electricity_maps_section_with_env(raw, || {
        std::env::var("PERF_SENTINEL_EMAPS_TOKEN").ok()
    })
}

/// Test-friendly inner form: takes the env-var lookup as a closure so tests
/// can pass `|| None` instead of mutating the global process env. Avoids the
/// `unsafe` that Rust 2024 requires on `std::env::remove_var` (`set_var` and
/// `remove_var` are data races with other threads inside the same process,
/// including the `cargo test` harness).
pub(super) fn convert_electricity_maps_section_with_env(
    raw: &ElectricityMapsSection,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<crate::score::electricity_maps::ElectricityMapsConfig> {
    // Auth token: env var takes precedence over config file.
    let from_env = env_lookup();
    let token = from_env.clone().or_else(|| raw.api_key.clone())?;

    if token.is_empty() {
        return None;
    }

    // Nudge users toward the env var when the token is in the config file.
    if from_env.is_none() && raw.api_key.is_some() {
        tracing::warn!(
            "[green.electricity_maps] api_key is set in the config file. \
             Prefer the PERF_SENTINEL_EMAPS_TOKEN environment variable \
             to avoid committing secrets to version control."
        );
    }

    let poll_secs = raw.poll_interval_secs.unwrap_or(300);
    // Trim trailing slashes so the URL we build downstream
    // (`format!("{api_endpoint}/carbon-intensity/latest?zone={zone}")`)
    // never produces a double-slash like `.../v4//carbon-intensity/...`,
    // and so `is_legacy_v3_endpoint` matches `.../v3/` (trailing slash).
    let api_endpoint = raw
        .endpoint
        .clone()
        .unwrap_or_else(|| {
            crate::score::electricity_maps::config::DEFAULT_ELECTRICITY_MAPS_ENDPOINT.to_string()
        })
        .trim_end_matches('/')
        .to_string();
    let emission_factor_type =
        crate::score::electricity_maps::config::EmissionFactorType::from_config(
            raw.emission_factor_type.as_deref(),
        );
    let temporal_granularity =
        crate::score::electricity_maps::config::TemporalGranularity::from_config(
            raw.temporal_granularity.as_deref(),
        );
    Some(crate::score::electricity_maps::ElectricityMapsConfig {
        api_endpoint,
        auth_token: token,
        poll_interval: Duration::from_secs(poll_secs),
        // Lowercase region keys so scoring loop lookups match regardless
        // of config casing (same pattern as service_regions).
        region_map: raw
            .region_map
            .iter()
            .map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))
            .collect(),
        emission_factor_type,
        temporal_granularity,
    })
}

/// Resolve an `env:VAR` indirection on the daemon ack `api_key`.
///
/// A plain string passes through; `env:VAR` is replaced by the named env
/// var's value, or `None` when it is unset (fail-closed: the auth gate then
/// refuses a non-loopback bind). Lets operators feed the key from a
/// Kubernetes Secret instead of the committed config. The env lookup is a
/// closure so tests avoid mutating the global process env.
pub(super) fn resolve_ack_api_key(
    config_value: Option<String>,
    env_lookup: impl FnOnce() -> Option<String>,
) -> Option<String> {
    // `PERF_SENTINEL_ACK_API_KEY` overrides the config value (same convention as
    // `PERF_SENTINEL_EMAPS_TOKEN`), so the key can come from a Secret, not the
    // committed config. Trimmed for trailing-newline Secrets; a set-but-empty
    // var stays `Some("")` so validate rejects a mounted-but-empty Secret. The
    // closure keeps the env lookup out of the global process env in tests.
    env_lookup().or(config_value).map(|s| s.trim().to_string())
}