Skip to content

[llm][kv][6/N] Enable token-level request lifecycle tracking - #64327

Merged
kouroshHakha merged 34 commits into
masterfrom
request-lifecycle-tracking
Jul 1, 2026
Merged

kouroshHakha merged 34 commits into
masterfrom
request-lifecycle-tracking

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the plumbing that reports each request's token lifecycle from the vLLM engine to the deployment-scoped KVRouterActor, so a follow-up PR can feed in-flight load back into KV-aware routing decisions.

  • KVRouterActor lifecycle hooks : The hooks are no-ops on this branch; their bodies (booking load into the selection service) land in the follow-up. The wiring/ordering is established and tested in isolation here.
  • enable_token_tracking: wraps vLLM's AsyncLLM so every generate() stream emits those events. Applied only on KV-aware deployments; other deployments get the bare engine, so there's no per-request overhead where it isn't used.
image

Token-tracking mechanics

enable_token_tracking(AsyncLLM) subclasses the engine and intercepts generate(). Per request, a RequestTokenTracker observes the output stream and emits:

  • on_request_added(request_id, worker_id, prompt_token_ids): at admission, before the first token.
  • on_prefill_complete(request_id): on the first output token (prefill→decode transition).
  • on_decode_progress(request_id, cumulative_output_tokens): once per step that produces new tokens, carrying the exact running total.
  • on_request_completed(request_id): once, on normal end / early close / error.

Delivery goes through a per-replica LifecycleEventForwarder with events. Events that pile up during an in-flight call coalesce into the next batch, and actor failures are swallowed so the token stream is never disrupted.

Why we only handle DELTA and FINAL_ONLY (not CUMULATIVE)

vLLM's OpenAI serving layer sets SamplingParams.output_kind directly from the request's stream flag:

output_kind = RequestOutputKind.DELTA if request.stream else RequestOutputKind.FINAL_ONLY

As a result, the tracker only sees:

  • DELTA (streaming): each chunk contains only newly generated tokens.
  • FINAL_ONLY (non-streaming): a single final chunk containing the complete output.

Both modes are effectively new-tokens-per-chunk, so progress can be computed by simply accumulating token counts across chunks. Chunks with no new tokens contribute 0 and are ignored.

The third mode, CUMULATIVE, repeats the entire output-so-far in every chunk. Although it is the default SamplingParams value, the OpenAI serving layer never uses it, so it never reaches the tracker. Supporting it would require different accounting logic (tracking the latest total rather than summing deltas), which we intentionally do not implement.

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.

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

@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 for KV-aware routing by introducing a token tracking mechanism that reports prefill, decode, and completion events to the KVRouterActor. The feedback recommends safeguarding _get_prompt_token_ids against non-dictionary prompt types to prevent potential runtime crashes, and suggests upgrading the logging level from debug to warning for dropped lifecycle events and disabled token tracking to enhance production observability.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@jeffreywang88
jeffreywang88 marked this pull request as ready for review June 26, 2026 23:15
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner June 26, 2026 23:15
@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Jun 27, 2026
…ation

# Conflicts:
#	release/llm_tests/kv_router_test/test_kv_event_ingestion.py
#	release/llm_tests/kv_router_test/test_kv_events.py
# Conflicts:
#	python/ray/llm/_internal/serve/core/ingress/builder.py
#	python/ray/llm/_internal/serve/core/ingress/router.py
#	python/ray/llm/_internal/serve/core/ingress/tokenizer.py
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/utils.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/test_router.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/test_tokenizer.py
#	release/llm_tests/kv_router_test/test_kv_events.py
# Conflicts:
#	python/ray/llm/_internal/serve/routing_policies/kv_aware/utils.py
#	python/ray/llm/tests/serve/cpu/deployments/routers/kv/test_kv_aware_router.py
#	release/llm_tests/kv_router_test/test_kv_events.py
Signed-off-by: Jeffrey Wang <[email protected]>
Base automatically changed from kv-scoring to pre-routing-tokenization June 29, 2026 16:09
Base automatically changed from pre-routing-tokenization to master June 30, 2026 04:59
Brings the request-lifecycle-tracking branch up to date with master, which
landed the pre-routing tokenization & KV cache aware routing work (#64224)
that this branch had developed in separate commits.

Conflict resolutions (adopt master's finalized shared infra; keep the
branch's unique request-lifecycle / token-tracking additions on top):

- core/ingress/builder.py, vllm_engine.py, test_request_lifecycle_tracking.py:
  converge on master's canonical is_kv_aware(llm_config) API, dropping the
  branch's equivalent is_kv_aware_routing(request_router_config) helper.
- kv_aware/kv_aware_router.py: take master's choose_replicas behavior
  (route token-less requests to a random replica) over the branch's earlier
  strict ValueError design, and its is_kv_aware() definition.
- tests/.../kv/test_kv_aware_router.py: take master's random-routing tests
  to match the adopted behavior.
- kv_aware/kv_aware_actor.py: keep the branch's on_lifecycle_events dispatch
  and the lifecycle hook signatures the token-tracking forwarder calls.
- release/.../test_kv_event_ingestion.py: take master's no-arg
  LocalKVRouterActor.remote() (block_size now flows via kv_event_metadata).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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 1 potential issue.

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 e50395c. Configure here.

"""Cancel the delivery task on engine shutdown."""
if self._delivery_task is not None:
self._delivery_task.cancel()
self._delivery_task = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Close allows duplicate delivery loop

Medium Severity

LifecycleEventForwarder.close() cancels the delivery task and immediately sets _delivery_task to None, while the cancelled task may still be running. A later report() (for example from tracker.finish() on in-flight generate() during engine shutdown) starts a second _deliver loop on the same queue, so two coroutines can consume and batch events concurrently and break the ordering guarantees the actor relies on.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit e50395c. Configure here.

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Jun 30, 2026
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

@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.

Clean, well-structured plumbing PR. The design choices are well-reasoned: batch delivery with a single per-replica task prevents head-of-line blocking; the DELTA/FINAL_ONLY vs CUMULATIVE distinction is clearly documented; and LifecycleEventForwarder correctly isolates actor failures from the token stream. Lifecycle hooks being intentional no-ops here is fine. Test coverage is comprehensive — error isolation, early close, zero-token requests, CUMULATIVE skip, and order guarantees are all covered.

One non-inline note: KVRouterActor._schedule (already in master) uses asyncio.ensure_future() for its task reference pattern. For the pure-coroutine case, asyncio.create_task() is the modern equivalent — more explicit, attaches cleanly to the running loop, supports task naming. Worth a follow-up cleanup.

Note

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

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

Copy link
Copy Markdown
Contributor Author

Tracking the following with #64389 (comment).

One non-inline note: KVRouterActor._schedule (already in master) uses asyncio.ensure_future() for its task reference pattern. For the pure-coroutine case, asyncio.create_task() is the modern equivalent — more explicit, attaches cleanly to the running loop, supports task naming. Worth a follow-up cleanup.

Signed-off-by: Jeffrey Wang <[email protected]>
@kouroshHakha
kouroshHakha enabled auto-merge (squash) July 1, 2026 19:33
@kouroshHakha
kouroshHakha merged commit 4f1b322 into master Jul 1, 2026
4 checks passed
@kouroshHakha
kouroshHakha deleted the request-lifecycle-tracking branch July 1, 2026 20:16
elliot-barn pushed a commit that referenced this pull request Jul 9, 2026
Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…ject#64327)

Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: 400Ping <[email protected]>
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