pd_router.rs 72.6 KB
Newer Older
1
2
3
// PD (Prefill-Decode) Router Implementation
// This module handles routing for disaggregated prefill-decode systems

4
5
use super::pd_types::{api_path, Bootstrap, ChatReqInput, GenerateReqInput, PDRouterError};
use super::request_adapter::ToPdRequest;
6
use crate::core::{HealthChecker, Worker, WorkerFactory, WorkerLoadGuard};
7
use crate::metrics::RouterMetrics;
8
9
use crate::openai_api_types::{ChatCompletionRequest, CompletionRequest, GenerateRequest};
use crate::policies::LoadBalancingPolicy;
10
use crate::tree::Tree;
11
12
13
14
15
16
17
18
use axum::{
    body::Body,
    extract::Request,
    http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use futures_util::StreamExt;
19
20
21
22
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
23
use tokio_stream::wrappers::UnboundedReceiverStream;
24
25
26
27
use tracing::{debug, error, info, warn};

#[derive(Debug)]
pub struct PDRouter {
28
29
    pub prefill_workers: Arc<RwLock<Vec<Box<dyn Worker>>>>,
    pub decode_workers: Arc<RwLock<Vec<Box<dyn Worker>>>>,
30
31
    pub prefill_policy: Arc<dyn LoadBalancingPolicy>,
    pub decode_policy: Arc<dyn LoadBalancingPolicy>,
32
    pub prefill_tree: Option<Arc<Mutex<Tree>>>,
33
    pub decode_tree: Option<Arc<Mutex<Tree>>>,
34
35
36
37
38
    pub timeout_secs: u64,
    pub interval_secs: u64,
    pub worker_loads: Arc<tokio::sync::watch::Receiver<HashMap<String, isize>>>,
    pub load_monitor_handle: Option<Arc<tokio::task::JoinHandle<()>>>,
    pub http_client: reqwest::Client,
39
40
    _prefill_health_checker: Option<HealthChecker>,
    _decode_health_checker: Option<HealthChecker>,
41
42
43
}

impl PDRouter {
44
45
46
47
48
49
50
    // Dynamic worker management methods for service discovery
    pub async fn add_prefill_server(
        &self,
        url: String,
        bootstrap_port: Option<u16>,
    ) -> Result<String, PDRouterError> {
        // Wait for the new server to be healthy
51
        crate::routers::router::Router::wait_for_healthy_workers(
52
53
54
55
56
57
            &[url.clone()],
            self.timeout_secs,
            self.interval_secs,
        )
        .map_err(|_| PDRouterError::HealthCheckFailed { url: url.clone() })?;

58
59
60
        // Create Worker for the new prefill server
        let worker = WorkerFactory::create_prefill(url.clone(), bootstrap_port);

61
62
63
64
65
66
67
68
69
        // Add to prefill workers list
        let mut workers = self
            .prefill_workers
            .write()
            .map_err(|_| PDRouterError::LockError {
                operation: "prefill_workers write".to_string(),
            })?;

        // Check if already exists
70
        if workers.iter().any(|w| w.url() == &url) {
71
72
73
            return Err(PDRouterError::WorkerAlreadyExists { url: url.clone() });
        }

74
        workers.push(worker);
75

76
        // Add to cache tree if using cache-aware policy for prefill
77
78
79
80
81
82
83
84
85
86
        if let Some(ref tree) = self.prefill_tree {
            tree.lock().unwrap().insert("", &url);
        }

        info!("Added prefill server: {}", url);
        Ok(format!("Successfully added prefill server: {}", url))
    }

    pub async fn add_decode_server(&self, url: String) -> Result<String, PDRouterError> {
        // Wait for the new server to be healthy
87
        crate::routers::router::Router::wait_for_healthy_workers(
88
89
90
91
92
93
            &[url.clone()],
            self.timeout_secs,
            self.interval_secs,
        )
        .map_err(|_| PDRouterError::HealthCheckFailed { url: url.clone() })?;

94
95
96
        // Create Worker for the new decode server
        let worker = WorkerFactory::create_decode(url.clone());

97
98
99
100
101
102
103
104
105
        // Add to decode workers list
        let mut workers = self
            .decode_workers
            .write()
            .map_err(|_| PDRouterError::LockError {
                operation: "decode_workers write".to_string(),
            })?;

        // Check if already exists
106
        if workers.iter().any(|w| w.url() == &url) {
107
108
109
            return Err(PDRouterError::WorkerAlreadyExists { url: url.clone() });
        }

110
        workers.push(worker);
111

112
113
114
115
116
        // Add to cache tree if using cache-aware policy for decode
        if let Some(ref tree) = self.decode_tree {
            tree.lock().unwrap().insert("", &url);
        }

117
118
119
120
121
122
123
124
125
126
127
128
129
130
        info!("Added decode server: {}", url);
        Ok(format!("Successfully added decode server: {}", url))
    }

    pub async fn remove_prefill_server(&self, url: &str) -> Result<String, PDRouterError> {
        let mut workers = self
            .prefill_workers
            .write()
            .map_err(|_| PDRouterError::LockError {
                operation: "prefill_workers write".to_string(),
            })?;

        // Find and remove the server
        let initial_len = workers.len();
131
        workers.retain(|w| w.url() != url);
132
133
134
135
136
137
138
139
140

        if workers.len() == initial_len {
            return Err(PDRouterError::WorkerNotFound {
                url: url.to_string(),
            });
        }

        // Remove from cache tree if using cache-aware policy
        if let Some(ref tree) = self.prefill_tree {
141
            tree.lock().unwrap().remove_tenant(url);
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        }

        info!("Removed prefill server: {}", url);
        Ok(format!("Successfully removed prefill server: {}", url))
    }

    pub async fn remove_decode_server(&self, url: &str) -> Result<String, PDRouterError> {
        let mut workers = self
            .decode_workers
            .write()
            .map_err(|_| PDRouterError::LockError {
                operation: "decode_workers write".to_string(),
            })?;

        // Find and remove the server
        let initial_len = workers.len();
158
        workers.retain(|w| w.url() != url);
159
160
161
162
163
164
165

        if workers.len() == initial_len {
            return Err(PDRouterError::WorkerNotFound {
                url: url.to_string(),
            });
        }

166
167
168
169
170
        // Remove from the cache tree if using cache-aware policy for decode
        if let Some(ref tree) = self.decode_tree {
            tree.lock().unwrap().remove_tenant(url);
        }

171
172
173
        info!("Removed decode server: {}", url);
        Ok(format!("Successfully removed decode server: {}", url))
    }
174
175
176
177

    pub fn new(
        prefill_urls: Vec<(String, Option<u16>)>,
        decode_urls: Vec<String>,
178
179
        prefill_policy: Arc<dyn LoadBalancingPolicy>,
        decode_policy: Arc<dyn LoadBalancingPolicy>,
180
181
182
        timeout_secs: u64,
        interval_secs: u64,
    ) -> Result<Self, String> {
183
184
        // Convert URLs to Worker trait objects
        let prefill_workers: Vec<Box<dyn Worker>> = prefill_urls
185
            .into_iter()
186
            .map(|(url, port)| WorkerFactory::create_prefill(url, port))
187
188
            .collect();

189
        let decode_workers: Vec<Box<dyn Worker>> = decode_urls
190
            .into_iter()
191
            .map(WorkerFactory::create_decode)
192
193
            .collect();

194
        // Wait for PD workers to be healthy (skip if empty - for service discovery mode)
195
196
197
        let all_urls: Vec<String> = prefill_workers
            .iter()
            .chain(decode_workers.iter())
198
            .map(|worker| worker.url().to_string())
199
            .collect();
200
201
202
203
204
205
206
        if !all_urls.is_empty() {
            crate::routers::router::Router::wait_for_healthy_workers(
                &all_urls,
                timeout_secs,
                interval_secs,
            )?;
        }
207

208
209
        // Initialize cache-aware components if needed for prefill policy
        let prefill_tree = if prefill_policy.name() == "cache_aware" {
210
            // Initialize the policy's internal tree with prefill workers
211
            if let Some(cache_policy) = prefill_policy
212
213
214
215
216
217
218
219
220
221
                .as_any()
                .downcast_ref::<crate::policies::CacheAwarePolicy>()
            {
                cache_policy.init_workers(&prefill_workers);
            }

            let tree = Arc::new(Mutex::new(Tree::new()));
            // Initialize tree with prefill workers
            for worker in &prefill_workers {
                tree.lock().unwrap().insert("", worker.url());
222
            }
223
224
225
            Some(tree)
        } else {
            None
226
227
        };

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        // Initialize cache-aware components if needed for decode policy
        let decode_tree = if decode_policy.name() == "cache_aware" {
            // Initialize the policy's internal tree with decode workers
            if let Some(cache_policy) = decode_policy
                .as_any()
                .downcast_ref::<crate::policies::CacheAwarePolicy>()
            {
                cache_policy.init_workers(&decode_workers);
            }

            let tree = Arc::new(Mutex::new(Tree::new()));
            // Initialize tree with decode workers
            for worker in &decode_workers {
                tree.lock().unwrap().insert("", worker.url());
            }
            Some(tree)
        } else {
            None
        };

248
249
250
251
252
253
254
255
256
257
        // Set up background load monitoring for power-of-two selection
        let (tx, rx) = tokio::sync::watch::channel(HashMap::new());
        let worker_loads = Arc::new(rx);

        // Create a shared HTTP client for all operations
        let http_client = reqwest::Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .build()
            .map_err(|e| format!("Failed to create HTTP client: {}", e))?;

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        let load_monitor_handle =
            if prefill_policy.name() == "power_of_two" || decode_policy.name() == "power_of_two" {
                let monitor_urls = all_urls.clone();
                let monitor_interval = interval_secs;
                let monitor_client = http_client.clone();
                let prefill_policy_clone = Arc::clone(&prefill_policy);
                let decode_policy_clone = Arc::clone(&decode_policy);

                Some(Arc::new(tokio::spawn(async move {
                    Self::monitor_worker_loads_with_client(
                        monitor_urls,
                        tx,
                        monitor_interval,
                        monitor_client,
                        prefill_policy_clone,
                        decode_policy_clone,
                    )
                    .await;
                })))
            } else {
                None
            };
280

281
282
283
284
285
286
287
288
289
        let prefill_workers = Arc::new(RwLock::new(prefill_workers));
        let decode_workers = Arc::new(RwLock::new(decode_workers));

        // Start health checkers for both worker pools
        let prefill_health_checker =
            crate::core::start_health_checker(Arc::clone(&prefill_workers), interval_secs);
        let decode_health_checker =
            crate::core::start_health_checker(Arc::clone(&decode_workers), interval_secs);

290
        Ok(PDRouter {
291
292
            prefill_workers,
            decode_workers,
293
294
            prefill_policy,
            decode_policy,
295
            prefill_tree,
296
            decode_tree,
297
298
299
300
301
            timeout_secs,
            interval_secs,
            worker_loads,
            load_monitor_handle,
            http_client,
302
303
            _prefill_health_checker: Some(prefill_health_checker),
            _decode_health_checker: Some(decode_health_checker),
304
305
306
307
308
309
        })
    }

    // Route a typed generate request
    pub async fn route_generate(
        &self,
310
311
        client: &Client,
        headers: Option<&HeaderMap>,
312
313
        mut typed_req: GenerateReqInput,
        route: &str,
314
    ) -> Response {
315
316
317
        let start = Instant::now();

        // Get stream flag and return_logprob flag before moving the request
318
        let is_stream = typed_req.stream;
319
320
321
322
323
324
        let return_logprob = typed_req
            .other
            .get("return_logprob")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

325
326
327
328
329
330
        // Extract text for cache-aware routing from the typed request
        let request_text = typed_req.text.as_ref().and_then(|t| match t {
            super::pd_types::InputText::Single(s) => Some(s.as_str()),
            super::pd_types::InputText::Batch(v) => v.first().map(|s| s.as_str()),
        });

331
        // Select servers
332
        let (prefill, decode) = match self.select_pd_pair(client, request_text).await {
333
334
            Ok(pair) => pair,
            Err(e) => {
335
                error!("Failed to select PD pair error={}", e);
336
                RouterMetrics::record_pd_error("server_selection");
337
338
339
340
341
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("No available servers: {}", e),
                )
                    .into_response();
342
343
344
345
346
            }
        };

        // Log routing decision
        info!(
347
            "PD routing decision route={} prefill_url={} decode_url={}",
348
349
350
            route,
            prefill.url(),
            decode.url()
351
352
353
        );

        // Add bootstrap info using the trait method
354
        if let Err(e) = typed_req.add_bootstrap_info(prefill.as_ref()) {
355
            error!("Failed to add bootstrap info error={}", e);
356
            RouterMetrics::record_pd_error("bootstrap_injection");
357
358
359
360
361
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Bootstrap injection failed: {}", e),
            )
                .into_response();
362
363
364
365
366
367
        }

        // Convert to JSON after bootstrap injection
        let json_with_bootstrap = match serde_json::to_value(&typed_req) {
            Ok(json) => json,
            Err(e) => {
368
369
370
371
372
373
                error!("Failed to serialize request error={}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Failed to serialize request",
                )
                    .into_response();
374
375
376
377
378
379
            }
        };

        // Execute dual dispatch
        self.execute_dual_dispatch(
            client,
380
            headers,
381
382
            json_with_bootstrap,
            route,
383
384
            prefill.as_ref(),
            decode.as_ref(),
385
386
387
388
389
390
391
392
393
394
            is_stream,
            return_logprob,
            start,
        )
        .await
    }

    // Route a typed chat request
    pub async fn route_chat(
        &self,
395
396
        client: &Client,
        headers: Option<&HeaderMap>,
397
398
        mut typed_req: ChatReqInput,
        route: &str,
399
    ) -> Response {
400
401
402
        let start = Instant::now();

        // Get stream flag and return_logprob flag before moving the request
403
        let is_stream = typed_req.stream;
404
405
406
407
408
409
        let return_logprob = typed_req
            .other
            .get("return_logprob")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

410
411
412
413
414
415
416
417
418
        // Extract text for cache-aware routing from chat messages
        let request_text = typed_req
            .other
            .get("messages")
            .and_then(|messages| messages.as_array())
            .and_then(|arr| arr.first())
            .and_then(|msg| msg.get("content"))
            .and_then(|content| content.as_str());

419
        // Select servers
420
        let (prefill, decode) = match self.select_pd_pair(client, request_text).await {
421
422
            Ok(pair) => pair,
            Err(e) => {
423
                error!("Failed to select PD pair error={}", e);
424
                RouterMetrics::record_pd_error("server_selection");
425
426
427
428
429
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("No available servers: {}", e),
                )
                    .into_response();
430
431
432
433
434
            }
        };

        // Log routing decision
        info!(
435
            "PD routing decision route={} prefill_url={} decode_url={}",
436
437
438
            route,
            prefill.url(),
            decode.url()
439
440
441
        );

        // Add bootstrap info using the trait method
442
        if let Err(e) = typed_req.add_bootstrap_info(prefill.as_ref()) {
443
            error!("Failed to add bootstrap info error={}", e);
444
            RouterMetrics::record_pd_error("bootstrap_injection");
445
446
447
448
449
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Bootstrap injection failed: {}", e),
            )
                .into_response();
450
451
452
453
454
455
        }

        // Convert to JSON after bootstrap injection
        let json_with_bootstrap = match serde_json::to_value(&typed_req) {
            Ok(json) => json,
            Err(e) => {
456
457
458
459
460
461
                error!("Failed to serialize request error={}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Failed to serialize request",
                )
                    .into_response();
462
463
464
465
466
467
            }
        };

        // Execute dual dispatch
        self.execute_dual_dispatch(
            client,
468
            headers,
469
470
            json_with_bootstrap,
            route,
471
472
            prefill.as_ref(),
            decode.as_ref(),
473
474
475
476
477
478
479
            is_stream,
            return_logprob,
            start,
        )
        .await
    }

480
481
482
    // Route a completion request while preserving OpenAI format
    pub async fn route_completion(
        &self,
483
484
        client: &Client,
        headers: Option<&HeaderMap>,
485
486
        mut typed_req: CompletionRequest,
        route: &str,
487
    ) -> Response {
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
        let start = Instant::now();

        // Get stream flag and return_logprob flag before moving the request
        let is_stream = typed_req.stream;
        let return_logprob = typed_req.logprobs.is_some();

        // Extract text for cache-aware routing from the typed request
        let request_text = match &typed_req.prompt {
            crate::openai_api_types::StringOrArray::String(s) => Some(s.as_str()),
            crate::openai_api_types::StringOrArray::Array(arr) => arr.first().map(|s| s.as_str()),
        };

        // Select servers
        let (prefill, decode) = match self.select_pd_pair(client, request_text).await {
            Ok(pair) => pair,
            Err(e) => {
504
                error!("Failed to select PD pair error={}", e);
505
                RouterMetrics::record_pd_error("server_selection");
506
507
508
509
510
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("No available servers: {}", e),
                )
                    .into_response();
511
512
513
514
515
            }
        };

        // Log routing decision
        info!(
516
            "PD routing decision route={} prefill_url={} decode_url={}",
517
518
519
            route,
            prefill.url(),
            decode.url()
520
521
522
523
        );

        // Add bootstrap info using the trait method
        if let Err(e) = typed_req.add_bootstrap_info(prefill.as_ref()) {
524
            error!("Failed to add bootstrap info error={}", e);
525
            RouterMetrics::record_pd_error("bootstrap_injection");
526
527
528
529
530
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Bootstrap injection failed: {}", e),
            )
                .into_response();
531
532
533
534
535
536
        }

        // Convert to JSON after bootstrap injection
        let json_with_bootstrap = match serde_json::to_value(&typed_req) {
            Ok(json) => json,
            Err(e) => {
537
538
539
540
541
542
                error!("Failed to serialize request error={}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Failed to serialize request",
                )
                    .into_response();
543
544
545
546
547
548
            }
        };

        // Execute dual dispatch
        self.execute_dual_dispatch(
            client,
549
            headers,
550
551
552
553
554
555
556
557
558
559
560
            json_with_bootstrap,
            route,
            prefill.as_ref(),
            decode.as_ref(),
            is_stream,
            return_logprob,
            start,
        )
        .await
    }

561
562
563
564
    // Execute the dual dispatch to prefill and decode servers
    #[allow(clippy::too_many_arguments)]
    async fn execute_dual_dispatch(
        &self,
565
566
567
        client: &Client,
        headers: Option<&HeaderMap>,
        json_request: Value,
568
        route: &str,
569
570
        prefill: &dyn Worker,
        decode: &dyn Worker,
571
572
573
        is_stream: bool,
        return_logprob: bool,
        start_time: Instant,
574
    ) -> Response {
575
        // Update load tracking for both workers
576
        let _guard = WorkerLoadGuard::new_multi(vec![prefill, decode]);
577
578

        // Build requests using .json() method
579
580
581
        let mut prefill_request = client
            .post(api_path(prefill.url(), route))
            .json(&json_request);
582

583
584
585
        let mut decode_request = client
            .post(api_path(decode.url(), route))
            .json(&json_request);
586

587
588
589
590
591
592
593
594
595
596
597
        // Copy headers from original request (excluding content-type and content-length which are set by .json())
        if let Some(headers) = headers {
            for (name, value) in headers.iter() {
                let name_str = name.as_str();
                if name_str != "content-type" && name_str != "content-length" {
                    // Skip headers with non-ASCII values
                    if value.to_str().is_ok() {
                        prefill_request = prefill_request.header(name, value);
                        decode_request = decode_request.header(name, value);
                    }
                }
598
599
600
601
602
603
604
605
606
            }
        }

        // Send both requests concurrently
        let (prefill_result, decode_result) =
            tokio::join!(prefill_request.send(), decode_request.send());

        // Update metrics
        let duration = start_time.elapsed();
607
608
609
610
        RouterMetrics::record_pd_request_duration(route, duration);
        RouterMetrics::record_pd_request(route);
        RouterMetrics::record_pd_prefill_request(prefill.url());
        RouterMetrics::record_pd_decode_request(decode.url());
611
612
613
614

        // Process decode response
        match decode_result {
            Ok(res) => {
615
616
                let status = StatusCode::from_u16(res.status().as_u16())
                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
617
618

                if !status.is_success() {
619
                    RouterMetrics::record_pd_decode_error(decode.url());
620
                    error!(
621
                        "Decode server returned error status decode_url={} status={}",
622
623
                        decode.url(),
                        status
624
625
626
627
628
                    );

                    // Return the error response from decode server
                    match res.bytes().await {
                        Ok(error_body) => {
629
                            return (status, error_body).into_response();
630
631
                        }
                        Err(e) => {
632
                            return (status, format!("Decode server error: {}", e)).into_response();
633
634
635
636
637
638
639
                        }
                    }
                }

                // Log prefill errors for debugging
                if let Err(e) = &prefill_result {
                    error!(
640
                        "Prefill server failed (non-critical) prefill_url={} error={}",
641
642
                        prefill.url(),
                        e
643
                    );
644
                    RouterMetrics::record_pd_prefill_error(prefill.url());
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
                }

                if is_stream {
                    // Streaming response
                    if return_logprob {
                        // Get prefill logprobs for merging
                        let prefill_logprobs =
                            match prefill_result {
                                Ok(prefill_res) => match prefill_res.bytes().await {
                                    Ok(body) => serde_json::from_slice::<Value>(&body)
                                        .ok()
                                        .and_then(|json| {
                                            json.pointer("/meta_info/input_token_logprobs").cloned()
                                        }),
                                    Err(_) => None,
                                },
                                Err(_) => None,
                            };

                        // Stream with logprob merging
665
666
667
668
669
670
                        let stream = res.bytes_stream();
                        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

                        tokio::spawn(async move {
                            let mut stream = stream;
                            while let Some(chunk_result) = stream.next().await {
671
672
673
674
675
676
677
                                match chunk_result {
                                    Ok(chunk) => {
                                        // Try to merge logprobs
                                        if let Ok(merged) = Self::merge_streaming_logprobs(
                                            prefill_logprobs.clone(),
                                            &chunk,
                                        ) {
678
679
680
                                            if tx.send(Ok(merged)).is_err() {
                                                break;
                                            }
681
                                        } else {
682
683
684
                                            if tx.send(Ok(chunk)).is_err() {
                                                break;
                                            }
685
686
                                        }
                                    }
687
688
689
690
                                    Err(e) => {
                                        let _ = tx.send(Err(format!("Stream error: {}", e)));
                                        break;
                                    }
691
                                }
692
693
694
695
696
697
698
699
700
701
702
703
                            }
                        });

                        let stream = UnboundedReceiverStream::new(rx);
                        let body = Body::from_stream(stream);

                        let mut response = Response::new(body);
                        *response.status_mut() = status;
                        response
                            .headers_mut()
                            .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
                        response
704
705
                    } else {
                        // No logprob merging needed
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
                        let stream = res.bytes_stream();
                        let decode_url = decode.url().to_string();
                        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

                        tokio::spawn(async move {
                            let mut stream = stream;
                            while let Some(chunk) = stream.next().await {
                                match chunk {
                                    Ok(bytes) => {
                                        if tx.send(Ok(bytes)).is_err() {
                                            break;
                                        }
                                    }
                                    Err(e) => {
                                        error!(
                                            "Stream error from decode server {}: {}",
                                            decode_url, e
                                        );
                                        RouterMetrics::record_pd_stream_error(&decode_url);
                                        let _ = tx.send(Err(format!("Stream error: {}", e)));
                                        break;
                                    }
                                }
                            }
                        });

                        let stream = UnboundedReceiverStream::new(rx);
                        let body = Body::from_stream(stream);

                        let mut response = Response::new(body);
                        *response.status_mut() = status;
                        response
                            .headers_mut()
                            .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
                        response
741
742
743
744
745
746
747
748
749
                    }
                } else {
                    // Non-streaming response
                    match res.bytes().await {
                        Ok(decode_body) => {
                            if return_logprob {
                                self.merge_logprobs(prefill_result, decode_body, status)
                                    .await
                            } else {
750
                                (status, decode_body).into_response()
751
752
753
754
                            }
                        }
                        Err(e) => {
                            error!("Failed to read decode response: {}", e);
755
756
                            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read response")
                                .into_response()
757
758
759
760
761
                        }
                    }
                }
            }
            Err(e) => {
762
763
764
765
766
                error!(
                    decode_url = %decode.url(),
                    error = %e,
                    "Decode request failed"
                );
767
                RouterMetrics::record_pd_decode_error(decode.url());
768
769
770
771
772
                (
                    StatusCode::BAD_GATEWAY,
                    format!("Decode server error: {}", e),
                )
                    .into_response()
773
774
775
776
777
778
779
780
781
            }
        }
    }

    // Merge logprobs from prefill and decode responses
    async fn merge_logprobs(
        &self,
        prefill_result: Result<reqwest::Response, reqwest::Error>,
        decode_body: bytes::Bytes,
782
783
        status: StatusCode,
    ) -> Response {
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
        match prefill_result {
            Ok(prefill_res) => {
                match prefill_res.bytes().await {
                    Ok(prefill_body) => {
                        match (
                            serde_json::from_slice::<Value>(&prefill_body),
                            serde_json::from_slice::<Value>(&decode_body),
                        ) {
                            (Ok(prefill_json), Ok(mut decode_json)) => {
                                // Merge input_token_logprobs
                                if let (Some(prefill_meta), Some(decode_meta)) = (
                                    prefill_json.get("meta_info"),
                                    decode_json.get_mut("meta_info"),
                                ) {
                                    if let (Some(prefill_logprobs), Some(decode_logprobs)) = (
                                        prefill_meta.get("input_token_logprobs"),
                                        decode_meta.get_mut("input_token_logprobs"),
                                    ) {
                                        if let (Some(p_arr), Some(d_arr)) = (
                                            prefill_logprobs.as_array(),
                                            decode_logprobs.as_array(),
                                        ) {
                                            let mut merged = p_arr.clone();
                                            merged.extend(d_arr.clone());
                                            decode_meta["input_token_logprobs"] =
                                                Value::Array(merged);
                                        }
                                    }
                                }
813
814
815
                                let mut response = Json(decode_json).into_response();
                                *response.status_mut() = status;
                                response
816
817
818
                            }
                            _ => {
                                warn!("Failed to parse responses for logprob merging");
819
                                (status, decode_body).into_response()
820
821
822
823
824
                            }
                        }
                    }
                    Err(e) => {
                        warn!("Failed to read prefill response: {}", e);
825
                        (status, decode_body).into_response()
826
827
828
                    }
                }
            }
829
            Err(_) => (status, decode_body).into_response(),
830
831
832
833
834
835
        }
    }

    // Select a pair of prefill and decode servers
    async fn select_pd_pair(
        &self,
836
        _client: &Client,
837
        request_text: Option<&str>,
838
    ) -> Result<(Box<dyn Worker>, Box<dyn Worker>), String> {
839
840
        // Get read locks for both worker lists
        let prefill_workers = self
841
842
            .prefill_workers
            .read()
843
844
            .map_err(|e| format!("Failed to acquire prefill workers lock: {}", e))?;
        let decode_workers = self
845
846
            .decode_workers
            .read()
847
848
849
850
851
852
853
            .map_err(|e| format!("Failed to acquire decode workers lock: {}", e))?;

        // Check we have workers
        if prefill_workers.is_empty() {
            return Err("No prefill workers available. Please check if prefill servers are configured and healthy.".to_string());
        }
        if decode_workers.is_empty() {
854
855
856
            return Err("No decode workers available. Please check if decode servers are configured and healthy.".to_string());
        }

857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        // Select prefill worker using prefill policy
        let prefill_idx = self
            .prefill_policy
            .select_worker(&prefill_workers, request_text)
            .ok_or("Failed to select prefill worker")?;

        // Select decode worker using decode policy
        let decode_idx = self
            .decode_policy
            .select_worker(&decode_workers, request_text)
            .ok_or("Failed to select decode worker")?;

        let prefill = prefill_workers[prefill_idx].clone_worker();
        let decode = decode_workers[decode_idx].clone_worker();
        Ok((prefill, decode))
872
873
874
875
876
877
878
    }

    // Background task to monitor worker loads with shared client
    async fn monitor_worker_loads_with_client(
        worker_urls: Vec<String>,
        tx: tokio::sync::watch::Sender<HashMap<String, isize>>,
        interval_secs: u64,
879
        client: Client,
880
881
        prefill_policy: Arc<dyn LoadBalancingPolicy>,
        decode_policy: Arc<dyn LoadBalancingPolicy>,
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
    ) {
        loop {
            let mut loads = HashMap::new();

            let futures: Vec<_> = worker_urls
                .iter()
                .map(|url| {
                    let client = client.clone();
                    let url = url.clone();
                    async move {
                        let load = get_worker_load(&client, &url).await.unwrap_or(0);
                        (url, load)
                    }
                })
                .collect();

            let results = futures_util::future::join_all(futures).await;

            for (url, load) in results {
                loads.insert(url, load);
            }

            debug!("Worker loads updated: {:?}", loads);

906
907
908
            // Update both policies with current loads
            prefill_policy.update_loads(&loads);
            decode_policy.update_loads(&loads);
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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
            // Check if receiver is still active
            if tx.send(loads).is_err() {
                info!("Load monitor receiver dropped, shutting down monitor task");
                break;
            }

            tokio::time::sleep(Duration::from_secs(interval_secs)).await;
        }
    }

    // Simple helper to merge logprobs in streaming responses
    fn merge_streaming_logprobs(
        prefill_logprobs: Option<Value>,
        decode_chunk: &[u8],
    ) -> Result<bytes::Bytes, ()> {
        // Skip non-data chunks
        let chunk_str = std::str::from_utf8(decode_chunk).map_err(|_| ())?;
        if !chunk_str.starts_with("data: ") || chunk_str.contains("[DONE]") {
            return Err(());
        }

        // Parse JSON from chunk
        let json_str = chunk_str.trim_start_matches("data: ").trim();
        let mut decode_json: Value = serde_json::from_str(json_str).map_err(|_| ())?;

        // Merge prefill logprobs if available
        if let Some(ref p_logprobs) = prefill_logprobs {
            if let Some(meta) = decode_json.get_mut("meta_info") {
                if let Some(d_logprobs) = meta.get_mut("input_token_logprobs") {
                    if let (Some(p_arr), Some(d_arr)) =
                        (p_logprobs.as_array(), d_logprobs.as_array())
                    {
                        let mut merged = p_arr.clone();
                        merged.extend(d_arr.clone());
                        *d_logprobs = Value::Array(merged);
                    }
                }
            }
        }

        // Re-serialize
        let merged_str = format!(
            "data: {}\n\n",
            serde_json::to_string(&decode_json).unwrap_or_default()
        );
        Ok(bytes::Bytes::from(merged_str))
    }
}

