Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,9 @@ class LightningRepo @Inject constructor(
// The prepared send held while its higher mining fee is reviewed, released before its node stops.
private val reviewedPreparedSend = AtomicReference<PreparedOnchainSend?>(null)
private val pendingStopJob = AtomicReference<Job?>(null)

/** Counts [stop] calls, so a start can tell a stop ran since its caller checked. */
private val stopRequestCount = AtomicLong(0)
private val pendingStopLock = Any()
private val lifecycleMutex = Mutex()

Expand All @@ -214,7 +217,8 @@ class LightningRepo @Inject constructor(
* recovery a failed change launches. [lifecycleMutex] is taken separately by `stop()` and
* `start()`, so without this a detached recovery can restart the previous config between a
* request's stop and start, leaving the request to report and persist a config that never
* started. Recovery is cheap to wait on: it skips the release gate, so it is a plain rebuild.
* started. Recovery skips the release gate, but while the stopped node's VSS writes keep the
* store busy it can take up to [RECOVERY_START_ATTEMPTS] builds of up to 60 s each.
*/
private val configChangeMutex = Mutex()
private val isChangingAddressType = AtomicBoolean(false)
Expand Down Expand Up @@ -398,12 +402,14 @@ class LightningRepo @Inject constructor(
shouldValidateGraph: Boolean = true,
shouldRetryYieldToStop: Boolean = false,
shouldCancelPendingStop: Boolean = true,
stopRequestsSeen: Long? = null,
): Result<Unit> = withContext(bgDispatcher) {
if (_isRecoveryMode.value) {
return@withContext Result.failure(RecoveryModeError())
}

if (shouldCancelPendingStop) cancelPendingStop()
val stopRequestsAtStart = stopRequestsSeen ?: stopRequestCount.get()

// Spark needs no node, so it starts alongside it and stays up while the node stops in background.
if (!isWiping) scope.launch { sparkRepo.start(walletIndex) }
Expand All @@ -417,6 +423,11 @@ class LightningRepo @Inject constructor(

val result = lifecycleMutex.withLock {
if (isWiping) return@withLock Result.failure(WipeInProgressError())
// A stop that ran since the caller checked wins, including one that found the node already stopped.
if (stopRequestsSeen != null && stopRequestCount.get() != stopRequestsSeen) {
Logger.info("Skipped start because a stop was requested", context = TAG)
return@withLock Result.failure(NodeStartYieldedToStopError(null))
}
initialLifecycleState = _lightningState.value.nodeLifecycleState
if (initialLifecycleState.isRunningOrStarting()) {
return@withLock skipStartForRunningNode(
Expand Down Expand Up @@ -536,7 +547,7 @@ class LightningRepo @Inject constructor(

// Restart after graph reset OUTSIDE the mutex to avoid deadlock
if (shouldRestartForGraphReset) {
Comment thread
ovitrif marked this conversation as resolved.
Resolved
return@withContext start(
return@withContext startNode(
walletIndex = walletIndex,
timeout = timeout,
shouldRetry = shouldRetry,
Expand All @@ -545,6 +556,8 @@ class LightningRepo @Inject constructor(
eventHandler = eventHandler,
channelMigration = channelMigration,
shouldValidateGraph = false, // Prevent infinite loop
shouldCancelPendingStop = shouldCancelPendingStop,
stopRequestsSeen = stopRequestsAtStart,
)
}

Expand Down Expand Up @@ -765,6 +778,7 @@ class LightningRepo @Inject constructor(
fun cancelPendingStop() = synchronized(pendingStopLock) { pendingStopJob.getAndSet(null)?.cancel() }

suspend fun stop(): Result<Unit> = withContext(bgDispatcher) {
stopRequestCount.incrementAndGet()
lifecycleMutex.withLock { stopLocked() }
}

Expand Down Expand Up @@ -1300,6 +1314,7 @@ class LightningRepo @Inject constructor(
}

Logger.debug("Starting node with previous config for recovery", context = TAG)
val stopRequests = stopRequestCount.get()

var result: Result<Unit>
var attempt = 0
Expand All @@ -1314,7 +1329,12 @@ class LightningRepo @Inject constructor(
if (attempt > 1) {
Logger.warn("Retrying recovery start '$attempt/$RECOVERY_START_ATTEMPTS'", context = TAG)
}
result = startNode(shouldRetry = false, shouldCancelPendingStop = false)
// A direct stop since recovery's own stop wins over every attempt.
result = startNode(
shouldRetry = false,
shouldCancelPendingStop = false,
stopRequestsSeen = stopRequests,
)
} while (result.exceptionOrNull().isKvStoreSetupFailure() && attempt < RECOVERY_START_ATTEMPTS)
result.onSuccess {
Logger.debug("Successfully started node with previous config", context = TAG)
Expand Down
117 changes: 117 additions & 0 deletions app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
Expand Down Expand Up @@ -4698,6 +4699,122 @@ class LightningRepoTest : BaseUnitTest() {
assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}

@Test
fun `restartWithElectrumServer recovery does not retry over a direct stop`() = test {
startNodeForTesting()
val badUrl = "ssl://10.0.2.2:60001"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))
whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) }
.doSuspendableAnswer { throw busy }
var recoveryAttempts = 0
val testScope = this
whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) }
.doSuspendableAnswer {
recoveryAttempts++
if (recoveryAttempts == 1) {
testScope.launch { sut.stop() }
// Stands in for the build's wait on the stopped node's writes.
delay(60.seconds)
throw busy
}
}

assertTrue(sut.restartWithElectrumServer(badUrl).isFailure)
testScheduler.advanceUntilIdle()

assertEquals(1, recoveryAttempts)
assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}

@Test
fun `restartWithElectrumServer recovery graph reset keeps a requested stop`() = test {
startNodeForTesting()
val badUrl = "ssl://10.0.2.2:60001"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit))
whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true))
val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))
whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) }
.doSuspendableAnswer { throw busy }
var recoveryAttempts = 0
whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) }
.doSuspendableAnswer {
recoveryAttempts++
if (recoveryAttempts == 1) {
whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true)
sut.stopDebounced()
}
}

assertTrue(sut.restartWithElectrumServer(badUrl).isFailure)
testScheduler.advanceUntilIdle()

assertEquals(2, recoveryAttempts)
assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}

@Test
fun `restartWithElectrumServer recovery graph reset keeps a debounced stop that fires mid-build`() = test {
startNodeForTesting()
val badUrl = "ssl://10.0.2.2:60001"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit))
whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true))
val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))
whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) }
.doSuspendableAnswer { throw busy }
var recoveryAttempts = 0
whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) }
.doSuspendableAnswer {
recoveryAttempts++
if (recoveryAttempts == 1) {
whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true)
sut.stopDebounced()
delay(6.seconds)
}
}

assertTrue(sut.restartWithElectrumServer(badUrl).isFailure)
testScheduler.advanceUntilIdle()

assertEquals(1, recoveryAttempts)
assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}

@Test
fun `restartWithElectrumServer recovery graph reset keeps a direct stop made mid-build`() = test {
startNodeForTesting()
val badUrl = "ssl://10.0.2.2:60001"
whenever(lightningService.node).thenReturn(null)
whenever(lightningService.stop()).thenReturn(Unit)
whenever(vssBackupClientLdk.setup(any())).thenReturn(Result.success(Unit))
whenever(vssBackupClientLdk.deleteObject(any(), any())).thenReturn(Result.success(true))
val busy = AppError(LdkError(BuildException.KvStoreSetupFailed("in flight")))
whenever { lightningService.setup(any(), eq(badUrl), anyOrNull(), anyOrNull()) }
.doSuspendableAnswer { throw busy }
var recoveryAttempts = 0
val testScope = this
whenever { lightningService.setup(any(), isNull(), isNull(), anyOrNull()) }
.doSuspendableAnswer {
recoveryAttempts++
if (recoveryAttempts == 1) {
whenever(lightningService.aresRequiredPeersInNetworkGraph()).thenReturn(false, true)
testScope.launch { sut.stop() }
delay(1.seconds)
}
}

assertTrue(sut.restartWithElectrumServer(badUrl).isFailure)
testScheduler.advanceUntilIdle()

assertEquals(1, recoveryAttempts)
assertNotEquals(NodeLifecycleState.Running, sut.lightningState.value.nodeLifecycleState)
}

// Regression: a server that cannot work is rejected by the probe before the node is touched.
// Tearing the node down for one is what leaves its electrum tasks wedged, so that a later
// free_node blocks for tens of seconds instead of milliseconds.
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/2012.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed the Lightning node starting again after it was stopped while recovering from a failed server change.