Repository navigation
Support owned exception payload construction #9734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
youknowone
merged 7 commits into
RustPython:main
from
JMLX42:feat/owned-exception-payloads
Nov 10, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
158f64b
Support owned exception payload construction
JMLX42 42bf66f
Keep native exception regression payload alignment portable
JMLX42 bc3744e
Isolate exception cycle collection from parallel interpreter fixtures
JMLX42 318a448
Retry CI after transient GitHub advisory lookup failure
JMLX42 dbd03c6
Clear exception references and limit owned wrapper construction
youknowone 5b7284a
Strengthen owned exception cycle regression evidence
JMLX42 fe88c60
Merge owned exception payload tests into one file
youknowone File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| #![cfg(test)] | ||
| #![cfg(all(feature = "compiler", feature = "gc"))] | ||
|
|
||
| extern crate alloc; | ||
|
|
||
| use alloc::sync::Arc; | ||
| use core::sync::atomic::{AtomicBool, Ordering}; | ||
| use rustpython_vm::{ | ||
| AsObject, Interpreter, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, | ||
| builtins::{PyBaseException, PyType, PyValueError}, | ||
| class::{PyClassImpl, PySubclass}, | ||
| function::FuncArgs, | ||
| object::{Traverse, TraverseFn}, | ||
| pyclass, | ||
| types::Constructor, | ||
| }; | ||
|
|
||
| static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); | ||
|
|
||
| #[pyclass(module = "exception_payload_test", name = "DropError", base = PyValueError, traverse = "manual")] | ||
| #[repr(C)] | ||
| #[derive(Debug)] | ||
| struct DropError { | ||
| base: PyValueError, | ||
| dropped: Arc<AtomicBool>, | ||
| } | ||
|
|
||
| // SAFETY: repr(C) keeps the valid base first; pyclass checks offset and alignment. | ||
| unsafe impl PySubclass for DropError { | ||
| type Base = PyValueError; | ||
|
|
||
| fn as_base(&self) -> &Self::Base { | ||
| &self.base | ||
| } | ||
| } | ||
|
|
||
| // SAFETY: The base owns every Python reference; the flag owns none. | ||
| unsafe impl Traverse for DropError { | ||
| fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { | ||
| self.base.traverse(tracer_fn); | ||
| } | ||
|
|
||
| fn clear(&mut self, out: &mut Vec<PyObjectRef>) { | ||
| self.base.clear(out); | ||
| } | ||
| } | ||
|
|
||
| #[pyclass(with(Constructor))] | ||
| impl DropError {} | ||
|
|
||
| impl Constructor for DropError { | ||
| type Args = FuncArgs; | ||
|
|
||
| fn py_new(cls: &Py<PyType>, args: FuncArgs, vm: &VirtualMachine) -> PyResult<Self> { | ||
| Ok(Self { | ||
| base: PyValueError::py_new(cls, args, vm)?, | ||
| dropped: Arc::new(AtomicBool::new(false)), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| impl Drop for DropError { | ||
| fn drop(&mut self) { | ||
| self.dropped.store(true, Ordering::SeqCst); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn owned_native_exception_round_trips_through_python() { | ||
| let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| Interpreter::without_stdlib(Default::default()).enter(|vm| { | ||
| let class = DropError::make_static_type(); | ||
| let argument = vm.ctx.new_str("payload"); | ||
| let payload = DropError::py_new(&class, vec![argument.clone().into()].into(), vm).unwrap(); | ||
| let dropped = payload.dropped.clone(); | ||
| let exception = payload.into_ref_with_type(vm, class).unwrap(); | ||
| let base = exception.as_base().as_base().as_base(); | ||
| assert!(base.__traceback__().is_none()); | ||
| assert!(base.__cause__().is_none()); | ||
| assert!(base.__context__().is_none()); | ||
| assert!( | ||
| !exception | ||
| .as_object() | ||
| .get_attr("__suppress_context__", vm) | ||
| .unwrap() | ||
| .try_to_bool(vm) | ||
| .unwrap() | ||
| ); | ||
| assert!(!dropped.load(Ordering::SeqCst)); | ||
|
|
||
| let scope = vm.new_scope_with_builtins(); | ||
| scope.globals.set_item("exc", exception.into(), vm).unwrap(); | ||
| scope.globals.set_item("arg", argument.into(), vm).unwrap(); | ||
| let source = r#" | ||
| try: | ||
| raise exc | ||
| except ValueError as e: | ||
| assert e.args == (arg,) | ||
| assert isinstance(e, ValueError) | ||
| caught = e | ||
| "#; | ||
| let code = vm | ||
| .compile( | ||
| source, | ||
| rustpython_vm::compiler::Mode::Exec, | ||
| "<native-exception>", | ||
| ) | ||
| .map_err(|error| error.into_pyexception(vm, Some(source))) | ||
| .unwrap(); | ||
| if let Err(error) = vm.run_code_obj(code, scope.clone()) { | ||
| vm.print_exception(&error); | ||
| panic!("owned native exception round-trip failed"); | ||
| } | ||
| let caught = scope.globals.get_item("caught", vm).unwrap(); | ||
| let native = caught.downcast::<DropError>().unwrap(); | ||
| assert!(Arc::ptr_eq(&native.dropped, &dropped)); | ||
| assert!(!native.dropped.load(Ordering::SeqCst)); | ||
| }); | ||
| } | ||
|
|
||
| #[test] | ||
| fn context_cycle_destroys_owned_exception_payload() { | ||
| let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); | ||
| Interpreter::without_stdlib(Default::default()).enter(|vm| { | ||
| let class = DropError::make_static_type(); | ||
| let payload = DropError::py_new(&class, FuncArgs::default(), vm).unwrap(); | ||
| let dropped = payload.dropped.clone(); | ||
| let exception = payload.into_ref_with_type(vm, class).unwrap(); | ||
| let base = exception.as_base().as_base().as_base(); | ||
| base.set_context(Some(exception.clone().upcast::<PyBaseException>())); | ||
| assert!(base.__context__().unwrap().is(exception.as_object())); | ||
| assert!(!dropped.load(Ordering::SeqCst)); | ||
| drop(exception); | ||
| assert!(!dropped.load(Ordering::SeqCst)); | ||
| vm.state.gc.collect_force(2); | ||
| assert!(dropped.load(Ordering::SeqCst)); | ||
| }); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.