Skip to content

[llm][kv][7/N] Prefill/decode token load aware request routing - #64400

Merged
kouroshHakha merged 7 commits into
masterfrom
load-tracking
Jul 10, 2026
Merged

kouroshHakha merged 7 commits into
masterfrom
load-tracking

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Follow-up to #64327, the KV-aware router previously scored candidates on KV-cache overlap only; this PR feeds each request's lifecycle into Dynamo's SelectionService so scoring also accounts for per-worker token load.

  • KVRouterActor books a reservation per routed request (create_reservation) and applies engine lifecycle hooks:
    • prefill_complete shifts load prefill→decode
    • add_output_block books decode blocks as generation crosses block boundaries (weighted by a decay fraction from expected_output_tokens)
    • free_reservation releases on completion.
  • RequestTokenTracker forwards sampling_params.max_tokens as the admission-time expected output length.
image

How the token-load score works

For each candidate worker the selection service computes a cost and routes to the lowest.

cost(worker) = prefill_load_scale · max(0, prefill_blocks − overlap_credit) + decode_blocks
  • prefill_blocks: (worker's in-flight prefill tokens + this request's prompt tokens) / block_size, booked by create_reservation and dropped by prefill_complete when decode begins. overlap_credit subtracts the blocks already KV-cached on that worker, so a cache hit cheapens prefill.
  • prefill_load_scale (default 1.0) sets how hard prefill backlog is penalized.
  • decode_blocks: the worker's active decode-block count. One added per crossed KV-block boundary by add_output_block, each weighted by its request's decay fraction max(0, 1 − output/expected), so requests near completion barely count.
  • free_reservation releases both terms on completion.

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements request lifecycle tracking and active load booking for KV-aware routing in Ray LLM. It introduces a RequestLifecycle dataclass to track in-flight request states and updates KVRouterActor to book reservations, update decode progress, and free reservations in the selection service. Additionally, token_tracking.py is updated to pass the expected output tokens, and extensive tests are added to validate these behaviors. The review feedback highlights three key areas for improvement: addressing a potential memory leak in _effective_prefill_tokens_by_request when requests are cancelled or fail prematurely, improving robustness in token tracking to prevent exceptions from disrupting the core engine stream, and ensuring _get_decay_fraction safely handles negative or zero values for expected output tokens.

Base automatically changed from request-lifecycle-tracking to master July 1, 2026 20:16
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Jul 7, 2026
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 marked this pull request as ready for review July 7, 2026 07:04
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner July 7, 2026 07:04
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm labels Jul 7, 2026
Signed-off-by: Jeffrey Wang <[email protected]>
"worker_id": worker_id,
"token_ids": token_ids,
"expected_output_tokens": expected_output_tokens,
"effective_prefill_tokens": effective_prefill_tokens,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Routing and lifecycle IDs differ

Medium Severity

select_worker stores effective_prefill_tokens under Serve’s routing request_id, but lifecycle hooks admit load under get_serve_request_id() or the vLLM engine id. When those differ—as with separate direct-streaming hops or missing X-Request-Id—create_reservation gets effective_prefill_tokens as None, so booked prefill load can disagree with the overlap-aware routing score.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a58e516. Configure here.

@kouroshHakha kouroshHakha left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

leaving manual review

# Actors defined in a test module are pickled by reference, so a worker on
# another node would have to import this module to load them, which fails.
# Pickle it by value so the actor classes ship in full and run on any node.
ray.cloudpickle.register_pickle_by_value(sys.modules[__name__])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this needed? I am not sure you need this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated the comment with the reasoning, but yeah I'm not sure how to get around this 🤔

# Actors defined in a test module are pickled by reference, so a worker on
# another node would have to import this module to load them, which fails.
# Pickle it by value so the actor classes ship in full and run on any node.

@kouroshHakha kouroshHakha left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach is sound — and the three-level test coverage (mock service, e2e, real Dynamo on GPU) is great. Just a few important questions that need to be resolved or addressed:

  1. One failing hook can drop other requests' events. Now that the lifecycle hooks call into the live selection service (and do arithmetic on self._block_size), they can raise — e.g. create_reservation for a worker that hasn't registered yet at cold start, or _block_size still None when a token-less request gets randomly routed before the first LongPoll snapshot. on_lifecycle_events applies the batch in a plain loop, so one failure aborts the rest of the batch and the forwarder drops it wholesale — and a dropped on_request_completed for an unrelated request in the same batch leaks its reservation in the selection service permanently, biasing all future routing away from that worker. Interestingly the release-test subclass already wraps each event in its own try/except to keep one failure from poisoning the rest — production should probably be at least as defensive. Can we do per-event try/except (log + continue), plus skipping the hooks when _svc/_block_size are unset?

  2. _effective_prefill_tokens_by_request can grow unbounded until the follow-up lands. I saw the reply on the Gemini thread — agreed the map goes away once the selection service caches select() results, but in the interim: a request that's routed but never starts generate() on the replica (client disconnects while queued, replica dies, backpressure timeout) never fires on_request_added or on_request_completed, so its entry lives forever in the long-running router actor. If the follow-up is imminent, punting is fine — otherwise a cheap cap + FIFO evict (or purging on remove_worker) is a few lines.

Note

This review was co-written with AI assistance (Claude Code).

@jeffreywang88

Copy link
Copy Markdown
Contributor Author

One failing hook can drop other requests' events

addressed in f3a3579 with per-event try/except and skipped the hooks when _svc / block_size are unset.

_effective_prefill_tokens_by_request can grow unbounded until the follow-up land

the removal of this will come 2 PRs later as we rely on dynamo's selection service to track booking metadata such as effective prefill tokens between select (replica selection) and create_reservation (book request on a replica to track its token load). not going to cheap cap + FIFO evict in this PR.

Signed-off-by: Jeffrey Wang <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 9c3dea2. Configure here.

@kouroshHakha
kouroshHakha merged commit 1d27192 into master Jul 10, 2026
3 checks passed
@kouroshHakha
kouroshHakha deleted the load-tracking branch July 10, 2026 17:56
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests llm serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

2 participants