DEP: Stage-based routing coordination
Area
router
1. Summary
PR #14570 shares worker-selection logic between the frontend and EPP. Each still coordinates stages separately.
Introduce a RoutingCoordinator to select compatible workers and manage their reservations. It supports selecting all stages upfront or selecting the next stage as execution progresses. The frontend sends requests to workers; EPP returns destinations and routing headers. Each adapter manages its reservations and cleanup.
2. Motivation
The current code mixes coordination with host and backend behavior:
| Current behavior | Limitation |
|---|---|
| The frontend wires Encode → Prefill → Decode into the request pipeline. | Adding a stage requires changing pipeline construction and discovery logic. |
| PrefillRouter selects P, dispatches it, handles the transfer, and constrains D. | EPP cannot reuse this coordination without also taking on frontend execution behavior. |
Conditional disaggregation previews D through its RoutingHost. |
The conditional decision is coupled to the frontend. |
| Decode configuration is changed inside the prefill path. | Stage scoring and load accounting are partly controlled by another stage's implementation. |
| Runtime EPP reserves P, queries D, and separately records D load. | It implements its own P/D ordering and reservation lifecycle. |
| Standalone EPP builds an aggregate selector; Encode uses a runtime round-robin router. | The hosts do not yet share a general stage interface. |
These references describe checkout 7d9ab7bc5c, which includes #14570 and later changes.
3. Goals and Non-Goals
Goals
- Support named stages, including Agg, P/D, and E/P/D.
- Share coordination between frontend and EPP, with upfront or step-by-step selection.
- Apply taints, placement rules, and caller restrictions across stages.
- Support preview-based decisions, including conditional disaggregation.
- Configure selection per stage and allow custom Rust coordination policies alongside Filter → Score → Pick policies.
- Share admission and reservation handling; keep execution, retries, and transfer cleanup in adapters.
- Let stages overlap once the next stage's inputs are ready.
- Preserve compatibility and efficiency: avoid duplicate selections, load accounting, and KV lookups.
Non-Goals
- Replace
SelectionCore, its scheduler, or worker-selection plugins. - Build a general workflow engine or scripting language.
- Find a globally optimal combination of workers.
- Support arbitrary backend protocols through headers alone.
- Split a stage across multiple workers (deferred).
- Expose custom execution scheduling, recovery, or placement plugins.
4. Proposal
4.1 High-Level Architecture and Responsibilities
flowchart TD
T[Topology: branches and handoff dependencies] --> C[RoutingCoordinator]
P[Policy: selection order, branch, profiles] --> C
B[StageBindings and prepared request] --> C
C --- S[RouteSession]
C --> SS[StageSelector per stage]
SS --> SC[SelectionService / SelectionCore]
SC --> WP[WorkerSelectionPolicy]
C -->|Ready target and reservation| F[Frontend adapter]
C -->|DelegatedPlan and reservations| E[EPP adapter]
F --> RT[Runtime dispatch, streams, and cleanup]
E --> H[Destinations, headers, and request guard]
F -. Handoff readiness and routing-relevant failures .-> C| Term | Responsibility |
|---|---|
Topology |
Define execution paths, stage dependencies, and placement rules. |
StageBinding |
Connect a stage to its worker pool, selector, settings, and capabilities. |
RoutingCoordinator |
Select workers, enforce constraints, and return stages ready to run. |
CoordinationPolicy |
Choose selection order, execution path, and selection profiles. |
RouteSession |
Track previews, selections, reservations, and stage readiness for one request. |
StageSelector |
Preview or select and reserve a worker. |
DelegatedPlan |
Give EPP the selected workers, execution path, dependencies, and reservations. |
SelectionService / SelectionCore |
Provide worker registration, indexing, admission, and load tracking. |
WorkerSelectionPolicy |
Run Filter → Score → Pick within a stage's eligible workers. |
| Frontend adapter | Send requests to selected workers and manage their execution and cleanup. |
| EPP adapter | Return destinations and headers; manage reservations using observed responses. |
The coordinator lives in lib/kv-router/src/coordination/ without runtime or ext-proc dependencies. Host adapters live in lib/llm and deploy/inference-gateway/ext-proc.
4.2 Stages, Topology, and Configuration
Each named stage (StageId) has a worker pool and selection profiles—the settings used to choose a worker. WorkerType supplies defaults. Stages can share a role or pool; stages sharing a pool also share capacity accounting.
An invocation (InvocationId) is a stage's work for one request. Initially, each stage has one invocation and selects one worker per attempt.
Topology defines execution paths (branches) and dependencies. Fixed flows use a configured branch; conditional policies choose one before admission. Previews can run first.
A handoff provides data or transfer information needed by the next stage. In P/D, D may be selected before P but must wait for P's handoff to run. P may still be running then.
| Stage | Default selection | Accounted work |
|---|---|---|
| Agg | Existing aggregate policy | Prefill and decode |
| P | KV overlap and prefill load | Prefill |
| D after remote prefill | Decode load | Decode |
| D with local prefill | Cache-aware selection | Prefill and decode |
| E | Round-robin initially | Supported encoder load signals |
Profiles are fixed at setup and chosen per request. Scoring and accounting are independent: disabling KV scoring does not remove prompt-load accounting. Separate pools keep separate selection state.
4.3 Interface Sketch
These Rust stubs show the contracts; supporting fields and error handling are omitted.
struct StageBinding {
id: StageId,
selector: Arc<dyn StageSelector>,
profiles: StageProfiles,
capabilities: StageCapabilities,
}
struct SelectedTarget {
invocation: InvocationId, // Logical stage invocation, stable across retries.
stage: StageId,
pool: PoolRef, // Retains the selected binding generation.
worker: WorkerWithDpRank,
facts: Arc<WorkerFacts>, // Metadata for this worker instance.
}
struct Preview {
target: SelectedTarget,
signals: SelectionSignals,
}
#[must_use]
struct StageReservation {
target: SelectedTarget,
signals: SelectionSignals,
lease: ReservationLease, // Owns cleanup of this exact attempt.
}
enum AdmissionTarget {
AnyEligible,
FromPreview(Preview), // Reserve this worker/rank or fail.
}
#[async_trait]
trait StageSelector: Send + Sync {
async fn preview(&self, input: SelectionInput<'_>) -> Result<Preview>;
async fn admit(
&self,
input: SelectionInput<'_>,
target: AdmissionTarget,
) -> Result<StageReservation>;
}
trait CoordinationPolicy: Send {
fn next(&mut self, view: &CoordinationView<'_>) -> Result<CoordinationOp>;
}
enum CoordinationOp {
Preview(SelectionIntent),
Admit(AdmissionIntent),
SelectBranch(BranchId), // Choose a branch declared by the topology.
Wait, // Await routing input needed for selection.
Finish, // No further selection decisions.
}
impl RoutingCoordinator {
fn start(&self, request: RoutingRequest, mode: PlanningMode) -> Result<RouteSession>;
async fn advance(
&self,
session: &mut RouteSession,
event: HostEvent,
) -> Result<HostAction>;
async fn plan_all(&self, request: RoutingRequest) -> Result<DelegatedPlan>;
}SelectionInput carries stage inputs, request/invocation/attempt IDs, the profile, work accounting, and routing restrictions such as priority, affinity, pins, and allowlists. Prompt data is shared across stages.
| Policy operation | Meaning |
|---|---|
Preview |
Inspect a candidate and its cache/load signals without reserving it or creating an affinity binding. |
Admit |
Select and reserve a worker, or reserve the exact worker/rank from a preview. |
SelectBranch |
Choose a configured execution path. |
Wait |
Wait for information needed for selection; stages already ready may still run. |
Finish |
End selection decisions. Execution and cleanup may continue. |
advance returns a worker and reservation ready for dispatch, waits for more input, or reports routing complete. The host reports handoffs, dispatch acceptance, and failures or cancellation that affect remaining selections. The coordinator derives Execute actions from topology; policies cannot dispatch work or change dependencies.
plan_all returns a complete plan without dispatching. It rejects policies that need execution results before finishing selection. Reservation ownership, preview validation, and failure handling are defined in §6.
4.4 Compiled Coordination Policies
CoordinationPolicy chooses the next stage, execution path, and selection profile. WorkerSelectionPolicy chooses a worker for that stage.
Register custom Rust policies by name, as with WorkerSelectionPolicyRegistry. Each request gets its own policy state. Built-ins cover Agg, P-first, D-first, progressive P/D, conditional disaggregation, and Encode; existing conditional-disaggregation checks can be reused.
Policies can use request facts, capabilities, previews, selections, and handoffs. EPP requires a policy that can select all workers before execution starts.
4.5 Cross-Stage Routing Constraints
Placement rules connect stages:
| Rule | Behavior |
|---|---|
SameDomain(key, Required) |
Require the same domain, such as a rack. |
SameDomain(key, Preferred) |
Prefer the same domain using a configured weight. |
TransferCompatible |
Require compatible backend transfer metadata. |
Shared functions filter candidates and validate selected pairs using the same rules, in either selection order. New rules require code changes.
- Combine required constraints, intersect allowlists, and preserve exact pins.
- Keep preferences optional and define how their weights combine.
- Apply caller restrictions to the intended stage. A gateway destination subset may not describe the encoder or prefill pool.
- Check both workers' transfer requirements for E → P and P → D, including D-first selection.
Missing required metadata or no eligible workers produces a placement error. Changes to selections and retry limits follow §6.
4.6 Frontend and EPP Adapters
The frontend sends requests to selected workers without selecting again. It owns their reservations, response streams, accounting, retries, cancellation, and buffer cleanup. Backend payloads and results stay here; it reports events needed for remaining selections.
EPP converts a complete plan into destinations and headers (x-dynamo-* or supported backend headers such as x-prefiller-host-port). It owns the reservations and uses observed responses for accounting and cleanup. Downstream workers handle execution and transfer cleanup. EPP rejects unsupported plans. A plan without P includes instructions for local prefill when the backend requires them. It does not invent per-stage completion events.
5. Request Flows Through the Proposed Interfaces
E, P, and D mean Encode, Prefill, and Decode. In these examples, policies select workers; the coordinator produces Execute actions. Finish ends selection, not execution.
5.1 Aggregated Serving
A single stage uses the same coordination interface.
sequenceDiagram
participant H as Frontend
participant C as Coordinator
participant A as Agg selector
C->>A: Admit request
A-->>C: Reserved target
C-->>H: Ready target and reservation
H->>H: Dispatch and supervise response
C-->>H: Routing complete
H->>H: Finish execution and cleanupPolicy: Admit(Agg), Finish
Coordinator: Execute(Agg) when admitted; transfer reservation
Host: Dispatch, observe response, and release reservationEPP uses plan_all to export the Agg target and reservation before execution.
5.2 Frontend/Router P/D
The progressive policy selects D after P supplies its handoff. Topology defines the P → D dependency.
sequenceDiagram
participant C as Coordinator
participant S as Stage selectors
participant H as Frontend
C->>S: Admit P
S-->>C: P target
C-->>H: Ready P target and reservation
H->>H: Dispatch P and observe its stream
H->>C: P handoff ready
C->>S: Admit D constrained by P
S-->>C: D target
C-->>H: Ready D target and reservation
H->>H: Dispatch D with P handoff
C-->>H: Routing complete
H->>H: Supervise both streams and cleanupPolicy: Admit(P)
Wait until P.handoff_ready
Admit(D, work=decode_only), Finish
Coordinator: Execute(P) when admitted
Execute(D) when admitted and P.handoff_ready
Host: Own P/D streams, pass handoff, handle failures and cleanupP may still run when D starts. If P completes the request without D, the frontend closes routing; the coordinator cancels remaining admissions and releases reservations it still owns.
5.3 EPP P/D
One coordination call chooses both workers before EPP returns its response.
sequenceDiagram
participant H as EPP
participant C as Coordinator
participant S as Stage selectors
H->>C: plan_all(request)
C->>S: Admit P
S-->>C: P target
C->>S: Admit D constrained by P
S-->>C: D target
C-->>H: Complete plan with P and D
H-->>H: Encode D destination and P routing headersAdmit(P)
Admit(D, work=decode_only)
Finish // Selection complete; export plan and reservation ownership to EPP.“All at once” means one call returns the full plan; the internal selections may be sequential.
5.4 Conditional Disaggregation
Preview D before deciding whether remote prefill is needed.
sequenceDiagram
participant C as Coordinator
participant S as Stage selectors
participant H as Host adapter
C->>S: Preview D
S-->>C: D target and cache/load signals
opt Policy needs prefill load
C->>S: Preview P
S-->>C: P load signals
end
alt Local prefill is allowed
C->>S: Admit the previewed D for local prefill/decode
C-->>H: Execute or export D
else Remote prefill
C->>S: Select P and D using configured order
C-->>H: Execute or export P/D
endPreview(D, profile=cache_aware, work=local_prefill_decode)
if bypass_condition(D.signals):
SelectBranch(local_prefill_decode)
Admit(D, FromPreview(D), work=local_prefill_decode)
Finish
else:
SelectBranch(remote_prefill_decode)
continue with the configured P/D selection orderThe selected path determines whether D needs P's handoff. Local prefill accounts for prompt work even if expected cache reuse disappears. Preview reuse and admission checks follow §6.
5.5 Encode/Prefill/Decode
Select one encoder for the request's multimodal input. Topology defines E → P → D; the frontend retains and passes the encoder result.
sequenceDiagram
participant C as Coordinator
participant S as Stage selectors
participant H as Frontend
C->>S: Admit E
S-->>C: E target
C-->>H: Ready E target and reservation
H->>H: Dispatch E and retain encoder result
H->>C: E handoff ready
C->>S: Admit P constrained by E
C-->>H: Ready P target and reservation
H->>H: Dispatch P with encoder result
H->>C: P handoff ready
C->>S: Admit D constrained by P
C-->>H: Ready D target and reservation
H->>H: Dispatch D and supervise execution
C-->>H: Routing completePolicy: Admit(E)
Wait until E.handoff_ready
Admit(P, compatible_with=E)
Wait until P.handoff_ready
Admit(D, work=decode_only, compatible_with=P), Finish
Coordinator: Execute each admitted stage when its topology inputs are ready
Host: Pass E/P handoffs and own execution and cleanup for every stageEPP can select all targets upfront with a policy that needs no execution results, when the downstream protocol supports the E/P/D handoffs.
5.6 Custom Selection Order
A compiled policy can select D first while retaining P-to-D execution dependencies.
sequenceDiagram
participant C as Coordinator
participant S as Stage selectors
participant H as Host adapter
C->>S: Admit D
S-->>C: D target
C->>S: Admit a compatible P
S-->>C: P target
C-->>H: Plan selects D then P, execution follows P handoff to DAdmit(D, work=decode_only)
Admit(P, compatible_with=D)
Finish // Selection complete; topology still gates execution on P handoff.Both workers' transfer requirements still apply. The frontend runs P before D; EPP includes that dependency in its plan.
6. Lifecycle and Correctness
Each reservation has one owner: the session, then a frontend guard before dispatch or EPP at export. That owner handles cleanup even after routing ends. Releasing a reservation does not clear affinity or free remote buffers.
Previews stay in the session; policies refer to them by invocation. Request and pool/profile definitions stay fixed. Retries keep the InvocationId and get a new attempt ID.
| Situation | Rule |
|---|---|
| Preview inputs change | Discard affected previews and update constraints when inputs, profiles, paths, or upstream selections change. |
| Admitting a previewed worker | Recheck the exact worker/rank, eligibility, required constraints, and capacity. Cache/load changes alone do not change the chosen path; local prefill must account for prompt and decode work and handle cache misses. |
| Admission or plan export fails | Bound admission retries and reservation holds by a shared deadline. Cancel affected pending work and release coordinator-owned or undispatched plan reservations. |
| Execution fails or retries | The host cleans up and decides whether retry is supported. Cancel affected routing if needed. Release the old reservation and complete required backend cleanup before retrying. Match invocation and attempt IDs so old events cannot affect the replacement. |
| Client cancels | Keep or complete admissions needed for handoff cleanup; cancel other work and release its reservations. The host completes cleanup through the coordinator-selected consumer or an explicit backend cleanup path, within the shared cleanup budget. |
| A worker or path is replaced | Discard affecte |
Source: ai-dynamo/dynamo