vecboost 0.2.0

High-performance embedding vector service written in Rust
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
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
// Copyright (c) 2025-2026 Kirky.X
//
// Licensed under MIT License
// See LICENSE file in the project root for full license information

#![allow(clippy::all)]

use super::InferenceEngine;
use crate::config::model::{DeviceType, ModelConfig, Precision};
use crate::device::memory_limit::{MemoryLimitController, MemoryLimitStatus};
use crate::error::VecboostError;
use crate::model::recovery::{ModelRecovery, RecoveryConfig};
use crate::monitor::MemoryMonitor;
use crate::text::{CachedTokenizer, Encoding};
use crate::utils::hash::{check_model_integrity, verify_sha256};
use crate::utils::hf_hub::build_hf_repo;
use async_trait::async_trait;
use candle_core::{DType, Device, Tensor};
use candle_nn::{VarBuilder, VarMap};
use candle_transformers::models::bert::{BertModel, Config as BertConfig};
use candle_transformers::models::xlm_roberta::{Config as XlmRobertaConfig, XLMRobertaModel};
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(target_os = "macos")]
use tokenizers::Tokenizer as HfTokenizer;

#[cfg(not(target_os = "macos"))]
type HfTokenizer = crate::text::Tokenizer;

#[derive(Debug, Clone)]
pub enum ModelArchitecture {
    Bert,
    XlmRoberta,
}

#[derive(Deserialize)]
struct ModelConfigJson {
    pub architectures: Option<Vec<String>>,
    pub model_type: Option<String>,
}

impl ModelConfigJson {
    pub fn get_architecture(&self) -> ModelArchitecture {
        if let Some(arch) = &self.architectures {
            for a in arch {
                if a.contains("XLMRoberta") || a.contains("xlm_roberta") {
                    return ModelArchitecture::XlmRoberta;
                }
            }
        }
        if let Some(t) = &self.model_type
            && (t.contains("xlm-roberta") || t.contains("xlm_roberta"))
        {
            return ModelArchitecture::XlmRoberta;
        }
        ModelArchitecture::Bert
    }
}

enum ModelWrapper {
    Bert(BertModel),
    XlmRoberta(XLMRobertaModel),
}

pub struct CandleEngine {
    model: ModelWrapper,
    tokenizer: CachedTokenizer,
    device: Device,
    precision: Precision,
    memory_monitor: Option<Arc<MemoryMonitor>>,
    memory_limit_controller: Option<Arc<MemoryLimitController>>,
    fallback_triggered: bool,
    device_type: DeviceType,
    model_architecture: ModelArchitecture,
    use_quantization: bool, // 是否使用 INT8 量化
}

impl CandleEngine {
    pub fn new(config: &ModelConfig, precision: Precision) -> Result<Self, VecboostError> {
        Self::with_device(config, precision, config.device.clone())
    }

    pub fn with_device(
        config: &ModelConfig,
        precision: Precision,
        device_type: DeviceType,
    ) -> Result<Self, VecboostError> {
        let device = if device_type == DeviceType::Cuda && candle_core::utils::cuda_is_available() {
            log::info!("Using CUDA GPU");
            Device::new_cuda(0).map_err(|e| VecboostError::InferenceError(e.to_string()))?
        } else if device_type == DeviceType::Metal && candle_core::utils::metal_is_available() {
            log::info!("Using Metal GPU");
            Device::new_metal(0).map_err(|e| VecboostError::InferenceError(e.to_string()))?
        } else if matches!(device_type, DeviceType::Amd | DeviceType::OpenCL) {
            log::warn!(
                "Candle engine does not natively support AMD GPUs. AMD GPU support requires ROCm-enabled Candle build or ONNX Runtime. Falling back to CPU."
            );
            Device::Cpu
        } else {
            log::info!("Using CPU");
            Device::Cpu
        };

        // 确定计算数据类型,支持 FP16 和 INT8 量化
        let compute_dtype = match (&precision, device.is_cuda()) {
            (Precision::Int8, true) => {
                log::info!("Using INT8 quantization (CPU inference, reduced precision)");
                DType::U8 // Candle 使用 U8 而非 I8
            }
            (Precision::Int8, false) => {
                log::warn!("INT8 quantization requested but CUDA not available, using FP32");
                DType::F32
            }
            (Precision::Fp16, true) => {
                log::info!("Using FP16 precision");
                DType::F16
            }
            (Precision::Fp16, false) => {
                log::warn!("FP16 not supported on non-CUDA devices, falling back to FP32");
                DType::F32
            }
            (Precision::Fp32, _) => {
                log::info!("Using FP32 precision");
                DType::F32
            }
        };

        // INT8 量化需要特殊处理:在 CPU 上量化,然后可能传输到 GPU
        let (dtype, use_quantization) = if matches!(precision, Precision::Int8) {
            (DType::F32, true) // INT8 量化使用 FP32 存储,推理时量化
        } else {
            (compute_dtype, false)
        };

        let model_path = &config.model_path;
        let is_local_path = model_path.exists() && model_path.is_dir();

        // 安全增强:如果是本地路径,进行路径遍历攻击检测
        if is_local_path {
            // 检查路径是否包含 ".." 或其他可疑模式
            let model_path_str = model_path.to_string_lossy();
            if model_path_str.contains("..") || model_path_str.contains('~') {
                log::warn!(
                    "Potential path traversal attempt detected in model path: {:?}",
                    model_path
                );
                // 注意:这里不直接拒绝,因为可能是合法的相对路径
                // 但会记录警告日志用于安全审计
            }
        }

        let (config_filename, tokenizer_filename, weights_filename): (
            std::path::PathBuf,
            std::path::PathBuf,
            std::path::PathBuf,
        ) = if is_local_path {
            log::info!("Loading model from local path: {:?}", model_path);
            let config_path = model_path.join("config.json");
            let tokenizer_path = model_path.join("tokenizer.json");
            let weights_path = model_path.join("model.safetensors");
            let alt_weights_path = model_path.join("pytorch_model.bin");

            let weights_filename = if weights_path.exists() {
                weights_path
            } else if alt_weights_path.exists() {
                alt_weights_path
            } else {
                return Err(VecboostError::ModelLoadError(
                    "No model weights file found (model.safetensors or pytorch_model.bin)"
                        .to_string(),
                ));
            };

            (config_path, tokenizer_path, weights_filename)
        } else {
            // vuln-0009 修复:repo_id 格式校验由 build_hf_repo 统一执行,防止恶意配置注入
            let repo_id = model_path.to_string_lossy().into_owned();

            // vuln-0009 加固:远程下载时若未设置 model_sha256,记录警告
            // .bin(pickle)格式有代码执行风险,model_sha256 是完整性校验的最后防线
            if config.model_sha256.is_none() {
                log::warn!(
                    "Loading model from remote HuggingFace repo '{}' without model_sha256 \
                     verification — recommend setting model_sha256 in config to prevent \
                     tampering and supply-chain attacks",
                    repo_id
                );
            }

            log::info!(
                "Downloading/Loading model from HuggingFace Hub: {:?}",
                model_path
            );
            let repo = build_hf_repo(&repo_id)?;

            let config_filename = repo
                .download_file()
                .filename("config.json")
                .send()
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
            let tokenizer_filename = repo
                .download_file()
                .filename("tokenizer.json")
                .send()
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
            let weights_filename = repo
                .download_file()
                .filename("model.safetensors")
                .send()
                .or_else(|_| {
                    log::warn!(
                        "model.safetensors unavailable, falling back to pytorch_model.bin; \
                         pickle format carries code-execution risk — only load .bin models \
                         from trusted sources, prefer safetensors"
                    );
                    repo.download_file().filename("pytorch_model.bin").send()
                })
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

            (config_filename, tokenizer_filename, weights_filename)
        };

        let config_content = std::fs::read_to_string(&config_filename)?;
        let model_config_json: ModelConfigJson = serde_json::from_str(&config_content)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
        let model_architecture = model_config_json.get_architecture();

        log::info!("Detected model architecture: {:?}", model_architecture);

        let (bert_config, xlm_config) = match &model_architecture {
            ModelArchitecture::Bert => {
                let bert_config: BertConfig = serde_json::from_str(&config_content)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                (Some(bert_config), None)
            }
            ModelArchitecture::XlmRoberta => {
                let xlm_config: XlmRobertaConfig = serde_json::from_str(&config_content)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                (None, Some(xlm_config))
            }
        };

        let hf_tokenizer = HfTokenizer::from_file(tokenizer_filename.to_string_lossy().as_ref())
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        let max_position_embeddings = match (&model_architecture, &bert_config, &xlm_config) {
            (ModelArchitecture::Bert, Some(bert), _) => bert.max_position_embeddings,
            (ModelArchitecture::XlmRoberta, _, Some(xlm)) => xlm.max_position_embeddings,
            _ => {
                return Err(VecboostError::ModelLoadError(format!(
                    "Invalid configuration for architecture: {:?}",
                    model_architecture
                )));
            }
        };

        let tokenizer = CachedTokenizer::new(hf_tokenizer, max_position_embeddings, 2048);

        let is_pytorch = weights_filename.to_string_lossy().ends_with(".bin");

        let config_str = config_filename.to_string_lossy().to_string();
        let tokenizer_str = tokenizer_filename.to_string_lossy().to_string();
        let weights_str = weights_filename.to_string_lossy().to_string();

        let files_to_check = vec![
            (config_str.clone(), None),
            (tokenizer_str.clone(), None),
            (weights_str.clone(), config.model_sha256.clone()),
        ];

        let min_sizes = {
            let mut sizes = HashMap::new();
            sizes.insert(config_str.clone(), 100);
            sizes.insert(tokenizer_str.clone(), 1000);
            sizes.insert(weights_str.clone(), 1024 * 1024);
            sizes
        };

        log::info!("Checking model file integrity...");
        let integrity_report = check_model_integrity(&config.name, files_to_check, Some(min_sizes))
            .map_err(|e| {
                VecboostError::ModelIntegrityError(format!("Integrity check failed: {}", e))
            })?;

        if !integrity_report.overall_valid {
            log::error!("Model file integrity check failed!");
            for check in &integrity_report.files_checked {
                if !check.is_valid {
                    log::error!(
                        "  File: {}, Error: {}",
                        check.file_path,
                        check.error_message.as_deref().unwrap_or("Unknown error")
                    );
                }
            }

            log::info!("Attempting automatic recovery of corrupted files...");
            let recovery_config = RecoveryConfig::default();
            let recovery = ModelRecovery::new(recovery_config);

            let repo_id_str = if !is_local_path {
                Some(config.model_path.to_string_lossy().to_string())
            } else {
                None
            };

            let repo_id = repo_id_str.as_deref();

            let recovery_result = recovery
                .recover_corrupted_files(
                    &config.name,
                    model_path,
                    repo_id,
                    &integrity_report.corrupted_files,
                )
                .map_err(|e| {
                    VecboostError::ModelIntegrityError(format!("Recovery failed: {}", e))
                })?;

            if recovery_result.success {
                log::info!("Successfully recovered all corrupted files");
                log::info!("Re-running integrity check after recovery...");

                let files_to_check = vec![
                    (config_str.clone(), None),
                    (tokenizer_str.clone(), None),
                    (weights_str.clone(), config.model_sha256.clone()),
                ];

                let min_sizes = {
                    let mut sizes = HashMap::new();
                    sizes.insert(config_str, 100);
                    sizes.insert(tokenizer_str, 1000);
                    sizes.insert(weights_str, 1024 * 1024);
                    sizes
                };

                let recovery_integrity_report =
                    check_model_integrity(&config.name, files_to_check, Some(min_sizes)).map_err(
                        |e| {
                            VecboostError::ModelIntegrityError(format!(
                                "Post-recovery integrity check failed: {}",
                                e
                            ))
                        },
                    )?;

                if !recovery_integrity_report.overall_valid {
                    return Err(VecboostError::ModelFileCorrupted(format!(
                        "Model files still corrupted after recovery. Corrupted files: {:?}",
                        recovery_integrity_report.corrupted_files
                    )));
                }

                log::info!("Post-recovery integrity check passed");
            } else {
                return Err(VecboostError::ModelFileCorrupted(format!(
                    "Failed to recover corrupted files after {} attempts. Corrupted files: {:?}",
                    recovery_result.attempts, recovery_result.failed_files
                )));
            }
        }

        log::info!("Model file integrity check passed");

        if let Some(ref expected_hash) = config.model_sha256 {
            log::info!("Verifying model file SHA256 hash...");
            let is_valid = verify_sha256(&weights_filename, expected_hash).map_err(|e| {
                VecboostError::ModelLoadError(format!("Failed to verify SHA256: {}", e))
            })?;

            if !is_valid {
                return Err(VecboostError::ModelFileCorrupted(format!(
                    "Model file SHA256 verification failed. Expected: {}, File: {:?}",
                    expected_hash, weights_filename
                )));
            }

            log::info!("Model file SHA256 verification passed");
        }

        // 使用之前确定的 dtype(支持量化)
        let vb: VarBuilder = if is_pytorch {
            log::info!("Loading PyTorch model weights from: {:?}", weights_filename);

            let file_size = std::fs::metadata(&weights_filename)
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
                .len();

            if file_size > 2 * 1024 * 1024 * 1024 {
                log::warn!(
                    "PyTorch model file is large ({} GB). Large PyTorch files may have loading issues.",
                    file_size as f64 / 1024.0 / 1024.0 / 1024.0
                );
                log::info!("Consider converting to safetensors format for better performance:");
                log::info!(
                    "  python -c \"from transformers import AutoModel; AutoModel.from_pretrained('{}').save_pretrained('./model_converted')\"",
                    config.model_path.to_string_lossy()
                );
                log::info!("  Then use './model_converted' as the model_path in config.toml");
            }

            let mut varmap = VarMap::new();
            match varmap.load(&weights_filename) {
                Ok(_) => {
                    log::info!("PyTorch weights loaded successfully");
                }
                Err(e) => {
                    log::error!("Failed to load PyTorch weights: {}", e);
                    log::error!("This is often due to large model files or incompatible formats.");
                    log::error!("Please convert the model to safetensors format:");
                    log::error!("  pip install optimum");
                    log::error!(
                        "  optimum-cli export onnx --model {} --task feature-extraction ./model_safetensors",
                        config.model_path.to_string_lossy()
                    );
                    return Err(VecboostError::ModelLoadError(format!(
                        "Failed to load PyTorch weights: {}. Please convert the model to safetensors format.",
                        e
                    )));
                }
            }
            VarBuilder::from_varmap(&varmap, dtype, &device)
        } else {
            log::info!(
                "Loading safetensors model weights from: {:?}",
                weights_filename
            );
            let vb =
                unsafe { VarBuilder::from_mmaped_safetensors(&[weights_filename], dtype, &device) };
            vb.map_err(|e| VecboostError::ModelLoadError(e.to_string()))?
        };

        if is_pytorch {
            log::info!("Loaded PyTorch model weights successfully");
        } else {
            log::info!("Loaded safetensors model weights successfully");
        }

        let model = match &model_architecture {
            ModelArchitecture::Bert => {
                let config = bert_config.ok_or_else(|| {
                    VecboostError::ModelLoadError(
                        "Bert config is required for Bert model".to_string(),
                    )
                })?;
                let bert_model = BertModel::load(vb, &config)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                ModelWrapper::Bert(bert_model)
            }
            ModelArchitecture::XlmRoberta => {
                let config = xlm_config.ok_or_else(|| {
                    VecboostError::ModelLoadError("XLM-RoBERTa config is required".to_string())
                })?;
                let xlm_model = XLMRobertaModel::new(&config, vb)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                ModelWrapper::XlmRoberta(xlm_model)
            }
        };

        let memory_monitor = if device.is_cuda() || device.is_metal() {
            Some(Arc::new(MemoryMonitor::new()))
        } else {
            None
        };

        Ok(Self {
            model,
            tokenizer,
            device,
            precision,
            memory_monitor,
            memory_limit_controller: None,
            fallback_triggered: false,
            device_type,
            model_architecture,
            use_quantization,
        })
    }

    pub fn set_memory_limit_controller(&mut self, controller: Arc<MemoryLimitController>) {
        self.memory_limit_controller = Some(controller);
    }

    pub fn device_type(&self) -> DeviceType {
        self.device_type.clone()
    }

    pub fn is_fallback_triggered(&self) -> bool {
        self.fallback_triggered
    }

    pub async fn check_memory_pressure(&self, threshold_percent: u64) -> bool {
        if let Some(ref monitor) = self.memory_monitor {
            let stats = monitor.get_memory_stats().await;
            let usage_percent = if stats.total_bytes > 0 {
                (stats.current_bytes * 100) / stats.total_bytes
            } else {
                0
            };
            usage_percent >= threshold_percent
        } else {
            false
        }
    }

    pub async fn check_memory_limit_and_fallback(
        &mut self,
        config: &ModelConfig,
    ) -> Result<bool, VecboostError> {
        if self.fallback_triggered {
            return Ok(false);
        }

        if let Some(ref controller) = self.memory_limit_controller {
            let status = controller.check_limit().await;

            if status == MemoryLimitStatus::Exceeded {
                log::warn!("Memory limit exceeded, attempting fallback to CPU");
                self.try_fallback_to_cpu(config).await?;
                return Ok(true);
            } else if status == MemoryLimitStatus::Critical {
                log::warn!("Memory limit critical, checking memory pressure for fallback");
                if self.check_memory_pressure(90).await {
                    self.try_fallback_to_cpu(config).await?;
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    pub async fn update_memory_limit(&self, used_bytes: u64) {
        if let Some(ref controller) = self.memory_limit_controller {
            controller.update_usage(used_bytes).await;
        }
    }

    pub async fn get_memory_status(&self) -> Option<MemoryLimitStatus> {
        if let Some(ref controller) = self.memory_limit_controller {
            Some(controller.check_limit().await)
        } else {
            None
        }
    }

    pub async fn update_gpu_memory(&self) {
        if let Some(ref _monitor) = self.memory_monitor {
            #[cfg(feature = "cuda")]
            _monitor.update_gpu_memory_from_candle().await;
            #[cfg(feature = "metal")]
            _monitor.update_gpu_memory_from_metal().await;
        }
    }

    async fn forward_pass(&self, text: &str) -> Result<Vec<f32>, VecboostError> {
        let encoding = self
            .tokenizer
            .encode(text, true)
            .await
            .map_err(|e| VecboostError::TokenizationError(e.to_string()))?;

        let ids = encoding.get_ids();
        let attention_mask = encoding.get_attention_mask();

        log::debug!("Token IDs: {:?}", ids);
        log::debug!("Max token ID: {}", ids.iter().max().copied().unwrap_or(0));
        log::debug!("Attention mask: {:?}", attention_mask);

        let vocab_size = 250002;
        let max_id = ids.iter().max().copied().unwrap_or(0);
        if max_id >= vocab_size {
            log::warn!(
                "Token ID {} exceeds vocab_size {}, clamping",
                max_id,
                vocab_size
            );
        }

        let max_len = self.tokenizer.max_length().min(512);

        let ids_slice: Vec<u32> = ids
            .iter()
            .take(max_len)
            .map(|&id| if id >= vocab_size { vocab_size - 1 } else { id })
            .collect();

        let mask_slice: Vec<u32> = attention_mask
            .iter()
            .take(max_len)
            .map(|&id| if id >= vocab_size { vocab_size - 1 } else { id })
            .collect();

        let token_ids = Tensor::new(ids_slice, &self.device)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            .unsqueeze(0)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        let attention_mask_tensor = Tensor::new(mask_slice, &self.device)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            .unsqueeze(0)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        let embeddings = match &self.model {
            ModelWrapper::Bert(bert_model) => bert_model
                .forward(&token_ids, &attention_mask_tensor, None)
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?,
            ModelWrapper::XlmRoberta(xlm_model) => {
                let type_ids_slice: Vec<u32> =
                    encoding.type_ids.iter().take(max_len).cloned().collect();
                let token_type_ids = Tensor::new(type_ids_slice, &self.device)
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?
                    .unsqueeze(0)
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
                xlm_model
                    .forward(
                        &token_ids,
                        &attention_mask_tensor,
                        &token_type_ids,
                        None,
                        None,
                        None,
                    )
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            }
        };

        log::debug!("Embeddings shape: {:?}", embeddings.shape());
        log::debug!("Embeddings dims: {}", embeddings.dims().len());
        log::debug!("Embeddings dims array: {:?}", embeddings.dims());

        self.update_gpu_memory().await;

        let embedding_result: Tensor;
        let dims = embeddings.dims();
        log::debug!("Processing embedding with {} dimensions", dims.len());

        if dims.len() == 1 {
            log::debug!("1D embedding, using directly");
            embedding_result = embeddings.clone();
        } else if dims.len() == 2 {
            if dims[0] == 1 && dims[1] > 1 {
                log::debug!("2D embedding [1, hidden_size], extracting batch 0");
                embedding_result = embeddings
                    .get(0)
                    .map_err(|e| {
                        VecboostError::InferenceError(format!("Failed to get batch 0: {}", e))
                    })?
                    .clone();
            } else {
                log::debug!("2D embedding [seq_len, hidden_size], extracting CLS token (index 0)");
                embedding_result = embeddings
                    .get(0)
                    .map_err(|e| {
                        VecboostError::InferenceError(format!("Failed to get token 0: {}", e))
                    })?
                    .clone();
            }
        } else if dims.len() == 3 {
            log::debug!("3D embedding [batch, seq_len, hidden], extracting batch 0, token 0");
            embedding_result = embeddings
                .get(0)
                .map_err(|e| {
                    VecboostError::InferenceError(format!("Failed to get batch 0: {}", e))
                })?
                .get(0)
                .map_err(|e| {
                    VecboostError::InferenceError(format!("Failed to get token 0: {}", e))
                })?
                .clone();
        } else {
            return Err(VecboostError::InferenceError(format!(
                "Unsupported embedding dimensions: {} (shape: {:?})",
                dims.len(),
                embeddings.shape()
            )));
        }

        log::debug!("Final embedding shape: {:?}", embedding_result.shape());

        let vec = embedding_result
            .to_vec1::<f32>()
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        Ok(vec)
    }

    /// 优化的批量前向传播,使用真正的批量处理而非串行处理
    async fn forward_pass_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, VecboostError> {
        if texts.is_empty() {
            return Ok(vec![]);
        }

        log::debug!(
            "Processing batch of {} texts using optimized batch processing",
            texts.len()
        );

        // 批量编码所有文本
        let encodings: Vec<Encoding> = {
            let mut encodings = Vec::with_capacity(texts.len());
            for &text in texts {
                let encoding = self
                    .tokenizer
                    .encode(text, true)
                    .await
                    .map_err(|e| VecboostError::TokenizationError(e.to_string()))?;
                encodings.push(encoding);
            }
            encodings
        };

        // 计算最大序列长度
        let max_seq_len = encodings
            .iter()
            .map(|e| e.get_ids().len())
            .max()
            .unwrap_or(0)
            .min(self.tokenizer.max_length());

        if max_seq_len == 0 {
            return Ok(vec![vec![0f32; 768]; texts.len()]);
        }

        // 创建批量张量
        let batch_size = texts.len();

        // 构建 input_ids 批量张量
        let mut batch_ids = vec![0i64; batch_size * max_seq_len];
        for (batch_idx, encoding) in encodings.iter().enumerate() {
            let ids = encoding.get_ids();
            for (seq_idx, &id) in ids.iter().enumerate().take(max_seq_len) {
                batch_ids[batch_idx * max_seq_len + seq_idx] = id as i64;
            }
        }

        // 直接动态分配 token_ids 张量
        // (Candle Tensor 不可变,张量池取出后仍需重建,无实际收益)
        let token_ids = Tensor::new(batch_ids, &self.device)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            .reshape(&[batch_size, max_seq_len])
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        // 构建 attention_mask 批量张量
        let mut batch_mask = vec![0i64; batch_size * max_seq_len];
        for (batch_idx, encoding) in encodings.iter().enumerate() {
            let mask = encoding.get_attention_mask();
            for (seq_idx, &m) in mask.iter().enumerate().take(max_seq_len) {
                batch_mask[batch_idx * max_seq_len + seq_idx] = m as i64;
            }
        }

        // 直接动态分配 attention_mask 张量
        // (原张量池路径有 TODO 未回填数据导致 mask 全零的 bug;Candle Tensor 不可变,池无实际收益)
        let attention_mask_tensor = Tensor::new(batch_mask, &self.device)
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            .reshape(&[batch_size, max_seq_len])
            .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

        // 执行批量前向传播
        let embeddings = match (&self.model, &self.model_architecture) {
            (ModelWrapper::Bert(bert_model), ModelArchitecture::Bert) => bert_model
                .forward(&token_ids, &attention_mask_tensor, None)
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?,
            (ModelWrapper::XlmRoberta(xlm_model), ModelArchitecture::XlmRoberta) => {
                // 构建 type_ids 批量张量
                let mut batch_type_ids = vec![0i64; batch_size * max_seq_len];
                for (batch_idx, encoding) in encodings.iter().enumerate() {
                    let type_ids = encoding.get_type_ids();
                    for (seq_idx, &tid) in type_ids.iter().enumerate().take(max_seq_len) {
                        batch_type_ids[batch_idx * max_seq_len + seq_idx] = tid as i64;
                    }
                }

                let token_type_ids = Tensor::new(batch_type_ids, &self.device)
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?
                    .reshape(&[batch_size, max_seq_len])
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?;

                xlm_model
                    .forward(
                        &token_ids,
                        &attention_mask_tensor,
                        &token_type_ids,
                        None,
                        None,
                        None,
                    )
                    .map_err(|e| VecboostError::InferenceError(e.to_string()))?
            }
            _ => {
                return Err(VecboostError::InferenceError(format!(
                    "Model architecture mismatch for batch processing: {:?}",
                    self.model_architecture
                )));
            }
        };

        self.update_gpu_memory().await;

        // 提取每个样本的嵌入向量(使用 CLS token)
        let mut results = Vec::with_capacity(batch_size);
        for i in 0..batch_size {
            let embedding_tensor = embeddings
                .get(i)
                .map_err(|e| {
                    VecboostError::InferenceError(format!("Failed to get batch {}: {}", i, e))
                })?
                .get(0)
                .map_err(|e| {
                    VecboostError::InferenceError(format!(
                        "Failed to get CLS token for batch {}: {}",
                        i, e
                    ))
                })?
                .clone();

            let vec = embedding_tensor
                .to_vec1::<f32>()
                .map_err(|e| VecboostError::InferenceError(e.to_string()))?;
            results.push(vec);
        }

        log::debug!(
            "Batch processing completed, {} embeddings generated",
            results.len()
        );
        Ok(results)
    }
}

#[async_trait]
impl InferenceEngine for CandleEngine {
    fn embed(&self, text: &str) -> Result<Vec<f32>, VecboostError> {
        tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(async { self.forward_pass(text).await })
        })
    }

    fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, VecboostError> {
        let texts_refs: Vec<&str> = texts.iter().map(|s| s.as_str()).collect();
        tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current()
                .block_on(async { self.forward_pass_batch(&texts_refs).await })
        })
    }

    fn precision(&self) -> &Precision {
        &self.precision
    }

    fn supports_mixed_precision(&self) -> bool {
        self.device.is_cuda()
    }

    fn is_fallback_triggered(&self) -> bool {
        self.fallback_triggered
    }

    async fn try_fallback_to_cpu(&mut self, config: &ModelConfig) -> Result<(), VecboostError> {
        self.try_fallback_to_cpu_impl(config).await
    }
}

impl CandleEngine {
    /// 检查是否启用了 INT8 量化
    pub fn uses_quantization(&self) -> bool {
        self.use_quantization
    }

    /// 获取内存使用估算(基于精度和量化)
    pub fn estimate_memory_usage(&self, batch_size: usize, sequence_length: usize) -> u64 {
        let hidden_size = self.get_hidden_size();
        let num_params = self.estimate_parameter_count();

        // 基础模型大小(MB)
        let model_size_mb = match (&self.precision, self.use_quantization) {
            (Precision::Fp32, _) => num_params * 4 / (1024 * 1024), // 4 bytes per param
            (Precision::Fp16, _) => num_params * 2 / (1024 * 1024), // 2 bytes per param
            (Precision::Int8, true) => num_params * 1 / (1024 * 1024), // 1 byte per param
            (Precision::Int8, false) => num_params * 4 / (1024 * 1024), // Fallback to FP32
        };

        // 激活值大小(MB)
        let activation_size_mb = batch_size * sequence_length * hidden_size * 4 / (1024 * 1024);

        model_size_mb + activation_size_mb as u64
    }

    /// 估算模型参数数量
    fn estimate_parameter_count(&self) -> u64 {
        // 基于 BERT-Base 的估算(约 110M 参数)
        match &self.model_architecture {
            ModelArchitecture::Bert => 110_000_000,
            ModelArchitecture::XlmRoberta => 270_000_000, // XLM-RoBERTa base 约为 270M
        }
    }

    /// 获取隐藏层大小
    fn get_hidden_size(&self) -> usize {
        match &self.model_architecture {
            ModelArchitecture::Bert => 768,       // BERT-Base
            ModelArchitecture::XlmRoberta => 768, // XLM-RoBERTa-Base
        }
    }

    async fn try_fallback_to_cpu_impl(
        &mut self,
        config: &ModelConfig,
    ) -> Result<(), VecboostError> {
        if self.fallback_triggered {
            return Ok(());
        }

        log::info!("Attempting fallback from GPU to CPU due to memory pressure");

        self.memory_monitor = None;
        self.device = Device::Cpu;
        self.device_type = DeviceType::Cpu;
        self.fallback_triggered = true;

        let model_path = &config.model_path;
        let is_local_path = model_path.exists() && model_path.is_dir();

        let (config_filename, tokenizer_filename, weights_filename): (
            std::path::PathBuf,
            std::path::PathBuf,
            std::path::PathBuf,
        ) = if is_local_path {
            log::info!(
                "Loading model from local path for fallback: {:?}",
                model_path
            );
            let config_path = model_path.join("config.json");
            let tokenizer_path = model_path.join("tokenizer.json");
            let weights_path = model_path.join("model.safetensors");
            let alt_weights_path = model_path.join("pytorch_model.bin");

            let weights_filename = if weights_path.exists() {
                weights_path
            } else if alt_weights_path.exists() {
                alt_weights_path
            } else {
                return Err(VecboostError::ModelLoadError(
                    "No model weights file found during fallback".to_string(),
                ));
            };

            (config_path, tokenizer_path, weights_filename)
        } else {
            log::info!(
                "Loading model from HuggingFace Hub for fallback: {:?}",
                model_path
            );
            let repo_id = model_path.to_string_lossy().into_owned();
            let repo = build_hf_repo(&repo_id)?;

            let config_filename = repo
                .download_file()
                .filename("config.json")
                .send()
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
            let tokenizer_filename = repo
                .download_file()
                .filename("tokenizer.json")
                .send()
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
            let weights_filename = repo
                .download_file()
                .filename("model.safetensors")
                .send()
                .or_else(|_| {
                    log::warn!(
                        "model.safetensors unavailable, falling back to pytorch_model.bin; \
                         pickle format carries code-execution risk — only load .bin models \
                         from trusted sources, prefer safetensors"
                    );
                    repo.download_file().filename("pytorch_model.bin").send()
                })
                .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

            (config_filename, tokenizer_filename, weights_filename)
        };

        let config_content = std::fs::read_to_string(config_filename)?;
        let model_config_json: ModelConfigJson = serde_json::from_str(&config_content)
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
        let fallback_architecture = model_config_json.get_architecture();

        log::info!(
            "Fallback: Detected model architecture: {:?}",
            fallback_architecture
        );

        let (bert_config, xlm_config) = match &fallback_architecture {
            ModelArchitecture::Bert => {
                let bert_config: BertConfig = serde_json::from_str(&config_content)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                (Some(bert_config), None)
            }
            ModelArchitecture::XlmRoberta => {
                let xlm_config: XlmRobertaConfig = serde_json::from_str(&config_content)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                (None, Some(xlm_config))
            }
        };

        let hf_tokenizer = HfTokenizer::from_file(tokenizer_filename.to_string_lossy().as_ref())
            .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        let max_position_embeddings = match (&fallback_architecture, &bert_config, &xlm_config) {
            (ModelArchitecture::Bert, Some(bert), _) => bert.max_position_embeddings,
            (ModelArchitecture::XlmRoberta, _, Some(xlm)) => xlm.max_position_embeddings,
            _ => {
                return Err(VecboostError::ModelLoadError(format!(
                    "Invalid configuration for architecture: {:?}",
                    fallback_architecture
                )));
            }
        };

        self.tokenizer = CachedTokenizer::new(hf_tokenizer, max_position_embeddings, 2048);

        let vb = unsafe {
            VarBuilder::from_mmaped_safetensors(&[weights_filename], DType::F32, &self.device)
        }
        .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;

        self.model = match &fallback_architecture {
            ModelArchitecture::Bert => {
                let config = bert_config.ok_or_else(|| {
                    VecboostError::ModelLoadError("Bert config is required".to_string())
                })?;
                let bert_model = BertModel::load(vb, &config)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                ModelWrapper::Bert(bert_model)
            }
            ModelArchitecture::XlmRoberta => {
                let config = xlm_config.ok_or_else(|| {
                    VecboostError::ModelLoadError("XLM-RoBERTa config is required".to_string())
                })?;
                let xlm_model = XLMRobertaModel::new(&config, vb)
                    .map_err(|e| VecboostError::ModelLoadError(e.to_string()))?;
                ModelWrapper::XlmRoberta(xlm_model)
            }
        };

        self.model_architecture = fallback_architecture;
        // 回退时禁用量化
        self.use_quantization = false;

        log::info!("Successfully fell back to CPU");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::model::{EngineType, ModelConfig};
    use std::path::PathBuf;

    fn test_config() -> ModelConfig {
        ModelConfig {
            name: "test-candle".to_string(),
            engine_type: EngineType::Candle,
            model_path: PathBuf::from("/nonexistent/model"),
            tokenizer_path: None,
            device: DeviceType::Cpu,
            max_batch_size: 32,
            pooling_mode: None,
            expected_dimension: Some(768),
            memory_limit_bytes: None,
            oom_fallback_enabled: true,
            model_sha256: None,
        }
    }

    /// T006 H6: 验证 `tokio::task::block_in_place(|| Handle::current().block_on(...))` 模式
    /// 在 multi-thread runtime 下不 panic。
    ///
    /// 此前 `embed`/`embed_batch` 使用 `futures::executor::block_on`,在 Tokio 异步上下文中
    /// 会阻塞当前 worker 线程并可能死锁(若 future 需要 Tokio 资源)。
    /// 改用 `block_in_place` 后,Tokio 会将其他任务调度到其他 worker,避免死锁。
    ///
    /// 注:CandleEngine 构造需要真实模型文件,无法在单元测试中实例化;
    /// 此测试验证 block_in_place 调用模式本身的正确性——这是 H6 修复的核心。
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_block_in_place_pattern_completes_without_panic() {
        let result = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(async {
                // 模拟 forward_pass 内部的异步操作
                tokio::task::yield_now().await;
                42
            })
        });
        assert_eq!(
            result, 42,
            "block_in_place pattern must complete without panic in multi-thread runtime"
        );
    }

    /// T006 H6: 验证 block_in_place 内部的 block_on 可以正确 await Tokio 异步原语
    /// (如 tokio::sync::RwLock)。这模拟了 forward_pass_batch 中 pool.write().await 的场景。
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_block_in_place_with_tokio_rwlock_does_not_deadlock() {
        let lock = std::sync::Arc::new(tokio::sync::RwLock::new(0i32));
        let lock_clone = std::sync::Arc::clone(&lock);

        let result = tokio::task::block_in_place(|| {
            tokio::runtime::Handle::current().block_on(async {
                let mut guard = lock_clone.write().await;
                *guard = 42;
                *guard
            })
        });

        assert_eq!(
            result, 42,
            "block_in_place must allow Tokio RwLock acquisition"
        );
        // 验证锁已释放
        let guard = lock.try_read();
        assert!(
            guard.is_ok(),
            "RwLock must be released after block_on completes"
        );
    }

    /// 验证 `ModelConfigJson::get_architecture` 从 architectures 字段识别 XLM-RoBERTa
    #[test]
    fn test_get_architecture_xlm_roberta_from_architectures() {
        let config = ModelConfigJson {
            architectures: Some(vec!["XLMRobertaForMaskedLM".to_string()]),
            model_type: None,
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 architectures 字段中的小写 "xlm_roberta" 也能被识别
    #[test]
    fn test_get_architecture_xlm_roberta_from_lowercase_arch() {
        let config = ModelConfigJson {
            architectures: Some(vec!["xlm_roberta".to_string()]),
            model_type: None,
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 model_type 字段为 "xlm-roberta" 时识别为 XLM-RoBERTa
    #[test]
    fn test_get_architecture_xlm_roberta_from_model_type_hyphen() {
        let config = ModelConfigJson {
            architectures: None,
            model_type: Some("xlm-roberta".to_string()),
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 model_type 字段为 "xlm_roberta" 时识别为 XLM-RoBERTa
    #[test]
    fn test_get_architecture_xlm_roberta_from_model_type_underscore() {
        let config = ModelConfigJson {
            architectures: None,
            model_type: Some("xlm_roberta".to_string()),
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证空字段时默认返回 Bert
    #[test]
    fn test_get_architecture_bert_default_when_all_none() {
        let config = ModelConfigJson {
            architectures: None,
            model_type: None,
        };
        assert!(matches!(config.get_architecture(), ModelArchitecture::Bert));
    }

    /// 验证 architectures 仅含 Bert 类项时返回 Bert
    #[test]
    fn test_get_architecture_bert_when_no_xlm_in_architectures() {
        let config = ModelConfigJson {
            architectures: Some(vec!["BertForMaskedLM".to_string()]),
            model_type: Some("bert".to_string()),
        };
        assert!(matches!(config.get_architecture(), ModelArchitecture::Bert));
    }

    /// 验证 architectures 字段优先级高于 model_type
    #[test]
    fn test_get_architecture_architectures_takes_precedence_over_model_type() {
        let config = ModelConfigJson {
            architectures: Some(vec!["XLMRobertaModel".to_string()]),
            model_type: Some("bert".to_string()),
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 ModelArchitecture 的 Clone 行为
    #[test]
    fn test_model_architecture_clone_preserves_variant() {
        let bert = ModelArchitecture::Bert;
        let bert_clone = bert.clone();
        assert!(matches!(bert_clone, ModelArchitecture::Bert));

        let xlm = ModelArchitecture::XlmRoberta;
        let xlm_clone = xlm.clone();
        assert!(matches!(xlm_clone, ModelArchitecture::XlmRoberta));
    }

    /// 验证 CandleEngine::new 在空目录上返回 ModelLoadError(不依赖网络)
    #[test]
    fn test_candle_engine_new_returns_error_for_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::new(&config, Precision::Fp32);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError, got {:?}",
                e
            );
        }
    }

    /// 验证 with_device 在空目录(CPU)上返回带特定消息的 ModelLoadError
    #[test]
    fn test_candle_engine_with_device_empty_dir_cpu() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("No model weights file found"),
                "Expected 'No model weights file found', got: {}",
                msg
            );
        }
    }

    /// 验证 FP16 精度在空目录上仍返回错误(覆盖 dtype 分支)
    #[test]
    fn test_candle_engine_with_device_fp16_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp16, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 INT8 精度在空目录上仍返回错误(覆盖 INT8 量化分支)
    #[test]
    fn test_candle_engine_with_device_int8_empty_dir() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Int8, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 AMD 设备类型会回退到 CPU 并在空目录上返回 ModelLoadError
    #[test]
    fn test_candle_engine_with_device_amd_falls_back_to_cpu() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Amd);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError, got {:?}",
                e
            );
        }
    }

    /// 验证 OpenCL 设备类型同样回退到 CPU 并在空目录上返回错误
    #[test]
    fn test_candle_engine_with_device_opencl_falls_back_to_cpu() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::OpenCL);
        assert!(result.is_err());
    }

    /// 验证存在 model.safetensors 但缺失 config.json 时返回错误
    #[test]
    fn test_candle_engine_with_safetensors_but_no_config() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.safetensors"), b"fake")
            .expect("Failed to write fake safetensors");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            let msg = e.to_string();
            assert!(
                msg.contains("config.json")
                    || msg.contains("No such file")
                    || matches!(
                        e,
                        VecboostError::IoError(_) | VecboostError::ModelLoadError(_)
                    ),
                "Expected IO/ModelLoadError related to config.json, got: {}",
                msg
            );
        }
    }

    /// 验证存在 pytorch_model.bin 但缺失 config.json 时返回错误
    #[test]
    fn test_candle_engine_with_pytorch_bin_but_no_config() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("pytorch_model.bin"), b"fake")
            .expect("Failed to write fake pytorch_model.bin");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
    }

    /// 验证 `Precision` 的 Display 实现
    #[test]
    fn test_precision_display() {
        assert_eq!(Precision::Fp32.to_string(), "fp32");
        assert_eq!(Precision::Fp16.to_string(), "fp16");
        assert_eq!(Precision::Int8.to_string(), "int8");
    }

    /// 验证 `DeviceType` 的序列化形式(serde rename)
    #[test]
    fn test_device_type_serialization() {
        let cpu_json = serde_json::to_string(&DeviceType::Cpu).expect("serialize Cpu");
        assert_eq!(cpu_json, "\"cpu\"");

        let amd_json = serde_json::to_string(&DeviceType::Amd).expect("serialize Amd");
        assert_eq!(amd_json, "\"amd\"");

        let opencl_json = serde_json::to_string(&DeviceType::OpenCL).expect("serialize OpenCL");
        assert_eq!(opencl_json, "\"opencl\"");
    }

    /// 验证 architectures 为空 Vec 时回退到 model_type 判断
    #[test]
    fn test_get_architecture_empty_architectures_vec_falls_to_model_type() {
        let config = ModelConfigJson {
            architectures: Some(vec![]),
            model_type: Some("xlm-roberta".to_string()),
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 architectures 列表中 XLM-RoBERTa 出现在 Bert 之后时仍能识别
    #[test]
    fn test_get_architecture_xlm_after_bert_in_list() {
        let config = ModelConfigJson {
            architectures: Some(vec![
                "BertForMaskedLM".to_string(),
                "XLMRobertaForMaskedLM".to_string(),
            ]),
            model_type: None,
        };
        assert!(matches!(
            config.get_architecture(),
            ModelArchitecture::XlmRoberta
        ));
    }

    /// 验证 architectures 和 model_type 均无 XLM 关键字时返回 Bert
    #[test]
    fn test_get_architecture_bert_with_non_xlm_model_type() {
        let config = ModelConfigJson {
            architectures: Some(vec!["BertModel".to_string()]),
            model_type: Some("roberta".to_string()),
        };
        assert!(matches!(config.get_architecture(), ModelArchitecture::Bert));
    }

    /// 验证 ModelArchitecture 的 Debug 派生输出正确
    #[test]
    fn test_model_architecture_debug_format() {
        let bert_debug = format!("{:?}", ModelArchitecture::Bert);
        assert!(bert_debug.contains("Bert"));

        let xlm_debug = format!("{:?}", ModelArchitecture::XlmRoberta);
        assert!(xlm_debug.contains("XlmRoberta"));
    }

    /// 验证路径包含 ".." 时触发路径遍历警告但不阻断流程(仍返回 ModelLoadError)
    #[test]
    fn test_candle_engine_path_with_dotdot_traversal_warning() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let sub_dir = temp_dir.path().join("sub");
        std::fs::create_dir(&sub_dir).expect("Failed to create sub dir");
        let model_path = sub_dir.join("..").join("sub");

        assert!(
            model_path.exists(),
            "Path with .. must resolve to existing dir"
        );
        assert!(model_path.is_dir(), "Resolved path must be a directory");

        let mut config = test_config();
        config.model_path = model_path;

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("No model weights file found"),
                "Expected weights error despite path traversal, got: {}",
                msg
            );
        }
    }

    /// 验证 config.json 为非 JSON 文本时返回 ModelLoadError
    #[test]
    fn test_candle_engine_malformed_config_json() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.safetensors"), b"fake")
            .expect("Failed to write fake safetensors");
        std::fs::write(temp_dir.path().join("config.json"), b"not valid json {{{")
            .expect("Failed to write malformed config");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError for malformed JSON, got {:?}",
                e
            );
        }
    }

    /// 验证 config.json 为空文件时返回 ModelLoadError
    #[test]
    fn test_candle_engine_empty_config_json() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.safetensors"), b"fake")
            .expect("Failed to write fake safetensors");
        std::fs::write(temp_dir.path().join("config.json"), b"")
            .expect("Failed to write empty config");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError for empty JSON, got {:?}",
                e
            );
        }
    }

    /// 验证 config.json 为合法 JSON 但非对象(如数字)时返回 ModelLoadError
    #[test]
    fn test_candle_engine_non_object_config_json() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        std::fs::write(temp_dir.path().join("model.safetensors"), b"fake")
            .expect("Failed to write fake safetensors");
        std::fs::write(temp_dir.path().join("config.json"), b"42")
            .expect("Failed to write non-object config");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(
                matches!(e, VecboostError::ModelLoadError(_)),
                "Expected ModelLoadError for non-object JSON, got {:?}",
                e
            );
        }
    }

    /// 验证 model_sha256 设置但模型文件不存在时返回错误(覆盖 SHA256 设置路径)
    #[test]
    fn test_candle_engine_with_sha256_but_no_weights() {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");

        let mut config = test_config();
        config.model_path = temp_dir.path().to_path_buf();
        config.model_sha256 = Some("abc123".to_string());

        let result = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu);
        assert!(result.is_err());
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("No model weights file found"),
                "Expected weights error when SHA256 set but no weights, got: {}",
                msg
            );
        }
    }

    // ===== 真实模型集成测试 =====

    const REAL_MODEL_PATH: &str = "models/BAAI-bge-small-en-v1.5";

    fn real_model_config() -> ModelConfig {
        ModelConfig {
            name: "bge-small-en".to_string(),
            engine_type: EngineType::Candle,
            model_path: PathBuf::from(REAL_MODEL_PATH),
            tokenizer_path: None,
            device: DeviceType::Cpu,
            max_batch_size: 32,
            pooling_mode: None,
            expected_dimension: Some(384),
            memory_limit_bytes: None,
            oom_fallback_enabled: true,
            model_sha256: None,
        }
    }

    fn require_real_model() -> bool {
        let path = format!("{}/config.json", REAL_MODEL_PATH);
        if !std::path::Path::new(&path).exists() {
            eprintln!(
                "Skipping test: model files not found at {}",
                REAL_MODEL_PATH
            );
            return false;
        }
        true
    }

    /// 验证 CandleEngine::new 成功加载真实 BERT 模型并完成单文本推理、
    /// 同时覆盖 precision/device_type/supports_mixed_precision/is_fallback_triggered/
    /// uses_quantization/estimate_memory_usage/内存方法/embed_batch 等核心路径。
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_load_and_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");

        assert_eq!(*engine.precision(), Precision::Fp32);
        assert_eq!(engine.device_type(), DeviceType::Cpu);
        assert!(!engine.supports_mixed_precision());
        assert!(!engine.is_fallback_triggered());
        assert!(!engine.uses_quantization());

        let result = engine.embed("hello world");
        assert!(result.is_ok(), "embed failed: {:?}", result.err());
        let embedding = result.unwrap();
        assert_eq!(
            embedding.len(),
            384,
            "Expected 384-dim embedding, got {}",
            embedding.len()
        );
        let non_zero = embedding.iter().filter(|v| **v != 0.0).count();
        assert!(non_zero > 0, "Embedding should have non-zero values");

        let result2 = engine.embed("hello world");
        assert!(result2.is_ok());
        let embedding2 = result2.unwrap();
        for (a, b) in embedding.iter().zip(embedding2.iter()) {
            assert!((a - b).abs() < 1e-5, "Same text should give same embedding");
        }

        let empty_result = engine.embed("");
        assert!(
            empty_result.is_err(),
            "embed empty string should return error"
        );
        assert!(matches!(
            empty_result.unwrap_err(),
            VecboostError::TokenizationError(_)
        ));

        let mem = engine.estimate_memory_usage(1, 128);
        assert!(
            mem > 0,
            "estimate_memory_usage should return positive value"
        );

        assert!(
            !engine.check_memory_pressure(90).await,
            "check_memory_pressure should be false without monitor"
        );
        assert_eq!(
            engine.get_memory_status().await,
            None,
            "get_memory_status should be None without controller"
        );
        engine.update_memory_limit(1024).await;
        engine.update_gpu_memory().await;

        let empty_batch: Vec<String> = vec![];
        let batch_result = engine.embed_batch(&empty_batch);
        assert!(batch_result.is_ok());
        assert_eq!(batch_result.unwrap().len(), 0);

        let texts: Vec<String> = vec!["hello world".to_string(), "machine learning".to_string()];
        let batch_result = engine.embed_batch(&texts);
        assert!(
            batch_result.is_ok(),
            "embed_batch failed: {:?}",
            batch_result.err()
        );
        let embeddings = batch_result.unwrap();
        assert_eq!(embeddings.len(), 2);
        for (i, emb) in embeddings.iter().enumerate() {
            assert_eq!(
                emb.len(),
                384,
                "Batch embedding {} should be 384-dim, got {}",
                i,
                emb.len()
            );
        }
    }

    /// 验证 try_fallback_to_cpu 在 CPU 引擎上仍能重新加载模型并继续推理
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_try_fallback_to_cpu() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let mut engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");

        assert!(!engine.is_fallback_triggered());

        let fallback_result = engine.try_fallback_to_cpu(&config).await;
        assert!(
            fallback_result.is_ok(),
            "try_fallback_to_cpu failed: {:?}",
            fallback_result.err()
        );
        assert!(engine.is_fallback_triggered());
        assert_eq!(engine.device_type(), DeviceType::Cpu);
        assert!(
            !engine.uses_quantization(),
            "use_quantization should be disabled after fallback"
        );

        let result = engine.embed("post fallback text");
        assert!(
            result.is_ok(),
            "embed after fallback failed: {:?}",
            result.err()
        );
        assert_eq!(result.unwrap().len(), 384);

        let second_fallback = engine.try_fallback_to_cpu(&config).await;
        assert!(second_fallback.is_ok(), "Repeated fallback should be no-op");
    }

    /// 验证 set_memory_limit_controller 后内存状态查询与回退检查路径
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_with_memory_controller() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let mut engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");

        assert_eq!(engine.get_memory_status().await, None);

        let controller = Arc::new(MemoryLimitController::new());
        engine.set_memory_limit_controller(controller);

        let status = engine.get_memory_status().await;
        assert!(status.is_some(), "get_memory_status should return Some");
        assert_eq!(status.unwrap(), MemoryLimitStatus::Ok);

        let fallback_result = engine.check_memory_limit_and_fallback(&config).await;
        assert!(
            fallback_result.is_ok(),
            "check_memory_limit_and_fallback failed: {:?}",
            fallback_result.err()
        );
        assert!(
            !fallback_result.unwrap(),
            "Should not fallback when under limit"
        );

        engine.update_memory_limit(1024 * 1024).await;
        assert_eq!(
            engine.get_memory_status().await,
            Some(MemoryLimitStatus::Ok)
        );
    }

    /// 验证 FP16 精度在 CPU 上回退到 FP32 后仍可正常推理
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_loads_fp16_cpu() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine = CandleEngine::new(&config, Precision::Fp16)
            .expect("Failed to load real model with FP16");

        assert_eq!(*engine.precision(), Precision::Fp16);
        assert!(
            !engine.supports_mixed_precision(),
            "CPU should not support mixed precision"
        );

        let result = engine.embed("fp16 precision test");
        assert!(
            result.is_ok(),
            "embed with FP16 on CPU failed: {:?}",
            result.err()
        );
        assert_eq!(result.unwrap().len(), 384);
    }

    /// 验证 INT8 精度在 CPU 上启用 use_quantization 标志并可推理
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_loads_int8_cpu() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine = CandleEngine::new(&config, Precision::Int8)
            .expect("Failed to load real model with INT8");

        assert_eq!(*engine.precision(), Precision::Int8);
        assert!(
            engine.uses_quantization(),
            "INT8 precision should set use_quantization=true"
        );

        let result = engine.embed("int8 precision test");
        assert!(
            result.is_ok(),
            "embed with INT8 on CPU failed: {:?}",
            result.err()
        );
        assert_eq!(result.unwrap().len(), 384);
    }

    /// 验证不同 PoolingMode 配置下引擎均能加载并推理
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_loads_with_all_pooling_modes() {
        if !require_real_model() {
            return;
        }
        use crate::config::model::PoolingMode;
        for (name, mode) in [
            ("Mean", PoolingMode::Mean),
            ("Max", PoolingMode::Max),
            ("Cls", PoolingMode::Cls),
        ] {
            let mut config = real_model_config();
            config.pooling_mode = Some(mode.clone());
            let engine = CandleEngine::new(&config, Precision::Fp32)
                .unwrap_or_else(|e| panic!("Failed to load with {} pooling: {:?}", name, e));
            let result = engine.embed("pooling mode test");
            assert!(
                result.is_ok(),
                "embed with {} pooling failed: {:?}",
                name,
                result.err()
            );
            assert_eq!(result.unwrap().len(), 384);
        }
    }

    /// 验证 with_device 显式传入 Cpu 设备时行为与 new() 一致
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_with_device_cpu_no_pool() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine = CandleEngine::with_device(&config, Precision::Fp32, DeviceType::Cpu)
            .expect("Failed to load real model via with_device");

        assert_eq!(engine.device_type(), DeviceType::Cpu);
        let result = engine.embed("with_device test");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 384);
    }

    /// 验证 PyTorch 模型加载路径(覆盖 is_pytorch 分支 362-403 行)
    /// HuggingFace pytorch_model.bin 使用 pickle 格式,candle VarMap::load 不兼容,
    /// 返回 ModelLoadError 提示转换为 safetensors 格式
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_pytorch_bin_loading() {
        if !require_real_model() {
            return;
        }
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let real_path = std::path::Path::new(REAL_MODEL_PATH)
            .canonicalize()
            .expect("Failed to canonicalize real model path");
        for file in &["config.json", "tokenizer.json", "pytorch_model.bin"] {
            let src = real_path.join(file);
            let dst = temp_dir.path().join(file);
            std::os::unix::fs::symlink(&src, &dst)
                .unwrap_or_else(|e| panic!("Failed to symlink {}: {}", file, e));
        }
        let mut config = real_model_config();
        config.model_path = temp_dir.path().to_path_buf();
        let result = CandleEngine::new(&config, Precision::Fp32);
        assert!(
            result.is_err(),
            "PyTorch loading should fail with candle VarMap"
        );
        if let Err(VecboostError::ModelLoadError(msg)) = result {
            assert!(
                msg.contains("Failed to load PyTorch weights"),
                "Expected PyTorch load error, got: {}",
                msg
            );
        }
    }

    /// 验证内存超限时触发 CPU 回退(覆盖 Exceeded 分支)
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_memory_limit_exceeded_triggers_fallback() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let mut engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let controller = Arc::new(MemoryLimitController::with_config(
            crate::device::memory_limit::MemoryLimitConfig {
                limit_bytes: 1024,
                warning_threshold_percent: 80,
                critical_threshold_percent: 90,
            },
        ));
        controller.update_usage(2048).await;
        assert_eq!(controller.check_limit().await, MemoryLimitStatus::Exceeded);
        engine.set_memory_limit_controller(controller);
        let fallback = engine.check_memory_limit_and_fallback(&config).await;
        assert!(
            fallback.is_ok(),
            "check_memory_limit_and_fallback failed: {:?}",
            fallback.err()
        );
        assert!(
            fallback.unwrap(),
            "Should trigger fallback when memory exceeded"
        );
        assert!(
            engine.is_fallback_triggered(),
            "fallback_triggered flag must be set"
        );
    }

    /// 验证 Critical 状态在 CPU 上不触发回退(因 check_memory_pressure 返回 false)
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_memory_limit_critical_no_fallback_on_cpu() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let mut engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let controller = Arc::new(MemoryLimitController::with_config(
            crate::device::memory_limit::MemoryLimitConfig {
                limit_bytes: 1024,
                warning_threshold_percent: 80,
                critical_threshold_percent: 90,
            },
        ));
        controller.update_usage(922).await;
        assert_eq!(controller.check_limit().await, MemoryLimitStatus::Critical);
        engine.set_memory_limit_controller(controller);
        let fallback = engine.check_memory_limit_and_fallback(&config).await;
        assert!(
            fallback.is_ok(),
            "check_memory_limit_and_fallback failed: {:?}",
            fallback.err()
        );
        assert!(
            !fallback.unwrap(),
            "Should NOT trigger fallback on CPU with Critical status"
        );
        assert!(
            !engine.is_fallback_triggered(),
            "fallback_triggered should remain false"
        );
    }

    /// 验证大批量推理(4+ 文本)覆盖批量处理循环路径
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_large_batch_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let texts: Vec<String> = vec![
            "first sentence".to_string(),
            "second sentence".to_string(),
            "third sentence".to_string(),
            "fourth sentence".to_string(),
        ];
        let result = engine.embed_batch(&texts);
        assert!(result.is_ok(), "large batch failed: {:?}", result.err());
        let embeddings = result.unwrap();
        assert_eq!(embeddings.len(), 4);
        for (i, emb) in embeddings.iter().enumerate() {
            assert_eq!(emb.len(), 384, "Embedding {} should be 384-dim", i);
        }
    }

    /// 验证 estimate_memory_usage 在不同精度下的返回值(覆盖所有 precision 分支)
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_estimate_memory_usage_all_precisions() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();

        let engine_fp32 =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load FP32 model");
        let mem_fp32 = engine_fp32.estimate_memory_usage(1, 128);
        assert!(mem_fp32 > 0, "FP32 memory estimate should be positive");

        let engine_fp16 =
            CandleEngine::new(&config, Precision::Fp16).expect("Failed to load FP16 model");
        let mem_fp16 = engine_fp16.estimate_memory_usage(1, 128);
        assert!(mem_fp16 > 0, "FP16 memory estimate should be positive");
        assert!(mem_fp16 < mem_fp32, "FP16 should use less memory than FP32");

        let engine_int8 =
            CandleEngine::new(&config, Precision::Int8).expect("Failed to load INT8 model");
        let mem_int8 = engine_int8.estimate_memory_usage(1, 128);
        assert!(mem_int8 > 0, "INT8 memory estimate should be positive");
        assert!(mem_int8 < mem_fp16, "INT8 should use less memory than FP16");

        let mem_batch = engine_fp32.estimate_memory_usage(8, 256);
        assert!(
            mem_batch > mem_fp32,
            "Larger batch/seq should use more memory"
        );
    }

    /// 验证长文本推理覆盖 tokenization 长序列路径
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_long_text_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let long_text = "This is a very long text used for testing. ".repeat(20);
        let result = engine.embed(&long_text);
        assert!(result.is_ok(), "long text embed failed: {:?}", result.err());
        assert_eq!(result.unwrap().len(), 384);
    }

    /// 验证批量推理与单条推理结果的一致性
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_batch_vs_single_consistency() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let text1 = "hello world";
        let text2 = "machine learning";
        let single1 = engine.embed(text1).expect("single embed 1 failed");
        let single2 = engine.embed(text2).expect("single embed 2 failed");
        let batch: Vec<String> = vec![text1.to_string(), text2.to_string()];
        let batch_result = engine.embed_batch(&batch).expect("batch embed failed");
        assert_eq!(batch_result.len(), 2);
        for (i, (single, batch_emb)) in [single1, single2]
            .iter()
            .zip(batch_result.iter())
            .enumerate()
        {
            for (a, b) in single.iter().zip(batch_emb.iter()) {
                assert!(
                    (a - b).abs() < 1e-3,
                    "Batch vs single mismatch at index {} (diff > 1e-3)",
                    i
                );
            }
        }
    }

    /// 验证 Unicode 文本(中文+emoji)推理覆盖 tokenizer 多字节路径
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_unicode_text_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp32).expect("Failed to load real model");
        let result = engine.embed("你好世界 🌍 machine learning");
        assert!(result.is_ok(), "unicode embed failed: {:?}", result.err());
        assert_eq!(result.unwrap().len(), 384);
    }

    /// 验证 FP16 精度下的批量推理路径(CPU 回退到 FP32)
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_fp16_batch_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Fp16).expect("Failed to load FP16 model");
        let texts: Vec<String> = vec!["fp16 batch test".to_string(), "second text".to_string()];
        let result = engine.embed_batch(&texts);
        assert!(
            result.is_ok(),
            "FP16 batch embed failed: {:?}",
            result.err()
        );
        let embeddings = result.unwrap();
        assert_eq!(embeddings.len(), 2);
        for emb in &embeddings {
            assert_eq!(emb.len(), 384);
        }
    }

    /// 验证 INT8 精度下的批量推理路径
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_real_model_int8_batch_embed() {
        if !require_real_model() {
            return;
        }
        let config = real_model_config();
        let engine =
            CandleEngine::new(&config, Precision::Int8).expect("Failed to load INT8 model");
        let texts: Vec<String> = vec!["int8 batch test".to_string(), "second text".to_string()];
        let result = engine.embed_batch(&texts);
        assert!(
            result.is_ok(),
            "INT8 batch embed failed: {:?}",
            result.err()
        );
        let embeddings = result.unwrap();
        assert_eq!(embeddings.len(), 2);
        for emb in &embeddings {
            assert_eq!(emb.len(), 384);
        }
    }
}