// Helper functions

async fn get_worker_load(client: &reqwest::Client, worker_url: &str) -> Option<isize> {
    match client.get(format!("{}/get_load", worker_url)).send().await {
        Ok(res) if res.status().is_success() => match res.bytes().await {
            Ok(bytes) => match serde_json::from_slice::<Value>(&bytes) {
                Ok(data) => data
                    .get("load")
                    .and_then(|v| v.as_i64())
                    .map(|v| v as isize),
                Err(e) => {
                    debug!("Failed to parse load response from {}: {}", worker_url, e);
                    None
                }
            },
            Err(e) => {
                debug!("Failed to read load response from {}: {}", worker_url, e);
                None
            }
        },
        Ok(res) => {
            debug!(
                "Worker {} returned non-success status: {}",
                worker_url,
                res.status()
            );
            None
        }
        Err(e) => {
            debug!("Failed to get load from {}: {}", worker_url, e);
            None
        }
    }
}

// PD-specific endpoints
impl PDRouter {
996
    pub async fn health_generate(&self, client: &reqwest::Client) -> Response {
997
998
        // Test model generation capability by selecting a random pair and testing them
        // Note: This endpoint actually causes the model to generate tokens, so we only test one pair
999

1000
1001
1002
1003
        // Select a random worker pair using the policy
        let (prefill, decode) = match self.select_pd_pair(client, None).await {
            Ok(pair) => pair,
            Err(e) => {
1004
1005
1006
1007
1008
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("No healthy worker pair available: {}", e),
                )
                    .into_response();
1009
1010
            }
        };
1011

1012
1013
1014
        // Test prefill server's health_generate
        let prefill_url = format!("{}/health_generate", prefill.url());
        let prefill_result = client.get(&prefill_url).send().await;
1015

1016
1017
1018
        // Test decode server's health_generate
        let decode_url = format!("{}/health_generate", decode.url());
        let decode_result = client.get(&decode_url).send().await;
1019

1020
1021
        // Check results
        let mut errors = Vec::new();
1022

1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
        match prefill_result {
            Ok(res) if res.status().is_success() => {
                debug!(
                    "Health generate passed for prefill server: {}",
                    prefill.url()
                );
            }
            Ok(res) => {
                errors.push(format!(
                    "Prefill {} returned status {}",
                    prefill.url(),
                    res.status()
                ));
            }
            Err(e) => {
                errors.push(format!("Prefill {} error: {}", prefill.url(), e));
            }
        }
1041

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
        match decode_result {
            Ok(res) if res.status().is_success() => {
                debug!("Health generate passed for decode server: {}", decode.url());
            }
            Ok(res) => {
                errors.push(format!(
                    "Decode {} returned status {}",
                    decode.url(),
                    res.status()
                ));
            }
            Err(e) => {
                errors.push(format!("Decode {} error: {}", decode.url(), e));
1055
1056
1057
            }
        }

1058
        if errors.is_empty() {
1059
1060
1061
1062
1063
1064
1065
1066
1067
            (
                StatusCode::OK,
                format!(
                    "Health generate passed on selected pair: prefill={}, decode={}",
                    prefill.url(),
                    decode.url()
                ),
            )
                .into_response()
1068
        } else {
1069
1070
1071
1072
1073
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Health generate failed: {:?}", errors),
            )
                .into_response()
1074
1075
1076
        }
    }

1077
    pub async fn get_server_info(&self, client: &reqwest::Client) -> Response {
1078
1079
        // Get info from the first decode server to match sglang's server info format
        let first_decode_url = if let Ok(workers) = self.decode_workers.read() {
1080
            workers.first().map(|w| w.url().to_string())
1081
        } else {
1082
1083
1084
1085
1086
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access decode workers",
            )
                .into_response();
1087
        };
1088

1089
        if let Some(worker_url) = first_decode_url {
1090
1091
1092
1093
1094
1095
1096
1097
            match client
                .get(format!("{}/get_server_info", worker_url))
                .send()
                .await
            {
                Ok(res) if res.status().is_success() => {
                    match res.json::<Value>().await {
                        Ok(info) => {
1098
1099
                            // The decode server should already return the proper format
                            // with tokenizer_path and other fields that bench_one_batch_server.py expects
1100
                            Json(info).into_response()
1101
1102
1103
                        }
                        Err(e) => {
                            error!("Failed to parse server info: {}", e);
1104
1105
1106
1107
1108
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                format!("Failed to parse server info: {}", e),
                            )
                                .into_response()
1109
1110
1111
                        }
                    }
                }
1112
                Ok(res) => {
1113
1114
1115
1116
1117
1118
1119
                    let status = StatusCode::from_u16(res.status().as_u16())
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                    (
                        status,
                        format!("Decode server returned status: {}", res.status()),
                    )
                        .into_response()
1120
1121
1122
                }
                Err(e) => {
                    error!("Failed to get server info: {}", e);
1123
1124
1125
1126
1127
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to get server info: {}", e),
                    )
                        .into_response()
1128
                }
1129
1130
            }
        } else {
1131
1132
1133
1134
1135
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No decode servers available",
            )
                .into_response()
1136
1137
1138
        }
    }

1139
1140
1141
1142
    pub async fn get_models(&self, client: &reqwest::Client, req: Request<Body>) -> Response {
        // Extract headers first to avoid Send issues
        let headers = crate::routers::router::copy_request_headers(&req);

1143
1144
        // Get first prefill worker URL to avoid holding lock across await
        let first_worker_url = if let Ok(workers) = self.prefill_workers.read() {
1145
            workers.first().map(|w| w.url().to_string())
1146
        } else {
1147
1148
1149
1150
1151
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access prefill workers",
            )
                .into_response();
1152
1153
1154
1155
1156
        };

        if let Some(worker_url) = first_worker_url {
            // Send request directly without going through Router
            let mut request_builder = client.get(format!("{}/v1/models", worker_url));
1157
            for (name, value) in headers {
1158
1159
1160
1161
1162
1163
1164
                if name.to_lowercase() != "content-type" && name.to_lowercase() != "content-length"
                {
                    request_builder = request_builder.header(name, value);
                }
            }
            match request_builder.send().await {
                Ok(res) => {
1165
1166
                    let status = StatusCode::from_u16(res.status().as_u16())
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1167
                    match res.bytes().await {
1168
1169
1170
1171
1172
1173
                        Ok(body) => (status, body).into_response(),
                        Err(e) => (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to read response body: {}", e),
                        )
                            .into_response(),
1174
1175
                    }
                }
1176
1177
1178
1179
1180
                Err(e) => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to send request: {}", e),
                )
                    .into_response(),
1181
1182
            }
        } else {
1183
1184
1185
1186
1187
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No prefill servers available",
            )
                .into_response()
1188
1189
1190
        }
    }

1191
    pub async fn get_loads(&self, client: &reqwest::Client) -> Response {
1192
1193
1194
1195
1196
        let p_urls: Vec<_> = self
            .prefill_workers
            .read()
            .unwrap()
            .iter()
1197
            .map(|w| w.url().to_string())
1198
1199
1200
1201
1202
1203
            .collect();
        let d_urls: Vec<_> = self
            .decode_workers
            .read()
            .unwrap()
            .iter()
1204
            .map(|w| w.url().to_string())
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
            .collect();

        let mut prefill_loads = Vec::new();
        let mut decode_loads = Vec::new();

        for url in &p_urls {
            let load = get_worker_load(client, url).await.unwrap_or(-1);
            prefill_loads.push(serde_json::json!({
                "engine": format!("(Prefill@{})", url),
                "load": load as i64
            }));
        }

        for url in &d_urls {
            let load = get_worker_load(client, url).await.unwrap_or(-1);
            decode_loads.push(serde_json::json!({
                "engine": format!("(Decode@{})", url),
                "load": load as i64
            }));
        }

1226
        Json(serde_json::json!({
1227
1228
1229
            "prefill": prefill_loads,
            "decode": decode_loads
        }))
1230
        .into_response()
1231
1232
    }

