http-service.rs 40.7 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
// SPDX-License-Identifier: Apache-2.0

use anyhow::Error;
use async_stream::stream;
6
use dynamo_async_openai::config::OpenAIConfig;
Neelay Shah's avatar
Neelay Shah committed
7
use dynamo_llm::protocols::{
8
    Annotated,
Ryan Olson's avatar
Ryan Olson committed
9
10
    codec::SseLineCodec,
    convert_sse_stream,
11
    openai::{
12
        chat_completions::{NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse},
13
        completions::{NvCreateCompletionRequest, NvCreateCompletionResponse},
14
15
    },
};
16
17
18
19
20
21
22
23
24
use dynamo_llm::{
    http::{
        client::{
            GenericBYOTClient, HttpClientConfig, HttpRequestContext, NvCustomClient,
            PureOpenAIClient,
        },
        service::{
            Metrics,
            error::HttpError,
25
            metrics::{Endpoint, ErrorType, RequestType, Status},
26
27
28
29
30
            service_v2::HttpService,
        },
    },
    model_card::ModelDeploymentCard,
};
31
use dynamo_runtime::metrics::prometheus_names::{frontend_service, name_prefix};
Neelay Shah's avatar
Neelay Shah committed
32
use dynamo_runtime::{
33
    CancellationToken,
34
    engine::AsyncEngineContext,
35
    pipeline::{
36
        AsyncEngine, AsyncEngineContextProvider, ManyOut, ResponseStream, SingleIn, async_trait,
37
38
    },
};
39
use futures::StreamExt;
40
use prometheus::{Registry, proto::MetricType};
41
use reqwest::StatusCode;
Ryan Olson's avatar
Ryan Olson committed
42
43
44
use std::{io::Cursor, sync::Arc};
use tokio::time::timeout;
use tokio_util::codec::FramedRead;
45

46
47
48
49
#[path = "common/ports.rs"]
mod ports;
use ports::get_random_port;

50
51
struct CounterEngine {}

Ryan Olson's avatar
Ryan Olson committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Add a new long-running test engine
struct LongRunningEngine {
    delay_ms: u64,
    cancelled: Arc<std::sync::atomic::AtomicBool>,
}

impl LongRunningEngine {
    fn new(delay_ms: u64) -> Self {
        Self {
            delay_ms,
            cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    fn was_cancelled(&self) -> bool {
        self.cancelled.load(std::sync::atomic::Ordering::Acquire)
    }
}

71
72
73
#[async_trait]
impl
    AsyncEngine<
74
        SingleIn<NvCreateChatCompletionRequest>,
75
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
76
77
78
79
80
        Error,
    > for CounterEngine
{
    async fn generate(
        &self,
81
        request: SingleIn<NvCreateChatCompletionRequest>,
82
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
83
84
85
        let (request, context) = request.transfer(());
        let ctx = context.context();

Paul Hendricks's avatar
Paul Hendricks committed
86
        // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
Ryan Olson's avatar
Ryan Olson committed
87
        #[allow(deprecated)]
Paul Hendricks's avatar
Paul Hendricks committed
88
        let max_tokens = request.inner.max_tokens.unwrap_or(0) as u64;
89

90
        // let generator = NvCreateChatCompletionStreamResponse::generator(request.model.clone());
91
        let mut generator = request.response_generator(ctx.id().to_string());
92
93
94
95

        let stream = stream! {
            tokio::time::sleep(std::time::Duration::from_millis(max_tokens)).await;
            for i in 0..10 {
96
                let output = generator.create_choice(i, Some(format!("choice {i}")), None, None, None);
Paul Hendricks's avatar
Paul Hendricks committed
97
98

                yield Annotated::from_data(output);
99
100
101
102
103
104
105
            }
        };

        Ok(ResponseStream::new(Box::pin(stream), ctx))
    }
}

Ryan Olson's avatar
Ryan Olson committed
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
#[async_trait]
impl
    AsyncEngine<
        SingleIn<NvCreateChatCompletionRequest>,
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
        Error,
    > for LongRunningEngine
{
    async fn generate(
        &self,
        request: SingleIn<NvCreateChatCompletionRequest>,
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
        let (_request, context) = request.transfer(());
        let ctx = context.context();

        tracing::info!(
            "LongRunningEngine: Starting generation with {}ms delay",
            self.delay_ms
        );

        let cancelled_flag = self.cancelled.clone();
        let delay_ms = self.delay_ms;

        let ctx_clone = ctx.clone();
        let stream = async_stream::stream! {

            // the stream can be dropped or it can be cancelled
            // either way we consider this a cancellation
            cancelled_flag.store(true, std::sync::atomic::Ordering::SeqCst);

            tokio::select! {
                _ = tokio::time::sleep(std::time::Duration::from_millis(delay_ms)) => {
                    // the stream went to completion
                    cancelled_flag.store(false, std::sync::atomic::Ordering::SeqCst);

                }
                _ = ctx_clone.stopped() => {
                    cancelled_flag.store(true, std::sync::atomic::Ordering::SeqCst);
                }
            }

            yield Annotated::<NvCreateChatCompletionStreamResponse>::from_annotation("event.dynamo.test.sentinel", &"DONE".to_string()).expect("Failed to create annotated response");
        };

        Ok(ResponseStream::new(Box::pin(stream), ctx))
    }
}

154
155
156
157
158
struct AlwaysFailEngine {}

#[async_trait]
impl
    AsyncEngine<
159
        SingleIn<NvCreateChatCompletionRequest>,
160
        ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>,
161
162
163
164
165
        Error,
    > for AlwaysFailEngine
{
    async fn generate(
        &self,
166
        _request: SingleIn<NvCreateChatCompletionRequest>,
167
    ) -> Result<ManyOut<Annotated<NvCreateChatCompletionStreamResponse>>, Error> {
168
169
170
171
172
173
174
175
        Err(HttpError {
            code: 403,
            message: "Always fail".to_string(),
        })?
    }
}

#[async_trait]
176
177
178
179
180
181
impl
    AsyncEngine<
        SingleIn<NvCreateCompletionRequest>,
        ManyOut<Annotated<NvCreateCompletionResponse>>,
        Error,
    > for AlwaysFailEngine
182
183
184
{
    async fn generate(
        &self,
185
        _request: SingleIn<NvCreateCompletionRequest>,
186
    ) -> Result<ManyOut<Annotated<NvCreateCompletionResponse>>, Error> {
187
188
189
190
191
192
193
194
        Err(HttpError {
            code: 401,
            message: "Always fail".to_string(),
        })?
    }
}

fn compare_counter(
195
    metrics: &Metrics,
196
197
198
199
    model: &str,
    endpoint: &Endpoint,
    request_type: &RequestType,
    status: &Status,
200
    error_type: &ErrorType,
201
202
203
    expected: u64,
) {
    assert_eq!(
204
        metrics.get_request_counter(model, endpoint, request_type, status, error_type),
205
        expected,
206
        "model: {}, endpoint: {:?}, request_type: {:?}, status: {:?}, error_type: {:?}",
207
208
209
        model,
        endpoint.as_str(),
        request_type.as_str(),
210
211
        status.as_str(),
        error_type.as_str()
212
213
214
215
216
217
218
    );
}

fn compute_index(endpoint: &Endpoint, request_type: &RequestType, status: &Status) -> usize {
    let endpoint = match endpoint {
        Endpoint::Completions => 0,
        Endpoint::ChatCompletions => 1,
219
        Endpoint::Embeddings => todo!(),
220
        Endpoint::Responses => todo!(),
221
        Endpoint::AnthropicMessages => todo!(),
222
        Endpoint::Tensor => todo!(),
223
        Endpoint::Images => todo!(),
224
        Endpoint::Videos => todo!(),
225
        Endpoint::Audios => todo!(),
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    };

    let request_type = match request_type {
        RequestType::Unary => 0,
        RequestType::Stream => 1,
    };

    let status = match status {
        Status::Success => 0,
        Status::Error => 1,
    };

    endpoint * 4 + request_type * 2 + status
}

241
fn compare_counters(metrics: &Metrics, model: &str, expected: &[u64; 8]) {
242
243
244
245
    for endpoint in &[Endpoint::Completions, Endpoint::ChatCompletions] {
        for request_type in &[RequestType::Unary, RequestType::Stream] {
            for status in &[Status::Success, Status::Error] {
                let index = compute_index(endpoint, request_type, status);
246
247
248
249
                let error_type = match status {
                    Status::Success => &ErrorType::None,
                    Status::Error => &ErrorType::Validation, // Test engines return 4xx errors
                };
250
                compare_counter(
251
                    metrics,
252
253
254
255
                    model,
                    endpoint,
                    request_type,
                    status,
256
                    error_type,
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
                    expected[index],
                );
            }
        }
    }
}

fn inc_counter(
    endpoint: Endpoint,
    request_type: RequestType,
    status: Status,
    expected: &mut [u64; 8],
) {
    let index = compute_index(&endpoint, &request_type, &status);
    expected[index] += 1;
}

Paul Hendricks's avatar
Paul Hendricks committed
274
#[allow(deprecated)]
275
276
#[tokio::test]
async fn test_http_service() {
277
    let port = get_random_port().await;
278
    let service = HttpService::builder()
279
        .port(port)
280
281
282
283
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
        .build()
        .unwrap();
284
285
    let state = service.state_clone();
    let manager = state.manager();
286
287
288
289
290

    let token = CancellationToken::new();
    let cancel_token = token.clone();
    let task = tokio::spawn(async move { service.run(token.clone()).await });

291
292
293
    // Wait for the service to be ready before proceeding
    wait_for_service_ready(port).await;

294
295
    let registry = Registry::new();

296
297
    // TODO: Shouldn't this test know the card before it registers a model?
    let card = ModelDeploymentCard::with_name_only("foo");
298
    let counter = Arc::new(CounterEngine {});
299
    let result = manager.add_chat_completions_model("foo", card.mdcsum(), counter);
300
301
302
    assert!(result.is_ok());

    let failure = Arc::new(AlwaysFailEngine {});
303
304
    let card = ModelDeploymentCard::with_name_only("bar");
    let result = manager.add_chat_completions_model("bar", card.mdcsum(), failure.clone());
305
306
    assert!(result.is_ok());

307
    let result = manager.add_completions_model("bar", card.mdcsum(), failure);
308
309
    assert!(result.is_ok());

310
    let metrics = state.metrics_clone();
311
312
313
314
315
    metrics.register(&registry).unwrap();

    let mut foo_counters = [0u64; 8];
    let mut bar_counters = [0u64; 8];

316
317
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
318
319
320

    let client = reqwest::Client::new();

321
322
323
    let message = dynamo_async_openai::types::ChatCompletionRequestMessage::User(
        dynamo_async_openai::types::ChatCompletionRequestUserMessage {
            content: dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
Paul Hendricks's avatar
Paul Hendricks committed
324
325
326
327
328
329
                "hi".to_string(),
            ),
            name: None,
        },
    );

330
    let mut request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
331
        .model("foo")
Paul Hendricks's avatar
Paul Hendricks committed
332
        .messages(vec![message])
333
        .build()
Paul Hendricks's avatar
Paul Hendricks committed
334
335
336
337
338
339
340
        .expect("Failed to build request");

    // let mut request = ChatCompletionRequest::builder()
    //     .model("foo")
    //     .add_user_message("hi")
    //     .build()
    //     .unwrap();
341
342
343

    // ==== ChatCompletions / Stream / Success ====
    request.stream = Some(true);
Paul Hendricks's avatar
Paul Hendricks committed
344
345

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
346
347
348
    request.max_tokens = Some(3000);

    let response = client
349
        .post(format!("http://localhost:{}/v1/chat/completions", port))
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        .json(&request)
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success(), "{:?}", response);

    tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
    assert_eq!(metrics.get_inflight_count("foo"), 1);

    // process byte stream
    let _ = response.bytes().await.unwrap();

    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Stream,
        Status::Success,
        &mut foo_counters,
    );
369
370
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
371
372
373
374
375

    // check registry and look or the request duration histogram
    let families = registry.gather();
    let histogram_metric_family = families
        .into_iter()
376
377
378
379
380
381
382
383
        .find(|m| {
            m.get_name()
                == format!(
                    "{}_{}",
                    name_prefix::FRONTEND,
                    frontend_service::REQUEST_DURATION_SECONDS
                )
        })
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        .expect("Histogram metric not found");

    assert_eq!(
        histogram_metric_family.get_field_type(),
        MetricType::HISTOGRAM
    );

    let histogram_metric = histogram_metric_family.get_metric();

    assert_eq!(histogram_metric.len(), 1); // We have one metric with label model

    let metric = &histogram_metric[0];
    let histogram = metric.get_histogram();

    let buckets = histogram.get_bucket();

    let mut found = false;
401
402
403
404
405
406
    let mut expected_count = 0;
    for bucket_idx in 1..buckets.len() {
        if buckets[bucket_idx].get_upper_bound() >= 2.5
            && buckets[bucket_idx - 1].get_upper_bound() < 2.5
        {
            found = true;
407
            assert_eq!(
408
409
410
                buckets[bucket_idx].get_cumulative_count(),
                1,
                "Observation should be counted in the bucket containing 2.5"
411
            );
412
            expected_count = 1;
413
414
        } else {
            assert_eq!(
415
416
                buckets[bucket_idx].get_cumulative_count(),
                expected_count,
417
418
419
420
421
422
423
424
425
426
                "No observations should be in this bucket"
            );
        }
    }

    assert!(found, "The expected bucket was not found");
    // ==== ChatCompletions / Stream / Success ====

    // ==== ChatCompletions / Unary / Success ====
    request.stream = Some(false);
Paul Hendricks's avatar
Paul Hendricks committed
427
428

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
429
430
431
    request.max_tokens = Some(0);

    let future = client
432
        .post(format!("http://localhost:{}/v1/chat/completions", port))
433
434
435
436
437
438
439
440
441
442
443
444
        .json(&request)
        .send();

    let response = future.await.unwrap();

    assert!(response.status().is_success(), "{:?}", response);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Unary,
        Status::Success,
        &mut foo_counters,
    );
445
446
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
447
448
449
450
    // ==== ChatCompletions / Unary / Success ====

    // ==== ChatCompletions / Stream / Error ====
    request.model = "bar".to_string();
Paul Hendricks's avatar
Paul Hendricks committed
451
452

    // ALLOW: max_tokens is deprecated in favor of completion_usage_tokens
453
454
455
456
    request.max_tokens = Some(0);
    request.stream = Some(true);

    let response = client
457
        .post(format!("http://localhost:{}/v1/chat/completions", port))
458
459
460
461
462
463
464
465
466
467
468
469
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Stream,
        Status::Error,
        &mut bar_counters,
    );
470
471
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
472
473
474
475
476
477
    // ==== ChatCompletions / Stream / Error ====

    // ==== ChatCompletions / Unary / Error ====
    request.stream = Some(false);

    let response = client
478
        .post(format!("http://localhost:{}/v1/chat/completions", port))
479
480
481
482
483
484
485
486
487
488
489
490
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    inc_counter(
        Endpoint::ChatCompletions,
        RequestType::Unary,
        Status::Error,
        &mut bar_counters,
    );
491
492
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
493
494
495
    // ==== ChatCompletions / Unary / Error ====

    // ==== Completions / Unary / Error ====
496
    let mut request = dynamo_async_openai::types::CreateCompletionRequestArgs::default()
497
498
499
500
501
502
        .model("bar")
        .prompt("hi")
        .build()
        .unwrap();

    let response = client
503
        .post(format!("http://localhost:{}/v1/completions", port))
504
505
506
507
508
509
510
511
512
513
514
515
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    inc_counter(
        Endpoint::Completions,
        RequestType::Unary,
        Status::Error,
        &mut bar_counters,
    );
516
517
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
518
519
520
521
522
523
    // ==== Completions / Unary / Error ====

    // ==== Completions / Stream / Error ====
    request.stream = Some(true);

    let response = client
524
        .post(format!("http://localhost:{}/v1/completions", port))
525
526
527
528
529
530
531
532
533
534
535
536
        .json(&request)
        .send()
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    inc_counter(
        Endpoint::Completions,
        RequestType::Stream,
        Status::Error,
        &mut bar_counters,
    );
537
538
    compare_counters(&metrics, "foo", &foo_counters);
    compare_counters(&metrics, "bar", &bar_counters);
539
540
541
542
543
544
545
    // ==== Completions / Stream / Error ====

    // =========== Test Invalid Request ===========
    // send a completion request to a chat endpoint
    request.stream = Some(false);

    let response = client
546
        .post(format!("http://localhost:{}/v1/chat/completions", port))
547
548
549
550
551
        .json(&request)
        .send()
        .await
        .unwrap();

552
    assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{:?}", response);
553
554
555

    // =========== Query /metrics endpoint ===========
    let response = client
556
        .get(format!("http://localhost:{}/metrics", port))
557
558
559
560
561
562
563
564
565
566
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success(), "{:?}", response);
    println!("{}", response.text().await.unwrap());

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

// === HTTP Client Tests ===

/// Wait for the HTTP service to be ready by checking its health endpoint
async fn wait_for_service_ready(port: u16) {
    let start = tokio::time::Instant::now();
    let timeout = tokio::time::Duration::from_secs(5);
    loop {
        match reqwest::get(&format!("http://localhost:{}/health", port)).await {
            Ok(_) => break,
            Err(_) if start.elapsed() < timeout => {
                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            }
            Err(e) => panic!("Service failed to start within timeout: {}", e),
        }
    }
}

585
586
async fn service_with_engines() -> (HttpService, Arc<CounterEngine>, Arc<AlwaysFailEngine>, u16) {
    let port = get_random_port().await;
587
588
589
590
591
592
    let service = HttpService::builder()
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
        .port(port)
        .build()
        .unwrap();
593
594
595
596
597
    let manager = service.model_manager();

    let counter = Arc::new(CounterEngine {});
    let failure = Arc::new(AlwaysFailEngine {});

598
    let card = ModelDeploymentCard::with_name_only("foo");
599
    manager
600
        .add_chat_completions_model("foo", card.mdcsum(), counter.clone())
601
        .unwrap();
602
    let card = ModelDeploymentCard::with_name_only("bar");
603
    manager
604
        .add_chat_completions_model("bar", card.mdcsum(), failure.clone())
605
606
        .unwrap();
    manager
607
        .add_completions_model("bar", card.mdcsum(), failure.clone())
608
609
        .unwrap();

610
    (service, counter, failure, port)
611
612
}

613
fn pure_openai_client(port: u16) -> PureOpenAIClient {
614
615
616
617
618
619
620
    let config = HttpClientConfig {
        openai_config: OpenAIConfig::new().with_api_base(format!("http://localhost:{}/v1", port)),
        verbose: false,
    };
    PureOpenAIClient::new(config)
}

621
fn nv_custom_client(port: u16) -> NvCustomClient {
622
623
624
625
626
627
628
    let config = HttpClientConfig {
        openai_config: OpenAIConfig::new().with_api_base(format!("http://localhost:{}/v1", port)),
        verbose: false,
    };
    NvCustomClient::new(config)
}

629
fn generic_byot_client(port: u16) -> GenericBYOTClient {
630
631
632
633
634
635
636
637
    let config = HttpClientConfig {
        openai_config: OpenAIConfig::new().with_api_base(format!("http://localhost:{}/v1", port)),
        verbose: false,
    };
    GenericBYOTClient::new(config)
}

#[tokio::test]
638
639
640
641
async fn test_pure_openai_client() {
    let (service, _counter, _failure, port) = service_with_engines().await;
    let pure_openai_client = pure_openai_client(port);

642
643
644
645
646
647
648
    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
649
    wait_for_service_ready(port).await;
650
651

    // Test successful streaming request
652
    let request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
653
654
        .model("foo")
        .messages(vec![
655
656
657
658
659
660
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let result = pure_openai_client.chat_stream(request).await;
    assert!(result.is_ok(), "PureOpenAI client should succeed");

    let (mut stream, _context) = result.unwrap().dissolve();
    let mut count = 0;
    while let Some(response) = stream.next().await {
        count += 1;
        assert!(response.is_ok(), "Response should be ok");
        if count >= 3 {
            break; // Don't consume entire stream
        }
    }
    assert!(count > 0, "Should receive at least one response");

    // Test error case with invalid model
685
    let request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
686
687
        .model("bar") // This model will fail
        .messages(vec![
688
689
690
691
692
693
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
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
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let result = pure_openai_client.chat_stream(request).await;
    assert!(
        result.is_ok(),
        "Client should return stream even for failing model"
    );

    let (mut stream, _context) = result.unwrap().dissolve();
    if let Some(response) = stream.next().await {
        assert!(
            response.is_err(),
            "Response should be error for failing model"
        );
    }

    // Test context management
    let ctx = HttpRequestContext::new();
719
    let request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
720
721
        .model("foo")
        .messages(vec![
722
723
724
725
726
727
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let result = pure_openai_client
        .chat_stream_with_context(request, ctx.clone())
        .await;
    assert!(result.is_ok(), "Context-based request should succeed");

    let (_stream, context) = result.unwrap().dissolve();
    assert_eq!(context.id(), ctx.id(), "Context ID should match");

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}

#[tokio::test]
750
751
752
753
async fn test_nv_custom_client() {
    let (service, _counter, _failure, port) = service_with_engines().await;
    let nv_custom_client = nv_custom_client(port);

754
755
756
757
758
759
760
    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
761
    wait_for_service_ready(port).await;
762
763

    // Test successful streaming request
764
    let inner_request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
765
766
        .model("foo")
        .messages(vec![
767
768
769
770
771
772
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
773
774
775
776
777
778
779
780
781
782
783
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let request = NvCreateChatCompletionRequest {
        inner: inner_request,
784
        common: Default::default(),
785
        nvext: None,
786
        chat_template_args: None,
787
        media_io_kwargs: None,
788
        unsupported_fields: Default::default(),
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
    };

    let result = nv_custom_client.chat_stream(request).await;
    assert!(result.is_ok(), "NvCustom client should succeed");

    let (mut stream, _context) = result.unwrap().dissolve();
    let mut count = 0;
    while let Some(response) = stream.next().await {
        count += 1;
        assert!(response.is_ok(), "Response should be ok");
        if count >= 3 {
            break; // Don't consume entire stream
        }
    }
    assert!(count > 0, "Should receive at least one response");

    // Test error case with invalid model
806
    let inner_request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
807
808
        .model("bar") // This model will fail
        .messages(vec![
809
810
811
812
813
814
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
815
816
817
818
819
820
821
822
823
824
825
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let request = NvCreateChatCompletionRequest {
        inner: inner_request,
826
        common: Default::default(),
827
        nvext: None,
828
        chat_template_args: None,
829
        media_io_kwargs: None,
830
        unsupported_fields: Default::default(),
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
    };

    let result = nv_custom_client.chat_stream(request).await;
    assert!(
        result.is_ok(),
        "Client should return stream even for failing model"
    );

    let (mut stream, _context) = result.unwrap().dissolve();
    if let Some(response) = stream.next().await {
        assert!(
            response.is_err(),
            "Response should be error for failing model"
        );
    }

    // Test context management
    let ctx = HttpRequestContext::new();
849
    let inner_request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
850
851
        .model("foo")
        .messages(vec![
852
853
854
855
856
857
            dynamo_async_openai::types::ChatCompletionRequestMessage::User(
                dynamo_async_openai::types::ChatCompletionRequestUserMessage {
                    content:
                        dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
                            "Hi".to_string(),
                        ),
858
859
860
861
862
863
864
865
866
867
868
                    name: None,
                },
            ),
        ])
        .stream(true)
        .max_tokens(50u32)
        .build()
        .unwrap();

    let request = NvCreateChatCompletionRequest {
        inner: inner_request,
869
        common: Default::default(),
870
        nvext: None,
871
        chat_template_args: None,
872
        media_io_kwargs: None,
873
        unsupported_fields: Default::default(),
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
    };

    let result = nv_custom_client
        .chat_stream_with_context(request, ctx.clone())
        .await;
    assert!(result.is_ok(), "Context-based request should succeed");

    let (_stream, context) = result.unwrap().dissolve();
    assert_eq!(context.id(), ctx.id(), "Context ID should match");

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}

#[tokio::test]
889
890
891
892
async fn test_generic_byot_client() {
    let (service, _counter, _failure, port) = service_with_engines().await;
    let generic_byot_client = generic_byot_client(port);

893
894
895
896
897
898
899
    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
900
    wait_for_service_ready(port).await;
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

    // Test successful streaming request
    let request = serde_json::json!({
        "model": "foo",
        "messages": [
            {
                "role": "user",
                "content": "Hi"
            }
        ],
        "stream": true,
        "max_tokens": 50
    });

    let result = generic_byot_client.chat_stream(request).await;
    assert!(result.is_ok(), "GenericBYOT client should succeed");

    let (mut stream, _context) = result.unwrap().dissolve();
    let mut count = 0;
    while let Some(response) = stream.next().await {
        println!("Response: {:?}", response);
        count += 1;
        assert!(response.is_ok(), "Response should be ok");
        if count >= 3 {
            break; // Don't consume entire stream
        }
    }
    assert!(count > 0, "Should receive at least one response");

    // Test error case with invalid model
    let request = serde_json::json!({
        "model": "bar", // This model will fail
        "messages": [
            {
                "role": "user",
                "content": "Hi"
            }
        ],
        "stream": true,
        "max_tokens": 50
    });

    let result = generic_byot_client.chat_stream(request).await;
    assert!(
        result.is_ok(),
        "Client should return stream even for failing model"
    );

    let (mut stream, _context) = result.unwrap().dissolve();
    if let Some(response) = stream.next().await {
        assert!(
            response.is_err(),
            "Response should be error for failing model"
        );
    }

    // Test context management
    let ctx = HttpRequestContext::new();
    let request = serde_json::json!({
        "model": "foo",
        "messages": [
            {
                "role": "user",
                "content": "Hi"
            }
        ],
        "stream": true,
        "max_tokens": 50
    });

    let result = generic_byot_client
        .chat_stream_with_context(request, ctx.clone())
        .await;
    assert!(result.is_ok(), "Context-based request should succeed");

    let (_stream, context) = result.unwrap().dissolve();
    assert_eq!(context.id(), ctx.id(), "Context ID should match");

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}
Ryan Olson's avatar
Ryan Olson committed
982
983
984

#[tokio::test]
async fn test_client_disconnect_cancellation_unary() {
985
    let port = get_random_port().await;
986
987
988
    let service = HttpService::builder()
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
989
        .port(port)
990
991
        .build()
        .unwrap();
Ryan Olson's avatar
Ryan Olson committed
992
993
994
995
996
997
998
999
1000
1001
    let state = service.state_clone();
    let manager = state.manager();

    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
1002
    wait_for_service_ready(port).await;
Ryan Olson's avatar
Ryan Olson committed
1003
1004

    // Create a long-running engine (10 seconds)
1005
    let card = ModelDeploymentCard::with_name_only("slow-model");
Ryan Olson's avatar
Ryan Olson committed
1006
1007
    let long_running_engine = Arc::new(LongRunningEngine::new(10_000));
    manager
1008
        .add_chat_completions_model("slow-model", card.mdcsum(), long_running_engine.clone())
Ryan Olson's avatar
Ryan Olson committed
1009
1010
1011
1012
        .unwrap();

    let client = reqwest::Client::new();

1013
1014
1015
    let message = dynamo_async_openai::types::ChatCompletionRequestMessage::User(
        dynamo_async_openai::types::ChatCompletionRequestUserMessage {
            content: dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
Ryan Olson's avatar
Ryan Olson committed
1016
1017
1018
1019
1020
1021
                "This will take a long time".to_string(),
            ),
            name: None,
        },
    );

1022
    let request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
Ryan Olson's avatar
Ryan Olson committed
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
        .model("slow-model")
        .messages(vec![message])
        .stream(false) // Test unary response
        .build()
        .expect("Failed to build request");

    // Start the request and cancel it after 1 second
    let start_time = std::time::Instant::now();

    let request_future = async {
        client
1034
            .post(format!("http://localhost:{}/v1/chat/completions", port))
Ryan Olson's avatar
Ryan Olson committed
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
            .json(&request)
            .send()
            .await
    };

    // Use timeout to simulate client disconnect after 1 second
    let result = timeout(std::time::Duration::from_millis(1000), request_future).await;

    let elapsed = start_time.elapsed();

    // The request should timeout (simulating client disconnect)
    assert!(result.is_err(), "Request should have timed out");

    // Give the service a moment to detect the disconnect and propagate cancellation
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    // Verify the engine was cancelled
    assert!(
        long_running_engine.was_cancelled(),
        "Engine should have been cancelled due to client disconnect"
    );

    // Verify cancellation happened quickly (within 2 seconds, not the full 10 seconds)
    assert!(
        elapsed < std::time::Duration::from_secs(2),
        "Cancellation should have propagated quickly, took {:?}",
        elapsed
    );

    tracing::info!(
        "✅ Client disconnect test passed! Request cancelled in {:?}, engine detected cancellation",
        elapsed
    );

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}

#[tokio::test]
async fn test_client_disconnect_cancellation_streaming() {
    dynamo_runtime::logging::init();

1077
    let port = get_random_port().await;
1078
1079
1080
    let service = HttpService::builder()
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
1081
        .port(port)
1082
1083
        .build()
        .unwrap();
Ryan Olson's avatar
Ryan Olson committed
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    let state = service.state_clone();
    let manager = state.manager();

    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
1094
    wait_for_service_ready(port).await;
Ryan Olson's avatar
Ryan Olson committed
1095
1096

    // Create a long-running engine (10 seconds)
1097
    let card = ModelDeploymentCard::with_name_only("slow-stream-model");
Ryan Olson's avatar
Ryan Olson committed
1098
1099
    let long_running_engine = Arc::new(LongRunningEngine::new(10_000));
    manager
1100
1101
1102
1103
1104
        .add_chat_completions_model(
            "slow-stream-model",
            card.mdcsum(),
            long_running_engine.clone(),
        )
Ryan Olson's avatar
Ryan Olson committed
1105
1106
1107
1108
        .unwrap();

    let client = reqwest::Client::new();

1109
1110
1111
    let message = dynamo_async_openai::types::ChatCompletionRequestMessage::User(
        dynamo_async_openai::types::ChatCompletionRequestUserMessage {
            content: dynamo_async_openai::types::ChatCompletionRequestUserMessageContent::Text(
Ryan Olson's avatar
Ryan Olson committed
1112
1113
1114
1115
1116
1117
                "This will stream for a long time".to_string(),
            ),
            name: None,
        },
    );

1118
    let request = dynamo_async_openai::types::CreateChatCompletionRequestArgs::default()
Ryan Olson's avatar
Ryan Olson committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
        .model("slow-stream-model")
        .messages(vec![message])
        .stream(true) // Test streaming response
        .build()
        .expect("Failed to build request");

    // Start the request and cancel it after 1 second
    let start_time = std::time::Instant::now();

    let request_future = async {
        let response = client
1130
            .post(format!("http://localhost:{}/v1/chat/completions", port))
Ryan Olson's avatar
Ryan Olson committed
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
            .json(&request)
            .send()
            .await
            .unwrap();

        // Start reading the stream, then drop it to simulate client disconnect
        let mut stream = response.bytes_stream();
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        // Read one chunk then drop the stream (simulating client disconnect)
        let _ = StreamExt::next(&mut stream).await;
        // Stream gets dropped here when function exits
    };

    // Use timeout to simulate the streaming request timing out
    let _result = timeout(std::time::Duration::from_millis(1500), request_future).await;

    let elapsed = start_time.elapsed();

    // Give the service time to detect the disconnect
    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;

    // Verify the engine was cancelled
    assert!(
        long_running_engine.was_cancelled(),
        "Engine should have been cancelled due to streaming client disconnect"
    );

    // Verify cancellation happened reasonably quickly
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "Stream cancellation should have propagated reasonably quickly, took {:?}",
        elapsed
    );

    tracing::info!(
        "✅ Streaming client disconnect test passed! Stream cancelled in {:?}, engine detected cancellation",
        elapsed
    );

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}

#[tokio::test]
async fn test_request_id_annotation() {
    // TODO(ryan): make better fixtures, this is too much to test sometime so simple
    dynamo_runtime::logging::init();

1180
    let port = get_random_port().await;
1181
1182
1183
    let service = HttpService::builder()
        .enable_chat_endpoints(true)
        .enable_cmpl_endpoints(true)
1184
        .port(port)
1185
1186
        .build()
        .unwrap();
Ryan Olson's avatar
Ryan Olson committed
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
    let state = service.state_clone();
    let manager = state.manager();

    let token = CancellationToken::new();
    let cancel_token = token.clone();

    // Start the service
    let task = tokio::spawn(async move { service.run(token).await });

    // Wait for service to be ready
1197
    wait_for_service_ready(port).await;
Ryan Olson's avatar
Ryan Olson committed
1198
1199

    // Add a counter engine for this test
1200
    let card = ModelDeploymentCard::with_name_only("test-model");
Ryan Olson's avatar
Ryan Olson committed
1201
1202
    let counter_engine = Arc::new(CounterEngine {});
    manager
1203
        .add_chat_completions_model("test-model", card.mdcsum(), counter_engine)
Ryan Olson's avatar
Ryan Olson committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
        .unwrap();

    // Create reqwest client directly
    let client = reqwest::Client::new();

    // Generate a UUID for the request ID
    let request_uuid = uuid::Uuid::new_v4();

    // Create the request JSON directly
    let request_json = serde_json::json!({
        "model": "test-model",
        "messages": [
            {
                "role": "user",
                "content": "Test request with annotation"
            }
        ],
        "stream": true,
        "max_tokens": 50,
        "nvext": {
            "annotations": ["request_id"]
        }
    });

    // Make the streaming request with custom header
    let response = client
1230
        .post(format!("http://localhost:{}/v1/chat/completions", port))
Ryan Olson's avatar
Ryan Olson committed
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
        .header("x-dynamo-request-id", request_uuid.to_string())
        .json(&request_json)
        .send()
        .await
        .expect("Request should succeed");

    assert!(
        response.status().is_success(),
        "Response should be successful"
    );

    // Collect the entire response body as bytes first
    let body_bytes = response
        .bytes()
        .await
        .expect("Failed to read response body");
    let body_text = String::from_utf8_lossy(&body_bytes);

    // Create a cursor from the text and use SseLineCodec to parse it
    let cursor = Cursor::new(body_text.to_string());
    let framed = FramedRead::new(cursor, SseLineCodec::new());
    let annotated_stream = convert_sse_stream::<NvCreateChatCompletionStreamResponse>(framed);

    // Look for the annotation in the stream
    let mut found_request_id_annotation = false;
    let mut received_request_id = None;

    // Process the annotated stream and look for the request_id annotation
    let mut annotated_stream = std::pin::pin!(annotated_stream);
    while let Some(annotated_response) = annotated_stream.next().await {
        // Check if this is a request_id annotation
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
        if let Some(event) = &annotated_response.event
            && event == "request_id"
        {
            found_request_id_annotation = true;
            // Extract the request ID from the annotation
            if let Some(comments) = &annotated_response.comment
                && let Some(comment) = comments.first()
            {
                // The comment contains a JSON-encoded string, so we need to parse it
                if let Ok(parsed_value) = serde_json::from_str::<String>(comment) {
                    received_request_id = Some(parsed_value);
                } else {
                    // Fallback: remove quotes manually if JSON parsing fails
                    received_request_id = Some(comment.trim_matches('"').to_string());
Ryan Olson's avatar
Ryan Olson committed
1276
1277
                }
            }
1278
            break;
Ryan Olson's avatar
Ryan Olson committed
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
        }
    }

    // Verify we found the annotation
    assert!(
        found_request_id_annotation,
        "Should have received request_id annotation in the stream"
    );

    // Verify the request ID matches what we sent
    assert!(
        received_request_id.is_some(),
        "Should have received the request ID in the annotation"
    );

    let received_uuid_str = received_request_id.unwrap();
    assert_eq!(
        received_uuid_str,
        request_uuid.to_string(),
        "Received request ID should match the one we sent: expected {}, got {}",
        request_uuid,
        received_uuid_str
    );

    tracing::info!(
        "✅ Request ID annotation test passed! Sent UUID: {}, Received: {}",
        request_uuid,
        received_uuid_str
    );

    cancel_token.cancel();
    task.await.unwrap().unwrap();
}