vecboost 0.3.0-rc.1

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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "http")]
use axum::extract::FromRef;
use std::sync::Arc;
#[cfg(feature = "http")]
use tokio::sync::RwLock;

// 公共 API 模块 - SDK 入口,HTTP/MCP/CLI 协议共享
#[cfg(any(feature = "http", feature = "mcp", feature = "cli"))]
pub mod api;
pub mod audit;
#[cfg(feature = "auth")]
pub mod auth;
pub mod config;
#[cfg(feature = "db")]
pub mod db;
pub mod doctor;
pub mod domain;
pub mod engine;
pub mod i18n;
pub mod library;
pub mod metrics;
pub mod pipeline;
pub mod rate_limit;
pub mod registry;
pub mod security;
pub mod service;
pub mod utils;

pub mod logger;

pub use crate::pipeline::PriorityConfig;

pub(crate) mod cache;
pub(crate) mod device;
pub mod error;
pub(crate) mod model;
pub(crate) mod monitor;
pub(crate) mod text;

// 重新导出必要的内部类型(最小化暴露原则)
pub use config::VecboostConfig;
#[cfg(feature = "db")]
pub use config::app::DatabaseConfig;
pub use config::app::{AuthConfig, CsrfConfig, RateLimitConfig, RerankConfig, ServerConfig};
pub use config::model::ModelConfig;
pub use domain::{
    EmbedRequest, EmbedResponse, RerankRequest, RerankResponse, SimilarityRequest,
    SimilarityResponse,
};
pub use error::VecboostError;
pub use library::{LibraryConfig, VecBoostLibrary, VecBoostModuleBuilder};
pub use service::embedding::EmbeddingService;
pub use service::rerank::RerankService;
pub use utils::SimilarityMetric;
pub use utils::vector::{TaskType, information_retention_rate, recommended_dimension};

// 重新导出内存分页类型(供 benchmark 和外部集成测试使用)
pub use device::memory_paging::{PagingConfig, PagingStats, WeightPagingManager};

/// 线程调优公共 API:bin 与外部工具共享物理核检测与优先级解析。
/// 模型驻留管理(server 接线):`model` 为 pub(crate),
/// 经最小面重导出供 bin 装配 ModelManager。
pub mod model_management {
    pub use crate::model::heat::DEFAULT_HEAT_PATH;
    pub use crate::model::loader::LocalModelLoader;
    pub use crate::model::manager::ModelManager;
}

pub mod thread_tune {
    pub use crate::device::thread_tune::{
        detect_physical_cores, parse_lscpu_sockets, parse_thread_siblings_lists,
        resolve_worker_threads,
    };
}

/// 硬件感知启动规划公共 API。
pub mod planner {
    pub use crate::device::planner::{
        Bottleneck, HardwarePlan, PlanOverride, Probes, apply_plan, plan,
    };
}

pub use cache::{ComparisonMode, SemanticCache, SemanticCacheConfig, SemanticCacheStats};

// 再导出 sdforge 多协议框架(gRPC E2E 集成测试经此使用生成的 tonic 客户端)
#[cfg(feature = "grpc")]
pub use sdforge;

/// Application state
///
/// 所有能力通过 `AsyncKit<Ready>` 查询。
/// 启动时由 `main.rs` 通过 `kit.set_config()` 注入预构建对象 + `kit.register::<M>()`
/// 注册 17 个 Module,`kit.build().await` 后注入到 `VecboostState`。
///
/// 路由 handler 通过 `state.kit.require::<M>().expect("...")` 检索能力,
/// 或通过 Axum `FromRef` 自动注入(`FromRef` impl 也走 `kit.require`)。
#[derive(Clone)]
pub struct VecboostState {
    /// trait-kit AsyncKit — 模块能力管理中心
    ///
    /// `AsyncKit<Ready>` 是 `Send + Sync`(基于 `Arc<RwLock>`),可安全存入
    /// `VecboostState` 并跨线程共享。包含 17 个 Module 的能力查询入口:
    /// - 4 现有:EmbeddingModule/AuthModule/RateLimitModule/AuditModule
    /// - 13 新增:覆盖原 14 字段剩余 13 个(详见 registry/mod.rs)
    pub(crate) kit: Arc<trait_kit::AsyncKit<trait_kit::AsyncReady>>,
}

impl VecboostState {
    pub fn new(kit: Arc<trait_kit::AsyncKit<trait_kit::AsyncReady>>) -> Self {
        Self { kit }
    }

    pub fn kit(&self) -> &Arc<trait_kit::AsyncKit<trait_kit::AsyncReady>> {
        &self.kit
    }
}

/// 生成 `FromRef<VecboostState>` 实现:直接 require 模式(能力类型非 Option)。
#[cfg(feature = "http")]
macro_rules! impl_from_ref_direct {
    ($target:ty, $module:ty, $msg:literal) => {
        #[cfg(feature = "http")]
        impl FromRef<VecboostState> for $target {
            fn from_ref(state: &VecboostState) -> Self {
                state.kit.require::<$module>().expect($msg)
            }
        }
    };
}

/// 生成 `FromRef<VecboostState>` 实现:Option 能力解包模式。
#[cfg(feature = "http")]
macro_rules! impl_from_ref_option {
    ($target:ty, $module:ty, $key:literal, $msg:literal) => {
        #[cfg(feature = "http")]
        impl FromRef<VecboostState> for $target {
            fn from_ref(state: &VecboostState) -> Self {
                state
                    .kit
                    .require::<$module>()
                    .and_then(|opt| {
                        opt.ok_or_else(|| trait_kit::TraitKitError::MissingCapability {
                            key: $key.to_string(),
                        })
                    })
                    .expect($msg)
            }
        }
    };
}

#[cfg(feature = "http")]
impl_from_ref_direct!(
    Arc<RwLock<EmbeddingService>>,
    registry::EmbeddingModule,
    "EmbeddingService capability not registered in kit"
);

#[cfg(feature = "http")]
impl_from_ref_direct!(
    Arc<RwLock<RerankService>>,
    registry::RerankModule,
    "RerankService capability not registered in kit"
);

#[cfg(feature = "http")]
impl_from_ref_direct!(
    Arc<rate_limit::LimiteronAdapter>,
    registry::RateLimitModule,
    "RateLimitModule capability not registered in kit"
);

#[cfg(feature = "http")]
impl_from_ref_direct!(
    Option<Arc<audit::AuditLogger>>,
    registry::AuditModule,
    "AuditModule capability not registered in kit"
);

#[cfg(all(feature = "http", feature = "auth"))]
impl_from_ref_option!(
    Arc<auth::GarrisonCsrfConfig>,
    registry::CsrfConfigModule,
    "csrf_config (auth disabled at runtime)",
    "GarrisonCsrfConfig capability not available"
);

#[cfg(feature = "http")]
impl_from_ref_option!(
    Arc<metrics::InferenceCollector>,
    registry::MetricsCollectorModule,
    "metrics_collector (not configured)",
    "InferenceCollector capability not available"
);

#[cfg(feature = "http")]
impl_from_ref_option!(
    Arc<metrics::PrometheusCollector>,
    registry::PrometheusCollectorModule,
    "prometheus_collector (not configured)",
    "PrometheusCollector capability not available"
);

/// AuthConfig substate extractor — provides `trusted_proxies` and other auth
/// configuration to middleware via axum's `FromRef` pattern. The config is
/// injected via `kit.set_config(config.auth.clone())` in `main.rs` and
/// retrieved through `kit.config::<AuthConfig>()` at request time.
#[cfg(all(feature = "http", feature = "auth"))]
impl FromRef<VecboostState> for config::app::AuthConfig {
    fn from_ref(state: &VecboostState) -> Self {
        state
            .kit
            .config::<config::app::AuthConfig>()
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "http")]
    use crate::config::model::Precision;
    #[cfg(feature = "http")]
    use crate::engine::InferenceEngine;
    use crate::logger::LoggerModule;
    #[cfg(feature = "http")]
    use crate::pipeline::{PriorityConfig, WorkerConfig};
    #[cfg(feature = "http")]
    use crate::registry::PrometheusCollectorModule;
    #[cfg(feature = "http")]
    use crate::registry::{
        AuditModule, AuthEnabled, CacheConfig, CacheModule, DbConfig, DbModule, EmbeddingModule,
        IpWhitelistModule, MetricsCollectorModule, PipelineEnabled, PipelineQueueModule,
        PriorityCalculatorModule, RateLimitEnabled, RateLimitModule, RerankModule,
        ResponseChannelModule, WorkerManagerModule,
    };
    #[cfg(feature = "auth")]
    use crate::registry::{AuthModule, CsrfConfigModule};
    #[cfg(feature = "http")]
    use async_trait::async_trait;

    #[cfg(feature = "http")]
    struct MockEngine;

    #[cfg(feature = "http")]
    #[async_trait]
    impl InferenceEngine for MockEngine {
        fn embed(&self, _text: &str) -> Result<Vec<f32>, VecboostError> {
            Ok(vec![0.0; 384])
        }

        fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, VecboostError> {
            Ok(texts.iter().map(|_| vec![0.0; 384]).collect())
        }

        fn precision(&self) -> &Precision {
            &Precision::Fp32
        }

        fn supports_mixed_precision(&self) -> bool {
            false
        }

        async fn try_fallback_to_cpu(
            &mut self,
            _config: &crate::config::model::ModelConfig,
        ) -> Result<(), VecboostError> {
            Ok(())
        }
    }

    /// 参数化构建 VecboostState:可选注入 metrics/prometheus/audit 能力
    ///
    /// `metrics` / `prometheus` / `audit` 为 None 时,Module 仍注册但能力查询返回 None,
    /// 用于测试 FromRef panic 路径。其他能力(service/rate_limiter/pipeline 组件)
    /// 始终注入,因为这些是必需能力(missing config = build 失败)。
    #[cfg(feature = "http")]
    async fn make_app_state_with_options(
        metrics: Option<Arc<metrics::InferenceCollector>>,
        prometheus: Option<Arc<metrics::PrometheusCollector>>,
        audit: Option<Arc<audit::AuditLogger>>,
    ) -> VecboostState {
        let engine: Arc<RwLock<dyn InferenceEngine + Send + Sync>> =
            Arc::new(RwLock::new(MockEngine));
        let service = Arc::new(RwLock::new(EmbeddingService::new(engine.clone(), None)));
        let rerank_service = Arc::new(RwLock::new(RerankService::new(engine, None)));
        let rate_limiter = Arc::new(rate_limit::LimiteronAdapter::with_defaults().await);
        let pipeline_queue = Arc::new(pipeline::PriorityRequestQueue::new(100));
        let response_channel = Arc::new(pipeline::ResponseChannel::new());
        let priority_calculator =
            Arc::new(pipeline::PriorityCalculator::new(PriorityConfig::default()));
        let worker_manager = Arc::new(pipeline::WorkerManager::new(
            pipeline_queue.clone(),
            response_channel.clone(),
            WorkerConfig::default(),
            service.clone(),
        ));

        let mut kit = trait_kit::AsyncKit::new();
        // 注入复杂类型能力(预构建对象)
        kit.set_config(service.clone());
        kit.set_config(rerank_service.clone());
        kit.set_config(rate_limiter.clone());
        kit.set_config(metrics.clone());
        kit.set_config(prometheus.clone());
        kit.set_config(audit.clone());
        kit.set_config(pipeline_queue.clone());
        kit.set_config(response_channel.clone());
        kit.set_config(priority_calculator.clone());
        kit.set_config(worker_manager.clone());
        kit.set_config(Vec::<String>::new());
        // bool newtype 配置(missing = false,与 CacheModule/DbModule 一致)
        kit.set_config(AuthEnabled(false));
        kit.set_config(RateLimitEnabled(false));
        kit.set_config(PipelineEnabled(false));
        kit.set_config(CacheConfig {
            enabled: false,
            size: 0,
        });
        kit.set_config(DbConfig { enabled: false });
        kit.set_config(RerankConfig::default());

        // LoggerModule: 构建最小 logger manager 注入 kit
        let logger_manager = Arc::new(
            inklog::LoggerManager::builder()
                .level("warn")
                .console(false)
                .build()
                .await
                .expect("test logger manager"),
        );
        kit.set_config(logger_manager);

        // auth feature 能力(全部 None — 默认禁用)
        #[cfg(feature = "auth")]
        {
            kit.set_config(Option::<Arc<crate::auth::GarrisonHandle>>::None);
            kit.set_config(Option::<Arc<crate::auth::GarrisonCsrfConfig>>::None);
        }

        // 注册所有 Module(除 ConfigWatcherModule;auth 模块按 feature 注入)
        kit.register::<LoggerModule>().unwrap();
        kit.register::<EmbeddingModule>().unwrap();
        kit.register::<RerankModule>().unwrap();
        kit.register::<RateLimitModule>().unwrap();
        kit.register::<CacheModule>().unwrap();
        kit.register::<DbModule>().unwrap();
        kit.register::<AuditModule>().unwrap();
        kit.register::<MetricsCollectorModule>().unwrap();
        kit.register::<PrometheusCollectorModule>().unwrap();
        kit.register::<IpWhitelistModule>().unwrap();
        kit.register::<PipelineQueueModule>().unwrap();
        kit.register::<ResponseChannelModule>().unwrap();
        kit.register::<PriorityCalculatorModule>().unwrap();
        kit.register::<WorkerManagerModule>().unwrap();

        #[cfg(feature = "auth")]
        {
            kit.register::<AuthModule>().unwrap();
            kit.register::<CsrfConfigModule>().unwrap();
        }

        kit.register_lifecycle::<EmbeddingModule>();
        kit.register_lifecycle::<RerankModule>();
        kit.register_lifecycle::<RateLimitModule>();
        kit.register_lifecycle::<AuditModule>();
        kit.register_health_check::<EmbeddingModule>();
        kit.register_health_check::<RerankModule>();
        kit.register_health_check::<RateLimitModule>();
        kit.register_health_check::<CacheModule>();

        let kit = kit.build().await.expect("Failed to build AsyncKit");
        VecboostState { kit: Arc::new(kit) }
    }

    /// 默认完整 VecboostState:metrics=Some, prometheus=Some, audit=None
    #[cfg(feature = "http")]
    pub(crate) async fn make_app_state() -> VecboostState {
        make_app_state_with_options(
            Some(Arc::new(metrics::InferenceCollector::new())),
            Some(Arc::new(
                metrics::PrometheusCollector::new().expect("Failed to create PrometheusCollector"),
            )),
            None,
        )
        .await
    }

    // -------------------------------------------------------------------------
    // 构建与 Clone 测试
    // -------------------------------------------------------------------------

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_app_state_construction() {
        let state = make_app_state().await;
        assert!(state.kit.contains::<EmbeddingModule>());
        assert!(state.kit.contains::<RerankModule>());
        assert!(state.kit.contains::<RateLimitModule>());
        assert!(state.kit.contains::<AuditModule>());
        assert!(state.kit.contains::<MetricsCollectorModule>());
        assert!(state.kit.contains::<PrometheusCollectorModule>());
        assert!(state.kit.contains::<IpWhitelistModule>());
        assert!(state.kit.contains::<PipelineQueueModule>());
        assert!(state.kit.contains::<WorkerManagerModule>());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_app_state_clone_preserves_kit_arc() {
        let state = make_app_state().await;
        let cloned = state.clone();
        assert!(Arc::ptr_eq(&state.kit, &cloned.kit));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_app_state_multiple_clones_share_kit() {
        let state = make_app_state().await;
        let clone1 = state.clone();
        let clone2 = state.clone();
        let clone3 = state.clone();
        assert!(Arc::ptr_eq(&state.kit, &clone1.kit));
        assert!(Arc::ptr_eq(&state.kit, &clone2.kit));
        assert!(Arc::ptr_eq(&state.kit, &clone3.kit));
    }

    // -------------------------------------------------------------------------
    // kit.require 能力查询测试
    // -------------------------------------------------------------------------

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_embedding_service() {
        let state = make_app_state().await;
        let service = state.kit.require::<EmbeddingModule>().unwrap();
        let _guard = service.read().await;
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_rate_limiter() {
        let state = make_app_state().await;
        let _limiter = state.kit.require::<RateLimitModule>().unwrap();
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_metrics_collector_returns_some() {
        let state = make_app_state().await;
        let collector = state.kit.require::<MetricsCollectorModule>().unwrap();
        assert!(collector.is_some());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_prometheus_collector_returns_some() {
        let state = make_app_state().await;
        let collector = state.kit.require::<PrometheusCollectorModule>().unwrap();
        assert!(collector.is_some());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_audit_logger_returns_none() {
        let state = make_app_state().await;
        let logger = state.kit.require::<AuditModule>().unwrap();
        assert!(logger.is_none());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_ip_whitelist_empty() {
        let state = make_app_state().await;
        let whitelist = state.kit.require::<IpWhitelistModule>().unwrap();
        assert!(whitelist.is_empty());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_config_bool_flags_default_false() {
        let state = make_app_state().await;
        let auth_enabled = state
            .kit
            .config::<AuthEnabled>()
            .map(|c| c.0)
            .unwrap_or(false);
        let rate_limit_enabled = state
            .kit
            .config::<RateLimitEnabled>()
            .map(|c| c.0)
            .unwrap_or(false);
        let pipeline_enabled = state
            .kit
            .config::<PipelineEnabled>()
            .map(|c| c.0)
            .unwrap_or(false);
        assert!(!auth_enabled);
        assert!(!rate_limit_enabled);
        assert!(!pipeline_enabled);
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_pipeline_components() {
        let state = make_app_state().await;
        let _queue = state.kit.require::<PipelineQueueModule>().unwrap();
        let _channel = state.kit.require::<ResponseChannelModule>().unwrap();
        let _calculator = state.kit.require::<PriorityCalculatorModule>().unwrap();
        let _manager = state.kit.require::<WorkerManagerModule>().unwrap();
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_cache_and_db_default_false() {
        let state = make_app_state().await;
        let cache_enabled = state.kit.require::<CacheModule>().unwrap();
        let db_enabled = state.kit.require::<DbModule>().unwrap();
        assert!(!cache_enabled);
        assert!(!db_enabled);
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_require_logger_module() {
        let state = make_app_state().await;
        assert!(
            state.kit.contains::<LoggerModule>(),
            "LoggerModule should be registered in kit"
        );
        let logger: Arc<inklog::LoggerManager> = state
            .kit
            .require::<LoggerModule>()
            .expect("require LoggerModule");
        let _ = logger;
    }

    // -------------------------------------------------------------------------
    // FromRef 测试(http feature)
    // -------------------------------------------------------------------------

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_service() {
        let state = make_app_state().await;
        let service: Arc<RwLock<EmbeddingService>> = FromRef::from_ref(&state);
        let kit_service = state.kit.require::<EmbeddingModule>().unwrap();
        assert!(Arc::ptr_eq(&service, &kit_service));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_rate_limiter() {
        let state = make_app_state().await;
        let limiter: Arc<rate_limit::LimiteronAdapter> = FromRef::from_ref(&state);
        let kit_limiter = state.kit.require::<RateLimitModule>().unwrap();
        assert!(Arc::ptr_eq(&limiter, &kit_limiter));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_metrics_collector() {
        let state = make_app_state().await;
        let collector: Arc<metrics::InferenceCollector> = FromRef::from_ref(&state);
        let kit_collector = state.kit.require::<MetricsCollectorModule>().unwrap();
        assert!(Arc::ptr_eq(&collector, kit_collector.as_ref().unwrap()));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_prometheus_collector() {
        let state = make_app_state().await;
        let collector: Arc<metrics::PrometheusCollector> = FromRef::from_ref(&state);
        let kit_collector = state.kit.require::<PrometheusCollectorModule>().unwrap();
        assert!(Arc::ptr_eq(&collector, kit_collector.as_ref().unwrap()));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_audit_logger_returns_none() {
        let state = make_app_state().await;
        let logger: Option<Arc<audit::AuditLogger>> = FromRef::from_ref(&state);
        assert!(logger.is_none());
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_audit_logger_returns_some() {
        let config = audit::AuditConfig {
            enabled: false,
            ..Default::default()
        };
        let logger = Arc::new(audit::AuditLogger::new(config));
        let state = make_app_state_with_options(
            Some(Arc::new(metrics::InferenceCollector::new())),
            Some(Arc::new(
                metrics::PrometheusCollector::new().expect("Failed to create PrometheusCollector"),
            )),
            Some(logger.clone()),
        )
        .await;
        let extracted: Option<Arc<audit::AuditLogger>> = FromRef::from_ref(&state);
        assert!(extracted.is_some());
        assert!(Arc::ptr_eq(&extracted.unwrap(), &logger));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_service_after_clone() {
        let state = make_app_state().await;
        let cloned = state.clone();
        let service: Arc<RwLock<EmbeddingService>> = FromRef::from_ref(&cloned);
        let kit_service = state.kit.require::<EmbeddingModule>().unwrap();
        assert!(Arc::ptr_eq(&service, &kit_service));
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_rate_limiter_after_clone() {
        let state = make_app_state().await;
        let cloned = state.clone();
        let limiter: Arc<rate_limit::LimiteronAdapter> = FromRef::from_ref(&cloned);
        let kit_limiter = state.kit.require::<RateLimitModule>().unwrap();
        assert!(Arc::ptr_eq(&limiter, &kit_limiter));
    }

    // -------------------------------------------------------------------------
    // FromRef panic 测试(None 能力触发 panic)
    // -------------------------------------------------------------------------

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_metrics_collector_panics_when_none() {
        let state = make_app_state_with_options(None, None, None).await;
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _: Arc<metrics::InferenceCollector> = FromRef::from_ref(&state);
        }));
        assert!(
            result.is_err(),
            "from_ref should panic when metrics_collector is None"
        );
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_from_ref_prometheus_collector_panics_when_none() {
        let state = make_app_state_with_options(None, None, None).await;
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _: Arc<metrics::PrometheusCollector> = FromRef::from_ref(&state);
        }));
        assert!(
            result.is_err(),
            "from_ref should panic when prometheus_collector is None"
        );
    }

    // -------------------------------------------------------------------------
    // VecboostState Send + Sync 编译期断言
    // -------------------------------------------------------------------------

    #[test]
    fn test_vecboost_state_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<VecboostState>();
    }

    #[test]
    fn test_vecboost_state_is_clone() {
        fn assert_clone<T: Clone>() {}
        assert_clone::<VecboostState>();
    }

    // -------------------------------------------------------------------------
    // Health check + graceful shutdown integration tests
    // -------------------------------------------------------------------------

    /// Verify health checks return Healthy for all registered modules.
    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_health_checks_return_healthy() {
        use trait_kit::prelude::HealthStatus;

        let state = make_app_state().await;

        let embedding_health = state.kit.health_check::<EmbeddingModule>();
        assert!(
            embedding_health.is_ok(),
            "EmbeddingModule health check should be registered"
        );
        assert_eq!(embedding_health.unwrap(), HealthStatus::Healthy);

        let rerank_health = state.kit.health_check::<RerankModule>();
        assert!(
            rerank_health.is_ok(),
            "RerankModule health check should be registered"
        );
        assert_eq!(rerank_health.unwrap(), HealthStatus::Healthy);

        let rate_limit_health = state.kit.health_check::<RateLimitModule>();
        assert!(
            rate_limit_health.is_ok(),
            "RateLimitModule health check should be registered"
        );
        assert_eq!(rate_limit_health.unwrap(), HealthStatus::Healthy);

        let cache_health = state.kit.health_check::<CacheModule>();
        assert!(
            cache_health.is_ok(),
            "CacheModule health check should be registered"
        );
        // Cache disabled → Degraded (expected config state, not Unhealthy)
        assert_eq!(
            cache_health.unwrap(),
            HealthStatus::Degraded {
                detail: "cache disabled".into(),
            }
        );
    }

    /// Verify AsyncKit shutdown invokes lifecycle hooks without panic.
    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_kit_shutdown_completes_cleanly() {
        let state = make_app_state().await;
        // AsyncKit::shutdown_async() awaits async shutdown callbacks (lifecycle modules)
        // Should not panic even with async lifecycle modules registered
        state.kit.shutdown_async().await;
    }

    /// VecboostState::new() and kit()
    /// Verifies that `kit()` returns a reference to the internal `Arc<AsyncKit>`
    /// and that all registered modules are accessible through it.
    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_vecboost_state_new_and_kit_accessor() {
        let state = make_app_state().await;
        let kit_ref = state.kit();
        // kit() returns &Arc<AsyncKit>; only `state` owns the Arc → strong_count == 1
        assert_eq!(Arc::strong_count(kit_ref), 1);
        assert!(kit_ref.contains::<EmbeddingModule>());
        assert!(kit_ref.contains::<RerankModule>());
        assert!(kit_ref.contains::<RateLimitModule>());
        assert!(kit_ref.contains::<AuditModule>());
    }

    /// VecboostState::new() constructs from Arc<AsyncKit>
    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_vecboost_state_constructor() {
        let state = make_app_state().await;
        let kit_clone = state.kit().clone();
        let new_state = VecboostState::new(kit_clone);
        assert!(new_state.kit.contains::<EmbeddingModule>());
    }

    /// MockEngine direct trait method calls for coverage
    #[cfg(feature = "http")]
    #[tokio::test]
    async fn test_mock_engine_direct_method_calls() {
        let engine = MockEngine;
        let vec = engine.embed("hello").unwrap();
        assert_eq!(vec.len(), 384);
        assert!(vec.iter().all(|&v| v == 0.0));
        let texts = vec!["hello".to_string(), "world".to_string()];
        let batch = engine.embed_batch(&texts).unwrap();
        assert_eq!(batch.len(), 2);
        assert_eq!(batch[0].len(), 384);
        assert_eq!(*engine.precision(), Precision::Fp32);
        assert!(!engine.supports_mixed_precision());
        let config = crate::config::model::ModelConfig::default();
        let mut engine_mut = MockEngine;
        let result = engine_mut.try_fallback_to_cpu(&config).await;
        assert!(result.is_ok());
    }

    /// FromRef<VecboostState> for AuthConfig
    #[cfg(all(feature = "http", feature = "auth"))]
    #[tokio::test]
    async fn test_from_ref_auth_config_returns_default() {
        let state = make_app_state().await;
        let auth_config: config::app::AuthConfig = FromRef::from_ref(&state);
        // When auth is not configured, should return default
        let _ = auth_config;
    }
}