Skip to content

[Serve] Fix ZeroDivisionError in router and AttributeError in Deployment.__eq__ - #64577

Closed
jiangxt2 wants to merge 1 commit into
ray-project:masterfrom
jiangxt2:fix/minor-serve-bugs
Closed

jiangxt2 wants to merge 1 commit into
ray-project:masterfrom
jiangxt2:fix/minor-serve-bugs

Conversation

@jiangxt2

@jiangxt2 jiangxt2 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Two boundary check bugs in Ray Serve:

  1. prefix_aware_router crashes with ZeroDivisionError when input_text is an empty string (e.g., for unsupported multimodal content that yields no extractable text). The match rate calculation len(matched_text) / len(input_text) divides by zero.

  2. Deployment.__eq__() directly accesses other._name without checking if other is a Deployment instance. Comparing a Deployment to any non-Deployment object (string, None, int) raises AttributeError.

What changes are made?

  • python/ray/llm/_internal/serve/routing_policies/prefix_aware/prefix_aware_router.py: Add empty string guard before match rate division, setting match_rate = 0.0 to trigger fallback routing
  • python/ray/serve/deployment.py: Add isinstance(other, Deployment) guard returning NotImplemented per Python's data model convention
  • python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py: Add test for empty input handling
  • python/ray/serve/tests/unit/test_schema.py: Add tests for __eq__ with non-Deployment types
  • Minor formatting adjustment in deployment_to_schema (parenthesized ternary, auto-formatted by black)

Related issues

Fixes #64573
Fixes #64574

Checks

  • I've signed off every commit (using git commit -s)
  • I've run pre-commit hooks (ruff, black, semgrep, pydoclint) to lint the changes
  • I've added tests for the new behavior

@jiangxt2
jiangxt2 requested review from a team as code owners July 7, 2026 16:53

@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 addresses two main issues: it prevents a ZeroDivisionError in the prefix-aware router when handling empty input text by checking the length of input_text before calculating the match rate, and it fixes an AttributeError in Deployment.eq by returning NotImplemented when comparing a Deployment instance with a non-Deployment object. Unit tests have been added to verify both fixes. No review comments were provided, so there is no additional feedback.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Jul 7, 2026
@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Jul 15, 2026
@abrarsheikh
abrarsheikh enabled auto-merge (squash) July 15, 2026 17:33
@jiangxt2

Copy link
Copy Markdown
Contributor Author

Thanks for the approval, @abrarsheikh!

The premerge CI has four failures, but they all appear to be pre-existing and unrelated to this PR's changes (4 Python files: a ZeroDivisionError guard in prefix_aware_router.py, an isinstance check in deployment.py.__eq__, and their tests):

  1. lint-pre-commit (g11-s0) — ESLint crashed with TypeError in @typescript-eslint/type-utils. Only touches dashboard/client/ (TypeScript frontend), nothing to do with the PR's Python-only changes.

  2. serve-haproxy-tests (g16-s18) — test_cluster::test_head_and_worker_nodes_no_replicas failed with assert 404 == 200 on /-/healthz. Tracked by flaky-tracker [CI] linux://python/ray/serve/tests:test_cluster is failing/flaky on master. #64585 — confirmed failing on master commits (6427337, 17e0dba) in postmerge.

  3. llm-gpu-tests (g12-s3) — 6 doc examples failed. All fail at vLLM deployment stage (e.g. NameError: 'SpecialTokens' in prefix_aware_example), long before routing logic is reached. Tracked by [CI] linux://python/ray/llm/tests:serve/gpu/integration/test_openai_compatibility_direct_streaming is failing/flaky on master. #63731.

  4. api-doc-consistency (g9-s4) — 3 Sphinx warnings about a missing tune_pytorch_asha document reference in tune/examples/index.rst, unrelated to serve or llm.

Locally, pre-commit run --all-files passes cleanly (including ESLint), and the PR's unit tests (test_schema.py 109 passed, test_prefix_aware_request_router.py 15 passed) all pass.

Would it be possible to trigger a re-run, or is there anything else I should do on my end?

auto-merge was automatically disabled July 21, 2026 03:24

Head branch was pushed to by a user without write access

@jiangxt2
jiangxt2 force-pushed the fix/minor-serve-bugs branch from c2b337e to a8ccf6e Compare July 21, 2026 03:24
@jiangxt2
jiangxt2 requested a review from abrarsheikh July 21, 2026 03:24
@jiangxt2
jiangxt2 force-pushed the fix/minor-serve-bugs branch 2 times, most recently from c90eabe to 643c038 Compare July 23, 2026 13:39
@jiangxt2
jiangxt2 force-pushed the fix/minor-serve-bugs branch from 643c038 to 9e83881 Compare August 4, 2026 12:17
@jiangxt2

jiangxt2 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Hi @abrarsheikh — CI is all green now. Could this be merged? Thanks!

@github-actions

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 Aug 19, 2026
@jiangxt2
jiangxt2 force-pushed the fix/minor-serve-bugs branch from 9e83881 to 8ac5f2d Compare August 19, 2026 05:37
…or in Deployment.__eq__()

Fix two boundary check bugs in Ray Serve:

1. prefix_aware_router crashes with ZeroDivisionError when input_text
   is empty (e.g., unsupported multimodal content). Added guard to set
   match_rate = 0.0 for empty input, triggering fallback routing.
2. Deployment.__eq__() raises AttributeError when compared to
   non-Deployment types. Added isinstance check returning NotImplemented
   per Python's data model convention.

Fixes ray-project#64573
Fixes ray-project#64574

Signed-off-by: jiangxt2 <[email protected]>
@jiangxt2
jiangxt2 force-pushed the fix/minor-serve-bugs branch from 8ac5f2d to da14e2d Compare August 19, 2026 08:01
@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 Aug 19, 2026
@jiangxt2 jiangxt2 closed this Oct 10, 2026
ArturNiederfahrenhorst added a commit that referenced this pull request Oct 22, 2026
…or (#66671)

PrefixCacheAffinityRouter called ray.get on its prefix tree actor inside
choose_replicas (one or two round trips per routing attempt) and in
on_request_routed, update_replicas and on_replica_actor_died. Each call
stalled the router's event loop, which every DeploymentHandle in the
process shares, so routing throughput was capped by the actor round trip
and other requests' queue length probes waited behind it.

- Await the tree lookup instead of calling ray.get, and send it before
the load check so the round trip overlaps with any queue length probes.
- Do the prefix match and the smallest-tenants fallback in one actor
call, prefix_match_or_smallest_tenants. Empty text now falls back to the
smallest tenants instead of raising ZeroDivisionError.
- Don't wait on insert, add_tenants, remove_tenants or
start_eviction_loop. The actor runs one caller's tasks in submission
order, so later lookups from this process still see them.
- Drop tree results for replicas that left while the lookup was in
flight.

### Benchmark

The release test added here,
`llm_serve_prefix_router_overhead_benchmark`
(`release/llm_tests/serve/prefix_router_overhead_benchmark.py`): 2
replicas behind `PrefixCacheAffinityRouter` (default kwargs) that reply
immediately, so only routing costs time. Prompts are ~1 KiB from 8
shared system prompts; closed-loop clients for 5 s per concurrency
level. `handle` is `handle.remote()`, as `OpenAiIngress` calls
`LLMServer`; `direct` is `handle.choose_replica(..., _reserve=False)`,
as the direct-streaming `LLMRouter` does. "Loop stall" is the p99
oversleep of a 1 ms heartbeat on the router's event loop.

Run on the release test's setup (Anyscale m5.2xlarge,
`anyscale/ray-llm:nightly-py312-cu130` at master `a4a924c1c5`), 5 rounds
alternating the image's router with this PR's (`prefix_aware_router.py`
and `prefix_tree.py` at `f4ea105b04` copied over the installed ones).
Median of 5, master → this PR:

| path | concurrency | req/s | p50 ms | p99 ms | router loop stall p99
ms |
|---|---|---|---|---|---|
| handle | 1 | 192 → 213 | 5.1 → 4.6 | 7.3 → 7.0 | 1.9 → 1.1 |
| handle | 8 | 249 → 316 | 31.5 → 24.7 | 42.9 → 36.7 | 14.3 → 5.6 |
| handle | 32 | 260 → 315 | 121.8 → 100.8 | 146.3 → 132.1 | 54.8 → 12.7
|
| handle | 64 | 256 → 312 | 242.5 → 202.9 | 320.4 → 238.9 | 143.1 → 13.1
|
| direct | 1 | 357 → 436 | 2.7 → 2.1 | 5.1 → 5.1 | 3.8 → 1.6 |
| direct | 8 | 375 → 645 | 21.1 → 11.4 | 31.6 → 29.9 | 21.6 → 5.0 |
| direct | 32 | 379 → 596 | 83.0 → 49.2 | 118.2 → 111.7 | 85.4 → 12.0 |
| direct | 64 | 370 → 794 | 165.7 → 71.6 | 461.6 → 366.3 | 455.2 → 36.1
|

On master, throughput is flat in concurrency and the loop stall grows
with it. In every round, this PR had higher throughput and a lower loop
stall than master at every level. The nightly includes #66489, so
`direct` picks also insert into the tree (with a blocking `ray.get` on
master). Because routing is now concurrent, a new prefix's first request
can be routed before earlier inserts reach the tree: on the `handle`
path the 8 prefixes split 5/3 across the 2 replicas in 2 of 5 runs with
this PR and 4/4 in all runs on master; on the `direct` path, 4/4 in all
runs for both.

### Tests

```
python -m pytest --noconftest --import-mode=importlib -q \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py
68 passed
```

Run locally on macOS (`--noconftest` because the llm `conftest.py`
imports vLLM). New tests: `TestNonBlockingTreeCalls` (3) and
`TestPrefixTreePrefixMatchOrSmallestTenants` (4). All but
`test_replica_removed_during_tree_lookup_is_not_chosen`, which guards a
window master doesn't have, fail on master.

No existing issue or PR does this (searched open PRs for
`PrefixCacheAffinityRouter`, `prefix_aware_router`,
`get_smallest_tenants`, "prefix tree actor ray.get"); #64577 fixes the
same `ZeroDivisionError`. Written with AI assistance (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
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 go add ONLY when ready to merge, run all tests 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

2 participants