realizar 0.8.5

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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

    // =========================================================================
    // Server Command Tests (EXTREME TDD - PAR-112)
    // =========================================================================

    #[tokio::test]
    async fn test_serve_model_invalid_extension() {
        // Test that unsupported file extensions return error
        let result = serve_model("127.0.0.1", 8080, "/nonexistent/model.xyz", false, false, true).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unsupported file extension"));
    }

    #[tokio::test]
    async fn test_serve_model_nonexistent_gguf() {
        // Test that nonexistent GGUF file returns error
        let result = serve_model("127.0.0.1", 8080, "/nonexistent/model.gguf", false, false, true).await;
        assert!(result.is_err());
        // Should fail during GGUF loading
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to load GGUF")
                || err.to_string().contains("No such file")
                || err.to_string().contains("mmap")
        );
    }

    #[tokio::test]
    async fn test_serve_model_nonexistent_safetensors() {
        // Test that nonexistent SafeTensors file returns error
        let result = serve_model(
            "127.0.0.1",
            8080,
            "/nonexistent/model.safetensors",
            false,
            false,
            true,
        )
        .await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to read") || err.to_string().contains("No such file")
        );
    }

    #[tokio::test]
    async fn test_serve_model_nonexistent_apr() {
        // Test that nonexistent APR file returns error
        let result = serve_model("127.0.0.1", 8080, "/nonexistent/model.apr", false, false, true).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to read") || err.to_string().contains("No such file")
        );
    }

    #[test]
    fn test_serve_model_extension_detection() {
        // Verify extension detection logic
        assert!("/path/to/model.gguf".ends_with(".gguf"));
        assert!("/path/to/model.safetensors".ends_with(".safetensors"));
        assert!("/path/to/model.apr".ends_with(".apr"));
        assert!(!"/path/to/model.xyz".ends_with(".gguf"));
        assert!(!"/path/to/model.xyz".ends_with(".safetensors"));
        assert!(!"/path/to/model.xyz".ends_with(".apr"));
    }

    #[test]
    fn test_serve_model_address_parsing() {
        // Verify address parsing works correctly
        let addr: std::result::Result<std::net::SocketAddr, _> = "127.0.0.1:8080".parse();
        assert!(addr.is_ok());

        let addr: std::result::Result<std::net::SocketAddr, _> = "0.0.0.0:3000".parse();
        assert!(addr.is_ok());

        let addr: std::result::Result<std::net::SocketAddr, _> = "invalid:port".parse();
        assert!(addr.is_err());
    }

    #[test]
    fn test_serve_model_port_ranges() {
        // Verify port range handling
        let addr: std::result::Result<std::net::SocketAddr, _> = "127.0.0.1:0".parse();
        assert!(addr.is_ok()); // Port 0 = OS assigns

        let addr: std::result::Result<std::net::SocketAddr, _> = "127.0.0.1:65535".parse();
        assert!(addr.is_ok()); // Max port

        let addr: std::result::Result<std::net::SocketAddr, _> = "127.0.0.1:80".parse();
        assert!(addr.is_ok()); // Privileged port (may need root)
    }

    #[test]
    fn test_batch_mode_flag_logic() {
        // Test batch mode flag combinations
        let batch_mode = true;
        let force_gpu = false;
        assert!(batch_mode && !force_gpu); // Valid: batch without forced GPU

        let batch_mode = true;
        let force_gpu = true;
        assert!(batch_mode && force_gpu); // Valid: batch with GPU

        let batch_mode = false;
        let force_gpu = true;
        assert!(!batch_mode && force_gpu); // Valid: single-request with GPU (true streaming)
    }

    #[test]
    fn test_cuda_env_var_detection() {
        // Test REALIZAR_BACKEND environment variable detection
        std::env::remove_var("REALIZAR_BACKEND");
        let use_cuda = std::env::var("REALIZAR_BACKEND")
            .map(|v| v.eq_ignore_ascii_case("cuda"))
            .unwrap_or(false);
        assert!(!use_cuda);

        std::env::set_var("REALIZAR_BACKEND", "cuda");
        let use_cuda = std::env::var("REALIZAR_BACKEND")
            .map(|v| v.eq_ignore_ascii_case("cuda"))
            .unwrap_or(false);
        assert!(use_cuda);

        std::env::set_var("REALIZAR_BACKEND", "CUDA");
        let use_cuda = std::env::var("REALIZAR_BACKEND")
            .map(|v| v.eq_ignore_ascii_case("cuda"))
            .unwrap_or(false);
        assert!(use_cuda);

        std::env::set_var("REALIZAR_BACKEND", "cpu");
        let use_cuda = std::env::var("REALIZAR_BACKEND")
            .map(|v| v.eq_ignore_ascii_case("cuda"))
            .unwrap_or(false);
        assert!(!use_cuda);

        // Cleanup
        std::env::remove_var("REALIZAR_BACKEND");
    }

    // =========================================================================
    // ModelType Tests
    // =========================================================================

    #[test]
    fn test_model_type_display() {
        assert_eq!(format!("{}", ModelType::Gguf), "GGUF");
        assert_eq!(format!("{}", ModelType::SafeTensors), "SafeTensors");
        assert_eq!(format!("{}", ModelType::Apr), "APR");
    }

    #[test]
    fn test_model_type_debug() {
        assert_eq!(format!("{:?}", ModelType::Gguf), "Gguf");
        assert_eq!(format!("{:?}", ModelType::SafeTensors), "SafeTensors");
        assert_eq!(format!("{:?}", ModelType::Apr), "Apr");
    }

    #[test]
    fn test_model_type_clone_copy() {
        let mt = ModelType::Gguf;
        let mt_clone = mt;
        let mt_copy = mt;
        assert_eq!(mt, mt_clone);
        assert_eq!(mt, mt_copy);
    }

    #[test]
    fn test_model_type_equality() {
        assert_eq!(ModelType::Gguf, ModelType::Gguf);
        assert_eq!(ModelType::SafeTensors, ModelType::SafeTensors);
        assert_eq!(ModelType::Apr, ModelType::Apr);
        assert_ne!(ModelType::Gguf, ModelType::SafeTensors);
        assert_ne!(ModelType::SafeTensors, ModelType::Apr);
        assert_ne!(ModelType::Apr, ModelType::Gguf);
    }

    // =========================================================================
    // PreparedServer Tests
    // =========================================================================

    #[test]
    fn test_prepared_server_debug() {
        // Create a demo AppState for testing
        let state = crate::api::AppState::demo().expect("demo state");
        let prepared = PreparedServer {
            state,
            batch_mode_enabled: true,
            model_type: ModelType::Gguf,
        };
        let debug_str = format!("{:?}", prepared);
        assert!(debug_str.contains("PreparedServer"));
        assert!(debug_str.contains("batch_mode_enabled: true"));
        assert!(debug_str.contains("model_type: Gguf"));
    }

    #[test]
    fn test_prepared_server_fields() {
        let state = crate::api::AppState::demo().expect("demo state");
        let prepared = PreparedServer {
            state,
            batch_mode_enabled: false,
            model_type: ModelType::SafeTensors,
        };
        assert!(!prepared.batch_mode_enabled);
        assert_eq!(prepared.model_type, ModelType::SafeTensors);
    }

    // =========================================================================
    // prepare_serve_state Tests (EXTREME TDD)
    // =========================================================================

    #[test]
    fn test_prepare_serve_state_invalid_extension() {
        // Test that unsupported file extensions return error
        let result = prepare_serve_state("/nonexistent/model.xyz", false, false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unsupported file extension"));
    }

    #[test]
    fn test_prepare_serve_state_nonexistent_gguf() {
        // Test that nonexistent GGUF file returns error
        let result = prepare_serve_state("/nonexistent/model.gguf", false, false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to load GGUF")
                || err.to_string().contains("No such file")
                || err.to_string().contains("mmap")
        );
    }

    #[test]
    fn test_prepare_serve_state_nonexistent_safetensors() {
        // Test that nonexistent SafeTensors file returns error
        let result = prepare_serve_state("/nonexistent/model.safetensors", false, false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to read") || err.to_string().contains("No such file")
        );
    }

    #[test]
    fn test_prepare_serve_state_nonexistent_apr() {
        // Test that nonexistent APR file returns error
        let result = prepare_serve_state("/nonexistent/model.apr", false, false);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Failed to read") || err.to_string().contains("No such file")
        );
    }

    #[test]
    fn test_prepare_serve_state_with_batch_mode_flag() {
        // Test batch_mode flag is recorded even when loading fails
        let result = prepare_serve_state("/nonexistent/model.gguf", true, false);
        assert!(result.is_err()); // File doesn't exist, but flag should be processed before
    }

    #[test]
    fn test_prepare_serve_state_with_force_gpu_flag() {
        // Test force_gpu flag is recorded even when loading fails
        let result = prepare_serve_state("/nonexistent/model.gguf", false, true);
        assert!(result.is_err()); // File doesn't exist, but flag should be processed before
    }

    #[test]
    fn test_prepare_serve_state_extension_variants() {
        // Test various file extension patterns
        let extensions = vec![
            ("/path/model.gguf", true, "GGUF"),
            ("/path/MODEL.GGUF", false, "uppercase"),
            ("/path/model.safetensors", true, "SafeTensors"),
            ("/path/model.apr", true, "APR"),
            ("/path/model.pt", false, "PyTorch"),
            ("/path/model.bin", false, "binary"),
            ("/path/model.h5", false, "HDF5"),
            ("/path/model", false, "no extension"),
        ];

        for (path, should_detect, name) in extensions {
            let is_gguf = path.ends_with(".gguf");
            let is_safetensors = path.ends_with(".safetensors");
            let is_apr = path.ends_with(".apr");
            let detected = is_gguf || is_safetensors || is_apr;
            assert_eq!(
                detected, should_detect,
                "Extension detection failed for {name}: {path}"
            );
        }
    }

    // =========================================================================
    // serve_demo Tests (EXTREME TDD)
    // =========================================================================

    #[test]
    fn test_serve_demo_address_validation() {
        // Test that address parsing logic works correctly
        let valid_addresses = vec![
            ("127.0.0.1", 8080),
            ("0.0.0.0", 3000),
            ("localhost", 8000), // This won't parse as SocketAddr directly
        ];

        for (host, port) in valid_addresses {
            let addr_str = format!("{}:{}", host, port);
            let result: std::result::Result<std::net::SocketAddr, _> = addr_str.parse();
            // localhost won't parse, but IP addresses should
            if host != "localhost" {
                assert!(result.is_ok(), "Address {addr_str} should be valid");
            }
        }
    }

    #[test]
    fn test_serve_demo_port_zero() {
        // Port 0 should be valid (OS assigns port)
        let addr: std::result::Result<std::net::SocketAddr, _> = "127.0.0.1:0".parse();
        assert!(addr.is_ok());
    }

    // =========================================================================
    // Integration Tests (run with `cargo test -- --ignored`)
    // =========================================================================

    /// Integration test for prepare_serve_state with a real GGUF model
    /// Run with: cargo test test_prepare_serve_state_gguf_success -- --ignored
    #[test]
    #[ignore = "requires real GGUF model file"]
    fn test_prepare_serve_state_gguf_success() {
        // Look for a test model file
        let home = std::env::var("HOME").expect("HOME env var not set");
        let model_paths = [
            format!("{}/.apr/models/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf", home),
            format!("{}/src/single-shot-eval/models/raw/qwen2.5-coder-0.5b-instruct-q4_k_m.gguf", home),
        ];

        let model_path = model_paths
            .iter()
            .find(|p| std::path::Path::new(p).exists())
            .expect("No test model file found. Run tests with a valid GGUF model.");

        let result = prepare_serve_state(model_path, false, false);
        assert!(
            result.is_ok(),
            "prepare_serve_state failed: {:?}",
            result.err()
        );

        let prepared = result.expect("operation failed");
        assert_eq!(prepared.model_type, ModelType::Gguf);
        assert!(!prepared.batch_mode_enabled);
        // State should have a quantized model
    }

    /// Integration test for prepare_serve_state with batch mode
    /// Run with: cargo test test_prepare_serve_state_gguf_batch -- --ignored
    #[tokio::test]
    #[ignore = "requires real GGUF model file"]
    async fn test_prepare_serve_state_gguf_batch() {
        let home = std::env::var("HOME").expect("HOME env var not set");
        let model_paths = [
            format!("{}/.apr/models/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf", home),
            format!("{}/src/single-shot-eval/models/raw/qwen2.5-coder-0.5b-instruct-q4_k_m.gguf", home),
        ];

        let model_path = model_paths
            .iter()
            .find(|p| std::path::Path::new(p).exists())
            .expect("No test model file found.");

        // Batch mode requires Tokio runtime for spawn_batch_processor
        let result = prepare_serve_state(model_path, true, false);
        assert!(
            result.is_ok(),
            "prepare_serve_state failed: {:?}",
            result.err()
        );

        let prepared = result.expect("operation failed");
        assert_eq!(prepared.model_type, ModelType::Gguf);
        // batch_mode_enabled is true since we enabled it and gpu feature is available
        assert!(prepared.batch_mode_enabled);
    }

    /// Test all model type variants are properly detected
    #[test]
    fn test_model_type_from_extension() {
        // This tests the extension detection logic in prepare_serve_state
        let test_cases = vec![
            ("model.gguf", Some("gguf")),
            ("model.safetensors", Some("safetensors")),
            ("model.apr", Some("apr")),
            ("model.bin", None),
            ("model", None),
        ];

        for (path, expected_ext) in test_cases {
            let is_gguf = path.ends_with(".gguf");
            let is_safetensors = path.ends_with(".safetensors");
            let is_apr = path.ends_with(".apr");

            let actual = if is_gguf {
                Some("gguf")
            } else if is_safetensors {
                Some("safetensors")
            } else if is_apr {
                Some("apr")
            } else {
                None
            };

            assert_eq!(
                actual, expected_ext,
                "Extension detection failed for {path}"
            );
        }
    }

    /// Test PreparedServer with all model types
    #[test]
    fn test_prepared_server_all_model_types() {
        for model_type in [ModelType::Gguf, ModelType::SafeTensors, ModelType::Apr] {
            let state = crate::api::AppState::demo().expect("demo state");
            let prepared = PreparedServer {
                state,
                batch_mode_enabled: false,
                model_type,
            };
            assert_eq!(prepared.model_type, model_type);
            // Test that debug output includes the model type
            let debug = format!("{:?}", prepared);
            assert!(debug.contains(&format!("{:?}", model_type)));
        }
    }