From 416f5720ef648cf908fe60c1e44af6e6ff7c34e6 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 01:11:36 +0100 Subject: [PATCH 1/3] chore: bump ldk-node to 0.7.0-rc.82 Retries the recovery start while the build fails on a VSS store still busy with the stopped node's writes, and skips it once a stop was requested. Verified: unit suite (CI selection) on an iPhone 17 Pro simulator, iOS 26.5, with bitkit-ios#1519 applied locally; simulator run of node start, two restarts and a failed Electrum change recovering. --- Bitkit.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/swiftpm/Package.resolved | 4 +- Bitkit/Services/LightningService.swift | 60 ++++++++++++++++--- BitkitTests/LightningServiceTests.swift | 60 +++++++++++++++++++ changelog.d/next/1520.fixed.md | 1 + 5 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 changelog.d/next/1520.fixed.md diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index df9571d4a..7dbe440ca 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1295,7 +1295,7 @@ repositoryURL = "https://github.com/synonymdev/ldk-node"; requirement = { kind = exactVersion; - version = "0.7.0-rc.81"; + version = "0.7.0-rc.82"; }; }; 96DEA0382DE8BBA1009932BF /* XCRemoteSwiftPackageReference "bitkit-core" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 879f7e42c..b4553c9dd 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/ldk-node", "state" : { - "revision" : "366d56ef3c735406146ed12a34aba291776d29f6", - "version" : "0.7.0-rc.81" + "revision" : "1dd2f42e44561ee4005f109c0d2cb61e1de99123", + "version" : "0.7.0-rc.82" } }, { diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 9b6158e9a..092e1e5ae 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -158,6 +158,10 @@ class LightningService: NodeLifecycleService { private let restartLock = NSLock() private var lastRestart: Task? + /// Counts the stops callers asked for, so a recovery start can tell that one came in after it began. + private var requestedStops = 0 + /// Recovery starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s for them. + static let recoveryStartAttempts = 5 private let eventLoopLock = NSLock() /// The current event loop and the node it serves, so only that node's lifecycle can cancel it. @@ -435,13 +439,14 @@ class LightningService: NodeLifecycleService { // Stop the current node if it exists, ignore errors if already stopped if let node { do { - try await stop() + try await stopNode() } catch { Logger.debug("Node was already stopped or failed to stop: \(error)") // Clear the node reference anyway await releaseAfterFailedStop(of: node) } } + let stopsBefore = restartLock.withLock { requestedStops } // Restart the node with the current configuration do { @@ -453,7 +458,7 @@ class LightningService: NodeLifecycleService { // Attempt to restart with previous config // If recovery fails, log it but still throw the original error do { - try await restartWithPreviousConfig() + try await restartWithPreviousConfig(stopsBefore: stopsBefore) } catch { Logger.error("Recovery attempt also failed: \(error)") } @@ -464,13 +469,13 @@ class LightningService: NodeLifecycleService { /// Restarts the node with the previous stored configuration (recovery method) /// This is called when a config change fails to restore the node to a working state - private func restartWithPreviousConfig() async throws { + private func restartWithPreviousConfig(stopsBefore: Int) async throws { Logger.debug("Stopping node for recovery attempt") // Stop the current node if it exists if let node { do { - try await stop() + try await stopNode() } catch { Logger.error("Failed to stop node during recovery: \(error)") await releaseAfterFailedStop(of: node) @@ -480,9 +485,12 @@ class LightningService: NodeLifecycleService { Logger.debug("Starting node with previous config for recovery") do { - // Restart with nil URLs to use stored/default configuration - try await setup(walletIndex: currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil) - try await start() + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + try await Self.startRetryingBusyStore(stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } }) { + // Restart with nil URLs to use stored/default configuration + try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: nil, rgsServerUrl: nil) + try await self.start() + } Logger.debug("Successfully started node with previous config") } catch { Logger.error("Failed starting node with previous config: \(error)") @@ -490,6 +498,38 @@ class LightningService: NodeLifecycleService { } } + /// Runs `start` again while it fails because the store is still busy with a stopped node's VSS writes, up to + /// `recoveryStartAttempts` times. A stop requested meanwhile wins: no further start runs. + static func startRetryingBusyStore( + attempts: Int = recoveryStartAttempts, + stopRequested: () -> Bool, + start: () async throws -> Void + ) async throws { + var attempt = 0 + while true { + guard !stopRequested() else { + Logger.info("Skipped recovery start because a stop was requested", context: "LightningService") + throw AppError(serviceError: .nodeNotSetup) + } + attempt += 1 + if attempt > 1 { + Logger.warn("Retrying recovery start '\(attempt)/\(attempts)'", context: "LightningService") + } + do { + try await start() + return + } catch where isKvStoreSetupFailure(error) && attempt < attempts { + continue + } + } + } + + static func isKvStoreSetupFailure(_ error: Error) -> Bool { + let underlying = (error as? AppError)?.underlyingError ?? error + if case BuildError.KvStoreSetupFailed = underlying { return true } + return false + } + /// Pass onEvent when being used in the background to listen for payments, channels, closes, etc /// - Parameter onEvent: Triggered on any LDK node event func start(onEvent: ((Event) -> Void)? = nil) async throws { @@ -550,6 +590,12 @@ class LightningService: NodeLifecycleService { } func stop(clearEventCallback: Bool = false) async throws { + restartLock.withLock { requestedStops += 1 } + try await stopNode(clearEventCallback: clearEventCallback) + } + + /// Stops the node without counting as a requested stop, for the restart and its recovery. + private func stopNode(clearEventCallback: Bool = false) async throws { guard let node else { Logger.warn("Node not started, nothing to stop") return diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index 20b5db00a..51808006f 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -61,4 +61,64 @@ final class LightningServiceTests: XCTestCase { release.continuation.finish() await task.value } + + // Regression: a stopped node's VSS writes can keep retrying past one build's wait for them, so the recovery start + // retries while the build fails on the busy store instead of leaving the node offline. + func testRecoveryStartRetriesWhileTheVssStoreIsBusy() async throws { + let busy = Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + var attempts = 0 + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + if attempts < 3 { throw busy } + } + XCTAssertEqual(attempts, 3) + } + + func testRecoveryStartGivesUpAfterItsAttempts() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + XCTFail("expected the last failure") + } catch {} + XCTAssertEqual(attempts, Bitkit.LightningService.recoveryStartAttempts) + } + + func testRecoveryStartDoesNotRetryOtherFailures() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { + attempts += 1 + throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: "")) + } + XCTFail("expected the failure") + } catch {} + XCTAssertEqual(attempts, 1) + } + + // Regression: a stop requested while the recovery runs wins over its retry. + func testRecoveryStartDoesNotRetryOverARequestedStop() async { + var attempts = 0 + var stopRequested = false + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { stopRequested }) { + attempts += 1 + stopRequested = true + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + XCTFail("expected the skipped start to fail") + } catch {} + XCTAssertEqual(attempts, 1) + } + + func testRecoveryStartDoesNotStartOverAStopRequestedBeforeIt() async { + var attempts = 0 + do { + try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { true }) { attempts += 1 } + XCTFail("expected the skipped start to fail") + } catch {} + XCTAssertEqual(attempts, 0) + } } diff --git a/changelog.d/next/1520.fixed.md b/changelog.d/next/1520.fixed.md new file mode 100644 index 000000000..45ee7f9fe --- /dev/null +++ b/changelog.d/next/1520.fixed.md @@ -0,0 +1 @@ +Fixed a rare case where restarting the Lightning node could overwrite its newer backed-up state with older data. From 443d622c63ab9dac4f24c2d18deda317bb73569f Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 09:25:27 +0100 Subject: [PATCH 2/3] style: wrap if bodies for swiftformat Verified: swiftformat --lint on both files (0 require formatting) --- Bitkit/Services/LightningService.swift | 4 +++- BitkitTests/LightningServiceTests.swift | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 092e1e5ae..6a7625dba 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -526,7 +526,9 @@ class LightningService: NodeLifecycleService { static func isKvStoreSetupFailure(_ error: Error) -> Bool { let underlying = (error as? AppError)?.underlyingError ?? error - if case BuildError.KvStoreSetupFailed = underlying { return true } + if case BuildError.KvStoreSetupFailed = underlying { + return true + } return false } diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index 51808006f..e1ffefdd8 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -69,7 +69,9 @@ final class LightningServiceTests: XCTestCase { var attempts = 0 try await Bitkit.LightningService.startRetryingBusyStore(stopRequested: { false }) { attempts += 1 - if attempts < 3 { throw busy } + if attempts < 3 { + throw busy + } } XCTAssertEqual(attempts, 3) } From 3ca8946444d70b4e570cb71c89c388777cdc29a1 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 10:30:04 +0100 Subject: [PATCH 3/3] fix: retry a config change's own start on a busy vss store An Electrum or RGS change whose build fails because the stopped node's VSS writes are still in flight now retries its own start before falling back to the previous config. Verified: unit suite (CI selection) on an iPhone 17 Pro simulator, iOS 26.5; swiftformat --lint on both files. --- Bitkit/Services/LightningService.swift | 43 ++++++++++++++++--------- BitkitTests/LightningServiceTests.swift | 39 +++++++++++++++++++++- 2 files changed, 66 insertions(+), 16 deletions(-) diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 6a7625dba..8d262df86 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -160,8 +160,8 @@ class LightningService: NodeLifecycleService { private var lastRestart: Task? /// Counts the stops callers asked for, so a recovery start can tell that one came in after it began. private var requestedStops = 0 - /// Recovery starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s for them. - static let recoveryStartAttempts = 5 + /// Starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s for them. + static let busyStoreStartAttempts = 5 private let eventLoopLock = NSLock() /// The current event loop and the node it serves, so only that node's lifecycle can cancel it. @@ -448,21 +448,34 @@ class LightningService: NodeLifecycleService { } let stopsBefore = restartLock.withLock { requestedStops } - // Restart the node with the current configuration + try await Self.applyConfigChange( + stopRequested: { self.restartLock.withLock { self.requestedStops != stopsBefore } }, + start: { + try await self.setup(walletIndex: self.currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl) + try await self.start() + }, + recover: { try await self.restartWithPreviousConfig(stopsBefore: stopsBefore) } + ) + } + + /// Starts the node with a changed config, retrying while the store is busy with the stopped node's VSS writes, which have + /// nothing to do with the new config. Any other failure, or a busy store past every attempt, runs `recover` and rethrows. + static func applyConfigChange( + stopRequested: () -> Bool, + start: () async throws -> Void, + recover: () async throws -> Void + ) async throws { do { - try await setup(walletIndex: currentWalletIndex, electrumServerUrl: electrumServerUrl, rgsServerUrl: rgsServerUrl) - try await start() - Logger.info("Node restarted successfully") + try await startRetryingBusyStore(stopRequested: stopRequested, start: start) + Logger.info("Node restarted successfully", context: "LightningService") } catch { - Logger.warn("Failed ldk-node config change, attempting recovery…") - // Attempt to restart with previous config + Logger.warn("Failed ldk-node config change, attempting recovery…", context: "LightningService") // If recovery fails, log it but still throw the original error do { - try await restartWithPreviousConfig(stopsBefore: stopsBefore) + try await recover() } catch { - Logger.error("Recovery attempt also failed: \(error)") + Logger.error("Recovery attempt also failed: \(error)", context: "LightningService") } - // Always re-throw the original error that caused the restart failure throw error } } @@ -499,21 +512,21 @@ class LightningService: NodeLifecycleService { } /// Runs `start` again while it fails because the store is still busy with a stopped node's VSS writes, up to - /// `recoveryStartAttempts` times. A stop requested meanwhile wins: no further start runs. + /// `busyStoreStartAttempts` times. A stop requested meanwhile wins: no further start runs. static func startRetryingBusyStore( - attempts: Int = recoveryStartAttempts, + attempts: Int = busyStoreStartAttempts, stopRequested: () -> Bool, start: () async throws -> Void ) async throws { var attempt = 0 while true { guard !stopRequested() else { - Logger.info("Skipped recovery start because a stop was requested", context: "LightningService") + Logger.info("Skipped node start because a stop was requested", context: "LightningService") throw AppError(serviceError: .nodeNotSetup) } attempt += 1 if attempt > 1 { - Logger.warn("Retrying recovery start '\(attempt)/\(attempts)'", context: "LightningService") + Logger.warn("Retrying node start on a busy store '\(attempt)/\(attempts)'", context: "LightningService") } do { try await start() diff --git a/BitkitTests/LightningServiceTests.swift b/BitkitTests/LightningServiceTests.swift index e1ffefdd8..3341a37d7 100644 --- a/BitkitTests/LightningServiceTests.swift +++ b/BitkitTests/LightningServiceTests.swift @@ -85,7 +85,7 @@ final class LightningServiceTests: XCTestCase { } XCTFail("expected the last failure") } catch {} - XCTAssertEqual(attempts, Bitkit.LightningService.recoveryStartAttempts) + XCTAssertEqual(attempts, Bitkit.LightningService.busyStoreStartAttempts) } func testRecoveryStartDoesNotRetryOtherFailures() async { @@ -123,4 +123,41 @@ final class LightningServiceTests: XCTestCase { } catch {} XCTAssertEqual(attempts, 0) } + + // Regression: a busy store has nothing to do with the requested Electrum or RGS server, so the change retries it + // instead of falling back to the previous config. + func testConfigChangeRetriesItsOwnStartWhileTheVssStoreIsBusy() async throws { + var attempts = 0 + var recovered = false + try await Bitkit.LightningService.applyConfigChange( + stopRequested: { false }, + start: { + attempts += 1 + if attempts < 2 { + throw Bitkit.AppError(error: BuildError.KvStoreSetupFailed(message: "in flight")) + } + }, + recover: { recovered = true } + ) + XCTAssertEqual(attempts, 2) + XCTAssertFalse(recovered) + } + + func testConfigChangeRecoversAfterAnotherFailure() async { + var attempts = 0 + var recovered = false + do { + try await Bitkit.LightningService.applyConfigChange( + stopRequested: { false }, + start: { + attempts += 1 + throw Bitkit.AppError(error: BuildError.WalletSetupFailed(message: "")) + }, + recover: { recovered = true } + ) + XCTFail("expected the change to fail") + } catch {} + XCTAssertEqual(attempts, 1) + XCTAssertTrue(recovered) + } }