Skip to content

Conversation

@ishandhanani
Copy link
Contributor

@ishandhanani ishandhanani commented Jul 30, 2025

Summary by CodeRabbit

  • Documentation

    • Removed placeholder sections for "Speculative Decoding" and "Structured Output and Tool Calling" from the SGLang backend README.
  • New Features

    • Introduced a new base handler for worker endpoints, providing unified methods for cache management and expert distribution recording.
    • Added a graceful shutdown utility for improved runtime management.
  • Refactor

    • Updated worker and decode handler classes to inherit from the new base handler and use shared utilities, streamlining code structure and imports.

@copy-pr-bot
Copy link

copy-pr-bot bot commented Jul 30, 2025

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 30, 2025

Walkthrough

This change introduces a new common module for sglang worker handlers, refactors both decode and worker handler classes to inherit from a shared abstract base class, and centralizes utility functions such as graceful shutdown. It also removes placeholder documentation sections from the SGLang backend README.

Changes

Cohort / File(s) Change Summary
Common Module Introduction & Re-exports
components/backends/sglang/src/dynamo/sglang/common/__init__.py
Adds a new __init__.py to re-export base handler, protocol types, and utility functions, defining the public API for the common package.
Base Handler Implementation
components/backends/sglang/src/dynamo/sglang/common/base_handlers.py
Introduces BaseWorkerHandler abstract class for sglang worker endpoints, with required async methods for generation, cache flushing, and expert distribution recording/dumping.
Utility Function Enhancement
components/backends/sglang/src/dynamo/sglang/common/sgl_utils.py
Adds logging and an async graceful_shutdown(runtime) function for orderly shutdown of runtimes.
Decode Worker Refactor
components/backends/sglang/src/dynamo/sglang/decode_worker/main.py
Refactors DecodeRequestHandler to inherit from BaseWorkerHandler, updates constructor, removes local flush_cache and graceful_shutdown, and imports shared utilities from the new common module.
Worker Refactor
components/backends/sglang/src/dynamo/sglang/worker/main.py
Refactors RequestHandler to inherit from BaseWorkerHandler, updates constructor, removes local graceful_shutdown, and imports shared utilities from the new common module.
Documentation Cleanup
components/backends/sglang/README.md
Removes placeholder subsections for "Speculative Decoding" and "Structured Output and Tool Calling" under "Advanced Examples."

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WorkerHandler (BaseWorkerHandler)
    participant Engine
    participant Runtime

    User->>WorkerHandler: generate(request)
    WorkerHandler->>Engine: generate tokens
    Engine-->>WorkerHandler: tokens/result
    WorkerHandler-->>User: response

    User->>WorkerHandler: flush_cache(request)
    WorkerHandler->>Engine: flush_cache()
    Engine-->>WorkerHandler: result
    WorkerHandler-->>User: {"success": True/False, "msg": ...}

    User->>WorkerHandler: start_expert_distribution_record(request)
    WorkerHandler->>Engine: start_recording()
    WorkerHandler-->>User: {"success": True, "msg": ...}

    User->>WorkerHandler: stop_expert_distribution_record(request)
    WorkerHandler->>Engine: stop_recording()
    WorkerHandler-->>User: {"success": True, "msg": ...}

    User->>WorkerHandler: dump_expert_distribution_record(request)
    WorkerHandler->>Engine: dump_record()
    WorkerHandler-->>User: {"success": True/False, "msg": ...}

    Note over WorkerHandler,Runtime: On shutdown signal
    WorkerHandler->>Runtime: graceful_shutdown()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

  • feat: add dynamo components for sglang #1721: Refactored DecodeRequestHandler to inherit from BaseWorkerHandler and centralized the graceful_shutdown function, directly related to the handler and utility refactoring in this PR.

Poem

A rabbit hops through code so neat,
Refactors shared, a tidy feat!
Handlers now with common base,
Utilities in a single place.
Old docs trimmed, the garden pruned—
The sglang meadow’s freshly tuned!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
components/backends/sglang/src/dynamo/sglang/common/base_handlers.py (2)

15-26: Consider making init concrete instead of abstract.

Making the constructor abstract is unusual in Python. Since all subclasses need the same base initialization logic, consider making this a concrete method that subclasses can call via super().__init__().

-    @abstractmethod
-    def __init__(
+    def __init__(
         self,
         engine: sgl.Engine,
         server_args: ServerArgs,
         component,
         decode_client: Optional[Any] = None,
     ):
         self.engine = engine
         self.server_args = server_args
         self.component = component

70-84: Improve directory validation and error handling.

The directory validation logic could be more robust by checking if the path is actually a directory and handling edge cases.

         # Validate directory
-        if not os.path.exists(dir):
+        if not os.path.exists(dir):
             yield {
                 "status": "error",
                 "message": f"Directory {dir} does not exist",
             }
             return
+        
+        if not os.path.isdir(dir):
+            yield {
+                "status": "error", 
+                "message": f"Path {dir} is not a directory",
+            }
+            return
components/backends/sglang/src/dynamo/sglang/worker/main.py (1)

287-293: Clarify flush_cache method override.

This class has its own flush_cache method that differs from the base class implementation (uses tokenizer_manager.flush_cache() vs engine.flush_cache()). Consider adding a comment explaining why this override is necessary.

     async def flush_cache(self, request: dict):
+        """Override base class to use tokenizer_manager for worker-specific cache flushing"""
         _ = request
         asyncio.create_task(self.engine.tokenizer_manager.flush_cache())
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between da0c572 and 9ac4f86.

📒 Files selected for processing (6)
  • components/backends/sglang/README.md (0 hunks)
  • components/backends/sglang/src/dynamo/sglang/common/__init__.py (1 hunks)
  • components/backends/sglang/src/dynamo/sglang/common/base_handlers.py (1 hunks)
  • components/backends/sglang/src/dynamo/sglang/common/sgl_utils.py (2 hunks)
  • components/backends/sglang/src/dynamo/sglang/decode_worker/main.py (2 hunks)
  • components/backends/sglang/src/dynamo/sglang/worker/main.py (1 hunks)
💤 Files with no reviewable changes (1)
  • components/backends/sglang/README.md
🧰 Additional context used
🧠 Learnings (3)
components/backends/sglang/src/dynamo/sglang/common/sgl_utils.py (1)

Learnt from: nnshah1
PR: #1444
File: tests/fault_tolerance/utils/metrics.py:30-32
Timestamp: 2025-07-01T13:55:03.940Z
Learning: The @dynamo_worker() decorator in the dynamo codebase returns a wrapper that automatically injects the runtime parameter before calling the wrapped function. This means callers only need to provide the non-runtime parameters, while the decorator handles injecting the runtime argument automatically. For example, a function with signature async def get_metrics(runtime, log_dir) decorated with @dynamo_worker() can be called as get_metrics(log_dir) because the decorator wrapper injects the runtime parameter.

components/backends/sglang/src/dynamo/sglang/decode_worker/main.py (1)

Learnt from: nnshah1
PR: #1444
File: tests/fault_tolerance/utils/metrics.py:30-32
Timestamp: 2025-07-01T13:55:03.940Z
Learning: The @dynamo_worker() decorator in the dynamo codebase returns a wrapper that automatically injects the runtime parameter before calling the wrapped function. This means callers only need to provide the non-runtime parameters, while the decorator handles injecting the runtime argument automatically. For example, a function with signature async def get_metrics(runtime, log_dir) decorated with @dynamo_worker() can be called as get_metrics(log_dir) because the decorator wrapper injects the runtime parameter.

components/backends/sglang/src/dynamo/sglang/worker/main.py (1)

Learnt from: nnshah1
PR: #1444
File: tests/fault_tolerance/utils/metrics.py:30-32
Timestamp: 2025-07-01T13:55:03.940Z
Learning: The @dynamo_worker() decorator in the dynamo codebase returns a wrapper that automatically injects the runtime parameter before calling the wrapped function. This means callers only need to provide the non-runtime parameters, while the decorator handles injecting the runtime argument automatically. For example, a function with signature async def get_metrics(runtime, log_dir) decorated with @dynamo_worker() can be called as get_metrics(log_dir) because the decorator wrapper injects the runtime parameter.

🪛 GitHub Actions: Copyright Checks
components/backends/sglang/src/dynamo/sglang/common/base_handlers.py

[error] 1-1: Copyright check failed: Invalid or missing copyright header.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: pre-merge-rust (lib/runtime/examples)
  • GitHub Check: pre-merge-rust (.)
  • GitHub Check: pre-merge-rust (lib/bindings/python)
  • GitHub Check: Build and Test - vllm
🔇 Additional comments (7)
components/backends/sglang/src/dynamo/sglang/common/sgl_utils.py (2)

18-18: LGTM: Logging import added appropriately.

The logging import is correctly added to support the new graceful_shutdown function.


61-64: LGTM: Clean graceful shutdown implementation.

The graceful_shutdown function is well-implemented with appropriate logging and clean separation of concerns. The function signature correctly expects the runtime parameter to be passed explicitly, which aligns with how it's called in the worker modules.

components/backends/sglang/src/dynamo/sglang/worker/main.py (2)

30-35: LGTM: Clean import consolidation.

The import consolidation from dynamo.sglang.common improves code organization and reduces import complexity.


40-48: LGTM: Proper inheritance implementation.

The RequestHandler class correctly inherits from BaseWorkerHandler and properly calls the superclass constructor.

components/backends/sglang/src/dynamo/sglang/decode_worker/main.py (3)

18-22: LGTM: Consistent import consolidation.

The import consolidation follows the same pattern as the worker module, improving consistency across the codebase.


27-29: LGTM: Proper base class integration.

The DecodeRequestHandler correctly inherits from BaseWorkerHandler and the constructor properly passes the required parameters to the superclass.


79-79: LGTM: Handler instantiation updated correctly.

The handler instantiation correctly includes the new server_args and component parameters required by the updated constructor.

@ishandhanani ishandhanani changed the title feat: reorg sgl feat: reorganize sglang and add expert distribution endpoints Jul 30, 2025
@ishandhanani
Copy link
Contributor Author

/ok to test ba4bc6e

@PeaBrane
Copy link
Contributor

PeaBrane commented Jul 30, 2025

@ishandhanani would it make sense to put the benchmarking scripts somewhere in benchmarks.

Also, not part of this PR, but there are some duplicate instructions in the README.md that already exists in the top-level README.md (launching etcd nats, support matrix, etc). Should we slim it down?

Copy link
Contributor

@biswapanda biswapanda left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

Copy link
Contributor

@rmccorm4 rmccorm4 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

left some non-blocking comments/questions

@ishandhanani ishandhanani merged commit 3bf22bb into main Jul 31, 2025
9 checks passed
@ishandhanani ishandhanani deleted the ishan/more-sgl branch July 31, 2025 18:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants