Skip to content

Commit 4d103be

Browse files
youknowdotcodex
andauthored
Unify signed timeouts across wait APIs (#9652)
* Reuse signed timeout conversion for channels and joins Share native thread wait limits with the PyTime conversion helpers. Normalize channel and join timeouts with signed nanosecond precision, native index/float precedence, checked bounds, and timeout rounding. Preserve each API-specific None, negative, and nonblocking policy. Add generic conversion and boundary coverage without snippet tests. Assisted-by: OpenAI Codex:model version not exposed * Gate exported timeout bound to threading builds Keep the shared microsecond limit available to channel waits, but compile the seconds-only _thread export when its threading consumer is enabled. Assisted-by: OpenAI Codex:model version not exposed * Reuse signed timeout conversion for lock acquisition Bind raw lock arguments with FromArgs before callbacks, use Python truthiness and the shared PyTime conversion, and retain converted arguments throughout acquisition. Validate rounded sentinels and native timeout bounds rather than rounded-down public metadata. Add focused binding, conversion-order, and timeout policy tests. Assisted-by: OpenAI Codex:model version not exposed * Preserve integer daemon values in joinable thread audits CPython builds this audit payload with OiO, so daemon is the normalized integer 0 or 1 rather than a bool. Keep the existing binding and audit-before-launch ordering. Assisted-by: OpenAI Codex:model version not exposed * Keep timeout tests focused on changed thread behavior Drop three standalone tests of the unchanged shared time converter. Existing test_time covers its signed range and rounding; retain acquire conversion ordering, sentinel rounding, error precedence, and native wait-bound regressions. Assisted-by: OpenAI Codex:model version not exposed * Retire passing Linux thread audit expectation The exact-head Linux CI and its test rerun both pass test_audit.test_threading. Preserve expected failure on other platforms until their results establish parity. Generated with scripts/update_lib helpers. Assisted-by: OpenAI Codex:model version not exposed * Retire the passing thread audit marker Use scripts/update_lib auto-mark helpers with the exact-head hosted CI results to retire only observed unexpected-success markers. Test bodies, assertions, and platform skips remain unchanged. Assisted-by: OpenAI Codex:model version not exposed * Bound thread join waits without resetting the timeout Cap each native condition-variable wait at the platform finite-wait limit and track elapsed time across chunks. Add a native boundary test for capped waits and deadline exhaustion. Assisted-by: OpenAI Codex:model version not exposed * Align select-family conversion and timeouts Reuse signed pytime conversion and descriptor/argument binding across select, poll, epoll and kqueue. Preserve conversion order, argument roots, timeout bounds and rounding, and poll event masks. Use ppoll where supported for nanosecond deadlines. Assisted-by: OpenAI Codex:model version not exposed * Consume permits for nonblocking SimpleQueue get Assisted-by: OpenAI Codex:model version not exposed * Validate SimpleQueue timeouts without panicking Assisted-by: OpenAI Codex:model version not exposed * Use truth testing for SimpleQueue block arguments Assisted-by: OpenAI Codex:model version not exposed * Publish SimpleQueue items and permits together Assisted-by: OpenAI Codex:model version not exposed * Reuse shared signed time conversion in SimpleQueue Use the same nanosecond conversion as thread and select APIs while preserving SimpleQueue ceiling rounding, nonblocking timeout bypass, negative checks, and checked deadline construction. Assisted-by: OpenAI Codex:model version not exposed * Rely on scope cleanup for redundant explicit drops Keep retained owners outside lock scopes and preserve callback-sensitive release ordering. Assisted-by: OpenAI Codex:model version not exposed --------- Co-authored-by: Codex <[email protected]> Co-authored-by: youknowdot <[email protected]>
1 parent 34f4999 commit 4d103be

8 files changed

Lines changed: 739 additions & 350 deletions

File tree

‎Lib/test/test_audit.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,6 @@ def test_sys_getframemodulename(self):
214214
self.assertEqual(actual, expected)
215215

216216

217-
@unittest.expectedFailure # TODO: RUSTPYTHON
218217
def test_threading(self):
219218
returncode, events, stderr = self.run_python("test_threading")
220219
if returncode:

‎crates/host_env/src/select.rs‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,19 @@ pub fn duration_to_timeval(d: Duration) -> timeval {
291291
tv
292292
}
293293

294+
pub fn duration_to_timeval_ceiling(duration: Duration) -> Option<timeval> {
295+
let micros = i64::try_from(duration.as_nanos().div_ceil(1000)).ok()?;
296+
timeval_from_microseconds(micros)
297+
}
298+
299+
#[allow(clippy::useless_conversion, reason = "timeval fields can be 32-bit")]
300+
pub fn timeval_from_microseconds(micros: i64) -> Option<timeval> {
301+
Some(timeval {
302+
tv_sec: micros.div_euclid(1_000_000).try_into().ok()?,
303+
tv_usec: micros.rem_euclid(1_000_000).try_into().ok()?,
304+
})
305+
}
306+
294307
fn saturate_secs<T>(secs: u64, _sample: T) -> T
295308
where
296309
T: TryFrom<u64> + TryFrom<i32>,
@@ -482,6 +495,83 @@ pub fn poll_fds(fds: &mut [PollFd], timeout: i32) -> std::io::Result<i32> {
482495
}
483496
}
484497

498+
// ppoll preserves Python's nanosecond timeout on platforms with a supported
499+
// binding. Other poll backends continue to use rounded signed milliseconds.
500+
#[cfg(unix)]
501+
pub struct PollTimeout {
502+
#[cfg(any(target_os = "linux", target_os = "android"))]
503+
timespec: Option<libc::timespec>,
504+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
505+
milliseconds: i32,
506+
}
507+
508+
#[cfg(unix)]
509+
impl PollTimeout {
510+
#[allow(clippy::useless_conversion, reason = "time_t can be 32-bit")]
511+
pub fn from_nanoseconds(timeout: Option<i64>) -> Option<Self> {
512+
#[cfg(any(target_os = "linux", target_os = "android"))]
513+
if let Some(nanoseconds) = timeout {
514+
// CPython validates timespec even for negative (infinite) waits.
515+
// Floor division matches the normalized signed timespec seconds.
516+
libc::time_t::try_from(nanoseconds.div_euclid(1_000_000_000)).ok()?;
517+
}
518+
Self::from_duration(
519+
timeout
520+
.filter(|&ns| ns >= 0)
521+
.map(|ns| Duration::from_nanos(ns as u64)),
522+
)
523+
}
524+
525+
pub fn from_duration(timeout: Option<Duration>) -> Option<Self> {
526+
#[cfg(any(target_os = "linux", target_os = "android"))]
527+
{
528+
let timespec = match timeout {
529+
Some(duration) => Some(libc::timespec {
530+
tv_sec: duration.as_secs().try_into().ok()?,
531+
tv_nsec: duration.subsec_nanos() as _,
532+
}),
533+
None => None,
534+
};
535+
Some(Self { timespec })
536+
}
537+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
538+
{
539+
let milliseconds = match timeout {
540+
Some(duration) => duration_as_millis_ceiling(duration)?,
541+
None => -1,
542+
};
543+
Some(Self { milliseconds })
544+
}
545+
}
546+
}
547+
548+
#[cfg(unix)]
549+
pub fn poll_fds_with_timeout(fds: &mut [PollFd], timeout: &PollTimeout) -> io::Result<i32> {
550+
#[cfg(any(target_os = "linux", target_os = "android"))]
551+
{
552+
let timespec = timeout.timespec.as_ref().map_or(core::ptr::null(), |ts| ts);
553+
// A null mask preserves the calling thread's signal mask. libc owns
554+
// any platform-specific copying needed by the ppoll syscall.
555+
let result = unsafe {
556+
libc::ppoll(
557+
fds.as_mut_ptr(),
558+
fds.len() as _,
559+
timespec,
560+
core::ptr::null(),
561+
)
562+
};
563+
if result < 0 {
564+
Err(io::Error::last_os_error())
565+
} else {
566+
Ok(result)
567+
}
568+
}
569+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
570+
{
571+
poll_fds(fds, timeout.milliseconds)
572+
}
573+
}
574+
485575
#[cfg(any(target_os = "linux", target_os = "android", target_os = "redox"))]
486576
pub mod epoll {
487577
use std::os::fd::{IntoRawFd, RawFd};

‎crates/stdlib/src/_queue.rs‎

Lines changed: 65 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ mod _queue {
99
use crate::vm::{
1010
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
1111
builtins::{PyBaseExceptionRef, PyException, PyGenericAlias, PyStr, PyType, PyTypeRef},
12-
function::TimeoutSeconds,
12+
function::OptionalArg,
1313
protocol::PyNumberMethods,
14+
stdlib::time::pytime,
1415
types::{AsNumber, Constructor, Representable},
1516
};
1617

@@ -85,15 +86,6 @@ mod _queue {
8586
vm.allow_threads(|| self.mutex.lock())
8687
}
8788

88-
fn release(&self, vm: &VirtualMachine) {
89-
{
90-
let mut count = self.lock_count(vm);
91-
*count += 1;
92-
} // lock dropped. now we can notify a waiting thread
93-
94-
self.cond.notify_one();
95-
}
96-
9789
/// `Ok(true)` if acquired, `Ok(false)` on timeout, `Err` if a signal
9890
/// handler raised (e.g. `KeyboardInterrupt`) while we were waiting.
9991
fn acquire(
@@ -167,10 +159,21 @@ mod _queue {
167159
expect(unused_variables, reason = "only the semaphore needs the vm")
168160
)]
169161
fn push(&self, item: PyObjectRef, vm: &VirtualMachine) {
170-
self.buf.lock().push_back(item);
171-
172162
#[cfg(feature = "threading")]
173-
self.sem.release(vm);
163+
{
164+
// Publish the permit before unlocking the buffer, so another
165+
// thread cannot observe an item that no getter can claim.
166+
let mut count = self.sem.lock_count(vm);
167+
{
168+
let mut buf = self.buf.lock();
169+
buf.push_back(item);
170+
*count += 1;
171+
}
172+
drop(count);
173+
self.sem.cond.notify_one();
174+
}
175+
#[cfg(not(feature = "threading"))]
176+
self.buf.lock().push_back(item);
174177
}
175178

176179
/// Returns a strong reference from the head of the buffer.
@@ -204,26 +207,25 @@ mod _queue {
204207
struct PutArgs {
205208
#[pyarg(any)]
206209
item: PyObjectRef,
207-
#[expect(
208-
dead_code,
209-
reason = "Intentional. Provide compatibility with the Queue class"
210-
)]
211-
#[pyarg(any, default = true)]
212-
block: bool,
213-
#[expect(
214-
dead_code,
215-
reason = "Intentional. Provide compatibility with the Queue class"
216-
)]
210+
#[pyarg(any, optional, py_default = "True")]
211+
block: OptionalArg<PyObjectRef>,
217212
#[pyarg(any, optional)]
218213
timeout: Option<PyObjectRef>,
219214
}
220215

221216
#[derive(FromArgs)]
222217
struct GetArgs {
223-
#[pyarg(any, default = true)]
224-
block: bool,
218+
#[pyarg(any, optional, py_default = "True")]
219+
block: OptionalArg<PyObjectRef>,
225220
#[pyarg(any, optional)]
226-
timeout: Option<TimeoutSeconds>,
221+
timeout: Option<PyObjectRef>,
222+
}
223+
224+
fn is_blocking(block: &OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult<bool> {
225+
match block {
226+
OptionalArg::Present(value) => value.try_to_bool(vm),
227+
OptionalArg::Missing => Ok(true),
228+
}
227229
}
228230

229231
#[pyclass(
@@ -248,9 +250,15 @@ mod _queue {
248250
}
249251

250252
#[pymethod]
251-
fn put(zelf: &Py<Self>, args: PutArgs, vm: &VirtualMachine) {
252-
let PutArgs { item, .. } = args;
253+
fn put(zelf: &Py<Self>, args: PutArgs, vm: &VirtualMachine) -> PyResult<()> {
254+
let PutArgs {
255+
item,
256+
block,
257+
timeout: _timeout,
258+
} = args;
259+
is_blocking(&block, vm)?;
253260
zelf.push(item, vm);
261+
Ok(())
254262
}
255263

256264
#[pymethod]
@@ -261,10 +269,11 @@ mod _queue {
261269
#[pymethod]
262270
fn get(zelf: &Py<Self>, args: GetArgs, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
263271
let GetArgs { block, timeout } = args;
272+
let blocking = is_blocking(&block, vm)?;
264273

265274
// Non-blocking: just try once
266-
if !block {
267-
return Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm));
275+
if !blocking {
276+
return Self::get_nowait(zelf, vm);
268277
}
269278

270279
#[cfg_attr(
@@ -274,22 +283,37 @@ mod _queue {
274283
reason = "We are still validating the 'timeout' arg even if we don't have threading"
275284
)
276285
)]
277-
let deadline = match timeout.map(|v| v.to_secs_f64()) {
278-
Some(v) if v < 0.0 => {
279-
return Err(vm.new_value_error("'timeout' must be a non-negative number"));
286+
let deadline = match timeout.as_ref() {
287+
Some(value) => {
288+
let overflow =
289+
|| vm.new_overflow_error("timestamp out of range for C PyTime_t");
290+
// SimpleQueue uses ceiling, unlike the away-from-zero
291+
// rounding used by thread locks and select timeouts.
292+
let nanos = pytime::from_seconds_object(value, pytime::Round::Ceiling, vm)?;
293+
if nanos < 0 {
294+
return Err(vm.new_value_error("'timeout' must be a non-negative number"));
295+
}
296+
Some(
297+
Instant::now()
298+
.checked_add(Duration::from_nanos(nanos as u64))
299+
.ok_or_else(overflow)?,
300+
)
280301
}
281-
Some(v) => Some(Instant::now() + Duration::from_secs_f64(v)),
282302
None => None,
283303
};
284304

285305
#[cfg(feature = "threading")]
286306
{
287-
if !zelf.sem.acquire(block, deadline, vm)? {
307+
if !zelf.sem.acquire(blocking, deadline, vm)? {
288308
return Err(empty_error(vm));
289309
}
290310
}
291311

292-
Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm))
312+
let item = {
313+
let mut buf = zelf.buf.lock();
314+
Self::get_inner(&mut buf)
315+
};
316+
item.ok_or_else(|| empty_error(vm))
293317
}
294318

295319
#[pymethod]
@@ -301,7 +325,11 @@ mod _queue {
301325
}
302326
}
303327

304-
Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm))
328+
let item = {
329+
let mut buf = zelf.buf.lock();
330+
Self::get_inner(&mut buf)
331+
};
332+
item.ok_or_else(|| empty_error(vm))
305333
}
306334

307335
#[pyclassmethod]

0 commit comments

Comments
 (0)