From 6059cd20bd55544165cf9e81dad266e88aa630d0 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 10:57:42 +0100 Subject: [PATCH 1/7] fix: retry a server change 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, up to 5 times and never past a requested stop, before falling back to the previous config. Verified: just compile, just test, just lint; emulator run of two RGS server changes (dev debug, Android 16). --- .../to/bitkit/repositories/LightningRepo.kt | 55 ++++++++++++++----- .../bitkit/repositories/LightningRepoTest.kt | 24 ++++++++ changelog.d/next/2147.fixed.md | 1 + 3 files changed, 67 insertions(+), 13 deletions(-) create mode 100644 changelog.d/next/2147.fixed.md diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 55d8e16096..71fa28dc7d 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) @@ -1029,10 +1029,7 @@ class LightningRepo @Inject constructor( Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG) - start( - shouldRetry = false, - customServerUrl = newServerUrl, - ) + startConfigChange(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. @@ -1069,10 +1066,7 @@ class LightningRepo @Inject constructor( Logger.debug("Starting node with new RGS server: '$newRgsUrl'", context = TAG) - start( - shouldRetry = false, - customRgsServerUrl = newRgsUrl, - ) + startConfigChange(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. @@ -1086,6 +1080,41 @@ class LightningRepo @Inject constructor( } } + /** + * 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( + customServerUrl: String? = null, + customRgsServerUrl: String? = null, + ): Result { + var result = start( + shouldRetry = false, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + ) + val stopRequests = stopRequestCount.get() + 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) + // A direct stop since the first attempt wins over every retry. + result = startNode( + shouldRetry = false, + customServerUrl = customServerUrl, + customRgsServerUrl = customRgsServerUrl, + shouldCancelPendingStop = false, + stopRequestsSeen = stopRequests, + ) + } + return result + } + private inline fun recoverOnCancellation(block: () -> T): T { try { return block() @@ -1328,7 +1357,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 +1365,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 +3474,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..354b656d10 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4875,6 +4875,30 @@ 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 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 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. From eebf9cae77053cdf47972e1d63490f6b15818017 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 11:24:21 +0100 Subject: [PATCH 2/7] fix: keep a stop requested during a server change's first build The change reads the stop counter right after its own stop, so a direct stop during the first build also blocks the retries and the recovery of the previous config. Verified: just compile, just test, just lint (LightningRepoTest incl. the new stop and RGS busy-store cases). --- .../to/bitkit/repositories/LightningRepo.kt | 29 ++++++++---- .../bitkit/repositories/LightningRepoTest.kt | 47 +++++++++++++++++++ 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 71fa28dc7d..5c1a5319eb 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1021,20 +1021,23 @@ class LightningRepo @Inject constructor( configChangeMutex.withLock { waitForNodeToStop().onFailure { return@withContext Result.failure(it) } + var stopRequests: Long? = null recoverOnCancellation { 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) - startConfigChange(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 { @@ -1058,20 +1061,23 @@ class LightningRepo @Inject constructor( configChangeMutex.withLock { waitForNodeToStop().onFailure { return@withContext Result.failure(it) } + var stopRequests: Long? = null recoverOnCancellation { 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) - startConfigChange(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) } @@ -1085,15 +1091,16 @@ class LightningRepo @Inject constructor( * 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 = start( + var result = startNode( shouldRetry = false, customServerUrl = customServerUrl, customRgsServerUrl = customRgsServerUrl, + stopRequestsSeen = stopRequests, ) - val stopRequests = stopRequestCount.get() 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) { @@ -1103,7 +1110,6 @@ class LightningRepo @Inject constructor( } attempt++ Logger.warn("Retrying server change start '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) - // A direct stop since the first attempt wins over every retry. result = startNode( shouldRetry = false, customServerUrl = customServerUrl, @@ -1332,10 +1338,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 -> diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 354b656d10..e29f6c6080 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4899,6 +4899,53 @@ class LightningRepoTest : BaseUnitTest() { 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 `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 From 407710e6c0321b406cc50fc0ba232364aed77c4b Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 12:08:39 +0100 Subject: [PATCH 3/7] fix: keep a stop requested before a server change is cancelled Cancellation recovery now skips the previous config's start when a stop arrived since the change's own stop, as the failure recovery does. Verified: just compile, just test, just lint; the new LightningRepoTest case failed before the fix. --- .../to/bitkit/repositories/LightningRepo.kt | 10 ++++--- .../bitkit/repositories/LightningRepoTest.kt | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 5c1a5319eb..d5d99641ba 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1022,7 +1022,7 @@ class LightningRepo @Inject constructor( waitForNodeToStop().onFailure { return@withContext Result.failure(it) } var stopRequests: Long? = null - recoverOnCancellation { + recoverOnCancellation(stopRequestsSeen = { stopRequests }) { stop().onFailure { Logger.error("Failed to stop node during electrum server change", it, context = TAG) return@withContext Result.failure(it) @@ -1062,7 +1062,7 @@ class LightningRepo @Inject constructor( waitForNodeToStop().onFailure { return@withContext Result.failure(it) } var stopRequests: Long? = null - recoverOnCancellation { + recoverOnCancellation(stopRequestsSeen = { stopRequests }) { stop().onFailure { Logger.error("Failed to stop node during RGS server change", it, context = TAG) return@withContext Result.failure(it) @@ -1121,7 +1121,7 @@ class LightningRepo @Inject constructor( return result } - private inline fun recoverOnCancellation(block: () -> T): T { + private inline fun recoverOnCancellation(stopRequestsSeen: () -> Long?, block: () -> T): T { try { return block() } catch (e: CancellationException) { @@ -1129,8 +1129,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 } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index e29f6c6080..608c46e8dd 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4924,6 +4924,32 @@ class LightningRepoTest : BaseUnitTest() { assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + @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() From c2633b0597bf105a4f878e062e92de1956f6c734 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 13:02:24 +0100 Subject: [PATCH 4/7] fix: keep a stop requested during a server change's successful build A server change rechecks the stop counter after setup and yields to a stop requested during the build, instead of starting the node and saving the server. Verified: just compile, just test, just lint; the new LightningRepoTest case failed before the fix. --- .../to/bitkit/repositories/LightningRepo.kt | 7 ++++++ .../bitkit/repositories/LightningRepoTest.kt | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index d5d99641ba..2bef77224d 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -457,6 +457,13 @@ class LightningRepo @Inject constructor( } } + // A stop requested during the build waits on this lock; it wins and releases the built node. + if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + Logger.info("Skipped start because a stop was requested during setup", context = TAG) + _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } + return@withLock Result.failure(NodeStartYieldedToStopError(null)) + } + if (lightningService.status?.isRunning == true) { Logger.info("LDK node already running", context = TAG) runSuspendCatching { lightningService.reconcileWatchOnlyAccounts() } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 608c46e8dd..ea4b5cad47 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4924,6 +4924,29 @@ class LightningRepoTest : BaseUnitTest() { 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" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + clearInvocations(lightningService, settingsStore) + whenever { lightningService.setup(any(), eq(newUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + testScope.launch { sut.stop() } + delay(1) + } + + assertTrue(sut.restartWithElectrumServer(newUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService, never()).start(anyOrNull(), any()) + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + verify(settingsStore, never()).update(any()) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + @Test fun `restartWithElectrumServer cancelled after a stop does not recover the previous config`() = test { startNodeForTesting() From abd015b0741013ef38e1b9b29e7234f2133a8217 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 13:38:04 +0100 Subject: [PATCH 5/7] fix: release a server change's node that never runs A node built with a changed server is released when its start yields to a stop, fails or is cancelled, so a foreground start that cancelled a background stop rebuilds from the saved server instead of reusing it. Verified: just compile, just test, just lint; the new cancelled-background-stop and cancel-after-setup LightningRepoTest cases failed before the fix. --- .../to/bitkit/repositories/LightningRepo.kt | 24 ++- .../bitkit/repositories/LightningRepoTest.kt | 156 +++++++++++++++++- 2 files changed, 175 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 2bef77224d..b03bd28756 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -457,10 +457,12 @@ class LightningRepo @Inject constructor( } } - // A stop requested during the build waits on this lock; it wins and releases the built node. + // A stop requested during the build wins. A foreground start can cancel that stop before it runs, + // so release the built node here, or that start would reuse it with the change's server. if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { Logger.info("Skipped start because a stop was requested during setup", context = TAG) - _lightningState.update { it.copy(nodeLifecycleState = initialLifecycleState) } + releaseUnsavedConfigNode() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } return@withLock Result.failure(NodeStartYieldedToStopError(null)) } @@ -506,7 +508,15 @@ class LightningRepo @Inject constructor( Result.success(Unit) }.getOrElse { e -> if (e is CancellationException) { - withContext(NonCancellable) { reconcileCancelledStart(initialLifecycleState) } + withContext(NonCancellable) { + if (customServerUrl != null || customRgsServerUrl != null) { + // The change was never saved, so neither keep nor adopt a node built with its server. + releaseUnsavedConfigNode() + _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + } else { + reconcileCancelledStart(initialLifecycleState) + } + } throw e } @@ -527,6 +537,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 (customServerUrl != null || customRgsServerUrl != null) releaseUnsavedConfigNode() _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } Result.failure(e) } @@ -580,6 +593,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()) { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index ea4b5cad47..9adcd3d1ee 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4929,24 +4929,176 @@ class LightningRepoTest : BaseUnitTest() { startNodeForTesting() val testScope = this val newUrl = "ssl://10.0.2.2:60001" - whenever(lightningService.node).thenReturn(null) - whenever(lightningService.stop()).thenReturn(Unit) + 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 cancelled after a stop does not recover the previous config`() = test { startNodeForTesting() From 0907e4c4b02ac5f5e0a255985e5f0a66385d1841 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 14:43:13 +0100 Subject: [PATCH 6/7] fix: build a server change's own node before starting it A config-change attempt releases any handle another start left before it builds, and fails if it cannot. A cancelled change stops through the repository's stop transition, so Stopping is published and the state reset before its node is released. The cancellation journey now expects the release line. Verified: just compile, just test, just lint; the two new LightningRepoTest cases failed before the fix. --- .../to/bitkit/repositories/LightningRepo.kt | 15 +++-- .../bitkit/repositories/LightningRepoTest.kt | 56 +++++++++++++++++++ .../node-lifecycle/cancelled-node-restart.xml | 8 +-- 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index b03bd28756..596e18d6fd 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -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) } @@ -509,10 +516,10 @@ class LightningRepo @Inject constructor( }.getOrElse { e -> if (e is CancellationException) { withContext(NonCancellable) { - if (customServerUrl != null || customRgsServerUrl != null) { + if (isConfigChange) { // The change was never saved, so neither keep nor adopt a node built with its server. - releaseUnsavedConfigNode() - _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Stopped) } + stopLocked() + Logger.info("Released the node of a cancelled config change", context = TAG) } else { reconcileCancelledStart(initialLifecycleState) } @@ -539,7 +546,7 @@ class LightningRepo @Inject constructor( } 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 (customServerUrl != null || customRgsServerUrl != null) releaseUnsavedConfigNode() + if (isConfigChange) releaseUnsavedConfigNode() _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.ErrorStarting(e)) } Result.failure(e) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 9adcd3d1ee..e712436256 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -5099,6 +5099,62 @@ class LightningRepoTest : BaseUnitTest() { 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 cancelled after a stop does not recover the previous config`() = test { startNodeForTesting() 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 From a45ca2ae49d74007957677eef7b8df568310a354 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Fri, 27 Nov 2026 15:26:56 +0100 Subject: [PATCH 7/7] fix: keep a stop during setup from stopping ordinary starts The post-setup stop check now applies only to server changes and their recovery, so a stale-graph rebuild whose background stop was cancelled still starts, while recovery still yields to a stop. Verified: just compile, just test, just lint; the two new LightningRepoTest cases failed before the fix. --- .../to/bitkit/repositories/LightningRepo.kt | 8 ++- .../bitkit/repositories/LightningRepoTest.kt | 67 +++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 596e18d6fd..cf66f48e61 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -464,9 +464,11 @@ class LightningRepo @Inject constructor( } } - // A stop requested during the build wins. A foreground start can cancel that stop before it runs, - // so release the built node here, or that start would reuse it with the change's server. - if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) { + // 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) } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index e712436256..b50a9e7f18 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -5155,6 +5155,33 @@ class LightningRepoTest : BaseUnitTest() { 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() @@ -5392,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.