kapsl-backends 0.1.0

Pluggable inference backends (ONNX, llama.cpp) for the Kapsl 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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
use async_trait::async_trait;
use half::f16;
use kapsl_engine_api::{
    BinaryTensorPacket, Engine, EngineError, EngineMetrics, EngineModelInfo, InferenceRequest,
    TensorDtype,
};
use ndarray::ArrayD;
use ort::execution_providers::ExecutionProvider as OrtExecutionProvider;
use ort::session::builder::GraphOptimizationLevel;
use ort::session::{Session, SessionInputValue};
use ort::tensor::TensorElementType;
use ort::value::Value;
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
use std::time::Instant;

// TODO: Consider adding support for OpenVINO and other backends
#[derive(Debug, Clone, Copy)]
pub enum ExecutionProvider {
    CPU,
    CUDA,
    TensorRT,
    DirectML,
    ROCm,
    OpenVINO,
    CoreML,
}

#[derive(Debug, Clone)]
pub struct ModelMetadata {
    pub input_names: Vec<String>,
    pub output_names: Vec<String>,
    pub input_shapes: Vec<Vec<i64>>,
    pub output_shapes: Vec<Vec<i64>>,
    pub input_dtypes: Vec<Option<TensorDtype>>,
    pub output_dtypes: Vec<Option<TensorDtype>>,
}

pub struct OnnxBackend {
    session: Arc<RwLock<Option<Session>>>,
    bucket_sessions: Arc<RwLock<BucketSessionState>>,
    model_path: Arc<RwLock<Option<PathBuf>>>,
    provider: ExecutionProvider,
    optimization_level: u8,
    device_id: i32,
    memory_pattern: bool,
    disable_cpu_mem_arena: bool,
    max_bucket_sessions: usize,
    bucket_dim_granularity: usize,
    bucket_max_dims: usize,
    peak_concurrency_hint: Option<u32>,
    metrics: Arc<RwLock<EngineMetrics>>,
    metadata: Arc<RwLock<Option<ModelMetadata>>>,
    warmed_up: Arc<AtomicBool>,
}

#[derive(Default)]
struct BucketSessionState {
    primary_bucket_key: Option<String>,
    sessions: HashMap<String, Session>,
    lru: VecDeque<String>,
}

const ORT_MEMORY_PATTERN_ENV: &str = "KAPSL_ORT_MEMORY_PATTERN";
const ORT_DISABLE_CPU_MEM_ARENA_ENV: &str = "KAPSL_ORT_DISABLE_CPU_MEM_ARENA";
const ORT_SESSION_BUCKETS_ENV: &str = "KAPSL_ORT_SESSION_BUCKETS";
const ORT_BUCKET_DIM_GRANULARITY_ENV: &str = "KAPSL_ORT_BUCKET_DIM_GRANULARITY";
const ORT_BUCKET_MAX_DIMS_ENV: &str = "KAPSL_ORT_BUCKET_MAX_DIMS";
const MODEL_PEAK_CONCURRENCY_ENV: &str = "KAPSL_MODEL_PEAK_CONCURRENCY";
const ORT_SESSION_BUCKETS_MAX: usize = 64;

fn read_env_flag(name: &str, default: bool) -> bool {
    std::env::var(name)
        .ok()
        .and_then(|value| match value.trim().to_ascii_lowercase().as_str() {
            "1" | "true" | "yes" | "on" => Some(true),
            "0" | "false" | "no" | "off" => Some(false),
            _ => None,
        })
        .unwrap_or(default)
}

fn read_env_usize(name: &str) -> Option<usize> {
    std::env::var(name)
        .ok()
        .and_then(|value| value.trim().parse::<usize>().ok())
}

fn read_env_u32(name: &str) -> Option<u32> {
    std::env::var(name)
        .ok()
        .and_then(|value| value.trim().parse::<u32>().ok())
        .filter(|value| *value > 0)
}

fn expose_sensitive_ids_in_logs() -> bool {
    static CACHE: OnceLock<bool> = OnceLock::new();
    *CACHE.get_or_init(|| {
        std::env::var("KAPSL_LOG_SENSITIVE_IDS")
            .or_else(|_| std::env::var("KAPSL_LOG_SENSITIVE_IDS"))
            .ok()
            .map(|value| {
                matches!(
                    value.trim().to_ascii_lowercase().as_str(),
                    "1" | "true" | "yes" | "on"
                )
            })
            .unwrap_or(false)
    })
}

fn redact_session_id_for_log(session_id: &str) -> String {
    if expose_sensitive_ids_in_logs() || session_id.is_empty() {
        return session_id.to_string();
    }
    let prefix: String = session_id.chars().take(4).collect();
    format!("{}...[redacted]", prefix)
}

fn map_ort_dtype(dtype: TensorElementType) -> Option<TensorDtype> {
    match dtype {
        TensorElementType::Float32 => Some(TensorDtype::Float32),
        TensorElementType::Float64 => Some(TensorDtype::Float64),
        TensorElementType::Float16 => Some(TensorDtype::Float16),
        TensorElementType::Int32 => Some(TensorDtype::Int32),
        TensorElementType::Int64 => Some(TensorDtype::Int64),
        TensorElementType::Uint8 => Some(TensorDtype::Uint8),
        _ => None,
    }
}

// TODO: Review if manual unsafe impl is necessary - Session should already be Send + Sync
// TODO: Add documentation explaining thread safety guarantees
// Session is Send + Sync, so OnnxBackend is Send + Sync
unsafe impl Send for OnnxBackend {}
unsafe impl Sync for OnnxBackend {}

#[derive(Debug)]
pub struct OnnxBackendBuilder {
    provider: ExecutionProvider,
    optimization_level: GraphOptimizationLevel,
    device_id: i32,
    memory_pattern: bool,
    disable_cpu_mem_arena: bool,
    max_bucket_sessions: usize,
    bucket_dim_granularity: usize,
    bucket_max_dims: usize,
    peak_concurrency_hint: Option<u32>,
}

impl OnnxBackendBuilder {
    pub fn new() -> Self {
        let memory_pattern = read_env_flag(ORT_MEMORY_PATTERN_ENV, true);
        let disable_cpu_mem_arena = read_env_flag(ORT_DISABLE_CPU_MEM_ARENA_ENV, false);
        let max_bucket_sessions = read_env_usize(ORT_SESSION_BUCKETS_ENV)
            .unwrap_or(4)
            .clamp(1, ORT_SESSION_BUCKETS_MAX);
        let bucket_dim_granularity = read_env_usize(ORT_BUCKET_DIM_GRANULARITY_ENV)
            .unwrap_or(64)
            .max(1);
        let bucket_max_dims = read_env_usize(ORT_BUCKET_MAX_DIMS_ENV).unwrap_or(4).max(1);
        let peak_concurrency_hint = read_env_u32(MODEL_PEAK_CONCURRENCY_ENV);
        Self {
            provider: ExecutionProvider::CPU,
            optimization_level: GraphOptimizationLevel::Level3,
            device_id: 0,
            memory_pattern,
            disable_cpu_mem_arena,
            max_bucket_sessions,
            bucket_dim_granularity,
            bucket_max_dims,
            peak_concurrency_hint,
        }
    }

    pub fn with_provider(mut self, provider: ExecutionProvider) -> Self {
        self.provider = provider;
        self
    }

    pub fn with_optimization_level(mut self, opt_level: GraphOptimizationLevel) -> Self {
        self.optimization_level = opt_level;
        self
    }

    pub fn with_device_id(mut self, device_id: i32) -> Result<Self, String> {
        if device_id < 0 {
            return Err("Device ID must be non-negative".to_string());
        }
        self.device_id = device_id;
        Ok(self)
    }

    pub fn with_memory_pattern(mut self, enabled: bool) -> Self {
        self.memory_pattern = enabled;
        self
    }

    pub fn with_disable_cpu_mem_arena(mut self, disabled: bool) -> Self {
        self.disable_cpu_mem_arena = disabled;
        self
    }

    pub fn with_max_bucket_sessions(mut self, max_bucket_sessions: usize) -> Self {
        self.max_bucket_sessions = max_bucket_sessions.clamp(1, ORT_SESSION_BUCKETS_MAX);
        self
    }

    pub fn with_bucket_dim_granularity(mut self, bucket_dim_granularity: usize) -> Self {
        self.bucket_dim_granularity = bucket_dim_granularity.max(1);
        self
    }

    pub fn with_bucket_max_dims(mut self, bucket_max_dims: usize) -> Self {
        self.bucket_max_dims = bucket_max_dims.max(1);
        self
    }

    pub fn with_peak_concurrency_hint(mut self, peak_concurrency_hint: u32) -> Self {
        self.peak_concurrency_hint = Some(peak_concurrency_hint.max(1));
        self
    }

    pub fn build(self) -> OnnxBackend {
        let level_value = match self.optimization_level {
            GraphOptimizationLevel::Disable => 0,
            GraphOptimizationLevel::Level1 => 1,
            GraphOptimizationLevel::Level2 => 2,
            GraphOptimizationLevel::Level3 => 3,
            GraphOptimizationLevel::All => 4,
        };
        OnnxBackend {
            session: Arc::new(RwLock::new(None)),
            bucket_sessions: Arc::new(RwLock::new(BucketSessionState::default())),
            model_path: Arc::new(RwLock::new(None)),
            provider: self.provider,
            optimization_level: level_value,
            device_id: self.device_id,
            memory_pattern: self.memory_pattern,
            disable_cpu_mem_arena: self.disable_cpu_mem_arena,
            max_bucket_sessions: self.max_bucket_sessions,
            bucket_dim_granularity: self.bucket_dim_granularity,
            bucket_max_dims: self.bucket_max_dims,
            peak_concurrency_hint: self.peak_concurrency_hint,
            metrics: Arc::new(RwLock::new(EngineMetrics::default())),
            metadata: Arc::new(RwLock::new(None)),
            warmed_up: Arc::new(AtomicBool::new(false)),
        }
    }
}

impl Default for OnnxBackendBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl OnnxBackend {
    /// Convert stored u8 optimization level to GraphOptimizationLevel
    fn get_opt_level(&self) -> GraphOptimizationLevel {
        match self.optimization_level {
            0 => GraphOptimizationLevel::Disable,
            1 => GraphOptimizationLevel::Level1,
            2 => GraphOptimizationLevel::Level2,
            3 => GraphOptimizationLevel::Level3,
            _ => GraphOptimizationLevel::All,
        }
    }

    pub fn builder() -> OnnxBackendBuilder {
        OnnxBackendBuilder::new()
    }

    pub fn new_cpu() -> Self {
        Self::builder().build()
    }

    pub fn new_cpu_with_optimization(opt_level: GraphOptimizationLevel) -> Self {
        Self::builder().with_optimization_level(opt_level).build()
    }

    pub fn new_cuda(device_id: i32) -> Result<Self, String> {
        Self::new_cuda_with_optimization(GraphOptimizationLevel::Level3, device_id)
    }

    pub fn new_cuda_with_optimization(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::CUDA)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    pub fn new_tensorrt(device_id: i32) -> Result<Self, String> {
        Self::new_tensorrt_with_optimization(GraphOptimizationLevel::Level3, device_id)
    }

    pub fn new_tensorrt_with_optimization(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::TensorRT)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    pub fn new_directml(device_id: i32) -> Result<Self, String> {
        Self::new_directml_with_optimization(GraphOptimizationLevel::Level3, device_id)
    }

    pub fn new_directml_with_optimization(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::DirectML)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    pub fn new_rocm(device_id: i32) -> Result<Self, String> {
        Self::new_rocm_with_optimization(GraphOptimizationLevel::Level3, device_id)
    }

    pub fn new_rocm_with_optimization(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::ROCm)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    pub fn new_openvino_with_optimiation(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::OpenVINO)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    pub fn new_coreml_with_optimiation(
        opt_level: GraphOptimizationLevel,
        device_id: i32,
    ) -> Result<Self, String> {
        Ok(Self::builder()
            .with_provider(ExecutionProvider::CoreML)
            .with_optimization_level(opt_level)
            .with_device_id(device_id)?
            .build())
    }

    fn bucket_key_for_request(&self, request: &InferenceRequest) -> Option<String> {
        if self.max_bucket_sessions <= 1 {
            return None;
        }

        let mut key = format!(
            "{}:r{}",
            request.input.dtype.as_str(),
            request.input.shape.len()
        );
        for (index, dim) in request
            .input
            .shape
            .iter()
            .take(self.bucket_max_dims)
            .copied()
            .enumerate()
        {
            let rounded = if dim <= 0 {
                -1
            } else if index == 0 {
                dim
            } else {
                let granularity = self.bucket_dim_granularity as i64;
                ((dim + granularity - 1) / granularity) * granularity
            };
            key.push(':');
            key.push_str(&rounded.to_string());
        }
        if request.input.shape.len() > self.bucket_max_dims {
            key.push_str(":*");
        }
        Some(key)
    }

    fn touch_bucket_lru(state: &mut BucketSessionState, bucket_key: &str) {
        if let Some(pos) = state.lru.iter().position(|existing| existing == bucket_key) {
            state.lru.remove(pos);
        }
        state.lru.push_back(bucket_key.to_string());
    }

    fn get_or_create_bucket_session<'a>(
        &self,
        state: &'a mut BucketSessionState,
        bucket_key: &str,
    ) -> Result<&'a mut Session, EngineError> {
        if !state.sessions.contains_key(bucket_key) {
            let secondary_capacity = self.max_bucket_sessions.saturating_sub(1).max(1);
            while state.sessions.len() >= secondary_capacity {
                let Some(evict_key) = state.lru.pop_front() else {
                    break;
                };
                state.sessions.remove(&evict_key);
            }

            let model_path = self
                .model_path
                .read()
                .map_err(|_| EngineError::Backend {
                    message: "Lock poisoned".to_string(),
                    source: None,
                })?
                .clone()
                .ok_or(EngineError::ModelNotLoaded)?;
            let session = self.create_session(&model_path, self.get_opt_level())?;
            state.sessions.insert(bucket_key.to_string(), session);
        }

        Self::touch_bucket_lru(state, bucket_key);
        state
            .sessions
            .get_mut(bucket_key)
            .ok_or(EngineError::ModelNotLoaded)
    }

    fn create_session(
        &self,
        model_path: &Path,
        opt_level: GraphOptimizationLevel,
    ) -> Result<Session, EngineError> {
        // Common builder setup
        let mut builder = Session::builder()
            .map_err(|e| EngineError::ModelLoadError {
                path: model_path.to_string_lossy().into_owned(),
                source: Box::new(std::io::Error::other(e.to_string())),
            })?
            .with_optimization_level(opt_level)
            .map_err(|e| EngineError::ModelLoadError {
                path: model_path.to_string_lossy().into_owned(),
                source: Box::new(std::io::Error::other(e.to_string())),
            })?
            .with_memory_pattern(self.memory_pattern)
            .map_err(|e| EngineError::ModelLoadError {
                path: model_path.to_string_lossy().into_owned(),
                source: Box::new(std::io::Error::other(e.to_string())),
            })?;
        if self.disable_cpu_mem_arena {
            builder = builder
                .with_config_entry("session.disable_cpu_mem_arena", "1")
                .map_err(|e| EngineError::ModelLoadError {
                    path: model_path.to_string_lossy().into_owned(),
                    source: Box::new(std::io::Error::other(e.to_string())),
                })?;
        }

        // Configure execution providers based on the selected backend
        let builder = match self.provider {
            ExecutionProvider::CUDA => {
                if !ort::execution_providers::CUDAExecutionProvider::default()
                    .is_available()
                    .unwrap_or(false)
                {
                    return Err(EngineError::Backend {
                        message:
                            "CUDA execution provider is not available. Please check your CUDA installation."
                                .to_string(),
                        source: None,
                    });
                }
                builder
                    .with_execution_providers([
                        ort::execution_providers::CUDAExecutionProvider::default()
                            .with_device_id(self.device_id)
                            .build(),
                    ])
                    .map_err(|e| EngineError::ModelLoadError {
                        path: model_path.to_string_lossy().into_owned(),
                        source: Box::new(std::io::Error::other(e.to_string())),
                    })?
            }
            ExecutionProvider::TensorRT => {
                if !ort::execution_providers::TensorRTExecutionProvider::default()
                    .is_available()
                    .unwrap_or(false)
                {
                    return Err(EngineError::Backend {
                        message: "TensorRT execution provider is not available.".to_string(),
                        source: None,
                    });
                }
                builder
                    .with_execution_providers([
                        ort::execution_providers::TensorRTExecutionProvider::default()
                            .with_device_id(self.device_id)
                            .build(),
                        // Fallback to CUDA if TensorRT has issues with some nodes
                        ort::execution_providers::CUDAExecutionProvider::default()
                            .with_device_id(self.device_id)
                            .build(),
                    ])
                    .map_err(|e| EngineError::ModelLoadError {
                        path: model_path.to_string_lossy().into_owned(),
                        source: Box::new(std::io::Error::other(e.to_string())),
                    })?
            }
            ExecutionProvider::DirectML => {
                #[cfg(target_os = "windows")]
                {
                    if !ort::execution_providers::DirectMLExecutionProvider::default()
                        .is_available()
                        .unwrap_or(false)
                    {
                        return Err(EngineError::Backend {
                            message: "DirectML execution provider is not available.".to_string(),
                            source: None,
                        });
                    }
                    builder
                        .with_execution_providers([
                            ort::execution_providers::DirectMLExecutionProvider::default()
                                .with_device_id(self.device_id)
                                .build(),
                        ])
                        .map_err(|e| EngineError::ModelLoadError {
                            path: model_path.to_string_lossy().into_owned(),
                            source: Box::new(std::io::Error::other(e.to_string())),
                        })?
                }
                #[cfg(not(target_os = "windows"))]
                {
                    return Err(EngineError::Backend {
                        message: "DirectML execution provider is only supported on Windows."
                            .to_string(),
                        source: None,
                    });
                }
            }
            ExecutionProvider::ROCm => {
                if !ort::execution_providers::ROCmExecutionProvider::default()
                    .is_available()
                    .unwrap_or(false)
                {
                    return Err(EngineError::Backend {
                        message: "ROCm execution provider is not available.".to_string(),
                        source: None,
                    });
                }
                builder
                    .with_execution_providers([
                        ort::execution_providers::ROCmExecutionProvider::default()
                            .with_device_id(self.device_id)
                            .build(),
                    ])
                    .map_err(|e| EngineError::ModelLoadError {
                        path: model_path.to_string_lossy().into_owned(),
                        source: Box::new(std::io::Error::other(e.to_string())),
                    })?
            }
            ExecutionProvider::OpenVINO => {
                if !ort::execution_providers::OpenVINOExecutionProvider::default()
                    .is_available()
                    .unwrap_or(false)
                {
                    return Err(EngineError::Backend {
                        message: "OpenVINO execution provider is not available.".to_string(),
                        source: None,
                    });
                }
                builder
                    .with_execution_providers([
                        ort::execution_providers::OpenVINOExecutionProvider::default().build(),
                    ])
                    .map_err(|e| EngineError::ModelLoadError {
                        path: model_path.to_string_lossy().into_owned(),
                        source: Box::new(std::io::Error::other(e.to_string())),
                    })?
            }
            ExecutionProvider::CoreML => {
                if !ort::execution_providers::CoreMLExecutionProvider::default()
                    .is_available()
                    .unwrap_or(false)
                {
                    return Err(EngineError::Backend {
                        message: "CoreML execution provider is not available.".to_string(),
                        source: None,
                    });
                }
                builder
                    .with_execution_providers([
                        ort::execution_providers::CoreMLExecutionProvider::default().build(),
                        // Keep CPU registered as a fallback for nodes CoreML cannot handle. Without
                        // this, ONNXRuntime will hard-fail on models that partially compile/run
                        // under CoreML (ex: plan-building failures for certain ops).
                        ort::execution_providers::CPUExecutionProvider::default().build(),
                    ])
                    .map_err(|e| EngineError::ModelLoadError {
                        path: model_path.to_string_lossy().into_owned(),
                        source: Box::new(std::io::Error::other(e.to_string())),
                    })?
            }
            ExecutionProvider::CPU => {
                // CPU is always available, nothing special to add
                builder
            }
        };

        // Finalize session from file
        builder
            .commit_from_file(model_path)
            .map_err(|e| EngineError::ModelLoadError {
                path: model_path.to_string_lossy().into_owned(),
                source: Box::new(std::io::Error::other(e.to_string())),
            })
    }
}

/// PreparedInput is returned by the input validation helper. It contains the
/// typed vector of elements parsed from raw bytes.
///
/// Note: kept at module scope so tests can access it.
#[derive(Debug)]
enum PreparedInput {
    F32(Vec<f32>),
    F64(Vec<f64>),
    F16(Vec<f16>),
    I32(Vec<i32>),
    I64(Vec<i64>),
    U8(Vec<u8>),
}

fn validate_byte_len(
    input: &BinaryTensorPacket,
    num_elements: usize,
    elem_size: usize,
    dtype_label: &str,
) -> Result<(), EngineError> {
    let expected =
        num_elements
            .checked_mul(elem_size)
            .ok_or_else(|| EngineError::InvalidInput {
                message: "Data size overflow".to_string(),
                source: None,
            })?;
    if input.data.len() != expected {
        return Err(EngineError::InvalidInput {
            message: format!(
                "Data length mismatch: expected {} bytes ({} {} values) but got {} bytes",
                expected,
                num_elements,
                dtype_label,
                input.data.len()
            ),
            source: None,
        });
    }
    Ok(())
}

fn parse_ne_f32(bytes: &[u8], num_elements: usize) -> Vec<f32> {
    if let Some(values) = try_aligned_copy::<f32>(bytes) {
        return values;
    }
    let mut values = Vec::with_capacity(num_elements);
    for chunk in bytes.chunks_exact(4) {
        values.push(f32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
    }
    values
}

fn parse_ne_f64(bytes: &[u8], num_elements: usize) -> Vec<f64> {
    if let Some(values) = try_aligned_copy::<f64>(bytes) {
        return values;
    }
    let mut values = Vec::with_capacity(num_elements);
    for chunk in bytes.chunks_exact(8) {
        values.push(f64::from_ne_bytes([
            chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
        ]));
    }
    values
}

fn parse_ne_f16(bytes: &[u8], num_elements: usize) -> Vec<f16> {
    if let Some(values) = try_aligned_copy::<u16>(bytes) {
        let mut out = Vec::with_capacity(num_elements);
        out.extend(values.into_iter().map(f16::from_bits));
        return out;
    }
    let mut values = Vec::with_capacity(num_elements);
    for chunk in bytes.chunks_exact(2) {
        values.push(f16::from_bits(u16::from_ne_bytes([chunk[0], chunk[1]])));
    }
    values
}

fn parse_ne_i32(bytes: &[u8], num_elements: usize) -> Vec<i32> {
    if let Some(values) = try_aligned_copy::<i32>(bytes) {
        return values;
    }
    let mut values = Vec::with_capacity(num_elements);
    for chunk in bytes.chunks_exact(4) {
        values.push(i32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
    }
    values
}

fn parse_ne_i64(bytes: &[u8], num_elements: usize) -> Vec<i64> {
    if let Some(values) = try_aligned_copy::<i64>(bytes) {
        return values;
    }
    let mut values = Vec::with_capacity(num_elements);
    for chunk in bytes.chunks_exact(8) {
        values.push(i64::from_ne_bytes([
            chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
        ]));
    }
    values
}

fn find_additional_input_by_name<'a>(
    additional_inputs: &'a [kapsl_engine_api::NamedTensor],
    name: &str,
) -> Option<&'a BinaryTensorPacket> {
    additional_inputs
        .iter()
        .find(|entry| entry.name == name)
        .map(|entry| &entry.tensor)
}

fn ensure_unique_additional_input_names(
    additional_inputs: &[kapsl_engine_api::NamedTensor],
) -> Result<(), EngineError> {
    for i in 0..additional_inputs.len() {
        for j in (i + 1)..additional_inputs.len() {
            if additional_inputs[i].name == additional_inputs[j].name {
                return Err(EngineError::InvalidInput {
                    message: format!(
                        "Duplicate additional input name: {}",
                        additional_inputs[i].name
                    ),
                    source: None,
                });
            }
        }
    }
    Ok(())
}

fn try_aligned_copy<T: Copy>(bytes: &[u8]) -> Option<Vec<T>> {
    // SAFETY: The concrete call sites only use plain numeric POD types.
    let (prefix, aligned, suffix) = unsafe { bytes.align_to::<T>() };
    if prefix.is_empty() && suffix.is_empty() {
        Some(aligned.to_vec())
    } else {
        None
    }
}

/// Validate an incoming BinaryTensorPacket and return the shape and a typed
/// vector if valid. This performs:
///  - dtype support checking
///  - shape -> element count computation
///  - buffer length validation (must equal element_count * dtype_size)
///  - safe byte->value conversion
fn validate_and_prepare_input(
    input: &kapsl_engine_api::BinaryTensorPacket,
) -> Result<(Vec<i64>, PreparedInput), EngineError> {
    // Compute number of elements from shape; treat empty shape as scalar (1 element)
    let num_elements: usize = if input.shape.is_empty() {
        1
    } else {
        // If any dimension is <= 0, reject as invalid shape
        let mut prod: usize = 1;
        for &d in &input.shape {
            if d <= 0 {
                return Err(EngineError::InvalidInput {
                    message: format!("Invalid shape dimension: {}", d),
                    source: None,
                });
            }
            prod = prod
                .checked_mul(d as usize)
                .ok_or_else(|| EngineError::InvalidInput {
                    message: "Shape multiplication overflow".to_string(),
                    source: None,
                })?;
        }
        prod
    };

    // Determine element size and branch by dtype
    match input.dtype {
        TensorDtype::Float32 => {
            validate_byte_len(input, num_elements, 4, "float32")?;
            let values = parse_ne_f32(&input.data, num_elements);
            Ok((input.shape.clone(), PreparedInput::F32(values)))
        }
        TensorDtype::Float64 => {
            validate_byte_len(input, num_elements, 8, "float64")?;
            let values = parse_ne_f64(&input.data, num_elements);
            Ok((input.shape.clone(), PreparedInput::F64(values)))
        }
        TensorDtype::Float16 => {
            validate_byte_len(input, num_elements, 2, "float16")?;
            let values = parse_ne_f16(&input.data, num_elements);
            Ok((input.shape.clone(), PreparedInput::F16(values)))
        }
        TensorDtype::Int32 => {
            validate_byte_len(input, num_elements, 4, "int32")?;
            let values = parse_ne_i32(&input.data, num_elements);
            Ok((input.shape.clone(), PreparedInput::I32(values)))
        }
        TensorDtype::Int64 => {
            validate_byte_len(input, num_elements, 8, "int64")?;
            let values = parse_ne_i64(&input.data, num_elements);
            Ok((input.shape.clone(), PreparedInput::I64(values)))
        }
        TensorDtype::Uint8 => {
            validate_byte_len(input, num_elements, 1, "uint8")?;
            Ok((input.shape.clone(), PreparedInput::U8(input.data.clone())))
        }
        other => Err(EngineError::InvalidInput {
            message: format!(
                "Unsupported dtype: {}. Supported: float32, float64, float16, int32, int64, uint8",
                other
            ),
            source: None,
        }),
    }
}

fn tensor_packet_to_session_input(
    input: &BinaryTensorPacket,
) -> Result<(Vec<usize>, SessionInputValue<'_>), EngineError> {
    let (shape_i64, prepared) = validate_and_prepare_input(input)?;
    let shape_usize = get_shape_usize(&shape_i64);

    let value: SessionInputValue = match prepared {
        PreparedInput::F32(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
        PreparedInput::F64(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
        PreparedInput::F16(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
        PreparedInput::I32(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
        PreparedInput::I64(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
        PreparedInput::U8(v) => Value::from_array((shape_usize.clone(), v)).map(|v| v.into()),
    }
    .map_err(|e| EngineError::InferenceError {
        reason: "Failed to create input tensor".to_string(),
        source: Some(Box::new(e)),
    })?;

    Ok((shape_usize, value))
}

fn run_inference_with_session(
    session: &mut Session,
    request: &InferenceRequest,
    metadata: &ModelMetadata,
    shape_usize: Vec<usize>,
    main_input_tensor: SessionInputValue<'_>,
) -> Result<BinaryTensorPacket, EngineError> {
    // We assume the first input maps to the provided input packet
    if metadata.input_names.is_empty() {
        return Err(EngineError::InferenceError {
            reason: "Model has no inputs defined".to_string(),
            source: None,
        });
    }

    let outputs = if metadata.input_names.len() == 1 && request.additional_inputs.is_empty() {
        session.run([main_input_tensor]).map_err(|e| {
            log::error!("ONNX Runtime inference error: {:?}", e);
            EngineError::InferenceError {
                reason: format!("Inference failed: {}", e),
                source: Some(Box::new(e)),
            }
        })?
    } else {
        // Prepare named input map only when required by multi-input models.
        let mut inputs: Vec<(Cow<'_, str>, SessionInputValue)> =
            Vec::with_capacity(metadata.input_names.len());
        inputs.push((
            Cow::Borrowed(metadata.input_names[0].as_str()),
            main_input_tensor,
        ));
        ensure_unique_additional_input_names(&request.additional_inputs)?;

        // Get batch size from main input (assume dim 0 is batch)
        let batch_size = if !shape_usize.is_empty() {
            shape_usize[0]
        } else {
            1
        };
        let seq_len = if shape_usize.len() > 1 {
            shape_usize[1]
        } else {
            1
        };

        // Fill other inputs
        // Workaround: ORT Value::from_array rejects 0-dimension (e.g. past_seq_len=0).
        // Try to use ndarray which might handle it better, or maybe it was just a vector check.
        // We set workaround length to 0 (correct behavior).
        let workaround_past_len = 0;

        for (i, name) in metadata.input_names.iter().enumerate().skip(1) {
            let shape_def = &metadata.input_shapes[i];
            if let Some(named_input) =
                find_additional_input_by_name(&request.additional_inputs, name)
            {
                let (_, value) = tensor_packet_to_session_input(named_input)?;
                inputs.push((Cow::Borrowed(name.as_str()), value));
                continue;
            }

            if name.contains("attention_mask") {
                // Attention mask: [batch, total_seq_len] -> 1s for active, 0 for past workaround
                // Total len = seq_len + workaround_past_len
                let total_len = seq_len + workaround_past_len;
                // Attention mask: [batch, total_seq_len] -> 1s for active
                let mask_shape = vec![batch_size as i64, total_len as i64];

                let mut mask_data = Vec::with_capacity(batch_size * total_len);
                for _ in 0..batch_size {
                    // Mask out the dummy past
                    mask_data.extend(std::iter::repeat_n(0i64, workaround_past_len));
                    // Active sequence
                    mask_data.extend(std::iter::repeat_n(1i64, seq_len));
                }

                log::debug!(
                    "Creating attention_mask tensor for {} with shape {:?}",
                    name,
                    mask_shape
                );

                let mask_tensor = Value::from_array((get_shape_usize(&mask_shape), mask_data))
                    .map_err(|e| EngineError::InferenceError {
                        reason: format!("Failed to create attention_mask tensor for {}", name),
                        source: Some(Box::new(e)),
                    })?;
                inputs.push((Cow::Borrowed(name.as_str()), mask_tensor.into()));
            } else if name.contains("position_ids") {
                let pos_shape = vec![batch_size as i64, seq_len as i64];
                let mut pos_data = Vec::with_capacity(batch_size * seq_len);
                // Position IDs should likely start after past? Or 0?
                // If we have dummy past at 0..1, then real tokens start at 0?
                // Actually if past is masked, it's effectively like it doesn't exist.
                // So we keep pos ids 0-based.
                for _ in 0..batch_size {
                    for s in 0..seq_len {
                        pos_data.push(s as i64);
                    }
                }
                let pos_tensor = Value::from_array((get_shape_usize(&pos_shape), pos_data))
                    .map_err(|e| EngineError::InferenceError {
                        reason: format!("Failed to create position_ids tensor for {}", name),
                        source: Some(Box::new(e)),
                    })?;
                inputs.push((Cow::Borrowed(name.as_str()), pos_tensor.into()));
            } else if name.starts_with("past_key_values") {
                let mut new_shape = Vec::new();
                new_shape.push(batch_size); // dim 0

                if shape_def.len() == 4 {
                    let dim1 = if shape_def[1] > 0 {
                        shape_def[1] as usize
                    } else {
                        1
                    };
                    new_shape.push(dim1);

                    new_shape.push(workaround_past_len); // dim 2: 0

                    let dim3 = if shape_def[3] > 0 {
                        shape_def[3] as usize
                    } else {
                        64
                    };
                    new_shape.push(dim3);

                    log::debug!("Creating KV tensor for {} with shape {:?}", name, new_shape);

                    let count: usize = new_shape.iter().product();
                    let empty_data: Vec<f16> = vec![f16::ZERO; count];

                    // Use ndarray to construct possibly 0-dim tensor
                    let kv_array = ArrayD::from_shape_vec(new_shape, empty_data).map_err(|e| {
                        EngineError::InferenceError {
                            reason: format!("Failed to create ndarray for {}: {:?}", name, e),
                            source: Some(Box::new(e)),
                        }
                    })?;

                    let kv_tensor =
                        Value::from_array(kv_array).map_err(|e| EngineError::InferenceError {
                            reason: format!(
                                "Failed to create empty KV tensor for {}: {:?}",
                                name, e
                            ),
                            source: Some(Box::new(e)),
                        })?;
                    inputs.push((Cow::Borrowed(name.as_str()), kv_tensor.into()));
                } else {
                    log::warn!(
                        "Skipping input {} due to unknown shape pattern {:?}",
                        name,
                        shape_def
                    );
                }
            } else {
                log::warn!(
                    "Skipping input {} as it is not recognized as auto-fillable",
                    name
                );
            }
        }

        session.run(inputs).map_err(|e| {
            log::error!("ONNX Runtime inference error: {:?}", e);
            EngineError::InferenceError {
                reason: format!("Inference failed: {}", e),
                source: Some(Box::new(e)),
            }
        })?
    };

    // For LLMs, we often get multiple outputs (logits + KV cache).
    // We currently only ignore the KV cache return values and just use the first output (logits).
    if outputs.len() > 1 {
        log::debug!(
            "Backend received {} outputs, using only the first one (logits)",
            outputs.len()
        );
    }

    // Handle output - try f32 first, otherwise return an error.
    let output_value = &outputs[0];
    let output_packet = if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<f32>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Float32,
            data: data.iter().flat_map(|&x| x.to_ne_bytes()).collect(),
        }
    } else if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<f64>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Float64,
            data: data.iter().flat_map(|&x| x.to_ne_bytes()).collect(),
        }
    } else if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<f16>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Float16,
            data: data
                .iter()
                .flat_map(|x| x.to_bits().to_ne_bytes())
                .collect(),
        }
    } else if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<i32>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Int32,
            data: data.iter().flat_map(|&x| x.to_ne_bytes()).collect(),
        }
    } else if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<i64>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Int64,
            data: data.iter().flat_map(|&x| x.to_ne_bytes()).collect(),
        }
    } else if let Ok((shape_ref, data)) = output_value.try_extract_tensor::<u8>() {
        BinaryTensorPacket {
            shape: shape_ref.to_vec(),
            dtype: TensorDtype::Uint8,
            data: data.to_vec(),
        }
    } else {
        return Err(EngineError::InferenceError {
            reason: "Failed to extract output tensor. Supported output dtypes: float32, float64, float16, int32, int64, uint8"
                .to_string(),
            source: None,
        });
    };

    Ok(output_packet)
}

#[async_trait]
impl Engine for OnnxBackend {
    // TODO: Extract session creation to a helper method to reduce duplication
    // TODO: Add better error messages with execution provider fallback information
    // TODO: Add capability checking before attempting to use hardware accelerators
    // TODO: Consider async loading for large models
    // TODO: Add progress callback for large model loads
    async fn load(&mut self, model_path: &Path) -> Result<(), EngineError> {
        let opt_level = self.get_opt_level();
        log::info!(
            "Loading ONNX model with optimization level: {:?} on provider {:?}",
            opt_level,
            self.provider
        );
        log::info!(
            "ORT memory config: memory_pattern={} disable_cpu_mem_arena={} session_buckets={} bucket_dim_granularity={} bucket_max_dims={} peak_concurrency_hint={:?}",
            self.memory_pattern,
            self.disable_cpu_mem_arena,
            self.max_bucket_sessions,
            self.bucket_dim_granularity,
            self.bucket_max_dims,
            self.peak_concurrency_hint
        );

        let session = self.create_session(model_path, opt_level)?;

        log::info!("Model Inputs:");
        for (i, input) in session.inputs().iter().enumerate() {
            log::info!("  Input {}: {} ({:?})", i, input.name(), input.dtype());
        }

        // Extract metadata
        let input_names: Vec<String> = session
            .inputs()
            .iter()
            .map(|i| i.name().to_string())
            .collect();
        let output_names: Vec<String> = session
            .outputs()
            .iter()
            .map(|o| o.name().to_string())
            .collect();

        let mut input_shapes = Vec::new();
        let mut input_dtypes = Vec::new();
        for input in session.inputs() {
            let (shape, dtype) = match input.dtype() {
                ort::value::ValueType::Tensor { ty, shape, .. } => {
                    (shape.iter().copied().collect(), map_ort_dtype(*ty))
                }
                _ => (vec![], None),
            };
            input_shapes.push(shape);
            input_dtypes.push(dtype);
        }

        let mut output_shapes = Vec::new();
        let mut output_dtypes = Vec::new();
        for output in session.outputs() {
            let (shape, dtype) = match output.dtype() {
                ort::value::ValueType::Tensor { ty, shape, .. } => {
                    (shape.iter().copied().collect(), map_ort_dtype(*ty))
                }
                _ => (vec![], None),
            };
            output_shapes.push(shape);
            output_dtypes.push(dtype);
        }

        let metadata = ModelMetadata {
            input_names,
            output_names,
            input_shapes,
            output_shapes,
            input_dtypes,
            output_dtypes,
        };

        // Store metadata
        if let Ok(mut meta_guard) = self.metadata.write() {
            *meta_guard = Some(metadata);
        }

        let mut session_guard = self.session.write().map_err(|_| EngineError::Backend {
            message: "Lock poisoned".to_string(),
            source: None,
        })?;
        *session_guard = Some(session);
        drop(session_guard);

        if let Ok(mut model_path_guard) = self.model_path.write() {
            *model_path_guard = Some(model_path.to_path_buf());
        }
        if let Ok(mut bucket_guard) = self.bucket_sessions.write() {
            bucket_guard.primary_bucket_key = None;
            bucket_guard.sessions.clear();
            bucket_guard.lru.clear();
        }

        // Reset warmup state
        self.warmed_up.store(false, Ordering::SeqCst);

        Ok(())
    }

    fn infer(&self, request: &InferenceRequest) -> Result<BinaryTensorPacket, EngineError> {
        let start_time = Instant::now();
        if let Some(session_id) = &request.session_id {
            log::debug!(
                "Processing request for session: {}",
                redact_session_id_for_log(session_id)
            );
        }

        let metadata = self.metadata.read().map_err(|_| EngineError::Backend {
            message: "Lock poisoned".to_string(),
            source: None,
        })?;
        let metadata = metadata
            .as_ref()
            .cloned()
            .ok_or(EngineError::ModelNotLoaded)?;

        // Validate and convert primary input.
        let (shape_usize, main_input_tensor) = tensor_packet_to_session_input(&request.input)?;
        let mut prepared_input = Some((shape_usize, main_input_tensor));

        let output_packet = if let Some(bucket_key) = self.bucket_key_for_request(request) {
            let use_primary = {
                let mut bucket_guard =
                    self.bucket_sessions
                        .write()
                        .map_err(|_| EngineError::Backend {
                            message: "Lock poisoned".to_string(),
                            source: None,
                        })?;
                let primary_key = bucket_guard
                    .primary_bucket_key
                    .get_or_insert_with(|| bucket_key.clone());
                *primary_key == bucket_key
            };

            if use_primary {
                let mut session_guard = self.session.write().map_err(|_| EngineError::Backend {
                    message: "Lock poisoned".to_string(),
                    source: None,
                })?;
                let session = session_guard.as_mut().ok_or(EngineError::ModelNotLoaded)?;
                let (shape_usize, main_input_tensor) = prepared_input
                    .take()
                    .ok_or_else(|| EngineError::backend("input already consumed".to_string()))?;
                run_inference_with_session(
                    session,
                    request,
                    &metadata,
                    shape_usize,
                    main_input_tensor,
                )?
            } else {
                let mut bucket_guard =
                    self.bucket_sessions
                        .write()
                        .map_err(|_| EngineError::Backend {
                            message: "Lock poisoned".to_string(),
                            source: None,
                        })?;
                let session = self.get_or_create_bucket_session(&mut bucket_guard, &bucket_key)?;
                let (shape_usize, main_input_tensor) = prepared_input
                    .take()
                    .ok_or_else(|| EngineError::backend("input already consumed".to_string()))?;
                run_inference_with_session(
                    session,
                    request,
                    &metadata,
                    shape_usize,
                    main_input_tensor,
                )?
            }
        } else {
            let mut session_guard = self.session.write().map_err(|_| EngineError::Backend {
                message: "Lock poisoned".to_string(),
                source: None,
            })?;
            let session = session_guard.as_mut().ok_or(EngineError::ModelNotLoaded)?;
            let (shape_usize, main_input_tensor) = prepared_input
                .take()
                .ok_or_else(|| EngineError::backend("input already consumed".to_string()))?;
            run_inference_with_session(session, request, &metadata, shape_usize, main_input_tensor)?
        };

        // Update metrics
        let duration = start_time.elapsed().as_secs_f64();
        if let Ok(mut metrics) = self.metrics.write() {
            metrics.inference_time = duration;
            // We can't easily get exact memory usage per inference from ONNX Runtime easily here without allocator hooks,
            // so we leave it as is or update if we had a way.
        }

        // Mark as warmed up
        self.warmed_up.store(true, Ordering::SeqCst);

        Ok(output_packet)
    }

    // TODO: Implement proper streaming for LLM models with token-by-token generation
    // TODO: This is a placeholder - real streaming should yield tokens as they're generated
    fn infer_stream(
        &self,
        request: &InferenceRequest,
    ) -> std::pin::Pin<
        Box<dyn futures::stream::Stream<Item = Result<BinaryTensorPacket, EngineError>> + Send>,
    > {
        // Call infer immediately to avoid lifetime issues
        let result = self.infer(request);
        // Wrap the single result in a stream using futures::stream::once
        Box::pin(futures::stream::once(async move { result }))
    }

    // TODO: Add proper cleanup (free GPU memory, release resources)
    // TODO: Log unload operations for debugging
    fn unload(&mut self) {
        if let Ok(mut session_guard) = self.session.write() {
            *session_guard = None;
        }
        if let Ok(mut bucket_guard) = self.bucket_sessions.write() {
            bucket_guard.primary_bucket_key = None;
            bucket_guard.sessions.clear();
            bucket_guard.lru.clear();
        }
        if let Ok(mut model_path_guard) = self.model_path.write() {
            *model_path_guard = None;
        }
        if let Ok(mut meta_guard) = self.metadata.write() {
            *meta_guard = None;
        }
    }

    fn metrics(&self) -> kapsl_engine_api::EngineMetrics {
        if let Ok(metrics) = self.metrics.read() {
            metrics.clone()
        } else {
            kapsl_engine_api::EngineMetrics::default()
        }
    }

    fn health_check(&self) -> Result<(), EngineError> {
        // Check if session is loaded and lock is not poisoned
        let session_guard = self.session.read().map_err(|_| EngineError::Backend {
            message: "Session lock poisoned".to_string(),
            source: None,
        })?;
        let bucket_guard = self
            .bucket_sessions
            .read()
            .map_err(|_| EngineError::Backend {
                message: "Session cache lock poisoned".to_string(),
                source: None,
            })?;

        if session_guard.is_some() || !bucket_guard.sessions.is_empty() {
            Ok(())
        } else {
            Err(EngineError::ModelNotLoaded)
        }
    }

    fn model_info(&self) -> Option<EngineModelInfo> {
        let metadata_guard = self.metadata.read().ok()?;
        let metadata = metadata_guard.as_ref()?;
        Some(EngineModelInfo {
            input_names: metadata.input_names.clone(),
            output_names: metadata.output_names.clone(),
            input_shapes: metadata.input_shapes.clone(),
            output_shapes: metadata.output_shapes.clone(),
            input_dtypes: metadata
                .input_dtypes
                .iter()
                .map(|dtype| {
                    dtype
                        .as_ref()
                        .map(TensorDtype::as_str)
                        .unwrap_or("unknown")
                        .to_string()
                })
                .collect(),
            output_dtypes: metadata
                .output_dtypes
                .iter()
                .map(|dtype| {
                    dtype
                        .as_ref()
                        .map(TensorDtype::as_str)
                        .unwrap_or("unknown")
                        .to_string()
                })
                .collect(),
            framework: Some("onnx".to_string()),
            model_version: None,
            peak_concurrency: self.peak_concurrency_hint,
        })
    }
}

fn get_shape_usize(shape: &[i64]) -> Vec<usize> {
    shape.iter().map(|&v| v as usize).collect()
}

#[path = "onnx_tests.rs"]
mod onnx_tests;