Skip to content

[Serve] Support ordered list of candidate multiplexed model IDs - #67095

Open
Asthenia0412 wants to merge 9 commits into
ray-project:masterfrom
Asthenia0412:feat/serve-ordered-model-ids
Open

Asthenia0412 wants to merge 9 commits into
ray-project:masterfrom
Asthenia0412:feat/serve-ordered-model-ids

Conversation

@Asthenia0412

Copy link
Copy Markdown

Background / Problem

Ray Serve's RequestMetadata.multiplexed_model_id — and the corresponding
handle.options(multiplexed_model_id=...) API — only accepts a single model
ID. Users who know several mutually-compatible model IDs (e.g. when doing LLM
routing across a small family of quantised checkpoints, or when the same request
can be satisfied by multiple fine-tuned variants) have no way to say "pick
whichever replica already has one of these models loaded". As a result they
either route to an arbitrarily-chosen replica and pay a cold-load penalty, or
load-balance naively and waste GPU memory.

Issue: #65348 — "[Serve] Support passing an ordered list of model_ids to controllers"

Solution

Add a new optional field candidate_multiplexed_model_ids: Optional[List[str]]
that flows through the whole Serve stack:

  • RequestMetadata.candidate_multiplexed_model_ids
  • DynamicHandleOptionsBase.candidate_multiplexed_model_ids
  • Public DeploymentHandle.options(...) / GenericDeploymentHandle.options(...)
    callable API

The routing changes live in MultiplexMixin (shared by every default
router, including Pow2Router and the experimental RoundRobinRouter):

  1. New helpers _get_effective_multiplexed_model_ids() and
    _get_first_available_multiplexed_model_id(). The first merges the legacy
    single multiplexed_model_id (treated as highest priority, prepended)
    with the new ordered candidate list and de-duplicates while preserving
    order. The second walks that list and returns the first model ID that
    currently has a warm replica.
  2. apply_multiplex_routing() and
    _get_pending_request_matching_multiplexed_model_id() now call those
    helpers, so both dispatch and pending-request coalescing naturally prefer
    whichever replica already hosts any of the caller's candidates.
  3. Both pow_2_router and round_robin_router recognise the new field in
    their early "has multiplexed" gates, and resolve the effective ID via
    _get_first_available_multiplexed_model_id so per-model round-robin
    counters are keyed by whichever model actually routed.

Backward compatibility

Callers that still set only multiplexed_model_id see exactly the same
behaviour
as before. When both fields are set, the single value is
treated as highest priority (prepended to the candidate list), so existing
code that mixes the two still gets deterministic results.

# New API
handle.options(candidate_multiplexed_model_ids=["model-a", "model-b", "model-c"]).remote(...)

# Old API still works unchanged
handle.options(multiplexed_model_id="model-a").remote(...)

# Mix: single value wins
handle.options(
    multiplexed_model_id="model-preferred",
    candidate_multiplexed_model_ids=["model-a", "model-b"],
).remote(...)

What is not in this PR (follow-up work)

  • HTTP ingress: the proxy currently parses serve_multiplexed_model_id from a
    single header. Adding support for comma-separated / repeated headers is out
    of scope here (can be done once this API lands).
  • gRPC / Java ingress: the proto schema would need a new repeated field. Again,
    follow-up work; the Python-side handle API is the primary user-facing path.

Testing

New tests added to python/ray/serve/tests/unit/test_round_robin_router.py:

Test What it covers
test_candidate_model_ids_picks_first_warm Router prefers the first candidate that has warm replicas, skipping cold ones
test_candidate_model_ids_fallback_when_no_warm When none of the candidates are warm, falls back to the legacy timeout-driven hierarchy
test_legacy_single_model_id_still_works Backward-compat: a single multiplexed_model_id works exactly as before
test_single_id_prepended_to_candidate_list When both are set, the single value is treated as highest priority

Run locally:

python -m pytest python/ray/serve/tests/unit/test_round_robin_router.py -v

The rest of the existing test_round_robin_router.py, test_pow_2_request_router.py,
and Serve router unit tests should continue to pass without modification — the
change is additive and preserves the legacy single-ID path.

@Asthenia0412
Asthenia0412 requested a review from a team as a code owner October 15, 2026 23:19

@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 introduces support for an ordered list of candidate multiplexed model IDs (candidate_multiplexed_model_ids) in Ray Serve's request routing, allowing the router to pick the first warm replica matching any of the candidates to reduce cold-start latency while maintaining backwards compatibility. The review feedback identifies a critical issue where pending-request coalescing is broken for candidate-only requests because they are not properly indexed in _add_pending_request_to_indices. Additionally, the feedback points out a discrepancy between the docstring and implementation of rank_replicas_via_multiplex, and a bug in the timeout fallback unit test where a new request is incorrectly instantiated instead of reusing the original request.

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

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Oct 16, 2026
@Asthenia0412
Asthenia0412 force-pushed the feat/serve-ordered-model-ids branch from 7fd7879 to fa5b7ca Compare October 16, 2026 04:29

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

Stale Bugbot comment from a previous run.

@Asthenia0412

Copy link
Copy Markdown
Author

Fixed two critical bugs: (1) pending request coalescing index was missing candidate IDs so fallback never worked, (2) resolved multiplexed_model_id was never written back to metadata so replicas saw empty strings. Could someone please re-trigger Buildkite microcheck to verify?

@Asthenia0412
Asthenia0412 force-pushed the feat/serve-ordered-model-ids branch from fa5b7ca to 0b17d7d Compare October 16, 2026 10:22
@Asthenia0412
Asthenia0412 requested review from a team as code owners October 16, 2026 10:22
@Asthenia0412
Asthenia0412 force-pushed the feat/serve-ordered-model-ids branch from c9b936c to 40f943c Compare October 17, 2026 01:27

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

Stale Bugbot comment from a previous run.

@Asthenia0412

Copy link
Copy Markdown
Author

All reviewer comments have been resolved:

gemini-code-assist comments:

  1. ✅ _add_pending_request_to_indices now indexes requests under all effective multiplexed model IDs (both the legacy single ID and the new candidate list), so candidate-only requests are properly indexed for pending-request coalescing.
  2. ✅ rank_replicas_via_multiplex docstring updated to match the implementation — it operates on a single resolved model ID, and callers should resolve the candidate list first via apply_multiplex_routing or _get_first_available_multiplexed_model_id.
  3. ✅ test_candidate_model_ids_fallback_when_no_warm now reuses the same request object across choose_replicas calls, so the timeout (anchored at multiplexed_start_matching_time = 100.0) is properly exercised when the clock advances to 102.5.

cursor bugbot comments:
All 5 issues were fixed in prior commits (already marked resolved):

  • ✅ Chosen model ID written back to metadata.multiplexed_model_id
  • ✅ Candidate requests properly indexed in _add_pending_request_to_indices
  • ✅ Test bug fixed
  • ✅ hasattr guard protects base router from mixin-only helper
  • ✅ Candidate list cleared after write-back to preserve caller ordering

Pushed an empty commit to re-trigger Buildkite microcheck.

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

Stale Bugbot comment from a previous run.

pending_request.metadata.candidate_multiplexed_model_ids
and multiplexed_model_id
):
pending_request.metadata.candidate_multiplexed_model_ids = 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.

Early model lock breaks candidate fallback

High Severity

apply_multiplex_routing writes a single resolved ID onto RequestMetadata and clears candidate_multiplexed_model_ids before any replica is assigned. The request stays indexed under every original candidate, so coalescing can hand it a replica selected for a different model while the replica still sees the locked ID and may cold-load it. Other already-warm candidates are also ignored once the first one is busy.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fa55609. Configure here.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 2, 2026
1. Index pending requests under every effective multiplexed model ID, not
   just the legacy single-value field.  Requests that only set
   candidate_multiplexed_model_ids (without multiplexed_model_id) were never
   added to _pending_requests_by_model_id, so same-model coalescing could
   never find them.

2. After resolving the effective model ID in apply_multiplex_routing,
   write it back to pending_request.metadata.multiplexed_model_id so that
   replica-side @serve.multiplexed loaders see whichever ID the router
   actually routed to.  Without this write-back the replica saw an empty
   model ID on candidate-only requests and either cold-loaded the wrong
   model or failed to multiplex at all.

Both bugs surfaced in the upstream microcheck CI.

Signed-off-by: Asthenia0412 <[email protected]>
…tiplexMixin

RequestRouter._add_pending_request_to_indices calls
self._get_effective_multiplexed_model_ids unconditionally, but that
helper lives only on MultiplexMixin. Routers that do not compose the
mixin (e.g. ConsistentHashRouter or custom RequestRouter subclasses)
raise AttributeError on every request.

Wrap the call in hasattr() with a fallback that reconstructs the
legacy single-ID behaviour. This matches the defensive pattern used
in on_replica_actor_died and update_replicas.


Signed-off-by: Asthenia0412 <[email protected]>
Three targeted fixes for bot-flagged issues on the ordered candidate model ID PR:

1. Write-back no longer inverts caller priority.
   After apply_multiplex_routing resolves an ordered candidate list to a
   warm model ID and writes it back to metadata.multiplexed_model_id, we
   now also clear candidate_multiplexed_model_ids.  Otherwise
   _get_effective_multiplexed_model_ids re-prepends the resolved ID as
   highest priority on the next call, permanently reordering the caller's
   original list so retries and pending-request coalescing could no longer
   fall back to later candidates once an earlier one warms up.

2. Fix timeout-fallback unit test to actually exercise the timeout.
   test_candidate_model_ids_fallback_when_no_warm advanced the clock then
   created a brand-new request with a fresh multiplexed_start_matching_time,
   so the timeout never elapsed.  It also reset routing_context on an
   unused object.  Now we reuse the same request across successive calls:
   one call after timeout to try the fewest-model fallback (the single
   allowed retry there), and a second call to verify it falls back to
   all replicas.

3. Correct rank_replicas_via_multiplex docstring.
   The old docstring implied the method handled ordered candidate lists
   directly, but it accepts only a single resolved model ID.  Clarify
   that apply_multiplex_routing (or _get_first_available_multiplexed_model_id)
   is the right place to do candidate-list resolution before passing a
   single ID here.

All three fixes are local to the changes already in this PR and do not
touch unrelated code paths.

Signed-off-by: Asthenia0412 <[email protected]>
All inline reviewer comments have been addressed in prior commits:
- _add_pending_request_to_indices now indexes under all effective model IDs
  with hasattr() guard for routers without MultiplexMixin
- apply_multiplex_routing writes the resolved model ID back to metadata and
  clears the candidate list to preserve caller ordering
- rank_replicas_via_multiplex docstring updated to match implementation
- test_candidate_model_ids_fallback_when_no_warm reuses the same request
  so the timeout is properly exercised


Signed-off-by: Asthenia0412 <[email protected]>
These functions were removed but are still imported by
plan_generated_id_ops.py, causing ImportError at runtime.

Signed-off-by: Asthenia0412 <[email protected]>
@Asthenia0412
Asthenia0412 force-pushed the feat/serve-ordered-model-ids branch from 9246b3d to 50e36fd Compare November 2, 2026 19:41

@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 and found 2 potential issues.

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.


For ``generated_id_column`` configs it also loads the checkpoint when
execution starts; the planned ``ListFiles`` / ``ReadFiles`` operators
read it through :meth:`load_checkpoint`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Generated-ID checkpoint load removed

High Severity

LoadCheckpointCallback no longer loads a generated-ID checkpoint at execution start and no longer exposes load_checkpoint, but Planner.plan still passes checkpoint_callback.load_checkpoint into generated-ID restore planning. Resuming a job that uses generated_id_column fails.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.

# Both root-path listing and the prelisted route must honor them.
excluded_ids = ctx.kwargs.get(EXCLUDED_READ_UNIT_IDS_KWARG_NAME)
if isinstance(excluded_ids, (pa.Array, pa.ChunkedArray)):
# A set built straight from an Arrow array holds Arrow scalars, which

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Excluded IDs skip Arrow conversion

Medium Severity

list_files_for_each_block now builds excluded_read_unit_ids with frozenset(excluded_ids) and no longer converts Arrow arrays to Python strings. plan_list_files_op_with_done_read_units still passes done_unit_ids, a pa.Array, so the frozenset holds Arrow scalars that never match string unit IDs and finished work is listed again.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 50e36fd. Configure here.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Nov 3, 2026
abrarsheikh pushed a commit that referenced this pull request Nov 18, 2026
…68085)

## Description
Ray Serve request routers never free finished multiplexed requests from
`_pending_requests_by_model_id`, so each one keeps its `args`/`kwargs`
alive.

`_remove_pending_request_from_indices` only cleans
`_pending_requests_by_id`. The model ID index relies on lazy cleanup
that only `FIFOMixin` runs, and only when a later request for the same
model ID is fulfilled. Before this fix:

- `FIFOMixin` routers, including the default
`PowerOfTwoChoicesRequestRouter`, kept the last request of every model
ID, so memory grew with the number of distinct model IDs.
- Routers without `FIFOMixin` (`ConsistentHashRouter`, `KVAwareRouter`,
`PrefixCacheAffinityRouter`, custom routers) kept every multiplexed
request, so memory grew with traffic. With Serve LLM's KV-aware or
prefix-aware routing, this happens on every LoRA request.
- Cancelling a request didn't clean the model ID index in any router.

**Fix:** every fulfilled or cancelled request already calls
`_remove_pending_request_from_indices` once its future is done. That
method now pops done entries from the front of the request's model ID
deque, and drops the key when the deque is empty. The cost stays
amortized O(1), and routing behavior doesn't change.

## Related issues
- Related to #60139, which introduced the lazy cleanup.
- Related to #67095, which extends the same index to lists of model IDs
and will need the same cleanup per ID.

## Additional information

Standalone repro (script below). Run it on master vs. this branch.
Entries left in `_pending_requests_by_model_id` after 200 finished
requests over 50 model IDs, 1 MiB args each:

| Router | Fulfilled (master → PR) | Cancelled (master → PR) |
|---|---|---|
| `PowerOfTwoChoicesRequestRouter` | 50 → 0 | 200 → 0 |
| `ConsistentHashRouter` | 200 → 0 | 200 → 0 |

<details>
<summary><code>repro_router_leak.py</code></summary>

```python
"""Count finished multiplexed requests left in `_pending_requests_by_model_id`.

Run with the Ray you want to check, e.g. on master vs. this PR's branch:
    python repro_router_leak.py
"""

import asyncio

from ray.serve._private.common import (
    DeploymentHandleSource,
    DeploymentID,
    RequestMetadata,
)
from ray.serve._private.request_router import PendingRequest
from ray.serve._private.request_router.pow_2_router import (
    PowerOfTwoChoicesRequestRouter,
)
from ray.serve._private.test_utils import FakeRunningReplica
from ray.serve._private.utils import generate_request_id
from ray.serve.experimental.consistent_hash_router import ConsistentHashRouter

NUM_REQUESTS = 200
NUM_MODEL_IDS = 50
PAYLOAD_BYTES = 1024 * 1024


async def run(router_cls, cancel: bool):
    model_ids = [f"model-{i}" for i in range(NUM_MODEL_IDS)]
    router = router_cls(
        deployment_id=DeploymentID(name="repro"),
        handle_source=DeploymentHandleSource.REPLICA,
        self_actor_id="repro-actor",
        self_actor_handle=None,
        use_replica_queue_len_cache=False,
    )
    replica = FakeRunningReplica("r1", model_ids=set(model_ids))
    replica.set_queue_len_response(0)
    router.update_replicas([replica])

    for i in range(NUM_REQUESTS):
        request = PendingRequest(
            args=[b"x" * PAYLOAD_BYTES],
            kwargs={},
            metadata=RequestMetadata(
                request_id=generate_request_id(),
                internal_request_id=generate_request_id(),
                multiplexed_model_id=model_ids[i % NUM_MODEL_IDS],
            ),
        )
        task = asyncio.create_task(router._choose_replica_for_request(request))
        if cancel:
            await asyncio.sleep(0)
            task.cancel()
        await asyncio.gather(task, return_exceptions=True)

    for task in list(router._routing_tasks):
        task.cancel()
    await asyncio.gather(*router._routing_tasks, return_exceptions=True)

    entries = [pr for dq in router._pending_requests_by_model_id.values() for pr in dq]
    assert all(pr.future.done() for pr in entries)
    return len(entries), len(entries) * PAYLOAD_BYTES / 2**20


async def main():
    print(
        f"{NUM_REQUESTS} finished requests over {NUM_MODEL_IDS} model IDs, "
        f"{PAYLOAD_BYTES // 2**20} MiB args each. Entries left in the index:"
    )
    for router_cls in (PowerOfTwoChoicesRequestRouter, ConsistentHashRouter):
        for cancel in (False, True):
            entries, mib = await run(router_cls, cancel)
            ending = "cancelled" if cancel else "fulfilled"
            print(f"  {router_cls.__name__:<32}{ending:<11}{entries:>4} ({mib:.0f} MiB)")


if __name__ == "__main__":
    asyncio.run(main())
```

</details>

---------

Signed-off-by: GNITOAHC <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant