pipeline.rs 19.7 KB
Newer Older
1
//! Pipeline orchestrator for gRPC router request processing
2
//!
3
4
//! This module defines the RequestPipeline orchestrator that coordinates
//! the execution of pipeline stages from request preparation to response delivery.
5

6
use std::{collections::HashMap, sync::Arc};
7

8
use axum::response::{IntoResponse, Response};
9
use tokio::sync::RwLock;
10
use tracing::{debug, error};
11

12
13
// Import all stage types from the stages module
use super::stages::*;
14
use super::{context::*, error, harmony, processing, responses::BackgroundTaskInfo, streaming};
15
use crate::{
16
    core::WorkerRegistry,
17
    policies::PolicyRegistry,
18
19
20
21
    protocols::{
        chat::{ChatCompletionRequest, ChatCompletionResponse},
        generate::GenerateRequest,
    },
22
23
24
25
26
    reasoning_parser::ParserFactory as ReasoningParserFactory,
    tokenizer::traits::Tokenizer,
    tool_parser::ParserFactory as ToolParserFactory,
};

27
28
29
30
// ============================================================================
// Pipeline Orchestrator
// ============================================================================

31
/// Generic request pipeline for all request types
32
33
34
35
///
/// Orchestrates all stages from request preparation to response delivery.
/// Configured differently for regular vs PD mode.
#[derive(Clone)]
36
pub struct RequestPipeline {
37
38
39
    stages: Arc<Vec<Box<dyn PipelineStage>>>,
}

40
impl RequestPipeline {
41
42
43
44
    /// Create a regular (single-worker) pipeline
    pub fn new_regular(
        worker_registry: Arc<WorkerRegistry>,
        policy_registry: Arc<PolicyRegistry>,
45
46
47
48
49
        tokenizer: Arc<dyn Tokenizer>,
        tool_parser_factory: ToolParserFactory,
        reasoning_parser_factory: ReasoningParserFactory,
        configured_tool_parser: Option<String>,
        configured_reasoning_parser: Option<String>,
50
    ) -> Self {
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        // Create response processor
        let processor = processing::ResponseProcessor::new(
            tokenizer.clone(),
            tool_parser_factory.clone(),
            reasoning_parser_factory.clone(),
            configured_tool_parser.clone(),
            configured_reasoning_parser.clone(),
        );

        // Create streaming processor
        let streaming_processor = Arc::new(streaming::StreamingProcessor::new(
            tokenizer,
            tool_parser_factory,
            reasoning_parser_factory,
            configured_tool_parser,
            configured_reasoning_parser,
        ));

69
70
71
72
73
74
75
76
77
78
79
        let stages: Vec<Box<dyn PipelineStage>> = vec![
            Box::new(PreparationStage),
            Box::new(WorkerSelectionStage::new(
                worker_registry,
                policy_registry,
                WorkerSelectionMode::Regular,
            )),
            Box::new(ClientAcquisitionStage),
            Box::new(RequestBuildingStage::new(false)), // No PD metadata
            Box::new(DispatchMetadataStage),
            Box::new(RequestExecutionStage::new(ExecutionMode::Single)),
80
            Box::new(ResponseProcessingStage::new(processor, streaming_processor)),
81
82
83
84
85
86
87
        ];

        Self {
            stages: Arc::new(stages),
        }
    }

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
    /// Create a Harmony (single-worker) pipeline for Harmony-capable models
    pub fn new_harmony(
        worker_registry: Arc<WorkerRegistry>,
        policy_registry: Arc<PolicyRegistry>,
        _tokenizer: Arc<dyn Tokenizer>,
        _tool_parser_factory: ToolParserFactory,
        _reasoning_parser_factory: ReasoningParserFactory,
        _configured_tool_parser: Option<String>,
        _configured_reasoning_parser: Option<String>,
    ) -> Self {
        let stages: Vec<Box<dyn PipelineStage>> = vec![
            Box::new(harmony::stages::HarmonyPreparationStage::new()),
            Box::new(WorkerSelectionStage::new(
                worker_registry,
                policy_registry,
                WorkerSelectionMode::Regular,
            )),
            Box::new(ClientAcquisitionStage),
            Box::new(harmony::stages::HarmonyRequestBuildingStage::new(false)),
            Box::new(DispatchMetadataStage),
            Box::new(RequestExecutionStage::new(ExecutionMode::Single)),
            Box::new(harmony::stages::HarmonyResponseProcessingStage::new()),
        ];

        Self {
            stages: Arc::new(stages),
        }
    }

    /// Create a Harmony PD (prefill-decode) pipeline
    pub fn new_harmony_pd(
        worker_registry: Arc<WorkerRegistry>,
        policy_registry: Arc<PolicyRegistry>,
        _tokenizer: Arc<dyn Tokenizer>,
        _tool_parser_factory: ToolParserFactory,
        _reasoning_parser_factory: ReasoningParserFactory,
        _configured_tool_parser: Option<String>,
        _configured_reasoning_parser: Option<String>,
    ) -> Self {
        let stages: Vec<Box<dyn PipelineStage>> = vec![
            Box::new(harmony::stages::HarmonyPreparationStage::new()),
            Box::new(WorkerSelectionStage::new(
                worker_registry,
                policy_registry,
                WorkerSelectionMode::PrefillDecode,
            )),
            Box::new(ClientAcquisitionStage),
            Box::new(harmony::stages::HarmonyRequestBuildingStage::new(true)),
            Box::new(DispatchMetadataStage),
            Box::new(RequestExecutionStage::new(ExecutionMode::DualDispatch)),
            Box::new(harmony::stages::HarmonyResponseProcessingStage::new()),
        ];

        Self {
            stages: Arc::new(stages),
        }
    }

146
147
148
149
    /// Create a PD (prefill-decode) pipeline
    pub fn new_pd(
        worker_registry: Arc<WorkerRegistry>,
        policy_registry: Arc<PolicyRegistry>,
150
151
152
153
154
        tokenizer: Arc<dyn Tokenizer>,
        tool_parser_factory: ToolParserFactory,
        reasoning_parser_factory: ReasoningParserFactory,
        configured_tool_parser: Option<String>,
        configured_reasoning_parser: Option<String>,
155
    ) -> Self {
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        // Create response processor
        let processor = processing::ResponseProcessor::new(
            tokenizer.clone(),
            tool_parser_factory.clone(),
            reasoning_parser_factory.clone(),
            configured_tool_parser.clone(),
            configured_reasoning_parser.clone(),
        );

        // Create streaming processor
        let streaming_processor = Arc::new(streaming::StreamingProcessor::new(
            tokenizer,
            tool_parser_factory,
            reasoning_parser_factory,
            configured_tool_parser,
            configured_reasoning_parser,
        ));

174
175
176
177
178
179
180
181
182
183
184
        let stages: Vec<Box<dyn PipelineStage>> = vec![
            Box::new(PreparationStage),
            Box::new(WorkerSelectionStage::new(
                worker_registry,
                policy_registry,
                WorkerSelectionMode::PrefillDecode,
            )),
            Box::new(ClientAcquisitionStage),
            Box::new(RequestBuildingStage::new(true)), // Inject PD metadata
            Box::new(DispatchMetadataStage),
            Box::new(RequestExecutionStage::new(ExecutionMode::DualDispatch)),
185
            Box::new(ResponseProcessingStage::new(processor, streaming_processor)),
186
187
188
189
190
191
192
193
194
195
        ];

        Self {
            stages: Arc::new(stages),
        }
    }

    /// Execute the complete pipeline for a chat request
    pub async fn execute_chat(
        &self,
196
197
        request: Arc<ChatCompletionRequest>,
        headers: Option<http::HeaderMap>,
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
        model_id: Option<String>,
        components: Arc<SharedComponents>,
    ) -> Response {
        let mut ctx = RequestContext::for_chat(request, headers, model_id, components);

        // Execute each stage in sequence
        for (idx, stage) in self.stages.iter().enumerate() {
            match stage.execute(&mut ctx).await {
                Ok(Some(response)) => {
                    // Stage completed successfully with a response (e.g., streaming)
                    return response;
                }
                Ok(None) => {
                    // Continue to next stage
                    continue;
                }
                Err(response) => {
                    // Error occurred
                    error!(
                        "Stage {} ({}) failed with status {}",
                        idx + 1,
                        stage.name(),
                        response.status()
                    );
                    return response;
                }
            }
        }

        // Extract final response
        match ctx.state.response.final_response {
            Some(FinalResponse::Chat(response)) => axum::Json(response).into_response(),
            Some(FinalResponse::Generate(_)) => {
231
                error::internal_error("Internal error: wrong response type")
232
            }
233
            None => error::internal_error("No response produced"),
234
235
236
237
238
239
        }
    }

    /// Execute the complete pipeline for a generate request
    pub async fn execute_generate(
        &self,
240
241
        request: Arc<GenerateRequest>,
        headers: Option<http::HeaderMap>,
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
        model_id: Option<String>,
        components: Arc<SharedComponents>,
    ) -> Response {
        let mut ctx = RequestContext::for_generate(request, headers, model_id, components);

        // Execute each stage in sequence
        for (idx, stage) in self.stages.iter().enumerate() {
            match stage.execute(&mut ctx).await {
                Ok(Some(response)) => {
                    // Stage completed successfully with a response (e.g., streaming)
                    return response;
                }
                Ok(None) => {
                    // Continue to next stage
                    continue;
                }
                Err(response) => {
                    // Error occurred
                    error!(
                        "Stage {} ({}) failed with status {}",
                        idx + 1,
                        stage.name(),
                        response.status()
                    );
                    return response;
                }
            }
        }

        // Extract final response
        match ctx.state.response.final_response {
273
            Some(FinalResponse::Generate(response)) => axum::Json(response).into_response(),
274
            Some(FinalResponse::Chat(_)) => {
275
                error::internal_error("Internal error: wrong response type")
276
            }
277
            None => error::internal_error("No response produced"),
278
279
        }
    }
280

281
    /// Execute chat pipeline for responses endpoint
282
    ///
283
284
285
286
287
288
289
    /// TODO: The support for background tasks is not scalable. Consider replacing this with
    /// a better design in the future.
    /// Used by ALL non-streaming /v1/responses requests (both sync and background modes).
    /// Uses the same 7 pipeline stages as execute_chat(), with three differences:
    /// 1. Returns Result<ChatCompletionResponse, Response> for tool_loop composition
    /// 2. Disallows streaming (responses endpoint uses different SSE format)
    /// 3. Injects hooks for background task cancellation (only active when response_id provided)
290
291
292
293
294
295
296
297
    pub async fn execute_chat_for_responses(
        &self,
        request: Arc<ChatCompletionRequest>,
        headers: Option<http::HeaderMap>,
        model_id: Option<String>,
        components: Arc<SharedComponents>,
        response_id: Option<String>,
        background_tasks: Option<Arc<RwLock<HashMap<String, BackgroundTaskInfo>>>>,
298
    ) -> Result<ChatCompletionResponse, Response> {
299
300
301
302
303
304
305
        let mut ctx = RequestContext::for_chat(request, headers, model_id, components);

        // Execute each stage in sequence
        for (idx, stage) in self.stages.iter().enumerate() {
            match stage.execute(&mut ctx).await {
                Ok(Some(_response)) => {
                    // Streaming not supported for responses sync mode
306
                    return Err(error::bad_request(
307
308
                        "Streaming is not supported in this context".to_string(),
                    ));
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
                }
                Ok(None) => {
                    let stage_name = stage.name();

                    // After ClientAcquisitionStage, store client for background task cancellation
                    if stage_name == "ClientAcquisition" {
                        if let (Some(ref clients), Some(ref resp_id), Some(ref tasks)) =
                            (&ctx.state.clients, &response_id, &background_tasks)
                        {
                            let client_to_store = match clients {
                                ClientSelection::Single { client } => client.clone(),
                                ClientSelection::Dual { decode, .. } => decode.clone(),
                            };

                            if let Some(task_info) = tasks.write().await.get_mut(resp_id.as_str()) {
                                *task_info.client.write().await = Some(client_to_store);
                                debug!("Stored client for response_id: {}", resp_id);
                            }
                        }
                    }

                    // After DispatchMetadataStage, store grpc_request_id for background task cancellation
                    if stage_name == "DispatchMetadata" {
                        if let (Some(ref dispatch), Some(ref resp_id), Some(ref tasks)) =
                            (&ctx.state.dispatch, &response_id, &background_tasks)
                        {
                            let grpc_request_id = dispatch.request_id.clone();

                            if let Some(task_info) = tasks.write().await.get_mut(resp_id.as_str()) {
                                task_info.grpc_request_id = grpc_request_id.clone();
                                debug!("Stored grpc_request_id for response_id: {}", resp_id);
                            }
                        }
                    }

                    // Continue to next stage
                    continue;
                }
                Err(response) => {
348
                    // Error occurred - return the response as-is to preserve HTTP status codes
349
350
351
352
353
354
                    error!(
                        "Stage {} ({}) failed with status {}",
                        idx + 1,
                        stage.name(),
                        response.status()
                    );
355
                    return Err(response);
356
357
358
359
360
361
362
                }
            }
        }

        // Extract final response
        match ctx.state.response.final_response {
            Some(FinalResponse::Chat(response)) => Ok(response),
363
364
365
366
            Some(FinalResponse::Generate(_)) => {
                Err(error::internal_error("Internal error: wrong response type"))
            }
            None => Err(error::internal_error("No response produced")),
367
368
        }
    }
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386

    /// Execute Responses API pipeline
    ///
    /// TODO: Implement Responses API native execution
    /// This is a stub to allow compilation. The actual implementation should:
    /// 1. Support multi-turn MCP loop orchestration
    /// 2. Handle tool call execution and result injection
    /// 3. Emit proper SSE events for streaming mode
    /// 4. Store responses in data connector
    ///
    /// For now, this returns an error indicating the feature is not implemented.
    pub async fn execute_responses(
        &self,
        _request: Arc<crate::protocols::responses::ResponsesRequest>,
        _headers: Option<http::HeaderMap>,
        _model_id: Option<String>,
        _components: Arc<SharedComponents>,
    ) -> Response {
387
        error::internal_error("Responses API execution not yet implemented")
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
    }

    /// Execute Harmony Responses API request through all pipeline stages
    ///
    /// This method runs a single iteration of the Responses API request,
    /// returning either ToolCallsFound (continue serving) or Completed (final response).
    ///
    /// Called by harmony::responses::serve_harmony_responses() for each iteration.
    ///
    /// # Arguments
    ///
    /// * `request` - Responses API request
    /// * `ctx` - Harmony Responses context with MCP manager and components
    ///
    /// # Returns
    ///
    /// ResponsesIterationResult indicating whether to continue iteration or return
    pub async fn execute_harmony_responses(
        &self,
        request: &crate::protocols::responses::ResponsesRequest,
        harmony_ctx: &harmony::responses::HarmonyResponsesContext,
    ) -> Result<harmony::ResponsesIterationResult, Response> {
        // Create RequestContext for this Responses request
        let mut ctx = RequestContext::for_responses(
            Arc::new(request.clone()),
            None, // No headers needed for internal pipeline execution
            None, // Model ID already set in request
            harmony_ctx.components.clone(),
        );

        // Execute each pipeline stage in sequence
        for (idx, stage) in self.stages.iter().enumerate() {
            match stage.execute(&mut ctx).await {
                Ok(Some(response)) => {
                    // Stage returned early response (e.g., streaming) - not expected for Responses iteration
                    error!(
                        "Stage {} ({}) returned unexpected response during Responses iteration",
                        idx + 1,
                        stage.name()
                    );
                    return Err(response);
                }
                Ok(None) => {
                    // Stage completed successfully, continue to next stage
                    continue;
                }
                Err(response) => {
                    // Stage failed
                    error!(
                        "Stage {} ({}) failed with status {}",
                        idx + 1,
                        stage.name(),
                        response.status()
                    );
                    return Err(response);
                }
            }
        }

        // Extract ResponsesIterationResult from context
        // This should have been set by HarmonyResponseProcessingStage
        ctx.state
            .response
            .responses_iteration_result
            .take()
            .ok_or_else(|| {
454
                error::internal_error("No ResponsesIterationResult produced by pipeline")
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

    /// Execute Harmony Responses pipeline iteration with streaming support
    ///
    /// This version executes the pipeline up to the dispatch stage and returns
    /// the raw ExecutionResult (with stream) for token-level streaming processing.
    pub async fn execute_harmony_responses_streaming(
        &self,
        request: &crate::protocols::responses::ResponsesRequest,
        harmony_ctx: &harmony::responses::HarmonyResponsesContext,
    ) -> Result<ExecutionResult, Response> {
        // Create RequestContext for this Responses request
        let mut ctx = RequestContext::for_responses(
            Arc::new(request.clone()),
            None,
            None,
            harmony_ctx.components.clone(),
        );

        // Execute pipeline stages up to dispatch (which creates the stream)
        for (idx, stage) in self.stages.iter().enumerate() {
            match stage.execute(&mut ctx).await {
                Ok(Some(response)) => {
                    error!(
                        "Stage {} ({}) returned unexpected response during streaming Responses",
                        idx + 1,
                        stage.name()
                    );
                    return Err(response);
                }
                Ok(None) => continue,
                Err(response) => {
                    error!(
                        "Stage {} ({}) failed with status {}",
                        idx + 1,
                        stage.name(),
                        response.status()
                    );
                    return Err(response);
                }
            }
        }

        // Extract execution_result (the raw stream from workers)
        ctx.state
            .response
            .execution_result
            .take()
504
            .ok_or_else(|| error::internal_error("No ExecutionResult produced by pipeline"))
505
    }
506
}