endpoint.rs 8.7 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
use std::{future::Future, pin::Pin, sync::Arc};
5

6
use crate::{
7
    backend::Backend,
8
    engines::StreamingEngineAdapter,
9
    model_type::{ModelInput, ModelType},
10
    preprocessor::{BackendOutput, PreprocessedRequest},
11
    types::{
12
        Annotated,
13
14
15
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
        },
16
    },
17
};
18

19
use dynamo_runtime::engine::AsyncEngineStream;
Neelay Shah's avatar
Neelay Shah committed
20
use dynamo_runtime::pipeline::{
21
    Context, ManyOut, Operator, SegmentSource, ServiceBackend, SingleIn, Source, network::Ingress,
22
};
23
use dynamo_runtime::{DistributedRuntime, protocols::EndpointId};
24

25
use crate::entrypoint::EngineConfig;
26
27

pub async fn run(
28
    distributed_runtime: DistributedRuntime,
29
30
31
    path: String,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
32
    let cancel_token = distributed_runtime.primary_token().clone();
33
    let endpoint_id: EndpointId = path.parse()?;
34

35
    let component = distributed_runtime
36
        .namespace(&endpoint_id.namespace)?
37
        .component(&endpoint_id.component)?;
38
39
40
    let endpoint = component.endpoint(&endpoint_id.name);

    let rt_fut: Pin<Box<dyn Future<Output = _> + Send + 'static>> = match engine_config {
41
        EngineConfig::StaticFull { engine, mut model } => {
42
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
43
44
45
46
            let ingress_chat = Ingress::<
                Context<NvCreateChatCompletionRequest>,
                Pin<Box<dyn AsyncEngineStream<Annotated<NvCreateChatCompletionStreamResponse>>>>,
            >::for_engine(engine)?;
47
48
49
            model
                .attach(&endpoint, ModelType::Chat, ModelInput::Text)
                .await?;
50
51
            let fut_chat = endpoint.endpoint_builder().handler(ingress_chat).start();

52
            Box::pin(fut_chat)
53
        }
54
55
        EngineConfig::StaticCore {
            engine: inner_engine,
56
            mut model,
57
            is_prefill,
58
        } => {
59
            // Pre-processing is done ingress-side, so it should be already done.
60
61
62
63
            let frontend = SegmentSource::<
                SingleIn<PreprocessedRequest>,
                ManyOut<Annotated<BackendOutput>>,
            >::new();
64
            let backend = Backend::from_mdc(model.card()).into_operator();
65
66
67
68
69
70
            let engine = ServiceBackend::from_engine(inner_engine);
            let pipeline = frontend
                .link(backend.forward_edge())?
                .link(engine)?
                .link(backend.backward_edge())?
                .link(frontend)?;
71
            let ingress = Ingress::for_pipeline(pipeline)?;
72

73
74
75
76
77
78
79
80
            let model_type = if is_prefill {
                ModelType::Prefill
            } else {
                ModelType::Chat | ModelType::Completions
            };
            model
                .attach(&endpoint, model_type, ModelInput::Tokens)
                .await?;
81

82
            let fut = endpoint.endpoint_builder().handler(ingress).start();
83
            Box::pin(fut)
84
        }
85
        EngineConfig::Dynamic(_) => {
86
            unreachable!("An endpoint input will never have a Dynamic engine");
87
        }
88
89
    };

90
91
92
93
    // Capture the actual error from rt_fut when it completes
    // Note: We must return rt_result to propagate the actual error back to the user.
    // If we don't return the specific error, the programmer/user won't know what actually
    // caused the endpoint service to fail, making debugging much more difficult.
94
    tokio::select! {
95
96
97
98
99
100
101
102
103
104
105
106
        rt_result = rt_fut => {
            tracing::debug!("Endpoint service completed");
            match rt_result {
                Ok(_) => {
                    tracing::warn!("Endpoint service completed unexpectedly for endpoint: {}", path);
                    Err(anyhow::anyhow!("Endpoint service completed unexpectedly for endpoint: {}", path))
                }
                Err(e) => {
                    tracing::error!(%e, "Endpoint service failed for endpoint: {} - Error: {}", path, e);
                    Err(anyhow::anyhow!("Endpoint service failed for endpoint: {} - Error: {}", path, e))
                }
            }
107
108
        }
        _ = cancel_token.cancelled() => {
109
110
            tracing::debug!("Endpoint service cancelled");
            Ok(())
111
112
113
        }
    }
}
114
115
116
117
118

#[cfg(test)]
#[cfg(feature = "integration")]
mod integration_tests {
    use super::*;
119
    use dynamo_runtime::protocols::EndpointId;
120
121
122
123
124
125
126
127
128
129

    async fn create_test_environment() -> anyhow::Result<(DistributedRuntime, EngineConfig)> {
        // Create a minimal distributed runtime and engine config for testing
        let runtime = dynamo_runtime::Runtime::from_settings()
            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;

        let distributed_runtime = dynamo_runtime::DistributedRuntime::from_settings(runtime)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create distributed runtime: {}", e))?;

130
131
        let engine_config = EngineConfig::StaticFull {
            engine: crate::engines::make_echo_engine(),
132
133
134
135
136
137
138
139
140
141
142
143
144
            model: Box::new(
                crate::local_model::LocalModelBuilder::default()
                    .model_name(Some("test-model".to_string()))
                    .build()
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to build LocalModel: {}", e))?,
            ),
        };

        Ok((distributed_runtime, engine_config))
    }

    #[tokio::test]
145
    #[ignore = "Failing in CI"]
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
    async fn test_run_function_valid_endpoint() {
        // Test that run() works correctly with valid endpoints

        let (runtime, engine_config) = match create_test_environment().await {
            Ok(env) => env,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Test with valid endpoint - start the service and then connect to it
        let valid_path = "dyn://valid-endpoint.mocker.generate";
        let valid_endpoint: EndpointId = valid_path.parse().expect("Valid endpoint should parse");

        let runtime_clone = runtime.clone();
        let engine_config_clone = engine_config.clone();
        let valid_path_clone = valid_path.to_string();

        let service_handle =
            tokio::spawn(
                async move { run(runtime_clone, valid_path_clone, engine_config_clone).await },
            );

        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let client_result = async {
            let namespace = runtime.namespace(&valid_endpoint.namespace)?;
            let component = namespace.component(&valid_endpoint.component)?;
            let client = component.endpoint(&valid_endpoint.name).client().await?;
            client.wait_for_instances().await?;
            Ok::<_, anyhow::Error>(client)
        }
        .await;

        match client_result {
            Ok(_client) => {
                println!("Valid endpoint: Successfully connected to service");
                service_handle.abort(); // Abort the service since we've verified it works
            }
            Err(e) => {
                println!("Valid endpoint: Failed to connect to service: {}", e);
                service_handle.abort(); // Abort the service since the test failed
                panic!(
                    "Valid endpoint should allow client connections, but failed: {}",
                    e
                );
            }
        }
    }

    #[tokio::test]
    #[ignore = "DistributedRuntime drop issue persists - test logic validates error propagation correctly"]
    async fn test_run_function_invalid_endpoint() {
        // Test that invalid endpoints fail validation during run()
        let invalid_path = "dyn://@@@123.mocker.generate";

        // Create test environment
        let (runtime, engine_config) = create_test_environment()
            .await
            .expect("Failed to create test environment");

        // Call run() directly - it should fail quickly for invalid endpoints
        let result = run(runtime, invalid_path.to_string(), engine_config).await;

        // Should return an error for invalid endpoints
        assert!(
            result.is_err(),
            "run() should fail for invalid endpoint: {:?}",
            result
        );

        // Check that the error message contains validation-related keywords
        let error_msg = result.unwrap_err().to_string().to_lowercase();
        assert!(
            error_msg.contains("invalid")
                || error_msg.contains("namespace")
                || error_msg.contains("validation")
                || error_msg.contains("failed"),
            "Error message should contain validation keywords, got: {}",
            error_msg
        );
    }
}