From 92160e7574bba3e30ff163f9d79d11228b637991 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 13:02:42 +0100 Subject: [PATCH 1/5] fix: settle spark retries by their own attempt id Each Spark send passes a fresh idempotency key, which Spark keeps as the attempt's payment id, so only that attempt's outcome ends its hold. Verified: SparkRepoTest and CacheStoreTest pass --- .../main/java/to/bitkit/data/CacheStore.kt | 33 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 165 +++++------ .../to/bitkit/repositories/SparkRepoTest.kt | 268 +++++++++++++++--- 3 files changed, 343 insertions(+), 123 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 6b6930e6ba..46a6b84ca7 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -174,16 +174,30 @@ class CacheStore internal constructor( } } - /** Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, since [failedAt] epoch seconds. */ - suspend fun addSparkUncertainSend(paymentHash: String, failedAt: Long) { + /** + * Keeps Spark's send of [paymentHash] as one whose outcome Spark didn't report, started at [startedAt] epoch + * seconds as the attempt Spark knows by [attemptId]. + */ + suspend fun addSparkUncertainSend(paymentHash: String, startedAt: Long, attemptId: String) { val hash = paymentHash.lowercase() - store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends + (hash to failedAt)) } + store.updateData { + it.copy( + sparkUncertainSends = it.sparkUncertainSends + (hash to startedAt), + sparkSendAttemptIds = it.sparkSendAttemptIds + (hash to attemptId), + ) + } } suspend fun removeSparkUncertainSend(paymentHash: String) { val hash = paymentHash.lowercase() - if (hash !in store.data.first().sparkUncertainSends) return - store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) } + val data = store.data.first() + if (hash !in data.sparkUncertainSends && hash !in data.sparkSendAttemptIds) return + store.updateData { + it.copy( + sparkUncertainSends = it.sparkUncertainSends - hash, + sparkSendAttemptIds = it.sparkSendAttemptIds - hash, + ) + } } suspend fun addMoveToSparkHash(paymentHash: String) { @@ -371,10 +385,15 @@ data class AppCacheData( /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ val sparkSendExpiries: Map = mapOf(), /** - * Spark's sends whose outcome it didn't report, by hash, with when they failed in epoch seconds, so a restart - * never reads a retry's earlier failed attempt as its outcome. + * Spark's sends whose outcome it didn't report, by hash, with when they started in epoch seconds, kept across a + * restart until Spark settles them. */ val sparkUncertainSends: Map = mapOf(), + /** + * The idempotency key each of the [sparkUncertainSends] passed, which Spark keeps as that attempt's payment id, so + * only its own outcome settles it. A hold without one waits for a paid attempt or its invoice's expiry. + */ + val sparkSendAttemptIds: Map = mapOf(), /** * Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and * Activity shows the move as one. diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9733315ad4..f88e0178ee 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -124,12 +124,6 @@ class SparkRepo @Inject constructor( /** Tries to learn the outcome of a send whose result was lost while Spark cannot list its payments. */ private const val SETTLE_ATTEMPTS = 10 - /** - * How far before a send's start Spark may date its own failure, as Spark's clock can differ from the phone's. - * Shared with bitkit-ios. - */ - private const val OWN_FAILURE_CLOCK_MARGIN_SECS = 10uL - /** How long a journaled withdrawal Spark doesn't list stays open before a sync closes it as never sent. */ private val UNLISTED_WITHDRAWAL_GRACE = 10.minutes @@ -185,8 +179,8 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() - /** The latest failure Spark dated for each send seen this process, by payment hash, in epoch seconds. */ - private val sendFailedAt = ConcurrentHashMap() + /** Sends taken back at start, whose outcome Spark settled while the app was closed, so none is reported again. */ + private val restoredAtStart = ConcurrentHashMap.newKeySet() /** Spark payment ids of the sends whose outcome was reported, so the poll and Spark's event report it once. */ private val reportedSendIds = ConcurrentHashMap.newKeySet() @@ -281,7 +275,7 @@ class SparkRepo @Inject constructor( _state.update { it.copy(hasStartFailed = false) } runSuspendCatching { collectEvents() - restoreUncertainSends() + restoreUncertainSends(atStart = true) val isExiting = exitStore(walletIndex).isActive() _state.update { it.copy(isExiting = isExiting) } val connected = sparkService.connect(walletIndex, isExiting) @@ -326,7 +320,7 @@ class SparkRepo @Inject constructor( unsavedPayments.clear() sendsInFlight.clear() uncertainSends.clear() - sendFailedAt.clear() + restoredAtStart.clear() hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false @@ -589,13 +583,15 @@ class SparkRepo @Inject constructor( if (!isEntered) throw PaymentPendingException(paymentHash) // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. try { - val startedAt = sendStartedAt(paymentHash) + // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. + val attemptId = UUID.randomUUID().toString() + restoredAtStart.remove(paymentHash.lowercase()) val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, startedAt) + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds, attemptId) // The checks above and both writes suspend, so the deadline and an exit that started meanwhile // are checked last, before the send. runCatching { @@ -606,10 +602,9 @@ class SparkRepo @Inject constructor( cacheStore.removeSparkSendHash(paymentHash) throw it } - runSuspendCatching { sparkService.send(prepared) } + runSuspendCatching { sparkService.send(prepared, attemptId) } } } - sent.onSuccess { noteFailure(it) } val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. if (it.isInvoiceExpired()) { @@ -625,16 +620,21 @@ class SparkRepo @Inject constructor( throw SparkError.SendRefused("Spark balance can't cover the payment", it) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) - settleUncertainSend(paymentHash, expiresAt) + settleUncertainSend(paymentHash, expiresAt, attemptId) throw PaymentPendingException(paymentHash) } // A send Spark took stays held until Spark settles it or its invoice expires, as Spark's list may not // show it yet. if (payment.status == PaymentStatus.PENDING) { - settleUncertainSend(paymentHash, expiresAt) + settleUncertainSend(paymentHash, expiresAt, attemptId) } else { cacheStore.removeSparkUncertainSend(paymentHash) } + // Spark's failure event during its send call was left to this result, so the result reports it. + if (payment.status == PaymentStatus.FAILED) { + recordActivity(payment, isOwnAttempt = true) + if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash } finally { @@ -651,18 +651,19 @@ class SparkRepo @Inject constructor( } } - private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong) { + private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong, attemptId: String) { val failedAt = clock.now().epochSeconds - // The time kept before the send went out stays its start, which tells its own failure from earlier ones. val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt - uncertainSends[paymentHash.lowercase()] = UncertainSend(startedAt.toULong(), failedAt.toULong(), expiresAt) - cacheStore.addSparkUncertainSend(paymentHash, startedAt) + uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) + cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } } repeat(SETTLE_ATTEMPTS) { + // A send its own payment event settled meanwhile needs no sync. + if (!uncertainSends.containsKey(paymentHash.lowercase())) return@launch runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } if (trySettleUncertainSend(paymentHash)) return@launch @@ -701,16 +702,18 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if send.status == PaymentStatus.COMPLETED -> true // A pending send ends with its own payment event, or at its invoice's expiry. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> isFinal - is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash, listing) + is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash, uncertain.attemptId, listing) SparkLightningSend.Unavailable -> false } // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false if (!takeUncertainSend(paymentHash, uncertain, send)) return true + // A send that settled while the app was closed updates its row only, as nobody waits for it now. + val isReported = !restoredAtStart.remove(key) when (send) { SparkLightningSend.NotFound -> { // A retry that entered Spark's send call since the hold was taken reports its own outcome. - if (!sendsInFlight.containsKey(key)) { + if (isReported && !sendsInFlight.containsKey(key)) { _nodeEvents.emit( Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) ) @@ -719,23 +722,25 @@ class SparkRepo @Inject constructor( // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit is SparkLightningSend.Found -> { - val listed = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) - ?.latestSend(paymentHash) - val isOwn = listed != null && - listed.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() >= uncertain.startedAt + val payments = listing ?: runSuspendCatching { listPayments() }.getOrNull() + val deciding = payments?.latestSend(paymentHash) + // The send's own failure decides its row and outcome, also when another attempt failed later. + val own = payments?.firstOrNull { it.id == uncertain.attemptId } + val listed = own?.takeIf { deciding?.status == PaymentStatus.FAILED } ?: deciding if (send.status == PaymentStatus.FAILED) { // Its row stayed pending while held, so it takes the failure now. - listed?.let { recordActivity(it) } + listed?.let { recordActivity(it, isOwnAttempt = it === own) } } when { + !isReported -> Unit listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } // A retry started after the hold was taken reads as pending, and its own event reports it. listed.status == PaymentStatus.PENDING -> Unit // A retry that entered Spark's send call since the hold was taken reports its own outcome. listed.status == PaymentStatus.FAILED && isHeldFrom(listed) -> Unit // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. - isOwn -> if (reportedSendIds.add(listed.id)) listed.toNodeEvent()?.let { _nodeEvents.emit(it) } - // An earlier attempt's failure ends the send at its expiry, so it claims no payment. + listed === own -> if (reportedSendIds.add(own.id)) own.toNodeEvent()?.let { _nodeEvents.emit(it) } + // Another attempt's failure ends the send at its expiry, so it claims no payment. else -> listed.toNodeEvent()?.let { _nodeEvents.emit(it) } } } @@ -763,17 +768,24 @@ class SparkRepo @Inject constructor( } } - /** A send whose outcome Spark didn't report: when it failed, and when its invoice expires, in epoch seconds. */ - private data class UncertainSend(val startedAt: ULong, val failedAt: ULong, val expiresAt: ULong) + /** + * A send whose outcome Spark didn't report: the payment id Spark knows its attempt by, null for a hold kept by an + * older build, and when it failed and when its invoice expires, in epoch seconds. + */ + private data class UncertainSend(val attemptId: String?, val failedAt: ULong, val expiresAt: ULong) - /** Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. */ - private suspend fun restoreUncertainSends() = holdRestoreMutex.withLock { + /** + * Takes back the sends whose outcome Spark didn't report before a restart, so a sync can still settle them. Those + * taken back [atStart] settled, if at all, while the app was closed. + */ + private suspend fun restoreUncertainSends(atStart: Boolean = false) = holdRestoreMutex.withLock { val cache = cacheStore.data.first() - cache.sparkUncertainSends.forEach { (hash, failedAt) -> + cache.sparkUncertainSends.forEach { (hash, startedAt) -> // A send still in Spark's send call is settled by its result. if (sendsInFlight.containsKey(hash)) return@forEach val expiresAt = cache.sparkSendExpiries[hash]?.toULong() ?: ULong.MAX_VALUE - uncertainSends.putIfAbsent(hash, UncertainSend(failedAt.toULong(), failedAt.toULong(), expiresAt)) + val restored = UncertainSend(cache.sparkSendAttemptIds[hash], startedAt.toULong(), expiresAt) + if (uncertainSends.putIfAbsent(hash, restored) == null && atStart) restoredAtStart.add(hash) } } @@ -1535,34 +1547,32 @@ class SparkRepo @Inject constructor( suspend fun settledSendEvent(paymentHash: String): Event? = withContext(bgDispatcher) { if (!sparkService.isConnected) return@withContext null // Read before the list, so a hold its success event ends while the list is read still keeps it pending. - val heldStart = sendHoldStart(paymentHash.lowercase()) + val held = sendHold(paymentHash.lowercase()) runSuspendCatching { listPayments() } .onFailure { Logger.warn("Failed to list Spark payments", it, context = TAG) } .getOrNull() ?.latestSend(paymentHash) // A send in doubt or in Spark's send call is pending until Spark settles it, so a listed failure, which // may be an earlier attempt's, settles nothing yet. - ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it, heldStart) } + ?.takeUnless { it.status == PaymentStatus.FAILED && isHeldFrom(it, held) } ?.toNodeEvent() } /** * Whether [failure] leaves its send pending: while it is in Spark's send call, whose result settles it, or in doubt - * and Spark dates the failure more than [OWN_FAILURE_CLOCK_MARGIN_SECS] before the send started, as an earlier - * attempt's. + * and the failure is not the held attempt's own, as told by its payment id. A hold [held] read earlier counts too. */ - private suspend fun isHeldFrom(failure: Payment, heldStart: ULong? = null): Boolean { + private suspend fun isHeldFrom(failure: Payment, held: SendHold? = null): Boolean { val hash = failure.sendHash()?.lowercase() ?: return false if (sendsInFlight.containsKey(hash)) return true - val startedAt = listOfNotNull(heldStart, sendHoldStart(hash)).maxOrNull() ?: return false - return failure.timestamp.safe() + OWN_FAILURE_CLOCK_MARGIN_SECS.safe() < startedAt + return listOfNotNull(held, sendHold(hash)).any { it.attemptId != failure.id } } - private suspend fun hasOwnFailure(paymentHash: String, listing: List? = null): Boolean { - val failure = (listing ?: runSuspendCatching { listPayments() }.getOrNull()) - ?.latestSend(paymentHash) - ?.takeIf { it.status == PaymentStatus.FAILED } ?: return false - return !isHeldFrom(failure) + private suspend fun hasOwnFailure(paymentHash: String, attemptId: String?, listing: List?): Boolean { + attemptId ?: return false + val payments = listing ?: runSuspendCatching { listPayments() }.getOrNull() ?: return false + if (payments.latestSend(paymentHash)?.status != PaymentStatus.FAILED) return false + return payments.any { it.id == attemptId && it.status == PaymentStatus.FAILED } } /** @@ -1611,9 +1621,9 @@ class SparkRepo @Inject constructor( val hash = paymentHash.lowercase() val isUnlistedHeld = hash in unexpiredStartedSends() // Read before the list, so a hold its success event ends while the list is read still keeps it pending. - val wasUncertain = sendHoldStart(hash) != null + val wasUncertain = sendHold(hash) != null val send = listedLightningSend(paymentHash) - val isUncertain = wasUncertain || sendHoldStart(hash) != null + val isUncertain = wasUncertain || sendHold(hash) != null val isHeld = when (send) { SparkLightningSend.NotFound, SparkLightningSend.Unavailable -> isUncertain || isUnlistedHeld is SparkLightningSend.Found -> isUncertain && send.status == PaymentStatus.FAILED @@ -1621,8 +1631,16 @@ class SparkRepo @Inject constructor( if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } - private suspend fun sendHoldStart(hash: String): ULong? = - uncertainSends[hash]?.startedAt ?: cacheStore.data.first().sparkUncertainSends[hash]?.toULong() + /** The hold on the send of [hash] whose outcome Spark didn't report, null when none. */ + private suspend fun sendHold(hash: String): SendHold? { + uncertainSends[hash]?.let { return SendHold(it.attemptId) } + val cache = cacheStore.data.first() + if (hash !in cache.sparkUncertainSends) return null + return SendHold(cache.sparkSendAttemptIds[hash]) + } + + /** A send in doubt, held until the outcome of its attempt [attemptId], when known, settles it. */ + private data class SendHold(val attemptId: String?) /** Spark's listed record of the Lightning send with [paymentHash], as [lightningSend] reads it before its holds. */ private suspend fun listedLightningSend( @@ -1980,26 +1998,7 @@ class SparkRepo @Inject constructor( private fun recordedSince(records: Long): Set = sendRecordedAt.filterValues { it > records }.keys - private suspend fun listPayments(): List = sparkService.listPayments().onEach { noteFailure(it) } - - private fun noteFailure(payment: Payment) { - val hash = payment.sendHash(PaymentStatus.FAILED)?.lowercase() ?: return - sendFailedAt.merge(hash, payment.timestamp) { old, new -> maxOf(old, new) } - } - - /** - * When a send of [paymentHash] starting now counts as started: past every failure Spark dated for it by more than - * [OWN_FAILURE_CLOCK_MARGIN_SECS], so an earlier attempt's failure never reads as this send's own. Refused when - * Spark's list can't be read, as it may hold a failure unknown to this process; nothing has gone out yet. - */ - private suspend fun sendStartedAt(paymentHash: String): Long { - runSuspendCatching { listPayments() }.onFailure { - throw SparkError.SendRefused("Spark could not list its payments to date the send", it) - } - val now = clock.now().epochSeconds.toULong() - val failedAt = sendFailedAt[paymentHash.lowercase()] ?: return now.toLong() - return maxOf(now, failedAt.safe() + (OWN_FAILURE_CLOCK_MARGIN_SECS + 1uL).safe()).toLong() - } + private suspend fun listPayments(): List = sparkService.listPayments() /** The payment hash of this send, at [status] when given. */ private fun Payment.sendHash(status: PaymentStatus? = null): String? = (details as? PaymentDetails.Lightning) @@ -2044,7 +2043,6 @@ class SparkRepo @Inject constructor( } private suspend fun onPayment(payment: Payment) { - noteFailure(payment) // The event carries its outcome, so a failed balance read never holds back its settlement. runSuspendCatching { refresh() } .onFailure { Logger.warn("Failed to refresh Spark after payment '${payment.id}'", it, context = TAG) } @@ -2060,7 +2058,8 @@ class SparkRepo @Inject constructor( val deciding = runSuspendCatching { listPayments() }.getOrNull()?.latestSend(hash) if (deciding != null && deciding.id != payment.id) return } - recordActivity(payment, settlesJournal = false) + val isOwnAttempt = payment.sendHash()?.let { sendHold(it.lowercase())?.attemptId == payment.id } == true + recordActivity(payment, settlesJournal = false, isOwnAttempt = isOwnAttempt) val isRetried = payment.sendHash()?.let { hash -> val isFailed = payment.status == PaymentStatus.FAILED val isReleased = isFailed && listedLightningSend(hash).let { @@ -2072,6 +2071,7 @@ class SparkRepo @Inject constructor( holdRestoreMutex.withLock { if (isFailed && isHeldFrom(payment)) return@withLock true uncertainSends.remove(hash.lowercase()) + restoredAtStart.remove(hash.lowercase()) cacheStore.removeSparkUncertainSend(hash) if (isReleased) cacheStore.removeSparkSendHash(hash) false @@ -2086,18 +2086,23 @@ class SparkRepo @Inject constructor( /** * Records [payment] as activity and returns whether it is saved; a failed write is kept in [unsavedPayments]. Only * Spark's list or its send response [settlesJournal]: a payment event can come before the list holds the - * withdrawal, which recovery reads, so its journal stays open until the list shows it. + * withdrawal, which recovery reads, so its journal stays open until the list shows it. A failure of the send's own + * attempt [isOwnAttempt] writes its details, which another attempt's failure leaves as they are. */ - private suspend fun recordActivity(payment: Payment, settlesJournal: Boolean = true): Boolean { + private suspend fun recordActivity( + payment: Payment, + settlesJournal: Boolean = true, + isOwnAttempt: Boolean = false, + ): Boolean { (payment.details as? PaymentDetails.Withdraw)?.let { return recordWithdrawal(payment, it, settlesJournal) } val lightning = payment.details as? PaymentDetails.Lightning ?: return true if (payment.status == PaymentStatus.PENDING && payment.paymentType == SparkPaymentType.RECEIVE) { return true } val id = lightning.htlcDetails.paymentHash - // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever an earlier attempt - // on its invoice failed with. - if (payment.status == PaymentStatus.FAILED && isHeldFrom(payment)) { + // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever another attempt on + // its invoice failed with. + if (payment.status == PaymentStatus.FAILED && !isOwnAttempt && isHeldFrom(payment)) { return true } // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. @@ -2123,7 +2128,9 @@ class SparkRepo @Inject constructor( // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. - val failedRow = existing?.takeIf { payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT } + val failedRow = existing?.takeIf { + payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT && !isOwnAttempt + } if (failedRow?.status == PaymentState.FAILED) return true val activity = failedRow?.copy(status = PaymentState.FAILED) ?: LightningActivity.create( id = id, diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3d6dc9e827..a04fc1d7b0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -3735,7 +3735,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(sentPayment(fees = 0)) val deadline = now + 1.seconds - whenever { cacheStore.addSparkUncertainSend(any(), any()) }.thenAnswer { + whenever { cacheStore.addSparkUncertainSend(any(), any(), any()) }.thenAnswer { now = deadline + 1.seconds Unit } @@ -3883,19 +3883,29 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val taken = sentPayment(fees = 0).copy(id = "retry", status = PaymentStatus.PENDING, timestamp = 5uL) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(taken) + val taken = sentPayment(fees = 0).copy(status = PaymentStatus.PENDING, timestamp = now.epochSeconds.toULong()) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { taken.copy(id = it.getArgument(1)) } val sut = createSut() sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() - // Spark's list doesn't show the send it took yet, only the invoice's earlier failed attempt. - val earlier = sentPayment(fees = 0).copy(id = "earlier", status = PaymentStatus.FAILED, timestamp = 1uL) + // Spark's list doesn't show the send it took yet, only an earlier attempt's failure it hadn't listed before, + // as from another device, dated within seconds of the retry. + val earlier = sentPayment(fees = 0).copy( + id = "earlier", + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong() - 5uL, + ) whenever(sparkService.listPayments()).thenReturn(listOf(earlier)) sparkEvents.emit(SdkEvent.Synced) + sparkEvents.emit(SdkEvent.PaymentFailed(earlier)) advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "another attempt's failure reached the retry's screen") + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1", "hash")) assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) verify(sparkService, times(1)).send(any(), anyOrNull()) @@ -4047,7 +4057,7 @@ class SparkRepoTest : BaseUnitTest() { var listed = emptyList() whenever(sparkService.listPayments()).thenAnswer { listed } whenever(sparkService.send(any(), anyOrNull())).thenAnswer { - listed = listOf(own) + listed = listOf(own.copy(id = it.getArgument(1))) throw SdkException.Generic("timeout") } val backing = InMemoryDataStore(AppCacheData()) @@ -4089,13 +4099,16 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } - val own = sentPayment(fees = 0).copy( - id = "own", - status = PaymentStatus.FAILED, - timestamp = now.epochSeconds.toULong(), - ) - whenever(sparkService.listPayments()).thenReturn(listOf(own)) + var own: Payment? = null + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + own = sentPayment(fees = 0).copy( + id = it.getArgument(1), + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) + throw SdkException.Generic("timeout") + } + whenever(sparkService.listPayments()).thenAnswer { listOfNotNull(own) } val sut = createSut() sut.start(0).getOrThrow() val events = mutableListOf() @@ -4104,7 +4117,7 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() // Spark's callback for the same payment arrives after the poll settled it. - sparkEvents.emit(SdkEvent.PaymentFailed(own)) + sparkEvents.emit(SdkEvent.PaymentFailed(requireNotNull(own))) advanceUntilIdle() assertEquals(1, events.count { it is Event.PaymentFailed }, "the failure was reported twice") @@ -4211,7 +4224,7 @@ class SparkRepoTest : BaseUnitTest() { val records = mutableListOf() whenever { cacheStore.addSparkSendHash(any(), anyOrNull()) }.doSuspendableAnswer { records += "add" } whenever { cacheStore.removeSparkSendHash(any()) }.doSuspendableAnswer { records += "remove" } - whenever { cacheStore.addSparkUncertainSend(any(), any()) }.doSuspendableAnswer { records += "hold" } + whenever { cacheStore.addSparkUncertainSend(any(), any(), any()) }.doSuspendableAnswer { records += "hold" } whenever { cacheStore.removeSparkUncertainSend(any()) }.doSuspendableAnswer { records += "unhold" } val sut = createSut() sut.start(0).getOrThrow() @@ -4269,7 +4282,7 @@ class SparkRepoTest : BaseUnitTest() { } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) val own = sentPayment(fees = 0).copy( - id = "own", + id = sentKey(), status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong(), ) @@ -4306,8 +4319,8 @@ class SparkRepoTest : BaseUnitTest() { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) advanceUntilIdle() - // Spark dates a send's own failure at its start, by a clock that may run a few seconds behind the phone's. - val own = sentPayment(fees = 0).copy(id = "own", status = PaymentStatus.FAILED, timestamp = startedAt - 5uL) + // Spark knows the send by the key it passed, and dates it by its own clock. + val own = sentPayment(fees = 0).copy(id = sentKey(), status = PaymentStatus.FAILED, timestamp = startedAt - 5uL) whenever(sparkService.listPayments()).thenReturn(listOf(own)) sparkEvents.emit(SdkEvent.PaymentFailed(own)) advanceUntilIdle() @@ -4430,23 +4443,6 @@ class SparkRepoTest : BaseUnitTest() { return Triple(sut, events, store) } - @Test - fun `a spark send is refused before it goes out while spark can't list its payments`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) - whenever(sparkService.isConnected).thenReturn(true) - val prepared = unexpiredPrepared() - whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val sut = createSut(store) - sut.start(0).getOrThrow() - whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } - - assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) - - verify(sparkService, never()).send(any(), anyOrNull()) - assertFalse("hash" in store.data.first().sparkUncertainSends) - assertFalse("hash" in store.data.first().sparkSendHashes) - } - @Test fun `a spark send held while a sync writes its list is not settled from that list`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) @@ -4584,7 +4580,11 @@ class SparkRepoTest : BaseUnitTest() { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1uL) ) // Spark lists the send's own failure to the restart's sync, and every read after it fails. - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + val failed = sentPayment(fees = 0).copy( + id = sentKey(), + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) var isListed = true whenever { sparkService.listPayments() }.doSuspendableAnswer { if (isListed) listOf(failed) else throw SdkException.Generic("offline") @@ -4660,7 +4660,7 @@ class SparkRepoTest : BaseUnitTest() { fun `an uncertain spark retry past an older failure reads as pending to paykit and quickpay`() = test { val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) store.addSparkSendHash("hash", expiresAt = now.epochSeconds + 3_600) - store.addSparkUncertainSend("hash", now.epochSeconds) + store.addSparkUncertainSend("hash", now.epochSeconds, "older-build") whenever(sparkService.isConnected).thenReturn(true) whenever { sparkService.listPayments() } .thenReturn(listOf(sentPayment(fees = 0).copy(status = PaymentStatus.FAILED))) @@ -4850,6 +4850,200 @@ class SparkRepoTest : BaseUnitTest() { return copy(details = lightning.copy(htlcDetails = lightning.htlcDetails.copy(paymentHash = hash))) } + @Test + fun `a spark send's own failure ends its hold while the phone clock runs ahead of spark's`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + // The phone clock runs 30 s ahead of Spark's, which dates the send. + val pending = sentPayment(fees = 0).copy( + status = PaymentStatus.PENDING, + timestamp = now.epochSeconds.toULong() - 30uL, + ) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { pending.copy(id = it.getArgument(1)) } + val sut = createSut(store) + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + + val failed = pending.copy(id = sentKey(), status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() + + assertTrue(events.any { it is Event.PaymentFailed }, "the send's own failure never reached the send screen") + assertFalse("hash" in store.data.first().sparkUncertainSends, "the failed send kept its hold") + assertNull(sut.earlierLightningSend("lnbc1", "hash"), "the failed send still refuses a retry") + } + + @Test + fun `a spark send settled before its poll starts forces no extra wallet sync`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val pending = sentPayment(fees = 0).copy(status = PaymentStatus.PENDING, timestamp = now.epochSeconds.toULong()) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { pending.copy(id = it.getArgument(1)) } + val sut = createSut(store) + sut.start(0).getOrThrow() + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + // Spark settles the send at once, before the poll's first pass. + val completed = pending.copy(id = sentKey(), status = PaymentStatus.COMPLETED) + whenever(sparkService.listPayments()).thenReturn(listOf(completed)) + sparkEvents.emit(SdkEvent.PaymentSucceeded(completed)) + runCurrent() + assertFalse("hash" in store.data.first().sparkUncertainSends) + clearInvocations(sparkService) + + advanceUntilIdle() + + verify(sparkService, never()).syncWallet() + } + + @Test + fun `a held spark send that failed while closed updates its row without reporting at launch`() = test { + val sentAt = now.epochSeconds + // Spark took the send, then the app closed; the send failed while it was closed. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkSendAttemptIds = mapOf("hash" to "attempt"), + ) + ), + clock, + ) + whenever(sparkService.isConnected).thenReturn(true) + now += 1.minutes + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val failed = sentPayment(fees = 0).copy( + id = "attempt", + status = PaymentStatus.FAILED, + timestamp = sentAt.toULong() + 5uL, + ) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSends) + assertEquals( + emptyList(), + events.filter { it is Event.PaymentSuccessful || it is Event.PaymentFailed }, + "a payment settled while the app was closed was reported at launch", + ) + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + + @Test + fun `a spark send its call returns as failed reports its failure`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + // Spark reports the failure during its send call, then returns the same payment as failed. + whenever { sparkService.send(any(), anyOrNull()) }.doSuspendableAnswer { + val own = failed.copy(id = it.getArgument(1)) + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + own + } + val sut = createSut() + sut.start(0).getOrThrow() + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + runCurrent() + + sut.payInvoice("lnbc1", 100uL) + advanceUntilIdle() + + assertEquals(1, events.count { it is Event.PaymentFailed }, "quickpay never learned the send failed") + verify(activityRepo).upsertActivity( + argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } + ) + } + + @Test + fun `a spark retry's own failure takes its details over an earlier attempt's failed row`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + // The earlier attempt's failed row was saved; the retry's pending row never was. + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.FAILED)))) + val sut = createSut() + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + + val retryAt = now.epochSeconds.toULong() + val own = sentPayment(fees = 3).copy(id = sentKey(), status = PaymentStatus.FAILED, timestamp = retryAt) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + verify(activityRepo).upsertActivity( + argThat { + this is Activity.Lightning && v1.status == PaymentState.FAILED && v1.fee == 3uL && + v1.timestamp == retryAt + } + ) + } + + @Test + fun `a spark send held by an older build stays held past a listed failure until its invoice expires`() = test { + val sentAt = now.epochSeconds + // An older build kept the hold without the attempt's id. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + val failed = sentPayment(fees = 0).copy(id = "some", status = PaymentStatus.FAILED, timestamp = sentAt.toULong()) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals(SparkLightningSend.Found(PaymentStatus.PENDING, null), sut.lightningSend("hash")) + + now += 2.hours + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSends, "the hold outlived its invoice") + } + + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ + private suspend fun sentKey(): String = + argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue + private fun sentPayment(fees: Int) = Payment( id = "send", paymentType = PaymentType.SEND, From af7fa265c234d1afe9c4f954f076111a6d13a4e7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 13:13:43 +0100 Subject: [PATCH 2/5] fix: report a paid spark attempt once when its hold ends Also splits the listed-send report out of the settle step and drops comments that still described dating failures. Verified: just compile, just test and just lint pass --- .../java/to/bitkit/repositories/SparkRepo.kt | 64 +++++++++++-------- .../bitkit/repositories/LightningRepoTest.kt | 2 +- .../to/bitkit/repositories/SparkRepoTest.kt | 6 +- 3 files changed, 43 insertions(+), 29 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f88e0178ee..6daa26df61 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -566,8 +566,8 @@ class SparkRepo @Inject constructor( is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) // Spark's list, synced or unreadable, can lack a send it made before the restore, as on the node's - // path, so the operators decide. Before Spark syncs, its list can't date an earlier attempt they show - // failed, which a send must start past, so that one is refused too. + // path, so the operators decide. Before Spark syncs, its list can lack an earlier attempt they show + // failed, so that one is refused too. else -> refuseUnverifiedRestoredInvoice( bolt11, invoice.timestamp.toEpochSeconds(), @@ -697,11 +697,10 @@ class SparkRepo @Inject constructor( val send = listedLightningSend(paymentHash, listing) val isSettled = when (send) { SparkLightningSend.NotFound -> isFinal - // A failure dated before the send started is an earlier attempt's, so it is final only when a missing - // send would be. is SparkLightningSend.Found if send.status == PaymentStatus.COMPLETED -> true // A pending send ends with its own payment event, or at its invoice's expiry. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> isFinal + // Another attempt's failure is final only when a missing send would be. is SparkLightningSend.Found -> isFinal || hasOwnFailure(paymentHash, uncertain.attemptId, listing) SparkLightningSend.Unavailable -> false } @@ -721,34 +720,45 @@ class SparkRepo @Inject constructor( } // Spark still runs a pending send past its invoice's expiry, so its own payment event reports it. is SparkLightningSend.Found if send.status == PaymentStatus.PENDING -> Unit - is SparkLightningSend.Found -> { - val payments = listing ?: runSuspendCatching { listPayments() }.getOrNull() - val deciding = payments?.latestSend(paymentHash) - // The send's own failure decides its row and outcome, also when another attempt failed later. - val own = payments?.firstOrNull { it.id == uncertain.attemptId } - val listed = own?.takeIf { deciding?.status == PaymentStatus.FAILED } ?: deciding - if (send.status == PaymentStatus.FAILED) { - // Its row stayed pending while held, so it takes the failure now. - listed?.let { recordActivity(it, isOwnAttempt = it === own) } - } - when { - !isReported -> Unit - listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } - // A retry started after the hold was taken reads as pending, and its own event reports it. - listed.status == PaymentStatus.PENDING -> Unit - // A retry that entered Spark's send call since the hold was taken reports its own outcome. - listed.status == PaymentStatus.FAILED && isHeldFrom(listed) -> Unit - // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. - listed === own -> if (reportedSendIds.add(own.id)) own.toNodeEvent()?.let { _nodeEvents.emit(it) } - // Another attempt's failure ends the send at its expiry, so it claims no payment. - else -> listed.toNodeEvent()?.let { _nodeEvents.emit(it) } - } - } + is SparkLightningSend.Found -> reportListedSend(paymentHash, uncertain, send, listing, isReported) SparkLightningSend.Unavailable -> Unit } return true } + private suspend fun reportListedSend( + paymentHash: String, + uncertain: UncertainSend, + send: SparkLightningSend.Found, + listing: List?, + isReported: Boolean, + ) { + val payments = listing ?: runSuspendCatching { listPayments() }.getOrNull() + val deciding = payments?.latestSend(paymentHash) + // The send's own failure decides its row and outcome, also when another attempt failed later. + val own = payments?.firstOrNull { it.id == uncertain.attemptId } + val listed = own?.takeIf { deciding?.status == PaymentStatus.FAILED } ?: deciding + if (send.status == PaymentStatus.FAILED) { + // Its row stayed pending while held, so it takes the failure now. + listed?.let { recordActivity(it, isOwnAttempt = it === own) } + } + when { + !isReported -> Unit + listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } + // A retry started after the hold was taken reads as pending, and its own event reports it. + listed.status == PaymentStatus.PENDING -> Unit + // A retry that entered Spark's send call since the hold was taken reports its own outcome. + listed.status == PaymentStatus.FAILED && isHeldFrom(listed) -> Unit + // The send's own outcome is claimed, so Spark's event for the same payment reports nothing more. + listed === own -> if (reportedSendIds.add(own.id)) own.toNodeEvent()?.let { _nodeEvents.emit(it) } + // A paid attempt is claimed, so Spark's event for the same payment reports nothing more. + listed.status == PaymentStatus.COMPLETED -> + if (reportedSendIds.add(listed.id)) listed.toNodeEvent()?.let { _nodeEvents.emit(it) } + // Another attempt's failure ends the send at its expiry, so it claims no payment. + else -> listed.toNodeEvent()?.let { _nodeEvents.emit(it) } + } + } + private suspend fun takeUncertainSend( paymentHash: String, uncertain: UncertainSend, diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 2e60238226..08322d3f81 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2020,7 +2020,7 @@ class LightningRepoTest : BaseUnitTest() { startNodeForTesting() val first = async { spark.payInvoice("bolt11", 1_000uL) } runCurrent() - verify(sparkService).send(prepared) + verify(sparkService).send(eq(prepared), any()) whenever(lightningService.channels).thenReturn(listOf(createChannelDetails().copy(isUsable = true))) val retry = sut.payInvoice("bolt11", 1_000uL) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index a04fc1d7b0..312d79dadd 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5024,7 +5024,11 @@ class SparkRepoTest : BaseUnitTest() { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } - val failed = sentPayment(fees = 0).copy(id = "some", status = PaymentStatus.FAILED, timestamp = sentAt.toULong()) + val failed = sentPayment(fees = 0).copy( + id = "some", + status = PaymentStatus.FAILED, + timestamp = sentAt.toULong(), + ) whenever(sparkService.listPayments()).thenReturn(listOf(failed)) val sut = createSut(store) sut.start(0).getOrThrow() From 627b6d520ac4ebb2958e5dcc0c430a148fab5184 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 13:15:12 +0100 Subject: [PATCH 3/5] chore: add changelog fragment Verified: none (changelog text only) --- changelog.d/next/2007.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2007.fixed.md diff --git a/changelog.d/next/2007.fixed.md b/changelog.d/next/2007.fixed.md new file mode 100644 index 0000000000..a091f792ba --- /dev/null +++ b/changelog.d/next/2007.fixed.md @@ -0,0 +1 @@ +Fixed Spark payment retries so a retry stays pending until its own outcome, and a payment settled while the app was closed no longer shows its result again at launch. From fa7c56b5efd0b34c79d3daf4355506f33a0adcde Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 13:49:49 +0100 Subject: [PATCH 4/5] fix: refuse a spark send while its synced list can't be read Also reports a send Spark never recorded at its expiry after a restart, keeps a newer retry's row from an old failure, keeps a failure's ownership through a failed activity write, and keeps Spark's callback for a hold settled while closed quiet. Verified: just compile, just test and just lint; SparkRepoTest and lint again after the last one-line change --- .../java/to/bitkit/repositories/SparkRepo.kt | 57 +++++++--- .../to/bitkit/repositories/SparkRepoTest.kt | 104 +++++++++++++++++- 2 files changed, 140 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6daa26df61..dd02499a75 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -179,6 +179,9 @@ class SparkRepo @Inject constructor( /** The invoice of each send still inside Spark's send call, by lowercase payment hash. */ private val sendsInFlight = ConcurrentHashMap() + /** Payment ids of failed attempts whose own details a failed write still has to save over an older row. */ + private val unsavedOwnFailures = ConcurrentHashMap.newKeySet() + /** Sends taken back at start, whose outcome Spark settled while the app was closed, so none is reported again. */ private val restoredAtStart = ConcurrentHashMap.newKeySet() @@ -318,6 +321,7 @@ class SparkRepo @Inject constructor( broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() + unsavedOwnFailures.clear() sendsInFlight.clear() uncertainSends.clear() restoredAtStart.clear() @@ -558,7 +562,10 @@ class SparkRepo @Inject constructor( val paymentHash = method.invoiceDetails.paymentHash val invoice = method.invoiceDetails val expiresAt = invoice.timestamp.safe() + invoice.expiry.safe() - when (val earlier = lightningSend(paymentHash)) { + // A caller asking for the invoice again waits for its outcome, also for a send settled while closed. + restoredAtStart.remove(paymentHash.lowercase()) + val earlier = lightningSend(paymentHash) + when (earlier) { is SparkLightningSend.Found if earlier.status == PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash @@ -575,6 +582,10 @@ class SparkRepo @Inject constructor( isFailedUnsent = canListPayments(), ) } + // A synced list that can't be read may hide a payment of the invoice, also one from another device. + if (earlier == SparkLightningSend.Unavailable && canListPayments()) { + throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() val isEntered = holdRestoreMutex.withLock { @@ -585,7 +596,6 @@ class SparkRepo @Inject constructor( try { // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. val attemptId = UUID.randomUUID().toString() - restoredAtStart.remove(paymentHash.lowercase()) val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) @@ -707,12 +717,13 @@ class SparkRepo @Inject constructor( // Only the caller that takes the hash off settles it, so its outcome is reported once. if (!isSettled) return false if (!takeUncertainSend(paymentHash, uncertain, send)) return true - // A send that settled while the app was closed updates its row only, as nobody waits for it now. + // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. val isReported = !restoredAtStart.remove(key) when (send) { + // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { // A retry that entered Spark's send call since the hold was taken reports its own outcome. - if (isReported && !sendsInFlight.containsKey(key)) { + if (!sendsInFlight.containsKey(key)) { _nodeEvents.emit( Event.PaymentFailed(paymentHash, paymentHash, PaymentFailureReason.UNEXPECTED_ERROR) ) @@ -740,10 +751,12 @@ class SparkRepo @Inject constructor( val listed = own?.takeIf { deciding?.status == PaymentStatus.FAILED } ?: deciding if (send.status == PaymentStatus.FAILED) { // Its row stayed pending while held, so it takes the failure now. - listed?.let { recordActivity(it, isOwnAttempt = it === own) } + // A retry that started since the hold was taken keeps its own row. + listed?.let { recordActivity(it, isOwnAttempt = it === own && !isHeldFrom(it)) } } when { - !isReported -> Unit + // Spark's event for the same payment, which can follow a reconnect, reports nothing either. + !isReported -> listed?.let { reportedSendIds.add(it.id) } listed == null -> settledSendEvent(paymentHash)?.let { _nodeEvents.emit(it) } // A retry started after the hold was taken reads as pending, and its own event reports it. listed.status == PaymentStatus.PENDING -> Unit @@ -2081,7 +2094,7 @@ class SparkRepo @Inject constructor( holdRestoreMutex.withLock { if (isFailed && isHeldFrom(payment)) return@withLock true uncertainSends.remove(hash.lowercase()) - restoredAtStart.remove(hash.lowercase()) + if (restoredAtStart.remove(hash.lowercase())) reportedSendIds.add(payment.id) cacheStore.removeSparkUncertainSend(hash) if (isReleased) cacheStore.removeSparkSendHash(hash) false @@ -2110,6 +2123,7 @@ class SparkRepo @Inject constructor( return true } val id = lightning.htlcDetails.paymentHash + val isOwn = payment.status == PaymentStatus.FAILED && (isOwnAttempt || payment.id in unsavedOwnFailures) // A send in doubt or in Spark's send call shows as pending until Spark settles it, whatever another attempt on // its invoice failed with. if (payment.status == PaymentStatus.FAILED && !isOwnAttempt && isHeldFrom(payment)) { @@ -2118,28 +2132,20 @@ class SparkRepo @Inject constructor( // A failed read would drop the stored note, contact and seen time, so the write waits for the next refresh. val stored = activityRepo.get().getActivity(id).getOrElse { unsavedPayments.add(payment.id) + if (isOwn) unsavedOwnFailures.add(payment.id) return false } val existing = (stored as? Activity.Lightning)?.v1 // A receive sharing its hash with a channel send is a move to Spark, which Activity shows as that send; // the completed receive proves the send settled. if (payment.paymentType == SparkPaymentType.RECEIVE && existing?.txType == PaymentType.SENT) { - if (payment.status != PaymentStatus.COMPLETED || existing.status == PaymentState.SUCCEEDED) return true - val settled = Activity.Lightning(existing.copy(status = PaymentState.SUCCEEDED)) - val saved = activityRepo.get().upsertActivity(settled) - .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } - if (!saved) { - unsavedPayments.add(payment.id) - return false - } - unsavedPayments.remove(payment.id) - return true + return settleMoveToSpark(payment, existing) } // Another attempt of the same invoice, on either rail, already paid it. if (existing?.status == PaymentState.SUCCEEDED && payment.status != PaymentStatus.COMPLETED) return true // A failure, possibly an earlier attempt's, only fails the send's row, which keeps its own details. val failedRow = existing?.takeIf { - payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT && !isOwnAttempt + payment.status == PaymentStatus.FAILED && it.txType == PaymentType.SENT && !isOwn } if (failedRow?.status == PaymentState.FAILED) return true val activity = failedRow?.copy(status = PaymentState.FAILED) ?: LightningActivity.create( @@ -2167,9 +2173,11 @@ class SparkRepo @Inject constructor( .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } if (!saved) { unsavedPayments.add(payment.id) + if (isOwn) unsavedOwnFailures.add(payment.id) return false } unsavedPayments.remove(payment.id) + unsavedOwnFailures.remove(payment.id) if (payment.paymentType == SparkPaymentType.SEND && payment.fees.toLong() == 0L) { sendsRecordedWithoutFee.add(payment.id) } else { @@ -2178,6 +2186,19 @@ class SparkRepo @Inject constructor( return true } + private suspend fun settleMoveToSpark(payment: Payment, send: LightningActivity): Boolean { + if (payment.status != PaymentStatus.COMPLETED || send.status == PaymentState.SUCCEEDED) return true + val settled = Activity.Lightning(send.copy(status = PaymentState.SUCCEEDED)) + val saved = activityRepo.get().upsertActivity(settled) + .let { it.isSuccess || it.exceptionOrNull() is ActivityDeletedError } + if (!saved) { + unsavedPayments.add(payment.id) + return false + } + unsavedPayments.remove(payment.id) + return true + } + /** * Records a withdrawal to a Paykit contact as an on-chain send, settling the journal entry it matches. Transfers to * Savings have no row here: the node lists their arrival as the transfer. diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 312d79dadd..3d6fe36fbc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -4164,7 +4164,7 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) val own = sentPayment(fees = 0).copy( - id = "own", + id = sentKey(), status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong(), ) @@ -4177,6 +4177,7 @@ class SparkRepoTest : BaseUnitTest() { val reads = ArrayDeque(listOf(listOf(own), listOf(own))) whenever(sparkService.listPayments()).thenAnswer { reads.removeFirstOrNull() ?: listOf(own, retry) } advanceUntilIdle() + verify(cacheStore).removeSparkUncertainSend("hash") val paid = retry.copy(status = PaymentStatus.COMPLETED) whenever(sparkService.listPayments()).thenReturn(listOf(own, paid)) @@ -4191,6 +4192,9 @@ class SparkRepoTest : BaseUnitTest() { val events = settleWithRetryEntering(mutableListOf()) assertTrue(events.none { it is Event.PaymentFailed }, "the earlier send's failure reached the retry's screen") + verify(activityRepo, never()).upsertActivity( + argThat { this is Activity.Lightning && v1.status == PaymentState.FAILED } + ) } @Test @@ -4731,7 +4735,7 @@ class SparkRepoTest : BaseUnitTest() { fun `a spark send that fails after its polling stopped no longer holds the node off`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) - val prepared = prepared(feeSats = 0uL) + val prepared = unexpiredPrepared() whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) whenever { sparkService.send(any(), anyOrNull()) }.thenAnswer { throw SdkException.Generic("timeout") } val sut = createSut() @@ -4743,7 +4747,11 @@ class SparkRepoTest : BaseUnitTest() { advanceUntilIdle() // Spark resumes the send later and it fails. - val failed = sentPayment(fees = 0).copy(status = PaymentStatus.FAILED, timestamp = now.epochSeconds.toULong()) + val failed = sentPayment(fees = 0).copy( + id = sentKey(), + status = PaymentStatus.FAILED, + timestamp = now.epochSeconds.toULong(), + ) whenever { sparkService.listPayments() }.thenReturn(listOf(failed)) sparkEvents.emit(SdkEvent.PaymentFailed(failed)) advanceUntilIdle() @@ -4938,6 +4946,9 @@ class SparkRepoTest : BaseUnitTest() { sut.start(0).getOrThrow() sparkEvents.emit(SdkEvent.Synced) advanceUntilIdle() + // Spark's own callback for the payment can follow the reconnect. + sparkEvents.emit(SdkEvent.PaymentFailed(failed)) + advanceUntilIdle() assertFalse("hash" in store.data.first().sparkUncertainSends) assertEquals( @@ -5044,6 +5055,93 @@ class SparkRepoTest : BaseUnitTest() { assertFalse("hash" in store.data.first().sparkUncertainSends, "the hold outlived its invoice") } + @Test + fun `a spark send is refused before it goes out while spark's synced list can't be read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sut = createSut(store) + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + // Another device may have paid the invoice, which only Spark's list would show. + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertFalse("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { + val sentAt = now.epochSeconds + // The app saved the hold, then died before Spark recorded the send. + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to sentAt + 3_600), + sparkUncertainSends = mapOf("hash" to sentAt), + sparkSendAttemptIds = mapOf("hash" to "attempt"), + ) + ), + clock, + ) + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + now += 2.hours + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a spark retry's own failure keeps its details through a failed activity write`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.Generic("timeout") } + whenever { activityRepo.getActivity(eq("hash"), any()) } + .thenReturn(Result.success(Activity.Lightning(storedSend(PaymentState.FAILED)))) + val sut = createSut() + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + val retryAt = now.epochSeconds.toULong() + val own = sentPayment(fees = 3).copy(id = sentKey(), status = PaymentStatus.FAILED, timestamp = retryAt) + whenever(sparkService.listPayments()).thenReturn(listOf(own)) + // The first write of the retry's failure fails. + var writes = 0 + whenever { activityRepo.upsertActivity(any()) }.doSuspendableAnswer { + if (writes++ == 0) Result.failure(SdkException.Generic("storage")) else Result.success(Unit) + } + sparkEvents.emit(SdkEvent.PaymentFailed(own)) + advanceUntilIdle() + + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + verify(activityRepo, atLeastOnce()).upsertActivity( + argThat { this is Activity.Lightning && v1.fee == 3uL && v1.timestamp == retryAt } + ) + } + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue From 2d68d2fc3e57465deb3151c7e3339b87df3b80f2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 24 Nov 2026 13:55:32 +0100 Subject: [PATCH 5/5] fix: mute spark holds only on the first start of the process Verified: just compile, just test and just lint pass --- .../java/to/bitkit/repositories/SparkRepo.kt | 8 ++++- .../to/bitkit/repositories/SparkRepoTest.kt | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index dd02499a75..f00c626747 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -185,6 +185,9 @@ class SparkRepo @Inject constructor( /** Sends taken back at start, whose outcome Spark settled while the app was closed, so none is reported again. */ private val restoredAtStart = ConcurrentHashMap.newKeySet() + @Volatile + private var hasRestoredAtStart = false + /** Spark payment ids of the sends whose outcome was reported, so the poll and Spark's event report it once. */ private val reportedSendIds = ConcurrentHashMap.newKeySet() @@ -278,7 +281,9 @@ class SparkRepo @Inject constructor( _state.update { it.copy(hasStartFailed = false) } runSuspendCatching { collectEvents() - restoreUncertainSends(atStart = true) + // Only the first start of the process takes back holds that settled while the app was closed. + restoreUncertainSends(atStart = !hasRestoredAtStart) + hasRestoredAtStart = true val isExiting = exitStore(walletIndex).isActive() _state.update { it.copy(isExiting = isExiting) } val connected = sparkService.connect(walletIndex, isExiting) @@ -325,6 +330,7 @@ class SparkRepo @Inject constructor( sendsInFlight.clear() uncertainSends.clear() restoredAtStart.clear() + hasRestoredAtStart = false hasSyncedActivities = false hasMergedRemoteExitState = false isLostForExit = false diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3d6fe36fbc..a451196628 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5142,6 +5142,42 @@ class SparkRepoTest : BaseUnitTest() { ) } + @Test + fun `a cancelled spark send restored by a foreground restart reports its failure at expiry`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { awaitCancellation() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + val send = launch { sut.payInvoice("lnbc1", 100uL) } + runCurrent() + send.cancel() + advanceUntilIdle() + + // The node restarts in the foreground in the same process, which starts Spark again while it stays connected. + sut.start(0).getOrThrow() + advanceUntilIdle() + + // Spark never lists the send, and syncs after its invoice expired. + now += 2.hours + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertFalse("hash" in store.data.first().sparkUncertainSends, "a cancelled send stayed held past expiry") + assertEquals( + 1, + events.count { it is Event.PaymentFailed }, + "a send cancelled in this process was taken as settled while the app was closed", + ) + } + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue