From a3fff8525ec5eb1ceb170e204fbf7b90281ca1ac Mon Sep 17 00:00:00 2001 From: ajaysehwal Date: Tue, 24 Nov 2026 21:37:45 +0530 Subject: [PATCH] Don't panic when background event processing fails A failing background processor used to `panic!`, which aborted the host process or, for embedders that unwind, left a node that kept running without persisting anything. `Node::stop` then panicked again while holding the `is_running` write lock, poisoning it for all later calls. Have the background processor task return its result instead. On failure it now logs, signals the other background tasks to stop and disconnects all peers, so no further channel state changes happen. `wait_on_background_processor_task` reports a failed or panicked task as `Error::PersistenceFailed`, which `Node::stop` returns after marking the node as not running. --- src/lib.rs | 44 ++++++++++++++++++++++++++++----------- src/runtime.rs | 56 ++++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 77 insertions(+), 23 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ed8b35ff61..bb2fc24b1e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -318,7 +318,7 @@ impl Node { // Startup spawns background tasks before it can fail, e.g., when binding our // listening addresses. Wind them all back down rather than leaving them running // behind a node that never came up. - self.shutdown(); + let _ = self.shutdown(); Err(e) }, } @@ -816,6 +816,8 @@ impl Node { let background_onion_messenger = Arc::clone(&self.onion_messenger); let background_logger = Arc::clone(&self.logger); let background_error_logger = Arc::clone(&self.logger); + let background_failure_stop_sender = self.stop_sender.clone(); + let background_failure_peer_man = Arc::clone(&self.peer_manager); let background_scorer = Arc::clone(&self.scorer); let stop_bp = self.background_processor_stop_sender.subscribe(); let sleeper_logger = Arc::clone(&self.logger); @@ -839,7 +841,7 @@ impl Node { }; self.runtime.spawn_background_processor_task(async move { - process_events_async( + let res = process_events_async( background_persister, |e| background_event_handler.handle_event(e), background_chain_mon, @@ -861,11 +863,19 @@ impl Node { ) }, ) - .await - .unwrap_or_else(|e| { - log_error!(background_error_logger, "Failed to process events: {}", e); - panic!("Failed to process events"); - }); + .await; + + if let Err(e) = &res { + log_error!( + background_error_logger, + "Background processing of events failed, halting node activity: {}", + e + ); + let _ = background_failure_stop_sender.send(()); + background_failure_peer_man.disconnect_all_peers(); + } + + res }); let mut stop_liquidity_handler = self.stop_sender.subscribe(); @@ -968,6 +978,9 @@ impl Node { /// Disconnects all peers, stops all running background tasks, and shuts down [`Node`]. /// /// After this returns most API methods will return [`Error::NotRunning`]. + /// + /// Returns [`Error::PersistenceFailed`] if background event processing failed. The node is + /// shut down regardless. pub fn stop(&self) -> Result<(), Error> { let mut is_running_lock = self.is_running.write().expect("lock"); if !*is_running_lock { @@ -976,11 +989,16 @@ impl Node { log_info!(self.logger, "Shutting down LDK Node with node ID {}...", self.node_id()); - self.shutdown(); + let shutdown_res = self.shutdown(); - log_info!(self.logger, "Shutdown complete."); *is_running_lock = false; - Ok(()) + match shutdown_res { + Ok(()) => log_info!(self.logger, "Shutdown complete."), + Err(_) => { + log_error!(self.logger, "Shutdown complete, but background processing failed.") + }, + } + shutdown_res } /// Winds down everything [`Node::start_inner`] may have brought up. @@ -989,7 +1007,7 @@ impl Node { /// also used to clean up after a [`Node::start`] that failed part-way through, in which case /// some of the background tasks below were never spawned and the shutdown signals accordingly /// find no receivers. - fn shutdown(&self) { + fn shutdown(&self) -> Result<(), Error> { // Prevent blocking Electrum syncs from making any further callbacks before persistence // tasks stop accepting work. self.chain_source.begin_shutdown(); @@ -1021,10 +1039,12 @@ impl Node { } // Finally, wait until background processing stopped, at least until a timeout is reached. - self.runtime.wait_on_background_processor_task(); + let background_processor_res = self.runtime.wait_on_background_processor_task(); #[cfg(tokio_unstable)] self.runtime.log_metrics(); + + background_processor_res } /// Returns the status of the [`Node`]. diff --git a/src/runtime.rs b/src/runtime.rs index 8f9e94ccf3..289933618f 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -19,13 +19,14 @@ use tokio_util::task::TaskTracker; use crate::config::{ BACKGROUND_TASK_SHUTDOWN_TIMEOUT_SECS, LDK_EVENT_HANDLER_SHUTDOWN_TIMEOUT_SECS, }; +use crate::error::Error; use crate::logger::{log_debug, log_error, log_trace, LdkLogger, Logger}; pub(crate) struct Runtime { mode: RuntimeMode, background_tasks: Mutex>, cancellable_background_tasks: Mutex, - background_processor_task: Mutex>>, + background_processor_task: Mutex>>>, logger: Arc, } @@ -156,7 +157,7 @@ impl Runtime { pub fn spawn_background_processor_task(&self, future: F) where - F: Future + Send + 'static, + F: Future> + Send + 'static, { let mut background_processor_task = self.background_processor_task.lock().expect("lock"); debug_assert!(background_processor_task.is_none(), "Expected no background processor_task"); @@ -238,7 +239,9 @@ impl Runtime { /// /// Note this may find no task at all, as it's also reached when winding down a startup that /// failed before spawning it. - pub fn wait_on_background_processor_task(&self) { + /// + /// Returns [`Error::PersistenceFailed`] if the task failed or panicked. + pub fn wait_on_background_processor_task(&self) -> Result<(), Error> { if let Some(background_processor_task) = self.background_processor_task.lock().expect("lock").take() { @@ -256,17 +259,17 @@ impl Runtime { match timeout_res { Ok(stop_res) => match stop_res { - Ok(()) => { + Ok(Ok(())) => { log_debug!(self.logger, "Stopped background processing of events."); }, + Ok(Err(e)) => { + log_error!(self.logger, "Background processing of events failed: {}", e); + return Err(Error::PersistenceFailed); + }, Err(e) => { abort_handle.abort(); - log_error!( - self.logger, - "Stopping event handling failed. This should never happen: {}", - e - ); - panic!("Stopping event handling failed. This should never happen."); + log_error!(self.logger, "Background processing of events panicked: {}", e); + return Err(Error::PersistenceFailed); }, }, Err(e) => { @@ -275,6 +278,7 @@ impl Runtime { }, } } + Ok(()) } #[cfg(tokio_unstable)] @@ -474,7 +478,37 @@ mod tests { let runtime = test_runtime(); runtime.abort_cancellable_background_tasks(); runtime.wait_on_background_tasks(); - runtime.wait_on_background_processor_task(); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_success_is_reported_as_ok() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { Ok(()) }); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_error_is_returned_instead_of_panicking() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { + Err(lightning::io::Error::new(lightning::io::ErrorKind::Other, "persist failed")) + }); + assert!(matches!( + runtime.wait_on_background_processor_task(), + Err(Error::PersistenceFailed) + )); + assert!(runtime.wait_on_background_processor_task().is_ok()); + } + + #[test] + fn background_processor_panic_is_returned_instead_of_propagated() { + let runtime = test_runtime(); + runtime.spawn_background_processor_task(async { panic!("background processor panicked") }); + assert!(matches!( + runtime.wait_on_background_processor_task(), + Err(Error::PersistenceFailed) + )); } #[test]