Skip to content

Conversation

@michaelfeil
Copy link
Contributor

@michaelfeil michaelfeil commented Jul 28, 2025

Overview:

Details:

Where should the reviewer start?

Related Issues: (use one of the action keywords Closes / Fixes / Resolves / Relates to)

  • closes GitHub issue: #xxx

Summary by CodeRabbit

  • New Features
    • Introduced a new context object accessible from Python, enabling both synchronous and asynchronous methods to query and control the context's state.
    • Python endpoint functions can now receive a context argument, allowing access to context-specific information and controls.
  • Enhancements
    • Logging now includes additional context information for improved traceability.
  • Integration
    • Context objects are now passed automatically to endpoint functions when supported, improving extensibility for advanced use cases.

@copy-pr-bot
Copy link

copy-pr-bot bot commented Jul 28, 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.

@github-actions
Copy link

👋 Hi michaelfeil! Thank you for contributing to ai-dynamo/dynamo.

Just a reminder: The NVIDIA Test Github Validation CI runs an essential subset of the testing framework to quickly catch errors.Your PR reviewers may elect to test the changes comprehensively before approving your changes.

🚀

@github-actions github-actions bot added the external-contribution Pull request is from an external contributor label Jul 28, 2025
@michaelfeil michaelfeil changed the title add test pycontext feat: pycontext, propagating the is_stopped into python land. Jul 28, 2025
@github-actions github-actions bot added the feat label Jul 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 28, 2025

Walkthrough

A new Python context object (Context/PyContext) is introduced and integrated into the request handling pipeline, spanning Rust and Python bindings. The context object is now passed to endpoint generator functions and is accessible in Python, with both synchronous and asynchronous methods exposed for context lifecycle management. Decorator logic is updated to inject the context where needed.

Changes

Cohort / File(s) Change Summary
Python Example Update
examples/runtime/hello_world/hello_world.py
Modified content_generator to accept a Context parameter, updated logging to include context.id(), and imported Context from dynamo.runtime.
Rust Python Context Binding
lib/bindings/python/rust/context.rs
Added new file defining PyContext, a Python-exposed wrapper for AsyncEngineContext, with both sync and async methods for state inspection and control.
Rust Engine Integration
lib/bindings/python/rust/engine.rs
Updated to pass the new Python context object as an argument to the Python generator call within PythonServerStreamingEngine.
Rust Python Module Registration
lib/bindings/python/rust/lib.rs
Registered the new PyContext class in the Python module _core by importing and adding the context module.
Python Decorator Context Injection
lib/bindings/python/src/dynamo/runtime/__init__.py
Enhanced dynamo_endpoint decorator to detect and inject a Context argument into endpoint functions if present.

Sequence Diagram(s)

sequenceDiagram
    participant RustEngine
    participant PythonGenerator
    participant Context

    RustEngine->>Context: Create PyContext from AsyncEngineContext
    RustEngine->>PythonGenerator: Call generator(request, context)
    PythonGenerator->>Context: Access context.id(), is_stopped(), etc.
    PythonGenerator-->>RustEngine: Yield/return results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

In the garden of code, a new context appears,
Hopping from Rust to Python, bringing us cheers.
Now endpoints grow wiser, with context in tow,
They know when to stop, and which way to go.
With every async hop, our engines delight—
A rabbit’s proud leap makes the future more bright! 🐇✨


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: 4

🧹 Nitpick comments (2)
lib/bindings/python/rust/context.rs (2)

7-7: Fix typo in comment.

"jsut" should be "just".

-// Not all methods of the AsyncEngineContext are exposed, jsut the primary ones for tracing + cancellation.
+// Not all methods of the AsyncEngineContext are exposed, just the primary ones for tracing + cancellation.

32-34: Fix missing semicolon in stop_generating method.

For consistency with Rust conventions, void methods should end with a semicolon.

 fn stop_generating(&self) {
-    self.inner.stop_generating();
+    self.inner.stop_generating();
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cfc6178 and cefe9ea.

📒 Files selected for processing (5)
  • examples/runtime/hello_world/hello_world.py (1 hunks)
  • lib/bindings/python/rust/context.rs (1 hunks)
  • lib/bindings/python/rust/engine.rs (3 hunks)
  • lib/bindings/python/rust/lib.rs (2 hunks)
  • lib/bindings/python/src/dynamo/runtime/__init__.py (3 hunks)
🧰 Additional context used
🧠 Learnings (5)
lib/bindings/python/rust/lib.rs (1)

Learnt from: ryanolson
PR: #1919
File: lib/runtime/src/engine.rs:168-168
Timestamp: 2025-07-14T21:25:56.930Z
Learning: The AsyncEngineContextProvider trait in lib/runtime/src/engine.rs was intentionally changed from Send + Sync + Debug to Send + Debug because the Sync bound was overly constraining. The trait should only require Send + Debug as designed.

examples/runtime/hello_world/hello_world.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.

lib/bindings/python/rust/engine.rs (2)

Learnt from: ryanolson
PR: #1919
File: lib/runtime/src/engine.rs:168-168
Timestamp: 2025-07-14T21:25:56.930Z
Learning: The AsyncEngineContextProvider trait in lib/runtime/src/engine.rs was intentionally changed from Send + Sync + Debug to Send + Debug because the Sync bound was overly constraining. The trait should only require Send + Debug as designed.

Learnt from: PeaBrane
PR: #1236
File: lib/llm/src/mocker/engine.rs:140-161
Timestamp: 2025-06-17T00:50:44.845Z
Learning: In Rust async code, when an Arc<Mutex<_>> is used solely to transfer ownership of a resource (like a channel receiver) into a spawned task rather than for sharing between multiple tasks, holding the mutex lock across an await is not problematic since there's no actual contention.

lib/bindings/python/src/dynamo/runtime/__init__.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.

lib/bindings/python/rust/context.rs (1)

Learnt from: ryanolson
PR: #1919
File: lib/runtime/src/engine.rs:168-168
Timestamp: 2025-07-14T21:25:56.930Z
Learning: The AsyncEngineContextProvider trait in lib/runtime/src/engine.rs was intentionally changed from Send + Sync + Debug to Send + Debug because the Sync bound was overly constraining. The trait should only require Send + Debug as designed.

🪛 GitHub Actions: Pre Merge Validation of (ai-dynamo/dynamo/refs/pull/2158/merge) by michaelfeil.
examples/runtime/hello_world/hello_world.py

[error] 18-26: isort formatting check failed. Imports were reordered. Please run 'isort' to fix import order.

lib/bindings/python/src/dynamo/runtime/__init__.py

[error] 15-90: isort and black formatting checks failed. File was modified to fix import order and code style. Please run 'isort' and 'black' to fix formatting issues.

🪛 GitHub Actions: Copyright Checks
lib/bindings/python/rust/context.rs

[error] 1-1: Invalid or missing copyright header detected by copyright checker. File is out of compliance with required SPDX 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). (3)
  • GitHub Check: Build and Test - vllm
  • GitHub Check: pre-merge-rust (lib/runtime/examples)
  • GitHub Check: pre-merge-rust (.)
🔇 Additional comments (10)
lib/bindings/python/rust/lib.rs (2)

46-46: LGTM!

Correctly declares the new context module.


104-104: LGTM!

Properly registers the PyContext class in the Python module, making it accessible from Python code.

examples/runtime/hello_world/hello_world.py (1)

30-31: LGTM!

The function signature correctly accepts the context parameter and the logging demonstrates proper usage of the context ID. This is a good example of how to use the new context functionality.

lib/bindings/python/rust/engine.rs (3)

18-18: LGTM!

Correctly imports the PyContext module for use in the engine.


167-167: LGTM!

The context cloning is safe due to the Arc wrapper and enables passing the context to Python.


182-184: LGTM!

The PyContext creation and argument passing to the Python generator is correctly implemented. The context is properly wrapped and passed as the second argument, enabling Python code to access the context functionality.

lib/bindings/python/src/dynamo/runtime/__init__.py (3)

32-32: LGTM!

Correctly imports and aliases PyContext as Context for Python use.


69-69: LGTM!

Properly uses function signature introspection to detect if the function accepts a context parameter.


75-80: LGTM!

The context detection and injection logic is well-implemented. It correctly:

  • Detects if the last argument is a Context instance
  • Separates the context from other arguments
  • Injects the context into kwargs if the function accepts it
  • Preserves the existing request processing logic
lib/bindings/python/rust/context.rs (1)

44-63: LGTM!

The async_is_stopped method is well-implemented with proper:

  • Input validation for timeout bounds
  • Timeout handling using tokio::time::timeout
  • Proper async-to-Python conversion using pyo3_async_runtimes
  • Correct logic for checking stopped/killed state

@pull-request-size pull-request-size bot added size/L and removed size/M labels Aug 19, 2025
@michaelfeil
Copy link
Contributor Author

michaelfeil commented Aug 19, 2025

@kthui As discussed, I moved the inspect code inside of rust. This should make the end-2-end examples pass. inspect is part of the python3 std libary, and can be always used via py03.

Ready to be merged / please squash and merge.

Copy link
Contributor

@kthui kthui left a comment

Choose a reason for hiding this comment

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

Looks good to me! I like the idea you keep the signature check in Rust.

@kthui
Copy link
Contributor

kthui commented Aug 19, 2025

@nnshah1 can you also help review this PR? We need a reviewer with devops and Python permission on the Cargo.lock and .py files.

The change passed TRT-LLM and SGLang 1 GPU E2E test on pipeline #33470282

@kthui kthui enabled auto-merge (squash) August 19, 2025 02:41
@kthui kthui disabled auto-merge August 19, 2025 17:34
@kthui kthui enabled auto-merge (squash) August 20, 2025 01:56
@kthui kthui disabled auto-merge August 20, 2025 01:56
@kthui kthui enabled auto-merge (squash) August 20, 2025 02:12
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.

Approving to unblock as this has been sitting a couple days - approved by Jacky as PIC and assuming signoff from @ryanolson @nnshah1 from discussions

@rmccorm4 rmccorm4 disabled auto-merge August 20, 2025 17:09
@kthui kthui requested a review from ryanolson August 20, 2025 17:59
@kthui kthui merged commit 626d7e1 into ai-dynamo:main Aug 20, 2025
11 checks passed
@kthui
Copy link
Contributor

kthui commented Aug 20, 2025

Congratulations @michaelfeil on getting your first PR merged into main!

This feature updates some of the deeper Dynamo interfaces. I believe your future PRs will be much smoother now that you've successfully implemented this in-depth feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

external-contribution Pull request is from an external contributor fault tolerance feat size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants