Skip to content

Commit 721d573

Browse files
committed
Align shutdown flush and unraisable reporting with CPython
Share the fallible default writer, retain the selected output stream across callbacks, and keep user hooks available during finalization. Flush after exit callbacks and propagate either stream failure to exit status 120. Assisted-by: OpenAI Codex:model version not exposed
1 parent e288ec6 commit 721d573

5 files changed

Lines changed: 135 additions & 175 deletions

File tree

‎crates/vm/src/exceptions.rs‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -194,12 +194,7 @@ impl VirtualMachine {
194194
/// Display `exc` through `traceback._print_exception_bltin`, falling back
195195
/// to the native printer writing to `file`.
196196
pub(crate) fn display_exception_to(&self, file: &PyObject, exc: &Py<PyBaseException>) {
197-
if let Ok(print_exception) = self
198-
.import("traceback", 0)
199-
.and_then(|traceback| traceback.get_attr("_print_exception_bltin", self))
200-
&& print_exception.is_callable()
201-
&& print_exception.call((exc.to_owned(),), self).is_ok()
202-
{
197+
if self.try_display_exception_to(file, exc.as_object()) {
203198
return;
204199
}
205200
if self
@@ -212,6 +207,19 @@ impl VirtualMachine {
212207
let _ = self.call_method(file, "flush", ());
213208
}
214209

210+
/// Try the shared Python formatter with the caller's retained output file.
211+
/// Reporting paths provide their own native fallback if it is unavailable.
212+
pub(crate) fn try_display_exception_to(&self, file: &PyObject, exc: &PyObject) -> bool {
213+
self.import("traceback", 0)
214+
.and_then(|traceback| traceback.get_attr("_print_exception_bltin", self))
215+
.is_ok_and(|print_exception| {
216+
print_exception.is_callable()
217+
&& print_exception
218+
.call((exc.to_owned(), file.to_owned()), self)
219+
.is_ok()
220+
})
221+
}
222+
215223
pub fn write_exception<W: Write>(
216224
&self,
217225
output: &mut W,

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

Lines changed: 62 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ pub mod sys {
4545
},
4646
convert::ToPyObject,
4747
frame::FrameObjectRef,
48-
function::{FuncArgs, KwArgs, OptionalArg, PosArgs},
48+
function::{FuncArgs, OptionalArg, PosArgs},
4949
stdlib::_warnings::warn,
5050
types::PyStructSequence,
5151
version,
@@ -1314,110 +1314,100 @@ pub mod sys {
13141314
Ok(PyWindowsVersion::from_data(winver, vm))
13151315
}
13161316

1317-
fn _unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) -> PyResult<()> {
1318-
use super::PyStderr;
1317+
/// Shared by sys.__unraisablehook__ and the fallback when a user hook fails.
1318+
/// Only the outer unraisable dispatcher discards reporting failures.
1319+
pub(crate) fn write_unraisable(
1320+
unraisable: UnraisableHookArgsData,
1321+
vm: &VirtualMachine,
1322+
) -> PyResult<()> {
1323+
let Some(file) = vm.sys_module.dict().get_item_opt("stderr", vm)? else {
1324+
return Ok(());
1325+
};
1326+
if vm.is_none(&file) {
1327+
return Ok(());
1328+
}
1329+
let write = |value: PyObjectRef| vm.call_method(&file, "write", (value,)).map(drop);
1330+
let text = |value: &str| write(vm.ctx.new_str(value).into());
13191331

1320-
let stderr = PyStderr(vm);
13211332
if !vm.is_none(&unraisable.object) {
13221333
if !vm.is_none(&unraisable.err_msg) {
1323-
write!(stderr, "{}: ", unraisable.err_msg.str(vm)?);
1334+
write(unraisable.err_msg.str(vm)?.into())?;
1335+
text(": ")?;
13241336
} else {
1325-
write!(stderr, "Exception ignored in: ");
1337+
text("Exception ignored in: ")?;
13261338
}
1327-
// exception in del will be ignored but printed
1328-
let repr = &unraisable.object.repr(vm);
1329-
let str = match repr {
1330-
Ok(v) => v.to_string(),
1331-
Err(_) => format!(
1332-
"<object {} repr() failed>",
1333-
unraisable.object.class().name()
1334-
),
1335-
};
1336-
writeln!(stderr, "{str}");
1339+
if unraisable
1340+
.object
1341+
.repr(vm)
1342+
.and_then(|value| write(value.into()))
1343+
.is_err()
1344+
{
1345+
text("<object repr() failed>")?;
1346+
}
1347+
text("\n")?;
13371348
} else if !vm.is_none(&unraisable.err_msg) {
1338-
writeln!(stderr, "{}:", unraisable.err_msg.str(vm)?);
1349+
write(unraisable.err_msg.str(vm)?.into())?;
1350+
text(":\n")?;
13391351
}
13401352

1341-
// Print traceback (using actual exc_traceback, not current stack)
1342-
if !vm.is_none(&unraisable.exc_traceback) {
1343-
let tb_module = vm.import("traceback", 0)?;
1344-
let print_tb = tb_module.get_attr("print_tb", vm)?;
1345-
let stderr_obj = super::get_stderr(vm)?;
1346-
let kwargs: KwArgs = core::iter::once(("file".to_string(), stderr_obj)).collect();
1347-
let _ = print_tb.call(
1348-
FuncArgs::new(vec![unraisable.exc_traceback.clone()], kwargs),
1349-
vm,
1350-
);
1353+
if vm.try_display_exception_to(&file, &unraisable.exc_value) {
1354+
return Ok(());
13511355
}
13521356

1353-
// Check exc_type
1354-
if vm.is_none(unraisable.exc_type.as_object()) {
1355-
return Ok(());
1357+
// Imports can fail during teardown. Keep a native fallback, and keep
1358+
// printing the exception even if writing its traceback fails.
1359+
if let Ok(traceback) = unraisable
1360+
.exc_traceback
1361+
.downcast::<crate::builtins::PyTraceback>()
1362+
{
1363+
let mut writer = crate::py_io::PyWriter(file.clone(), vm);
1364+
let _ = crate::exceptions::write_traceback(&mut writer, &traceback);
13561365
}
1357-
assert!(
1358-
unraisable
1359-
.exc_type
1360-
.fast_issubclass(vm.ctx.exceptions.base_exception_type)
1361-
);
1362-
1363-
// Print module name (if not builtins or __main__).
1364-
// A failed lookup or a non-str `__module__` is discarded: print
1365-
// `<unknown>` with no trailing `.`, then the qualname.
1366-
let module_name = unraisable.exc_type.__module__(vm).ok();
1366+
1367+
let module_name = unraisable
1368+
.exc_type
1369+
.as_object()
1370+
.get_attr("__module__", vm)
1371+
.ok();
13671372
if let Some(module_str) = module_name
13681373
.as_ref()
13691374
.and_then(|name| name.downcast_ref::<PyStr>())
13701375
{
13711376
let module = module_str.as_wtf8();
13721377
if module != "builtins" && module != "__main__" {
1373-
write!(stderr, "{module}.");
1378+
write(module_str.to_owned().into())?;
1379+
text(".")?;
13741380
}
13751381
} else {
1376-
write!(stderr, "<unknown>");
1382+
text("<unknown>")?;
13771383
}
13781384

1379-
// Print qualname
13801385
let qualname = unraisable.exc_type.__qualname__(vm);
13811386
if let Ok(qualname_str) = qualname.downcast::<PyStr>() {
1382-
write!(stderr, "{}", qualname_str.as_wtf8());
1387+
write(qualname_str.into())?;
13831388
} else {
1384-
write!(stderr, "{}", unraisable.exc_type.name());
1389+
text("<unknown>")?;
13851390
}
13861391

1387-
// Print exception value
13881392
if !vm.is_none(&unraisable.exc_value) {
1389-
write!(stderr, ": ");
1390-
if let Ok(str) = unraisable.exc_value.str(vm) {
1391-
write!(stderr, "{}", str.as_wtf8());
1392-
} else {
1393-
write!(stderr, "<exception str() failed>");
1393+
text(": ")?;
1394+
if unraisable
1395+
.exc_value
1396+
.str(vm)
1397+
.and_then(|value| write(value.into()))
1398+
.is_err()
1399+
{
1400+
text("<exception str() failed>")?;
13941401
}
13951402
}
1396-
writeln!(stderr);
1397-
1398-
// Flush stderr
1399-
if let Ok(stderr_obj) = super::get_stderr(vm)
1400-
&& let Ok(flush) = stderr_obj.get_attr("flush", vm)
1401-
{
1402-
let _ = flush.call((), vm);
1403-
}
1404-
1405-
Ok(())
1403+
text("\n")?;
1404+
vm.call_method(&file, "flush", ()).map(drop)
14061405
}
14071406

14081407
#[pyattr]
14091408
#[pyfunction(name = "__unraisablehook__")]
1410-
fn unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) {
1411-
if let Err(e) = _unraisablehook(unraisable, vm) {
1412-
let stderr = super::PyStderr(vm);
1413-
writeln!(
1414-
stderr,
1415-
"{}",
1416-
e.as_object()
1417-
.repr(vm)
1418-
.unwrap_or_else(|_| vm.ctx.empty_str.to_owned())
1419-
);
1420-
}
1409+
fn unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) -> PyResult<()> {
1410+
write_unraisable(unraisable, vm)
14211411
}
14221412

14231413
#[pyattr]

‎crates/vm/src/vm/interpreter.rs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -724,11 +724,11 @@ impl Interpreter {
724724
/// Finalize vm and turns an exception to exit code.
725725
///
726726
/// Finalization steps (matching Py_FinalizeEx):
727-
/// 1. Flush stdout and stderr.
728727
/// 1. Handle exit exception and turn it to exit code.
729728
/// 1. Call threading._shutdown() to join non-daemon threads.
730729
/// 1. Run atexit exit functions.
731730
/// 1. Set finalizing flag and hang remaining daemon threads.
731+
/// 1. Flush stdout and stderr.
732732
/// 1. Forced GC collection pass (collect cycles while builtins are available).
733733
/// 1. Module finalization (finalize_modules).
734734
/// 1. Clear interpreter-owned cross-interpreter data.
@@ -748,13 +748,11 @@ impl Interpreter {
748748

749749
fn finalize_inner(self, exit_code: impl FnOnce(&VirtualMachine) -> u32) -> u32 {
750750
self.enter(|vm| {
751-
let flush_status = vm.flush_std();
752-
753751
// See if any exception leaked out:
754752
let exit_code = exit_code(vm);
755753

756-
// Match CPython: if exit_code is 0 and stdout flush failed, exit 120
757-
if vm.finalize_ex(flush_status) < 0 && exit_code == 0 {
754+
// A failed shutdown flush overrides even an explicit nonzero exit code.
755+
if vm.finalize_ex() < 0 {
758756
EXITCODE_FLUSH_FAILURE
759757
} else {
760758
exit_code
@@ -771,17 +769,17 @@ impl VirtualMachine {
771769
if self.state.thread_is_running_main() {
772770
self.state.set_not_running_main();
773771
}
774-
let status = if self.finalize_ex(self.flush_std()) < 0 {
772+
let status = if self.finalize_ex() < 0 {
775773
EXITCODE_FLUSH_FAILURE
776774
} else {
777775
status
778776
};
779777
crate::host_env::os::exit(status as i32)
780778
}
781779

782-
/// The steps of Py_FinalizeEx after the first flush of stdout and stderr.
780+
/// The steps of Py_FinalizeEx.
783781
/// Return a negative value if any flush failed.
784-
fn finalize_ex(&self, mut flush_status: i32) -> i32 {
782+
fn finalize_ex(&self) -> i32 {
785783
let vm = self;
786784
// Wait for thread shutdown - call threading._shutdown() if available.
787785
// This waits for all non-daemon threads to complete.
@@ -835,6 +833,10 @@ impl VirtualMachine {
835833
vm.state.finalizing.store(true, Ordering::Release);
836834
}
837835

836+
// Exit callbacks have finished, but modules and the user unraisable
837+
// hook are still available to report a failed stream flush.
838+
let mut flush_status = vm.flush_std();
839+
838840
// GC pass - collect cycles before module cleanup
839841
vm.state.gc.collect_force(2);
840842

0 commit comments

Comments
 (0)