Skip to content

Commit a44059a

Browse files
committed
Fix list cmp deadlock, wasm digit overflow, REPL prompt
Do not hold list/deque locks across item comparison callbacks. Compute int-to-str digit bounds in u64 so the check cannot wrap on wasm32. Snapshot set contents when list.extend copies a set. For a non-TTY stdin, write the REPL prompt to stderr and read lines from stdin. Flush stdout/stderr after each interactive command. Set sys.ps1/ps2 to ">>> " and "... ". Unskip list mutation compares, asyncio all_tasks race, importlib deadlock/parallel/circular-import tests, and REPL stdout flush. Assisted-by: Grok:4.6
1 parent 170c7c6 commit a44059a

13 files changed

Lines changed: 127 additions & 52 deletions

File tree

‎Lib/test/test_asyncio/test_free_threading.py‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,6 @@ def tearDown(self):
189189
def factory(self, loop, coro, **kwargs):
190190
return asyncio.tasks._PyTask(coro, loop=loop, **kwargs)
191191

192-
@unittest.skip("TODO: RUSTPYTHON; hangs - Python _current_tasks dict not thread-safe")
193-
def test_all_tasks_race(self):
194-
return super().test_all_tasks_race()
195-
196192

197193
@unittest.skipUnless(hasattr(asyncio.tasks, "_c_all_tasks"), "requires _asyncio")
198194
class TestCFreeThreading(TestFreeThreading, TestCase):
@@ -224,10 +220,6 @@ class TestEagerPyFreeThreading(TestPyFreeThreading):
224220
def factory(self, loop, coro, eager_start=True, **kwargs):
225221
return asyncio.tasks._PyTask(coro, loop=loop, **kwargs, eager_start=eager_start)
226222

227-
@unittest.skip("TODO: RUSTPYTHON; hangs - Python _current_tasks dict not thread-safe")
228-
def test_all_tasks_race(self):
229-
return super().test_all_tasks_race()
230-
231223

232224
@unittest.skipUnless(hasattr(asyncio.tasks, "_c_all_tasks"), "requires _asyncio")
233225
class TestEagerCFreeThreading(TestCFreeThreading, TestCase):

‎Lib/test/test_cmd_line_script.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,19 +208,17 @@ def check_repl_stderr_flush(self, separate_stderr=False):
208208
self.assertIn(b' ~^~', stderr.readline())
209209
self.assertIn(b'ZeroDivisionError', stderr.readline())
210210

211-
@unittest.skip("TODO: RUSTPYTHON; test hang in middle")
212211
def test_repl_stdout_flush(self):
213212
self.check_repl_stdout_flush()
214213

215-
@unittest.skip("TODO: RUSTPYTHON; test hang in middle")
216214
def test_repl_stdout_flush_separate_stderr(self):
217215
self.check_repl_stdout_flush(True)
218216

219-
@unittest.skip("TODO: RUSTPYTHON; test hang in middle")
217+
@unittest.skip("TODO: RUSTPYTHON; <stdin> traceback omits the source line and caret")
220218
def test_repl_stderr_flush(self):
221219
self.check_repl_stderr_flush()
222220

223-
@unittest.skip("TODO: RUSTPYTHON; test hang in middle")
221+
@unittest.skip("TODO: RUSTPYTHON; <stdin> traceback omits the source line and caret")
224222
def test_repl_stderr_flush_separate_stderr(self):
225223
self.check_repl_stderr_flush(True)
226224

‎Lib/test/test_importlib/test_locks.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ def f():
9999
self.assertEqual(len(results), NTHREADS)
100100
return results
101101

102-
@unittest.skip("TODO: RUSTPYTHON; sometimes hangs")
103102
def test_deadlock(self):
104103
results = self.run_deadlock_avoidance_test(True)
105104
# At least one of the threads detected a potential deadlock on its

‎Lib/test/test_importlib/test_threaded_import.py‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@ def check_parallel_module_init(self, mock_os):
135135
if verbose:
136136
print("OK.")
137137

138-
@unittest.skip("TODO: RUSTPYTHON; flaky")
139138
@support.bigmemtest(size=50, memuse=76*2**20, dry_run=False)
140139
def test_parallel_module_init(self, size):
141140
self.check_parallel_module_init()
@@ -247,15 +246,13 @@ def target():
247246
__import__(TESTFN)
248247
del sys.modules[TESTFN]
249248

250-
@unittest.skip("TODO: RUSTPYTHON; hang; Suspected cause of crashes in Windows CI - PermissionError: [WinError 32] Permission denied: \"C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\test_python_0cdrhhs_\\test_python_6340æ\"")
251249
@support.bigmemtest(size=1, memuse=1.8*2**30, dry_run=False)
252250
def test_concurrent_futures_circular_import(self, size):
253251
# Regression test for bpo-43515
254252
fn = os.path.join(os.path.dirname(__file__),
255253
'partial', 'cfimport.py')
256254
script_helper.assert_python_ok(fn)
257255

258-
@unittest.skip("TODO: RUSTPYTHON; hang")
259256
@support.bigmemtest(size=1, memuse=1.8*2**30, dry_run=False)
260257
def test_multiprocessing_pool_circular_import(self, size):
261258
# Regression test for bpo-41567

‎Lib/test/test_list.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,6 @@ class L(list): pass
226226
with self.assertRaises(TypeError):
227227
(3,) + L([1,2])
228228

229-
@unittest.skip("TODO: RUSTPYTHON; hang")
230229
def test_equal_operator_modifying_operand(self):
231230
# test fix for seg fault reported in bpo-38588 part 2.
232231
class X:
@@ -252,7 +251,6 @@ def __eq__(self, other):
252251
list4 = [1]
253252
self.assertFalse(list3 == list4)
254253

255-
@unittest.skip("TODO: RUSTPYTHON; hang")
256254
def test_lt_operator_modifying_operand(self):
257255
# See gh-120298
258256
class evil:

‎crates/host_env/src/readline.rs‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,22 @@ pub enum ReadlineResult {
1818
Other(OtherError),
1919
}
2020

21+
fn stdio_readline(prompt: &str) -> ReadlineResult {
22+
use std::io::prelude::*;
23+
eprint!("{prompt}");
24+
if let Err(e) = io::stderr().flush() {
25+
return ReadlineResult::Io(e);
26+
}
27+
28+
let line = io::stdin().lock().lines().next();
29+
match line {
30+
Some(Ok(line)) => ReadlineResult::Line(line),
31+
None => ReadlineResult::Eof,
32+
Some(Err(e)) if e.kind() == io::ErrorKind::Interrupted => ReadlineResult::Interrupt,
33+
Some(Err(e)) => ReadlineResult::Io(e),
34+
}
35+
}
36+
2137
#[allow(unused)]
2238
pub mod basic_readline {
2339
use super::*;
@@ -48,19 +64,7 @@ pub mod basic_readline {
4864
}
4965

5066
pub fn readline(&mut self, prompt: &str) -> ReadlineResult {
51-
use std::io::prelude::*;
52-
print!("{prompt}");
53-
if let Err(e) = io::stdout().flush() {
54-
return ReadlineResult::Io(e);
55-
}
56-
57-
let next_line = io::stdin().lock().lines().next();
58-
match next_line {
59-
Some(Ok(line)) => ReadlineResult::Line(line),
60-
None => ReadlineResult::Eof,
61-
Some(Err(e)) if e.kind() == io::ErrorKind::Interrupted => ReadlineResult::Interrupt,
62-
Some(Err(e)) => ReadlineResult::Io(e),
63-
}
67+
stdio_readline(prompt)
6468
}
6569
}
6670
}
@@ -126,6 +130,13 @@ pub mod rustyline_readline {
126130
}
127131

128132
pub fn readline(&mut self, prompt: &str) -> ReadlineResult {
133+
use std::io::IsTerminal;
134+
// Pipes have no termios. Write the prompt to stderr and read
135+
// stdin, matching PyOS_StdioReadline, so `python -i` under
136+
// spawn still emits `>>> `.
137+
if !io::stdin().is_terminal() {
138+
return stdio_readline(prompt);
139+
}
129140
use rustyline::error::ReadlineError;
130141
loop {
131142
break match self.repl.readline(prompt) {

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -707,8 +707,10 @@ pub(crate) fn check_int_to_str_digits(value: &BigInt, vm: &VirtualMachine) -> Py
707707
return Ok(());
708708
}
709709
// Upper bound on decimal digit count: ⌈bits × log10(2)⌉ + 1, with log10(2) ≈ 0.30103.
710-
let digits_upper = (bits as usize * 30103 / 100000) + 1;
711-
if digits_upper > limit {
710+
// Multiply in u64: `bits as usize * 30103` wraps on 32-bit (wasm32) once
711+
// bits ≳ 142_500, which silently accepts over-limit conversions.
712+
let digits_upper = (bits as u64).saturating_mul(30103) / 100_000 + 1;
713+
if digits_upper > limit as u64 {
712714
return Err(vm.new_value_error(format!(
713715
"Exceeds the limit ({limit} digits) for integer string conversion; \
714716
use sys.set_int_max_str_digits() to increase the limit"

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ use crate::{
1414
class::PyClassImpl,
1515
convert::ToPyObject,
1616
function::{ArgSize, Either, FuncArgs, OptionalArg, PyComparisonValue},
17-
iter::PyExactSizeIterator,
1817
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
1918
recursion::ReprGuard,
2019
sequence::{MutObjectSequenceOp, OptionalRangeArgs, SequenceExt, SequenceMutExt},
@@ -590,11 +589,21 @@ impl Comparable for PyList {
590589
return Ok(res.into());
591590
}
592591
let other = class_or_notimplemented!(Self, other);
593-
let a = &*zelf.borrow_vec();
594-
let b = &*other.borrow_vec();
595-
a.iter()
596-
.richcompare(b.iter(), op, vm)
597-
.map(PyComparisonValue::Implemented)
592+
// Item comparison can mutate either list (clear, resize). Holding the
593+
// element lock across that callback deadlocks on the write side.
594+
crate::iter::richcompare_mutating_seqs(
595+
|i| {
596+
let a = zelf.borrow_vec();
597+
(a.len(), a.get(i).cloned())
598+
},
599+
|i| {
600+
let b = other.borrow_vec();
601+
(b.len(), b.get(i).cloned())
602+
},
603+
op,
604+
vm,
605+
)
606+
.map(PyComparisonValue::Implemented)
598607
}
599608
}
600609

‎crates/vm/src/iter.rs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,51 @@ pub trait PyExactSizeIterator<'a>: ExactSizeIterator<Item = &'a PyObjectRef> + S
5151
}
5252

5353
impl<'a, T> PyExactSizeIterator<'a> for T where T: ExactSizeIterator<Item = &'a PyObjectRef> + Sized {}
54+
55+
/// Compare two sequences whose item-comparison callbacks may mutate the
56+
/// containers. `get(i)` must snapshot `(len, item_at_i)` and drop any
57+
/// container lock before returning.
58+
///
59+
/// After an unequal item, sizes are read again: if a callback shrank a
60+
/// sequence so `i` is now past the end, the result is a length comparison
61+
/// rather than the item inequality.
62+
pub fn richcompare_mutating_seqs(
63+
mut get_a: impl FnMut(usize) -> (usize, Option<PyObjectRef>),
64+
mut get_b: impl FnMut(usize) -> (usize, Option<PyObjectRef>),
65+
op: PyComparisonOp,
66+
vm: &VirtualMachine,
67+
) -> PyResult<bool> {
68+
if matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) {
69+
let (a_len, _) = get_a(0);
70+
let (b_len, _) = get_b(0);
71+
if a_len != b_len {
72+
return Ok(op == PyComparisonOp::Ne);
73+
}
74+
}
75+
76+
let mut i = 0usize;
77+
loop {
78+
let (a_len, a_item) = get_a(i);
79+
let (b_len, b_item) = get_b(i);
80+
let (Some(a_item), Some(b_item)) = (a_item, b_item) else {
81+
return Ok(op.eval_ord(a_len.cmp(&b_len)));
82+
};
83+
84+
if vm.bool_eq(&a_item, &b_item)? {
85+
i += 1;
86+
continue;
87+
}
88+
89+
let (a_len, _) = get_a(i);
90+
let (b_len, _) = get_b(i);
91+
if i >= a_len || i >= b_len {
92+
return Ok(op.eval_ord(a_len.cmp(&b_len)));
93+
}
94+
95+
return match op {
96+
PyComparisonOp::Eq => Ok(false),
97+
PyComparisonOp::Ne => Ok(true),
98+
_ => a_item.rich_compare_bool(&b_item, op, vm),
99+
};
100+
}
101+
}

‎crates/vm/src/stdlib/_collections.rs‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ mod _collections {
1313
common::lock::{PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard},
1414
convert::ToPyObject,
1515
function::{FuncArgs, KwArgs, OptionalArg, PyComparisonValue},
16-
iter::PyExactSizeIterator,
1716
object::{Traverse, TraverseFn},
1817
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
1918
recursion::ReprGuard,
@@ -587,11 +586,19 @@ mod _collections {
587586
}
588587

589588
let other = class_or_notimplemented!(Self, other);
590-
let lhs = zelf.borrow_deque();
591-
let rhs = other.borrow_deque();
592-
lhs.iter()
593-
.richcompare(rhs.iter(), op, vm)
594-
.map(PyComparisonValue::Implemented)
589+
crate::iter::richcompare_mutating_seqs(
590+
|i| {
591+
let lhs = zelf.borrow_deque();
592+
(lhs.len(), lhs.get(i).cloned())
593+
},
594+
|i| {
595+
let rhs = other.borrow_deque();
596+
(rhs.len(), rhs.get(i).cloned())
597+
},
598+
op,
599+
vm,
600+
)
601+
.map(PyComparisonValue::Implemented)
595602
}
596603
}
597604

0 commit comments

Comments
 (0)