Skip to content

Commit a4b8c53

Browse files
authored
misc fixes to unwinding (#1094)
1 parent 82a9abd commit a4b8c53

4 files changed

Lines changed: 164 additions & 17 deletions

File tree

‎crates/monty/src/bytecode/vm/exceptions.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -457,18 +457,15 @@ impl VM<'_> {
457457
}
458458
}
459459

460-
/// Unwinds the call stack to collect all frames for a traceback.
461-
///
462-
/// Used for terminal resource errors that can't be handled
463-
/// but still need a complete traceback showing all active call frames.
460+
/// Collects terminal-error traceback frames up to the next synchronous boundary.
461+
/// Native callers must release their borrows before their Python frames are unwound.
464462
fn unwind_for_traceback(&mut self, mut error: RunError) -> RunError {
465463
// Pop frames and add caller frame info to the traceback
466464
while !self.suspended_frames.is_empty() {
467465
// Get the caller's call-site offset before popping frame
468466
let call_offset = self.current_frame().call_offset;
469467

470-
// Pop this frame (cleans up namespace, etc.)
471-
self.pop_frame();
468+
let should_return = self.pop_frame();
472469

473470
// Add caller frame info to traceback. Resolve the offset against the
474471
// caller, which is the current frame after the pop above.
@@ -483,6 +480,9 @@ impl VM<'_> {
483480
RunError::Internal(_) => {}
484481
}
485482
}
483+
if should_return {
484+
break;
485+
}
486486
}
487487
error
488488
}

‎crates/monty/src/bytecode/vm/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1274,7 +1274,7 @@ impl<'h> VM<'h> {
12741274
countdown = c;
12751275
} else {
12761276
countdown = CHECK_INTERVAL;
1277-
self.dispatch_checkpoint(check_limits, poll_print)?;
1277+
try_catch!(self, self.dispatch_checkpoint(check_limits, poll_print));
12781278
}
12791279

12801280
// Track instruction IP for exception table lookup

‎crates/monty/tests/print_writer.rs‎

Lines changed: 105 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,111 @@
1-
//! Tests for `PrintWriter::CollectString` — the output capture mode used by
2-
//! hosts that need to intercept `print()` rather than pass it through to
3-
//! stdout.
4-
//!
5-
//! Expected output is asserted via [`insta::assert_snapshot!`] with inline
6-
//! snapshots — multi-line print output renders naturally in the snapshot
7-
//! literal, which is substantially clearer than an escaped `"a\nb\n"` string.
8-
//! To update after an intentional change, run `cargo insta review` (or set
9-
//! `INSTA_UPDATE=always`).
1+
//! Tests for captured print output and callback errors.
2+
3+
use std::{borrow::Cow, mem};
104

