Skip to content

[Serve] Select request body forwarding by router - #66434

Closed
eicherseiji wants to merge 2 commits into
masterfrom
seiji/serve-auto-forward-body
Closed

eicherseiji wants to merge 2 commits into
masterfrom
seiji/serve-auto-forward-body

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Select HAProxy ingress request-body forwarding from each application's routing requirements. Body-aware applications opt in through persisted application metadata, while body-independent applications avoid the buffering and re-emission cost.

Routing topology Forward request body Reason
Single model with round-robin or consistent-hash routing No Deployment and replica selection are body-independent
Single model with KV-aware or prefix-cache-aware routing Yes Replica selection uses the prompt or messages
Multi-model direct HTTP Yes Deployment selection uses the OpenAI model field

The multi-model rule makes this compatible with #66315, where the ingress request router selects a model deployment before selecting a replica. The private attachment API requires an explicit body-forwarding decision so new direct-HTTP builders cannot silently default to the wrong behavior.

The decision is carried through application build metadata, deployment state, controller target groups, and the per-application HAProxy Lua configuration. Existing pickled deployment state defaults missing metadata to false. This builds on the body-forwarding gate from #63183.

This removes the global RAY_SERVE_INGRESS_REQUEST_ROUTER_FORWARD_BODY environment variable. The application routing contract is now authoritative, so a cluster-wide override cannot disable data required for a correct routing decision.

Related PRs

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

Tests

  • Focused Serve coverage for application metadata, controller target groups, HAProxy configuration, and router requirements: 91 passed, 2 skipped
  • Builder coverage for single-model, multi-model, data-parallel, and prefill/decode routing requirements
  • Pre-commit, including Ruff, Black, mypy, Pyrefly, docs style, and import-order checks
  • git diff --check

Duplicate search

I searched open Ray PRs for this environment variable and automatic body-forwarding changes and found no 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-auto-forward-body branch from 1f82082 to 9a24c15 Compare September 23, 2026 23:15
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch from 35f7e2a to 7a5d47b Compare September 23, 2026 23:15
@eicherseiji
eicherseiji force-pushed the seiji/serve-auto-forward-body branch from 9a24c15 to d9a2ee1 Compare September 24, 2026 01:03
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch from 7a5d47b to ae47c1b 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-default-swaps branch from ae47c1b to 7f91224 Compare September 24, 2026 17:31
@eicherseiji
eicherseiji force-pushed the seiji/serve-auto-forward-body branch 3 times, most recently from 0402b44 to 2a80546 Compare September 24, 2026 18:33
@eicherseiji
eicherseiji changed the base branch from seiji/serve-default-swaps to master September 24, 2026 18:33
@eicherseiji
eicherseiji force-pushed the seiji/serve-auto-forward-body branch from 2a80546 to c285b10 Compare September 24, 2026 18:57
@eicherseiji
eicherseiji force-pushed the seiji/serve-auto-forward-body branch from c285b10 to 214e8e5 Compare September 24, 2026 19:10
eicherseiji added a commit that referenced this pull request Sep 29, 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
[#48897](#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](#61229) and reverted in
[#61369](#61369).

## 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)
- [#66435 Apply Serve LLM replica performance
defaults](#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]>
@eicherseiji

Copy link
Copy Markdown
Contributor Author

Deferring, may move this logic to an application, as opposed to separate deployment

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]>
@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 Oct 14, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

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

Thanks again for your contribution!

@github-actions github-actions Bot closed this Oct 28, 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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant