From d2b834f5903fa16864086d1182cf00931ae40642 Mon Sep 17 00:00:00 2001 From: Marcos Date: Thu, 1 Oct 2026 18:27:33 +0200 Subject: [PATCH] fix: add Failed status for unrealized channel promotions and implement related logic --- src/Data/Models/ChannelOpenRecommendation.cs | 6 +- .../ChannelOpenRecommendationRepository.cs | 30 +++++ .../IChannelOpenRecommendationRepository.cs | 7 ++ src/Jobs/AutoChannelOpenJob.cs | 9 ++ ...hannelOpenRecommendationRepositoryTests.cs | 110 ++++++++++++++++++ .../Jobs/AutoChannelOpenJobTests.cs | 22 ++++ 6 files changed, 183 insertions(+), 1 deletion(-) diff --git a/src/Data/Models/ChannelOpenRecommendation.cs b/src/Data/Models/ChannelOpenRecommendation.cs index 2e6c847b..1c304326 100644 --- a/src/Data/Models/ChannelOpenRecommendation.cs +++ b/src/Data/Models/ChannelOpenRecommendation.cs @@ -42,7 +42,11 @@ public enum ChannelOpenRecommendationStatus Dismissed = 2, /// Not reproduced by the latest run. Re-opened in place if the demand returns. - Expired = 3 + Expired = 3, + + /// Promoted, but the channel never opened — the request failed or was cancelled. Unlike a + /// dismissal this says nothing about the peer, so it leaves no cooldown behind. + Failed = 4 } /// How a recommendation's channel size was derived. diff --git a/src/Data/Repositories/ChannelOpenRecommendationRepository.cs b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs index 7c01dd18..fe1b48be 100644 --- a/src/Data/Repositories/ChannelOpenRecommendationRepository.cs +++ b/src/Data/Repositories/ChannelOpenRecommendationRepository.cs @@ -164,6 +164,36 @@ public async Task ExpireOpen(int nodeId) .SetProperty(x => x.UpdateDatetime, DateTimeOffset.UtcNow)); } + public async Task FailUnrealizedPromotions(int nodeId) + { + await using var context = await _dbContextFactory.CreateDbContextAsync(); + + // Rejected is an operator turning the peer down and Cancelled is not, so only the latter joins + // Failed here — a rejection suppresses the peer exactly as a dismissal does. + var unrealized = await context.ChannelOpenRecommendations + .Where(x => x.NodeId == nodeId + && x.Status == ChannelOpenRecommendationStatus.Promoted + && x.ChannelOperationRequest != null + && (x.ChannelOperationRequest.Status == ChannelOperationRequestStatus.Failed + || x.ChannelOperationRequest.Status == ChannelOperationRequestStatus.Cancelled)) + .ToListAsync(); + + if (unrealized.Count == 0) + { + return 0; + } + + foreach (var recommendation in unrealized) + { + recommendation.Status = ChannelOpenRecommendationStatus.Failed; + recommendation.SetUpdateDatetime(); + } + + await context.SaveChangesAsync(); + + return unrealized.Count; + } + public async Task> GetLastDecisionByPeer(int nodeId) { await using var context = await _dbContextFactory.CreateDbContextAsync(); diff --git a/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs b/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs index 70ac390b..5752b8bc 100644 --- a/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs +++ b/src/Data/Repositories/Interfaces/IChannelOpenRecommendationRepository.cs @@ -41,6 +41,13 @@ public interface IChannelOpenRecommendationRepository /// Task ExpireOpen(int nodeId); + /// + /// Flips a Promoted row whose channel never opened to Failed. The promotion was a + /// decision to fund the peer, not a verdict on it, so once it comes to nothing it must stop + /// feeding — hence this runs ahead of it every cycle. + /// + Task FailUnrealizedPromotions(int nodeId); + /// /// Feeds the per-peer cooldown, which is what stops a drained sink peer being re-proposed every run. /// diff --git a/src/Jobs/AutoChannelOpenJob.cs b/src/Jobs/AutoChannelOpenJob.cs index 31e81802..a1cb4fc7 100644 --- a/src/Jobs/AutoChannelOpenJob.cs +++ b/src/Jobs/AutoChannelOpenJob.cs @@ -132,6 +132,15 @@ private async Task ProcessNode(Node node, decimal feeRate) node.Name, expired); } + // Ahead of the cooldown this run derives: a promotion whose channel never opened committed + // nothing to the peer, so leaving it Promoted would suppress the peer for a channel it never got. + var unrealized = await _recommendationRepository.FailUnrealizedPromotions(node.Id); + if (unrealized > 0) + { + _logger.LogInformation("Node {NodeName}: {Count} promoted recommendation(s) whose channel never opened marked failed, releasing their peers from the cooldown", + node.Name, unrealized); + } + // Check if a wallet is set to the node, otherwise we cannot proceed with channel opening. if (node.AutoChannelOpenWalletId == null) { diff --git a/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs b/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs index c94c8f35..0db2f9f5 100644 --- a/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs +++ b/test/NodeGuard.Tests/Data/Repositories/ChannelOpenRecommendationRepositoryTests.cs @@ -109,6 +109,24 @@ public async Task Upsert_DismissedRow_IsRecycledAndTheReasonCleared() persisted.SuggestedCapacitySats.Should().Be(4_000_000); } + [Fact] + public async Task Upsert_FailedRow_IsRecycledAndTheLinkCleared() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add( + Stored(ChannelOpenRecommendationStatus.Failed, requestId: 55)); + await seed.SaveChangesAsync(); + + var (persisted, error) = await sut.Upsert(Plan()); + + // The peer never got the channel and carries no cooldown, so the next run that still sees the + // demand must be able to propose it again. + error.Should().BeNull(); + persisted!.Status.Should().Be(ChannelOpenRecommendationStatus.Open); + persisted.SuggestedCapacitySats.Should().Be(4_000_000); + persisted.ChannelOperationRequestId.Should().BeNull(); + } + [Fact] public async Task Upsert_PromotedRowWhoseOpenIsStillUnresolved_IsLeftUntouched() { @@ -251,4 +269,96 @@ public async Task GetLastDecisionByPeer_IgnoresOpenAndExpiredRows() // cooldown nobody asked for, and the demand would stay unproposed for the whole window. result.Should().BeEmpty(); } + + [Fact] + public async Task GetLastDecisionByPeer_IgnoresFailedRows() + { + var (sut, seed) = SetupDb(); + seed.ChannelOpenRecommendations.Add(Row(NodeId, Peer, ChannelOpenRecommendationStatus.Failed)); + await seed.SaveChangesAsync(); + + var result = await sut.GetLastDecisionByPeer(NodeId); + + // The whole point of the status: a promotion that produced no channel must not suppress the + // peer, or the demand behind it goes unserved for the length of the cooldown. + result.Should().BeEmpty(); + } + + [Theory] + [InlineData(ChannelOperationRequestStatus.Failed)] + [InlineData(ChannelOperationRequestStatus.Cancelled)] + public async Task FailUnrealizedPromotions_PromotedRowWhoseChannelNeverOpened_IsMarkedFailed( + ChannelOperationRequestStatus unrealized) + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = unrealized + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + count.Should().Be(1); + var stored = await seed.ChannelOpenRecommendations.AsNoTracking().SingleAsync(); + stored.Status.Should().Be(ChannelOpenRecommendationStatus.Failed); + } + + [Theory] + [InlineData(ChannelOperationRequestStatus.Pending)] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmationPending)] + [InlineData(ChannelOperationRequestStatus.OnChainConfirmed)] + [InlineData(ChannelOperationRequestStatus.Rejected)] + public async Task FailUnrealizedPromotions_PromotedRowWhoseOpenIsLiveOrDecided_StaysPromoted( + ChannelOperationRequestStatus kept) + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = kept + }); + seed.ChannelOpenRecommendations.Add(Stored(ChannelOpenRecommendationStatus.Promoted, requestId: 55)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + // An open still on its way keeps its peer suppressed so the run cannot double the intent, and + // a rejection is an operator turning the peer down — a decision, like a dismissal. + count.Should().Be(0); + var stored = await seed.ChannelOpenRecommendations.AsNoTracking().SingleAsync(); + stored.Status.Should().Be(ChannelOpenRecommendationStatus.Promoted); + } + + [Fact] + public async Task FailUnrealizedPromotions_LeavesOtherNodesAndUnpromotedRowsAlone() + { + var (sut, seed) = SetupDb(); + seed.ChannelOperationRequests.Add(new ChannelOperationRequest + { + Id = 55, + RequestType = OperationRequestType.Open, + Status = ChannelOperationRequestStatus.Failed + }); + var otherNodesRow = Row(2, "03otherNode", ChannelOpenRecommendationStatus.Promoted); + otherNodesRow.ChannelOperationRequestId = 55; + seed.ChannelOpenRecommendations.AddRange( + otherNodesRow, + Row(NodeId, "03dismissed", ChannelOpenRecommendationStatus.Dismissed), + Row(NodeId, "03open", ChannelOpenRecommendationStatus.Open)); + await seed.SaveChangesAsync(); + + var count = await sut.FailUnrealizedPromotions(NodeId); + + count.Should().Be(0); + var statuses = await seed.ChannelOpenRecommendations.AsNoTracking() + .ToDictionaryAsync(x => x.PeerPubKey, x => x.Status); + statuses["03otherNode"].Should().Be(ChannelOpenRecommendationStatus.Promoted); + statuses["03dismissed"].Should().Be(ChannelOpenRecommendationStatus.Dismissed); + statuses["03open"].Should().Be(ChannelOpenRecommendationStatus.Open); + } } diff --git a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs index 70454411..b2b84adf 100644 --- a/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs +++ b/test/NodeGuard.Tests/Jobs/AutoChannelOpenJobTests.cs @@ -124,6 +124,7 @@ private Node ArrangeQualifyingDemand( _nodeRepository.Setup(x => x.GetAllWithAutoChannelOpenEnabled()).ReturnsAsync(new List { node }); _nbXplorerService.Setup(x => x.GetFeesByType(MempoolRecommendedFeesType.HourFee, default)).ReturnsAsync(10m); _recommendationRepository.Setup(x => x.ExpireOpen(NodeId)).ReturnsAsync(0); + _recommendationRepository.Setup(x => x.FailUnrealizedPromotions(NodeId)).ReturnsAsync(0); _channelOperationRequestRepository .Setup(x => x.GetOpenSatsCommittedSince(NodeId, It.IsAny())) .ReturnsAsync(committedSats); @@ -266,6 +267,27 @@ public async Task Execute_DemandClearsEveryGate_ExpiresFirstThenRecords() VerifyRecorded(Times.Once()); } + [Fact] + public async Task Execute_UnrealizedPromotions_AreReleasedBeforeTheCooldownIsRead() + { + ArrangeQualifyingDemand(); + var released = false; + var cooldownSawTheRelease = false; + _recommendationRepository.Setup(x => x.FailUnrealizedPromotions(NodeId)) + .ReturnsAsync(1) + .Callback(() => released = true); + _recommendationRepository.Setup(x => x.GetLastDecisionByPeer(NodeId)) + .ReturnsAsync(new Dictionary()) + .Callback(() => cooldownSawTheRelease = released); + + await Run(); + + // The cooldown is derived from the stored statuses, so a promotion that came to nothing has to + // be cleared first or its peer stays suppressed for a channel it never got. + released.Should().BeTrue(); + cooldownSawTheRelease.Should().BeTrue(); + } + [Fact] public async Task Execute_BudgetExhausted_StillExpiresAndRecordsNothing() {