@@ -47,14 +47,18 @@ impl WorkloadLauncher {
4747 let ( result_tx, result_rx) = mpsc:: sync_channel ( 1 ) ;
4848 self . jobs
4949 . send ( Box :: new ( move || {
50- let _ = result_tx. send ( operation ( ) ) ;
50+ let mut reply = PanicReply ( Some ( result_tx) ) ;
51+ let result = operation ( ) ;
52+ if let Some ( tx) = reply. 0 . take ( ) {
53+ let _ = tx. send ( Ok ( result) ) ;
54+ }
5155 } ) )
5256 . map_err ( |_| io:: Error :: new ( io:: ErrorKind :: BrokenPipe , "workload launcher stopped" ) ) ?;
53- result_rx. recv ( ) . map_err ( |_| {
54- io:: Error :: new (
57+ result_rx. recv ( ) . unwrap_or_else ( |_| {
58+ Err ( io:: Error :: new (
5559 io:: ErrorKind :: BrokenPipe ,
56- "workload launcher dropped the spawn result " ,
57- )
60+ "workload launcher stopped before running the job " ,
61+ ) )
5862 } )
5963 }
6064
@@ -92,7 +96,47 @@ pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> {
9296 }
9397 }
9498 while let Ok ( job) = jobs_rx. recv ( ) {
95- job ( ) ;
99+ // Contain a job panic the way the network broker contains a
100+ // handler panic. The launcher thread owns the inherited
101+ // listener filter, and its state past a mid-job panic is not
102+ // known-good, so stop accepting work: the health flag turns
103+ // false and every later spawn fails fast instead of hanging
104+ // on a launcher that reports healthy.
105+ if let Err ( panic) = std:: panic:: catch_unwind ( std:: panic:: AssertUnwindSafe ( job) ) {
106+ // Flip the health flag before reporting the panic, so
107+ // every later spawn fails fast even if the reporting
108+ // below were to go wrong.
109+ thread_alive. store ( false , Ordering :: Release ) ;
110+ tracing:: error!( "workload launcher job panicked: {}" , panic_message( & * panic) ) ;
111+ // A dead launcher means no new workload process can ever
112+ // start in this sandbox, which operators must be able to
113+ // see in structured logs, not only in tracing output.
114+ openshell_ocsf:: ocsf_emit!(
115+ openshell_ocsf:: DetectionFindingBuilder :: new(
116+ openshell_ocsf:: ctx:: ctx( )
117+ )
118+ . activity( openshell_ocsf:: ActivityId :: Open )
119+ . severity( openshell_ocsf:: SeverityId :: Medium )
120+ . confidence( openshell_ocsf:: ConfidenceId :: High )
121+ . is_alert( true )
122+ . finding_info(
123+ openshell_ocsf:: FindingInfo :: new(
124+ "workload-launcher-unavailable" ,
125+ "Workload Launcher Unavailable" ,
126+ )
127+ . with_desc( & format!(
128+ "The workload launcher thread stopped after a \
129+ job panicked ({}), so no new workload process \
130+ can start in this sandbox. Every later spawn \
131+ fails fast instead of hanging.",
132+ panic_message( & * panic) ,
133+ ) ) ,
134+ )
135+ . message( "workload launcher job panicked; no new workload processes can start" )
136+ . build( )
137+ ) ;
138+ break ;
139+ }
96140 }
97141 thread_alive. store ( false , Ordering :: Release ) ;
98142 } )
@@ -113,21 +157,53 @@ pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> {
113157 ) )
114158}
115159
160+ /// Render a caught panic payload for a log message.
161+ fn panic_message ( panic : & ( dyn std:: any:: Any + Send ) ) -> String {
162+ panic
163+ . downcast_ref :: < String > ( )
164+ . map ( String :: as_str)
165+ . or_else ( || panic. downcast_ref :: < & ' static str > ( ) . copied ( ) )
166+ . unwrap_or ( "non-string panic payload" )
167+ . to_string ( )
168+ }
169+
170+ /// Reply channel guard for one launcher job.
171+ ///
172+ /// If the operation panics, the reply sender is dropped while unwinding. The
173+ /// guard turns that into a precise error for the waiting caller instead of a
174+ /// bare closed-channel recv, which cannot distinguish a panic from any other
175+ /// teardown. The normal path takes the sender out first, so the guard sends
176+ /// exactly once either way.
177+ struct PanicReply < T > ( Option < mpsc:: SyncSender < io:: Result < T > > > ) ;
178+
179+ impl < T > Drop for PanicReply < T > {
180+ fn drop ( & mut self ) {
181+ if let Some ( tx) = self . 0 . take ( ) {
182+ let _ = tx. send ( Err ( io:: Error :: new (
183+ io:: ErrorKind :: BrokenPipe ,
184+ "workload launcher job panicked before returning a result" ,
185+ ) ) ) ;
186+ }
187+ }
188+ }
189+
116190#[ cfg( test) ]
117191#[ allow( unsafe_code) ]
118192mod tests {
119193 use std:: mem:: size_of;
120194 use std:: os:: fd:: AsRawFd as _;
195+ use std:: process:: Command ;
121196
122197 use super :: * ;
198+ use tracing_subscriber:: layer:: SubscriberExt as _;
123199
124200 #[ test]
125201 fn one_listener_mediates_launcher_and_inherited_child ( ) {
126202 let ( launcher, listener) = start ( ) . expect ( "start launcher" ) ;
127203 let executable = std:: env:: current_exe ( ) . expect ( "test executable" ) ;
128204 let mut child = launcher
129205 . execute ( move || {
130- let mut command = std :: process :: Command :: new ( executable) ;
206+ let mut command = Command :: new ( executable) ;
131207 command
132208 . arg ( "--exact" )
133209 . arg ( "linux::workload_launcher::tests::inherited_listener_child" )
@@ -173,6 +249,124 @@ mod tests {
173249 assert ! ( listener. as_raw_fd( ) >= 0 ) ;
174250 }
175251
252+ #[ test]
253+ fn panicking_job_marks_the_launcher_unhealthy ( ) {
254+ const HELPER_ENV : & str = "OPENSHELL_LAUNCHER_PANIC_TEST_HELPER" ;
255+ if std:: env:: var_os ( HELPER_ENV ) . is_none ( ) {
256+ // The panic hook's backtrace symbolization opens files on the
257+ // launcher thread, whose user-notify filter traps opens. Nothing
258+ // services that listener here, so run with backtraces off; the
259+ // parent environment must not leak RUST_BACKTRACE=1 into the
260+ // child.
261+ let output = Command :: new ( std:: env:: current_exe ( ) . unwrap ( ) )
262+ . args ( [
263+ "--exact" ,
264+ "linux::workload_launcher::tests::panicking_job_marks_the_launcher_unhealthy" ,
265+ "--nocapture" ,
266+ ] )
267+ . env ( HELPER_ENV , "1" )
268+ . env ( "RUST_BACKTRACE" , "0" )
269+ . output ( )
270+ . expect ( "start isolated launcher panic test" ) ;
271+ assert ! (
272+ output. status. success( ) ,
273+ "launcher panic test failed: {}" ,
274+ String :: from_utf8_lossy( & output. stderr)
275+ ) ;
276+ return ;
277+ }
278+
279+ let ( launcher, _listener) = start ( ) . expect ( "start launcher" ) ;
280+ assert ! ( launcher. is_alive( ) ) ;
281+
282+ // The launcher thread emits the structured finding, so capture needs a
283+ // process-global subscriber; this helper process runs one test only.
284+ let capture = openshell_ocsf:: test_support:: OcsfCapture :: default ( ) ;
285+ tracing:: subscriber:: set_global_default (
286+ tracing_subscriber:: registry ( ) . with ( capture. clone ( ) ) ,
287+ )
288+ . expect ( "install global capture subscriber" ) ;
289+
290+ let failure = launcher
291+ . execute ( || panic ! ( "launcher job failed" ) )
292+ . expect_err ( "a panicking job must fail its caller, not hang it" ) ;
293+ assert_eq ! ( failure. kind( ) , io:: ErrorKind :: BrokenPipe ) ;
294+ assert ! (
295+ failure. to_string( ) . contains( "panicked" ) ,
296+ "the panicked job's error must say the job panicked: {failure}"
297+ ) ;
298+
299+ // The health flag flips when the launcher thread leaves its job loop,
300+ // after the caller has already observed the failure.
301+ let deadline = std:: time:: Instant :: now ( ) + std:: time:: Duration :: from_secs ( 5 ) ;
302+ while launcher. is_alive ( ) {
303+ assert ! (
304+ std:: time:: Instant :: now( ) < deadline,
305+ "the launcher never reported the job panic"
306+ ) ;
307+ thread:: sleep ( std:: time:: Duration :: from_millis ( 10 ) ) ;
308+ }
309+
310+ // The health flag flips before the finding is reported, so wait for
311+ // the capture itself with the same bounded poll.
312+ let events = {
313+ let deadline = std:: time:: Instant :: now ( ) + std:: time:: Duration :: from_secs ( 5 ) ;
314+ loop {
315+ let events = capture. json_events ( ) ;
316+ if !events. is_empty ( ) {
317+ break events;
318+ }
319+ assert ! (
320+ std:: time:: Instant :: now( ) < deadline,
321+ "the launcher never reported its structured finding"
322+ ) ;
323+ thread:: sleep ( std:: time:: Duration :: from_millis ( 10 ) ) ;
324+ }
325+ } ;
326+ assert_eq ! (
327+ events. len( ) ,
328+ 1 ,
329+ "the dead launcher must emit one structured finding: {events:?}"
330+ ) ;
331+ assert_eq ! (
332+ events[ 0 ] [ "finding_info" ] [ "uid" ] ,
333+ "workload-launcher-unavailable"
334+ ) ;
335+ assert_eq ! ( events[ 0 ] [ "severity_id" ] , 3 ) ;
336+ assert_eq ! ( events[ 0 ] [ "is_alert" ] . as_bool( ) , Some ( true ) ) ;
337+ assert ! (
338+ events[ 0 ] [ "message" ]
339+ . as_str( )
340+ . is_some_and( |message| message. contains( "panicked" ) ) ,
341+ "finding message: {events:?}"
342+ ) ;
343+
344+ let failure = launcher
345+ . execute ( || ( ) )
346+ . expect_err ( "the launcher must refuse work after a job panic" ) ;
347+ assert_eq ! ( failure. kind( ) , io:: ErrorKind :: BrokenPipe ) ;
348+ assert ! (
349+ failure. to_string( ) . contains( "not running" ) ,
350+ "unexpected refusal error: {failure}"
351+ ) ;
352+ }
353+
354+ #[ test]
355+ fn panic_message_renders_every_payload_shape ( ) {
356+ #[ derive( Debug ) ]
357+ struct CustomPayload ;
358+
359+ // A job that panics through a format argument carries a String payload.
360+ let formatted = "job failed after 3 attempts" . to_string ( ) ;
361+ assert_eq ! ( panic_message( & formatted) , "job failed after 3 attempts" ) ;
362+
363+ // `panic!` with a literal carries a &'static str payload.
364+ assert_eq ! ( panic_message( & "literal panic" ) , "literal panic" ) ;
365+
366+ // Any other payload type falls back to the placeholder.
367+ assert_eq ! ( panic_message( & CustomPayload ) , "non-string panic payload" ) ;
368+ }
369+
176370 #[ test]
177371 fn inherited_listener_child ( ) {
178372 if std:: env:: var_os ( "OPENSHELL_WORKLOAD_LAUNCHER_CHILD" ) . is_none ( ) {
0 commit comments