pd_router.rs 78.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::bootstrap_injector::inject_bootstrap_fields;
use super::pd_types::{api_path, PDRouterError};
6
use crate::config::types::RetryConfig;
7
use crate::core::{HealthChecker, Worker, WorkerFactory, WorkerLoadGuard};
8
use crate::metrics::RouterMetrics;
9
10
use crate::openai_api_types::{ChatCompletionRequest, CompletionRequest, GenerateRequest};
use crate::policies::LoadBalancingPolicy;
11
use crate::routers::{RouterTrait, WorkerManagement};
12
use crate::tree::Tree;
13
use async_trait::async_trait;
14
15
16
17
18
19
20
21
use axum::{
    body::Body,
    extract::Request,
    http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use futures_util::StreamExt;
22
23
use rand::Rng;
use reqwest::Client;
24
25
26
27
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
28
use tokio_stream::wrappers::UnboundedReceiverStream;
29
30
31
32
use tracing::{debug, error, info, warn};

#[derive(Debug)]
pub struct PDRouter {
33
34
    pub prefill_workers: Arc<RwLock<Vec<Box<dyn Worker>>>>,
    pub decode_workers: Arc<RwLock<Vec<Box<dyn Worker>>>>,
35
36
    pub prefill_policy: Arc<dyn LoadBalancingPolicy>,
    pub decode_policy: Arc<dyn LoadBalancingPolicy>,
37
    pub prefill_tree: Option<Arc<Mutex<Tree>>>,
38
    pub decode_tree: Option<Arc<Mutex<Tree>>>,
39
40
41
42
    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<()>>>,
43
    pub client: Client,
44
    pub retry_config: RetryConfig,
45
46
    _prefill_health_checker: Option<HealthChecker>,
    _decode_health_checker: Option<HealthChecker>,
47
48
49
}

impl PDRouter {
50
    // Dynamic worker management methods for service discovery
51
52
53
54
55
56
57
58
59
60
61
62
63

    // Private helper method to perform health check on a new server
    async fn wait_for_server_health(&self, url: &str) -> Result<(), PDRouterError> {
        crate::routers::router::Router::wait_for_healthy_workers(
            &[url.to_string()],
            self.timeout_secs,
            self.interval_secs,
        )
        .map_err(|_| PDRouterError::HealthCheckFailed {
            url: url.to_string(),
        })
    }

64
65
66
67
68
69
    pub async fn add_prefill_server(
        &self,
        url: String,
        bootstrap_port: Option<u16>,
    ) -> Result<String, PDRouterError> {
        // Wait for the new server to be healthy
70
        self.wait_for_server_health(&url).await?;
71

72
73
74
        // Create Worker for the new prefill server
        let worker = WorkerFactory::create_prefill(url.clone(), bootstrap_port);

75
76
77
78
79
80
81
82
83
        // 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
84
        if workers.iter().any(|w| w.url() == &url) {
85
86
87
            return Err(PDRouterError::WorkerAlreadyExists { url: url.clone() });
        }

88
        workers.push(worker);
89

90
        // Add to cache tree if using cache-aware policy for prefill
91
92
93
94
95
96
97
98
99
100
        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
101
        self.wait_for_server_health(&url).await?;
102

103
104
105
        // Create Worker for the new decode server
        let worker = WorkerFactory::create_decode(url.clone());

106
107
108
109
110
111
112
113
114
        // 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
115
        if workers.iter().any(|w| w.url() == &url) {
116
117
118
            return Err(PDRouterError::WorkerAlreadyExists { url: url.clone() });
        }

119
        workers.push(worker);
120

121
122
123
124
125
        // Add to cache tree if using cache-aware policy for decode
        if let Some(ref tree) = self.decode_tree {
            tree.lock().unwrap().insert("", &url);
        }

126
127
128
129
130
131
132
133
134
135
136
137
138
139
        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();
140
        workers.retain(|w| w.url() != url);
141
142
143
144
145
146
147
148
149

        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 {
150
            tree.lock().unwrap().remove_tenant(url);
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        }

        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();
167
        workers.retain(|w| w.url() != url);
168
169
170
171
172
173
174

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

175
176
177
178
179
        // 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);
        }

180
181
182
        info!("Removed decode server: {}", url);
        Ok(format!("Successfully removed decode server: {}", url))
    }
183
184
185
186

    pub fn new(
        prefill_urls: Vec<(String, Option<u16>)>,
        decode_urls: Vec<String>,
187
188
        prefill_policy: Arc<dyn LoadBalancingPolicy>,
        decode_policy: Arc<dyn LoadBalancingPolicy>,
189
        client: Client,
190
191
        timeout_secs: u64,
        interval_secs: u64,
192
        retry_config: RetryConfig,
193
    ) -> Result<Self, String> {
194
195
        // Convert URLs to Worker trait objects
        let prefill_workers: Vec<Box<dyn Worker>> = prefill_urls
196
            .into_iter()
197
            .map(|(url, port)| WorkerFactory::create_prefill(url, port))
198
199
            .collect();

200
        let decode_workers: Vec<Box<dyn Worker>> = decode_urls
201
            .into_iter()
202
            .map(WorkerFactory::create_decode)
203
204
            .collect();

205
        // Wait for PD workers to be healthy (skip if empty - for service discovery mode)
206
207
208
        let all_urls: Vec<String> = prefill_workers
            .iter()
            .chain(decode_workers.iter())
209
            .map(|worker| worker.url().to_string())
210
            .collect();
211
212
213
214
215
216
217
        if !all_urls.is_empty() {
            crate::routers::router::Router::wait_for_healthy_workers(
                &all_urls,
                timeout_secs,
                interval_secs,
            )?;
        }
218

219
        // Initialize cache-aware components if needed for prefill policy
220
        let prefill_tree = Self::initialize_radix_tree(&prefill_policy, &prefill_workers)?;
221

222
        // Initialize cache-aware components if needed for decode policy
223
        let decode_tree = Self::initialize_radix_tree(&decode_policy, &decode_workers)?;
224

225
226
227
228
        // 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);

229
230
231
232
        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;
233
                let monitor_client = client.clone();
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
                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
            };
251

252
253
254
255
256
257
258
259
260
        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);

261
        Ok(PDRouter {
262
263
            prefill_workers,
            decode_workers,
264
265
            prefill_policy,
            decode_policy,
266
            prefill_tree,
267
            decode_tree,
268
269
270
271
            timeout_secs,
            interval_secs,
            worker_loads,
            load_monitor_handle,
272
            client,
273
            retry_config,
274
275
            _prefill_health_checker: Some(prefill_health_checker),
            _decode_health_checker: Some(decode_health_checker),
276
277
278
        })
    }

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    // Helper function to initialize radix tree for cache-aware policies
    fn initialize_radix_tree(
        policy: &Arc<dyn LoadBalancingPolicy>,
        workers: &[Box<dyn Worker>],
    ) -> Result<Option<Arc<Mutex<Tree>>>, String> {
        if let Some(cache_policy) = policy
            .as_any()
            .downcast_ref::<crate::policies::CacheAwarePolicy>()
        {
            // Initialize the policy's internal tree with workers
            cache_policy.init_workers(workers);

            let tree = Arc::new(Mutex::new(Tree::new()));

            {
                let tree_guard = tree
                    .lock()
                    .map_err(|e| format!("Failed to lock tree: {}", e))?;
                for worker in workers {
                    tree_guard.insert("", worker.url());
                }
            }

            Ok(Some(tree))
        } else {
            Ok(None)
        }
    }

308
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
    // Helper to handle server selection errors
    fn handle_server_selection_error(error: String) -> Response {
        error!("Failed to select PD pair error={}", error);
        RouterMetrics::record_pd_error("server_selection");
        (
            StatusCode::SERVICE_UNAVAILABLE,
            format!("No available servers: {}", error),
        )
            .into_response()
    }

    // Helper to handle bootstrap injection errors
    fn handle_bootstrap_error(error: impl std::fmt::Display) -> Response {
        error!("Failed to add bootstrap info error={}", error);
        RouterMetrics::record_pd_error("bootstrap_injection");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Bootstrap injection failed: {}", error),
        )
            .into_response()
    }

    // Helper to handle serialization errors
    fn handle_serialization_error(error: impl std::fmt::Display) -> Response {
        error!("Failed to serialize request error={}", error);
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to serialize request",
        )
            .into_response()
    }

    // Execute the dual dispatch to prefill and decode servers with retry logic
341
342
    async fn execute_dual_dispatch(
        &self,
343
344
        headers: Option<&HeaderMap>,
        json_request: Value,
345
        route: &str,
346
347
        prefill: &dyn Worker,
        decode: &dyn Worker,
348
349
350
        is_stream: bool,
        return_logprob: bool,
        start_time: Instant,
351
    ) -> Response {
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        for attempt in 0..self.retry_config.max_retries {
            if attempt > 0 {
                // Calculate backoff with exponential growth and jitter
                let base_backoff = self.retry_config.initial_backoff_ms as f64
                    * self
                        .retry_config
                        .backoff_multiplier
                        .powf((attempt - 1) as f32) as f64;
                let backoff_ms = base_backoff.min(self.retry_config.max_backoff_ms as f64) as u64;

                // Add jitter to prevent thundering herd
                let jitter = {
                    let mut rng = rand::thread_rng();
                    rng.gen_range(0..backoff_ms / 2)
                };
                let total_backoff = Duration::from_millis(backoff_ms + jitter);

                info!(
                    "Retrying request (attempt {}/{}) after {:?} backoff",
                    attempt + 1,
                    self.retry_config.max_retries,
                    total_backoff
                );
375

376
377
                tokio::time::sleep(total_backoff).await;
            }
378

379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
            debug!(
                "Executing request attempt {}/{}",
                attempt + 1,
                self.retry_config.max_retries
            );
            let result = self
                .execute_dual_dispatch_inner(
                    headers,
                    json_request.clone(),
                    route,
                    prefill,
                    decode,
                    is_stream,
                    return_logprob,
                    start_time,
                )
                .await;
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
            // Check if we should retry based on the response status
            let status = result.status();
            debug!(
                "Request attempt {} returned status: {}",
                attempt + 1,
                status
            );

            // Don't retry client errors (4xx) or successful responses
            if status.is_client_error() || status.is_success() {
                debug!(
                    "Returning response with status {} (no retry needed)",
                    status
                );
                return result;
            }

            // Check if this is the last attempt
            if attempt == self.retry_config.max_retries - 1 {
                warn!("Final attempt failed with status {}", status);
                return result;
            }

            // Log retry decision for retryable errors
            if status.is_server_error()
                || status == StatusCode::BAD_GATEWAY
                || status == StatusCode::GATEWAY_TIMEOUT
            {
                warn!(
                    "Retryable error status: {} on attempt {}/{}. Will retry.",
                    status,
                    attempt + 1,
                    self.retry_config.max_retries
                );
            } else {
                // Don't retry other statuses
                debug!("Status {} is not retryable, returning response", status);
                return result;
435
436
437
            }
        }

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        // This should never be reached due to the loop logic, but just in case
        unreachable!("Retry loop completed without returning")
    }

    // Inner implementation of dual dispatch (extracted for retry logic)
    async fn execute_dual_dispatch_inner(
        &self,
        headers: Option<&HeaderMap>,
        json_request: Value,
        route: &str,
        prefill: &dyn Worker,
        decode: &dyn Worker,
        is_stream: bool,
        return_logprob: bool,
        start_time: Instant,
    ) -> Response {
        // Update load tracking for both workers
        let _guard = WorkerLoadGuard::new_multi(vec![prefill, decode]);

        // Build requests with headers
        let prefill_request =
            self.build_request_with_headers(prefill.url(), route, &json_request, headers);

        let decode_request =
            self.build_request_with_headers(decode.url(), route, &json_request, headers);

464
        // Send both requests concurrently
465
466
467
468
469
        debug!(
            "Sending concurrent requests to prefill={} decode={}",
            prefill.url(),
            decode.url()
        );
470
471
        let (prefill_result, decode_result) =
            tokio::join!(prefill_request.send(), decode_request.send());
472
        debug!("Received responses from both servers");
473
474
475

        // Update metrics
        let duration = start_time.elapsed();
476
477
478
479
        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());
480

481
482
483
484
485
486
487
488
489
        // Process prefill response
        let (_prefill_status, prefill_body) = match self
            .process_prefill_response(prefill_result, prefill.url(), return_logprob)
            .await
        {
            Ok(result) => result,
            Err(error_response) => return error_response,
        };

490
        // Process decode response
491
        debug!("Processing decode response");
492
493
        match decode_result {
            Ok(res) => {
494
495
                let status = StatusCode::from_u16(res.status().as_u16())
                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
496
                debug!("Decode response status: {}", status);
497
498

                if !status.is_success() {
499
                    RouterMetrics::record_pd_decode_error(decode.url());
500
                    error!(
501
                        "Decode server returned error status decode_url={} status={}",
502
503
                        decode.url(),
                        status
504
505
506
507
508
                    );

                    // Return the error response from decode server
                    match res.bytes().await {
                        Ok(error_body) => {
509
                            return (status, error_body).into_response();
510
511
                        }
                        Err(e) => {
512
                            return (status, format!("Decode server error: {}", e)).into_response();
513
514
515
516
517
518
                        }
                    }
                }

                if is_stream {
                    // Streaming response
519
520
521
522
523
524
525
                    let prefill_logprobs = if return_logprob {
                        prefill_body
                            .as_ref()
                            .and_then(|body| serde_json::from_slice::<Value>(body).ok())
                            .and_then(|json| {
                                json.pointer("/meta_info/input_token_logprobs").cloned()
                            })
526
                    } else {
527
528
                        None
                    };
529

530
531
532
533
534
                    let decode_url = if !return_logprob {
                        Some(decode.url().to_string())
                    } else {
                        None
                    };
535

536
537
538
539
540
541
542
                    Self::create_streaming_response(
                        res.bytes_stream(),
                        status,
                        prefill_logprobs,
                        return_logprob,
                        decode_url,
                    )
543
                } else {
544
545
546
                    // Non-streaming response - use helper
                    self.process_non_streaming_response(res, status, return_logprob, prefill_body)
                        .await
547
548
549
                }
            }
            Err(e) => {
550
551
552
553
554
                error!(
                    decode_url = %decode.url(),
                    error = %e,
                    "Decode request failed"
                );
555
                RouterMetrics::record_pd_decode_error(decode.url());
556
557
558
559
560
                (
                    StatusCode::BAD_GATEWAY,
                    format!("Decode server error: {}", e),
                )
                    .into_response()
561
562
563
564
565
566
567
            }
        }
    }

    // Select a pair of prefill and decode servers
    async fn select_pd_pair(
        &self,
568
        request_text: Option<&str>,
569
    ) -> Result<(Box<dyn Worker>, Box<dyn Worker>), String> {
570
571
        // Get read locks for both worker lists
        let prefill_workers = self
572
573
            .prefill_workers
            .read()
574
575
            .map_err(|e| format!("Failed to acquire prefill workers lock: {}", e))?;
        let decode_workers = self
576
577
            .decode_workers
            .read()
578
579
580
581
582
583
584
            .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() {
585
586
587
            return Err("No decode workers available. Please check if decode servers are configured and healthy.".to_string());
        }

588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
        // 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))
603
604
605
606
607
608
609
    }

    // 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,
610
        client: Client,
611
612
        prefill_policy: Arc<dyn LoadBalancingPolicy>,
        decode_policy: Arc<dyn LoadBalancingPolicy>,
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
    ) {
        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);

637
638
639
            // Update both policies with current loads
            prefill_policy.update_loads(&loads);
            decode_policy.update_loads(&loads);
640

641
642
643
644
645
646
647
648
649
650
            // 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;
        }
    }

651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
    // Helper to create a streaming response
    fn create_streaming_response(
        stream: impl futures_util::Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send + 'static,
        status: StatusCode,
        prefill_logprobs: Option<Value>,
        return_logprob: bool,
        decode_url: Option<String>,
    ) -> Response {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

        tokio::spawn(async move {
            futures_util::pin_mut!(stream);
            while let Some(chunk_result) = stream.next().await {
                match chunk_result {
                    Ok(chunk) => {
                        let result = if return_logprob && prefill_logprobs.is_some() {
                            // Try to merge logprobs
                            Self::merge_streaming_logprobs(prefill_logprobs.clone(), &chunk)
                                .unwrap_or(chunk)
                        } else {
                            chunk
                        };

                        if tx.send(Ok(result)).is_err() {
                            break;
                        }
                    }
                    Err(e) => {
                        if let Some(ref url) = decode_url {
                            error!("Stream error from decode server {}: {}", url, e);
                            RouterMetrics::record_pd_stream_error(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
    }

    // Helper to process non-streaming decode response with logprob merging
    async fn process_non_streaming_response(
        &self,
        res: reqwest::Response,
        status: StatusCode,
        return_logprob: bool,
        prefill_body: Option<bytes::Bytes>,
    ) -> Response {
        match res.bytes().await {
            Ok(decode_body) => {
                if return_logprob && prefill_body.is_some() {
                    // Merge logprobs from prefill and decode
                    let prefill_body = prefill_body.as_ref().unwrap();
                    match (
                        serde_json::from_slice::<Value>(prefill_body),
                        serde_json::from_slice::<Value>(&decode_body),
                    ) {
                        (Ok(prefill_json), Ok(mut decode_json)) => {
                            // Use helper to merge logprobs
                            Self::merge_logprobs_in_json(&prefill_json, &mut decode_json);

                            // Return merged response
                            match serde_json::to_vec(&decode_json) {
                                Ok(body) => (status, body).into_response(),
                                Err(e) => {
                                    error!("Failed to serialize merged response: {}", e);
                                    (status, decode_body).into_response()
                                }
                            }
                        }
                        _ => {
                            // If parsing fails, just return decode response
                            warn!("Failed to parse responses for logprob merging");
                            (status, decode_body).into_response()
                        }
                    }
                } else {
                    (status, decode_body).into_response()
                }
            }
            Err(e) => {
                error!("Failed to read decode response: {}", e);
                (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read response").into_response()
            }
        }
    }

    // Helper to process prefill response and extract body if needed for logprobs
    async fn process_prefill_response(
        &self,
        prefill_result: Result<reqwest::Response, reqwest::Error>,
        prefill_url: &str,
        return_logprob: bool,
    ) -> Result<(StatusCode, Option<bytes::Bytes>), Response> {
        // Check prefill result first - it's critical for disaggregated mode
        let prefill_response = match prefill_result {
            Ok(response) => response,
            Err(e) => {
                RouterMetrics::record_pd_prefill_error(prefill_url);
                error!(
                    "Prefill server failed (CRITICAL) prefill_url={} error={}. Decode will timeout without prefill KV cache.",
                    prefill_url,
                    e
                );

                // Return error immediately - don't wait for decode to timeout
                return Err((
                    StatusCode::BAD_GATEWAY,
                    format!(
                        "Prefill server error: {}. This will cause decode timeout.",
                        e
                    ),
                )
                    .into_response());
            }
        };

        let prefill_status = StatusCode::from_u16(prefill_response.status().as_u16())
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

        // Check if prefill succeeded
        if !prefill_status.is_success() {
            RouterMetrics::record_pd_prefill_error(prefill_url);

            // Get error body from prefill
            let error_msg = prefill_response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown prefill error".to_string());

            error!(
                "Prefill server returned error status prefill_url={} status={} body={}",
                prefill_url, prefill_status, error_msg
            );

            return Err((
                prefill_status,
                format!("Prefill server error ({}): {}", prefill_status, error_msg),
            )
                .into_response());
        }

        // Read prefill body if needed for logprob merging
        let prefill_body = if return_logprob {
            match prefill_response.bytes().await {
                Ok(body) => Some(body),
                Err(e) => {
                    warn!("Failed to read prefill response body for logprobs: {}", e);
                    None
                }
            }
        } else {
            // For non-logprob requests, just consume the response without storing
            debug!("Consuming prefill response body (non-logprob request)");
            match prefill_response.bytes().await {
                Ok(_) => debug!("Prefill response consumed successfully"),
                Err(e) => warn!("Error consuming prefill response: {}", e),
            }
            None
        };

        Ok((prefill_status, prefill_body))
    }

    // Helper to build a request with headers copied from the original request
    fn build_request_with_headers(
        &self,
        url: &str,
        route: &str,
        json_request: &Value,
        headers: Option<&HeaderMap>,
    ) -> reqwest::RequestBuilder {
        let mut request = self.client.post(api_path(url, route)).json(json_request);

        // 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() {
                        request = request.header(name, value);
                    }
                }
            }
        }

        request
    }

    // Helper to merge logprobs from prefill and decode responses
    fn merge_logprobs_in_json(prefill_json: &Value, decode_json: &mut Value) -> bool {
        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(prefill_arr), Some(decode_arr)) =
                    (prefill_logprobs.as_array(), decode_logprobs.as_array_mut())
                {
                    let mut merged = prefill_arr.clone();
                    merged.extend(decode_arr.clone());
                    decode_meta["input_token_logprobs"] = Value::Array(merged);
                    return true;
                }
            }
        }
        false
    }

874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
    // 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

915
async fn get_worker_load(client: &Client, worker_url: &str) -> Option<isize> {
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
    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
        }
    }
}

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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
#[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
    }
}

#[async_trait]
impl RouterTrait for PDRouter {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    async fn health(&self, _req: Request<Body>) -> Response {
        // 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 {
            (StatusCode::OK, "All servers healthy").into_response()
        } else {
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Unhealthy servers: {:?}", unhealthy_servers),
            )
                .into_response()
        }
    }

    async fn health_generate(&self, _req: Request<Body>) -> Response {
1038
1039
        // 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
1040

1041
        // Select a random worker pair using the policy
1042
        let (prefill, decode) = match self.select_pd_pair(None).await {
1043
1044
            Ok(pair) => pair,
            Err(e) => {
1045
1046
1047
1048
1049
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    format!("No healthy worker pair available: {}", e),
                )
                    .into_response();
1050
1051
            }
        };
1052

1053
1054
        // Test prefill server's health_generate
        let prefill_url = format!("{}/health_generate", prefill.url());
1055
        let prefill_result = self.client.get(&prefill_url).send().await;
1056

1057
1058
        // Test decode server's health_generate
        let decode_url = format!("{}/health_generate", decode.url());
1059
        let decode_result = self.client.get(&decode_url).send().await;
1060

1061
1062
        // Check results
        let mut errors = Vec::new();
1063

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
        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));
            }
        }
1082

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
        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));
1096
1097
1098
            }
        }

1099
        if errors.is_empty() {
1100
1101
1102
1103
1104
1105
1106
1107
1108
            (
                StatusCode::OK,
                format!(
                    "Health generate passed on selected pair: prefill={}, decode={}",
                    prefill.url(),
                    decode.url()
                ),
            )
                .into_response()
1109
        } else {
1110
1111
1112
1113
1114
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Health generate failed: {:?}", errors),
            )
                .into_response()
1115
1116
1117
        }
    }

1118
    async fn get_server_info(&self, _req: Request<Body>) -> Response {
1119
1120
        // 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() {
1121
            workers.first().map(|w| w.url().to_string())
1122
        } else {
1123
1124
1125
1126
1127
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access decode workers",
            )
                .into_response();
1128
        };
1129

1130
        if let Some(worker_url) = first_decode_url {
1131
1132
            match self
                .client
1133
1134
1135
1136
1137
1138
1139
                .get(format!("{}/get_server_info", worker_url))
                .send()
                .await
            {
                Ok(res) if res.status().is_success() => {
                    match res.json::<Value>().await {
                        Ok(info) => {
1140
1141
                            // The decode server should already return the proper format
                            // with tokenizer_path and other fields that bench_one_batch_server.py expects
1142
                            Json(info).into_response()
1143
1144
1145
                        }
                        Err(e) => {
                            error!("Failed to parse server info: {}", e);
1146
1147
1148
1149
1150
                            (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                format!("Failed to parse server info: {}", e),
                            )
                                .into_response()
1151
1152
1153
                        }
                    }
                }
1154
                Ok(res) => {
1155
1156
1157
1158
1159
1160
1161
                    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()
1162
1163
1164
                }
                Err(e) => {
                    error!("Failed to get server info: {}", e);
1165
1166
1167
1168
1169
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to get server info: {}", e),
                    )
                        .into_response()
1170
                }
1171
1172
            }
        } else {
1173
1174
1175
1176
1177
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No decode servers available",
            )
                .into_response()
1178
1179
1180
        }
    }

1181
    async fn get_models(&self, req: Request<Body>) -> Response {
1182
1183
1184
        // Extract headers first to avoid Send issues
        let headers = crate::routers::router::copy_request_headers(&req);

1185
1186
        // Get first prefill worker URL to avoid holding lock across await
        let first_worker_url = if let Ok(workers) = self.prefill_workers.read() {
1187
            workers.first().map(|w| w.url().to_string())
1188
        } else {
1189
1190
1191
1192
1193
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access prefill workers",
            )
                .into_response();
1194
1195
1196
        };

        if let Some(worker_url) = first_worker_url {
1197
1198
1199
1200
            let url = format!("{}/v1/models", worker_url);
            let mut request_builder = self.client.get(&url);

            // Add headers
1201
            for (name, value) in headers {
1202
                request_builder = request_builder.header(name, value);
1203
            }
1204

1205
            match request_builder.send().await {
1206
1207
1208
1209
1210
                Ok(res) if res.status().is_success() => match res.bytes().await {
                    Ok(body) => (StatusCode::OK, body).into_response(),
                    Err(e) => {
                        error!("Failed to read response body: {}", e);
                        (
1211
1212
1213
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to read response body: {}", e),
                        )
1214
                            .into_response()
1215
                    }
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
                },
                Ok(res) => {
                    let status = StatusCode::from_u16(res.status().as_u16())
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                    (
                        status,
                        format!("Prefill server returned status: {}", res.status()),
                    )
                        .into_response()
                }
                Err(e) => {
                    error!("Failed to get models: {}", e);
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to get models: {}", e),
                    )
                        .into_response()
1233
1234
1235
                }
            }
        } else {
1236
1237
1238
1239
1240
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No prefill servers available",
            )
                .into_response()
1241
1242
1243
        }
    }

1244
    async fn get_model_info(&self, req: Request<Body>) -> Response {
1245
1246
1247
        // Extract headers first to avoid Send issues
        let headers = crate::routers::router::copy_request_headers(&req);

1248
1249
        // Get first prefill worker URL to avoid holding lock across await
        let first_worker_url = if let Ok(workers) = self.prefill_workers.read() {
1250
            workers.first().map(|w| w.url().to_string())
1251
        } else {
1252
1253
1254
1255
1256
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to access prefill workers",
            )
                .into_response();
1257
1258
1259
        };

        if let Some(worker_url) = first_worker_url {
1260
1261
1262
1263
            let url = format!("{}/get_model_info", worker_url);
            let mut request_builder = self.client.get(&url);

            // Add headers
1264
            for (name, value) in headers {
1265
                request_builder = request_builder.header(name, value);
1266
            }
1267

1268
            match request_builder.send().await {
1269
1270
1271
1272
1273
                Ok(res) if res.status().is_success() => match res.bytes().await {
                    Ok(body) => (StatusCode::OK, body).into_response(),
                    Err(e) => {
                        error!("Failed to read response body: {}", e);
                        (
1274
1275
1276
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to read response body: {}", e),
                        )
1277
                            .into_response()
1278
                    }
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
                },
                Ok(res) => {
                    let status = StatusCode::from_u16(res.status().as_u16())
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                    (
                        status,
                        format!("Prefill server returned status: {}", res.status()),
                    )
                        .into_response()
                }
                Err(e) => {
                    error!("Failed to get model info: {}", e);
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to get model info: {}", e),
                    )
                        .into_response()
1296
1297
1298
                }
            }
        } else {
1299
1300
1301
1302
1303
            (
                StatusCode::SERVICE_UNAVAILABLE,
                "No prefill servers available",
            )
                .into_response()
1304
1305
1306
        }
    }

1307
1308
1309
1310
1311
1312
    async fn route_generate(
        &self,
        headers: Option<&HeaderMap>,
        body: &GenerateRequest,
    ) -> Response {
        let start = Instant::now();
1313

1314
1315
1316
1317
1318
        // Convert directly to JSON to preserve all fields automatically
        let mut json = match serde_json::to_value(body) {
            Ok(json) => json,
            Err(e) => return Self::handle_serialization_error(e),
        };
1319

1320
1321
1322
        // Extract flags for routing logic
        let is_stream = body.stream;
        let return_logprob = body.return_logprob;
1323

1324
1325
1326
1327
1328
1329
1330
        // Extract text for cache-aware routing
        let request_text = body.text.as_deref().or_else(|| {
            body.prompt.as_ref().and_then(|p| match p {
                crate::openai_api_types::StringOrArray::String(s) => Some(s.as_str()),
                crate::openai_api_types::StringOrArray::Array(v) => v.first().map(|s| s.as_str()),
            })
        });
1331

1332
1333
1334
1335
1336
        // Select servers
        let (prefill, decode) = match self.select_pd_pair(request_text).await {
            Ok(pair) => pair,
            Err(e) => return Self::handle_server_selection_error(e),
        };
1337

1338
1339
1340
1341
1342
1343
        // Log routing decision
        info!(
            "PD routing decision route=/generate prefill_url={} decode_url={}",
            prefill.url(),
            decode.url()
        );
1344

1345
1346
1347
1348
        // Inject bootstrap fields directly into JSON
        if let Err(e) = inject_bootstrap_fields(&mut json, prefill.as_ref()) {
            return Self::handle_bootstrap_error(e);
        }
1349

1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
        // Execute dual dispatch
        self.execute_dual_dispatch(
            headers,
            json,
            "/generate",
            prefill.as_ref(),
            decode.as_ref(),
            is_stream,
            return_logprob,
            start,
1360
        )
1361
        .await
1362
1363
    }

1364
1365
1366
1367
1368
1369
    async fn route_chat(
        &self,
        headers: Option<&HeaderMap>,
        body: &ChatCompletionRequest,
    ) -> Response {
        let start = Instant::now();
1370

1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
        // Convert directly to JSON to preserve all fields automatically
        let mut json = match serde_json::to_value(body) {
            Ok(json) => json,
            Err(e) => return Self::handle_serialization_error(e),
        };

        // Extract flags for routing logic
        let is_stream = body.stream;
        let return_logprob = body.logprobs;

        // Extract text for cache-aware routing from chat messages
        let request_text = body.messages.first().and_then(|msg| match msg {
            crate::openai_api_types::ChatMessage::User { content, .. } => {
                match content {
                    crate::openai_api_types::UserMessageContent::Text(text) => Some(text.as_str()),
                    crate::openai_api_types::UserMessageContent::Parts(_) => None, // Skip complex content
                }
1388
            }
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
            crate::openai_api_types::ChatMessage::System { content, .. } => Some(content.as_str()),
            _ => None,
        });

        // Select servers
        let (prefill, decode) = match self.select_pd_pair(request_text).await {
            Ok(pair) => pair,
            Err(e) => return Self::handle_server_selection_error(e),
        };

        // Log routing decision
        info!(
            "PD routing decision route=/v1/chat/completions prefill_url={} decode_url={}",
            prefill.url(),
            decode.url()
        );

        // Inject bootstrap fields directly into JSON
        if let Err(e) = inject_bootstrap_fields(&mut json, prefill.as_ref()) {
            return Self::handle_bootstrap_error(e);
1409
        }
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422

        // Execute dual dispatch
        self.execute_dual_dispatch(
            headers,
            json,
            "/v1/chat/completions",
            prefill.as_ref(),
            decode.as_ref(),
            is_stream,
            return_logprob,
            start,
        )
        .await
1423
1424
    }

1425
1426
1427
1428
1429
1430
    async fn route_completion(
        &self,
        headers: Option<&HeaderMap>,
        body: &CompletionRequest,
    ) -> Response {
        let start = Instant::now();
1431

1432
1433
1434
1435
1436
        // Convert directly to JSON to preserve all fields automatically
        let mut json = match serde_json::to_value(body) {
            Ok(json) => json,
            Err(e) => return Self::handle_serialization_error(e),
        };
1437

1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
        // Extract flags for routing logic
        let is_stream = body.stream;
        let return_logprob = body.logprobs.is_some();

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

        // Select servers
        let (prefill, decode) = match self.select_pd_pair(request_text).await {
            Ok(pair) => pair,
            Err(e) => return Self::handle_server_selection_error(e),
        };

        // Log routing decision
        info!(
            "PD routing decision route=/v1/completions prefill_url={} decode_url={}",
            prefill.url(),
            decode.url()
        );

        // Inject bootstrap fields directly into JSON
        if let Err(e) = inject_bootstrap_fields(&mut json, prefill.as_ref()) {
            return Self::handle_bootstrap_error(e);
1464
1465
        }

1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
        // Execute dual dispatch
        self.execute_dual_dispatch(
            headers,
            json,
            "/v1/completions",
            prefill.as_ref(),
            decode.as_ref(),
            is_stream,
            return_logprob,
            start,
        )
        .await
1478
1479
    }

1480
1481
1482
    async fn flush_cache(&self) -> Response {
        let mut results = Vec::new();
        let mut errors = Vec::new();
1483

1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
        // Get prefill worker URLs first to avoid holding lock across await
        let prefill_urls = if let Ok(workers) = self.prefill_workers.read() {
            workers
                .iter()
                .map(|w| w.url().to_string())
                .collect::<Vec<_>>()
        } else {
            errors.push("Failed to access prefill workers".to_string());
            Vec::new()
        };
1494

1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
        // Flush prefill workers
        for worker_url in prefill_urls {
            let url = format!("{}/flush_cache", worker_url);
            match self.client.post(&url).send().await {
                Ok(res) if res.status().is_success() => {
                    results.push(format!("Prefill {}: OK", worker_url));
                }
                Ok(res) => {
                    errors.push(format!(
                        "Prefill {} returned status: {}",
                        worker_url,
                        res.status()
                    ));
                }
                Err(e) => {
                    errors.push(format!("Prefill {} error: {}", worker_url, e));
                }
1512
1513
1514
            }
        }

1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
        // Get decode worker URLs first to avoid holding lock across await
        let decode_urls = if let Ok(workers) = self.decode_workers.read() {
            workers
                .iter()
                .map(|w| w.url().to_string())
                .collect::<Vec<_>>()
        } else {
            errors.push("Failed to access decode workers".to_string());
            Vec::new()
        };

        // Flush decode workers
        for worker_url in decode_urls {
            let url = format!("{}/flush_cache", worker_url);
            match self.client.post(&url).send().await {
                Ok(res) if res.status().is_success() => {
                    results.push(format!("Decode {}: OK", worker_url));
                }
                Ok(res) => {
                    errors.push(format!(
                        "Decode {} returned status: {}",
                        worker_url,
                        res.status()
                    ));
                }
                Err(e) => {
                    errors.push(format!("Decode {} error: {}", worker_url, e));
                }
1543
1544
1545
            }
        }

1546
1547
1548
1549
1550
1551
        if errors.is_empty() {
            (
                StatusCode::OK,
                format!("Cache flushed successfully: {:?}", results),
            )
                .into_response()
1552
        } else {
1553
            (
1554
1555
1556
1557
1558
                StatusCode::PARTIAL_CONTENT,
                format!(
                    "Partial success. Results: {:?}, Errors: {:?}",
                    results, errors
                ),
1559
1560
            )
                .into_response()
1561
1562
1563
        }
    }

1564
1565
1566
    async fn get_worker_loads(&self) -> Response {
        let mut loads = HashMap::new();
        let mut errors = Vec::new();
1567

1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
        // Get prefill worker URLs first to avoid holding lock across await
        let prefill_urls = if let Ok(workers) = self.prefill_workers.read() {
            workers
                .iter()
                .map(|w| w.url().to_string())
                .collect::<Vec<_>>()
        } else {
            errors.push("Failed to access prefill workers".to_string());
            Vec::new()
        };
1578

1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
        // Get loads from prefill workers
        for worker_url in prefill_urls {
            match get_worker_load(&self.client, &worker_url).await {
                Some(load) => {
                    loads.insert(format!("prefill_{}", worker_url), load);
                }
                None => {
                    errors.push(format!("Failed to get load from prefill {}", worker_url));
                }
            }
        }
1590

1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
        // Get decode worker URLs first to avoid holding lock across await
        let decode_urls = if let Ok(workers) = self.decode_workers.read() {
            workers
                .iter()
                .map(|w| w.url().to_string())
                .collect::<Vec<_>>()
        } else {
            errors.push("Failed to access decode workers".to_string());
            Vec::new()
        };
1601

1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
        // Get loads from decode workers
        for worker_url in decode_urls {
            match get_worker_load(&self.client, &worker_url).await {
                Some(load) => {
                    loads.insert(format!("decode_{}", worker_url), load);
                }
                None => {
                    errors.push(format!("Failed to get load from decode {}", worker_url));
                }
            }
        }
1613

1614
1615
1616
1617
        let response_data = serde_json::json!({
            "loads": loads,
            "errors": errors
        });
1618

1619
        (StatusCode::OK, Json(response_data)).into_response()
1620
1621
1622
1623
1624
1625
    }

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

1626
    fn readiness(&self) -> Response {
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
        // 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 {
1648
            Json(serde_json::json!({
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
                "status": "ready",
                "prefill": {
                    "healthy": healthy_prefill_count,
                    "total": total_prefill
                },
                "decode": {
                    "healthy": healthy_decode_count,
                    "total": total_decode
                }
            }))
1659
            .into_response()
1660
1661
1662
1663
1664
1665
1666
1667
1668
        } 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");
            }

1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
            (
                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()
1685
1686
1687
        }
    }
}
1688
1689
1690
1691
1692
1693
1694
1695

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

    fn create_test_pd_router() -> PDRouter {
1696
1697
        let prefill_policy = Arc::new(RandomPolicy::new());
        let decode_policy = Arc::new(RandomPolicy::new());
1698
1699
1700
1701

        PDRouter {
            prefill_workers: Arc::new(RwLock::new(vec![])),
            decode_workers: Arc::new(RwLock::new(vec![])),
1702
1703
            prefill_policy,
            decode_policy,
1704
            prefill_tree: None,
1705
            decode_tree: None,
1706
1707
1708
1709
            timeout_secs: 5,
            interval_secs: 1,
            worker_loads: Arc::new(tokio::sync::watch::channel(HashMap::new()).1),
            load_monitor_handle: None,
1710
            client: Client::new(),
1711
            retry_config: RetryConfig::default(),
1712
1713
1714
1715
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
1743
1744
1745
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
            _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() {
1845
        let cache_policy = Arc::new(CacheAwarePolicy::new());
1846
        let mut router = create_test_pd_router();
1847
        router.prefill_policy = cache_policy;
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

        // 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() {
1875
        let cache_policy = Arc::new(CacheAwarePolicy::new());
1876
        let mut router = create_test_pd_router();
1877
        router.prefill_policy = cache_policy;
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
1971

        // 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());
    }

    // ============= 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);

1972
        let result = router.select_pd_pair(None).await;
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985

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

1986
        let result = router.select_pd_pair(None).await;
1987
1988
1989
1990
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

        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
2016
2017
2018
        let http_req = axum::http::Request::builder()
            .body(axum::body::Body::empty())
            .unwrap();
2019
        let response = router.health(http_req).await;
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031

        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() {
2032
        let power_of_two_policy = Arc::new(crate::policies::PowerOfTwoPolicy::new());
2033
        let mut router = create_test_pd_router();
2034
2035
        router.prefill_policy = power_of_two_policy.clone();
        router.decode_policy = power_of_two_policy;
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
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116

        // 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);
    }
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270

    #[tokio::test]
    async fn test_simplified_routing_preserves_sglang_fields() {
        use crate::openai_api_types::GenerateRequest;
        use crate::routers::bootstrap_injector::inject_bootstrap_fields;

        // Create a test worker
        let worker = BasicWorker::new(
            "http://test-server:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(5678),
            },
        );

        // Create a GenerateRequest with SGLang extensions
        let mut session_params = std::collections::HashMap::new();
        session_params.insert("test_key".to_string(), serde_json::json!("test_value"));

        let request = GenerateRequest {
            text: Some("Test prompt".to_string()),
            stream: false,
            return_logprob: true,
            // SGLang extensions
            lora_path: Some(crate::openai_api_types::LoRAPath::Single(Some(
                "test.bin".to_string(),
            ))),
            session_params: Some(session_params.clone()),
            return_hidden_states: true,
            rid: Some("test-request-id".to_string()),
            // Other fields default to None/false
            prompt: None,
            input_ids: None,
            parameters: None,
            sampling_params: None,
        };

        // Convert to JSON (simulating the simplified routing path)
        let mut json = serde_json::to_value(&request).unwrap();

        // Inject bootstrap fields
        let result = inject_bootstrap_fields(&mut json, &worker);
        assert!(result.is_ok());

        // Verify all SGLang fields are preserved
        assert_eq!(json["text"], serde_json::json!("Test prompt"));
        assert_eq!(json["stream"], serde_json::json!(false));
        assert_eq!(json["return_logprob"], serde_json::json!(true));
        assert_eq!(json["lora_path"], serde_json::json!("test.bin")); // LoRAPath::Single serializes as just the inner value
        assert_eq!(
            json["session_params"],
            serde_json::to_value(&session_params).unwrap()
        );
        assert_eq!(json["return_hidden_states"], serde_json::json!(true));
        assert_eq!(json["rid"], serde_json::json!("test-request-id"));

        // Verify bootstrap fields were added
        assert_eq!(json["bootstrap_host"], serde_json::json!("test-server"));
        assert_eq!(json["bootstrap_port"], serde_json::json!(5678));
        assert!(json["bootstrap_room"].is_number());
    }

    #[tokio::test]
    async fn test_simplified_routing_chat_completion() {
        use crate::openai_api_types::{ChatCompletionRequest, ChatMessage, UserMessageContent};
        use crate::routers::bootstrap_injector::inject_bootstrap_fields;

        // Create a test worker
        let worker = BasicWorker::new(
            "http://chat-server:8000".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(9999),
            },
        );

        // Create a ChatCompletionRequest with SGLang extensions
        let request = ChatCompletionRequest {
            model: "gpt-4".to_string(),
            messages: vec![ChatMessage::User {
                role: "user".to_string(),
                content: UserMessageContent::Text("Hello world!".to_string()),
                name: None,
            }],
            stream: false,
            n: Some(2), // This should create batch bootstrap
            // SGLang extensions
            top_k: Some(50),
            separate_reasoning: false,
            stream_reasoning: true,
            // Set all other fields to defaults
            temperature: None,
            top_p: None,
            stream_options: None,
            stop: None,
            max_tokens: None,
            max_completion_tokens: None,
            presence_penalty: None,
            frequency_penalty: None,
            logit_bias: None,
            user: None,
            seed: None,
            logprobs: false,
            top_logprobs: None,
            response_format: None,
            tools: None,
            tool_choice: None,
            parallel_tool_calls: None,
            functions: None,
            function_call: None,
            min_p: None,
            min_tokens: None,
            repetition_penalty: None,
            regex: None,
            ebnf: None,
            stop_token_ids: None,
            no_stop_trim: false,
            ignore_eos: false,
            continue_final_message: false,
            skip_special_tokens: true,
            lora_path: None,
            session_params: None,
            return_hidden_states: false,
        };

        // Convert to JSON (simulating the simplified routing path)
        let mut json = serde_json::to_value(&request).unwrap();

        // Inject bootstrap fields
        let result = inject_bootstrap_fields(&mut json, &worker);
        assert!(result.is_ok());

        // Verify original fields preserved
        assert_eq!(json["model"], serde_json::json!("gpt-4"));
        assert_eq!(json["stream"], serde_json::json!(false));
        assert_eq!(json["n"], serde_json::json!(2));
        assert_eq!(json["top_k"], serde_json::json!(50));
        assert_eq!(json["separate_reasoning"], serde_json::json!(false));
        assert_eq!(json["stream_reasoning"], serde_json::json!(true));

        // Verify batch bootstrap fields for n=2
        let bootstrap_hosts = json["bootstrap_host"].as_array().unwrap();
        assert_eq!(bootstrap_hosts.len(), 2);
        assert_eq!(bootstrap_hosts[0], serde_json::json!("chat-server"));
        assert_eq!(bootstrap_hosts[1], serde_json::json!("chat-server"));

        let bootstrap_ports = json["bootstrap_port"].as_array().unwrap();
        assert_eq!(bootstrap_ports.len(), 2);
        assert_eq!(bootstrap_ports[0], serde_json::json!(9999));
        assert_eq!(bootstrap_ports[1], serde_json::json!(9999));

        let bootstrap_rooms = json["bootstrap_room"].as_array().unwrap();
        assert_eq!(bootstrap_rooms.len(), 2);
        // Rooms should be different (randomness)
        assert_ne!(bootstrap_rooms[0], bootstrap_rooms[1]);
    }
2271
}