Repository navigation
fix: release the old node on each restart - #1395
Conversation
Takes ldk-node 0.7.0-rc.81, which keeps the runtime alive until detached work ends. Verified: none (unit suite runs next on m1a)
The event loop awaited nextEventAsync(), which cannot be cancelled and never returns once its node stops, so every restart kept the stopped node, its runtime and a loop alive. Poll nextEvent() in a stored task that is cancelled when the node changes, is cleared or fails to start, and that ends once its node is no longer current. Verified: none (unit suite runs next on m1a)
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 86131400ed
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
[Medium impact] The change reaches Lightning node startup and restart workflows. The PR appears safe to merge, with a non-blocking test gap around releasing old nodes. Findings
SummaryReplaces the uncancellable event wait with polling tied to one node.
ovitrif explicitly acknowledged unsynchronized access to Reviews (1) · Last reviewed commit: "fix: release the old node on each restar..." · Reviewed by Greptile |
|
Retargeted to master: #1394 is approved and merges first, so its commit drops out of this diff once it lands. |
{"kind":"bitkit-retarget-execution-v1","repository":"synonymdev/bitkit-ios","pr":1395,"generation":"45188365721-1","sourceSha":"f17214e929dce5d3cbf62434e92d7f45bc418de7","sourceRef":"master","owner":"github-actions[bot]"}
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Replaces the uncancellable nextEventAsync() await with a 100 ms nextEvent() poll bound to the node it was started for, cancelled whenever node changes, is cleared, fails to start, or a new loop starts. Reviewed 86131400, full tier, static: bitkit-ios does not build on Linux, so the PR was not built or run here.
What I checked, and 6 candidates I ruled out
Read in full: LightningService.swift lifecycle (setup, restart, restartWithPreviousConfig, start, stop, stopReleasingFinishedNode) and listenForEvents; the ldk-node 0.7.0-rc.81 Swift binding for nextEvent() -> Event? (non-blocking) and nextEventAsync().
Call sites traced: listenForEvents has one caller (start); every write to node (setup L308, restart/recovery L334/L369, stop L456) goes through the didSet cancel.
CI: SwiftFormat green, Run Tests pending at review time.
Ruled out
- Deadlock on
eventLoopLock:didSetandlistenForEventseach take the lock once, neither setsnodeor re-enters while holding it, and the task body never touches the lock. - Old loop handling the new node's events: the loop captures its own
nodeand exits onself.node !== node, and thedidSetcancels it before the new loop starts. - Loop left running after a failed
start():cancelEventLoop()runs in the catch, and the loop also exits once a laterstop()clearsnode. - Polling before
node.start():nextEvent()only pops the event queue, so events already queued before start are handled exactly as the old await handled them, and an empty queue just sleeps. - Event dropped on cancel: cancellation is checked only at the loop head, so an event already taken is marked handled and delivered.
- Unlocked cross-thread read of
self.nodein the loop condition: the same unlocked access existed before and the PR lists it under Out of Scope.
Merge confidence: 4/5, no test exercises the loop's lifecycle and Run Tests was still pending; manual test 1 (Memory Graph) is the evidence that would close it.
Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the review runtime does not report it to the reviewer)
coreyphillips
left a comment
There was a problem hiding this comment.
Two independent reviews.
worth doing, does not block
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. - A redundant start disables events on the running node (Bitkit/Services/LightningService.swift:405-407)
the reviewers disagree, your call
- A failed start() on a running node cancels that node's only event loop (Bitkit/Services/LightningService.swift:398-407)
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR diff against its merge base, at 8613140. The diff includes the ldk-node 0.7.0-rc.81 bump from the dependency #1394 (45ff9d4, an ancestor of this head). For #1394, only the contract this PR relies on was checked, not a full review.
No new actionable code findings.
No new actionable code findings. The new event loop matches the ldk-node source at v0.7.0-rc.81 (366d56e):
nextEvent()only reads the front of the queue under a mutex and does not block.eventHandled()pops and persists the event exactly as it did before this change.- The loop holds a strong reference to its node while it runs. The old node is only dropped, and its runtime only closed, after the loop exits, so
eventHandled()cannot reach the closed-runtime panic inRuntime::block_on. - Every write to
node(setup, restart, recovery, stop) goes through thedidSetcancel. Cancellation is checked only at the top of the loop, so an event already taken is still delivered. - The payment and on-chain handlers run in their own unstructured tasks, which do not inherit the loop's cancellation.
Open review concern, mechanism verified (not repeated as a new finding): A failed start() on a running node cancels that node's only event loop (also this thread). At this head, listenForEvents cancels the running node's loop (LightningService.swift:2448). node.start() then throws AlreadyRunning, and the catch at :405-407 cancels the replacement loop. The running node is left with no loop. Payment, channel and sync events stay in the persisted queue and are not handled until the next restart. Before this change, the same call left a duplicate loop instead. Reaching it takes a LightningService.restart() call (Settings Electrum/RGS, the LDK debug screen, or post-migration), which does not take WalletViewModel's lifecycle lock or update its state, overlapping with a WalletViewModel.start() while the wallet state is still .stopped or .errorStarting. Example: the user changes the Electrum server after a failed start, then returns from the background before a sync event moves the state to .running. Reachability is timing-dependent and was established by reading the code, not reproduced. Suggested fix: skip cancelEventLoop() for NodeError.AlreadyRunning, or keep an existing uncancelled loop that is bound to the same node.
Existing concern, already present before this PR: stop() returns before the cancelled loop has finished with the stopped node. The overlap of an in-flight eventHandled() persist with the next node's setup() existed at the base in a wider form. This PR narrows it rather than introducing it.
Not promoted: the ServiceQueue comment. nextEvent() is a non-blocking, mutex-guarded read, and the base loop already called the blocking eventHandled() outside ServiceQueue(.ldk). No hazard was demonstrated, so this is a convention point rather than a defect.
Coverage: LightningServiceTests only covers stopReleasingFinishedNode. No test asserts that the loop ends, that its node is released, or that a repeated start() leaves exactly one loop (see this thread). Because Node is a concrete FFI class, a unit regression test would need the loop extracted behind an injectable event source. Until then, author manual test 1 is the check that would show it.
Android parity: compared against LightningService.kt on bitkit-android master at e71a339. Android also binds its loop to the node it was started for (node === this.node), and its stop() waits for the listener job with cancelAndJoin before stopping the node. That difference is what leaves the existing stop() concern open on iOS only.
Validation: on this head, Run Tests, Run Integration Tests and SwiftFormat passed. The e2e-status failure is a CI infrastructure failure: Simulator.app was missing on the runner, the session never started and no specs ran. It is neither evidence for nor against this change. No build was run in this review, because the reviewer runs on Linux. The prebuilt LDKNode xcframework was not inspected; only its Rust and Swift binding source at the pinned tag was. Not established: which thread releases the old Node last. That matters because ldk-node's drop path can block for up to 5 s while draining stuck detached work.
Device testing: not performed in this review.
Suggested additional test cases
- iOS, regtest, node running: in Settings → Advanced → Electrum, reconnect to the current server, then immediately background the app and bring it back. Then receive a Lightning payment. Expected: the payment appears once in Activity and the balance updates without restarting the app.
- iOS, regtest: restart the node several times from Dev Settings → LDK while an on-chain transaction is confirming. Expected: each received or confirmed event produces a single activity update, with no duplicate entries after the restarts.
Reviewer model: claude-opus-5-5
Reasoning effort: high
- start() cancelled the event loop on any failure of node.start(), including AlreadyRunning, which left a node that keeps running without one. It now keeps the loop then. - stop() returned while the cancelled loop could still be handling an event of the stopped node, so the next node could load a queue that still held it and deliver it again. stop() now waits up to 5 s for the loop to end. Verified: swiftformat --lint; build and unit suite run next.
ServiceQueue wraps the error of node.start() in AppError, so the AlreadyRunning check never matched and a redundant start still cancelled the running node's loop. A new loop now also waits for the one it replaces, so both never handle the same event, and stop() clears the node only after its loop ended. Verified: swiftformat --lint
@coreyphillips @piotr-iohk Addressed in 7a75ac7 and 787467c: |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 8613140, including affected code paths and prior findings, at 787467c. Baseline: QA review.
No new actionable code findings.
No new actionable code findings in the follow-up.
The follow-up keeps the running node's loop when node.start() throws AlreadyRunning, including the AppError wrapper from ServiceQueue, and a replacement loop waits until the previous loop finishes the event it already took. The resolved threads A failed start() on a running node cancels that node's only event loop and A redundant start disables events on the running node are marked resolved. At this head that catch leaves the running node's loop in place. This is source analysis of LightningService.swift, not a runtime reproduction.
#1397 asks stop() to wait for the in-flight loop, with a bound because eventHandled() can block on a VSS write. stop() now cancels the loop and waits up to 5 seconds before clearing node. Past that bound it logs, clears node, and the next loop polls without waiting for the task already removed from eventLoopTask. When stop() throws, restart() still clears node in its existing catch, with no wait. That catch is unchanged from the baseline.
The ldk-node 0.7.0-rc.81 bump and the changelog fragments are unchanged since the baseline. For bitkit-ios#1394 at 45ff9d4, this follow-up checked only the AlreadyRunning and event-queue contracts at ldk-node 366d56e, not a full review of that pull request. nextEvent() still only clones the front of the in-memory queue. Node::start returns AlreadyRunning both when the node is already running and when detached work has not drained.
Android parity: LightningService.kt at e71a339 joins its listener before node.stop(). iOS waits after node.stop(), for up to 5 seconds.
The new LightningServiceTests cover waitForEnd and isAlreadyRunning. They do not drive the loop. Author manual test 1 remains the check that one payment is shown and one LDKNode.Node remains after repeated restarts. The author reports LightningServiceTests passed on this commit. This review did not run the suite.
Ready for device testing.
Device testing: not performed in this review.
Reviewer model: grok-4.7
Reasoning effort: xhigh
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 2 new commits (7a75ac7, 787467c). Nothing blocking remains.
addressed
- A failed start() on a running node cancels that node's only event loop (Bitkit/Services/LightningService.swift:398-407). Fixed:
start()at LightningService.swift:408-414 now skipscancelEventLoop()whenSelf.isAlreadyRunning(error).isAlreadyRunning(:2706-2715) unwrapsAppError.underlyingError, andAppError(ldkError:)(Errors.swift:243-244), whichServiceQueue.queueErroruses, keeps theNodeError. The replacement loop installed at :2457-2463 waits for the old one and then keeps running for the node. I confirmed this by reading the code and the new unwrap test, and did not run it locally (no simulator tooling here). - A redundant start disables events on the running node (Bitkit/Services/LightningService.swift:405-407). Fixed: This is the same fix as point 1. A redundant
start()replaces the loop at :2457-2463, where the new loop awaits the old one, and theAlreadyRunningexemption at :410 keeps that replacement. The node is left with exactly one loop instead of none.
still open
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. Codex still sees it: Bitkit/Services/LightningService.swift:464-467 still clears the node after a five-second timeout. Nothing then preventsrestart()from building the replacement while the old loop'seventHandled()write remains unfinished.
new since the last review
worth doing, does not block
- A failed start() cancels whichever loop is current, possibly another start's (Bitkit/Services/LightningService.swift:408-414)
- Timer cancellation can report a false shutdown timeout (Bitkit/Services/LightningService.swift:2694-2701)
@coreyphillips This one is addressed at this head: |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since 787467c. Nothing blocking remains.
still open
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. Codex still sees it: The reply identifies an existing bounded wait, but Bitkit/Services/LightningService.swift:464-467 still clearsnodeafter a timeout. SincecancelEventLoop()clears the task handle at line 2676, an unfinished old loop can still overlap replacement setup. - A failed start() cancels whichever loop is current, possibly another start's (Bitkit/Services/LightningService.swift:408-414). The catch in
start()callscancelEventLoop(), which cancels whatevereventLoopTaskholds at that moment. That can be a loop installed by a concurrentstart()on the same node, not the one this call installed. Since 787467c onlyAlreadyRunningis exempt, so any other start error can still leave a running node with no loop. An interleaving that does this, between aLightningService.restart()(which bypassesWalletViewModel's lifecycle lock) and aNodeRestarterwallet start on the node the restart just built:restart: listenForEvents -> LB wallet: listenForEvents -> LA (cancels LB) .ldk: wallet node.start() fails, e.g. fee-rate update with Electrum down wallet: catch -> cancelEventLoop() cancels LA .ldk: restart node.start() succeedsThe node is now running witheventLoopTask == nil. The restart reports success and the wallet is.errorStarting. Events stay in the persisted queue until a later wallet retry installs a loop (it then getsAlreadyRunningand keeps it) or the node restarts. This needs twonode.start()calls on the same node to straddle a transient failure. I found it by reading LightningService.swift:401-414 and :2671-2679 and did not reproduce it. Possible fix: havelistenForEventsreturn the task it installs, and in the catch cancel it only ifeventLoopTaskis still that task (compared undereventLoopLock). The catch at LightningService.swift:408-414 is unchanged. It still calls cancelEventLoop(), which cancels whatever eventLoopTask holds, including a loop a concurrent start() installed. @ovitrif agreed and moved the fix to the rc.82 follow-up. That is a deferral, not a rebuttal, so the point stays open at this head. - Timer cancellation can report a false shutdown timeout (Bitkit/Services/LightningService.swift:2694-2701).
waitForEndcan returnfalsefor an already-completed task. Cancelling the timer wakes its sleep, andtry?letsresume(false)race the followingresume(true). Using the unchanged helper, I reproduced 6 false results in 32,000 waits on already-completed tasks with ten-second timeouts. This produces false shutdown warnings. WaitForEnd at LightningService.swift:2694-2701 is unchanged.try? await Task.sleepfollowed byresume(false)still lets the cancelled timer race the watcher'sresume(true). @ovitrif confirmed the race and deferred the fix to the rc.82 follow-up, so it is not fixed here.
@coreyphillips That timeout is by design: #1397 asks for a bound, because |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since 787467c. Nothing blocking remains.
still open
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. The bounded wait at LightningService.swift:464-466 covers the usual case, and #1397 does ask for a bound. Past 5 s, though, the reply relies on synonymdev/ldk-node#140 to fence the old node's late write, and that fence is not in this branch. #140 is open and unmerged.gh api compareshows the pinned revision 366d56e ('chore: release 0.7.0-rc.81') is 7 commits behind #140's head, and none of the fence commits are included. So after a timeout, the late write and the double delivery that #1397 describes can still happen.restart()andrestartWithPreviousConfig()also clearnodeat :337 and :372 without waiting whenstop()throws. To close this, either pin an ldk-node release that contains #140, or drop 'Closes #1397' and keep the residual tracked. - A failed start() cancels whichever loop is current, possibly another start's (Bitkit/Services/LightningService.swift:408-414). The catch in
start()callscancelEventLoop(), which cancels whatevereventLoopTaskholds at that moment. That can be a loop installed by a concurrentstart()on the same node, not the one this call installed. Since 787467c onlyAlreadyRunningis exempt, so any other start error can still leave a running node with no loop. An interleaving that does this, between aLightningService.restart()(which bypassesWalletViewModel's lifecycle lock) and aNodeRestarterwallet start on the node the restart just built:restart: listenForEvents -> LB wallet: listenForEvents -> LA (cancels LB) .ldk: wallet node.start() fails, e.g. fee-rate update with Electrum down wallet: catch -> cancelEventLoop() cancels LA .ldk: restart node.start() succeedsThe node is now running witheventLoopTask == nil. The restart reports success and the wallet is.errorStarting. Events stay in the persisted queue until a later wallet retry installs a loop (it then getsAlreadyRunningand keeps it) or the node restarts. This needs twonode.start()calls on the same node to straddle a transient failure. I found it by reading LightningService.swift:401-414 and :2671-2679 and did not reproduce it. Possible fix: havelistenForEventsreturn the task it installs, and in the catch cancel it only ifeventLoopTaskis still that task (compared undereventLoopLock). The catch block at LightningService.swift:408-414 is unchanged. It still callscancelEventLoop()on whatever loop is current, so the interleaving described in the point still applies. The reply defers this to an rc.82 follow-up but does not dispute the defect. I found no tracking issue, and the PR's Out of Scope section lists only theself.nodelocking. - Timer cancellation can report a false shutdown timeout (Bitkit/Services/LightningService.swift:2694-2701).
waitForEndcan returnfalsefor an already-completed task. Cancelling the timer wakes its sleep, andtry?letsresume(false)race the followingresume(true). Using the unchanged helper, I reproduced 6 false results in 32,000 waits on already-completed tasks with ten-second timeouts. This produces false shutdown warnings.waitForEndat LightningService.swift:2694-2701 is unchanged. Cancelling the timer still wakesTask.sleep,try?swallows the cancellation, andresume(false)can still win the race againstresume(true). The reply defers this to the rc.82 follow-up without a fix. The fix is small: callresume(false)only when the sleep did not throw. No tracking issue or Out of Scope entry exists for it.
@coreyphillips Right, the fence is not in rc.81. This PR now only refs #1397, which closes with the rc.82 bump that pins synonymdev/ldk-node#140. The late write, the start catch and the |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since 787467c. Nothing blocking remains.
still open
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. Codex still sees it: AtBitkit/Services/LightningService.swift:464-467,stop()still clears the node after the five-second timeout even if its loop remains unfinished. The response acknowledges the missing write fence and defers it to rc.82, so the shutdown-ordering gap remains. - A failed start() cancels whichever loop is current, possibly another start's (Bitkit/Services/LightningService.swift:408-414). The catch in
start()callscancelEventLoop(), which cancels whatevereventLoopTaskholds at that moment. That can be a loop installed by a concurrentstart()on the same node, not the one this call installed. Since 787467c onlyAlreadyRunningis exempt, so any other start error can still leave a running node with no loop. An interleaving that does this, between aLightningService.restart()(which bypassesWalletViewModel's lifecycle lock) and aNodeRestarterwallet start on the node the restart just built:restart: listenForEvents -> LB wallet: listenForEvents -> LA (cancels LB) .ldk: wallet node.start() fails, e.g. fee-rate update with Electrum down wallet: catch -> cancelEventLoop() cancels LA .ldk: restart node.start() succeedsThe node is now running witheventLoopTask == nil. The restart reports success and the wallet is.errorStarting. Events stay in the persisted queue until a later wallet retry installs a loop (it then getsAlreadyRunningand keeps it) or the node restarts. This needs twonode.start()calls on the same node to straddle a transient failure. I found it by reading LightningService.swift:401-414 and :2671-2679 and did not reproduce it. Possible fix: havelistenForEventsreturn the task it installs, and in the catch cancel it only ifeventLoopTaskis still that task (compared undereventLoopLock). The catch at LightningService.swift:408-414 is unchanged and still cancels whatevereventLoopTaskholds, so it can cancel another start's loop. Your reply defers it to the rc.82 bump PR, which acknowledges the race rather than showing it is wrong. The Out of Scope bullet also doesn't link an issue or PR for it. - Timer cancellation can report a false shutdown timeout (Bitkit/Services/LightningService.swift:2694-2701).
waitForEndcan returnfalsefor an already-completed task. Cancelling the timer wakes its sleep, andtry?letsresume(false)race the followingresume(true). Using the unchanged helper, I reproduced 6 false results in 32,000 waits on already-completed tasks with ten-second timeouts. This produces false shutdown warnings.waitForEndat LightningService.swift:2692-2701 is unchanged.timer.cancel()still wakes the sleep,try?still swallows the cancellation, andresume(false)can still win againstresume(true). Deferring it to the rc.82 bump PR doesn't settle it here.
@coreyphillips Now tracked in #1399, linked from Out of Scope. The other points stand as answered: all three are fixed in the rc.82 bump PR. |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since 787467c. Nothing blocking remains.
still open
- stop() returns before the cancelled loop has finished with the stopped node (Bitkit/Services/LightningService.swift:456).
stop()cancels the loop through thenodesetter'sdidSet. It then returns without waiting for the loop, so a loop that is mid-iteration when the node is cleared finishes that iteration afterstop()has returned. The iteration can be blocked in either of two places: -node.eventHandled(), which pops the event and then persists the queue viaruntime.block_on(a VSS write). - TheMainActorhop indeliverEvent.restart()then builds the next node on the same storage. If the old node's persist has not landed yet, the new node loads a queue that still holds the event and delivers it a second time. The old node's late write can also overwrite the new node's queue. #1276 asks that a stopped node's events never reach the app, and that its runtime shut down before or as the next node starts. The window is narrow: an event has to be dequeued whilenode.stop()runs (sync events during an Electrum or RGS restart are the likeliest). The same overlap existed before this PR in a wider form, so this is a remaining gap, not a regression. Possible fix: after clearing the node, havestop()take the task, cancel it andawaititsvalue. That way no old-node work overlapssetup()of the next node. Found by reading the code, not reproduced. Codex still sees it: Bitkit/Services/LightningService.swift:464-467 still clears the node when the five-second wait expires, allowing unfinished eventHandled() work to overlap its replacement. The response places the fix in another PR; this branch still pins rc.81. - A failed start() cancels whichever loop is current, possibly another start's (Bitkit/Services/LightningService.swift:408-414). The catch in
start()callscancelEventLoop(), which cancels whatevereventLoopTaskholds at that moment. That can be a loop installed by a concurrentstart()on the same node, not the one this call installed. Since 787467c onlyAlreadyRunningis exempt, so any other start error can still leave a running node with no loop. An interleaving that does this, between aLightningService.restart()(which bypassesWalletViewModel's lifecycle lock) and aNodeRestarterwallet start on the node the restart just built:restart: listenForEvents -> LB wallet: listenForEvents -> LA (cancels LB) .ldk: wallet node.start() fails, e.g. fee-rate update with Electrum down wallet: catch -> cancelEventLoop() cancels LA .ldk: restart node.start() succeedsThe node is now running witheventLoopTask == nil. The restart reports success and the wallet is.errorStarting. Events stay in the persisted queue until a later wallet retry installs a loop (it then getsAlreadyRunningand keeps it) or the node restarts. This needs twonode.start()calls on the same node to straddle a transient failure. I found it by reading LightningService.swift:401-414 and :2671-2679 and did not reproduce it. Possible fix: havelistenForEventsreturn the task it installs, and in the catch cancel it only ifeventLoopTaskis still that task (compared undereventLoopLock). Bitkit/Services/LightningService.swift:408-414 is unchanged: the catch still callscancelEventLoop()on whatevereventLoopTaskholds at that moment. The reply defers the fix to the rc.82 bump and does not show the point is wrong. Issue #1399 (open, milestone 3.2.0) tracks it, so it need not hold this merge, but the defect is still in this branch. - Timer cancellation can report a false shutdown timeout (Bitkit/Services/LightningService.swift:2694-2701).
waitForEndcan returnfalsefor an already-completed task. Cancelling the timer wakes its sleep, andtry?letsresume(false)race the followingresume(true). Using the unchanged helper, I reproduced 6 false results in 32,000 waits on already-completed tasks with ten-second timeouts. This produces false shutdown warnings. Bitkit/Services/LightningService.swift:2694-2701 is unchanged. Cancellingtimerstill wakesTask.sleep,try?still swallows the cancellation, and theresume(false)that follows can still beat the watcher'sresume(true). The reply defers the fix to #1399, which is open and describes the right fix, but nothing changed here.
|
@ovitrif please resolve conflicts. |
# Conflicts: # Bitkit/Services/LightningService.swift
@piotr-iohk Resolved in 103d911: merged master and moved this PR's event-loop cancel onto the new |
Verified: swiftformat --lint . (0 files need formatting); comment-only change
|
Pushed 58130cc: SwiftFormat wanted a doc comment on |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR at 58130cc, re-reviewed after the comparison base changed from f17214e to c52c593 and that base change touches LightningService.swift.
No new actionable code findings.
No new actionable code findings. The master merge keeps the loop bound to configuredNode: replacing or releasing the node still cancels it, and stop() still waits up to 5 seconds before clearing the node.
The thread A failed start() cancels whichever loop is current is marked resolved. The reply defers the fix. At this head the start() catch still calls cancelEventLoop() for every error other than AlreadyRunning, so one start can cancel a loop installed by a concurrent start and leave the node running with no listener. Events stay in the persisted queue. Tracked in #1399. Source analysis, not a runtime reproduction.
The thread Timer cancellation can report a false shutdown timeout is marked resolved. waitForEnd still uses try? await Task.sleep, so a cancelled timer can resume false after the task has finished. stop() clears the node either way; the effect is a false warning. Also tracked in #1399. An earlier review reported 6 false results in 32,000 waits; this review did not re-run that harness.
Past the 5 second wait, stop() still clears the node while eventHandled() can be persisting. The write fence for that overlap is ldk-node#140, which is not in the pinned 0.7.0-rc.81. Tracked in #1397. If stop() throws, restart() still releases the node in its existing catch with no wait. Same bounded gap as before this base change.
The resolved AlreadyRunning case still keeps the replacement loop, including when ServiceQueue wraps the error in AppError.
Compatibility with #1394 at 30e8acbc: only the runtime-lifetime contract was checked, not a full review. Both pins use ldk-node 0.7.0-rc.81 (366d56ef). Its Runtime shutdown keeps the runtime until detached work ends instead of aborting under it.
Android 69931fb9 still awaits nextEventAsync(), joins that listener before node.stop(), and gates the next build on handle release. iOS polls nextEvent() because the Swift async call cannot be cancelled, and bounds the stop wait at 5 seconds.
Device testing: not performed in this review. The author's manual test 1 was not run; it needs Xcode's Memory Graph. SwiftFormat succeeded on this commit. Run Tests was still in progress, so this review does not treat it as a pass and did not execute the suite.
Suggested additional test cases
- iOS regtest, with one Lightning payment already visible: Restart once from Settings → Dev Settings → LDK. That payment stays listed once, a new incoming payment after restart appears once, and Memory Graph shows one
LDKNode.Node.
Reviewer model: grok-4.7
Reasoning effort: xhigh
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 58130cc.
Low — Idle polling at Bitkit/Services/LightningService.swift:2479 can replay an acknowledged event after restart. If a poll lands between the producer releasing the queue mutex and submitting its enqueue snapshot, eventHandled() can submit the empty snapshot first. The producer's older snapshot then receives the higher VSS write version and can become the last persisted state. Restarting before another queue write reloads the acknowledged event. Queue operations VSS write ordering
The listener handle can become unavailable to other lifecycle callers while the listener still has work in flight.
Low — Tapping Reset while Electrum Connect is still loading can bypass the drain at Bitkit/Services/LightningService.swift:478. If the first stop already took the listener handle, the second accepts the native NotRunning result and proceeds to rebuild while the first is still waiting. The first stop can then clear the replacement at Bitkit/Services/LightningService.swift:481.
Low — A failed startup at Bitkit/Services/LightningService.swift:425 can leave an in-flight acknowledgement or delivery that a retry or wipe has no handle to await. This requires a persisted event to have been taken before startup failed. The overlap also existed on the base, where the failed start left its listener running.
Low — The settings restart and previous-configuration recovery both release the node on a native stop error at Bitkit/Services/LightningService.swift:351 and Bitkit/Services/LightningService.swift:386. If native stop returns PersistenceFailed during an event iteration, both paths can rebuild against the same wallet queue while that iteration can still acknowledge or deliver. The base also released the node immediately on these error paths.
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Cross-project review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
A second stop of the same node waits for the event loop the first stop took, and a stop releases the node only while it is still the configured one. Verified: iOS unit suite on simulator (all pass except BackupServiceTests.testAutomaticBackupRetriesContentionAndChangesDuringUpload, which then passed 3 of 3 alone); swiftformat --lint
Fixed in c3f47e9: a second stop of the same node now waits for the loop the first stop took, and a stop releases the node only while it is still the configured one, so a late stop can no longer clear the replacement.
Agreed on the ordering; the fix belongs in ldk-node, so I filed synonymdev/ldk-node#143 (take the store write, and its version, under the queue lock). The window is the producer's synchronous path from dropping the lock to calling
Both predate this PR, as you note; they're on #1399 with the |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 58130cc, including affected code paths and prior findings, at c3f47e9. Baseline: QA review.
1 actionable finding — resolve or provide an evidence-backed rebuttal.
release(_:) keeps a late stop from clearing a replacement node. The second stop still waits on its own 5 second deadline, so after the first stop times out and setup() has taken the lightning lock, the later stop() deletes that lock. Electrum Reset stays enabled while Connect is loading. If that first rebuild has already started the node, Reset's restart() treats it as success and saves the default server while the node keeps Connect's server. Source analysis only; this review did not run the suite.
Inherited from the baseline: start-failure and AlreadyRunning handling, the ldk-node 0.7.0-rc.81 pin, and the changelog fragments. The stop/wait path was re-read because it changed. Compatibility with #1394 at 0581a55: only the runtime-lifetime contract was checked, not a full review. Both pins are ldk-node 0.7.0-rc.81 (366d56ef), whose shutdown keeps the runtime until detached work ends.
Existing concerns, with the original threads marked resolved, are unchanged in this delta. A failed start() can still cancel another start's loop, and waitForEnd can still report a false timeout, both tracked in #1399. A stopped node's queue write after the 5 second wait is still fenced only by ldk-node#140, tracked in #1397. The comment that the first stop clears the replacement node is addressed for the node reference. The queue-version replay note is unchanged; the author points it at ldk-node#143.
SwiftFormat and Run Tests succeeded on this commit. Device testing: not performed in this review. Manual test 1 still needs Xcode's Memory Graph.
Recommended before device testing: keep a stop that no longer owns the node from unlocking, and keep a restart that did not build that node from saving the Electrum server.
Suggested additional test cases
- iOS regtest, node running. Settings → Electrum Server: Connect to a non-default server, then tap Reset to default while Connect is still loading and the first stop is inside its event-loop wait (the 5 second bound, such as while
eventHandled()is stuck). After both calls return, the running node's server matches the saved server, and the lightning lock is still held.
Findings
- [MEDIUM] Keep a late stop from unlocking the replacement node — inline at
Bitkit/Services/LightningService.swift:2704.
Reviewer model: grok-4.7
Reasoning effort: xhigh
Restarts run one after another, so Reset during Electrum Connect waits for Connect's node and saves the server the running node uses. A stop whose node was already replaced leaves the lightning lock to the replacement. Verified: iOS unit suite on simulator; swiftformat --lint
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 9d68d56. Electrum Connect and Reset now run their node restarts in sequence. Wallet lifecycle calls still reach the same event-loop slot independently, and the slot can be changed before the caller checks which node owns it.
Low candidate: If a wallet graph reset or routing-cache reset is still stopping the old node when a settings restart installs its replacement listener, the late stop can cancel that listener at Bitkit/Services/LightningService.swift:512. The identity check at Bitkit/Services/LightningService.swift:516 keeps the replacement configured, so it can be left running without a listener until another start installs one.
Low candidate: If a wallet retry reads the old node at Bitkit/Services/LightningService.swift:2501 and a settings restart installs the replacement listener before the retry takes eventLoopLock, the retry can cancel the replacement at Bitkit/Services/LightningService.swift:2509. The retry's own loop then exits at Bitkit/Services/LightningService.swift:2513 because its node is no longer current. Payment and on-chain events can stay queued until a later start installs a listener.
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Cross-project review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
Both come from the event-loop slot not knowing which node its loop serves, the same root as the |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since c3f47e9, at 9d68d56. Baseline: previous QA review. Inherited coverage is start-failure and AlreadyRunning handling, the ldk-node 0.7.0-rc.81 pin and runtime lifetime, and the changelog fragments.
No new actionable code findings.
Overlapping restart() calls run one after another. stop() keeps the lightning lock when the node it stopped has already been replaced. When that stop still owns the node, it unlocks after the stop finishes, and the following setup takes the lock again.
Compared bitkit-ios#1394 at 0581a550 only for the shared ldk-node pin: both trees pin 0.7.0-rc.81 (366d56ef). This was not a full review of that pull request. Android was not compared; this follow-up is iOS lock ownership around restart.
Device testing: not performed in this review. Ready for device testing: the follow-up has no new code findings, and manual test 1 remains the runtime check. The existing LightningServiceTests cases do not cover two overlapping restart() calls; they were inspected, not executed in this review.
Suggested additional test cases
- iOS regtest, with the node running. Start a second restart before the first
restart()returns (Debug Settings → Restart twice, or an Electrum connect overlapping a debug restart). Expected: a following Lightning payment is recorded once, and Memory Graph shows oneLDKNode.Node.
Earlier findings reconciled at this revision: 2 still present, 1 verified fixed.
Existing concerns
- [MEDIUM] A failed start can cancel another start's event loop — The thread is marked resolved. The reply defers the fix to the rc.82 bump and to #1399; that is not a fix at this head. A settings restart and a wallet start can both call start() on the node the restart just built. listenForEvents replaces the current loop, then a non-AlreadyRunning start error calls cancelEventLoop(), which cancels whichever loop is installed, including the other caller's. The running node is left with no listener. Payment and on-chain events stay in the persisted queue until a later start installs one. Source analysis at 9d68d56; this pass did not run the interleaving.
- [LOW] A finished event-loop wait can log a false timeout — The thread is marked resolved. The reply defers the fix and says the effect is a wrong warning because stop() clears the node either way. That deferral is not a fix. waitForEnd still lets the cancelled timer's resume(false) race resume(true). stop() then logs that the loop did not end. An earlier review reported 6 false results in 32,000 waits; this pass did not re-run that harness. The helper source at this head still has the race.
Reviewer model: grok-4.7
Reasoning effort: xhigh
Closes #1276
Refs: #1397
Dependency: #1394
Releases the old node on each restart. The event loop kept every stopped node, its runtime and a loop alive.
Description
nextEventAsync(). UniFFI's Swift async calls cannot be cancelled, and the call never returns once its node stops, so the loop, the stoppedNodeand its runtime stayed alive after every restart. Each start also spawned another loop, and an old loop that re-readself.nodecould attach to the new node and handle its events too.nextEvent()every 100 ms, bound to the node it was started for. It ends once that node is no longer the current one, and its task is cancelled when the node changes, is cleared, fails to start, or a new loop starts.stop()waits up to 5 s for the loop to end before it clears the node, so a stopped node's lasteventHandled()lands before the next node loads the event queue. A start that fails withAlreadyRunning, also whenServiceQueuewraps it inAppError, keeps the running node's loop, and a new loop waits for the one it replaces, so two loops never handle the same event.Out of Scope
self.nodeis still read and written from different threads without a lock, as before this change.start()cancels whichever loop is current, possibly another start's;waitForEndcan report a false timeout for a finished task. Both are fixed in the rc.82 bump PR, tracked in bug: a failed node start can leave the running node without an event loop #1399.Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
Regtest build.
Journeys
N/A — no user-visible behaviour change.
Manual Tests
LDKNode.Node— Memory Graph not in CapabilitiesAutomated Checks
LightningServiceTestscases — the bounded wait returns once the loop ends and gives up on a loop that does not end, andAlreadyRunningis recognized through the queue'sAppErrorwrapperEvidence
AppErrorcase passed on 3155cd971 (ldk-node 0.7.0-rc.81); that case's test was fixed in 787467c, whereLightningServiceTestspassed.Gaps
Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)gemini-4-neon-high(reasoning:Not exposed)The pre-PR review run records only its model id.