From a3fff8525ec5eb1ceb170e204fbf7b90281ca1ac Mon Sep 17 00:00:00 2001 From: ajaysehwal Date: Tue, 24 Nov 2026 21:37:45 +0530 Subject: [PATCH 1/2] 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] From 14c6059134f5c205b7a2d2d029b0d2349fd7f446 Mon Sep 17 00:00:00 2001 From: ajaysehwal Date: Sat, 28 Nov 2026 12:06:12 +0530 Subject: [PATCH 2/2] Keep watching the chain when background processing fails Previously a failed background processor stopped all background tasks, including chain syncing and transaction broadcasting, so the node no longer reacted to the chain until restarted. Only cut off peers instead, which is what keeps channel state from changing while the `ChannelManager` can't be persisted. To this end, `ConnectionManager` can now refuse connections at runtime, which also covers reconnects, LSP discovery and `Node::connect`, and the listener drops inbound connections while connections are disabled. --- src/connection.rs | 17 ++++++++++++++--- src/lib.rs | 12 +++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/connection.rs b/src/connection.rs index 70013cbb29..9eef8f7765 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -7,6 +7,7 @@ use std::collections::hash_map::{self, HashMap}; use std::ops::Deref; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -57,7 +58,7 @@ where { pending_connections: PendingConnections, peer_manager: Arc, - disable_lightning_connections: bool, + connections_disabled: AtomicBool, tor_proxy_config: Option, keys_manager: Arc, logger: L, @@ -76,7 +77,7 @@ where Self { pending_connections, peer_manager, - disable_lightning_connections, + connections_disabled: AtomicBool::new(disable_lightning_connections), tor_proxy_config, keys_manager, logger, @@ -93,6 +94,16 @@ where self.do_connect_peer(node_id, addr).await } + /// Refuses any further peer connections and disconnects all connected peers. + pub(crate) fn disable_connections(&self) { + self.connections_disabled.store(true, Ordering::Release); + self.peer_manager.disconnect_all_peers(); + } + + pub(crate) fn connections_disabled(&self) -> bool { + self.connections_disabled.load(Ordering::Acquire) + } + pub(crate) fn disconnect_peer(&self, node_id: PublicKey) { self.peer_manager.disconnect_by_node_id(node_id); } @@ -123,7 +134,7 @@ where async fn do_connect_peer_internal( &self, node_id: PublicKey, addr: SocketAddress, ) -> Result<(), Error> { - if self.disable_lightning_connections { + if self.connections_disabled() { log_warn!(self.logger, "Lightning peer connections are disabled."); return Err(Error::ConnectionFailed); } diff --git a/src/lib.rs b/src/lib.rs index bb2fc24b1e..fc40f1f60a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -551,6 +551,7 @@ impl Node { for listener in listeners { let logger = Arc::clone(&listening_logger); let peer_mgr = Arc::clone(&peer_manager_connection_handler); + let listen_cm = Arc::clone(&self.connection_manager); let mut stop_listen = self.stop_sender.subscribe(); let runtime = Arc::clone(&self.runtime); self.runtime.spawn_cancellable_background_task(async move { @@ -571,6 +572,9 @@ impl Node { continue; }, }; + if listen_cm.connections_disabled() { + continue; + } let peer_mgr = Arc::clone(&peer_mgr); let logger = Arc::clone(&logger); runtime.spawn_cancellable_background_task(async move { @@ -816,8 +820,7 @@ 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_failure_cm = Arc::clone(&self.connection_manager); let background_scorer = Arc::clone(&self.scorer); let stop_bp = self.background_processor_stop_sender.subscribe(); let sleeper_logger = Arc::clone(&self.logger); @@ -868,11 +871,10 @@ impl Node { if let Err(e) = &res { log_error!( background_error_logger, - "Background processing of events failed, halting node activity: {}", + "Background processing of events failed, disconnecting all peers: {}", e ); - let _ = background_failure_stop_sender.send(()); - background_failure_peer_man.disconnect_all_peers(); + background_failure_cm.disable_connections(); } res