-
Notifications
You must be signed in to change notification settings - Fork 31
fix: detect free-threaded Python from venv and uv before setting PYTHONMALLOC #539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
not-matthias
wants to merge
2
commits into
main
Choose a base branch
from
cod-296-fails-with-python313-freethreaded
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,103 @@ | ||
| use std::ffi::OsStr; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::Command; | ||
|
|
||
| /// Checks if the Python interpreter supports free-threaded mode. | ||
| /// Returns true if Python is free-threaded (GIL disabled), false otherwise. | ||
| pub fn is_free_threaded_python() -> bool { | ||
| // Use sysconfig.get_config_var("Py_GIL_DISABLED") as recommended by Python docs at https://docs.python.org/3/howto/free-threading-python.html#identifying-free-threaded-python | ||
| let output = Command::new("python") | ||
| .args([ | ||
| "-c", | ||
| "import sysconfig; print(sysconfig.get_config_var('Py_GIL_DISABLED') or 0)", | ||
| ]) | ||
| .output(); | ||
|
|
||
| match output { | ||
| Ok(output) if output.status.success() => { | ||
| let stdout = String::from_utf8_lossy(&output.stdout); | ||
| stdout.trim() == "1" | ||
| use crate::prelude::*; | ||
|
|
||
| /// Free-threaded builds carry the `t` ABI flag. `sys.abiflags` needs no `sysconfig` | ||
| /// import, which fails when `_PYTHON_SYSCONFIGDATA_NAME` names a module the | ||
| /// interpreter does not ship. | ||
| const GIL_DISABLED_PROBE: &str = "import sys; print(int('t' in sys.abiflags))"; | ||
|
|
||
| /// Returns true if any Python interpreter the benchmark command could resolve to is | ||
| /// free-threaded: PATH `python`/`python3`, `$VIRTUAL_ENV`, the working directory's | ||
| /// `.venv`, and the interpreter `uv` selects for `$UV_PYTHON`. | ||
| /// | ||
| /// `uv` downloads a requested interpreter lazily, so when `$UV_PYTHON` is not installed | ||
| /// yet the request string itself decides. | ||
| pub fn is_free_threaded_python(working_directory: Option<&Path>) -> bool { | ||
| let cwd = working_directory.unwrap_or(Path::new(".")); | ||
|
|
||
| let mut candidates: Vec<PathBuf> = vec![PathBuf::from("python"), PathBuf::from("python3")]; | ||
| if let Some(venv) = std::env::var_os("VIRTUAL_ENV") { | ||
| candidates.push(Path::new(&venv).join("bin/python")); | ||
| } | ||
| candidates.push(cwd.join(".venv/bin/python")); | ||
| if let Some(request) = std::env::var_os("UV_PYTHON") { | ||
| match uv_python_find(&request, cwd) { | ||
| Some(python) => candidates.push(python), | ||
| None if is_free_threaded_request(&request.to_string_lossy()) => { | ||
| debug!("free-threaded Python requested via UV_PYTHON={request:?}"); | ||
| return true; | ||
| } | ||
| None => {} | ||
| } | ||
| _ => false, // If Python is not available or command fails, assume not free-threaded | ||
| } | ||
|
|
||
| candidates.into_iter().any(|python| { | ||
| let free_threaded = is_gil_disabled(&python); | ||
| if free_threaded { | ||
| debug!("detected free-threaded Python: {}", python.display()); | ||
| } | ||
| free_threaded | ||
| }) | ||
| } | ||
|
|
||
| fn is_gil_disabled(python: &Path) -> bool { | ||
| let Ok(output) = Command::new(python) | ||
| .args(["-c", GIL_DISABLED_PROBE]) | ||
| .output() | ||
| else { | ||
| return false; | ||
| }; | ||
| output.status.success() && String::from_utf8_lossy(&output.stdout).trim() == "1" | ||
| } | ||
|
|
||
| fn uv_python_find(request: &OsStr, cwd: &Path) -> Option<PathBuf> { | ||
| let output = Command::new("uv") | ||
| .args(["python", "find"]) | ||
| .arg(request) | ||
| .current_dir(cwd) | ||
| .output() | ||
| .ok()?; | ||
| if !output.status.success() { | ||
| return None; | ||
| } | ||
| let path = String::from_utf8_lossy(&output.stdout).trim().to_owned(); | ||
| (!path.is_empty()).then(|| PathBuf::from(path)) | ||
| } | ||
|
|
||
| /// Matches a full key variant (`cpython-3.13.0+freethreaded-linux-x86_64-gnu`) or a | ||
| /// version with the `t` suffix (`3.13t`, `cpython@3.13.1t`). | ||
| fn is_free_threaded_request(request: &str) -> bool { | ||
| if request.contains("+freethreaded") { | ||
| return true; | ||
| } | ||
| request.split(['-', '@']).any(|segment| { | ||
| let Some(version) = segment.strip_suffix('t') else { | ||
| return false; | ||
| }; | ||
| version.ends_with(|c: char| c.is_ascii_digit()) | ||
| }) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::is_free_threaded_request; | ||
| use rstest::rstest; | ||
|
|
||
| #[rstest] | ||
| #[case("3.13t", true)] | ||
| #[case("3.13.1t", true)] | ||
| #[case("cpython@3.14t", true)] | ||
| #[case("cpython-3.13t-linux-x86_64-gnu", true)] | ||
| #[case("cpython-3.13.0+freethreaded-linux-x86_64-gnu", true)] | ||
| #[case("3.13", false)] | ||
| #[case("cpython@3.13", false)] | ||
| #[case("cpython-3.13.0-linux-x86_64-gnu", false)] | ||
| #[case("pypy@3.10", false)] | ||
| #[case("graalpy", false)] | ||
| fn classifies_uv_python_request(#[case] request: &str, #[case] expected: bool) { | ||
| assert_eq!(is_free_threaded_request(request), expected); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
python3.13t script.pyor apytestconsole script from a custom-named virtual environment. Those commands are accepted as arbitrary shell commands, but detection checks onlypython,python3, two conventional virtual-environment paths, andUV_PYTHON. The detector therefore returns false,measuresetsPYTHONMALLOC=malloc, and the free-threaded interpreter refuses to start. Resolve or probe the interpreter used by the configured command rather than assuming this list covers every possible interpreter.Knowledge Base Used: Valgrind measurement
Prompt To Fix With AI