Skip to content

[serve] Enforce type checking on the controller-critical modules - #64753

Merged
abrarsheikh merged 7 commits into
ray-project:masterfrom
johntaylor-cell:serve-typecheck-controller
Aug 10, 2026
Merged

abrarsheikh merged 7 commits into
ray-project:masterfrom
johntaylor-cell:serve-typecheck-controller

Conversation

@johntaylor-cell

@johntaylor-cell johntaylor-cell commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

This is the second PR to enable mypy and pyrefly on ray/serve. This PR brings the four controller-critical modules under the mypy and pyrefly serve hooks: deployment_state.py, replica.py, controller.py, and application_state.py.

The changes made:

  • Fix the type errors in all four files (annotation-driven, with a few incidental invariant-hardening and one latent-bug fix): Optional for lazily-populated attrs and honest return types, precise container/callback annotations, typing.cast for invariants a checker cannot see, and narrowly-scoped ignores for actor .remote dynamics. Add the four files to both hook allowlists and pyrefly-serve.toml.
  • Two annotations were made honest and rippled to their call sites: get_ingress_replicas_info now returns Optional node-id/ports (pending replicas), and get_alive_replica_actor_ids returns Optional actor-ids (starting replicas); the controller call sites cast to the landed consumer signatures rather than widening them.

First mypy/pyrefly PR was #64643.
The PR that initiated this effort is #63862 (the checkpoint/recovery state machine where type confusion becomes persistent state corruption).

@johntaylor-cell
johntaylor-cell requested a review from a team as a code owner July 14, 2026 20: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 integrates several core Ray Serve private modules into the static type-checking pipeline by adding type annotations, casts, and type-ignore comments. The reviewer's feedback focuses on improving type safety and code quality by replacing many of the newly introduced type-ignore comments with explicit runtime assertions, type guards, or None checks. Additionally, the reviewer identified a pre-existing bug in replica.py where string concatenation with a non-string self._deployment_id would raise a TypeError instead of a RayServeException, and provided a suggestion to fix it using an f-string.

Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/controller.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@johntaylor-cell

Copy link
Copy Markdown
Contributor Author

@gemini-code-assist thanks — applied all of your suggestions in c86affa. Replaced the invariant type-ignore comments with assert ... is not None narrowing at the sites you flagged (the rank-assign callback + node_id, recover_rank's actor_node_id/rank, on_replica_running's node_id, the _start_time latency and is_slow reads, _http_options in the timeout message, and _replica_results), and used an isinstance(status.code, grpc.StatusCode) guard for the gRPC status union. The controller target_capacity comparison now checks both operands explicitly instead of ignoring.

Also fixed the genuine bug you caught: call_reconfigure built its error message with str + self._deployment_id (a DeploymentID dataclass), which raised TypeError instead of the intended RayServeException — now an f-string.

Both serve type-check hooks stay green over the four files. The lint shard here is red only on the pre-existing constants.py master regression, fixed by #64752; this PR goes green once that lands and I rebase onto it.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Thanks for the update, @johntaylor-cell. The changes look great—using assert ... is not None for narrowing and adding isinstance guards are excellent ways to improve type safety while keeping the code clean. The fix for the TypeError in call_reconfigure is also a solid catch. Since the linting issue is tied to the pending #64752, this looks ready to go once that lands and you rebase. Nice work.

@johntaylor-cell johntaylor-cell added go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue labels Jul 14, 2026
@johntaylor-cell johntaylor-cell self-assigned this Jul 14, 2026

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

did not review completely, high level feedback is that there are a lot of places we are doing cast; see if it can be tightened up by eigher fixing the function signature or asserting invariants in code.

@johntaylor-cell

Copy link
Copy Markdown
Contributor Author

did not review completely, high level feedback is that there are a lot of places we are doing cast; see if it can be tightened up by eigher fixing the function signature or asserting invariants in code.

Swept the casts across all four files: application_state 9→2, controller 13→9, replica 14→5, and deployment_state's route_patterns chain fixed. Approach per your guidance: fix the source signature where the cast hid a wrong type, assert where an invariant is guaranteed, early-return where None is a real handled case, and direct-index where a lookup must succeed.

The casts that remain are load-bearing and documented inline — each would change behavior or break the checker if converted:

Cross-language node_id/rank (deployment_state ×3, controller ×2): Java replicas reach SUCCEEDED/RUNNING with these None (they skip the Python allocation ray.get), so an assert would abort the controller loop.
Conditional streaming callbacks (replica ×2): None off the streaming/HTTP path, so an unconditional assert would crash non-streaming calls.
Type refinements the declared signature can't express: the awaitable return of the user autoscaling-stats fn, Hashable→str metric-store keys, and Any from metric-report decompression.
global_logging_config (controller ×2): asserting a self-attribute in init triggers mypy's has-type cascade that poisons inference of every later attribute, so a cast is required there.
Two more (controller 684/741) could be fully removed by widening the set[str]/tuple signatures in the already-merged autoscaling_state.py/node_port_manager.py — happy to do that as a follow-up if you'd prefer widening the landed signatures.

@johntaylor-cell
johntaylor-cell force-pushed the serve-typecheck-controller branch 3 times, most recently from f4882cb to b30451a Compare July 15, 2026 21:21
@johntaylor-cell
johntaylor-cell force-pushed the serve-typecheck-controller branch 2 times, most recently from 11e62c9 to d897ad2 Compare July 23, 2026 20:51
@github-actions

github-actions Bot commented Aug 7, 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 Aug 7, 2026
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/controller.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@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 8, 2026

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 4928355. Configure here.

Second step of the ray/serve type-check ratchet (ray-project#64643). Brings the
four controller-critical modules under the mypy + pyrefly serve hooks:
deployment_state.py, replica.py, controller.py, application_state.py --
the checkpoint/recovery state machine where type confusion becomes
persistent state corruption (the ray-project#63862 rank bug lived here).

- Fix the type errors in all four files (annotation-only; no runtime
  behavior change): Optional for lazily-populated attrs and honest
  return types, precise container/callback annotations, typing.cast for
  invariants a checker cannot see, and narrowly-scoped ignores for
  actor .remote dynamics. Add the four files to both hook allowlists
  and pyrefly-serve.toml.
- Two annotations were made honest and rippled to their call sites:
  get_ingress_replicas_info now returns Optional node-id/ports (pending
  replicas), and get_alive_replica_actor_ids returns Optional actor-ids
  (starting replicas); the controller call sites cast to the landed
  consumer signatures rather than widening them.

Related to ray-project#64643.

Signed-off-by: john.taylor <[email protected]>
Apply the reviewer suggestions: replace invariant type-ignore comments
with assert-based narrowing (documents the invariant and checks it at
runtime), use an isinstance type-guard for the grpc StatusCode union,
and fix a genuine latent bug the review surfaced -- call_reconfigure
built its error message with str + DeploymentID (a dataclass), which
raised TypeError instead of the intended RayServeException; now an
f-string. Both serve type-check hooks remain green over the four files.

Signed-off-by: john.taylor <[email protected]>
…de id

Cursor Bugbot correctly flagged that the assert-narrowing suggested for
the replica-success path is unsafe: cross-language (Java) replicas skip
the Python allocation ray.get that sets _node_id (deployment_state.py
gates it on `if not self._is_cross_language`), so they reach SUCCEEDED
with actor_node_id/rank still None. An assert there would raise and
abort the controller reconcile loop -- a regression vs the prior
pass-through behavior.

Revert those two sites (recover_rank and on_replica_running) to
typing.cast, which is runtime-identity and preserves the prior
behavior while keeping both checkers green. The other asserts adopted
from review are on unconditionally-set values (_start_time,
_http_options) or are already gated to the non-cross-language branch
(the start()-path node_id assert), so they stay.

Signed-off-by: john.taylor <[email protected]>
…ants

Per review feedback to reduce casts across the controller-critical
modules, tighten each one to the most honest form:

- Fix source signatures where the cast papered over a wrong type:
  get_deployment_route_patterns now returns Optional[List[RoutePattern]]
  (the route_patterns type-chain in deployment_state.py is aligned to
  RoutePattern, matching replica.py); AutoscalingStateManager.drop_stale_handle_metrics
  takes Set[Optional[str]] (STARTING replicas have no actor id yet); and
  NodePortManager.update_ports takes tuples with Optional node-id/ports
  (pending replicas are not fully allocated, and the body already guarded
  those None cases). These let the corresponding casts be dropped.

- Narrow invariant-guaranteed Optionals with assert instead of cast
  (application_state target-state / build-task fields; replica autoscaling
  config, grpc/http options, actor id, user-hook callables; controller
  route_prefix and actor id).

- Use early returns where None is a real (handled) case (docs_path,
  ingress replica details); prefer direct indexing over .get()+cast where
  a lookup must succeed (application_args). Import RoutePattern/KeyType
  normally (no circular dep) instead of under TYPE_CHECKING.

Casts kept only where load-bearing, each documented inline: cross-language
replicas reach SUCCEEDED/RUNNING with node_id/rank None (asserting aborts
the controller loop); conditional streaming callbacks; type refinements the
declared signature cannot express (awaitable return, Hashable->str keys, Any
from decompression); and a self-attribute assert in __init__ would poison
mypy inference of later attributes.

Both serve type-check hooks stay green over all allowlisted files.

Signed-off-by: john.taylor <[email protected]>
- deployment_state: add DeploymentState._deployed_info property (asserts the
  target info is set) and use it in place of the per-site type: ignore on
  self._target_state.info; keep the one genuinely-Optional try/except access.
- get_alive_replica_actor_ids: filter None so the return stays Set[str];
  revert drop_stale_handle_metrics signatures back to Set[str].
- controller.get_deployment_timestamps: return None explicitly.
- application_state: skip actor configs without a name (no None key); move the
  deployment_infos assert ahead of the try.
- replica: drop the unconditional casts; assert generator_result_callback and
  asgi_args at their use sites instead.

Signed-off-by: john.taylor <[email protected]>
…racing code

- target_info must not route through the asserting _deployed_info: it is None
  before the first deploy and callers (e.g. _record_deployment_usage) guard on
  None, so asserting broke deploying any new deployment. Reverted it to the
  ignore-based accessor (flagged by Cursor Bugbot on 4928355).
- _advance_shutdown (new upstream code): assert the shutdown-tier attributes the
  caller populates before invoking it, so pyrefly can narrow the Optionals.
- replica setup_tracing (new upstream code): ignore the ActorHandle .remote
  attr-defined and the ray.get-overload arg-type false positive.

Signed-off-by: john.taylor <[email protected]>
@johntaylor-cell
johntaylor-cell force-pushed the serve-typecheck-controller branch from 4928355 to 85c7ae9 Compare August 9, 2026 21:20
Its sole live caller (_call_http_entrypoint) always passes a non-None
generator_result_callback (send) and asgi_args, so the Optional advertised a
call mode that no longer exists -- the always-true casts/asserts were the tell.
Drop the Optional on both params and the two now-redundant asserts.

Signed-off-by: john.taylor <[email protected]>

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

Please plan for dropping mypy, in future iterations.

@abrarsheikh
abrarsheikh merged commit ea74d3f into ray-project:master Aug 10, 2026
6 checks passed
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…-project#64753)

This is the second PR to enable mypy and pyrefly on ray/serve. This PR
brings the four controller-critical modules under the mypy and pyrefly
serve hooks: deployment_state.py, replica.py, controller.py, and
application_state.py.

The changes made:
- Fix the type errors in all four files (annotation-driven, with a few
incidental invariant-hardening and one latent-bug fix): Optional for
lazily-populated attrs and honest return types, precise
container/callback annotations, typing.cast for invariants a checker
cannot see, and narrowly-scoped ignores for actor .remote dynamics. Add
the four files to both hook allowlists and pyrefly-serve.toml.
- Two annotations were made honest and rippled to their call sites:
get_ingress_replicas_info now returns Optional node-id/ports (pending
replicas), and get_alive_replica_actor_ids returns Optional actor-ids
(starting replicas); the controller call sites cast to the landed
consumer signatures rather than widening them.

First mypy/pyrefly PR was ray-project#64643.
The PR that initiated this effort is ray-project#63862 (the checkpoint/recovery
state machine where type confusion becomes persistent state corruption).

---------

Signed-off-by: john.taylor <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…-project#64753)

This is the second PR to enable mypy and pyrefly on ray/serve. This PR
brings the four controller-critical modules under the mypy and pyrefly
serve hooks: deployment_state.py, replica.py, controller.py, and
application_state.py.

The changes made:
- Fix the type errors in all four files (annotation-driven, with a few
incidental invariant-hardening and one latent-bug fix): Optional for
lazily-populated attrs and honest return types, precise
container/callback annotations, typing.cast for invariants a checker
cannot see, and narrowly-scoped ignores for actor .remote dynamics. Add
the four files to both hook allowlists and pyrefly-serve.toml.
- Two annotations were made honest and rippled to their call sites:
get_ingress_replicas_info now returns Optional node-id/ports (pending
replicas), and get_alive_replica_actor_ids returns Optional actor-ids
(starting replicas); the controller call sites cast to the landed
consumer signatures rather than widening them.

First mypy/pyrefly PR was ray-project#64643.
The PR that initiated this effort is ray-project#63862 (the checkpoint/recovery
state machine where type confusion becomes persistent state corruption).

---------

Signed-off-by: john.taylor <[email protected]>
Signed-off-by: 400Ping <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#64753)

This is the second PR to enable mypy and pyrefly on ray/serve. This PR
brings the four controller-critical modules under the mypy and pyrefly
serve hooks: deployment_state.py, replica.py, controller.py, and
application_state.py.

The changes made:
- Fix the type errors in all four files (annotation-driven, with a few
incidental invariant-hardening and one latent-bug fix): Optional for
lazily-populated attrs and honest return types, precise
container/callback annotations, typing.cast for invariants a checker
cannot see, and narrowly-scoped ignores for actor .remote dynamics. Add
the four files to both hook allowlists and pyrefly-serve.toml.
- Two annotations were made honest and rippled to their call sites:
get_ingress_replicas_info now returns Optional node-id/ports (pending
replicas), and get_alive_replica_actor_ids returns Optional actor-ids
(starting replicas); the controller call sites cast to the landed
consumer signatures rather than widening them.

First mypy/pyrefly PR was ray-project#64643.
The PR that initiated this effort is ray-project#63862 (the checkpoint/recovery
state machine where type confusion becomes persistent state corruption).

---------

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

2 participants