Skip to content

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Jan 14, 2026

Summary by CodeRabbit

  • New Features
    • Context variables are now iterable and provide an items() view; context tokens support with-statement management.
    • Lock and reentrant lock objects now expose a locked() method to check their state.
    • Threads can be named via a new set_name() function with platform-specific behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 14, 2026

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Extends PyContext to support Python iteration and items(); adds ContextToken enter/exit for with-statement semantics; adds locked() on Lock/RLock and a platform-aware set_name(name: PyStrRef) thread API.

Changes

Cohort / File(s) Summary
PyContext Iterable & items
crates/stdlib/src/contextvars.rs
Added Iterable in #[pyclass(...)]; implemented Iterable for PyContext to iterate keys; added items(self, vm) returning key-value tuple list; adjusted imports (PyList, Iterable).
ContextToken context manager
crates/stdlib/src/contextvars.rs
Added __enter__ returning the token and __exit__ delegating to ContextVar::reset to support with semantics.
Lock/RLock locked() & thread naming
crates/vm/src/stdlib/thread.rs
Added locked(&self) -> bool methods to Lock and RLock; added #[pyfunction] set_name(name: PyStrRef) with platform-specific implementations (Linux/macOS/Windows/others); added PyStrRef import.

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • thread.setname and context #6726: Very closely related changes touching crates/stdlib/src/contextvars.rs and crates/vm/src/stdlib/thread.rs (Iterable/items, ContextToken context manager, locked/set_name additions).

Poem

🐰 I hopped through code with nimble paws,
I added iteration with no pause,
Tokens enter, tokens flee,
Locks now whisper truth to me,
Threads may wear their names with glee.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title refers to two real changes in the PR: thread.setname functionality and context-related modifications (PyContext Iterable implementation), but is vague and does not clearly convey the primary purpose or specifics of either change. Revise title to be more specific and descriptive, such as 'Add thread.set_name() function and context iteration support' or similar, to clearly indicate what functionality is being introduced.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 890b018 and d22c48b.

📒 Files selected for processing (1)
  • crates/vm/src/stdlib/thread.rs

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@youknowone youknowone marked this pull request as ready for review January 14, 2026 07:59
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: 1

🧹 Nitpick comments (1)
crates/vm/src/stdlib/thread.rs (1)

319-327: Consider adding truncation for macOS thread names.

macOS pthread_setname_np has a 64-byte limit. While less restrictive than Linux, names exceeding this limit will cause the call to fail silently. Consider adding truncation similar to the Linux implementation for consistency.

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2e5257d and 890b018.

📒 Files selected for processing (2)
  • crates/stdlib/src/contextvars.rs
  • crates/vm/src/stdlib/thread.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint code (cargo clippy) before completing tasks and fix any warnings or lints introduced by changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass, pymodule, pyfunction, etc.) when implementing Python functionality in Rust

Files:

  • crates/vm/src/stdlib/thread.rs
  • crates/stdlib/src/contextvars.rs
🧠 Learnings (1)
📚 Learning: 2025-12-27T14:03:49.034Z
Learnt from: CR
Repo: RustPython/RustPython PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-27T14:03:49.034Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust

Applied to files:

  • crates/stdlib/src/contextvars.rs
🧬 Code graph analysis (1)
crates/stdlib/src/contextvars.rs (2)
crates/stdlib/src/mmap.rs (2)
  • __enter__ (1257-1260)
  • __exit__ (1263-1265)
crates/stdlib/src/select.rs (2)
  • __enter__ (723-726)
  • __exit__ (729-736)
🔇 Additional comments (8)
crates/vm/src/stdlib/thread.rs (3)

12-12: LGTM!

The import addition of PyStrRef is needed to support the new set_name function parameter type.


171-174: LGTM!

The locked method correctly exposes the lock state and follows the existing pattern used in repr_lock_impl! and release methods.


263-266: LGTM!

