forked from Michael-A-Kuykendall/shimmy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
1854 lines (1618 loc) · 67.4 KB
/
main.rs
File metadata and controls
1854 lines (1618 loc) · 67.4 KB
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
// Suppress function pointer comparison warnings from auto-generated bindings
#![allow(unpredictable_function_pointer_comparisons)]
mod anthropic_compat;
mod api;
mod api_errors;
mod auto_discovery;
mod cache;
mod cli;
mod engine;
mod invariant_ppt;
mod main_integration;
mod model_registry;
mod observability;
mod openai_compat;
mod port_manager;
mod server;
mod templates;
#[cfg(feature = "vision")]
mod vision;
#[cfg(feature = "vision")]
mod vision_license;
mod util {
pub mod diag;
pub mod memory;
}
use clap::Parser;
use model_registry::{ModelEntry, Registry};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::info;
pub struct AppState {
pub engine: Box<dyn engine::InferenceEngine>,
pub registry: Registry,
pub observability: observability::ObservabilityManager,
pub response_cache: cache::ResponseCache,
#[cfg(feature = "vision")]
pub vision_license_manager: Option<crate::vision_license::VisionLicenseManager>,
}
impl AppState {
pub fn new(engine: Box<dyn engine::InferenceEngine>, registry: Registry) -> Self {
#[allow(unused_mut)]
let mut state = Self {
engine,
registry,
observability: observability::ObservabilityManager::new(),
response_cache: cache::ResponseCache::new(),
#[cfg(feature = "vision")]
vision_license_manager: None,
};
#[cfg(feature = "vision")]
{
state.vision_license_manager = Some(crate::vision_license::VisionLicenseManager::new());
}
state
}
}
/// Runtime version validation - prevents Issue #63 broken binary distribution
fn validate_runtime_version() {
let version = env!("CARGO_PKG_VERSION");
// Check for the specific issue reported in #63
if version == "0.1.0" {
eprintln!();
eprintln!("❌ ERROR: Invalid shimmy version detected!");
eprintln!();
eprintln!("This binary reports version 0.1.0, which indicates it was built incorrectly.");
eprintln!("This is the exact issue reported in GitHub Issue #63.");
eprintln!();
eprintln!("🔧 Solutions:");
eprintln!(" • Download the official release from: https://github.com/Michael-A-Kuykendall/shimmy/releases");
eprintln!(" • If building from source, ensure you're building from a proper Git tag");
eprintln!(" • If forking, update the version in Cargo.toml before building");
eprintln!();
eprintln!("Current version: {}", version);
eprintln!("Expected version: 1.4.1+ (not 0.1.0)");
eprintln!();
std::process::exit(1);
}
// Additional validation for empty or malformed versions
if version.is_empty() {
eprintln!("ERROR: Empty version detected. This binary was built incorrectly.");
std::process::exit(1);
}
// Validate basic semver format
let parts: Vec<&str> = version.split('.').collect();
if parts.len() < 2 || parts.iter().take(2).any(|p| p.parse::<u32>().is_err()) {
eprintln!(
"ERROR: Invalid version format '{}'. Expected semantic versioning.",
version
);
std::process::exit(1);
}
}
/// Print startup diagnostics for serve command
fn print_startup_diagnostics(
version: &str,
#[cfg_attr(not(feature = "llama"), allow(unused_variables))] gpu_backend: Option<&str>,
#[cfg_attr(not(feature = "llama"), allow(unused_variables))] cpu_moe: bool,
#[cfg_attr(not(feature = "llama"), allow(unused_variables))] n_cpu_moe: Option<usize>,
model_count: usize,
) {
println!("🎯 Shimmy v{}", version);
// GPU backend info
#[cfg(feature = "llama")]
{
let backend_display = match gpu_backend {
Some("cpu") => "CPU only".to_string(),
Some("cuda") => "CUDA (GPU acceleration)".to_string(),
Some("vulkan") => "Vulkan (GPU acceleration)".to_string(),
Some("opencl") => "OpenCL (GPU acceleration)".to_string(),
Some("auto") | None => {
// Auto-detect logic mirrors what LlamaEngine does
if cfg!(feature = "llama-cuda") {
"CUDA (auto-detected)".to_string()
} else if cfg!(feature = "llama-vulkan") {
"Vulkan (auto-detected)".to_string()
} else if cfg!(feature = "llama-opencl") {
"OpenCL (auto-detected)".to_string()
} else {
"CPU (no GPU acceleration)".to_string()
}
}
Some(other) => format!("{} (custom)", other),
};
println!("🔧 Backend: {}", backend_display);
}
#[cfg(not(feature = "llama"))]
{
println!("🔧 Backend: Stub mode (no llama feature)");
}
// MoE configuration - NOW WORKING (Issue #108 fix)
#[cfg(feature = "llama")]
if cpu_moe || n_cpu_moe.is_some() {
if let Some(n) = n_cpu_moe {
println!(
"🧠 MoE: CPU offload first {} layers (saves VRAM for large MoE models)",
n
);
} else if cpu_moe {
println!("🧠 MoE: CPU offload ALL expert tensors (saves ~80-85% VRAM)");
}
}
// Model count
println!("📦 Models: {} available", model_count);
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Version validation - prevents Issue #63 distribution of broken binaries
validate_runtime_version();
// Smart ANSI detection: respect NO_COLOR, check TTY, and verify TERM capability
let use_ansi = std::env::var("NO_COLOR").is_err()
&& std::io::IsTerminal::is_terminal(&std::io::stdout())
&& std::env::var("TERM")
.map(|t| !t.is_empty() && t != "dumb")
.unwrap_or(false);
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.with_ansi(use_ansi)
.init();
// Platform capability notice
#[cfg(all(target_arch = "aarch64", target_os = "macos", not(feature = "llama")))]
info!("llama.cpp temporarily disabled on macOS ARM64 due to upstream i8mm build incompatibility; using SafeTensors backend");
let cli = cli::Cli::parse();
// Add custom model directories from command line to environment
if let Some(model_dirs) = &cli.model_dirs {
std::env::set_var("SHIMMY_MODEL_PATHS", model_dirs);
}
// Initialize registry with auto-discovery
let mut reg = Registry::with_discovery();
// Add default model from environment variables if available
reg.register(ModelEntry {
name: "phi3-lora".into(),
base_path: std::env::var("SHIMMY_BASE_GGUF")
.unwrap_or_else(|_| "./models/phi3-mini.gguf".into())
.into(),
lora_path: std::env::var("SHIMMY_LORA_GGUF").ok().map(Into::into),
template: Some("chatml".into()),
ctx_len: Some(8192),
n_threads: None,
});
// Create engine with MoE configuration if needed
let engine: Box<dyn engine::InferenceEngine> = {
#[cfg(feature = "llama")]
{
let mut adapter = engine::adapter::InferenceEngineAdapter::new_with_backend(
cli.gpu_backend.as_deref(),
);
// Apply MoE configuration from global flags
if cli.cpu_moe || cli.n_cpu_moe.is_some() {
adapter = adapter.with_moe_config(cli.cpu_moe, cli.n_cpu_moe);
}
Box::new(adapter)
}
#[cfg(not(feature = "llama"))]
{
let adapter = engine::adapter::InferenceEngineAdapter::new_with_backend(
cli.gpu_backend.as_deref(),
);
Box::new(adapter)
}
};
// Handle model-path registration for serve command
if let cli::Command::Serve {
model_path: Some(ref path),
..
} = cli.cmd
{
let path_buf = PathBuf::from(path);
if path_buf.exists() {
let model_name = path_buf
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("direct-model")
.to_string();
// Register the direct model before creating AppState
reg.register(ModelEntry {
name: model_name.clone(),
base_path: path_buf.clone(),
lora_path: None,
template: None,
ctx_len: None,
n_threads: None,
});
println!("🎯 Direct model loaded: {} -> {}", model_name, path);
} else {
eprintln!("❌ Model file not found: {}", path);
std::process::exit(1);
}
}
let state = AppState::new(engine, reg);
let state = Arc::new(state);
match cli.cmd {
cli::Command::Serve { ref bind, .. } => {
// Use smart bind address resolution instead of direct parsing
let addr = port_manager::GLOBAL_PORT_ALLOCATOR
.resolve_bind_address(bind)
.unwrap_or_else(|e| {
eprintln!("❌ Failed to resolve bind address '{}': {}", bind, e);
eprintln!();
eprintln!("💡 Valid bind address examples:");
eprintln!(" auto # Auto-allocate (default)");
eprintln!(" 127.0.0.1:11435 # Specific address");
eprintln!(" 0.0.0.0:8080 # All interfaces");
eprintln!();
eprintln!("🔧 Environment variable: SHIMMY_BIND_ADDRESS=127.0.0.1:11435");
std::process::exit(1);
});
// Print startup diagnostics before server starts
print_startup_diagnostics(
env!("CARGO_PKG_VERSION"),
cli.gpu_backend.as_deref(),
cli.cpu_moe,
cli.n_cpu_moe,
0, // Will update after model discovery
);
println!("🚀 Starting server on {}", addr);
// Auto-register discovered models if we only have the default
let manual_count = state.registry.list().len();
if manual_count <= 1 {
// Only the default phi3-lora entry
// Create new engine with same configuration (including MoE if set)
let enhanced_engine: Box<dyn engine::InferenceEngine> = {
#[cfg(feature = "llama")]
{
let mut adapter = engine::adapter::InferenceEngineAdapter::new_with_backend(
cli.gpu_backend.as_deref(),
);
// Apply MoE configuration from global flags
if cli.cpu_moe || cli.n_cpu_moe.is_some() {
adapter = adapter.with_moe_config(cli.cpu_moe, cli.n_cpu_moe);
}
Box::new(adapter)
}
#[cfg(not(feature = "llama"))]
{
let adapter = engine::adapter::InferenceEngineAdapter::new_with_backend(
cli.gpu_backend.as_deref(),
);
Box::new(adapter)
}
};
let mut enhanced_state = AppState::new(enhanced_engine, state.registry.clone());
enhanced_state.registry.auto_register_discovered();
let enhanced_state = Arc::new(enhanced_state);
let available_models = enhanced_state.registry.list_all_available();
if available_models.is_empty() {
eprintln!("❌ No models available. Please:");
eprintln!(" • Set SHIMMY_BASE_GGUF environment variable, or");
eprintln!(" • Place .gguf files in ./models/ directory, or");
eprintln!(" • Place .gguf files in ~/.cache/huggingface/hub/");
std::process::exit(1);
}
// Show final model count and ready message
println!("📦 Models: {} available", available_models.len());
println!("✅ Ready to serve requests");
println!(" • POST /api/generate (streaming + non-streaming)");
println!(" • GET /health (health check + metrics)");
println!(" • GET /v1/models (OpenAI-compatible)");
info!(%addr, models=%available_models.len(), "shimmy serving with {} available models", available_models.len());
return server::run(addr, enhanced_state).await;
}
// Use existing state if manually configured
let available_models = state.registry.list_all_available();
if available_models.is_empty() {
eprintln!("❌ No models available. Please:");
eprintln!(" • Set SHIMMY_BASE_GGUF environment variable, or");
eprintln!(" • Place .gguf files in ./models/ directory, or");
eprintln!(" • Place .gguf files in ~/.cache/huggingface/hub/");
std::process::exit(1);
}
// Show final model count and ready message
println!("📦 Models: {} available", available_models.len());
println!("✅ Ready to serve requests");
println!(" • POST /api/generate (streaming + non-streaming)");
println!(" • GET /health (health check + metrics)");
println!(" • GET /v1/models (OpenAI-compatible)");
info!(%addr, models=%available_models.len(), "shimmy serving with {} available models", available_models.len());
server::run(addr, state).await?;
}
cli::Command::List { short } => {
if short {
// Short format: just model names for programmatic use
let all_available = state.registry.list_all_available();
for model_name in all_available {
println!("{}", model_name);
}
} else {
// Original verbose format
// Show manually registered models
let manual_models = state.registry.list();
if !manual_models.is_empty() {
println!("📋 Registered Models:");
for e in &manual_models {
println!(" {} => {:?}", e.name, e.base_path);
}
}
// Show auto-discovered models
let auto_discovered = state.registry.discovered_models.clone();
if !auto_discovered.is_empty() {
if !manual_models.is_empty() {
println!();
}
println!("🔍 Auto-Discovered Models:");
for (name, model) in auto_discovered {
let size_mb = model.size_bytes / (1024 * 1024);
let type_info = match (&model.parameter_count, &model.quantization) {
(Some(params), Some(quant)) => format!(" ({}·{})", params, quant),
(Some(params), None) => format!(" ({})", params),
(None, Some(quant)) => format!(" ({})", quant),
_ => String::new(),
};
let lora_info = if model.lora_path.is_some() {
" + LoRA"
} else {
""
};
println!(
" {} => {:?} [{}MB{}{}]",
name, model.path, size_mb, type_info, lora_info
);
}
}
// Show total available models
let all_available = state.registry.list_all_available();
if all_available.is_empty() {
println!(
"❌ No models found. Set SHIMMY_BASE_GGUF or place .gguf files in ./models/"
);
} else {
println!("\n✅ Total available models: {}", all_available.len());
}
}
}
cli::Command::Discover { llm_only } => {
println!("🔍 Refreshing model discovery...");
let registry = Registry::with_discovery();
let mut discovered = registry.discovered_models.clone();
// Apply LLM-only filtering if requested
if llm_only {
discovered.retain(|name, _| {
let name_lower = name.to_lowercase();
// Filter out known non-LLM model types
!name_lower.contains("clip")
&& !name_lower.contains("text-to-image")
&& !name_lower.contains("vision")
&& !name_lower.contains("image")
&& !name_lower.contains("video")
&& !name_lower.contains("audio")
&& !name_lower.contains("tts")
&& !name_lower.contains("stt")
&& !name_lower.contains("embedding")
&& !name_lower.contains("encoder")
});
println!("🎯 Filtering to LLM models only...");
}
if discovered.is_empty() {
if llm_only {
println!("❌ No LLM models found after filtering");
println!("💡 Try running without --llm-only to see all models");
} else {
println!("❌ No models found in search paths:");
let discovery = crate::auto_discovery::ModelAutoDiscovery::new();
for path in &discovery.search_paths {
println!(" • {:?}", path);
}
println!(" • Ollama models (if installed)");
println!("\n💡 Try downloading a GGUF model or setting SHIMMY_BASE_GGUF");
}
} else {
println!("✅ Found {} models:", discovered.len());
for (name, model) in discovered {
let size_mb = model.size_bytes / (1024 * 1024);
let lora_info = if model.lora_path.is_some() {
" + LoRA"
} else {
""
};
println!(" {} [{}MB{}]", name, size_mb, lora_info);
println!(" Base: {:?}", model.path);
if let Some(lora) = &model.lora_path {
println!(" LoRA: {:?}", lora);
}
}
}
}
cli::Command::Probe { name } => {
let Some(spec) = state.registry.to_spec(&name) else {
anyhow::bail!("no model {name}");
};
match state.engine.load(&spec).await {
Ok(_) => println!("ok: loaded {name}"),
Err(e) => {
eprintln!("probe failed: {e}");
std::process::exit(2);
}
}
}
cli::Command::Bench { name, max_tokens } => {
let Some(spec) = state.registry.to_spec(&name) else {
anyhow::bail!("no model {name}");
};
let loaded = state.engine.load(&spec).await?;
let t0 = std::time::Instant::now();
let out = loaded
.generate(
"Say hi.",
engine::GenOptions {
max_tokens,
stream: false,
..Default::default()
},
None,
)
.await?;
let elapsed = t0.elapsed();
println!("bench output (truncated): {}", &out[..out.len().min(120)]);
println!("elapsed: {:?}", elapsed);
}
cli::Command::Generate {
name,
prompt,
max_tokens,
} => {
let Some(spec) = state.registry.to_spec(&name) else {
anyhow::bail!("no model {name}");
};
let loaded = state.engine.load(&spec).await?;
let out = loaded
.generate(
&prompt,
engine::GenOptions {
max_tokens,
stream: false,
..Default::default()
},
None,
)
.await?;
println!("{}", out);
}
cli::Command::GpuInfo => {
println!("🖥️ GPU Backend Information");
println!();
// Check llama.cpp backend info
#[cfg(feature = "llama")]
{
use crate::engine::llama::LlamaEngine;
let llama_engine = LlamaEngine::new_with_backend(cli.gpu_backend.as_deref());
println!("🔧 llama.cpp Backend: {}", llama_engine.get_backend_info());
// Show available features
println!("📋 Available GPU Features:");
#[cfg(feature = "llama-cuda")]
println!(" ✅ CUDA support enabled");
#[cfg(not(feature = "llama-cuda"))]
println!(" ❌ CUDA support disabled");
#[cfg(feature = "llama-vulkan")]
println!(" ✅ Vulkan support enabled");
#[cfg(not(feature = "llama-vulkan"))]
println!(" ❌ Vulkan support disabled");
#[cfg(feature = "llama-opencl")]
println!(" ✅ OpenCL support enabled");
#[cfg(not(feature = "llama-opencl"))]
println!(" ❌ OpenCL support disabled");
}
#[cfg(not(feature = "llama"))]
{
println!("❌ llama.cpp backend not available (compile with --features llama)");
}
// Check MLX backend info
#[cfg(feature = "mlx")]
{
use crate::engine::mlx::MLXEngine;
if MLXEngine::is_hardware_supported() {
// Check if MLX Python packages are available
let python_available = MLXEngine::check_mlx_python_available();
if python_available {
println!("🍎 MLX Backend: ✅ Available (Apple Silicon + MLX installed)");
} else {
println!("🍎 MLX Backend: ⚠️ Hardware supported (Apple Silicon detected)");
println!(" 📦 MLX Python packages not found");
println!(" 💡 Install with: pip install mlx-lm");
}
} else {
println!("🍎 MLX Backend: ❌ Not supported (requires Apple Silicon macOS)");
}
}
#[cfg(not(feature = "mlx"))]
{
println!("🍎 MLX Backend: Disabled (compile with --features mlx)");
}
println!();
println!("💡 To enable GPU acceleration:");
#[cfg(target_os = "macos")]
if std::env::consts::ARCH == "aarch64" {
println!(
" cargo install shimmy --features apple # Apple Silicon optimized"
);
println!(" cargo install shimmy --features gpu # All GPU backends");
println!(
" pip install mlx-lm # For MLX Python support"
);
} else {
println!(" cargo install shimmy --features llama-cuda # NVIDIA CUDA");
println!(
" cargo install shimmy --features llama-vulkan # Cross-platform Vulkan"
);
println!(" cargo install shimmy --features llama-opencl # AMD/Intel OpenCL");
println!(" cargo install shimmy --features gpu # All GPU backends");
}
#[cfg(not(target_os = "macos"))]
{
println!(" cargo install shimmy --features llama-cuda # NVIDIA CUDA");
println!(
" cargo install shimmy --features llama-vulkan # Cross-platform Vulkan"
);
println!(" cargo install shimmy --features llama-opencl # AMD/Intel OpenCL");
println!(" cargo install shimmy --features gpu # All GPU backends");
}
}
cli::Command::Init {
template,
output,
name,
} => {
let result = templates::generate_template(&template, &output, name.as_deref());
match result {
Ok(message) => println!("{}", message),
Err(e) => {
eprintln!("❌ Template generation failed: {}", e);
std::process::exit(1);
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::InferenceEngine;
use std::env;
use std::sync::Arc;
// Mock engine that doesn't require actual model loading
struct MockEngine;
#[async_trait::async_trait]
impl engine::InferenceEngine for MockEngine {
async fn load(
&self,
_spec: &engine::ModelSpec,
) -> anyhow::Result<Box<dyn engine::LoadedModel>> {
Ok(Box::new(MockLoadedModel))
}
}
struct MockLoadedModel;
#[async_trait::async_trait]
impl engine::LoadedModel for MockLoadedModel {
async fn generate(
&self,
prompt: &str,
opts: engine::GenOptions,
_on_token: Option<Box<dyn FnMut(String) + Send>>,
) -> anyhow::Result<String> {
Ok(format!(
"Generated response to: {} (max_tokens: {})",
prompt, opts.max_tokens
))
}
}
#[tokio::test]
async fn test_main_initialization_paths() {
// Test initialization paths in main() - lines 25-44
env::remove_var("SHIMMY_BASE_GGUF");
env::remove_var("SHIMMY_LORA_GGUF");
// Test registry with discovery (line 30)
let mut reg = model_registry::Registry::with_discovery();
// Test model registration with default values (lines 33-40)
reg.register(model_registry::ModelEntry {
name: "phi3-lora".into(),
base_path: "./models/phi3-mini.gguf".into(),
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(8192),
n_threads: None,
});
// Test engine creation (line 42)
let engine: Box<dyn engine::InferenceEngine> =
Box::new(engine::adapter::InferenceEngineAdapter::new());
// Test state creation (lines 43-44)
let state = AppState::new(engine, reg);
let _state_arc = Arc::new(state);
// Test completed successfully
}
#[tokio::test]
async fn test_environment_variable_handling() {
// Test environment variable handling (lines 35-36)
// First clean up any existing vars to ensure clean state
env::remove_var("SHIMMY_BASE_GGUF");
env::remove_var("SHIMMY_LORA_GGUF");
env::set_var("SHIMMY_BASE_GGUF", "/custom/path/model.gguf");
env::set_var("SHIMMY_LORA_GGUF", "/custom/path/lora.safetensors");
let base_path =
env::var("SHIMMY_BASE_GGUF").unwrap_or_else(|_| "./models/phi3-mini.gguf".into());
let lora_path = env::var("SHIMMY_LORA_GGUF").ok();
assert_eq!(base_path, "/custom/path/model.gguf");
assert_eq!(lora_path, Some("/custom/path/lora.safetensors".to_string()));
// Clean up
env::remove_var("SHIMMY_BASE_GGUF");
env::remove_var("SHIMMY_LORA_GGUF");
}
#[test]
fn test_serve_command_address_parsing() {
// Test address parsing with dynamic port allocation
use crate::port_manager::GLOBAL_PORT_ALLOCATOR;
let dynamic_port = GLOBAL_PORT_ALLOCATOR
.allocate_ephemeral_port("test-serve-parsing")
.unwrap();
let bind_str = format!("127.0.0.1:{}", dynamic_port);
let addr: std::net::SocketAddr = bind_str.parse().expect("bad bind address");
assert_eq!(addr.port(), dynamic_port);
GLOBAL_PORT_ALLOCATOR.release_port(dynamic_port);
// Test invalid address parsing
let invalid_bind = "invalid:address";
let result = invalid_bind.parse::<std::net::SocketAddr>();
assert!(result.is_err());
}
#[test]
fn test_serve_command_model_count_logic() {
// Test model count logic (lines 51-52)
let registry = model_registry::Registry::with_discovery();
let manual_count = registry.list().len();
// Test condition for auto-registration
let _should_auto_register = manual_count <= 1;
// This will be true in test environment with no models
// Either auto-registration path is valid - test that logic works
}
#[tokio::test]
async fn test_list_command_execution_logic() {
// Test List command execution logic (lines 86-121)
let mut registry = model_registry::Registry::with_discovery();
// Add a test model to exercise manual models display (lines 88-94)
registry.register(model_registry::ModelEntry {
name: "test-model".into(),
base_path: "./test.gguf".into(),
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(2048),
n_threads: None,
});
let manual_models = registry.list();
assert!(!manual_models.is_empty());
// Test discovered models access (lines 97-112)
let _auto_discovered = registry.discovered_models.clone();
// Test all available models (lines 115-120)
let _all_available = registry.list_all_available();
// The logic paths are exercised by calling the methods
// Test completed successfully
}
#[tokio::test]
async fn test_discover_command_execution_logic() {
// Test Discover command execution logic (lines 122-147)
let registry = model_registry::Registry::with_discovery();
let discovered = registry.discovered_models.clone();
// Test both empty and non-empty discovery paths
if discovered.is_empty() {
// Lines 127-135 - no models found path
assert!(discovered.is_empty());
} else {
// Lines 136-146 - models found path
assert!(!discovered.is_empty());
for (name, model) in discovered {
let _size_mb = model.size_bytes / (1024 * 1024);
let _lora_info = if model.lora_path.is_some() {
" + LoRA"
} else {
""
};
// Exercise the display logic
assert!(!name.is_empty());
}
}
}
#[tokio::test]
async fn test_probe_command_execution_logic() {
// Test Probe command execution logic (lines 148-157)
let mut registry = model_registry::Registry::with_discovery();
registry.register(model_registry::ModelEntry {
name: "test-probe-model".into(),
base_path: "./test.gguf".into(),
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(2048),
n_threads: None,
});
let engine = MockEngine;
let name = "test-probe-model";
// Test successful model spec retrieval (line 149)
let spec_result = registry.to_spec(name);
if let Some(spec) = spec_result {
// Test engine load (line 150)
let load_result = engine.load(&spec).await;
match load_result {
Ok(_) => {
// Line 151 - success path
// Test completed successfully
}
Err(_) => {
// Lines 152-155 - error path
// Test completed successfully
}
}
} else {
// Line 149 - no model found path
// Test completed successfully
}
}
#[tokio::test]
async fn test_bench_command_execution_logic() {
// Test Bench command execution logic (lines 158-170)
let mut registry = model_registry::Registry::with_discovery();
registry.register(model_registry::ModelEntry {
name: "test-bench-model".into(),
base_path: "./test.gguf".into(),
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(2048),
n_threads: None,
});
let engine = MockEngine;
let name = "test-bench-model";
let max_tokens = 100;
// Test model spec retrieval (line 159)
if let Some(spec) = registry.to_spec(name) {
// Test engine load (line 160)
let loaded = engine.load(&spec).await.unwrap();
// Test timing (line 161)
let t0 = std::time::Instant::now();
// Test generation with specific options (lines 162-166)
let out = loaded
.generate(
"Say hi.",
engine::GenOptions {
max_tokens,
stream: false,
..Default::default()
},
None,
)
.await
.unwrap();
// Test elapsed calculation (line 167)
let elapsed = t0.elapsed();
// Test output processing (lines 168-169)
let truncated = &out[..out.len().min(120)];
assert!(!truncated.is_empty());
assert!(elapsed.as_nanos() > 0);
}
}
#[tokio::test]
async fn test_generate_command_execution_logic() {
// Test Generate command execution logic (lines 171-176)
let mut registry = model_registry::Registry::with_discovery();
registry.register(model_registry::ModelEntry {
name: "test-gen-model".into(),
base_path: "./test.gguf".into(),
lora_path: None,
template: Some("chatml".into()),
ctx_len: Some(2048),
n_threads: None,
});
let engine = MockEngine;
let name = "test-gen-model";
let prompt = "Hello, world!";
let max_tokens = 50;
// Test model spec retrieval (line 172)
if let Some(spec) = registry.to_spec(name) {
// Test engine load (line 173)
let loaded = engine.load(&spec).await.unwrap();
// Test generation (line 174)
let out = loaded
.generate(
prompt,
engine::GenOptions {
max_tokens,
stream: false,
..Default::default()
},
None,
)
.await
.unwrap();
// Line 175 - output would be printed here
assert!(out.contains("Generated response to: Hello, world!"));
}
}
#[test]
fn test_command_execution_paths() {
use crate::cli::{Cli, Command};
use clap::Parser;
// Test Generate command path (exercises CLI parsing for lines 171-176)
let gen_args = vec![
"shimmy",
"generate",
"test-model",
"--prompt",
"Hello",
"--max-tokens",
"50",
];
let cli = Cli::try_parse_from(gen_args).unwrap();
match cli.cmd {
Command::Generate {
name,
prompt,
max_tokens,
} => {
assert_eq!(name, "test-model");
assert_eq!(prompt, "Hello");
assert_eq!(max_tokens, 50);
}
_ => panic!("Expected Generate command"),
}
}
#[tokio::test]
async fn test_state_initialization() {
use crate::engine::adapter::InferenceEngineAdapter;
use crate::model_registry::Registry;
// Test state creation paths
let registry = Registry::with_discovery();
let engine = Box::new(InferenceEngineAdapter::new());
let state = std::sync::Arc::new(crate::AppState::new(engine, registry));
// Validate state is properly created
assert_ne!(std::mem::size_of_val(&state), 0);
let _models = state.registry.list();
// Models vec was created successfully
}
#[test]
fn test_serve_enhanced_state_logic() {
// Test enhanced state creation for serve command (lines 53-58)
let registry = model_registry::Registry::with_discovery();
let mut enhanced_state = AppState::new(
Box::new(engine::llama::LlamaEngine::new()),
registry.clone(),
);
// Test auto-registration call (line 57)
enhanced_state.registry.auto_register_discovered();
let enhanced_state_arc = Arc::new(enhanced_state);
// Test available models access (line 60)