@@ -24,6 +24,7 @@ pub(crate) mod proto_gen {
2424 include ! ( concat!( env!( "OUT_DIR" ) , "/datafusion_java.rs" ) ) ;
2525}
2626
27+ use std:: panic:: { catch_unwind, AssertUnwindSafe } ;
2728use std:: path:: PathBuf ;
2829use std:: sync:: { Arc , OnceLock } ;
2930
@@ -170,9 +171,27 @@ impl Iterator for StreamingReader {
170171 type Item = Result < RecordBatch , ArrowError > ;
171172
172173 fn next ( & mut self ) -> Option < Self :: Item > {
173- runtime ( )
174- . block_on ( self . stream . next ( ) )
175- . map ( |r| r. map_err ( |e| ArrowError :: ExternalError ( Box :: new ( e) ) ) )
174+ // Arrow's C ABI invokes this iterator through FFI_ArrowArrayStream's
175+ // vtable, outside the JNI handler's try_unwrap_or_throw guard. A panic
176+ // here (buggy UDF, arrow cast that panics, runtime poison) would
177+ // unwind across C/FFI -- undefined behaviour. Catch it and surface as
178+ // an ArrowError so the Java side sees a normal exception instead.
179+ let next = catch_unwind ( AssertUnwindSafe ( || runtime ( ) . block_on ( self . stream . next ( ) ) ) ) ;
180+ match next {
181+ Ok ( item) => item. map ( |r| r. map_err ( |e| ArrowError :: ExternalError ( Box :: new ( e) ) ) ) ,
182+ Err ( panic) => {
183+ let msg = if let Some ( s) = panic. downcast_ref :: < String > ( ) {
184+ s. clone ( )
185+ } else if let Some ( s) = panic. downcast_ref :: < & str > ( ) {
186+ ( * s) . to_string ( )
187+ } else {
188+ "rust panic with non-string payload" . to_string ( )
189+ } ;
190+ Some ( Err ( ArrowError :: ExternalError (
191+ format ! ( "panic in DataFrame stream: {msg}" ) . into ( ) ,
192+ ) ) )
193+ }
194+ }
176195 }
177196}
178197
0 commit comments