embellama 0.10.0

High-performance Rust library for generating text embeddings using llama-cpp
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
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
// Copyright 2025 Embellama Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Embedding engine module for the embellama library.
//!
//! This module provides the main `EmbeddingEngine` struct which serves as
//! the primary interface for the library, managing model lifecycle and
//! providing high-level embedding generation APIs.

use crate::batch::BatchProcessorBuilder;
use crate::cache::embedding_cache::EmbeddingCache;
use crate::cache::prefix_cache::PrefixCache;
use crate::cache::token_cache::TokenCache;
use crate::cache::{CacheStats, CacheStore};
use crate::config::{EngineConfig, NormalizationMode, TruncateTokens};
use crate::error::{Error, Result};
use crate::model::EmbeddingModel;
use llama_cpp_2::llama_backend::LlamaBackend;
use parking_lot::RwLock;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use tracing::{debug, info, instrument};

// Global singleton instance of the engine
static INSTANCE: RwLock<Option<Arc<Mutex<EmbeddingEngine>>>> = RwLock::new(None);

// Lock to protect singleton initialization
static INIT_LOCK: Mutex<()> = Mutex::new(());

// Global singleton backend instance
static BACKEND: OnceLock<Arc<Mutex<LlamaBackend>>> = OnceLock::new();

// Thread-local storage for models due to !Send constraint of LlamaContext
thread_local! {
    static THREAD_MODELS: RefCell<HashMap<String, EmbeddingModel>> = RefCell::new(HashMap::new());
}

// Thread-local reference to the token cache for fast access
thread_local! {
    static THREAD_TOKEN_CACHE: RefCell<Option<Arc<TokenCache>>> = const { RefCell::new(None) };
}

/// The main entry point for the embellama library.
///
/// `EmbeddingEngine` manages the lifecycle of embedding models and provides
/// a high-level API for generating embeddings. It supports loading multiple
/// models and switching between them.
///
/// # Important
///
/// Due to the `!Send` constraint of `LlamaContext`, each thread maintains
/// its own copy of loaded models. This means:
/// - Models are loaded per-thread when first accessed
/// - Memory usage scales with number of threads × number of models
/// - Model loading may happen multiple times across threads
///
/// # Example
///
/// ```ignore
/// use embellama::{EmbeddingEngine, EngineConfig};
///
/// let config = EngineConfig::builder()
///     .with_model_path("path/to/model.gguf")
///     .with_model_name("my-model")
///     .build()?;
///
/// let engine = EmbeddingEngine::new(config)?;
/// let embedding = engine.embed("my-model", "Hello, world!")?;
/// ```
pub struct EmbeddingEngine {
    /// Shared reference to the llama backend instance
    backend: Arc<Mutex<LlamaBackend>>,
    /// Registry of model configurations
    model_configs: Arc<RwLock<HashMap<String, EngineConfig>>>,
    /// Default model name if none specified
    default_model: Option<String>,
    /// Embedding cache for performance optimization
    embedding_cache: Option<Arc<EmbeddingCache>>,
    /// Token cache for caching tokenization results
    token_cache: Option<Arc<TokenCache>>,
    /// Prefix cache for KV cache optimization
    prefix_cache: Option<Arc<PrefixCache>>,
}

impl EmbeddingEngine {
    /// Gets or creates the singleton `LlamaBackend` instance.
    ///
    /// This ensures only one backend is created per process, avoiding the
    /// `BackendAlreadyInitialized` error when creating multiple engines.
    fn get_or_create_backend() -> Result<Arc<Mutex<LlamaBackend>>> {
        if let Some(backend) = BACKEND.get() {
            return Ok(Arc::clone(backend));
        }

        // Initialize the backend for the first time
        let mut backend = LlamaBackend::init().map_err(|e| {
            let error_str = format!("{e}");
            if error_str.contains("BackendAlreadyInitialized") {
                Error::ConfigurationError {
                    message: "LlamaBackend already initialized. This is an internal error."
                        .to_string(),
                }
            } else {
                Error::ModelInitError {
                    message: "Failed to initialize llama backend".to_string(),
                    source: Some(anyhow::anyhow!("{e}")),
                }
            }
        })?;
        backend.void_logs();

        let backend_arc = Arc::new(Mutex::new(backend));
        // Try to set it, but if another thread beat us to it, use theirs
        match BACKEND.set(Arc::clone(&backend_arc)) {
            Ok(()) => Ok(backend_arc),
            Err(_) => Ok(Arc::clone(BACKEND.get().unwrap())),
        }
    }

    /// Gets or initializes the singleton embedding engine with the given configuration.
    ///
    /// If the engine is already initialized, returns the existing instance.
    /// The configuration is only used for the first initialization.
    ///
    /// # Arguments
    ///
    /// * `config` - The engine configuration (used only on first call)
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the engine instance or an error.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The configuration is invalid (on first initialization)
    /// - Model loading fails (on first initialization)
    /// - The initialization lock is poisoned
    #[instrument(skip(config), fields(model_name = %config.model_config.model_name))]
    pub fn get_or_init(config: EngineConfig) -> Result<Arc<Mutex<Self>>> {
        // Fast path: check if already initialized
        {
            let instance_guard = INSTANCE.read();
            if let Some(ref instance) = *instance_guard {
                debug!("Returning existing engine instance");
                return Ok(Arc::clone(instance));
            }
        }

        // Slow path: initialize the singleton
        let _lock = INIT_LOCK.lock().map_err(|_| Error::LockPoisoned)?;

        // Double-check after acquiring lock
        {
            let instance_guard = INSTANCE.read();
            if let Some(ref instance) = *instance_guard {
                debug!("Returning existing engine instance (after lock)");
                return Ok(Arc::clone(instance));
            }
        }

        // Create new instance
        info!("Initializing singleton embedding engine");
        let engine = Self::new_internal(config)?;
        let arc_engine = Arc::new(Mutex::new(engine));

        // Store the instance
        {
            let mut instance_guard = INSTANCE.write();
            *instance_guard = Some(Arc::clone(&arc_engine));
        }

        Ok(arc_engine)
    }

    /// Gets the existing engine instance if it has been initialized.
    ///
    /// # Returns
    ///
    /// Returns `Some(engine)` if initialized, `None` otherwise.
    pub fn instance() -> Option<Arc<Mutex<Self>>> {
        let instance_guard = INSTANCE.read();
        instance_guard.as_ref().map(Arc::clone)
    }

    /// Resets the singleton instance (test-only).
    ///
    /// This method is only available in test builds and should be called
    /// at the start of tests that need a fresh engine state.
    ///
    /// # Safety
    ///
    /// This method should only be called when no other code is using the engine.
    /// Tests using this must be marked with `#[serial]` to prevent parallel execution.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock cannot be acquired
    #[cfg(test)]
    pub fn reset() {
        let _lock = INIT_LOCK.lock().unwrap();

        // Clear thread-local models first
        THREAD_MODELS.with(|models| {
            models.borrow_mut().clear();
        });

        // Take and drop the instance to ensure backend is dropped
        let mut instance_guard = INSTANCE.write();
        if let Some(instance) = instance_guard.take() {
            // Check if we're the only reference
            if Arc::strong_count(&instance) > 1 {
                // Other references exist - this is likely a test error
                // Put it back and panic
                *instance_guard = Some(instance);
                panic!(
                    "Cannot reset engine: other references exist. Ensure tests are marked with #[serial]"
                );
            }
            // Explicitly drop the instance (and its backend)
            drop(instance);
            debug!("Dropped engine instance and backend");
        }

        // instance_guard is now None
        info!("Engine singleton reset - backend dropped");
    }

    /// Convenience method for tests to get a fresh instance.
    ///
    /// Resets the singleton and initializes with the given config.
    ///
    /// # Errors
    ///
    /// Returns an error if engine creation fails
    #[cfg(test)]
    pub fn fresh_instance(config: EngineConfig) -> Result<Arc<Mutex<Self>>> {
        Self::reset();
        Self::get_or_init(config)
    }

    /// Internal method to create a new engine instance.
    ///
    /// This is the actual implementation, separated from the singleton logic.
    fn new_internal(config: EngineConfig) -> Result<Self> {
        // Validate configuration
        config.validate()?;

        let model_name = config.model_config.model_name.clone();
        info!("Initializing embedding engine with model: {}", model_name);

        // Get or create the shared backend
        let backend = Self::get_or_create_backend()?;
        info!("Llama backend ready");

        // Initialize caches if enabled
        let (embedding_cache, token_cache, prefix_cache) = if let Some(cache_config) = &config.cache
        {
            if cache_config.enabled {
                info!(
                    "Initializing embedding cache with {} max entries",
                    cache_config.embedding_cache_size
                );
                let embedding_cache = Some(Arc::new(EmbeddingCache::new(
                    cache_config.embedding_cache_size as u64,
                    cache_config.ttl_seconds,
                )));

                info!(
                    "Initializing token cache with {} max entries",
                    cache_config.token_cache_size
                );
                let token_cache = Some(Arc::new(TokenCache::with_ttl(
                    cache_config.token_cache_size,
                    Some(cache_config.ttl_seconds),
                )));

                // Initialize prefix cache if enabled
                let prefix_cache = if cache_config.prefix_cache_enabled {
                    info!(
                        "Initializing prefix cache with {} max sessions",
                        cache_config.prefix_cache_size
                    );
                    Some(Arc::new(
                        PrefixCache::new(
                            cache_config.prefix_cache_size,
                            cache_config.ttl_seconds,
                            5,    // Frequency threshold for automatic caching
                            None, // No persistent storage for now
                        )
                        .map_err(|e| Error::ConfigurationError {
                            message: format!("Failed to create prefix cache: {e}"),
                        })?,
                    ))
                } else {
                    None
                };

                (embedding_cache, token_cache, prefix_cache)
            } else {
                (None, None, None)
            }
        } else {
            (None, None, None)
        };

        // Create the engine with the initial model config
        let mut model_configs = HashMap::new();
        model_configs.insert(model_name.clone(), config);

        let engine = Self {
            backend,
            model_configs: Arc::new(RwLock::new(model_configs)),
            default_model: Some(model_name.clone()),
            embedding_cache,
            token_cache: token_cache.clone(),
            prefix_cache,
        };

        // Store token cache reference in thread-local storage
        if let Some(ref cache) = token_cache {
            THREAD_TOKEN_CACHE.with(|tc| {
                *tc.borrow_mut() = Some(Arc::clone(cache));
            });
        }

        // Load the model in the current thread
        engine.ensure_model_loaded(&model_name)?;

        info!("Embedding engine initialized successfully");
        Ok(engine)
    }

    /// Creates a new embedding engine with the given configuration.
    ///
    /// **Note**: This now uses the singleton pattern internally. Use `get_or_init()`
    /// for explicit singleton access.
    ///
    /// # Arguments
    ///
    /// * `config` - The engine configuration
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the engine or an error.
    ///
    /// # Errors
    ///
    /// Returns an error if model loading fails
    pub fn new(config: EngineConfig) -> Result<Self> {
        // Use the internal method directly for backward compatibility
        // This allows tests to create instances without singleton
        Self::new_internal(config)
    }

    /// Loads a model with the given configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The model configuration
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - A model with the same name is already loaded
    /// - Model loading fails
    #[instrument(skip(self, config), fields(model_name = %config.model_config.model_name))]
    pub fn load_model(&mut self, config: EngineConfig) -> Result<()> {
        // Validate configuration
        config.validate()?;

        let model_name = config.model_config.model_name.clone();

        // Check if model already exists
        {
            let configs = self.model_configs.read();
            if configs.contains_key(&model_name) {
                return Err(Error::ConfigurationError {
                    message: format!("Model '{model_name}' is already loaded"),
                });
            }
        }

        // Add configuration to registry
        {
            let mut configs = self.model_configs.write();
            configs.insert(model_name.clone(), config);
        }

        // Set as default if it's the first model
        if self.default_model.is_none() {
            self.default_model = Some(model_name.clone());
        }

        info!("Model '{}' configuration added to registry", model_name);
        Ok(())
    }

    /// Unregisters a model from the registry, preventing future loads.
    ///
    /// This removes the model configuration from the registry but does not
    /// affect already-loaded model instances in threads.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to unregister
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found in the registry.
    #[instrument(skip(self))]
    pub fn unregister_model(&mut self, model_name: &str) -> Result<()> {
        // Remove from config registry
        {
            let mut configs = self.model_configs.write();
            if !configs.contains_key(model_name) {
                return Err(Error::ModelNotFound {
                    name: model_name.to_string(),
                });
            }
            configs.remove(model_name);
        }

        // Update default model if needed
        if self.default_model.as_ref() == Some(&model_name.to_string()) {
            let configs = self.model_configs.read();
            self.default_model = configs.keys().next().cloned();
        }

        info!("Model '{}' unregistered from config registry", model_name);
        Ok(())
    }

    /// Drops a model from the current thread's cache.
    ///
    /// This removes the model instance from the current thread but keeps
    /// its configuration in the registry, allowing it to be reloaded later.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to drop from thread
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not registered.
    #[instrument(skip(self))]
    pub fn drop_model_from_thread(&self, model_name: &str) -> Result<()> {
        // First check if model is registered
        {
            let configs = self.model_configs.read();
            if !configs.contains_key(model_name) {
                return Err(Error::ModelNotFound {
                    name: model_name.to_string(),
                });
            }
        }

        // Remove from thread-local storage
        THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            if models.remove(model_name).is_some() {
                info!("Model '{}' dropped from current thread", model_name);
            } else {
                debug!("Model '{}' was not loaded in current thread", model_name);
            }
        });

        Ok(())
    }

    /// Unloads a model completely (unregisters and drops from thread).
    ///
    /// This is a convenience method that combines `unregister_model` and
    /// `drop_model_from_thread`. It maintains backward compatibility with
    /// the original `unload_model` behavior.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to unload
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found.
    #[instrument(skip(self))]
    pub fn unload_model(&mut self, model_name: &str) -> Result<()> {
        // Drop from current thread first (while config still exists)
        self.drop_model_from_thread(model_name)?;

        // Then unregister from config
        self.unregister_model(model_name)?;

        info!("Model '{}' fully unloaded", model_name);
        Ok(())
    }

    /// Ensures a model is loaded in the current thread.
    ///
    /// This is an internal method that handles thread-local model loading.
    fn ensure_model_loaded(&self, model_name: &str) -> Result<()> {
        THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();

            // Check if model is already loaded in this thread
            if models.contains_key(model_name) {
                debug!("Model '{}' already loaded in current thread", model_name);
                return Ok(());
            }

            // Get configuration from registry
            let config = {
                let configs = self.model_configs.read();
                configs
                    .get(model_name)
                    .ok_or_else(|| Error::ModelNotFound {
                        name: model_name.to_string(),
                    })?
                    .clone()
            };

            info!("Loading model '{}' in current thread", model_name);

            // Use the model configuration from EngineConfig
            let backend_guard = self.backend.lock().map_err(|_| Error::LockPoisoned)?;
            let model = EmbeddingModel::new(&backend_guard, &config.model_config)?;
            drop(backend_guard); // Release lock as soon as we're done

            // Update the stored engine config with resolved pooling/normalization values
            // so that cache keys and other downstream reads reflect the actual model semantics.
            {
                let resolved = model.config();
                let mut configs = self.model_configs.write();
                if let Some(stored) = configs.get_mut(model_name) {
                    stored.model_config.pooling_strategy = resolved.pooling_strategy;
                    stored.model_config.normalization_mode = resolved.normalization_mode;
                }
            }

            // Store in thread-local map
            models.insert(model_name.to_string(), model);

            info!(
                "Model '{}' loaded successfully in current thread",
                model_name
            );
            Ok(())
        })
    }

    /// Generates an embedding for a single text using the specified model.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to use (or None for default)
    /// * `text` - The text to generate embeddings for
    ///
    /// # Returns
    ///
    /// Returns a vector of f32 values representing the embedding.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The model is not found
    /// - Embedding generation fails
    ///
    /// # Panics
    ///
    /// This function may panic if:
    /// - The model configuration is not found after validation (internal inconsistency)
    #[instrument(skip(self, text), fields(text_len = text.len()))]
    pub fn embed(&self, model_name: Option<&str>, text: &str) -> Result<Vec<f32>> {
        // Determine which model to use
        let model_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        // Get model config (needed for both caching and truncation)
        let config = self
            .model_configs
            .read()
            .get(&model_name)
            .ok_or_else(|| Error::ModelNotFound {
                name: model_name.clone(),
            })?
            .clone();

        // Get truncation setting from config
        let truncate = config
            .embedding
            .as_ref()
            .map_or(TruncateTokens::No, |e| e.truncate_tokens);

        // Check cache first if enabled
        if let Some(cache) = &self.embedding_cache {
            // Compute cache key
            let key = EmbeddingCache::compute_key(
                text,
                &model_name,
                config.model_config.pooling_strategy.unwrap_or_default(),
                config.model_config.normalization_mode.unwrap_or_default(),
            );

            // Check cache
            if let Some(embedding) = cache.get(&key) {
                debug!("Cache hit for text of length {}", text.len());
                return Ok(embedding);
            }
            debug!("Cache miss for text of length {}", text.len());
        }

        // Ensure model is loaded in current thread
        self.ensure_model_loaded(&model_name)?;

        // Generate embedding using thread-local model with token cache
        let embedding = THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            let model = models
                .get_mut(&model_name)
                .ok_or_else(|| Error::ModelNotFound {
                    name: model_name.clone(),
                })?;

            // Check prefix cache if enabled
            if let Some(ref prefix_cache) = self.prefix_cache {
                // First tokenize to check for prefix matches
                let tokens = model.tokenize(text)?;
                let token_ids: Vec<i32> = tokens.iter().map(|t| t.0).collect();

                // Try to find a matching prefix
                if let Some((_prefix_len, _session_data)) =
                    prefix_cache.find_prefix_session(text, &token_ids)
                {
                    debug!("Prefix cache hit for text of length {}", text.len());
                    // Use the prefix-aware embedding generation
                    // Pass the whole prefix_cache - the method will find the session internally
                    return THREAD_TOKEN_CACHE.with(|tc| {
                        let cache_ref = tc.borrow();
                        model.generate_embedding_with_prefix(
                            text,
                            Some(prefix_cache.as_ref()),
                            cache_ref.as_deref(),
                            truncate,
                        )
                    });
                }

                // Analyze for future caching opportunities
                // > TODO: Implement automatic prefix detection and registration
                // This would require tracking patterns over time
            }

            // Get thread-local token cache reference
            THREAD_TOKEN_CACHE.with(|tc| {
                let cache_ref = tc.borrow();
                if let Some(ref cache) = *cache_ref {
                    model.generate_embedding_cached(text, Some(cache.as_ref()), truncate)
                } else {
                    model.generate_embedding(text)
                }
            })
        })?;

        // Update cache with result if enabled
        if let Some(cache) = &self.embedding_cache {
            // Get model config again for cache key (already validated above)
            let config = self.model_configs.read();
            let config = config.get(&model_name).unwrap();

            let key = EmbeddingCache::compute_key(
                text,
                &model_name,
                config.model_config.pooling_strategy.unwrap_or_default(),
                config.model_config.normalization_mode.unwrap_or_default(),
            );

            cache.insert(key, embedding.clone());
            debug!("Cached embedding for text of length {}", text.len());
        }

        Ok(embedding)
    }

    /// Generates per-token (multi-vector) embeddings for a single text.
    ///
    /// Returns one embedding vector per token, suitable for ColBERT-style late
    /// interaction reranking. Each vector is individually normalized.
    ///
    /// This method does not use the embedding cache (since multi-vector results
    /// have a different shape than cached single-vector embeddings).
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to use (or None for default)
    /// * `text` - The text to generate per-token embeddings for
    ///
    /// # Returns
    ///
    /// Returns a vector of embedding vectors, one per token.
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found or embedding generation fails.
    #[instrument(skip(self, text), fields(text_len = text.len()))]
    pub fn embed_multi(&self, model_name: Option<&str>, text: &str) -> Result<Vec<Vec<f32>>> {
        let model_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        let config = self
            .model_configs
            .read()
            .get(&model_name)
            .ok_or_else(|| Error::ModelNotFound {
                name: model_name.clone(),
            })?
            .clone();

        let truncate = config
            .embedding
            .as_ref()
            .map_or(TruncateTokens::No, |e| e.truncate_tokens);

        self.ensure_model_loaded(&model_name)?;

        THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            let model = models
                .get_mut(&model_name)
                .ok_or_else(|| Error::ModelNotFound {
                    name: model_name.clone(),
                })?;

            THREAD_TOKEN_CACHE.with(|tc| {
                let cache_ref = tc.borrow();
                model.generate_multi_embedding(text, cache_ref.as_deref(), truncate)
            })
        })
    }

    /// Generates per-token (multi-vector) embeddings for a batch of texts.
    ///
    /// Returns one `Vec<Vec<f32>>` per input text — each containing one embedding
    /// vector per token. Suitable for ColBERT-style late interaction reranking.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to use (or None for default)
    /// * `texts` - Texts to generate per-token embeddings for
    ///
    /// # Returns
    ///
    /// Returns a vector of multi-vector embeddings, one per input text.
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found or embedding generation fails.
    #[instrument(skip(self, texts), fields(batch_size = texts.len()))]
    pub fn embed_batch_multi(
        &self,
        model_name: Option<&str>,
        texts: &[&str],
    ) -> Result<Vec<Vec<Vec<f32>>>> {
        let model_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        let config = self
            .model_configs
            .read()
            .get(&model_name)
            .ok_or_else(|| Error::ModelNotFound {
                name: model_name.clone(),
            })?
            .clone();

        let truncate = config
            .embedding
            .as_ref()
            .map_or(TruncateTokens::No, |e| e.truncate_tokens);

        self.ensure_model_loaded(&model_name)?;

        THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            let model = models
                .get_mut(&model_name)
                .ok_or_else(|| Error::ModelNotFound {
                    name: model_name.clone(),
                })?;

            // Tokenize all texts
            let token_sequences: Vec<Vec<_>> = texts
                .iter()
                .map(|text| model.tokenize(text))
                .collect::<Result<Vec<_>>>()?;

            model.process_batch_tokens_multi(&token_sequences, truncate)
        })
    }

    /// Generates embeddings for a batch of texts using the specified model.
    ///
    /// This method processes multiple texts efficiently using parallel processing
    /// for tokenization and post-processing while respecting the single-threaded
    /// constraint of model inference.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to use (or None for default)
    /// * `texts` - A vector of texts to generate embeddings for
    ///
    /// # Returns
    ///
    /// Returns a vector of embedding vectors.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The model is not found
    /// - Any embedding generation fails
    ///
    /// # Panics
    ///
    /// This function may panic if:
    /// - A cached result is unexpectedly None after successful cache population
    #[instrument(skip(self, texts), fields(batch_size = texts.len()))]
    pub fn embed_batch(&self, model_name: Option<&str>, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        // Determine which model to use
        let model_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        // Get model configuration
        let config = self
            .model_configs
            .read()
            .get(&model_name)
            .ok_or_else(|| Error::ModelNotFound {
                name: model_name.clone(),
            })?
            .clone();

        // Get truncation setting from config
        let truncate = config
            .embedding
            .as_ref()
            .map_or(TruncateTokens::No, |e| e.truncate_tokens);

        // If cache is enabled, check for cached embeddings
        let mut results = Vec::with_capacity(texts.len());
        let mut uncached_indices = Vec::new();
        let mut uncached_texts = Vec::new();

        if let Some(cache) = &self.embedding_cache {
            for (i, text) in texts.iter().enumerate() {
                let key = EmbeddingCache::compute_key(
                    text,
                    &model_name,
                    config.model_config.pooling_strategy.unwrap_or_default(),
                    config.model_config.normalization_mode.unwrap_or_default(),
                );

                if let Some(embedding) = cache.get(&key) {
                    debug!("Batch cache hit for text {} of length {}", i, text.len());
                    results.push(Some(embedding));
                } else {
                    debug!("Batch cache miss for text {} of length {}", i, text.len());
                    results.push(None);
                    uncached_indices.push(i);
                    uncached_texts.push(*text);
                }
            }

            // If all are cached, return early
            if uncached_texts.is_empty() {
                debug!("All {} texts found in cache", texts.len());
                return Ok(results.into_iter().map(|r| r.unwrap()).collect());
            }

            debug!(
                "Processing {} uncached texts out of {}",
                uncached_texts.len(),
                texts.len()
            );
        } else {
            // No cache, process all texts
            uncached_texts = texts.to_vec();
        }

        // Ensure model is loaded in current thread
        self.ensure_model_loaded(&model_name)?;

        // Create batch processor with model configuration
        let batch_processor = BatchProcessorBuilder::default()
            .with_max_batch_size(64) // Default batch size
            .with_normalization(
                config.model_config.normalization_mode.unwrap_or_default()
                    != NormalizationMode::None,
            )
            .with_pooling_strategy(config.model_config.pooling_strategy.unwrap_or_default())
            .build();

        // Process uncached texts using the BatchProcessor
        let new_embeddings = THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            let model = models
                .get_mut(&model_name)
                .ok_or_else(|| Error::ModelNotFound {
                    name: model_name.clone(),
                })?;

            batch_processor.process_batch(model, &uncached_texts, truncate)
        })?;

        // Update cache and results
        if let Some(cache) = &self.embedding_cache {
            for (idx, embedding) in new_embeddings.into_iter().enumerate() {
                let text = uncached_texts[idx];
                let key = EmbeddingCache::compute_key(
                    text,
                    &model_name,
                    config.model_config.pooling_strategy.unwrap_or_default(),
                    config.model_config.normalization_mode.unwrap_or_default(),
                );

                cache.insert(key, embedding.clone());

                // Update results at the correct position
                let original_idx = uncached_indices[idx];
                results[original_idx] = Some(embedding);
            }

            // Convert results to final output
            Ok(results.into_iter().map(|r| r.unwrap()).collect())
        } else {
            // No cache, return new embeddings directly
            Ok(new_embeddings)
        }
    }

    /// Reranks documents against a query using a cross-encoder reranking model.
    ///
    /// The model must be configured with `PoolingStrategy::Rank`. Each document
    /// is scored against the query, and results are returned sorted by relevance
    /// (descending).
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the reranking model (or None for default)
    /// * `query` - The query text
    /// * `documents` - Documents to rerank
    /// * `top_n` - Optional limit on number of results returned
    /// * `normalize` - Whether to apply sigmoid normalization to \[0, 1\]
    ///
    /// # Returns
    ///
    /// Returns a vector of `RerankResult` sorted by relevance score (descending).
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found, not configured for reranking,
    /// or inference fails.
    #[instrument(skip(self, query, documents), fields(query_len = query.len(), n_docs = documents.len()))]
    pub fn rerank(
        &self,
        model_name: Option<&str>,
        query: &str,
        documents: &[&str],
        top_n: Option<usize>,
        normalize: bool,
    ) -> Result<Vec<crate::config::RerankResult>> {
        let model_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        let config = self
            .model_configs
            .read()
            .get(&model_name)
            .ok_or_else(|| Error::ModelNotFound {
                name: model_name.clone(),
            })?
            .clone();

        let truncate = config
            .embedding
            .as_ref()
            .map_or(TruncateTokens::No, |e| e.truncate_tokens);

        self.ensure_model_loaded(&model_name)?;

        let raw_scores = THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();
            let model = models
                .get_mut(&model_name)
                .ok_or_else(|| Error::ModelNotFound {
                    name: model_name.clone(),
                })?;

            model.generate_rerank_scores_batch(query, documents, truncate)
        })?;

        let mut results: Vec<crate::config::RerankResult> = raw_scores
            .into_iter()
            .enumerate()
            .map(|(index, score)| {
                let relevance_score = if normalize {
                    // Sigmoid normalization: 1 / (1 + e^(-x))
                    1.0 / (1.0 + (-score).exp())
                } else {
                    score
                };
                crate::config::RerankResult {
                    index,
                    relevance_score,
                }
            })
            .collect();

        // Reject NaN scores that would corrupt sort order
        for r in &results {
            if r.relevance_score.is_nan() {
                return Err(Error::EmbeddingGenerationError {
                    message: "Model produced NaN relevance score".to_string(),
                    source: None,
                });
            }
        }

        // Sort by relevance score descending (total_cmp provides well-defined ordering)
        results.sort_by(|a, b| b.relevance_score.total_cmp(&a.relevance_score));

        // Apply top_n filtering
        if let Some(n) = top_n {
            results.truncate(n);
        }

        Ok(results)
    }

    /// Lists all currently loaded models.
    ///
    /// Note: This returns models registered in the engine, not necessarily
    /// loaded in the current thread.
    ///
    /// # Returns
    ///
    /// Returns a vector of model names.
    pub fn list_models(&self) -> Vec<String> {
        let configs = self.model_configs.read();
        configs.keys().cloned().collect()
    }

    /// Get model configurations with their metadata.
    ///
    /// Returns a vector of tuples containing (`model_name`, `context_size`).
    pub fn get_model_details(&self) -> Vec<(String, Option<u32>)> {
        let configs = self.model_configs.read();
        configs
            .iter()
            .map(|(name, config)| {
                // Get context_size from the model configuration
                let context_size = config
                    .model_config
                    .context_size
                    .or(config.model_config.n_ctx);
                (name.clone(), context_size)
            })
            .collect()
    }

    /// Gets cache statistics if caching is enabled.
    ///
    /// # Returns
    ///
    /// Returns cache statistics if caching is enabled, None otherwise.
    pub fn get_cache_stats(&self) -> Option<CacheStats> {
        self.embedding_cache.as_ref().map(|cache| cache.stats())
    }

    /// Clears the embedding cache if enabled.
    ///
    /// This removes all cached embeddings and resets statistics.
    pub fn clear_cache(&self) {
        if let Some(cache) = &self.embedding_cache {
            cache.clear();
            info!("Embedding cache cleared");
        }
        if let Some(cache) = &self.token_cache {
            cache.clear();
            info!("Token cache cleared");
        }
        if let Some(cache) = &self.prefix_cache {
            cache.clear();
            info!("Prefix cache cleared");
        }
    }

    /// Warms up the cache by pre-computing embeddings for the given texts.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The model to use (None uses default)
    /// * `texts` - The texts to pre-compute embeddings for
    ///
    /// # Returns
    ///
    /// Returns Ok(()) if successful, or an error if pre-computation fails.
    ///
    /// # Errors
    ///
    /// Returns an error if embedding generation fails for any text.
    pub fn warm_cache(&self, model_name: Option<&str>, texts: &[&str]) -> Result<()> {
        if self.embedding_cache.is_none() {
            return Ok(()); // No-op if cache is disabled
        }

        info!("Warming cache with {} texts", texts.len());
        for text in texts {
            // This will compute and cache the embedding
            self.embed(model_name, text)?;
        }
        info!("Cache warmed successfully");
        Ok(())
    }

    /// Checks if caching is enabled.
    ///
    /// # Returns
    ///
    /// Returns true if caching is enabled, false otherwise.
    pub fn is_cache_enabled(&self) -> bool {
        self.embedding_cache.is_some()
    }

    /// Checks if a model is registered in the config registry.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to check
    ///
    /// # Returns
    ///
    /// Returns true if the model is registered, false otherwise.
    pub fn is_model_registered(&self, model_name: &str) -> bool {
        let configs = self.model_configs.read();
        configs.contains_key(model_name)
    }

    /// Checks if a model is loaded in the current thread.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to check
    ///
    /// # Returns
    ///
    /// Returns true if the model is loaded in the current thread, false otherwise.
    pub fn is_model_loaded_in_thread(&self, model_name: &str) -> bool {
        THREAD_MODELS.with(|models| {
            let models = models.borrow();
            models.contains_key(model_name)
        })
    }

    /// Gets the default model name.
    ///
    /// # Returns
    ///
    /// Returns the default model name if set.
    pub fn default_model(&self) -> Option<String> {
        self.default_model.clone()
    }

    /// Sets the default model.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to set as default
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not loaded.
    pub fn set_default_model(&mut self, model_name: &str) -> Result<()> {
        if !self.is_model_registered(model_name) {
            return Err(Error::ModelNotFound {
                name: model_name.to_string(),
            });
        }
        self.default_model = Some(model_name.to_string());
        Ok(())
    }

    /// Gets information about a loaded model.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model
    ///
    /// # Returns
    ///
    /// Returns model information if the model is loaded.
    ///
    /// # Errors
    ///
    /// Returns an error if the model is not found
    pub fn model_info(&self, model_name: &str) -> Result<ModelInfo> {
        // Ensure model is loaded in current thread
        self.ensure_model_loaded(model_name)?;

        THREAD_MODELS.with(|models| {
            let models = models.borrow();
            let model = models.get(model_name).ok_or_else(|| Error::ModelNotFound {
                name: model_name.to_string(),
            })?;

            Ok(ModelInfo {
                name: model_name.to_string(),
                dimensions: model.embedding_dimensions(),
                max_tokens: model.max_sequence_length(),
                model_size: model.model_size(),
            })
        })
    }

    /// Warms up a model by generating a test embedding.
    ///
    /// This can be useful to ensure the model is fully loaded and ready
    /// before processing actual requests.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The name of the model to warm up (or None for default)
    ///
    /// # Errors
    ///
    /// Returns an error if warmup fails.
    pub fn warmup_model(&self, model_name: Option<&str>) -> Result<()> {
        let resolved_name = model_name
            .map(std::string::ToString::to_string)
            .or_else(|| self.default_model.clone())
            .ok_or_else(|| Error::ConfigurationError {
                message: "No model specified and no default model set".to_string(),
            })?;

        // Ensure the model is loaded so the resolved config is available
        self.ensure_model_loaded(&resolved_name)?;

        // Check the resolved pooling strategy to pick the right warmup path
        let is_reranker = {
            let configs = self.model_configs.read();
            configs
                .get(&resolved_name)
                .and_then(|c| c.model_config.pooling_strategy)
                == Some(crate::config::PoolingStrategy::Rank)
        };

        if is_reranker {
            let _ = self.rerank(
                Some(&resolved_name),
                "warmup query",
                &["warmup document"],
                None,
                false,
            )?;
        } else {
            let _ = self.embed(
                Some(&resolved_name),
                "This is a warmup text for model initialization.",
            )?;
        }

        debug!("Model warmed up successfully");
        Ok(())
    }

    /// Performs explicit cleanup of all models in the current thread.
    ///
    /// With global tracing subscriber, this method is now optional but can
    /// still be useful for explicit resource management in tests.
    pub fn cleanup_thread_models(&self) {
        THREAD_MODELS.with(|models| {
            let mut models = models.borrow_mut();

            // Clear all models from the thread
            let count = models.len();
            models.clear();

            if count > 0 {
                info!("Cleared {} thread-local models", count);
            }
        });
    }

    // Prefix cache management methods

    /// Registers a text prefix for KV cache optimization.
    ///
    /// This method allows manual registration of common text prefixes for caching.
    /// The KV cache state will be saved and reused for texts that share this prefix.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The model to use (None uses default)
    /// * `prefix` - The prefix text to cache
    ///
    /// # Returns
    ///
    /// Returns Ok(()) if successful, or an error if registration fails.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No model is specified and no default model is set
    /// - The model is not found
    /// - Embedding generation for the prefix fails
    ///
    /// # Performance Notes
    ///
    /// - Only beneficial for prefixes >100 tokens due to session loading overhead
    /// - Best for code embeddings with common imports, template documents
    /// - Memory usage: ~100MB per cached prefix (typical models)
    pub fn register_prefix(&self, model_name: Option<&str>, prefix: &str) -> Result<()> {
        if let Some(cache) = &self.prefix_cache {
            // Determine which model to use
            let model_name = model_name
                .map(std::string::ToString::to_string)
                .or_else(|| self.default_model.clone())
                .ok_or_else(|| Error::ConfigurationError {
                    message: "No model specified and no default model set".to_string(),
                })?;

            // Ensure model is loaded in current thread
            self.ensure_model_loaded(&model_name)?;

            // Generate session state for the prefix
            let (tokens, session_data) = THREAD_MODELS.with(|models| {
                let mut models = models.borrow_mut();
                let model = models
                    .get_mut(&model_name)
                    .ok_or_else(|| Error::ModelNotFound {
                        name: model_name.clone(),
                    })?;

                // Tokenize the prefix
                let tokens = model.tokenize(prefix)?;

                // Generate embedding to populate KV cache
                model.generate_embedding(prefix)?;

                // Save the session state
                let session_data = model.save_session_state()?;

                Ok::<_, Error>((tokens, session_data))
            })?;

            // Register with prefix cache
            // Convert tokens to u32 for the cache API
            let token_ids: Vec<i32> = tokens.iter().map(|t| t.0).collect();
            cache.register_prefix(prefix, &token_ids, session_data)?;

            info!(
                "Registered prefix of {} tokens for caching",
                token_ids.len()
            );
            Ok(())
        } else {
            Err(Error::ConfigurationError {
                message: "Prefix cache is not enabled".to_string(),
            })
        }
    }

    /// Gets prefix cache statistics.
    ///
    /// # Returns
    ///
    /// Returns statistics about the prefix cache if enabled, None otherwise.
    pub fn get_prefix_cache_stats(&self) -> Option<crate::cache::prefix_cache::PrefixCacheStats> {
        self.prefix_cache.as_ref().map(|cache| cache.stats())
    }

    /// Clears the prefix cache.
    ///
    /// This removes all cached prefix sessions and resets statistics.
    pub fn clear_prefix_cache(&self) {
        if let Some(cache) = &self.prefix_cache {
            cache.clear();
            info!("Prefix cache cleared");
        }
    }

    /// Lists all cached prefixes.
    ///
    /// # Returns
    ///
    /// Returns a vector of prefix information if cache is enabled, empty vector otherwise.
    pub fn list_cached_prefixes(&self) -> Vec<String> {
        if let Some(_cache) = &self.prefix_cache {
            // > TODO: Implement a method in PrefixCache to list cached prefixes
            // For now, return empty vector
            vec![]
        } else {
            vec![]
        }
    }

    /// Checks if prefix caching is enabled.
    ///
    /// # Returns
    ///
    /// Returns true if prefix caching is enabled, false otherwise.
    pub fn is_prefix_cache_enabled(&self) -> bool {
        self.prefix_cache.is_some()
    }
}

/// Information about a loaded model.
#[derive(Debug, Clone)]
pub struct ModelInfo {
    /// Model name
    pub name: String,
    /// Embedding dimensions
    pub dimensions: usize,
    /// Maximum token count
    pub max_tokens: usize,
    /// Approximate model size in bytes (None if unable to calculate)
    pub model_size: Option<usize>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn create_test_config() -> EngineConfig {
        let dir = tempdir().unwrap();
        let model_path = dir.path().join("test_model.gguf");
        fs::write(&model_path, b"dummy model file").unwrap();

        EngineConfig::builder()
            .with_model_path(model_path)
            .with_model_name("test-model")
            .build()
            .unwrap()
    }

    #[test]
    fn test_engine_creation() {
        // This test would require a real GGUF model file
        // For now, we just test that the structure compiles correctly
    }

    #[test]
    fn test_model_listing() {
        // Test would require real model files
    }

    #[test]
    #[ignore = "Requires actual GGUF model file"]
    fn test_embedding_generation() {
        let config = create_test_config();
        let engine = EmbeddingEngine::new(config).unwrap();

        let text = "Hello, world!";
        let embedding = engine.embed(None, text).unwrap();

        assert!(!embedding.is_empty());
    }
}