← Back to Pull requests

Cover virtual environment interpreter caching through symlinks #2547

Open
astral-automations-bot[bot] opened this pull request with 468 lines diff across 2 files
View on GitHub
astral-automations-bot[bot] astral-automations-bot[bot] commented on Oct 09, 2026 06:17 UTC
Author

Characterize interpreter-cache behavior for symlinked Python executables, including environment recreation, absolute symlink targets, and the executable-symlink limit. Keep regular executables and parent environments as separate controls, and expose stale base paths retained in interpreter-v4.

Refs astral-sh/uv#22383.

Stacked on astral-sh/uv#22524.

Diff: 468 lines (+429 / -39) across 2 files Reviewer: woodruffw Review duration: 7765m
All Vouch review confidence checks passed
Residual risk 0.03 = Change Risk (0.41) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.41 · 468 lines diff across 2 files
0.41
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.94 · 3 substantive comment(s)
0.94
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
92%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.368
Real PR Conversation Timeline
4 items
codspeed[bot] codspeed[bot] commented on Oct 09, 2026 06:50 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will not alter performance

<details>
<summary>:warning: <b>8 benchmarks spent significant time in system calls</b></summary>

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

> Measurement and system calls

> - ` install_wheel_many_files

- unpack_sdist_many_files

- resolve_warm_airflow

- run_python_version_synthetic_workspace

- resolve_warm_jupyter

- discover_workspace_from_all_members_with_excludes

- resolve_warm_jupyter_universal

- discover_workspace_from_all_members

</details>

✅ 54 untouched benchmarks
⏩ 35` skipped benchmarks[^skipped]

---

<sub>Comparing <code>automations/reproduce-bug/22383</code> (32d694a) with <code>main</code> (06bf2e8)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/astral-sh/uv-dev/branches/automations%2Freproduce-bug%2F22383?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 35 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>zb/restore-interpreter-cache-warming</code> (e83627b) during the generation of this report, so <code>main</code> (06bf2e8) was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

astral-automations-bot[bot] astral-automations-bot[bot] commented on code on Oct 09, 2026 15:36 UTC
Code Review
crates/uv/tests/python/venv.rs:1
@@ -73,51 +77,364 @@ fn create_venv() {
     context.venv.assert(predicates::path::is_dir());
 }
 
-/// Creating a venv caches the same interpreter metadata that Python would report.
+/// Creating a venv from a regular executable caches the metadata that Python reports.
 #[test]
 fn create_venv_caches_interpreter() -> Result<()> {
+    let context = uv_test::test_context_with_versions!(&["3.12"]);
+    let python = context
+        .python_versions
+        .first()
+        .context("No Python installation")?
+        .1
+        .canonicalize()?;
+    let cache = Cache::from_path(context.cache_dir.path().to_path_buf())
+        .init_no_wait()?
+        .context("Interpreter cache is locked")?;
+
+    let root = tempfile::tempdir_in(context.temp_dir.path())?;
+    // Canonicalization adds a Windows verbatim prefix, which Python omits from its metadata.
+    let root_path = root.path().canonicalize()?;
+    context
+        .venv()
+        .arg(&root_path)
+        .arg("--python")
+        .arg(&python)
+        .assert()
+        .success();
+
+    let site_packages = site_packages_path(&root_path, "python3.12");
+    fs_err::write(
+        site_packages.join("interpreter-started.pth"),
+        "import pathlib, sys; pathlib.Path(sys.prefix, 'interpreter-started').touch()\n",
+    )?;
+    let startup_marker = ChildPath::new(root_path.join("interpreter-started"));
+
+    let cached = PythonEnvironment::from_root(&root_path, &cache)?;
+    startup_marker.assert(predicate::path::missing());
+
+    let fresh_cache = Cache::temp()?
+        .init_no_wait()?
+        .context("Fresh interpreter cache is locked")?;
+    let queried = PythonEnvironment::from_root(&root_path, &fresh_cache)?;
+    startup_marker.assert(predicate::path::is_file());
+    assert_eq!(cached, queried);
+
+    Ok(())
+}
+
+/// Creating a venv from another venv caches the metadata that Python reports.
+#[test]
+fn create_venv_caches_interpreter_from_venv() -> Result<()> {
     let context = uv_test::test_context!("3.12");
     let cache = Cache::from_path(context.cache_dir.path().to_path_buf())
         .init_no_wait()?
         .context("Interpreter cache is locked")?;
 
-    // It should cache for both a system interpreter and when starting from another venv.
-    for python in [Path::new("3.12"), context.venv.path()] {
-        let root = tempfile::tempdir_in(context.temp_dir.path())?;
-        // Check that cached metadata matches Python's output even when the venv path has
-        // a Windows verbatim prefix.
-        let root_path = root.path().canonicalize()?;
-        context
-            .venv()
-            .arg(&root_path)
-            .arg("--clear")
-            .arg("--python")
-            .arg(python)
-            .assert()
-            .success();
-
-        let site_packages = site_packages_path(&root_path, "python3.12");
-        fs_err::write(
-            site_packages.join("sitecustomize.py"),
-            indoc! {r#"
-                from pathlib import Path
-
-                Path(__file__).with_name("interpreter-started").touch()
-            "#},
-        )?;
-        let startup_marker = site_packages.join("interpreter-started");
-
-        let cached = PythonEnvironment::from_root(&root_path, &cache)?;
-        assert!(!startup_marker.exists());
-
-        let fresh_cache = Cache::temp()?
-            .init_no_wait()?
-            .context("Fresh interpreter cache is locked")?;
-        let queried = PythonEnvironment::from_root(&root_path, &fresh_cache)?;
-        assert!(startup_marker.is_file());
-        assert_eq!(cached, queried);
+    let root = tempfile::tempdir_in(context.temp_dir.path())?;
+    // Canonicalization adds a Windows verbatim prefix, which Python omits from its metadata.
+    let root_path = root.path().canonicalize()?;
+    context
+        .venv()
+        .arg(&root_path)
+        .arg("--python")
+        .arg(context.venv.path())
+        .assert()
+        .success();
+
+    let site_packages = site_packages_path(&root_path, "python3.12");
+    fs_err::write(
+        site_packages.join("interpreter-started.pth"),
+        "import pathlib, sys; pathlib.Path(sys.prefix, 'interpreter-started').touch()\n",
+    )?;
+    let startup_marker = ChildPath::new(root_path.join("interpreter-started"));
+
+    let cached = PythonEnvironment::from_root(&root_path, &cache)?;
+    startup_marker.assert(predicate::path::missing());
+
+    let fresh_cache = Cache::temp()?
+        .init_no_wait()?
+        .context("Fresh interpreter cache is locked")?;
+    let queried = PythonEnvironment::from_root(&root_path, &fresh_cache)?;
+    startup_marker.assert(predicate::path::is_file());
+    assert_eq!(cached, queried);
+
+    Ok(())
+}
+
+/// A symlink inside a Python installation is retained when deriving cached venv metadata,
+/// but resolved by CPython when querying the venv.
+#[test]
+#[cfg(all(target_os = "linux", feature = "test-python-managed"))]
+fn create_venv_caches_symlinked_base_interpreter() -> Result<()> {
+    let context = uv_test::test_context_with_versions!(&[]).with_managed_python_dirs();
+    context.python_install().arg("3.12.9").assert().success();
+    let output = context.python_find().arg("3.12.9").assert().success();
+    let python = Path::new(std::str::from_utf8(&output.get_output().stdout)?.trim());
+
+    // Move the installation out of the managed directory to avoid transparent patch upgrades.
+    let installation = python
+        .parent()
+        .and_then(Path::parent)
+        .context("Python executable has no installation directory")?;
+    let relocated = context.temp_dir.child("python");
+    fs_err::rename(installation, relocated.path())?;
+    let python_directory = relocated.child("bin");
+    let symlinked_python = python_directory.child("python3");
+    assert!(symlinked_python.is_symlink());
+    let context = context.with_filtered_path(python_directory.path(), "PYTHON_BIN");
+
+    uv_snapshot!(context.filters(), context.venv().arg("--python").arg(symlinked_python.path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: python/bin/python3
+    Creating virtual environment at: .venv
+    Activate with: source .venv/[BIN]/activate
+    ");
+
+    let site_packages = site_packages_path(context.venv.path(), "python3.12");
+    fs_err::write(
+        site_packages.join("interpreter-started.pth"),
+        "import pathlib, sys; pathlib.Path(sys.prefix, 'interpreter-started').touch()\n",
+    )?;
+    let startup_marker = context.venv.child("interpreter-started");
+
+    let cache = Cache::from_path(context.cache_dir.path().to_path_buf())
+        .init_no_wait()?
+        .context("Interpreter cache is locked")?;
+    let cached = PythonEnvironment::from_root(context.venv.path(), &cache)?;
+    startup_marker.assert(predicate::path::missing());
+    let cached_again = PythonEnvironment::from_root(context.venv.path(), &cache)?;
+    startup_marker.assert(predicate::path::missing());
+    assert_eq!(cached, cached_again);
+    let fresh_cache = Cache::temp()?
+        .init_no_wait()?
+        .context("Fresh interpreter cache is locked")?;
+    let queried = PythonEnvironment::from_root(context.venv.path(), &fresh_cache)?;
+    startup_marker.assert(predicate::path::is_file());
+
+    // The base executable should not depend on whether the cache is warm: astral-sh/uv#22383.
+    let cached_base = cached.interpreter().to_base_python()?;
+    let queried_base = queried.interpreter().to_base_python()?;
+    insta::with_settings!({ filters => context.filters() }, {
+        insta::assert_snapshot!(cached_base.display(), @"[PYTHON_BIN]/python3");
+        insta::assert_snapshot!(queried_base.display(), @"[PYTHON_BIN]/python3.12");
+    });
+
+    // Consume the created environment with each cache to expose the different executable targets.
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("cached")
+        .arg("--python")
+        .arg(context.venv.path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: .venv/bin/python
+    Creating virtual environment at: cached
+    Activate with: source cached/[BIN]/activate
+    ");
+    let context = context.with_cache_dir(fresh_cache.root());
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("queried")
+        .arg("--python")
+        .arg(context.venv.path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: .venv/bin/python
+    Creating virtual environment at: queried
+    Activate with: source queried/[BIN]/activate
+    ");
+
+    let cached_target = fs_err::read_link(context.temp_dir.child("cached/bin/python"))?;
+    let queried_target = fs_err::read_link(context.temp_dir.child("queried/bin/python"))?;
+    insta::with_settings!({ filters => context.filters() }, {
+        insta::assert_snapshot!(cached_target.display(), @"[PYTHON_BIN]/python3");
+        insta::assert_snapshot!(queried_target.display(), @"[PYTHON_BIN]/python3.12");
+    });
+
+    Ok(())
+}
+
+/// Recreating a venv through an executable symlink leaves its canonical target unchanged.
+#[test]
+#[cfg(all(target_os = "linux", feature = "test-python-managed"))]
+fn create_venv_caches_recreated_symlinked_interpreter() -> Result<()> {
+    let context = uv_test::test_context_with_versions!(&[]).with_managed_python_dirs();
+    context.python_install().arg("3.12.9").assert().success();
+    let output = context.python_find().arg("3.12.9").assert().success();
+    let python = Path::new(std::str::from_utf8(&output.get_output().stdout)?.trim());
+
+    // Move the installation out of the managed directory to avoid transparent patch upgrades.
+    let installation = python
+        .parent()
+        .and_then(Path::parent)
+        .context("Python executable has no installation directory")?;
+    let relocated = context.temp_dir.child("python");
+    fs_err::rename(installation, relocated.path())?;
+    let python_directory = relocated.child("bin");
+    let context = context.with_filtered_path(python_directory.path(), "PYTHON_BIN");
+
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("--python")
+        .arg(python_directory.child("python3.12").path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: python/bin/python3.12
+    Creating virtual environment at: .venv
+    Activate with: source .venv/[BIN]/activate
+    ");
+
+    let executable_target = fs_err::canonicalize(context.venv.child("bin/python"))?;
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("--clear")
+        .arg("--python")
+        .arg(python_directory.child("python3").path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: python/bin/python3
+    Creating virtual environment at: .venv
+    Activate with: source .venv/[BIN]/activate
+    ");
+    assert_eq!(
+        fs_err::canonicalize(context.venv.child("bin/python"))?,
+        executable_target
+    );
+
+    let site_packages = site_packages_path(context.venv.path(), "python3.12");
+    fs_err::write(
+        site_packages.join("interpreter-started.pth"),
+        "import pathlib, sys; pathlib.Path(sys.prefix, 'interpreter-started').touch()\n",
+    )?;
+    let startup_marker = context.venv.child("interpreter-started");
+    let cache = Cache::from_path(context.cache_dir.path().to_path_buf())
+        .init_no_wait()?
+        .context("Interpreter cache is locked")?;
+    let cached = PythonEnvironment::from_root(context.venv.path(), &cache)?;
+    startup_marker.assert(predicate::path::missing());
+
+    let fresh_cache = Cache::temp()?
+        .init_no_wait()?
+        .context("Fresh interpreter cache is locked")?;
+    let queried = PythonEnvironment::from_root(context.venv.path(), &fresh_cache)?;
+    startup_marker.assert(predicate::path::is_file());
+    let cached_base = cached.interpreter().to_base_python()?;
+    let queried_base = queried.interpreter().to_base_python()?;
+    insta::with_settings!({ filters => context.filters() }, {
+        insta::assert_snapshot!(cached_base.display(), @"[PYTHON_BIN]/python3");
+        insta::assert_snapshot!(queried_base.display(), @"[PYTHON_BIN]/python3.12");
+    });
+
+    Ok(())
+}
+
+/// An absolute executable symlink can contain a directory symlink followed by `..`.
+/// Normalizing that target lexically can turn a working Python path into a missing file.
+#[test]
+#[cfg(all(target_os = "linux", feature = "test-python-managed"))]
+fn create_venv_caches_absolute_symlink_target() -> Result<()> {
+    let context = uv_test::test_context_with_versions!(&[]).with_managed_python_dirs();
+    context.python_install().arg("3.12.9").assert().success();
+    let output = context.python_find().arg("3.12.9").assert().success();
+    let python = Path::new(std::str::from_utf8(&output.get_output().stdout)?.trim());
+
+    // Move the installation out of the managed directory to avoid transparent patch upgrades.
+    let installation = python
+        .parent()
+        .and_then(Path::parent)
+        .context("Python executable has no installation directory")?;
+    let relocated = context.temp_dir.child("python");
+    fs_err::rename(installation, relocated.path())?;
+    let python_directory = relocated.child("bin");
+    let context = context.with_filtered_path(python_directory.path(), "PYTHON_BIN");
+
+    let directory_link = python_directory.child("alias");
+    symlink(python_directory.path(), directory_link.path())?;
+    let executable_target = directory_link.join("../bin/python3.12");
+    let symlinked_python = python_directory.child("python-link");
+    symlink(&executable_target, symlinked_python.path())?;
+
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("--python")
+        .arg(symlinked_python.path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: python/bin/python-link
+    Creating virtual environment at: .venv
+    Activate with: source .venv/[BIN]/activate
+    ");
+
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("child")
+        .arg("--python")
+        .arg(context.venv.path()), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: .venv/bin/python
+    Creating virtual environment at: child
+    Activate with: source child/[BIN]/activate
+    ");
+
+    uv_snapshot!(context.filters(), context.external_command(context.temp_dir.child("child/bin/python").path())
+        .arg("-I")
+        .arg("-c")
+        .arg("print('ok')"), @"
+    exit_code: 0 (success)
+    ----- stdout -----
+    ok
+    ");
+
+    let target = fs_err::read_link(context.temp_dir.child("child/bin/python"))?;
+    insta::with_settings!({ filters => context.filters() }, {
+        insta::assert_snapshot!(target.display(), @"[PYTHON_BIN]/python-link");
+    });
+
+    Ok(())
+}
+
+/// Linux can execute a venv with 40 executable symlinks, including its own `bin/python`.
+/// CPython falls back to the executable in `pyvenv.cfg`'s home at its resolution limit.
+#[test]
+#[cfg(all(target_os = "linux", feature = "test-python-managed"))]
+fn create_venv_caches_interpreter_at_symlink_limit() -> Result<()> {
+    let context = uv_test::test_context_with_versions!(&[]).with_managed_python_dirs();
+    context.python_install().arg("3.12.9").assert().success();
+    let output = context.python_find().arg("3.12.9").assert().success();
+    let python = Path::new(std::str::from_utf8(&output.get_output().stdout)?.trim());
+
+    // Move the installation out of the managed directory to avoid transparent patch upgrades.
+    let installation = python
+        .parent()
+        .and_then(Path::parent)
+        .context("Python executable has no installation directory")?;
+    let relocated = context.temp_dir.child("python");
+    fs_err::rename(installation, relocated.path())?;
+    let python_directory = relocated.child("bin");
+    let context = context.with_filtered_path(python_directory.path(), "PYTHON_BIN");
+
+    let mut target = python_directory.child("python3.12").to_path_buf();
+    for index in (0..39).rev() {
+        let link = python_directory.child(format!("chain-{index}"));
+        symlink(&target, link.path())?;
+        target = link.to_path_buf();
     }
 
+    uv_snapshot!(context.filters(), context.venv()
+        .arg("--python")
+        .arg(&target), @"
+    exit_code: 0 (success)
+    ----- stderr -----
+    Using CPython 3.12.9 interpreter at: python/bin/chain-0
+    Creating virtual environment at: .venv
+    Activate with: source .venv/[BIN]/activate
+    ");
+
+    uv_snapshot!(context.filters(), context.external_command(context.venv.child("bin/python").path())
+        .arg("-I")
+        .arg("-c")
+        .arg("print('ok')"), @"

[P3] Check cached metadata at the symlink-resolution limit

This invocation bypasses uv’s interpreter cache, and print('ok') does not observe CPython’s base-executable fallback. An incorrect inferred sys_base_executable would therefore pass, leaving the cache behavior at this boundary uncharacterized. Load the created environment using the populated cache and a fresh cache, then snapshot their base executables as in the preceding symlink tests.

woodruffw woodruffw commented on code on Oct 09, 2026 16:01 UTC
Code Review
crates/uv-python-interpreter/src/interpreter.rs:1
@@ -1792,6 +1792,64 @@ mod tests {
         Ok(())
     }
 
+    /// The v4 cache can contain an inferred base path that differs from Python's response.
+    #[tokio::test]
+    async fn test_legacy_virtualenv_cache() -> Result<()> {
+        let mock_dir = tempdir()?;
+        let base_python = mock_dir.path().join("python3.12");
+        let symlinked_python = mock_dir.path().join("python3");
+        let executable = mock_dir.path().join("venv/bin/python");
+        let query_log = mock_dir.path().join("queries");
+        fs::create_dir_all(executable.parent().context("Executable has no parent")?)?;
+        fs::os::unix::fs::symlink(&base_python, &symlinked_python)?;
+        fs::os::unix::fs::symlink(&symlinked_python, &executable)?;
+        fs::write(&query_log, "")?;
+
+        let mut response = serde_json::from_str::<Value>(mocked_interpreter_response())?;
+        response["sys_executable"] = serde_json::to_value(&executable)?;

It seems kind of weird to test a negative here, i.e. test something that can't happen (v5 bump means we'll always miss this fake v4 entry)

Reviewers
Assignees
astral-automations-bot[bot] astral-automations-bot[bot]
Labels
risk: low confidence: 92.7% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 41.2% (MEDIUM) · Higher = larger blast radius
41.2%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 92.7% · Lower = rushed or shallow review
92.7%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 3% · Safe to merge
3%