Skip to content

[Serve] Run sync deployment methods in a thread pool - #66436

Merged
eicherseiji merged 2 commits into
masterfrom
seiji/serve-sync-threadpool-default
Sep 29, 2026
Merged

eicherseiji merged 2 commits into
masterfrom
seiji/serve-sync-threadpool-default

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Run synchronous deployment methods in a thread pool by default so blocking synchronous I/O does not block the replica event loop. RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0 retains the legacy behavior for deployments whose shared state is not thread-safe.

Environment variable master After this PR
RAY_SERVE_RUN_SYNC_IN_THREADPOOL OFF ON

The opt-in warning has been emitted since #48897 merged on November 26, 2024—667 days (about 22 months) before this default swap. This provided an extended migration period for users to make synchronous deployment code thread-safe or convert it to async def.

The documentation now describes thread safety requirements and the opt-out. This default was previously enabled in #61229 and reverted in #61369.

Related PRs

These default changes are independent and can merge in any order:

Tests

  • RAY_USE_UVLOOP=0 python -m pytest -q python/ray/serve/tests/test_replica_sync_methods.py: 9 passed. The executor-introspection cases target the standard asyncio loop used by this Bazel test.
  • Updated the thread-pool test target description
  • Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs style, and import-order checks

Duplicate search

I searched open Ray PRs for this environment variable and found no active duplicate.

AI assistance

AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready.

@eicherseiji
eicherseiji force-pushed the seiji/serve-llm-replica-defaults branch from 74c26a6 to a772a06 Compare September 23, 2026 23:15
@eicherseiji
eicherseiji force-pushed the seiji/serve-sync-threadpool-default branch 2 times, most recently from 6b94cdc to 4492e5a Compare September 24, 2026 00:21
@eicherseiji
eicherseiji force-pushed the seiji/serve-llm-replica-defaults branch 2 times, most recently from 1b0d010 to d48a9a1 Compare September 24, 2026 01:03
@eicherseiji
eicherseiji force-pushed the seiji/serve-sync-threadpool-default branch from 4492e5a to 4e3ca5c Compare September 24, 2026 01:03
@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Sep 24, 2026
@eicherseiji
eicherseiji force-pushed the seiji/serve-llm-replica-defaults branch from d48a9a1 to feb7664 Compare September 24, 2026 17:31
@eicherseiji
eicherseiji force-pushed the seiji/serve-sync-threadpool-default branch 2 times, most recently from 8f5912d to 0fe7989 Compare September 24, 2026 18:28
@eicherseiji
eicherseiji force-pushed the seiji/serve-llm-replica-defaults branch 2 times, most recently from f381235 to 641444c Compare September 24, 2026 18:33
@eicherseiji
eicherseiji force-pushed the seiji/serve-sync-threadpool-default branch from 0fe7989 to 2ffca3e Compare September 24, 2026 18:33
@eicherseiji
eicherseiji changed the base branch from seiji/serve-llm-replica-defaults to master September 24, 2026 18:33
@eicherseiji
eicherseiji force-pushed the seiji/serve-sync-threadpool-default branch from 2ffca3e to c7835a1 Compare September 24, 2026 22:14
@eicherseiji
eicherseiji marked this pull request as ready for review September 24, 2026 22:18
@eicherseiji
eicherseiji requested review from a team as code owners September 24, 2026 22:18
@eicherseiji eicherseiji self-assigned this Sep 24, 2026

@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 changes the default behavior of RAY_SERVE_RUN_SYNC_IN_THREADPOOL from 0 to 1, meaning synchronous methods in a deployment will now run in a threadpool by default. The documentation, warning messages, and test configurations have been updated accordingly. Feedback on these changes suggests removing or silencing the warning message when a user explicitly opts out by setting the flag to 0 to avoid spam, and adding test coverage for the legacy/opt-out behavior (RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0) in the CI suite.

Comment on lines +645 to 648
"Calling sync method '{method_name}' directly on the asyncio loop because "
"RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0. This can block other requests. Make "
"the method `async def` or restore threadpool dispatch by setting "
"RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1."

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.

medium

Now that RAY_SERVE_RUN_SYNC_IN_THREADPOOL defaults to 1, setting it to 0 is an explicit opt-out by the user to retain legacy behavior. Emitting a warning (RAY_SERVE_RUN_SYNC_IN_THREADPOOL_WARNING) when the user has explicitly opted out is spammy and defeats the purpose of providing a clean opt-out mechanism. We should consider removing this warning entirely, or refactoring the replica initialization logic so that the warning is only emitted if the user is running sync methods on the event loop without having explicitly set the environment variable (which is no longer possible since the default is 1). Since we want to support RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0 as a silent fallback for non-thread-safe deployments, this warning should be removed or silenced.


# Test currently off-by-default behavior to run replica sync methods in a threadpool.
# TODO(edoakes): remove this once the FF is flipped on by default.
# Test the default behavior that runs replica sync methods in a threadpool.

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.

medium

Since RAY_SERVE_RUN_SYNC_IN_THREADPOOL now defaults to 1, the default test suite will already run with this behavior enabled. However, the legacy/opt-out behavior (RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0) is now completely untested in the CI. We should update this test target (or add a new one) to run with RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0 to ensure that the opt-out path is actively tested and does not regress.

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation labels Sep 25, 2026
@abrarsheikh

Copy link
Copy Markdown
Contributor

just adding here for reference, with this change the microbenchmarks will look worse. But we are okay with that because the microbench are not representative of real workloads.

@eicherseiji
eicherseiji enabled auto-merge (squash) September 28, 2026 22:27
@eicherseiji
eicherseiji merged commit e430ec9 into master Sep 29, 2026
7 checks passed
@eicherseiji
eicherseiji deleted the seiji/serve-sync-threadpool-default branch September 29, 2026 00:07
eicherseiji added a commit that referenced this pull request Sep 30, 2026
## Description

Apply the performance-oriented replica defaults only to the default Ray
Serve LLM path. General Serve defaults remain unchanged.

| Serve LLM setting | `master` | After this PR |
| --- | --- | --- |
| OpenAI ingress model-handle transport | `ray.remote` | gRPC |
| `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | ON | OFF |
| `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | ON | OFF |

The same-event-loop defaults are injected into `OpenAiIngress`, the
vLLM-backed `LLMServer`, and the direct LLM routers. Explicit
`runtime_env.env_vars` values take precedence.

Serve LLM's `OpenAiIngress` configures its model deployment handles with
`_by_reference=False`, selecting the gRPC transport directly at the
point where those handles are created. This avoids changing generic
Serve handle construction and does not add a Serve LLM opt-out.

