From 0fab7cda272b2a94643d4f30af634b0077135c42 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sun, 29 Nov 2026 14:26:24 +0100 Subject: [PATCH 1/6] chore: bump ldk-node to 0.7.0-rc.84 rc.84 unwinds on a panic instead of aborting: the node stops itself and cannot start again. A start, the sync retry and a returning network replace such a node, and the event listener stops instead of redelivering an event the node can no longer mark handled. Verified: testDevDebugUnitTest, detekt, assembleDevDebug --- .../to/bitkit/repositories/LightningRepo.kt | 33 +++++++++++++ .../to/bitkit/services/LightningService.kt | 20 +++++++- .../bitkit/repositories/LightningRepoTest.kt | 49 ++++++++++++++++++- .../bitkit/services/LightningServiceTest.kt | 28 +++++++++++ .../next/node-restart-after-panic.fixed.md | 1 + gradle/libs.versions.toml | 2 +- gradle/verification-metadata.xml | 11 +++++ 7 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 changelog.d/next/node-restart-after-panic.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 1d3acb5bdf..bd2cd1e5e8 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -249,6 +249,8 @@ class LightningRepo @Inject constructor( return@collect } + if (restartStoppedNode()) return@collect + if (_lightningState.value.nodeLifecycleState.isRunning()) { scheduleOrdinaryFollowupRetry() } @@ -285,6 +287,7 @@ class LightningRepo @Inject constructor( } delay(SYNC_RETRY_DELAY_MS) + if (restartStoppedNode()) return@launch Logger.info("Retrying sync after failure", context = TAG) sync().onSuccess { Logger.info("Sync retry succeeded", context = TAG) @@ -296,6 +299,30 @@ class LightningRepo @Inject constructor( syncRetryJob.set(job) } + /** + * Replaces a node that stopped itself, which ldk-node does after a panic: the lifecycle still reads as running. + * + * @return true when the node had stopped and a new start was launched + */ + private fun restartStoppedNode(): Boolean { + if (!_lightningState.value.nodeLifecycleState.isRunning() || !lightningService.hasStoppedNode) return false + + Logger.warn("LDK node stopped itself, restarting it", context = TAG) + val stops = stopRequestCount.get() + scope.launch { + whileStartPending { + startNode( + walletIndex = lightningService.currentWalletIndex, + // A retry would cancel a pending background stop; the next trigger starts it again. + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stops, + ) + } + } + return true + } + /** * Executes the provided operation only if the node is running. * If the node is not running, waits for it to be running for a specified timeout. @@ -448,6 +475,7 @@ class LightningRepo @Inject constructor( Logger.info("Skipped start because a stop was requested", context = TAG) return@withLock Result.failure(NodeStartYieldedToStopError(null)) } + dropStoppedNode() initialLifecycleState = _lightningState.value.nodeLifecycleState if (initialLifecycleState.isRunningOrStarting()) { return@withLock skipStartForRunningNode( @@ -612,6 +640,11 @@ class LightningRepo @Inject constructor( result } + // A node that panicked stopped itself and refuses to start again, so drop it and build a new one. + private suspend fun dropStoppedNode() { + if (lightningService.hasStoppedNode) stopLocked() + } + private suspend fun adoptRunningNode(): Result { _lightningState.update { it.copy(nodeLifecycleState = NodeLifecycleState.Running) } scheduleOrdinaryFollowupRetry() diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 26f5eabc54..089121beb2 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -312,6 +312,10 @@ class LightningService internal constructor( @Volatile var node: Node? = null + /** Whether a start was tried on [node], which one that is only built has not had. */ + @Volatile + private var isStartTried = false + @Volatile var currentWalletIndex: Int = 0 private set @@ -360,6 +364,7 @@ class LightningService internal constructor( ) currentWalletIndex = walletIndex runtimeMonitor = monitor + isStartTried = false node = builtNode Logger.info("LDK node setup", context = TAG) @@ -528,6 +533,8 @@ class LightningService internal constructor( Env.activeElectrumServerUrl.update { chainElectrumUrl } } catch (e: NodeException) { throw LdkError(e) + } finally { + isStartTried = true } } @@ -1643,7 +1650,15 @@ class LightningService internal constructor( Logger.debug("LDK event fired: ${jsonLogOf(event)}", context = TAG) runCatching { node.eventHandled() } .onSuccess { Logger.verbose("LDK eventHandled: '$event'", context = TAG) } - .onFailure { Logger.verbose("LDK eventHandled error: '$event'", it, context = TAG) } + .onFailure { + Logger.verbose("LDK eventHandled error: '$event'", it, context = TAG) + // A refused event stays first in the queue and would come back at once. A node that panicked + // refuses, so leave the event for the next node. + if (node.nextEvent() == event) { + Logger.warn("Event listener stopping: node refused a handled event", it, context = TAG) + return@withContext + } + } onEvent?.invoke(event) } } @@ -1702,6 +1717,9 @@ class LightningService internal constructor( val nodeId: String? get() = node?.nodeId() val balances: BalanceDetails? get() = node?.listBalances() val status: NodeStatus? get() = node?.status() + + /** A node a start was tried on that is not running: ldk-node stops one after a panic, and it cannot start again. */ + val hasStoppedNode: Boolean get() = isStartTried && status?.isRunning == false val config: Config? get() = node?.config() val peers: List? get() = node?.listPeers() val channels: List? get() = node?.listChannels() diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index e5d00c5ddd..33ec0da458 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -163,6 +163,7 @@ class LightningRepoTest : BaseUnitTest() { private val onchainSendAttemptStore = mock() private val lnurlService = mock() private val connectivityRepo = mock() + private val isOnline = MutableStateFlow(ConnectivityState.CONNECTED) private val vssBackupClientLdk = mock() private val electrumProbeService = mock() private val urlValidator = UrlValidator { Result.success(Unit) } @@ -180,7 +181,7 @@ class LightningRepoTest : BaseUnitTest() { whenever(lightningService.start(anyOrNull(), any())).thenReturn(Unit) whenever { electrumProbeService.probe(any(), any()) }.thenReturn(Result.success(Unit)) whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(ldkSendHashesSeeded = true))) - whenever(connectivityRepo.isOnline).thenReturn(MutableStateFlow(ConnectivityState.CONNECTED)) + whenever(connectivityRepo.isOnline).thenReturn(isOnline) whenever(settingsStore.data).thenReturn(flowOf(SettingsData())) whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(true) sut = LightningRepo( @@ -636,6 +637,52 @@ class LightningRepoTest : BaseUnitTest() { verify(cacheStore, never()).invalidateReceiveOnchainAddress(any()) } + @Test + fun `start drops a node that stopped itself`() = test { + startNodeForTesting() + stubStoppedNode() + + sut.start(shouldRetry = false) + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `sync retry restarts a node that stopped itself`() = test { + startNodeForTesting() + stubStoppedNode() + var isSyncFailing = true + whenever(lightningService.sync()).doSuspendableAnswer { check(!isSyncFailing) { "node not running" } } + + sut.sync() + isSyncFailing = false + testScheduler.advanceTimeBy(16.seconds) + testScheduler.runCurrent() + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `a returning network restarts a node that stopped itself`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + stubStoppedNode() + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + verifyBlocking(lightningService) { stop() } + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + private suspend fun stubStoppedNode() { + var hasStoppedNode = true + whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } + whenever(lightningService.stop()).doSuspendableAnswer { hasStoppedNode = false } + } + @Test fun `start reconciles watch-only accounts when the underlying node is already running`() = test { sut.setInitNodeLifecycleState() diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index ce53236cad..5804f281e7 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -57,6 +57,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doNothing +import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.doThrow import org.mockito.kotlin.eq @@ -877,6 +878,33 @@ class LightningServiceTest : BaseUnitTest() { verify(newNode, never()).nextEventAsync() } + @Test + fun `listener stops without delivering an event the node refuses to mark handled`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + whenever(node.nextEventAsync()).thenReturn(event) + whenever(node.nextEvent()).thenReturn(event) + whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(0, delivered) + verify(node, times(1)).nextEventAsync() + } + + @Test + fun `a node counts as stopped only once a start was tried on it`() = test { + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) + val wasStoppedBeforeStart = sut.hasStoppedNode + + sut.start() + + assertEquals(false, wasStoppedBeforeStart) + assertEquals(true, sut.hasStoppedNode) + } + private class GateFixture( scope: CoroutineScope, val gated: LightningService, diff --git a/changelog.d/next/node-restart-after-panic.fixed.md b/changelog.d/next/node-restart-after-panic.fixed.md new file mode 100644 index 0000000000..7e5d0cba02 --- /dev/null +++ b/changelog.d/next/node-restart-after-panic.fixed.md @@ -0,0 +1 @@ +Fixed the Lightning node staying offline after an internal error until the app was closed and reopened. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index e7efb21c44..a900e08477 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -69,7 +69,7 @@ ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "k ktor-client-mock = { module = "io.ktor:ktor-client-mock", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } -ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.83" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.84" } lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index af52336ec6..8c403f28b6 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4439,6 +4439,17 @@ + + + + + + + + + + + From c6cc1f4a4c11f9b04c83537fcf0cda40159c758b Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 15:13:25 +0100 Subject: [PATCH 2/6] fix: avoid restart races with a stopped node A node the app is stopping or already starting is no longer taken for one that stopped itself. Verified: gradlew testDevDebugUnitTest detekt assembleDevDebug lintDevDebug --- .../to/bitkit/repositories/LightningRepo.kt | 5 ++++- .../to/bitkit/services/LightningService.kt | 2 ++ .../bitkit/services/LightningServiceTest.kt | 19 ++++++++++++++++++- 3 files changed, 24 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 bd2cd1e5e8..38bc32348f 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -305,10 +305,13 @@ class LightningRepo @Inject constructor( * @return true when the node had stopped and a new start was launched */ private fun restartStoppedNode(): Boolean { + // Read before the checks, so a stop that lands after them wins over this start. + val stops = stopRequestCount.get() + // A pending background stop or a start in flight already takes care of the node. + if (pendingStopJob.get()?.isActive == true || pendingStartCount.value > 0) return false if (!_lightningState.value.nodeLifecycleState.isRunning() || !lightningService.hasStoppedNode) return false Logger.warn("LDK node stopped itself, restarting it", context = TAG) - val stops = stopRequestCount.get() scope.launch { whileStartPending { startNode( diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 089121beb2..4b060521e9 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -656,6 +656,8 @@ class LightningService internal constructor( val monitor = runtimeMonitor Logger.debug("Stopping node…", context = TAG) + // A node the app stops is not one that stopped itself. + isStartTried = false ServiceQueue.LDK.background(ldkQueue) { runSuspendCatching { node.stop() } .onFailure { diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 5804f281e7..02ebf5f3fc 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -883,7 +883,7 @@ class LightningServiceTest : BaseUnitTest() { val event = Event.PaymentSuccessful(null, "hash", null, null) whenever(node.nextEventAsync()).thenReturn(event) whenever(node.nextEvent()).thenReturn(event) - whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + whenever(node.eventHandled()).thenThrow(IllegalStateException("refused")) var delivered = 0 sut.startEventListener { delivered++ } @@ -893,6 +893,23 @@ class LightningServiceTest : BaseUnitTest() { verify(node, times(1)).nextEventAsync() } + @Test + fun `listener delivers an event that left the queue although marking it handled failed`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + var polls = 0 + whenever(node.nextEventAsync()).doSuspendableAnswer { + if (polls++ == 0) event else awaitCancellation() + } + whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(1, delivered) + sut.stop() + } + @Test fun `a node counts as stopped only once a start was tried on it`() = test { val status = mock { on { isRunning } doReturn false } From c3c996f78733a085f6c32924dac2acd6b496fbb7 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 15:29:07 +0100 Subject: [PATCH 3/6] fix: launch one restart for a stopped node Two triggers at once could each launch a start. Verified: gradlew testDevDebugUnitTest detekt assembleDevDebug lintDevDebug --- .../to/bitkit/repositories/LightningRepo.kt | 24 +++++++------- .../bitkit/repositories/LightningRepoTest.kt | 33 +++++++++++++++++++ .../bitkit/services/LightningServiceTest.kt | 13 ++++++++ 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 38bc32348f..81f7ed8534 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -307,22 +307,22 @@ class LightningRepo @Inject constructor( private fun restartStoppedNode(): Boolean { // Read before the checks, so a stop that lands after them wins over this start. val stops = stopRequestCount.get() - // A pending background stop or a start in flight already takes care of the node. - if (pendingStopJob.get()?.isActive == true || pendingStartCount.value > 0) return false + // A pending background stop takes care of the node. + if (pendingStopJob.get()?.isActive == true) return false if (!_lightningState.value.nodeLifecycleState.isRunning() || !lightningService.hasStoppedNode) return false + // Counted before launching, so neither a start in flight nor a second trigger gets another start. + if (!pendingStartCount.compareAndSet(expect = 0, update = 1)) return false Logger.warn("LDK node stopped itself, restarting it", context = TAG) scope.launch { - whileStartPending { - startNode( - walletIndex = lightningService.currentWalletIndex, - // A retry would cancel a pending background stop; the next trigger starts it again. - shouldRetry = false, - shouldCancelPendingStop = false, - stopRequestsSeen = stops, - ) - } - } + startNode( + walletIndex = lightningService.currentWalletIndex, + // A retry would cancel a pending background stop; the next trigger starts it again. + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stops, + ) + }.invokeOnCompletion { pendingStartCount.update { it - 1 } } return true } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 33ec0da458..28d8715c56 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -677,6 +677,39 @@ class LightningRepoTest : BaseUnitTest() { verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } } + @Test + fun `a second trigger does not restart a stopped node while a restart is in flight`() = test { + startNodeForTesting() + val startGate = CompletableDeferred() + whenever(lightningService.start(anyOrNull(), any())).doSuspendableAnswer { startGate.await() } + whenever(lightningService.hasStoppedNode).thenReturn(true) + + repeat(2) { + isOnline.value = ConnectivityState.DISCONNECTED + testScheduler.runCurrent() + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + } + startGate.complete(Unit) + testScheduler.runCurrent() + + verifyBlocking(lightningService, times(2)) { start(anyOrNull(), any()) } + } + + @Test + fun `a pending background stop wins over restarting a stopped node`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + stubStoppedNode() + + sut.stopDebounced() + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + verifyBlocking(lightningService, times(1)) { start(anyOrNull(), any()) } + sut.cancelPendingStop() + } + private suspend fun stubStoppedNode() { var hasStoppedNode = true whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 02ebf5f3fc..5bd99accca 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -922,6 +922,19 @@ class LightningServiceTest : BaseUnitTest() { assertEquals(true, sut.hasStoppedNode) } + @Test + fun `a node the app is stopping does not count as stopped by itself`() = test { + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) + sut.start() + var wasStoppedDuringStop: Boolean? = null + whenever(node.stop()).thenAnswer { wasStoppedDuringStop = sut.hasStoppedNode } + + sut.stop() + + assertEquals(false, wasStoppedDuringStop) + } + private class GateFixture( scope: CoroutineScope, val gated: LightningService, From 5489368596ef913f86924ff3ce41add4190ea2a2 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 15:50:28 +0100 Subject: [PATCH 4/6] chore: name the changelog fragment after the pr Verified: none (file rename only) --- .../next/{node-restart-after-panic.fixed.md => 2197.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{node-restart-after-panic.fixed.md => 2197.fixed.md} (100%) diff --git a/changelog.d/next/node-restart-after-panic.fixed.md b/changelog.d/next/2197.fixed.md similarity index 100% rename from changelog.d/next/node-restart-after-panic.fixed.md rename to changelog.d/next/2197.fixed.md From be0644b584df919937af523125b3d3c12b3c0eb8 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 16:35:55 +0100 Subject: [PATCH 5/6] fix: keep the event loop and retry a busy restart The loop stops only when the node also is not running, and restarting a stopped node retries while its store is busy. Verified: gradlew testDevDebugUnitTest detekt assembleDevDebug lintDevDebug --- .../to/bitkit/repositories/LightningRepo.kt | 23 +++++++++++------ .../to/bitkit/services/LightningService.kt | 7 +++--- .../bitkit/repositories/LightningRepoTest.kt | 25 +++++++++++++++++++ .../bitkit/services/LightningServiceTest.kt | 23 +++++++++++++++++ 4 files changed, 68 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 81f7ed8534..51066790b6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -315,13 +315,22 @@ class LightningRepo @Inject constructor( Logger.warn("LDK node stopped itself, restarting it", context = TAG) scope.launch { - startNode( - walletIndex = lightningService.currentWalletIndex, - // A retry would cancel a pending background stop; the next trigger starts it again. - shouldRetry = false, - shouldCancelPendingStop = false, - stopRequestsSeen = stops, - ) + var attempt = 0 + // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. + do { + attempt++ + if (attempt > 1) { + if (pendingStopJob.get()?.isActive == true) break + Logger.warn("Retrying stopped node restart '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) + } + val result = startNode( + walletIndex = lightningService.currentWalletIndex, + // A retry would cancel a pending background stop. + shouldRetry = false, + shouldCancelPendingStop = false, + stopRequestsSeen = stops, + ) + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < BUSY_STORE_START_ATTEMPTS) }.invokeOnCompletion { pendingStartCount.update { it - 1 } } return true } diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 4b060521e9..a6d262963a 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -1654,9 +1654,10 @@ class LightningService internal constructor( .onSuccess { Logger.verbose("LDK eventHandled: '$event'", context = TAG) } .onFailure { Logger.verbose("LDK eventHandled error: '$event'", it, context = TAG) - // A refused event stays first in the queue and would come back at once. A node that panicked - // refuses, so leave the event for the next node. - if (node.nextEvent() == event) { + // A node that panicked refuses the event, which stays first in the queue and would come back at + // once, so leave it for the next node. A running node whose write failed has removed it, and an + // equal event may follow. + if (node.nextEvent() == event && !node.status().isRunning) { Logger.warn("Event listener stopping: node refused a handled event", it, context = TAG) return@withContext } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 28d8715c56..d0dc8a8407 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -710,6 +710,31 @@ class LightningRepoTest : BaseUnitTest() { sut.cancelPendingStop() } + @Test + fun `restarting a stopped node retries while the store is busy`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + var hasNode = true + var hasStoppedNode = true + whenever(lightningService.node).thenAnswer { if (hasNode) mock() else null } + whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } + whenever(lightningService.stop()).doSuspendableAnswer { + hasNode = false + hasStoppedNode = false + } + var setups = 0 + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) }.doSuspendableAnswer { + if (setups++ == 0) throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + hasNode = true + } + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + assertEquals(2, setups) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + private suspend fun stubStoppedNode() { var hasStoppedNode = true whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode } diff --git a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt index 5bd99accca..6957ef60b7 100644 --- a/app/src/test/java/to/bitkit/services/LightningServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/LightningServiceTest.kt @@ -884,6 +884,8 @@ class LightningServiceTest : BaseUnitTest() { whenever(node.nextEventAsync()).thenReturn(event) whenever(node.nextEvent()).thenReturn(event) whenever(node.eventHandled()).thenThrow(IllegalStateException("refused")) + val status = mock { on { isRunning } doReturn false } + whenever(node.status()).thenReturn(status) var delivered = 0 sut.startEventListener { delivered++ } @@ -910,6 +912,27 @@ class LightningServiceTest : BaseUnitTest() { sut.stop() } + @Test + fun `listener keeps running when an equal event follows a failed write on a running node`() = test { + val event = Event.PaymentSuccessful(null, "hash", null, null) + var polls = 0 + whenever(node.nextEventAsync()).doSuspendableAnswer { + if (polls++ == 0) event else awaitCancellation() + } + whenever(node.nextEvent()).thenReturn(event) + whenever(node.eventHandled()).thenThrow(IllegalStateException("persistence failed")) + val status = mock { on { isRunning } doReturn true } + whenever(node.status()).thenReturn(status) + var delivered = 0 + + sut.startEventListener { delivered++ } + testScheduler.advanceUntilIdle() + + assertEquals(1, delivered) + assertEquals(2, polls) + sut.stop() + } + @Test fun `a node counts as stopped only once a start was tried on it`() = test { val status = mock { on { isRunning } doReturn false } From 6ac16d5b24d2d49c1284fd88c649794036ee5546 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Sun, 29 Nov 2026 16:49:45 +0100 Subject: [PATCH 6/6] fix: end busy restart retries on any stop Verified: gradlew testDevDebugUnitTest detekt --- .../to/bitkit/repositories/LightningRepo.kt | 2 +- .../bitkit/repositories/LightningRepoTest.kt | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 51066790b6..5fb4ad25c7 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -320,7 +320,7 @@ class LightningRepo @Inject constructor( do { attempt++ if (attempt > 1) { - if (pendingStopJob.get()?.isActive == true) break + if (pendingStopJob.get()?.isActive == true || stopRequestCount.get() != stops) break Logger.warn("Retrying stopped node restart '$attempt/$BUSY_STORE_START_ATTEMPTS'", context = TAG) } val result = startNode( diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index d0dc8a8407..e8621c1234 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -735,6 +735,28 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + @Test + fun `a background stop ends the busy store retries of a stopped node restart`() = test { + startNodeForTesting() + isOnline.value = ConnectivityState.DISCONNECTED + var hasNode = true + whenever(lightningService.node).thenAnswer { if (hasNode) mock() else null } + whenever(lightningService.hasStoppedNode).thenAnswer { hasNode } + whenever(lightningService.stop()).doSuspendableAnswer { hasNode = false } + var setups = 0 + whenever { lightningService.setup(any(), anyOrNull(), anyOrNull(), anyOrNull()) }.doSuspendableAnswer { + setups++ + sut.stopDebounced() + throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + } + + isOnline.value = ConnectivityState.CONNECTED + testScheduler.runCurrent() + + assertEquals(1, setups) + sut.cancelPendingStop() + } + private suspend fun stubStoppedNode() { var hasStoppedNode = true whenever(lightningService.hasStoppedNode).thenAnswer { hasStoppedNode }