1233
1234
1235
1236
    pub async fn get_model_info(&self, client: &reqwest::Client, req: Request<Body>) -> Response {
        // Extract headers first to avoid Send issues
        let headers = crate::routers::router::copy_request_headers(&req);

1237
1238
1239
        // Get model info from the first prefill server (matches original Rust PDLB behavior)
        // Get first prefill worker URL to avoid holding lock across await
        let first_worker_url = if let Ok(workers) = self.prefill_workers.read() {
1240
            workers.first().map(|w| w.url().to_string())
1241
        } else {
1242
1243
1244
1245
1246
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access prefill workers",
            )
                .into_response();
1247
1248
1249
1250
        };

        if let Some(worker_url) = first_worker_url {
            let mut request_builder = client.get(format!("{}/get_model_info", worker_url));
1251
            for (name, value) in headers {
1252
1253
1254
1255
1256
1257
1258
                if name.to_lowercase() != "content-type" && name.to_lowercase() != "content-length"
                {
                    request_builder = request_builder.header(name, value);
                }
            }
            match request_builder.send().await {
                Ok(res) => {
1259
1260
                    let status = StatusCode::from_u16(res.status().as_u16())
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1261
                    match res.bytes().await {
1262
1263
1264
1265
1266
1267
                        Ok(body) => (status, body).into_response(),
                        Err(e) => (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to read response body: {}", e),
                        )
                            .into_response(),
1268
1269
                    }
                }
1270
1271
1272
1273
1274
                Err(e) => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to send request: {}", e),
                )
                    .into_response(),
1275
1276
            }
        } else {
1277
1278
1279
1280
1281
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No prefill servers available",
            )
                .into_response()
1282
1283
1284
        }
    }

1285
    pub async fn flush_cache(&self, client: &reqwest::Client) -> Response {
1286
1287
1288
1289
        let mut tasks = Vec::new();

        // Flush cache on all prefill servers
        for worker in self.prefill_workers.read().unwrap().iter() {
1290
            let url = format!("{}/flush_cache", worker.url());
1291
1292
1293
1294
1295
            tasks.push(client.post(&url).send());
        }

        // Flush cache on all decode servers
        for worker in self.decode_workers.read().unwrap().iter() {
1296
            let url = format!("{}/flush_cache", worker.url());
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
            tasks.push(client.post(&url).send());
        }

        let results = futures_util::future::join_all(tasks).await;

        let mut all_success = true;
        for (i, result) in results.into_iter().enumerate() {
            match result {
                Ok(res) if res.status().is_success() => {}
                Ok(res) => {
                    all_success = false;
                    warn!(
                        "Server {} returned status {} for flush_cache",
                        i,
                        res.status()
                    );
                }
                Err(e) => {
                    all_success = false;
                    error!("Server {} error during flush_cache: {}", i, e);
                }
            }
        }

        if all_success {
1322
            (StatusCode::OK, "Cache flushed on all servers").into_response()
1323
        } else {
1324
1325
1326
1327
1328
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Cache flush failed on one or more servers",
            )
                .into_response()
1329
1330
1331
        }
    }
}
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386

use crate::routers::{RouterTrait, WorkerManagement};
use async_trait::async_trait;
use reqwest::Client;

#[async_trait]
impl WorkerManagement for PDRouter {
    async fn add_worker(&self, _worker_url: &str) -> Result<String, String> {
        // For PD router, we don't support adding workers via this generic method
        Err(
            "PD router requires specific add_prefill_server or add_decode_server methods"
                .to_string(),
        )
    }

    fn remove_worker(&self, worker_url: &str) {
        // For PD router, we would need to know if it's a prefill or decode server
        // For now, try both
        if let Ok(mut workers) = self.prefill_workers.write() {
            if let Some(index) = workers.iter().position(|w| w.url() == worker_url) {
                workers.remove(index);
                info!("Removed prefill worker: {}", worker_url);
                return;
            }
        }

        if let Ok(mut workers) = self.decode_workers.write() {
            if let Some(index) = workers.iter().position(|w| w.url() == worker_url) {
                workers.remove(index);
                info!("Removed decode worker: {}", worker_url);
            }
        }
    }

    fn get_worker_urls(&self) -> Vec<String> {
        let mut urls = Vec::new();

        // Add prefill worker URLs
        if let Ok(workers) = self.prefill_workers.read() {
            for worker in workers.iter() {
                urls.push(worker.url().to_string());
            }
        }

        // Add decode worker URLs
        if let Ok(workers) = self.decode_workers.read() {
            for worker in workers.iter() {
                urls.push(worker.url().to_string());
            }
        }

        urls
    }
}

1387
#[async_trait]
1388
1389
1390
1391
1392
impl RouterTrait for PDRouter {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

1393
    async fn health(&self, _client: &Client, _req: Request<Body>) -> Response {
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
        // This is a server readiness check - checking if we have healthy workers
        // Workers handle their own health checks in the background
        let mut all_healthy = true;
        let mut unhealthy_servers = Vec::new();

        // Check prefill servers
        for worker in self.prefill_workers.read().unwrap().iter() {
            if !worker.is_healthy() {
                all_healthy = false;
                unhealthy_servers.push(format!("Prefill: {}", worker.url()));
            }
        }

        // Check decode servers
        for worker in self.decode_workers.read().unwrap().iter() {
            if !worker.is_healthy() {
                all_healthy = false;
                unhealthy_servers.push(format!("Decode: {}", worker.url()));
            }
        }

        if all_healthy {
1416
            (StatusCode::OK, "All servers healthy").into_response()
1417
        } else {
1418
1419
1420
1421
1422
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Unhealthy servers: {:?}", unhealthy_servers),
            )
                .into_response()
1423
1424
1425
        }
    }

1426
    async fn health_generate(&self, client: &Client, _req: Request<Body>) -> Response {
1427
1428
1429
1430
        // Use the existing PDRouter health_generate method
        PDRouter::health_generate(self, client).await
    }

1431
    async fn get_server_info(&self, client: &Client, _req: Request<Body>) -> Response {
1432
1433
1434
1435
        // Use the existing PDRouter get_server_info method
        PDRouter::get_server_info(self, client).await
    }

1436
1437
1438
    async fn get_models(&self, client: &Client, req: Request<Body>) -> Response {
        // Use the existing PDRouter get_models method
        PDRouter::get_models(self, client, req).await
1439
1440
    }

1441
1442
1443
    async fn get_model_info(&self, client: &Client, req: Request<Body>) -> Response {
        // Use the existing PDRouter get_model_info method
        PDRouter::get_model_info(self, client, req).await
1444
1445
1446
1447
1448
    }

    async fn route_generate(
        &self,
        client: &Client,
1449
1450
1451
1452
1453
1454
1455
        headers: Option<&HeaderMap>,
        body: &GenerateRequest,
    ) -> Response {
        // Convert OpenAI format to PD format
        let pd_req = body.clone().to_pd_request();

        PDRouter::route_generate(self, client, headers, pd_req, "/generate").await
1456
1457
1458
1459
1460
    }

    async fn route_chat(
        &self,
        client: &Client,
1461
1462
1463
1464
1465
1466
1467
        headers: Option<&HeaderMap>,
        body: &ChatCompletionRequest,
    ) -> Response {
        // Convert OpenAI format to PD format
        let pd_req = body.clone().to_pd_request();

        PDRouter::route_chat(self, client, headers, pd_req, "/v1/chat/completions").await
1468
1469
1470
1471
1472
    }

    async fn route_completion(
        &self,
        client: &Client,
1473
1474
1475
1476
1477
        headers: Option<&HeaderMap>,
        body: &CompletionRequest,
    ) -> Response {
        // Use the new method that preserves OpenAI format
        PDRouter::route_completion(self, client, headers, body.clone(), "/v1/completions").await
1478
1479
    }

1480
    async fn flush_cache(&self, client: &Client) -> Response {
1481
1482
1483
1484
        // Use the existing PDRouter flush_cache method
        PDRouter::flush_cache(self, client).await
    }

1485
    async fn get_worker_loads(&self, client: &Client) -> Response {
1486
1487
1488
1489
1490
1491
1492
1493
        // Use the existing PDRouter get_loads method
        PDRouter::get_loads(self, client).await
    }

    fn router_type(&self) -> &'static str {
        "pd"
    }

1494
    fn readiness(&self) -> Response {
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
        // PD router is ready if it has at least one healthy prefill AND one healthy decode worker
        let healthy_prefill_count = self
            .prefill_workers
            .read()
            .unwrap()
            .iter()
            .filter(|w| w.is_healthy())
            .count();

        let healthy_decode_count = self
            .decode_workers
            .read()
            .unwrap()
            .iter()
            .filter(|w| w.is_healthy())
            .count();

        let total_prefill = self.prefill_workers.read().unwrap().len();
        let total_decode = self.decode_workers.read().unwrap().len();

        if healthy_prefill_count > 0 && healthy_decode_count > 0 {
1516
            Json(serde_json::json!({
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
                "status": "ready",
                "prefill": {
                    "healthy": healthy_prefill_count,
                    "total": total_prefill
                },
                "decode": {
                    "healthy": healthy_decode_count,
                    "total": total_decode
                }
            }))
1527
            .into_response()
1528
1529
1530
1531
1532
1533
1534
1535
1536
        } else {
            let mut reasons = Vec::new();
            if healthy_prefill_count == 0 {
                reasons.push("no healthy prefill workers");
            }
            if healthy_decode_count == 0 {
                reasons.push("no healthy decode workers");
            }

1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
            (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({
                    "status": "not_ready",
                    "reason": reasons.join(", "),
                    "prefill": {
                        "healthy": healthy_prefill_count,
                        "total": total_prefill
                    },
                    "decode": {
                        "healthy": healthy_decode_count,
                        "total": total_decode
                    }
                })),
            )
                .into_response()
1553
1554
1555
        }
    }
}
1556
1557
1558
1559
1560
1561
1562
1563
1564

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{BasicWorker, WorkerType};
    use crate::policies::{CacheAwarePolicy, RandomPolicy};
    use crate::routers::pd_types::SingleOrBatch;

    fn create_test_pd_router() -> PDRouter {
1565
1566
        let prefill_policy = Arc::new(RandomPolicy::new());
        let decode_policy = Arc::new(RandomPolicy::new());
1567
1568
1569
1570

        PDRouter {
            prefill_workers: Arc::new(RwLock::new(vec![])),
            decode_workers: Arc::new(RwLock::new(vec![])),
1571
1572
            prefill_policy,
            decode_policy,
1573
            prefill_tree: None,
1574
            decode_tree: None,
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
            timeout_secs: 5,
            interval_secs: 1,
            worker_loads: Arc::new(tokio::sync::watch::channel(HashMap::new()).1),
            load_monitor_handle: None,
            http_client: reqwest::Client::new(),
            _prefill_health_checker: None,
            _decode_health_checker: None,
        }
    }

    fn create_test_worker(url: String, worker_type: WorkerType, healthy: bool) -> Box<dyn Worker> {
        let worker = BasicWorker::new(url, worker_type);
        worker.set_healthy(healthy);
        Box::new(worker)
    }

    // ============= Worker Management Tests =============

    #[tokio::test]
    async fn test_add_prefill_server_already_exists() {
        let router = create_test_pd_router();

        // Add a worker first
        let worker = create_test_worker(
            "http://localhost:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(8080),
            },
            true,
        );
        router.prefill_workers.write().unwrap().push(worker);

        // Try to add the same URL again - this would fail during health check in real scenario
        // For unit test, we test the duplicate check logic
        let workers = router.prefill_workers.read().unwrap();
        let exists = workers.iter().any(|w| w.url() == "http://localhost:8000");
        assert!(exists);
    }

    #[tokio::test]
    async fn test_remove_prefill_server_success() {
        let router = create_test_pd_router();

        // Add servers first
        let worker1 = create_test_worker(
            "http://worker1".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        let worker2 = create_test_worker(
            "http://worker2".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(8080),
            },
            true,
        );

        router.prefill_workers.write().unwrap().push(worker1);
        router.prefill_workers.write().unwrap().push(worker2);

        // Remove one
        let result = router.remove_prefill_server("http://worker1").await;

        assert!(result.is_ok());
        assert!(result.unwrap().contains("Successfully removed"));

        let workers = router.prefill_workers.read().unwrap();
        assert_eq!(workers.len(), 1);
        assert_eq!(workers[0].url(), "http://worker2");
    }

    #[tokio::test]
    async fn test_remove_prefill_server_not_found() {
        let router = create_test_pd_router();

        let result = router.remove_prefill_server("http://nonexistent").await;

        assert!(result.is_err());
        match result.unwrap_err() {
            PDRouterError::WorkerNotFound { url } => {
                assert_eq!(url, "http://nonexistent");
            }
            _ => panic!("Expected WorkerNotFound error"),
        }
    }

    #[tokio::test]
    async fn test_remove_decode_server_success() {
        let router = create_test_pd_router();

        // Add server first
        let worker = create_test_worker("http://decode1".to_string(), WorkerType::Decode, true);
        router.decode_workers.write().unwrap().push(worker);

        let result = router.remove_decode_server("http://decode1").await;

        assert!(result.is_ok());
        assert!(result.unwrap().contains("Successfully removed"));

        let workers = router.decode_workers.read().unwrap();
        assert_eq!(workers.len(), 0);
    }

    // ============= Lock Error Handling Tests =============

    #[test]
    fn test_lock_operations() {
        let router = create_test_pd_router();

        // Test read/write locks work correctly
        {
            let read_guard = router.prefill_workers.read().unwrap();
            assert_eq!(read_guard.len(), 0);
        }

        {
            let mut write_guard = router.prefill_workers.write().unwrap();
            write_guard.push(create_test_worker(
                "http://test".to_string(),
                WorkerType::Prefill {
                    bootstrap_port: None,
                },
                true,
            ));
        }

        {
            let read_guard = router.prefill_workers.read().unwrap();
            assert_eq!(read_guard.len(), 1);
        }
    }

    // ============= Cache Tree Integration Tests =============

    #[tokio::test]
    async fn test_cache_tree_operations() {
1713
        let cache_policy = Arc::new(CacheAwarePolicy::new());
1714
        let mut router = create_test_pd_router();
1715
        router.prefill_policy = cache_policy;
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742

        // Initialize cache tree
        let tree = Arc::new(Mutex::new(Tree::new()));
        router.prefill_tree = Some(Arc::clone(&tree));

        // Manually add worker and update tree
        let worker = create_test_worker(
            "http://worker1".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        router.prefill_workers.write().unwrap().push(worker);

        // Update tree
        tree.lock().unwrap().insert("", "http://worker1");

        // Verify tree contains the worker
        let tree_guard = tree.lock().unwrap();
        let (_matched_text, tenant) = tree_guard.prefix_match("");
        // Since we inserted with empty prefix, we should get a match
        assert_eq!(tenant, "http://worker1");
    }

    #[tokio::test]
    async fn test_cache_tree_rebuild_on_remove() {
1743
        let cache_policy = Arc::new(CacheAwarePolicy::new());
1744
        let mut router = create_test_pd_router();
1745
        router.prefill_policy = cache_policy;
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970

        // Initialize cache tree
        let tree = Arc::new(Mutex::new(Tree::new()));
        router.prefill_tree = Some(Arc::clone(&tree));

        // Add multiple workers
        let worker1 = create_test_worker(
            "http://worker1".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        let worker2 = create_test_worker(
            "http://worker2".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );

        router.prefill_workers.write().unwrap().push(worker1);
        router.prefill_workers.write().unwrap().push(worker2);

        // Initialize tree with both workers
        {
            let tree_guard = tree.lock().unwrap();
            tree_guard.insert("", "http://worker1");
            tree_guard.insert("", "http://worker2");
        }

        // Remove one worker
        let result = router.remove_prefill_server("http://worker1").await;
        assert!(result.is_ok());

        // Verify tree only contains remaining worker
        let tree_guard = tree.lock().unwrap();
        let (_matched_text, tenant) = tree_guard.prefix_match("");
        // After rebuild, tree should only have worker2
        assert_eq!(tenant, "http://worker2");
    }

    #[tokio::test]
    async fn test_no_cache_tree_operations() {
        let router = create_test_pd_router();
        assert!(router.prefill_tree.is_none());

        // Add a worker without cache tree
        let worker = create_test_worker(
            "http://worker1".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        router.prefill_workers.write().unwrap().push(worker);

        // Remove should work without tree
        let result = router.remove_prefill_server("http://worker1").await;
        assert!(result.is_ok());
    }

    // ============= Bootstrap Injection Tests =============

    #[test]
    fn test_bootstrap_injection_with_existing_fields() {
        let mut req = GenerateReqInput {
            text: Some(SingleOrBatch::Single("Test".to_string())),
            input_ids: None,
            stream: false,
            bootstrap_host: Some(SingleOrBatch::Single("existing-host".to_string())),
            bootstrap_port: Some(SingleOrBatch::Single(Some(9999))),
            bootstrap_room: Some(SingleOrBatch::Single(12345)),
            other: Value::Object(serde_json::Map::new()),
        };

        let prefill_worker = create_test_worker(
            "http://new-host:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(8080),
            },
            true,
        );

        // Bootstrap info is added regardless of existing fields
        let result = req.add_bootstrap_info(prefill_worker.as_ref());
        assert!(result.is_ok());

        // Bootstrap info should be updated with new values
        assert_eq!(
            req.bootstrap_host,
            Some(SingleOrBatch::Single("new-host".to_string()))
        );
        assert_eq!(req.bootstrap_port, Some(SingleOrBatch::Single(Some(8080))));
        // Room should be regenerated (different from original)
        if let Some(SingleOrBatch::Single(room)) = req.bootstrap_room {
            assert_ne!(room, 12345);
        } else {
            panic!("Expected single room ID");
        }
    }

    #[test]
    fn test_bootstrap_room_generation() {
        let mut req1 = GenerateReqInput {
            text: Some(SingleOrBatch::Single("Test".to_string())),
            input_ids: None,
            stream: false,
            bootstrap_host: None,
            bootstrap_port: None,
            bootstrap_room: None,
            other: Value::Object(serde_json::Map::new()),
        };

        let mut req2 = GenerateReqInput {
            text: Some(SingleOrBatch::Single("Test".to_string())),
            input_ids: None,
            stream: false,
            bootstrap_host: None,
            bootstrap_port: None,
            bootstrap_room: None,
            other: Value::Object(serde_json::Map::new()),
        };

        let prefill_worker = create_test_worker(
            "http://host:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(8080),
            },
            true,
        );

        // Add bootstrap info to both requests
        let _ = req1.add_bootstrap_info(prefill_worker.as_ref());
        let _ = req2.add_bootstrap_info(prefill_worker.as_ref());

        // Room IDs should be different
        if let (Some(SingleOrBatch::Single(room1)), Some(SingleOrBatch::Single(room2))) =
            (req1.bootstrap_room, req2.bootstrap_room)
        {
            assert_ne!(room1, room2, "Room IDs should be unique");
        } else {
            panic!("Expected single room IDs");
        }
    }

    // ============= Worker Selection Tests =============

    #[tokio::test]
    async fn test_select_healthy_prefill_worker() {
        let router = create_test_pd_router();

        // Add mix of healthy and unhealthy workers
        let healthy_worker = create_test_worker(
            "http://healthy".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        let unhealthy_worker = create_test_worker(
            "http://unhealthy".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            false,
        );
        let decode_worker =
            create_test_worker("http://decode".to_string(), WorkerType::Decode, true);

        router
            .prefill_workers
            .write()
            .unwrap()
            .push(unhealthy_worker);
        router.prefill_workers.write().unwrap().push(healthy_worker);
        router.decode_workers.write().unwrap().push(decode_worker);

        let client = reqwest::Client::new();
        let result = router.select_pd_pair(&client, None).await;

        assert!(result.is_ok());
        let (prefill, _decode) = result.unwrap();

        // Should select the healthy worker
        assert_eq!(prefill.url(), "http://healthy");
        assert!(prefill.is_healthy());
    }

    #[tokio::test]
    async fn test_empty_worker_lists() {
        let router = create_test_pd_router();

        let client = reqwest::Client::new();
        let result = router.select_pd_pair(&client, None).await;

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No prefill workers available"));
    }

    // ============= Health Endpoints Tests =============

    #[tokio::test]
    async fn test_health_endpoints() {
        let router = create_test_pd_router();

        // Add healthy workers
        let prefill_worker = create_test_worker(
            "http://localhost:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        let decode_worker = create_test_worker(
            "http://localhost:8001".to_string(),
            WorkerType::Decode,
            true,
        );

        router.prefill_workers.write().unwrap().push(prefill_worker);
        router.decode_workers.write().unwrap().push(decode_worker);

        // Test health endpoint
        let client = reqwest::Client::new();
1971
1972
1973
1974
        let http_req = axum::http::Request::builder()
            .body(axum::body::Body::empty())
            .unwrap();
        let response = router.health(&client, http_req).await;
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986

        assert_eq!(response.status(), 200);

        // Test readiness endpoint
        let response = router.readiness();
        assert_eq!(response.status(), 200);
    }

    // ============= Load Monitoring Tests =============

    #[tokio::test]
    async fn test_load_monitor_updates() {
1987
        let power_of_two_policy = Arc::new(crate::policies::PowerOfTwoPolicy::new());
1988
        let mut router = create_test_pd_router();
1989
1990
        router.prefill_policy = power_of_two_policy.clone();
        router.decode_policy = power_of_two_policy;
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072

        // Create load channel
        let (tx, rx) = tokio::sync::watch::channel(HashMap::new());
        router.worker_loads = Arc::new(rx);

        // Simulate load updates
        let mut loads = HashMap::new();
        loads.insert("http://worker1".to_string(), 10);
        loads.insert("http://worker2".to_string(), 5);

        let _ = tx.send(loads.clone());

        // Router should receive updates
        let received = router.worker_loads.borrow().clone();
        assert_eq!(received.get("http://worker1"), Some(&10));
        assert_eq!(received.get("http://worker2"), Some(&5));
    }

    // ============= Worker Load Tests =============

    #[test]
    fn test_worker_load_metrics() {
        let prefill_worker = create_test_worker(
            "http://prefill".to_string(),
            WorkerType::Prefill {
                bootstrap_port: None,
            },
            true,
        );
        let decode_worker =
            create_test_worker("http://decode".to_string(), WorkerType::Decode, true);

        // Create load guard for both workers
        let _guard =
            WorkerLoadGuard::new_multi(vec![prefill_worker.as_ref(), decode_worker.as_ref()]);

        // Load should be incremented
        assert_eq!(prefill_worker.load(), 1);
        assert_eq!(decode_worker.load(), 1);

        // Drop guard - load should decrement
        drop(_guard);

        assert_eq!(prefill_worker.load(), 0);
        assert_eq!(decode_worker.load(), 0);
    }

    // ============= Concurrent Operations Tests =============

    #[tokio::test]
    async fn test_concurrent_worker_operations() {
        let router = Arc::new(create_test_pd_router());

        let mut handles = vec![];

        // Spawn tasks to add workers
        for i in 0..5 {
            let router_clone = Arc::clone(&router);
            let url = format!("http://worker{}", i);
            let handle = tokio::spawn(async move {
                let worker = create_test_worker(
                    url,
                    WorkerType::Prefill {
                        bootstrap_port: None,
                    },
                    true,
                );
                router_clone.prefill_workers.write().unwrap().push(worker);
            });
            handles.push(handle);
        }

        // Wait for all tasks
        for handle in handles {
            let _ = handle.await;
        }

        // Check final state
        let workers = router.prefill_workers.read().unwrap();
        assert_eq!(workers.len(), 5);
    }
}