115
use insta::assert_snapshot;
126
use monty::MontyRun;
13-
use monty_types::{CollectedStreams, CompileOptions, PrintStream, PrintWriter, ResourceTracker};
7+
use monty_types::{
8+
CollectedStreams, CompileOptions, ExcType, MontyException, MontyObject, PrintStream, PrintWriter,
9+
PrintWriterCallback, ResourceTracker,
10+
};
11+
12+
/// Checkpoint errors must reach handlers inside a synchronously evaluated callback.
13+
#[test]
14+
fn checkpoint_error_caught_inside_synchronous_callback() {
15+
let code = r"
16+
seen = []
17+
18+
def key(value):
19+
try:
20+
print('arm')
21+
for _ in range(1000):
22+
pass
23+
except ValueError as exc:
24+
assert str(exc) == 'checkpoint failed'
25+
seen.append(value)
26+
return -value
27+
28+
def outer():
29+
result = sorted([1, 2], key=key)
30+
assert result == [2, 1]
31+
assert seen == [1]
32+
return 42
33+
34+
outer()
35+
";
36+
assert_eq!(run_with_checkpoint_failure(code), MontyObject::int(42));
37+
}
38+
39+
/// A checkpoint failure must unwind nested frames before a native caller returns to its outer handler.
40+
#[test]
41+
fn checkpoint_error_unwinds_synchronous_callback() {
42+
let code = r"
43+
def leaf(value):
44+
print('arm')
45+
for _ in range(1000):
46+
pass
47+
return value
48+
49+
def key(value):
50+
return sorted([value], key=leaf)[0]
51+
52+
def outer():
53+
kept = ['alive']
54+
try:
55+
sorted([1], key=key)
56+
assert False, 'expected checkpoint failure'
57+
except ValueError as exc:
58+
assert str(exc) == 'checkpoint failed'
59+
assert kept == ['alive']
60+
assert sorted([3, 1, 2], key=lambda value: -value) == [3, 2, 1]
61+
return 42
62+
63+
outer()
64+
";
65+
assert_eq!(run_with_checkpoint_failure(code), MontyObject::int(42));
66+
}
67+
68+
/// Arms a single failure from Python so setup cannot consume it before synchronous re-entry.
69+
fn run_with_checkpoint_failure(code: &str) -> MontyObject {
70+
let mut runner = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap();
71+
let mut writer = FailCheckpoint::default();
72+
let result = runner
73+
.run(vec![], ResourceTracker::default(), PrintWriter::Callback(&mut writer))
74+
.unwrap();
75+
assert_eq!(writer.failures, 1);
76+
result
77+
}
78+
79+
/// Fails the first flush poll after `print('arm')`, without relying on elapsed time.
80+
#[derive(Default)]
81+
struct FailCheckpoint {
82+
armed: bool,
83+
failures: usize,
84+
}
85+
86+
impl PrintWriterCallback for FailCheckpoint {
87+
fn stdout_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException> {
88+
assert_eq!(output, "arm");
89+
self.armed = self.failures == 0;
90+
Ok(())
91+
}
92+
93+
fn stdout_push(&mut self, _end: char) -> Result<(), MontyException> {
94+
Ok(())
95+
}
96+
97+
fn poll_flush(&mut self) -> Result<(), MontyException> {
98+
if mem::take(&mut self.armed) {
99+
self.failures += 1;
100+
Err(MontyException::new(
101+
ExcType::ValueError,
102+
Some("checkpoint failed".to_owned()),
103+
))
104+
} else {
105+
Ok(())
106+
}
107+
}
108+
}
14109

15110
/// Run `code` under Monty with a string-collecting `PrintWriter` and return
16111
/// whatever was printed. Panics on parse/runtime errors — callers only care

‎crates/monty/tests/resource_limits.rs‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,58 @@ use monty_types::{
1313
ResourceTracker,
1414
};
1515

16+
/// Terminal errors must cross each native caller before unwinding its Python frame.
17+
#[test]
18+
fn terminal_error_respects_synchronous_reentry_boundaries() {
19+
let code = "\
20+
def fail():
21+
return ''.ljust(width, 'é')
22+
23+
def middle():
24+
for value in iter(fail, None):
25+
pass
26+
27+
def outer():
28+
for value in iter(middle, None):
29+
pass
30+
31+
outer()
32+
";
33+
let mut runner = MontyRun::new(
34+
code.to_owned(),
35+
"test.py",
36+
vec!["width".to_owned()],
37+
CompileOptions::default(),
38+
)
39+
.unwrap();
40+
// Twice this width exceeds StringBuilder's capacity ceiling without attempting an allocation.
41+
let width = isize::MAX as usize / 2 + 1;
42+
let error = runner
43+
.run_no_limits(vec![MontyObject::int(i64::try_from(width).unwrap())])
44+
.expect_err("oversized padding must return a terminal MemoryError");
45+
assert_eq!(error.exc_type(), ExcType::MemoryError);
46+
let message = error
47+
.message()
48+
.unwrap()
49+
.replace(&(width * 2).to_string(), "<requested>")
50+
.replace(&isize::MAX.to_string(), "<limit>");
51+
insta::assert_snapshot!(message, @"memory limit exceeded: <requested> bytes > <limit> bytes");
52+
let frames: Vec<_> = error
53+
.traceback()
54+
.iter()
55+
.map(|frame| (frame.frame_name.as_deref(), frame.start.line))
56+
.collect();
57+
assert_eq!(
58+
frames,
59+
vec![
60+
(Some("<module>"), 12),
61+
(Some("outer"), 9),
62+
(Some("middle"), 5),
63+
(Some("fail"), 2)
64+
]
65+
);
66+
}
67+
1668
/// Resolves consecutive `NameLookup` yields by providing a `Function` object for each name.
1769
///
1870
/// External functions are no longer declared upfront. Instead, the VM yields `NameLookup`

0 commit comments

Comments
 (0)