-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathpd_router.rs
More file actions
1715 lines (1546 loc) · 64 KB
/
Copy pathpd_router.rs
File metadata and controls
1715 lines (1546 loc) · 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
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
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
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
996
997
998
999
1000
use std::{sync::Arc, time::Instant};
use async_trait::async_trait;
use axum::{
body::Body,
extract::Request,
http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
};
use futures_util::StreamExt;
use memchr::memmem;
use reqwest::Client;
use serde::Serialize;
use serde_json::{json, Value};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tracing::{debug, error, warn};
use super::pd_types::api_path;
use crate::{
config::types::RetryConfig,
core::{
is_retryable_status, HashRing, RetryExecutor, Worker, WorkerLoadGuard, WorkerRegistry,
WorkerType, UNKNOWN_MODEL_ID,
},
observability::{
events::{self, Event},
metrics::{bool_to_static_str, metrics_labels, Metrics},
otel_trace::inject_trace_context_http,
},
policies::{LoadBalancingPolicy, PolicyRegistry, SelectWorkerInfo},
protocols::{
chat::{ChatCompletionRequest, ChatMessage, MessageContent},
classify::ClassifyRequest,
common::{InputIds, StringOrArray},
completion::CompletionRequest,
embedding::EmbeddingRequest,
generate::GenerateRequest,
rerank::RerankRequest,
},
routers::{
error,
grpc::utils::{error_type_from_status, route_to_endpoint},
header_utils,
streaming_utils::BreakerTrackedStream,
RouterTrait,
},
};
#[derive(Debug)]
pub struct PDRouter {
pub worker_registry: Arc<WorkerRegistry>,
pub policy_registry: Arc<PolicyRegistry>,
pub client: Client,
pub retry_config: RetryConfig,
pub api_key: Option<String>,
pub enable_igw: bool,
}
#[derive(Clone)]
struct PDRequestContext<'a> {
route: &'static str,
batch_size: Option<usize>,
is_stream: bool,
return_logprob: bool,
request_text: Option<String>,
model_id: Option<&'a str>,
headers: Option<HeaderMap>,
}
/// Marker placed on a `Response` by paths inside
/// `execute_dual_dispatch_internal` that have already recorded prefill and
/// decode breaker outcomes against the workers' actual per-side results
/// (rather than the final response status). The outer dispatcher reads this
/// and skips its own status-based `record_outcome` calls so a decode-only
/// transport failure can't be misattributed to a healthy prefill.
#[derive(Clone, Copy)]
struct BreakerOutcomesRecorded;
impl PDRouter {
async fn proxy_to_first_prefill_worker(
&self,
endpoint: &str,
headers: Option<Vec<(String, String)>>,
) -> Response {
let workers = self.worker_registry.get_prefill_workers();
let first_worker_url = workers.first().map(|w| w.url().to_string());
if let Some(worker_url) = first_worker_url {
self.proxy_to_worker(worker_url, endpoint, headers).await
} else {
error::service_unavailable("no_prefill_servers", "No prefill servers available")
}
}
async fn proxy_to_worker(
&self,
worker_url: String,
endpoint: &str,
headers: Option<Vec<(String, String)>>,
) -> Response {
let url = format!("{}/{}", worker_url, endpoint);
let mut request_builder = self.client.get(&url);
if let Some(headers) = headers {
for (name, value) in headers {
request_builder = request_builder.header(name, value);
}
}
match request_builder.send().await {
Ok(res) if res.status().is_success() => {
let response_headers = header_utils::preserve_response_headers(res.headers());
match res.bytes().await {
Ok(body) => {
let mut response = Response::new(Body::from(body));
*response.status_mut() = StatusCode::OK;
*response.headers_mut() = response_headers;
response
}
Err(e) => {
error!("Failed to read response body: {}", e);
error::internal_error(
"read_response_body_failed",
format!("Failed to read response body: {}", e),
)
}
}
}
Ok(res) => {
let status = StatusCode::from_u16(res.status().as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
// Use the status code to determine which error function to use
match status {
StatusCode::BAD_REQUEST => error::bad_request(
"server_bad_request",
format!("Server returned status: {}", res.status()),
),
StatusCode::NOT_FOUND => error::not_found(
"server_not_found",
format!("Server returned status: {}", res.status()),
),
StatusCode::INTERNAL_SERVER_ERROR => error::internal_error(
"server_internal_error",
format!("Server returned status: {}", res.status()),
),
StatusCode::SERVICE_UNAVAILABLE => error::service_unavailable(
"server_unavailable",
format!("Server returned status: {}", res.status()),
),
StatusCode::BAD_GATEWAY => error::bad_gateway(
"server_bad_gateway",
format!("Server returned status: {}", res.status()),
),
_ => error::internal_error(
"server_error",
format!("Server returned status: {}", res.status()),
),
}
}
Err(e) => {
error!("Failed to proxy request server: {}", e);
error::internal_error(
"proxy_request_failed",
format!("Failed to proxy request: {}", e),
)
}
}
}
pub async fn new(ctx: &Arc<crate::app_context::AppContext>) -> Result<Self, String> {
Ok(PDRouter {
worker_registry: Arc::clone(&ctx.worker_registry),
policy_registry: Arc::clone(&ctx.policy_registry),
client: ctx.client.clone(),
retry_config: ctx.router_config.effective_retry_config(),
api_key: ctx.router_config.api_key.clone(),
enable_igw: ctx.router_config.enable_igw,
})
}
fn handle_server_selection_error(error: String) -> Response {
error!("Failed to select PD pair error={}", error);
error::service_unavailable(
"server_selection_failed",
format!("No available servers: {}", error),
)
}
fn handle_serialization_error(error: impl std::fmt::Display) -> Response {
error!("Failed to serialize request error={}", error);
error::internal_error("serialization_failed", "Failed to serialize request")
}
fn get_generate_batch_size(req: &GenerateRequest) -> Option<usize> {
// GenerateRequest doesn't support batch via arrays, only via input_ids
if let Some(InputIds::Batch(batches)) = &req.input_ids {
if !batches.is_empty() {
return Some(batches.len());
}
}
None
}
fn get_chat_batch_size(req: &ChatCompletionRequest) -> Option<usize> {
if let Some(n) = req.n {
if n > 1 {
return Some(n as usize);
}
}
None
}
fn get_completion_batch_size(req: &CompletionRequest) -> Option<usize> {
if let StringOrArray::Array(arr) = &req.prompt {
if !arr.is_empty() {
return Some(arr.len());
}
}
None
}
// Static key strings to avoid per-request allocations
const BOOTSTRAP_HOST_KEY: &'static str = "bootstrap_host";
const BOOTSTRAP_PORT_KEY: &'static str = "bootstrap_port";
const BOOTSTRAP_ROOM_KEY: &'static str = "bootstrap_room";
fn inject_bootstrap_into_value(
mut original: Value,
prefill_worker: &dyn Worker,
batch_size: Option<usize>,
) -> Result<Value, String> {
let obj = original
.as_object_mut()
.ok_or_else(|| "Request must be a JSON object".to_string())?;
if let Some(n) = batch_size {
let mut hosts = Vec::with_capacity(n);
let mut ports = Vec::with_capacity(n);
let mut rooms = Vec::with_capacity(n);
for _ in 0..n {
hosts.push(prefill_worker.bootstrap_host());
ports.push(prefill_worker.bootstrap_port());
rooms.push(super::pd_types::generate_room_id());
}
// Use static string keys to avoid per-request allocations
obj.insert(
Self::BOOTSTRAP_HOST_KEY.to_string(),
Value::Array(hosts.into_iter().map(Value::from).collect()),
);
obj.insert(
Self::BOOTSTRAP_PORT_KEY.to_string(),
Value::Array(
ports
.into_iter()
.map(|p| match p {
Some(v) => Value::from(v),
None => Value::Null,
})
.collect(),
),
);
obj.insert(
Self::BOOTSTRAP_ROOM_KEY.to_string(),
Value::Array(rooms.into_iter().map(Value::from).collect()),
);
} else {
// Use static string keys to avoid per-request allocations
obj.insert(
Self::BOOTSTRAP_HOST_KEY.to_string(),
Value::from(prefill_worker.bootstrap_host()),
);
obj.insert(
Self::BOOTSTRAP_PORT_KEY.to_string(),
match prefill_worker.bootstrap_port() {
Some(v) => Value::from(v),
None => Value::Null,
},
);
obj.insert(
Self::BOOTSTRAP_ROOM_KEY.to_string(),
Value::from(super::pd_types::generate_room_id()),
);
}
Ok(original)
}
async fn execute_dual_dispatch<T: Serialize + Clone>(
&self,
headers: Option<&HeaderMap>,
original_request: &T,
context: PDRequestContext<'_>,
) -> Response {
let start_time = Instant::now();
let route = context.route;
let model = context.model_id.unwrap_or(UNKNOWN_MODEL_ID);
let endpoint = route_to_endpoint(route);
// Record request start (Layer 2)
Metrics::record_router_request(
metrics_labels::ROUTER_HTTP,
metrics_labels::BACKEND_PD,
metrics_labels::CONNECTION_HTTP,
model,
endpoint,
bool_to_static_str(context.is_stream),
);
// Clone request once outside the retry loop, then use Arc to share across attempts
// This avoids O(retries) clones by sharing the same data
let shared_request = Arc::new(original_request.clone());
let response = RetryExecutor::execute_response_with_retry(
&self.retry_config,
{
move |attempt: u32| {
// Clone Arc (cheap reference count increment) instead of cloning the entire request
let shared_request = Arc::clone(&shared_request);
let context = context.clone();
async move {
let (prefill, decode) = match self
.select_pd_pair(
context.request_text.as_deref(),
context.model_id,
context.headers.as_ref(),
)
.await
{
Ok(pair) => pair,
Err(e) => {
return Self::handle_server_selection_error(e);
}
};
debug!(
"PD retry attempt {} using prefill={} decode={}",
attempt,
prefill.url(),
decode.url()
);
let mut json_request = match serde_json::to_value(shared_request.as_ref()) {
Ok(v) => v,
Err(e) => return Self::handle_serialization_error(e),
};
json_request = match Self::inject_bootstrap_into_value(
json_request,
prefill.as_ref(),
context.batch_size,
) {
Ok(v) => v,
Err(e) => return Self::handle_serialization_error(e),
};
let ctx_is_stream = context.is_stream;
let response = self
.execute_dual_dispatch_internal(
headers,
json_request,
context,
Arc::clone(&prefill),
Arc::clone(&decode),
start_time,
)
.await;
let status = response.status();
let outcomes_already_recorded = response
.extensions()
.get::<BreakerOutcomesRecorded>()
.is_some();
if !outcomes_already_recorded {
let not_error = status.is_success() || status.is_client_error();
// Prefill is always non-streaming and fully read before
// we get here, so its outcome is final.
prefill.record_outcome(not_error);
// Decode for a streaming request is still mid-flight at
// this point; the `BreakerTrackedStream` wrapped around
// its byte stream records the outcome on drop. Skip the
// eager success record to avoid masking "200-then-broken"
// decode workers.
if !ctx_is_stream {
decode.record_outcome(not_error);
}
}
// Record worker errors for server errors (5xx)
if status.is_server_error() {
let error_type = error_type_from_status(status);
Metrics::record_worker_error(
metrics_labels::WORKER_PREFILL,
metrics_labels::CONNECTION_HTTP,
error_type,
);
Metrics::record_worker_error(
metrics_labels::WORKER_DECODE,
metrics_labels::CONNECTION_HTTP,
error_type,
);
}
response
}
}
},
|res, _attempt| is_retryable_status(res.status()),
|delay, attempt| {
// Layer 3 worker metrics (PD mode uses both prefill and decode workers)
Metrics::record_worker_retry(metrics_labels::WORKER_PREFILL, endpoint);
Metrics::record_worker_retry(metrics_labels::WORKER_DECODE, endpoint);
Metrics::record_worker_retry_backoff(attempt, delay);
},
|| {
Metrics::record_worker_retries_exhausted(metrics_labels::WORKER_PREFILL, endpoint);
Metrics::record_worker_retries_exhausted(metrics_labels::WORKER_DECODE, endpoint);
},
)
.await;
// Record Layer 2 metrics
let duration = start_time.elapsed();
if response.status().is_success() {
Metrics::record_router_duration(
metrics_labels::ROUTER_HTTP,
metrics_labels::BACKEND_PD,
metrics_labels::CONNECTION_HTTP,
model,
endpoint,
duration,
);
} else if !is_retryable_status(response.status()) {
Metrics::record_router_error(
metrics_labels::ROUTER_HTTP,
metrics_labels::BACKEND_PD,
metrics_labels::CONNECTION_HTTP,
model,
endpoint,
error_type_from_status(response.status()),
);
}
response
}
async fn handle_decode_error_response(
&self,
res: reqwest::Response,
context: &PDRequestContext<'_>,
prefill: Arc<dyn Worker>,
decode: Arc<dyn Worker>,
) -> Response {
let status = res.status();
if context.is_stream {
// Handle streaming error response
let response_headers = header_utils::preserve_response_headers(res.headers());
let error_payload = match res.bytes().await {
Ok(error_body) => match serde_json::from_slice::<Value>(&error_body) {
Ok(error_json) => {
json!({ "message": error_json, "status": status.as_u16() })
}
Err(parse_err) => {
let body_text = String::from_utf8_lossy(&error_body).to_string();
let preview: String = body_text.chars().take(256).collect();
tracing::warn!(
"Failed to parse decode error body as JSON from {}: {} \
(status={}, body preview: {:?})",
decode.url(),
parse_err,
status.as_u16(),
preview
);
json!({ "message": body_text, "status": status.as_u16() })
}
},
Err(e) => {
json!({ "message": format!("Decode server error: {}", e), "status": status.as_u16() })
}
};
let sse_data = format!(
"data: {{'error': {}}}",
serde_json::to_string(&error_payload).unwrap_or_default()
);
let error_stream = tokio_stream::once(Ok(axum::body::Bytes::from(sse_data)));
self.create_streaming_response(
error_stream,
status,
None,
context.return_logprob,
Some(response_headers),
prefill,
decode,
)
} else {
// Handle non-streaming error response
match res.bytes().await {
Ok(error_body) => {
// Try to parse error message from body, fallback to status-based error
let error_message = if let Ok(error_json) =
serde_json::from_slice::<Value>(&error_body)
{
if let Some(msg) = error_json
.get("error")
.and_then(|e| e.get("message"))
.and_then(|m| m.as_str())
{
msg.to_string()
} else if let Some(msg) = error_json.get("message").and_then(|m| m.as_str())
{
msg.to_string()
} else {
String::from_utf8_lossy(&error_body).to_string()
}
} else {
String::from_utf8_lossy(&error_body).to_string()
};
let status_code = StatusCode::from_u16(status.as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
match status_code {
StatusCode::BAD_REQUEST => {
error::bad_request("decode_bad_request", error_message)
}
StatusCode::NOT_FOUND => {
error::not_found("decode_not_found", error_message)
}
StatusCode::INTERNAL_SERVER_ERROR => {
error::internal_error("decode_internal_error", error_message)
}
StatusCode::SERVICE_UNAVAILABLE => {
error::service_unavailable("decode_unavailable", error_message)
}
StatusCode::BAD_GATEWAY => {
error::bad_gateway("decode_bad_gateway", error_message)
}
_ => error::internal_error("decode_error", error_message),
}
}
Err(e) => {
let error_message = format!("Decode server error: {}", e);
let status_code = StatusCode::from_u16(status.as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
match status_code {
StatusCode::BAD_REQUEST => {
error::bad_request("decode_read_failed", error_message)
}
StatusCode::NOT_FOUND => {
error::not_found("decode_read_failed", error_message)
}
StatusCode::INTERNAL_SERVER_ERROR => {
error::internal_error("decode_read_failed", error_message)
}
StatusCode::SERVICE_UNAVAILABLE => {
error::service_unavailable("decode_read_failed", error_message)
}
StatusCode::BAD_GATEWAY => {
error::bad_gateway("decode_read_failed", error_message)
}
_ => error::internal_error("decode_read_failed", error_message),
}
}
}
}
}
// Internal method that performs the actual dual dispatch (without retry logic)
async fn execute_dual_dispatch_internal(
&self,
headers: Option<&HeaderMap>,
json_request: Value,
context: PDRequestContext<'_>,
prefill: Arc<dyn Worker>,
decode: Arc<dyn Worker>,
_start_time: Instant,
) -> Response {
// For non-streaming: use guard for automatic load management
// For streaming: load will be managed in create_streaming_response
let _prefill_guard =
(!context.is_stream).then(|| WorkerLoadGuard::new(prefill.clone(), headers));
let _decode_guard =
(!context.is_stream).then(|| WorkerLoadGuard::new(decode.clone(), headers));
let mut headers_with_trace = headers.cloned().unwrap_or_default();
inject_trace_context_http(&mut headers_with_trace);
let headers = Some(&headers_with_trace);
// Build both requests
let prefill_request = self.build_post_with_headers(
&self.client,
prefill.url(),
context.route,
&json_request,
headers,
false,
);
let decode_request = self.build_post_with_headers(
&self.client,
decode.url(),
context.route,
&json_request,
headers,
false,
);
// Send both requests concurrently and wait for both
// Note: Using borrowed references avoids heap allocation
events::RequestPDSentEvent {
prefill_url: prefill.url(),
decode_url: decode.url(),
}
.emit();
let (prefill_result, decode_result) =
tokio::join!(prefill_request.send(), decode_request.send());
events::RequestReceivedEvent {}.emit();
// Process decode response
match decode_result {
Ok(res) => {
let status = StatusCode::from_u16(res.status().as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
debug!("Decode response status: {}", status);
if !status.is_success() {
error!(
"Decode server returned error status decode_url={} status={}",
decode.url(),
status
);
// Per-worker breaker attribution before the synthetic 5xx
// response takes over. Prefill ran concurrently in the
// `tokio::join!`: tick it based on its actual response
// status, not on the decode-driven failure. For
// non-streaming the response carries no tracked stream
// so record decode's outcome here too — but treat 4xx
// as a client fault rather than a worker fault, matching
// the legacy outer-dispatcher rule and the streaming
// `BreakerTrackedStream` pre-mark in
// `create_streaming_response`. For streaming
// `handle_decode_error_response` wraps the synthetic
// error SSE in a `BreakerTrackedStream` that ticks
// decode on drop, so skip to avoid double-counting.
// Mark the response so the outer dispatcher skips its
// status-derived `record_outcome`.
let prefill_ok = match &prefill_result {
Ok(r) => {
let s = r.status();
s.is_success() || s.is_client_error()
}
Err(_) => false,
};
prefill.record_outcome(prefill_ok);
if !context.is_stream {
let decode_ok = status.is_success() || status.is_client_error();
decode.record_outcome(decode_ok);
}
let mut response = self
.handle_decode_error_response(res, &context, prefill, decode)
.await;
response.extensions_mut().insert(BreakerOutcomesRecorded);
return response;
}
// Process prefill response
let prefill_body = if context.return_logprob {
match self
.process_prefill_response(
prefill_result,
prefill.url(),
context.return_logprob,
)
.await
{
Ok((_, body)) => body,
Err(error_response) => return error_response,
}
} else {
// Even if we don't need logprobs, we should check prefill status
match self
.process_prefill_response(prefill_result, prefill.url(), false)
.await
{
Ok((_, body)) => body,
Err(error_response) => return error_response,
}
};
if context.is_stream {
// Streaming response
let prefill_logprobs = if context.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()
})
} else {
None
};
let response_headers = header_utils::preserve_response_headers(res.headers());
self.create_streaming_response(
res.bytes_stream(),
status,
prefill_logprobs,
context.return_logprob,
Some(response_headers),
prefill,
decode,
)
} else {
// Non-streaming response
if context.return_logprob {
self.process_non_streaming_response(
res,
status,
context.return_logprob,
prefill_body,
)
.await
} else {
// Direct passthrough when no logprobs needed
let response_headers =
header_utils::preserve_response_headers(res.headers());
match res.bytes().await {
Ok(decode_body) => {
let mut response = Response::new(Body::from(decode_body));
*response.status_mut() = status;
*response.headers_mut() = response_headers;
response
}
Err(e) => {
error!("Failed to read decode response: {}", e);
error::internal_error(
"read_response_failed",
"Failed to read response",
)
}
}
}
}
}
Err(e) => {
error!(
decode_url = %decode.url(),
error = %e,
"Decode request failed"
);
// Decode failed at TCP/transport level. No tracked
// stream will ever wrap a response (streaming path) and
// we shortcut past the outer non-streaming
// `record_outcome` too — so record decode failure
// directly. Prefill ran concurrently in the
// `tokio::join!`: record its real per-worker outcome
// (success on a 2xx/4xx send, failure on transport
// error) so the decode-driven 502 doesn't penalise a
// healthy prefill. Mark the response so the outer
// dispatcher skips its status-derived `record_outcome`
// and we don't double-count.
decode.record_outcome(false);
let prefill_ok = match &prefill_result {
Ok(res) => {
let s = res.status();
s.is_success() || s.is_client_error()
}
Err(_) => false,
};
prefill.record_outcome(prefill_ok);
let mut response = error::bad_gateway(
"decode_server_error",
format!("Decode server error: {}", e),
);
response.extensions_mut().insert(BreakerOutcomesRecorded);
response
}
}
}
fn policies_need_request_text(&self) -> bool {
let prefill_policy = self.policy_registry.get_prefill_policy();
let decode_policy = self.policy_registry.get_decode_policy();
prefill_policy.needs_request_text() || decode_policy.needs_request_text()
}
async fn select_pd_pair(
&self,
request_text: Option<&str>,
model_id: Option<&str>,
headers: Option<&HeaderMap>,
) -> Result<(Arc<dyn Worker>, Arc<dyn Worker>), String> {
let effective_model_id = if !self.enable_igw { None } else { model_id };
debug!(
"Selecting PD pair: enable_igw={}, model_id={:?}, effective_model_id={:?}",
self.enable_igw, model_id, effective_model_id
);
let prefill_workers = if let Some(model) = effective_model_id {
self.worker_registry
.get_by_model(model)
.iter()
.filter(|w| matches!(w.worker_type(), WorkerType::Prefill { .. }))
.cloned()
.collect()
} else {
self.worker_registry.get_prefill_workers()
};
let decode_workers = if let Some(model) = effective_model_id {
self.worker_registry
.get_by_model(model)
.iter()
.filter(|w| matches!(w.worker_type(), WorkerType::Decode))
.cloned()
.collect()
} else {
self.worker_registry.get_decode_workers()
};
let prefill_policy = self.policy_registry.get_prefill_policy();
let decode_policy = self.policy_registry.get_decode_policy();
// Get cached hash ring for consistent hashing
let hash_ring = self
.worker_registry
.get_hash_ring(effective_model_id.unwrap_or(UNKNOWN_MODEL_ID));
let prefill = Self::pick_worker_by_policy_arc(
&prefill_workers,
&*prefill_policy,
request_text,
headers,
hash_ring.clone(),
"prefill",
)
.await?;
let decode = Self::pick_worker_by_policy_arc(
&decode_workers,
&*decode_policy,
request_text,
headers,
hash_ring,
"decode",
)
.await?;
// Record worker selection metrics (Layer 3)
let model = model_id.unwrap_or(UNKNOWN_MODEL_ID);
Metrics::record_worker_selection(
metrics_labels::WORKER_PREFILL,
metrics_labels::CONNECTION_HTTP,
model,
prefill_policy.name(),
);
Metrics::record_worker_selection(
metrics_labels::WORKER_DECODE,
metrics_labels::CONNECTION_HTTP,
model,
decode_policy.name(),
);
Ok((prefill, decode))
}
async fn pick_worker_by_policy_arc(
workers: &[Arc<dyn Worker>],
policy: &dyn LoadBalancingPolicy,
request_text: Option<&str>,
headers: Option<&HeaderMap>,
hash_ring: Option<Arc<HashRing>>,
worker_type: &str,
) -> Result<Arc<dyn Worker>, String> {
if workers.is_empty() {
return Err(format!(
"No {} workers available. Please check if {} servers are configured and healthy.",
worker_type, worker_type
));
}
let available_workers: Vec<Arc<dyn Worker>> = workers
.iter()
.filter(|w| w.is_available())
.cloned()
.collect();
if available_workers.is_empty() {
return Err(format!(
"No available {} workers (all circuits open or unhealthy)",
worker_type
));
}
let selected_idx = policy
.select_worker(
&available_workers,
&SelectWorkerInfo {
request_text,
tokens: None, // HTTP doesn't have tokens, use gRPC for PrefixHash
headers,
hash_ring,
},
)
.await
.ok_or_else(|| {
format!(
"Policy {} failed to select a {} worker",
policy.name(),
worker_type
)
})?;
Ok(available_workers[selected_idx].clone())
}
#[allow(clippy::too_many_arguments)]
fn create_streaming_response(
&self,
stream: impl futures_util::Stream<Item = Result<bytes::Bytes, reqwest::Error>> + Send + 'static,
status: StatusCode,
prefill_logprobs: Option<Value>,
return_logprob: bool,
headers: Option<HeaderMap>,
prefill: Arc<dyn Worker>,
decode: Arc<dyn Worker>,
) -> Response {
use crate::core::AttachedBody;
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
// Uses select! to race stream.next() against tx.closed() so that
// when the client disconnects the upstream HTTP connection is dropped
// promptly, allowing the engine to abort the request.
// `biased;` drains a ready upstream chunk before observing client
// disconnect, so a chunk already produced by reqwest reaches the
// client (and the logprob merger) before we tear the loop down.
//
// The upstream stream is wrapped in `BreakerTrackedStream` so the
// decode worker's circuit breaker is updated once on drop: success
// on clean completion (`[DONE]` sentinel or `None`), failure on
// stream error, neither on client disconnect. PD's pre-PR semantics
// treated 4xx (client error) as not-a-worker-fault, so we only
// pre-mark the wrapper as Errored on 5xx — `handle_decode_error_response`
// synthesizes a single-chunk SSE error envelope that would otherwise
// stream cleanly to None and record a spurious success.
let mut tracked =
BreakerTrackedStream::new(stream, Arc::clone(&decode), decode.url().to_string());
if !(status.is_success() || status.is_client_error()) {
tracked.mark_errored();
}
let decode_for_log = decode.clone();
tokio::spawn(async move {
loop {
tokio::select! {
biased;
chunk_result = tracked.next() => {
match chunk_result {
Some(Ok(chunk)) => {
let is_done = memmem::find(&chunk, b"data: [DONE]").is_some();
let result = if return_logprob && prefill_logprobs.is_some() {
Self::merge_streaming_logprobs(prefill_logprobs.clone(), &chunk)
.unwrap_or(chunk)
} else {
chunk
};
// Mark the wrapper completed before the client
// send: upstream finished cleanly regardless of
// whether the client is still listening, and
// the worker deserves the success tick either
// way. `mark_completed` is a no-op once Errored
// is set, so the synthetic-error path is unaffected.
if is_done {
tracked.mark_completed();
}
if tx.send(Ok(result)).is_err() {
tracing::debug!(
"Receiver dropped (likely client disconnect), \
cancelling upstream PD stream"
);
break;
}
if is_done {
break;
}
}
Some(Err(e)) => {
// BreakerTrackedStream already logged the error
// and marked the terminal state as Errored so