Skip to content
Open
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
102 changes: 83 additions & 19 deletions swapclientserver/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ type swapClientService struct {
// and duplicate in-flight checks before swap creation mutates remote
// swapdk-server state.
chainParams *chaincfg.Params

// workerRetryDelay is the pause between daemon-owned attempts to resume
// a durable swap that remains pending after a transient driver error.
// Keeping the delay on the service makes the retry loop deterministic
// in tests without moving retry policy into the swap FSM.
workerRetryDelay time.Duration
}

// receiveScanKey orders durable receives by creation time and payment hash.
Expand All @@ -194,6 +200,8 @@ const (
receiveRefillRetryDelay = time.Second
)

const defaultWorkerRetryDelay = time.Second

// operatorPubKeyFetcher returns the current Ark operator pubkey. It exists so
// daemon-hosted swap clients can bypass the cached GetInfo snapshot when they
// construct fresh vHTLC policies.
Expand Down Expand Up @@ -720,6 +728,7 @@ func newSwapClientService(ctx context.Context, rpcServer *waved.RPCServer,
receiveMinAmount: minAmount,
payMinAmount: minAmount,
chainParams: chainParams,
workerRetryDelay: defaultWorkerRetryDelay,
}
service.pendingReceiveSet = make(map[string]struct{})

Expand Down Expand Up @@ -2280,18 +2289,18 @@ func (s *swapClientService) startPayWorker(hash lntypes.Hash) {
defer s.markInactive(key)
defer s.publishHash(hash)

session, err := s.client.ResumePayViaLightning(s.rootCtx, hash)
if err != nil {
s.log.Warnf("unable to resume pay swap %s: %v", key,
err)
s.runSwapWorker(hash, "pay", func(ctx context.Context) error {
session, err := s.client.ResumePayViaLightning(
ctx, hash,
)
if err != nil {
return err
}

return
}
_, err = session.Wait(ctx)

_, err = session.Wait(s.rootCtx)
if err != nil && !errors.Is(err, context.Canceled) {
s.log.Warnf("pay swap %s stopped: %v", key, err)
}
return err
})
})
}

Expand Down Expand Up @@ -2331,21 +2340,76 @@ func (s *swapClientService) runReceiveWorker(hash lntypes.Hash, key string) {
defer s.finishReceiveWorker(key)
defer s.publishHash(hash)

session, err := s.client.ResumeReceiveViaLightning(
s.rootCtx, hash,
s.runSwapWorker(
hash, "receive",
func(ctx context.Context) error {
session, err :=
s.client.ResumeReceiveViaLightning(
ctx, hash,
)
if err != nil {
return err
}

_, err = session.Wait(ctx)

return err
},
)
if err != nil {
s.log.Warnf("unable to resume receive swap %s: %v", key,
err)
})
}

// runSwapWorker drives one durable swap until the SDK reports success, the
// persisted FSM becomes terminal, or the daemon stops. A Wait or resume error
// alone is not terminal: transport loss can interrupt the process-local driver
// while the durable FSM remains resumable.
func (s *swapClientService) runSwapWorker(hash lntypes.Hash, direction string,
drive func(context.Context) error) {

key := hex.EncodeToString(hash[:])
for {
err := drive(s.rootCtx)
Comment on lines +2370 to +2371

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Requeue failed receives instead of monopolizing worker slots

When a receive driver errors while its durable summary remains pending, this loop retries without returning, so the deferred finishReceiveWorker never releases activeReceives or transfers the slot to the FIFO. If the pool is saturated—especially with MaxActiveReceiveSwaps=1—one permanently failing session can prevent every queued or overflow receive from ever being attempted; requeue the failed hash behind the existing backlog before retrying it.

AGENTS.md reference: swapclientserver/AGENTS.md:L97-L105

Useful? React with 👍 / 👎.

if err == nil || errors.Is(err, context.Canceled) ||
s.rootCtx.Err() != nil {
return
}

summary, summaryErr := s.client.GetSwapSummary(s.rootCtx, hash)
if errors.Is(summaryErr, swaps.ErrSwapSummaryNotFound) {
return
}
if summaryErr == nil && !summary.Pending {
return
}

_, err = session.Wait(s.rootCtx)
if err != nil && !errors.Is(err, context.Canceled) {
s.log.Warnf("receive swap %s stopped: %v", key, err)
if summaryErr != nil {
s.log.Warnf("%s swap %s stopped and durable state "+
"could not be checked: %v (driver error: %v)",
direction, key, summaryErr, err)
} else {
s.log.Warnf("%s swap %s stopped while still pending; "+
"retrying: %v", direction, key, err)
Comment on lines +2390 to +2391

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Lower the severity of recurring retry messages

During a sustained transport or mailbox outage, every pending worker reaches this branch once per second indefinitely, generating repeated Warn alerts rather than one actionable event; with the receive pool at its default size this can produce more than a hundred warnings per second, plus any pay workers. Emit recurring retry noise at Info/Debug or rate-limit it so an outage does not flood operator alerts.

AGENTS.md reference: AGENTS.md:L38-L41

Useful? React with 👍 / 👎.

}
})

delay := s.workerRetryDelay
if delay <= 0 {
delay = defaultWorkerRetryDelay
}
timer := time.NewTimer(delay)
select {
case <-s.rootCtx.Done():
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}

return

case <-timer.C:
}
}
}

// markActive records that the daemon has an in-process worker responsible for
Expand Down
45 changes: 44 additions & 1 deletion swapclientserver/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,39 @@ func TestStartReceiveReleasesReservationOnCreationFailure(t *testing.T) {
require.True(t, service.reserveReceiveWorker())
}

// TestReceiveWorkerRetriesWhileDurableSwapIsPending verifies a transient
// process-local Wait failure does not strand a resumable receive FSM until the
// daemon restarts. The worker keeps ownership across the retry and resumes the
// same payment hash once more.
func TestReceiveWorkerRetriesWhileDurableSwapIsPending(t *testing.T) {
t.Parallel()

receiveHash := testHash(3)
fakeClient := newFakeSwapRuntime(swaps.SwapSummary{
Direction: swaps.SwapDirectionReceive,
PaymentHash: receiveHash,
State: "claim_initiated",
Pending: true,
})
fakeClient.receiveResumeSessions = []receiveSwapSession{
&fakeReceiveSession{
hash: receiveHash,
waitErr: errors.New("temporary mailbox disconnect"),
},
&fakeReceiveSession{
hash: receiveHash,
},
}
service := newTestSwapClientService(fakeClient)
service.workerRetryDelay = 10 * time.Millisecond
defer service.cancel()

service.startReceiveWorker(receiveHash)
fakeClient.awaitReceiveResume(t, receiveHash)
fakeClient.awaitReceiveResume(t, receiveHash)
require.Equal(t, 2, fakeClient.receiveResumeCount(receiveHash))
}

// TestChainParamsForNetworkAcceptsTestNet4 verifies the swapruntime daemon
// subserver accepts every network string the main daemon config advertises.
func TestChainParamsForNetworkAcceptsTestNet4(t *testing.T) {
Expand Down Expand Up @@ -1967,6 +2000,7 @@ type fakeSwapRuntime struct {
payResumeCalls map[lntypes.Hash]int
receiveResumeCalls map[lntypes.Hash]int
receiveDone map[lntypes.Hash]chan struct{}
receiveResumeSessions []receiveSwapSession

payResumeCh chan lntypes.Hash
receiveResumeCh chan lntypes.Hash
Expand Down Expand Up @@ -2066,6 +2100,10 @@ func (f *fakeSwapRuntime) ResumeReceiveViaLightning(ctx context.Context,

f.receiveResumeCalls[hash]++
f.receiveResumeCh <- hash
resumeIndex := f.receiveResumeCalls[hash] - 1
if resumeIndex < len(f.receiveResumeSessions) {
return f.receiveResumeSessions[resumeIndex], nil
}

return &fakeReceiveSession{hash: hash, done: f.receiveDone[hash]}, nil
}
Expand Down Expand Up @@ -2269,6 +2307,7 @@ type fakeReceiveSession struct {
done <-chan struct{}
hash lntypes.Hash
invoice string
waitErr error
}

func (f *fakeReceiveSession) PaymentHash() lntypes.Hash {
Expand All @@ -2283,9 +2322,13 @@ func (f *fakeReceiveSession) Invoice() string {
func (f *fakeReceiveSession) Wait(ctx context.Context) (*swaps.ReceiveResult,
error) {

if f.waitErr != nil {
return nil, f.waitErr
}

select {
case <-f.done:
return nil, errors.New("temporary receive failure")
return nil, nil

case <-ctx.Done():
}
Expand Down
Loading