Skip to content

Commit dde7d24

Browse files
authored
Fix /dev/fd, rlimit, spawn scheduler, and context cache (#8651)
* Fix /dev/fd, rlimit, spawn scheduler, and context cache Honor PYTHONEXECUTABLE when computing sys.executable. Rewind the file offset after a pyc magic probe. Stop masking rlimit values with RLIM_INFINITY. Print the pyrepl-unavailable warning before the rustyline shell. Parse posix_spawn scheduler and apply it where the host supports it. Update ContextVar cache fields under one lock. Remove expectedFailure and skip markers for tests that now pass. Assisted-by: Grok:4.6 * address review: check rlim_t overflow on convert Replace the u64-to-rlim_t as-cast in py2rlim_limit with a checked try_from, matching py2rlim. Assisted-by: Grok:4.6
1 parent bca6c95 commit dde7d24

13 files changed

Lines changed: 178 additions & 37 deletions

File tree

‎Lib/test/test_cmd_line.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,6 @@ def test_python_dump_refs_file(self):
985985
contents = file.read()
986986
self.assertIn('Remaining objects', contents)
987987

988-
@unittest.expectedFailureIf(sys.platform == "darwin", "TODO: RUSTPYTHON")
989988
@unittest.skipUnless(sys.platform == 'darwin', 'PYTHONEXECUTABLE only works on macOS')
990989
def test_python_executable(self):
991990
code = 'import sys; print(sys.executable)'

‎Lib/test/test_cmd_line_script.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,6 @@ def test_nonexisting_script(self):
806806
self.assertIn(": can't open file ", err)
807807
self.assertNotEqual(proc.returncode, 0)
808808

809-
@unittest.skipIf(sys.platform.startswith("darwin"), "TODO: RUSTPYTHON; Problems with Mac os descriptor")
810809
@unittest.skipUnless(os.path.exists('/dev/fd/0'), 'requires /dev/fd platform')
811810
@unittest.skipIf(sys.platform.startswith("freebsd") and
812811
os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,

‎Lib/test/test_context.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,6 @@ def test_context_isinstance(self):
380380
with self.subTest(name=name):
381381
self.assertTrue(callable(getattr(ctx, name)))
382382

383-
@unittest.skipIf(sys.platform == "darwin", "TODO: RUSTPYTHON; Flaky on Mac, self.assertEqual(cvar.get(), num + i) AssertionError: 8 != 12")
384383
@isolated_context
385384
@threading_helper.requires_working_threading()
386385
def test_context_threads_1(self):

‎Lib/test/test_posix.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2044,7 +2044,6 @@ def test_scheduler_allow_none(self):
20442044
pid = self.spawn_func(path, args, os.environ, scheduler=None)
20452045
support.wait_process(pid, exitcode=0)
20462046

2047-
@unittest.expectedFailure # TODO: RUSTPYTHON; Wrong error message
20482047
@support.subTests("scheduler", [object(), 1, [1, 2]])
20492048
def test_scheduler_wrong_type(self, scheduler):
20502049
path, args = self.NOOP_PROGRAM[0], self.NOOP_PROGRAM
@@ -2054,7 +2053,6 @@ def test_scheduler_wrong_type(self, scheduler):
20542053
):
20552054
self.spawn_func(path, args, os.environ, scheduler=scheduler)
20562055

2057-
@unittest.expectedFailureIf(sys.platform in ("darwin", "linux"), "TODO: RUSTPYTHON; NotImplementedError: scheduler parameter is not yet implemented")
20582056
@requires_sched
20592057
@unittest.skipIf(sys.platform.startswith(('freebsd', 'netbsd')),
20602058
"bpo-34685: test can fail on BSD")
@@ -2075,7 +2073,6 @@ def test_setscheduler_only_param(self):
20752073
)
20762074
support.wait_process(pid, exitcode=0)
20772075

2078-
@unittest.expectedFailureIf(sys.platform in ("darwin", "linux"), "TODO: RUSTPYTHON; NotImplementedError: scheduler parameter is not yet implemented")
20792076
@requires_sched
20802077
@unittest.skipIf(sys.platform.startswith(('freebsd', 'netbsd')),
20812078
"bpo-34685: test can fail on BSD")

‎Lib/test/test_pyrepl/test_pyrepl.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1521,7 +1521,6 @@ def test_bracketed_paste_single_line(self):
15211521

15221522
@skipUnless(pty, "requires pty")
15231523
class TestDumbTerminal(ReplTestCase):
1524-
@unittest.expectedFailureIf(sys.platform in ("darwin", "linux"), "TODO: RUSTPYTHON")
15251524
def test_dumb_terminal_exits_cleanly(self):
15261525
env = os.environ.copy()
15271526
env.pop('PYTHON_BASIC_REPL', None)

‎Lib/test/test_resource.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ def test_fsize_too_big(self):
106106
except (OverflowError, ValueError):
107107
pass
108108

109-
@unittest.skipIf(sys.platform == "darwin", "TODO: RUSTPYTHON; crash")
110109
@unittest.skipIf(sys.platform == "vxworks",
111110
"setting RLIMIT_FSIZE is not supported on VxWorks")
112111
@unittest.skipUnless(hasattr(resource, 'RLIMIT_FSIZE'), 'requires resource.RLIMIT_FSIZE')

‎crates/host_env/src/posix.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,15 @@ pub enum PosixSpawnFileAction {
8282
},
8383
}
8484

85+
#[cfg(all(
86+
any(target_os = "linux", target_os = "freebsd", target_os = "android"),
87+
not(target_env = "musl")
88+
))]
89+
pub struct PosixSpawnScheduler {
90+
pub policy: Option<i32>,
91+
pub param: libc::sched_param,
92+
}
93+
8594
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "macos"))]
8695
pub struct PosixSpawnConfig<'a> {
8796
pub path: &'a CStr,
@@ -94,6 +103,11 @@ pub struct PosixSpawnConfig<'a> {
94103
pub setsid: bool,
95104
pub setsigmask: Option<&'a [i32]>,
96105
pub spawnp: bool,
106+
#[cfg(all(
107+
any(target_os = "linux", target_os = "freebsd", target_os = "android"),
108+
not(target_env = "musl")
109+
))]
110+
pub scheduler: Option<PosixSpawnScheduler>,
97111
}
98112

99113
pub fn set_inheritable(fd: BorrowedFd<'_>, inheritable: bool) -> std::io::Result<()> {
@@ -1428,6 +1442,32 @@ fn build_posix_spawn_attrs(
14281442
flags.insert(nix::spawn::PosixSpawnFlags::POSIX_SPAWN_SETSIGMASK);
14291443
}
14301444

1445+
#[cfg(all(
1446+
any(target_os = "linux", target_os = "freebsd", target_os = "android"),
1447+
not(target_env = "musl")
1448+
))]
1449+
if let Some(scheduler) = &config.scheduler {
1450+
// nix does not wrap these yet; the attr type is transparent over
1451+
// posix_spawnattr_t.
1452+
let attr_ptr = (&raw mut attrp).cast::<libc::posix_spawnattr_t>();
1453+
if let Some(policy) = scheduler.policy {
1454+
let err = unsafe { libc::posix_spawnattr_setschedpolicy(attr_ptr, policy) };
1455+
if err != 0 {
1456+
return Err(std::io::Error::from_raw_os_error(err));
1457+
}
1458+
flags.insert(nix::spawn::PosixSpawnFlags::from_bits_retain(
1459+
libc::POSIX_SPAWN_SETSCHEDULER,
1460+
));
1461+
}
1462+
let err = unsafe { libc::posix_spawnattr_setschedparam(attr_ptr, &scheduler.param) };
1463+
if err != 0 {
1464+
return Err(std::io::Error::from_raw_os_error(err));
1465+
}
1466+
flags.insert(nix::spawn::PosixSpawnFlags::from_bits_retain(
1467+
libc::POSIX_SPAWN_SETSCHEDPARAM,
1468+
));
1469+
}
1470+
14311471
if !flags.is_empty() {
14321472
attrp.set_flags(flags).map_err(std::io::Error::from)?;
14331473
}

‎crates/stdlib/src/contextvars.rs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,20 +335,23 @@ mod _contextvars {
335335
Ok(())
336336
}
337337

338-
// contextvar_set in CPython
338+
// contextvar_set
339339
fn set_inner(zelf: &Py<Self>, value: PyObjectRef, vm: &VirtualMachine) {
340340
let ctx = PyContext::current(vm);
341341

342342
let replaced = ctx.borrow_vars_mut().insert(zelf.to_owned(), value.clone());
343343
drop(replaced);
344344

345-
zelf.cached_id.store(ctx.get_id(), Ordering::SeqCst);
346-
345+
// cached and cached_id are one snapshot: another thread's get()
346+
// must not observe a new id with an old value, or the reverse.
347347
let cache = ContextVarCache {
348348
object: value,
349349
idx: ctx.inner.idx.load(Ordering::Relaxed),
350350
};
351-
let replaced = zelf.cached.lock().replace(cache);
351+
let mut cached = zelf.cached.lock();
352+
zelf.cached_id.store(ctx.get_id(), Ordering::SeqCst);
353+
let replaced = cached.replace(cache);
354+
drop(cached);
352355
drop(replaced);
353356
}
354357

‎crates/stdlib/src/resource.rs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ mod resource {
1010
convert::{ToPyException, ToPyObject},
1111
types::PyStructSequence,
1212
};
13+
use num_traits::Signed;
1314
use rustpython_host_env::resource as host_resource;
1415
use std::io;
1516

