Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions crates/uv-static/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1346,6 +1346,13 @@ impl EnvVars {
#[attr_added_in("0.5.19")]
pub const UV_GIT_LFS: &'static str = "UV_GIT_LFS";

/// Sets the soft open-file descriptor limit for commands executed by `uv run`.
///
/// The limit is applied after uv prepares the environment and immediately before the command
/// is spawned. The hard open-file descriptor limit remains unchanged. Only supported on Unix.
#[attr_added_in("0.12.2")]
pub const UV_RUN_ULIMIT: &'static str = "UV_RUN_ULIMIT";

/// Number of times that `uv run` has been recursively invoked. Used to guard against infinite
/// recursion, e.g., when `uv run`` is used in a script shebang.
#[attr_hidden]
Expand Down
38 changes: 38 additions & 0 deletions crates/uv/src/commands/project/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, anyhow, bail};
use futures::StreamExt;
use itertools::Itertools;
#[cfg(unix)]
use nix::sys::resource::{RLIM_INFINITY, Resource, getrlimit, rlim_t, setrlimit};
use owo_colors::OwoColorize;
use thiserror::Error;
use tokio::process::Command;
Expand Down Expand Up @@ -1303,6 +1305,9 @@ pub(crate) async fn run(
process.env(EnvVars::VIRTUAL_ENV, interpreter.sys_prefix().as_os_str());
}

#[cfg(unix)]
set_run_open_file_limit()?;

// Spawn and wait for completion
// Standard input, output, and error streams are all inherited
// TODO(zanieb): Throw a nicer error message if the command is not found
Expand All @@ -1313,6 +1318,39 @@ pub(crate) async fn run(
run_to_completion(handle).await
}

/// Apply the requested soft open-file descriptor limit before running the command.
#[cfg(unix)]
fn set_run_open_file_limit() -> anyhow::Result<()> {
let Some(limit) = std::env::var_os(EnvVars::UV_RUN_ULIMIT) else {
return Ok(());
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should thread this through instead.


let limit = limit.to_str().ok_or_else(|| {
anyhow!(
"Invalid value for `{}`: expected a non-negative integer",
EnvVars::UV_RUN_ULIMIT
)
})?;
let soft = limit
.parse::<u32>()
.with_context(|| format!("Invalid value for `{}`: `{limit}`", EnvVars::UV_RUN_ULIMIT))?;
let soft = rlim_t::from(soft);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This should be parsed in our environment options handling


let (_, hard) =
getrlimit(Resource::RLIMIT_NOFILE).context("Failed to read the open-file limit")?;
if hard != RLIM_INFINITY && soft > hard {
bail!(
"`{}` value `{soft}` exceeds the hard open-file limit `{hard}`",
EnvVars::UV_RUN_ULIMIT
);
}

setrlimit(Resource::RLIMIT_NOFILE, soft, hard)
.with_context(|| format!("Failed to set the open-file limit to `{soft}`"))?;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we share utility for doing this update?


Ok(())
}

/// Returns `true` if we can skip creating an additional ephemeral environment in `uv run`.
fn can_skip_ephemeral(
spec: &RequirementsSpecification,
Expand Down
83 changes: 83 additions & 0 deletions crates/uv/tests/it/resource_limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,86 @@ fn adjust_open_file_limit() {
True
");
}

#[test]
fn run_open_file_limit_override() {
let context = uv_test::test_context!("3.12");
let python = &context.python_versions[0].1;

let mut command = Command::new(get_bin!());
command
.arg("run")
.arg("--no-project")
.arg("--")
.arg(python)
.arg("-c")
.arg(
"import resource; soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE); print(soft); print(hard > soft)",
)
.current_dir(context.temp_dir.path())
.env(EnvVars::UV_CACHE_DIR, context.cache_dir.path())
.env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
.env(EnvVars::UV_RUN_ULIMIT, "128");

uv_snapshot!(context.filters(), command, @r"
exit_code: 0 (success)
----- stdout -----
128
True
");
}

#[test]
fn run_open_file_limit_override_invalid() {
let context = uv_test::test_context!("3.12");
let python = &context.python_versions[0].1;

let mut command = Command::new(get_bin!());
command
.arg("run")
.arg("--no-project")
.arg("--")
.arg(python)
.arg("-c")
.arg("pass")
.current_dir(context.temp_dir.path())
.env(EnvVars::UV_CACHE_DIR, context.cache_dir.path())
.env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
.env(EnvVars::UV_RUN_ULIMIT, "invalid");

uv_snapshot!(context.filters(), command, @r"
exit_code: 2 (failure)
----- stderr -----
error: Invalid value for `UV_RUN_ULIMIT`: `invalid`
Caused by: invalid digit found in string
");
}

#[test]
fn run_open_file_limit_override_exceeds_hard_limit() {
let context = uv_test::test_context!("3.12");
let python = &context.python_versions[0].1;

let mut command = Command::new("sh");
command
.arg("-c")
.arg("ulimit -S -n 128; ulimit -H -n 128; exec \"$@\"")
.arg("sh")
.arg(get_bin!())
.arg("run")
.arg("--no-project")
.arg("--")
.arg(python)
.arg("-c")
.arg("pass")
.current_dir(context.temp_dir.path())
.env(EnvVars::UV_CACHE_DIR, context.cache_dir.path())
.env(EnvVars::UV_PYTHON_DOWNLOADS, "never")
.env(EnvVars::UV_RUN_ULIMIT, "256");

uv_snapshot!(context.filters(), command, @r"
exit_code: 2 (failure)
----- stderr -----
error: `UV_RUN_ULIMIT` value `256` exceeds the hard open-file limit `128`
");
}
Loading