push_router.rs 33.4 KB
Newer Older
1
2
3
4
5
6
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

use anyhow::Result;
7
use dynamo_kv_router::protocols::{TokensWithHashes, WorkerWithDpRank};
8
use dynamo_runtime::{
9
    dynamo_nvtx_range,
10
    metrics::frontend_perf::{STAGE_DISPATCH, STAGE_ROUTE, StageGuard},
11
12
13
14
15
16
17
18
    pipeline::{
        AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, PushRouter, ResponseStream,
        SingleIn, async_trait,
    },
    protocols::annotated::Annotated,
};
use futures::stream::{self, StreamExt};
use serde_json::json;
19
use tracing::Instrument;
20
21

use crate::{
22
23
24
25
26
27
    kv_router::{
        KvRouter,
        agent_controller::{AgentController, SessionCloseAction},
        metrics::RouterRequestMetrics,
        sticky_sessions::{InMemoryAffinityStore, StickySessionRouter},
    },
28
    preprocessor::PreprocessedRequest,
29
30
    protocols::common::{
        llm_backend::LLMEngineOutput,
31
        preprocessor::RoutingHints,
32
33
        timing::{RequestPhase, RequestTracker},
    },
34
35
36
37
38
};

pub struct KvPushRouter {
    inner: PushRouter<PreprocessedRequest, Annotated<LLMEngineOutput>>,
    pub chooser: Arc<KvRouter>,
39
40
41
42
    /// Sticky session routing. Lazily activated when requests carry session_control.
    sticky_sessions: Arc<StickySessionRouter>,
    /// Session lifecycle RPCs (open/close). Client is lazy (OnceCell).
    agent_controller: Arc<AgentController>,
43
44
45
46
47
}

/// Result of worker selection containing instance ID, dp_rank, and overlap amount.
struct WorkerSelection {
    instance_id: u64,
48
49
50
51
52
53
54
    dp_rank: u32,
    overlap_amount: u32,
    effective_overlap_blocks: f64,
    cached_tokens: usize,
    /// Whether the scheduler is tracking this request (add_request or
    /// find_best_match_details with update_states=true was called).
    scheduler_tracked: bool,
55
56
}

57
58
/// Drop guard that manages the full lifecycle of a routed request:
/// per-item tracking (prefill, first token, output blocks) and final cleanup (free + metrics).
59
60
61
62
63
64
///
/// In the happy path, `finish().await` runs cleanup inline in the async context.
/// If the stream is dropped early (e.g., client disconnect, consumer drop), the
/// `Drop` impl fires and spawns a task to call `free()`.
struct RequestGuard {
    chooser: Arc<KvRouter>,
65
    scheduler_tracked: bool,
66
67
    context_id: String,
    tracker: Option<Arc<RequestTracker>>,
68
    request_metrics: Arc<RouterRequestMetrics>,
69
70
71
    cumulative_osl: usize,
    metrics_recorded: bool,
    freed: bool,
72
73
    prefill_marked: bool,
    first_token_recorded: bool,
74
75
    first_response_received: bool,
    dispatch_guard: Option<StageGuard>,
76
77
78
79
80
    track_output_blocks: bool,
    current_total_blocks: usize,
    isl_tokens: usize,
    block_size: usize,
    expected_output_tokens: Option<u32>,
81
82
    /// Deferred session close action (fires after generation completes)
    deferred_close: Option<SessionCloseAction>,
83
84
85
86
87
    /// True once inner.direct() has returned Ok — guards record_metrics() so
    /// that a dispatch failure does not emit metrics for a request that never
    /// reached the backend (spurious requests_total increment, OSL histogram
    /// zeros, premature tracker.record_finish()).
    dispatched: bool,
88
89
}

90
impl RequestGuard {
91
    async fn on_item(&mut self, item: &Annotated<LLMEngineOutput>) {
92
93
94
95
96
97
        // End dispatch stage on first response from backend (any item, not just tokens).
        if !self.first_response_received {
            self.first_response_received = true;
            self.dispatch_guard.take();
        }

98
99
100
101
102
103
104
        if !self.prefill_marked {
            let has_tokens = item
                .data
                .as_ref()
                .map(|d| !d.token_ids.is_empty())
                .unwrap_or(false);
            if has_tokens {
105
106
107
                if self.scheduler_tracked
                    && let Err(e) = self.chooser.mark_prefill_completed(&self.context_id).await
                {
108
109
110
111
112
113
114
115
116
117
118
119
120
121
                    tracing::warn!(
                        "Failed to mark prefill completed for request {}: {e}",
                        self.context_id
                    );
                }
                self.prefill_marked = true;
            }
        }

        let new_tokens = item.data.as_ref().map(|d| d.token_ids.len()).unwrap_or(0);

        if !self.first_token_recorded && new_tokens > 0 {
            if let Some(ref tracker) = self.tracker {
                tracker.record_first_token();
122
123
124
125
126
127
                // Record decode-phase first token for KV transfer latency metric.
                // In disaggregated serving, first_token_time is locked by the prefill phase,
                // so we need a separate timestamp for the decode worker's first token.
                if tracker.phase() == RequestPhase::Decode {
                    tracker.record_decode_first_token();
                }
128
129
130
131
                if let Some(ttft) = tracker.ttft_ms() {
                    self.request_metrics
                        .time_to_first_token_seconds
                        .observe(ttft / 1000.0);
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
                }
            }
            self.first_token_recorded = true;
        }

        self.cumulative_osl += new_tokens;

        if self.track_output_blocks {
            let new_total_blocks =
                (self.isl_tokens + self.cumulative_osl).div_ceil(self.block_size);
            if new_total_blocks > self.current_total_blocks {
                let decay_fraction = self
                    .expected_output_tokens
                    .map(|eot| (1.0 - (self.cumulative_osl as f64 / eot.max(1) as f64)).max(0.0));
                if let Err(e) = self
                    .chooser
                    .add_output_block(&self.context_id, decay_fraction)
                {
                    tracing::warn!(
                        "Failed to add output block for request {}: {e}",
                        self.context_id
                    );
                }

                if let Some(ref tracker) = self.tracker {
                    tracker.record_osl(self.cumulative_osl);
                    tracker.record_finish();
159
160
161
162
                    if let Some(avg_itl) = tracker.avg_itl_ms() {
                        self.request_metrics
                            .inter_token_latency_seconds
                            .observe(avg_itl / 1000.0);
163
164
165
166
167
168
169
170
                    }
                }

                self.current_total_blocks = new_total_blocks;
            }
        }
    }

171
172
    async fn finish(&mut self) {
        self.record_metrics();
173
174
175
        if self.scheduler_tracked
            && let Err(e) = self.chooser.free(&self.context_id).await
        {
176
177
178
            tracing::warn!("Failed to free request {}: {e}", self.context_id);
        }
        self.freed = true;
179
180
181
182
183

        // Take to prevent double-fire from Drop
        if let Some(close) = self.deferred_close.take() {
            close.execute(&self.context_id);
        }
184
185
186
    }

    fn record_metrics(&mut self) {
187
188
189
190
        // Skip metrics for requests that never reached the backend (dispatch
        // failure before direct() returned Ok). Recording here would emit
        // spurious requests_total increments and OSL-histogram zeros.
        if self.metrics_recorded || !self.dispatched {
191
192
193
194
195
196
            return;
        }
        self.metrics_recorded = true;
        if let Some(ref tracker) = self.tracker {
            tracker.record_finish();
            tracker.record_osl(self.cumulative_osl);
197
198
199
200
201
202
            // Observe KV transfer estimated latency (disaggregated paths)
            if let Some(latency) = tracker.kv_transfer_estimated_latency_secs() {
                self.request_metrics
                    .kv_transfer_estimated_latency_seconds
                    .observe(latency);
            }
203
        }
204
205
206
207
208
209
210
211
212
        // Only record output sequence length for requests that actually
        // produced output tokens. Recording zero for failed/cancelled requests
        // would corrupt histogram averages (sum/count) and percentiles.
        // Failures are already tracked by requests_total.
        if self.cumulative_osl > 0 {
            self.request_metrics
                .output_sequence_tokens
                .observe(self.cumulative_osl as f64);
        }
213
        self.request_metrics.requests_total.inc();
214
215
216
217
218
219
    }
}

impl Drop for RequestGuard {
    fn drop(&mut self) {
        self.record_metrics();
220

221
222
        let deferred_close = self.deferred_close.take();
        let needs_free = !self.freed && self.scheduler_tracked;
223

224
225
        if deferred_close.is_none() && !needs_free {
            return;
226
        }
227

228
229
230
231
232
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            tracing::warn!(
                "No tokio runtime for drop guard cleanup of request {}",
                self.context_id
            );
233
            return;
234
        };
235

236
237
238
239
240
241
242
243
244
245
246
247
248
        // Mirror finish(): free the scheduler slot first, then fire the
        // deferred session close so the worker's KV isn't released while
        // generation teardown is still in progress.
        let chooser = self.chooser.clone();
        let context_id = self.context_id.clone();
        handle.spawn(async move {
            if needs_free && let Err(e) = chooser.free(&context_id).await {
                tracing::warn!("Failed to free request {context_id} (drop guard): {e}");
            }
            if let Some(close) = deferred_close {
                close.execute(&context_id);
            }
        });
249
250
251
    }
}

252
253
254
255
256
impl KvPushRouter {
    pub fn new(
        inner: PushRouter<PreprocessedRequest, Annotated<LLMEngineOutput>>,
        chooser: Arc<KvRouter>,
    ) -> Self {
257
258
259
260
        // Eagerly register router request metrics (as zeros) so they are
        // scrapeable before any requests arrive. Both the frontend pipeline
        // and the standalone router create KvPushRouter, so this covers both.
        RouterRequestMetrics::from_component(chooser.client().endpoint.component());
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
        // Agent controller manages session lifecycle RPCs (open/close).
        // Always created; the event-plane client inside is lazy (OnceCell)
        // so there is zero cost until a request actually carries session_control.
        let component = chooser.client().endpoint.component().clone();
        let agent_controller = Arc::new(AgentController::new(component));

        // Sticky sessions share expiry handling with the agent controller so
        // router-side reap also closes the worker session.
        let on_expire = {
            let controller = agent_controller.clone();
            Arc::new(move |session_id: String, worker_id: u64| {
                controller
                    .clone()
                    .close_expired_session(session_id, worker_id);
            }) as Arc<dyn Fn(String, u64) + Send + Sync>
        };
        let sticky_sessions = Arc::new(StickySessionRouter::new(
            InMemoryAffinityStore::new_with_on_expire(Some(on_expire)),
        ));

        KvPushRouter {
            inner,
            chooser,
            sticky_sessions,
            agent_controller,
        }
288
289
    }

290
291
    /// Select a worker for the request, either using an exact phase-specific pin
    /// or by finding the best KV overlap match.
292
293
294
295
296
297
298
    async fn select_worker(
        &self,
        context_id: &str,
        request: &PreprocessedRequest,
        phase: RequestPhase,
        is_query_only: bool,
    ) -> Result<WorkerSelection, Error> {
299
        let _nvtx_select = dynamo_nvtx_range!("route.select_worker");
300
301
        let routing = request.routing.as_ref();
        let lora_name = routing.and_then(|r| r.lora_name.clone());
302
        let priority_jump = routing.and_then(|r| r.priority_jump).unwrap_or(0.0);
303
        let expected_output_tokens = routing.and_then(|r| r.expected_output_tokens);
304
        let allowed_worker_ids = routing.and_then(|r| r.allowed_worker_ids.clone());
305
        let (routing_token_ids, block_mm_infos) = request.block_mm_routing_info();
306
        let Some((pinned_worker_id, requested_dp_rank)) = pinned_worker_hint(phase, routing) else {
307
            let _nvtx_kv = dynamo_nvtx_range!("route.kv_match");
308
            let selection = self
309
                .chooser
310
                .find_best_match_details(
311
                    Some(context_id),
312
313
                    routing_token_ids,
                    block_mm_infos,
314
315
316
                    request.router_config_override.as_ref(),
                    !is_query_only,
                    lora_name,
317
                    priority_jump,
318
                    expected_output_tokens,
319
                    None,
320
                    allowed_worker_ids,
321
322
                )
                .await?;
323
324
325
326
            let best_worker = selection.worker;
            let effective_overlap_blocks = selection.cache_hit.effective_overlap_blocks;
            let cached_tokens = selection.cache_hit.cached_tokens;
            let overlap_amount = selection.cache_hit.rounded_overlap_blocks();
327

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
            if !is_query_only {
                let total_blocks = routing_token_ids
                    .len()
                    .div_ceil(self.chooser.block_size() as usize);
                // NOTE: tests/mm_router/test_vllm_mm_router_e2e.py parses this log line.
                // Keep the "[ROUTING] ... with X/Y blocks overlap" shape stable unless
                // router tests are updated together.
                tracing::debug!(
                    request_id = %context_id,
                    worker_id = best_worker.worker_id,
                    dp_rank = best_worker.dp_rank,
                    overlap_blocks = overlap_amount,
                    total_blocks = total_blocks,
                    "[ROUTING] Best: worker_{} dp_rank={} with {}/{} blocks overlap",
                    best_worker.worker_id,
                    best_worker.dp_rank,
                    overlap_amount,
                    total_blocks,
                );
            }

349
350
            return Ok(WorkerSelection {
                instance_id: best_worker.worker_id,
351
352
353
354
355
                dp_rank: best_worker.dp_rank,
                overlap_amount,
                effective_overlap_blocks,
                cached_tokens,
                scheduler_tracked: !is_query_only,
356
357
358
            });
        };

359
        let resolved_pinned_worker: Option<WorkerWithDpRank> = requested_dp_rank
360
361
362
363
            .or_else(|| self.chooser.unique_dp_rank_for_worker(pinned_worker_id))
            .map(|dp_rank| WorkerWithDpRank::new(pinned_worker_id, dp_rank));

        if !is_query_only && let Some(pinned_worker) = resolved_pinned_worker {
364
            let selection = self
365
                .chooser
366
                .find_best_match_details(
367
368
369
370
371
372
373
374
375
376
377
378
                    Some(context_id),
                    routing_token_ids,
                    block_mm_infos,
                    request.router_config_override.as_ref(),
                    true,
                    lora_name.clone(),
                    priority_jump,
                    expected_output_tokens,
                    Some(pinned_worker),
                    allowed_worker_ids,
                )
                .await?;
379
380
381
382
            let best_worker = selection.worker;
            let effective_overlap_blocks = selection.cache_hit.effective_overlap_blocks;
            let cached_tokens = selection.cache_hit.cached_tokens;
            let overlap_amount = selection.cache_hit.rounded_overlap_blocks();
383
384
385

            return Ok(WorkerSelection {
                instance_id: best_worker.worker_id,
386
387
388
389
390
                dp_rank: best_worker.dp_rank,
                overlap_amount,
                effective_overlap_blocks,
                cached_tokens,
                scheduler_tracked: true,
391
392
393
            });
        }

394
395
396
397
398
        // Fallback: pinned worker hint was present but dp_rank could not be
        // resolved (or this is a query-only request that skipped the scheduler
        // path above).  Estimate cache hit directly and, when possible, register
        // the request with the scheduler for bookkeeping.
        let resolved_dp_rank: Option<u32> = resolved_pinned_worker.map(|w| w.dp_rank);
399

400
        tracing::debug!(
401
            worker_id = pinned_worker_id,
402
            dp_rank = ?resolved_dp_rank,
403
404
405
406
            ?phase,
            "Routing to specified worker"
        );

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        // Build a WorkerWithDpRank; use 0 as a fallback dp_rank when it
        // couldn't be resolved -- this is only used for the cache-hit
        // estimate query and won't affect scheduler state.
        let effective_dp_rank = resolved_dp_rank.unwrap_or(0);
        let worker = WorkerWithDpRank::new(pinned_worker_id, effective_dp_rank);
        let cache_hit = self
            .chooser
            .get_cache_hit_estimate(
                routing_token_ids,
                block_mm_infos,
                worker,
                lora_name.as_deref(),
            )
            .await?;
        let effective_overlap_blocks = cache_hit.effective_overlap_blocks;
        let cached_tokens = cache_hit.cached_tokens;
        let overlap_blocks = cache_hit.rounded_overlap_blocks();
424

425
426
        if !is_query_only {
            if let Some(_dp_rank) = resolved_dp_rank {
427
428
429
430
431
                self.chooser
                    .add_request(
                        context_id.to_string(),
                        routing_token_ids,
                        block_mm_infos,
432
                        cached_tokens,
433
434
435
436
437
438
439
440
441
                        expected_output_tokens,
                        worker,
                        lora_name,
                        request.router_config_override.as_ref(),
                    )
                    .await;
            } else {
                tracing::debug!(
                    request_id = %context_id,
442
                    worker_id = pinned_worker_id,
443
444
                    ?phase,
                    "Routing to specified worker without resolved dp_rank; skipping scheduler bookkeeping"
445
446
                );
            }
447
448
449
        } else {
            tracing::debug!(
                request_id = %context_id,
450
                worker_id = pinned_worker_id,
451
452
                dp_rank = ?resolved_dp_rank,
                "Skipping add_request - query-only request"
453
            );
454
        }
455
456

        Ok(WorkerSelection {
457
            instance_id: pinned_worker_id,
458
459
460
461
462
            dp_rank: effective_dp_rank,
            overlap_amount: overlap_blocks,
            effective_overlap_blocks,
            cached_tokens,
            scheduler_tracked: !is_query_only && resolved_dp_rank.is_some(),
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        })
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<LLMEngineOutput>>, Error>
    for KvPushRouter
{
    /// Generate method that handles KV-aware routing with three distinct behaviors:
    ///
    /// 1. **If `query_instance_id` annotation is set**:
    ///    - Returns the best matching worker ID without routing the request
    ///    - Does NOT update any router local states
    ///    - Response includes worker_instance_id and token_data annotations
    ///
478
479
480
481
    /// 2. **If a phase-specific worker or `backend_instance_id` is set in the request**:
    ///    - Query-only requests return that worker selection without state updates
    ///    - Execution requests route through the scheduler as an exact pin when dp_rank is resolved
    ///    - If dp_rank cannot be resolved, falls back to direct routing without scheduler bookkeeping
482
483
484
485
486
487
488
489
490
491
    ///
    /// 3. **If neither are set (default behavior)**:
    ///    - Finds the best worker based on KV cache overlap
    ///    - Updates router states to track the request
    ///    - Routes to the selected worker
    ///
    /// The router state updates include tracking active sequences and managing
    /// prefill/completion lifecycle for proper KV cache management.
    async fn generate(
        &self,
492
        mut request: SingleIn<PreprocessedRequest>,
493
494
495
496
497
498
499
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
        // Extract context ID for request tracking
        let context_id = request.context().id().to_string();

        // Simple query-only detection: presence of query_instance_id annotation means query-only mode
        let is_query_only = request.get_annotation_value("query_instance_id").is_some();

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
        // Resolve session affinity: if the request has a session_id, inject the
        // pinned worker_id into backend_instance_id before worker selection.
        // Skip entirely for non-session requests to keep them off the sticky path.
        if request
            .routing
            .as_ref()
            .and_then(|r| r.session_control.as_ref())
            .is_some()
            && request
                .routing
                .as_ref()
                .and_then(|r| r.backend_instance_id)
                .is_none()
            && let Some(worker_id) = self.sticky_sessions.resolve(&request)
        {
            request.routing_mut().backend_instance_id = Some(worker_id);
        }

518
519
520
521
522
523
        // Get phase from tracker (defaults to Aggregated if no tracker or phase not set)
        let phase = request
            .tracker
            .as_ref()
            .map(|t| t.phase())
            .unwrap_or(RequestPhase::Aggregated);
524
525
        let phase_label = phase.to_string();
        let route_guard = StageGuard::new(STAGE_ROUTE, &phase_label);
526
527
528

        let block_size = self.chooser.block_size() as usize;
        let selection = self
529
            .select_worker(&context_id, &request, phase, is_query_only)
530
            .instrument(tracing::info_span!("kv_router.select_worker"))
531
532
533
            .await?;
        let WorkerSelection {
            instance_id,
534
            dp_rank,
535
            overlap_amount,
536
537
538
            effective_overlap_blocks,
            cached_tokens,
            scheduler_tracked,
539
540
541
542
543
544
        } = selection;

        // In approximate mode (use_kv_events=false), record the routing decision
        // so the indexer can track cache state based on routing decisions.
        // This covers both pre-selected workers and find_best_match selections.
        if !is_query_only && !self.chooser.kv_router_config().use_kv_events {
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
            let lora_name = request.routing.as_ref().and_then(|r| r.lora_name.clone());
            let (routing_token_ids, block_mm_infos) = request.block_mm_routing_info();
            let worker = WorkerWithDpRank::new(instance_id, dp_rank);
            let mut tokens_with_hashes =
                TokensWithHashes::new(routing_token_ids.to_vec(), self.chooser.block_size())
                    .with_is_eagle(self.chooser.is_eagle());
            if let Some(infos) = block_mm_infos {
                tokens_with_hashes = tokens_with_hashes.with_mm_infos(infos.to_vec());
            }
            if let Some(lora_name) = lora_name {
                tokens_with_hashes = tokens_with_hashes.with_lora_name(lora_name);
            }
            if let Err(e) = self
                .chooser
                .record_routing_decision(tokens_with_hashes, worker)
                .await
            {
                tracing::warn!(
563
564
                    request_id = %context_id,
                    worker_id = instance_id,
565
566
567
                    dp_rank = dp_rank,
                    error = %e,
                    "Failed to record routing decision in approximate mode"
568
569
570
571
                );
            }
        }

572
        // Record routing metrics on tracker and observe ISL + prefill start.
573
574
        let request_metrics =
            RouterRequestMetrics::from_component(self.chooser.client().endpoint.component());
575
        if let Some(ref tracker) = request.tracker {
576
            let (routing_token_ids, _) = request.block_mm_routing_info();
577
            let isl_blocks = routing_token_ids.len().div_ceil(block_size);
578
579
580
            tracker.record_kv_hit(effective_overlap_blocks, isl_blocks);
            tracker.record_isl(routing_token_ids.len(), Some(cached_tokens));
            tracker.record_worker(instance_id, Some(dp_rank), self.chooser.worker_type());
581
            tracker.record_router_queue_depth(self.chooser.pending_count());
582
583
            if let Some(hit_rate) = tracker.kv_hit_rate() {
                request_metrics.kv_hit_rate.observe(hit_rate);
584
            }
585
        }
586
587
588
        request_metrics
            .input_sequence_tokens
            .observe(request.token_ids.len() as f64);
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

        // Handle query-only requests: early return with worker info
        if is_query_only {
            let stream_context = request.context().clone();
            let worker_id_info = request.tracker.as_ref().and_then(|t| t.get_worker_info());

            tracing::trace!(
                ?phase,
                worker_id = instance_id,
                ?worker_id_info,
                "Returning worker selection (query-only mode)"
            );

            let output = LLMEngineOutput {
                disaggregated_params: Some(json!({
                    "worker_id": worker_id_info,
                    "token_ids": request.token_ids
                })),
                ..Default::default()
            };
            let response = Annotated::from_data(output);
            let stream = stream::iter(vec![response]);
            return Ok(ResponseStream::new(Box::pin(stream), stream_context));
        }

614
615
616
617
618
619
        // End route stage — worker has been selected and routing metrics recorded.
        // Dispatch stage starts immediately so there is no gap between stages.
        drop(route_guard);
        let stage_dispatch_guard = StageGuard::new(STAGE_DISPATCH, &phase_label);

        // Dispatch to worker
620
621
622
623
624
        let isl_tokens = request.token_ids.len();
        let expected_output_tokens = request
            .routing
            .as_ref()
            .and_then(|r| r.expected_output_tokens);
625
        let track_output_blocks = self.chooser.kv_router_config().router_track_output_blocks;
626
        let tracker = request.tracker.clone();
627

628
629
630
631
632
633
634
635
636
637
638
639
        // Session lifecycle RPCs via agent controller.
        // Fails fast if session_control.open is requested but the client can't be created.
        let deferred_close = self
            .agent_controller
            .on_routed(
                &request,
                instance_id,
                &context_id,
                Some(&*self.sticky_sessions),
            )
            .await?;

640
        let (mut backend_input, context) = request.into_parts();
641
        backend_input.routing_mut().dp_rank = Some(dp_rank);
642
643
        let updated_request = context.map(|_| backend_input);

644
645
646
647
648
        // Record prefill start right before pushing to backend (OnceLock: first call wins).
        if let Some(ref tracker) = tracker {
            tracker.record_prefill_start();
        }

649
        let chooser = self.chooser.clone();
650
651
652
653
654
655
656
657
658
659
660
661
662

        // Build the guard BEFORE calling direct() so that its Drop covers the
        // error path as well as the drop-before-first-poll path.
        //
        // Without this, if direct().await? below returns Err, both the
        // scheduler slot (booked by find_best_match with update_states=true)
        // and the SessionCloseAction (obtained above via on_routed) are leaked:
        // SessionCloseAction has no Drop impl, so dropping it never sends the
        // close_session RPC; chooser.free() is only called via RequestGuard::Drop.
        //
        // All guard fields are available here (deferred_close was just obtained;
        // isl_tokens/block_size/tracker were set before request.into_parts()).
        let mut guard = RequestGuard {
663
664
665
666
667
668
669
670
671
672
            chooser: chooser.clone(),
            scheduler_tracked,
            context_id: context_id.clone(),
            tracker: tracker.clone(),
            request_metrics: request_metrics.clone(),
            cumulative_osl: 0,
            metrics_recorded: false,
            freed: false,
            prefill_marked: false,
            first_token_recorded: false,
673
674
            first_response_received: false,
            dispatch_guard: Some(stage_dispatch_guard),
675
676
677
678
679
680
            track_output_blocks: scheduler_tracked && track_output_blocks,
            current_total_blocks: isl_tokens.div_ceil(block_size),
            isl_tokens,
            block_size,
            expected_output_tokens,
            deferred_close,
681
            dispatched: false,
682
        };
683

684
685
686
687
688
689
690
        let mut response_stream = self
            .inner
            .direct(updated_request, instance_id)
            .instrument(tracing::info_span!(
                "kv_router.route_request",
                request_id = %context_id,
                worker_id = instance_id,
691
692
                dp_rank = dp_rank,
                overlap_blocks = overlap_amount,
693
694
695
696
697
698
699
700
701
702
703
                phase = ?phase,
            ))
            .await?;
        // direct() succeeded — mark dispatched so record_metrics() fires.
        // If direct() returned Err above, guard drops here with dispatched=false
        // → RequestGuard::Drop fires → chooser.free() + deferred_close.execute()
        //   but record_metrics() is suppressed (no backend work was done).
        guard.dispatched = true;
        let stream_context = response_stream.context();
        let context_for_monitoring = stream_context.clone();

704
        let wrapped_stream = Box::pin(async_stream::stream! {
705
706
            // Move guard into the stream closure. Drop fires here if the stream
            // is polled to completion, or via the outer Drop if never polled.
707
            let mut guard = guard;
708
709
710
711
712
713
714
715
716
717
718
719
720
721

            loop {
                tokio::select! {
                    biased;

                    _ = context_for_monitoring.stopped() => {
                        tracing::debug!("Request {context_id} cancelled, ending stream");
                        break;
                    }

                    item = response_stream.next() => {
                        let Some(item) = item else {
                            break;
                        };
722
                        guard.on_item(&item).await;
723
724
725
726
727
                        yield item;
                    }
                }
            }

728
            guard.finish().await;
729
730
731
732
        });
        Ok(ResponseStream::new(wrapped_stream, stream_context))
    }
}
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
/// Extract a phase-specific (worker_id, dp_rank) pin from routing hints.
///
/// Returns `Some((worker_id, optional_dp_rank))` when the request should be
/// pinned to a particular worker, or `None` when the normal KV-overlap
/// selection path should be used.
fn pinned_worker_hint(
    phase: RequestPhase,
    routing: Option<&RoutingHints>,
) -> Option<(u64, Option<u32>)> {
    let routing = routing?;
    match phase {
        RequestPhase::Prefill => {
            let worker_id = routing.prefill_worker_id.or(routing.backend_instance_id)?;
            let dp_rank = routing.prefill_dp_rank.or(routing.dp_rank);
            Some((worker_id, dp_rank))
        }
        RequestPhase::Decode => {
            let worker_id = routing.decode_worker_id.or(routing.backend_instance_id)?;
            let dp_rank = routing.dp_rank;
            Some((worker_id, dp_rank))
        }
        RequestPhase::Aggregated => {
            let worker_id = routing.backend_instance_id?;
            let dp_rank = routing.dp_rank;
            Some((worker_id, dp_rank))
        }
    }
}

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
/// A direct routing wrapper for `RouterMode::Direct`.
///
/// This wraps a `PushRouter` and reads worker IDs from each request's routing hints,
/// then routes directly to the specified worker. Used when an external router
/// (e.g., EPP) handles worker selection.
pub struct DirectRoutingRouter {
    inner: PushRouter<PreprocessedRequest, Annotated<LLMEngineOutput>>,
}

impl DirectRoutingRouter {
    pub fn new(inner: PushRouter<PreprocessedRequest, Annotated<LLMEngineOutput>>) -> Self {
        DirectRoutingRouter { inner }
    }

    /// Extract worker ID from request routing hints.
    /// Returns an error if no worker ID is found (required in direct routing mode).
    fn get_worker_id(request: &PreprocessedRequest) -> Result<u64, Error> {
        let routing = request.routing.as_ref();
        let worker_id = routing.and_then(|r| r.decode_worker_id.or(r.backend_instance_id));

        worker_id.ok_or_else(|| {
            anyhow::anyhow!(
                "Worker ID required (--direct-route) but none found in request. \
                 Expected decode_worker_id or backend_instance_id to be set by external router (e.g., EPP)."
            )
        })
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<LLMEngineOutput>>, Error>
    for DirectRoutingRouter
{
    async fn generate(
        &self,
        request: SingleIn<PreprocessedRequest>,
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
        let worker_id = Self::get_worker_id(&request)?;

        tracing::debug!(worker_id = worker_id, "Direct routing to specified worker");

        self.inner.direct(request, worker_id).await
    }
}
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

#[cfg(test)]
mod tests {
    use super::pinned_worker_hint;
    use crate::protocols::common::{preprocessor::RoutingHints, timing::RequestPhase};

    #[test]
    fn pinned_worker_hint_prefill_uses_prefill_worker_before_backend() {
        let routing = RoutingHints {
            backend_instance_id: Some(1),
            prefill_worker_id: Some(2),
            dp_rank: Some(3),
            prefill_dp_rank: Some(4),
            ..Default::default()
        };

        let hint = pinned_worker_hint(RequestPhase::Prefill, Some(&routing));
        assert_eq!(hint, Some((2, Some(4))));
    }

    #[test]
    fn pinned_worker_hint_decode_uses_decode_worker_before_backend() {
        let routing = RoutingHints {
            backend_instance_id: Some(1),
            decode_worker_id: Some(5),
            dp_rank: Some(6),
            ..Default::default()
        };

        let hint = pinned_worker_hint(RequestPhase::Decode, Some(&routing));
        assert_eq!(hint, Some((5, Some(6))));
    }

    #[test]
    fn pinned_worker_hint_aggregated_uses_backend_worker() {
        let routing = RoutingHints {
            backend_instance_id: Some(9),
            dp_rank: Some(7),
            ..Default::default()
        };

        let hint = pinned_worker_hint(RequestPhase::Aggregated, Some(&routing));
        assert_eq!(hint, Some((9, Some(7))));
    }
}