Skip to content

Commit f862b4b

Browse files
authored
Fix Windows/x86 deallocation and sequence compatibility (#9427)
* Adopt pymath remainder fix on Windows Pin pymath to the merged CPython-compatible remainder implementation and remove the passing Windows expected-failure marker. Investigation, implementation, and validation assisted by Codex. Assisted-by: Codex:GPT-5 * Keep deferred object deallocation iterative Run deferred deallocators inside a guarded trashcan context so their end calls cannot recursively drain the same queue. Reset the depth on unwind and test the drain invariant. Fixes stack overflow while dropping deeply nested Element trees on Windows. Investigation, implementation, validation, and focused review assisted by Codex. Assisted-by: Codex:GPT-5 * Fix 32-bit sequence hashes, repetition errors, and range state Use the declared 64-bit hash width for tuple hashing on every target, raise MemoryError for oversized sequence allocations, and preserve arbitrary-precision positions in long range iterators. Keep exhausted iterators exhausted instead of wrapping their counters. Add Rust regression tests and verify the canonical Python suites with an optimized Windows x86 interpreter. Implementation, investigation, validation, and focused review assisted by Codex. Assisted-by: Codex:GPT-5
1 parent 0342b80 commit f862b4b

7 files changed

Lines changed: 160 additions & 74 deletions

File tree

‎Cargo.lock‎

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

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ pem-rfc7468 = "1.0"
283283
pkcs8 = "0.11"
284284
proc-macro2 = "1.0.105"
285285
psm = "0.1"
286-
pymath = { git = "https://github.com/RustPython/pymath.git", rev = "dd1e9a4cf26d68caf3b549c09476f52e356e16a3", features = ["mul_add", "malachite-bigint", "complex"] }
286+
pymath = { git = "https://github.com/RustPython/pymath.git", rev = "6992bbfc853707545d0fb4b91931a2f36df89abe", features = ["mul_add", "malachite-bigint", "complex"] }
287287
pyo3 = "0.30"
288288
quote = "1.0.45"
289289
radium = "1.1.1"

‎Lib/test/test_math.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1759,7 +1759,6 @@ def testRadians(self):
17591759
self.ftest('radians(-45)', math.radians(-45), -math.pi/4)
17601760
self.ftest('radians(0)', math.radians(0), 0)
17611761

1762-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; Error message too long")
17631762
@requires_IEEE_754
17641763
def testRemainder(self):
17651764
from fractions import Fraction

‎crates/common/src/hash.rs‎

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -214,29 +214,12 @@ pub fn keyed_hash(key: u64, buf: &[u8]) -> u64 {
214214
pub fn hash_tuple<E>(
215215
element_hashes: impl IntoIterator<Item = Result<PyHash, E>>,
216216
) -> Result<PyHash, E> {
217-
const PRIME1: PyUHash = cfg_select! {
218-
target_pointer_width = "64" => 11400714785074694791,
219-
target_pointer_width = "32" => 2654435761,
220-
_ => unreachable!(),
221-
};
222-
223-
const PRIME2: PyUHash = cfg_select! {
224-
target_pointer_width = "64" => 14029467366897019727,
225-
target_pointer_width = "32" => 2246822519,
226-
_ => unreachable!(),
227-
};
228-
229-
const PRIME5: PyUHash = cfg_select! {
230-
target_pointer_width = "64" => 2870177450012600261,
231-
target_pointer_width = "32" => 374761393,
232-
_ => unreachable!(),
233-
};
234-
235-
const ROTATE: u32 = cfg_select! {
236-
target_pointer_width = "64" => 31,
237-
target_pointer_width = "32" => 13,
238-
_ => unreachable!(),
239-
};
217+
// PyHash is 64-bit even on 32-bit targets, so the xxHash parameters
218+
// must follow the hash width rather than the pointer width.
219+
const PRIME1: PyUHash = 11400714785074694791;
220+
const PRIME2: PyUHash = 14029467366897019727;
221+
const PRIME5: PyUHash = 2870177450012600261;
222+
const ROTATE: u32 = 31;
240223

241224
let mut acc = PRIME5;
242225
let mut len: PyUHash = 0;
@@ -309,6 +292,18 @@ impl FrozenSetHash {
309292
mod tests {
310293
use super::*;
311294

295+
#[test]
296+
fn tuple_hash_uses_the_declared_hash_width() {
297+
for (elements, expected) in [
298+
(&[][..], 5740354900026072187),
299+
(&[0][..], -8753497827991233192),
300+
(&[0, 0][..], -8458139203682520985),
301+
] {
302+
let actual = hash_tuple(elements.iter().copied().map(Ok::<_, ()>)).unwrap();
303+
assert_eq!(actual, expected);
304+
}
305+
}
306+
312307
#[test]
313308
fn from_keys_is_stable_and_seed_independent() {
314309
const K0: u64 = 0x0706_0504_0302_0100;

‎crates/vm/src/builtins/range.rs‎

Lines changed: 85 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use super::{
22
PyGenericAlias, PyInt, PyIntRef, PySlice, PyTupleRef, PyType, PyTypeRef, builtins_iter,
33
tuple::tuple_hash,
44
};
5-
use crate::common::lock::LazyLock;
5+
use crate::common::lock::{LazyLock, PyMutex};
66
use crate::{
77
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
88
VirtualMachine, atomic_func,
@@ -16,7 +16,6 @@ use crate::{
1616
},
1717
};
1818
use core::cell::Cell;
19-
use core::cmp::max;
2019
use core::ptr::NonNull;
2120
use crossbeam_utils::atomic::AtomicCell;
2221
use malachite_bigint::{BigInt, Sign};
@@ -376,7 +375,7 @@ impl Py<PyRange> {
376375
.into_pyobject(vm)
377376
} else {
378377
PyLongRangeIterator {
379-
index: AtomicCell::new(0),
378+
index: PyMutex::new(BigInt::zero()),
380379
start,
381380
step,
382381
length,
@@ -544,7 +543,7 @@ impl Iterable for PyRange {
544543
.into_pyobject(vm))
545544
} else {
546545
Ok(PyLongRangeIterator {
547-
index: AtomicCell::new(0),
546+
index: PyMutex::new(BigInt::zero()),
548547
start: start.clone(),
549548
step: step.clone(),
550549
length,
@@ -566,18 +565,11 @@ impl Representable for PyRange {
566565
}
567566
}
568567

569-
// Semantically, this is the same as the previous representation.
570-
//
571-
// Unfortunately, since AtomicCell requires a Copy type, no BigInt implementations can
572-
// generally be used. As such, usize::MAX is the upper bound on number of elements (length)
573-
// the range can contain in RustPython.
574-
//
575-
// This doesn't preclude the range from containing large values, since start and step
576-
// can be BigInts, we can store any arbitrary range of values.
568+
// Long ranges need arbitrary-precision positions as well as values.
577569
#[pyclass(module = false, name = "longrange_iterator")]
578570
#[derive(Debug)]
579571
pub(crate) struct PyLongRangeIterator {
580-
index: AtomicCell<usize>,
572+
index: PyMutex<BigInt>,
581573
start: BigInt,
582574
step: BigInt,
583575
length: BigInt,
@@ -594,7 +586,7 @@ impl PyPayload for PyLongRangeIterator {
594586
impl Py<PyLongRangeIterator> {
595587
#[pymethod]
596588
fn __length_hint__(&self) -> BigInt {
597-
let index = BigInt::from(self.index.load());
589+
let index = self.index.lock().clone();
598590
if index < self.length {
599591
self.length.clone() - index
600592
} else {
@@ -604,17 +596,19 @@ impl Py<PyLongRangeIterator> {
604596

605597
#[pymethod]
606598
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
607-
self.index.store(range_state(&self.length, &state, vm)?);
599+
let index = range_state(&self.length, &state, vm)?;
600+
*self.index.lock() = index;
608601
Ok(())
609602
}
610603

611604
#[pymethod]
612605
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
606+
let index = self.index.lock().clone();
613607
range_iter_reduce(
614608
self.start.clone(),
615609
self.length.clone(),
616610
self.step.clone(),
617-
self.index.load(),
611+
index,
618612
vm,
619613
)
620614
}
@@ -623,17 +617,17 @@ impl Py<PyLongRangeIterator> {
623617
impl SelfIter for PyLongRangeIterator {}
624618
impl IterNext for PyLongRangeIterator {
625619
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
626-
// TODO: In pathological case (index == usize::MAX) this can wrap around
627-
// (since fetch_add wraps). This would result in the iterator spinning again
628-
// from the beginning.
629-
let index = BigInt::from(zelf.index.fetch_add(1));
630-
let r = if index < zelf.length {
631-
let value = zelf.start.clone() + index * zelf.step.clone();
632-
PyIterReturn::Return(vm.ctx.new_int(value).into())
633-
} else {
634-
PyIterReturn::StopIteration(None)
620+
let index = {
621+
let mut index = zelf.index.lock();
622+
if *index >= zelf.length {
623+
return Ok(PyIterReturn::StopIteration(None));
624+
}
625+
let current = index.clone();
626+
*index += 1;
627+
current
635628
};
636-
Ok(r)
629+
let value = zelf.start.clone() + index * zelf.step.clone();
630+
Ok(PyIterReturn::Return(vm.ctx.new_int(value).into()))
637631
}
638632
}
639633

@@ -665,8 +659,11 @@ impl Py<PyRangeIterator> {
665659

666660
#[pymethod]
667661
fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
668-
self.index
669-
.store(range_state(&BigInt::from(self.length), &object, vm)?);
662+
self.index.store(
663+
range_state(&BigInt::from(self.length), &object, vm)?
664+
.to_usize()
665+
.unwrap(),
666+
);
670667
Ok(())
671668
}
672669

@@ -676,7 +673,7 @@ impl Py<PyRangeIterator> {
676673
BigInt::from(self.start),
677674
BigInt::from(self.length),
678675
BigInt::from(self.step),
679-
self.index.load(),
676+
BigInt::from(self.index.load()),
680677
vm,
681678
)
682679
}
@@ -686,12 +683,14 @@ impl PyRangeIterator {
686683
/// Fast path for FOR_ITER specialization. Returns the next isize value
687684
/// without allocating PyInt or PyIterReturn.
688685
pub(crate) fn fast_next(&self) -> Option<isize> {
689-
let index = self.index.fetch_add(1);
690-
if index < self.length {
691-
Some(self.start + (index as isize) * self.step)
692-
} else {
693-
None
694-
}
686+
let index = self
687+
.index
688+
.fetch_update(|index| (index < self.length).then(|| index + 1))
689+
.ok()?;
690+
Some(
691+
self.start
692+
.wrapping_add((index as isize).wrapping_mul(self.step)),
693+
)
695694
}
696695
}
697696

@@ -710,13 +709,12 @@ fn range_iter_reduce(
710709
start: BigInt,
711710
length: BigInt,
712711
step: BigInt,
713-
index: usize,
712+
index: BigInt,
714713
vm: &VirtualMachine,
715714
) -> PyResult<PyTupleRef> {
716715
let iter = builtins_iter(vm)?;
717-
// CPython pickles the remaining range with a None state. next() increments
718-
// the index unconditionally, so clamp it to length before rebasing start.
719-
let index = BigInt::from(index).min(length.clone());
716+
// CPython pickles the remaining range with a None state.
717+
let index = index.min(length.clone());
720718
let stop = start.clone() + length * step.clone();
721719
let start = start + index * step.clone();
722720
let range = PyRange {
@@ -727,15 +725,10 @@ fn range_iter_reduce(
727725
Ok(vm.new_tuple((iter, (range,), vm.ctx.none())))
728726
}
729727

730-
// Silently clips state (i.e index) in range [0, usize::MAX].
731-
fn range_state(length: &BigInt, state: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
728+
// Silently clips state (i.e index) in range [0, length].
729+
fn range_state(length: &BigInt, state: &PyObject, vm: &VirtualMachine) -> PyResult<BigInt> {
732730
if let Some(i) = state.downcast_ref::<PyInt>() {
733-
let mut index = i.as_bigint();
734-
let max_usize = BigInt::from(usize::MAX);
735-
if index > length {
736-
index = max(length, &max_usize);
737-
}
738-
Ok(index.to_usize().unwrap_or(0))
731+
Ok(i.as_bigint().clone().clamp(BigInt::zero(), length.clone()))
739732
} else {
740733
Err(vm.new_type_error("an integer is required."))
741734
}
@@ -761,3 +754,48 @@ impl TryFromObject for RangeIndex {
761754
})
762755
}
763756
}
757+
758+
#[cfg(test)]
759+
mod tests {
760+
use super::*;
761+
762+
#[test]
763+
fn long_iterator_preserves_arbitrary_precision_state() {
764+
crate::Interpreter::without_stdlib(Default::default()).enter(|vm| {
765+
let length: BigInt = BigInt::one() << 100;
766+
let iter = PyLongRangeIterator {
767+
index: PyMutex::new(BigInt::zero()),
768+
start: BigInt::zero(),
769+
step: BigInt::one(),
770+
length: length.clone(),
771+
}
772+
.into_ref(&vm.ctx);
773+
let state: BigInt = &length - 1;
774+
iter.__setstate__(vm.ctx.new_bigint(&state).into(), vm)
775+
.unwrap();
776+
assert_eq!(iter.__length_hint__(), BigInt::one());
777+
let PyIterReturn::Return(value) = PyLongRangeIterator::next(&iter, vm).unwrap() else {
778+
panic!("wide iterator state was lost");
779+
};
780+
assert_eq!(value.downcast_ref::<PyInt>().unwrap().as_bigint(), &state);
781+
for _ in 0..2 {
782+
assert!(matches!(
783+
PyLongRangeIterator::next(&iter, vm).unwrap(),
784+
PyIterReturn::StopIteration(None)
785+
));
786+
}
787+
});
788+
}
789+
790+
#[test]
791+
fn exhausted_fast_iterator_does_not_wrap_its_index() {
792+
let iter = PyRangeIterator {
793+
index: AtomicCell::new(usize::MAX),
794+
start: 0,
795+
step: 1,
796+
length: usize::MAX,
797+
};
798+
assert_eq!(iter.fast_next(), None);
799+
assert_eq!(iter.fast_next(), None);
800+
}
801+
}

‎crates/vm/src/object/core.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,45 @@ mod trashcan {
144144
item
145145
};
146146
if let Some((obj, dealloc)) = next {
147+
// A queued deallocator may defer more objects, but its
148+
// end() must not start another drain.
149+
t.depth.set(1);
150+
let _draining = scopeguard::guard((), |()| t.depth.set(0));
147151
unsafe { dealloc(obj) };
148152
} else {
149153
break;
150154
}
151155
}
152156
})
153157
}
158+
159+
#[cfg(test)]
160+
mod tests {
161+
use super::*;
162+
163+
unsafe fn assert_guarded_dealloc(_: *mut super::super::PyObject) {
164+
assert!(TRASHCAN.with(|t| t.depth.get() > 0));
165+
}
166+
167+
#[test]
168+
fn deferred_deallocations_remain_guarded() {
169+
// This callback never dereferences its opaque object pointer.
170+
let obj = core::ptr::null_mut();
171+
unsafe {
172+
for _ in 0..TRASHCAN_LIMIT {
173+
assert!(begin(obj, assert_guarded_dealloc));
174+
}
175+
assert!(!begin(obj, assert_guarded_dealloc));
176+
for _ in 0..TRASHCAN_LIMIT {
177+
end();
178+
}
179+
}
180+
TRASHCAN.with(|t| {
181+
assert_eq!(t.depth.get(), 0);
182+
assert!(t.queue.take().is_empty());
183+
});
184+
}
185+
}
154186
}
155187

156188
/// Default dealloc: handles __del__, weakref clearing, tp_clear, and memory free.

0 commit comments

Comments
 (0)