@@ -145,11 +146,11 @@ mod resource {
145146

146147
impl<'a> TryFromBorrowedObject<'a> for Limits {
147148
fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> {
148-
let seq: Vec<host_resource::rlim_t> = obj.try_to_value(vm)?;
149-
match *seq {
149+
let seq: Vec<PyObjectRef> = obj.try_to_value(vm)?;
150+
match seq.as_slice() {
150151
[cur, max] => Ok(Self(host_resource::rlimit {
151-
rlim_cur: cur & RLIM_INFINITY,
152-
rlim_max: max & RLIM_INFINITY,
152+
rlim_cur: py2rlim_limit(cur, vm)?,
153+
rlim_max: py2rlim_limit(max, vm)?,
153154
})),
154155
_ => Err(vm.new_value_error("expected a tuple of 2 integers")),
155156
}
@@ -173,6 +174,18 @@ mod resource {
173174
.map_err(|_| vm.new_overflow_error("Python int too large to convert to C rlim_t"))
174175
}
175176

177+
fn py2rlim_limit(obj: &PyObject, vm: &VirtualMachine) -> PyResult<host_resource::rlim_t> {
178+
let int = obj.try_to_ref::<crate::vm::builtins::PyInt>(vm)?;
179+
if int.as_bigint().is_negative() {
180+
return Err(vm.new_value_error("Cannot convert negative int"));
181+
}
182+
let value = int
183+
.try_to_primitive::<u64>(vm)
184+
.map_err(|_| vm.new_overflow_error("Python int too large to convert to C rlim_t"))?;
185+
host_resource::rlim_t::try_from(value)
186+
.map_err(|_| vm.new_overflow_error("Python int too large to convert to C rlim_t"))
187+
}
188+
176189
#[pyfunction]
177190
fn getrlimit(resource: PyIntRef, vm: &VirtualMachine) -> PyResult<Limits> {
178191
let resource = py2rlim(resource, vm)?;

‎crates/vm/src/getpath.rs‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -115,15 +115,13 @@ pub fn init_path_config(settings: &Settings) -> Paths {
115115
.map(|p| p.to_string_lossy().into_owned())
116116
.unwrap_or_default();
117117

118-
// Step 1: Check for __PYVENV_LAUNCHER__ environment variable
119-
// When launched from a venv launcher, __PYVENV_LAUNCHER__ contains the venv's python.exe path
120-
// In this case:
121-
// - sys.executable should be the launcher path (where user invoked Python)
122-
// - sys._base_executable should be the real Python executable
123-
let exe_dir = if let Ok(launcher) = crate::host_env::os::var("__PYVENV_LAUNCHER__") {
124-
paths.executable.clone_from(&launcher);
118+
// Step 1: Check for PYTHONEXECUTABLE / __PYVENV_LAUNCHER__
119+
// When set, these are used as sys.executable and when searching for venvs.
120+
// The argv0 path is kept as the base executable for prefix calculation.
121+
let exe_dir = if let Some(override_exe) = env_executable_override() {
122+
paths.executable.clone_from(&override_exe);
125123
paths.base_executable = real_executable;
126-
PathBuf::from(&launcher).parent().map(PathBuf::from)
124+
PathBuf::from(&override_exe).parent().map(PathBuf::from)
127125
} else {
128126
paths.executable = real_executable;
129127
executable
@@ -165,7 +163,7 @@ pub fn init_path_config(settings: &Settings) -> Paths {
165163
};
166164
paths.base_exec_prefix.clone_from(&paths.base_prefix);
167165

168-
// Step 7: Calculate base_executable (if not already set by __PYVENV_LAUNCHER__)
166+
// Step 7: Calculate base_executable (if not already set by an env override)
169167
if paths.base_executable.is_empty() {
170168
paths.base_executable = calculate_base_executable(executable.as_ref(), home_dir.as_ref());
171169
}
@@ -367,6 +365,19 @@ fn build_module_search_paths(settings: &Settings, prefix: &str, exec_prefix: &st
367365
paths
368366
}
369367

368+
/// `PYTHONEXECUTABLE` takes precedence over `__PYVENV_LAUNCHER__`.
369+
/// An empty value is ignored.
370+
fn env_executable_override() -> Option<String> {
371+
for name in ["PYTHONEXECUTABLE", "__PYVENV_LAUNCHER__"] {
372+
if let Ok(value) = crate::host_env::os::var(name)
373+
&& !value.is_empty()
374+
{
375+
return Some(value);
376+
}
377+
}
378+
None
379+
}
380+
370381
/// Get the current executable path
371382
fn get_executable_path() -> Option<PathBuf> {
372383
#[cfg(not(target_arch = "wasm32"))]

0 commit comments

Comments
 (0)