diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index edd8bba7fe..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() @@ -214,7 +217,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) @@ -398,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) } @@ -417,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( @@ -536,7 +547,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 +556,8 @@ class LightningRepo @Inject constructor( eventHandler = eventHandler, channelMigration = channelMigration, shouldValidateGraph = false, // Prevent infinite loop + shouldCancelPendingStop = shouldCancelPendingStop, + stopRequestsSeen = stopRequestsAtStart, ) } @@ -765,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() } } @@ -1300,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 @@ -1314,7 +1329,12 @@ class LightningRepo @Inject constructor( 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 1f83ad43cb..6b5397f3e5 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,122 @@ 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) + } + + @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. 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.