The locked method implementation for RLock is consistent with the Lock implementation.

crates/stdlib/src/contextvars.rs (5)

27-32: LGTM!

Import additions for PyList and Iterable are necessary to support the new Iterable implementation for PyContext.


166-166: LGTM!

Adding Iterable to the pyclass decorator properly integrates the new iteration capability.


237-244: LGTM!

The items method implementation is consistent with the existing keys and values methods. The TODO comment appropriately notes the return type should eventually be a proper view type.


288-295: LGTM!

The Iterable implementation correctly creates a snapshot of keys and delegates to PyList's iterator. This approach is safe and avoids holding the borrow during iteration.


590-605: LGTM!

The context manager implementation for ContextToken is correct:

  • __enter__ returns self following standard patterns (similar to mmap.rs and select.rs).
  • __exit__ properly delegates to ContextVar::reset, which handles restoring the previous value and marking the token as used to prevent reuse.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines 304 to 317
#[cfg(target_os = "linux")]
{
use std::ffi::CString;
if let Ok(c_name) = CString::new(name.as_str()) {
// pthread_setname_np on Linux has a 16-byte limit including null terminator
let truncated = if c_name.as_bytes().len() > 15 {
CString::new(&c_name.as_bytes()[..15]).unwrap_or(c_name)
} else {
c_name
};
unsafe {
libc::pthread_setname_np(libc::pthread_self(), truncated.as_ptr());
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Potential UTF-8 boundary issue when truncating thread name on Linux.

The truncation at byte 15 may split a multi-byte UTF-8 character, producing an invalid UTF-8 sequence. While CString::new won't fail (it only checks for interior nulls), passing invalid UTF-8 to the OS could cause unexpected behavior.

Consider truncating at a valid UTF-8 character boundary:

Proposed fix
         #[cfg(target_os = "linux")]
         {
             use std::ffi::CString;
             if let Ok(c_name) = CString::new(name.as_str()) {
                 // pthread_setname_np on Linux has a 16-byte limit including null terminator
-                let truncated = if c_name.as_bytes().len() > 15 {
-                    CString::new(&c_name.as_bytes()[..15]).unwrap_or(c_name)
+                let truncated = if name.as_str().len() > 15 {
+                    // Find a valid UTF-8 boundary at or before byte 15
+                    let s = name.as_str();
+                    let mut end = 15;
+                    while end > 0 && !s.is_char_boundary(end) {
+                        end -= 1;
+                    }
+                    CString::new(&s[..end]).unwrap_or(c_name)
                 } else {
                     c_name
                 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[cfg(target_os = "linux")]
{
use std::ffi::CString;
if let Ok(c_name) = CString::new(name.as_str()) {
// pthread_setname_np on Linux has a 16-byte limit including null terminator
let truncated = if c_name.as_bytes().len() > 15 {
CString::new(&c_name.as_bytes()[..15]).unwrap_or(c_name)
} else {
c_name
};
unsafe {
libc::pthread_setname_np(libc::pthread_self(), truncated.as_ptr());
}
}
#[cfg(target_os = "linux")]
{
use std::ffi::CString;
if let Ok(c_name) = CString::new(name.as_str()) {
// pthread_setname_np on Linux has a 16-byte limit including null terminator
let truncated = if name.as_str().len() > 15 {
// Find a valid UTF-8 boundary at or before byte 15
let s = name.as_str();
let mut end = 15;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
CString::new(&s[..end]).unwrap_or(c_name)
} else {
c_name
};
unsafe {
libc::pthread_setname_np(libc::pthread_self(), truncated.as_ptr());
}
}
}

@youknowone youknowone merged commit 3d4aaaa into RustPython:main Jan 14, 2026
10 of 13 checks passed
@youknowone youknowone deleted the thread-context branch January 14, 2026 08:20
terryluan12 pushed a commit to terryluan12/RustPython that referenced this pull request Jan 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant