Skip to content

Commit bca6c95

Browse files
authored
Raise MemoryError without allocating via a MemoryError freelist (#8645)
* Add no_memory_error for allocation failures Assisted-by: Claude Code:claude-fable-5-1 * Use no_memory_error at allocation failure sites Assisted-by: Claude Code:claude-fable-5-1 * Raise MemoryError instead of aborting on sequence repeat allocation failure Vec::with_capacity and Vec::reserve in SequenceExt::mul and SequenceMutExt::imul call handle_alloc_error on failure, which aborts the process under panic = "abort". `[1, 2, 3] * 10**17` passes the MAX_MEMORY_SIZE guard (2.4e18 bytes < isize::MAX) and aborted at the allocation instead of raising MemoryError. Use try_reserve_exact and map failures to vm.no_memory_error(). This also removes the n != 2 special case in imul: with the reserve done unconditionally, the copy loop runs zero times for n == 2 and the final append uses the reserved capacity. Assisted-by: Claude Code:claude-fable-5-1 * Recycle MemoryError instances through a dedicated payload freelist no_memory_error allocated the exception object on every raise, so under real memory exhaustion the raise itself could abort. Keep dead MemoryError husks in a process-wide reserve and revive them on the next raise without touching the allocator. The freelist is scoped to MemoryError at the type level. PyMemoryError already exists as a transparent wrapper payload, but instances never used it: the default exception slot_new delegates to the base class, so everything was constructed as PyBaseException. Route no_memory_error through a PyMemoryError-typed construction instead; the freelist hooks live on PyMemoryError's own PyPayload impl, the dealloc glue is monomorphized per payload type, and the existing exact-type push gate admits exactly MemoryError husks. The #[pyexception] macro always generates the PyPayload impl, which left no way to attach freelist configuration; a payload = "manual" attribute now skips that generation so a type can write its own impl, mirroring the generated PAYLOAD_TYPE_ID chain and class-based downcast validation that keep the payload flavors interchangeable. Exceptions are the first HAS_DICT freelist type, so their husks carry an ObjExt prefix that PyInner::dealloc would normally drop; clear its instance dict and member slots before pushing so no stale attributes survive into a revived instance. The reserve is a process-wide Mutex rather than a thread_local so a single prewarm at interpreter init covers every thread; MemoryError is a cold path, so the lock is uncontended. Python-level MemoryError() still constructs a PyBaseException payload through the delegated slot_new and simply does not participate, matching CPython, where only the PyErr_NoMemory path uses the preallocated reserve. Assisted-by: Claude Code:claude-fable-5-1 * Clear MemoryError husks before they enter the freelist Assisted-by: Claude Code:claude-fable-5-1 * Use no_memory_error for the bz2 allocation failure The shared bz2 engine maps BZ_MEM_ERROR to Bz2Error::Mem; report it through no_memory_error like the other allocation-failure sites, matching PyErr_NoMemory in CPython's _bz2module. Assisted-by: Claude Code:claude-fable-5-1 * Change MemoryError husks Vec to a fixed-size array Assisted-by: Claude Code:claude-fable-5-1 * Increase MemoryError freelist size from 4 to 16 * Address review: keep repeat and husk clearing allocation-safe Assisted-by: Claude Code:claude-fable-5-1
1 parent 8915474 commit bca6c95

20 files changed

Lines changed: 169 additions & 44 deletions

File tree

‎crates/derive-impl/src/pyclass.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -712,7 +712,9 @@ pub(crate) fn impl_pyclass(attr: PunctuatedNestedMeta, item: Item) -> Result<Tok
712712

713713
// Generate PyPayload impl based on whether base exists
714714
#[allow(clippy::collapsible_else_if)]
715-
let impl_payload = if let Some(base_type) = &base {
715+
let impl_payload = if class_meta.manual_payload()? {
716+
quote! {}
717+
} else if let Some(base_type) = &base {
716718
let class_fn = if let Some(ctx_type_name) = class_meta.ctx_name()? {
717719
let ctx_type_ident = Ident::new(&ctx_type_name, ident.span());
718720
quote! { ctx.types.#ctx_type_ident }
@@ -803,8 +805,13 @@ pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: &Item) -> Resul
803805
None => quote! {},
804806
};
805807

808+
let payload_attr = match class_meta.inner()._optional_str("payload")? {
809+
Some(value) => quote! { , payload = #value },
810+
None => quote! {},
811+
};
812+
806813
let ret = quote! {
807-
#[pyclass(module = false, name = #class_name, base = #base_class_name #traverse_attr)]
814+
#[pyclass(module = false, name = #class_name, base = #base_class_name #traverse_attr #payload_attr)]
808815
#item
809816
#impl_pyclass
810817
};

‎crates/derive-impl/src/util.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@ impl ItemMeta for ClassItemMeta {
362362
"impl",
363363
"traverse",
364364
"clear", // tp_clear
365+
"payload",
365366
];
366367

367368
fn from_inner(inner: ItemMetaInner) -> Self {
@@ -403,6 +404,10 @@ impl ClassItemMeta {
403404
self.inner()._optional_str("ctx")
404405
}
405406

407+
pub(crate) fn manual_payload(&self) -> Result<bool> {
408+
Ok(self.inner()._optional_str("payload")?.as_deref() == Some("manual"))
409+
}
410+
406411
pub(crate) fn base(&self) -> Result<Option<syn::Path>> {
407412
self.inner()._optional_path("base")
408413
}
@@ -473,6 +478,7 @@ impl ItemMeta for ExceptionItemMeta {
473478
"ctx",
474479
"impl",
475480
"traverse",
481+
"payload",
476482
];
477483

478484
fn from_inner(inner: ItemMetaInner) -> Self {

‎crates/stdlib/src/array.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ pub mod array {
417417
$(ArrayContentType::$n(v) => {
418418
// MemoryError instead Overflow Error, hard to says it is right
419419
// but it is how cpython doing right now
420-
let elements = v.mul(vm, value).map_err(|_| vm.new_memory_error("".to_owned()))?;
420+
let elements = v.mul(vm, value).map_err(|_| vm.no_memory_error())?;
421421
Ok(ArrayContentType::$n(elements))
422422
})*
423423
}
@@ -428,7 +428,7 @@ pub mod array {
428428
$(ArrayContentType::$n(v) => {
429429
// MemoryError instead Overflow Error, hard to says it is right
430430
// but it is how cpython doing right now
431-
v.imul(vm, value).map_err(|_| vm.new_memory_error("".to_owned()))
431+
v.imul(vm, value).map_err(|_| vm.no_memory_error())
432432
})*
433433
}
434434
}

‎crates/stdlib/src/bz2.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ mod _bz2 {
2525
backend::Bz2Error::Sequence => vm.new_runtime_error(
2626
"Internal error - Invalid sequence of commands sent to libbzip2",
2727
),
28-
backend::Bz2Error::Mem => vm.new_memory_error("out of memory"),
28+
backend::Bz2Error::Mem => vm.no_memory_error(),
2929
}
3030
}
3131

‎crates/stdlib/src/lzma.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ mod _lzma {
9090

9191
fn map_backend_error(error: backend::Error, vm: &VirtualMachine) -> PyBaseExceptionRef {
9292
match error {
93-
backend::Error::Memory => vm.new_memory_error(""),
93+
backend::Error::Memory => vm.no_memory_error(),
9494
backend::Error::Value(message) => vm.new_value_error(message),
9595
backend::Error::Lzma(message) => new_lzma_error(message, vm),
9696
backend::Error::Eof => vm.new_eof_error("End of stream already reached"),

‎crates/stdlib/src/socket.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1602,7 +1602,7 @@ mod _socket {
16021602
let mut buffer = Vec::new();
16031603
buffer
16041604
.try_reserve_exact(bufsize)
1605-
.map_err(|_| vm.new_memory_error(""))?;
1605+
.map_err(|_| vm.no_memory_error())?;
16061606
let sock = self.sock()?;
16071607
let n = self.sock_op(vm, SockWaitKind::Read, || {
16081608
sock.recv_with_flags(buffer.spare_capacity_mut(), flags)
@@ -1655,7 +1655,7 @@ mod _socket {
16551655
let mut buffer = Vec::new();
16561656
buffer
16571657
.try_reserve_exact(bufsize)
1658-
.map_err(|_| vm.new_memory_error(""))?;
1658+
.map_err(|_| vm.no_memory_error())?;
16591659
let (n, addr) = self.sock_op(vm, SockWaitKind::Read, || {
16601660
self.sock()?
16611661
.recv_from_with_flags(buffer.spare_capacity_mut(), flags)
@@ -2412,7 +2412,7 @@ mod _socket {
24122412
let mut scratch = Vec::new();
24132413
scratch
24142414
.try_reserve_exact(len)
2415-
.map_err(|_| vm.new_memory_error(""))?;
2415+
.map_err(|_| vm.no_memory_error())?;
24162416
Ok(scratch)
24172417
}
24182418

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1336,7 +1336,7 @@ impl PyStr {
13361336
let filled = self
13371337
.as_wtf8()
13381338
.py_zfill(width)
1339-
.ok_or_else(|| vm.new_memory_error(""))?;
1339+
.ok_or_else(|| vm.no_memory_error())?;
13401340
// SAFETY: this is safe-guaranteed because the original self.as_wtf8() is valid wtf8
13411341
Ok(unsafe { Wtf8Buf::from_bytes_unchecked(filled) })
13421342
}
@@ -1358,7 +1358,7 @@ impl PyStr {
13581358
return Ok(self.as_wtf8().to_owned());
13591359
}
13601360
pad(self.as_wtf8(), width as usize, fillchar, self.len())
1361-
.ok_or_else(|| vm.new_memory_error(""))
1361+
.ok_or_else(|| vm.no_memory_error())
13621362
}
13631363

13641364
#[pymethod]

‎crates/vm/src/bytes_inner.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ impl PyBytesInner {
594594
if len as isize >= width {
595595
return Ok(Vec::from(&self.elements[..]));
596596
}
597-
pad(&self.elements, width as usize, fillchar, len).ok_or_else(|| vm.new_memory_error(""))
597+
pad(&self.elements, width as usize, fillchar, len).ok_or_else(|| vm.no_memory_error())
598598
}
599599

600600
pub fn center(
@@ -847,7 +847,7 @@ impl PyBytesInner {
847847
pub fn zfill(&self, width: isize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
848848
self.elements
849849
.py_zfill(width)
850-
.ok_or_else(|| vm.new_memory_error(""))
850+
.ok_or_else(|| vm.no_memory_error())
851851
}
852852

853853
// len(self)>=1, from="", len(to)>=1, max_count>=1

‎crates/vm/src/exceptions.rs‎

Lines changed: 79 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1-
use self::types::{PyBaseException, PyBaseExceptionRef};
1+
use self::types::{PyBaseException, PyBaseExceptionRef, PyException, PyMemoryError};
2+
pub use super::exception_group::exception_group;
23
use crate::common::lock::PyRwLock;
34
use crate::object::{Traverse, TraverseFn};
45
use crate::{
5-
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
6+
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
7+
VirtualMachine,
68
builtins::{
79
PyList, PyNone, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef,
810
traceback::{PyTraceback, PyTracebackRef},
@@ -20,10 +22,9 @@ use crossbeam_utils::atomic::AtomicCell;
2022
use itertools::Itertools;
2123
#[cfg(feature = "host_env")]
2224
use std::io::{BufRead, BufReader};
25+
use std::sync::Mutex;
2326
use std::{collections::HashSet, io};
2427

25-
pub use super::exception_group::exception_group;
26-
2728
unsafe impl Traverse for PyBaseException {
2829
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
2930
self.traceback.traverse(tracer_fn);
@@ -40,13 +41,59 @@ impl core::fmt::Debug for PyBaseException {
4041
}
4142
}
4243

44+
const MEMORY_ERROR_FREELIST_SIZE: usize = 16;
45+
46+
struct MemoryErrorHusk(*mut PyObject);
47+
unsafe impl Send for MemoryErrorHusk {}
48+
49+
static MEMORY_ERROR_FREELIST: Mutex<[Option<MemoryErrorHusk>; MEMORY_ERROR_FREELIST_SIZE]> =
50+
Mutex::new([const { None }; MEMORY_ERROR_FREELIST_SIZE]);
51+
4352
impl PyPayload for PyBaseException {
4453
#[inline]
4554
fn class(ctx: &Context) -> &'static Py<PyType> {
4655
ctx.exceptions.base_exception_type
4756
}
4857
}
4958

59+
impl PyPayload for PyMemoryError {
60+
const PAYLOAD_TYPE_ID: core::any::TypeId = <PyException as PyPayload>::PAYLOAD_TYPE_ID;
61+
const HAS_FREELIST: bool = true;
62+
const MAX_FREELIST: usize = MEMORY_ERROR_FREELIST_SIZE;
63+
64+
#[inline]
65+
unsafe fn validate_downcastable_from(obj: &PyObject) -> bool {
66+
obj.class()
67+
.fast_issubclass(<Self as StaticType>::static_type())
68+
}
69+
70+
fn class(_ctx: &Context) -> &'static Py<PyType> {
71+
<Self as StaticType>::static_type()
72+
}
73+
74+
unsafe fn freelist_push(obj: *mut PyObject) -> bool {
75+
let Ok(mut list) = MEMORY_ERROR_FREELIST.lock() else {
76+
return false;
77+
};
78+
match list.iter_mut().find(|element| element.is_none()) {
79+
Some(element) => {
80+
*element = Some(MemoryErrorHusk(obj));
81+
true
82+
}
83+
None => false,
84+
}
85+
}
86+
87+
unsafe fn freelist_pop(_payload: &Self) -> Option<core::ptr::NonNull<PyObject>> {
88+
let husk = MEMORY_ERROR_FREELIST
89+
.lock()
90+
.ok()?
91+
.iter_mut()
92+
.find_map(|element| element.take())?;
93+
core::ptr::NonNull::new(husk.0)
94+
}
95+
}
96+
5097
impl VirtualMachine {
5198
// Why `impl VirtualMachine`?
5299
// These functions are natively free function in CPython - not methods of PyException
@@ -2013,11 +2060,38 @@ pub(super) mod types {
20132060
}
20142061
}
20152062

2016-
#[pyexception(name, base = PyException, ctx = "memory_error", impl)]
2063+
#[pyexception(name, base = PyException, ctx = "memory_error", impl, payload = "manual", traverse = "manual")]
20172064
#[derive(Debug)]
20182065
#[repr(transparent)]
20192066
pub struct PyMemoryError(PyException);
20202067

2068+
impl PyMemoryError {
2069+
pub(crate) fn empty(vm: &VirtualMachine) -> Self {
2070+
Self(PyException(PyBaseException::new(vec![], vm)))
2071+
}
2072+
}
2073+
2074+
unsafe impl Traverse for PyMemoryError {
2075+
fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
2076+
self.0.0.traverse(tracer_fn);
2077+
}
2078+
2079+
fn clear(&mut self, out: &mut Vec<PyObjectRef>) {
2080+
let base = &mut self.0.0;
2081+
if let Some(traceback) = base.traceback.get_mut().take() {
2082+
out.push(traceback.into());
2083+
}
2084+
2085+
if let Some(cause) = base.cause.get_mut().take() {
2086+
out.push(cause.into());
2087+
}
2088+
2089+
if let Some(context) = base.context.get_mut().take() {
2090+
out.push(context.into());
2091+
}
2092+
}
2093+
}
2094+
20212095
#[pyexception(name, base = PyException, ctx = "name_error")]
20222096
#[derive(Debug)]
20232097
#[repr(transparent)]

‎crates/vm/src/function/buffer.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ impl ArgBytesLike {
6666
}
6767
let mut copy = Vec::new();
6868
copy.try_reserve_exact(borrowed.len())
69-
.map_err(|_| vm.new_memory_error(""))?;
69+
.map_err(|_| vm.no_memory_error())?;
7070
copy.extend_from_slice(&borrowed);
7171
Ok(UnlockedBuf::Copied(copy))
7272
}

0 commit comments

Comments
 (0)