aprender-serve 0.64.0

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

#[test]
fn test_gpu_status_response_debug() {
    let response = GpuStatusResponse {
        cache_ready: false,
        cache_memory_bytes: 0,
        batch_threshold: 32,
        recommended_min_batch: 32,
    };

    let debug = format!("{:?}", response);
    assert!(debug.contains("GpuStatusResponse"));
}

// =============================================================================
// BatchConfig Tests (GPU feature)
// =============================================================================

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_default() {
    use crate::api::BatchConfig;

    let config = BatchConfig::default();
    assert_eq!(config.window_ms, 50);
    assert_eq!(config.min_batch, 4);
    assert_eq!(config.optimal_batch, 32);
    assert_eq!(config.max_batch, 64);
    assert_eq!(config.queue_size, 1024);
    assert_eq!(config.gpu_threshold, 32);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_low_latency() {
    use crate::api::BatchConfig;

    let config = BatchConfig::low_latency();
    assert_eq!(config.window_ms, 5);
    assert_eq!(config.min_batch, 2);
    assert_eq!(config.optimal_batch, 8);
    assert_eq!(config.max_batch, 16);
    assert_eq!(config.queue_size, 512);
    assert_eq!(config.gpu_threshold, 32);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_high_throughput() {
    use crate::api::BatchConfig;

    let config = BatchConfig::high_throughput();
    assert_eq!(config.window_ms, 100);
    assert_eq!(config.min_batch, 8);
    assert_eq!(config.optimal_batch, 32);
    assert_eq!(config.max_batch, 128);
    assert_eq!(config.queue_size, 2048);
    assert_eq!(config.gpu_threshold, 32);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_should_process() {
    use crate::api::BatchConfig;

    let config = BatchConfig::default(); // optimal_batch = 32
    assert!(!config.should_process(0));
    assert!(!config.should_process(16));
    assert!(!config.should_process(31));
    assert!(config.should_process(32));
    assert!(config.should_process(64));
    assert!(config.should_process(100));
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_meets_minimum() {
    use crate::api::BatchConfig;

    let config = BatchConfig::default(); // min_batch = 4
    assert!(!config.meets_minimum(0));
    assert!(!config.meets_minimum(1));
    assert!(!config.meets_minimum(3));
    assert!(config.meets_minimum(4));
    assert!(config.meets_minimum(5));
    assert!(config.meets_minimum(100));
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_clone() {
    use crate::api::BatchConfig;

    let config = BatchConfig::default();
    let cloned = config.clone();
    assert_eq!(cloned.window_ms, config.window_ms);
    assert_eq!(cloned.min_batch, config.min_batch);
    assert_eq!(cloned.optimal_batch, config.optimal_batch);
    assert_eq!(cloned.max_batch, config.max_batch);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_config_debug() {
    use crate::api::BatchConfig;

    let config = BatchConfig::default();
    let debug = format!("{:?}", config);
    assert!(debug.contains("BatchConfig"));
    assert!(debug.contains("window_ms"));
}

// =============================================================================
// ContinuousBatchResponse Tests (GPU feature)
// =============================================================================

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_single() {
    use crate::api::ContinuousBatchResponse;

    let response = ContinuousBatchResponse::single(
        vec![1, 2, 3, 4, 5], // token_ids
        3,                   // prompt_len
        12.5,                // latency_ms
    );

    assert_eq!(response.token_ids, vec![1, 2, 3, 4, 5]);
    assert_eq!(response.prompt_len, 3);
    assert!(!response.batched);
    assert_eq!(response.batch_size, 1);
    assert!((response.latency_ms - 12.5).abs() < 0.01);
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_batched() {
    use crate::api::ContinuousBatchResponse;

    let response = ContinuousBatchResponse::batched(
        vec![10, 20, 30, 40, 50, 60], // token_ids
        4,                            // prompt_len
        16,                           // batch_size
        50.0,                         // latency_ms
    );

    assert_eq!(response.token_ids, vec![10, 20, 30, 40, 50, 60]);
    assert_eq!(response.prompt_len, 4);
    assert!(response.batched);
    assert_eq!(response.batch_size, 16);
    assert!((response.latency_ms - 50.0).abs() < 0.01);
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_generated_tokens() {
    use crate::api::ContinuousBatchResponse;

    // Normal case: token_ids longer than prompt_len
    let response = ContinuousBatchResponse::single(vec![1, 2, 3, 4, 5, 6, 7], 3, 10.0);
    let generated = response.generated_tokens();
    assert_eq!(generated, &[4, 5, 6, 7]);
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_generated_tokens_empty() {
    use crate::api::ContinuousBatchResponse;

    // Edge case: prompt_len equals token_ids.len()
    let response = ContinuousBatchResponse::single(vec![1, 2, 3], 3, 5.0);
    let generated = response.generated_tokens();
    assert!(generated.is_empty());
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_generated_tokens_overflow() {
    use crate::api::ContinuousBatchResponse;

    // Edge case: prompt_len > token_ids.len() (shouldn't happen but handle gracefully)
    let response = ContinuousBatchResponse::single(vec![1, 2], 10, 5.0);
    let generated = response.generated_tokens();
    assert!(generated.is_empty());
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_clone() {
    use crate::api::ContinuousBatchResponse;

    let response = ContinuousBatchResponse::batched(vec![1, 2, 3], 1, 8, 25.0);
    let cloned = response.clone();

    assert_eq!(cloned.token_ids, response.token_ids);
    assert_eq!(cloned.prompt_len, response.prompt_len);
    assert_eq!(cloned.batched, response.batched);
    assert_eq!(cloned.batch_size, response.batch_size);
}

#[cfg(feature = "gpu")]
#[test]
fn test_continuous_batch_response_debug() {
    use crate::api::ContinuousBatchResponse;

    let response = ContinuousBatchResponse::single(vec![1], 0, 1.0);
    let debug = format!("{:?}", response);
    assert!(debug.contains("ContinuousBatchResponse"));
}

// =============================================================================
// BatchQueueStats Tests (GPU feature)
// =============================================================================

#[cfg(feature = "gpu")]
#[test]
fn test_batch_queue_stats_default() {
    use crate::api::BatchQueueStats;

    let stats = BatchQueueStats::default();
    assert_eq!(stats.total_queued, 0);
    assert_eq!(stats.total_batches, 0);
    assert_eq!(stats.total_single, 0);
    assert!((stats.avg_batch_size - 0.0).abs() < f64::EPSILON);
    assert!((stats.avg_wait_ms - 0.0).abs() < f64::EPSILON);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_queue_stats_clone() {
    use crate::api::BatchQueueStats;

    let stats = BatchQueueStats {
        total_queued: 100,
        total_batches: 10,
        total_single: 20,
        avg_batch_size: 10.0,
        avg_wait_ms: 5.5,
    };

    let cloned = stats.clone();
    assert_eq!(cloned.total_queued, stats.total_queued);
    assert_eq!(cloned.total_batches, stats.total_batches);
    assert_eq!(cloned.total_single, stats.total_single);
}

#[cfg(feature = "gpu")]
#[test]
fn test_batch_queue_stats_debug() {
    use crate::api::BatchQueueStats;

    let stats = BatchQueueStats::default();
    let debug = format!("{:?}", stats);
    assert!(debug.contains("BatchQueueStats"));
    assert!(debug.contains("total_queued"));
}

// =============================================================================
// BatchProcessResult Tests (GPU feature)
// =============================================================================

#[cfg(feature = "gpu")]
#[test]
fn test_batch_process_result_debug() {
    use crate::api::BatchProcessResult;

    let result = BatchProcessResult {
        requests_processed: 5,
        was_batched: true,
        total_time_ms: 50.0,
        avg_latency_ms: 10.0,
    };

    let debug = format!("{:?}", result);
    assert!(debug.contains("BatchProcessResult"));
    assert!(debug.contains("requests_processed"));
    assert!(debug.contains("was_batched"));
}

// =============================================================================
// GPU Endpoint HTTP Tests
// =============================================================================

#[tokio::test]
async fn test_gpu_warmup_endpoint_no_gpu_model() {
    let app = create_test_app_shared();

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/gpu/warmup")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Demo app doesn't have GPU model, should return error
    // When GPU feature is enabled, returns 503; when not, also returns 503
    assert!(
        response.status() == StatusCode::SERVICE_UNAVAILABLE
            || response.status() == StatusCode::INTERNAL_SERVER_ERROR
            || response.status() == StatusCode::NOT_FOUND
    );
}

#[tokio::test]
async fn test_gpu_status_endpoint() {
    let app = create_test_app_shared();

    let response = app
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/v1/gpu/status")
                .body(Body::empty())
                .expect("build request"),
        )
        .await
        .expect("send request");

    // GPU status always returns OK (even without GPU model)
    assert!(
        response.status() == StatusCode::OK
            || response.status() == StatusCode::NOT_FOUND
            || response.status() == StatusCode::INTERNAL_SERVER_ERROR
            || response.status() == StatusCode::SERVICE_UNAVAILABLE
            || response.status() == StatusCode::UNPROCESSABLE_ENTITY
    );
    if response.status() != StatusCode::OK {
        return;
    }

    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("read body");
    let status: GpuStatusResponse = serde_json::from_slice(&body).expect("parse json");

    // Without GPU model, cache_ready should be false
    assert!(!status.cache_ready);
    assert_eq!(status.cache_memory_bytes, 0);
    assert_eq!(status.batch_threshold, 32);
    assert_eq!(status.recommended_min_batch, 32);
}

#[tokio::test]
async fn test_gpu_batch_completions_empty_prompts() {
    let app = create_test_app_shared();

    let request = GpuBatchRequest {
        prompts: vec![], // Empty prompts array - should fail
        max_tokens: 50,
        temperature: 0.7,
        top_k: 40,
        stop: vec![],
    };

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/batch/completions")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request).expect("serialize"),
                ))
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Empty prompts should return 400 Bad Request
    // Note: Non-GPU build might return 503 instead
    assert!(
        response.status() == StatusCode::BAD_REQUEST
            || response.status() == StatusCode::SERVICE_UNAVAILABLE
    );
}

#[tokio::test]
async fn test_gpu_batch_completions_no_gpu_model() {
    let app = create_test_app_shared();

    let request = GpuBatchRequest {
        prompts: vec!["Hello".to_string(), "World".to_string()],
        max_tokens: 10,
        temperature: 0.5,
        top_k: 40,
        stop: vec![],
    };

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/batch/completions")
                .header("content-type", "application/json")
                .body(Body::from(
                    serde_json::to_string(&request).expect("serialize"),
                ))
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Demo app doesn't have GPU/cached model, should return error
    assert!(
        response.status() == StatusCode::SERVICE_UNAVAILABLE
            || response.status() == StatusCode::INTERNAL_SERVER_ERROR
            || response.status() == StatusCode::NOT_FOUND
    );
}

#[tokio::test]
async fn test_gpu_batch_completions_invalid_json() {
    let app = create_test_app_shared();

    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/v1/batch/completions")
                .header("content-type", "application/json")
                .body(Body::from("not valid json"))
                .expect("build request"),
        )
        .await
        .expect("send request");

    // Invalid JSON should return 400 Bad Request
    assert!(
        response.status() == StatusCode::BAD_REQUEST
            || response.status() == StatusCode::NOT_FOUND
            || response.status() == StatusCode::INTERNAL_SERVER_ERROR
            || response.status() == StatusCode::SERVICE_UNAVAILABLE
            || response.status() == StatusCode::UNPROCESSABLE_ENTITY
    );
}