From fbde703ca59fe7613fc9220040ce5179e3e09ee2 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 14:15:29 +0100 Subject: [PATCH 1/3] fix: let a stop win over every recovery retry A direct stop queued behind a failed recovery build now ends the retries, and the graph-reset restart inside a recovery start keeps a requested background stop. Verified: just compile, just test, just lint --- .../to/bitkit/repositories/LightningRepo.kt | 14 ++++- .../bitkit/repositories/LightningRepoTest.kt | 58 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index edd8bba7fe..e48a4ff1de 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -214,7 +214,8 @@ class LightningRepo @Inject constructor( * recovery a failed change launches. [lifecycleMutex] is taken separately by `stop()` and * `start()`, so without this a detached recovery can restart the previous config between a * request's stop and start, leaving the request to report and persist a config that never - * started. Recovery is cheap to wait on: it skips the release gate, so it is a plain rebuild. + * started. Recovery skips the release gate, but while the stopped node's VSS writes keep the + * store busy it can take up to [RECOVERY_START_ATTEMPTS] builds of up to 60 s each. */ private val configChangeMutex = Mutex() private val isChangingAddressType = AtomicBoolean(false) @@ -536,7 +537,7 @@ class LightningRepo @Inject constructor( // Restart after graph reset OUTSIDE the mutex to avoid deadlock if (shouldRestartForGraphReset) { - return@withContext start( + return@withContext startNode( walletIndex = walletIndex, timeout = timeout, shouldRetry = shouldRetry, @@ -545,6 +546,7 @@ class LightningRepo @Inject constructor( eventHandler = eventHandler, channelMigration = channelMigration, shouldValidateGraph = false, // Prevent infinite loop + shouldCancelPendingStop = shouldCancelPendingStop, ) } @@ -1310,6 +1312,14 @@ class LightningRepo @Inject constructor( Logger.info("Skipped recovery start because a stop was requested", context = TAG) return@withContext Result.failure(NodeStartYieldedToStopError(null)) } + if (attempt > 0) { + // A direct stop queued behind the failed build runs first and wins. + lifecycleMutex.withLock { } + if (_lightningState.value.nodeLifecycleState is NodeLifecycleState.Stopped) { + Logger.info("Skipped recovery start because the node was stopped", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) + } + } attempt++ if (attempt > 1) { Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 1f83ad43cb..390f371158 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -26,6 +26,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -4698,6 +4699,63 @@ class LightningRepoTest : BaseUnitTest() { assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + @Test + fun `restartWithElectrumServer recovery does not retry over a direct stop`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + val testScope = this + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts == 1) { + testScope.launch { sut.stop() } + // Stands in for the build's wait on the stopped node's writes. + delay(60.seconds) + throw busy + } + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(1, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + @Test + fun `restartWithElectrumServer recovery graph reset keeps a requested stop`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) + whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true)) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts == 1) { + whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true) + sut.stopDebounced() + } + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(2, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds. From 47dcfe5fbf54e1d386398dd9a3982c41489413aa Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 15:08:09 +0100 Subject: [PATCH 2/3] chore: add changelog for the recovery stop fix Verified: none (changelog fragment only) --- changelog.d/next/2012.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2012.fixed.md diff --git a/changelog.d/next/2012.fixed.md b/changelog.d/next/2012.fixed.md new file mode 100644 index 0000000000..d7b0c8fc97 --- /dev/null +++ b/changelog.d/next/2012.fixed.md @@ -0,0 +1 @@ +Fixed the Lightning node starting again after it was stopped while recovering from a failed server change. From 49d45ddf7b4e30205f9e396cf6f8d5fae8f310f5 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 16:10:13 +0100 Subject: [PATCH 3/3] fix: let a stop that already ran win over a recovery start Stops are counted, and recovery and the graph-reset restart start only while no stop ran since they checked, compared inside the start's lock. Verified: just compile, just test, just lint --- .../to/bitkit/repositories/LightningRepo.kt | 28 ++++++--- .../bitkit/repositories/LightningRepoTest.kt | 59 +++++++++++++++++++ 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index e48a4ff1de..0c4896e3d6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -206,6 +206,9 @@ class LightningRepo @Inject constructor( // The prepared send held while its higher mining fee is reviewed, released before its node stops. private val reviewedPreparedSend = AtomicReference(null) private val pendingStopJob = AtomicReference(null) + + /** Counts [stop] calls, so a start can tell a stop ran since its caller checked. */ + private val stopRequestCount = AtomicLong(0) private val pendingStopLock = Any() private val lifecycleMutex = Mutex() @@ -399,12 +402,14 @@ class LightningRepo @Inject constructor( shouldValidateGraph: Boolean = true, shouldRetryYieldToStop: Boolean = false, shouldCancelPendingStop: Boolean = true, + stopRequestsSeen: Long? = null, ): Result = withContext(bgDispatcher) { if (_isRecoveryMode.value) { return@withContext Result.failure(RecoveryModeError()) } if (shouldCancelPendingStop) cancelPendingStop() + val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get() // Spark needs no node, so it starts alongside it and stays up while the node stops in background. if (!isWiping) scope.launch { sparkRepo.start(walletIndex) } @@ -418,6 +423,11 @@ class LightningRepo @Inject constructor( val result = lifecycleMutex.withLock { if (isWiping) return@withLock Result.failure(WipeInProgressError()) + // A stop that ran since the caller checked wins, including one that found the node already stopped. + if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped start because a stop was requested", context = TAG) + return@withLock Result.failure(NodeStartYieldedToStopError(null)) + } initialLifecycleState = _lightningState.value.nodeLifecycleState if (initialLifecycleState.isRunningOrStarting()) { return@withLock skipStartForRunningNode( @@ -547,6 +557,7 @@ class LightningRepo @Inject constructor( channelMigration = channelMigration, shouldValidateGraph = false, // Prevent infinite loop shouldCancelPendingStop = shouldCancelPendingStop, + stopRequestsSeen = stopRequestsAtStart, ) } @@ -767,6 +778,7 @@ class LightningRepo @Inject constructor( fun cancelPendingStop() = synchronized(pendingStopLock) { pendingStopJob.getAndSet(null)?.cancel() } suspend fun stop(): Result = withContext(bgDispatcher) { + stopRequestCount.incrementAndGet() lifecycleMutex.withLock { stopLocked() } } @@ -1302,6 +1314,7 @@ class LightningRepo @Inject constructor( } Logger.debug("Starting node with previous config for recovery", context = TAG) + val stopRequests = stopRequestCount.get() var result: Result var attempt = 0 @@ -1312,19 +1325,16 @@ class LightningRepo @Inject constructor( Logger.info("Skipped recovery start because a stop was requested", context = TAG) return@withContext Result.failure(NodeStartYieldedToStopError(null)) } - if (attempt > 0) { - // A direct stop queued behind the failed build runs first and wins. - lifecycleMutex.withLock { } - if (_lightningState.value.nodeLifecycleState is NodeLifecycleState.Stopped) { - Logger.info("Skipped recovery start because the node was stopped", context = TAG) - return@withContext Result.failure(NodeStartYieldedToStopError(null)) - } - } attempt++ if (attempt > 1) { Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) } - result = startNode(shouldRetry = false, shouldCancelPendingStop = false) + // A direct stop since recovery's own stop wins over every attempt. + result = startNode( + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stopRequests, + ) } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 390f371158..6b5397f3e5 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4756,6 +4756,65 @@ class LightningRepoTest : BaseUnitTest() { assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + @Test + fun `restartWithElectrumServer recovery graph reset keeps a debounced stop that fires mid-build`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) + whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true)) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts == 1) { + whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true) + sut.stopDebounced() + delay(6.seconds) + } + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(1, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + @Test + fun `restartWithElectrumServer recovery graph reset keeps a direct stop made mid-build`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) + whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true)) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + val testScope = this + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts == 1) { + whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true) + testScope.launch { sut.stop() } + delay(1.seconds) + } + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(1, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds.