endpoint.rs 9.25 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 mut component = distributed_runtime
36
        .namespace(&endpoint_id.namespace)?
37
        .component(&endpoint_id.component)?;
38
39
40
41
42
43
44
45
46

    // We can only make the NATS service if we have NATS
    if distributed_runtime.nats_client().is_some() {
        // TODO fix in next PR, ServiceConfigBuilder is silly
        component = component.service_builder().create().await?;
    }
    let endpoint = component.endpoint(&endpoint_id.name);

    let rt_fut: Pin<Box<dyn Future<Output = _> + Send + 'static>> = match engine_config {
47
48
49
50
51
        EngineConfig::StaticFull {
            engine,
            mut model,
            is_static,
        } => {
52
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
53
54
55
56
57
            let ingress_chat = Ingress::<
                Context<NvCreateChatCompletionRequest>,
                Pin<Box<dyn AsyncEngineStream<Annotated<NvCreateChatCompletionStreamResponse>>>>,
            >::for_engine(engine)?;

58
            if !is_static {
59
60
61
                model
                    .attach(&endpoint, ModelType::Chat, ModelInput::Text)
                    .await?;
62
            }
63
64
            let fut_chat = endpoint.endpoint_builder().handler(ingress_chat).start();

65
            Box::pin(fut_chat)
66
        }
67
68
        EngineConfig::StaticCore {
            engine: inner_engine,
69
            mut model,
70
            is_static,
71
        } => {
72
            // Pre-processing is done ingress-side, so it should be already done.
73
74
75
76
            let frontend = SegmentSource::<
                SingleIn<PreprocessedRequest>,
                ManyOut<Annotated<BackendOutput>>,
            >::new();
77
            let backend = Backend::from_mdc(model.card()).into_operator();
78
79
80
81
82
83
            let engine = ServiceBackend::from_engine(inner_engine);
            let pipeline = frontend
                .link(backend.forward_edge())?
                .link(engine)?
                .link(backend.backward_edge())?
                .link(frontend)?;
84
            let ingress = Ingress::for_pipeline(pipeline)?;
85

86
            if !is_static {
87
88
89
90
91
                // Default to supporting both Chat and Completions endpoints
                let model_type = ModelType::Chat | ModelType::Completions;
                model
                    .attach(&endpoint, model_type, ModelInput::Tokens)
                    .await?;
92
            }
93

94
95
            let fut = endpoint.endpoint_builder().handler(ingress).start();

96
            Box::pin(fut)
97
        }
98
99
100
        EngineConfig::StaticRemote(_) => {
            panic!("StaticRemote definitions are only for the frontend end node.");
        }
101
        EngineConfig::Dynamic(_) => {
102
            unreachable!("An endpoint input will never have a Dynamic engine");
103
        }
104
105
    };

106
107
108
109
    // 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.
110
    tokio::select! {
111
112
113
114
115
116
117
118
119
120
121
122
        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))
                }
            }
123
124
        }
        _ = cancel_token.cancelled() => {
125
126
            tracing::debug!("Endpoint service cancelled");
            Ok(())
127
128
129
        }
    }
}
130
131
132
133
134

#[cfg(test)]
#[cfg(feature = "integration")]
mod integration_tests {
    use super::*;
135
    use dynamo_runtime::protocols::EndpointId;
136
137
138
139
140
141
142
143
144
145

    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))?;

146
147
        let engine_config = EngineConfig::StaticFull {
            engine: crate::engines::make_echo_engine(),
148
149
150
151
152
153
154
            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))?,
            ),
155
            is_static: false,
156
157
158
159
160
161
        };

        Ok((distributed_runtime, engine_config))
    }

    #[tokio::test]
162
    #[ignore = "Failing in CI"]
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
    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
        );
    }
}