Skip to content

Commit ad12342

Browse files
Add a preview feature for lazy build backend imports (#21967)
Build backend hooks run in short-lived Python processes, so importing backend code that a hook never uses can add startup overhead. Add the `build-lazy-imports` preview feature to invoke build hooks with `-X lazy_imports=all` on CPython 3.15 and later. Other interpreters and ordinary builds are unchanged. The behavior remains opt-in because global lazy imports can affect import-time side effects in third-party backends. Warm wheel builds on CPython `3.15.0rc2`, using an AMD EPYC 9V74 Linux host and uv's `profiling` profile: | Source distribution | Backend | Normal | Lazy | Time reduction, 90% CI | | --- | --- | ---: | ---: | ---: | | `six==1.17.0` | setuptools `84.0.0` | 233.5 ms | 206.0 ms | 11.8% [11.1%, 12.4%] | | `requests==2.32.5` | setuptools `84.0.0` | 256.6 ms | 231.2 ms | 9.9% [8.7%, 11.1%] | | `packaging==25.0` | Flit Core `4.0.2` | 108.7 ms | 89.7 ms | 17.5% [16.7%, 18.3%] | | `attrs==25.3.0` | Hatchling `1.32.0` | 172.2 ms | 152.1 ms | 11.7% [11.4%, 12.0%] | | `cleo==2.1.0` | Poetry Core `2.4.1` | 269.4 ms | 235.6 ms | 12.5% [12.0%, 13.1%] | | `pdm-backend==2.4.5` | self-hosted `pdm.backend.intree` | 164.7 ms | 136.6 ms | 17.1% [16.7%, 17.5%] | Each case uses preinstalled build dependencies and 40 order-balanced AB/BA pairs of `uv build --wheel --no-build-isolation --offline --no-progress --no-sources`. Times are arithmetic means; reductions use the geometric paired lazy/normal ratio, with two-sided 90% paired-block bootstrap intervals from 100,000 resamples. A same-binary toggle based on [83d556d](83d556d) isolates the interpreter flag; these are not exact-head measurements of the preview-feature integration. The results cover warm pure-Python builds, not overall `uv sync` or `uv lock` performance. --------- Co-authored-by: zaniebot <[email protected]>
1 parent dd965a2 commit ad12342

9 files changed

Lines changed: 168 additions & 3 deletions

File tree

‎.python-versions‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@
1717
3.8.20
1818
# The following is needed for `==3.13` request tests
1919
3.13.0
20-
# A pre-release version required for testing
20+
# Pre-release versions required for testing
2121
3.14.0rc2
22+
3.15.0rc2

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/uv-build-frontend/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ uv-fs = { workspace = true }
2727
uv-normalize = { workspace = true }
2828
uv-pep440 = { workspace = true }
2929
uv-pep508 = { workspace = true }
30+
uv-preview = { workspace = true }
3031
uv-pypi-types = { workspace = true }
3132
uv-python = { workspace = true }
3233
uv-static = { workspace = true }

‎crates/uv-build-frontend/src/lib.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ use uv_fs::{LockedFile, LockedFileMode};
3939
use uv_fs::{PythonExt, Simplified};
4040
use uv_normalize::PackageName;
4141
use uv_pep440::Version;
42+
use uv_preview::PreviewFeature;
4243
use uv_pypi_types::VerbatimParsedUrl;
4344
use uv_python::{Interpreter, PythonEnvironment};
4445
use uv_static::EnvVars;
@@ -1290,7 +1291,15 @@ impl PythonRunner {
12901291

12911292
let _permit = self.concurrent_build_slots.acquire().await.unwrap();
12921293

1293-
let mut child = Command::new(venv.python_executable())
1294+
let mut command = Command::new(venv.python_executable());
1295+
if uv_preview::is_enabled(PreviewFeature::BuildLazyImports)
1296+
&& venv.interpreter().implementation_name() == "cpython"
1297+
&& venv.interpreter().python_tuple() >= (3, 15)
1298+
{
1299+
command.args(["-X", "lazy_imports=all"]);
1300+
}
1301+
1302+
let mut child = command
12941303
.args(["-c", script])
12951304
.current_dir(source_tree.simplified())
12961305
.envs(environment_variables)

‎crates/uv-dev/src/generate_preview_features_reference.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ mod tests {
115115
- <a id="azure-endpoint" href="#azure-endpoint"><code>azure-endpoint</code></a>: Allows signing requests to Azure Blob Storage endpoints with Azure credentials.
116116
- <a id="batch-export" href="#batch-export"><code>batch-export</code></a>: Allows using `uv export --batch`.
117117
- <a id="build-dependency-check" href="#build-dependency-check"><code>build-dependency-check</code></a>: Checks build dependencies before nonisolated builds with `uv build`.
118+
- <a id="build-lazy-imports" href="#build-lazy-imports"><code>build-lazy-imports</code></a>: Enables lazy imports in build backend invocations on CPython 3.15 and later.
119+
This can affect import-time side effects in third-party build backends.
118120
- <a id="cache-physical-space" href="#cache-physical-space"><code>cache-physical-space</code></a>: Reports the physical disk space reclaimed by cache cleanup, accounting for hardlinks and copy-on-write clones.
119121
- <a id="cache-size" href="#cache-size"><code>cache-size</code></a>: Allows using `uv cache size`.
120122
- <a id="centralized-project-envs" href="#centralized-project-envs"><code>centralized-project-envs</code></a>: Stores [project virtual environments](./projects/layout.md#centralized-project-environments)

‎crates/uv-preview/src/lib.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,9 @@ pub enum PreviewFeature {
344344
MinimumLibcVersion,
345345
/// Checks build dependencies before nonisolated builds with `uv build`.
346346
BuildDependencyCheck,
347+
/// Enables lazy imports in build backend invocations on CPython 3.15 and later.
348+
/// This can affect import-time side effects in third-party build backends.
349+
BuildLazyImports,
347350
}
348351

349352
impl Display for PreviewFeature {

‎crates/uv/tests/build/build.rs‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,152 @@ fn build_basic() -> Result<()> {
156156
Ok(())
157157
}
158158

159+
/// Global lazy imports are opt-in on supported build interpreters.
160+
#[test]
161+
fn build_lazy_imports() -> Result<()> {
162+
let context = uv_test::test_context!("3.15");
163+
let project = context.temp_dir.child("project");
164+
project.child("pyproject.toml").write_str(indoc! {r#"
165+
[project]
166+
name = "project"
167+
version = "0.1.0"
168+
169+
[build-system]
170+
requires = []
171+
build-backend = "backend"
172+
backend-path = ["."]
173+
"#})?;
174+
project.child("unused_module.py").write_str("VALUE = 1\n")?;
175+
project.child("backend.py").write_str(indoc! {r#"
176+
import sys
177+
import unused_module
178+
179+
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
180+
import pathlib
181+
import zipfile
182+
183+
pathlib.Path("mode").write_text(
184+
"eager" if "unused_module" in sys.modules else "lazy"
185+
)
186+
name = "project-0.1.0-py3-none-any.whl"
187+
with zipfile.ZipFile(pathlib.Path(wheel_directory) / name, "w") as wheel:
188+
wheel.writestr("project-0.1.0.dist-info/METADATA", "Metadata-Version: 2.3\nName: project\nVersion: 0.1.0\n")
189+
wheel.writestr("project-0.1.0.dist-info/WHEEL", "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n")
190+
wheel.writestr("project-0.1.0.dist-info/RECORD", "")
191+
return name
192+
"#})?;
193+
194+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").env("PYTHON_LAZY_IMPORTS", "normal"), @"
195+
exit_code: 0 (success)
196+
----- stderr -----
197+
Building wheel...
198+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
199+
");
200+
project.child("mode").assert("eager");
201+
202+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").arg("--preview-features").arg("build-lazy-imports").env("PYTHON_LAZY_IMPORTS", "normal"), @"
203+
exit_code: 0 (success)
204+
----- stderr -----
205+
Building wheel...
206+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
207+
");
208+
project.child("mode").assert("lazy");
209+
210+
context.temp_dir.child("uv.toml").write_str(indoc! {r#"
211+
preview-features = ["build-lazy-imports"]
212+
"#})?;
213+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").env("PYTHON_LAZY_IMPORTS", "normal"), @"
214+
exit_code: 0 (success)
215+
----- stderr -----
216+
Building wheel...
217+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
218+
");
219+
project.child("mode").assert("lazy");
220+
221+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").arg("--no-preview").env("PYTHON_LAZY_IMPORTS", "normal"), @"
222+
exit_code: 0 (success)
223+
----- stderr -----
224+
Building wheel...
225+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
226+
");
227+
project.child("mode").assert("eager");
228+
229+
Ok(())
230+
}
231+
232+
/// Global lazy imports remain disabled on unsupported build interpreters.
233+
#[test]
234+
fn build_lazy_imports_unsupported_python() -> Result<()> {
235+
let context = uv_test::test_context!("3.12");
236+
let project = context.temp_dir.child("project");
237+
project.child("pyproject.toml").write_str(indoc! {r#"
238+
[project]
239+
name = "project"
240+
version = "0.1.0"
241+
242+
[build-system]
243+
requires = []
244+
build-backend = "backend"
245+
backend-path = ["."]
246+
"#})?;
247+
project.child("unused_module.py").write_str("VALUE = 1\n")?;
248+
project.child("backend.py").write_str(indoc! {r#"
249+
import sys
250+
import unused_module
251+
252+
def build_wheel(wheel_directory, config_settings=None, metadata_directory=None):
253+
import pathlib
254+
import zipfile
255+
256+
pathlib.Path("mode").write_text(
257+
"eager" if "unused_module" in sys.modules else "lazy"
258+
)
259+
name = "project-0.1.0-py3-none-any.whl"
260+
with zipfile.ZipFile(pathlib.Path(wheel_directory) / name, "w") as wheel:
261+
wheel.writestr("project-0.1.0.dist-info/METADATA", "Metadata-Version: 2.3\nName: project\nVersion: 0.1.0\n")
262+
wheel.writestr("project-0.1.0.dist-info/WHEEL", "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n")
263+
wheel.writestr("project-0.1.0.dist-info/RECORD", "")
264+
return name
265+
"#})?;
266+
267+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").env("PYTHON_LAZY_IMPORTS", "normal"), @"
268+
exit_code: 0 (success)
269+
----- stderr -----
270+
Building wheel...
271+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
272+
");
273+
project.child("mode").assert("eager");
274+
275+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").arg("--preview-features").arg("build-lazy-imports").env("PYTHON_LAZY_IMPORTS", "normal"), @"
276+
exit_code: 0 (success)
277+
----- stderr -----
278+
Building wheel...
279+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
280+
");
281+
project.child("mode").assert("eager");
282+
283+
context.temp_dir.child("uv.toml").write_str(indoc! {r#"
284+
preview-features = ["build-lazy-imports"]
285+
"#})?;
286+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").env("PYTHON_LAZY_IMPORTS", "normal"), @"
287+
exit_code: 0 (success)
288+
----- stderr -----
289+
Building wheel...
290+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
291+
");
292+
project.child("mode").assert("eager");
293+
294+
uv_snapshot!(context.filters(), context.build().arg("--wheel").arg("project").arg("--no-preview").env("PYTHON_LAZY_IMPORTS", "normal"), @"
295+
exit_code: 0 (success)
296+
----- stderr -----
297+
Building wheel...
298+
Successfully built project/dist/project-0.1.0-py3-none-any.whl
299+
");
300+
project.child("mode").assert("eager");
301+
302+
Ok(())
303+
}
304+
159305
/// Build hooks can invoke uv while building a wheel from an extracted source distribution.
160306
/// Regression test for <https://github.com/astral-sh/uv/issues/19878>.
161307
#[test]

‎crates/uv/tests/sync/show_settings.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3816,6 +3816,7 @@ fn preview_features() {
38163816
+ BatchExport,
38173817
+ MinimumLibcVersion,
38183818
+ BuildDependencyCheck,
3819+
+ BuildLazyImports,
38193820
+ ],
38203821
},
38213822
python_preference: Managed,

‎uv.schema.json‎

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)