diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 55d8e16096..cf66f48e61 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -219,7 +219,7 @@ class LightningRepo @Inject constructor( * `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 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. + * store busy it can take up to [BUSY_STORE_START_ATTEMPTS] builds of up to 60 s each. */ private val configChangeMutex = Mutex() private val isChangingAddressType = AtomicBoolean(false) @@ -411,6 +411,7 @@ class LightningRepo @Inject constructor( if (shouldCancelPendingStop) cancelPendingStop() val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get() + val isConfigChange = customServerUrl != null || customRgsServerUrl != null // 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) } @@ -438,6 +439,12 @@ class LightningRepo @Inject constructor( ) } + // A changed config starts only a node it built itself, never a handle another start left behind. + if (isConfigChange && lightningService.node != null) { + releaseUnsavedConfigNode() + if (lightningService.node != null) return@withLock Result.failure(NodeConfigNotAppliedError()) + } + runCatching { _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Starting) } @@ -457,6 +464,17 @@ class LightningRepo @Inject constructor( } } + // A stop requested during a server change's or recovery's build wins. A foreground start can cancel + // that stop before it runs, so release the built node here, or that start would reuse it. An ordinary + // start, which cancels pending stops, is not held back by one. + val yieldsToStop = isConfigChange || !shouldCancelPendingStop + if (yieldsToStop && stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped start because a stop was requested during setup", context = TAG) + releaseUnsavedConfigNode() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + return@withLock Result.failure(NodeStartYieldedToStopError(null)) + } + if (lightningService.status?.isRunning == true) { Logger.info("LDK node already running", context = TAG) runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } @@ -499,7 +517,15 @@ class LightningRepo @Inject constructor( Result.success(Unit) }.getOrElse { e -> if (e is CancellationException) { - withContext(NonCancellable) { reconcileCancelledStart(initialLifecycleState) } + withContext(NonCancellable) { + if (isConfigChange) { + // The change was never saved, so neither keep nor adopt a node built with its server. + stopLocked() + Logger.info("Released the node of a cancelled config change", context = TAG) + } else { + reconcileCancelledStart(initialLifecycleState) + } + } throw e } @@ -520,6 +546,9 @@ class LightningRepo @Inject constructor( shouldRetryStart = true Result.failure(e) } else { + // A node built with a changed server must not outlive its failed start: the next start would + // reuse it although the change was never saved. + if (isConfigChange) releaseUnsavedConfigNode() _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } Result.failure(e) } @@ -573,6 +602,11 @@ class LightningRepo @Inject constructor( } } + private suspend fun releaseUnsavedConfigNode() { + runSuspendCatching { lightningService.stop() } + .onFailure { Logger.warn("Failed to release node built with an unsaved config", it, context = TAG) } + } + private suspend fun reconcileCancelledStart(initialLifecycleState: NodeLifecycleState) { if (lightningService.status?.isRunning == true) { if (_lightningState.value.nodeLifecycleState.isRunning()) { @@ -1021,23 +1055,23 @@ class LightningRepo @Inject constructor( configChangeMutex.withLock { waitForNodeToStop().onFailure { return@withContext Result.failure(it) } - recoverOnCancellation { + var stopRequests: Long? = null + recoverOnCancellation(stopRequestsSeen = { stopRequests }) { stop().onFailure { Logger.error("Failed to stop node during electrum server change", it, context = TAG) return@withContext Result.failure(it) } + // A stop requested from here on, during the change's first build included, wins over every start. + stopRequests = stopRequestCount.get() Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) - start( - shouldRetry = false, - customServerUrl = newServerUrl, - ) + startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl) }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. Logger.warn("Failed ldk-node config change, recovering in background…", context = TAG) - scope.launch { restartWithPreviousConfig() } + scope.launch { restartWithPreviousConfig(stopRequests) } }.onSuccess { runSuspendCatching { settingsStore.update { it.copy(electrumServer = newServerUrl) } } .onFailure { @@ -1061,23 +1095,23 @@ class LightningRepo @Inject constructor( configChangeMutex.withLock { waitForNodeToStop().onFailure { return@withContext Result.failure(it) } - recoverOnCancellation { + var stopRequests: Long? = null + recoverOnCancellation(stopRequestsSeen = { stopRequests }) { stop().onFailure { Logger.error("Failed to stop node during RGS server change", it, context = TAG) return@withContext Result.failure(it) } + // A stop requested from here on, during the change's first build included, wins over every start. + stopRequests = stopRequestCount.get() Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) - start( - shouldRetry = false, - customRgsServerUrl = newRgsUrl, - ) + startConfigChange(stopRequests = stopRequests, customRgsServerUrl = newRgsUrl) }.onFailure { // Recover in the background: a wedged node's release can gate the rebuild for tens of // seconds, and the caller must surface this failure now rather than block on recovery. Logger.warn("Failed ldk-node config change, recovering in background…", context = TAG) - scope.launch { restartWithPreviousConfig() } + scope.launch { restartWithPreviousConfig(stopRequests) } }.onSuccess { settingsStore.update { it.copy(rgsServerUrl = newRgsUrl) } @@ -1086,7 +1120,42 @@ class LightningRepo @Inject constructor( } } - private inline fun recoverOnCancellation(block: () -> T): T { + /** + * Starts the node with a changed server, retrying while the build fails because the stopped node's VSS + * writes keep the store busy, which has nothing to do with the new server. A stop requested meanwhile wins. + */ + private suspend fun startConfigChange( + stopRequests: Long?, + customServerUrl: String? = null, + customRgsServerUrl: String? = null, + ): Result { + var result = startNode( + shouldRetry = false, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + stopRequestsSeen = stopRequests, + ) + var attempt = 1 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) { + if (pendingStopJob.get() != null) { + Logger.info("Skipped server change retry because a stop was requested", context = TAG) + return result + } + attempt++ + Logger.warn("Retrying server change start '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) + result = startNode( + shouldRetry = false, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + shouldCancelPendingStop = false, + stopRequestsSeen = stopRequests, + ) + } + return result + } + + private inline fun recoverOnCancellation(stopRequestsSeen: () -> Long?, block: () -> T): T { try { return block() } catch (e: CancellationException) { @@ -1094,8 +1163,10 @@ class LightningRepo @Inject constructor( // and start() rethrow the cancellation instead of reporting a failure, so the onFailure // recovery never runs and the node would stay down until the next ON_START. Hand the // recovery to the repo scope, which outlives the caller, then preserve the cancellation. + // A stop requested since the change's own stop still wins over that recovery. Logger.warn("Cancelled ldk-node config change, recovering in background…", context = TAG) - scope.launch { restartWithPreviousConfig() } + val stopRequests = stopRequestsSeen() + scope.launch { restartWithPreviousConfig(stopRequests) } throw e } } @@ -1303,10 +1374,17 @@ class LightningRepo @Inject constructor( return remaining.isEmpty() } - private suspend fun restartWithPreviousConfig(): Result = withContext(bgDispatcher) { + /** [stopRequestsSeen] is the failed change's reading: a stop requested since then wins over recovery. */ + private suspend fun restartWithPreviousConfig( + stopRequestsSeen: Long? = null, + ): Result = withContext(bgDispatcher) { // Runs detached from the failed change, so it takes the same transaction lock: without it // this recovery can restart the previous config between a later change's stop and start. configChangeMutex.withLock { + if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped recovery because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) + } Logger.debug("Stopping node for recovery attempt", context = TAG) stop().onFailure { e -> @@ -1328,7 +1406,7 @@ class LightningRepo @Inject constructor( } attempt++ if (attempt > 1) { - Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + Logger.warn("Retrying recovery start '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) } // A direct stop since recovery's own stop wins over every attempt. result = startNode( @@ -1336,7 +1414,7 @@ class LightningRepo @Inject constructor( shouldCancelPendingStop = false, stopRequestsSeen = stopRequests, ) - } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) }.onFailure { @@ -3445,8 +3523,8 @@ class LightningRepo @Inject constructor( private const val SYNC_RETRY_DELAY_MS = 15_000L private const val MSATS_PER_SAT = 1_000uL - /** Recovery starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s. */ - private const val RECOVERY_START_ATTEMPTS = 5 + /** Starts while a stopped node's VSS writes keep the store busy; each build waits up to 60 s. */ + private const val BUSY_STORE_START_ATTEMPTS = 5 /** LDK's default routing fee limit is 1% of the amount, this divisor, plus [DEFAULT_ROUTING_FEE_BASE_MSAT]. */ private const val DEFAULT_ROUTING_FEE_DIVISOR = 100uL diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 89ebd6ee93..b50a9e7f18 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4875,6 +4875,361 @@ class LightningRepoTest : BaseUnitTest() { testScheduler.advanceUntilIdle() } + // Regression: a busy store has nothing to do with the requested server, so the change retries its own + // start instead of rejecting the server and falling back to the previous config. + @Test + fun `restartWithElectrumServer retries its own start while the vss store is busy`() = test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + var changeAttempts = 0 + whenever { lightningService.setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + changeAttempts++ + if (changeAttempts < 3) throw busy + } + + assertTrue(sut.restartWithElectrumServer(newUrl).isSuccess) + testScheduler.advanceUntilIdle() + + assertEquals(3, changeAttempts) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + // Regression: a direct stop (e.g. from LightningNodeService) during the change's first build sets no + // pending stop, so the change's own stop reading is what keeps the retry and the recovery from restarting. + @Test + fun `restartWithElectrumServer keeps a stop requested during its first build`() = test { + startNodeForTesting() + val testScope = this + val newUrl = "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(newUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + testScope.launch { sut.stop() } + delay(1) + throw busy + } + + assertTrue(sut.restartWithElectrumServer(newUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService, times(1)).setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + @Test + fun `restartWithElectrumServer keeps a stop requested during a build that succeeds`() = test { + startNodeForTesting() + val testScope = this + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + clearInvocations(lightningService, settingsStore) + whenever { lightningService.setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + testScope.launch { sut.stop() } + delay(1) + hasNode = true + } + + assertTrue(sut.restartWithElectrumServer(newUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService, times(1)).setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) + verify(lightningService, never()).start(anyOrNull(), any()) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + verify(settingsStore, never()).update(any()) + assertFalse(hasNode) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + // A background stop that the user's return cancelled before it ran stopped nothing, so it must not + // keep the node on the server the change rejected. + @Test + fun `restartWithElectrumServer leaves no node on the rejected server after a cancelled background stop`() = + test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var builtWith: String? = null + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + builtWith = it.getArgument(1) + hasNode = true + } + var newServerStarts = 0 + whenever { lightningService.start(anyOrNull(), any()) } + .doSuspendableAnswer { + if (builtWith == newUrl && ++newServerStarts == 1) { + delay(10.seconds) + throw AppError("Feerate estimation update timeout") + } + } + + val change = async { sut.restartWithElectrumServer(newUrl) } + runCurrent() + sut.stopDebounced() + testScheduler.advanceTimeBy(BACKGROUND_STOP_DELAY_MS + 1) + runCurrent() + sut.cancelPendingStop() + val foreground = async { sut.start() } + val changeResult = change.await() + foreground.await() + testScheduler.advanceUntilIdle() + + assertTrue(changeResult.isFailure) + assertNull(builtWith, "Node left on '$builtWith', the server the change rejected and never persisted") + } + + @Test + fun `restartWithElectrumServer releases its node when a cancelled background stop arrived during setup`() = + test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var builtWith: String? = null + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + if (it.getArgument(1) == newUrl) delay(10.seconds) + builtWith = it.getArgument(1) + hasNode = true + } + + val change = async { sut.restartWithElectrumServer(newUrl) } + runCurrent() + sut.stopDebounced() + testScheduler.advanceTimeBy(BACKGROUND_STOP_DELAY_MS + 1) + runCurrent() + sut.cancelPendingStop() + val foreground = async { sut.start() } + val changeResult = change.await() + foreground.await() + testScheduler.advanceUntilIdle() + + assertTrue(changeResult.isFailure) + assertNull(builtWith, "Node left on '$builtWith', the server the change rejected and never persisted") + } + + @Test + fun `restartWithRgsServer leaves no node on the rejected server after a cancelled background stop`() = test { + startNodeForTesting() + val newRgsUrl = "https://rgs.example.com/snapshot" + val node = mock() + var builtWith: String? = null + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + builtWith = it.getArgument(2) + hasNode = true + } + var newServerStarts = 0 + whenever { lightningService.start(anyOrNull(), any()) } + .doSuspendableAnswer { + if (builtWith == newRgsUrl && ++newServerStarts == 1) { + delay(10.seconds) + throw AppError("Feerate estimation update timeout") + } + } + + val change = async { sut.restartWithRgsServer(newRgsUrl) } + runCurrent() + sut.stopDebounced() + testScheduler.advanceTimeBy(BACKGROUND_STOP_DELAY_MS + 1) + runCurrent() + sut.cancelPendingStop() + val foreground = async { sut.start() } + val changeResult = change.await() + foreground.await() + testScheduler.advanceUntilIdle() + + assertTrue(changeResult.isFailure) + assertNull(builtWith, "Node left on '$builtWith', the RGS server the change rejected and never persisted") + } + + @Test + fun `restartWithElectrumServer cancelled after setup releases its node`() = test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var builtWith: String? = null + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + builtWith = it.getArgument(1) + hasNode = true + } + val startReached = CompletableDeferred() + whenever { lightningService.start(anyOrNull(), any()) } + .doSuspendableAnswer { + if (builtWith == newUrl) { + startReached.complete(Unit) + awaitCancellation() + } + } + + val change = launch { sut.restartWithElectrumServer(newUrl) } + startReached.await() + sut.stopDebounced() + testScheduler.advanceTimeBy(BACKGROUND_STOP_DELAY_MS + 1) + runCurrent() + sut.cancelPendingStop() + change.cancelAndJoin() + sut.start() + testScheduler.advanceUntilIdle() + + assertNull(builtWith, "Node left on '$builtWith', the server of the cancelled change") + } + + @Test + fun `restartWithElectrumServer retry builds its own node over a handle another start left`() = test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var builtWith: String? = null + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + var changeAttempts = 0 + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + if (it.getArgument(1) == newUrl && ++changeAttempts == 1) { + // A foreground start built from the saved server and left its handle before the retry. + builtWith = null + hasNode = true + throw busy + } + builtWith = it.getArgument(1) + hasNode = true + } + + assertTrue(sut.restartWithElectrumServer(newUrl).isSuccess) + + assertEquals(2, changeAttempts) + assertEquals(newUrl, builtWith) + } + + @Test + fun `restartWithElectrumServer cancelled while running publishes Stopping before releasing its node`() = test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + val node = mock() + var hasNode = false + val statesAtRelease = mutableListOf() + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { + if (hasNode) statesAtRelease += sut.lightningState.value.nodeLifecycleState + hasNode = false + } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { hasNode = true } + val refreshReached = CompletableDeferred() + whenever(lightningService.disconnectIdlePeers()).doSuspendableAnswer { + refreshReached.complete(Unit) + awaitCancellation() + } + + val change = launch { sut.restartWithElectrumServer(newUrl) } + refreshReached.await() + change.cancelAndJoin() + + assertEquals(NodeLifecycleState.Stopping, statesAtRelease.first()) + } + + @Test + fun `restartWithElectrumServer recovery keeps a stop requested during its build`() = test { + startNodeForTesting() + val testScope = this + val badUrl = "ssl://10.0.2.2:60001" + val node = mock() + var hasNode = false + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw AppError("Electrum unreachable") } + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + testScope.launch { sut.stop() } + delay(1) + hasNode = true + } + clearInvocations(lightningService) + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService).setup(any(), isNull(), isNull(), anyOrNull()) + verify(lightningService, never()).start(anyOrNull(), any()) + assertFalse(hasNode) + } + + @Test + fun `restartWithElectrumServer cancelled after a stop does not recover the previous config`() = test { + startNodeForTesting() + val newUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val buildStarted = CompletableDeferred() + whenever { lightningService.setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + buildStarted.complete(Unit) + awaitCancellation() + } + + val change = launch { sut.restartWithElectrumServer(newUrl) } + buildStarted.await() + val directStop = launch { sut.stop() } + testScheduler.runCurrent() + change.cancelAndJoin() + directStop.join() + testScheduler.advanceUntilIdle() + + assertTrue(change.isCancelled) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + + @Test + fun `restartWithRgsServer retries its own start while the vss store is busy`() = test { + startNodeForTesting() + val newRgsUrl = "https://rgs.example.com/snapshot" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + var changeAttempts = 0 + whenever { lightningService.setup(any(), isNull(), eq(newRgsUrl), anyOrNull()) } + .doSuspendableAnswer { + changeAttempts++ + if (changeAttempts < 3) throw busy + } + + assertTrue(sut.restartWithRgsServer(newRgsUrl).isSuccess) + testScheduler.advanceUntilIdle() + + assertEquals(3, changeAttempts) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // 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. @Test @@ -5064,6 +5419,46 @@ class LightningRepoTest : BaseUnitTest() { assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + @Test + fun `start keeps the node running when a cancelled background stop arrived during the graph reset rebuild`() = + test { + sut.setInitNodeLifecycleState() + whenever(lightningService.sync()).thenReturn(Unit) + val blocktank = mock() + whenever(coreService.blocktank).thenReturn(blocktank) + whenever(blocktank.info(any())).thenReturn(null) + whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit)) + whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true)) + whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true) + val node = mock() + var hasNode = false + var builds = 0 + whenever(lightningService.node).thenAnswer { if (hasNode) node else null } + whenever(lightningService.stop()).thenAnswer { hasNode = false } + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + builds++ + if (builds == 2) delay(10.seconds) + hasNode = true + } + + val start = async { sut.start() } + runCurrent() + sut.stopDebounced() + testScheduler.advanceTimeBy(BACKGROUND_STOP_DELAY_MS + 1) + runCurrent() + sut.cancelPendingStop() + val result = start.await() + testScheduler.advanceUntilIdle() + + assertEquals(2, builds) + assertEquals( + NodeLifecycleState.Running, + sut.lightningState.value.nodeLifecycleState, + "Foreground node left down after graph reset rebuild, start returned '$result'", + ) + } + // 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/2147.fixed.md b/changelog.d/next/2147.fixed.md new file mode 100644 index 0000000000..68f856229a --- /dev/null +++ b/changelog.d/next/2147.fixed.md @@ -0,0 +1 @@ +Fixed a valid Electrum or RGS server being rejected while the Lightning node was still saving its backup. diff --git a/journeys/node-lifecycle/cancelled-node-restart.xml b/journeys/node-lifecycle/cancelled-node-restart.xml index ab91c0face..629530b144 100644 --- a/journeys/node-lifecycle/cancelled-node-restart.xml +++ b/journeys/node-lifecycle/cancelled-node-restart.xml @@ -6,7 +6,7 @@ repo scope, so leaving the screen no longer cancels it — the restart completes and this journey asserts that outcome instead of a cancellation. The Rapid-Gossip-Sync screen's view model is route-scoped, so backing out of a Connect mid-rebuild really does cancel the start; that is the - route that exercises the reconcile. It is used instead of the Electrum Server screen because a + route that exercises the cancelled start. It is used instead of the Electrum Server screen because a dev emulator is already connected to the default Electrum server: `ResetToDefault` refills the same host/port/protocol, `hasEdited` stays false, the Connect button stays disabled, and no rebuild ever starts. The RGS screen has no such block — appending a trailing slash to the @@ -20,8 +20,8 @@ seconds on the emulator, which is the window the back press must land in. The lifecycle lines are only in the app log, not in `android layout`; read `files/logs/` through `run-as`, and list the logs again before each grep because they rotate mid-run. The cancellation has two possible - log orders and only one of them reconciles: cancelled inside the start, `startNode` reconciles - and logs a lifecycle line before `recoverOnCancellation` logs the recovery; cancelled while the + log orders and only one of them releases the node: cancelled inside the start, `startNode` releases + the node built with the unsaved server and logs that before `recoverOnCancellation` logs the recovery; cancelled while the stop is still finishing, the stop completes under `NonCancellable` and rethrows before the start begins, so the recovery line is logged on its own. The run waits for the start to begin before pressing Back to aim at the first order, but only the recovery line is asserted unconditionally. @@ -42,7 +42,7 @@ Run `adb shell input keyevent KEYCODE_ENTER` to dismiss the keyboard, wait about 2 seconds for the debounced validation, and verify `ConnectToHost` is enabled in `android layout` (a disabled button reports no click interaction) before tapping it Poll the newest log until it contains "Starting node with new RGS server", which is written after the stop finished and immediately before the start, then tap `NavigationBack` at once so the cancellation lands in the start phase rather than in the stop Verify the newest log contains "Cancelled ldk-node config change, recovering in background" after that line: this is the only line the cancellation always emits, whichever phase it lands in - Verify that the same log also contains one of "Restored lifecycle state" or "Adopted running LDK node after start cancellation" or "Kept running LDK node and its event listener after start cancellation" before that recovery line. This reconcile line is expected because the previous step pressed Back inside the start, but it is not guaranteed: if the back press still landed during the stop, the stop runs to completion under `NonCancellable` and rethrows before the start begins, so recovery is logged with no reconcile line at all. Treat a missing reconcile line as the stop-phase order, not a failure, and note which of the two orders the run produced + Verify that the same log also contains "Released the node of a cancelled config change" before that recovery line. This release line is expected because the previous step pressed Back inside the start, but it is not guaranteed: if the back press still landed during the stop, the stop runs to completion under `NonCancellable` and rethrows before the start begins, so recovery is logged with no release line at all. Treat a missing release line as the stop-phase order, not a failure, and note which of the two orders the run produced Verify within 60 seconds that the same log then contains "Successfully started node with previous config", with no "Node setup error" and no "Failed starting node with previous config" line after it Tap `RGSServer` again and verify `ConnectedUrl` still shows the default snapshot URL with no trailing slash: a cancelled change is never persisted, so the emulator is left as it was found. If it shows the trailing slash the back press landed after the rebuild finished — tap `ResetToDefault`, tap `ConnectToHost`, wait until `ConnectedUrl` drops the slash, then rerun from the step that taps the `RGSUrl` field with an earlier back press Press the device back button until the wallet overview (tag "TotalBalance") is visible