Repository navigation
[serve] Enforce type checking on the controller-critical modules - #64753
Conversation
There was a problem hiding this comment.
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.
|
@gemini-code-assist thanks — applied all of your suggestions in c86affa. Replaced the invariant type-ignore comments with Also fixed the genuine bug you caught: Both serve type-check hooks stay green over the four files. The lint shard here is red only on the pre-existing |
|
Thanks for the update, @johntaylor-cell. The changes look great—using |
abrarsheikh
left a comment
There was a problem hiding this comment.
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.
d946be4 to
087c031
Compare
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. |
f4882cb to
b30451a
Compare
11e62c9 to
d897ad2
Compare
|
This pull request has been automatically marked as stale because it has not had 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. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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]>
4928355 to
85c7ae9
Compare
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
left a comment
There was a problem hiding this comment.
Please plan for dropping mypy, in future iterations.
…-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]>
…-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]>
…-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]>

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