gRPC transport was introduced in
[#59908](#59908). The
same-event-loop defaults were previously proposed globally in
[#62156](#62156); this PR limits
them to Serve LLM.

## Related PRs

These default changes are independent and can merge in any order:

- [#66432 Enable HAProxy by default on
Linux](#66432)
- [#66434 Select request body forwarding by
router](#66434)
- [#66436 Run sync deployment methods in a thread
pool](#66436)

## Tests

- The live GPU reproducer below completed a real OpenAI-compatible
request and observed only the consolidated `main` loop on both
production replicas
- Focused unit tests for LLMServer runtime env defaults and overrides,
OpenAI ingress gRPC handles, and router runtime env propagation: 5
passed in 4.22s
- The commit hooks passed Ruff, Black, pydoclint, docs style, import
order, and the other applicable repository checks

## Local performance benchmark

The short-request workload is intentionally framework-heavy while
retaining a real vLLM engine. Lower latency is better; higher throughput
is better.

```mermaid
---
config:
  themeCSS: |
    .plot path { stroke-width: 5px !important; stroke-linecap: round; }
    .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; }
  themeVariables:
    xyChart:
      plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00"
---
xychart-beta
    title "Effect of consolidating replica event loops"
    x-axis "Maximum concurrency" [64, 128, 256]
    y-axis "Requests per second" 0 --> 400
    line "This PR: shared main loop" [264.0, 355.9, 368.8]
    line "Separate user-code thread only" [246.4, 325.8, 318.6]
    line "Separate router loop only" [255.4, 318.4, 305.7]
    line "Current default: both separate" [244.1, 302.3, 272.9]
```

Compared with the previous loop defaults, the new defaults increased
throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256,
respectively. Both individual settings contributed; their relative
impact varied with concurrency. The concurrency-256 values are the mean
of two runs; the other points are one run each.

The chart uses thick series lines and a dot legend with a
color-blind-friendly palette in this order: blue, purple, green, and
vermilion.

| Chart series | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` |
`RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` |
| --- | ---: | ---: |
| This PR: shared main loop | `0` | `0` |
| Separate user-code thread only | `1` | `0` |
| Separate router loop only | `0` | `1` |
| Current default: both separate | `1` | `1` |

### Benchmark setup

| Item | Configuration |
| --- | --- |
| Hardware | NVIDIA A10G (23 GiB) |
| Software | Python 3.12, vLLM 0.29.0, Torch 2.13, HAProxy 2.8.25 |
| Model | `Qwen/Qwen3-0.6B` on one vLLM-backed `LLMServer` replica |
| Serve topology | One `OpenAiIngress` replica and one `LLMServer`
replica; HAProxy was enabled with `RAY_SERVE_ENABLE_HA_PROXY=1` and
received requests on port 8000; ingress-to-model handles used gRPC in
both cases |
| Workload | `vllm bench serve`, OpenAI completions endpoint, random
input 32 tokens and output 8 tokens with `--random-range-ratio 0.5`,
`--ignore-eos`, and `--temperature 0` |
| Load | Infinite offered request rate at maximum concurrency 64, 128,
and 256 |
| Samples | 256 warmup requests, then 2,048 measured requests per point;
deterministic seed `20260928`; 32,768 measured requests and zero
failures across all four configurations |
| Environment application | Each environment-variable combination was
applied to both `OpenAiIngress` and `LLMServer` before their replicas
started |

As a control, an engine-heavy workload (1,024-token random input,
128-token random output, concurrency 64) delivered approximately 12
requests/s under either setting. This indicates that the difference
above is in framework overhead and becomes hidden when model execution
dominates.

## Duplicate search

I searched open Ray PRs for each environment variable and found no
duplicate of this Serve LLM-scoped change.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

## Live GPU reproducer

The reproducer uses the Python 3.12 `ray[llm]` wheel built from this
branch's merge base, then symlinks only `ray/llm` to the checkout.
Serve, generated protobufs, and compiled extensions remain from the
matching wheel.

```bash
uv venv --python 3.12 /tmp/ray-66435-live-venv
uv pip install --python /tmp/ray-66435-live-venv/bin/python \
  "https://s3-us-west-2.amazonaws.com/ray-wheels/master/98d8084dbf690739ef2921c25918cd49aa1db556/ray-3.0.0.dev0-cp312-cp312-manylinux2014_x86_64.whl[llm]"

SITE=/tmp/ray-66435-live-venv/lib/python3.12/site-packages/ray
mv "$SITE/llm" "$SITE/llm-wheel"
ln -s "$PWD/python/ray/llm" "$SITE/llm"

RAY_USAGE_STATS_ENABLED=0 /tmp/ray-66435-live-venv/bin/python - <<'PY'
import json
import time

import openai
from prometheus_client.parser import text_string_to_metric_families
import requests

import ray
from ray import serve
from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app


MODEL = "Qwen/Qwen3-0.6B"
METRICS_URL = "http://127.0.0.1:9999/metrics"
METRIC = "ray_serve_event_loop_monitoring_iterations_total"


def replica_event_loops():
    response = requests.get(METRICS_URL, timeout=5)
    response.raise_for_status()
    samples = [
        sample
        for family in text_string_to_metric_families(response.text)
        for sample in family.samples
        if sample.name == METRIC
        and sample.labels.get("component") == "replica"
        and sample.labels.get("application") == "default"
    ]
    actor_to_deployment = {
        sample.labels["actor_id"]: sample.labels["deployment"]
        for sample in samples
        if sample.labels.get("loop_type") == "main"
        and (
            sample.labels["deployment"] == "OpenAiIngress"
            or sample.labels["deployment"].startswith("LLMServer:")
        )
    }
    return {
        deployment: sorted(
            {
                sample.labels["loop_type"]
                for sample in samples
                if sample.labels["actor_id"] == actor_id
            }
        )
        for actor_id, deployment in actor_to_deployment.items()
    }


try:
    ray.init(
        num_cpus=8,
        num_gpus=1,
        include_dashboard=False,
        _metrics_export_port=9999,
        _system_config={"metrics_report_interval_ms": 1000},
    )
    config = LLMConfig(
        model_loading_config=ModelLoadingConfig(model_id=MODEL, model_source=MODEL),
        engine_kwargs={
            "max_model_len": 1024,
            "gpu_memory_utilization": 0.5,
            "enforce_eager": True,
        },
        deployment_config={"num_replicas": 1},
    )
    serve.run(build_openai_app(LLMServingArgs(llm_configs=[config])))

    client = openai.OpenAI(
        base_url="http://127.0.0.1:8000/v1", api_key="test", timeout=60
    )
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": "Reply with: loop test passed"}],
        max_tokens=8,
        temperature=0,
    )
    print("COMPLETION", completion.choices[0].message.content)

    deadline = time.time() + 90
    while time.time() < deadline:
        loops = replica_event_loops()
        if len(loops) == 2:
            break
        time.sleep(1)
    else:
        raise RuntimeError("Timed out waiting for replica event-loop metrics")

    # Check three later scrapes so a separate loop cannot be hidden by a
    # just-created metric that has not reached the exporter yet.
    for _ in range(3):
        time.sleep(2)
        loops = replica_event_loops()
        assert len(loops) == 2
        assert all(loop_types == ["main"] for loop_types in loops.values())

    print("REPLICA_EVENT_LOOPS", json.dumps(loops, sort_keys=True))
finally:
    serve.shutdown()
    ray.shutdown()
PY
```

The script builds the unmodified `build_openai_app` application, starts
its real `OpenAiIngress` and vLLM-backed `LLMServer` deployments, sends
an OpenAI-compatible completion request, and reads Serve's event-loop
heartbeat metrics for those replica actors.

Relevant output:

```text
Deployment Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

Ingress Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK"
COMPLETION <think>
Okay, the user wants me
REPLICA_EVENT_LOOPS {"LLMServer:Qwen--Qwen3-0_6B": ["main"], "OpenAiIngress": ["main"]}
```

The completion request initializes the ingress model handle before
metrics are checked. A separate user-code loop or handle-router loop
would emit `user_code` or `router` for the same replica actor. Both
production replicas emit only `main`, showing that the environment
settings take effect and consolidate those loops onto the replica event
loop.

---------

Signed-off-by: Seiji Eicher <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Description

Run synchronous deployment methods in a thread pool by default so
blocking synchronous I/O does not block the replica event loop.
`RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for
deployments whose shared state is not thread-safe.

| Environment variable | `master` | After this PR |
| --- | --- | --- |
| `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON |

The opt-in warning has been emitted since
[ray-project#48897](ray-project#48897) merged on
November 26, 2024—667 days (about 22 months) before this default swap.
This provided an extended migration period for users to make synchronous
deployment code thread-safe or convert it to `async def`.

The documentation now describes thread safety requirements and the
opt-out. This default was previously enabled in
[ray-project#61229](ray-project#61229) and reverted in
[ray-project#61369](ray-project#61369).

## Related PRs

These default changes are independent and can merge in any order:

- [ray-project#66432 Enable HAProxy by default on
Linux](ray-project#66432)
- [ray-project#66434 Select request body forwarding by
router](ray-project#66434)
- [ray-project#66435 Apply Serve LLM replica performance
defaults](ray-project#66435)

## Tests

- `RAY_USE_UVLOOP=0 python -m pytest -q
python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The
executor-introspection cases target the standard asyncio loop used by
this Bazel test.
- Updated the thread-pool test target description
- Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs
style, and import-order checks

## Duplicate search

I searched open Ray PRs for this environment variable and found no
active duplicate.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

Signed-off-by: Seiji Eicher <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Description

Apply the performance-oriented replica defaults only to the default Ray
Serve LLM path. General Serve defaults remain unchanged.

| Serve LLM setting | `master` | After this PR |
| --- | --- | --- |
| OpenAI ingress model-handle transport | `ray.remote` | gRPC |
| `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | ON | OFF |
| `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | ON | OFF |

The same-event-loop defaults are injected into `OpenAiIngress`, the
vLLM-backed `LLMServer`, and the direct LLM routers. Explicit
`runtime_env.env_vars` values take precedence.

Serve LLM's `OpenAiIngress` configures its model deployment handles with
`_by_reference=False`, selecting the gRPC transport directly at the
point where those handles are created. This avoids changing generic
Serve handle construction and does not add a Serve LLM opt-out.

gRPC transport was introduced in
[ray-project#59908](ray-project#59908). The
same-event-loop defaults were previously proposed globally in
[ray-project#62156](ray-project#62156); this PR limits
them to Serve LLM.

## Related PRs

These default changes are independent and can merge in any order:

- [ray-project#66432 Enable HAProxy by default on
Linux](ray-project#66432)
- [ray-project#66434 Select request body forwarding by
router](ray-project#66434)
- [ray-project#66436 Run sync deployment methods in a thread
pool](ray-project#66436)

## Tests

- The live GPU reproducer below completed a real OpenAI-compatible
request and observed only the consolidated `main` loop on both
production replicas
- Focused unit tests for LLMServer runtime env defaults and overrides,
OpenAI ingress gRPC handles, and router runtime env propagation: 5
passed in 4.22s
- The commit hooks passed Ruff, Black, pydoclint, docs style, import
order, and the other applicable repository checks

## Local performance benchmark

The short-request workload is intentionally framework-heavy while
retaining a real vLLM engine. Lower latency is better; higher throughput
is better.

```mermaid
---
config:
  themeCSS: |
    .plot path { stroke-width: 5px !important; stroke-linecap: round; }
    .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; }
  themeVariables:
    xyChart:
      plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00"
---
xychart-beta
    title "Effect of consolidating replica event loops"
    x-axis "Maximum concurrency" [64, 128, 256]
    y-axis "Requests per second" 0 --> 400
    line "This PR: shared main loop" [264.0, 355.9, 368.8]
    line "Separate user-code thread only" [246.4, 325.8, 318.6]
    line "Separate router loop only" [255.4, 318.4, 305.7]
    line "Current default: both separate" [244.1, 302.3, 272.9]
```

Compared with the previous loop defaults, the new defaults increased
throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256,
respectively. Both individual settings contributed; their relative
impact varied with concurrency. The concurrency-256 values are the mean
of two runs; the other points are one run each.

The chart uses thick series lines and a dot legend with a
color-blind-friendly palette in this order: blue, purple, green, and
vermilion.

| Chart series | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` |
`RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` |
| --- | ---: | ---: |
| This PR: shared main loop | `0` | `0` |
| Separate user-code thread only | `1` | `0` |
| Separate router loop only | `0` | `1` |
| Current default: both separate | `1` | `1` |

### Benchmark setup

| Item | Configuration |
| --- | --- |
| Hardware | NVIDIA A10G (23 GiB) |
| Software | Python 3.12, vLLM 0.29.0, Torch 2.13, HAProxy 2.8.25 |
| Model | `Qwen/Qwen3-0.6B` on one vLLM-backed `LLMServer` replica |
| Serve topology | One `OpenAiIngress` replica and one `LLMServer`
replica; HAProxy was enabled with `RAY_SERVE_ENABLE_HA_PROXY=1` and
received requests on port 8000; ingress-to-model handles used gRPC in
both cases |
| Workload | `vllm bench serve`, OpenAI completions endpoint, random
input 32 tokens and output 8 tokens with `--random-range-ratio 0.5`,
`--ignore-eos`, and `--temperature 0` |
| Load | Infinite offered request rate at maximum concurrency 64, 128,
and 256 |
| Samples | 256 warmup requests, then 2,048 measured requests per point;
deterministic seed `20260928`; 32,768 measured requests and zero
failures across all four configurations |
| Environment application | Each environment-variable combination was
applied to both `OpenAiIngress` and `LLMServer` before their replicas
started |

As a control, an engine-heavy workload (1,024-token random input,
128-token random output, concurrency 64) delivered approximately 12
requests/s under either setting. This indicates that the difference
above is in framework overhead and becomes hidden when model execution
dominates.

## Duplicate search

I searched open Ray PRs for each environment variable and found no
duplicate of this Serve LLM-scoped change.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

## Live GPU reproducer

The reproducer uses the Python 3.12 `ray[llm]` wheel built from this
branch's merge base, then symlinks only `ray/llm` to the checkout.
Serve, generated protobufs, and compiled extensions remain from the
matching wheel.

```bash
uv venv --python 3.12 /tmp/ray-66435-live-venv
uv pip install --python /tmp/ray-66435-live-venv/bin/python \
  "https://s3-us-west-2.amazonaws.com/ray-wheels/master/98d8084dbf690739ef2921c25918cd49aa1db556/ray-3.0.0.dev0-cp312-cp312-manylinux2014_x86_64.whl[llm]"

SITE=/tmp/ray-66435-live-venv/lib/python3.12/site-packages/ray
mv "$SITE/llm" "$SITE/llm-wheel"
ln -s "$PWD/python/ray/llm" "$SITE/llm"

RAY_USAGE_STATS_ENABLED=0 /tmp/ray-66435-live-venv/bin/python - <<'PY'
import json
import time

import openai
from prometheus_client.parser import text_string_to_metric_families
import requests

import ray
from ray import serve
from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app


MODEL = "Qwen/Qwen3-0.6B"
METRICS_URL = "http://127.0.0.1:9999/metrics"
METRIC = "ray_serve_event_loop_monitoring_iterations_total"


def replica_event_loops():
    response = requests.get(METRICS_URL, timeout=5)
    response.raise_for_status()
    samples = [
        sample
        for family in text_string_to_metric_families(response.text)
        for sample in family.samples
        if sample.name == METRIC
        and sample.labels.get("component") == "replica"
        and sample.labels.get("application") == "default"
    ]
    actor_to_deployment = {
        sample.labels["actor_id"]: sample.labels["deployment"]
        for sample in samples
        if sample.labels.get("loop_type") == "main"
        and (
            sample.labels["deployment"] == "OpenAiIngress"
            or sample.labels["deployment"].startswith("LLMServer:")
        )
    }
    return {
        deployment: sorted(
            {
                sample.labels["loop_type"]
                for sample in samples
                if sample.labels["actor_id"] == actor_id
            }
        )
        for actor_id, deployment in actor_to_deployment.items()
    }


try:
    ray.init(
        num_cpus=8,
        num_gpus=1,
        include_dashboard=False,
        _metrics_export_port=9999,
        _system_config={"metrics_report_interval_ms": 1000},
    )
    config = LLMConfig(
        model_loading_config=ModelLoadingConfig(model_id=MODEL, model_source=MODEL),
        engine_kwargs={
            "max_model_len": 1024,
            "gpu_memory_utilization": 0.5,
            "enforce_eager": True,
        },
        deployment_config={"num_replicas": 1},
    )
    serve.run(build_openai_app(LLMServingArgs(llm_configs=[config])))

    client = openai.OpenAI(
        base_url="http://127.0.0.1:8000/v1", api_key="test", timeout=60
    )
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": "Reply with: loop test passed"}],
        max_tokens=8,
        temperature=0,
    )
    print("COMPLETION", completion.choices[0].message.content)

    deadline = time.time() + 90
    while time.time() < deadline:
        loops = replica_event_loops()
        if len(loops) == 2:
            break
        time.sleep(1)
    else:
        raise RuntimeError("Timed out waiting for replica event-loop metrics")

    # Check three later scrapes so a separate loop cannot be hidden by a
    # just-created metric that has not reached the exporter yet.
    for _ in range(3):
        time.sleep(2)
        loops = replica_event_loops()
        assert len(loops) == 2
        assert all(loop_types == ["main"] for loop_types in loops.values())

    print("REPLICA_EVENT_LOOPS", json.dumps(loops, sort_keys=True))
finally:
    serve.shutdown()
    ray.shutdown()
PY
```

The script builds the unmodified `build_openai_app` application, starts
its real `OpenAiIngress` and vLLM-backed `LLMServer` deployments, sends
an OpenAI-compatible completion request, and reads Serve's event-loop
heartbeat metrics for those replica actors.

Relevant output:

```text
Deployment Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

Ingress Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK"
COMPLETION <think>
Okay, the user wants me
REPLICA_EVENT_LOOPS {"LLMServer:Qwen--Qwen3-0_6B": ["main"], "OpenAiIngress": ["main"]}
```

The completion request initializes the ingress model handle before
metrics are checked. A separate user-code loop or handle-router loop
would emit `user_code` or `router` for the same replica actor. Both
production replicas emit only `main`, showing that the environment
settings take effect and consolidate those loops onto the replica event
loop.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants