From 4f79529cb87f32387fd60a68401835c4dec8bfe9 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 00:12:05 +0100 Subject: [PATCH 1/8] fix: keep a stopped node's late writes off its rebuilt node Bumps ldk-node to 0.7.0-rc.82, which fences a replaced VSS store's writes. The release-gate kdocs now say the gate waits for free_node, not for the old node's detached work (#2003), and the background exit is named for the overlap it avoids. Verified: none (metadata and build run next) --- .../to/bitkit/services/LightningService.kt | 28 ++++++++++--------- gradle/libs.versions.toml | 2 +- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt index 9b639c2f48..03bb0313bc 100644 --- a/app/src/main/java/to/bitkit/services/LightningService.kt +++ b/app/src/main/java/to/bitkit/services/LightningService.kt @@ -575,14 +575,15 @@ class LightningService internal constructor( } // A stop can leave tasks detached, e.g. a VSS write that keeps retrying. ldk-node keeps their runtime // alive until they end, but the release returns before that, so a rebuilt node could run while the old - // node's work still writes. In the background, kill the process instead; a cold start restores - // everything. In the foreground, release as before. - if (monitor.hasDetachedWork && isAppInBackground() && exitBeforeRuntimeShutdown()) return@withContext + // node's work still runs. Building the next node waits up to 60 s for the old node's VSS writes in + // flight and drops any it starts later. In the background, kill the process instead; a cold start + // restores everything. In the foreground, release as before. + if (monitor.hasDetachedWork && isAppInBackground() && exitBeforeDetachedWorkOverlaps()) return@withContext releaseHandle(node) Logger.info("Node stopped", context = TAG) } - private suspend fun exitBeforeRuntimeShutdown(): Boolean { + private suspend fun exitBeforeDetachedWorkOverlaps(): Boolean { Logger.warn("Exiting process: node stop left ldk_node tasks detached while in background", context = TAG) delay(EXIT_LOG_FLUSH_DELAY) if (!isAppInBackground()) { @@ -597,11 +598,12 @@ class LightningService internal constructor( * Releases the rust handle instead of leaving it to the GC finalizer, keeping it off the * single-threaded LDK queue and off the lifecycle critical path. * - * `free_node` only returns once the node's background tasks drain, which takes tens of seconds - * when a failed start left them wedged, so the wait is bounded and the release is joined rather - * than run inline: cancelling a blocking FFI call does nothing, but abandoning the join lets the - * caller continue while the release finishes on its own. [awaitNodeRelease] gates the next - * rebuild or destructive storage work on the same job so native lifetimes never overlap. + * `free_node` waits a bounded time for the node's background tasks to drain, which can take tens + * of seconds when a failed start left them wedged, so the wait here is bounded too and the release + * is joined rather than run inline: cancelling a blocking FFI call does nothing, but abandoning the + * join lets the caller continue while the release finishes on its own. [awaitNodeRelease] gates + * the next rebuild or destructive storage work on the same job. After a timed-out stop, `free_node` + * can return while detached work of the old node still runs. */ private suspend fun releaseHandle(node: Node) { val release = launch(ioDispatcher) { @@ -616,10 +618,10 @@ class LightningService internal constructor( } /** - * Blocks until the previous node's release ([releaseHandle] / `free_node`) has finished, so a - * rebuild or destructive storage operation never overlaps the old node's native lifetime. The - * wait is bounded: a stuck free_node throws rather than proceeding (which would overlap) or - * blocking forever (which would brick every future rebuild). + * Blocks until the previous node's release ([releaseHandle] / `free_node`) has returned. It does + * not wait for the old node's detached work, which can still run after a timed-out stop. The wait + * is bounded: a stuck free_node throws rather than proceeding or blocking forever (which would + * brick every future rebuild). */ suspend fun awaitNodeRelease(timeout: Duration = NODE_RELEASE_GATE_TIMEOUT) { val release = releaseJob ?: return diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bf4e7b28fb..d3d9efc7d1 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.81" } +ldk-node-android = { module = "com.synonym:ldk-node-android", version = "0.7.0-rc.82" } 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" } From dab084a6ca3f4bb5e42081858677edd7ce0e2a34 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 00:22:07 +0100 Subject: [PATCH 2/8] chore: add ldk-node 0.7.0-rc.82 verification metadata Verified: ./gradlew --write-verification-metadata sha256 :app:assembleDevDebug --- gradle/verification-metadata.xml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index ec844f9130..a618f3c14f 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -4417,6 +4417,17 @@ + + + + + + + + + + + From 7f8ef77fbe02df946ebfb80c899ec05e29237a7b Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 00:40:53 +0100 Subject: [PATCH 3/8] chore: add changelog entry for the vss write fence Verified: none (changelog text only) --- changelog.d/next/2004.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2004.fixed.md diff --git a/changelog.d/next/2004.fixed.md b/changelog.d/next/2004.fixed.md new file mode 100644 index 0000000000..45ee7f9fe7 --- /dev/null +++ b/changelog.d/next/2004.fixed.md @@ -0,0 +1 @@ +Fixed a rare case where restarting the Lightning node could overwrite its newer backed-up state with older data. From 5084f1d07d29c5e1b5f583a2e616974a5f198c63 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 01:21:47 +0100 Subject: [PATCH 4/8] fix: retry recovery while the old node's vss writes run A stopped node's VSS write can keep retrying for minutes, past one build's 60 s wait, so the single recovery start failed and Lightning stayed offline until the app restarted. Recovery now retries the start while the build fails on the busy store, up to five times. Verified: none (gate runs next) --- .../to/bitkit/repositories/LightningRepo.kt | 17 ++++++++++++- app/src/main/java/to/bitkit/utils/Errors.kt | 3 ++- .../bitkit/repositories/LightningRepoTest.kt | 25 +++++++++++++++++++ 3 files changed, 43 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 17b271bee6..3802379ff5 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -108,6 +108,7 @@ import to.bitkit.services.NetworkGraphInfo import to.bitkit.services.NodeEventHandler import to.bitkit.services.SparkError import to.bitkit.utils.AppError +import to.bitkit.utils.LdkError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError import to.bitkit.utils.UrlValidator @@ -1297,7 +1298,15 @@ class LightningRepo @Inject constructor( Logger.debug("Starting node with previous config for recovery", context = TAG) - start(shouldRetry = false).onSuccess { + var result = start(shouldRetry = false) + 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 < RECOVERY_START_ATTEMPTS) { + attempt++ + Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + result = start(shouldRetry = false) + } + result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) }.onFailure { Logger.error("Failed starting node with previous config", it, context = TAG) @@ -3264,6 +3273,9 @@ 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 + /** 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 @@ -3488,3 +3500,6 @@ sealed interface EarlierSend { /** Spark invoices hold whole sats, so an exact msat amount the channels can't receive has nowhere to go. */ class SubSatAmountUnsupportedError(amountMsats: ULong) : AppError("Spark can only receive whole sats, not '$amountMsats' msat, and the channels can't receive it") + +private fun Throwable?.isKvStoreSetupFailure() = + generateSequence(this) { it.cause }.any { (it as? LdkError)?.isKvStoreSetupFailed == true } diff --git a/app/src/main/java/to/bitkit/utils/Errors.kt b/app/src/main/java/to/bitkit/utils/Errors.kt index 4eb6a2c26b..e722f97e8d 100644 --- a/app/src/main/java/to/bitkit/utils/Errors.kt +++ b/app/src/main/java/to/bitkit/utils/Errors.kt @@ -34,12 +34,13 @@ class LdkError(private val inner: LdkException) : AppError("Unknown LDK error.") override val message get() = inner.message ?: super.message val compactType get() = inner.compactType + val isKvStoreSetupFailed get() = (inner as? LdkException.Build)?.exception is BuildException.KvStoreSetupFailed sealed interface LdkException { val message: String? val compactType: String? - class Build(exception: BuildException) : LdkException { + class Build(val exception: BuildException) : LdkException { override val compactType = exception::class.simpleName override val message = when (exception) { is BuildException.InvalidChannelMonitor -> "Invalid channel monitor." diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 625724b33f..35c91c0b9f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -43,6 +43,7 @@ import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.Node +import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentDetails @@ -4538,6 +4539,30 @@ class LightningRepoTest : BaseUnitTest() { testScheduler.advanceUntilIdle() } + // 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 + fun `restartWithElectrumServer recovery retries while the vss store is busy`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + whenever(lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull())) + .thenThrow(AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))) + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + if (recoveryAttempts < 3) throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(3, recoveryAttempts) + assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds. From 08ef1a4bf876492d395d1a161607e944c4b58eab Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 01:21:59 +0100 Subject: [PATCH 5/8] test: sort the build exception import Verified: none (gate runs next) --- app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 35c91c0b9f..447a123812 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -39,11 +39,11 @@ import org.junit.Before import org.junit.Test import org.lightningdevkit.ldknode.AddressTypeBalance import org.lightningdevkit.ldknode.BalanceDetails +import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.ChannelDataMigration import org.lightningdevkit.ldknode.ChannelDetails import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.Node -import org.lightningdevkit.ldknode.BuildException import org.lightningdevkit.ldknode.NodeException import org.lightningdevkit.ldknode.NodeStatus import org.lightningdevkit.ldknode.PaymentDetails From 48204146f6c9c48fc693595c9f5cb2ac8fe56638 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 01:36:51 +0100 Subject: [PATCH 6/8] test: throw the busy vss store error from suspend answers Verified: none (gate runs next) --- .../test/java/to/bitkit/repositories/LightningRepoTest.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 447a123812..9d60f49cb1 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4547,13 +4547,14 @@ class LightningRepoTest : BaseUnitTest() { val badUrl = "ssl://10.0.2.2:60001" whenever(lightningService.node).thenReturn(null) whenever(lightningService.stop()).thenReturn(Unit) - whenever(lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull())) - .thenThrow(AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } var recoveryAttempts = 0 whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } .doSuspendableAnswer { recoveryAttempts++ - if (recoveryAttempts < 3) throw AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + if (recoveryAttempts < 3) throw busy } assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) From 6fc5bb2ee86adab603a92aad0d24a6d1064644bc Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 02:08:53 +0100 Subject: [PATCH 7/8] fix: let a background stop win over recovery retries Verified: none (gate runs next) --- .../to/bitkit/repositories/LightningRepo.kt | 7 ++++- .../bitkit/repositories/LightningRepoTest.kt | 27 +++++++++++++++++++ 2 files changed, 33 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 3802379ff5..7f64275821 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1302,9 +1302,14 @@ class LightningRepo @Inject constructor( 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 < RECOVERY_START_ATTEMPTS) { + // A stop requested while the app went to the background wins over the retry. + if (pendingStopJob.get() != null) { + Logger.info("Skipped recovery start retry because a stop was requested", context = TAG) + break + } attempt++ Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) - result = start(shouldRetry = false) + result = startNode(shouldRetry = false, shouldCancelPendingStop = false) } result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 9d60f49cb1..bc8e503456 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -116,6 +116,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -4564,6 +4565,32 @@ class LightningRepoTest : BaseUnitTest() { assertEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + // Regression: a stop requested while the app went to the background wins over the recovery retry, + // which would otherwise cancel it and leave the node running with background payments off. + @Test + fun `restartWithElectrumServer recovery does not retry over a requested stop`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { throw busy } + var recoveryAttempts = 0 + whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) } + .doSuspendableAnswer { + recoveryAttempts++ + sut.stopDebounced() + throw busy + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + assertEquals(1, recoveryAttempts) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds. From 35873ab4ef881bc5717f1c34f4a859f9afc2bf53 Mon Sep 17 00:00:00 2001 From: ovitrif Date: Tue, 24 Nov 2026 08:13:53 +0100 Subject: [PATCH 8/8] fix: keep a background stop over the first recovery start Verified: none (gate runs next) --- .../to/bitkit/repositories/LightningRepo.kt | 18 ++++++++------- .../bitkit/repositories/LightningRepoTest.kt | 22 +++++++++++++++++++ 2 files changed, 32 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 7f64275821..84aba06367 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1298,19 +1298,21 @@ class LightningRepo @Inject constructor( Logger.debug("Starting node with previous config for recovery", context = TAG) - var result = start(shouldRetry = false) - var attempt = 1 + var result: Result + var attempt = 0 // The stopped node's VSS writes can keep retrying for minutes, past one build's wait for them. - while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) { - // A stop requested while the app went to the background wins over the retry. + do { + // A stop requested since the app went to the background wins over recovery. if (pendingStopJob.get() != null) { - Logger.info("Skipped recovery start retry because a stop was requested", context = TAG) - break + Logger.info("Skipped recovery start because a stop was requested", context = TAG) + return@withContext Result.failure(NodeStartYieldedToStopError(null)) } attempt++ - Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + if (attempt > 1) { + Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG) + } result = startNode(shouldRetry = false, shouldCancelPendingStop = false) - } + } while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS) result.onSuccess { Logger.debug("Successfully started node with previous config", context = TAG) }.onFailure { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index bc8e503456..1432a1f9f6 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -4591,6 +4591,28 @@ class LightningRepoTest : BaseUnitTest() { assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) } + // Regression: a stop requested during the failed change's build is kept by recovery, whose first + // start would otherwise cancel it before any retry could see it. + @Test + fun `restartWithElectrumServer recovery does not start over a stop requested before it`() = test { + startNodeForTesting() + val badUrl = "ssl://10.0.2.2:60001" + whenever(lightningService.node).thenReturn(null) + whenever(lightningService.stop()).thenReturn(Unit) + val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight"))) + whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) } + .doSuspendableAnswer { + sut.stopDebounced() + throw busy + } + + assertTrue(sut.restartWithElectrumServer(badUrl).isFailure) + testScheduler.advanceUntilIdle() + + verify(lightningService, never()).setup(any(), isNull(), isNull(), anyOrNull()) + assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState) + } + // Regression: a server that cannot work is rejected by the probe before the node is touched. // Tearing the node down for one is what leaves its electrum tasks wedged, so that a later // free_node blocks for tens of seconds instead of milliseconds.