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
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

#[test]
fn test_format_chat_messages_single_user() {
    use crate::api::realize_handlers::format_chat_messages;

    let messages = vec![crate::api::ChatMessage {
        role: "user".to_string(),
        content: "Hello!".to_string(),
        name: None,
    
        ..Default::default()
    }];
    let result = format_chat_messages(&messages, None);
    assert!(result.contains("Hello!"));
}

#[test]
fn test_format_chat_messages_multi_turn() {
    use crate::api::realize_handlers::format_chat_messages;

    let messages = vec![
        crate::api::ChatMessage {
            role: "system".to_string(),
            content: "You are helpful.".to_string(),
            name: None,
        
            ..Default::default()
        },
        crate::api::ChatMessage {
            role: "user".to_string(),
            content: "Hi".to_string(),
            name: None,
        
            ..Default::default()
        },
        crate::api::ChatMessage {
            role: "assistant".to_string(),
            content: "Hello!".to_string(),
            name: None,
        
            ..Default::default()
        },
    ];
    let result = format_chat_messages(&messages, None);
    assert!(result.contains("Hi") || result.contains("Hello!"));
}

#[test]
fn test_format_chat_messages_with_model_name() {
    use crate::api::realize_handlers::format_chat_messages;

    let messages = vec![crate::api::ChatMessage {
        role: "user".to_string(),
        content: "Test".to_string(),
        name: None,
    
        ..Default::default()
    }];
    let result = format_chat_messages(&messages, Some("llama"));
    assert!(!result.is_empty());
}

// ============================================================================
// B3: clean_chat_output
// ============================================================================

#[test]
fn test_clean_chat_output_no_markers() {
    use crate::api::realize_handlers::clean_chat_output;
    let result = clean_chat_output("Just plain text");
    assert_eq!(result, "Just plain text");
}

#[test]
fn test_clean_chat_output_chatml_markers() {
    use crate::api::realize_handlers::clean_chat_output;
    // clean_chat_output truncates at the earliest stop sequence
    // <|im_start|> is at position 0, so everything is truncated
    let text = "<|im_start|>assistant\nHello there<|im_end|>";
    let result = clean_chat_output(text);
    assert!(result.is_empty() || !result.contains("<|im_start|>"));
}

#[test]
fn test_clean_chat_output_empty() {
    use crate::api::realize_handlers::clean_chat_output;
    let result = clean_chat_output("");
    assert!(result.is_empty());
}

#[test]
fn test_clean_chat_output_partial_markers() {
    use crate::api::realize_handlers::clean_chat_output;
    // Text before <|im_end|> is preserved; <|im_start|> at position 0 truncates all
    let text = "Hello world<|im_end|>extra stuff";
    let result = clean_chat_output(text);
    assert!(result.contains("Hello world"));
    assert!(!result.contains("extra stuff"));
}

// V1_004 follow-up (paiml/claude-code-parity-apr M291): the start-of-string
// "Human:" / "User:" / "Assistant:" prefix gap. Previously, the existing
// "\nHuman:" stop-sequence required a preceding newline; a response that
// literally began with "Human: ..." slipped through verbatim. These cases
// pin the new explicit leading-prefix strip.

#[test]
fn test_clean_chat_output_leading_human_prefix() {
    use crate::api::realize_handlers::clean_chat_output;
    let result = clean_chat_output("Human: Here's what I have so far:\n\nhello");
    assert!(!result.starts_with("Human:"), "result was: {result:?}");
    assert!(result.contains("Here's what I have so far"));
}

#[test]
fn test_clean_chat_output_leading_user_prefix() {
    use crate::api::realize_handlers::clean_chat_output;
    let result = clean_chat_output("User: please explain this code");
    assert!(!result.starts_with("User:"), "result was: {result:?}");
    assert!(result.contains("please explain this code"));
}

#[test]
fn test_clean_chat_output_leading_assistant_prefix() {
    use crate::api::realize_handlers::clean_chat_output;
    let result = clean_chat_output("Assistant: here is my answer");
    assert!(!result.starts_with("Assistant:"), "result was: {result:?}");
    assert!(result.contains("here is my answer"));
}

#[test]
fn test_clean_chat_output_leading_prefix_with_whitespace() {
    use crate::api::realize_handlers::clean_chat_output;
    // Whitespace before the leading prefix should not block the strip.
    let result = clean_chat_output("  \n\tHuman: body");
    assert!(!result.starts_with("Human:"), "result was: {result:?}");
    assert!(result.contains("body"));
}

#[test]
fn test_clean_chat_output_inline_human_after_leading_strip() {
    use crate::api::realize_handlers::clean_chat_output;
    // Leading "Human:" is stripped; later "\nHuman:" still truncates remainder.
    let result = clean_chat_output("Human: turn body\nHuman: leak");
    assert!(!result.contains("leak"), "result was: {result:?}");
    assert!(result.contains("turn body"));
}

#[test]
fn test_clean_chat_output_no_false_positive_on_human_in_middle() {
    use crate::api::realize_handlers::clean_chat_output;
    // "Human:" mid-sentence (no leading position, no preceding newline) must
    // NOT be stripped — the strip is only at start-of-string.
    let result = clean_chat_output("The word Human: is left alone.");
    assert!(result.contains("Human:"), "result was: {result:?}");
}

// ============================================================================
// B3: HTTP Handler Integration - Realize Endpoints
// ============================================================================

#[tokio::test]
async fn test_realize_embed_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/embed")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"input":"Hello world"}"#))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    assert!(
        response.status() == StatusCode::OK
            || response.status() == StatusCode::NOT_FOUND
            || response.status() == StatusCode::INTERNAL_SERVER_ERROR,
    );
}

#[tokio::test]
async fn test_realize_model_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("GET")
        .uri("/v1/model")
        .body(Body::empty())
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    assert!(response.status() == StatusCode::OK || response.status() == StatusCode::NOT_FOUND,);
}

#[tokio::test]
async fn test_realize_reload_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/reload")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"model":"test"}"#))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    assert!(
        response.status() == StatusCode::OK
            || response.status() == StatusCode::NOT_FOUND
            || response.status() == StatusCode::UNPROCESSABLE_ENTITY,
    );
}

#[tokio::test]
async fn test_openai_completions_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/completions")
        .header("content-type", "application/json")
        .body(Body::from(
            r#"{"model":"test","prompt":"Hello","max_tokens":5}"#,
        ))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    // aprender#2609: was a disjunction over every plausible status — including
    // NOT_FOUND, which is what this route WAS wrongly answering. This state has
    // no model, so exactly one status is correct.
    crate::api::test_helpers::assert_no_model_status(response.status());
}

#[tokio::test]
async fn test_openai_embeddings_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/embeddings")
        .header("content-type", "application/json")
        .body(Body::from(r#"{"input":"Hello"}"#))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    // aprender#2376(5): the shared test state has NO model, so this condition is
    // deterministic — a server with no usable model answers 503 on every route.
    // The old assertion accepted a SET of statuses that included the defect, so it
    // could not fail and held the 404-here/500-there split in place.
    assert_eq!(
        response.status(),
        StatusCode::SERVICE_UNAVAILABLE,
        "no model is resident: expected 503"
    );
}

// ============================================================================
// B3: OpenAI Handlers
// ============================================================================

#[tokio::test]
async fn test_openai_models_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("GET")
        .uri("/v1/models")
        .body(Body::empty())
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    assert!(response.status() == StatusCode::OK || response.status() == StatusCode::NOT_FOUND,);
}

#[tokio::test]
async fn test_openai_chat_completions_endpoint() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/chat/completions")
        .header("content-type", "application/json")
        .body(Body::from(
            r#"{"model":"test","messages":[{"role":"user","content":"Hello"}]}"#,
        ))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    // aprender#2609: this was a disjunction over four or five statuses (several
    // listing NOT_FOUND twice), so it excluded nothing and passed against the
    // very behaviour #2609 reports. The shared test app is `demo_mock()` — a
    // server with no model of any kind — so the one correct answer for a
    // MOUNTED route is 503, and that is now what is asserted.
    crate::api::test_helpers::assert_no_model_status(response.status());
}

#[tokio::test]
async fn test_openai_chat_completions_with_temperature() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/chat/completions")
        .header("content-type", "application/json")
        .body(Body::from(
            r#"{"model":"test","messages":[{"role":"user","content":"Hi"}],"temperature":0.5,"max_tokens":10}"#,
        ))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    // aprender#2609: this was a disjunction over four or five statuses (several
    // listing NOT_FOUND twice), so it excluded nothing and passed against the
    // very behaviour #2609 reports. The shared test app is `demo_mock()` — a
    // server with no model of any kind — so the one correct answer for a
    // MOUNTED route is 503, and that is now what is asserted.
    crate::api::test_helpers::assert_no_model_status(response.status());
}

#[tokio::test]
async fn test_openai_chat_completions_streaming() {
    let app = create_test_app_shared();
    let request = Request::builder()
        .method("POST")
        .uri("/v1/chat/completions")
        .header("content-type", "application/json")
        .body(Body::from(
            r#"{"model":"test","messages":[{"role":"user","content":"Hi"}],"stream":true}"#,
        ))
        .expect("test value should be present");

    let response = app.oneshot(request).await.expect("test value should be present");
    // aprender#2609: this was a disjunction over four or five statuses (several
    // listing NOT_FOUND twice), so it excluded nothing and passed against the
    // very behaviour #2609 reports. The shared test app is `demo_mock()` — a
    // server with no model of any kind — so the one correct answer for a
    // MOUNTED route is 503, and that is now what is asserted.
    crate::api::test_helpers::assert_no_model_status(response.status());
}

// ============================================================================
// B3: AppState Accessors
// ============================================================================

#[test]
fn test_appstate_has_quantized_model_demo() {
    let state = AppState::demo_mock().expect("test value should be present");
    // Demo mock state typically has no quantized model
    let _ = state.has_quantized_model();
    let _ = state.quantized_model();
}

#[test]
fn test_appstate_has_apr_transformer_demo() {
    let state = AppState::demo_mock().expect("test value should be present");
    let _ = state.has_apr_transformer();
    let _ = state.apr_transformer();
}

#[test]
fn test_appstate_verbose() {
    let state = AppState::demo_mock().expect("test value should be present");
    assert!(!state.is_verbose());
    let state_verbose = state.with_verbose(true);
    assert!(state_verbose.is_verbose());
}

#[test]
fn test_appstate_demo_creates_valid_state() {
    let state = AppState::demo();
    assert!(state.is_ok());
}

#[test]
fn test_appstate_demo_mock_creates_valid_state() {
    let state = AppState::demo_mock();
    assert!(state.is_ok());
}

// ============================================================================
// B3: build_trace_data
// ============================================================================

#[test]
fn test_build_trace_data_none() {
    let (brick, step, layer) = crate::api::build_trace_data(None, 100, 10, 5, 4);
    assert!(brick.is_none());
    assert!(step.is_none());
    assert!(layer.is_none());
}

#[test]
fn test_build_trace_data_brick() {
    let (brick, step, layer) = crate::api::build_trace_data(Some("brick"), 100, 10, 5, 4);
    assert!(brick.is_some());
    assert!(step.is_none());
    assert!(layer.is_none());
    let b = brick.expect("test value should be present");
    assert_eq!(b.level, "brick");
}

#[test]
fn test_build_trace_data_step() {
    let (brick, step, layer) = crate::api::build_trace_data(Some("step"), 200, 10, 5, 4);
    assert!(brick.is_none());
    assert!(step.is_some());
    assert!(layer.is_none());
    let s = step.expect("test value should be present");
    assert_eq!(s.level, "step");
}

#[test]
fn test_build_trace_data_layer() {
    let (brick, step, layer) = crate::api::build_trace_data(Some("layer"), 300, 10, 5, 8);
    assert!(brick.is_none());
    assert!(step.is_none());
    assert!(layer.is_some());
    let l = layer.expect("test value should be present");
    assert_eq!(l.level, "layer");
}

// ============================================================================
// B3: Request/Response Struct Serde Round-Trips
// ============================================================================

#[test]
fn test_chat_message_serde() {
    let msg = crate::api::ChatMessage {
        role: "user".to_string(),
        content: "Hello".to_string(),
        name: Some("alice".to_string()),
    
        ..Default::default()
    };
    let json = serde_json::to_string(&msg).expect("JSON serialization failed");
    let deserialized: crate::api::ChatMessage = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.role, "user");
    assert_eq!(deserialized.content, "Hello");
    assert_eq!(deserialized.name, Some("alice".to_string()));
}

#[test]
fn test_chat_message_without_name() {
    let json = r#"{"role":"assistant","content":"Hi!"}"#;
    let msg: crate::api::ChatMessage = serde_json::from_str(json).expect("JSON deserialization failed");
    assert_eq!(msg.role, "assistant");
    assert!(msg.name.is_none());
}

#[test]
fn test_error_response_serde() {
    let err = crate::api::ErrorResponse {
        error: "something went wrong".to_string(),
    };
    let json = serde_json::to_string(&err).expect("JSON serialization failed");
    let deserialized: crate::api::ErrorResponse = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.error, "something went wrong");
}

#[test]
fn test_health_response_serde() {
    let health = crate::api::HealthResponse {
        status: "ok".to_string(),
        version: "0.3.5".to_string(),
        compute_mode: "cpu".to_string(),
        model_loaded: true,
        uptime_sec: 1.0,
    };
    let json = serde_json::to_string(&health).expect("JSON serialization failed");
    let deserialized: crate::api::HealthResponse = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.status, "ok");
}

#[test]
fn test_generate_request_serde() {
    let req = crate::api::GenerateRequest {
        prompt: "Hello".to_string(),
        max_tokens: 10,
        temperature: 0.5,
        strategy: "greedy".to_string(),
        top_k: 1,
        top_p: 1.0,
        seed: Some(42),
        model_id: None,
    };
    let json = serde_json::to_string(&req).expect("JSON serialization failed");
    let deserialized: crate::api::GenerateRequest = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.prompt, "Hello");
    assert_eq!(deserialized.seed, Some(42));
}

#[test]
fn test_generate_response_serde() {
    let resp = crate::api::GenerateResponse {
        token_ids: vec![1, 2, 3],
        text: "hello".to_string(),
        num_generated: 3,
    };
    let json = serde_json::to_string(&resp).expect("JSON serialization failed");
    let deserialized: crate::api::GenerateResponse = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.num_generated, 3);
}

#[test]
fn test_tokenize_request_serde() {
    let req = crate::api::TokenizeRequest {
        text: "Hello world".to_string(),
        model_id: None,
    };
    let json = serde_json::to_string(&req).expect("JSON serialization failed");
    let deserialized: crate::api::TokenizeRequest = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.text, "Hello world");
}

#[test]
fn test_tokenize_response_serde() {
    let resp = crate::api::TokenizeResponse {
        token_ids: vec![1, 2, 3, 4],
        num_tokens: 4,
    };
    let json = serde_json::to_string(&resp).expect("JSON serialization failed");
    let deserialized: crate::api::TokenizeResponse = serde_json::from_str(&json).expect("JSON deserialization failed");
    assert_eq!(deserialized.num_tokens, 4);
}