Skip to content

[serve] Enforce type checking on the scheduling/routing modules - #65410

Merged
abrarsheikh merged 2 commits into
ray-project:masterfrom
johntaylor-cell:serve-typecheck-scheduling-routing
Aug 21, 2026
Merged

abrarsheikh merged 2 commits into
ray-project:masterfrom
johntaylor-cell:serve-typecheck-scheduling-routing

Conversation

@johntaylor-cell

@johntaylor-cell johntaylor-cell commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Add deployment_scheduler.py, router.py, and request_router.py to the mypy + pyrefly serve allowlists and fix their type errors.

  • request_router: declare the members MultiplexMixin/FIFOMixin use from the composed RequestRouter (bare annotations, Callable for methods, so they don't shadow the real methods via MRO), fix the ReplicaID/str key confusion at its sources, assert-narrow where a None would already crash, ignore the asyncio.Task .replica monkey-patch.
  • router: add an asserting _active_request_router property (through the lazy-loading request_router) for the guaranteed-non-None accesses, keeping the Optional accessor for the None-checks, narrow the singleton _asyncio_loop, the async-router variant returns asyncio.Future by design (override), cast the LongPoll (namespace, DeploymentID) key dicts.
  • deployment_scheduler: fix the ReplicaID-keyed dicts (str -> ReplicaID), import IMPLICIT_RESOURCE_PREFIX/node_labels_match_selector with one ignore, annotate the scheduling-strategy union, give the launching/running loops distinct vars.

@johntaylor-cell
johntaylor-cell requested a review from a team as a code owner August 12, 2026 02:17
@johntaylor-cell johntaylor-cell self-assigned this Aug 12, 2026
@johntaylor-cell johntaylor-cell added serve Ray Serve Related Issue go add ONLY when ready to merge, run all tests labels Aug 12, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@johntaylor-cell
johntaylor-cell marked this pull request as draft August 12, 2026 14:17
Add deployment_scheduler.py, router.py, and request_router/request_router.py to
the mypy + pyrefly serve allowlists and fix their type errors. Where an error
pointed at a genuinely-wrong or too-narrow annotation, fix the declaration
rather than suppress at the call site.

- request_router: declare the members MultiplexMixin/FIFOMixin use from the
  composed RequestRouter (bare annotations; Callable for methods, so they don't
  shadow the real methods via MRO); fix the ReplicaID/str key confusion at its
  sources; assert-narrow where a None would already crash; replace the
  asyncio.Task `.replica` monkey-patch with an explicit task->replica map; widen
  update_backoff_params to Optional[float] and skip None stores (the config
  values are optional and a None would later crash _compute_backoff_s).
- router: add an asserting `_active_request_router` property (through the
  lazy-loading `request_router`) for the guaranteed-non-None accesses, keeping
  the Optional accessor for the None-checks; narrow the singleton `_asyncio_loop`;
  the async-router variant returns asyncio.Future by design (override); cast the
  LongPoll (namespace, DeploymentID) key dicts.
- deployment_scheduler: fix the ReplicaID-keyed dicts (str -> ReplicaID); import
  IMPLICIT_RESOURCE_PREFIX/node_labels_match_selector with one ignore; annotate
  the scheduling-strategy union; give the launching/running loops distinct vars.

Two shared declarations were widened to drop ignores honestly:
CreatePlacementGroupRequest.target_node_id -> Optional[str] (the gang path
passes None), and set_span_exception's `exc` -> BaseException (it only forwards
to record_exception, which accepts BaseException) -- which also removes the now
unnecessary ignores at its proxy.py and replica.py call sites.

Signed-off-by: john.taylor <[email protected]>
@johntaylor-cell
johntaylor-cell force-pushed the serve-typecheck-scheduling-routing branch from 546890f to da99513 Compare August 12, 2026 18:31
@johntaylor-cell
johntaylor-cell marked this pull request as ready for review August 12, 2026 18:32

@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 focuses on improving type safety and static analysis compatibility across several Ray Serve private modules by adding type annotations, imports, and assertions. The review feedback suggests enhancing robustness by replacing several newly introduced assert statements with defensive checks or early returns to avoid potential runtime crashes during uninitialized states. Additionally, the feedback recommends updating overridden get methods in deployment_scheduler.py to accept a default parameter, resolving Liskov Substitution Principle violations and removing the need for type-ignore comments.

Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
Accept the standard dict.get `default` argument in AvailableNodeResources.get
and RequestedResources.get. This resolves the real override/bad-override
violation and lets the type ignores go. No caller passes a default today, so
super().get(key, default) is behavior-identical to the previous
super().get(key); an explicit default now takes precedence over the
implicit-resource default, matching dict.get semantics.

Signed-off-by: john.taylor <[email protected]>
abrarsheikh pushed a commit that referenced this pull request Aug 14, 2026
## Why

`python/ray/serve/request_router.py` re-exports the public
request-router extension surface, but declares it implicitly through `#
noqa: F401` imports rather than explicitly through `__all__`. This
declares it.

The seven names are each decorated `@PublicAPI(stability="alpha")` at
their definition site and documented in the Serve API reference at
`doc/source/serve/api/index.md` under their `serve.request_router.*`
path. `doc/source/serve/advanced-guides/custom-request-router.md` and
its `doc_code/custom_request_router.py` teach users to import from this
module. So the change records an existing contract rather than creating
a new one.

It also makes the surface visible to the API-doc consistency check.
`API._is_public_reexport()`, added in #65340, treats a name in a public
module's `__all__` as public regardless of where its implementation
lives, but it requires an *explicit* `__all__` entry, which this module
didn't have.

## Coordination

This is a small mechanical change, so per `AGENTS.md` it's worth saying
it was coordinated rather than volunteered. It follows from a ruling
Richard Liaw gave on Ray's API location policy: a private definition
re-exported through a public module's `__all__` is compliant, and the
test that matters is whether users have to import a private package.
Declaring the surface here is the fix that ruling implies. Happy to
close this if the Serve team would rather handle the module differently.

## `ReplicaResult` is deliberately excluded

It's the one name in the file left out of `__all__`, because unlike the
other seven it carries no API annotation (`class ReplicaResult(ABC)`, no
decorator) and has no reference-page entry. Including it would newly
assert a public contract instead of recording one. Its import keeps an
F401 suppression since the re-export is still in use.

**This is the one judgment call in the PR and it's yours to make.** If
Serve considers `ReplicaResult` part of the public extension surface,
say so and I'll add it.

`PowerOfTwoChoicesRequestRouter` is out of scope: it's absent from both
this module's re-exports and the autosummary, so it needs a separate
decision.

## Removing the per-import suppressions

The seven declared names lose their `# noqa: F401` comments. A name
listed in `__all__` counts as used, so pyflakes and ruff no longer flag
it. `ReplicaResult` keeps its suppression.

## Testing

Verified statically:

- `ruff check python/ray/serve/request_router.py` — passes.
- `black --check` and `ruff format --check` — already formatted.
- Full `pre-commit run` on the changed file — all applicable hooks pass
(ruff, black, pydoclint, docstyle, import order, semgrep).
- Confirmed the declared `__all__` is exactly the set of seven names in
the `serve.request_router.*` autosummary block, with no extras and
nothing missing.

**Not verified locally: `api_policy_check`.** It needs a Ray build, and
master's Python source doesn't import against a released binary, so I'm
relying on CI for that check rather than claiming a local run. The
expected effect is on the resolve check only. I'm specifically *not*
claiming this clears the `tracked_doc_debt` entries for these symbols:
those fail the must-be-documented check, which #65340 explicitly left
untouched. If CI shows any of them can drop, I'll follow up separately
rather than bundling it here.

## Duplicate check

No open PR touches `python/ray/serve/request_router.py`. #65410
(`[serve] Enforce type checking on the scheduling/routing modules`)
touches `_private/request_router/request_router.py` but not this module,
so no conflict.

## AI assistance

AI-assisted, per `AGENTS.md`: the analysis and the patch were drafted
with Claude Code, and I reviewed every changed line.

Signed-off-by: Douglas Strodtman <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
## Why

`python/ray/serve/request_router.py` re-exports the public
request-router extension surface, but declares it implicitly through `#
noqa: F401` imports rather than explicitly through `__all__`. This
declares it.

The seven names are each decorated `@PublicAPI(stability="alpha")` at
their definition site and documented in the Serve API reference at
`doc/source/serve/api/index.md` under their `serve.request_router.*`
path. `doc/source/serve/advanced-guides/custom-request-router.md` and
its `doc_code/custom_request_router.py` teach users to import from this
module. So the change records an existing contract rather than creating
a new one.

It also makes the surface visible to the API-doc consistency check.
`API._is_public_reexport()`, added in ray-project#65340, treats a name in a public
module's `__all__` as public regardless of where its implementation
lives, but it requires an *explicit* `__all__` entry, which this module
didn't have.

## Coordination

This is a small mechanical change, so per `AGENTS.md` it's worth saying
it was coordinated rather than volunteered. It follows from a ruling
Richard Liaw gave on Ray's API location policy: a private definition
re-exported through a public module's `__all__` is compliant, and the
test that matters is whether users have to import a private package.
Declaring the surface here is the fix that ruling implies. Happy to
close this if the Serve team would rather handle the module differently.

## `ReplicaResult` is deliberately excluded

It's the one name in the file left out of `__all__`, because unlike the
other seven it carries no API annotation (`class ReplicaResult(ABC)`, no
decorator) and has no reference-page entry. Including it would newly
assert a public contract instead of recording one. Its import keeps an
F401 suppression since the re-export is still in use.

**This is the one judgment call in the PR and it's yours to make.** If
Serve considers `ReplicaResult` part of the public extension surface,
say so and I'll add it.

`PowerOfTwoChoicesRequestRouter` is out of scope: it's absent from both
this module's re-exports and the autosummary, so it needs a separate
decision.

## Removing the per-import suppressions

The seven declared names lose their `# noqa: F401` comments. A name
listed in `__all__` counts as used, so pyflakes and ruff no longer flag
it. `ReplicaResult` keeps its suppression.

## Testing

Verified statically:

- `ruff check python/ray/serve/request_router.py` — passes.
- `black --check` and `ruff format --check` — already formatted.
- Full `pre-commit run` on the changed file — all applicable hooks pass
(ruff, black, pydoclint, docstyle, import order, semgrep).
- Confirmed the declared `__all__` is exactly the set of seven names in
the `serve.request_router.*` autosummary block, with no extras and
nothing missing.

**Not verified locally: `api_policy_check`.** It needs a Ray build, and
master's Python source doesn't import against a released binary, so I'm
relying on CI for that check rather than claiming a local run. The
expected effect is on the resolve check only. I'm specifically *not*
claiming this clears the `tracked_doc_debt` entries for these symbols:
those fail the must-be-documented check, which ray-project#65340 explicitly left
untouched. If CI shows any of them can drop, I'll follow up separately
rather than bundling it here.

## Duplicate check

No open PR touches `python/ray/serve/request_router.py`. ray-project#65410
(`[serve] Enforce type checking on the scheduling/routing modules`)
touches `_private/request_router/request_router.py` but not this module,
so no conflict.

## AI assistance

AI-assisted, per `AGENTS.md`: the analysis and the patch were drafted
with Claude Code, and I reviewed every changed line.

Signed-off-by: Douglas Strodtman <[email protected]>
Signed-off-by: 400Ping <[email protected]>
@abrarsheikh
abrarsheikh merged commit 5aa9055 into ray-project:master Aug 21, 2026
6 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Why

`python/ray/serve/request_router.py` re-exports the public
request-router extension surface, but declares it implicitly through `#
noqa: F401` imports rather than explicitly through `__all__`. This
declares it.

The seven names are each decorated `@PublicAPI(stability="alpha")` at
their definition site and documented in the Serve API reference at
`doc/source/serve/api/index.md` under their `serve.request_router.*`
path. `doc/source/serve/advanced-guides/custom-request-router.md` and
its `doc_code/custom_request_router.py` teach users to import from this
module. So the change records an existing contract rather than creating
a new one.

It also makes the surface visible to the API-doc consistency check.
`API._is_public_reexport()`, added in ray-project#65340, treats a name in a public
module's `__all__` as public regardless of where its implementation
lives, but it requires an *explicit* `__all__` entry, which this module
didn't have.

## Coordination

This is a small mechanical change, so per `AGENTS.md` it's worth saying
it was coordinated rather than volunteered. It follows from a ruling
Richard Liaw gave on Ray's API location policy: a private definition
re-exported through a public module's `__all__` is compliant, and the
test that matters is whether users have to import a private package.
Declaring the surface here is the fix that ruling implies. Happy to
close this if the Serve team would rather handle the module differently.

## `ReplicaResult` is deliberately excluded

It's the one name in the file left out of `__all__`, because unlike the
other seven it carries no API annotation (`class ReplicaResult(ABC)`, no
decorator) and has no reference-page entry. Including it would newly
assert a public contract instead of recording one. Its import keeps an
F401 suppression since the re-export is still in use.

**This is the one judgment call in the PR and it's yours to make.** If
Serve considers `ReplicaResult` part of the public extension surface,
say so and I'll add it.

`PowerOfTwoChoicesRequestRouter` is out of scope: it's absent from both
this module's re-exports and the autosummary, so it needs a separate
decision.

## Removing the per-import suppressions

The seven declared names lose their `# noqa: F401` comments. A name
listed in `__all__` counts as used, so pyflakes and ruff no longer flag
it. `ReplicaResult` keeps its suppression.

## Testing

Verified statically:

- `ruff check python/ray/serve/request_router.py` — passes.
- `black --check` and `ruff format --check` — already formatted.
- Full `pre-commit run` on the changed file — all applicable hooks pass
(ruff, black, pydoclint, docstyle, import order, semgrep).
- Confirmed the declared `__all__` is exactly the set of seven names in
the `serve.request_router.*` autosummary block, with no extras and
nothing missing.

**Not verified locally: `api_policy_check`.** It needs a Ray build, and
master's Python source doesn't import against a released binary, so I'm
relying on CI for that check rather than claiming a local run. The
expected effect is on the resolve check only. I'm specifically *not*
claiming this clears the `tracked_doc_debt` entries for these symbols:
those fail the must-be-documented check, which ray-project#65340 explicitly left
untouched. If CI shows any of them can drop, I'll follow up separately
rather than bundling it here.

## Duplicate check

No open PR touches `python/ray/serve/request_router.py`. ray-project#65410
(`[serve] Enforce type checking on the scheduling/routing modules`)
touches `_private/request_router/request_router.py` but not this module,
so no conflict.

## AI assistance

AI-assisted, per `AGENTS.md`: the analysis and the patch were drafted
with Claude Code, and I reviewed every changed line.

Signed-off-by: Douglas Strodtman <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…project#65410)

Add deployment_scheduler.py, router.py, and request_router.py to the
mypy + pyrefly serve allowlists and fix their type errors.

- request_router: declare the members MultiplexMixin/FIFOMixin use from
the composed RequestRouter (bare annotations, Callable for methods, so
they don't shadow the real methods via MRO), fix the ReplicaID/str key
confusion at its sources, assert-narrow where a None would already
crash, ignore the asyncio.Task `.replica` monkey-patch.
- router: add an asserting `_active_request_router` property (through
the lazy-loading `request_router`) for the guaranteed-non-None accesses,
keeping the Optional accessor for the None-checks, narrow the singleton
`_asyncio_loop`, the async-router variant returns asyncio.Future by
design (override), cast the LongPoll (namespace, DeploymentID) key
dicts.
- deployment_scheduler: fix the ReplicaID-keyed dicts (str ->
ReplicaID), import IMPLICIT_RESOURCE_PREFIX/node_labels_match_selector
with one ignore, annotate the scheduling-strategy union, give the
launching/running loops distinct vars.

---------

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

Labels

go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants