ferrum-types 0.8.3

Shared type definitions for the Ferrum LLM inference engine
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
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! Configuration types for Ferrum components

use crate::{
    parse_bool_env_value, parse_path_env_value, parse_usize_env_value, AttentionExecutionPolicy,
    DataType, Device, ModelId, ModelInfo, ObservabilityProfileDetail, ProfileEntrypoint,
    RuntimeConfigSnapshot, SamplingParams, SamplingPresets, TokenId,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{collections::HashMap, path::PathBuf, time::Duration};

/// Product policy for proving that a sequence fits before prefill admission.
///
/// This is a non-reserving fit gate: it does not claim future KV blocks. The
/// execution runtime still acquires exact live-frontier resources transactionally.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SequenceFitPolicy {
    FullInputMustFit,
    ImmediateOnly,
}

impl SequenceFitPolicy {
    pub const fn as_runtime_value(self) -> &'static str {
        match self {
            Self::FullInputMustFit => "full-input-must-fit",
            Self::ImmediateOnly => "immediate-only",
        }
    }

    pub fn parse_runtime_value(raw: &str) -> std::result::Result<Self, String> {
        match raw.trim().to_ascii_lowercase().replace('_', "-").as_str() {
            "full-input-must-fit" => Ok(Self::FullInputMustFit),
            "immediate-only" => Ok(Self::ImmediateOnly),
            _ => Err(format!(
                "expected full-input-must-fit or immediate-only; got {raw:?}"
            )),
        }
    }
}

impl Default for SequenceFitPolicy {
    fn default() -> Self {
        Self::ImmediateOnly
    }
}

/// Explicit one-shot faults used to prove product-path failure attribution.
/// These are never inferred and remain disabled in normal execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum VNextDiagnosticFault {
    PrefillResourceAfterSubmitOnce,
}

impl VNextDiagnosticFault {
    pub const fn as_runtime_value(self) -> &'static str {
        match self {
            Self::PrefillResourceAfterSubmitOnce => "prefill-resource-after-submit-once",
        }
    }

    pub fn parse_runtime_value(raw: &str) -> std::result::Result<Self, String> {
        match raw.trim().to_ascii_lowercase().replace('_', "-").as_str() {
            "prefill-resource-after-submit-once" => Ok(Self::PrefillResourceAfterSubmitOnce),
            _ => Err(format!(
                "expected prefill-resource-after-submit-once; got {raw:?}"
            )),
        }
    }
}

/// Explicit diagnostic capture of semantic vNext activations. Product paths
/// leave this unset; release tooling must supply a dedicated empty directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VNextCheckpointCaptureConfig {
    pub output_dir: PathBuf,
    pub value_ids: Vec<String>,
    pub maximum_prefill_waves: usize,
    #[serde(default)]
    pub maximum_decode_waves: usize,
    /// Persist the product output that the executor already reads back. Unlike
    /// `value_ids`, this does not retain an activation or alter memory planning.
    #[serde(default)]
    pub capture_product_output: bool,
    /// Optional canonical output history for a same-history numerical
    /// diagnostic. The vNext executor persists each unmodified full-logits
    /// result before forcing the corresponding token into the engine-facing
    /// copy. Ordinary product inference leaves this unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub teacher_forcing: Option<VNextTeacherForcingConfig>,
}

pub const MAX_VNEXT_TEACHER_FORCED_TOKENS: usize = 512;

/// Bounded token history used only by explicit vNext checkpoint diagnostics.
///
/// Construction and executor binding both validate this contract. The latter
/// is required because deserialization can bypass `new` and only model binding
/// knows the live vocabulary size.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VNextTeacherForcingConfig {
    token_ids: Vec<TokenId>,
}

impl VNextTeacherForcingConfig {
    pub fn new(token_ids: Vec<TokenId>) -> std::result::Result<Self, String> {
        let value = Self { token_ids };
        value.validate()?;
        Ok(value)
    }

    pub fn validate(&self) -> std::result::Result<(), String> {
        if self.token_ids.is_empty() || self.token_ids.len() > MAX_VNEXT_TEACHER_FORCED_TOKENS {
            return Err(format!(
                "vNext checkpoint teacher forcing requires 1..={MAX_VNEXT_TEACHER_FORCED_TOKENS} tokens"
            ));
        }
        Ok(())
    }

    pub fn token_ids(&self) -> &[TokenId] {
        &self.token_ids
    }

    pub fn token_count(&self) -> usize {
        self.token_ids.len()
    }

    /// Canonical identity used by release validators: concatenated little-
    /// endian u32 token IDs, with no JSON or path-dependent representation.
    pub fn token_ids_sha256(&self) -> String {
        let mut digest = Sha256::new();
        for token in &self.token_ids {
            digest.update(token.get().to_le_bytes());
        }
        format!("{:x}", digest.finalize())
    }
}

/// Engine runtime knobs the CLI/autosizer resolves and injects via the
/// runtime-config snapshot. The continuous engine reads these from the typed
/// config instead of `std::env::vars()`, so the env bridge stays at the
/// composition root and tests can vary the knobs per `EngineConfig`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RuntimeKnobs {
    pub kv_capacity: Option<usize>,
    pub max_model_len: Option<usize>,
    pub chunked_prefill_size: Option<usize>,
    pub batch_decode_prof: bool,
    pub next_batch_prof: bool,
    pub rbd_prof: bool,
    #[serde(default)]
    pub profile_jsonl: Option<PathBuf>,
    pub scheduler_trace_jsonl: Option<PathBuf>,
    pub legacy_scheduler_trace_jsonl: Option<PathBuf>,
    pub profile_entrypoint: Option<ProfileEntrypoint>,
    pub profile_detail: ObservabilityProfileDetail,
    pub unified_post_prof: bool,
    pub prefix_cache_enabled: bool,
    pub recurrent_state_max_slots: Option<usize>,
    pub attention_execution_policy: AttentionExecutionPolicy,

    // Engine-build composition knobs. Previously read directly from the
    // environment by `builder.rs` (FERRUM_MODEL_PATH / FERRUM_SPEC_DRAFT /
    // FERRUM_SPEC_N) and `registry.rs` (FERRUM_DTYPE / FERRUM_METAL_DTYPE /
    // FERRUM_TP). The CLI composition root now resolves them into this typed
    // field so the engine builder and component registry read the snapshot,
    // not `std::env`.
    pub model_path: Option<String>,
    pub spec_draft: Option<String>,
    pub spec_n: Option<usize>,
    pub dtype: Option<String>,
    pub metal_dtype: Option<String>,
    pub tp: Option<usize>,
    #[serde(default)]
    pub vnext_checkpoint_capture: Option<VNextCheckpointCaptureConfig>,
    #[serde(default)]
    pub vnext_diagnostic_fault: Option<VNextDiagnosticFault>,
}

/// Engine configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EngineConfig {
    pub model: EngineModelConfig,
    pub scheduler: SchedulerConfig,
    pub sampling: SamplingConfig,
    pub backend: BackendConfig,
    pub kv_cache: KvCacheConfig,
    pub memory: MemoryConfig,
    pub batching: BatchConfig,
    pub monitoring: MonitoringConfig,
    #[serde(default)]
    pub runtime: RuntimeKnobs,
}

impl EngineConfig {
    pub fn apply_runtime_config_snapshot(
        &mut self,
        snapshot: &RuntimeConfigSnapshot,
    ) -> std::result::Result<(), String> {
        self.scheduler.apply_runtime_config_snapshot(snapshot)?;
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_KV_MAX_BLOCKS") {
            self.kv_cache.max_blocks =
                parse_required_positive_usize("FERRUM_KV_MAX_BLOCKS", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_MAX_BATCHED_TOKENS") {
            self.batching.max_num_batched_tokens =
                parse_required_positive_usize("FERRUM_MAX_BATCHED_TOKENS", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_PAGED_MAX_SEQS") {
            self.scheduler.max_running_requests =
                parse_required_positive_usize("FERRUM_PAGED_MAX_SEQS", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_RUNTIME_MEMORY_BUDGET_BYTES") {
            self.memory.usable_capacity_bytes = Some(parse_required_positive_usize(
                "FERRUM_RUNTIME_MEMORY_BUDGET_BYTES",
                value,
            )?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_BATCHED_GRAPH") {
            self.backend.enable_cuda_graphs = parse_presence_bool(value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_REUSABLE_EXECUTION") {
            self.backend.enable_reusable_execution = parse_presence_bool(value)?;
        }
        if let Some(value) =
            runtime_config_value(snapshot, "FERRUM_REUSABLE_EXECUTION_EXACT_DECODE_WIDTHS")
        {
            let widths =
                parse_positive_usize_list("FERRUM_REUSABLE_EXECUTION_EXACT_DECODE_WIDTHS", value)?;
            if widths
                .iter()
                .any(|width| *width > MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH)
            {
                return Err(format!(
                    "FERRUM_REUSABLE_EXECUTION_EXACT_DECODE_WIDTHS: startup capture widths must be within 1..={MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH}"
                ));
            }
            self.backend.reusable_execution_capture.exact_decode_widths = Some(widths);
        }
        if let Some(value) = runtime_config_value(
            snapshot,
            "FERRUM_REUSABLE_EXECUTION_MAX_AUTOMATIC_EXACT_DECODE_WIDTH",
        ) {
            let maximum = parse_required_positive_usize(
                "FERRUM_REUSABLE_EXECUTION_MAX_AUTOMATIC_EXACT_DECODE_WIDTH",
                value,
            )?;
            if maximum > MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH {
                return Err(format!(
                    "FERRUM_REUSABLE_EXECUTION_MAX_AUTOMATIC_EXACT_DECODE_WIDTH: must be within 1..={MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH}"
                ));
            }
            self.backend
                .reusable_execution_capture
                .maximum_automatic_exact_decode_width = maximum;
        }
        // Engine runtime knobs (previously read by the engine from env). The
        // CLI/autosizer resolves these into the snapshot; the engine reads the
        // typed `runtime` field instead of `std::env::vars()`.
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_KV_CAPACITY") {
            self.runtime.kv_capacity =
                Some(parse_required_positive_usize("FERRUM_KV_CAPACITY", value)?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_MAX_MODEL_LEN") {
            self.runtime.max_model_len = Some(parse_required_positive_usize(
                "FERRUM_MAX_MODEL_LEN",
                value,
            )?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_RECURRENT_STATE_MAX_SLOTS") {
            self.runtime.recurrent_state_max_slots = Some(parse_required_positive_usize(
                "FERRUM_RECURRENT_STATE_MAX_SLOTS",
                value,
            )?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_ATTENTION_POLICY") {
            self.runtime.attention_execution_policy =
                AttentionExecutionPolicy::parse_runtime_value(value)
                    .map_err(|reason| format!("FERRUM_ATTENTION_POLICY: {reason}"))?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_CHUNKED_PREFILL") {
            self.runtime.chunked_prefill_size =
                parse_usize_env_value(value).ok().filter(|&v| v > 0);
        }
        self.runtime.batch_decode_prof |=
            runtime_config_value(snapshot, "FERRUM_BATCH_DECODE_PROF").is_some();
        self.runtime.next_batch_prof |=
            runtime_config_value(snapshot, "FERRUM_NEXT_BATCH_PROF").is_some();
        self.runtime.rbd_prof |= runtime_config_value(snapshot, "FERRUM_RBD_PROF").is_some();
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_PROFILE_JSONL") {
            self.runtime.profile_jsonl = Some(parse_path_env_value(value)?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SCHEDULER_TRACE_JSONL") {
            self.runtime.scheduler_trace_jsonl = Some(parse_path_env_value(value)?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_LEGACY_SCHEDULER_TRACE_JSONL") {
            self.runtime.legacy_scheduler_trace_jsonl = Some(parse_path_env_value(value)?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_PROFILE_ENTRYPOINT") {
            self.runtime.profile_entrypoint = Some(parse_profile_entrypoint(
                "FERRUM_PROFILE_ENTRYPOINT",
                value,
            )?);
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_PROFILE_DETAIL") {
            self.runtime.profile_detail =
                ObservabilityProfileDetail::parse(value).ok_or_else(|| {
                    format!(
                    "FERRUM_PROFILE_DETAIL: expected one of off, basic, resource, latency, kernel, debug, replay, verify, full; got {value:?}"
                    )
                })?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_VNEXT_DIAGNOSTIC_FAULT") {
            self.runtime.vnext_diagnostic_fault = Some(
                VNextDiagnosticFault::parse_runtime_value(value)
                    .map_err(|reason| format!("FERRUM_VNEXT_DIAGNOSTIC_FAULT: {reason}"))?,
            );
        }
        self.runtime.unified_post_prof |=
            runtime_config_value(snapshot, "FERRUM_UNIFIED_POST_PROF").is_some();
        self.runtime.prefix_cache_enabled |=
            runtime_config_value(snapshot, "FERRUM_WHOLE_PROMPT_PREFIX_CACHE")
                .map(|v| v == "1")
                .unwrap_or(false);

        // Engine-build composition knobs (previously read by builder.rs /
        // registry.rs from env). Only overwrite when the key is present so a
        // later snapshot apply without the key keeps an earlier value.
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_MODEL_PATH") {
            self.runtime.model_path = Some(value.to_string());
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SPEC_DRAFT") {
            self.runtime.spec_draft = if value.is_empty() {
                None
            } else {
                Some(value.to_string())
            };
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SPEC_N") {
            self.runtime.spec_n = value.parse::<usize>().ok();
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_DTYPE") {
            self.runtime.dtype = Some(value.to_string());
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_METAL_DTYPE") {
            self.runtime.metal_dtype = Some(value.to_string());
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_TP") {
            self.runtime.tp = value.parse::<usize>().ok();
        }

        // Publish the resolved snapshot process-wide. Model code (which is not
        // threaded an EngineConfig) reads `active_runtime_snapshot()` for the
        // remaining FERRUM_* toggles instead of `std::env`, keeping the env
        // bridge at this single composition-root call.
        crate::install_runtime_snapshot(snapshot.clone());
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EngineModelConfig {
    pub model_id: ModelId,
    pub model_info: Option<ModelInfo>,
    pub tokenizer: TokenizerConfig,
    /// Typed identity of the source requested by the product entrypoint.
    /// The resolved local path remains a runtime/backend concern, while this
    /// value preserves repository/revision provenance for product composition.
    #[serde(default)]
    pub source: Option<crate::ModelSource>,
}

impl Default for EngineModelConfig {
    fn default() -> Self {
        Self {
            model_id: ModelId::new("default"),
            model_info: None,
            tokenizer: TokenizerConfig::default(),
            source: None,
        }
    }
}

/// Scheduler configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchedulerConfig {
    /// Scheduling policy
    pub policy: SchedulingPolicy,
    /// Maximum waiting queue size
    pub max_waiting_requests: usize,
    /// Maximum running requests
    pub max_running_requests: usize,
    /// Enable request preemption
    pub enable_preemption: bool,
    /// Enable load balancing
    pub enable_load_balancing: bool,
    /// Fair share weights per client
    pub fair_share_weights: HashMap<String, f32>,
    /// SLA enforcement enabled
    pub enable_sla_enforcement: bool,
    /// Use prompt-token metadata for initial continuous-batch admission estimates.
    #[serde(default = "default_prompt_token_estimate")]
    pub prompt_token_estimate: bool,
    /// Prefer new prefills over early decodes until this many requests are active.
    #[serde(default)]
    pub prefill_first_until_active: Option<usize>,
    /// Optional hard cap for per-request prefill chunks. `None` spends the
    /// live per-step token budget and lets capacity feedback narrow or regrow
    /// each request independently.
    #[serde(default)]
    pub prefill_step_chunk: Option<usize>,
    /// Cap prefill admission chunks only while decode requests are already active.
    #[serde(default)]
    pub active_decode_prefill_chunk: Option<usize>,
    /// Emit diagnostic scheduler None/SOME decisions.
    #[serde(default)]
    pub scheduler_none_prof: bool,
    /// Non-reserving sequence fit gate used before prefill admission.
    #[serde(default)]
    pub sequence_fit_policy: SequenceFitPolicy,
}

impl Default for SchedulerConfig {
    fn default() -> Self {
        Self {
            policy: SchedulingPolicy::Priority,
            max_waiting_requests: 1000,
            max_running_requests: 32,
            enable_preemption: true,
            enable_load_balancing: false,
            fair_share_weights: HashMap::new(),
            enable_sla_enforcement: false,
            prompt_token_estimate: default_prompt_token_estimate(),
            prefill_first_until_active: None,
            prefill_step_chunk: None,
            active_decode_prefill_chunk: None,
            scheduler_none_prof: false,
            sequence_fit_policy: SequenceFitPolicy::default(),
        }
    }
}

fn default_prompt_token_estimate() -> bool {
    true
}

impl SchedulerConfig {
    pub fn apply_runtime_config_snapshot(
        &mut self,
        snapshot: &RuntimeConfigSnapshot,
    ) -> std::result::Result<(), String> {
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SCHED_PROMPT_TOKEN_ESTIMATE") {
            self.prompt_token_estimate = parse_bool_env_value(value)
                .map_err(|reason| format!("FERRUM_SCHED_PROMPT_TOKEN_ESTIMATE: {reason}"))?;
        }
        if let Some(value) =
            runtime_config_value(snapshot, "FERRUM_SCHED_PREFILL_FIRST_UNTIL_ACTIVE")
        {
            self.prefill_first_until_active =
                parse_optional_positive_usize("FERRUM_SCHED_PREFILL_FIRST_UNTIL_ACTIVE", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SCHED_PREFILL_STEP_CHUNK") {
            self.prefill_step_chunk =
                parse_optional_positive_usize("FERRUM_SCHED_PREFILL_STEP_CHUNK", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_ACTIVE_DECODE_PREFILL_CHUNK") {
            self.active_decode_prefill_chunk =
                parse_optional_positive_usize("FERRUM_ACTIVE_DECODE_PREFILL_CHUNK", value)?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SCHED_NONE_PROF") {
            self.scheduler_none_prof = parse_presence_bool(value)
                .map_err(|reason| format!("FERRUM_SCHED_NONE_PROF: {reason}"))?;
        }
        if let Some(value) = runtime_config_value(snapshot, "FERRUM_SEQUENCE_FIT_POLICY") {
            self.sequence_fit_policy = SequenceFitPolicy::parse_runtime_value(value)
                .map_err(|reason| format!("FERRUM_SEQUENCE_FIT_POLICY: {reason}"))?;
        }
        Ok(())
    }
}

fn runtime_config_value<'a>(snapshot: &'a RuntimeConfigSnapshot, key: &str) -> Option<&'a str> {
    snapshot
        .entries
        .iter()
        .find(|entry| entry.key == key)
        .map(|entry| entry.effective_value.as_str())
}

fn parse_optional_positive_usize(
    key: &str,
    value: &str,
) -> std::result::Result<Option<usize>, String> {
    let parsed = parse_usize_env_value(value).map_err(|reason| format!("{key}: {reason}"))?;
    Ok((parsed > 0).then_some(parsed))
}

fn parse_required_positive_usize(key: &str, value: &str) -> std::result::Result<usize, String> {
    let parsed = parse_usize_env_value(value).map_err(|reason| format!("{key}: {reason}"))?;
    if parsed == 0 {
        Err(format!("{key}: must be greater than zero"))
    } else {
        Ok(parsed)
    }
}

fn parse_positive_usize_list(key: &str, value: &str) -> std::result::Result<Vec<usize>, String> {
    let values = value
        .split(',')
        .map(str::trim)
        .map(|value| parse_required_positive_usize(key, value))
        .collect::<std::result::Result<Vec<_>, _>>()?;
    if values.is_empty() {
        Err(format!("{key}: must contain at least one width"))
    } else {
        Ok(values)
    }
}

fn parse_profile_entrypoint(
    key: &str,
    value: &str,
) -> std::result::Result<ProfileEntrypoint, String> {
    ProfileEntrypoint::parse(value).ok_or_else(|| {
        format!("{key}: expected one of run, serve, bench_serve, synthetic; got {value:?}")
    })
}

fn parse_presence_bool(value: &str) -> std::result::Result<bool, String> {
    if value.trim().is_empty() {
        Ok(true)
    } else {
        parse_bool_env_value(value)
    }
}

/// Scheduling policies
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SchedulingPolicy {
    /// First-Come-First-Served
    FCFS,
    /// Priority-based scheduling
    Priority,
    /// Fair-share scheduling
    FairShare,
    /// Shortest-Job-First
    SJF,
    /// Round-Robin
    RoundRobin,
    /// Iteration-level continuous batching with preemption
    ContinuousBatch,
}

/// KV Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KvCacheConfig {
    /// Cache implementation type
    pub cache_type: KvCacheType,
    /// Element dtype (Dim 5 polymorphism point). FP16 is the
    /// validated production path; INT8 / FP8 require a backend impl
    /// of `BackendKvDtype<KvInt8>` / `BackendKvDtype<KvFp8>` and a
    /// model wired through `KvCacheQuant<B, K>`.
    #[serde(default)]
    pub dtype: KvCacheDtype,
    /// Block size for paged attention
    pub block_size: usize,
    /// Maximum number of blocks
    pub max_blocks: usize,
    /// Enable cache compression
    pub enable_compression: bool,
    /// Compression ratio target
    pub compression_ratio: f32,
    /// Enable multi-level caching (GPU + CPU)
    pub enable_multi_level: bool,
    /// Swap threshold (when to move to CPU)
    pub swap_threshold: f32,
    /// Enable prefix caching
    pub enable_prefix_caching: bool,
    /// Prefix cache size
    pub prefix_cache_size: usize,
}

impl Default for KvCacheConfig {
    fn default() -> Self {
        // 2048 blocks covers c=32 ShareGPT prompts (~32×500/16 = 1000
        // blocks). The previous 1024 floor crashed at c≥16 on real
        // workloads with "Block pool exhausted". Runtime overrides are
        // applied through EngineConfig::apply_runtime_config_snapshot.
        Self {
            cache_type: KvCacheType::Contiguous,
            dtype: KvCacheDtype::default(),
            block_size: 16,
            max_blocks: 2048,
            enable_compression: false,
            compression_ratio: 0.5,
            enable_multi_level: true,
            swap_threshold: 0.8,
            enable_prefix_caching: true,
            prefix_cache_size: 100,
        }
    }
}

/// KV Cache implementation types
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum KvCacheType {
    /// Simple contiguous memory allocation
    Contiguous,
    /// Paged attention with block-based allocation
    Paged,
    /// Tree-based cache for prefix sharing
    Tree,
}

/// KV Cache element dtype (Dim 5 polymorphism point).
///
/// Mirrors `ferrum_interfaces::kv_dtype::KvDtypeKind` markers but
/// lives here because `KvCacheConfig` is part of the user-facing
/// `EngineConfig` and needs `Serialize` / `Deserialize`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum KvCacheDtype {
    /// FP16 K/V — the validated production path on every backend.
    #[default]
    Fp16,
    /// BF16 K/V — same memory cost as FP16, slightly different precision.
    /// Marker only; no backend impl ships yet.
    Bf16,
    /// INT8 K/V with per-token per-kv-head FP16 scale (vLLM-style).
    /// Halves KV memory at small (<1%) accuracy hit. CUDA kernels
    /// land via `BackendKvDtype<KvInt8>` (PR #131); model wire-up
    /// (`KvCacheQuant<B, KvInt8>` through the model decode loop) is
    /// the only remaining step.
    Int8,
    /// FP8 (E4M3) K/V. Marker only; CUDA kernels pending.
    Fp8,
}

impl KvCacheDtype {
    /// Parse from a CLI / env-var string. Accepts fp16/f16/bf16/int8/fp8/f8e4m3.
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "fp16" | "f16" | "float16" => Some(Self::Fp16),
            "bf16" | "bfloat16" => Some(Self::Bf16),
            "int8" | "i8" => Some(Self::Int8),
            "fp8" | "f8" | "f8e4m3" | "e4m3" => Some(Self::Fp8),
            _ => None,
        }
    }

    /// Short label for display + telemetry.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Fp16 => "fp16",
            Self::Bf16 => "bf16",
            Self::Int8 => "int8",
            Self::Fp8 => "fp8",
        }
    }
}

/// Memory management configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// Memory pool size in bytes
    pub pool_size: Option<usize>,
    /// Exact device-wide usable runtime budget in bytes. When present this
    /// overrides the pressure-threshold calculation without changing the raw
    /// device or pool capacity.
    #[serde(default)]
    pub usable_capacity_bytes: Option<usize>,
    /// Enable memory pooling
    pub enable_pooling: bool,
    /// Memory alignment in bytes
    pub alignment: usize,
    /// Enable memory defragmentation
    pub enable_defragmentation: bool,
    /// Defragmentation threshold
    pub defragmentation_threshold: f32,
    /// Enable memory statistics tracking
    pub enable_memory_stats: bool,
    /// Memory pressure warning threshold
    pub pressure_warning_threshold: f32,
    /// Memory pressure critical threshold
    pub pressure_critical_threshold: f32,
}

/// Resolved device-wide memory budget consumed by runtime planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryCapacityBudget {
    pub capacity_bytes: u64,
    pub usable_capacity_bytes: u64,
    pub reserve_bytes: u64,
}

impl MemoryConfig {
    pub fn resolve_capacity_budget(
        &self,
        device_capacity_bytes: u64,
    ) -> std::result::Result<MemoryCapacityBudget, String> {
        if device_capacity_bytes == 0 {
            return Err("runtime device memory capacity must be greater than zero".to_string());
        }
        let capacity_bytes = self
            .pool_size
            .map(|bytes| bytes as u64)
            .unwrap_or(device_capacity_bytes)
            .min(device_capacity_bytes);
        if capacity_bytes == 0 {
            return Err("runtime memory capacity must be greater than zero".to_string());
        }

        let usable_capacity_bytes = if let Some(bytes) = self.usable_capacity_bytes {
            let bytes = bytes as u64;
            if bytes == 0 || bytes > capacity_bytes {
                return Err(format!(
                    "memory.usable_capacity_bytes must be in 1..={capacity_bytes}, got {bytes}"
                ));
            }
            bytes
        } else {
            let critical = self.pressure_critical_threshold;
            if !critical.is_finite() || critical <= 0.0 || critical > 1.0 {
                return Err(format!(
                    "memory.pressure_critical_threshold must be in (0, 1], got {critical}"
                ));
            }
            let threshold_bytes = ((capacity_bytes as f64) * f64::from(critical)).floor() as u64;
            capacity_bytes.saturating_sub(
                capacity_bytes
                    .saturating_sub(threshold_bytes)
                    .min(capacity_bytes - 1),
            )
        };
        Ok(MemoryCapacityBudget {
            capacity_bytes,
            usable_capacity_bytes,
            reserve_bytes: capacity_bytes - usable_capacity_bytes,
        })
    }
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            pool_size: None,
            usable_capacity_bytes: None,
            enable_pooling: true,
            alignment: 256,
            enable_defragmentation: false,
            defragmentation_threshold: 0.7,
            enable_memory_stats: true,
            pressure_warning_threshold: 0.8,
            pressure_critical_threshold: 0.95,
        }
    }
}

/// Non-configurable upper bound for startup decode capture width.
///
/// This bound is independent from scheduler admission. It protects startup
/// worker/resource creation even when a user supplies an extreme concurrency
/// value or an explicit capture list. Wider runtime batches remain valid and
/// use the documented eager fallback.
pub const MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH: usize = 32;

/// Default upper bound for automatically generated exact decode capture widths.
///
/// This is an independent startup-work safety bound, not a concurrency limit.
/// A resolver may automatically request every exact width through the minimum
/// of admission, this ceiling, and the hard startup bound. Admission above the
/// bound remains valid; wider runtime waves use eager fallback unless a future
/// independently bounded policy supports them.
pub const DEFAULT_MAXIMUM_AUTOMATIC_EXACT_DECODE_WIDTH: usize =
    MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH;

/// Product policy for reusable-execution startup capture.
///
/// `None` requests an automatically resolved exact-width matrix. Explicit
/// widths let operators bound startup work deliberately; widths omitted from
/// that matrix remain eligible for the runtime's documented eager fallback.
/// Neither form may exceed
/// [`MAXIMUM_REUSABLE_EXECUTION_STARTUP_CAPTURE_WIDTH`].
/// Validation against scheduler admission and backend capabilities belongs to
/// the runtime-policy resolver, where those resolved limits are available.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ReusableExecutionCaptureConfig {
    /// Exact concurrent decode widths to prepare. `None` selects automatic
    /// resolution from the admitted runtime capacity.
    pub exact_decode_widths: Option<Vec<usize>>,
    /// Safety ceiling for automatic exact-width expansion. This does not cap
    /// user concurrency and may only lower the independent startup hard bound.
    pub maximum_automatic_exact_decode_width: usize,
}

impl Default for ReusableExecutionCaptureConfig {
    fn default() -> Self {
        Self {
            exact_decode_widths: None,
            maximum_automatic_exact_decode_width: DEFAULT_MAXIMUM_AUTOMATIC_EXACT_DECODE_WIDTH,
        }
    }
}

/// Backend configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendConfig {
    /// Backend type
    pub backend_type: BackendType,
    /// Target device
    pub device: Device,
    /// Data type for computation
    pub dtype: DataType,
    /// Enable optimizations
    pub enable_optimizations: bool,
    /// Optimization level (0-3)
    pub optimization_level: u8,
    /// Enable CUDA graphs
    pub enable_cuda_graphs: bool,
    /// Prepare backend-owned reusable device programs when supported.
    #[serde(default = "default_enable_reusable_execution")]
    pub enable_reusable_execution: bool,
    /// Typed reusable-program capture policy shared by every product
    /// entrypoint. This is deliberately not a backend option or hidden env
    /// bridge: the resolved execution policy must fingerprint its outcome.
    #[serde(default)]
    pub reusable_execution_capture: ReusableExecutionCaptureConfig,
    /// Enable kernel fusion
    pub enable_kernel_fusion: bool,
    /// Custom backend-specific options
    pub backend_options: HashMap<String, serde_json::Value>,
}

impl Default for BackendConfig {
    fn default() -> Self {
        Self {
            backend_type: BackendType::Candle,
            device: Device::CPU,
            dtype: DataType::FP16,
            enable_optimizations: true,
            optimization_level: 2,
            enable_cuda_graphs: false,
            enable_reusable_execution: default_enable_reusable_execution(),
            reusable_execution_capture: ReusableExecutionCaptureConfig::default(),
            enable_kernel_fusion: true,
            backend_options: HashMap::new(),
        }
    }
}

const fn default_enable_reusable_execution() -> bool {
    true
}

/// Supported backend types
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum BackendType {
    /// Candle framework
    Candle,
    /// ONNX Runtime
    OnnxRuntime,
    /// TensorRT
    TensorRT,
    /// Custom backend
    Custom,
}

/// Tokenizer configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenizerConfig {
    /// Tokenizer type
    pub tokenizer_type: TokenizerType,
    /// Path to tokenizer files
    pub tokenizer_path: Option<String>,
    /// Enable fast tokenization
    pub enable_fast: bool,
    /// Add special tokens
    pub add_special_tokens: bool,
    /// Truncation strategy
    pub truncation: Option<TruncationConfig>,
    /// Padding strategy
    pub padding: Option<PaddingConfig>,
}

impl Default for TokenizerConfig {
    fn default() -> Self {
        Self {
            tokenizer_type: TokenizerType::BPE,
            tokenizer_path: None,
            enable_fast: true,
            add_special_tokens: true,
            truncation: None,
            padding: None,
        }
    }
}

/// Tokenizer algorithms
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TokenizerType {
    /// Byte Pair Encoding
    BPE,
    /// WordPiece tokenizer (BERT-style)
    WordPiece,
    /// SentencePiece tokenizer
    SentencePiece,
    /// Tiktoken tokenizer family
    Tiktoken,
    /// Any custom tokenizer implementation
    Custom,
}

/// Truncation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TruncationConfig {
    /// Maximum length
    pub max_length: usize,
    /// Truncation strategy
    pub strategy: TruncationStrategy,
}

/// Truncation strategies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TruncationStrategy {
    /// Remove from the beginning
    TruncateStart,
    /// Remove from the end
    TruncateEnd,
    /// Remove from both sides
    TruncateBoth,
}

/// Padding configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaddingConfig {
    /// Padding strategy
    pub strategy: PaddingStrategy,
    /// Padding token ID
    pub token_id: u32,
    /// Target length
    pub target_length: Option<usize>,
}

/// Padding strategies
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaddingStrategy {
    /// No padding
    None,
    /// Pad to maximum length in batch
    MaxLength,
    /// Pad to specific length
    FixedLength,
}

/// Sampling configuration presets

/// Security configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    /// Enable API authentication
    pub enable_auth: bool,
    /// API keys for authentication
    pub api_keys: Vec<String>,
    /// Enable rate limiting
    pub enable_rate_limiting: bool,
    /// Rate limit per client (requests per minute)
    pub rate_limit_rpm: u32,
    /// Enable content filtering
    pub enable_content_filter: bool,
    /// Maximum prompt length
    pub max_prompt_length: usize,
    /// Enable prompt validation
    pub enable_prompt_validation: bool,
    /// Allowed file extensions for uploads
    pub allowed_extensions: Vec<String>,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            enable_auth: false,
            api_keys: vec![],
            enable_rate_limiting: true,
            rate_limit_rpm: 60,
            enable_content_filter: false,
            max_prompt_length: 32768,
            enable_prompt_validation: true,
            allowed_extensions: vec!["txt".to_string(), "json".to_string()],
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SamplingConfig {
    pub default_params: SamplingParams,
    pub presets: SamplingPresets,
    pub enable_custom_processors: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
    pub enable_metrics: bool,
    pub enable_tracing: bool,
    pub export_interval: Duration,
}

impl Default for MonitoringConfig {
    fn default() -> Self {
        Self {
            enable_metrics: true,
            enable_tracing: true,
            export_interval: Duration::from_secs(5),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchConfig {
    pub max_batch_size: usize,
    pub max_wait_ms: u64,
    pub enable_dynamic: bool,
    pub enable_continuous: bool,
    /// vLLM-style per-iteration token budget. The scheduler emits a
    /// mixed prefill+decode batch summing to at most this many Q
    /// tokens (decode = 1 each, prefill chunk = its chunk size).
    /// Default 2048. Runtime snapshots can override this with
    /// `FERRUM_MAX_BATCHED_TOKENS`, usually from the GPU autosizer or a
    /// named workload preset rather than a user hand-written env bundle.
    #[serde(default = "BatchConfig::default_max_num_batched_tokens")]
    pub max_num_batched_tokens: usize,
}

impl BatchConfig {
    fn default_max_num_batched_tokens() -> usize {
        2048
    }
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_batch_size: 32,
            max_wait_ms: 8,
            enable_dynamic: true,
            enable_continuous: false,
            max_num_batched_tokens: Self::default_max_num_batched_tokens(),
        }
    }
}

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

    #[test]
    fn scheduler_keeps_immediate_fit_default_until_full_input_policy_is_gated() {
        assert_eq!(
            SchedulerConfig::default().sequence_fit_policy,
            SequenceFitPolicy::ImmediateOnly
        );
    }

    #[test]
    fn sequence_fit_policy_uses_canonical_product_values() {
        assert_eq!(
            serde_json::to_string(&SequenceFitPolicy::FullInputMustFit).unwrap(),
            "\"full-input-must-fit\""
        );
        assert_eq!(
            serde_json::from_str::<SequenceFitPolicy>("\"immediate-only\"").unwrap(),
            SequenceFitPolicy::ImmediateOnly
        );
    }

    #[test]
    fn diagnostic_fault_uses_one_canonical_product_value() {
        assert_eq!(
            VNextDiagnosticFault::parse_runtime_value("prefill_resource_after_submit_once")
                .unwrap(),
            VNextDiagnosticFault::PrefillResourceAfterSubmitOnce
        );
        assert_eq!(
            VNextDiagnosticFault::PrefillResourceAfterSubmitOnce.as_runtime_value(),
            "prefill-resource-after-submit-once"
        );
        assert!(VNextDiagnosticFault::parse_runtime_value("resource-failure").is_err());
    }

    #[test]
    fn engine_config_applies_typed_diagnostic_fault() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([(
            "FERRUM_VNEXT_DIAGNOSTIC_FAULT",
            "prefill-resource-after-submit-once",
        )]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.vnext_diagnostic_fault,
            Some(VNextDiagnosticFault::PrefillResourceAfterSubmitOnce)
        );
    }

    #[test]
    fn engine_config_rejects_unknown_diagnostic_fault() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([(
            "FERRUM_VNEXT_DIAGNOSTIC_FAULT",
            "resource-failure",
        )]);

        let error = config
            .apply_runtime_config_snapshot(&snapshot)
            .expect_err("unknown diagnostic fault must fail closed");

        assert!(error.contains("FERRUM_VNEXT_DIAGNOSTIC_FAULT"));
    }

    #[test]
    fn scheduler_deserialization_without_fit_policy_keeps_legacy_default() {
        let mut serialized = serde_json::to_value(SchedulerConfig::default()).unwrap();
        serialized
            .as_object_mut()
            .unwrap()
            .remove("sequence_fit_policy");

        let scheduler: SchedulerConfig = serde_json::from_value(serialized).unwrap();

        assert_eq!(
            scheduler.sequence_fit_policy,
            SequenceFitPolicy::ImmediateOnly
        );
    }

    #[test]
    fn checkpoint_capture_deserialization_keeps_decode_capture_disabled_by_default() {
        let capture: VNextCheckpointCaptureConfig = serde_json::from_value(serde_json::json!({
            "output_dir": "capture",
            "value_ids": ["value.output.logits"],
            "maximum_prefill_waves": 1
        }))
        .unwrap();

        assert_eq!(capture.maximum_decode_waves, 0);
        assert!(!capture.capture_product_output);
    }

    #[test]
    fn engine_config_applies_typed_sequence_fit_policy() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([(
            "FERRUM_SEQUENCE_FIT_POLICY",
            "full-input-must-fit",
        )]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.scheduler.sequence_fit_policy,
            SequenceFitPolicy::FullInputMustFit
        );
    }

    #[test]
    fn engine_config_rejects_unknown_sequence_fit_policy() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([(
            "FERRUM_SEQUENCE_FIT_POLICY",
            "reserve-everything",
        )]);

        let error = config
            .apply_runtime_config_snapshot(&snapshot)
            .expect_err("unknown fit policy must fail closed");

        assert!(error.contains("FERRUM_SEQUENCE_FIT_POLICY"));
    }

    #[test]
    fn engine_config_applies_recurrent_state_max_slots_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot =
            RuntimeConfigSnapshot::from_env_vars([("FERRUM_RECURRENT_STATE_MAX_SLOTS", "16")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(config.runtime.recurrent_state_max_slots, Some(16));
    }

    #[test]
    fn engine_config_does_not_apply_removed_qwen35_slot_alias() {
        let mut config = EngineConfig::default();
        let snapshot =
            RuntimeConfigSnapshot::from_env_vars([("FERRUM_QWEN35_LINEAR_STATE_MAX_SLOTS", "16")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(config.runtime.recurrent_state_max_slots, None);
    }

    #[test]
    fn engine_config_uses_generic_recurrent_state_slots_when_removed_alias_is_present() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([
            ("FERRUM_RECURRENT_STATE_MAX_SLOTS", "8"),
            ("FERRUM_QWEN35_LINEAR_STATE_MAX_SLOTS", "16"),
        ]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(config.runtime.recurrent_state_max_slots, Some(8));
    }

    #[test]
    fn engine_config_applies_profile_entrypoint_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_ENTRYPOINT", "run")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.profile_entrypoint,
            Some(ProfileEntrypoint::Run)
        );
    }

    #[test]
    fn engine_config_applies_typed_profile_detail_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_DETAIL", "full")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.profile_detail,
            ObservabilityProfileDetail::Full
        );
    }

    #[test]
    fn engine_config_applies_typed_latency_profile_detail_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_DETAIL", "latency")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("latency profile detail should apply");

        assert_eq!(
            config.runtime.profile_detail,
            ObservabilityProfileDetail::Latency
        );
    }

    #[test]
    fn engine_config_applies_typed_replay_profile_detail_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_DETAIL", "replay")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.profile_detail,
            ObservabilityProfileDetail::Replay
        );
    }

    #[test]
    fn engine_config_applies_typed_verification_profile_detail_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot = RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_DETAIL", "verify")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.profile_detail,
            ObservabilityProfileDetail::Verify
        );
    }

    #[test]
    fn engine_config_applies_typed_profile_jsonl_runtime_key() {
        let mut config = EngineConfig::default();
        let snapshot =
            RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_JSONL", "/tmp/profile.jsonl")]);

        config
            .apply_runtime_config_snapshot(&snapshot)
            .expect("runtime config should apply");

        assert_eq!(
            config.runtime.profile_jsonl.as_deref(),
            Some(std::path::Path::new("/tmp/profile.jsonl"))
        );
    }

    #[test]
    fn engine_config_rejects_unknown_profile_detail() {
        let mut config = EngineConfig::default();
        let snapshot =
            RuntimeConfigSnapshot::from_env_vars([("FERRUM_PROFILE_DETAIL", "everything")]);

        let error = config
            .apply_runtime_config_snapshot(&snapshot)
            .expect_err("unknown profile detail must fail closed");

        assert!(error.contains("FERRUM_PROFILE_DETAIL"));
    }
}